-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.py
executable file
·1653 lines (1430 loc) · 61.2 KB
/
manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# @author Jesus Alvarez <[email protected]>
"""Container scripts template injector and pipeline trigger."""
#
# !! IMPORTANT !!
#
# Editors of this file should use https://github.com/python/black for auto formatting.
#
# >>> REALLY IMPORTANT NOTICE ABOUT DEPENDENCIES... <<<
#
# 1. Dependency handling is done in two places
#
# a: Dependencies will be added automatically to the kitmaker trigger builder images
#
# 2. Gitlab pipeline "prepare" stage.
#
# a: This needs to be updated manually at the moment, to do this go to
# https://gitlab-master.nvidia.com/cuda-installer/cuda/-/pipelines/new and set the variable to "REBUILD_BUILDER=true" and
# run it. This will run the gitlab builder image rebuild to include the new dependencies.
#
# It is also possible to trigger builder rebuild with manager.py
#
import re
import os
import pathlib
import logging
import logging.config
import shutil
import glob
import sys
import io
import select
import time
import json
import subprocess
import collections
from packaging import version
import jinja2
from jinja2 import Environment, Template
from plumbum import cli, local
from plumbum.cmd import rm, grep, cut, sort, find
import yaml
import glom
import docker
import git
import deepdiff
import requests
from retry import retry
from config import *
from error import *
from utils import *
from shipitdata import *
from dotdict import *
class Manager(cli.Application):
"""CUDA CI Manager"""
PROGNAME = "manager.py"
VERSION = "0.0.1"
manifest = None
ci = None
manifest_path = cli.SwitchAttr(
"--manifest", str, excludes=["--shipit-uuid"], help="Select a manifest to use.",
)
shipit_uuid = cli.SwitchAttr(
"--shipit-uuid",
str,
excludes=["--manifest"],
help="Shipit UUID used to build release candidates (internal)",
)
def _load_manifest_yaml(self):
log.debug(f"Loading manifest: {self.manifest_path}")
with open(self.manifest_path, "r") as f:
self.manifest = yaml.load(f, yaml.Loader)
def load_ci_yaml(self):
with open(".gitlab-ci.yml", "r") as f:
self.ci = yaml.load(f, yaml.Loader)
def _load_app_config(self):
with open("manager-config.yaml", "r") as f:
logging.config.dictConfig(yaml.safe_load(f.read())["logging"])
# Get data from a object by dotted path. Example "cuda."v10.0".cuda_requires"
def get_data(self, obj, *path, can_skip=False):
try:
data = glom.glom(obj, glom.Path(*path))
except glom.PathAccessError:
if can_skip:
return
# raise glom.PathAccessError
log.error(f'get_data path: "{path}" not found!')
else:
return data
def main(self):
self._load_app_config()
if not self.nested_command: # will be ``None`` if no sub-command follows
log.fatal("No subcommand given!")
print()
self.help()
return 1
elif len(self.nested_command[1]) < 2 and any(
"generate" in arg for arg in self.nested_command[1]
):
log.error(
"Subcommand 'generate' missing required arguments! use 'generate --help'"
)
return 1
elif not any(halp in self.nested_command[1] for halp in ["-h", "--help"]):
log.info("cuda ci manager start")
if not self.shipit_uuid and self.manifest_path:
self._load_manifest_yaml()
@Manager.subcommand("trigger")
class ManagerTrigger(Manager):
DESCRIPTION = "Trigger for changes."
repo = None
trigger_all = False
trigger_explicit = []
key = ""
pipeline_name = "default"
CI_API_V4_URL = "https://gitlab-master.nvidia.com/api/v4"
CI_PROJECT_ID = 12064
dry_run = cli.Flag(
["-n", "--dry-run"], help="Show output but don't make any changes."
)
no_test = cli.Flag(["--no-test"], help="Don't run smoke tests")
no_scan = cli.Flag(["--no-scan"], help="Don't run security scans")
no_push = cli.Flag(["--no-push"], help="Don't push images to the registries")
rebuildb = cli.Flag(
["--rebuild-builder"],
help="Force rebuild of the builder image used to build the cuda images.",
)
branch = cli.SwitchAttr(
"--branch",
str,
help="The branch to trigger against on Gitlab.",
default="master",
)
distro = cli.SwitchAttr(
"--os-name",
str,
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="The distro name without version information",
default=None,
)
distro_version = cli.SwitchAttr(
"--os-version",
str,
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="The distro version",
default=None,
)
release_label = cli.SwitchAttr(
"--release-label",
str,
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="The cuda release label. Example: 11.2.0",
default=None,
)
arch = cli.SwitchAttr(
"--arch",
cli.Set("x86_64", "ppc64le", "arm64", case_sensitive=False),
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="Generate container scripts for a particular architecture",
)
candidate_number = cli.SwitchAttr(
"--candidate-number",
str,
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="The CUDA release candidate number",
default=None,
)
candidate_url = cli.SwitchAttr(
"--candidate-url",
str,
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="The CUDA release candidate url",
default=None,
)
webhook_url = cli.SwitchAttr(
"--webhook-url",
str,
group="Targeted",
excludes=["--manifest", "--trigger-override"],
help="The url to POST to when the job is done. POST will include a list of tags pushed",
default=None,
)
branch = cli.SwitchAttr(
"--branch",
str,
group="Targeted",
help="The branch to trigger against on gitlab.",
default=None,
)
trigger_override = cli.SwitchAttr(
"--trigger-override",
str,
excludes=["--shipit-uuid"],
help="Override triggering from gitlab with a variable",
default=None,
)
flavor = cli.SwitchAttr(
"--flavor",
str,
help="The container configuration to build (limited support).",
default="default",
)
def ci_pipeline_by_name(self, name):
rgx = re.compile(fr"^\s+- if: '\$([\w\._]*{name}[\w\._]*)\s+==\s.true.'$")
ci_vars = []
with open(".gitlab-ci.yml", "r") as fp:
for _, line in enumerate(fp):
match = rgx.match(line)
if match:
ci_vars.append(match.groups(0)[0])
return ci_vars
def ci_pipelines(
self, cuda_version, distro, distro_version, arch,
):
"""Returns a list of pipelines extracted from the gitlab-ci.yml
Iterates .gitlab-ci.yml line by line looking for a match on the pipeline variable.
For example:
- if: '$ubuntu20_04_11_3_1 == "true"'
Every pipeline has this variable defined, and that is used with the gitlab trigger api to trigger explicit
pipelines.
Returns a list of pipeline variables to pass to the gitlab API.
All arguments to this function can be None, in that case all of the pipelines are returned.
"""
if cuda_version:
distro_list_by_cuda_version = self.supported_distro_list_by_cuda_version(
version
)
if not cuda_version:
cuda_version = r"(\d{1,2}_\d{1,2}_?\d?)"
if not distro:
distro = r"(ubuntu\d{2}_\d{2})?(?(2)|([a-z]*\d))"
elif not distro_version:
distro = fr"({distro}\d)"
if "ubuntu" in distro:
distro = r"(ubuntu\d{2}_\d{2})"
else:
distro = f"{distro}{distro_version}"
rgx_temp = fr"^\s+- if: '\$({distro}_{cuda_version})\s+==\s.true.'$"
# log.debug(f"regex_matcher: {rgx_temp}")
rgx = re.compile(rgx_temp)
ci_vars = []
with open(".gitlab-ci.yml", "r") as fp:
for _, line in enumerate(fp):
match = rgx.match(line)
if match:
ci_vars.append(match.groups(0)[0])
return ci_vars
def get_cuda_version_from_trigger(self, trigger):
rgx = re.compile(r".*cuda-?([\d\.]+).*$")
match = rgx.match(trigger)
if (match := rgx.match(trigger)) is not None:
return match.group(1)
else:
log.info(f"Cuda version not found in trigger!")
def get_pipeline_name_from_trigger(self, trigger):
rgx = re.compile(r".*name:(\w+)$")
if (match := rgx.match(trigger)) is not None:
return match.group(1)
def get_distro_version_from_trigger(self, trigger):
rgx = re.compile(r".*cuda([\d\.]+).*$")
match = rgx.match(trigger)
if match is not None:
return match.group(1)
else:
log.warning(f"Could not extract version from trigger: '{trigger}'!")
def supported_distro_list_by_cuda_version(self, version):
if not version:
return
distros = ["ubuntu", "ubi", "centos"]
keys = self.parent.manifest[self.key].keys()
# There are other keys in the cuda field other than distros, we need to strip those out
def get_distro_name(name):
r = re.compile("[a-zA-Z]+")
return r.findall(name)[0]
return [f for f in keys if get_distro_name(f) in distros]
def check_explicit_trigger(self):
"""Checks for a pipeline trigger command and builds a list of pipelines to trigger.
Checks for a trigger command in the following order:
- git commit message
- trigger_override command line flag
Returns True if pipelines have been found matching the trigger command.
"""
self.repo = git.Repo(pathlib.Path("."))
commit = self.repo.commit("HEAD")
rgx = re.compile(r"ci\.trigger = (.*)")
log.debug("Commit message: %s", repr(commit.message))
if self.trigger_override:
log.info("Using trigger override!")
# check for illegal characters
if not re.search(
r"^(?:[cuda]+[\d\.]*(?:[_a-z0-9]*)?,?)+$", self.trigger_override
):
raise Exception(
"Regex match for trigger override failed! Allowed format is 'cuda<version>(_<distro_with_version>)[,...]' ex: 'cuda11.0.3' or 'cuda10.2_centos8`"
)
pipeline = self.trigger_override
else:
match = rgx.search(commit.message)
if not match:
log.debug("No explicit trigger found in commit message.")
return False
else:
log.info("Explicit trigger found in commit message")
pipeline = match.groups(0)[0].lower()
if "all" in pipeline:
log.info("Triggering ALL of the jobs!")
self.trigger_all = True
return True
else:
jobs = []
jobs.append(pipeline)
log.debug(f"jobs: {jobs}")
if "," in pipeline:
jobs = [x.strip() for x in pipeline.split(",")]
for job in jobs:
version = self.get_cuda_version_from_trigger(job)
if not version:
self.pipeline_name = self.get_pipeline_name_from_trigger(job)
log.debug("cuda_version: %s" % version)
log.debug("pipeline_name: %s" % self.pipeline_name)
self.key = f"cuda_v{version}"
if self.pipeline_name != "default":
self.key = f"cuda_v{version}_{self.pipeline_name}"
distro = next((d for d in SUPPORTED_DISTRO_LIST if d in job), None)
distro_version = None
if distro:
# The trigger specifies a distro
assert not any( # distro should not contain digits
char.isdigit() for char in distro
)
distro_version = (
re.match(fr"^.*{distro}([\d\.]*)", job).groups(0)[0] or None
)
arch = next(
(arch for arch in ["x86_64", "ppc64le", "arm64"] if arch in job),
None,
)
log.debug(
f"job: '{job}' name: '{self.pipeline_name}' version: '{version}' distro: '{distro}' distro_version: '{distro_version}' arch: '{arch}'"
)
# Any or all of the variables passed to this function can be None
for cvar in self.ci_pipelines(version, distro, distro_version, arch):
# log.debug(f"self.pipeline_name: {self.pipeline_name} cvar: {cvar}")
if self.pipeline_name and not "default" in self.pipeline_name:
pipeline_vars = self.ci_pipeline_by_name(self.pipeline_name)
else:
pipeline_vars = self.ci_pipelines(
version, distro, distro_version, arch
)
# sys.exit(1)
for cvar in pipeline_vars:
if not cvar in self.trigger_explicit:
log.info("Triggering '%s'", cvar)
self.trigger_explicit.append(cvar)
return True
def kickoff(self):
url = os.getenv("CI_API_V4_URL") or self.CI_API_V4_URL
project_id = os.getenv("CI_PROJECT_ID") or self.CI_PROJECT_ID
dry_run = os.getenv("DRY_RUN") or self.dry_run
no_test = os.getenv("NO_TEST") or self.no_test
no_scan = os.getenv("NO_SCAN") or self.no_scan
no_push = os.getenv("NO_PUSH") or self.no_push
rebuildb = os.getenv("REBUILD_BUILDER") or self.rebuildb
token = os.getenv("CI_JOB_TOKEN")
if not token:
log.warning("CI_JOB_TOKEN is unset!")
ref = os.getenv("CI_COMMIT_REF_NAME") or self.branch
payload = {"token": token, "ref": ref, "variables[TRIGGER]": "true"}
if self.trigger_all:
payload["variables[all]"] = "true"
elif self.trigger_explicit:
for job in self.trigger_explicit:
payload[f"variables[{job}]"] = "true"
if no_scan:
payload[f"variables[NO_SCAN]"] = "true"
if no_test:
payload[f"variables[NO_TEST]"] = "true"
if no_push:
payload[f"variables[NO_PUSH]"] = "true"
if rebuildb:
payload[f"variables[REBUILD_BUILDER]"] = "true"
if self.flavor:
payload[f"variables[FLAVOR]"] = self.flavor
final_url = f"{url}/projects/{project_id}/trigger/pipeline"
log.info("url %s", final_url)
log.info("payload %s", payload)
if not self.dry_run:
r = requests.post(final_url, data=payload)
log.debug("response status code %s", r.status_code)
log.debug("response body %s", r.json())
else:
log.info("In dry-run mode so not making gitlab trigger POST")
def kickoff_from_kitmaker(self):
url = os.getenv("CI_API_V4_URL") or self.CI_API_V4_URL
project_id = os.getenv("CI_PROJECT_ID") or self.CI_PROJECT_ID
dry_run = os.getenv("DRY_RUN") or self.dry_run
no_test = os.getenv("NO_TEST") or self.no_test
no_scan = os.getenv("NO_SCAN") or self.no_scan
no_push = os.getenv("NO_PUSH") or self.no_push
token = os.getenv("CI_JOB_TOKEN")
if not token:
log.warning("CI_JOB_TOKEN is unset!")
ref = os.getenv("CI_COMMIT_REF_NAME") or self.branch
payload = {"token": token, "ref": self.branch, "variables[KITMAKER]": "true"}
if no_scan:
payload[f"variables[NO_SCAN]"] = "true"
if no_test:
payload[f"variables[NO_TEST]"] = "true"
if no_push:
payload[f"variables[NO_PUSH]"] = "true"
if "l4t" in self.flavor:
# FIXME: HACK until these scripts can be made to have proper container image "flavor" support
payload[f"variables[UBUNTU18_04_L4T]"] = "true"
if self.flavor:
payload[f"variables[FLAVOR]"] = self.flavor
payload[f"variables[TRIGGER]"] = "true"
payload[f"variables[RELEASE_LABEL]"] = self.release_label
payload[f"variables[IMAGE_TAG_SUFFIX]"] = f"-{self.candidate_number}"
payload[f"variables[CANDIDATE_URL]"] = self.candidate_url
payload[f"variables[WEBHOOK_URL]"] = self.webhook_url
final_url = f"{url}/projects/{project_id}/trigger/pipeline"
log.info("url %s", final_url)
masked_payload = payload.copy()
masked_payload["token"] = "[ MASKED ]"
log.info("payload %s", masked_payload)
if not self.dry_run:
r = requests.post(final_url, data=payload)
log.debug("response status code %s", r.status_code)
log.debug("response body %s", r.json())
else:
log.info("In dry-run mode so not making gitlab trigger POST")
def main(self):
if self.dry_run:
log.info("Dryrun mode enabled. Not making changes")
if self.parent.shipit_uuid:
self.shipit = ShipitData(self.parent.shipit_uuid)
# Make sure all of our arguments are present
if any(
[
not i
for i in [
self.release_label,
self.candidate_number,
self.candidate_url,
self.webhook_url,
self.branch,
]
]
):
# Plumbum doesn't allow this check
log.error(
"""Missing arguments (one or all): ["--release_label", "--candidate-number", "--candidate_url", "--webhook-url", "--branch"]"""
)
sys.exit(1)
log.debug("Triggering gitlab kitmaker pipeline using shipit source")
self.kickoff_from_kitmaker()
else:
self.check_explicit_trigger()
if self.trigger_all or self.trigger_explicit or self.rebuildb:
self.kickoff()
@Manager.subcommand("push")
class ManagerContainerPush(Manager):
DESCRIPTION = (
"Login and push to the container registries.\n"
"Use either --image-name, --os-name, --os-version, --cuda-version 'to push images' or --readme 'to push readmes'."
)
dry_run = cli.Flag(["-n", "--dry-run"], help="Show output but don't do anything!")
image_name = cli.SwitchAttr(
"--image-name",
str,
excludes=["--readme"],
help="The image name to tag",
default="",
)
distro = cli.SwitchAttr("--os-name", str, help="The distro to use", default=None,)
distro_version = cli.SwitchAttr(
"--os-version", str, help="The distro version", default=None,
)
cuda_version = cli.SwitchAttr(
"--cuda-version",
str,
help="The cuda version to use. Example: '10.1'",
default=None,
)
image_tag_suffix = cli.SwitchAttr(
"--tag-suffix",
str,
help="The suffix to append to the tag name. Example 10.1-base-centos6<suffix>",
default="",
)
pipeline_name = cli.SwitchAttr(
"--pipeline-name",
str,
help="The name of the pipeline the deploy is coming from",
)
tag_manifest = cli.SwitchAttr("--tag-manifest", str, help="A list of tags to push",)
readme = cli.Flag("--readme", help="Path to the README.md",)
flavor = cli.SwitchAttr(
"--flavor",
str,
help="The container configuration to build (limited support).",
default="default",
)
client = None
repos = []
repos_dict = {}
tags = []
key = ""
push_repos = {}
target_repos = []
repo_creds = {}
def setup_repos(self):
# Regular pipeines use this:
self.push_repos = self.get_data(self.parent.manifest, "push_repos")
self.target_repos = self.get_data(self.parent.manifest, self.key, "push_repos")
excluded_repos = self.get_data(
self.parent.manifest,
self.key,
f"{self.distro}{self.distro_version}",
"exclude_repos",
can_skip=True,
)
for repo, metadata in self.push_repos.items():
# log.debug(repo)
# log.debug(self.target_repos)
if repo not in self.target_repos:
log.debug(f"IN HERE: {repo}")
continue
if "gitlab-master" in repo:
# Images have already been pushed to gitlab by this point
log.debug(f"Skipping push to {repo}")
continue
if metadata.get("only_if", False) and not os.getenv(metadata["only_if"]):
log.info("repo: '%s' only_if requirement not satisfied", repo)
continue
if self.push_repos and repo not in self.push_repos:
log.info("repo: '%s' is excluded for this image", repo)
continue
if excluded_repos and repo in excluded_repos:
log.info("repo: '%s' is excluded for this image", repo)
continue
user = os.getenv(metadata["user"])
if not user:
user = metadata["user"]
passwd = os.getenv(metadata["pass"])
if not passwd:
passwd = metadata["pass"]
registry = metadata["image_name"]
self.repo_creds[registry] = {"user": user, "pass": passwd}
self.repos.append(registry)
if not self.repos:
log.fatal(
"Could not retrieve container image repo credentials. Environment not set?"
)
sys.exit(1)
# sys.exit(1)
@retry(
(ImagePushRetry),
tries=HTTP_RETRY_ATTEMPTS,
delay=HTTP_RETRY_WAIT_SECS,
logger=log,
)
def push_images(self):
with open(self.tag_manifest) as f:
tags = f.readlines()
stags = [x.strip() for x in tags]
for tag in stags:
if not tag:
continue
log.info("Processing image: %s:%s", self.image_name, tag)
# pp(self.repo_creds)
for repo in self.repos:
log.info("COPYING to: %s:%s", repo, tag)
if self.dry_run:
log.debug("dry-run; not copying")
continue
if shellcmd(
"skopeo",
(
"copy",
"--all",
"--src-creds",
"{}:{}".format("gitlab-ci-token", os.getenv("CI_JOB_TOKEN")),
"--dest-creds",
"{}:{}".format(
self.repo_creds[repo]["user"],
self.repo_creds[repo]["pass"],
),
f"docker://{self.image_name}:{tag}",
f"docker://{repo}:{tag}",
"--retry-times",
"2",
# "--debug",
),
):
log.info("Copy was successful")
else:
raise ImagePushRetry()
def push_readmes(self):
if self.dry_run:
log.debug(
f"dry-run mode: otherwise; docker pushrm could happen for -> {self.repos_dict['docker.io']}"
)
else:
for readme, repo in self.repos_dict["docker.io"].items():
# docker pushrm
result = shellcmd(
"docker",
("pushrm", "-f", f"doc/{readme}", f"{repo}"),
printOutput=False,
returnOut=True,
)
if result.returncode > 0:
log.error(result.stderr)
log.error("Docker pushrm was unsuccessful for %s", repo)
else:
log.info("Docker pushrm was successful for %s", repo)
def main(self):
log.debug("dry-run: %s", self.dry_run)
if self.readme:
self.key = f"push_repos"
self.push_readmes()
else:
self.key = f"cuda_v{self.cuda_version}"
if self.pipeline_name:
self.key = f"cuda_v{self.cuda_version}_{self.pipeline_name}"
self.client = docker.DockerClient(
base_url="unix://var/run/docker.sock", timeout=600
)
self.setup_repos()
self.push_images()
log.info("Done")
@Manager.subcommand("generate")
class ManagerGenerate(Manager):
DESCRIPTION = "Generate Dockerfiles from templates."
cuda = {}
dist_base_path = None # pathlib object. The parent "base" path of output_path.
output_manifest_path = None # pathlib object. The path to save the shipit manifest.
output_path = {} # The product of parsing the input templates
key = ""
cuda_version_is_release_label = False
cuda_version_regex = re.compile(r"cuda_v([\d\.]+)(?:_(\w+))?$")
product_name = ""
candidate_number = ""
template_env = Environment(
extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"],
trim_blocks=True,
lstrip_blocks=True,
)
generate_ci = cli.Flag(["--ci"], help="Generate the gitlab pipelines only.",)
generate_all = cli.Flag(["--all"], help="Generate all of the templates.",)
generate_readme = cli.Flag(["--readme"], help="Generate all readmes.",)
generate_tag = cli.Flag(
["--tags"], help="Generate all supported and unsupported tag lists.",
)
distro = cli.SwitchAttr(
"--os-name",
str,
group="Targeted",
excludes=["--all", "--readme", "--tags"],
help="The distro to use.",
default=None,
)
distro_version = cli.SwitchAttr(
"--os-version",
str,
group="Targeted",
excludes=["--all", "--readme", "--tags"],
help="The distro version",
default=None,
)
cuda_version = cli.SwitchAttr(
"--cuda-version",
str,
excludes=["--all", "--readme", "--tags"],
group="Targeted",
help="[DEPRECATED for newer cuda versions!] The cuda version to use. Example: '11.2'",
default=None,
)
release_label = cli.SwitchAttr(
"--release-label",
str,
excludes=["--readme", "--tags"],
group="Targeted",
help="The cuda version to use. Example: '11.2.0'",
default=None,
)
pipeline_name = cli.SwitchAttr(
"--pipeline-name",
str,
excludes=["--all", "--readme", "--tags"],
group="Targeted",
help="Use a pipeline name for manifest matching.",
default="default",
)
flavor = cli.SwitchAttr(
"--flavor", str, help="Identifier passed to template context.",
)
#
# WAR ONLY USED FOR L4T and will be removed in the future
#
cudnn_json_path = cli.SwitchAttr(
"--cudnn-json-path",
str,
group="L4T",
help="File path to json encoded file containing cudnn package metadata.",
)
def supported_distro_list_by_cuda_version(self, version):
if not version:
return
distros = ["ubuntu", "ubi", "centos"]
keys = self.parent.manifest[self.key].keys()
# There are other keys in the cuda field other than distros, we need to strip those out
def get_distro_name(name):
r = re.compile("[a-zA-Z]+")
return r.findall(name)[0]
return [f for f in keys if get_distro_name(f) in distros]
def supported_arch_list(self):
ls = []
for k in glom.glom(
self.parent.manifest,
glom.Path(self.key, f"{self.distro}{self.distro_version}"),
):
if k in ["x86_64", "ppc64le", "arm64"]:
ls.append(k)
return ls
def cudnn_versions(self, arch):
obj = []
for k, v in self.cuda[arch]["components"].items():
if k.startswith("cudnn") and v:
obj.append(k)
return obj
def matched(self, key):
match = self.cuda_version_regex.match(key)
if match:
return match
# extracts arbitrary keys and inserts them into the templating context
def extract_keys(self, val, arch=None):
rgx = re.compile(r"^v\d+\.\d")
for k, v in val.items():
if rgx.match(k):
# Do not copy cuda version keys
continue
# These top level keys should be ignored since they are processed elsewhere
if k in [
"exclude_repos",
"components",
*self.supported_arch_list(),
*self.supported_distro_list_by_cuda_version(
self.cuda_version or self.release_label
),
]:
continue
if arch:
self.cuda[arch][k] = v
else:
self.cuda[k] = v
# For cudnn templates, we need a custom template context
def output_cudnn_template(self, cudnn_version_name, input_template, output_path):
new_ctx = {
"cudnn": self.cuda["cudnn"],
"version": self.cuda["version"],
"image_tag_suffix": self.cuda["image_tag_suffix"],
"os": self.cuda["os"],
"ml_repo_url": self.ml_repo_url_for_distro(),
}
for arch in self.arches:
if not cudnn_version_name in self.cuda[arch]["components"]:
continue
cudnn_manifest = self.cuda[arch]["components"][cudnn_version_name]
if cudnn_manifest:
if "source" in cudnn_manifest:
cudnn_manifest["basename"] = os.path.basename(
cudnn_manifest["source"]
)
cudnn_manifest["dev"]["basename"] = os.path.basename(
cudnn_manifest["dev"]["source"]
)
new_ctx[arch] = {}
new_ctx[arch]["cudnn"] = cudnn_manifest
log.debug(f"cudnn template context {pp(new_ctx, output=False)}")
self.output_template(
input_template=input_template, output_path=output_path, ctx=new_ctx
)
def output_template(self, input_template, output_path, ctx=None):
ctx = ctx if ctx is not None else self.cuda
def write_template(arch=None):
with open(input_template) as f:
log.debug("Processing template %s", input_template)
new_output_path = pathlib.Path(output_path)
extension = ".j2"
name = input_template.name
if "dockerfile" in input_template.name.lower():
new_filename = "Dockerfile"
elif ".jinja" in str(input_template):
extension = ".jinja"
new_filename = (
name[: -len(extension)] if name.endswith(extension) else name
)
else:
new_filename = (
name[len("base-") : -len(extension)]
if name.startswith("base-") and name.endswith(extension)
else name
)
if arch:
new_filename += f"-{arch}"
template = self.template_env.from_string(f.read())
if not new_output_path.exists():
log.debug(f"Creating {new_output_path}")
new_output_path.mkdir(parents=True)
log.info(f"Writing {new_output_path}/{new_filename}")
with open(f"{new_output_path}/{new_filename}", "w") as f2:
f2.write(template.render(cuda=ctx))
# sys.exit(1)
if any(f in input_template.as_posix() for f in ["cuda.repo", "ml.repo"]):
for arch in self.arches:
ctx["target_arch"] = arch
if "arm64" in arch:
ctx["target_arch"] = "sbsa"
write_template(arch)
else:
write_template()
def ml_repo_url_for_distro(self):
"""Returns the machine learning repo url for a distro. None if no url is found."""
return self.get_data(
self.parent.manifest,
self.key,
f"{self.distro}{self.distro_version}",
"ml_repo_url",
can_skip=True,
)
def use_ml_repo_for_distro(self):
"""Returns the machine learning repo url for an arch"""
if not self.ml_repo_url_for_distro():
log.warning(
f"ml_repo_url not set for {self.key}.{self.distro}{self.distro_version} in manifest"
)
return False
return True
def prepare_context(self):
# checks the cudnn components and ensures at least one is installed from the public "machine-learning" repo
conf = self.parent.manifest
if self.release_label:
major = self.release_label.split(".")[0]
minor = self.release_label.split(".")[1]
else:
major = self.cuda_version.split(".")[0]
minor = self.cuda_version.split(".")[1]
self.image_tag_suffix = self.get_data(
conf,
self.key,
f"{self.distro}{self.distro_version}",
"image_tag_suffix",
can_skip=True,
)
if not self.image_tag_suffix:
self.image_tag_suffix = ""
# The templating context. This data structure is used to fill the templates.
self.cuda = {
"flavor": self.flavor,
"version": {
"release_label": self.cuda_version,