forked from go-zookeeper/zk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zk_test.go
1366 lines (1206 loc) · 37.1 KB
/
zk_test.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
package zk
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"math/rand"
"net"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestIntegration_StateChanges(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
callbackChan := make(chan Event)
f := func(event Event) {
callbackChan <- event
}
zk, eventChan, err := ts.ConnectWithOptions(15*time.Second, WithEventCallback(f))
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
verifyEventOrder := func(c <-chan Event, expectedStates []State, source string) {
for _, state := range expectedStates {
for {
event, ok := <-c
if !ok {
t.Fatalf("unexpected channel close for %s", source)
}
if event.Type != EventSession {
continue
}
if event.State != state {
t.Fatalf("mismatched state order from %s, expected %v, received %v", source, state, event.State)
}
break
}
}
}
states := []State{StateConnecting, StateConnected, StateHasSession}
verifyEventOrder(callbackChan, states, "callback")
verifyEventOrder(eventChan, states, "event channel")
zk.Close()
verifyEventOrder(callbackChan, []State{StateDisconnected}, "callback")
verifyEventOrder(eventChan, []State{StateDisconnected}, "event channel")
}
func TestIntegration_Create(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
requireNoErrorf(t, err)
defer ts.Stop()
zk, _, err := ts.ConnectAll()
requireNoErrorf(t, err, "ConnectAll()")
defer zk.Close()
tests := []struct {
name string
createFlags int32
specifiedPath string
wantErr string
}{
{
name: "valid create persistant",
createFlags: FlagPersistent,
},
{
name: "valid container from Create",
createFlags: FlagContainer,
// NOTE for v2: we dont need CreateContainer method.
},
{
name: "invalid path",
specifiedPath: "not/valid",
wantErr: "zk: invalid path",
},
{
name: "invalid create ttl",
createFlags: FlagTTL,
wantErr: "zk: invalid flags specified",
},
{
name: "invalid flag for create mode",
createFlags: 999,
wantErr: "invalid flag value: [999]",
},
}
const testPath = "/ttl_znode_tests"
// create sub node to create per test in avoiding using the root path.
_, err = zk.Create(testPath, nil /* data */, FlagPersistent, WorldACL(PermAll))
requireNoErrorf(t, err)
for idx, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path := filepath.Join(testPath, fmt.Sprint(idx))
if tt.specifiedPath != "" {
path = tt.specifiedPath
}
_, err := zk.Create(path, []byte{12}, tt.createFlags, WorldACL(PermAll))
if tt.wantErr == "" {
requireNoErrorf(t, err, fmt.Sprintf("error not expected: path; %q; flags %v", path, tt.createFlags))
return
}
// want an error
if err == nil {
t.Fatalf("did not get expected error: %q", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("wanted error not found: %v; got: %v", tt.wantErr, err.Error())
}
})
}
}
func TestIntegration_CreateTTL(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
requireNoErrorf(t, err)
defer ts.Stop()
zk, _, err := ts.ConnectAll()
requireNoErrorf(t, err, "ConnectAll()")
defer zk.Close()
tests := []struct {
name string
createFlags int32
specifiedPath string
giveDuration time.Duration
wantErr string
wantErrIs error
}{
{
name: "valid create ttl",
specifiedPath: "/test-valid-create-ttl",
createFlags: FlagTTL,
giveDuration: time.Minute,
},
{
name: "valid change detector",
specifiedPath: "/test-valid-change",
createFlags: 5,
giveDuration: time.Minute,
},
{
name: "invalid path",
createFlags: FlagTTL,
specifiedPath: "not/valid",
wantErr: "zk: invalid path",
wantErrIs: ErrInvalidPath,
},
{
name: "invalid container with ttl",
specifiedPath: "/test-invalid-flags",
createFlags: FlagContainer,
wantErr: "zk: invalid flags specified",
wantErrIs: ErrInvalidFlags,
},
{
name: "invalid flag for create mode",
specifiedPath: "/test-invalid-mode",
createFlags: 999,
giveDuration: time.Minute,
wantErr: "invalid flag value: [999]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.specifiedPath == "" {
t.Fatalf("path for test required: %v", tt.name)
}
_, err := zk.CreateTTL(tt.specifiedPath, []byte{12}, tt.createFlags, WorldACL(PermAll), tt.giveDuration)
if tt.wantErr == "" {
requireNoErrorf(t, err,
fmt.Sprintf("error not expected: path; %q; flags %v", tt.specifiedPath, tt.createFlags))
return
}
// want an error
if tt.wantErrIs != nil {
if !errors.Is(err, tt.wantErrIs) {
t.Errorf("error expected Is: %q", tt.wantErr)
}
}
if err == nil {
t.Errorf("did not get expected error: %q", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("wanted error not found: %v; got: %v", tt.wantErr, err.Error())
}
})
}
}
// NOTE: Currently there is not a way to get the znode after creating and
// asserting it is once mode or another. This means these tests are only testing the
// path of creation, but is not asserting that the resulting znode is the
// mode we set with flags.
func TestIntegration_CreateContainer(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
tests := []struct {
name string
createFlags int32
specifiedPath string
wantErr string
}{
{
name: "valid create container",
createFlags: FlagContainer,
},
{
name: "valid create container hard coded flag int",
createFlags: 4,
// container flag, ensure matches ZK Create Mode (change detector test)
},
{
name: "invalid path",
createFlags: FlagContainer,
specifiedPath: "not/valid",
wantErr: "zk: invalid path",
},
{
name: "invalid create mode",
createFlags: 999,
wantErr: "invalid flag value: [999]",
},
{
name: "invalid containers cannot be persistant",
createFlags: FlagPersistent,
wantErr: ErrInvalidFlags.Error(),
},
{
name: "invalid containers cannot be ephemeral",
createFlags: FlagEphemeral,
wantErr: ErrInvalidFlags.Error(),
},
{
name: "invalid containers cannot be sequential",
createFlags: FlagSequence,
wantErr: ErrInvalidFlags.Error(),
},
{
name: "invalid container and sequential",
createFlags: FlagContainer | FlagSequence,
wantErr: ErrInvalidFlags.Error(),
},
{
name: "invliad TTLs cannot be used with Container znodes",
createFlags: FlagTTL,
wantErr: ErrInvalidFlags.Error(),
},
}
const testPath = "/container_test_znode"
// create sub node to create per test in avoiding using the root path.
_, err = zk.Create(testPath, nil /* data */, FlagPersistent, WorldACL(PermAll))
requireNoErrorf(t, err)
for idx, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path := filepath.Join(testPath, fmt.Sprint(idx))
if tt.specifiedPath != "" {
path = tt.specifiedPath
}
_, err := zk.CreateContainer(path, []byte{12}, tt.createFlags, WorldACL(PermAll))
if tt.wantErr == "" {
requireNoErrorf(t, err, fmt.Sprintf("error not expected: path; %q; flags %v", path, tt.createFlags))
return
}
// want an error
if err == nil {
t.Fatalf("did not get expected error: %q", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("wanted error not found: %v; got: %v", tt.wantErr, err.Error())
}
})
}
}
func TestIntegration_IncrementalReconfig(t *testing.T) {
requireMinimumZkVersion(t, "3.5")
ts, err := StartTestCluster(t, 3, nil, logWriter{t: t, p: "[ZKERR] "})
requireNoErrorf(t, err, "failed to setup test cluster")
defer ts.Stop()
// start and add a new server.
tmpPath := t.TempDir()
startPort := int(rand.Int31n(6000) + 10000)
srvPath := filepath.Join(tmpPath, fmt.Sprintf("srv4"))
if err := os.Mkdir(srvPath, 0700); err != nil {
requireNoErrorf(t, err, "failed to make server path")
}
testSrvConfig := ServerConfigServer{
ID: 4,
Host: "127.0.0.1",
PeerPort: startPort + 1,
LeaderElectionPort: startPort + 2,
}
cfg := ServerConfig{
ClientPort: startPort,
DataDir: srvPath,
Servers: []ServerConfigServer{testSrvConfig},
}
// TODO: clean all this server creating up to a better helper method
cfgPath := filepath.Join(srvPath, _testConfigName)
fi, err := os.Create(cfgPath)
requireNoErrorf(t, err)
requireNoErrorf(t, cfg.Marshall(fi))
fi.Close()
fi, err = os.Create(filepath.Join(srvPath, _testMyIDFileName))
requireNoErrorf(t, err)
_, err = fmt.Fprintln(fi, "4")
fi.Close()
requireNoErrorf(t, err)
testServer, err := NewIntegrationTestServer(t, cfgPath, nil, nil)
requireNoErrorf(t, err)
requireNoErrorf(t, testServer.Start())
defer testServer.Stop()
zk, events, err := ts.ConnectAll()
requireNoErrorf(t, err, "failed to connect to cluster")
defer zk.Close()
err = zk.AddAuth("digest", []byte("super:test"))
requireNoErrorf(t, err, "failed to auth to cluster")
waitCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err = waitForSession(waitCtx, events)
requireNoErrorf(t, err, "failed to wail for session")
_, _, err = zk.Get("/zookeeper/config")
if err != nil {
t.Fatalf("get config returned error: %+v", err)
}
// initially should be 1<<32, which is 0x100000000. This is the zxid
// of the first NEWLEADER message, used as the inital version
// reflect.DeepEqual(bytes.Split(data, []byte("\n")), []byte("version=100000000"))
// remove node 3.
_, err = zk.IncrementalReconfig(nil, []string{"3"}, -1)
if err != nil && err == ErrConnectionClosed {
t.Log("conneciton closed is fine since the cluster re-elects and we dont reconnect")
} else {
requireNoErrorf(t, err, "failed to remove node from cluster")
}
// add node a new 4th node
server := fmt.Sprintf("server.%d=%s:%d:%d;%d", testSrvConfig.ID, testSrvConfig.Host, testSrvConfig.PeerPort, testSrvConfig.LeaderElectionPort, cfg.ClientPort)
_, err = zk.IncrementalReconfig([]string{server}, nil, -1)
if err != nil && err == ErrConnectionClosed {
t.Log("conneciton closed is fine since the cluster re-elects and we dont reconnect")
} else {
requireNoErrorf(t, err, "failed to add new server to cluster")
}
}
func TestIntegration_Reconfig(t *testing.T) {
requireMinimumZkVersion(t, "3.5")
// This test enures we can do an non-incremental reconfig
ts, err := StartTestCluster(t, 3, nil, logWriter{t: t, p: "[ZKERR] "})
requireNoErrorf(t, err, "failed to setup test cluster")
defer ts.Stop()
zk, events, err := ts.ConnectAll()
requireNoErrorf(t, err, "failed to connect to cluster")
defer zk.Close()
err = zk.AddAuth("digest", []byte("super:test"))
requireNoErrorf(t, err, "failed to auth to cluster")
waitCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err = waitForSession(waitCtx, events)
requireNoErrorf(t, err, "failed to wail for session")
_, _, err = zk.Get("/zookeeper/config")
if err != nil {
t.Fatalf("get config returned error: %+v", err)
}
// essentially remove the first node
var s []string
for _, host := range ts.Config.Servers[1:] {
s = append(s, fmt.Sprintf("server.%d=%s:%d:%d;%d\n", host.ID, host.Host, host.PeerPort, host.LeaderElectionPort, ts.Config.ClientPort))
}
_, err = zk.Reconfig(s, -1)
requireNoErrorf(t, err, "failed to reconfig cluster")
// reconfig to all the hosts again
s = []string{}
for _, host := range ts.Config.Servers {
s = append(s, fmt.Sprintf("server.%d=%s:%d:%d;%d\n", host.ID, host.Host, host.PeerPort, host.LeaderElectionPort, ts.Config.ClientPort))
}
_, err = zk.Reconfig(s, -1)
requireNoErrorf(t, err, "failed to reconfig cluster")
}
func TestIntegration_OpsAfterCloseDontDeadlock(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
zk.Close()
path := "/gozk-test"
ch := make(chan struct{})
go func() {
defer close(ch)
for range make([]struct{}, 30) {
if _, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err == nil {
t.Fatal("Create did not return error")
}
}
}()
select {
case <-ch:
// expected
case <-time.After(10 * time.Second):
t.Fatal("ZK connection deadlocked when executing ops after a Close operation")
}
}
func TestIntegration_Multi(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
path := "/gozk-test"
if err := zk.Delete(path, -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
ops := []interface{}{
&CreateRequest{Path: path, Data: []byte{1, 2, 3, 4}, Acl: WorldACL(PermAll)},
&SetDataRequest{Path: path, Data: []byte{1, 2, 3, 4}, Version: -1},
}
if res, err := zk.Multi(ops...); err != nil {
t.Fatalf("Multi returned error: %+v", err)
} else if len(res) != 2 {
t.Fatalf("Expected 2 responses got %d", len(res))
} else {
t.Logf("%+v", res)
}
if data, stat, err := zk.Get(path); err != nil {
t.Fatalf("Get returned error: %+v", err)
} else if stat == nil {
t.Fatal("Get returned nil stat")
} else if len(data) < 4 {
t.Fatal("Get returned wrong size data")
}
}
func TestIntegration_IfAuthdataSurvivesReconnect(t *testing.T) {
// This test case ensures authentication data is being resubmited after
// reconnect.
testNode := "/auth-testnode"
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
acl := DigestACL(PermAll, "userfoo", "passbar")
_, err = zk.Create(testNode, []byte("Some very secret content"), 0, acl)
if err != nil && err != ErrNodeExists {
t.Fatalf("Failed to create test node : %+v", err)
}
_, _, err = zk.Get(testNode)
if err == nil || err != ErrNoAuth {
var msg string
if err == nil {
msg = "Fetching data without auth should have resulted in an error"
} else {
msg = fmt.Sprintf("Expecting ErrNoAuth, got `%+v` instead", err)
}
t.Fatalf(msg)
}
zk.AddAuth("digest", []byte("userfoo:passbar"))
_, _, err = zk.Get(testNode)
if err != nil {
t.Fatalf("Fetching data with auth failed: %+v", err)
}
ts.StopAllServers()
ts.StartAllServers()
_, _, err = zk.Get(testNode)
if err != nil {
t.Fatalf("Fetching data after reconnect failed: %+v", err)
}
}
func TestIntegration_MultiFailures(t *testing.T) {
// This test case ensures that we return the errors associated with each
// opeThis in the event a call to Multi() fails.
const firstPath = "/gozk-test-first"
const secondPath = "/gozk-test-second"
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
// Ensure firstPath doesn't exist and secondPath does. This will cause the
// 2nd operation in the Multi() to fail.
if err := zk.Delete(firstPath, -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
if _, err := zk.Create(secondPath, nil /* data */, 0, WorldACL(PermAll)); err != nil {
t.Fatalf("Create returned error: %+v", err)
}
ops := []interface{}{
&CreateRequest{Path: firstPath, Data: []byte{1, 2}, Acl: WorldACL(PermAll)},
&CreateRequest{Path: secondPath, Data: []byte{3, 4}, Acl: WorldACL(PermAll)},
}
res, err := zk.Multi(ops...)
if err != ErrNodeExists {
t.Fatalf("Multi() didn't return correct error: %+v", err)
}
if len(res) != 2 {
t.Fatalf("Expected 2 responses received %d", len(res))
}
if res[0].Error != nil {
t.Fatalf("First operation returned an unexpected error %+v", res[0].Error)
}
if res[1].Error != ErrNodeExists {
t.Fatalf("Second operation returned incorrect error %+v", res[1].Error)
}
if _, _, err := zk.Get(firstPath); err != ErrNoNode {
t.Fatalf("Node %s was incorrectly created: %+v", firstPath, err)
}
}
func TestIntegration_GetSetACL(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
if err := zk.AddAuth("digest", []byte("blah")); err != nil {
t.Fatalf("AddAuth returned error %+v", err)
}
path := "/gozk-test"
if err := zk.Delete(path, -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
if path, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil {
t.Fatalf("Create returned error: %+v", err)
} else if path != "/gozk-test" {
t.Fatalf("Create returned different path '%s' != '/gozk-test'", path)
}
expected := WorldACL(PermAll)
if acl, stat, err := zk.GetACL(path); err != nil {
t.Fatalf("GetACL returned error %+v", err)
} else if stat == nil {
t.Fatalf("GetACL returned nil Stat")
} else if len(acl) != 1 || expected[0] != acl[0] {
t.Fatalf("GetACL mismatch expected %+v instead of %+v", expected, acl)
}
expected = []ACL{{PermAll, "ip", "127.0.0.1"}}
if stat, err := zk.SetACL(path, expected, -1); err != nil {
t.Fatalf("SetACL returned error %+v", err)
} else if stat == nil {
t.Fatalf("SetACL returned nil Stat")
}
if acl, stat, err := zk.GetACL(path); err != nil {
t.Fatalf("GetACL returned error %+v", err)
} else if stat == nil {
t.Fatalf("GetACL returned nil Stat")
} else if len(acl) != 1 || expected[0] != acl[0] {
t.Fatalf("GetACL mismatch expected %+v instead of %+v", expected, acl)
}
}
func TestIntegration_Auth(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
path := "/gozk-digest-test"
if err := zk.Delete(path, -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
acl := DigestACL(PermAll, "user", "password")
if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, acl); err != nil {
t.Fatalf("Create returned error: %+v", err)
} else if p != path {
t.Fatalf("Create returned different path '%s' != '%s'", p, path)
}
if _, _, err := zk.Get(path); err != ErrNoAuth {
t.Fatalf("Get returned error %+v instead of ErrNoAuth", err)
}
if err := zk.AddAuth("digest", []byte("user:password")); err != nil {
t.Fatalf("AddAuth returned error %+v", err)
}
if a, stat, err := zk.GetACL(path); err != nil {
t.Fatalf("GetACL returned error %+v", err)
} else if stat == nil {
t.Fatalf("GetACL returned nil Stat")
} else if len(a) != 1 || acl[0] != a[0] {
t.Fatalf("GetACL mismatch expected %+v instead of %+v", acl, a)
}
if data, stat, err := zk.Get(path); err != nil {
t.Fatalf("Get returned error %+v", err)
} else if stat == nil {
t.Fatalf("Get returned nil Stat")
} else if len(data) != 4 {
t.Fatalf("Get returned wrong data length")
}
}
func TestIntegration_Children(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
deleteNode := func(node string) {
if err := zk.Delete(node, -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
}
deleteNode("/gozk-test-big")
if path, err := zk.Create("/gozk-test-big", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil {
t.Fatalf("Create returned error: %+v", err)
} else if path != "/gozk-test-big" {
t.Fatalf("Create returned different path '%s' != '/gozk-test-big'", path)
}
rb := make([]byte, 1000)
hb := make([]byte, 2000)
prefix := []byte("/gozk-test-big/")
for i := 0; i < 10000; i++ {
_, err := rand.Read(rb)
if err != nil {
t.Fatal("Cannot create random znode name")
}
hex.Encode(hb, rb)
expect := string(append(prefix, hb...))
if path, err := zk.Create(expect, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil {
t.Fatalf("Create returned error: %+v", err)
} else if path != expect {
t.Fatalf("Create returned different path '%s' != '%s'", path, expect)
}
defer deleteNode(string(expect))
}
children, _, err := zk.Children("/gozk-test-big")
if err != nil {
t.Fatalf("Children returned error: %+v", err)
} else if len(children) != 10000 {
t.Fatal("Children returned wrong number of nodes")
}
}
func TestIntegration_ChildWatch(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
children, stat, childCh, err := zk.ChildrenW("/")
if err != nil {
t.Fatalf("Children returned error: %+v", err)
} else if stat == nil {
t.Fatal("Children returned nil stat")
} else if len(children) < 1 {
t.Fatal("Children should return at least 1 child")
}
if path, err := zk.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil {
t.Fatalf("Create returned error: %+v", err)
} else if path != "/gozk-test" {
t.Fatalf("Create returned different path '%s' != '/gozk-test'", path)
}
select {
case ev := <-childCh:
if ev.Err != nil {
t.Fatalf("Child watcher error %+v", ev.Err)
}
if ev.Path != "/" {
t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/")
}
case _ = <-time.After(time.Second * 2):
t.Fatal("Child watcher timed out")
}
// Delete of the watched node should trigger the watch
children, stat, childCh, err = zk.ChildrenW("/gozk-test")
if err != nil {
t.Fatalf("Children returned error: %+v", err)
} else if stat == nil {
t.Fatal("Children returned nil stat")
} else if len(children) != 0 {
t.Fatal("Children should return 0 children")
}
if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
select {
case ev := <-childCh:
if ev.Err != nil {
t.Fatalf("Child watcher error %+v", ev.Err)
}
if ev.Path != "/gozk-test" {
t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/")
}
case _ = <-time.After(time.Second * 2):
t.Fatal("Child watcher timed out")
}
}
func TestIntegration_SetWatchers(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()
zk.reconnectLatch = make(chan struct{})
zk.setWatchLimit = 1024 // break up set-watch step into 1k requests
var setWatchReqs atomic.Value
zk.setWatchCallback = func(reqs []*setWatchesRequest) {
setWatchReqs.Store(reqs)
}
zk2, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk2.Close()
if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
testPaths := map[string]<-chan Event{}
defer func() {
// clean up all of the test paths we create
for p := range testPaths {
zk2.Delete(p, -1)
}
}()
// we create lots of paths to watch, to make sure a "set watches" request
// on re-create will be too big and be required to span multiple packets
for i := 0; i < 1000; i++ {
testPath, err := zk.Create(fmt.Sprintf("/gozk-test-%d", i), []byte{}, 0, WorldACL(PermAll))
if err != nil {
t.Fatalf("Create returned: %+v", err)
}
testPaths[testPath] = nil
_, _, testEvCh, err := zk.GetW(testPath)
if err != nil {
t.Fatalf("GetW returned: %+v", err)
}
testPaths[testPath] = testEvCh
}
children, stat, childCh, err := zk.ChildrenW("/")
if err != nil {
t.Fatalf("Children returned error: %+v", err)
} else if stat == nil {
t.Fatal("Children returned nil stat")
} else if len(children) < 1 {
t.Fatal("Children should return at least 1 child")
}
// Simulate network error by brutally closing the network connection.
zk.conn.Close()
for p := range testPaths {
if err := zk2.Delete(p, -1); err != nil && err != ErrNoNode {
t.Fatalf("Delete returned error: %+v", err)
}
}
if path, err := zk2.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil {
t.Fatalf("Create returned error: %+v", err)
} else if path != "/gozk-test" {
t.Fatalf("Create returned different path '%s' != '/gozk-test'", path)
}
time.Sleep(100 * time.Millisecond)
// zk should still be waiting to reconnect, so none of the watches should have been triggered
for p, ch := range testPaths {
select {
case <-ch:
t.Fatalf("GetW watcher for %q should not have triggered yet", p)
default:
}
}
select {
case <-childCh:
t.Fatalf("ChildrenW watcher should not have triggered yet")
default:
}
// now we let the reconnect occur and make sure it resets watches
close(zk.reconnectLatch)
for p, ch := range testPaths {
select {
case ev := <-ch:
if ev.Err != nil {
t.Fatalf("GetW watcher error %+v", ev.Err)
}
if ev.Path != p {
t.Fatalf("GetW watcher wrong path %s instead of %s", ev.Path, p)
}
case <-time.After(2 * time.Second):
t.Fatal("GetW watcher timed out")
}
}
select {
case ev := <-childCh:
if ev.Err != nil {
t.Fatalf("Child watcher error %+v", ev.Err)
}
if ev.Path != "/" {
t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/")
}
case <-time.After(2 * time.Second):
t.Fatal("Child watcher timed out")
}
// Yay! All watches fired correctly. Now we also inspect the actual set-watch request objects
// to ensure they didn't exceed the expected packet set.
buf := make([]byte, bufferSize)
totalWatches := 0
actualReqs := setWatchReqs.Load().([]*setWatchesRequest)
if len(actualReqs) < 12 {
// sanity check: we should have generated *at least* 12 requests to reset watches
t.Fatalf("too few setWatchesRequest messages: %d", len(actualReqs))
}
for _, r := range actualReqs {
totalWatches += len(r.ChildWatches) + len(r.DataWatches) + len(r.ExistWatches)
n, err := encodePacket(buf, r)
if err != nil {
t.Fatalf("encodePacket failed: %v! request:\n%+v", err, r)
} else if n > 1024 {
t.Fatalf("setWatchesRequest exceeded allowed size (%d > 1024)! request:\n%+v", n, r)
}
}
if totalWatches != len(testPaths)+1 {
t.Fatalf("setWatchesRequests did not include all expected watches; expecting %d, got %d", len(testPaths)+1, totalWatches)
}
}
func TestIntegration_ExpiringWatch(t *testing.T) {
ts, err := StartTestCluster(t, 1, nil, logWriter{t: t, p: "[ZKERR] "})
if err != nil {
t.Fatal(err)
}
defer ts.Stop()
zk, _, err := ts.ConnectAll()
if err != nil {
t.Fatalf("Connect returned error: %+v", err)
}
defer zk.Close()