cluster.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package integration
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "io/ioutil"
  19. "math/rand"
  20. "net"
  21. "net/http"
  22. "net/http/httptest"
  23. "os"
  24. "reflect"
  25. "sort"
  26. "strings"
  27. "sync"
  28. "sync/atomic"
  29. "testing"
  30. "time"
  31. "golang.org/x/net/context"
  32. "google.golang.org/grpc"
  33. "github.com/coreos/etcd/client"
  34. "github.com/coreos/etcd/clientv3"
  35. "github.com/coreos/etcd/etcdserver"
  36. "github.com/coreos/etcd/etcdserver/api"
  37. "github.com/coreos/etcd/etcdserver/api/v2http"
  38. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  39. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  40. "github.com/coreos/etcd/pkg/testutil"
  41. "github.com/coreos/etcd/pkg/transport"
  42. "github.com/coreos/etcd/pkg/types"
  43. "github.com/coreos/etcd/rafthttp"
  44. "github.com/coreos/pkg/capnslog"
  45. )
  46. const (
  47. tickDuration = 10 * time.Millisecond
  48. clusterName = "etcd"
  49. requestTimeout = 20 * time.Second
  50. basePort = 21000
  51. UrlScheme = "unix"
  52. UrlSchemeTLS = "unixs"
  53. )
  54. var (
  55. electionTicks = 10
  56. // integration test uses unique ports, counting up, to listen for each
  57. // member, ensuring restarted members can listen on the same port again.
  58. localListenCount int64 = 0
  59. testTLSInfo = transport.TLSInfo{
  60. KeyFile: "./fixtures/server.key.insecure",
  61. CertFile: "./fixtures/server.crt",
  62. TrustedCAFile: "./fixtures/ca.crt",
  63. ClientCertAuth: true,
  64. }
  65. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "integration")
  66. )
  67. type ClusterConfig struct {
  68. Size int
  69. PeerTLS *transport.TLSInfo
  70. ClientTLS *transport.TLSInfo
  71. DiscoveryURL string
  72. UseGRPC bool
  73. QuotaBackendBytes int64
  74. }
  75. type cluster struct {
  76. cfg *ClusterConfig
  77. Members []*member
  78. }
  79. func init() {
  80. // manually enable v3 capability since we know the cluster members all support v3.
  81. api.EnableCapability(api.V3rpcCapability)
  82. }
  83. func schemeFromTLSInfo(tls *transport.TLSInfo) string {
  84. if tls == nil {
  85. return UrlScheme
  86. }
  87. return UrlSchemeTLS
  88. }
  89. func (c *cluster) fillClusterForMembers() error {
  90. if c.cfg.DiscoveryURL != "" {
  91. // cluster will be discovered
  92. return nil
  93. }
  94. addrs := make([]string, 0)
  95. for _, m := range c.Members {
  96. scheme := schemeFromTLSInfo(m.PeerTLSInfo)
  97. for _, l := range m.PeerListeners {
  98. addrs = append(addrs, fmt.Sprintf("%s=%s://%s", m.Name, scheme, l.Addr().String()))
  99. }
  100. }
  101. clusterStr := strings.Join(addrs, ",")
  102. var err error
  103. for _, m := range c.Members {
  104. m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  105. if err != nil {
  106. return err
  107. }
  108. }
  109. return nil
  110. }
  111. func newCluster(t *testing.T, cfg *ClusterConfig) *cluster {
  112. c := &cluster{cfg: cfg}
  113. ms := make([]*member, cfg.Size)
  114. for i := 0; i < cfg.Size; i++ {
  115. ms[i] = c.mustNewMember(t)
  116. }
  117. c.Members = ms
  118. if err := c.fillClusterForMembers(); err != nil {
  119. t.Fatal(err)
  120. }
  121. return c
  122. }
  123. // NewCluster returns an unlaunched cluster of the given size which has been
  124. // set to use static bootstrap.
  125. func NewCluster(t *testing.T, size int) *cluster {
  126. return newCluster(t, &ClusterConfig{Size: size})
  127. }
  128. // NewClusterByConfig returns an unlaunched cluster defined by a cluster configuration
  129. func NewClusterByConfig(t *testing.T, cfg *ClusterConfig) *cluster {
  130. return newCluster(t, cfg)
  131. }
  132. func (c *cluster) Launch(t *testing.T) {
  133. errc := make(chan error)
  134. for _, m := range c.Members {
  135. // Members are launched in separate goroutines because if they boot
  136. // using discovery url, they have to wait for others to register to continue.
  137. go func(m *member) {
  138. errc <- m.Launch()
  139. }(m)
  140. }
  141. for range c.Members {
  142. if err := <-errc; err != nil {
  143. t.Fatalf("error setting up member: %v", err)
  144. }
  145. }
  146. // wait cluster to be stable to receive future client requests
  147. c.waitMembersMatch(t, c.HTTPMembers())
  148. c.waitVersion()
  149. }
  150. func (c *cluster) URL(i int) string {
  151. return c.Members[i].ClientURLs[0].String()
  152. }
  153. // URLs returns a list of all active client URLs in the cluster
  154. func (c *cluster) URLs() []string {
  155. urls := make([]string, 0)
  156. for _, m := range c.Members {
  157. select {
  158. case <-m.s.StopNotify():
  159. continue
  160. default:
  161. }
  162. for _, u := range m.ClientURLs {
  163. urls = append(urls, u.String())
  164. }
  165. }
  166. return urls
  167. }
  168. // HTTPMembers returns a list of all active members as client.Members
  169. func (c *cluster) HTTPMembers() []client.Member {
  170. ms := []client.Member{}
  171. for _, m := range c.Members {
  172. pScheme := schemeFromTLSInfo(m.PeerTLSInfo)
  173. cScheme := schemeFromTLSInfo(m.ClientTLSInfo)
  174. cm := client.Member{Name: m.Name}
  175. for _, ln := range m.PeerListeners {
  176. cm.PeerURLs = append(cm.PeerURLs, pScheme+"://"+ln.Addr().String())
  177. }
  178. for _, ln := range m.ClientListeners {
  179. cm.ClientURLs = append(cm.ClientURLs, cScheme+"://"+ln.Addr().String())
  180. }
  181. ms = append(ms, cm)
  182. }
  183. return ms
  184. }
  185. func (c *cluster) mustNewMember(t *testing.T) *member {
  186. m := mustNewMember(t,
  187. memberConfig{
  188. name: c.name(rand.Int()),
  189. peerTLS: c.cfg.PeerTLS,
  190. clientTLS: c.cfg.ClientTLS,
  191. quotaBackendBytes: c.cfg.QuotaBackendBytes,
  192. })
  193. m.DiscoveryURL = c.cfg.DiscoveryURL
  194. if c.cfg.UseGRPC {
  195. if err := m.listenGRPC(); err != nil {
  196. t.Fatal(err)
  197. }
  198. }
  199. return m
  200. }
  201. func (c *cluster) addMember(t *testing.T) {
  202. m := c.mustNewMember(t)
  203. scheme := schemeFromTLSInfo(c.cfg.PeerTLS)
  204. // send add request to the cluster
  205. var err error
  206. for i := 0; i < len(c.Members); i++ {
  207. clientURL := c.URL(i)
  208. peerURL := scheme + "://" + m.PeerListeners[0].Addr().String()
  209. if err = c.addMemberByURL(t, clientURL, peerURL); err == nil {
  210. break
  211. }
  212. }
  213. if err != nil {
  214. t.Fatalf("add member failed on all members error: %v", err)
  215. }
  216. m.InitialPeerURLsMap = types.URLsMap{}
  217. for _, mm := range c.Members {
  218. m.InitialPeerURLsMap[mm.Name] = mm.PeerURLs
  219. }
  220. m.InitialPeerURLsMap[m.Name] = m.PeerURLs
  221. m.NewCluster = false
  222. if err := m.Launch(); err != nil {
  223. t.Fatal(err)
  224. }
  225. c.Members = append(c.Members, m)
  226. // wait cluster to be stable to receive future client requests
  227. c.waitMembersMatch(t, c.HTTPMembers())
  228. }
  229. func (c *cluster) addMemberByURL(t *testing.T, clientURL, peerURL string) error {
  230. cc := MustNewHTTPClient(t, []string{clientURL}, c.cfg.ClientTLS)
  231. ma := client.NewMembersAPI(cc)
  232. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  233. if _, err := ma.Add(ctx, peerURL); err != nil {
  234. return err
  235. }
  236. cancel()
  237. // wait for the add node entry applied in the cluster
  238. members := append(c.HTTPMembers(), client.Member{PeerURLs: []string{peerURL}, ClientURLs: []string{}})
  239. c.waitMembersMatch(t, members)
  240. return nil
  241. }
  242. func (c *cluster) AddMember(t *testing.T) {
  243. c.addMember(t)
  244. }
  245. func (c *cluster) RemoveMember(t *testing.T, id uint64) {
  246. // send remove request to the cluster
  247. cc := MustNewHTTPClient(t, c.URLs(), c.cfg.ClientTLS)
  248. ma := client.NewMembersAPI(cc)
  249. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  250. if err := ma.Remove(ctx, types.ID(id).String()); err != nil {
  251. t.Fatalf("unexpected remove error %v", err)
  252. }
  253. cancel()
  254. newMembers := make([]*member, 0)
  255. for _, m := range c.Members {
  256. if uint64(m.s.ID()) != id {
  257. newMembers = append(newMembers, m)
  258. } else {
  259. select {
  260. case <-m.s.StopNotify():
  261. m.Terminate(t)
  262. // 1s stop delay + election timeout + 1s disk and network delay + connection write timeout
  263. // TODO: remove connection write timeout by selecting on http response closeNotifier
  264. // blocking on https://github.com/golang/go/issues/9524
  265. case <-time.After(time.Second + time.Duration(electionTicks)*tickDuration + time.Second + rafthttp.ConnWriteTimeout):
  266. t.Fatalf("failed to remove member %s in time", m.s.ID())
  267. }
  268. }
  269. }
  270. c.Members = newMembers
  271. c.waitMembersMatch(t, c.HTTPMembers())
  272. }
  273. func (c *cluster) Terminate(t *testing.T) {
  274. for _, m := range c.Members {
  275. m.Terminate(t)
  276. }
  277. }
  278. func (c *cluster) waitMembersMatch(t *testing.T, membs []client.Member) {
  279. for _, u := range c.URLs() {
  280. cc := MustNewHTTPClient(t, []string{u}, c.cfg.ClientTLS)
  281. ma := client.NewMembersAPI(cc)
  282. for {
  283. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  284. ms, err := ma.List(ctx)
  285. cancel()
  286. if err == nil && isMembersEqual(ms, membs) {
  287. break
  288. }
  289. time.Sleep(tickDuration)
  290. }
  291. }
  292. return
  293. }
  294. func (c *cluster) WaitLeader(t *testing.T) int { return c.waitLeader(t, c.Members) }
  295. func (c *cluster) waitLeader(t *testing.T, membs []*member) int {
  296. possibleLead := make(map[uint64]bool)
  297. var lead uint64
  298. for _, m := range membs {
  299. possibleLead[uint64(m.s.ID())] = true
  300. }
  301. for lead == 0 || !possibleLead[lead] {
  302. lead = 0
  303. for _, m := range membs {
  304. select {
  305. case <-m.s.StopNotify():
  306. continue
  307. default:
  308. }
  309. if lead != 0 && lead != m.s.Lead() {
  310. lead = 0
  311. time.Sleep(10 * tickDuration)
  312. break
  313. }
  314. lead = m.s.Lead()
  315. }
  316. }
  317. for i, m := range membs {
  318. if uint64(m.s.ID()) == lead {
  319. return i
  320. }
  321. }
  322. return -1
  323. }
  324. func (c *cluster) waitVersion() {
  325. for _, m := range c.Members {
  326. for {
  327. if m.s.ClusterVersion() != nil {
  328. break
  329. }
  330. time.Sleep(tickDuration)
  331. }
  332. }
  333. }
  334. func (c *cluster) name(i int) string {
  335. return fmt.Sprint("node", i)
  336. }
  337. // isMembersEqual checks whether two members equal except ID field.
  338. // The given wmembs should always set ID field to empty string.
  339. func isMembersEqual(membs []client.Member, wmembs []client.Member) bool {
  340. sort.Sort(SortableMemberSliceByPeerURLs(membs))
  341. sort.Sort(SortableMemberSliceByPeerURLs(wmembs))
  342. for i := range membs {
  343. membs[i].ID = ""
  344. }
  345. return reflect.DeepEqual(membs, wmembs)
  346. }
  347. func newLocalListener(t *testing.T) net.Listener {
  348. c := atomic.AddInt64(&localListenCount, 1)
  349. addr := fmt.Sprintf("127.0.0.1:%d.%d.sock", c+basePort, os.Getpid())
  350. return NewListenerWithAddr(t, addr)
  351. }
  352. func NewListenerWithAddr(t *testing.T, addr string) net.Listener {
  353. l, err := transport.NewUnixListener(addr)
  354. if err != nil {
  355. t.Fatal(err)
  356. }
  357. return l
  358. }
  359. type member struct {
  360. etcdserver.ServerConfig
  361. PeerListeners, ClientListeners []net.Listener
  362. grpcListener net.Listener
  363. // PeerTLSInfo enables peer TLS when set
  364. PeerTLSInfo *transport.TLSInfo
  365. // ClientTLSInfo enables client TLS when set
  366. ClientTLSInfo *transport.TLSInfo
  367. raftHandler *testutil.PauseableHandler
  368. s *etcdserver.EtcdServer
  369. hss []*httptest.Server
  370. grpcServer *grpc.Server
  371. grpcAddr string
  372. grpcBridge *bridge
  373. }
  374. func (m *member) GRPCAddr() string { return m.grpcAddr }
  375. type memberConfig struct {
  376. name string
  377. peerTLS *transport.TLSInfo
  378. clientTLS *transport.TLSInfo
  379. quotaBackendBytes int64
  380. }
  381. // mustNewMember return an inited member with the given name. If peerTLS is
  382. // set, it will use https scheme to communicate between peers.
  383. func mustNewMember(t *testing.T, mcfg memberConfig) *member {
  384. var err error
  385. m := &member{}
  386. peerScheme := schemeFromTLSInfo(mcfg.peerTLS)
  387. clientScheme := schemeFromTLSInfo(mcfg.clientTLS)
  388. pln := newLocalListener(t)
  389. m.PeerListeners = []net.Listener{pln}
  390. m.PeerURLs, err = types.NewURLs([]string{peerScheme + "://" + pln.Addr().String()})
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. m.PeerTLSInfo = mcfg.peerTLS
  395. cln := newLocalListener(t)
  396. m.ClientListeners = []net.Listener{cln}
  397. m.ClientURLs, err = types.NewURLs([]string{clientScheme + "://" + cln.Addr().String()})
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. m.ClientTLSInfo = mcfg.clientTLS
  402. m.Name = mcfg.name
  403. m.DataDir, err = ioutil.TempDir(os.TempDir(), "etcd")
  404. if err != nil {
  405. t.Fatal(err)
  406. }
  407. clusterStr := fmt.Sprintf("%s=%s://%s", mcfg.name, peerScheme, pln.Addr().String())
  408. m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  409. if err != nil {
  410. t.Fatal(err)
  411. }
  412. m.InitialClusterToken = clusterName
  413. m.NewCluster = true
  414. m.BootstrapTimeout = 10 * time.Millisecond
  415. if m.PeerTLSInfo != nil {
  416. m.ServerConfig.PeerTLSInfo = *m.PeerTLSInfo
  417. }
  418. m.ElectionTicks = electionTicks
  419. m.TickMs = uint(tickDuration / time.Millisecond)
  420. m.QuotaBackendBytes = mcfg.quotaBackendBytes
  421. return m
  422. }
  423. // listenGRPC starts a grpc server over a unix domain socket on the member
  424. func (m *member) listenGRPC() error {
  425. // prefix with localhost so cert has right domain
  426. m.grpcAddr = "localhost:" + m.Name + ".sock"
  427. l, err := transport.NewUnixListener(m.grpcAddr)
  428. if err != nil {
  429. return fmt.Errorf("listen failed on grpc socket %s (%v)", m.grpcAddr, err)
  430. }
  431. m.grpcBridge, err = newBridge(m.grpcAddr)
  432. if err != nil {
  433. l.Close()
  434. return err
  435. }
  436. m.grpcAddr = m.grpcBridge.URL()
  437. m.grpcListener = l
  438. return nil
  439. }
  440. func (m *member) DropConnections() { m.grpcBridge.Reset() }
  441. // NewClientV3 creates a new grpc client connection to the member
  442. func NewClientV3(m *member) (*clientv3.Client, error) {
  443. if m.grpcAddr == "" {
  444. return nil, fmt.Errorf("member not configured for grpc")
  445. }
  446. cfg := clientv3.Config{
  447. Endpoints: []string{m.grpcAddr},
  448. DialTimeout: 5 * time.Second,
  449. }
  450. if m.ClientTLSInfo != nil {
  451. tls, err := m.ClientTLSInfo.ClientConfig()
  452. if err != nil {
  453. return nil, err
  454. }
  455. cfg.TLS = tls
  456. }
  457. return clientv3.New(cfg)
  458. }
  459. // Clone returns a member with the same server configuration. The returned
  460. // member will not set PeerListeners and ClientListeners.
  461. func (m *member) Clone(t *testing.T) *member {
  462. mm := &member{}
  463. mm.ServerConfig = m.ServerConfig
  464. var err error
  465. clientURLStrs := m.ClientURLs.StringSlice()
  466. mm.ClientURLs, err = types.NewURLs(clientURLStrs)
  467. if err != nil {
  468. // this should never fail
  469. panic(err)
  470. }
  471. peerURLStrs := m.PeerURLs.StringSlice()
  472. mm.PeerURLs, err = types.NewURLs(peerURLStrs)
  473. if err != nil {
  474. // this should never fail
  475. panic(err)
  476. }
  477. clusterStr := m.InitialPeerURLsMap.String()
  478. mm.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  479. if err != nil {
  480. // this should never fail
  481. panic(err)
  482. }
  483. mm.InitialClusterToken = m.InitialClusterToken
  484. mm.ElectionTicks = m.ElectionTicks
  485. mm.PeerTLSInfo = m.PeerTLSInfo
  486. mm.ClientTLSInfo = m.ClientTLSInfo
  487. return mm
  488. }
  489. // Launch starts a member based on ServerConfig, PeerListeners
  490. // and ClientListeners.
  491. func (m *member) Launch() error {
  492. plog.Printf("launching %s (%s)", m.Name, m.grpcAddr)
  493. var err error
  494. if m.s, err = etcdserver.NewServer(&m.ServerConfig); err != nil {
  495. return fmt.Errorf("failed to initialize the etcd server: %v", err)
  496. }
  497. m.s.SyncTicker = time.Tick(500 * time.Millisecond)
  498. m.s.Start()
  499. m.raftHandler = &testutil.PauseableHandler{Next: v2http.NewPeerHandler(m.s)}
  500. for _, ln := range m.PeerListeners {
  501. hs := &httptest.Server{
  502. Listener: ln,
  503. Config: &http.Server{Handler: m.raftHandler},
  504. }
  505. if m.PeerTLSInfo == nil {
  506. hs.Start()
  507. } else {
  508. hs.TLS, err = m.PeerTLSInfo.ServerConfig()
  509. if err != nil {
  510. return err
  511. }
  512. hs.StartTLS()
  513. }
  514. m.hss = append(m.hss, hs)
  515. }
  516. for _, ln := range m.ClientListeners {
  517. hs := &httptest.Server{
  518. Listener: ln,
  519. Config: &http.Server{Handler: v2http.NewClientHandler(m.s, m.ServerConfig.ReqTimeout())},
  520. }
  521. if m.ClientTLSInfo == nil {
  522. hs.Start()
  523. } else {
  524. hs.TLS, err = m.ClientTLSInfo.ServerConfig()
  525. if err != nil {
  526. return err
  527. }
  528. hs.StartTLS()
  529. }
  530. m.hss = append(m.hss, hs)
  531. }
  532. if m.grpcListener != nil {
  533. var (
  534. tlscfg *tls.Config
  535. )
  536. if m.ClientTLSInfo != nil && !m.ClientTLSInfo.Empty() {
  537. tlscfg, err = m.ClientTLSInfo.ServerConfig()
  538. if err != nil {
  539. return err
  540. }
  541. }
  542. m.grpcServer = v3rpc.Server(m.s, tlscfg)
  543. go m.grpcServer.Serve(m.grpcListener)
  544. }
  545. plog.Printf("launched %s (%s)", m.Name, m.grpcAddr)
  546. return nil
  547. }
  548. func (m *member) WaitOK(t *testing.T) {
  549. cc := MustNewHTTPClient(t, []string{m.URL()}, m.ClientTLSInfo)
  550. kapi := client.NewKeysAPI(cc)
  551. for {
  552. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  553. _, err := kapi.Get(ctx, "/", nil)
  554. if err != nil {
  555. time.Sleep(tickDuration)
  556. continue
  557. }
  558. cancel()
  559. break
  560. }
  561. for m.s.Leader() == 0 {
  562. time.Sleep(tickDuration)
  563. }
  564. }
  565. func (m *member) URL() string { return m.ClientURLs[0].String() }
  566. func (m *member) Pause() {
  567. m.raftHandler.Pause()
  568. m.s.PauseSending()
  569. }
  570. func (m *member) Resume() {
  571. m.raftHandler.Resume()
  572. m.s.ResumeSending()
  573. }
  574. // Close stops the member's etcdserver and closes its connections
  575. func (m *member) Close() {
  576. if m.grpcBridge != nil {
  577. m.grpcBridge.Close()
  578. m.grpcBridge = nil
  579. }
  580. if m.grpcServer != nil {
  581. m.grpcServer.Stop()
  582. m.grpcServer = nil
  583. }
  584. m.s.Stop()
  585. for _, hs := range m.hss {
  586. hs.CloseClientConnections()
  587. hs.Close()
  588. }
  589. }
  590. // Stop stops the member, but the data dir of the member is preserved.
  591. func (m *member) Stop(t *testing.T) {
  592. plog.Printf("stopping %s (%s)", m.Name, m.grpcAddr)
  593. m.Close()
  594. m.hss = nil
  595. plog.Printf("stopped %s (%s)", m.Name, m.grpcAddr)
  596. }
  597. // StopNotify unblocks when a member stop completes
  598. func (m *member) StopNotify() <-chan struct{} {
  599. return m.s.StopNotify()
  600. }
  601. // Restart starts the member using the preserved data dir.
  602. func (m *member) Restart(t *testing.T) error {
  603. plog.Printf("restarting %s (%s)", m.Name, m.grpcAddr)
  604. newPeerListeners := make([]net.Listener, 0)
  605. for _, ln := range m.PeerListeners {
  606. newPeerListeners = append(newPeerListeners, NewListenerWithAddr(t, ln.Addr().String()))
  607. }
  608. m.PeerListeners = newPeerListeners
  609. newClientListeners := make([]net.Listener, 0)
  610. for _, ln := range m.ClientListeners {
  611. newClientListeners = append(newClientListeners, NewListenerWithAddr(t, ln.Addr().String()))
  612. }
  613. m.ClientListeners = newClientListeners
  614. if m.grpcListener != nil {
  615. if err := m.listenGRPC(); err != nil {
  616. t.Fatal(err)
  617. }
  618. }
  619. err := m.Launch()
  620. plog.Printf("restarted %s (%s)", m.Name, m.grpcAddr)
  621. return err
  622. }
  623. // Terminate stops the member and removes the data dir.
  624. func (m *member) Terminate(t *testing.T) {
  625. plog.Printf("terminating %s (%s)", m.Name, m.grpcAddr)
  626. m.Close()
  627. if err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {
  628. t.Fatal(err)
  629. }
  630. plog.Printf("terminated %s (%s)", m.Name, m.grpcAddr)
  631. }
  632. func MustNewHTTPClient(t *testing.T, eps []string, tls *transport.TLSInfo) client.Client {
  633. cfgtls := transport.TLSInfo{}
  634. if tls != nil {
  635. cfgtls = *tls
  636. }
  637. cfg := client.Config{Transport: mustNewTransport(t, cfgtls), Endpoints: eps}
  638. c, err := client.New(cfg)
  639. if err != nil {
  640. t.Fatal(err)
  641. }
  642. return c
  643. }
  644. func mustNewTransport(t *testing.T, tlsInfo transport.TLSInfo) *http.Transport {
  645. // tick in integration test is short, so 1s dial timeout could play well.
  646. tr, err := transport.NewTimeoutTransport(tlsInfo, time.Second, rafthttp.ConnReadTimeout, rafthttp.ConnWriteTimeout)
  647. if err != nil {
  648. t.Fatal(err)
  649. }
  650. return tr
  651. }
  652. type SortableMemberSliceByPeerURLs []client.Member
  653. func (p SortableMemberSliceByPeerURLs) Len() int { return len(p) }
  654. func (p SortableMemberSliceByPeerURLs) Less(i, j int) bool {
  655. return p[i].PeerURLs[0] < p[j].PeerURLs[0]
  656. }
  657. func (p SortableMemberSliceByPeerURLs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  658. type ClusterV3 struct {
  659. *cluster
  660. mu sync.Mutex
  661. clients []*clientv3.Client
  662. }
  663. // NewClusterV3 returns a launched cluster with a grpc client connection
  664. // for each cluster member.
  665. func NewClusterV3(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
  666. cfg.UseGRPC = true
  667. clus := &ClusterV3{
  668. cluster: NewClusterByConfig(t, cfg),
  669. }
  670. clus.Launch(t)
  671. for _, m := range clus.Members {
  672. client, err := NewClientV3(m)
  673. if err != nil {
  674. t.Fatalf("cannot create client: %v", err)
  675. }
  676. clus.clients = append(clus.clients, client)
  677. }
  678. return clus
  679. }
  680. func (c *ClusterV3) TakeClient(idx int) {
  681. c.mu.Lock()
  682. c.clients[idx] = nil
  683. c.mu.Unlock()
  684. }
  685. func (c *ClusterV3) Terminate(t *testing.T) {
  686. c.mu.Lock()
  687. for _, client := range c.clients {
  688. if client == nil {
  689. continue
  690. }
  691. if err := client.Close(); err != nil {
  692. t.Error(err)
  693. }
  694. }
  695. c.mu.Unlock()
  696. c.cluster.Terminate(t)
  697. }
  698. func (c *ClusterV3) RandClient() *clientv3.Client {
  699. return c.clients[rand.Intn(len(c.clients))]
  700. }
  701. func (c *ClusterV3) Client(i int) *clientv3.Client {
  702. return c.clients[i]
  703. }
  704. type grpcAPI struct {
  705. // Cluster is the cluster API for the client's connection.
  706. Cluster pb.ClusterClient
  707. // KV is the keyvalue API for the client's connection.
  708. KV pb.KVClient
  709. // Lease is the lease API for the client's connection.
  710. Lease pb.LeaseClient
  711. // Watch is the watch API for the client's connection.
  712. Watch pb.WatchClient
  713. // Maintenance is the maintenance API for the client's connection.
  714. Maintenance pb.MaintenanceClient
  715. }
  716. func toGRPC(c *clientv3.Client) grpcAPI {
  717. return grpcAPI{
  718. pb.NewClusterClient(c.ActiveConnection()),
  719. pb.NewKVClient(c.ActiveConnection()),
  720. pb.NewLeaseClient(c.ActiveConnection()),
  721. pb.NewWatchClient(c.ActiveConnection()),
  722. pb.NewMaintenanceClient(c.ActiveConnection()),
  723. }
  724. }