-
Notifications
You must be signed in to change notification settings - Fork 1
/
manage
executable file
·1538 lines (1235 loc) · 59.8 KB
/
manage
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
## LICENSE: MIT
import hashlib
import importlib
import platform
import re
import shutil
import sys, os, json, logging, subprocess
import time
import urllib.parse
import io
from datetime import datetime, timezone
from pathlib import Path
from traceback import print_tb
from click import Command, command, Option
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
from _manager_lib import *
except ModuleNotFoundError as e:
logger.error(f"Exception importing _manager_lib: ModuleNotFoundError: {e}")
logger.error("Try running `pip install -r _manager_lib/requirements.txt`")
sys.exit(1)
tracker = StateTracker()
state = tracker.read()
from attrdict import AttrDict, AttrDefault
from colorama import init, Fore, Back, Style
init()
from blessed import Terminal
from dotenv import load_dotenv, dotenv_values
import dotenv
import cfn_tools
from time import sleep
from contextlib import suppress
from collections import defaultdict
from botocore.exceptions import ClientError
import boto3
from boto3.s3.transfer import S3Transfer
import click
def get_env(name, default):
return os.environ.get(name, default)
S3_DEV_BUCKET = get_env("S3_DEV_BUCKET", get_env("S3_CFN_SUPPORT_BUCKET", "flux-voting-app-dev-public-assets"))
STACK_TMPL = "./stack/flux-securevote-voting-stack.yaml"
TEST_STACK_NAME = "sv-testnet-stack"
TEST_SUBDOMAIN = get_env("TEST_SUBDOMAIN", "tnalpha2")
TEST_NAMEPREFIX = "sv-testnet"
OFFSET = ""
VOTING_DOMAIN = get_env("VOTING_DOMAIN", "flux.vote")
MAXS_SSH_KEY = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDCr1lcY0jTSmCARinvFJHelYGx2p+Ky0YxskSVj53ywYaLRN96w8WdN7rpCCosDQbd9KzvmKbBHHAlL8noEtARmxP4tKRvGGRyKawLLPm530CJRv4bSz03Iw2kz2V2fUWjA/RO2gNK9DCXTdDM67avv8oB/QvSobm1rSNKj6CcjTTJuQxGhJcXKrU/BZwugMIM3ELByyD6w8Jizm12JWGVgJTEIkgqgaNhmek2OLsw8+1hIC9EfhQunH9izzhEd2HoGYf3IJXlESnuRyhb7uOvOPysQDL8Hrt/Po6Wi3Lhlczy7q6wrlGQwO5/ORAfpYXGuk1lc3mTI/srgSgc38Vt'
def set_offset(offset):
global TEST_STACK_NAME, TEST_NAMEPREFIX, TEST_SUBDOMAIN, OFFSET
TEST_STACK_NAME += f'-{offset}'
TEST_SUBDOMAIN += f'-{offset}'
TEST_NAMEPREFIX += f'-{offset}'
OFFSET = offset
cfn = None
SILENT = False
def echo(*args, sep: str = " ", **kwargs):
if not SILENT:
click.echo(sep.join(args), **kwargs)
def must_run(cmd, silent=False):
logger.info("Running `%s`" % cmd)
out = subprocess.PIPE
err = subprocess.STDOUT
if silent:
# disable silent for now
out = subprocess.PIPE # open('tmp-cmd-stdout', 'w')
err = subprocess.STDOUT # open('tmp-cmd-stderr', 'w')
if type(cmd) is list:
to_run = cmd
elif type(cmd) is str:
to_run = cmd.split(' ')
else:
raise Exception("must_run only accepts str or list")
exit_code = subprocess.check_call(to_run, stdout=out, stderr=err)
logger.debug("Command `%s` exited w code %d" % (cmd, exit_code))
if exit_code != 0:
logger.error("Failed to run %s" % cmd)
logger.error(f"\nstdout:\n{out.readall()}")
logger.error(f"\n\nstderr:\n{err.readall()}")
try:
out.close()
err.close()
except:
pass
raise Exception("Failed to run required cmd: %s" % cmd)
class CmdRunner:
def __init__(self, cmd_runner=must_run):
self.cmds = []
self.cmd_runner = cmd_runner
def add(self, name, cmd):
self.cmds.append((name, cmd))
def run(self, cmd_runner=None):
cmd_runner = self.cmd_runner if cmd_runner is None else cmd_runner
for (n, cmd) in self.cmds:
logger.info("Running ({name}) as cmd:\n\t{cmd}\n".format(name=n, cmd=cmd))
cmd_runner(cmd)
def print_output(msg):
print("\n### RESULT ###\n\n{}".format(msg))
def pause():
print("Press any key to continue...", end="")
input()
#
# STATE OF DEPLOYMENTS
#
def state_readonly_write(env_name, full_state):
with open(f"_deployState_{env_name}_readonly.yaml", 'w') as f:
yaml.dump(full_state, f)
def state_readonly_read(env_name):
with open(f"_deployState_{env_name}_readonly.yaml", 'r') as f:
return AttrDict(yaml.load(f))
#
# CFN STACKS
#
def get_stack(stack_name):
ss = list(filter(lambda s: s['StackName'] == stack_name, cfn.list_stacks()['StackSummaries']))
if len(ss) > 0:
return ss[0]
return None
def get_stack_details(stack_name):
ss = list(filter(lambda s: s['StackName'] == stack_name, cfn.describe_stacks(StackName=stack_name)['Stacks']))
return None if len(ss) == 0 else ss[0]
def get_stack_resource(stack_name, logical_resource_name):
return cfn.describe_stack_resource(StackName=stack_name, LogicalResourceId=logical_resource_name)[
'StackResourceDetail']
def is_in_prog(stack_name):
s = get_stack(stack_name)
return s and 'IN_PROGRESS' in s['StackStatus']
def stack_exists(stack_name):
s = get_stack(stack_name)
return s and s['StackStatus'] != 'DELETE_COMPLETE'
def stack_failed(stack_name):
s = get_stack(stack_name)
return s and ('FAILED' in s['StackStatus'] or 'ROLLBACK' in s['StackStatus'])
def await_in_prog(stack_name, heading_prefix="AWAITING", fullscreen=True):
if is_in_prog(stack_name):
logger.info("Waiting for CFN deploy to complete before we trigger another.")
stream_cfn_events(stack_name, heading_prefix=heading_prefix, fullscreen=fullscreen)
logger.info("Previous deploy completed, performing deploy...")
def delete_stack(stack_name):
r = cfn.delete_stack(StackName=stack_name)
while stack_exists(stack_name):
time.sleep(0.1)
return r
def stack_del_if_necessary(stack_name):
if stack_exists(stack_name) and get_stack(stack_name)['StackStatus'] == 'ROLLBACK_COMPLETE':
logger.warning("Deleting {} as it's in ROLLBACK_COMPLETE".format(stack_name))
delete_stack(stack_name)
def create_stack(stack_name, obj_url, params_aws):
extra = {} if params_aws is None else {'Parameters': params_aws}
logger.info(f"Parameters and extra provided to cfn_create_stack: {json.dumps(extra, indent=2)}")
r = cfn.create_stack(
StackName=stack_name,
TemplateURL=obj_url,
Capabilities=['CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],
OnFailure="DELETE",
TimeoutInMinutes=20,
**extra
)
return r['StackId']
def update_stack(stack_name, obj_url, params_aws):
extra = {} if params_aws is None else {'Parameters': params_aws}
r = cfn.update_stack(
StackName=stack_name,
TemplateURL=obj_url,
Capabilities=['CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],
**extra
)
return r['StackId']
def create_or_update_stack(stack_name, obj_url, params):
if stack_exists(stack_name):
return update_stack(stack_name, obj_url, params)
else:
return create_stack(stack_name, obj_url, params)
def get_failed_msgs(stack_name):
evts_after = get_stack(stack_name).get('LastUpdatedTime', None)
try:
evts = cfn.describe_stack_events(StackName=stack_name)['StackEvents']
except:
logger.warning("***** Failed to get stack events! *****")
return []
evts_notable = list(
filter(lambda evt:
('FAILED' in evt['ResourceStatus'] or 'ROLLBACK_IN_PROGRESS' in evt['ResourceStatus']) and
(evts_after is None or evt['Timestamp'] > evts_after), evts))
evts_w_dupes = list([(evt['LogicalResourceId'], evt.get('ResourceStatusReason', evt)) for evt in evts_notable])
resources_done = set()
evts_final = []
for (r_id, reason) in evts_w_dupes:
if r_id not in resources_done:
evts_final.append((r_id, reason))
resources_done.add(r_id)
return evts_final
def cfn_outputs_to_dict(outputs):
return {d['OutputKey']: d['OutputValue'] for d in outputs}
def _cfn_stack_extract_resources_status(stack_name, recursive=False, update_start: datetime = None, parent=None,
max_old=5):
try:
evts = cfn.describe_stack_events(StackName=stack_name)['StackEvents']
except ClientError as e:
if "does not exist" in str(e):
return {}, [], update_start
elif "(Throttling)" in str(e):
sleep(0.3)
return _cfn_stack_extract_resources_status(stack_name=stack_name, recursive=recursive,
update_start=update_start, parent=parent)
else:
raise e
resources = AttrDict()
_res_ord = []
root = None
# find update_start first
if update_start is None:
for evt in evts:
r_name = evt['LogicalResourceId']
is_update_create_complete = evt['ResourceStatus'] in ['UPDATE_IN_PROGRESS', 'CREATE_IN_PROGRESS',
'UPDATE_COMPLETE', 'CREATE_COMPLETE']
if update_start is None and r_name == stack_name and is_update_create_complete:
# just break when we get to this point since we don't want anything afterwards.
update_start = evt['Timestamp']
break
n_old_counter = 0
for evt in evts:
r_name = evt['LogicalResourceId']
if r_name in resources or r_name in _res_ord: # resources we already track
continue
if r_name == stack_name:
if parent is None and root is None:
root = r_name
else:
continue
is_root = root == r_name
is_stack = evt['ResourceType'] == "AWS::CloudFormation::Stack"
is_old = update_start and evt['Timestamp'] < update_start
# t_plus_seconds = (evt['Timestamp'] - update_start).total_seconds()
seconds_ago = (datetime.now(timezone.utc) - evt['Timestamp']).total_seconds()
resources[r_name] = r = AttrDict({'status': evt['ResourceStatus'],
'ts': colors('dim_white')(
" (old)") if is_old else f"{seconds_ago:>3.0f}s ago",
'reason': evt.get('ResourceStatusReason', '<MISSING>'),
'type': evt.get('ResourceType', ""),
# we always want to show stacks, so they're never "old"
'is_old': is_old,
'parent': parent or "<Root>",
'evt': evt,
'depth': 0 if is_root else 1
})
# n_old = len(list(filter(lambda k: resources[k]['is_old'] and resources[k]['parent'] == stack_name, resources)))
if is_stack or not r['is_old'] or n_old_counter < max_old:
_res_ord.insert(0, r_name)
n_old_counter += 1 if r['is_old'] and not is_stack else 0
if recursive and is_stack and r_name != stack_name:
phys_id = evt['PhysicalResourceId']
if phys_id != "":
sub_name = phys_id.split('/')[1]
sub_res, sub_res_ord, _meh = _cfn_stack_extract_resources_status(
sub_name, recursive=recursive, update_start=update_start, parent=stack_name
)
_res_ord = [f"{r_name}/{n}" for n in sub_res_ord] + _res_ord
resources.update({f"{r_name}/{k}": AttrDict(v, depth=v['depth'] + 1) for k, v in sub_res.items()})
root_list_maybe = [] if root is None else [root]
used = set(root_list_maybe)
res_ord = [r for r in _res_ord if r not in used and (used.add(r) or True)] + root_list_maybe
return resources, res_ord, update_start
def get_c(cs, name: str) -> str:
ns = name.split('_')
color = ns[-1].upper()
return (Style.DIM if 'dim' in ns else '') \
+ (Style.BRIGHT if 'l' in ns else '') \
+ cs.__getattribute__(ns[-1].upper()) if color else ''
def colors(fore='reset', back='reset', prefix='', suffix=''):
def mk_colorful(msg):
return f"{get_c(Fore, fore)}{get_c(Back, back)}{prefix}{msg}{suffix}{Fore.RESET}{Back.RESET}{Style.RESET_ALL}"
return mk_colorful
def fmt_type(_r):
tys = _r['type'].split('::')[1:]
abbreviations = {
'CloudFormation': 'CFN',
'ApiGateway': 'ApiG',
'Route53': 'R53'
}
return '::'.join([abbreviations.get(tys[0], tys[0])] + tys[1:])
def fmt_r(r, _r):
rs = r.split('/')
rs[-1] = colors('l_blue')(rs[-1])
status_colors = {
"DELETE_FAILED": colors('black', 'red'),
"DELETE_IN_PROGRESS": colors('red', 'black'),
"DELETE_COMPLETE": colors('l_red', 'black'),
"CREATE_FAILED": colors('red'),
"CREATE_IN_PROGRESS": colors('l_green'),
"CREATE_COMPLETE": colors('dim_green'),
"UPDATE_FAILED": colors('red'),
"UPDATE_IN_PROGRESS": colors('l_green'),
"UPDATE_COMPLETE": colors('dim_green'),
"CLEANUP": colors('l_cyan'),
"IS_OLD": colors('dim_white'),
}
s = _r['status']
color_key = "IS_OLD" if _r['is_old'] else "CLEANUP" if "CLEANUP_IN_PROG" in s else s
status = status_colors.get(color_key, colors())(_r['status'])
return f"{status} - {'/'.join(rs)}"
def stream_cfn_events(stack_name, heading_prefix=None, skip_old=False, fullscreen=True):
# echo(json.dumps(_cfn_stack_extract_resources_status(stack_name, recursive=True), indent=2))
# return
_e = None
term = Terminal()
def clear_term():
if fullscreen:
print(term.home + term.clear)
def _run():
nonlocal _e
ansi_escape = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]')
def true_len(msg: str):
return len(ansi_escape.sub('', msg))
def addstr(y, x, msg):
if fullscreen:
with term.location(x, y):
print(msg)
else:
print((x, y), msg)
def gen_heading(update_start: datetime = None):
dt = update_start or datetime.utcnow()
heading = f'CFN Status ({stack_name})'
if heading_prefix:
heading = f'[{heading_prefix}] {heading}'
return f'{dt.strftime("%H:%M:%S")} {heading}'
def gen_progress_rotate(i):
return {0: "|", 1: "/", 2: "—", 3: "\\"}[i % 4]
addstr(0, 0, gen_heading())
loop_counter = 0
try:
while is_in_prog(stack_name):
loop_counter += 1
try:
resources, _resources_order, _update_start = _cfn_stack_extract_resources_status(stack_name,
recursive=True)
except ClientError as e:
if 'does not exist' in str(e):
echo(f"ClientError: {str(e)}")
break
raise e
clear_term()
stdscr_height, stdscr_width = term.height, term.width
addstr(0, 0,
gen_heading(_update_start)) # + f" | update started: {_update_start.strftime('%H:%M:%S')}")
l_num = 1
# max_depth = max([s.count('/') for s in _resources_order])
# last_depth = 0
_rs_ord = _resources_order[::-1]
_rs_with_neighbours = list(zip([None] + _rs_ord, _rs_ord, _rs_ord[1:] + [None]))
for (prev_r, r, next_r) in _rs_with_neighbours:
resources[r]['next'] = resources[next_r] if next_r else None
resources[r]['prev'] = resources[prev_r] if prev_r else None
# addstr(l_num, 0, f"{_rs_with_neighbours}")
# l_num += 1
for (prev_r, r, next_r) in _rs_with_neighbours:
if r not in resources:
addstr(l_num, 0, colors('red')(f"Not found: {r}"))
l_num += 1
else:
if l_num > stdscr_height - 2:
break
_r = resources[r]
if _r['is_old'] and skip_old:
continue
depth = _r['depth']
next_depth = _r.next['depth'] if _r.next else 0
prev_depth = _r.prev['depth'] if _r.prev else 0
start_char = "├" if prev_depth <= depth == next_depth or prev_depth > depth \
else "└" if next_depth == 0 \
else "└" if next_depth > depth \
else "└" if next_depth < depth \
else "┬"
end_char = "─" if "::Stack" not in _r['type'] \
else "┬" if prev_depth < depth \
else "├" if prev_depth == depth \
else "┬" if prev_depth > depth \
else "x"
# end_char = ("┬" if depth > 0 else "├") if "::Stack" in _r['type'] else " "
prefix = " " if _r['is_old'] else \
(gen_progress_rotate(loop_counter) if "IN_PROGRESS" in _r['status'] else "✔")
prefix += ("┆ " if depth > 1 else "") + " " * (depth - 2) + (
f"{start_char}─" if depth > 0 else "")
prefix += end_char
# prefix += colors('red')(f"[{rs_left:>2d}]")
the_str = f"{_r['ts']} {prefix}─ {fmt_r(r, _r)}"
type_msg = fmt_type(_r)
total_len = true_len(the_str + type_msg) + 2
if total_len <= stdscr_width:
the_str = the_str + ' ' + colors('dim_cyan')("." * (stdscr_width - total_len))
else:
max_len = (stdscr_width - 2 - true_len(type_msg))
the_str = filter(lambda s: true_len(s) <= max_len,
[the_str[:i] for i in range(len(the_str))][::-1]).__next__()
the_str += "…" + Fore.RESET + Back.RESET + Style.RESET_ALL
the_str += ' ' + colors('cyan')(fmt_type(_r))
addstr(l_num, 0, the_str) # [:max_str_len]
if "FAILED" in _r['status']:
l_num += 1
addstr(l_num, 0, f" {prefix} --> {_r['reason']}") # [:max_str_len]
last_depth = depth
l_num += 1
while l_num < stdscr_height - 1:
addstr(l_num, 0, " ")
l_num += 1
time.sleep(2)
addstr(1, 0,
f"----------- STACK ({stack_name}) COMPLETED! ----------- In Progress: {is_in_prog(stack_name)}")
time.sleep(1.5)
except Exception as e:
logger.error(f"Error in CFN stream: {e}, {repr(e)}")
sys.stderr.write(f"Error in CFN stream: {e}, {repr(e)}\n")
print_tb(e.__traceback__)
with open('__tmp_manage_log', 'a') as f:
f.write(f"Exception ({e}) at {time.time()} while streaming CFN events")
f.write('\n\n'.join([str(time.time()), str(e), repr(e), '']))
_e = e
raise e
if fullscreen:
with term.fullscreen():
_run()
# clear_term()
else:
_run()
if _e is not None:
echo(f"Error in stream events: {_e}, {repr(_e)}")
sys.stderr.write(f"Error in stream events: {_e}, {repr(_e)}")
cached_s3 = None
def get_s3_and_tfer():
global cached_s3
if cached_s3 is None:
cached_s3 = boto3.client('s3')
s3_tfer = S3Transfer(cached_s3)
return cached_s3, s3_tfer
def s3_upload(obj_key, public_read=True, bucket_name=S3_DEV_BUCKET, filepath: str = None, binary_data: bytes = None):
s3, s3_tfer = get_s3_and_tfer()
extra_args = {'ACL': 'public-read'} if public_read else {}
if filepath and binary_data:
raise Exception('cannot upload both a file and raw bytes - pick one')
if filepath:
s3_tfer.upload_file(filepath, bucket_name, obj_key, extra_args=extra_args)
elif binary_data:
s3.put_object(
Body=binary_data,
Bucket=bucket_name,
ContentMD5=hashlib.md5(binary_data).hexdigest(),
Key=obj_key,
**({'ACL': 'public-read'} if public_read else {})
)
obj_url = "{}/{}/{}".format(s3.meta.endpoint_url, bucket_name, obj_key)
return obj_url
def dict_to_cfn_params(params):
return [{'ParameterKey': k, 'ParameterValue': v} for k, v in params.items()]
def is_wsl():
return os.path.exists('/bin/wslpath')
def docker_lambda(cmd, extra_args=''):
wsl = is_wsl()
if wsl:
print("Detected WSL...")
os.system(f'docker build -t voteflux/voting-alpha-lambda:latest -f docker/Dockerfile ./docker')
mnt_dir = '$PWD' if not wsl else '$(wslpath -w $PWD)'
# sts = boto3.client('sts')
# session_token = sts.get_session_token(DurationSeconds=900)['Credentials']
# env_args = ' '.join([f"-e {k}={v}" for k,v in {
# 'AWS_ACCESS_KEY_ID': session_token['AccessKeyId'],
# 'AWS_SESSION_TOKEN': session_token['SessionToken'],
# 'AWS_SECRET_ACCESS_KEY': session_token['SecretAccessKey'],
# }.items()])
env_args = ''
return os.system(
f'docker run --rm -t -v "{mnt_dir}":/var/task '
f' {env_args} {extra_args} '
f' voteflux/voting-alpha-lambda:latest {cmd}')
@click.group()
@click.option("--debug/--no-debug", default=False)
@click.option("--offset", "-o", default="", type=click.STRING, help="use an offset for names to avoid conflicts.")
@click.option("--region", default="", type=click.STRING, help="specify an AWS region if need be")
def cli(debug, offset, region):
global cfn
if debug:
logger.setLevel(level=logging.DEBUG)
logger.debug("Debug mode enabled")
if offset:
set_offset(offset)
cfn_extras = {} if region == '' else {'region_name': region}
cfn = boto3.client('cloudformation', **cfn_extras)
s3 = boto3.client('s3', **cfn_extras)
py_targets_raw = ["cr", "members"]
py_targets = click.Choice(py_targets_raw + ['all'])
@cli.command(name='pip')
@click.argument('target', default="all",
type=py_targets) # , help="The target python app to install deps for; with 'all' being all targets")
@click.argument('pkgs', nargs=-1)
@click.option('--no-system', type=click.BOOL, is_flag=True, default=False,
help="do not include --system in pip install args")
@click.option('--pip-args', type=click.STRING, default='', help="extra args to pass to pip3 install")
@click.option('--use-docker', type=click.BOOL, is_flag=True, default=False,
help="use the lambda-build docker container to install dependencies (required on MacOS and Windows")
def pip(target, pkgs, no_system, pip_args, use_docker):
targets = py_targets_raw if target == "all" else [target]
_pkgs = list(pkgs)
target_paths = [{'cr': 'stack/cr', 'members': 'stack/app/members'}[target] for target in targets]
for target_path in target_paths:
_pip(target_path, _pkgs, no_system, pip_args, use_docker)
def _pip(target_path, pkgs, no_system, pip_args, use_docker):
curr_dir = os.getcwd()
if os.path.exists(target_path):
reqs_file = 'requirements.txt'
os.chdir(target_path)
try:
with open(reqs_file, 'r') as f:
reqs_old = f.read().split('\n')
except FileNotFoundError as e:
reqs_old = []
reqs = list(reqs_old)
for pkg in pkgs:
if pkg in reqs_old:
continue
reqs.append(pkg)
print('New requirements file lines:', reqs)
with open(reqs_file, 'w+') as f:
f.write('\n'.join(reqs))
print('Platform:', platform.system())
system = '' if no_system else '--system'
_cmd_outer = '{}'
if platform.system() == "Darwin":
_cmd_outer = 'docker run --rm -v "$PWD":/var/task lambci/lambda:build-python3.7 {}'
system = ''
# _cmd = _cmd_outer.format(...origcmd here...)
pip_cmd = f'pip3 install --target=deps -r {reqs_file} --upgrade {pip_args}'
# _ec = docker_lambda(pip_cmd)
_ec = os.system(pip_cmd)
if _ec != 0:
raise Exception("Failed to install packages")
print_output(f"Installed packages {pkgs} / {reqs} to {target_path}")
else:
raise Exception("Target of {} is unknown".format(target_path))
os.chdir(curr_dir)
@cli.group("tools")
def tools():
pass
@tools.command(name="node-up")
def tools_start_node():
must_run([
"bash",
"-c",
" docker build -f docker/Dockerfile.run-openethereum -t voteflux/voting-alpha-note:latest ./docker & "
" docker stop voting-alpha-node & "
" docker network create voting-alpha & "
" wait "
])
must_run("docker run --rm --name voting-alpha-node --network voting-alpha "
"-p 8545:8545 -p 8546:8546 "
"-d voteflux/voting-alpha-note:latest")
@tools.command(name="node-logs")
def tools_node_logs():
os.system("docker logs -f voting-alpha-node")
@cli.group("test")
def test():
pass
@test.command(name='chaincode')
def test_chaincode():
test_cmd = 'bash -c "cd stack/cr/chaincode; ls -al && tail cfnwrapper.py && tail lib.py; python3 test/test_mk_contract.py"'
docker_lambda(test_cmd)
@test.command(name='api-members')
def test_api_members():
logger.info(f"""Ensuring a node is running in a docker container is a requirement for this test.
If the tests fail to connect to a node try: './manage tools start-node'""")
sts = boto3.client('sts')
session_token = sts.get_session_token(DurationSeconds=(60 * 15))
aki = session_token['Credentials']['AccessKeyId']
sak = session_token['Credentials']['SecretAccessKey']
st = session_token['Credentials']['SessionToken']
try:
deployed_state = state_readonly_read("dev")
# 0x7B8068D32AA298158E838Fcd9a324B9810AE8333 is from 16/06/20
except Exception as e:
deployed_state = AttrDict(dict(outputs={"oApgVotingAlphaAddr": "0x7B8068D32AA298158E838Fcd9a324B9810AE8333"}))
extra_args = \
f' -e AWS_DEFAULT_REGION=ap-southeast-2 -e AWS_ACCESS_KEY_ID={aki} ' \
f' -e AWS_SECRET_ACCESS_KEY={sak} -e AWS_SESSION_TOKEN={st} ' \
f' -e pNamePrefix={os.environ.get("NAME_PREFIX")} ' \
f' -e pEthHost=http://voting-alpha-node:8545/ ' \
f' -e pApgVotingAlphaAddr={deployed_state.outputs.oApgVotingAlphaAddr} ' \
f' --user root --network voting-alpha '
test_cmd = 'bash -c "export ORIG_DIR=$PWD && ' \
' cd stack/app/members/api && ' \
' (which pytest >/dev/null || pip3 install pytest) && pytest"'
docker_lambda(test_cmd, extra_args=extra_args)
@cli.command(name="stream-cfn")
@click.argument('stack-name', type=click.STRING, default='')
def cmd_stream_cfn(stack_name):
if stack_name == '':
stack_name = TEST_STACK_NAME
stream_cfn_events(stack_name)
@cli.command(name='upload-func')
@click.argument('func-path')
@click.argument('func-name')
def upload_func(func_path, func_name):
if func_path[-3:] != ".py":
logger.error("Must target a python file to upload (whole dir gets uploaded tho)")
sys.exit(1)
root_dir = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.dirname(func_path)
os.chdir(dir_path)
if os.path.exists(f"{root_dir}/tmp-func.zip"):
must_run(f'rm -v {root_dir}/tmp-func.zip', silent=True)
must_run(f'zip -r {root_dir}/tmp-func.zip ./', silent=True)
os.chdir(root_dir)
with open('./tmp-func.zip', 'rb') as f:
zip_bytes = f.read()
# obj_key = f'./tmp-func-{int(time.time())}.zip'
# obj_url = s3_upload(obj_key, filepath=hashlib.sha256(zip_bytes).hexdigest() + ".zip")
awslam = boto3.client('lambda')
awslam.update_function_code(FunctionName=func_name, ZipFile=zip_bytes, Publish=True)
print_output(f"Updated function {func_name}")
@cli.command(name='deploy-ns')
@click.argument('stack-path')
@click.argument('stack-name')
@click.option('--params', default='',
help="(JSON Dict) Parameters to use. Default will use '{\"pOffset\": \"<value provided via --offset>\"}'")
def deploy_nestedstack(stack_path, stack_name, params):
TMP_TMPL_FILE = "./tmp-nestedstack-dev.yaml"
pkg_cmd = f"aws cloudformation package --template-file {stack_path} --s3-bucket {S3_DEV_BUCKET} --output-template-file {TMP_TMPL_FILE}"
must_run(pkg_cmd, silent=True)
filename = os.path.basename(stack_path)
obj_key = f'./ns-dev/tmp-{int(time.time())}-{filename}'
obj_url = s3_upload(obj_key, filepath=TMP_TMPL_FILE)
if not params:
prev_params = cfn.describe_stacks(StackName=stack_name)['Stacks'][0]['Parameters']
cfn_params = [{'ParameterKey': p['ParameterKey'], 'UsePreviousValue': True} for p in prev_params]
print(f"Using params: {json.dumps(cfn_params)}")
else:
json_params = json.loads(params)
if type(json_params) is list:
cfn_params = json_params
else:
cfn_params = dict_to_cfn_params(json_params if params else {'pOffset': OFFSET})
sid = create_or_update_stack(stack_name, obj_url, cfn_params)
logger.info(f"Stack SID: {sid}")
stream_cfn_events(stack_name, heading_prefix="DEPLOY-NS-DEV")
print_output(f"Stack deploy/create/update run for {stack_name} w sid: {sid}")
if stack_failed(stack_name):
msgs = ["{}: {}".format(a, b) for (a, b) in get_failed_msgs(stack_name)]
print_output("Deploy failed. Msgs: \n\n{}".format('\n'.join(msgs)))
@cli.command(name='deploy-macros')
@click.argument('stack-name', default='sv-macros')
def deploy_macros(stack_name):
TMP_TMPL_FILE = "tmp-macros.yaml"
pkg_cmd = f"aws cloudformation package --template-file ./stack/sv-macros.yaml --s3-bucket {S3_DEV_BUCKET} --output-template-file {TMP_TMPL_FILE}"
print("Package:", pkg_cmd)
must_run(pkg_cmd, silent=True)
obj_key = "sv-macros.yaml"
s3 = boto3.client('s3')
s3_tfer = S3Transfer(s3)
s3_tfer.upload_file(TMP_TMPL_FILE, S3_DEV_BUCKET, obj_key, extra_args={'ACL': 'public-read'})
obj_url = "{}/{}/{}".format(s3.meta.endpoint_url, S3_DEV_BUCKET, obj_key)
params_aws = []
if stack_exists(stack_name):
sid = update_stack(stack_name, obj_url, params_aws)
else:
sid = create_stack(stack_name, obj_url, params_aws)
stream_cfn_events(stack_name, heading_prefix="DEPLOY")
print_output(f"Deploy succeeded!")
@cli.command(name='deploy-cfn')
@click.argument('stack-path')
@click.argument('stack-name')
def deploy_macros(stack_path, stack_name):
TMP_TMPL_FILE = f"tmp-{stack_name}.yaml"
pkg_cmd = f"aws cloudformation package --template-file {stack_path} --s3-bucket {S3_DEV_BUCKET} --output-template-file {TMP_TMPL_FILE}"
print("Package:", pkg_cmd)
must_run(pkg_cmd, silent=True)
obj_key = "sv-macros.yaml"
s3 = boto3.client('s3')
s3_tfer = S3Transfer(s3)
s3_tfer.upload_file(TMP_TMPL_FILE, S3_DEV_BUCKET, obj_key, extra_args={'ACL': 'public-read'})
obj_url = "{}/{}/{}".format(s3.meta.endpoint_url, S3_DEV_BUCKET, obj_key)
params_aws = []
if stack_exists(stack_name):
sid = update_stack(stack_name, obj_url, params_aws)
else:
sid = create_stack(stack_name, obj_url, params_aws)
stream_cfn_events(stack_name, heading_prefix="DEPLOY")
print_output(f"Deploy succeeded!")
@cli.command(name='destroy')
@click.argument('stack-name', type=click.STRING, default='')
@click.option("--watch", default=False, type=click.BOOL, is_flag=True, help="Stream CFN events as it deploys.")
@click.pass_context
def destroy(ctx, watch, stack_name):
if stack_name == '':
stack_name = TEST_STACK_NAME
if watch:
stream_cfn_events(stack_name, heading_prefix="AWAIT")
del_resp = cfn.delete_stack(StackName=stack_name)
print(f"Del response: {del_resp}")
if watch:
stream_cfn_events(stack_name, heading_prefix="DELETE")
print_output(f"Deleted: {del_resp}")
def _step_to_parameters(step: int):
steps = [{'pCreateNodes': 'false'}, {'pCreateChaincodeStack': 'false'}, {'pCreateMembersApp': 'false'}, {}]
return steps[step]
@cli.command(name='deploy')
@click.argument('stack-name', type=click.STRING, default='')
@click.option("--deploy/--no-deploy", default=True, is_flag=True)
@click.option("--open-browser/--no-open-browser", default=False, is_flag=True)
@click.option("--del-packaged-tmpl/--no-del-packaged-tmpl", default=True, is_flag=True,
help="Remove tmp-stack.yaml after we're done generating + uploading it")
@click.option("--watch", default=False, type=click.BOOL, is_flag=True, help="Stream CFN events as it deploys.")
@click.option("--ssh-key", default=MAXS_SSH_KEY, type=click.STRING,
help="the ssh key with which to configure EC2 nodes.")
@click.option("--use-existing", default=False, is_flag=True, type=click.BOOL,
help="use tmp-stack.yaml if it exists instead of running aws cfn package")
@click.option("--use-last-uploaded", default=False, is_flag=True, type=click.BOOL,
help="do not package a new template, just redeploy the last one uploaded to S3.")
@click.option("--step", default=3, type=click.IntRange(0, 3),
help="Proceed only to step N of the stack deployment. The stack will _progressively_ deploy more and more resources as you increase step. The default is to deploy everything.")
@click.pass_context
def deploy(ctx, stack_name, deploy, open_browser, del_packaged_tmpl, watch, ssh_key, use_existing,
use_last_uploaded, step):
raise Exception('deprecated')
if stack_name == '':
stack_name = TEST_STACK_NAME
if deploy:
await_in_prog(stack_name)
TMP_TMPL_FILE = 'tmp-stack.yaml'
obj_key = "templates/" + STACK_TMPL.split('/')[-1]
s3 = boto3.client('s3')
s3_tfer = S3Transfer(s3)
if not use_last_uploaded:
if os.path.exists(TMP_TMPL_FILE) and use_existing:
print(f"{TMP_TMPL_FILE} exists - skipping `aws cloudformation package`; "
f"use --disable-use-existing to disable this and rm the old tmp file.")
else:
must_run("aws cloudformation package --template-file {} --s3-bucket {} --output-template-file {}"
.format(STACK_TMPL, S3_DEV_BUCKET, TMP_TMPL_FILE), silent=True)
# upload tmp file regardless
s3_tfer.upload_file(TMP_TMPL_FILE, S3_DEV_BUCKET, obj_key, extra_args={'ACL': 'public-read'})
obj_url = "{}/{}/{}".format(s3.meta.endpoint_url, S3_DEV_BUCKET, obj_key)
print(f"Template URL: {obj_url}")
params = {
'NamePrefix': TEST_NAMEPREFIX,
# 'HostedZone': 'Z2NVOFJHPZ9S2O',
'HostedZoneDomain': VOTING_DOMAIN,
'EC2InstanceType': 't2.small',
'NumberOfEthereumConsensusNodes': '1',
'NumberOfEthereumPublicNodes': '1',
'Subdomain': TEST_SUBDOMAIN,
'SSHKey': ssh_key,
'AdminEmail': '[email protected]',
'pDeployMacros': 'false',
# 'pDeployAcmAutovalidate': 'false',
# 'Nonce': str(int(time.time()))
}
params.update(**_step_to_parameters(step))
params_aws = dict_to_cfn_params(params)
cfn_console_create_url = "https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/new?stackName={stack_name}&templateURL={tmpl_url}".format(
obj_url, region=s3.meta.region_name, stack_name=stack_name, tmpl_url=urllib.parse.quote(obj_url, safe=''))
def gen_cfn_evt_url(sid):
return "https://ap-southeast-2.console.aws.amazon.com/cloudformation/home?region=ap-southeast-2#/stacks/{}/events".format(
urllib.parse.quote(sid, safe=''))
def gen_open_url_cmd(url):
return "cmd.exe /c start {}".format(url)
if deploy:
await_in_prog(stack_name)
stack_del_if_necessary(stack_name)
if stack_exists(stack_name):
sid = update_stack(stack_name, obj_url, params_aws)
else:
sid = create_stack(stack_name, obj_url, params_aws)
cfn_evt_url = gen_cfn_evt_url(sid)
if open_browser:
os.system(gen_open_url_cmd(cfn_evt_url))
if watch:
stream_cfn_events(stack_name, heading_prefix="DEPLOY")
_exists = stack_exists(stack_name)
if not _exists or stack_failed(stack_name):
if _exists:
msgs = ["{}: {}".format(a, b) for (a, b) in get_failed_msgs(stack_name)]
print_output("Deploy failed. Msgs: \n\n{}".format('\n'.join(msgs)))
else:
print_output("Deploy failed and is deleted.")
else:
print_output("Deploy Success! {}".format(cfn_evt_url))
if del_packaged_tmpl:
os.system("rm {}".format(TMP_TMPL_FILE))
deets = get_stack_details(stack_name)
print_output(f"Outputs: {json.dumps(cfn_outputs_to_dict(deets['Outputs']), indent=2)}")
else:
print_output("Initiated deploy of {}\n\nLink: {}".format(sid, cfn_evt_url))
if del_packaged_tmpl:
os.system("rm {}".format(TMP_TMPL_FILE))
else:
if open_browser:
_to_run = gen_open_url_cmd(cfn_console_create_url)
print("Opening CFN template via console. CMD: {}".format(_to_run))
os.system(_to_run)
print_output("""Uploaded {}
Launch via CloudFormation: {}""".format(obj_url, cfn_console_create_url))