This repository has been archived by the owner on Oct 13, 2023. It is now read-only.
/
distgit.py
2047 lines (1703 loc) · 96.7 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
from __future__ import absolute_import, print_function, unicode_literals
import hashlib
import os
import shutil
import time
import traceback
import errno
from multiprocessing import Lock
import yaml
import logging
import bashlex
import glob
import re
import io
import copy
import pathlib
import json
from datetime import datetime, timedelta
import koji
from dockerfile_parse import DockerfileParser
from . import logutil
from . import assertion
from . import exectools
from .pushd import Dir
from .brew import watch_task, get_build_objects
from .model import Model, Missing, ListModel
from doozerlib.exceptions import DoozerFatalError
from doozerlib.util import yellow_print
from doozerlib import state
from doozerlib.source_modifications import SourceModifierFactory
from doozerlib import constants
from doozerlib import util
from doozerlib.dblib import Record
# 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://mojo.redhat.com/docs/DOC-1159997 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", "additional-tags"]
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 build_image_ref_name(name):
return 'openshift/ose-' + re.sub(pattern='^ose-', repl='', string=name)
class DistGitRepo(object):
def __init__(self, metadata, autoclone=True):
self.metadata = metadata
self.config = metadata.config
self.runtime = metadata.runtime
self.name = self.metadata.name
self.distgit_dir = None
self.dg_path = None
self.build_status = False
self.push_status = False
self.branch = self.runtime.branch
self.source_sha = None
self.source_full_sha = None
self.source_latest_tag = None
self.source_date_epoch = None
self.source_url = None
# This 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 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 clone(self, distgits_root_dir, distgit_branch):
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)
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))
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' and self.runtime.cache_dir:
# 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, '--single-branch']
if 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 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)
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.
"""
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 commit(self, commit_message, log_diff=False):
if self.runtime.local:
return '' # no commits if local
with Dir(self.distgit_dir):
self.logger.info("Adding commit to local repo: {}".format(commit_message))
if log_diff:
rc, out, err = exectools.cmd_gather(["git", "diff", "Dockerfile"])
assertion.success(rc, 'Failed fetching distgit diff')
self.runtime.add_distgits_diff(self.metadata.distgit_key, out)
if self.source_sha:
# add short sha of source for audit trail
commit_message += " - {}".format(self.source_sha)
commit_message += "\n- MaxFileSize: {}".format(50000000) # set dist-git size limit to 50MB
# 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_message])
rc, sha, err = exectools.cmd_gather(["git", "rev-parse", "HEAD"])
assertion.success(rc, "Failure fetching commit SHA for {}".format(self.distgit_dir))
return sha.strip()
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()):
super(ImageDistGitRepo, self).__init__(metadata, autoclone)
self.build_lock = Lock()
self.build_lock.acquire()
self.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()
@property
def image_build_method(self):
build_method = self.runtime.group_config.default_image_build_method
# If the build is multistage, override with 'imagebuilder' as required for multistage.
if 'builder' in self.config.get('from', {}):
build_method = '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_osbs_image_config(self):
# 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()
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):
"""
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://mojo.redhat.com/docs/DOC-1159997)
"""
# 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())
if self.image_build_method is not Missing:
config_overrides['image_build_method'] = self.image_build_method
if arches:
config_overrides.setdefault('platforms', {})['only'] = arches
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 _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', [])
shipping_repos = [repo for repo in enabled_repos if repo not in 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(shipping_repos=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):
"""
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)
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()
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 --filter-by-os=amd64 {} {} --filename={}'.format(dr, insecure, push_config)
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)
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 build_container(
self, profile, push_to_defaults, additional_registries, terminate_event,
scratch=False, retries=3, realtime=False, dry_run=False):
"""
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,
# 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)
# Allow an image to wait on an arbitrary image in the group. This is presently
# just a workaround for: https://projects.engineering.redhat.com/browse/OSBS-5592
if self.config.wait_for is not Missing:
self._set_wait_for(self.config.wait_for, terminate_event)
if self.runtime.local:
self.build_status = self._build_container_local(target_image, profile["repo_type"], realtime)
if not self.build_status:
state.record_image_fail(self.runtime.state[self.runtime.command], self.metadata, 'Build failure', self.runtime.logger)
else:
state.record_image_success(self.runtime.state[self.runtime.command], self.metadata)
return (self.metadata.distgit_key, self.build_status) # do nothing more since it's local only
else:
def wait(n):
self.logger.info("Async error in image build thread [attempt #{}]".format(n + 1))
# No need to retry if the failure will just recur
error = self._detect_permanent_build_failures(self.runtime.group_config.image_build_log_scanner)
if error is not None:
for match in re.finditer("No package (.*) available", error):
self._add_missing_pkgs(match.group(1))
raise exectools.RetryException(
"Saw permanent error in build logs:\n{}\nWill not retry after {} failed attempt(s)"
.format(error, n + 1)
)
# Brew does not handle an immediate retry correctly, wait
# before trying another build, terminating if interrupted.
if terminate_event.wait(timeout=5 * 60):
raise KeyboardInterrupt()
if len(profile["targets"]) > 1:
# FIXME: Currently we don't really support building images against multiple targets,
# or we would overwrite the image tag when pushing to the registry.
# `targets` is defined as an array just because we want to keep consistency with RPM build.
raise DoozerFatalError("Building images against multiple targets is not currently supported.")
target = '' if not profile["targets"] else profile["targets"][0]
exectools.retry(
retries=retries, wait_f=wait,
task_f=lambda: self._build_container(
target_image, target, profile["signing_intent"], profile["repo_type"], profile["repo_list"], terminate_event,
scratch, record, dry_run=dry_run))
# Just in case someone else is building an image, go ahead and find what was just
# built so that push_image will have a fixed point of reference and not detect any
# subsequent builds.
push_version, push_release = ('', '')
if not scratch:
_, push_version, push_release = self.metadata.get_latest_build_info()
record["message"] = "Success"
record["status"] = 0
self.build_status = True
except (Exception, KeyboardInterrupt):
tb = traceback.format_exc()
record["message"] = "Exception occurred:\n{}".format(tb)
self.logger.info("Exception occurred during build:\n{}".format(tb))
# This is designed to fall through to finally. Since this method is designed to be
# threaded, we should not throw an exception; instead return False.
finally:
# Regardless of success, allow other images depending on this one to progress or fail.
self.build_lock.release()
self.push_status = True # if if never pushes, the status is True
if not scratch and self.build_status and (push_to_defaults or additional_registries):
# If this is a scratch build, we aren't going to be pushing. We might be able to determine the
# image name by parsing the build log, but not worth the effort until we need scratch builds.
# The image name for a scratch build looks something like:
# brew-pulp-docker01.web.prod.ext.phx2.redhat.com:8888/openshift3/ose-base:rhaos-3.7-rhel-7-docker-candidate-16066-20170829214444
# To ensure we don't overwhelm the system building, pull & push synchronously
with self.runtime.mutex:
self.push_status = False
try:
self.push_image([], push_to_defaults, additional_registries, version_release_tuple=(push_version, push_release))
self.push_status = True
except Exception as push_e:
self.logger.info("Error during push after successful build: %s" % str(push_e))
self.push_status = False
record['push_status'] = '0' if self.push_status else '-1'
self.runtime.add_record(action, **record)
lstate = self.runtime.state[self.runtime.command]
if not (self.build_status and self.push_status):
state.record_image_fail(lstate, self.metadata, 'Build failure', self.runtime.logger)
else:
state.record_image_success(lstate, self.metadata)
return (self.metadata.distgit_key, self.build_status and self.push_status)
def _build_container_local(self, target_image, repo_type, realtime=False):
"""
The part of `build_container` which actually starts the build,
separated for clarity. Local build version.
"""
if self.image_build_method == 'imagebuilder':
builder = 'imagebuilder -mount '
else:
builder = 'podman build -v '
cmd = builder
self.logger.info("Building image: %s" % target_image)
cmd += '{dir}/.oit/{repo_type}.repo:/etc/yum.repos.d/{repo_type}.repo -t {name}{tag} -t {name}:latest .'
name_split = target_image.split(':')
name = name_split[0]
tag = None
if len(name_split) > 1:
tag = name_split[1]
args = {
'dir': self.distgit_dir,
'repo_type': repo_type,
'name': name,
'tag': ':{}'.format(tag) if tag else ''
}
cmd = cmd.format(**args)
with Dir(self.distgit_dir):
self.logger.info(cmd)
rc, out, err = exectools.cmd_gather(cmd, realtime=True)
if rc != 0:
self.logger.error("Error running {}: out={} ; err={}".format(builder, out, err))
return False
self.logger.debug(out + '\n\n' + err)
self.logger.info("Successfully built image: {}".format(target_image))
return True
def update_build_db(self, success_flag, task_id=None, scratch=False):
if scratch:
return
with Dir(self.distgit_dir):
commit_sha = exectools.cmd_assert('git rev-parse HEAD')[0].strip()[:8]
invoke_ts = str(int(round(time.time() * 1000)))
invoke_ts_iso = self.runtime.timestamp()
with self.runtime.db.record('build', metadata=self.metadata):
Record.set('build.time.unix', invoke_ts)
Record.set('build.time.iso', invoke_ts_iso)
Record.set('dg.commit', commit_sha)
Record.set('brew.task_state', 'success' if success_flag else 'failure')
Record.set('brew.task_id', task_id)
dfp = DockerfileParser(str(Dir.getpath().joinpath('Dockerfile')))
for label_name in ['version', 'release', 'name', 'com.redhat.component']:
Record.set(f'label.{label_name}', dfp.labels.get(label_name, ''))
Record.set('label.version', dfp.labels.get('version', ''))
Record.set('label.release', dfp.labels.get('release', ''))
for k, v in dfp.labels.items():
if k.startswith('io.openshift.'):
Record.set(f'label.{k}', dfp.labels[k])
for k, v in dfp.envs.items():
if k.startswith('KUBE_') or k.startswith('OS_'):
Record.set(f'env.{k}', dfp.envs.get(k, ''))
Record.set('incomplete', False)
if task_id is not None:
try:
with self.runtime.shared_koji_client_session() as kcs:
task_result = kcs.getTaskResult(task_id, raise_fault=False)
import pprint
pprint.pprint(task_result)
"""
success example result:
{ 'koji_builds': ['1182060'], # build_id created by task
'repositories': [
'registry-proxy.engineering.redhat.com/rh-osbs/openshift-ose-ose-metering-ansible-operator-metadata:latest',
...
]
}
fail example result:
{ 'faultCode': 1018,
'faultString': 'log entries',
}
"""
Record.set('brew.faultCode', task_result.get('faultCode', 0))
build_ids = task_result.get('koji_builds', [])
Record.set('brew.build_ids', ','.join(build_ids)) # comma delimited list if > 1
image_shas = []
for idx, build_id in enumerate(build_ids):
build_info = Model(kcs.getBuild(int(
build_id))) # Example: https://gist.github.com/jupierce/fe05f8fe310fdf8aa8b5c5991cf21f05
main_sha = build_info.extra.typeinfo.image.index.digests # Typically contains manifest list sha
if main_sha:
image_shas.extend(main_sha.values())
for build_datum in ['id', 'source', 'version', 'nvr', 'name', 'release',
'package_id']:
Record.set(f'build.{idx}.{build_datum}', build_info.get(build_datum, ''))
archives = ListModel(kcs.listArchives(int(build_id))) # https://gist.github.com/jupierce/6f27ebf35e88ed5a9a2c8e66fdcd34b4
for archive in archives:
archive_shas = archive.extra.docker.digests
if archive_shas:
image_shas.extend(archive_shas.values())
Record.set('brew.image_shas', ','.join(image_shas))
except:
Record.set('incomplete', True)
traceback.print_exc()
self.logger.error(f'Unable to extract brew task information for {task_id}')
def _build_container(self, target_image, target, signing_intent, repo_type, repo_list, terminate_event,
scratch, record, dry_run=False):
"""
The part of `build_container` which actually starts the build,
separated for clarity. Brew build version.
"""
self.logger.info("Building image: %s" % target_image)
cmd_list = ["rhpkg"]
if self.runtime.rhpkg_config_lst:
cmd_list.extend(self.runtime.rhpkg_config_lst)
cmd_list.append("--path=%s" % self.distgit_dir)
if self.runtime.user is not None:
cmd_list.append("--user=%s" % self.runtime.user)
cmd_list += (
"container-build",
"--nowait", # Run the build with --nowait so that we can immediately get information about the brew task
)
if target:
cmd_list.append("--target")
cmd_list.append(target)
# Determine if ODCS is enabled by looking at container.yaml.
odcs_enabled = False
osbs_image_config_path = os.path.join(self.distgit_dir, "container.yaml")
if os.path.isfile(osbs_image_config_path):
with open(osbs_image_config_path, "r") as f:
image_config = yaml.safe_load(f)
odcs_enabled = "compose" in image_config
if odcs_enabled:
self.logger.info("About to build image in ODCS mode with signing intent {}.".format(signing_intent))
cmd_list.append('--signing-intent')
cmd_list.append(signing_intent)
else:
if repo_type:
repo_list = list(repo_list) # In case we get a tuple
repo_list.append(self.metadata.cgit_url(".oit/" + repo_type + ".repo"))
if repo_list:
# rhpkg supports --repo-url [URL [URL ...]]
cmd_list.append("--repo-url")
cmd_list.extend(repo_list)
if scratch:
cmd_list.append("--scratch")
if dry_run:
# `rhpkg --dry-run container-build` doesn't really work. Print the command instread.
self.logger.warning("[Dry Run] Would have run command " + " ".join(cmd_list))
self.logger.info("[Dry Run] Successfully built image: {}".format(target_image))
return True
try:
# Run the build with --nowait so that we can immediately get information about the brew task
rc, out, err = exectools.cmd_gather(cmd_list)
if rc != 0:
# Probably no point in continuing.. can't contact brew?
self.logger.info("Unable to create brew task: out={} ; err={}".format(out, err))
self.update_build_db(False, scratch=scratch)
return False
# Otherwise, we should have a brew task we can monitor listed in the stdout.
out_lines = out.splitlines()
# Look for a line like: "Created task: 13949050" . Extract the identifier.
task_id = next((created_line.split(":")[1]).strip() for created_line in out_lines if
created_line.startswith("Created task:"))