-
Notifications
You must be signed in to change notification settings - Fork 2
/
run-test.py
executable file
·1763 lines (1480 loc) · 62.8 KB
/
run-test.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
#!/usr/bin/env python3
# vim: set ai et ts=4 sw=4:
import os
import sys
import subprocess
import argparse
import json
import time
import random
import traceback
import datetime
# Roles:
# jepsen-1: heavy
# jepsen-2: light
# jepsen-3: light
# jepsen-4: light
# jepsen-5: light
# jepsen-6: light
# jepsen-7: virtual (not-discovery)
# jepsen-8: virtual (not-discovery)
# jepsen-9: virtual (not-discovery)
# jepsen-10: virtual (not-discovery)
# jepsen-11: virtual (not-discovery)
# jepsen-12: pulsar
# jepsen-13: observer, PostgreSQL, Nginx
# jepsen-14: auth-service, PostgreSQL
START_PORT = 32000
VIRTUAL_START_RPC_PORT = 19000
VIRTUAL_START_ADMIN_PORT = 19100
INSPATH = "go/src/github.com/insolar/mainnet"
OLD_MEMBERS_FILE = ".artifacts/bench-members/members-from-start.txt"
MEMBERS_FILE = ".artifacts/bench-members/members.txt"
LIGHT_CHAIN_LIMIT = 5
PULSE_DELTA = 10
HEAVY = 1
LIGHTS = [2, 3, 4, 5, 6]
VIRTUALS = [7, 8, 9, 10, 11]
DISCOVERY_NODES = [HEAVY] + LIGHTS
NOT_DISCOVERY_NODES = VIRTUALS
NODES = DISCOVERY_NODES + NOT_DISCOVERY_NODES
PULSAR = 12
OBSERVER = 13
AUTHSERVICE = 14
ALL_PODS = NODES + [PULSAR, OBSERVER, AUTHSERVICE]
MIN_ROLES_VIRTUAL = 2
LOG_LEVEL = "Debug" # Info
NAMESPACE = "default"
SLOW_NETWORK_SPEED = '4mbps'
FAST_NETWORK_SPEED = '1000mbps'
SMALL_MTU = 1400
NORMAL_MTU = 1500
DEBUG = False
POD_NODES = dict() # is filled below
DEPENDENCIES = ['docker', 'kubectl', 'jq']
C = 5
R = 1
CURRENT_TEST_NAME = ""
K8S_YAML_TEMPLATE = """
kind: Service
apiVersion: v1
metadata:
name: {pod_name}
labels:
app: insolar-jepsen
spec:
type: NodePort
ports:
- port: 22
nodePort: {ssh_port}
selector:
name: {pod_name}
---
apiVersion: v1
kind: Pod
metadata:
name: {pod_name}
labels:
name: {pod_name}
app: insolar-jepsen
spec:
containers:
- name: {pod_name}
image: {image_name}
imagePullPolicy: {pull_policy}
securityContext:
capabilities:
add:
- NET_ADMIN
ports:
- containerPort: 22
---
"""
# A copy of K8S_YAML_TEMPLATE except `resources` section
K8S_OBSERVER_YAML_TEMPLATE = """
kind: Service
apiVersion: v1
metadata:
name: {pod_name}
labels:
app: insolar-jepsen
spec:
type: NodePort
ports:
- port: 22
nodePort: {ssh_port}
selector:
name: {pod_name}
---
apiVersion: v1
kind: Pod
metadata:
name: {pod_name}
labels:
name: {pod_name}
app: insolar-jepsen
spec:
containers:
- name: {pod_name}
image: {image_name}
imagePullPolicy: {pull_policy}
resources:
requests:
ephemeral-storage: "15Gi"
limits:
ephemeral-storage: "15Gi"
securityContext:
capabilities:
add:
- NET_ADMIN
ports:
- containerPort: 22
---
"""
PROXY_PORT_YAML_TEMPLATE = """
kind: Service
apiVersion: v1
metadata:
name: proxy-{pod_name}-{from_port}
labels:
app: insolar-jepsen
spec:
type: NodePort
ports:
- port: {from_port}
nodePort: {to_port}
selector:
name: {pod_name}
---
"""
K8S_AUTHSERVICE_YAML_TEMPLATE = """
apiVersion: v1
kind: Pod
metadata:
labels:
app: insolar-jepsen
component: auth-service
name: auth-service
spec:
containers:
- image: registry.insolar.io/auth-service:v1.0.0
command:
- /opt/app/auth-service
args:
- --config
- /auth-service.yaml
name: auth-service
volumeMounts:
- mountPath: /auth-service.yaml
name: auth-service-config
subPath: auth-service.yaml
workingDir: /
- env:
- name: POSTGRES_DB
value: "auth-service"
- name: POSTGRES_USER
value: "auth-service"
- name: POSTGRES_PASSWORD
value: "local_password"
image: postgres:12
name: postgres
volumeMounts:
- mountPath: /docker-entrypoint-initdb.d/auth-service.sql.gz
name: auth-service-db
subPath: auth-service.sql.gz
enableServiceLinks: false
restartPolicy: Always
volumes:
- configMap:
defaultMode: 420
name: auth-service
name: auth-service-config
- configMap:
name: auth-service-db
name: auth-service-db
---
apiVersion: v1
kind: Service
metadata:
name: auth-service
labels:
app: insolar-jepsen
component: auth-service
spec:
selector:
app: insolar-jepsen
component: auth-service
ports:
- protocol: TCP
port: 8080
targetPort: 8080
---
apiVersion: v1
data:
auth-service.yaml: |
host: http://localhost
listen: :8080
exptoken: 900
issuer: insolar-auth
secret: GLUEiXzHFLikRlpVbFWVmVY9SN8XuQLgjPKffDy2vno43RCIDOJXvD89mTdaG59G
admin:
login: auth-service
password: 9To9mhHs3FqAYCuO8
db:
url: postgres://auth-service:local_password@localhost:5432/auth-service?sslmode=disable
poolsize: 100
log:
level: debug
adapter: zerolog
formatter: text
outputtype: stderr
outputparallellimit:
outputparams:
buffersize: 0
llbuffersize: 0
kind: ConfigMap
metadata:
labels:
app: insolar-jepsen
component: auth-service
name: auth-service
---
apiVersion: v1
data:
kind: ConfigMap
binaryData:
auth-service.sql.gz: H4sICDElD18AA2R1bXAuc3FsALVXW2/aSBR+Dr9i1JckKqCZscfjCdoHGugWLTFtgG0rRUJzBatgs7bJZX/9HttQaG5N1C4SgvG5fec7Z86BVqvRaqGPaV7MMzv+NERGFlLJ3CKzWa1B1ijlPfhuDXJZutorXNssj9MEEdrG6KRnVSzrQ4u213MzJxi/JacH5uoOreez0u9LbRvj/gTlhSzsyibFrIhXNt0U6A+EO5VomepvD5/GZmlncTIrMpnkUhcQaJbbvAz4UFkv49K1TXRq4mQOguPp5H143NnFTozMzEyniUuzFWjM8iKDjxw006TUGvbPJ2ViGohZpvN2botKPZ6fHOdWZnoxW8ticdxEx/B2cpnb023shQX8bpPUGBUgsKXfSqdWuV0t03UphcfgtACsP+AGRLMV5CbnleWNzBIAV6tk6Q3krTdZXNyVaJ3r1Iwa6+RmCXxKtbT5Wmpbpn38mHQmtQb3EKNYpAbUFlauO2VTlIWN5MqebaHkHTS5W8Nx0n037HfQGLJbyTO03qhlrDtodJPY7AzJTbFo5Ta7jrWt2uv8st+d9GurrXJ76xGdNBC8YoNiyHxuMxSNJiiaDofNSqAzC61hZrJAZV2hWNBaN3GxqI7o3zSxteJmbV6maOzSvkgRCh0nUECZQYMBsGuZ3QHxJ9C4p7VGLpcFtHxhZX1ONqtZDKqyquY2oVq0lsDwQuaLQ/2yca8tUmm6tDLZJryQyby8STFELxrQRo1GdzjpXz5O3+hzVIpG6M0h628eL98sNtAt/+yqOO5/mvaj89cXcmd4D8zWfZVGd7zLvzqOJ93LCfo8mHxApHowiMDXRT+aoHdft4+iEboYRH93h9P+93P3y/583j3/0EfkeUK2GH4LL5WTHgB8OUE1sOf5+e72nrgdmzK3Q3yreF430++8eXun+8v3sMspY6ff7+KTbXjg61WMQ8xdRr3+++50OHktxzWMUTS8TyOq5eej4fQiKnMrB942CErsbXEtlyfHj1bm+Owss3O9hLt6ui9FD4Y+gs3wzChEve6k+4qqjD4+QH0Sm+bBtGseDLTmwcxq1mOpWc2e5o8Tp7mfMs3tbGnu5skpen85uoBlBxuw0yBHFFPcwrxFGCLszCdnBLcDH3vcf4vxQ6nH20FIMA1L6VV0lNk1gJdFmh1dXd1yxrCymFgirEedY4ELGHFeQMOQEWuPBPU9r9QUjAc+oRjUPYO1JIERhAtOtfaNh7nAAebKiVB6mmjFma809SWYUyw9gSWWGkuqnKacgyUJseKWh8r3BXYWGwYvZ2XAqNCCYSmo4dzDSlGDFVMeDZ3BATOUhz4XgQmZskYT31ee8Q2jyhCrnNQe1iENcOAL4wEtTAR+4KiCRK3hkgkMSXAuNeHW84zxQ0mIZ0LK/EAT4QWYuADMjHBOBFYQbIw0RFufOEc4V8SDkFJ5VjjhKV9y4sJAW22BORqCIdMEmJCUu5JWwwOltBM+syWvXClMgtBnRlIMWKUURFBtFAmoF2IbUl9oF4Sac0o9A/tdmtAxLZUJLfCHQy0MCTWGOB4xOFTYo8xBsZSCpCRhmIEDbUPuS8MNFN7XnqDCGOaU8JWR3MfMOgeelDQBQKTEOCDA+M4PLbCufEE968AdDaBAYUAIc0fFEWHCDykPBG9ctZ+6ZE8Mvl+4Z4dTL753Hcp2xwFwB6QegnrRkoDx8nJEj/6UfGYgNRFpoiLb2NP7q2E3N3YG62/2boftfBSNJ5fdQfT7pmq91Hu9A98/hEYfLwcX3cuv6K/+14rgp1fZwdf/DfU+xGPA7wH4KfbY3M52ye5H8Q73IOr1v7x6JVdWT3iGVO6vh+l4EP2JVJFZi072mg+gbuK9w2pT/BrKaTSANt+CfeD7ZzgrpQOIT/0Hhb89q3WZUhX6PzzYYW+wDgAA
metadata:
labels:
app: insolar-jepsen
component: auth-service
name: auth-service-db
"""
# to make `sed` work properly, otherwise it failes with an error:
# sed: RE error: illegal byte sequence
os.environ["LC_ALL"] = "C"
os.environ["LANG"] = "C"
os.environ["LC_CTYPE"] = "C"
def logto(fname, index=""):
# `tee` is used to see recent logs in tmux. please keep it!
return "2>&1 | tee /dev/tty | gzip --stdout > " + fname + "_`date +%s`.log.gz"
def start_test(msg):
global CURRENT_TEST_NAME
CURRENT_TEST_NAME = msg
print("##teamcity[testStarted name='%s']" % CURRENT_TEST_NAME)
def fail_test(failure_message):
global CURRENT_TEST_NAME
notify("Test failed")
msg = failure_message \
.replace("|", "||").replace("'", "|'") \
.replace("\n", "|n").replace("\r", "|r") \
.replace("[", "|[").replace("]", "|]")
print("##teamcity[testFailed name='%s' message='%s']" %
(CURRENT_TEST_NAME, msg))
trace = "".join(traceback.format_stack()[:-1]) \
.replace("|", "||").replace("'", "|'") \
.replace("\n", "|n").replace("\r", "|r") \
.replace("[", "|[").replace("]", "|]")
print("##teamcity[testFailed name='%s' message='%s']" %
(CURRENT_TEST_NAME, trace))
print_k8s_events()
stop_test()
info("Stops nodes after fail")
for node in NODES:
kill(node, "insolard")
kill(PULSAR, "pulsard")
wait_until_insolar_is_down()
sys.exit(1)
def print_k8s_events():
# Disable many screens of k8s-specific output to stdout
# print(get_output(k8s() + " get pods -o wide -l app=insolar-jepsen "))
# print(get_output(k8s() + " describe pods -l app=insolar-jepsen"))
# print(get_output(k8s() + " get events"))
pass
def stop_test():
global CURRENT_TEST_NAME
print("##teamcity[testFinished name='%s']" % CURRENT_TEST_NAME)
def info(msg):
print(str(datetime.datetime.now())+" INFO: "+str(msg))
def wait(nsec):
info("waiting "+str(nsec)+" second"+("s" if nsec > 1 else "")+"...")
time.sleep(nsec)
def notify(message):
run("""(which osascript 2>/dev/null 1>&2) && osascript -e 'display notification " """ +
message + """ " with title "Jepsen"' || true""")
def check(condition, failure_message):
if not condition:
fail_test(failure_message)
def check_alive(condition):
if not condition:
out = ssh_output(1, 'cd '+INSPATH+' && ' +
'timelimit -s9 -t10 ' + # timeout: 10 seconds
'./bin/pulsewatcher --single --config ./pulsewatcher.yaml')
msg = "Insolar must be alive, but its not:\n" + out
fail_test(msg)
def check_down(condition):
if not condition:
fail_test("Insolar must be down, but its not")
def check_benchmark(condition, out):
if not condition:
fail_test("Benchmark return error: \n" + out)
def debug(msg):
if not DEBUG:
return
print(" "+msg)
def run(cmd):
debug(cmd)
proc = subprocess.run(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if proc.returncode != 0:
print("Command `%s` returned non-zero status: %d, output: %s" %
(cmd, proc.returncode, str(proc.stdout)))
info("Stops nodes after fail")
for node in NODES:
kill(node, "insolard")
kill(PULSAR, "pulsard")
wait_until_insolar_is_down()
sys.exit(1)
def get_output(cmd):
debug(cmd)
proc = subprocess.run(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.returncode != 0:
print("Command `%s` returned non-zero status: %d, output: %s, error: %s" %
(cmd, proc.returncode, str(proc.stdout), str(proc.stderr)))
out = proc.stdout
data = out.decode('utf-8').strip()
return data
def ssh_user_host(pod):
return "gopher@"+POD_NODES['jepsen-'+str(pod)]
def ssh(pod, cmd):
run("ssh -tt -o 'StrictHostKeyChecking no' -i ./base-image/id_rsa -p" +
str(START_PORT + pod)+" "+ssh_user_host(pod) +
""" "bash -c 'source ./.bash_profile ; """ +
cmd + """ '" """)
def ssh_output(pod, cmd):
return get_output("ssh -tt -o 'StrictHostKeyChecking no' -i ./base-image/id_rsa -p" +
str(START_PORT + pod)+" "+ssh_user_host(pod) +
""" "bash -c 'source ./.bash_profile ; """ +
cmd + """ '" """)
def scp_to(pod, lpath, rpath, flags='', ignore_errors=False):
run("scp -o 'StrictHostKeyChecking no' -i ./base-image/id_rsa -P" +
str(START_PORT + pod)+" "+flags+" " + lpath + " "+ssh_user_host(pod) +
":"+rpath + (" || true" if ignore_errors else ""))
def scp_from(pod, rpath, lpath, flags=''):
run("scp -o 'StrictHostKeyChecking no' -i ./base-image/id_rsa -P" +
str(START_PORT + pod)+" " + flags + " "+ssh_user_host(pod) +
":"+rpath+" "+lpath)
def k8s():
return "kubectl --namespace "+NAMESPACE+" "
def k8s_gen_yaml(fname, image_name, pull_policy):
with open(fname, "w") as f:
to_port = 31008
for i in ALL_PODS:
pod_name = "jepsen-" + str(i)
ssh_port = str(32000 + i)
descr = K8S_YAML_TEMPLATE.format(
pod_name=pod_name,
ssh_port=ssh_port,
image_name=image_name,
pull_policy=pull_policy
)
# Proxy PostgreSQL and Nginx ports on OBSERVER
if i == OBSERVER:
# Rewrite `descr`
descr = K8S_OBSERVER_YAML_TEMPLATE.format(
pod_name=pod_name,
ssh_port=ssh_port,
image_name=image_name,
pull_policy=pull_policy
)
for from_port in [5432, 80]:
descr += PROXY_PORT_YAML_TEMPLATE.format(
pod_name=pod_name,
from_port=from_port,
to_port=to_port,
)
to_port += 1
if i == AUTHSERVICE:
descr = K8S_AUTHSERVICE_YAML_TEMPLATE.format(
pull_policy=pull_policy
)
f.write(descr)
def k8s_get_pod_ips():
"""
Returns a map PodName -> PodIP
"""
data = get_output(k8s()+"get pods -l app=insolar-jepsen -o=json | " +
"""jq -r '.items[] | .metadata.name + " " + .status.podIP'""")
res = {}
for kv in data.split("\n"):
[k, v] = kv.split(' ')
res[k] = v
return res
def k8s_get_pod_nodes():
"""
Returns a map PodName -> NodeName
"""
data = get_output(k8s() + "get pods -l app=insolar-jepsen -o=json | " +
"""jq -r '.items[] | .metadata.name + " " + .spec.nodeName'""")
res = {}
for kv in data.split("\n"):
[k, v] = kv.split(' ')
if v == "docker-for-desktop": # Docker Desktop 2.0, k8s 1.10, docker 18.09
v = "localhost"
if v == "docker-desktop": # Docker Desktop 2.1, k8s 1.14, docker 19.03
v = "localhost"
res[k] = v
return res
def k8s_stop_pods_if_running():
info("stopping pods and services with `insolar-jepsen` label")
run(k8s()+"delete services -l app=insolar-jepsen 2>/dev/null || true")
run(k8s()+"delete pods -l app=insolar-jepsen 2>/dev/null || true")
for n in range(60):
data = get_output(k8s()+"get pods -l app=insolar-jepsen -o=json | " +
"jq -r '.items[].metadata.name' | wc -l")
info("running pods: "+data)
if data == "0":
break
wait(3)
else:
fail_test("k8s_stop_pods_if_running no attempts left")
wait(20) # make sure services and everything else are gone as well
def k8s_start_pods(fname):
info("starting pods")
run(k8s()+"apply -f "+fname)
for n in range(60):
data = get_output(k8s()+"get pods -l app=insolar-jepsen -o=json | " +
"jq -r '.items[].status.phase' | grep Running | wc -l")
info("running pods: "+data)
if data == str(len(ALL_PODS)):
break
wait(3)
else:
fail_test("k8s_start_pods no attempts left")
def set_network_speed(pod, speed):
ssh(pod, 'sudo tc qdisc del dev eth0 root || true')
ssh(pod, 'sudo tc qdisc add dev eth0 root handle 1: tbf rate ' +
speed+' latency 1ms burst 1540')
ssh(pod, 'sudo tc qdisc del dev eth0 ingress || true')
ssh(pod, 'sudo tc qdisc add dev eth0 ingress')
ssh(pod, 'sudo tc filter add dev eth0 root protocol ip u32 match u32 0 0 police rate ' +
speed+' burst 10k drop flowid :1')
ssh(pod, 'sudo tc filter add dev eth0 parent ffff: protocol ip u32 match u32 0 0 police rate ' +
speed+' burst 10k drop flowid :1')
def set_mtu(pod, mtu):
ssh(pod, 'sudo ifconfig eth0 mtu '+str(mtu))
def create_simple_netsplit(pod, pod_ips):
"""
Simulates simplest netsplit: one node is cut-off from the rest of the network
"""
for current_pod in ALL_PODS:
if current_pod == pod:
continue
current_ip = pod_ips['jepsen-'+str(current_pod)]
ssh(pod, 'sudo iptables -A INPUT -s '+current_ip+' -j DROP && ' +
'sudo iptables -A OUTPUT -d '+current_ip+' -j DROP')
def fix_simple_netsplit(pod, pod_ips):
"""
Rolls back an effect of create_simple_netsplit()
"""
for current_pod in ALL_PODS:
if current_pod == pod:
continue
current_ip = pod_ips['jepsen-'+str(current_pod)]
ssh(pod, 'sudo iptables -D INPUT -s '+current_ip+' -j DROP && ' +
'sudo iptables -D OUTPUT -d '+current_ip+' -j DROP')
def old_node_is_down(status):
if 'PulseNumber' in status and \
'Error' in status:
return status['PulseNumber'] == -1 and \
status['Error'] != ''
else:
return 0
def new_node_is_down(status):
if 'pulseNumber' in status:
return status['pulseNumber'] == -1
else:
return 0
def node_is_down(status):
return old_node_is_down(status) or new_node_is_down(status)
def old_node_status_is_ok(status, nodes_online):
if 'NetworkState' in status and \
'ActiveListSize' in status and \
'WorkingListSize' in status and \
'Error' in status:
return status['NetworkState'] == 'CompleteNetworkState' and \
status['ActiveListSize'] == nodes_online and \
status['WorkingListSize'] == nodes_online and \
status['Error'] == ''
else:
return 0
def new_node_status_is_ok(status, nodes_online):
if 'networkState' in status and \
'activeListSize' in status and \
'workingListSize' in status:
return status['networkState'] == 'CompleteNetworkState' and \
status['activeListSize'] == nodes_online and \
status['workingListSize'] == nodes_online
else:
return 0
def node_status_is_ok(status, nodes_online):
return old_node_status_is_ok(status, nodes_online) or new_node_status_is_ok(status, nodes_online)
def network_status_is_ok(network_status, nodes_online):
online_list = [network_status[nodeIndex-1]
for nodeIndex in nodes_online if not node_is_down(network_status[nodeIndex-1])]
# make sure an expected number of nodes is online
if len(online_list) < len(nodes_online):
info("[NetworkStatus] error - {} nodes online, {} expected".format(len(online_list), nodes_online))
return False
# make sure all PulseNumber's are equal
pn = set(s['PulseNumber'] for s in online_list)
if len(pn) != 1:
info("[NetworkStatus] PulseNumber's differ: " +
str([s['PulseNumber'] for s in online_list]))
return False
else:
info("[NetworkStatus] PulseNumber is " + str(pn))
# check node statuses
for nodeIndex in nodes_online:
node_status = network_status[nodeIndex-1]
if node_is_down(node_status):
continue
if not node_status_is_ok(node_status, len(nodes_online)):
info("[NetworkStatus] Node status is not OK: "+str(node_status) +
" (nodes online: "+str(nodes_online)+")")
return False
info("[NetworkStatus] Everything is OK")
return True
def wait_until_current_pulse_will_be_finalized():
pulse = current_pulse()
finalized_pulse = get_finalized_pulse_from_exporter()
while pulse != finalized_pulse:
info("Current pulse: "+str(pulse) +
", finalized pulse: "+str(finalized_pulse))
wait(1)
finalized_pulse = get_finalized_pulse_from_exporter()
def get_finalized_pulse_from_exporter():
token = str(json.loads(ssh_output(HEAVY, 'curl -s "replicator:replicator@auth-service:8080/auth/token"'))["access_token"])
cmd = 'grpcurl -import-path /home/gopher/go/src -import-path ./go/src/github.com/insolar/mainnet/vendor' +\
' -proto /home/gopher/go/src/github.com/insolar/mainnet/pulse_exporter.proto' +\
' -H \\"authorization: Bearer {}\\"'.format(token) +\
""" -plaintext JEPSEN-1:5678 exporter.PulseExporter.TopSyncPulse"""
out = ssh_output(HEAVY, cmd)
pulse = json.loads(out)["PulseNumber"]
info("exporter said: " + str(pulse))
return pulse
def benchmark(pod_ips, api_pod=VIRTUALS[0], ssh_pod=1, extra_args="", c=C, r=R, timeout=30, background=False):
virtual_pod_name = 'jepsen-'+str(api_pod)
port = VIRTUAL_START_RPC_PORT + api_pod
out = ""
try:
out = ssh_output(ssh_pod, 'cd '+INSPATH+' && ' +
("tmux new-session -d \\\"" if background else "") +
'timelimit -s9 -t'+str(timeout)+' ' +
'./bin/benchmark -c ' + str(c) + ' -r ' + str(r) + ' -a http://'+pod_ips[virtual_pod_name] +
':'+str(port) + '/admin-api/rpc ' +
' -p http://'+pod_ips[virtual_pod_name]+':'+str(port + 100)+'/api/rpc ' +
'-k=./scripts/insolard/configs/ ' + extra_args +
' ' + (logto('background-bench-'+str(int(time.time()))) + "\\\"" if background else ""))
except Exception as e:
print(e)
out = "ssh_output() throwed an exception (non-zero return code): "+str(e)
return out
def migrate_member(pod_ips, api_pod=VIRTUALS[0], ssh_pod=1, members_file=MEMBERS_FILE, c=C*2, timeout=90):
ok, migration_out = run_benchmark(
pod_ips, api_pod, ssh_pod, c=c, extra_args='-t=migration -s --members-file=' + members_file, timeout=timeout
)
check_benchmark(ok, migration_out)
ok, migration_out = run_benchmark(
pod_ips, api_pod, ssh_pod, c=c, withoutBalanceCheck=True, extra_args='-t=migration -m --members-file=' + members_file, timeout=timeout,
)
check_benchmark(ok, migration_out)
ok, out = check_balance_at_benchmark(
pod_ips, extra_args='-m --members-file=' + members_file + ' --check-all-balance', timeout=timeout
)
check_benchmark(ok, out)
def run_benchmark(pod_ips, api_pod=VIRTUALS[0], ssh_pod=1, withoutBalanceCheck=False, extra_args="", c=C, r=R, timeout=90, background=False):
if withoutBalanceCheck:
extra_args = extra_args + ' -b'
out = benchmark(pod_ips, api_pod, ssh_pod,
extra_args, c, r, timeout, background)
if background:
return True, out
if 'Successes: '+str(c*r) in out:
if withoutBalanceCheck or 'Total balance successfully matched' in out:
return True, out
return False, out
def check_balance_at_benchmark(pod_ips, api_pod=VIRTUALS[0], ssh_pod=1, extra_args="", c=C, r=R, timeout=30, background=False):
out = benchmark(pod_ips, api_pod, ssh_pod,
extra_args, c, r, timeout, background)
if background:
return True, out
if 'Balances for members from file was successfully checked' in out:
return True, out
return False, out
def pulsewatcher_output(ssh_pod=1):
return ssh_output(ssh_pod, 'cd '+INSPATH+' && ' +
'timelimit -s9 -t10 ' + # timeout: 10 seconds
'./bin/pulsewatcher --single --json --config ./pulsewatcher.yaml')
def current_pulse(node_index=HEAVY, ssh_pod=1):
network_status = json.loads(pulsewatcher_output(ssh_pod))
pn = network_status[node_index]['PulseNumber']
return pn
def insolar_is_alive(pod_ips, virtual_pod, nodes_online, ssh_pod=1, skip_benchmark=False):
out = pulsewatcher_output(ssh_pod)
network_status = json.loads(out)
if not network_status_is_ok(network_status, nodes_online):
info('insolar_is_alive() is false, out = "'+out+'"')
return False
if skip_benchmark:
return True
ok, out = run_benchmark(pod_ips, virtual_pod, ssh_pod,
extra_args=" -t=createMember")
if ok:
return True
else:
info("Benchmark run wasn't success: " + out)
return False
def insolar_is_alive_on_pod(pod):
out = ssh_output(pod, 'pidof insolard || true')
return out != ''
def wait_until_insolar_is_alive(pod_ips, nodes_online, virtual_pod=-1, nattempts=20, pause_sec=5, step="", skip_benchmark=False):
min_nalive = 3
nalive = 0
if virtual_pod == -1:
virtual_pod = VIRTUALS[0]
for attempt in range(1, nattempts+1):
wait(pause_sec)
try:
alive = insolar_is_alive(
pod_ips, virtual_pod, nodes_online, skip_benchmark=skip_benchmark)
if alive:
nalive += 1
info("[Step: "+step+"] Alive check passed "+str(nalive)+"/" +
str(min_nalive)+" (attempt "+str(attempt)+" of "+str(nattempts)+")")
except Exception as e:
print(e)
info("[Step: "+step+"] Insolar is not alive yet (attempt " +
str(attempt)+" of "+str(nattempts)+")")
nalive = 0
if nalive >= min_nalive:
break
return nalive >= min_nalive
def start_insolar_net(nodes, pod_ips, extra_args_insolard="", step="", skip_benchmark=False, use_postgresql=False):
alive = False
for attempt in range(1, 4):
info("Insolar net not alive, kill all for clear start")
for node in NODES:
kill(node, "insolard")
info("Starting insolar net (attempt %s)" % str(attempt))
for pod in nodes:
start_insolard(pod, use_postgresql=use_postgresql, extra_args=extra_args_insolard)
info("Check insolar net alive")
alive = wait_until_insolar_is_alive(
pod_ips, NODES, step=step, skip_benchmark=skip_benchmark)
if alive:
break
check_alive(alive)
def wait_until_insolar_is_down(nattempts=10, pause_sec=5):
all_down = False
for pod in NODES:
for i in range(0, nattempts):
if not insolar_is_alive_on_pod(pod):
all_down = True
break
info('Insolard is not terminated yet at pod#'+str(pod))
all_down = False
wait(pause_sec)
return all_down
def run_genesis(use_postgresql=False):
if use_postgresql:
database = "postgres"
else:
database = "badger"
ssh(HEAVY, "cd " + INSPATH + " && " +
"INSOLAR_LOG_LEVEL="+LOG_LEVEL+" ./bin/insolard heavy --config " +
"./scripts/insolard/"+str(HEAVY) +
"/insolar_"+str(HEAVY)+".yaml --heavy-genesis scripts/insolard/configs/heavy_genesis.json " +
"--database=" + database + " " +
"--genesis-only")
def start_insolard(pod, use_postgresql=False, extra_args=""):
role = "unknown"
if pod == HEAVY:
if use_postgresql:
start_heavy(pod, extra_args, "postgres")
else:
start_heavy(pod, extra_args, "badger")
return
elif pod in VIRTUALS:
role = "virtual"
elif pod in LIGHTS:
role = "light"
ssh(pod, "cd " + INSPATH + " && tmux new-session -d "+extra_args+" " +
"""\\"INSOLAR_LOG_LEVEL="""+LOG_LEVEL+""" ./bin/insolard """+role+""" --config """ +
"./scripts/insolard/"+str(pod) +
"/insolar_"+str(pod)+".yaml " +
logto("insolard")+"""; bash\\" """)
def start_heavy(pod, extra_args="", database=""):
ssh(pod, "cd " + INSPATH + " && tmux new-session -d "+extra_args+" " +
"""\\"INSOLAR_LOG_LEVEL="""+LOG_LEVEL+""" ./bin/insolard heavy --config """ +
"./scripts/insolard/"+str(pod) +
"/insolar_"+str(pod)+".yaml --heavy-genesis=scripts/insolard/configs/heavy_genesis.json " +
"--database=" + database + " " +
logto("insolard")+"""; bash\\" """)
def start_pulsard(extra_args=""):
ssh(PULSAR, "cd " + INSPATH + """ && tmux new-session -d """ +
extra_args+""" \\"./bin/pulsard -c pulsar.yaml """ +
logto("pulsar") + """; bash\\" """)
def kill(pod, proc_name):
ssh(pod, "killall -s 9 "+proc_name+" || true")
def restore_heavy_from_backup(heavy_pod):
info("Restoring heavy from backup at pod#..."+str(heavy_pod))
kill(heavy_pod, "backupmanager")
ssh(heavy_pod, "cd "+INSPATH+" && " +
"backupmanager prepare_backup -d ./heavy_backup/ && " +
"rm -r data && cp -r heavy_backup data")
def check_ssh_is_up_on_pods():
try:
for pod in NODES + [PULSAR, OBSERVER]:
out = ssh_output(pod, "echo 1")
if out != "1":
return False
except Exception as e:
print(e)
return False
return True
def wait_until_ssh_is_up_on_pods():
info("Waiting until SSH daemons are up on all nodes")
is_up = False
nchecks = 10
for check in range(1, nchecks+1):
is_up = check_ssh_is_up_on_pods()
if is_up:
break
info("SSH daemons are not up yet (attempt " +
str(check)+" of "+str(nchecks)+")")
wait(1)
assert(is_up)
info("SSH daemons are up!")
def prepare_configs():
info("Building configs based on provided templates")
info("Replace old config-templates with new")
run("rm -r /tmp/insolar-jepsen-configs || true")
run("cp -r ./config-templates /tmp/insolar-jepsen-configs")
pod_ips = k8s_get_pod_ips()
# sorting is needed to replace JEPSEN-10 before JEPSEN-1
for k in sorted(pod_ips.keys(), reverse=True):
run("find /tmp/insolar-jepsen-configs -type f -print | grep -v .bak " +
"| xargs sed -i.bak 's/"+k.upper()+"/"+pod_ips[k]+"/g'")
def deploy_pulsar():
info("starting pulsar (before anything else, otherwise consensus will not be reached)")
ssh(PULSAR, "mkdir -p "+INSPATH+"/scripts/insolard/configs/")
scp_to(PULSAR, "/tmp/insolar-jepsen-configs/pulsar.yaml",
INSPATH+"/pulsar.yaml")
start_pulsard(extra_args="-s pulsard")
def deploy_postgresql(pod, service_name):
info("deploying PostgreSQL @ pod "+str(pod))
# The base64-encoded string is: listen_addresses = '*'
# I got tired to fight with escaping quotes in bash...
ssh(pod, """sudo bash -c \\"echo bGlzdGVuX2FkZHJlc3NlcyA9ICcqJwo= | base64 -d >> /etc/postgresql/11/main/postgresql.conf && echo host all all 0.0.0.0/0 md5 >> /etc/postgresql/11/main/pg_hba.conf && service postgresql start\\" """)
ssh(pod, """echo -e \\"CREATE DATABASE """+service_name+"""; CREATE USER """+service_name+""" WITH PASSWORD \\x27"""+service_name+"""\\x27; GRANT ALL ON DATABASE """+service_name+""" TO """+service_name+""";\\" | sudo -u postgres psql""")
def deploy_observer_deps():
deploy_postgresql(OBSERVER, 'observer')
info("starting Nginx @ pod "+str(OBSERVER))
scp_to(OBSERVER, "/tmp/insolar-jepsen-configs/nginx_default.conf",
"/tmp/nginx_default.conf")
ssh(OBSERVER, """sudo bash -c \\"cat /tmp/nginx_default.conf > /etc/nginx/sites-enabled/default && service nginx start\\" """)
def deploy_observer(path, keep_database=False, public=False):
cfgs_list = ["observer", "observerapi", "stats-collector", "migrate"]
build_mode = "all"
if public:
build_mode = "all-node"
cfgs_list = ["observer", "observerapi_public", "migrate"]
info("deploying observer @ pod "+str(OBSERVER) +
", using source code from "+path+"/observer")
# cleanup after previous deploy, if there was one
ssh(OBSERVER, "tmux kill-session -t observer || true")
ssh(OBSERVER, "tmux kill-session -t observerapi || true")
ssh(OBSERVER, "tmux kill-session -t stats-collector || true")
ssh(OBSERVER, "rm -rf "+INSPATH+"/../observer || true")
# ignore_errors=True is used because Observer's dependencies have symbolic links pointing to non-existing files
scp_to(OBSERVER, path + "/observer", INSPATH +
"/../observer", flags="-r", ignore_errors=True)
ssh(OBSERVER, "cd %s/../observer && GO111MODULE=on make %s && mkdir -p .artifacts" % (INSPATH, build_mode))
for cqw in cfgs_list:
scp_to(OBSERVER, f"/tmp/insolar-jepsen-configs/{cqw}.yaml",
INSPATH+f"/../observer/.artifacts/{cqw}.yaml")
if not keep_database:
info("purging observer's database...")
ssh(OBSERVER, """echo -e \\"DROP DATABASE observer; CREATE DATABASE observer;\\" | sudo -u postgres psql""")
ssh(OBSERVER, "cd "+INSPATH +
"/../observer && GO111MODULE=on make migrate-init")
ssh(OBSERVER, "cd " + INSPATH +
"/../observer && GO111MODULE=on make migrate")
# run observer
ssh(OBSERVER, """tmux new-session -d -s observer \\"cd """+INSPATH +
"""/../observer && ./bin/observer --config=./.artifacts/observer.yaml 2>&1 | tee -a observer.log; bash\\" """)
# run observer-api
if public:
ssh(OBSERVER, """tmux new-session -d -s observerapi \\"cd """+INSPATH +
"""/../observer && ./bin/api --config=./.artifacts/observerapi_public.yaml 2>&1 | tee -a observerapi.log; bash\\" """)
else:
ssh(OBSERVER, """tmux new-session -d -s observerapi \\"cd """ + INSPATH +
"""/../observer && ./bin/api --config=./.artifacts/observerapi.yaml 2>&1 | tee -a observerapi.log; bash\\" """)
if not public:
# run stats-collector every 10 seconds
ssh(OBSERVER, "tmux new-session -d -s stats-collector " +
"""\\"cd """+INSPATH+"""/../observer && while true; do ./bin/stats-collector --config=./.artifacts/stats-collector.yaml 2>&1 | tee -a stats-collector.log; sleep 10; done""" +
"""; bash\\" """)
def gen_certs():
ssh(HEAVY, "cd "+INSPATH+" && ./bin/insolar bootstrap --config scripts/insolard/bootstrap.yaml " +
"--certificates-out-dir scripts/insolard/certs")
run("mkdir -p /tmp/insolar-jepsen-configs/certs/ || true")
run("mkdir -p /tmp/insolar-jepsen-configs/reusekeys/not_discovery/ || true")
run("mkdir -p /tmp/insolar-jepsen-configs/reusekeys/discovery/ || true")
scp_from(HEAVY, INSPATH+"/scripts/insolard/certs/*",
"/tmp/insolar-jepsen-configs/certs/")
scp_from(HEAVY, INSPATH+"/scripts/insolard/reusekeys/not_discovery/*",
"/tmp/insolar-jepsen-configs/reusekeys/not_discovery/")
scp_from(HEAVY, INSPATH+"/scripts/insolard/reusekeys/discovery/*",
"/tmp/insolar-jepsen-configs/reusekeys/discovery/")
for pod in LIGHTS+VIRTUALS:
scp_to(pod, "/tmp/insolar-jepsen-configs/certs/*",
INSPATH+"/scripts/insolard/certs/")