This repository has been archived by the owner on Oct 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
distgit.py
2684 lines (2275 loc) · 132 KB
/
distgit.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
import asyncio
import copy
import errno
import glob
import hashlib
import io
import json
import logging
import os
import pathlib
import re
import shutil
import sys
import time
import traceback
from datetime import date, datetime
from multiprocessing import Event, Lock
from typing import Dict, List, Optional, Tuple, Union
import aiofiles
import bashlex
import requests
import yaml
from dockerfile_parse import DockerfileParser
from tenacity import (before_sleep_log, retry, retry_if_not_result,
stop_after_attempt, wait_fixed)
import doozerlib
from doozerlib import assertion, constants, exectools, logutil, state, util
from doozerlib.assembly import AssemblyTypes
from doozerlib.brew import get_build_objects, watch_task
from doozerlib.dblib import Record
from doozerlib.exceptions import DoozerFatalError
from doozerlib.model import ListModel, Missing, Model
from doozerlib.osbs2_builder import OSBS2Builder
from doozerlib.pushd import Dir
from doozerlib.release_schedule import ReleaseSchedule
from doozerlib.rpm_utils import parse_nvr
from doozerlib.source_modifications import SourceModifierFactory
from doozerlib.util import convert_remote_git_to_https, yellow_print
# doozer used to be part of OIT
OIT_COMMENT_PREFIX = '#oit##'
OIT_BEGIN = '##OIT_BEGIN'
OIT_END = '##OIT_END'
CONTAINER_YAML_HEADER = """
# This file is managed by doozer: https://github.com/openshift/doozer
# operated by the OpenShift Automated Release Tooling team (#aos-art on CoreOS Slack).
# Any manual changes will be overwritten by doozer on the next build.
#
# See https://source.redhat.com/groups/public/container-build-system/container_build_system_wiki/odcs_integration_with_osbs
# for more information on maintaining this file and the format and examples
---
"""
# Always ignore these files/folders when rebasing into distgit
# May be added to based on group/image config
BASE_IGNORE = [".git", ".oit"]
logger = logutil.getLogger(__name__)
def recursive_overwrite(src, dest, ignore=set()):
"""
Use rsync to copy one file tree to a new location
"""
exclude = ' --exclude .git '
for i in ignore:
exclude += ' --exclude="{}" '.format(i)
cmd = 'rsync -av {} {}/ {}/'.format(exclude, src, dest)
exectools.cmd_assert(cmd, retries=3)
def pull_image(url):
logger.info("Pulling image: %s" % url)
def wait(_):
logger.info("Error pulling image %s -- retrying in 60 seconds" % url)
time.sleep(60)
exectools.retry(
3, wait_f=wait,
task_f=lambda: exectools.cmd_gather(["podman", "pull", url])[0] == 0)
def map_image_name(name, image_map):
for match, replacement in image_map.items():
if name.find(match) != -1:
return name.replace(match, replacement)
return name
class DistGitRepo(object):
def __init__(self, metadata, autoclone=True):
self.metadata = metadata
self.config: Model = metadata.config
self.runtime: "doozerlib.runtime.Runtime" = metadata.runtime
self.name: str = self.metadata.name
self.distgit_dir: str = None
self.dg_path: pathlib.Path = None
self.build_status = False
self.push_status = False
self.branch: str = self.runtime.branch
self.sha: str = None
self.source_sha: str = None
self.source_full_sha: str = None
self.source_latest_tag: str = None
self.source_date_epoch = None
self.actual_source_url: str = None
self.public_facing_source_url: str = None
self.uuid_tag = None
# If this is a standard release, private_fix will be set to True if the source contains
# embargoed (private) CVE fixes. Defaulting to None which means the value should be determined while rebasing.
self.private_fix = None
if self.runtime.assembly_type != AssemblyTypes.STREAM:
# Only stream releases can have embargoed workflows.
self.private_fix = False
# If we are rebasing, this map can be populated with
# variables acquired from the source path.
self.env_vars_from_source = None
# Allow the config yaml to override branch
# This is primarily useful for a sync only group.
if self.config.distgit.branch is not Missing:
self.branch = self.config.distgit.branch
self.logger = self.metadata.logger
# Initialize our distgit directory, if necessary
if autoclone:
self.clone(self.runtime.distgits_dir, self.branch)
def pull_sources(self):
"""
Pull any distgit sources (use only after after clone)
"""
with Dir(self.distgit_dir):
sources_file: pathlib.Path = self.dg_path.joinpath('sources')
if not sources_file.exists():
self.logger.debug('No sources file exists; skipping rhpkg sources')
return
exectools.cmd_assert('rhpkg sources')
def clone(self, distgits_root_dir, distgit_branch):
if self.metadata.prevent_cloning:
raise IOError(f'Attempt to clone downstream {self.metadata.distgit_key} after cloning disabled; a regression has been introduced.')
with Dir(distgits_root_dir):
namespace_dir = os.path.join(distgits_root_dir, self.metadata.namespace)
# It is possible we have metadata for the same distgit twice in a group.
# There are valid scenarios (when they represent different branches) and
# scenarios where this is a user error. In either case, make sure we
# don't conflict by stomping on the same git directory.
self.distgit_dir = os.path.join(namespace_dir, self.metadata.distgit_key)
self.dg_path = pathlib.Path(self.distgit_dir)
fake_distgit = (self.runtime.local and 'content' in self.metadata.config)
if os.path.isdir(self.distgit_dir):
self.logger.info("Distgit directory already exists; skipping clone: %s" % self.distgit_dir)
if self.runtime.upcycle:
self.logger.info("Refreshing source for '{}' due to --upcycle".format(self.distgit_dir))
with Dir(self.distgit_dir):
exectools.cmd_assert('git fetch --all', retries=3)
exectools.cmd_assert('git reset --hard @{upstream}', retries=3)
else:
# Make a directory for the distgit namespace if it does not already exist
try:
os.mkdir(namespace_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
if fake_distgit and self.runtime.command in ['images:rebase', 'images:update-dockerfile']:
cmd_list = ['mkdir', '-p', self.distgit_dir]
self.logger.info("Creating local build dir: {}".format(self.distgit_dir))
exectools.cmd_assert(cmd_list)
else:
if self.runtime.command == 'images:build':
yellow_print('Warning: images:rebase was skipped and therefore your '
'local build will be sourced from the current dist-git '
'contents and not the typical GitHub source. '
)
self.logger.info("Cloning distgit repository [branch:%s] into: %s" % (distgit_branch, self.distgit_dir))
# Has the user specified a specific commit to checkout from distgit on the command line?
distgit_commitish = self.runtime.downstream_commitish_overrides.get(self.metadata.distgit_key, None)
timeout = str(self.runtime.global_opts['rhpkg_clone_timeout'])
rhpkg_clone_depth = int(self.runtime.global_opts.get('rhpkg_clone_depth', '0'))
if self.metadata.namespace == 'containers':
# Containers don't generally require distgit lookaside. We can rely on normal
# git clone & leverage git caches to greatly accelerate things if the user supplied it.
gitargs = ['--branch', distgit_branch]
if not distgit_commitish:
gitargs.append('--single-branch')
if not distgit_commitish and rhpkg_clone_depth > 0:
gitargs.extend(["--depth", str(rhpkg_clone_depth)])
self.runtime.git_clone(self.metadata.distgit_remote_url(), self.distgit_dir, gitargs=gitargs,
set_env=constants.GIT_NO_PROMPTS, timeout=timeout)
else:
# Use rhpkg -- presently no idea how to cache.
cmd_list = ["timeout", timeout]
cmd_list.append("rhpkg")
if self.runtime.rhpkg_config_lst:
cmd_list.extend(self.runtime.rhpkg_config_lst)
if self.runtime.user is not None:
cmd_list.append("--user=%s" % self.runtime.user)
cmd_list.extend(["clone", self.metadata.qualified_name, self.distgit_dir])
cmd_list.extend(["--branch", distgit_branch])
if not distgit_commitish and rhpkg_clone_depth > 0:
cmd_list.extend(["--depth", str(rhpkg_clone_depth)])
# Clone the distgit repository. Occasional flakes in clone, so use retry.
exectools.cmd_assert(cmd_list, retries=3, set_env=constants.GIT_NO_PROMPTS)
if distgit_commitish:
with Dir(self.distgit_dir):
exectools.cmd_assert(f'git checkout {distgit_commitish}')
self.sha, _ = exectools.cmd_assert(["git", "-C", self.distgit_dir, "rev-parse", "HEAD"], strip=True)
def merge_branch(self, target, allow_overwrite=False):
self.logger.info('Switching to branch: {}'.format(target))
cmd = ["rhpkg"]
if self.runtime.rhpkg_config_lst:
cmd.extend(self.runtime.rhpkg_config_lst)
cmd.extend(["switch-branch", target])
exectools.cmd_assert(cmd, retries=3)
if not allow_overwrite:
if os.path.isfile('Dockerfile') or os.path.isdir('.oit'):
raise IOError('Unable to continue merge. Dockerfile found in target branch. Use --allow-overwrite to force.')
self.logger.info('Merging source branch history over current branch')
msg = 'Merge branch {} into {}'.format(self.branch, target)
exectools.cmd_assert(
cmd=['git', 'merge', '--allow-unrelated-histories', '-m', msg, self.branch],
retries=3,
on_retry=['git', 'reset', '--hard', target], # in case merge failed due to storage
)
def has_source(self):
"""
Check whether this dist-git repo has source content
"""
return "git" in self.config.content.source or \
"alias" in self.config.content.source
def source_path(self):
"""
:return: Returns the directory containing the source which should be used to populate distgit. This includes
the source.path subdirectory if the metadata includes one.
"""
source_root = self.runtime.resolve_source(self.metadata)
sub_path = self.config.content.source.path
path = source_root
if sub_path is not Missing:
path = os.path.join(source_root, sub_path)
assertion.isdir(path, "Unable to find path for source [%s] for config: %s" % (path, self.metadata.config_filename))
return path
def source_repo_path(self):
"""
:return: Returns the directory containing the root of the cloned source repo.
"""
path = self.runtime.resolve_source(self.metadata)
assertion.isdir(path, "Unable to find path for source [%s] for config: %s" % (path, self.metadata.config_filename))
return path
def _get_diff(self):
return None # to actually record a diff, child classes must override this function
def commit(self, cmdline_commit_msg: str, commit_attributes: Optional[Dict[str, Union[int, str, bool]]] = None, log_diff=False):
if self.runtime.local:
return '' # no commits if local
with Dir(self.distgit_dir):
commit_payload: Dict[str, Union[int, str, bool]] = {
'MaxFileSize': 100 * 1024 * 1024, # 100MB push limit; see https://source.redhat.com/groups/public/release-engineering/release_engineering_rcm_wiki/dist_git_update_hooks
'jenkins.url': None if 'unittest' in sys.modules.keys() else os.getenv('BUILD_URL'), # Get the Jenkins build URL if available, but ignore if this is a unit test run
}
if self.dg_path: # Might not be set if this is a unittest
df_path = self.dg_path.joinpath('Dockerfile')
if df_path.exists():
# This is an image distgit commit, we can help the callers by reading in env variables for the commit message.
# RPM commits are expected to pass these values in directly in commit_attributes.
dfp = DockerfileParser(str(df_path))
for var_name in ['version', 'release', 'io.openshift.build.source-location', 'io.openshift.build.commit.id']:
commit_payload[var_name] = dfp.labels.get(var_name, None)
if commit_attributes:
commit_payload.update(commit_attributes)
# The commit should be a valid yaml document so we can retrieve details
# programmatically later. The human specified portion of the commit is
# included in comments above the yaml payload.
cmdline_commit_msg = cmdline_commit_msg.strip().replace('\n', '\n# ') # If multiple lines are specified, split across commented lines.
commit_msg = f'# {cmdline_commit_msg}\n' # Any message specified in '-m' during rebase
commit_msg += yaml.safe_dump(commit_payload, default_flow_style=False, sort_keys=True)
self.logger.info("Adding commit to local repo:\n{}".format(commit_msg))
if log_diff:
diff = self._get_diff()
if diff and diff.strip():
self.runtime.add_distgits_diff(self.metadata.distgit_key, diff)
# commit changes; if these flake there is probably not much we can do about it
exectools.cmd_assert(["git", "add", "-A", "."])
exectools.cmd_assert(["git", "commit", "--allow-empty", "-m", commit_msg])
rc, sha, err = exectools.cmd_gather(["git", "rev-parse", "HEAD"])
assertion.success(rc, "Failure fetching commit SHA for {}".format(self.distgit_dir))
self.sha = sha.strip()
return self.sha
def cgit_file_available(self, filename: str = ".oit/signed.repo") -> Tuple[bool, str]:
""" Check if the specified file associated with the commit hash pushed to distgit is available on cgit
:return: (existence, url)
"""
assert self.sha is not None
self.logger.debug("Checking if distgit commit %s is available on cgit...", self.sha)
url = self.metadata.cgit_file_url(filename, commit_hash=self.sha, branch=self.branch)
response = requests.head(url)
if response.status_code == 404:
self.logger.debug("Distgit commit %s is not available on cgit", self.sha)
return False, url
response.raise_for_status()
self.logger.debug("Distgit commit %s is available on cgit", self.sha)
return True, url
@retry(retry=retry_if_not_result(lambda r: r), wait=wait_fixed(10), stop=stop_after_attempt(60), before_sleep=before_sleep_log(logger, logging.WARNING))
def wait_on_cgit_file(self, filename: str = ".oit/signed.repo"):
""" Poll cgit for the specified file associated with the commit hash pushed to distgit
"""
existence, _ = self.cgit_file_available(filename)
return existence
def push(self):
with Dir(self.distgit_dir):
self.logger.info("Pushing distgit repository %s", self.name)
try:
# When initializing new release branches, a large amount of data needs to
# be pushed. If every distgit within a release is being pushed at the same
# time, a single push invocation can take hours to complete -- making the
# timeout value counterproductive. Limit to 5 simultaneous pushes.
with self.runtime.get_named_semaphore('rhpkg::push', count=5):
timeout = str(self.runtime.global_opts['rhpkg_push_timeout'])
exectools.cmd_assert("timeout {} rhpkg push".format(timeout), retries=3)
# rhpkg will create but not push tags :(
# Not asserting this exec since this is non-fatal if a tag already exists,
# and tags in dist-git can't be --force overwritten
exectools.cmd_gather(['timeout', '60', 'git', 'push', '--tags'])
except IOError as e:
return (self.metadata, repr(e))
return (self.metadata, True)
@exectools.limit_concurrency(limit=5)
async def push_async(self):
self.logger.info("Pushing distgit repository %s", self.name)
# When initializing new release branches, an large amount of data needs to
# be pushed. If every distgit within a release is being pushed at the same
# time, a single push invocation can take hours to complete -- making the
# timeout value counterproductive. Limit to 5 simultaneous pushes.
timeout = str(self.runtime.global_opts['rhpkg_push_timeout'])
await exectools.cmd_assert_async(["timeout", f"{timeout}", "git", "push", "--follow-tags"], cwd=self.distgit_dir, retries=3)
def tag(self, version, release):
if self.runtime.local:
return '' # no tags if local
if version is None:
return
tag = '{}'.format(version)
if release is not None:
tag = '{}-{}'.format(tag, release)
with Dir(self.distgit_dir):
self.logger.info("Adding tag to local repo: {}".format(tag))
exectools.cmd_gather(["git", "tag", "-f", tag, "-m", tag])
class ImageDistGitRepo(DistGitRepo):
source_labels = dict(
old=dict(
sha='io.openshift.source-repo-commit',
source='io.openshift.source-repo-url',
source_commit='io.openshift.source-commit-url',
),
now=dict(
sha='io.openshift.build.commit.id',
source='io.openshift.build.source-location',
source_commit='io.openshift.build.commit.url',
),
)
def __init__(self, metadata, autoclone=True,
source_modifier_factory=SourceModifierFactory()):
self.org_image_name = None
self.org_version = None
self.org_release = None
super(ImageDistGitRepo, self).__init__(metadata, autoclone=autoclone)
self.build_lock = Lock()
self.build_lock.acquire()
self.rebase_event = Event()
self.rebase_status = False
self.logger: logging.Logger = metadata.logger
self.source_modifier_factory = source_modifier_factory
def clone(self, distgits_root_dir, distgit_branch):
super(ImageDistGitRepo, self).clone(distgits_root_dir, distgit_branch)
self._read_master_data()
def _get_diff(self):
rc, out, _ = exectools.cmd_gather(["git", "-C", self.distgit_dir, "diff", "Dockerfile"])
assertion.success(rc, 'Failed fetching distgit diff')
return out
@property
def image_build_method(self):
build_method = self.runtime.group_config.default_image_build_method or "imagebuilder"
# If our config specifies something, override with that.
if self.config.image_build_method is not Missing:
build_method = self.config.image_build_method
return build_method
def _write_fetch_artifacts(self):
# Write fetch-artifacts-url.yaml for OSBS to fetch external artifacts
# See https://osbs.readthedocs.io/en/osbs_ocp3/users.html#using-artifacts-from-koji-or-project-newcastle-aka-pnc
config_value = None
if self.config.content.source.artifacts.from_urls is not Missing:
config_value = self.config.content.source.artifacts.from_urls.primitive()
path = self.dg_path.joinpath('fetch-artifacts-url.yaml')
if path.exists(): # upstream provides its own fetch-artifacts-url.yaml
if not config_value:
self.logger.info("Use fetch-artifacts-url.yaml provided by upstream.")
return
raise ValueError("Image config option content.source.artifacts.from_urls cannot be used if upstream source has fetch-artifacts-url.yaml")
if not config_value:
return # fetch-artifacts-url.yaml is not needed.
self.logger.info('Generating fetch-artifacts-url.yaml')
with path.open("w") as f:
yaml.safe_dump(config_value, f)
def _write_osbs_image_config(self, version: str):
# Writes OSBS image config (container.yaml).
# For more info about the format, see https://osbs.readthedocs.io/en/latest/users.html#image-configuration.
self.logger.info('Generating container.yaml')
container_config = self._generate_osbs_image_config(version)
if 'compose' in container_config:
self.logger.info("Rebasing with ODCS support")
else:
self.logger.info("Rebasing without ODCS support")
# generate yaml data with header
content_yml = yaml.safe_dump(container_config, default_flow_style=False)
with self.dg_path.joinpath('container.yaml').open('w', encoding="utf-8") as rc:
rc.write(CONTAINER_YAML_HEADER + content_yml)
def _generate_osbs_image_config(self, version: str) -> Dict:
"""
Generates OSBS image config (container.yaml).
Returns a dict for the config.
Example in image yml file:
odcs:
packages:
mode: auto (default) | manual
# auto - If container.yaml with packages is given from source, use them.
# Otherwise all packages with from the Koji build tag will be included.
# manual - only use list below
list:
- package1
- package2
arches: # Optional list of image specific arches. If given, it must be a subset of group arches.
- x86_64
- s390x
container_yaml: ... # verbatim container.yaml content (see https://source.redhat.com/groups/public/container-build-system/container_build_system_wiki/odcs_integration_with_osbs)
"""
# list of platform (architecture) names to build this image for
arches = self.metadata.get_arches()
# override image config with this dict
config_overrides = {}
if self.config.container_yaml is not Missing:
config_overrides = copy.deepcopy(self.config.container_yaml.primitive())
# Cachito will be configured if `cachito.enabled` is True in image meta, `content.source.pkg_managers` is set in image meta,
# or `cachito.enabled` is True in group config.
# https://osbs.readthedocs.io/en/latest/users.html#remote-sources
cachito_enabled = False
if self.config.cachito.enabled:
cachito_enabled = True
elif self.config.cachito.enabled is Missing:
if isinstance(self.config.content.source.pkg_managers, ListModel) or self.runtime.group_config.cachito.enabled:
cachito_enabled = True
if cachito_enabled and not self.has_source():
self.logger.warning("Cachito integration for distgit-only image %s is not supported.", self.name)
cachito_enabled = False
if cachito_enabled:
if config_overrides.get("go", {}).get("modules"):
raise ValueError(f"Cachito integration is enabled for image {self.name}. Specifying `go.modules` in `container.yaml` is not allowed.")
pkg_managers = [] # Note if cachito is enabled but `pkg_managers` is set to an empty array, Cachito will provide the sources with no package manager magic.
if isinstance(self.config.content.source.pkg_managers, ListModel):
# Use specified package managers
pkg_managers = self.config.content.source.pkg_managers.primitive()
elif self.config.content.source.pkg_managers in [Missing, None]:
# Auto-detect package managers
pkg_managers = self._detect_package_manangers()
else:
raise ValueError(f"Invalid content.source.pkg_managers config for image {self.name}: {self.config.content.source.pkg_managers}")
# Configure Cachito flags
# https://github.com/containerbuildsystem/cachito#flags
flags = []
if isinstance(self.config.cachito.flags, ListModel):
flags = self.config.cachito.flags.primitive()
elif isinstance(self.runtime.group_config.cachito.flags, ListModel):
flags = set(self.runtime.group_config.cachito.flags.primitive())
if 'gomod' not in pkg_managers:
# Remove gomod related flags if gomod is not used.
flags -= {"cgo-disable", "gomod-vendor", "gomod-vendor-check"}
elif not self.dg_path.joinpath('vendor').is_dir():
# Remove gomod-vendor-check flag if vendor/ is not present when gomod is used
flags -= {"gomod-vendor-check"}
flags = list(flags)
remote_source = {
'repo': convert_remote_git_to_https(self.actual_source_url),
'ref': self.source_full_sha,
'pkg_managers': pkg_managers,
}
if flags:
remote_source['flags'] = flags
# Allow user to customize `packages` option for Cachito configuration.
# See https://osbs.readthedocs.io/en/osbs_ocp3/users.html#remote-source-keys for details.
if self.config.cachito.packages is not Missing:
remote_source['packages'] = self.config.cachito.packages.primitive()
elif self.config.content.source.path: # source is in subdirectory
remote_source['packages'] = {pkg_manager: [{"path": self.config.content.source.path}] for pkg_manager in pkg_managers}
config_overrides.update({
'remote_sources': [
{
'name': 'cachito-gomod-with-deps', # The remote source name is always `cachito-gomod-with-deps` for backward compatibility even if gomod is not used.
'remote_source': remote_source,
}
]
})
if self.image_build_method is not Missing and self.image_build_method != "osbs2":
config_overrides['image_build_method'] = self.image_build_method
if arches:
config_overrides.setdefault('platforms', {})['only'] = arches
# Request OSBS to apply specified tags to the newly-built image as floating tags.
# See https://osbs.readthedocs.io/en/latest/users.html?highlight=tags#image-tags
#
# Include the UUID in the tags. This will allow other images being rebased
# to have a known tag to refer to this image if they depend on it - even
# before it is built.
floating_tags = {f"{version}.{self.runtime.uuid}"}
if self.runtime.assembly:
floating_tags.add(f"assembly.{self.runtime.assembly}")
vsplit = version.split(".") # Split the version number: v4.3.4 => [ 'v4', '3, '4' ]
if len(vsplit) > 1:
floating_tags.add(f"{vsplit[0]}.{vsplit[1]}")
if len(vsplit) > 2:
floating_tags.add(f"{vsplit[0]}.{vsplit[1]}.{vsplit[2]}")
if self.metadata.config.additional_tags:
floating_tags |= set(self.metadata.config.additional_tags)
if floating_tags:
config_overrides["tags"] = sorted(floating_tags)
if not self.runtime.group_config.doozer_feature_gates.odcs_enabled and not self.runtime.odcs_mode:
# ODCS mode is not enabled
return config_overrides
odcs = self.config.odcs
if odcs is Missing:
# image yml doesn't have `odcs` field defined
if not self.runtime.group_config.doozer_feature_gates.odcs_aggressive:
# Doozer's odcs_aggressive feature gate is off, disable ODCS mode for this image
return config_overrides
self.logger.warning("Enforce ODCS auto mode because odcs_aggressive feature gate is on")
package_mode = odcs.packages.get('mode', 'auto')
valid_package_modes = ['auto', 'manual']
if package_mode not in valid_package_modes:
raise ValueError('odcs.packages.mode must be one of {}'.format(', '.join(valid_package_modes)))
# generate container.yaml content for ODCS
config = {}
if self.has_source(): # if upstream source provides container.yaml, load it.
source_container_yaml = os.path.join(self.source_path(), 'container.yaml')
if os.path.isfile(source_container_yaml):
with open(source_container_yaml, 'r') as scy:
config = yaml.full_load(scy)
# ensure defaults
config.setdefault('compose', {}).setdefault('pulp_repos', True)
# create package list for ODCS, see https://osbs.readthedocs.io/en/latest/users.html#compose
if package_mode == 'auto':
if isinstance(config["compose"].get("packages"), list):
# container.yaml with packages was given from source
self.logger.info("Use ODCS package list from source")
else:
config["compose"]["packages"] = [] # empty list composes all packages from the current Koji target
elif package_mode == 'manual':
if not odcs.packages.list:
raise ValueError('odcs.packages.mode == manual but none specified in odcs.packages.list')
config["compose"]["packages"] = list(odcs.packages.list)
# apply overrides
config.update(config_overrides)
return config
def _detect_package_manangers(self):
""" Detect and return package managers used by the source
:return: a list of package managers
"""
if not self.dg_path or not self.dg_path.is_dir():
raise FileNotFoundError(f"Distgit directory for image {self.name} hasn't been cloned.")
pkg_manager_files = {
"gomod": ["go.mod"],
"npm": ["npm-shrinkwrap.json", "package-lock.json"],
"pip": ["requirements.txt", "requirements-build.txt"],
"yarn": ["yarn.lock"],
}
pkg_managers: List[str] = []
for pkg_manager, files in pkg_manager_files.items():
if any(self.dg_path.joinpath(file).is_file() for file in files):
pkg_managers.append(pkg_manager)
return pkg_managers
def _write_cvp_owners(self):
"""
The Container Verification Pipeline will notify image owners when their image is
not passing CVP tests. ART knows these owners and needs to write them into distgit
for CVP to find.
:return:
"""
self.logger.debug("Generating cvp-owners.yml for {}".format(self.metadata.distgit_key))
with self.dg_path.joinpath('cvp-owners.yml').open('w', encoding="utf-8") as co:
if self.config.owners: # Not missing and non-empty
# only spam owners on failure; ref. https://red.ht/2x0edYd
owners = {owner: "FAILURE" for owner in self.config.owners}
yaml.safe_dump(owners, co, default_flow_style=False)
def _generate_repo_conf(self):
"""
Generates a repo file in .oit/repo.conf
"""
self.logger.debug("Generating repo file for Dockerfile {}".format(self.metadata.distgit_key))
# Make our metadata directory if it does not exist
util.mkdirs(self.dg_path.joinpath('.oit'))
repos = self.runtime.repos
enabled_repos = self.config.get('enabled_repos', [])
non_shipping_repos = self.config.get('non_shipping_repos', [])
for t in repos.repotypes:
with self.dg_path.joinpath('.oit', f'{t}.repo').open('w', encoding="utf-8") as rc:
content = repos.repo_file(t, enabled_repos=enabled_repos)
rc.write(content)
with self.dg_path.joinpath('content_sets.yml').open('w', encoding="utf-8") as rc:
rc.write(repos.content_sets(enabled_repos=enabled_repos, non_shipping_repos=non_shipping_repos))
def _read_master_data(self):
with Dir(self.distgit_dir):
self.org_image_name = None
self.org_version = None
self.org_release = None
# Read in information about the image we are about to build
dockerfile = os.path.join(Dir.getcwd(), 'Dockerfile')
if os.path.isfile(dockerfile):
dfp = DockerfileParser(path=dockerfile)
self.org_image_name = dfp.labels.get("name")
self.org_version = dfp.labels.get("version")
self.org_release = dfp.labels.get("release") # occasionally no release given
def push_image(self, tag_list, push_to_defaults, additional_registries=[], version_release_tuple=None,
push_late=False, dry_run=False, registry_config_dir=None, filter_by_os=None):
"""
Pushes the most recent image built for this distgit repo. This is
accomplished by looking at the 'version' field in the Dockerfile or
the version_release_tuple argument and querying
brew for the most recent images built for that version.
:param tag_list: The list of tags to apply to the image (overrides default tagging pattern).
:param push_to_defaults: Boolean indicating whether group/image yaml defined registries should be pushed to.
:param additional_registries: A list of non-default registries (optional namespace included) to push the image to.
:param version_release_tuple: Specify a version/release to pull as the source (if None, the latest build will be pulled).
:param push_late: Whether late pushes should be included.
:param dry_run: Will only print the docker operations that would have taken place.
:return: Returns True if successful (exception otherwise)
"""
# Late pushes allow certain images to be the last of a group to be
# pushed to mirrors. CI/CD systems may initiate operations based on the
# update a given image and all other images need to be in place
# when that special image is updated. The special images are there
# pushed "late"
# Actions that need to push all images need to push all images
# need to make two passes/invocations of this method: one
# with push_late=False and one with push_late=True.
is_late_push = False
if self.config.push.late is not Missing:
is_late_push = self.config.push.late
if push_late != is_late_push:
return (self.metadata.distgit_key, True)
push_names = []
if push_to_defaults:
push_names.extend(self.metadata.get_default_push_names())
push_names.extend(self.metadata.get_additional_push_names(additional_registries))
# Nothing to push to? We are done.
if not push_names:
return (self.metadata.distgit_key, True)
# get registry_config_json file must before with Dir(self.distgit_dir)
# so that relative path or env like DOCKER_CONFIG will not pointed to distgit dir.
registry_config_file = ''
if registry_config_dir is not None:
registry_config_file = util.get_docker_config_json(registry_config_dir)
with Dir(self.distgit_dir):
if version_release_tuple:
version = version_release_tuple[0]
release = version_release_tuple[1]
else:
# History
# We used to rely on the "release" label being set in the Dockerfile, but this is problematic for several reasons.
# (1) If 'release' is not set, OSBS will determine one automatically that does not conflict
# with a pre-existing image build. This is extremely helpful since we don't have to
# worry about bumping the release during refresh images. This means we generally DON'T
# want the release label in the file and can't, therefore, rely on it being there.
# (2) People have logged into distgit before in order to bump the release field. This happening
# at the wrong time breaks the build.
# If the version & release information was not specified,
# try to detect latest build from brew.
# Read in version information from the Distgit dockerfile
_, version, release = self.metadata.get_latest_build_info(complete_before_event=-1)
image_name_and_version = "%s:%s-%s" % (self.config.name, version, release)
brew_image_url = self.runtime.resolve_brew_image_url(image_name_and_version)
push_tags = list(tag_list)
# If no tags were specified, build defaults
if not push_tags:
push_tags = self.metadata.get_default_push_tags(version, release)
all_push_urls = []
for image_name in push_names:
try:
repo = image_name.split('/', 1)
action = "push"
record = {
"distgit_key": self.metadata.distgit_key,
"distgit": '{}/{}'.format(self.metadata.namespace, self.metadata.name),
"repo": repo, # ns/repo
"name": image_name, # full registry/ns/repo
"version": version,
"release": release,
"message": "Unknown failure",
"tags": ", ".join(push_tags),
"status": -1,
# Status defaults to failure until explicitly set by success. This handles raised exceptions.
}
for push_tag in push_tags:
# Collect next SRC=DEST input
url = '{}:{}'.format(image_name, push_tag)
self.logger.info("Adding '{}' to push list".format(url))
all_push_urls.append("{}={}".format(brew_image_url, url))
if dry_run:
for push_url in all_push_urls:
self.logger.info('Would have tagged {} as {}'.format(brew_image_url, push_url.split('=')[1]))
dr = "--dry-run=true"
else:
dr = ""
if self.runtime.group_config.insecure_source:
insecure = "--insecure=true"
else:
insecure = ""
push_config_dir = os.path.join(self.runtime.working_dir, 'push')
if not os.path.isdir(push_config_dir):
try:
os.mkdir(push_config_dir)
except OSError as e:
# File exists, and it's a directory,
# another thread already created this dir, that's OK.
if e.errno == errno.EEXIST and os.path.isdir(push_config_dir):
pass
else:
raise
push_config = os.path.join(push_config_dir, self.metadata.distgit_key)
if os.path.isfile(push_config):
# just delete it to ease creating new config
os.remove(push_config)
with io.open(push_config, 'w', encoding="utf-8") as pc:
pc.write('\n'.join(all_push_urls))
mirror_cmd = 'oc image mirror '
if filter_by_os is not None:
mirror_cmd += "--filter-by-os={}".format(filter_by_os)
mirror_cmd += " {} {} --filename={}".format(dr, insecure, push_config)
if registry_config_file != '':
mirror_cmd += f" --registry-config={registry_config_file}"
if dry_run: # skip everything else if dry run
continue
else:
for r in range(10):
self.logger.info("Mirroring image [retry={}]".format(r))
rc, out, err = exectools.cmd_gather(mirror_cmd, timeout=1800)
if rc == 0:
break
self.logger.info("Error mirroring image -- retrying in 60 seconds.\n{}".format(err))
time.sleep(60)
lstate = self.runtime.state[self.runtime.command] if self.runtime.command == 'images:push' else None
if rc != 0:
if lstate:
state.record_image_fail(lstate, self.metadata, 'Build failure', self.runtime.logger)
# Unable to push to registry
raise IOError('Error pushing image: {}'.format(err))
else:
if lstate:
state.record_image_success(lstate, self.metadata)
self.logger.info('Success mirroring image')
record["message"] = "Successfully pushed all tags"
record["status"] = 0
except Exception as ex:
lstate = self.runtime.state[self.runtime.command] if self.runtime.command == 'images:push' else None
if lstate:
state.record_image_fail(lstate, self.metadata, str(ex), self.runtime.logger)
record["message"] = "Exception occurred: %s" % str(ex)
self.logger.info("Error pushing %s: %s" % (self.metadata.distgit_key, ex))
raise
finally:
self.runtime.add_record(action, **record)
return (self.metadata.distgit_key, True)
def wait_for_build(self, who_is_waiting):
"""
Blocks the calling thread until this image has been built by doozer or throws an exception if this
image cannot be built.
:param who_is_waiting: The caller's distgit_key (i.e. the waiting image).
:return: Returns when the image has been built or throws an exception if the image could not be built.
"""
self.logger.info("Member waiting for me to build: %s" % who_is_waiting)
# This lock is in an acquired state until this image definitively succeeds or fails.
# It is then released. Child images waiting on this image should block here.
with self.build_lock:
if not self.build_status:
raise IOError(
"Error building image: %s (%s was waiting)" % (self.metadata.qualified_name, who_is_waiting))
else:
self.logger.info("Member successfully waited for me to build: %s" % who_is_waiting)
def _set_wait_for(self, image_name, terminate_event):
image = self.runtime.resolve_image(image_name, False)
if image is None:
self.logger.info("Skipping image build since it is not included: %s" % image_name)
return
parent_dgr = image.distgit_repo()
parent_dgr.wait_for_build(self.metadata.qualified_name)
if terminate_event.is_set():
raise KeyboardInterrupt()
def wait_for_rebase(self, image_name, terminate_event):
""" Wait for image_name to be rebased. """
image = self.runtime.resolve_image(image_name, False)
if image is None:
self.logger.info("Skipping image rebase since it is not included: %s" % image_name)
return
dgr = image.distgit_repo()
self.logger.info("Waiting for image rebase: %s" % image_name)
dgr.rebase_event.wait()
if not dgr.rebase_status: # failed to rebase
raise IOError(f"Error rebasing image: {self.metadata.qualified_name} ({image_name} was waiting)")
self.logger.info("Image rebase for %s completed. Stop waiting." % image_name)
if terminate_event.is_set():
raise KeyboardInterrupt()
def build_container(
self, profile, push_to_defaults, additional_registries, terminate_event,
scratch=False, retries=3, realtime=False, dry_run=False, registry_config_dir=None, filter_by_os=None):
"""
This method is designed to be thread-safe. Multiple builds should take place in brew
at the same time. After a build, images are pushed serially to all mirrors.
DONT try to change cwd during this time, all threads active will change cwd
:param profile: image build profile
:param push_to_defaults: If default registries should be pushed to.
:param additional_registries: A list of non-default registries resultant builds should be pushed to.
:param terminate_event: Allows the main thread to interrupt the build.
:param scratch: Whether this is a scratch build. UNTESTED.
:param retries: Number of times the build should be retried.
:return: True if the build was successful
"""
if self.org_image_name is None or self.org_version is None:
if not os.path.isfile(os.path.join(self.distgit_dir, 'Dockerfile')):
msg = ('No Dockerfile found in {}'.format(self.distgit_dir))
else:
msg = ('Unknown error loading Dockerfile information')
self.logger.info(msg)
state.record_image_fail(self.runtime.state[self.runtime.command], self.metadata, msg, self.runtime.logger)
return (self.metadata.distgit_key, False)
action = "build"
release = self.org_release if self.org_release is not None else '?'
record = {
"dir": self.distgit_dir,
"dockerfile": "%s/Dockerfile" % self.distgit_dir,
"distgit": self.metadata.distgit_key,
"image": self.org_image_name,
"owners": ",".join(list(self.config.owners) if self.config.owners is not Missing else []),
"version": self.org_version,
"release": release,
"message": "Unknown failure",
"task_id": "n/a",
"task_url": "n/a",
"status": -1,
"push_status": -1,
"has_olm_bundle": 1 if self.config['update-csv'] is not Missing else 0,
# Status defaults to failure until explicitly set by success. This handles raised exceptions.
}
if self.runtime.local and release == '?':
target_tag = self.org_version
else:
target_tag = "{}-{}".format(self.org_version, release)
target_image = ":".join((self.org_image_name, target_tag))
try:
# If this image is FROM another group member, we need to wait on that group member
# Use .get('from',None) since from is a reserved word.
image_from = Model(self.config.get('from', None))
if image_from.member is not Missing:
self._set_wait_for(image_from.member, terminate_event)
for builder in image_from.get('builder', []):
if 'member' in builder:
self._set_wait_for(builder['member'], terminate_event)
if self.runtime.assembly and util.isolate_assembly_in_release(release) != self.runtime.assembly:
# Assemblies should follow its naming convention
raise ValueError(f"Image {self.name} is not rebased with assembly '{self.runtime.assembly}'.")