forked from saltstack/salt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathci.py
1296 lines (1159 loc) · 44.4 KB
/
ci.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
"""
These commands are used in the CI pipeline.
"""
# pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated
from __future__ import annotations
import json
import logging
import os
import pathlib
import random
import shutil
import sys
import time
from typing import TYPE_CHECKING, Any
import yaml
from ptscripts import Context, command_group
import tools.utils
import tools.utils.gh
if sys.version_info < (3, 11):
from typing_extensions import NotRequired, TypedDict
else:
from typing import NotRequired, TypedDict # pylint: disable=no-name-in-module
try:
import boto3
except ImportError:
print(
"\nPlease run 'python -m pip install -r "
"requirements/static/ci/py{}.{}/tools.txt'\n".format(*sys.version_info),
file=sys.stderr,
flush=True,
)
raise
log = logging.getLogger(__name__)
# Define the command group
ci = command_group(name="ci", help="CI Related Commands", description=__doc__)
@ci.command(
name="print-gh-event",
)
def print_gh_event(ctx: Context):
"""
Pretty print the GH Actions event.
"""
gh_event_path = os.environ.get("GITHUB_EVENT_PATH") or None
if gh_event_path is None:
ctx.warn("The 'GITHUB_EVENT_PATH' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert gh_event_path is not None
try:
gh_event = json.loads(open(gh_event_path).read())
except Exception as exc:
ctx.error(f"Could not load the GH Event payload from {gh_event_path!r}:\n", exc) # type: ignore[arg-type]
ctx.exit(1)
ctx.info("GH Event Payload:")
ctx.print(gh_event, soft_wrap=True)
ctx.exit(0)
@ci.command(
name="process-changed-files",
arguments={
"event_name": {
"help": "The name of the GitHub event being processed.",
},
"changed_files": {
"help": (
"Path to '.json' file containing the payload of changed files "
"from the 'dorny/paths-filter' GitHub action."
),
},
},
)
def process_changed_files(ctx: Context, event_name: str, changed_files: pathlib.Path):
"""
Process changed files to avoid path traversal.
"""
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is None:
ctx.warn("The 'GITHUB_OUTPUT' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_output is not None
if not changed_files.exists():
ctx.error(f"The '{changed_files}' file does not exist.")
ctx.exit(1)
contents = changed_files.read_text()
if not contents:
if event_name == "pull_request":
ctx.error(f"The '{changed_files}' file is empty.")
ctx.exit(1)
else:
ctx.debug(f"The '{changed_files}' file is empty.")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"changed-files={json.dumps({})}\n")
ctx.exit(0)
try:
changed_files_contents = json.loads(contents)
except Exception as exc:
ctx.error(f"Could not load the changed files from '{changed_files}': {exc}")
ctx.exit(1)
sanitized_changed_files = {}
ctx.info("Sanitizing paths and confirming no path traversal is being used...")
for key, data in changed_files_contents.items():
try:
loaded_data = json.loads(data)
except ValueError:
loaded_data = data
if key.endswith("_files"):
files = set()
for entry in list(loaded_data):
if not entry:
loaded_data.remove(entry)
try:
entry = (
tools.utils.REPO_ROOT.joinpath(entry)
.resolve()
.relative_to(tools.utils.REPO_ROOT)
)
except ValueError:
ctx.error(
f"While processing the changed files key {key!r}, the "
f"path entry {entry!r} was checked and it's not relative "
"to the repository root."
)
ctx.exit(1)
files.add(str(entry))
sanitized_changed_files[key] = sorted(files)
continue
sanitized_changed_files[key] = loaded_data
ctx.info("Writing 'changed-files' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"changed-files={json.dumps(sanitized_changed_files)}\n")
ctx.exit(0)
@ci.command(
name="runner-types",
arguments={
"event_name": {
"help": "The name of the GitHub event being processed.",
},
},
)
def runner_types(ctx: Context, event_name: str):
"""
Set GH Actions 'runners' output to know what can run where.
"""
gh_event_path = os.environ.get("GITHUB_EVENT_PATH") or None
if gh_event_path is None:
ctx.warn("The 'GITHUB_EVENT_PATH' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert gh_event_path is not None
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is None:
ctx.warn("The 'GITHUB_OUTPUT' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_output is not None
try:
gh_event = json.loads(open(gh_event_path).read())
except Exception as exc:
ctx.error(f"Could not load the GH Event payload from {gh_event_path!r}:\n", exc) # type: ignore[arg-type]
ctx.exit(1)
ctx.info("GH Event Payload:")
ctx.print(gh_event, soft_wrap=True)
# Let's it print until the end
time.sleep(1)
ctx.info("Selecting which type of runners(self hosted runners or not) to run")
runners = {"github-hosted": False, "self-hosted": False}
if event_name == "pull_request":
ctx.info("Running from a pull request event")
pr_event_data = gh_event["pull_request"]
if (
pr_event_data["head"]["repo"]["full_name"]
== pr_event_data["base"]["repo"]["full_name"]
):
# If this is a pull request coming from the same repository, don't run anything
ctx.info("Pull request is coming from the same repository.")
ctx.info("Not running any jobs since they will run against the branch")
ctx.info("Writing 'runners' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"runners={json.dumps(runners)}\n")
ctx.exit(0)
# This is a PR from a forked repository
ctx.info("Pull request is not comming from the same repository")
runners["github-hosted"] = runners["self-hosted"] = True
ctx.info("Writing 'runners' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"runners={json.dumps(runners)}\n")
ctx.exit(0)
# This is a push or a scheduled event
ctx.info(f"Running from a {event_name!r} event")
if (
gh_event["repository"]["fork"] is True
and os.environ.get("FORK_HAS_SELF_HOSTED_RUNNERS", "0") == "1"
):
# This is running on a forked repository, don't run tests
ctx.info("The push event is on a forked repository")
runners["github-hosted"] = True
ctx.info("Writing 'runners' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"runners={json.dumps(runners)}\n")
ctx.exit(0)
# Not running on a fork, or the fork has self hosted runners, run everything
ctx.info(f"The {event_name!r} event is from the main repository")
runners["github-hosted"] = runners["self-hosted"] = True
ctx.info("Writing 'runners' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"runners={json.dumps(runners)}")
ctx.exit(0)
@ci.command(
name="define-jobs",
arguments={
"event_name": {
"help": "The name of the GitHub event being processed.",
},
"skip_tests": {
"help": "Skip running the Salt tests",
},
"skip_pkg_tests": {
"help": "Skip running the Salt Package tests",
},
"skip_pkg_download_tests": {
"help": "Skip running the Salt Package download tests",
},
"changed_files": {
"help": (
"Path to '.json' file containing the payload of changed files "
"from the 'dorny/paths-filter' GitHub action."
),
},
},
)
def define_jobs(
ctx: Context,
event_name: str,
changed_files: pathlib.Path,
skip_tests: bool = False,
skip_pkg_tests: bool = False,
skip_pkg_download_tests: bool = False,
):
"""
Set GH Actions 'jobs' output to know which jobs should run.
"""
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is None:
ctx.warn("The 'GITHUB_OUTPUT' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_output is not None
github_step_summary = os.environ.get("GITHUB_STEP_SUMMARY")
if github_step_summary is None:
ctx.warn("The 'GITHUB_STEP_SUMMARY' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_step_summary is not None
jobs = {
"lint": True,
"test": True,
"test-pkg": True,
"test-pkg-download": True,
"prepare-release": True,
"build-docs": True,
"build-source-tarball": True,
"build-deps-onedir": True,
"build-salt-onedir": True,
"build-pkgs": True,
"build-deps-ci": True,
}
if skip_tests:
jobs["test"] = False
if skip_pkg_tests:
jobs["test-pkg"] = False
if skip_pkg_download_tests:
jobs["test-pkg-download"] = False
if event_name != "pull_request":
# In this case, all defined jobs should run
ctx.info("Writing 'jobs' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"jobs={json.dumps(jobs)}\n")
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
f"All defined jobs will run due to event type of `{event_name}`.\n"
)
return
# This is a pull-request
labels: list[str] = []
gh_event_path = os.environ.get("GITHUB_EVENT_PATH") or None
if gh_event_path is not None:
try:
gh_event = json.loads(open(gh_event_path).read())
except Exception as exc:
ctx.error(
f"Could not load the GH Event payload from {gh_event_path!r}:\n", exc # type: ignore[arg-type]
)
ctx.exit(1)
labels.extend(
label[0] for label in _get_pr_test_labels_from_event_payload(gh_event)
)
if not changed_files.exists():
ctx.error(f"The '{changed_files}' file does not exist.")
ctx.error(
"FYI, the command 'tools process-changed-files <changed-files-path>' "
"needs to run prior to this one."
)
ctx.exit(1)
try:
changed_files_contents = json.loads(changed_files.read_text())
except Exception as exc:
ctx.error(f"Could not load the changed files from '{changed_files}': {exc}")
ctx.exit(1)
# So, it's a pull request...
# Based on which files changed, we can decide what jobs to run.
required_lint_changes: set[str] = {
changed_files_contents["salt"],
changed_files_contents["tests"],
changed_files_contents["lint"],
}
if required_lint_changes == {"false"}:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("De-selecting the 'lint' job.\n")
jobs["lint"] = False
required_docs_changes: set[str] = {
changed_files_contents["salt"],
changed_files_contents["docs"],
}
if required_docs_changes == {"false"}:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("De-selecting the 'build-docs' job.\n")
jobs["build-docs"] = False
required_test_changes: set[str] = {
changed_files_contents["testrun"],
changed_files_contents["workflows"],
changed_files_contents["golden_images"],
}
if jobs["test"] and required_test_changes == {"false"}:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("De-selecting the 'test' job.\n")
jobs["test"] = False
required_pkg_test_changes: set[str] = {
changed_files_contents["pkg_tests"],
changed_files_contents["workflows"],
changed_files_contents["golden_images"],
}
if jobs["test-pkg"] and required_pkg_test_changes == {"false"}:
if "test:pkg" in labels:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
"The 'test-pkg' job is forcefully selected by the use of the 'test:pkg' label.\n"
)
jobs["test-pkg"] = True
else:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("De-selecting the 'test-pkg' job.\n")
jobs["test-pkg"] = False
if jobs["test-pkg-download"] and required_pkg_test_changes == {"false"}:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("De-selecting the 'test-pkg-download' job.\n")
jobs["test-pkg-download"] = False
if not jobs["test"] and not jobs["test-pkg"] and not jobs["test-pkg-download"]:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
for job in (
"build-deps-ci",
"build-deps-onedir",
"build-salt-onedir",
"build-pkgs",
):
wfh.write(f"De-selecting the '{job}' job.\n")
jobs[job] = False
if not jobs["build-docs"]:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("De-selecting the 'build-source-tarball' job.\n")
jobs["build-source-tarball"] = False
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Selected Jobs:\n")
for name, value in sorted(jobs.items()):
wfh.write(f" - {name}: {value}\n")
ctx.info("Writing 'jobs' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"jobs={json.dumps(jobs)}\n")
class TestRun(TypedDict):
type: str
skip_code_coverage: bool
from_filenames: NotRequired[str]
selected_tests: NotRequired[dict[str, bool]]
@ci.command(
name="define-testrun",
arguments={
"event_name": {
"help": "The name of the GitHub event being processed.",
},
"changed_files": {
"help": (
"Path to '.json' file containing the payload of changed files "
"from the 'dorny/paths-filter' GitHub action."
),
},
},
)
def define_testrun(ctx: Context, event_name: str, changed_files: pathlib.Path):
"""
Set GH Actions outputs for what and how Salt should be tested.
"""
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is None:
ctx.warn("The 'GITHUB_OUTPUT' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_output is not None
github_step_summary = os.environ.get("GITHUB_STEP_SUMMARY")
if github_step_summary is None:
ctx.warn("The 'GITHUB_STEP_SUMMARY' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_step_summary is not None
labels: list[str] = []
gh_event_path = os.environ.get("GITHUB_EVENT_PATH") or None
if gh_event_path is not None:
try:
gh_event = json.loads(open(gh_event_path).read())
except Exception as exc:
ctx.error(
f"Could not load the GH Event payload from {gh_event_path!r}:\n", exc # type: ignore[arg-type]
)
ctx.exit(1)
labels.extend(
label[0] for label in _get_pr_test_labels_from_event_payload(gh_event)
)
if "test:coverage" in labels:
ctx.info("Writing 'testrun' to the github outputs file")
testrun = TestRun(type="full", skip_code_coverage=False)
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"testrun={json.dumps(testrun)}\n")
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
"Full test run chosen because the label `test:coverage` is set.\n"
)
return
elif event_name != "pull_request":
# In this case, a full test run is in order
ctx.info("Writing 'testrun' to the github outputs file")
testrun = TestRun(type="full", skip_code_coverage=False)
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"testrun={json.dumps(testrun)}\n")
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(f"Full test run chosen due to event type of `{event_name}`.\n")
return
# So, it's a pull request...
if not changed_files.exists():
ctx.error(f"The '{changed_files}' file does not exist.")
ctx.error(
"FYI, the command 'tools process-changed-files <changed-files-path>' "
"needs to run prior to this one."
)
ctx.exit(1)
try:
changed_files_contents = json.loads(changed_files.read_text())
except Exception as exc:
ctx.error(f"Could not load the changed files from '{changed_files}': {exc}")
ctx.exit(1)
# Based on which files changed, or other things like PR labels we can
# decide what to run, or even if the full test run should be running on the
# pull request, etc...
changed_pkg_requirements_files = json.loads(
changed_files_contents["pkg_requirements_files"]
)
changed_test_requirements_files = json.loads(
changed_files_contents["test_requirements_files"]
)
if changed_files_contents["golden_images"] == "true":
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
"Full test run chosen because there was a change made "
"to `cicd/golden-images.json`.\n"
)
testrun = TestRun(type="full", skip_code_coverage=True)
elif changed_pkg_requirements_files or changed_test_requirements_files:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
"Full test run chosen because there was a change made "
"to the requirements files.\n"
)
wfh.write(
"<details>\n<summary>Changed Requirements Files (click me)</summary>\n<pre>\n"
)
for path in sorted(
changed_pkg_requirements_files + changed_test_requirements_files
):
wfh.write(f"{path}\n")
wfh.write("</pre>\n</details>\n")
testrun = TestRun(type="full", skip_code_coverage=True)
elif "test:full" in labels:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Full test run chosen because the label `test:full` is set.\n")
testrun = TestRun(type="full", skip_code_coverage=True)
else:
testrun_changed_files_path = tools.utils.REPO_ROOT / "testrun-changed-files.txt"
testrun = TestRun(
type="changed",
skip_code_coverage=True,
from_filenames=str(
testrun_changed_files_path.relative_to(tools.utils.REPO_ROOT)
),
)
ctx.info(f"Writing {testrun_changed_files_path.name} ...")
selected_changed_files = []
for fpath in json.loads(changed_files_contents["testrun_files"]):
if fpath.startswith(("tools/", "tasks/")):
continue
if fpath in ("noxfile.py",):
continue
if fpath == "tests/conftest.py":
# In this particular case, just run the full test suite
testrun["type"] = "full"
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
f"Full test run chosen because there was a change to `{fpath}`.\n"
)
selected_changed_files.append(fpath)
testrun_changed_files_path.write_text("\n".join(sorted(selected_changed_files)))
if testrun["type"] == "changed":
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Partial test run chosen.\n")
testrun["selected_tests"] = {
"core": False,
"slow": False,
"fast": True,
"flaky": False,
}
if "test:slow" in labels:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Slow tests chosen by `test:slow` label.\n")
testrun["selected_tests"]["slow"] = True
if "test:core" in labels:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Core tests chosen by `test:core` label.\n")
testrun["selected_tests"]["core"] = True
if "test:no-fast" in labels:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Fast tests deselected by `test:no-fast` label.\n")
testrun["selected_tests"]["fast"] = False
if "test:flaky-jail" in labels:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("Flaky jailed tests chosen by `test:flaky-jail` label.\n")
testrun["selected_tests"]["flaky"] = True
if selected_changed_files:
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write(
"<details>\n<summary>Selected Changed Files (click me)</summary>\n<pre>\n"
)
for path in sorted(selected_changed_files):
wfh.write(f"{path}\n")
wfh.write("</pre>\n</details>\n")
with open(github_step_summary, "a", encoding="utf-8") as wfh:
wfh.write("<details>\n<summary>All Changed Files (click me)</summary>\n<pre>\n")
for path in sorted(json.loads(changed_files_contents["repo_files"])):
wfh.write(f"{path}\n")
wfh.write("</pre>\n</details>\n")
ctx.info("Writing 'testrun' to the github outputs file")
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"testrun={json.dumps(testrun)}\n")
@ci.command(
arguments={
"distro_slug": {
"help": "The distribution slug to generate the matrix for",
},
"full": {
"help": "Full test run",
},
"workflow": {
"help": "Which workflow is running",
},
"fips": {
"help": "Include FIPS entries in the matrix",
},
},
)
def matrix(
ctx: Context,
distro_slug: str,
full: bool = False,
workflow: str = "ci",
fips: bool = False,
):
"""
Generate the test matrix.
"""
_matrix = []
_splits = {
"functional": 3,
"integration": 6,
"scenarios": 1,
"unit": 4,
}
# On nightly and scheduled builds we don't want splits at all
if workflow.lower() in ("nightly", "scheduled"):
ctx.info(f"Reducing splits definition since workflow is '{workflow}'")
for key in _splits:
new_value = _splits[key] - 1
if new_value < 1:
new_value = 1
_splits[key] = new_value
for transport in ("zeromq", "tcp"):
if transport == "tcp":
if distro_slug not in (
"centosstream-9",
"centosstream-9-arm64",
"photonos-5",
"photonos-5-arm64",
"ubuntu-22.04",
"ubuntu-22.04-arm64",
):
# Only run TCP transport tests on these distributions
continue
for chunk in ("unit", "functional", "integration", "scenarios"):
if transport == "tcp" and chunk in ("unit", "functional"):
# Only integration and scenarios shall be tested under TCP,
# the rest would be repeating tests
continue
if "macos" in distro_slug and chunk == "scenarios":
continue
splits = _splits.get(chunk) or 1
if full and splits > 1:
for split in range(1, splits + 1):
_matrix.append(
{
"transport": transport,
"tests-chunk": chunk,
"test-group": split,
"test-group-count": splits,
}
)
if fips is True and distro_slug.startswith(
("photonos-4", "photonos-5")
):
# Repeat the last one, but with fips
_matrix.append({"fips": "fips", **_matrix[-1]})
else:
_matrix.append({"transport": transport, "tests-chunk": chunk})
if fips is True and distro_slug.startswith(
("photonos-4", "photonos-5")
):
# Repeat the last one, but with fips
_matrix.append({"fips": "fips", **_matrix[-1]})
ctx.info("Generated matrix:")
ctx.print(_matrix, soft_wrap=True)
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is not None:
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"matrix={json.dumps(_matrix)}\n")
ctx.exit(0)
@ci.command(
name="pkg-matrix",
arguments={
"distro_slug": {
"help": "The distribution slug to generate the matrix for",
},
"pkg_type": {
"help": "The type of package we are testing against",
},
"testing_releases": {
"help": "The salt releases to test upgrades against",
"nargs": "+",
"required": True,
},
"fips": {
"help": "Include FIPS entries in the matrix",
},
},
)
def pkg_matrix(
ctx: Context,
distro_slug: str,
pkg_type: str,
testing_releases: list[tools.utils.Version] = None,
fips: bool = False,
):
"""
Generate the test matrix.
"""
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is None:
ctx.warn("The 'GITHUB_OUTPUT' variable is not set.")
if TYPE_CHECKING:
assert testing_releases
still_testing_3005 = False
for release_version in testing_releases:
if still_testing_3005:
break
if release_version < tools.utils.Version("3006.0"):
still_testing_3005 = True
if still_testing_3005 is False:
ctx.error(
f"No longer testing 3005.x releases please update {__file__} "
"and remove this error and the logic above the error. There may "
"be other places that need code removed as well."
)
ctx.exit(1)
adjusted_versions = []
for ver in testing_releases:
if ver < tools.utils.Version("3006.0"):
adjusted_versions.append((ver, "classic"))
adjusted_versions.append((ver, "tiamat"))
else:
adjusted_versions.append((ver, "relenv"))
ctx.info(f"Will look for the following versions: {adjusted_versions}")
# Filter out the prefixes to look under
if "macos-" in distro_slug:
# We don't have golden images for macos, handle these separately
prefixes = {
"classic": "osx/",
"tiamat": "salt/py3/macos/minor/",
"relenv": "salt/py3/macos/minor/",
}
else:
parts = distro_slug.split("-")
name = parts[0]
version = parts[1]
if name in ("debian", "ubuntu"):
arch = "amd64"
elif name in ("centos", "centosstream", "amazonlinux", "photonos"):
arch = "x86_64"
if len(parts) > 2:
arch = parts[2]
if name == "amazonlinux":
name = "amazon"
if "centos" in name:
name = "redhat"
if "photon" in name:
name = "photon"
if name == "windows":
prefixes = {
"classic": "windows/",
"tiamat": "salt/py3/windows/minor",
"relenv": "salt/py3/windows/minor",
}
else:
prefixes = {
"classic": f"py3/{name}/{version}/{arch}/",
"tiamat": f"salt/py3/{name}/{version}/{arch}/minor/",
"relenv": f"salt/py3/{name}/{version}/{arch}/minor/",
}
s3 = boto3.client("s3")
paginator = s3.get_paginator("list_objects_v2")
_matrix = [
{
"test-chunk": "install",
"version": None,
}
]
for version, backend in adjusted_versions:
prefix = prefixes[backend]
# TODO: Remove this after 3009.0
if backend == "relenv" and version >= tools.utils.Version("3006.5"):
prefix.replace("/arm64/", "/aarch64/")
# Using a paginator allows us to list recursively and avoid the item limit
page_iterator = paginator.paginate(
Bucket=f"salt-project-{tools.utils.SPB_ENVIRONMENT}-salt-artifacts-release",
Prefix=prefix,
)
# Uses a jmespath expression to test if the wanted version is in any of the filenames
key_filter = f"Contents[?contains(Key, '{version}')][]"
if pkg_type == "MSI":
# TODO: Add this back when we add MSI upgrade and downgrade tests
# key_filter = f"Contents[?contains(Key, '{version}')] | [?ends_with(Key, '.msi')]"
continue
elif pkg_type == "NSIS":
key_filter = (
f"Contents[?contains(Key, '{version}')] | [?ends_with(Key, '.exe')]"
)
objects = list(page_iterator.search(key_filter))
# Testing using `any` because sometimes the paginator returns `[None]`
if any(objects):
ctx.info(
f"Found {version} ({backend}) for {distro_slug}: {objects[0]['Key']}"
)
for session in ("upgrade", "downgrade"):
if backend == "classic":
session += "-classic"
_matrix.append(
{
"test-chunk": session,
"version": str(version),
}
)
if (
backend == "relenv"
and fips is True
and distro_slug.startswith(("photonos-4", "photonos-5"))
):
# Repeat the last one, but with fips
_matrix.append({"fips": "fips", **_matrix[-1]})
else:
ctx.info(f"No {version} ({backend}) for {distro_slug} at {prefix}")
ctx.info("Generated matrix:")
ctx.print(_matrix, soft_wrap=True)
if github_output is not None:
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"matrix={json.dumps(_matrix)}\n")
ctx.exit(0)
@ci.command(
name="get-releases",
arguments={
"repository": {
"help": "The repository to query for releases, e.g. saltstack/salt",
},
},
)
def get_releases(ctx: Context, repository: str = "saltstack/salt"):
"""
Generate the latest salt release.
"""
releases = tools.utils.get_salt_releases(ctx, repository)
str_releases = [str(version) for version in releases]
latest = str_releases[-1]
ctx.info("Releases:", sorted(str_releases))
ctx.info(f"Latest Release: '{latest}'")
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is not None:
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"latest-release={latest}\n")
wfh.write(f"releases={json.dumps(str_releases)}\n")
ctx.exit(0)
@ci.command(
name="get-release-changelog-target",
arguments={
"event_name": {
"help": "The name of the GitHub event being processed.",
},
},
)
def get_release_changelog_target(ctx: Context, event_name: str):
"""
Define which kind of release notes should be generated, next minor or major.
"""
gh_event_path = os.environ.get("GITHUB_EVENT_PATH") or None
if gh_event_path is None:
ctx.warn("The 'GITHUB_EVENT_PATH' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert gh_event_path is not None
try:
gh_event = json.loads(open(gh_event_path).read())
except Exception as exc:
ctx.error(f"Could not load the GH Event payload from {gh_event_path!r}:\n", exc) # type: ignore[arg-type]
ctx.exit(1)
github_output = os.environ.get("GITHUB_OUTPUT")
if github_output is None:
ctx.warn("The 'GITHUB_OUTPUT' variable is not set.")
ctx.exit(1)
if TYPE_CHECKING:
assert github_output is not None
shared_context = yaml.safe_load(
tools.utils.SHARED_WORKFLOW_CONTEXT_FILEPATH.read_text()
)
release_branches = shared_context["release_branches"]
release_changelog_target = "next-major-release"
if event_name == "pull_request":
if gh_event["pull_request"]["base"]["ref"] in release_branches:
release_changelog_target = "next-minor-release"
elif event_name == "schedule":
branch_name = gh_event["repository"]["default_branch"]
if branch_name in release_branches:
release_changelog_target = "next-minor-release"
else:
for branch_name in release_branches:
if branch_name in gh_event["ref"]:
release_changelog_target = "next-minor-release"
break
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"release-changelog-target={release_changelog_target}\n")
ctx.exit(0)
@ci.command(
name="get-pr-test-labels",
arguments={
"pr": {
"help": "Pull request number",
},
"repository": {
"help": "Github repository.",
},
},
)
def get_pr_test_labels(
ctx: Context, repository: str = "saltstack/salt", pr: int = None
):
"""
Set the pull-request labels.
"""
gh_event_path = os.environ.get("GITHUB_EVENT_PATH") or None
if gh_event_path is None:
labels = _get_pr_test_labels_from_api(ctx, repository, pr=pr)
else:
if TYPE_CHECKING:
assert gh_event_path is not None
try:
gh_event = json.loads(open(gh_event_path).read())
except Exception as exc:
ctx.error(
f"Could not load the GH Event payload from {gh_event_path!r}:\n", exc # type: ignore[arg-type]
)
ctx.exit(1)
if "pull_request" not in gh_event:
ctx.warn("The 'pull_request' key was not found on the event payload.")