cluster.go 30 KB

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