-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtmtestnet.py
executable file
·2055 lines (1753 loc) · 75.3 KB
/
tmtestnet.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
"""
Test network deployment and management utility script for Tendermint
(https://tendermint.com).
"""
import argparse
import os
import os.path
import string
import sys
import re
import logging
import subprocess
import shlex
import time
import hashlib
from typing import OrderedDict as OrderedDictType, List, Dict, Set
from collections import namedtuple, OrderedDict
from copy import copy, deepcopy
import zipfile
import shutil
import pwd
import json
import datetime
import base64
import tempfile
import yaml
import colorlog
import requests
import toml
import pytz
# The default logger is pretty plain and boring
logger = logging.getLogger("")
def main():
default_aws_keypair_name = get_current_user()
default_ec2_private_key = os.path.expanduser("~/.ssh/ec2-user.pem")
parser = argparse.ArgumentParser(
description="Test network deployment and management utility script for Tendermint (https://tendermint.com)",
)
parser.add_argument(
"-c", "--config",
default="./tmtestnet.yaml",
help="The path to the configuration file to use (default: ./tmtestnet.yaml)"
)
parser.add_argument(
"--aws-keypair-name",
default=default_aws_keypair_name,
help="The name of the AWS keypair you need to use to interact with AWS (defaults to your current username)",
)
parser.add_argument(
"--ec2-private-key",
default=default_ec2_private_key,
help="The path to the private key that corresponds to your AWS keypair (default: ~/.ssh/ec2-user.pem)",
)
parser.add_argument(
"--fail-on-missing-envvars",
action="store_true",
default=False,
help="Causes the script to fail entirely if an environment variable used in the config file is not set (default behaviour will just insert an empty value)",
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
default=False,
help="Increase output verbosity",
)
subparsers = parser.add_subparsers(
required=True,
dest="command",
help="The tmtestnet command to execute",
)
# network
parser_network = subparsers.add_parser(
"network",
help="Network-related functionality",
)
subparsers_network = parser_network.add_subparsers(
required=True,
dest="subcommand",
help="The network-related command to execute",
)
# network deploy
parser_network_deploy = subparsers_network.add_parser(
"deploy",
help="Deploy a network according to its configuration file",
)
parser_network_deploy.add_argument(
"--keep-existing-tendermint-config",
action="store_true",
help="If this flag is specified and configuration is already present for a particular node group, it will not be overwritten/regenerated",
)
# network destroy
parser_network_destroy = subparsers_network.add_parser(
"destroy",
help="Destroy a deployed network",
)
parser_network_destroy.add_argument(
"--keep-monitoring",
action="store_true",
help="If this flag is set, any deployed monitoring services will be preserved, while all other services will be destroyed",
)
# network start
parser_network_start = subparsers_network.add_parser(
"start",
help="Start one or more node(s) or node group(s)",
)
parser_network_start.add_argument(
"node_or_group_ids",
metavar="node_or_group_id",
nargs="*",
help="Zero or more node or group IDs of network node(s) to start. If this is not supplied, all nodes will be started."
)
parser_network_start.add_argument(
"--no-fail-on-missing",
default=False,
action="store_true",
help="By default, this command fails if a group/node reference has not yet been deployed. Specifying this flag will just skip that group/node instead.",
)
# network stop
parser_network_stop = subparsers_network.add_parser(
"stop",
help="Stop one or more node(s) or node group(s)",
)
parser_network_stop.add_argument(
"node_or_group_ids",
metavar="node_or_group_id",
nargs="*",
help="Zero or more node or group IDs of network node(s) to stop. If this is not supplied, all nodes will be stopped."
)
parser_network_stop.add_argument(
"--no-fail-on-missing",
default=False,
action="store_true",
help="By default, this command fails if a group/node reference has not yet been deployed. Specifying this flag will just skip that group/node instead.",
)
# network fetch_logs
parser_network_fetch_logs = subparsers_network.add_parser(
"fetch_logs",
help="Fetch the logs for one or more node(s) or node group(s). " +
"Note that this stops any running service instances on the target " +
"nodes prior to fetching the logs, and then restarts those instances " +
"that were running previously.",
)
parser_network_fetch_logs.add_argument(
"output_path",
help="Where to store all desired nodes' logs."
)
parser_network_fetch_logs.add_argument(
"node_or_group_ids",
metavar="node_or_group_id",
nargs="*",
help="Zero or more node or group IDs of network node(s). If this is not supplied, all nodes' logs will be fetched."
)
# network reset
parser_network_reset = subparsers_network.add_parser(
"reset",
help="Reset the entire Tendermint network without redeploying VMs",
)
parser_network_reset.add_argument(
"--truncate-logs",
action="store_true",
help="If set, the network reset operation will truncate the Tendermint logs prior to starting Tendermint",
)
# network info
subparsers_network.add_parser(
"info",
help="Show information about a deployed network (e.g. hostnames and node IDs)",
)
# loadtest
parser_loadtest = subparsers.add_parser(
"loadtest",
help="Load testing-related functionality",
)
subparsers_loadtest = parser_loadtest.add_subparsers(
required=True,
dest="subcommand",
help="The load testing-related sub-command to execute",
)
# loadtest start <id>
parser_loadtest_start = subparsers_loadtest.add_parser("start", help="Start a specific load test")
parser_loadtest_start.add_argument(
"load_test_id",
help="The ID of the load test to start",
)
# loadtest stop <id>
parser_loadtest_stop = subparsers_loadtest.add_parser(
"stop",
help="Stop any currently running load tests",
)
parser_loadtest_stop.add_argument(
"load_test_id",
help="The ID of the load test to stop",
)
# loadtest destroy
subparsers_loadtest.add_parser(
"destroy",
help="Stop any currently running load tests",
)
args = parser.parse_args()
configure_logging(verbose=args.verbose)
# Allow for interpolation of environment variables within YAML files
configure_env_var_yaml_loading(fail_on_missing=args.fail_on_missing_envvars)
kwargs = {
"aws_keypair_name": os.environ.get("AWS_KEYPAIR_NAME", getattr(args, "aws_keypair_name", default_aws_keypair_name)),
"ec2_private_key_path": os.environ.get("EC2_PRIVATE_KEY", getattr(args, "ec2_private_key", default_ec2_private_key)),
"keep_existing_tendermint_config": getattr(args, "keep_existing_tendermint_config", False),
"output_path": getattr(args, "output_path", None),
"node_or_group_ids": getattr(args, "node_or_group_ids", []),
"fail_on_missing": not getattr(args, "no_fail_on_missing", False),
"load_test_id": getattr(args, "load_test_id", None),
"keep_monitoring": getattr(args, "keep_monitoring", False),
"truncate_logs": getattr(args, "truncate_logs", False),
}
sys.exit(tmtestnet(args.config, args.command, args.subcommand, **kwargs))
# -----------------------------------------------------------------------------
#
# Constants
#
# -----------------------------------------------------------------------------
SUPPORTED_REGIONS = {
"us_east_1",
"us_east_2",
"us_west_1",
"ap_northeast_2",
"ap_southeast_2",
"eu_central_1",
"eu_west_1",
}
ALLOWED_GROUP_NAME_CHARSET = set(string.ascii_letters + string.digits + "_-")
ENV_VAR_MATCHERS = [
re.compile(r"\$\{(?P<env_var_name>[^}^{]+)\}"),
re.compile(r"\$(?P<env_var_name>[A-Za-z0-9_]+)"),
]
VALID_BROADCAST_TX_METHODS = {"async", "sync", "commit"}
MONITOR_INPUT_VARS_TEMPLATE = """influxdb_password = \"%(influxdb_password)s\"
keypair_name = \"%(keypair_name)s\"
instance_type = \"%(instance_type)s\"
group = \"%(resource_group_id)s\"
volume_size = %(volume_size)d
"""
MONITOR_OUTPUT_VARS_TEMPLATE = """host:
public_dns: "{{ terraform_output.outputs.host.value.public_dns }}"
public_ip: "{{ terraform_output.outputs.host.value.public_ip }}"
influxdb_url: "{{ terraform_output.outputs.influxdb_url.value }}"
grafana_url: "{{ terraform_output.outputs.grafana_url.value }}"
"""
TENDERMINT_INPUT_VARS_TEMPLATE = """keypair_name = \"%(keypair_name)s\"
influxdb_url = \"%(influxdb_url)s\"
influxdb_password = \"%(influxdb_password)s\"
group = \"%(resource_group_id)s__%(node_group)s\"
instance_type = \"%(instance_type)s\"
volume_size = %(volume_size)d
nodes_useast1 = %(nodes_useast1)d
startid_useast1 = %(startid_useast1)d
nodes_uswest1 = %(nodes_uswest1)d
startid_uswest1 = %(startid_uswest1)d
nodes_useast2 = %(nodes_useast2)d
startid_useast2 = %(startid_useast2)d
nodes_apnortheast2 = %(nodes_apnortheast2)d
startid_apnortheast2 = %(startid_apnortheast2)d
nodes_apsoutheast2 = %(nodes_apsoutheast2)d
startid_apsoutheast2 = %(startid_apsoutheast2)d
nodes_eucentral1 = %(nodes_eucentral1)d
startid_eucentral1 = %(startid_eucentral1)d
nodes_euwest1 = %(nodes_euwest1)d
startid_euwest1 = %(startid_euwest1)d
"""
TENDERMINT_OUTPUT_VARS_TEMPLATE = """hosts:
{% for region, hosts in terraform_output.outputs.items() %}{% if hosts.value %}
{{ region }}:{% for node_id, node in hosts.value.items() %}
- {{ node_id }}:
public_dns: {{ node.public_dns }}
public_ip: {{ node.public_ip }}
{% endfor %}{% endif %}{% endfor %}
"""
TMBENCH_INPUT_VARS_TEMPLATE = """keypair_name = \"%(keypair_name)s\"
influxdb_url = \"%(influxdb_url)s\"
influxdb_password = \"%(influxdb_password)s\"
group = \"%(resource_group_id)s__%(load_test_id)s\"
tendermint_node_endpoints = \"%(tendermint_node_endpoints)s\"
tmbench_instances = %(instances)d
tmbench_time = %(test_time)d
tmbench_broadcast_tx_method = \"%(broadcast_tx_method)s\"
tmbench_connections = %(connections)d
tmbench_rate = %(tx_rate)d
tmbench_size = %(tx_size)d
"""
TMBENCH_OUTPUT_VARS_TEMPLATE = """hosts:
{% for host_id, host in terraform_output.outputs.hosts.value.items() %} {{ host_id }}:
public_dns: {{ host.public_dns }}
public_ip: {{ host.public_ip }}
{% endfor %}
"""
TMTESTNET_HOME = os.environ.get("TMTESTNET_HOME", "~/.tmtestnet")
# -----------------------------------------------------------------------------
#
# Core functionality
#
# -----------------------------------------------------------------------------
def tmtestnet(cfg_file, command, subcommand, **kwargs) -> int:
"""The primary programmatic interface to the tmtestnet tool. Allows the
tool to be imported from other Python code. Returns the intended exit code
from execution."""
try:
cfg = load_testnet_config(cfg_file)
except Exception as e:
logger.error("Failed to load configuration from file: %s", cfg_file)
logger.exception(e)
return 1
fn = None
if command == "network":
if subcommand == "deploy":
fn = network_deploy
elif subcommand == "destroy":
fn = network_destroy
elif subcommand == "start":
fn = network_start
elif subcommand == "stop":
fn = network_stop
elif subcommand == "fetch_logs":
fn = network_fetch_logs
elif subcommand == "reset":
fn = network_reset
elif subcommand == "info":
fn = network_info
elif command == "loadtest":
if subcommand == "start":
fn = loadtest_start
elif subcommand == "stop":
fn = loadtest_stop
elif subcommand == "destroy":
fn = loadtest_destroy
if fn is None:
logger.error("Command/sub-command not yet supported: %s %s", command, subcommand)
return 1
try:
fn(cfg, **kwargs)
except Exception as e:
logger.error("Failed to execute \"%s %s\" for configuration file: %s", command, subcommand, cfg_file)
logger.exception(e)
return 1
return 0
def network_deploy(
cfg: "TestnetConfig",
aws_keypair_name: str = None,
ec2_private_key_path: str = None,
keep_existing_tendermint_config: bool = False,
**kwargs,
):
"""Deploys the network according to the given configuration."""
if not aws_keypair_name:
raise Exception("Missing AWS keypair name")
if not os.path.exists(ec2_private_key_path):
raise Exception("Cannot find EC2 private key: %s" % ec2_private_key_path)
testnet_home = os.path.join(cfg.home, cfg.id)
# next up, optionally deploy monitoring
influxdb_url = cfg.monitoring.influxdb.url
monitoring_outputs = None
if cfg.monitoring.influxdb.enabled and cfg.monitoring.influxdb.deploy:
monitoring_outputs = terraform_deploy_monitoring(
os.path.join(testnet_home, "monitoring"),
aws_keypair_name,
cfg.id,
cfg.monitoring.influxdb.password,
cfg.monitoring.influxdb.instance_type,
cfg.monitoring.influxdb.volume_size,
)
influxdb_url = monitoring_outputs["influxdb_url"]
# deploy the Tendermint nodes
tendermint_outputs = OrderedDict()
for name, node_group_cfg in cfg.node_groups.items():
tendermint_outputs[name] = terraform_deploy_tendermint_node_group(
os.path.join(testnet_home, "tendermint", name),
aws_keypair_name,
cfg.id,
name,
influxdb_url,
cfg.monitoring.influxdb.password,
node_group_cfg.instance_type,
node_group_cfg.volume_size,
node_group_cfg.regions,
)
# reuse the network_reset functionality
network_reset(
cfg,
ec2_private_key_path=ec2_private_key_path,
keep_existing_tendermint_config=keep_existing_tendermint_config,
**kwargs,
)
network_info(cfg)
def network_destroy(cfg: "TestnetConfig", keep_monitoring: bool = False, **kwargs):
"""Destroys the network according to the given configuration."""
testnet_home = os.path.join(cfg.home, cfg.id)
# (1) destroy any load testing infrastructure that may still be running
loadtest_destroy(cfg, **kwargs)
# (2) destroy all Tendermint node groups
for name, _ in reversed(cfg.node_groups.items()):
terraform_destroy_tendermint_node_group(os.path.join(testnet_home, "tendermint", name))
# (3) optionally destroy the monitoring
if cfg.monitoring.influxdb.enabled and cfg.monitoring.influxdb.deploy:
if not keep_monitoring:
terraform_destroy_monitoring(os.path.join(testnet_home, "monitoring"))
else:
logger.info("Keeping monitoring services")
def network_state(
cfg: "TestnetConfig",
state: str,
node_or_group_ids: List[str] = None,
ec2_private_key_path: str = None,
fail_on_missing: bool = True,
fail_on_error: bool = True,
**kwargs,
):
if not os.path.exists(ec2_private_key_path):
raise Exception("Cannot find EC2 private key: %s" % ec2_private_key_path)
testnet_home = os.path.join(cfg.home, cfg.id)
target_refs = as_testnet_node_refs(
node_or_group_ids or [],
"from command line parameter(s)",
)
# if we have no targets, assume all groups are targets
if len(target_refs) == 0:
for node_group_name, _ in cfg.node_groups.items():
target_refs.append(TestnetNodeRef(group=node_group_name))
logger.info("Attempting to change state of network component(s): %s", testnet_node_refs_to_str(target_refs))
ansible_set_tendermint_nodes_state(
os.path.join(testnet_home, "tendermint"),
target_refs,
dict([(name, node_group.abci) for name, node_group in cfg.node_groups.items()]),
cfg.abci,
ec2_private_key_path,
state,
fail_on_missing=fail_on_missing,
fail_on_error=fail_on_error,
)
logger.info("Successfully changed state of network component(s)")
def network_start(cfg: "TestnetConfig", **kwargs):
network_state(cfg, "started", **kwargs)
def network_stop(cfg: "TestnetConfig", **kwargs):
network_state(cfg, "stopped", **kwargs)
def network_fetch_logs(
cfg: "TestnetConfig",
output_path=None,
node_or_group_ids=None,
ec2_private_key_path=None,
**kwargs):
if output_path is None or len(output_path) == 0:
raise Exception("fetch_logs command requires an output path parameter")
if not os.path.exists(ec2_private_key_path):
raise Exception("Cannot find EC2 private key: %s" % ec2_private_key_path)
testnet_home = os.path.join(cfg.home, cfg.id)
target_refs = as_testnet_node_refs(
node_or_group_ids or [],
"from command line parameter(s)",
)
# if we have no targets, assume all groups are targets
if len(target_refs) == 0:
for node_group_name, _ in cfg.node_groups.items():
target_refs.append(TestnetNodeRef(group=node_group_name))
logger.info("Fetching logs")
ansible_fetch_logs(
os.path.join(testnet_home, "tendermint"),
target_refs,
resolve_relative_path(output_path, os.getcwd()),
ec2_private_key_path,
)
def network_reset(
cfg: "TestnetConfig",
truncate_logs: bool = False,
ec2_private_key_path: str = None,
keep_existing_tendermint_config: bool = False,
**kwargs,
):
"""(Re)deploys Tendermint on all target nodes."""
if not os.path.exists(ec2_private_key_path):
raise Exception("Cannot find EC2 private key: %s" % ec2_private_key_path)
binaries_path = os.path.join(cfg.home, "bin")
binaries = ensure_tendermint_binaries(cfg.node_groups, binaries_path)
testnet_home = os.path.join(cfg.home, cfg.id)
# load the deployment outputs for all node groups and generate/load
# Tendermint configuration for each one
tendermint_outputs = OrderedDict()
for name, node_group_cfg in cfg.node_groups.items():
output_vars_filename = os.path.join(testnet_home, "tendermint", name, "output-vars.yaml")
tendermint_outputs[name] = load_yaml_config(output_vars_filename)
# generate the Tendermint network configuration
tendermint_config = OrderedDict()
for node_group_name, node_group_outputs in tendermint_outputs.items():
node_group_cfg = cfg.node_groups[node_group_name]
node_count = len(node_group_outputs["inventory_ordered"])
# if we're generating configuration
if node_group_cfg.generate_tendermint_config:
config_path = os.path.join(testnet_home, "tendermint", node_group_name, "config")
tendermint_config[node_group_name] = tendermint_generate_config(
config_path,
node_group_name,
node_group_cfg.config_template,
node_count if node_group_cfg.validators else 0,
0 if node_group_cfg.validators else node_count,
node_group_outputs["inventory_ordered"],
keep_existing_tendermint_config,
)
else:
# if we're just loading/modifying existing configuration
tendermint_config[node_group_name] = tendermint_load_nodes_config(
node_group_cfg.custom_tendermint_config_root,
node_count,
)
# reconcile the configuration across the nodes
tendermint_finalize_config(cfg, tendermint_config)
# deploy all node groups' configuration and start the relevant nodes
ansible_deploy_tendermint(
cfg,
tendermint_outputs,
binaries,
ec2_private_key_path,
truncate_logs=truncate_logs,
)
def network_info(cfg: "TestnetConfig", **kwargs):
"""Displays high-level information about a deployed network. Right now it
just shows the node IDs and their corresponding hostnames."""
testnet_home = os.path.join(cfg.home, cfg.id)
if not os.path.isdir(testnet_home):
raise Exception("Cannot find testnet home directory for \"%s\" - have you deployed the network yet?" % cfg.id)
influxdb_url, _ = get_influxdb_creds(cfg)
logger.info("InfluxDB: %s", influxdb_url)
grafana_url = get_grafana_url(cfg)
if grafana_url is not None:
logger.info("Grafana: %s", grafana_url)
target_refs = [TestnetNodeRef(group=node_group_name) for node_group_name, _ in cfg.node_groups.items()]
host_refs = node_to_host_refs(
os.path.join(testnet_home, "tendermint"),
target_refs,
fail_on_missing=False,
)
for host_ref in host_refs:
logger.info("Tendermint node: %s[%d] => %s", host_ref.group, host_ref.id, host_ref.hostname)
def loadtest_start(
cfg: "TestnetConfig",
aws_keypair_name: str = None,
load_test_id: str = None,
**kwargs,
):
if aws_keypair_name is None:
raise Exception("Missing keypair name")
if load_test_id is None or len(load_test_id) == 0:
raise Exception("Missing load test ID")
if load_test_id not in cfg.load_tests:
raise Exception("Unrecognized load test ID: %s" % load_test_id)
influxdb_url, influxdb_password = get_influxdb_creds(cfg)
if influxdb_url is None or len(influxdb_url) == 0 or influxdb_password is None or len(influxdb_password) == 0:
raise Exception("Cannot find InfluxDB configuration for monitoring load test")
logger.debug("Using InfluxDB URL: %s", influxdb_url)
logger.debug("Using InfluxDB password: %s", mask_password(influxdb_password))
testnet_home = os.path.join(cfg.home, cfg.id)
workdir = os.path.join(testnet_home, load_test_id)
if isinstance(cfg.load_tests[load_test_id], TestnetTMBenchConfig):
tmbench_cfg = cfg.load_tests[load_test_id]
target_refs = as_testnet_node_refs(
tmbench_cfg.targets or [],
"from command line parameters",
)
logger.debug("Target refs for load test: %s", target_refs)
targets = [t.hostname for t in node_to_host_refs(
os.path.join(testnet_home, "tendermint"),
target_refs,
fail_on_missing=True,
)]
if len(targets) == 0:
raise Exception("No target hosts for load test")
logger.debug("Using hosts for tm-bench load test: %s", targets)
terraform_deploy_tmbench(
workdir,
aws_keypair_name,
cfg.id,
load_test_id,
tmbench_cfg.client_nodes,
[("%s:26657" % t) for t in targets],
tmbench_cfg.time,
tmbench_cfg.broadcast_tx_method,
tmbench_cfg.connections,
tmbench_cfg.rate,
tmbench_cfg.size,
influxdb_url,
influxdb_password,
)
else:
raise Exception("Unsupported load test type: %s" % type(cfg.load_tests[load_test_id]))
def loadtest_stop(
cfg: "TestnetConfig",
load_test_id: str = None,
fail_on_missing: bool = True,
**kwargs,
):
if load_test_id is None or len(load_test_id) == 0:
raise Exception("Missing load test ID")
if load_test_id not in cfg.load_tests:
raise Exception("Unrecognized load test ID: %s" % load_test_id)
workdir = os.path.join(cfg.home, cfg.id, load_test_id)
if isinstance(cfg.load_tests[load_test_id], TestnetTMBenchConfig):
terraform_destroy_tmbench(
workdir,
load_test_id,
fail_on_missing=fail_on_missing,
)
def loadtest_destroy(cfg: "TestnetConfig", **kwargs):
"""Destroys all load testing-related resources."""
_kwargs = deepcopy(kwargs)
_kwargs["fail_on_missing"] = False
for load_test_id, _ in cfg.load_tests.items():
_kwargs["load_test_id"] = load_test_id
loadtest_stop(cfg, **_kwargs)
# -----------------------------------------------------------------------------
#
# Configuration
#
# -----------------------------------------------------------------------------
TestnetConfig = namedtuple("TestnetConfig",
["id", "monitoring", "abci", "node_groups", "load_tests", "home", "tendermint_binaries"],
defaults=[None, None, dict(), OrderedDict(), OrderedDict(), TMTESTNET_HOME, dict()],
)
TestnetMonitoringConfig = namedtuple("TestnetMonitoringConfig",
["signalfx", "influxdb"],
defaults=[None, None],
)
TestnetSignalFXConfig = namedtuple("TestnetSignalFXConfig",
["enabled", "api_token", "realm"],
defaults=[False, None, None],
)
TestnetInfluxDBConfig = namedtuple("TestnetInfluxDBConfig",
["enabled", "deploy", "region", "url", "password", "instance_type", "volume_size"],
defaults=[False, False, "us-east-1", None, None, "t3.small", 10],
)
TestnetNodeGroupConfig = namedtuple("TestnetNodeGroupConfig",
[
"binary", "abci", "validators", "in_genesis", "power", "service_state",
"config_template", "use_seeds", "persistent_peers", "regions",
"instance_type", "volume_size", "generate_tendermint_config",
"custom_tendermint_config_root",
],
defaults=[
None, None, True, True, 1000, "started",
None, [], [], OrderedDict(),
"t3.small", 8, True,
None,
],
)
TestnetABCIConfig = namedtuple("TestnetABCIConfig",
["deploy", "start", "stop"],
)
TestnetABCIPlaybookConfig = namedtuple("TestnetABCIPlaybookConfig",
["playbook", "extra_vars"],
defaults=[None, dict()],
)
TestnetTMBenchConfig = namedtuple("TestnetTMBenchConfig",
["client_nodes", "targets", "time", "broadcast_tx_method", "connections", "rate", "size"],
defaults=[1, [], 60, "async", 1, 1000, 100],
)
TestnetRegionConfig = namedtuple("TestnetRegionConfig",
["node_count", "start_id"],
defaults=[0, 0],
)
TestnetNodeRef = namedtuple("TestnetNodeRef",
["group", "id"],
defaults=[None, None],
)
TestnetHostRef = namedtuple("TestnetHostRef",
["group", "id", "hostname"],
defaults=[None, None, None],
)
TendermintNodeConfig = namedtuple("TendermintNodeConfig",
["config_path", "config", "priv_validator_key", "node_key", "peer_id"],
)
TendermintNodePrivValidatorKey = namedtuple("TendermintNodePrivValidatorKey",
["address", "pub_key", "priv_key"],
)
TendermintNodeKey = namedtuple("TendermintNodeKey",
["type", "value"],
)
AnsibleInventoryEntry = namedtuple("AnsibleInventoryEntry",
["alias", "ansible_host", "node_group", "node_id"],
defaults=[None, None, None, None],
)
LOAD_TEST_METHODS = {
"tm-bench": TestnetTMBenchConfig,
}
def load_testnet_config(filename: str) -> TestnetConfig:
"""Loads the configuration from the given file. Throws an exception if any
validation fails. On success, returns the configuration."""
# resolve the tmtestnet home folder path
tmtestnet_home = os.path.expanduser(TMTESTNET_HOME)
ensure_path_exists(tmtestnet_home)
with open(filename, "rt") as f:
cfg_dict = yaml.safe_load(f)
if "id" not in cfg_dict:
raise Exception("Missing required \"id\" parameter in configuration file")
config_base_path = os.path.dirname(os.path.abspath(filename))
abci_config = load_abci_configs(cfg_dict.get("abci", dict()), config_base_path)
return TestnetConfig(
id=cfg_dict["id"],
monitoring=load_monitoring_config(cfg_dict.get("monitoring", dict())),
abci=abci_config,
node_groups=load_node_groups_config(cfg_dict.get("node_groups", []), config_base_path, abci_config),
load_tests=load_load_tests_config(cfg_dict.get("load_tests", [])),
home=tmtestnet_home,
)
def load_monitoring_config(cfg_dict: Dict) -> TestnetMonitoringConfig:
return TestnetMonitoringConfig(
signalfx=TestnetSignalFXConfig(**cfg_dict.get("signalfx", dict())),
influxdb=load_influxdb_config(cfg_dict.get("influxdb", dict())),
)
def load_influxdb_config(cfg_dict: Dict) -> TestnetInfluxDBConfig:
if "enabled" not in cfg_dict or not cfg_dict["enabled"]:
return TestnetInfluxDBConfig()
if "password" not in cfg_dict or len(cfg_dict["password"]) == 0:
raise Exception("Missing InfluxDB password in monitoring configuration")
return TestnetInfluxDBConfig(**cfg_dict)
def load_abci_configs(cfg_dict: Dict, config_base_path: str) -> Dict:
# it's okay for this to be None, which disables any ABCI deployment
if cfg_dict is None or len(cfg_dict) == 0:
return dict()
result = dict()
for abci_config_name, abci_config in cfg_dict.items():
result[abci_config_name] = load_abci_config(
abci_config,
config_base_path,
"in \"abci\" configuration for \"%s\"" % abci_config_name,
)
return result
def load_abci_config(cfg_dict: Dict, config_base_path: str, ctx: str) -> TestnetABCIConfig:
if not isinstance(cfg_dict, dict) or len(cfg_dict) == 0:
raise Exception("Invalid ABCI configuration (%s)" % ctx)
required_fields = ["deploy", "start", "stop"]
_cfg_dict = dict()
for f in required_fields:
if f not in cfg_dict:
raise Exception("Missing required field \"%s\" in ABCI app configuration (%s)" % (f, ctx))
_cfg_dict[f] = load_abci_playbook_config(cfg_dict[f], config_base_path, "for %s stage, %s" % (f, ctx))
return TestnetABCIConfig(**_cfg_dict)
def load_abci_playbook_config(cfg_dict: Dict, config_base_path: str, ctx: str) -> TestnetABCIPlaybookConfig:
if not isinstance(cfg_dict, dict):
raise Exception("Invalid ABCI playbook configuration (%s)" % ctx)
if "playbook" not in cfg_dict:
raise Exception("Missing required field \"playbook\" in ABCI app configuration (%s)" % ctx)
_cfg_dict = deepcopy(cfg_dict)
_cfg_dict["playbook"] = resolve_relative_path(cfg_dict["playbook"], config_base_path)
if not os.path.isfile(_cfg_dict["playbook"]):
raise Exception("Cannot find Ansible playbook: %s (%s)" % (_cfg_dict["playbook"], ctx))
return TestnetABCIPlaybookConfig(**cfg_dict)
def load_node_groups_config(
cfg_list: List,
config_base_path: str,
abci_config: TestnetABCIConfig,
) -> OrderedDictType[str, TestnetNodeGroupConfig]:
return as_ordered_dict(
cfg_list,
"in \"node_groups\" configuration",
value_transform=load_node_group_config,
additional_params={"config_base_path": config_base_path, "abci_config": abci_config},
)
def load_load_tests_config(cfg_list: list) -> OrderedDictType:
return as_ordered_dict(
cfg_list,
"in \"load_tests\" configuration",
value_transform=load_load_test_config,
)
def load_node_group_config(
cfg_dict: dict,
ctx: str,
config_base_path: str = None,
abci_config: TestnetABCIConfig = None,
) -> TestnetNodeGroupConfig:
# don't modify the original config
_cfg_dict = deepcopy(cfg_dict)
_cfg_dict["regions"] = parse_regions_list(
cfg_dict.get("regions", None),
ctx,
)
_cfg_dict["use_seeds"] = as_testnet_node_refs(cfg_dict.get("use_seeds", dict()), "in \"use_seeds\", %s" % ctx)
_cfg_dict["persistent_peers"] = as_testnet_node_refs(cfg_dict.get("persistent_peers", dict()), "in \"persistent_peers\", %s" % ctx)
# if a configuration template's been specified
if "config_template" in cfg_dict and len(cfg_dict["config_template"]) > 0:
_cfg_dict["config_template"] = resolve_relative_path(cfg_dict["config_template"], config_base_path)
if not os.path.isfile(_cfg_dict["config_template"]):
raise Exception("Cannot find configuration template: %s (%s)" % (_cfg_dict["config_template"], ctx))
if "abci" in _cfg_dict and _cfg_dict["abci"] not in abci_config:
raise Exception("Unrecognized ABCI configuration: %s (%s)" % (_cfg_dict["abci"], ctx))
return TestnetNodeGroupConfig(**_cfg_dict)
def load_load_test_config(cfg_dict: dict, ctx: str):
method = cfg_dict.get("method", None)
if method not in LOAD_TEST_METHODS:
raise Exception("Invalid method (%s)" % ctx)
_cfg_dict = deepcopy(cfg_dict)
if "method" in _cfg_dict:
del _cfg_dict["method"]
return LOAD_TEST_METHODS[method](**_cfg_dict)
def load_tendermint_priv_validator_key(path: str) -> TendermintNodePrivValidatorKey:
with open(path, "rt") as f:
priv_val_key = json.load(f)
for field in ["address", "pub_key", "priv_key"]:
if field not in priv_val_key:
raise Exception("Missing field \"%s\" in %s" % (field, path))
cfg = {
"address": priv_val_key["address"],
"pub_key": load_key(priv_val_key["pub_key"], "pub_key in %s" % path),
"priv_key": load_key(priv_val_key["priv_key"], "priv_key in %s" % path),
}
return TendermintNodePrivValidatorKey(**cfg)
def load_key(d, ctx) -> TendermintNodeKey:
if not isinstance(d, dict):
raise Exception("Expected key to consist of key/value pairs (%s)" % ctx)
return TendermintNodeKey(**d)
# -----------------------------------------------------------------------------
#
# Network Management
#
# -----------------------------------------------------------------------------
def terraform_deploy_monitoring(
workdir,
keypair_name,
resource_group_id,
influxdb_password,
instance_type,
volume_size,
):
"""Deploys the Grafana/InfluxDB monitoring service on AWS with the given
parameters."""
ensure_path_exists(workdir)
output_vars_template = os.path.join(workdir, "terraform-output-vars.yaml.jinja2")
with open(output_vars_template, "wt") as f:
f.write(MONITOR_OUTPUT_VARS_TEMPLATE)
output_vars_file = os.path.join(workdir, "terraform-output-vars.yaml")
input_vars_file = os.path.join(workdir, "terraform-input-vars.tfvars")
extra_vars_file = os.path.join(workdir, "terraform-extra-vars.yaml")
with open(input_vars_file, "wt") as f:
f.write(MONITOR_INPUT_VARS_TEMPLATE % {
"keypair_name": keypair_name,
"resource_group_id": resource_group_id,
"influxdb_password": influxdb_password,
"instance_type": instance_type,
"volume_size": volume_size,
})
extra_vars = {
"state": "present",
"project_path": "./monitor",
"workspace": resource_group_id,
"input_vars_file": input_vars_file,
"output_vars_template": output_vars_template,
"output_vars_file": output_vars_file,
}
save_yaml_config(extra_vars_file, extra_vars)