forked from go-mgo/mgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster_test.go
2090 lines (1685 loc) · 53.5 KB
/
cluster_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
// mgo - MongoDB driver for Go
//
// Copyright (c) 2010-2012 - Gustavo Niemeyer <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package mgo_test
import (
"fmt"
"io"
"net"
"strings"
"sync"
"time"
. "gopkg.in/check.v1"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func (s *S) TestNewSession(c *C) {
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
// Do a dummy operation to wait for connection.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"_id": 1})
c.Assert(err, IsNil)
// Tweak safety and query settings to ensure other has copied those.
session.SetSafe(nil)
session.SetBatch(-1)
other := session.New()
defer other.Close()
session.SetSafe(&mgo.Safe{})
// Clone was copied while session was unsafe, so no errors.
otherColl := other.DB("mydb").C("mycoll")
err = otherColl.Insert(M{"_id": 1})
c.Assert(err, IsNil)
// Original session was made safe again.
err = coll.Insert(M{"_id": 1})
c.Assert(err, NotNil)
// With New(), each session has its own socket now.
stats := mgo.GetStats()
c.Assert(stats.MasterConns, Equals, 2)
c.Assert(stats.SocketsInUse, Equals, 2)
// Ensure query parameters were cloned.
err = otherColl.Insert(M{"_id": 2})
c.Assert(err, IsNil)
// Ping the database to ensure the nonce has been received already.
c.Assert(other.Ping(), IsNil)
mgo.ResetStats()
iter := otherColl.Find(M{}).Iter()
c.Assert(err, IsNil)
m := M{}
ok := iter.Next(m)
c.Assert(ok, Equals, true)
err = iter.Close()
c.Assert(err, IsNil)
// If Batch(-1) is in effect, a single document must have been received.
stats = mgo.GetStats()
c.Assert(stats.ReceivedDocs, Equals, 1)
}
func (s *S) TestCloneSession(c *C) {
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
// Do a dummy operation to wait for connection.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"_id": 1})
c.Assert(err, IsNil)
// Tweak safety and query settings to ensure clone is copying those.
session.SetSafe(nil)
session.SetBatch(-1)
clone := session.Clone()
defer clone.Close()
session.SetSafe(&mgo.Safe{})
// Clone was copied while session was unsafe, so no errors.
cloneColl := clone.DB("mydb").C("mycoll")
err = cloneColl.Insert(M{"_id": 1})
c.Assert(err, IsNil)
// Original session was made safe again.
err = coll.Insert(M{"_id": 1})
c.Assert(err, NotNil)
// With Clone(), same socket is shared between sessions now.
stats := mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 1)
c.Assert(stats.SocketRefs, Equals, 2)
// Refreshing one of them should let the original socket go,
// while preserving the safety settings.
clone.Refresh()
err = cloneColl.Insert(M{"_id": 1})
c.Assert(err, IsNil)
// Must have used another connection now.
stats = mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 2)
c.Assert(stats.SocketRefs, Equals, 2)
// Ensure query parameters were cloned.
err = cloneColl.Insert(M{"_id": 2})
c.Assert(err, IsNil)
// Ping the database to ensure the nonce has been received already.
c.Assert(clone.Ping(), IsNil)
mgo.ResetStats()
iter := cloneColl.Find(M{}).Iter()
c.Assert(err, IsNil)
m := M{}
ok := iter.Next(m)
c.Assert(ok, Equals, true)
err = iter.Close()
c.Assert(err, IsNil)
// If Batch(-1) is in effect, a single document must have been received.
stats = mgo.GetStats()
c.Assert(stats.ReceivedDocs, Equals, 1)
}
func (s *S) TestModeStrong(c *C) {
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Monotonic, false)
session.SetMode(mgo.Strong, false)
c.Assert(session.Mode(), Equals, mgo.Strong)
result := M{}
cmd := session.DB("admin").C("$cmd")
err = cmd.Find(M{"ismaster": 1}).One(&result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, true)
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
stats := mgo.GetStats()
c.Assert(stats.MasterConns, Equals, 1)
c.Assert(stats.SlaveConns, Equals, 2)
c.Assert(stats.SocketsInUse, Equals, 1)
session.SetMode(mgo.Strong, true)
stats = mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 0)
}
func (s *S) TestModeMonotonic(c *C) {
// Must necessarily connect to a slave, otherwise the
// master connection will be available first.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Monotonic, false)
c.Assert(session.Mode(), Equals, mgo.Monotonic)
var result struct{ IsMaster bool }
cmd := session.DB("admin").C("$cmd")
err = cmd.Find(M{"ismaster": 1}).One(&result)
c.Assert(err, IsNil)
c.Assert(result.IsMaster, Equals, false)
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
err = cmd.Find(M{"ismaster": 1}).One(&result)
c.Assert(err, IsNil)
c.Assert(result.IsMaster, Equals, true)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
stats := mgo.GetStats()
c.Assert(stats.MasterConns, Equals, 1)
c.Assert(stats.SlaveConns, Equals, 2)
c.Assert(stats.SocketsInUse, Equals, 2)
session.SetMode(mgo.Monotonic, true)
stats = mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 0)
}
func (s *S) TestModeMonotonicAfterStrong(c *C) {
// Test that a strong session shifting to a monotonic
// one preserves the socket untouched.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
// Insert something to force a connection to the master.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
session.SetMode(mgo.Monotonic, false)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
// Master socket should still be reserved.
stats := mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 1)
// Confirm it's the master even though it's Monotonic by now.
result := M{}
cmd := session.DB("admin").C("$cmd")
err = cmd.Find(M{"ismaster": 1}).One(&result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, true)
}
func (s *S) TestModeStrongAfterMonotonic(c *C) {
// Test that shifting from Monotonic to Strong while
// using a slave socket will keep the socket reserved
// until the master socket is necessary, so that no
// switch over occurs unless it's actually necessary.
// Must necessarily connect to a slave, otherwise the
// master connection will be available first.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Monotonic, false)
// Ensure we're talking to a slave, and reserve the socket.
result := M{}
err = session.Run("ismaster", &result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, false)
// Switch to a Strong session.
session.SetMode(mgo.Strong, false)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
// Slave socket should still be reserved.
stats := mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 1)
// But any operation will switch it to the master.
result = M{}
err = session.Run("ismaster", &result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, true)
}
func (s *S) TestModeMonotonicWriteOnIteration(c *C) {
// Must necessarily connect to a slave, otherwise the
// master connection will be available first.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Monotonic, false)
c.Assert(session.Mode(), Equals, mgo.Monotonic)
coll1 := session.DB("mydb").C("mycoll1")
coll2 := session.DB("mydb").C("mycoll2")
ns := []int{40, 41, 42, 43, 44, 45, 46}
for _, n := range ns {
err := coll1.Insert(M{"n": n})
c.Assert(err, IsNil)
}
// Release master so we can grab a slave again.
session.Refresh()
// Wait until synchronization is done.
for {
n, err := coll1.Count()
c.Assert(err, IsNil)
if n == len(ns) {
break
}
}
iter := coll1.Find(nil).Batch(2).Iter()
i := 0
m := M{}
for iter.Next(&m) {
i++
if i > 3 {
err := coll2.Insert(M{"n": 47 + i})
c.Assert(err, IsNil)
}
}
c.Assert(i, Equals, len(ns))
}
func (s *S) TestModeEventual(c *C) {
// Must necessarily connect to a slave, otherwise the
// master connection will be available first.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Eventual, false)
c.Assert(session.Mode(), Equals, mgo.Eventual)
result := M{}
err = session.Run("ismaster", &result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, false)
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
result = M{}
err = session.Run("ismaster", &result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, false)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
stats := mgo.GetStats()
c.Assert(stats.MasterConns, Equals, 1)
c.Assert(stats.SlaveConns, Equals, 2)
c.Assert(stats.SocketsInUse, Equals, 0)
}
func (s *S) TestModeEventualAfterStrong(c *C) {
// Test that a strong session shifting to an eventual
// one preserves the socket untouched.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
// Insert something to force a connection to the master.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
session.SetMode(mgo.Eventual, false)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
// Master socket should still be reserved.
stats := mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 1)
// Confirm it's the master even though it's Eventual by now.
result := M{}
cmd := session.DB("admin").C("$cmd")
err = cmd.Find(M{"ismaster": 1}).One(&result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, true)
session.SetMode(mgo.Eventual, true)
stats = mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 0)
}
func (s *S) TestModeStrongFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
// With strong consistency, this will open a socket to the master.
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
// Kill the master.
host := result.Host
s.Stop(host)
// This must fail, since the connection was broken.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
// With strong consistency, it fails again until reset.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
session.Refresh()
// Now we should be able to talk to the new master.
// Increase the timeout since this may take quite a while.
session.SetSyncTimeout(3 * time.Minute)
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Not(Equals), host)
// Insert some data to confirm it's indeed a master.
err = session.DB("mydb").C("mycoll").Insert(M{"n": 42})
c.Assert(err, IsNil)
}
func (s *S) TestModePrimaryHiccup(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
// With strong consistency, this will open a socket to the master.
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
// Establish a few extra sessions to create spare sockets to
// the master. This increases a bit the chances of getting an
// incorrect cached socket.
var sessions []*mgo.Session
for i := 0; i < 20; i++ {
sessions = append(sessions, session.Copy())
err = sessions[len(sessions)-1].Run("serverStatus", result)
c.Assert(err, IsNil)
}
for i := range sessions {
sessions[i].Close()
}
// Kill the master, but bring it back immediatelly.
host := result.Host
s.Stop(host)
s.StartAll()
// This must fail, since the connection was broken.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
// With strong consistency, it fails again until reset.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
session.Refresh()
// Now we should be able to talk to the new master.
// Increase the timeout since this may take quite a while.
session.SetSyncTimeout(3 * time.Minute)
// Insert some data to confirm it's indeed a master.
err = session.DB("mydb").C("mycoll").Insert(M{"n": 42})
c.Assert(err, IsNil)
}
func (s *S) TestModeMonotonicFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Monotonic, true)
// Insert something to force a switch to the master.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// Wait a bit for this to be synchronized to slaves.
time.Sleep(3 * time.Second)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
// Kill the master.
host := result.Host
s.Stop(host)
// This must fail, since the connection was broken.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
// With monotonic consistency, it fails again until reset.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
session.Refresh()
// Now we should be able to talk to the new master.
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Not(Equals), host)
}
func (s *S) TestModeMonotonicWithSlaveFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
ssresult := &struct{ Host string }{}
imresult := &struct{ IsMaster bool }{}
// Figure the master while still using the strong session.
err = session.Run("serverStatus", ssresult)
c.Assert(err, IsNil)
err = session.Run("isMaster", imresult)
c.Assert(err, IsNil)
master := ssresult.Host
c.Assert(imresult.IsMaster, Equals, true, Commentf("%s is not the master", master))
// Create new monotonic session with an explicit address to ensure
// a slave is synchronized before the master, otherwise a connection
// with the master may be used below for lack of other options.
var addr string
switch {
case strings.HasSuffix(ssresult.Host, ":40021"):
addr = "localhost:40022"
case strings.HasSuffix(ssresult.Host, ":40022"):
addr = "localhost:40021"
case strings.HasSuffix(ssresult.Host, ":40023"):
addr = "localhost:40021"
default:
c.Fatal("Unknown host: ", ssresult.Host)
}
session, err = mgo.Dial(addr)
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Monotonic, true)
// Check the address of the socket associated with the monotonic session.
c.Log("Running serverStatus and isMaster with monotonic session")
err = session.Run("serverStatus", ssresult)
c.Assert(err, IsNil)
err = session.Run("isMaster", imresult)
c.Assert(err, IsNil)
slave := ssresult.Host
c.Assert(imresult.IsMaster, Equals, false, Commentf("%s is not a slave", slave))
c.Assert(master, Not(Equals), slave)
// Kill the master.
s.Stop(master)
// Session must still be good, since we were talking to a slave.
err = session.Run("serverStatus", ssresult)
c.Assert(err, IsNil)
c.Assert(ssresult.Host, Equals, slave,
Commentf("Monotonic session moved from %s to %s", slave, ssresult.Host))
// If we try to insert something, it'll have to hold until the new
// master is available to move the connection, and work correctly.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// Must now be talking to the new master.
err = session.Run("serverStatus", ssresult)
c.Assert(err, IsNil)
err = session.Run("isMaster", imresult)
c.Assert(err, IsNil)
c.Assert(imresult.IsMaster, Equals, true, Commentf("%s is not the master", master))
// ... which is not the old one, since it's still dead.
c.Assert(ssresult.Host, Not(Equals), master)
}
func (s *S) TestModeEventualFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
master := result.Host
session.SetMode(mgo.Eventual, true)
// Should connect to the master when needed.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// Wait a bit for this to be synchronized to slaves.
time.Sleep(3 * time.Second)
// Kill the master.
s.Stop(master)
// Should still work, with the new master now.
coll = session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Not(Equals), master)
}
func (s *S) TestModeSecondaryJustPrimary(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Secondary, true)
err = session.Ping()
c.Assert(err, ErrorMatches, "no reachable servers")
}
func (s *S) TestModeSecondaryPreferredJustPrimary(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.SecondaryPreferred, true)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
}
func (s *S) TestModeSecondaryPreferredFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
defer session.Close()
// Ensure secondaries are available for being picked up.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
session.SetMode(mgo.SecondaryPreferred, true)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(supvName(result.Host), Not(Equals), "rs1a")
secondary := result.Host
// Should connect to the primary when needed.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// Wait a bit for this to be synchronized to slaves.
time.Sleep(3 * time.Second)
// Kill the primary.
s.Stop("localhost:40011")
// It can still talk to the selected secondary.
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Equals, secondary)
// But cannot speak to the primary until reset.
coll = session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, Equals, io.EOF)
session.Refresh()
// Can still talk to a secondary.
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(supvName(result.Host), Not(Equals), "rs1a")
s.StartAll()
// Should now be able to talk to the primary again.
coll = session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
}
func (s *S) TestModePrimaryPreferredFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.PrimaryPreferred, true)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(supvName(result.Host), Equals, "rs1a")
// Kill the primary.
s.Stop("localhost:40011")
// Should now fail as there was a primary socket in use already.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
// Refresh so the reserved primary socket goes away.
session.Refresh()
// Should be able to talk to the secondary.
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
s.StartAll()
// Should wait for the new primary to become available.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// And should use the new primary in general, as it is preferred.
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(supvName(result.Host), Equals, "rs1a")
}
func (s *S) TestModePrimaryFallover(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
defer session.Close()
session.SetSyncTimeout(3 * time.Second)
session.SetMode(mgo.Primary, true)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(supvName(result.Host), Equals, "rs1a")
// Kill the primary.
s.Stop("localhost:40011")
session.Refresh()
err = session.Ping()
c.Assert(err, ErrorMatches, "no reachable servers")
}
func (s *S) TestModeSecondary(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
defer session.Close()
session.SetMode(mgo.Secondary, true)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(supvName(result.Host), Not(Equals), "rs1a")
secondary := result.Host
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Equals, secondary)
}
func (s *S) TestPreserveSocketCountOnSync(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
defer session.Close()
stats := mgo.GetStats()
for stats.SocketsAlive != 3 {
c.Logf("Waiting for all connections to be established (sockets alive currently %d)...", stats.SocketsAlive)
stats = mgo.GetStats()
time.Sleep(5e8)
}
c.Assert(stats.SocketsAlive, Equals, 3)
// Kill the master (with rs1, 'a' is always the master).
s.Stop("localhost:40011")
// Wait for the logic to run for a bit and bring it back.
startedAll := make(chan bool)
go func() {
time.Sleep(5e9)
s.StartAll()
startedAll <- true
}()
// Do not allow the test to return before the goroutine above is done.
defer func() {
<-startedAll
}()
// Do an action to kick the resync logic in, and also to
// wait until the cluster recognizes the server is back.
result := struct{ Ok bool }{}
err = session.Run("getLastError", &result)
c.Assert(err, IsNil)
c.Assert(result.Ok, Equals, true)
for i := 0; i != 20; i++ {
stats = mgo.GetStats()
if stats.SocketsAlive == 3 {
break
}
c.Logf("Waiting for 3 sockets alive, have %d", stats.SocketsAlive)
time.Sleep(5e8)
}
// Ensure the number of sockets is preserved after syncing.
stats = mgo.GetStats()
c.Assert(stats.SocketsAlive, Equals, 3)
c.Assert(stats.SocketsInUse, Equals, 1)
c.Assert(stats.SocketRefs, Equals, 1)
}
// Connect to the master of a deployment with a single server,
// run an insert, and then ensure the insert worked and that a
// single connection was established.
func (s *S) TestTopologySyncWithSingleMaster(c *C) {
// Use hostname here rather than IP, to make things trickier.
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1, "b": 2})
c.Assert(err, IsNil)
// One connection used for discovery. Master socket recycled for
// insert. Socket is reserved after insert.
stats := mgo.GetStats()
c.Assert(stats.MasterConns, Equals, 1)
c.Assert(stats.SlaveConns, Equals, 0)
c.Assert(stats.SocketsInUse, Equals, 1)
// Refresh session and socket must be released.
session.Refresh()
stats = mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 0)
}
func (s *S) TestTopologySyncWithSlaveSeed(c *C) {
// That's supposed to be a slave. Must run discovery
// and find out master to insert successfully.
session, err := mgo.Dial("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
coll.Insert(M{"a": 1, "b": 2})
result := struct{ Ok bool }{}
err = session.Run("getLastError", &result)
c.Assert(err, IsNil)
c.Assert(result.Ok, Equals, true)
// One connection to each during discovery. Master
// socket recycled for insert.
stats := mgo.GetStats()
c.Assert(stats.MasterConns, Equals, 1)
c.Assert(stats.SlaveConns, Equals, 2)
// Only one socket reference alive, in the master socket owned
// by the above session.
c.Assert(stats.SocketsInUse, Equals, 1)
// Refresh it, and it must be gone.
session.Refresh()
stats = mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 0)
}
func (s *S) TestSyncTimeout(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
s.Stop("localhost:40001")
timeout := 3 * time.Second
session.SetSyncTimeout(timeout)
started := time.Now()
// Do something.
result := struct{ Ok bool }{}