-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
cluster.go
1632 lines (1473 loc) · 47.6 KB
/
cluster.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package integration
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"os"
"reflect"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
pb "go.etcd.io/etcd/api/v3/etcdserverpb"
"go.etcd.io/etcd/client/pkg/v3/testutil"
"go.etcd.io/etcd/client/pkg/v3/tlsutil"
"go.etcd.io/etcd/client/pkg/v3/transport"
"go.etcd.io/etcd/client/pkg/v3/types"
"go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/pkg/v3/grpc_testing"
"go.etcd.io/etcd/raft/v3"
"go.etcd.io/etcd/server/v3/config"
"go.etcd.io/etcd/server/v3/embed"
"go.etcd.io/etcd/server/v3/etcdserver"
"go.etcd.io/etcd/server/v3/etcdserver/api/etcdhttp"
"go.etcd.io/etcd/server/v3/etcdserver/api/membership"
"go.etcd.io/etcd/server/v3/etcdserver/api/rafthttp"
"go.etcd.io/etcd/server/v3/etcdserver/api/v3client"
"go.etcd.io/etcd/server/v3/etcdserver/api/v3election"
epb "go.etcd.io/etcd/server/v3/etcdserver/api/v3election/v3electionpb"
"go.etcd.io/etcd/server/v3/etcdserver/api/v3lock"
lockpb "go.etcd.io/etcd/server/v3/etcdserver/api/v3lock/v3lockpb"
"go.etcd.io/etcd/server/v3/etcdserver/api/v3rpc"
"go.etcd.io/etcd/server/v3/verify"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/soheilhy/cmux"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
const (
// RequestWaitTimeout is the time duration to wait for a request to go through or detect leader loss.
RequestWaitTimeout = 5 * time.Second
TickDuration = 10 * time.Millisecond
RequestTimeout = 20 * time.Second
ClusterName = "etcd"
BasePort = 21000
URLScheme = "unix"
URLSchemeTLS = "unixs"
BaseGRPCPort = 30000
)
var (
ElectionTicks = 10
// LocalListenCount integration test uses unique ports, counting up, to listen for each
// member, ensuring restarted members can listen on the same port again.
LocalListenCount = int32(0)
TestTLSInfo = transport.TLSInfo{
KeyFile: MustAbsPath("../fixtures/server.key.insecure"),
CertFile: MustAbsPath("../fixtures/server.crt"),
TrustedCAFile: MustAbsPath("../fixtures/ca.crt"),
ClientCertAuth: true,
}
TestTLSInfoWithSpecificUsage = transport.TLSInfo{
KeyFile: MustAbsPath("../fixtures/server-serverusage.key.insecure"),
CertFile: MustAbsPath("../fixtures/server-serverusage.crt"),
ClientKeyFile: MustAbsPath("../fixtures/client-clientusage.key.insecure"),
ClientCertFile: MustAbsPath("../fixtures/client-clientusage.crt"),
TrustedCAFile: MustAbsPath("../fixtures/ca.crt"),
ClientCertAuth: true,
}
TestTLSInfoIP = transport.TLSInfo{
KeyFile: MustAbsPath("../fixtures/server-ip.key.insecure"),
CertFile: MustAbsPath("../fixtures/server-ip.crt"),
TrustedCAFile: MustAbsPath("../fixtures/ca.crt"),
ClientCertAuth: true,
}
TestTLSInfoExpired = transport.TLSInfo{
KeyFile: MustAbsPath("./fixtures-expired/server.key.insecure"),
CertFile: MustAbsPath("./fixtures-expired/server.crt"),
TrustedCAFile: MustAbsPath("./fixtures-expired/ca.crt"),
ClientCertAuth: true,
}
TestTLSInfoExpiredIP = transport.TLSInfo{
KeyFile: MustAbsPath("./fixtures-expired/server-ip.key.insecure"),
CertFile: MustAbsPath("./fixtures-expired/server-ip.crt"),
TrustedCAFile: MustAbsPath("./fixtures-expired/ca.crt"),
ClientCertAuth: true,
}
DefaultTokenJWT = fmt.Sprintf("jwt,pub-key=%s,priv-key=%s,sign-method=RS256,ttl=1s",
MustAbsPath("../fixtures/server.crt"), MustAbsPath("../fixtures/server.key.insecure"))
// UniqueNumber is used to generate unique port numbers
// Should only be accessed via atomic package methods.
UniqueNumber int32
)
type ClusterConfig struct {
Size int
PeerTLS *transport.TLSInfo
ClientTLS *transport.TLSInfo
DiscoveryURL string
AuthToken string
QuotaBackendBytes int64
MaxTxnOps uint
MaxRequestBytes uint
SnapshotCount uint64
SnapshotCatchUpEntries uint64
GRPCKeepAliveMinTime time.Duration
GRPCKeepAliveInterval time.Duration
GRPCKeepAliveTimeout time.Duration
ClientMaxCallSendMsgSize int
ClientMaxCallRecvMsgSize int
// UseIP is true to use only IP for gRPC requests.
UseIP bool
// UseBridge adds bridge between client and grpc server. Should be used in tests that
// want to manipulate connection or require connection not breaking despite server stop/restart.
UseBridge bool
// UseTCP configures server listen on tcp socket. If disabled unix socket is used.
UseTCP bool
EnableLeaseCheckpoint bool
LeaseCheckpointInterval time.Duration
LeaseCheckpointPersist bool
WatchProgressNotifyInterval time.Duration
ExperimentalMaxLearners int
StrictReconfigCheck bool
CorruptCheckTime time.Duration
}
type Cluster struct {
Cfg *ClusterConfig
Members []*Member
LastMemberNum int
mu sync.Mutex
clusterClient *clientv3.Client
}
func SchemeFromTLSInfo(tls *transport.TLSInfo) string {
if tls == nil {
return URLScheme
}
return URLSchemeTLS
}
func (c *Cluster) fillClusterForMembers() error {
if c.Cfg.DiscoveryURL != "" {
// Cluster will be discovered
return nil
}
addrs := make([]string, 0)
for _, m := range c.Members {
scheme := SchemeFromTLSInfo(m.PeerTLSInfo)
for _, l := range m.PeerListeners {
addrs = append(addrs, fmt.Sprintf("%s=%s://%s", m.Name, scheme, l.Addr().String()))
}
}
clusterStr := strings.Join(addrs, ",")
var err error
for _, m := range c.Members {
m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
if err != nil {
return err
}
}
return nil
}
func (c *Cluster) Launch(t testutil.TB) {
t.Logf("Launching new cluster...")
errc := make(chan error)
for _, m := range c.Members {
// Members are launched in separate goroutines because if they boot
// using discovery url, they have to wait for others to register to continue.
go func(m *Member) {
errc <- m.Launch()
}(m)
}
for range c.Members {
if err := <-errc; err != nil {
c.Terminate(t)
t.Fatalf("error setting up member: %v", err)
}
}
// wait Cluster to be stable to receive future client requests
c.WaitMembersMatch(t, c.ProtoMembers())
c.waitVersion()
for _, m := range c.Members {
t.Logf(" - %v -> %v (%v)", m.Name, m.ID(), m.GRPCURL())
}
}
// ProtoMembers returns a list of all active members as client.Members
func (c *Cluster) ProtoMembers() []*pb.Member {
ms := []*pb.Member{}
for _, m := range c.Members {
pScheme := SchemeFromTLSInfo(m.PeerTLSInfo)
cScheme := SchemeFromTLSInfo(m.ClientTLSInfo)
cm := &pb.Member{Name: m.Name}
for _, ln := range m.PeerListeners {
cm.PeerURLs = append(cm.PeerURLs, pScheme+"://"+ln.Addr().String())
}
for _, ln := range m.ClientListeners {
cm.ClientURLs = append(cm.ClientURLs, cScheme+"://"+ln.Addr().String())
}
ms = append(ms, cm)
}
return ms
}
func (c *Cluster) mustNewMember(t testutil.TB) *Member {
memberNumber := c.LastMemberNum
c.LastMemberNum++
m := MustNewMember(t,
MemberConfig{
Name: fmt.Sprintf("m%v", memberNumber),
MemberNumber: memberNumber,
AuthToken: c.Cfg.AuthToken,
PeerTLS: c.Cfg.PeerTLS,
ClientTLS: c.Cfg.ClientTLS,
QuotaBackendBytes: c.Cfg.QuotaBackendBytes,
MaxTxnOps: c.Cfg.MaxTxnOps,
MaxRequestBytes: c.Cfg.MaxRequestBytes,
SnapshotCount: c.Cfg.SnapshotCount,
SnapshotCatchUpEntries: c.Cfg.SnapshotCatchUpEntries,
GrpcKeepAliveMinTime: c.Cfg.GRPCKeepAliveMinTime,
GrpcKeepAliveInterval: c.Cfg.GRPCKeepAliveInterval,
GrpcKeepAliveTimeout: c.Cfg.GRPCKeepAliveTimeout,
ClientMaxCallSendMsgSize: c.Cfg.ClientMaxCallSendMsgSize,
ClientMaxCallRecvMsgSize: c.Cfg.ClientMaxCallRecvMsgSize,
UseIP: c.Cfg.UseIP,
UseBridge: c.Cfg.UseBridge,
UseTCP: c.Cfg.UseTCP,
EnableLeaseCheckpoint: c.Cfg.EnableLeaseCheckpoint,
LeaseCheckpointInterval: c.Cfg.LeaseCheckpointInterval,
LeaseCheckpointPersist: c.Cfg.LeaseCheckpointPersist,
WatchProgressNotifyInterval: c.Cfg.WatchProgressNotifyInterval,
ExperimentalMaxLearners: c.Cfg.ExperimentalMaxLearners,
StrictReconfigCheck: c.Cfg.StrictReconfigCheck,
CorruptCheckTime: c.Cfg.CorruptCheckTime,
})
m.DiscoveryURL = c.Cfg.DiscoveryURL
return m
}
// addMember return PeerURLs of the added member.
func (c *Cluster) addMember(t testutil.TB) types.URLs {
m := c.mustNewMember(t)
scheme := SchemeFromTLSInfo(c.Cfg.PeerTLS)
// send add request to the Cluster
var err error
for i := 0; i < len(c.Members); i++ {
peerURL := scheme + "://" + m.PeerListeners[0].Addr().String()
if err = c.AddMemberByURL(t, c.Members[i].Client, peerURL); err == nil {
break
}
}
if err != nil {
t.Fatalf("add member failed on all members error: %v", err)
}
m.InitialPeerURLsMap = types.URLsMap{}
for _, mm := range c.Members {
m.InitialPeerURLsMap[mm.Name] = mm.PeerURLs
}
m.InitialPeerURLsMap[m.Name] = m.PeerURLs
m.NewCluster = false
if err := m.Launch(); err != nil {
t.Fatal(err)
}
c.Members = append(c.Members, m)
// wait Cluster to be stable to receive future client requests
c.WaitMembersMatch(t, c.ProtoMembers())
return m.PeerURLs
}
func (c *Cluster) AddMemberByURL(t testutil.TB, cc *clientv3.Client, peerURL string) error {
ctx, cancel := context.WithTimeout(context.Background(), RequestTimeout)
_, err := cc.MemberAdd(ctx, []string{peerURL})
cancel()
if err != nil {
return err
}
// wait for the add node entry applied in the Cluster
members := append(c.ProtoMembers(), &pb.Member{PeerURLs: []string{peerURL}, ClientURLs: []string{}})
c.WaitMembersMatch(t, members)
return nil
}
// AddMember return PeerURLs of the added member.
func (c *Cluster) AddMember(t testutil.TB) types.URLs {
return c.addMember(t)
}
func (c *Cluster) RemoveMember(t testutil.TB, cc *clientv3.Client, id uint64) error {
// send remove request to the Cluster
ctx, cancel := context.WithTimeout(context.Background(), RequestTimeout)
_, err := cc.MemberRemove(ctx, id)
cancel()
if err != nil {
return err
}
newMembers := make([]*Member, 0)
for _, m := range c.Members {
if uint64(m.Server.MemberId()) != id {
newMembers = append(newMembers, m)
} else {
m.Client.Close()
select {
case <-m.Server.StopNotify():
m.Terminate(t)
// 1s stop delay + election timeout + 1s disk and network delay + connection write timeout
// TODO: remove connection write timeout by selecting on http response closeNotifier
// blocking on https://github.com/golang/go/issues/9524
case <-time.After(time.Second + time.Duration(ElectionTicks)*TickDuration + time.Second + rafthttp.ConnWriteTimeout):
t.Fatalf("failed to remove member %s in time", m.Server.MemberId())
}
}
}
c.Members = newMembers
c.WaitMembersMatch(t, c.ProtoMembers())
return nil
}
func (c *Cluster) WaitMembersMatch(t testutil.TB, membs []*pb.Member) {
ctx, cancel := context.WithTimeout(context.Background(), RequestTimeout)
defer cancel()
for _, m := range c.Members {
cc := ToGRPC(m.Client)
select {
case <-m.Server.StopNotify():
continue
default:
}
for {
resp, err := cc.Cluster.MemberList(ctx, &pb.MemberListRequest{Linearizable: false})
if errors.Is(err, context.DeadlineExceeded) {
t.Fatal(err)
}
if err != nil {
continue
}
if isMembersEqual(resp.Members, membs) {
break
}
time.Sleep(TickDuration)
}
}
}
// WaitLeader returns index of the member in c.Members that is leader
// or fails the test (if not established in 30s).
func (c *Cluster) WaitLeader(t testing.TB) int {
return c.WaitMembersForLeader(t, c.Members)
}
// WaitMembersForLeader waits until given members agree on the same leader,
// and returns its 'index' in the 'membs' list
func (c *Cluster) WaitMembersForLeader(t testing.TB, membs []*Member) int {
t.Logf("WaitMembersForLeader")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
l := 0
for l = c.waitMembersForLeader(ctx, t, membs); l < 0; {
if ctx.Err() != nil {
t.Fatalf("WaitLeader FAILED: %v", ctx.Err())
}
}
t.Logf("WaitMembersForLeader succeeded. Cluster leader index: %v", l)
// TODO: Consider second pass check as sometimes leadership is lost
// soon after election:
//
// We perform multiple attempts, as some-times just after successful WaitLLeader
// there is a race and leadership is quickly lost:
// - MsgAppResp message with higher term from 2acc3d3b521981 [term: 3] {"member": "m0"}
// - 9903a56eaf96afac became follower at term 3 {"member": "m0"}
// - 9903a56eaf96afac lost leader 9903a56eaf96afac at term 3 {"member": "m0"}
return l
}
// WaitMembersForLeader waits until given members agree on the same leader,
// and returns its 'index' in the 'membs' list
func (c *Cluster) waitMembersForLeader(ctx context.Context, t testing.TB, membs []*Member) int {
possibleLead := make(map[uint64]bool)
var lead uint64
for _, m := range membs {
possibleLead[uint64(m.Server.MemberId())] = true
}
cc, err := c.ClusterClient()
if err != nil {
t.Fatal(err)
}
// ensure leader is up via linearizable get
for {
ctx, cancel := context.WithTimeout(ctx, 10*TickDuration+time.Second)
_, err := cc.Get(ctx, "0")
cancel()
if err == nil || strings.Contains(err.Error(), "Key not found") {
break
}
}
for lead == 0 || !possibleLead[lead] {
lead = 0
for _, m := range membs {
select {
case <-m.Server.StopNotify():
continue
default:
}
if lead != 0 && lead != m.Server.Lead() {
lead = 0
time.Sleep(10 * TickDuration)
break
}
lead = m.Server.Lead()
}
}
for i, m := range membs {
if uint64(m.Server.MemberId()) == lead {
t.Logf("waitMembersForLeader found leader. Member: %v lead: %x", i, lead)
return i
}
}
t.Logf("waitMembersForLeader failed (-1)")
return -1
}
func (c *Cluster) WaitNoLeader() { c.WaitMembersNoLeader(c.Members) }
// WaitMembersNoLeader waits until given members lose leader.
func (c *Cluster) WaitMembersNoLeader(membs []*Member) {
noLeader := false
for !noLeader {
noLeader = true
for _, m := range membs {
select {
case <-m.Server.StopNotify():
continue
default:
}
if m.Server.Lead() != 0 {
noLeader = false
time.Sleep(10 * TickDuration)
break
}
}
}
}
func (c *Cluster) waitVersion() {
for _, m := range c.Members {
for {
if m.Server.ClusterVersion() != nil {
break
}
time.Sleep(TickDuration)
}
}
}
// isMembersEqual checks whether two members equal except ID field.
// The given wmembs should always set ID field to empty string.
func isMembersEqual(membs []*pb.Member, wmembs []*pb.Member) bool {
sort.Sort(SortableMemberSliceByPeerURLs(membs))
sort.Sort(SortableMemberSliceByPeerURLs(wmembs))
return cmp.Equal(membs, wmembs, cmpopts.IgnoreFields(pb.Member{}, "ID", "PeerURLs", "ClientURLs"))
}
func NewLocalListener(t testutil.TB) net.Listener {
c := atomic.AddInt32(&LocalListenCount, 1)
// Go 1.8+ allows only numbers in port
addr := fmt.Sprintf("127.0.0.1:%05d%05d", c+BasePort, os.Getpid())
return NewListenerWithAddr(t, addr)
}
func NewListenerWithAddr(t testutil.TB, addr string) net.Listener {
t.Logf("Creating listener with addr: %v", addr)
l, err := transport.NewUnixListener(addr)
if err != nil {
t.Fatal(err)
}
return l
}
type Member struct {
config.ServerConfig
UniqNumber int
MemberNumber int
PeerListeners, ClientListeners []net.Listener
GrpcListener net.Listener
// PeerTLSInfo enables peer TLS when set
PeerTLSInfo *transport.TLSInfo
// ClientTLSInfo enables client TLS when set
ClientTLSInfo *transport.TLSInfo
DialOptions []grpc.DialOption
RaftHandler *testutil.PauseableHandler
Server *etcdserver.EtcdServer
ServerClosers []func()
GrpcServerOpts []grpc.ServerOption
GrpcServer *grpc.Server
GrpcURL string
GrpcBridge *bridge
// ServerClient is a clientv3 that directly calls the etcdserver.
ServerClient *clientv3.Client
// Client is a clientv3 that communicates via socket, either UNIX or TCP.
Client *clientv3.Client
KeepDataDirTerminate bool
ClientMaxCallSendMsgSize int
ClientMaxCallRecvMsgSize int
UseIP bool
UseBridge bool
UseTCP bool
IsLearner bool
Closed bool
GrpcServerRecorder *grpc_testing.GrpcRecorder
}
func (m *Member) GRPCURL() string { return m.GrpcURL }
type MemberConfig struct {
Name string
UniqNumber int64
MemberNumber int
PeerTLS *transport.TLSInfo
ClientTLS *transport.TLSInfo
AuthToken string
QuotaBackendBytes int64
MaxTxnOps uint
MaxRequestBytes uint
SnapshotCount uint64
SnapshotCatchUpEntries uint64
GrpcKeepAliveMinTime time.Duration
GrpcKeepAliveInterval time.Duration
GrpcKeepAliveTimeout time.Duration
ClientMaxCallSendMsgSize int
ClientMaxCallRecvMsgSize int
UseIP bool
UseBridge bool
UseTCP bool
EnableLeaseCheckpoint bool
LeaseCheckpointInterval time.Duration
LeaseCheckpointPersist bool
WatchProgressNotifyInterval time.Duration
ExperimentalMaxLearners int
StrictReconfigCheck bool
CorruptCheckTime time.Duration
}
// MustNewMember return an inited member with the given name. If peerTLS is
// set, it will use https scheme to communicate between peers.
func MustNewMember(t testutil.TB, mcfg MemberConfig) *Member {
var err error
m := &Member{
MemberNumber: mcfg.MemberNumber,
UniqNumber: int(atomic.AddInt32(&LocalListenCount, 1)),
}
peerScheme := SchemeFromTLSInfo(mcfg.PeerTLS)
clientScheme := SchemeFromTLSInfo(mcfg.ClientTLS)
pln := NewLocalListener(t)
m.PeerListeners = []net.Listener{pln}
m.PeerURLs, err = types.NewURLs([]string{peerScheme + "://" + pln.Addr().String()})
if err != nil {
t.Fatal(err)
}
m.PeerTLSInfo = mcfg.PeerTLS
cln := NewLocalListener(t)
m.ClientListeners = []net.Listener{cln}
m.ClientURLs, err = types.NewURLs([]string{clientScheme + "://" + cln.Addr().String()})
if err != nil {
t.Fatal(err)
}
m.ClientTLSInfo = mcfg.ClientTLS
m.Name = mcfg.Name
m.DataDir, err = os.MkdirTemp(t.TempDir(), "etcd")
if err != nil {
t.Fatal(err)
}
clusterStr := fmt.Sprintf("%s=%s://%s", mcfg.Name, peerScheme, pln.Addr().String())
m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
if err != nil {
t.Fatal(err)
}
m.InitialClusterToken = ClusterName
m.NewCluster = true
m.BootstrapTimeout = 10 * time.Millisecond
if m.PeerTLSInfo != nil {
m.ServerConfig.PeerTLSInfo = *m.PeerTLSInfo
}
m.ElectionTicks = ElectionTicks
m.InitialElectionTickAdvance = true
m.TickMs = uint(TickDuration / time.Millisecond)
m.QuotaBackendBytes = mcfg.QuotaBackendBytes
m.MaxTxnOps = mcfg.MaxTxnOps
if m.MaxTxnOps == 0 {
m.MaxTxnOps = embed.DefaultMaxTxnOps
}
m.MaxRequestBytes = mcfg.MaxRequestBytes
if m.MaxRequestBytes == 0 {
m.MaxRequestBytes = embed.DefaultMaxRequestBytes
}
m.SnapshotCount = etcdserver.DefaultSnapshotCount
if mcfg.SnapshotCount != 0 {
m.SnapshotCount = mcfg.SnapshotCount
}
m.SnapshotCatchUpEntries = etcdserver.DefaultSnapshotCatchUpEntries
if mcfg.SnapshotCatchUpEntries != 0 {
m.SnapshotCatchUpEntries = mcfg.SnapshotCatchUpEntries
}
// for the purpose of integration testing, simple token is enough
m.AuthToken = "simple"
if mcfg.AuthToken != "" {
m.AuthToken = mcfg.AuthToken
}
m.BcryptCost = uint(bcrypt.MinCost) // use min bcrypt cost to speedy up integration testing
m.GrpcServerOpts = []grpc.ServerOption{}
if mcfg.GrpcKeepAliveMinTime > time.Duration(0) {
m.GrpcServerOpts = append(m.GrpcServerOpts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: mcfg.GrpcKeepAliveMinTime,
PermitWithoutStream: false,
}))
}
if mcfg.GrpcKeepAliveInterval > time.Duration(0) &&
mcfg.GrpcKeepAliveTimeout > time.Duration(0) {
m.GrpcServerOpts = append(m.GrpcServerOpts, grpc.KeepaliveParams(keepalive.ServerParameters{
Time: mcfg.GrpcKeepAliveInterval,
Timeout: mcfg.GrpcKeepAliveTimeout,
}))
}
m.ClientMaxCallSendMsgSize = mcfg.ClientMaxCallSendMsgSize
m.ClientMaxCallRecvMsgSize = mcfg.ClientMaxCallRecvMsgSize
m.UseIP = mcfg.UseIP
m.UseBridge = mcfg.UseBridge
m.UseTCP = mcfg.UseTCP
m.EnableLeaseCheckpoint = mcfg.EnableLeaseCheckpoint
m.LeaseCheckpointInterval = mcfg.LeaseCheckpointInterval
m.LeaseCheckpointPersist = mcfg.LeaseCheckpointPersist
m.WatchProgressNotifyInterval = mcfg.WatchProgressNotifyInterval
m.InitialCorruptCheck = true
if mcfg.CorruptCheckTime > time.Duration(0) {
m.CorruptCheckTime = mcfg.CorruptCheckTime
}
m.WarningApplyDuration = embed.DefaultWarningApplyDuration
m.WarningUnaryRequestDuration = embed.DefaultWarningUnaryRequestDuration
m.ExperimentalMaxLearners = membership.DefaultMaxLearners
if mcfg.ExperimentalMaxLearners != 0 {
m.ExperimentalMaxLearners = mcfg.ExperimentalMaxLearners
}
m.V2Deprecation = config.V2_DEPR_DEFAULT
m.GrpcServerRecorder = &grpc_testing.GrpcRecorder{}
m.Logger = memberLogger(t, mcfg.Name)
m.StrictReconfigCheck = mcfg.StrictReconfigCheck
if err := m.listenGRPC(); err != nil {
t.Fatalf("listenGRPC FAILED: %v", err)
}
t.Cleanup(func() {
// if we didn't cleanup the logger, the consecutive test
// might reuse this (t).
raft.ResetDefaultLogger()
})
return m
}
func memberLogger(t testutil.TB, name string) *zap.Logger {
level := zapcore.InfoLevel
if os.Getenv("CLUSTER_DEBUG") != "" {
level = zapcore.DebugLevel
}
options := zaptest.WrapOptions(zap.Fields(zap.String("member", name)))
return zaptest.NewLogger(t, zaptest.Level(level), options).Named(name)
}
// listenGRPC starts a grpc server over a unix domain socket on the member
func (m *Member) listenGRPC() error {
// prefix with localhost so cert has right domain
network, host, port := m.grpcAddr()
grpcAddr := host + ":" + port
wd, err := os.Getwd()
if err != nil {
return err
}
m.Logger.Info("LISTEN GRPC", zap.String("grpcAddr", grpcAddr), zap.String("m.Name", m.Name), zap.String("workdir", wd))
grpcListener, err := net.Listen(network, grpcAddr)
if err != nil {
return fmt.Errorf("listen failed on grpc socket %s (%v)", grpcAddr, err)
}
m.GrpcURL = fmt.Sprintf("%s://%s", m.clientScheme(), grpcAddr)
if m.UseBridge {
_, err = m.addBridge()
if err != nil {
grpcListener.Close()
return err
}
}
m.GrpcListener = grpcListener
return nil
}
func (m *Member) clientScheme() string {
switch {
case m.UseTCP && m.ClientTLSInfo != nil:
return "https"
case m.UseTCP && m.ClientTLSInfo == nil:
return "http"
case !m.UseTCP && m.ClientTLSInfo != nil:
return "unixs"
case !m.UseTCP && m.ClientTLSInfo == nil:
return "unix"
}
m.Logger.Panic("Failed to determine client schema")
return ""
}
func (m *Member) addBridge() (*bridge, error) {
network, host, port := m.grpcAddr()
grpcAddr := host + ":" + port
bridgeAddr := grpcAddr + "0"
m.Logger.Info("LISTEN BRIDGE", zap.String("grpc-address", bridgeAddr), zap.String("member", m.Name))
bridgeListener, err := transport.NewUnixListener(bridgeAddr)
if err != nil {
return nil, fmt.Errorf("listen failed on bridge socket %s (%v)", bridgeAddr, err)
}
m.GrpcBridge, err = newBridge(dialer{network: network, addr: grpcAddr}, bridgeListener)
if err != nil {
bridgeListener.Close()
return nil, err
}
m.GrpcURL = m.clientScheme() + "://" + bridgeAddr
return m.GrpcBridge, nil
}
func (m *Member) Bridge() *bridge {
if !m.UseBridge {
m.Logger.Panic("Bridge not available. Please configure using bridge before creating Cluster.")
}
return m.GrpcBridge
}
func (m *Member) grpcAddr() (network, host, port string) {
// prefix with localhost so cert has right domain
host = "localhost"
if m.UseIP { // for IP-only TLS certs
host = "127.0.0.1"
}
network = "unix"
if m.UseTCP {
network = "tcp"
}
port = m.Name
if m.UseTCP {
port = fmt.Sprintf("%d", GrpcPortNumber(m.UniqNumber, m.MemberNumber))
}
return network, host, port
}
func GrpcPortNumber(uniqNumber, memberNumber int) int {
return BaseGRPCPort + uniqNumber*10 + memberNumber
}
type dialer struct {
network string
addr string
}
func (d dialer) Dial() (net.Conn, error) {
return net.Dial(d.network, d.addr)
}
func (m *Member) ElectionTimeout() time.Duration {
return time.Duration(m.Server.Cfg.ElectionTicks*int(m.Server.Cfg.TickMs)) * time.Millisecond
}
func (m *Member) ID() types.ID { return m.Server.MemberId() }
// NewClientV3 creates a new grpc client connection to the member
func NewClientV3(m *Member) (*clientv3.Client, error) {
if m.GrpcURL == "" {
return nil, fmt.Errorf("member not configured for grpc")
}
cfg := clientv3.Config{
Endpoints: []string{m.GrpcURL},
DialTimeout: 5 * time.Second,
DialOptions: []grpc.DialOption{grpc.WithBlock()},
MaxCallSendMsgSize: m.ClientMaxCallSendMsgSize,
MaxCallRecvMsgSize: m.ClientMaxCallRecvMsgSize,
Logger: m.Logger.Named("client"),
}
if m.ClientTLSInfo != nil {
tls, err := m.ClientTLSInfo.ClientConfig()
if err != nil {
return nil, err
}
cfg.TLS = tls
}
if m.DialOptions != nil {
cfg.DialOptions = append(cfg.DialOptions, m.DialOptions...)
}
return newClientV3(cfg)
}
// Clone returns a member with the same server configuration. The returned
// member will not set PeerListeners and ClientListeners.
func (m *Member) Clone(t testutil.TB) *Member {
mm := &Member{}
mm.ServerConfig = m.ServerConfig
var err error
clientURLStrs := m.ClientURLs.StringSlice()
mm.ClientURLs, err = types.NewURLs(clientURLStrs)
if err != nil {
// this should never fail
panic(err)
}
peerURLStrs := m.PeerURLs.StringSlice()
mm.PeerURLs, err = types.NewURLs(peerURLStrs)
if err != nil {
// this should never fail
panic(err)
}
clusterStr := m.InitialPeerURLsMap.String()
mm.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr)
if err != nil {
// this should never fail
panic(err)
}
mm.InitialClusterToken = m.InitialClusterToken
mm.ElectionTicks = m.ElectionTicks
mm.PeerTLSInfo = m.PeerTLSInfo
mm.ClientTLSInfo = m.ClientTLSInfo
mm.Logger = memberLogger(t, mm.Name+"c")
return mm
}
// Launch starts a member based on ServerConfig, PeerListeners
// and ClientListeners.
func (m *Member) Launch() error {
m.Logger.Info(
"launching a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-url", m.GrpcURL),
)
var err error
if m.Server, err = etcdserver.NewServer(m.ServerConfig); err != nil {
return fmt.Errorf("failed to initialize the etcd server: %v", err)
}
m.Server.SyncTicker = time.NewTicker(500 * time.Millisecond)
m.Server.Start()
var peerTLScfg *tls.Config
if m.PeerTLSInfo != nil && !m.PeerTLSInfo.Empty() {
if peerTLScfg, err = m.PeerTLSInfo.ServerConfig(); err != nil {
return err
}
}
if m.GrpcListener != nil {
var (
tlscfg *tls.Config
)
if m.ClientTLSInfo != nil && !m.ClientTLSInfo.Empty() {
tlscfg, err = m.ClientTLSInfo.ServerConfig()
if err != nil {
return err
}
}
m.GrpcServer = v3rpc.Server(m.Server, tlscfg, m.GrpcServerRecorder.UnaryInterceptor(), m.GrpcServerOpts...)
m.ServerClient = v3client.New(m.Server)
lockpb.RegisterLockServer(m.GrpcServer, v3lock.NewLockServer(m.ServerClient))
epb.RegisterElectionServer(m.GrpcServer, v3election.NewElectionServer(m.ServerClient))
go m.GrpcServer.Serve(m.GrpcListener)
}
m.RaftHandler = &testutil.PauseableHandler{Next: etcdhttp.NewPeerHandler(m.Logger, m.Server)}
h := (http.Handler)(m.RaftHandler)
if m.GrpcListener != nil {
h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m.RaftHandler.ServeHTTP(w, r)
})
}
for _, ln := range m.PeerListeners {
cm := cmux.New(ln)
// don't hang on matcher after closing listener
cm.SetReadTimeout(time.Second)
// serve http1/http2 rafthttp/grpc
ll := cm.Match(cmux.Any())
if peerTLScfg != nil {
if ll, err = transport.NewTLSListener(ll, m.PeerTLSInfo); err != nil {
return err
}
}
hs := &httptest.Server{
Listener: ll,
Config: &http.Server{
Handler: h,
TLSConfig: peerTLScfg,
ErrorLog: log.New(io.Discard, "net/http", 0),
},
TLS: peerTLScfg,
}
hs.Start()
donec := make(chan struct{})
go func() {
defer close(donec)
cm.Serve()
}()
closer := func() {
ll.Close()
hs.CloseClientConnections()
hs.Close()
<-donec
}
m.ServerClosers = append(m.ServerClosers, closer)
}
for _, ln := range m.ClientListeners {
handler := http.NewServeMux()
etcdhttp.HandleDebug(handler)
etcdhttp.HandleVersion(handler, m.Server)
etcdhttp.HandleMetrics(handler)
etcdhttp.HandleHealth(m.Logger, handler, m.Server)
hs := &httptest.Server{