cluster.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. if err := c.removeMember(t, id); err != nil {
  247. t.Fatal(err)
  248. }
  249. }
  250. func (c *cluster) removeMember(t *testing.T, id uint64) error {
  251. // send remove request to the cluster
  252. cc := MustNewHTTPClient(t, c.URLs(), c.cfg.ClientTLS)
  253. ma := client.NewMembersAPI(cc)
  254. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  255. if err := ma.Remove(ctx, types.ID(id).String()); err != nil {
  256. return err
  257. }
  258. cancel()
  259. newMembers := make([]*member, 0)
  260. for _, m := range c.Members {
  261. if uint64(m.s.ID()) != id {
  262. newMembers = append(newMembers, m)
  263. } else {
  264. select {
  265. case <-m.s.StopNotify():
  266. m.Terminate(t)
  267. // 1s stop delay + election timeout + 1s disk and network delay + connection write timeout
  268. // TODO: remove connection write timeout by selecting on http response closeNotifier
  269. // blocking on https://github.com/golang/go/issues/9524
  270. case <-time.After(time.Second + time.Duration(electionTicks)*tickDuration + time.Second + rafthttp.ConnWriteTimeout):
  271. t.Fatalf("failed to remove member %s in time", m.s.ID())
  272. }
  273. }
  274. }
  275. c.Members = newMembers
  276. c.waitMembersMatch(t, c.HTTPMembers())
  277. return nil
  278. }
  279. func (c *cluster) Terminate(t *testing.T) {
  280. for _, m := range c.Members {
  281. m.Terminate(t)
  282. }
  283. }
  284. func (c *cluster) waitMembersMatch(t *testing.T, membs []client.Member) {
  285. for _, u := range c.URLs() {
  286. cc := MustNewHTTPClient(t, []string{u}, c.cfg.ClientTLS)
  287. ma := client.NewMembersAPI(cc)
  288. for {
  289. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  290. ms, err := ma.List(ctx)
  291. cancel()
  292. if err == nil && isMembersEqual(ms, membs) {
  293. break
  294. }
  295. time.Sleep(tickDuration)
  296. }
  297. }
  298. return
  299. }
  300. func (c *cluster) WaitLeader(t *testing.T) int { return c.waitLeader(t, c.Members) }
  301. // waitLeader waits until given members agree on the same leader.
  302. func (c *cluster) waitLeader(t *testing.T, membs []*member) int {
  303. possibleLead := make(map[uint64]bool)
  304. var lead uint64
  305. for _, m := range membs {
  306. possibleLead[uint64(m.s.ID())] = true
  307. }
  308. for lead == 0 || !possibleLead[lead] {
  309. lead = 0
  310. for _, m := range membs {
  311. select {
  312. case <-m.s.StopNotify():
  313. continue
  314. default:
  315. }
  316. if lead != 0 && lead != m.s.Lead() {
  317. lead = 0
  318. time.Sleep(10 * tickDuration)
  319. break
  320. }
  321. lead = m.s.Lead()
  322. }
  323. }
  324. for i, m := range membs {
  325. if uint64(m.s.ID()) == lead {
  326. return i
  327. }
  328. }
  329. return -1
  330. }
  331. func (c *cluster) WaitNoLeader(t *testing.T) { c.waitNoLeader(t, c.Members) }
  332. // waitNoLeader waits until given members lose leader.
  333. func (c *cluster) waitNoLeader(t *testing.T, membs []*member) {
  334. noLeader := false
  335. for !noLeader {
  336. noLeader = true
  337. for _, m := range membs {
  338. select {
  339. case <-m.s.StopNotify():
  340. continue
  341. default:
  342. }
  343. if m.s.Lead() != 0 {
  344. noLeader = false
  345. time.Sleep(10 * tickDuration)
  346. break
  347. }
  348. }
  349. }
  350. }
  351. func (c *cluster) waitVersion() {
  352. for _, m := range c.Members {
  353. for {
  354. if m.s.ClusterVersion() != nil {
  355. break
  356. }
  357. time.Sleep(tickDuration)
  358. }
  359. }
  360. }
  361. func (c *cluster) name(i int) string {
  362. return fmt.Sprint(i)
  363. }
  364. // isMembersEqual checks whether two members equal except ID field.
  365. // The given wmembs should always set ID field to empty string.
  366. func isMembersEqual(membs []client.Member, wmembs []client.Member) bool {
  367. sort.Sort(SortableMemberSliceByPeerURLs(membs))
  368. sort.Sort(SortableMemberSliceByPeerURLs(wmembs))
  369. for i := range membs {
  370. membs[i].ID = ""
  371. }
  372. return reflect.DeepEqual(membs, wmembs)
  373. }
  374. func newLocalListener(t *testing.T) net.Listener {
  375. c := atomic.AddInt64(&localListenCount, 1)
  376. // Go 1.8+ allows only numbers in port
  377. addr := fmt.Sprintf("127.0.0.1:%05d%05d", c+basePort, os.Getpid())
  378. return NewListenerWithAddr(t, addr)
  379. }
  380. func NewListenerWithAddr(t *testing.T, addr string) net.Listener {
  381. l, err := transport.NewUnixListener(addr)
  382. if err != nil {
  383. t.Fatal(err)
  384. }
  385. return l
  386. }
  387. type member struct {
  388. etcdserver.ServerConfig
  389. PeerListeners, ClientListeners []net.Listener
  390. grpcListener net.Listener
  391. // PeerTLSInfo enables peer TLS when set
  392. PeerTLSInfo *transport.TLSInfo
  393. // ClientTLSInfo enables client TLS when set
  394. ClientTLSInfo *transport.TLSInfo
  395. raftHandler *testutil.PauseableHandler
  396. s *etcdserver.EtcdServer
  397. hss []*httptest.Server
  398. grpcServer *grpc.Server
  399. grpcAddr string
  400. grpcBridge *bridge
  401. keepDataDirTerminate bool
  402. }
  403. func (m *member) GRPCAddr() string { return m.grpcAddr }
  404. type memberConfig struct {
  405. name string
  406. peerTLS *transport.TLSInfo
  407. clientTLS *transport.TLSInfo
  408. quotaBackendBytes int64
  409. }
  410. // mustNewMember return an inited member with the given name. If peerTLS is
  411. // set, it will use https scheme to communicate between peers.
  412. func mustNewMember(t *testing.T, mcfg memberConfig) *member {
  413. var err error
  414. m := &member{}
  415. peerScheme := schemeFromTLSInfo(mcfg.peerTLS)
  416. clientScheme := schemeFromTLSInfo(mcfg.clientTLS)
  417. pln := newLocalListener(t)
  418. m.PeerListeners = []net.Listener{pln}
  419. m.PeerURLs, err = types.NewURLs([]string{peerScheme + "://" + pln.Addr().String()})
  420. if err != nil {
  421. t.Fatal(err)
  422. }
  423. m.PeerTLSInfo = mcfg.peerTLS
  424. cln := newLocalListener(t)
  425. m.ClientListeners = []net.Listener{cln}
  426. m.ClientURLs, err = types.NewURLs([]string{clientScheme + "://" + cln.Addr().String()})
  427. if err != nil {
  428. t.Fatal(err)
  429. }
  430. m.ClientTLSInfo = mcfg.clientTLS
  431. m.Name = mcfg.name
  432. m.DataDir, err = ioutil.TempDir(os.TempDir(), "etcd")
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. clusterStr := fmt.Sprintf("%s=%s://%s", mcfg.name, peerScheme, pln.Addr().String())
  437. m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  438. if err != nil {
  439. t.Fatal(err)
  440. }
  441. m.InitialClusterToken = clusterName
  442. m.NewCluster = true
  443. m.BootstrapTimeout = 10 * time.Millisecond
  444. if m.PeerTLSInfo != nil {
  445. m.ServerConfig.PeerTLSInfo = *m.PeerTLSInfo
  446. }
  447. m.ElectionTicks = electionTicks
  448. m.InitialElectionTickAdvance = true
  449. m.TickMs = uint(tickDuration / time.Millisecond)
  450. m.QuotaBackendBytes = mcfg.quotaBackendBytes
  451. return m
  452. }
  453. // listenGRPC starts a grpc server over a unix domain socket on the member
  454. func (m *member) listenGRPC() error {
  455. // prefix with localhost so cert has right domain
  456. m.grpcAddr = "localhost:" + m.Name
  457. l, err := transport.NewUnixListener(m.grpcAddr)
  458. if err != nil {
  459. return fmt.Errorf("listen failed on grpc socket %s (%v)", m.grpcAddr, err)
  460. }
  461. m.grpcBridge, err = newBridge(m.grpcAddr)
  462. if err != nil {
  463. l.Close()
  464. return err
  465. }
  466. m.grpcAddr = m.grpcBridge.URL()
  467. m.grpcListener = l
  468. return nil
  469. }
  470. func (m *member) electionTimeout() time.Duration {
  471. return time.Duration(m.s.Cfg.ElectionTicks) * time.Millisecond
  472. }
  473. func (m *member) DropConnections() { m.grpcBridge.Reset() }
  474. func (m *member) PauseConnections() { m.grpcBridge.Pause() }
  475. func (m *member) UnpauseConnections() { m.grpcBridge.Unpause() }
  476. // NewClientV3 creates a new grpc client connection to the member
  477. func NewClientV3(m *member) (*clientv3.Client, error) {
  478. if m.grpcAddr == "" {
  479. return nil, fmt.Errorf("member not configured for grpc")
  480. }
  481. cfg := clientv3.Config{
  482. Endpoints: []string{m.grpcAddr},
  483. DialTimeout: 5 * time.Second,
  484. }
  485. if m.ClientTLSInfo != nil {
  486. tls, err := m.ClientTLSInfo.ClientConfig()
  487. if err != nil {
  488. return nil, err
  489. }
  490. cfg.TLS = tls
  491. }
  492. return newClientV3(cfg)
  493. }
  494. // Clone returns a member with the same server configuration. The returned
  495. // member will not set PeerListeners and ClientListeners.
  496. func (m *member) Clone(t *testing.T) *member {
  497. mm := &member{}
  498. mm.ServerConfig = m.ServerConfig
  499. var err error
  500. clientURLStrs := m.ClientURLs.StringSlice()
  501. mm.ClientURLs, err = types.NewURLs(clientURLStrs)
  502. if err != nil {
  503. // this should never fail
  504. panic(err)
  505. }
  506. peerURLStrs := m.PeerURLs.StringSlice()
  507. mm.PeerURLs, err = types.NewURLs(peerURLStrs)
  508. if err != nil {
  509. // this should never fail
  510. panic(err)
  511. }
  512. clusterStr := m.InitialPeerURLsMap.String()
  513. mm.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  514. if err != nil {
  515. // this should never fail
  516. panic(err)
  517. }
  518. mm.InitialClusterToken = m.InitialClusterToken
  519. mm.ElectionTicks = m.ElectionTicks
  520. mm.PeerTLSInfo = m.PeerTLSInfo
  521. mm.ClientTLSInfo = m.ClientTLSInfo
  522. return mm
  523. }
  524. // Launch starts a member based on ServerConfig, PeerListeners
  525. // and ClientListeners.
  526. func (m *member) Launch() error {
  527. plog.Printf("launching %s (%s)", m.Name, m.grpcAddr)
  528. var err error
  529. if m.s, err = etcdserver.NewServer(&m.ServerConfig); err != nil {
  530. return fmt.Errorf("failed to initialize the etcd server: %v", err)
  531. }
  532. m.s.SyncTicker = time.Tick(500 * time.Millisecond)
  533. m.s.Start()
  534. m.raftHandler = &testutil.PauseableHandler{Next: v2http.NewPeerHandler(m.s)}
  535. for _, ln := range m.PeerListeners {
  536. hs := &httptest.Server{
  537. Listener: ln,
  538. Config: &http.Server{Handler: m.raftHandler},
  539. }
  540. if m.PeerTLSInfo == nil {
  541. hs.Start()
  542. } else {
  543. hs.TLS, err = m.PeerTLSInfo.ServerConfig()
  544. if err != nil {
  545. return err
  546. }
  547. hs.StartTLS()
  548. }
  549. m.hss = append(m.hss, hs)
  550. }
  551. for _, ln := range m.ClientListeners {
  552. hs := &httptest.Server{
  553. Listener: ln,
  554. Config: &http.Server{Handler: v2http.NewClientHandler(m.s, m.ServerConfig.ReqTimeout())},
  555. }
  556. if m.ClientTLSInfo == nil {
  557. hs.Start()
  558. } else {
  559. hs.TLS, err = m.ClientTLSInfo.ServerConfig()
  560. if err != nil {
  561. return err
  562. }
  563. hs.StartTLS()
  564. }
  565. m.hss = append(m.hss, hs)
  566. }
  567. if m.grpcListener != nil {
  568. var (
  569. tlscfg *tls.Config
  570. )
  571. if m.ClientTLSInfo != nil && !m.ClientTLSInfo.Empty() {
  572. tlscfg, err = m.ClientTLSInfo.ServerConfig()
  573. if err != nil {
  574. return err
  575. }
  576. }
  577. m.grpcServer = v3rpc.Server(m.s, tlscfg)
  578. go m.grpcServer.Serve(m.grpcListener)
  579. }
  580. plog.Printf("launched %s (%s)", m.Name, m.grpcAddr)
  581. return nil
  582. }
  583. func (m *member) WaitOK(t *testing.T) {
  584. cc := MustNewHTTPClient(t, []string{m.URL()}, m.ClientTLSInfo)
  585. kapi := client.NewKeysAPI(cc)
  586. for {
  587. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  588. _, err := kapi.Get(ctx, "/", nil)
  589. if err != nil {
  590. time.Sleep(tickDuration)
  591. continue
  592. }
  593. cancel()
  594. break
  595. }
  596. for m.s.Leader() == 0 {
  597. time.Sleep(tickDuration)
  598. }
  599. }
  600. func (m *member) URL() string { return m.ClientURLs[0].String() }
  601. func (m *member) Pause() {
  602. m.raftHandler.Pause()
  603. m.s.PauseSending()
  604. }
  605. func (m *member) Resume() {
  606. m.raftHandler.Resume()
  607. m.s.ResumeSending()
  608. }
  609. // Close stops the member's etcdserver and closes its connections
  610. func (m *member) Close() {
  611. if m.grpcBridge != nil {
  612. m.grpcBridge.Close()
  613. m.grpcBridge = nil
  614. }
  615. if m.grpcServer != nil {
  616. m.grpcServer.Stop()
  617. m.grpcServer = nil
  618. }
  619. m.s.HardStop()
  620. for _, hs := range m.hss {
  621. hs.CloseClientConnections()
  622. hs.Close()
  623. }
  624. }
  625. // Stop stops the member, but the data dir of the member is preserved.
  626. func (m *member) Stop(t *testing.T) {
  627. plog.Printf("stopping %s (%s)", m.Name, m.grpcAddr)
  628. m.Close()
  629. m.hss = nil
  630. plog.Printf("stopped %s (%s)", m.Name, m.grpcAddr)
  631. }
  632. // checkLeaderTransition waits for leader transition, returning the new leader ID.
  633. func checkLeaderTransition(t *testing.T, m *member, oldLead uint64) uint64 {
  634. interval := time.Duration(m.s.Cfg.TickMs) * time.Millisecond
  635. for m.s.Lead() == 0 || (m.s.Lead() == oldLead) {
  636. time.Sleep(interval)
  637. }
  638. return m.s.Lead()
  639. }
  640. // StopNotify unblocks when a member stop completes
  641. func (m *member) StopNotify() <-chan struct{} {
  642. return m.s.StopNotify()
  643. }
  644. // Restart starts the member using the preserved data dir.
  645. func (m *member) Restart(t *testing.T) error {
  646. plog.Printf("restarting %s (%s)", m.Name, m.grpcAddr)
  647. newPeerListeners := make([]net.Listener, 0)
  648. for _, ln := range m.PeerListeners {
  649. newPeerListeners = append(newPeerListeners, NewListenerWithAddr(t, ln.Addr().String()))
  650. }
  651. m.PeerListeners = newPeerListeners
  652. newClientListeners := make([]net.Listener, 0)
  653. for _, ln := range m.ClientListeners {
  654. newClientListeners = append(newClientListeners, NewListenerWithAddr(t, ln.Addr().String()))
  655. }
  656. m.ClientListeners = newClientListeners
  657. if m.grpcListener != nil {
  658. if err := m.listenGRPC(); err != nil {
  659. t.Fatal(err)
  660. }
  661. }
  662. err := m.Launch()
  663. plog.Printf("restarted %s (%s)", m.Name, m.grpcAddr)
  664. return err
  665. }
  666. // Terminate stops the member and removes the data dir.
  667. func (m *member) Terminate(t *testing.T) {
  668. plog.Printf("terminating %s (%s)", m.Name, m.grpcAddr)
  669. m.Close()
  670. if !m.keepDataDirTerminate {
  671. if err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {
  672. t.Fatal(err)
  673. }
  674. }
  675. plog.Printf("terminated %s (%s)", m.Name, m.grpcAddr)
  676. }
  677. // Metric gets the metric value for a member
  678. func (m *member) Metric(metricName string) (string, error) {
  679. cfgtls := transport.TLSInfo{}
  680. tr, err := transport.NewTimeoutTransport(cfgtls, time.Second, time.Second, time.Second)
  681. if err != nil {
  682. return "", err
  683. }
  684. cli := &http.Client{Transport: tr}
  685. resp, err := cli.Get(m.ClientURLs[0].String() + "/metrics")
  686. if err != nil {
  687. return "", err
  688. }
  689. defer resp.Body.Close()
  690. b, rerr := ioutil.ReadAll(resp.Body)
  691. if rerr != nil {
  692. return "", rerr
  693. }
  694. lines := strings.Split(string(b), "\n")
  695. for _, l := range lines {
  696. if strings.HasPrefix(l, metricName) {
  697. return strings.Split(l, " ")[1], nil
  698. }
  699. }
  700. return "", nil
  701. }
  702. // InjectPartition drops connections from m to others, vice versa.
  703. func (m *member) InjectPartition(t *testing.T, others []*member) {
  704. for _, other := range others {
  705. m.s.CutPeer(other.s.ID())
  706. other.s.CutPeer(m.s.ID())
  707. }
  708. }
  709. // RecoverPartition recovers connections from m to others, vice versa.
  710. func (m *member) RecoverPartition(t *testing.T, others []*member) {
  711. for _, other := range others {
  712. m.s.MendPeer(other.s.ID())
  713. other.s.MendPeer(m.s.ID())
  714. }
  715. }
  716. func MustNewHTTPClient(t *testing.T, eps []string, tls *transport.TLSInfo) client.Client {
  717. cfgtls := transport.TLSInfo{}
  718. if tls != nil {
  719. cfgtls = *tls
  720. }
  721. cfg := client.Config{Transport: mustNewTransport(t, cfgtls), Endpoints: eps}
  722. c, err := client.New(cfg)
  723. if err != nil {
  724. t.Fatal(err)
  725. }
  726. return c
  727. }
  728. func mustNewTransport(t *testing.T, tlsInfo transport.TLSInfo) *http.Transport {
  729. // tick in integration test is short, so 1s dial timeout could play well.
  730. tr, err := transport.NewTimeoutTransport(tlsInfo, time.Second, rafthttp.ConnReadTimeout, rafthttp.ConnWriteTimeout)
  731. if err != nil {
  732. t.Fatal(err)
  733. }
  734. return tr
  735. }
  736. type SortableMemberSliceByPeerURLs []client.Member
  737. func (p SortableMemberSliceByPeerURLs) Len() int { return len(p) }
  738. func (p SortableMemberSliceByPeerURLs) Less(i, j int) bool {
  739. return p[i].PeerURLs[0] < p[j].PeerURLs[0]
  740. }
  741. func (p SortableMemberSliceByPeerURLs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  742. type ClusterV3 struct {
  743. *cluster
  744. mu sync.Mutex
  745. clients []*clientv3.Client
  746. }
  747. // NewClusterV3 returns a launched cluster with a grpc client connection
  748. // for each cluster member.
  749. func NewClusterV3(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
  750. cfg.UseGRPC = true
  751. clus := &ClusterV3{
  752. cluster: NewClusterByConfig(t, cfg),
  753. }
  754. clus.Launch(t)
  755. for _, m := range clus.Members {
  756. client, err := NewClientV3(m)
  757. if err != nil {
  758. t.Fatalf("cannot create client: %v", err)
  759. }
  760. clus.clients = append(clus.clients, client)
  761. }
  762. return clus
  763. }
  764. func (c *ClusterV3) TakeClient(idx int) {
  765. c.mu.Lock()
  766. c.clients[idx] = nil
  767. c.mu.Unlock()
  768. }
  769. func (c *ClusterV3) Terminate(t *testing.T) {
  770. c.mu.Lock()
  771. for _, client := range c.clients {
  772. if client == nil {
  773. continue
  774. }
  775. if err := client.Close(); err != nil {
  776. t.Error(err)
  777. }
  778. }
  779. c.mu.Unlock()
  780. c.cluster.Terminate(t)
  781. }
  782. func (c *ClusterV3) RandClient() *clientv3.Client {
  783. return c.clients[rand.Intn(len(c.clients))]
  784. }
  785. func (c *ClusterV3) Client(i int) *clientv3.Client {
  786. return c.clients[i]
  787. }
  788. type grpcAPI struct {
  789. // Cluster is the cluster API for the client's connection.
  790. Cluster pb.ClusterClient
  791. // KV is the keyvalue API for the client's connection.
  792. KV pb.KVClient
  793. // Lease is the lease API for the client's connection.
  794. Lease pb.LeaseClient
  795. // Watch is the watch API for the client's connection.
  796. Watch pb.WatchClient
  797. // Maintenance is the maintenance API for the client's connection.
  798. Maintenance pb.MaintenanceClient
  799. // Auth is the authentication API for the client's connection.
  800. Auth pb.AuthClient
  801. }