cluster.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. "github.com/coreos/etcd/client"
  32. "github.com/coreos/etcd/clientv3"
  33. "github.com/coreos/etcd/embed"
  34. "github.com/coreos/etcd/etcdserver"
  35. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  36. "github.com/coreos/etcd/etcdserver/api/v2http"
  37. "github.com/coreos/etcd/etcdserver/api/v3client"
  38. "github.com/coreos/etcd/etcdserver/api/v3election"
  39. epb "github.com/coreos/etcd/etcdserver/api/v3election/v3electionpb"
  40. "github.com/coreos/etcd/etcdserver/api/v3lock"
  41. lockpb "github.com/coreos/etcd/etcdserver/api/v3lock/v3lockpb"
  42. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  43. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  44. "github.com/coreos/etcd/pkg/testutil"
  45. "github.com/coreos/etcd/pkg/tlsutil"
  46. "github.com/coreos/etcd/pkg/transport"
  47. "github.com/coreos/etcd/pkg/types"
  48. "github.com/coreos/etcd/rafthttp"
  49. "github.com/coreos/pkg/capnslog"
  50. "golang.org/x/net/context"
  51. "google.golang.org/grpc"
  52. "google.golang.org/grpc/keepalive"
  53. )
  54. const (
  55. tickDuration = 10 * time.Millisecond
  56. clusterName = "etcd"
  57. requestTimeout = 20 * time.Second
  58. basePort = 21000
  59. UrlScheme = "unix"
  60. UrlSchemeTLS = "unixs"
  61. )
  62. var (
  63. electionTicks = 10
  64. // integration test uses unique ports, counting up, to listen for each
  65. // member, ensuring restarted members can listen on the same port again.
  66. localListenCount int64 = 0
  67. testTLSInfo = transport.TLSInfo{
  68. KeyFile: "./fixtures/server.key.insecure",
  69. CertFile: "./fixtures/server.crt",
  70. TrustedCAFile: "./fixtures/ca.crt",
  71. ClientCertAuth: true,
  72. }
  73. testTLSInfoExpired = transport.TLSInfo{
  74. KeyFile: "./fixtures-expired/server-key.pem",
  75. CertFile: "./fixtures-expired/server.pem",
  76. TrustedCAFile: "./fixtures-expired/etcd-root-ca.pem",
  77. ClientCertAuth: true,
  78. }
  79. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "integration")
  80. )
  81. type ClusterConfig struct {
  82. Size int
  83. PeerTLS *transport.TLSInfo
  84. ClientTLS *transport.TLSInfo
  85. DiscoveryURL string
  86. UseGRPC bool
  87. QuotaBackendBytes int64
  88. MaxRequestBytes uint
  89. GRPCKeepAliveMinTime time.Duration
  90. GRPCKeepAliveInterval time.Duration
  91. GRPCKeepAliveTimeout time.Duration
  92. // SkipCreatingClient to skip creating clients for each member.
  93. SkipCreatingClient bool
  94. ClientMaxCallSendMsgSize int
  95. ClientMaxCallRecvMsgSize int
  96. }
  97. type cluster struct {
  98. cfg *ClusterConfig
  99. Members []*member
  100. }
  101. func schemeFromTLSInfo(tls *transport.TLSInfo) string {
  102. if tls == nil {
  103. return UrlScheme
  104. }
  105. return UrlSchemeTLS
  106. }
  107. func (c *cluster) fillClusterForMembers() error {
  108. if c.cfg.DiscoveryURL != "" {
  109. // cluster will be discovered
  110. return nil
  111. }
  112. addrs := make([]string, 0)
  113. for _, m := range c.Members {
  114. scheme := schemeFromTLSInfo(m.PeerTLSInfo)
  115. for _, l := range m.PeerListeners {
  116. addrs = append(addrs, fmt.Sprintf("%s=%s://%s", m.Name, scheme, l.Addr().String()))
  117. }
  118. }
  119. clusterStr := strings.Join(addrs, ",")
  120. var err error
  121. for _, m := range c.Members {
  122. m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. return nil
  128. }
  129. func newCluster(t *testing.T, cfg *ClusterConfig) *cluster {
  130. c := &cluster{cfg: cfg}
  131. ms := make([]*member, cfg.Size)
  132. for i := 0; i < cfg.Size; i++ {
  133. ms[i] = c.mustNewMember(t)
  134. }
  135. c.Members = ms
  136. if err := c.fillClusterForMembers(); err != nil {
  137. t.Fatal(err)
  138. }
  139. return c
  140. }
  141. // NewCluster returns an unlaunched cluster of the given size which has been
  142. // set to use static bootstrap.
  143. func NewCluster(t *testing.T, size int) *cluster {
  144. return newCluster(t, &ClusterConfig{Size: size})
  145. }
  146. // NewClusterByConfig returns an unlaunched cluster defined by a cluster configuration
  147. func NewClusterByConfig(t *testing.T, cfg *ClusterConfig) *cluster {
  148. return newCluster(t, cfg)
  149. }
  150. func (c *cluster) Launch(t *testing.T) {
  151. errc := make(chan error)
  152. for _, m := range c.Members {
  153. // Members are launched in separate goroutines because if they boot
  154. // using discovery url, they have to wait for others to register to continue.
  155. go func(m *member) {
  156. errc <- m.Launch()
  157. }(m)
  158. }
  159. for range c.Members {
  160. if err := <-errc; err != nil {
  161. t.Fatalf("error setting up member: %v", err)
  162. }
  163. }
  164. // wait cluster to be stable to receive future client requests
  165. c.waitMembersMatch(t, c.HTTPMembers())
  166. c.waitVersion()
  167. }
  168. func (c *cluster) URL(i int) string {
  169. return c.Members[i].ClientURLs[0].String()
  170. }
  171. // URLs returns a list of all active client URLs in the cluster
  172. func (c *cluster) URLs() []string {
  173. return getMembersURLs(c.Members)
  174. }
  175. func getMembersURLs(members []*member) []string {
  176. urls := make([]string, 0)
  177. for _, m := range members {
  178. select {
  179. case <-m.s.StopNotify():
  180. continue
  181. default:
  182. }
  183. for _, u := range m.ClientURLs {
  184. urls = append(urls, u.String())
  185. }
  186. }
  187. return urls
  188. }
  189. // HTTPMembers returns a list of all active members as client.Members
  190. func (c *cluster) HTTPMembers() []client.Member {
  191. ms := []client.Member{}
  192. for _, m := range c.Members {
  193. pScheme := schemeFromTLSInfo(m.PeerTLSInfo)
  194. cScheme := schemeFromTLSInfo(m.ClientTLSInfo)
  195. cm := client.Member{Name: m.Name}
  196. for _, ln := range m.PeerListeners {
  197. cm.PeerURLs = append(cm.PeerURLs, pScheme+"://"+ln.Addr().String())
  198. }
  199. for _, ln := range m.ClientListeners {
  200. cm.ClientURLs = append(cm.ClientURLs, cScheme+"://"+ln.Addr().String())
  201. }
  202. ms = append(ms, cm)
  203. }
  204. return ms
  205. }
  206. func (c *cluster) mustNewMember(t *testing.T) *member {
  207. m := mustNewMember(t,
  208. memberConfig{
  209. name: c.name(rand.Int()),
  210. peerTLS: c.cfg.PeerTLS,
  211. clientTLS: c.cfg.ClientTLS,
  212. quotaBackendBytes: c.cfg.QuotaBackendBytes,
  213. maxRequestBytes: c.cfg.MaxRequestBytes,
  214. grpcKeepAliveMinTime: c.cfg.GRPCKeepAliveMinTime,
  215. grpcKeepAliveInterval: c.cfg.GRPCKeepAliveInterval,
  216. grpcKeepAliveTimeout: c.cfg.GRPCKeepAliveTimeout,
  217. clientMaxCallSendMsgSize: c.cfg.ClientMaxCallSendMsgSize,
  218. clientMaxCallRecvMsgSize: c.cfg.ClientMaxCallRecvMsgSize,
  219. })
  220. m.DiscoveryURL = c.cfg.DiscoveryURL
  221. if c.cfg.UseGRPC {
  222. if err := m.listenGRPC(); err != nil {
  223. t.Fatal(err)
  224. }
  225. }
  226. return m
  227. }
  228. func (c *cluster) addMember(t *testing.T) {
  229. m := c.mustNewMember(t)
  230. scheme := schemeFromTLSInfo(c.cfg.PeerTLS)
  231. // send add request to the cluster
  232. var err error
  233. for i := 0; i < len(c.Members); i++ {
  234. clientURL := c.URL(i)
  235. peerURL := scheme + "://" + m.PeerListeners[0].Addr().String()
  236. if err = c.addMemberByURL(t, clientURL, peerURL); err == nil {
  237. break
  238. }
  239. }
  240. if err != nil {
  241. t.Fatalf("add member failed on all members error: %v", err)
  242. }
  243. m.InitialPeerURLsMap = types.URLsMap{}
  244. for _, mm := range c.Members {
  245. m.InitialPeerURLsMap[mm.Name] = mm.PeerURLs
  246. }
  247. m.InitialPeerURLsMap[m.Name] = m.PeerURLs
  248. m.NewCluster = false
  249. if err := m.Launch(); err != nil {
  250. t.Fatal(err)
  251. }
  252. c.Members = append(c.Members, m)
  253. // wait cluster to be stable to receive future client requests
  254. c.waitMembersMatch(t, c.HTTPMembers())
  255. }
  256. func (c *cluster) addMemberByURL(t *testing.T, clientURL, peerURL string) error {
  257. cc := MustNewHTTPClient(t, []string{clientURL}, c.cfg.ClientTLS)
  258. ma := client.NewMembersAPI(cc)
  259. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  260. if _, err := ma.Add(ctx, peerURL); err != nil {
  261. return err
  262. }
  263. cancel()
  264. // wait for the add node entry applied in the cluster
  265. members := append(c.HTTPMembers(), client.Member{PeerURLs: []string{peerURL}, ClientURLs: []string{}})
  266. c.waitMembersMatch(t, members)
  267. return nil
  268. }
  269. func (c *cluster) AddMember(t *testing.T) {
  270. c.addMember(t)
  271. }
  272. func (c *cluster) RemoveMember(t *testing.T, id uint64) {
  273. if err := c.removeMember(t, id); err != nil {
  274. t.Fatal(err)
  275. }
  276. }
  277. func (c *cluster) removeMember(t *testing.T, id uint64) error {
  278. // send remove request to the cluster
  279. cc := MustNewHTTPClient(t, c.URLs(), c.cfg.ClientTLS)
  280. ma := client.NewMembersAPI(cc)
  281. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  282. if err := ma.Remove(ctx, types.ID(id).String()); err != nil {
  283. return err
  284. }
  285. cancel()
  286. newMembers := make([]*member, 0)
  287. for _, m := range c.Members {
  288. if uint64(m.s.ID()) != id {
  289. newMembers = append(newMembers, m)
  290. } else {
  291. select {
  292. case <-m.s.StopNotify():
  293. m.Terminate(t)
  294. // 1s stop delay + election timeout + 1s disk and network delay + connection write timeout
  295. // TODO: remove connection write timeout by selecting on http response closeNotifier
  296. // blocking on https://github.com/golang/go/issues/9524
  297. case <-time.After(time.Second + time.Duration(electionTicks)*tickDuration + time.Second + rafthttp.ConnWriteTimeout):
  298. t.Fatalf("failed to remove member %s in time", m.s.ID())
  299. }
  300. }
  301. }
  302. c.Members = newMembers
  303. c.waitMembersMatch(t, c.HTTPMembers())
  304. return nil
  305. }
  306. func (c *cluster) Terminate(t *testing.T) {
  307. var wg sync.WaitGroup
  308. wg.Add(len(c.Members))
  309. for _, m := range c.Members {
  310. go func(mm *member) {
  311. defer wg.Done()
  312. mm.Terminate(t)
  313. }(m)
  314. }
  315. wg.Wait()
  316. }
  317. func (c *cluster) waitMembersMatch(t *testing.T, membs []client.Member) {
  318. for _, u := range c.URLs() {
  319. cc := MustNewHTTPClient(t, []string{u}, c.cfg.ClientTLS)
  320. ma := client.NewMembersAPI(cc)
  321. for {
  322. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  323. ms, err := ma.List(ctx)
  324. cancel()
  325. if err == nil && isMembersEqual(ms, membs) {
  326. break
  327. }
  328. time.Sleep(tickDuration)
  329. }
  330. }
  331. }
  332. func (c *cluster) WaitLeader(t *testing.T) int { return c.waitLeader(t, c.Members) }
  333. // waitLeader waits until given members agree on the same leader.
  334. func (c *cluster) waitLeader(t *testing.T, membs []*member) int {
  335. possibleLead := make(map[uint64]bool)
  336. var lead uint64
  337. for _, m := range membs {
  338. possibleLead[uint64(m.s.ID())] = true
  339. }
  340. cc := MustNewHTTPClient(t, getMembersURLs(membs), nil)
  341. kapi := client.NewKeysAPI(cc)
  342. // ensure leader is up via linearizable get
  343. for {
  344. ctx, cancel := context.WithTimeout(context.Background(), 10*tickDuration+time.Second)
  345. _, err := kapi.Get(ctx, "0", &client.GetOptions{Quorum: true})
  346. cancel()
  347. if err == nil || strings.Contains(err.Error(), "Key not found") {
  348. break
  349. }
  350. }
  351. for lead == 0 || !possibleLead[lead] {
  352. lead = 0
  353. for _, m := range membs {
  354. select {
  355. case <-m.s.StopNotify():
  356. continue
  357. default:
  358. }
  359. if lead != 0 && lead != m.s.Lead() {
  360. lead = 0
  361. time.Sleep(10 * tickDuration)
  362. break
  363. }
  364. lead = m.s.Lead()
  365. }
  366. }
  367. for i, m := range membs {
  368. if uint64(m.s.ID()) == lead {
  369. return i
  370. }
  371. }
  372. return -1
  373. }
  374. func (c *cluster) WaitNoLeader(t *testing.T) { c.waitNoLeader(t, c.Members) }
  375. // waitNoLeader waits until given members lose leader.
  376. func (c *cluster) waitNoLeader(t *testing.T, membs []*member) {
  377. noLeader := false
  378. for !noLeader {
  379. noLeader = true
  380. for _, m := range membs {
  381. select {
  382. case <-m.s.StopNotify():
  383. continue
  384. default:
  385. }
  386. if m.s.Lead() != 0 {
  387. noLeader = false
  388. time.Sleep(10 * tickDuration)
  389. break
  390. }
  391. }
  392. }
  393. }
  394. func (c *cluster) waitVersion() {
  395. for _, m := range c.Members {
  396. for {
  397. if m.s.ClusterVersion() != nil {
  398. break
  399. }
  400. time.Sleep(tickDuration)
  401. }
  402. }
  403. }
  404. func (c *cluster) name(i int) string {
  405. return fmt.Sprint(i)
  406. }
  407. // isMembersEqual checks whether two members equal except ID field.
  408. // The given wmembs should always set ID field to empty string.
  409. func isMembersEqual(membs []client.Member, wmembs []client.Member) bool {
  410. sort.Sort(SortableMemberSliceByPeerURLs(membs))
  411. sort.Sort(SortableMemberSliceByPeerURLs(wmembs))
  412. for i := range membs {
  413. membs[i].ID = ""
  414. }
  415. return reflect.DeepEqual(membs, wmembs)
  416. }
  417. func newLocalListener(t *testing.T) net.Listener {
  418. c := atomic.AddInt64(&localListenCount, 1)
  419. // Go 1.8+ allows only numbers in port
  420. addr := fmt.Sprintf("127.0.0.1:%05d%05d", c+basePort, os.Getpid())
  421. return NewListenerWithAddr(t, addr)
  422. }
  423. func NewListenerWithAddr(t *testing.T, addr string) net.Listener {
  424. l, err := transport.NewUnixListener(addr)
  425. if err != nil {
  426. t.Fatal(err)
  427. }
  428. return l
  429. }
  430. type member struct {
  431. etcdserver.ServerConfig
  432. PeerListeners, ClientListeners []net.Listener
  433. grpcListener net.Listener
  434. // PeerTLSInfo enables peer TLS when set
  435. PeerTLSInfo *transport.TLSInfo
  436. // ClientTLSInfo enables client TLS when set
  437. ClientTLSInfo *transport.TLSInfo
  438. raftHandler *testutil.PauseableHandler
  439. s *etcdserver.EtcdServer
  440. hss []*httptest.Server
  441. grpcServerOpts []grpc.ServerOption
  442. grpcServer *grpc.Server
  443. grpcAddr string
  444. grpcBridge *bridge
  445. // serverClient is a clientv3 that directly calls the etcdserver.
  446. serverClient *clientv3.Client
  447. keepDataDirTerminate bool
  448. clientMaxCallSendMsgSize int
  449. clientMaxCallRecvMsgSize int
  450. }
  451. func (m *member) GRPCAddr() string { return m.grpcAddr }
  452. type memberConfig struct {
  453. name string
  454. peerTLS *transport.TLSInfo
  455. clientTLS *transport.TLSInfo
  456. quotaBackendBytes int64
  457. maxRequestBytes uint
  458. grpcKeepAliveMinTime time.Duration
  459. grpcKeepAliveInterval time.Duration
  460. grpcKeepAliveTimeout time.Duration
  461. clientMaxCallSendMsgSize int
  462. clientMaxCallRecvMsgSize int
  463. }
  464. // mustNewMember return an inited member with the given name. If peerTLS is
  465. // set, it will use https scheme to communicate between peers.
  466. func mustNewMember(t *testing.T, mcfg memberConfig) *member {
  467. var err error
  468. m := &member{}
  469. peerScheme := schemeFromTLSInfo(mcfg.peerTLS)
  470. clientScheme := schemeFromTLSInfo(mcfg.clientTLS)
  471. pln := newLocalListener(t)
  472. m.PeerListeners = []net.Listener{pln}
  473. m.PeerURLs, err = types.NewURLs([]string{peerScheme + "://" + pln.Addr().String()})
  474. if err != nil {
  475. t.Fatal(err)
  476. }
  477. m.PeerTLSInfo = mcfg.peerTLS
  478. cln := newLocalListener(t)
  479. m.ClientListeners = []net.Listener{cln}
  480. m.ClientURLs, err = types.NewURLs([]string{clientScheme + "://" + cln.Addr().String()})
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. m.ClientTLSInfo = mcfg.clientTLS
  485. m.Name = mcfg.name
  486. m.DataDir, err = ioutil.TempDir(os.TempDir(), "etcd")
  487. if err != nil {
  488. t.Fatal(err)
  489. }
  490. clusterStr := fmt.Sprintf("%s=%s://%s", mcfg.name, peerScheme, pln.Addr().String())
  491. m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  492. if err != nil {
  493. t.Fatal(err)
  494. }
  495. m.InitialClusterToken = clusterName
  496. m.NewCluster = true
  497. m.BootstrapTimeout = 10 * time.Millisecond
  498. if m.PeerTLSInfo != nil {
  499. m.ServerConfig.PeerTLSInfo = *m.PeerTLSInfo
  500. }
  501. m.ElectionTicks = electionTicks
  502. m.InitialElectionTickAdvance = true
  503. m.TickMs = uint(tickDuration / time.Millisecond)
  504. m.QuotaBackendBytes = mcfg.quotaBackendBytes
  505. m.MaxRequestBytes = mcfg.maxRequestBytes
  506. if m.MaxRequestBytes == 0 {
  507. m.MaxRequestBytes = embed.DefaultMaxRequestBytes
  508. }
  509. m.AuthToken = "simple" // for the purpose of integration testing, simple token is enough
  510. m.grpcServerOpts = []grpc.ServerOption{}
  511. if mcfg.grpcKeepAliveMinTime > time.Duration(0) {
  512. m.grpcServerOpts = append(m.grpcServerOpts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  513. MinTime: mcfg.grpcKeepAliveMinTime,
  514. PermitWithoutStream: false,
  515. }))
  516. }
  517. if mcfg.grpcKeepAliveInterval > time.Duration(0) &&
  518. mcfg.grpcKeepAliveTimeout > time.Duration(0) {
  519. m.grpcServerOpts = append(m.grpcServerOpts, grpc.KeepaliveParams(keepalive.ServerParameters{
  520. Time: mcfg.grpcKeepAliveInterval,
  521. Timeout: mcfg.grpcKeepAliveTimeout,
  522. }))
  523. }
  524. m.clientMaxCallSendMsgSize = mcfg.clientMaxCallSendMsgSize
  525. m.clientMaxCallRecvMsgSize = mcfg.clientMaxCallRecvMsgSize
  526. return m
  527. }
  528. // listenGRPC starts a grpc server over a unix domain socket on the member
  529. func (m *member) listenGRPC() error {
  530. // prefix with localhost so cert has right domain
  531. m.grpcAddr = "localhost:" + m.Name
  532. l, err := transport.NewUnixListener(m.grpcAddr)
  533. if err != nil {
  534. return fmt.Errorf("listen failed on grpc socket %s (%v)", m.grpcAddr, err)
  535. }
  536. m.grpcBridge, err = newBridge(m.grpcAddr)
  537. if err != nil {
  538. l.Close()
  539. return err
  540. }
  541. m.grpcAddr = schemeFromTLSInfo(m.ClientTLSInfo) + "://" + m.grpcBridge.inaddr
  542. m.grpcListener = l
  543. return nil
  544. }
  545. func (m *member) electionTimeout() time.Duration {
  546. return time.Duration(m.s.Cfg.ElectionTicks) * time.Millisecond
  547. }
  548. func (m *member) DropConnections() { m.grpcBridge.Reset() }
  549. func (m *member) PauseConnections() { m.grpcBridge.Pause() }
  550. func (m *member) UnpauseConnections() { m.grpcBridge.Unpause() }
  551. func (m *member) Blackhole() { m.grpcBridge.Blackhole() }
  552. func (m *member) Unblackhole() { m.grpcBridge.Unblackhole() }
  553. // NewClientV3 creates a new grpc client connection to the member
  554. func NewClientV3(m *member) (*clientv3.Client, error) {
  555. if m.grpcAddr == "" {
  556. return nil, fmt.Errorf("member not configured for grpc")
  557. }
  558. cfg := clientv3.Config{
  559. Endpoints: []string{m.grpcAddr},
  560. DialTimeout: 5 * time.Second,
  561. MaxCallSendMsgSize: m.clientMaxCallSendMsgSize,
  562. MaxCallRecvMsgSize: m.clientMaxCallRecvMsgSize,
  563. }
  564. if m.ClientTLSInfo != nil {
  565. tls, err := m.ClientTLSInfo.ClientConfig()
  566. if err != nil {
  567. return nil, err
  568. }
  569. cfg.TLS = tls
  570. }
  571. return newClientV3(cfg)
  572. }
  573. // Clone returns a member with the same server configuration. The returned
  574. // member will not set PeerListeners and ClientListeners.
  575. func (m *member) Clone(t *testing.T) *member {
  576. mm := &member{}
  577. mm.ServerConfig = m.ServerConfig
  578. var err error
  579. clientURLStrs := m.ClientURLs.StringSlice()
  580. mm.ClientURLs, err = types.NewURLs(clientURLStrs)
  581. if err != nil {
  582. // this should never fail
  583. panic(err)
  584. }
  585. peerURLStrs := m.PeerURLs.StringSlice()
  586. mm.PeerURLs, err = types.NewURLs(peerURLStrs)
  587. if err != nil {
  588. // this should never fail
  589. panic(err)
  590. }
  591. clusterStr := m.InitialPeerURLsMap.String()
  592. mm.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
  593. if err != nil {
  594. // this should never fail
  595. panic(err)
  596. }
  597. mm.InitialClusterToken = m.InitialClusterToken
  598. mm.ElectionTicks = m.ElectionTicks
  599. mm.PeerTLSInfo = m.PeerTLSInfo
  600. mm.ClientTLSInfo = m.ClientTLSInfo
  601. return mm
  602. }
  603. // Launch starts a member based on ServerConfig, PeerListeners
  604. // and ClientListeners.
  605. func (m *member) Launch() error {
  606. plog.Printf("launching %s (%s)", m.Name, m.grpcAddr)
  607. var err error
  608. if m.s, err = etcdserver.NewServer(&m.ServerConfig); err != nil {
  609. return fmt.Errorf("failed to initialize the etcd server: %v", err)
  610. }
  611. m.s.SyncTicker = time.NewTicker(500 * time.Millisecond)
  612. m.s.Start()
  613. m.raftHandler = &testutil.PauseableHandler{Next: etcdhttp.NewPeerHandler(m.s)}
  614. for _, ln := range m.PeerListeners {
  615. hs := &httptest.Server{
  616. Listener: ln,
  617. Config: &http.Server{Handler: m.raftHandler},
  618. }
  619. if m.PeerTLSInfo == nil {
  620. hs.Start()
  621. } else {
  622. info := m.PeerTLSInfo
  623. hs.TLS, err = info.ServerConfig()
  624. if err != nil {
  625. return err
  626. }
  627. tlsCert, err := tlsutil.NewCert(info.CertFile, info.KeyFile, nil)
  628. if err != nil {
  629. return err
  630. }
  631. hs.TLS.Certificates = []tls.Certificate{*tlsCert}
  632. hs.StartTLS()
  633. }
  634. m.hss = append(m.hss, hs)
  635. }
  636. for _, ln := range m.ClientListeners {
  637. hs := &httptest.Server{
  638. Listener: ln,
  639. Config: &http.Server{Handler: v2http.NewClientHandler(m.s, m.ServerConfig.ReqTimeout())},
  640. }
  641. if m.ClientTLSInfo == nil {
  642. hs.Start()
  643. } else {
  644. info := m.ClientTLSInfo
  645. hs.TLS, err = info.ServerConfig()
  646. if err != nil {
  647. return err
  648. }
  649. // baseConfig is called on initial TLS handshake start.
  650. //
  651. // Previously,
  652. // 1. Server has non-empty (*tls.Config).Certificates on client hello
  653. // 2. Server calls (*tls.Config).GetCertificate iff:
  654. // - Server's (*tls.Config).Certificates is not empty, or
  655. // - Client supplies SNI; non-empty (*tls.ClientHelloInfo).ServerName
  656. //
  657. // When (*tls.Config).Certificates is always populated on initial handshake,
  658. // client is expected to provide a valid matching SNI to pass the TLS
  659. // verification, thus trigger server (*tls.Config).GetCertificate to reload
  660. // TLS assets. However, a cert whose SAN field does not include domain names
  661. // but only IP addresses, has empty (*tls.ClientHelloInfo).ServerName, thus
  662. // it was never able to trigger TLS reload on initial handshake; first
  663. // ceritifcate object was being used, never being updated.
  664. //
  665. // Now, (*tls.Config).Certificates is created empty on initial TLS client
  666. // handshake, in order to trigger (*tls.Config).GetCertificate and populate
  667. // rest of the certificates on every new TLS connection, even when client
  668. // SNI is empty (e.g. cert only includes IPs).
  669. //
  670. // This introduces another problem with "httptest.Server":
  671. // when server initial certificates are empty, certificates
  672. // are overwritten by Go's internal test certs, which have
  673. // different SAN fields (e.g. example.com). To work around,
  674. // re-overwrite (*tls.Config).Certificates before starting
  675. // test server.
  676. tlsCert, err := tlsutil.NewCert(info.CertFile, info.KeyFile, nil)
  677. if err != nil {
  678. return err
  679. }
  680. hs.TLS.Certificates = []tls.Certificate{*tlsCert}
  681. hs.StartTLS()
  682. }
  683. m.hss = append(m.hss, hs)
  684. }
  685. if m.grpcListener != nil {
  686. var (
  687. tlscfg *tls.Config
  688. )
  689. if m.ClientTLSInfo != nil && !m.ClientTLSInfo.Empty() {
  690. tlscfg, err = m.ClientTLSInfo.ServerConfig()
  691. if err != nil {
  692. return err
  693. }
  694. }
  695. m.grpcServer = v3rpc.Server(m.s, tlscfg, m.grpcServerOpts...)
  696. m.serverClient = v3client.New(m.s)
  697. lockpb.RegisterLockServer(m.grpcServer, v3lock.NewLockServer(m.serverClient))
  698. epb.RegisterElectionServer(m.grpcServer, v3election.NewElectionServer(m.serverClient))
  699. go m.grpcServer.Serve(m.grpcListener)
  700. }
  701. plog.Printf("launched %s (%s)", m.Name, m.grpcAddr)
  702. return nil
  703. }
  704. func (m *member) WaitOK(t *testing.T) {
  705. cc := MustNewHTTPClient(t, []string{m.URL()}, m.ClientTLSInfo)
  706. kapi := client.NewKeysAPI(cc)
  707. for {
  708. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  709. _, err := kapi.Get(ctx, "/", nil)
  710. if err != nil {
  711. time.Sleep(tickDuration)
  712. continue
  713. }
  714. cancel()
  715. break
  716. }
  717. for m.s.Leader() == 0 {
  718. time.Sleep(tickDuration)
  719. }
  720. }
  721. func (m *member) URL() string { return m.ClientURLs[0].String() }
  722. func (m *member) Pause() {
  723. m.raftHandler.Pause()
  724. m.s.PauseSending()
  725. }
  726. func (m *member) Resume() {
  727. m.raftHandler.Resume()
  728. m.s.ResumeSending()
  729. }
  730. // Close stops the member's etcdserver and closes its connections
  731. func (m *member) Close() {
  732. if m.grpcBridge != nil {
  733. m.grpcBridge.Close()
  734. m.grpcBridge = nil
  735. }
  736. if m.serverClient != nil {
  737. m.serverClient.Close()
  738. m.serverClient = nil
  739. }
  740. if m.grpcServer != nil {
  741. m.grpcServer.GracefulStop()
  742. m.grpcServer = nil
  743. }
  744. m.s.HardStop()
  745. for _, hs := range m.hss {
  746. hs.CloseClientConnections()
  747. hs.Close()
  748. }
  749. }
  750. // Stop stops the member, but the data dir of the member is preserved.
  751. func (m *member) Stop(t *testing.T) {
  752. plog.Printf("stopping %s (%s)", m.Name, m.grpcAddr)
  753. m.Close()
  754. m.hss = nil
  755. plog.Printf("stopped %s (%s)", m.Name, m.grpcAddr)
  756. }
  757. // checkLeaderTransition waits for leader transition, returning the new leader ID.
  758. func checkLeaderTransition(t *testing.T, m *member, oldLead uint64) uint64 {
  759. interval := time.Duration(m.s.Cfg.TickMs) * time.Millisecond
  760. for m.s.Lead() == 0 || (m.s.Lead() == oldLead) {
  761. time.Sleep(interval)
  762. }
  763. return m.s.Lead()
  764. }
  765. // StopNotify unblocks when a member stop completes
  766. func (m *member) StopNotify() <-chan struct{} {
  767. return m.s.StopNotify()
  768. }
  769. // Restart starts the member using the preserved data dir.
  770. func (m *member) Restart(t *testing.T) error {
  771. plog.Printf("restarting %s (%s)", m.Name, m.grpcAddr)
  772. newPeerListeners := make([]net.Listener, 0)
  773. for _, ln := range m.PeerListeners {
  774. newPeerListeners = append(newPeerListeners, NewListenerWithAddr(t, ln.Addr().String()))
  775. }
  776. m.PeerListeners = newPeerListeners
  777. newClientListeners := make([]net.Listener, 0)
  778. for _, ln := range m.ClientListeners {
  779. newClientListeners = append(newClientListeners, NewListenerWithAddr(t, ln.Addr().String()))
  780. }
  781. m.ClientListeners = newClientListeners
  782. if m.grpcListener != nil {
  783. if err := m.listenGRPC(); err != nil {
  784. t.Fatal(err)
  785. }
  786. }
  787. err := m.Launch()
  788. plog.Printf("restarted %s (%s)", m.Name, m.grpcAddr)
  789. return err
  790. }
  791. // Terminate stops the member and removes the data dir.
  792. func (m *member) Terminate(t *testing.T) {
  793. plog.Printf("terminating %s (%s)", m.Name, m.grpcAddr)
  794. m.Close()
  795. if !m.keepDataDirTerminate {
  796. if err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {
  797. t.Fatal(err)
  798. }
  799. }
  800. plog.Printf("terminated %s (%s)", m.Name, m.grpcAddr)
  801. }
  802. // Metric gets the metric value for a member
  803. func (m *member) Metric(metricName string) (string, error) {
  804. cfgtls := transport.TLSInfo{}
  805. tr, err := transport.NewTimeoutTransport(cfgtls, time.Second, time.Second, time.Second)
  806. if err != nil {
  807. return "", err
  808. }
  809. cli := &http.Client{Transport: tr}
  810. resp, err := cli.Get(m.ClientURLs[0].String() + "/metrics")
  811. if err != nil {
  812. return "", err
  813. }
  814. defer resp.Body.Close()
  815. b, rerr := ioutil.ReadAll(resp.Body)
  816. if rerr != nil {
  817. return "", rerr
  818. }
  819. lines := strings.Split(string(b), "\n")
  820. for _, l := range lines {
  821. if strings.HasPrefix(l, metricName) {
  822. return strings.Split(l, " ")[1], nil
  823. }
  824. }
  825. return "", nil
  826. }
  827. // InjectPartition drops connections from m to others, vice versa.
  828. func (m *member) InjectPartition(t *testing.T, others ...*member) {
  829. for _, other := range others {
  830. m.s.CutPeer(other.s.ID())
  831. other.s.CutPeer(m.s.ID())
  832. }
  833. }
  834. // RecoverPartition recovers connections from m to others, vice versa.
  835. func (m *member) RecoverPartition(t *testing.T, others ...*member) {
  836. for _, other := range others {
  837. m.s.MendPeer(other.s.ID())
  838. other.s.MendPeer(m.s.ID())
  839. }
  840. }
  841. func MustNewHTTPClient(t *testing.T, eps []string, tls *transport.TLSInfo) client.Client {
  842. cfgtls := transport.TLSInfo{}
  843. if tls != nil {
  844. cfgtls = *tls
  845. }
  846. cfg := client.Config{Transport: mustNewTransport(t, cfgtls), Endpoints: eps}
  847. c, err := client.New(cfg)
  848. if err != nil {
  849. t.Fatal(err)
  850. }
  851. return c
  852. }
  853. func mustNewTransport(t *testing.T, tlsInfo transport.TLSInfo) *http.Transport {
  854. // tick in integration test is short, so 1s dial timeout could play well.
  855. tr, err := transport.NewTimeoutTransport(tlsInfo, time.Second, rafthttp.ConnReadTimeout, rafthttp.ConnWriteTimeout)
  856. if err != nil {
  857. t.Fatal(err)
  858. }
  859. return tr
  860. }
  861. type SortableMemberSliceByPeerURLs []client.Member
  862. func (p SortableMemberSliceByPeerURLs) Len() int { return len(p) }
  863. func (p SortableMemberSliceByPeerURLs) Less(i, j int) bool {
  864. return p[i].PeerURLs[0] < p[j].PeerURLs[0]
  865. }
  866. func (p SortableMemberSliceByPeerURLs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  867. type ClusterV3 struct {
  868. *cluster
  869. mu sync.Mutex
  870. clients []*clientv3.Client
  871. }
  872. // NewClusterV3 returns a launched cluster with a grpc client connection
  873. // for each cluster member.
  874. func NewClusterV3(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
  875. cfg.UseGRPC = true
  876. clus := &ClusterV3{
  877. cluster: NewClusterByConfig(t, cfg),
  878. }
  879. clus.Launch(t)
  880. if !cfg.SkipCreatingClient {
  881. for _, m := range clus.Members {
  882. client, err := NewClientV3(m)
  883. if err != nil {
  884. t.Fatalf("cannot create client: %v", err)
  885. }
  886. clus.clients = append(clus.clients, client)
  887. }
  888. }
  889. return clus
  890. }
  891. func (c *ClusterV3) TakeClient(idx int) {
  892. c.mu.Lock()
  893. c.clients[idx] = nil
  894. c.mu.Unlock()
  895. }
  896. func (c *ClusterV3) Terminate(t *testing.T) {
  897. c.mu.Lock()
  898. for _, client := range c.clients {
  899. if client == nil {
  900. continue
  901. }
  902. if err := client.Close(); err != nil {
  903. t.Error(err)
  904. }
  905. }
  906. c.mu.Unlock()
  907. c.cluster.Terminate(t)
  908. }
  909. func (c *ClusterV3) RandClient() *clientv3.Client {
  910. return c.clients[rand.Intn(len(c.clients))]
  911. }
  912. func (c *ClusterV3) Client(i int) *clientv3.Client {
  913. return c.clients[i]
  914. }
  915. type grpcAPI struct {
  916. // Cluster is the cluster API for the client's connection.
  917. Cluster pb.ClusterClient
  918. // KV is the keyvalue API for the client's connection.
  919. KV pb.KVClient
  920. // Lease is the lease API for the client's connection.
  921. Lease pb.LeaseClient
  922. // Watch is the watch API for the client's connection.
  923. Watch pb.WatchClient
  924. // Maintenance is the maintenance API for the client's connection.
  925. Maintenance pb.MaintenanceClient
  926. // Auth is the authentication API for the client's connection.
  927. Auth pb.AuthClient
  928. // Lock is the lock API for the client's connection.
  929. Lock lockpb.LockClient
  930. // Election is the election API for the client's connection.
  931. Election epb.ElectionClient
  932. }