forked from bakwc/PySyncObj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_syncobj.py
executable file
·2313 lines (1654 loc) · 64.2 KB
/
test_syncobj.py
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
from __future__ import print_function
import os
import time
import pytest
import random
import threading
import sys
import pysyncobj.pickle as pickle
import pysyncobj.dns_resolver as dns_resolver
import platform
if sys.version_info >= (3, 0):
xrange = range
from functools import partial
import functools
import struct
import logging
from pysyncobj import SyncObj, SyncObjConf, replicated, FAIL_REASON, _COMMAND_TYPE, \
createJournal, HAS_CRYPTO, replicated_sync, SyncObjException, SyncObjConsumer, _RAFT_STATE
from pysyncobj.syncobj_admin import executeAdminCommand
from pysyncobj.batteries import ReplCounter, ReplList, ReplDict, ReplSet, ReplLockManager, ReplQueue, ReplPriorityQueue
from pysyncobj.node import TCPNode
from collections import defaultdict
logging.basicConfig(format=u'[%(asctime)s %(filename)s:%(lineno)d %(levelname)s] %(message)s', level=logging.DEBUG)
_bchr = functools.partial(struct.pack, 'B')
class TEST_TYPE:
DEFAULT = 0
COMPACTION_1 = 1
COMPACTION_2 = 2
RAND_1 = 3
JOURNAL_1 = 4
AUTO_TICK_1 = 5
WAIT_BIND = 6
LARGE_COMMAND = 7
class TestObj(SyncObj):
def __init__(self, selfNodeAddr, otherNodeAddrs,
testType=TEST_TYPE.DEFAULT,
compactionMinEntries=0,
dumpFile=None,
journalFile=None,
password=None,
dynamicMembershipChange=False,
useFork=True,
testBindAddr=False,
consumers=None,
onStateChanged=None,
leaderFallbackTimeout=None):
cfg = SyncObjConf(autoTick=False, appendEntriesUseBatch=False)
cfg.appendEntriesPeriod = 0.1
cfg.raftMinTimeout = 0.5
cfg.raftMaxTimeout = 1.0
cfg.dynamicMembershipChange = dynamicMembershipChange
cfg.onStateChanged = onStateChanged
if leaderFallbackTimeout is not None:
cfg.leaderFallbackTimeout = leaderFallbackTimeout
if testBindAddr:
cfg.bindAddress = selfNodeAddr
if dumpFile is not None:
cfg.fullDumpFile = dumpFile
if password is not None:
cfg.password = password
cfg.useFork = useFork
if testType == TEST_TYPE.COMPACTION_1:
cfg.logCompactionMinEntries = compactionMinEntries
cfg.logCompactionMinTime = 0.1
cfg.appendEntriesUseBatch = True
if testType == TEST_TYPE.COMPACTION_2:
cfg.logCompactionMinEntries = 99999
cfg.logCompactionMinTime = 99999
cfg.fullDumpFile = dumpFile
if testType == TEST_TYPE.LARGE_COMMAND:
cfg.connectionTimeout = 15.0
cfg.logCompactionMinEntries = 99999
cfg.logCompactionMinTime = 99999
cfg.fullDumpFile = dumpFile
cfg.raftMinTimeout = 1.5
cfg.raftMaxTimeout = 2.5
# cfg.appendEntriesBatchSizeBytes = 2 ** 13
if testType == TEST_TYPE.RAND_1:
cfg.autoTickPeriod = 0.05
cfg.appendEntriesPeriod = 0.02
cfg.raftMinTimeout = 0.1
cfg.raftMaxTimeout = 0.2
cfg.logCompactionMinTime = 9999999
cfg.logCompactionMinEntries = 9999999
cfg.journalFile = journalFile
if testType == TEST_TYPE.JOURNAL_1:
cfg.logCompactionMinTime = 999999
cfg.logCompactionMinEntries = 999999
cfg.fullDumpFile = dumpFile
cfg.journalFile = journalFile
if testType == TEST_TYPE.AUTO_TICK_1:
cfg.autoTick = True
cfg.pollerType = 'select'
if testType == TEST_TYPE.WAIT_BIND:
cfg.maxBindRetries = 1
cfg.autoTick = True
super(TestObj, self).__init__(selfNodeAddr, otherNodeAddrs, cfg, consumers)
self.__counter = 0
self.__data = {}
if testType == TEST_TYPE.RAND_1:
self._SyncObj__transport._send_random_sleep_duration = 0.03
@replicated
def addValue(self, value):
self.__counter += value
return self.__counter
@replicated
def addKeyValue(self, key, value):
self.__data[key] = value
@replicated_sync
def addValueSync(self, value):
self.__counter += value
return self.__counter
@replicated
def testMethod(self):
self.__data['testKey'] = 'valueVer1'
@replicated(ver=1)
def testMethod(self):
self.__data['testKey'] = 'valueVer2'
def getCounter(self):
return self.__counter
def getValue(self, key):
return self.__data.get(key, None)
def dumpKeys(self):
print('keys:', sorted(self.__data.keys()))
def singleTickFunc(o, timeToTick, interval, stopFunc):
currTime = time.time()
finishTime = currTime + timeToTick
while time.time() < finishTime:
o._onTick(interval)
if stopFunc is not None:
if stopFunc():
break
def utilityTickFunc(args, currRes, key):
currRes[key] = executeAdminCommand(args)
def doSyncObjAdminTicks(objects, arguments, timeToTick, currRes, interval=0.05, stopFunc=None):
objThreads = []
utilityThreads = []
for o in objects:
t1 = threading.Thread(target=singleTickFunc, args=(o, timeToTick, interval, stopFunc))
t1.start()
objThreads.append(t1)
if arguments.get(o) is not None:
t2 = threading.Thread(target=utilityTickFunc, args=(arguments[o], currRes, o))
t2.start()
utilityThreads.append(t2)
for t in objThreads:
t.join()
for t in utilityThreads:
t.join()
def doTicks(objects, timeToTick, interval=0.05, stopFunc=None):
threads = []
for o in objects:
t = threading.Thread(target=singleTickFunc, args=(o, timeToTick, interval, stopFunc))
t.start()
threads.append(t)
for t in threads:
t.join()
def doAutoTicks(interval=0.05, stopFunc=None):
deadline = time.time() + interval
while not stopFunc():
time.sleep(0.02)
t2 = time.time()
if t2 >= deadline:
break
_g_nextAddress = 6000 + 60 * (int(time.time()) % 600)
def getNextAddr(ipv6=False, isLocalhost=False):
global _g_nextAddress
_g_nextAddress += 1
if ipv6:
return '::1:%d' % _g_nextAddress
if isLocalhost:
return 'localhost:%d' % _g_nextAddress
return '127.0.0.1:%d' % _g_nextAddress
_g_nextDumpFile = 1
_g_nextJournalFile = 1
def getNextDumpFile():
global _g_nextDumpFile
fname = 'dump%d.bin' % _g_nextDumpFile
_g_nextDumpFile += 1
return fname
def getNextJournalFile():
global _g_nextJournalFile
fname = 'journal%d.bin' % _g_nextJournalFile
_g_nextJournalFile += 1
return fname
def test_syncTwoObjects():
random.seed(42)
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]])
o2 = TestObj(a[1], [a[0]])
objs = [o1, o2]
assert not o1._isReady()
assert not o2._isReady()
doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())
o1.waitBinded()
o2.waitBinded()
o1._printStatus()
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
assert o1._isReady()
assert o2._isReady()
o1.addValue(150)
o2.addValue(200)
doTicks(objs, 10.0, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)
assert o1._isReady()
assert o2._isReady()
assert o1.getCounter() == 350
assert o2.getCounter() == 350
o1._destroy()
o2._destroy()
def test_hasQuorum():
random.seed(42)
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]])
o2 = TestObj(a[1], [a[0]])
objs = [o1, o2]
doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())
o1.waitBinded()
o2.waitBinded()
o1._printStatus()
assert o1.hasQuorum
# Stop the second node in the cluster
o2._destroy()
doTicks(objs, 10.0, stopFunc=lambda: not o1.hasQuorum)
assert not o1.hasQuorum
o1._destroy()
def test_singleObject():
random.seed(42)
a = [getNextAddr(), ]
o1 = TestObj(a[0], [])
objs = [o1, ]
assert not o1._isReady()
doTicks(objs, 3.0, stopFunc=lambda: o1._isReady())
o1._printStatus()
assert o1._getLeader().address in a
assert o1._isReady()
o1.addValue(150)
o1.addValue(200)
doTicks(objs, 3.0, stopFunc=lambda: o1.getCounter() == 350)
assert o1._isReady()
assert o1.getCounter() == 350
o1._destroy()
def test_syncThreeObjectsLeaderFail():
random.seed(12)
a = [getNextAddr(), getNextAddr(), getNextAddr()]
states = defaultdict(list)
o1 = TestObj(a[0], [a[1], a[2]], testBindAddr=True, onStateChanged=lambda old, new: states[a[0]].append(new))
o2 = TestObj(a[1], [a[2], a[0]], testBindAddr=True, onStateChanged=lambda old, new: states[a[1]].append(new))
o3 = TestObj(a[2], [a[0], a[1]], testBindAddr=True, onStateChanged=lambda old, new: states[a[2]].append(new))
objs = [o1, o2, o3]
assert not o1._isReady()
assert not o2._isReady()
assert not o3._isReady()
doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())
assert o1._isReady()
assert o2._isReady()
assert o3._isReady()
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
assert o1._getLeader() == o3._getLeader()
assert _RAFT_STATE.LEADER in states[o1._getLeader().address]
o1.addValue(150)
o2.addValue(200)
doTicks(objs, 10.0, stopFunc=lambda: o3.getCounter() == 350)
assert o3.getCounter() == 350
prevLeader = o1._getLeader()
newObjs = [o for o in objs if o._SyncObj__selfNode != prevLeader]
assert len(newObjs) == 2
doTicks(newObjs, 10.0, stopFunc=lambda: newObjs[0]._getLeader() != prevLeader and \
newObjs[0]._getLeader() is not None and \
newObjs[0]._getLeader().address in a and \
newObjs[0]._getLeader() == newObjs[1]._getLeader())
assert newObjs[0]._getLeader() != prevLeader
assert newObjs[0]._getLeader().address in a
assert newObjs[0]._getLeader() == newObjs[1]._getLeader()
assert _RAFT_STATE.LEADER in states[newObjs[0]._getLeader().address]
newObjs[1].addValue(50)
doTicks(newObjs, 10, stopFunc=lambda: newObjs[0].getCounter() == 400)
assert newObjs[0].getCounter() == 400
doTicks(objs, 10.0, stopFunc=lambda: sum([int(o.getCounter() == 400) for o in objs]) == len(objs))
for o in objs:
assert o.getCounter() == 400
o1._destroy()
o2._destroy()
o3._destroy()
def test_manyActionsLogCompaction():
random.seed(42)
a = [getNextAddr(), getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1], a[2]], TEST_TYPE.COMPACTION_1, compactionMinEntries=100)
o2 = TestObj(a[1], [a[2], a[0]], TEST_TYPE.COMPACTION_1, compactionMinEntries=100)
o3 = TestObj(a[2], [a[0], a[1]], TEST_TYPE.COMPACTION_1, compactionMinEntries=100)
objs = [o1, o2, o3]
assert not o1._isReady()
assert not o2._isReady()
assert not o3._isReady()
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())
assert o1._isReady()
assert o2._isReady()
assert o3._isReady()
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
assert o1._getLeader() == o3._getLeader()
for i in xrange(0, 500):
o1.addValue(1)
o2.addValue(1)
doTicks(objs, 10, stopFunc=lambda:
o1.getCounter() == 1000 and
o2.getCounter() == 1000 and
o3.getCounter() == 1000 and
o1._getRaftLogSize() <= 100 and
o2._getRaftLogSize() <= 100 and
o3._getRaftLogSize() <= 100
)
assert o1.getCounter() == 1000
assert o2.getCounter() == 1000
assert o3.getCounter() == 1000
assert o1._getRaftLogSize() <= 100
assert o2._getRaftLogSize() <= 100
assert o3._getRaftLogSize() <= 100
newObjs = [o1, o2]
doTicks(newObjs, 10, stopFunc=lambda: o3._getLeader() is None)
for i in xrange(0, 500):
o1.addValue(1)
o2.addValue(1)
doTicks(newObjs, 10, stopFunc=lambda:
o1.getCounter() == 2000 and
o2.getCounter() == 2000 and
o1._getRaftLogSize() <= 100 and
o2._getRaftLogSize() <= 100 and
o3._getRaftLogSize() <= 100
)
assert o1.getCounter() == 2000
assert o2.getCounter() == 2000
assert o3.getCounter() != 2000
doTicks(objs, 10, stopFunc=lambda: o3.getCounter() == 2000)
assert o3.getCounter() == 2000
assert o1._getRaftLogSize() <= 100
assert o2._getRaftLogSize() <= 100
assert o3._getRaftLogSize() <= 100
o1._destroy()
o2._destroy()
o3._destroy()
def onAddValue(res, err, info):
assert res == 3
assert err == FAIL_REASON.SUCCESS
info['callback'] = True
def test_checkCallbacksSimple():
random.seed(42)
a = [getNextAddr(), getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1], a[2]])
o2 = TestObj(a[1], [a[2], a[0]])
o3 = TestObj(a[2], [a[0], a[1]])
objs = [o1, o2, o3]
assert not o1._isReady()
assert not o2._isReady()
assert not o3._isReady()
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())
assert o1._isReady()
assert o2._isReady()
assert o3._isReady()
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
assert o1._getLeader() == o3._getLeader()
callbackInfo = {
'callback': False
}
o1.addValue(3, callback=partial(onAddValue, info=callbackInfo))
doTicks(objs, 10, stopFunc=lambda: o2.getCounter() == 3 and callbackInfo['callback'] == True)
assert o2.getCounter() == 3
assert callbackInfo['callback'] == True
o1._destroy()
o2._destroy()
o3._destroy()
def removeFiles(files):
for f in (files):
if os.path.isfile(f):
for i in xrange(0, 15):
try:
if os.path.isfile(f):
os.remove(f)
break
else:
break
except:
time.sleep(1.0)
def checkDumpToFile(useFork):
dumpFiles = [getNextDumpFile(), getNextDumpFile()]
removeFiles(dumpFiles)
random.seed(42)
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0], useFork=useFork)
o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1], useFork=useFork)
objs = [o1, o2]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
o1.addValue(150)
o2.addValue(200)
doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)
assert o1.getCounter() == 350
assert o2.getCounter() == 350
o1._forceLogCompaction()
o2._forceLogCompaction()
doTicks(objs, 1.5)
o1._destroy()
o2._destroy()
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0], useFork=useFork)
o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1], useFork=useFork)
objs = [o1, o2]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._isReady()
assert o2._isReady()
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
assert o1.getCounter() == 350
assert o2.getCounter() == 350
o1._destroy()
o2._destroy()
removeFiles(dumpFiles)
def test_checkDumpToFile():
if hasattr(os, 'fork'):
checkDumpToFile(True)
checkDumpToFile(False)
def getRandStr():
return '%0100000x' % random.randrange(16 ** 100000)
def test_checkBigStorage():
dumpFiles = [getNextDumpFile(), getNextDumpFile()]
removeFiles(dumpFiles)
random.seed(42)
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0])
o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1])
objs = [o1, o2]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
# Store ~50Mb data.
testRandStr = getRandStr()
for i in xrange(0, 500):
o1.addKeyValue(i, getRandStr())
o1.addKeyValue('test', testRandStr)
# Wait for replication.
doTicks(objs, 60, stopFunc=lambda: o1.getValue('test') == testRandStr and \
o2.getValue('test') == testRandStr)
assert o1.getValue('test') == testRandStr
o1._forceLogCompaction()
o2._forceLogCompaction()
# Wait for disk dump
doTicks(objs, 8.0)
o1._destroy()
o2._destroy()
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0])
o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1])
objs = [o1, o2]
# Wait for disk load, election and replication
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
assert o1.getValue('test') == testRandStr
assert o2.getValue('test') == testRandStr
o1._destroy()
o2._destroy()
removeFiles(dumpFiles)
@pytest.mark.skipif(sys.platform == "win32" or platform.python_implementation() != 'CPython', reason="does not run on windows or pypy")
def test_encryptionCorrectPassword():
assert HAS_CRYPTO
random.seed(42)
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]], password='asd')
o2 = TestObj(a[1], [a[0]], password='asd')
objs = [o1, o2]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
o1.addValue(150)
o2.addValue(200)
doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)
assert o1.getCounter() == 350
assert o2.getCounter() == 350
for conn in list(o1._SyncObj__transport._connections.values()) + list(o2._SyncObj__transport._connections.values()):
conn.disconnect()
doTicks(objs, 10)
o1.addValue(100)
doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 450 and o2.getCounter() == 450)
assert o1.getCounter() == 450
assert o2.getCounter() == 450
o1._destroy()
o2._destroy()
@pytest.mark.skipif(platform.python_implementation() != 'CPython', reason="does not have crypto on pypy")
def test_encryptionWrongPassword():
assert HAS_CRYPTO
random.seed(12)
a = [getNextAddr(), getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1], a[2]], password='asd')
o2 = TestObj(a[1], [a[2], a[0]], password='asd')
o3 = TestObj(a[2], [a[0], a[1]], password='qwe')
objs = [o1, o2, o3]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
doTicks(objs, 1.0)
assert o3._getLeader() is None
o1._destroy()
o2._destroy()
o3._destroy()
def _checkSameLeader(objs):
for obj1 in objs:
l1 = obj1._getLeader()
if l1 != obj1._SyncObj__selfNode:
continue
t1 = obj1._getTerm()
for obj2 in objs:
l2 = obj2._getLeader()
if l2 != obj2._SyncObj__selfNode:
continue
if obj2._getTerm() != t1:
continue
if l2 != l1:
obj1._printStatus()
obj2._printStatus()
return False
return True
def _checkSameLeader2(objs):
for obj1 in objs:
l1 = obj1._getLeader()
if l1 is None:
continue
t1 = obj1._getTerm()
for obj2 in objs:
l2 = obj2._getLeader()
if l2 is None:
continue
if obj2._getTerm() != t1:
continue
if l2 != l1:
obj1._printStatus()
obj2._printStatus()
return False
return True
def test_randomTest1():
journalFiles = [getNextJournalFile(), getNextJournalFile(), getNextJournalFile()]
removeFiles(journalFiles)
removeFiles([e + '.meta' for e in journalFiles])
random.seed(12)
a = [getNextAddr(), getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1], a[2]], TEST_TYPE.RAND_1, journalFile=journalFiles[0])
o2 = TestObj(a[1], [a[2], a[0]], TEST_TYPE.RAND_1, journalFile=journalFiles[1])
o3 = TestObj(a[2], [a[0], a[1]], TEST_TYPE.RAND_1, journalFile=journalFiles[2])
objs = [o1, o2, o3]
raft_commit_indices = [0, 0, 0]
st = time.time()
while time.time() - st < 120.0:
doTicks(objs, random.random() * 0.3, interval=0.05)
for i in range(3):
new_commit_idx = objs[i]._SyncObj__raftCommitIndex
assert new_commit_idx >= raft_commit_indices[i]
raft_commit_indices[i] = new_commit_idx
assert _checkSameLeader(objs)
assert _checkSameLeader2(objs)
for i in xrange(0, random.randint(0, 2)):
random.choice(objs).addValue(random.randint(0, 10))
newObjs = list(objs)
newObjs.pop(random.randint(0, len(newObjs) - 1))
doTicks(newObjs, random.random() * 0.3, interval=0.05)
for i in range(3):
new_commit_idx = objs[i]._SyncObj__raftCommitIndex
assert new_commit_idx >= raft_commit_indices[i]
raft_commit_indices[i] = new_commit_idx
assert _checkSameLeader(objs)
assert _checkSameLeader2(objs)
for i in xrange(0, random.randint(0, 2)):
random.choice(objs).addValue(random.randint(0, 10))
if not (o1.getCounter() == o2.getCounter() == o3.getCounter()):
print(time.time(), 'counters:', o1.getCounter(), o2.getCounter(), o3.getCounter())
# disable send delays to make test finish faster
for obj in objs:
obj._SyncObj__transport._send_random_sleep_duration = 0.00
st = time.time()
while not (o1.getCounter() == o2.getCounter() == o3.getCounter()):
doTicks(objs, 2.0, interval=0.05)
if time.time() - st > 30:
break
if not (o1.getCounter() == o2.getCounter() == o3.getCounter()):
o1._printStatus()
o2._printStatus()
o3._printStatus()
print('Logs same:', o1._SyncObj__raftLog == o2._SyncObj__raftLog == o3._SyncObj__raftLog)
print(time.time(), 'counters:', o1.getCounter(), o2.getCounter(), o3.getCounter())
raise AssertionError('Values not equal')
counter = o1.getCounter()
o1._destroy()
o2._destroy()
o3._destroy()
del o1
del o2
del o3
time.sleep(0.1)
o1 = TestObj(a[0], [a[1], a[2]], TEST_TYPE.RAND_1, journalFile=journalFiles[0])
o2 = TestObj(a[1], [a[2], a[0]], TEST_TYPE.RAND_1, journalFile=journalFiles[1])
o3 = TestObj(a[2], [a[0], a[1]], TEST_TYPE.RAND_1, journalFile=journalFiles[2])
objs = [o1, o2, o3]
st = time.time()
while not (o1.getCounter() == o2.getCounter() == o3.getCounter() == counter):
doTicks(objs, 2.0, interval=0.05)
if time.time() - st > 30:
break
if not (o1.getCounter() == o2.getCounter() == o3.getCounter() >= counter):
o1._printStatus()
o2._printStatus()
o3._printStatus()
print('Logs same:', o1._SyncObj__raftLog == o2._SyncObj__raftLog == o3._SyncObj__raftLog)
print(time.time(), 'counters:', o1.getCounter(), o2.getCounter(), o3.getCounter(), counter)
raise AssertionError('Values not equal')
removeFiles(journalFiles)
removeFiles([e + '.meta' for e in journalFiles])
# Ensure that raftLog after serialization is the same as in serialized data
def test_logCompactionRegressionTest1():
random.seed(42)
a = [getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1]])
o2 = TestObj(a[1], [a[0]])
objs = [o1, o2]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader()
o1._forceLogCompaction()
doTicks(objs, 0.5)
assert o1._SyncObj__forceLogCompaction == False
logAfterCompaction = o1._SyncObj__raftLog
o1._SyncObj__loadDumpFile(True)
logAfterDeserialize = o1._SyncObj__raftLog
assert logAfterCompaction == logAfterDeserialize
o1._destroy()
o2._destroy()
def test_logCompactionRegressionTest2():
dumpFiles = [getNextDumpFile(), getNextDumpFile(), getNextDumpFile()]
removeFiles(dumpFiles)
random.seed(12)
a = [getNextAddr(), getNextAddr(), getNextAddr()]
o1 = TestObj(a[0], [a[1], a[2]], dumpFile=dumpFiles[0])
o2 = TestObj(a[1], [a[2], a[0]], dumpFile=dumpFiles[1])
o3 = TestObj(a[2], [a[0], a[1]], dumpFile=dumpFiles[2])
objs = [o1, o2]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
objs = [o1, o2, o3]
o1.addValue(2)
o1.addValue(3)
doTicks(objs, 10, stopFunc=lambda: o3.getCounter() == 5)
o3._forceLogCompaction()
doTicks(objs, 0.5)
assert o1._getLeader().address in a
assert o1._getLeader() == o2._getLeader() == o3._getLeader()
o3._destroy()
objs = [o1, o2]
o1.addValue(2)
o1.addValue(3)
doTicks(objs, 0.5)
o1._forceLogCompaction()
o2._forceLogCompaction()
doTicks(objs, 0.5)
o3 = TestObj(a[2], [a[0], a[1]], dumpFile=dumpFiles[2])
objs = [o1, o2, o3]
doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())
assert o1._isReady()
assert o2._isReady()
assert o3._isReady()
o1._destroy()
o2._destroy()
o3._destroy()
removeFiles(dumpFiles)
def __checkParnerNodeExists(obj, nodeAddr, shouldExist=True):
nodeAddrSet = {node.address for node in obj._SyncObj__otherNodes}
return (
nodeAddr in nodeAddrSet) == shouldExist # either nodeAddr is in nodeAddrSet and shouldExist is True, or nodeAddr isn't in the set and shouldExist is False
def test_doChangeClusterUT1():
dumpFiles = [getNextDumpFile()]
removeFiles(dumpFiles)
baseAddr = getNextAddr()
oterAddr = getNextAddr()
o1 = TestObj(baseAddr, ['localhost:1235', oterAddr], dumpFile=dumpFiles[0], dynamicMembershipChange=True)
__checkParnerNodeExists(o1, 'localhost:1238', False)
__checkParnerNodeExists(o1, 'localhost:1239', False)
__checkParnerNodeExists(o1, 'localhost:1235', True)
noop = _bchr(_COMMAND_TYPE.NO_OP)
member = _bchr(_COMMAND_TYPE.MEMBERSHIP)
# Check regular configuration change - adding
o1._SyncObj__onMessageReceived(TCPNode('localhost:12345'), {
'type': 'append_entries',
'term': 1,
'prevLogIdx': 1,
'prevLogTerm': 0,
'commit_index': 2,
'entries': [(noop, 2, 1), (noop, 3, 1), (member + pickle.dumps(['add', 'localhost:1238']), 4, 1)]
})
__checkParnerNodeExists(o1, 'localhost:1238', True)
__checkParnerNodeExists(o1, 'localhost:1239', False)
# Check rollback adding
o1._SyncObj__onMessageReceived(TCPNode('localhost:1236'), {
'type': 'append_entries',
'term': 2,
'prevLogIdx': 2,
'prevLogTerm': 1,
'commit_index': 3,
'entries': [(noop, 3, 2), (member + pickle.dumps(['add', 'localhost:1239']), 4, 2)]
})
__checkParnerNodeExists(o1, 'localhost:1238', False)
__checkParnerNodeExists(o1, 'localhost:1239', True)
__checkParnerNodeExists(o1, oterAddr, True)
# Check regular configuration change - removing
o1._SyncObj__onMessageReceived(TCPNode('localhost:1236'), {
'type': 'append_entries',
'term': 2,
'prevLogIdx': 4,
'prevLogTerm': 2,
'commit_index': 4,
'entries': [(member + pickle.dumps(['rem', 'localhost:1235']), 5, 2)]
})
__checkParnerNodeExists(o1, 'localhost:1238', False)
__checkParnerNodeExists(o1, 'localhost:1239', True)
__checkParnerNodeExists(o1, 'localhost:1235', False)
# Check log compaction
o1._forceLogCompaction()
doTicks([o1], 0.5)
o1._destroy()
o2 = TestObj(oterAddr, [baseAddr, 'localhost:1236'], dumpFile='dump1.bin', dynamicMembershipChange=True)
doTicks([o2], 0.5)
__checkParnerNodeExists(o2, oterAddr, False)
__checkParnerNodeExists(o2, baseAddr, True)