forked from aptos-labs/aptos-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforge.py
2363 lines (1997 loc) · 68.1 KB
/
forge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import atexit
import json
import os
from pprint import pprint
import pwd
import random
import re
import resource
import subprocess
import sys
import tempfile
import textwrap
import time
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Sequence,
Set,
Tuple,
TypedDict,
Union,
)
from urllib.parse import ParseResult, urlunparse, urlencode
@dataclass
class RunResult:
exit_code: int
output: bytes
def unwrap(self) -> bytes:
if not self.succeeded():
raise Exception(self.output.decode("utf-8"))
return self.output
def succeeded(self) -> bool:
return self.exit_code == 0
class Shell:
def run(self, command: Sequence[str], stream_output: bool = False) -> RunResult:
raise NotImplementedError()
async def gen_run(
self, command: Sequence[str], stream_output: bool = False
) -> RunResult:
raise NotImplementedError()
@dataclass
class LocalShell(Shell):
verbose: bool = False
def run(self, command: Sequence[str], stream_output: bool = False) -> RunResult:
# Write to a temp file, stream to stdout
tmpname = tempfile.mkstemp()[1]
with open(tmpname, "wb") as writer, open(tmpname, "rb") as reader:
if self.verbose:
print(f"+ {' '.join(command)}")
process = subprocess.Popen(command, stdout=writer, stderr=writer)
output = b""
while process.poll() is None:
chunk = reader.read()
output += chunk
if stream_output:
sys.stdout.write(chunk.decode("utf-8"))
time.sleep(0.1)
output += reader.read()
return RunResult(process.returncode, output)
async def gen_run(
self, command: Sequence[str], stream_output: bool = False
) -> RunResult:
# Write to a temp file, stream to stdout
tmpname = tempfile.mkstemp()[1]
with open(tmpname, "wb") as writer, open(tmpname, "rb") as reader:
if self.verbose:
print(f"+ {' '.join(command)}")
try:
process = await asyncio.create_subprocess_exec(
command[0], *command[1:], stdout=writer, stderr=writer
)
except Exception as e:
raise Exception(f"Failed running {command}") from e
output = b""
while True:
wait_task = asyncio.create_task(process.wait())
finished, running = await asyncio.wait({wait_task}, timeout=1)
assert bool(finished) ^ bool(
running
), "Cannot have both finished and running"
if finished:
break
chunk = reader.read()
output += chunk
if stream_output:
sys.stdout.write(chunk.decode("utf-8"))
await asyncio.sleep(1)
output += reader.read()
exit_code = process.returncode
assert exit_code is not None, "Process must have exited"
return RunResult(exit_code, output)
def install_dependency(dependency: str) -> None:
print(f"{dependency} is not currently installed")
answer = os.getenv("FORGE_INSTALL_DEPENDENCIES") or os.getenv("CI")
if not answer:
answer = input("Would you like to install it now? (y/n) ").strip().lower()
if answer in ("y", "yes", "yeet", "yessir", "si", "true"):
shell = LocalShell(True)
shell.run(["pip3", "install", dependency], stream_output=True).unwrap()
else:
print(f"Please install click (pip install {dependency}) and try again")
exit(1)
try:
import click
except ImportError:
install_dependency("click")
import click
try:
import psutil
except ImportError:
install_dependency("psutil")
import psutil
def get_current_user() -> str:
return pwd.getpwuid(os.getuid())[0]
@click.group()
def main() -> None:
# Check that the current directory is the root of the repository.
if not os.path.exists(".git"):
print("This script must be run from the root of the repository.")
raise SystemExit(1)
def envoption(name: str, default: Optional[Any] = None) -> Any:
return click.option(
f"--{name.lower().replace('_', '-')}",
default=lambda: os.getenv(name, default() if callable(default) else default),
show_default=True,
)
class Filesystem:
def write(self, filename: str, contents: bytes) -> None:
raise NotImplementedError()
def read(self, filename: str) -> bytes:
raise NotImplementedError()
def mkstemp(self) -> str:
raise NotImplementedError()
def rlimit(self, resource_type: int, soft: int, hard: int) -> None:
raise NotImplementedError()
def unlink(self, filename: str) -> None:
raise NotImplementedError()
class LocalFilesystem(Filesystem):
def write(self, filename: str, contents: bytes) -> None:
with open(filename, "wb") as f:
f.write(contents)
def read(self, filename: str) -> bytes:
with open(filename, "rb") as f:
return f.read()
def mkstemp(self) -> str:
return tempfile.mkstemp()[1]
def rlimit(self, resource_type: int, soft: int, hard: int) -> None:
resource.setrlimit(resource_type, (soft, hard))
def unlink(self, filename: str) -> None:
os.unlink(filename)
# o11y resources
GRAFANA_BASE_URL = (
"https://o11y.aptosdev.com/grafana/d/overview/overview?orgId=1&refresh=10s&"
"var-Datasource=VictoriaMetrics%20Global"
)
class Process:
def name(self) -> str:
raise NotImplementedError()
def ppid(self) -> int:
raise NotImplementedError()
class Processes:
def processes(self) -> Generator[Process, None, None]:
raise NotImplementedError()
def get_pid(self) -> int:
raise NotImplementedError()
def atexit(self, callback: Callable[[], None]) -> None:
raise NotImplementedError()
def user(self) -> str:
raise NotImplementedError()
@dataclass
class SystemProcess(Process):
process: psutil.Process
def name(self) -> str:
return self.process.name()
def ppid(self) -> int:
return self.process.ppid()
class SystemProcesses(Processes):
def processes(self) -> Generator[Process, None, None]:
for process in psutil.process_iter():
yield SystemProcess(process)
def get_pid(self) -> int:
return os.getpid()
def atexit(self, callback: Callable[[], None]) -> None:
atexit.register(callback)
def user(self) -> str:
return get_current_user()
class ForgeState(Enum):
RUNNING = "RUNNING"
PASS = "PASS"
FAIL = "FAIL"
SKIP = "SKIP"
EMPTY = "EMPTY"
class ForgeResult:
def __init__(self):
self.state: ForgeState = ForgeState.EMPTY
self.output: str = ""
self.debugging_output: str = ""
self._start_time: Optional[datetime] = None
self._end_time: Optional[datetime] = None
@property
def start_time(self) -> datetime:
assert self._start_time is not None, "start_time is not set"
return self._start_time
@property
def end_time(self) -> datetime:
assert self._end_time is not None, "end_time is not set"
return self._end_time
@classmethod
def from_args(cls, state: ForgeState, output: str) -> "ForgeResult":
result = cls()
result.state = state
result.output = output
return result
@classmethod
def empty(cls) -> "ForgeResult":
return cls.from_args(ForgeState.EMPTY, "")
@classmethod
@contextmanager
def with_context(
cls, context: "ForgeContext"
) -> Generator["ForgeResult", None, None]:
result = cls()
result.state = ForgeState.RUNNING
result._start_time = context.time.now()
try:
yield result
result.set_debugging_output(
dump_forge_state(
context.shell,
context.forge_namespace,
context.forge_cluster.kubeconf,
)
)
except Exception as e:
result.set_state(ForgeState.FAIL)
result.set_debugging_output(
"{}\n{}\n".format(
str(e),
dump_forge_state(
context.shell,
context.forge_namespace,
context.forge_cluster.kubeconf,
)
)
)
result._end_time = context.time.now()
if result.state not in (ForgeState.PASS, ForgeState.FAIL, ForgeState.SKIP):
raise Exception("Forge result never entered terminal state")
if result.output is None:
raise Exception("Forge result didnt record output")
def set_state(self, state: ForgeState) -> None:
self.state = state
def set_output(self, output: str) -> None:
self.output = output
def set_debugging_output(self, output: str) -> None:
self.debugging_output = output
def format(self, context: ForgeContext) -> str:
output_lines = []
if not self.succeeded():
output_lines.append(self.debugging_output)
output_lines.extend([
f"Forge output: {self.output}",
f"Forge {self.state.value.lower()}ed",
])
return "\n".join(output_lines)
def succeeded(self) -> bool:
return self.state == ForgeState.PASS
class Time:
def epoch(self) -> str:
return self.now().strftime("%s")
def now(self) -> datetime:
raise NotImplementedError()
class SystemTime(Time):
def now(self) -> datetime:
return datetime.now(timezone.utc)
@dataclass
class SystemContext:
shell: Shell
filesystem: Filesystem
processes: Processes
time: Time
@dataclass
class ForgeContext:
shell: Shell
filesystem: Filesystem
processes: Processes
time: Time
# forge cluster options
forge_namespace: str
forge_args: Sequence[str]
# aws related options
aws_account_num: Optional[str]
aws_region: str
forge_image_tag: str
image_tag: str
upgrade_image_tag: str
forge_cluster: ForgeCluster
forge_test_suite: str
forge_blocking: bool
github_actions: str
github_job_url: Optional[str]
def report(
self,
result: ForgeResult,
outputs: List[ForgeFormatter]
) -> None:
for formatter in outputs:
output = formatter.format(self, result)
print(f"=== Start {formatter} ===")
print(output)
print(f"=== End {formatter} ===")
self.filesystem.write(formatter.filename, output.encode())
@property
def forge_chain_name(self) -> str:
forge_chain_name = self.forge_cluster.name.lstrip("aptos-")
if "forge" not in forge_chain_name:
forge_chain_name += "net"
return forge_chain_name
@dataclass
class ForgeFormatter:
filename: str
_format: Callable[[ForgeContext, ForgeResult], str]
def format(self, context: ForgeContext, result: ForgeResult) -> str:
return self._format(context, result)
def __str__(self) -> str:
return self.filename
def format_report(context: ForgeContext, result: ForgeResult) -> str:
report_lines = []
recording = False
error_buffer = []
error_length = 10
for line in result.output.splitlines():
if line in ("====json-report-begin===", "====json-report-end==="):
recording = not recording
elif recording:
report_lines.append(line)
else:
if len(error_buffer) == error_length and not report_lines:
error_buffer.pop(0)
error_buffer.append(line)
report_output = "\n".join(report_lines)
error_output = "\n".join(error_buffer)
debugging_appendix = (
"Trailing Log Lines:\n{}\nDebugging output:\n{}".format(
error_output, result.debugging_output
)
)
if not report_lines:
return "Forge test runner terminated:\n{}".format(debugging_appendix)
report_text = None
try:
report_text = json.loads(report_output).get("text")
except Exception as e:
return "Forge report malformed: {}\n{}\n{}".format(
e, repr(report_output), debugging_appendix
)
if not report_text:
return "Forge report text empty. See test runner output.\n{}".format(
debugging_appendix
)
else:
if result.state == ForgeState.FAIL:
return "{}\n{}".format(report_text, debugging_appendix)
return report_text
def get_dashboard_link(
forge_namespace: str,
forge_chain_name: str,
time_filter: Union[bool, Tuple[datetime, datetime]],
) -> str:
if time_filter is True:
grafana_time_filter = "&refresh=10s&from=now-15m&to=now"
elif isinstance(time_filter, tuple):
start_ms = int(time_filter[0].timestamp()) * 1000
end_ms = int(time_filter[1].timestamp()) * 1000
grafana_time_filter = f"&from={start_ms}&to={end_ms}"
else:
raise Exception(f"Invalid refresh argument: {time_filter}")
return (
f"{GRAFANA_BASE_URL}&var-namespace={forge_namespace}"
f"&var-chain_name={forge_chain_name}{grafana_time_filter}"
)
def shorten_link(link: str) -> str:
headers = {
"x-api-key": os.getenv("SHORTENER_API_KEY"),
"Content-Type": "application/json"
}
body = json.dumps({
"longUrl": link,
})
try:
import requests
response = requests.post(
'https://api.aws3.link/shorten',
headers=headers,
data=body
)
return f"https://{response.json()['shortUrl']}"
# Dont fail if we fail to shorten
except Exception:
return link
def milliseconds(timestamp: datetime) -> int:
return int(timestamp.timestamp()) * 1000
def apply_humio_time_filter(
urlparts: Dict[str, Union[str, bool, int]],
time_filter: Union[bool, Tuple[datetime, datetime]],
) -> Dict:
if time_filter is True:
urlparts = {
**urlparts,
"live": "true",
"start": "30m",
}
elif isinstance(time_filter, tuple):
start_ms = milliseconds(time_filter[0])
end_ms = milliseconds(time_filter[1])
urlparts = {
**urlparts,
"live": "false",
"start": start_ms,
"end": end_ms,
}
else:
raise Exception(f"Invalid refresh argument: {time_filter}")
return urlparts
def get_humio_forge_link(
forge_namespace: str,
time_filter: Union[bool, Tuple[datetime, datetime]],
) -> str:
columns = [
{
'type': 'field',
'fieldName': '@timestamp',
'format': 'timestamp',
'width': 180
},
{
"type": "link",
"openInNewBrowserTab": "***",
"style": "button",
"hrefTemplate": "https://github.com/aptos-labs/aptos-core/pull/{{fields[\"github_pr\"]}}",
"textTemplate": "{{fields[\"github_pr\"]}}",
"header": "Forge PR",
"width": 79
},
{
"type": "field",
"fieldName": "k8s.namespace",
"format": "text",
"width": 104
},
{
'type': 'field',
'fieldName': 'message',
'format': 'text',
'width': 3760
},
]
urlparts = {
'query': (
'$forgeLogs(validator_instance=*)'
f' | {forge_namespace}'
' | "k8s.labels.app.kubernetes.io/name" = forge'
),
'widgetType': 'list-view',
'columns': json.dumps(columns),
'newestAtBottom': 'true',
'showOnlyFirstLine': 'false',
}
urlparts = apply_humio_time_filter(urlparts, time_filter)
query = urlencode(urlparts)
return urlunparse(
ParseResult(
'https',
'cloud.us.humio.com',
'/k8s/search',
'',
query,
''
)
)
def get_humio_logs_link(
forge_namespace: str,
time_filter: Union[bool, Tuple[datetime, datetime]],
) -> str:
query = f'$forgeLogs(validator_instance=*) | {forge_namespace}'
columns = [
{
"type": "field",
"fieldName": "@timestamp",
"format": "timestamp",
"width": 180
},
{
"type": "field",
"fieldName": "level",
"format": "text",
"width": 54
},
{
"type": "link",
"openInNewBrowserTab": "***",
"style": "button",
"hrefTemplate": "https://github.com/aptos-labs/aptos-core/pull/{{fields[\"github_pr\"]}}",
"textTemplate": "{{fields[\"github_pr\"]}}",
"header": "Forge PR",
"width": 79
},
{
"type": "field",
"fieldName": "k8s.namespace",
"format": "text",
"width": 104
},
{
"type": "field",
"fieldName": "k8s.pod_name",
"format": "text",
"width": 126
},
{
"type": "field",
"fieldName": "k8s.container_name",
"format": "text",
"width": 85
},
{
"type": "field",
"fieldName": "message",
"format": "text"
},
]
urlparts = {
'query': query,
'widgetType': 'list-view',
'columns': json.dumps(columns),
'newestAtBottom': '***',
'showOnlyFirstLine': 'false',
}
urlparts = apply_humio_time_filter(urlparts, time_filter)
return urlunparse(
ParseResult(
'https',
'cloud.us.humio.com',
'/k8s/search',
'',
urlencode(urlparts),
''
)
)
def format_github_info(context: ForgeContext) -> str:
if not context.github_job_url:
return ""
else:
return (
textwrap.dedent(
f"""
* [Test runner output]({context.github_job_url})
* Test run is {'' if context.forge_blocking else 'not '}land-blocking
"""
)
.lstrip()
.strip()
)
def get_testsuite_images(context: ForgeContext) -> str:
# If image tags dont match then we're upgrading
if context.image_tag != context.upgrade_image_tag:
return f"`{context.image_tag}` ==> `{context.upgrade_image_tag}`"
else:
return f"`{context.image_tag}`"
def format_pre_comment(context: ForgeContext) -> str:
dashboard_link = get_dashboard_link(
context.forge_namespace,
context.forge_chain_name,
True,
)
humio_logs_link = get_humio_logs_link(
context.forge_namespace,
True,
)
return (
textwrap.dedent(
f"""
### Forge is running suite `{context.forge_test_suite}` on {get_testsuite_images(context)}
* [Grafana dashboard (auto-refresh)]({dashboard_link})
* [Humio Logs]({humio_logs_link})
"""
).lstrip()
+ format_github_info(context)
)
def format_comment(context: ForgeContext, result: ForgeResult) -> str:
dashboard_link = get_dashboard_link(
context.forge_namespace,
context.forge_chain_name,
(result.start_time, result.end_time),
)
humio_logs_link = get_humio_logs_link(
context.forge_namespace,
(result.start_time, result.end_time),
)
if result.state == ForgeState.PASS:
forge_comment_header = (
f"### :white_check_mark: Forge suite `{context.forge_test_suite}` success on {get_testsuite_images(context)}"
)
elif result.state == ForgeState.FAIL:
forge_comment_header = (
f"### :x: Forge suite `{context.forge_test_suite}` failure on {get_testsuite_images(context)}"
)
elif result.state == ForgeState.SKIP:
forge_comment_header = (
f"### :thought_balloon: Forge suite `{context.forge_test_suite}` preempted on {get_testsuite_images(context)}"
)
else:
raise Exception(f"Invalid forge state: {result.state}")
return (
textwrap.dedent(
f"""
{forge_comment_header}
```
"""
).lstrip()
+ format_report(context, result)
+ textwrap.dedent(
f"""
```
* [Grafana dashboard]({dashboard_link})
* [Humio Logs]({humio_logs_link})
"""
)
+ format_github_info(context)
)
class ForgeRunner:
def run(self, context: ForgeContext) -> ForgeResult:
raise NotImplementedError
def dump_forge_state(
shell: Shell,
forge_namespace: str,
kubeconf: str,
) -> str:
try:
output = (
shell.run(
[
"kubectl",
"--kubeconfig",
kubeconf,
"get",
"pods",
"-n",
forge_namespace,
]
)
.unwrap()
.decode()
)
return "" if "No resources found" in output else output
except Exception as e:
return f"Failed to get debugging output: {e}"
def find_the_killer(
shell: Shell,
forge_namespace: str,
kubeconf: str,
) -> str:
killer = shell.run(
[
"kubectl",
"--kubeconfig",
kubeconf,
"get",
"pod",
"-l",
f"forge-namespace={forge_namespace}",
"-o",
"jsonpath={.items[0].metadata.name}",
]
).output.decode()
return f"Likely killed by {killer}"
class LocalForgeRunner(ForgeRunner):
def run(self, context: ForgeContext) -> ForgeResult:
# Set rlimit to unlimited for txn emitter locally
context.filesystem.rlimit(
resource.RLIMIT_NOFILE, resource.RLIM_INFINITY, resource.RLIM_INFINITY
)
with ForgeResult.with_context(context) as forge_result:
result = context.shell.run(
context.forge_args,
stream_output=True,
)
forge_result.set_output(result.output.decode())
forge_result.set_state(
ForgeState.PASS if result.succeeded() else ForgeState.FAIL
)
return forge_result
class K8sForgeRunner(ForgeRunner):
def run(self, context: ForgeContext) -> ForgeResult:
forge_pod_name = sanitize_forge_resource_name(
f"{context.forge_namespace}-{context.time.epoch()}-{context.image_tag}"
)
context.shell.run(
[
"kubectl",
"--kubeconfig",
context.forge_cluster.kubeconf,
"delete",
"pod",
"-n",
"default",
"-l",
f"forge-namespace={context.forge_namespace}",
"--force",
]
)
context.shell.run(
[
"kubectl",
"--kubeconfig",
context.forge_cluster.kubeconf,
"wait",
"-n",
"default",
"--for=delete",
"pod",
"-l",
f"forge-namespace={context.forge_namespace}",
]
)
template = context.filesystem.read("testsuite/forge-test-runner-template.yaml")
forge_triggered_by = "github-actions" if context.github_actions else "other"
assert context.aws_account_num is not None, "AWS account number is required"
rendered = template.decode().format(
FORGE_POD_NAME=forge_pod_name,
FORGE_IMAGE_TAG=context.forge_image_tag,
IMAGE_TAG=context.image_tag,
UPGRADE_IMAGE_TAG=context.upgrade_image_tag,
AWS_ACCOUNT_NUM=context.aws_account_num,
AWS_REGION=context.aws_region,
FORGE_NAMESPACE=context.forge_namespace,
FORGE_ARGS=" ".join(context.forge_args),
FORGE_TRIGGERED_BY=forge_triggered_by,
)
with ForgeResult.with_context(context) as forge_result:
specfile = context.filesystem.mkstemp()
context.filesystem.write(specfile, rendered.encode())
context.shell.run(
[
"kubectl",
"--kubeconfig",
context.forge_cluster.kubeconf,
"apply",
"-n", "default",
"-f", specfile]
).unwrap()
context.shell.run(
[
"kubectl",
"--kubeconfig",
context.forge_cluster.kubeconf,
"wait",
"-n",
"default",
"--timeout=5m",
"--for=condition=Ready",
f"pod/{forge_pod_name}",
]
)
state = None
attempts = 100
streaming = True
while state is None:
forge_logs = context.shell.run(
[
"kubectl",
"--kubeconfig",
context.forge_cluster.kubeconf,
"logs",
"-n", "default",
"-f", forge_pod_name
],
stream_output=streaming,
)
# After the first invocation, stop streaming duplicate logs
if streaming:
streaming = False
forge_result.set_output(forge_logs.output.decode())
# parse the pod status: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase
forge_status = (
context.shell.run(
[
"kubectl",
"--kubeconfig",
context.forge_cluster.kubeconf,
"get",
"pod",
"-n",
"default",
forge_pod_name,
"-o",
"jsonpath='{.status.phase}'",
]
)
.output.decode()
.lower()
)
if "running" in forge_status:
continue
elif "succeeded" in forge_status:
state = ForgeState.PASS
elif re.findall(r"not\s*found", forge_status, re.IGNORECASE):
state = ForgeState.SKIP
forge_result.set_debugging_output(
find_the_killer(
context.shell,
context.forge_namespace,
context.forge_cluster.kubeconf,
)
)
else:
state = ForgeState.FAIL
attempts -= 1
if attempts <= 0:
raise Exception("Exhausted attempt to get forge pod status")
forge_result.set_state(state)
return forge_result
class AwsError(Exception):
pass
def get_aws_account_num(shell: Shell) -> str:
caller_id = shell.run(["aws", "sts", "get-caller-identity"])
return json.loads(caller_id.unwrap()).get("Account")
def assert_aws_auth(shell: Shell) -> None:
# Simple read command which should fail
list_eks_clusters(shell)
class ListClusterResult(TypedDict):
clusters: List[str]
def list_eks_clusters(shell: Shell) -> List[str]:
cluster_json = shell.run(["aws", "eks", "list-clusters"]).unwrap()
# This type annotation is not enforced, just helpful
try:
cluster_result: ListClusterResult = json.loads(cluster_json.decode())
clusters = []
for cluster_name in cluster_result["clusters"]:
if cluster_name.startswith("aptos-forge-"):
clusters.append(cluster_name)
return clusters
except Exception as e:
raise AwsError("Failed to list eks clusters") from e
async def write_cluster_config(
shell: Shell, forge_cluster_name: str, temp: str