cluster.go 19 KB

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