repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
projectatomic/atomic-reactor | docs/manpage/generate_manpage.py | ManPageFormatter.create_subcommand_synopsis | def create_subcommand_synopsis(self, parser):
""" show usage with description for commands """
self.add_usage(parser.usage, parser._get_positional_actions(),
None, prefix='')
usage = self._format_usage(parser.usage, parser._get_positional_actions(),
None, '')
return self._bold(usage) | python | def create_subcommand_synopsis(self, parser):
""" show usage with description for commands """
self.add_usage(parser.usage, parser._get_positional_actions(),
None, prefix='')
usage = self._format_usage(parser.usage, parser._get_positional_actions(),
None, '')
return self._bold(usage) | [
"def",
"create_subcommand_synopsis",
"(",
"self",
",",
"parser",
")",
":",
"self",
".",
"add_usage",
"(",
"parser",
".",
"usage",
",",
"parser",
".",
"_get_positional_actions",
"(",
")",
",",
"None",
",",
"prefix",
"=",
"''",
")",
"usage",
"=",
"self",
"... | show usage with description for commands | [
"show",
"usage",
"with",
"description",
"for",
"commands"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/docs/manpage/generate_manpage.py#L89-L95 | train | 28,500 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | get_worker_build_info | def get_worker_build_info(workflow, platform):
"""
Obtain worker build information for a given platform
"""
workspace = workflow.plugin_workspace[OrchestrateBuildPlugin.key]
return workspace[WORKSPACE_KEY_BUILD_INFO][platform] | python | def get_worker_build_info(workflow, platform):
"""
Obtain worker build information for a given platform
"""
workspace = workflow.plugin_workspace[OrchestrateBuildPlugin.key]
return workspace[WORKSPACE_KEY_BUILD_INFO][platform] | [
"def",
"get_worker_build_info",
"(",
"workflow",
",",
"platform",
")",
":",
"workspace",
"=",
"workflow",
".",
"plugin_workspace",
"[",
"OrchestrateBuildPlugin",
".",
"key",
"]",
"return",
"workspace",
"[",
"WORKSPACE_KEY_BUILD_INFO",
"]",
"[",
"platform",
"]"
] | Obtain worker build information for a given platform | [
"Obtain",
"worker",
"build",
"information",
"for",
"a",
"given",
"platform"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L60-L65 | train | 28,501 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | override_build_kwarg | def override_build_kwarg(workflow, k, v, platform=None):
"""
Override a build-kwarg for all worker builds
"""
key = OrchestrateBuildPlugin.key
# Use None to indicate an override for all platforms
workspace = workflow.plugin_workspace.setdefault(key, {})
override_kwargs = workspace.setdefault(WORKSPACE_KEY_OVERRIDE_KWARGS, {})
override_kwargs.setdefault(platform, {})
override_kwargs[platform][k] = v | python | def override_build_kwarg(workflow, k, v, platform=None):
"""
Override a build-kwarg for all worker builds
"""
key = OrchestrateBuildPlugin.key
# Use None to indicate an override for all platforms
workspace = workflow.plugin_workspace.setdefault(key, {})
override_kwargs = workspace.setdefault(WORKSPACE_KEY_OVERRIDE_KWARGS, {})
override_kwargs.setdefault(platform, {})
override_kwargs[platform][k] = v | [
"def",
"override_build_kwarg",
"(",
"workflow",
",",
"k",
",",
"v",
",",
"platform",
"=",
"None",
")",
":",
"key",
"=",
"OrchestrateBuildPlugin",
".",
"key",
"# Use None to indicate an override for all platforms",
"workspace",
"=",
"workflow",
".",
"plugin_workspace",... | Override a build-kwarg for all worker builds | [
"Override",
"a",
"build",
"-",
"kwarg",
"for",
"all",
"worker",
"builds"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L76-L86 | train | 28,502 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | wait_for_any_cluster | def wait_for_any_cluster(contexts):
"""
Wait until any of the clusters are out of retry-wait
:param contexts: List[ClusterRetryContext]
:raises: AllClustersFailedException if no more retry attempts allowed
"""
try:
earliest_retry_at = min(ctx.retry_at for ctx in contexts.values()
if not ctx.failed)
except ValueError: # can't take min() of empty sequence
raise AllClustersFailedException(
"Could not find appropriate cluster for worker build."
)
time_until_next = earliest_retry_at - dt.datetime.now()
time.sleep(max(timedelta(seconds=0), time_until_next).seconds) | python | def wait_for_any_cluster(contexts):
"""
Wait until any of the clusters are out of retry-wait
:param contexts: List[ClusterRetryContext]
:raises: AllClustersFailedException if no more retry attempts allowed
"""
try:
earliest_retry_at = min(ctx.retry_at for ctx in contexts.values()
if not ctx.failed)
except ValueError: # can't take min() of empty sequence
raise AllClustersFailedException(
"Could not find appropriate cluster for worker build."
)
time_until_next = earliest_retry_at - dt.datetime.now()
time.sleep(max(timedelta(seconds=0), time_until_next).seconds) | [
"def",
"wait_for_any_cluster",
"(",
"contexts",
")",
":",
"try",
":",
"earliest_retry_at",
"=",
"min",
"(",
"ctx",
".",
"retry_at",
"for",
"ctx",
"in",
"contexts",
".",
"values",
"(",
")",
"if",
"not",
"ctx",
".",
"failed",
")",
"except",
"ValueError",
"... | Wait until any of the clusters are out of retry-wait
:param contexts: List[ClusterRetryContext]
:raises: AllClustersFailedException if no more retry attempts allowed | [
"Wait",
"until",
"any",
"of",
"the",
"clusters",
"are",
"out",
"of",
"retry",
"-",
"wait"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L129-L145 | train | 28,503 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | OrchestrateBuildPlugin.validate_arrangement_version | def validate_arrangement_version(self):
"""Validate if the arrangement_version is supported
This is for autorebuilds to fail early otherwise they may failed
on workers because of osbs-client validation checks.
Method should be called after self.adjust_build_kwargs
Shows a warning when version is deprecated
:raises ValueError: when version is not supported
"""
arrangement_version = self.build_kwargs['arrangement_version']
if arrangement_version is None:
return
if arrangement_version <= 5:
# TODO: raise as ValueError in release 1.6.38+
self.log.warning("arrangement_version <= 5 is deprecated and will be removed"
" in release 1.6.38") | python | def validate_arrangement_version(self):
"""Validate if the arrangement_version is supported
This is for autorebuilds to fail early otherwise they may failed
on workers because of osbs-client validation checks.
Method should be called after self.adjust_build_kwargs
Shows a warning when version is deprecated
:raises ValueError: when version is not supported
"""
arrangement_version = self.build_kwargs['arrangement_version']
if arrangement_version is None:
return
if arrangement_version <= 5:
# TODO: raise as ValueError in release 1.6.38+
self.log.warning("arrangement_version <= 5 is deprecated and will be removed"
" in release 1.6.38") | [
"def",
"validate_arrangement_version",
"(",
"self",
")",
":",
"arrangement_version",
"=",
"self",
".",
"build_kwargs",
"[",
"'arrangement_version'",
"]",
"if",
"arrangement_version",
"is",
"None",
":",
"return",
"if",
"arrangement_version",
"<=",
"5",
":",
"# TODO: ... | Validate if the arrangement_version is supported
This is for autorebuilds to fail early otherwise they may failed
on workers because of osbs-client validation checks.
Method should be called after self.adjust_build_kwargs
Shows a warning when version is deprecated
:raises ValueError: when version is not supported | [
"Validate",
"if",
"the",
"arrangement_version",
"is",
"supported"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L421-L440 | train | 28,504 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | OrchestrateBuildPlugin.get_clusters | def get_clusters(self, platform, retry_contexts, all_clusters):
''' return clusters sorted by load. '''
possible_cluster_info = {}
candidates = set(copy.copy(all_clusters))
while candidates and not possible_cluster_info:
wait_for_any_cluster(retry_contexts)
for cluster in sorted(candidates, key=attrgetter('priority')):
ctx = retry_contexts[cluster.name]
if ctx.in_retry_wait:
continue
if ctx.failed:
continue
try:
cluster_info = self.get_cluster_info(cluster, platform)
possible_cluster_info[cluster] = cluster_info
except OsbsException:
ctx.try_again_later(self.find_cluster_retry_delay)
candidates -= set([c for c in candidates if retry_contexts[c.name].failed])
ret = sorted(possible_cluster_info.values(), key=lambda c: c.cluster.priority)
ret = sorted(ret, key=lambda c: c.load)
return ret | python | def get_clusters(self, platform, retry_contexts, all_clusters):
''' return clusters sorted by load. '''
possible_cluster_info = {}
candidates = set(copy.copy(all_clusters))
while candidates and not possible_cluster_info:
wait_for_any_cluster(retry_contexts)
for cluster in sorted(candidates, key=attrgetter('priority')):
ctx = retry_contexts[cluster.name]
if ctx.in_retry_wait:
continue
if ctx.failed:
continue
try:
cluster_info = self.get_cluster_info(cluster, platform)
possible_cluster_info[cluster] = cluster_info
except OsbsException:
ctx.try_again_later(self.find_cluster_retry_delay)
candidates -= set([c for c in candidates if retry_contexts[c.name].failed])
ret = sorted(possible_cluster_info.values(), key=lambda c: c.cluster.priority)
ret = sorted(ret, key=lambda c: c.load)
return ret | [
"def",
"get_clusters",
"(",
"self",
",",
"platform",
",",
"retry_contexts",
",",
"all_clusters",
")",
":",
"possible_cluster_info",
"=",
"{",
"}",
"candidates",
"=",
"set",
"(",
"copy",
".",
"copy",
"(",
"all_clusters",
")",
")",
"while",
"candidates",
"and"... | return clusters sorted by load. | [
"return",
"clusters",
"sorted",
"by",
"load",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L472-L495 | train | 28,505 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | OrchestrateBuildPlugin.get_koji_upload_dir | def get_koji_upload_dir():
"""
Create a path name for uploading files to
:return: str, path name expected to be unique
"""
dir_prefix = 'koji-upload'
random_chars = ''.join([random.choice(ascii_letters)
for _ in range(8)])
unique_fragment = '%r.%s' % (time.time(), random_chars)
return os.path.join(dir_prefix, unique_fragment) | python | def get_koji_upload_dir():
"""
Create a path name for uploading files to
:return: str, path name expected to be unique
"""
dir_prefix = 'koji-upload'
random_chars = ''.join([random.choice(ascii_letters)
for _ in range(8)])
unique_fragment = '%r.%s' % (time.time(), random_chars)
return os.path.join(dir_prefix, unique_fragment) | [
"def",
"get_koji_upload_dir",
"(",
")",
":",
"dir_prefix",
"=",
"'koji-upload'",
"random_chars",
"=",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"ascii_letters",
")",
"for",
"_",
"in",
"range",
"(",
"8",
")",
"]",
")",
"unique_fragment",
... | Create a path name for uploading files to
:return: str, path name expected to be unique | [
"Create",
"a",
"path",
"name",
"for",
"uploading",
"files",
"to"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L503-L513 | train | 28,506 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | OrchestrateBuildPlugin.select_and_start_cluster | def select_and_start_cluster(self, platform):
''' Choose a cluster and start a build on it '''
clusters = self.reactor_config.get_enabled_clusters_for_platform(platform)
if not clusters:
raise UnknownPlatformException('No clusters found for platform {}!'
.format(platform))
retry_contexts = {
cluster.name: ClusterRetryContext(self.max_cluster_fails)
for cluster in clusters
}
while True:
try:
possible_cluster_info = self.get_clusters(platform,
retry_contexts,
clusters)
except AllClustersFailedException as ex:
cluster = ClusterInfo(None, platform, None, None)
build_info = WorkerBuildInfo(build=None,
cluster_info=cluster,
logger=self.log)
build_info.monitor_exception = repr(ex)
self.worker_builds.append(build_info)
return
for cluster_info in possible_cluster_info:
ctx = retry_contexts[cluster_info.cluster.name]
try:
self.log.info('Attempting to start build for platform %s on cluster %s',
platform, cluster_info.cluster.name)
self.do_worker_build(cluster_info)
return
except OsbsException:
ctx.try_again_later(self.failure_retry_delay) | python | def select_and_start_cluster(self, platform):
''' Choose a cluster and start a build on it '''
clusters = self.reactor_config.get_enabled_clusters_for_platform(platform)
if not clusters:
raise UnknownPlatformException('No clusters found for platform {}!'
.format(platform))
retry_contexts = {
cluster.name: ClusterRetryContext(self.max_cluster_fails)
for cluster in clusters
}
while True:
try:
possible_cluster_info = self.get_clusters(platform,
retry_contexts,
clusters)
except AllClustersFailedException as ex:
cluster = ClusterInfo(None, platform, None, None)
build_info = WorkerBuildInfo(build=None,
cluster_info=cluster,
logger=self.log)
build_info.monitor_exception = repr(ex)
self.worker_builds.append(build_info)
return
for cluster_info in possible_cluster_info:
ctx = retry_contexts[cluster_info.cluster.name]
try:
self.log.info('Attempting to start build for platform %s on cluster %s',
platform, cluster_info.cluster.name)
self.do_worker_build(cluster_info)
return
except OsbsException:
ctx.try_again_later(self.failure_retry_delay) | [
"def",
"select_and_start_cluster",
"(",
"self",
",",
"platform",
")",
":",
"clusters",
"=",
"self",
".",
"reactor_config",
".",
"get_enabled_clusters_for_platform",
"(",
"platform",
")",
"if",
"not",
"clusters",
":",
"raise",
"UnknownPlatformException",
"(",
"'No cl... | Choose a cluster and start a build on it | [
"Choose",
"a",
"cluster",
"and",
"start",
"a",
"build",
"on",
"it"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L666-L702 | train | 28,507 |
projectatomic/atomic-reactor | atomic_reactor/plugins/build_orchestrate_build.py | OrchestrateBuildPlugin.set_build_image | def set_build_image(self):
"""
Overrides build_image for worker, to be same as in orchestrator build
"""
current_platform = platform.processor()
orchestrator_platform = current_platform or 'x86_64'
current_buildimage = self.get_current_buildimage()
for plat, build_image in self.build_image_override.items():
self.log.debug('Overriding build image for %s platform to %s',
plat, build_image)
self.build_image_digests[plat] = build_image
manifest_list_platforms = self.platforms - set(self.build_image_override.keys())
if not manifest_list_platforms:
self.log.debug('Build image override used for all platforms, '
'skipping build image manifest list checks')
return
# orchestrator platform is same as platform on which we want to built on,
# so we can use the same image
if manifest_list_platforms == set([orchestrator_platform]):
self.build_image_digests[orchestrator_platform] = current_buildimage
return
# BuildConfig exists
build_image, imagestream = self.get_image_info_from_buildconfig()
if not (build_image or imagestream):
# get image build from build metadata, which is set for direct builds
# this is explicitly set by osbs-client, it isn't default OpenShift behaviour
build_image, imagestream = self.get_image_info_from_annotations()
# if imageStream is used
if imagestream:
build_image = self.get_build_image_from_imagestream(imagestream)
# we have build_image with tag, so we can check for manifest list
if build_image:
self.check_manifest_list(build_image, orchestrator_platform,
manifest_list_platforms, current_buildimage) | python | def set_build_image(self):
"""
Overrides build_image for worker, to be same as in orchestrator build
"""
current_platform = platform.processor()
orchestrator_platform = current_platform or 'x86_64'
current_buildimage = self.get_current_buildimage()
for plat, build_image in self.build_image_override.items():
self.log.debug('Overriding build image for %s platform to %s',
plat, build_image)
self.build_image_digests[plat] = build_image
manifest_list_platforms = self.platforms - set(self.build_image_override.keys())
if not manifest_list_platforms:
self.log.debug('Build image override used for all platforms, '
'skipping build image manifest list checks')
return
# orchestrator platform is same as platform on which we want to built on,
# so we can use the same image
if manifest_list_platforms == set([orchestrator_platform]):
self.build_image_digests[orchestrator_platform] = current_buildimage
return
# BuildConfig exists
build_image, imagestream = self.get_image_info_from_buildconfig()
if not (build_image or imagestream):
# get image build from build metadata, which is set for direct builds
# this is explicitly set by osbs-client, it isn't default OpenShift behaviour
build_image, imagestream = self.get_image_info_from_annotations()
# if imageStream is used
if imagestream:
build_image = self.get_build_image_from_imagestream(imagestream)
# we have build_image with tag, so we can check for manifest list
if build_image:
self.check_manifest_list(build_image, orchestrator_platform,
manifest_list_platforms, current_buildimage) | [
"def",
"set_build_image",
"(",
"self",
")",
":",
"current_platform",
"=",
"platform",
".",
"processor",
"(",
")",
"orchestrator_platform",
"=",
"current_platform",
"or",
"'x86_64'",
"current_buildimage",
"=",
"self",
".",
"get_current_buildimage",
"(",
")",
"for",
... | Overrides build_image for worker, to be same as in orchestrator build | [
"Overrides",
"build_image",
"for",
"worker",
"to",
"be",
"same",
"as",
"in",
"orchestrator",
"build"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/build_orchestrate_build.py#L838-L877 | train | 28,508 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | GroupManifestsPlugin.get_manifest | def get_manifest(self, session, repository, ref):
"""
Downloads a manifest from a registry. ref can be a digest, or a tag.
"""
self.log.debug("%s: Retrieving manifest for %s:%s", session.registry, repository, ref)
headers = {
'Accept': ', '.join(self.manifest_media_types)
}
url = '/v2/{}/manifests/{}'.format(repository, ref)
response = session.get(url, headers=headers)
response.raise_for_status()
return (response.content,
response.headers['Docker-Content-Digest'],
response.headers['Content-Type'],
int(response.headers['Content-Length'])) | python | def get_manifest(self, session, repository, ref):
"""
Downloads a manifest from a registry. ref can be a digest, or a tag.
"""
self.log.debug("%s: Retrieving manifest for %s:%s", session.registry, repository, ref)
headers = {
'Accept': ', '.join(self.manifest_media_types)
}
url = '/v2/{}/manifests/{}'.format(repository, ref)
response = session.get(url, headers=headers)
response.raise_for_status()
return (response.content,
response.headers['Docker-Content-Digest'],
response.headers['Content-Type'],
int(response.headers['Content-Length'])) | [
"def",
"get_manifest",
"(",
"self",
",",
"session",
",",
"repository",
",",
"ref",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"%s: Retrieving manifest for %s:%s\"",
",",
"session",
".",
"registry",
",",
"repository",
",",
"ref",
")",
"headers",
"=",
... | Downloads a manifest from a registry. ref can be a digest, or a tag. | [
"Downloads",
"a",
"manifest",
"from",
"a",
"registry",
".",
"ref",
"can",
"be",
"a",
"digest",
"or",
"a",
"tag",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L83-L99 | train | 28,509 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | GroupManifestsPlugin.link_manifest_references_into_repository | def link_manifest_references_into_repository(self, session, manifest, media_type,
source_repo, target_repo):
"""
Links all the blobs referenced by the manifest from source_repo into target_repo.
"""
if source_repo == target_repo:
return
parsed = json.loads(manifest.decode('utf-8'))
references = []
if media_type in (MEDIA_TYPE_DOCKER_V2_SCHEMA2, MEDIA_TYPE_OCI_V1):
references.append(parsed['config']['digest'])
for l in parsed['layers']:
references.append(l['digest'])
else:
# manifest list support could be added here, but isn't needed currently, since
# we never copy a manifest list as a whole between repositories
raise RuntimeError("Unhandled media-type {}".format(media_type))
for digest in references:
self.link_blob_into_repository(session, digest, source_repo, target_repo) | python | def link_manifest_references_into_repository(self, session, manifest, media_type,
source_repo, target_repo):
"""
Links all the blobs referenced by the manifest from source_repo into target_repo.
"""
if source_repo == target_repo:
return
parsed = json.loads(manifest.decode('utf-8'))
references = []
if media_type in (MEDIA_TYPE_DOCKER_V2_SCHEMA2, MEDIA_TYPE_OCI_V1):
references.append(parsed['config']['digest'])
for l in parsed['layers']:
references.append(l['digest'])
else:
# manifest list support could be added here, but isn't needed currently, since
# we never copy a manifest list as a whole between repositories
raise RuntimeError("Unhandled media-type {}".format(media_type))
for digest in references:
self.link_blob_into_repository(session, digest, source_repo, target_repo) | [
"def",
"link_manifest_references_into_repository",
"(",
"self",
",",
"session",
",",
"manifest",
",",
"media_type",
",",
"source_repo",
",",
"target_repo",
")",
":",
"if",
"source_repo",
"==",
"target_repo",
":",
"return",
"parsed",
"=",
"json",
".",
"loads",
"(... | Links all the blobs referenced by the manifest from source_repo into target_repo. | [
"Links",
"all",
"the",
"blobs",
"referenced",
"by",
"the",
"manifest",
"from",
"source_repo",
"into",
"target_repo",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L128-L150 | train | 28,510 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | GroupManifestsPlugin.store_manifest_in_repository | def store_manifest_in_repository(self, session, manifest, media_type,
source_repo, target_repo, digest=None, tag=None):
"""
Stores the manifest into target_repo, possibly tagging it. This may involve
copying referenced blobs from source_repo.
"""
if tag:
self.log.debug("%s: Tagging manifest (or list) from %s as %s:%s",
session.registry, source_repo, target_repo, tag)
ref = tag
elif digest:
self.log.debug("%s: Storing manifest (or list) %s from %s in %s",
session.registry, digest, source_repo, target_repo)
ref = digest
else:
raise RuntimeError("Either digest or tag must be specified")
self.link_manifest_references_into_repository(session, manifest, media_type,
source_repo, target_repo)
url = '/v2/{}/manifests/{}'.format(target_repo, ref)
headers = {'Content-Type': media_type}
response = session.put(url, data=manifest, headers=headers)
response.raise_for_status() | python | def store_manifest_in_repository(self, session, manifest, media_type,
source_repo, target_repo, digest=None, tag=None):
"""
Stores the manifest into target_repo, possibly tagging it. This may involve
copying referenced blobs from source_repo.
"""
if tag:
self.log.debug("%s: Tagging manifest (or list) from %s as %s:%s",
session.registry, source_repo, target_repo, tag)
ref = tag
elif digest:
self.log.debug("%s: Storing manifest (or list) %s from %s in %s",
session.registry, digest, source_repo, target_repo)
ref = digest
else:
raise RuntimeError("Either digest or tag must be specified")
self.link_manifest_references_into_repository(session, manifest, media_type,
source_repo, target_repo)
url = '/v2/{}/manifests/{}'.format(target_repo, ref)
headers = {'Content-Type': media_type}
response = session.put(url, data=manifest, headers=headers)
response.raise_for_status() | [
"def",
"store_manifest_in_repository",
"(",
"self",
",",
"session",
",",
"manifest",
",",
"media_type",
",",
"source_repo",
",",
"target_repo",
",",
"digest",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"tag",
":",
"self",
".",
"log",
".",
"deb... | Stores the manifest into target_repo, possibly tagging it. This may involve
copying referenced blobs from source_repo. | [
"Stores",
"the",
"manifest",
"into",
"target_repo",
"possibly",
"tagging",
"it",
".",
"This",
"may",
"involve",
"copying",
"referenced",
"blobs",
"from",
"source_repo",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L152-L176 | train | 28,511 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | GroupManifestsPlugin.build_list | def build_list(self, manifests):
"""
Builds a manifest list or OCI image out of the given manifests
"""
media_type = manifests[0]['media_type']
if (not all(m['media_type'] == media_type for m in manifests)):
raise PluginFailedException('worker manifests have inconsistent types: {}'
.format(manifests))
if media_type == MEDIA_TYPE_DOCKER_V2_SCHEMA2:
list_type = MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST
elif media_type == MEDIA_TYPE_OCI_V1:
list_type = MEDIA_TYPE_OCI_V1_INDEX
else:
raise PluginFailedException('worker manifests have unsupported type: {}'
.format(media_type))
return list_type, json.dumps({
"schemaVersion": 2,
"mediaType": list_type,
"manifests": [
{
"mediaType": media_type,
"size": m['size'],
"digest": m['digest'],
"platform": {
"architecture": m['architecture'],
"os": "linux"
}
} for m in manifests
],
}, indent=4) | python | def build_list(self, manifests):
"""
Builds a manifest list or OCI image out of the given manifests
"""
media_type = manifests[0]['media_type']
if (not all(m['media_type'] == media_type for m in manifests)):
raise PluginFailedException('worker manifests have inconsistent types: {}'
.format(manifests))
if media_type == MEDIA_TYPE_DOCKER_V2_SCHEMA2:
list_type = MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST
elif media_type == MEDIA_TYPE_OCI_V1:
list_type = MEDIA_TYPE_OCI_V1_INDEX
else:
raise PluginFailedException('worker manifests have unsupported type: {}'
.format(media_type))
return list_type, json.dumps({
"schemaVersion": 2,
"mediaType": list_type,
"manifests": [
{
"mediaType": media_type,
"size": m['size'],
"digest": m['digest'],
"platform": {
"architecture": m['architecture'],
"os": "linux"
}
} for m in manifests
],
}, indent=4) | [
"def",
"build_list",
"(",
"self",
",",
"manifests",
")",
":",
"media_type",
"=",
"manifests",
"[",
"0",
"]",
"[",
"'media_type'",
"]",
"if",
"(",
"not",
"all",
"(",
"m",
"[",
"'media_type'",
"]",
"==",
"media_type",
"for",
"m",
"in",
"manifests",
")",
... | Builds a manifest list or OCI image out of the given manifests | [
"Builds",
"a",
"manifest",
"list",
"or",
"OCI",
"image",
"out",
"of",
"the",
"given",
"manifests"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L178-L210 | train | 28,512 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | GroupManifestsPlugin.group_manifests_and_tag | def group_manifests_and_tag(self, session, worker_digests):
"""
Creates a manifest list or OCI image index that groups the different manifests
in worker_digests, then tags the result with with all the configured tags found
in workflow.tag_conf.
"""
self.log.info("%s: Creating manifest list", session.registry)
# Extract information about the manifests that we will group - we get the
# size and content type of the manifest by querying the registry
manifests = []
for platform, worker_image in worker_digests.items():
repository = worker_image['repository']
digest = worker_image['digest']
media_type = get_manifest_media_type(worker_image['version'])
if media_type not in self.manifest_media_types:
continue
content, _, media_type, size = self.get_manifest(session, repository, digest)
manifests.append({
'content': content,
'repository': repository,
'digest': digest,
'size': size,
'media_type': media_type,
'architecture': self.goarch.get(platform, platform),
})
list_type, list_json = self.build_list(manifests)
self.log.info("%s: Created manifest, Content-Type=%s\n%s", session.registry,
list_type, list_json)
# Now push the manifest list to the registry once per each tag
self.log.info("%s: Tagging manifest list", session.registry)
for image in self.workflow.tag_conf.images:
target_repo = image.to_str(registry=False, tag=False)
# We have to call store_manifest_in_repository directly for each
# referenced manifest, since they potentially come from different repos
for manifest in manifests:
self.store_manifest_in_repository(session,
manifest['content'],
manifest['media_type'],
manifest['repository'],
target_repo,
digest=manifest['digest'])
self.store_manifest_in_repository(session, list_json, list_type,
target_repo, target_repo, tag=image.tag)
# Get the digest of the manifest list using one of the tags
registry_image = self.workflow.tag_conf.unique_images[0]
_, digest_str, _, _ = self.get_manifest(session,
registry_image.to_str(registry=False, tag=False),
registry_image.tag)
if list_type == MEDIA_TYPE_OCI_V1_INDEX:
digest = ManifestDigest(oci_index=digest_str)
else:
digest = ManifestDigest(v2_list=digest_str)
# And store the manifest list in the push_conf
push_conf_registry = self.workflow.push_conf.add_docker_registry(session.registry,
insecure=session.insecure)
for image in self.workflow.tag_conf.images:
push_conf_registry.digests[image.tag] = digest
self.log.info("%s: Manifest list digest is %s", session.registry, digest_str)
return registry_image.get_repo(explicit_namespace=False), digest | python | def group_manifests_and_tag(self, session, worker_digests):
"""
Creates a manifest list or OCI image index that groups the different manifests
in worker_digests, then tags the result with with all the configured tags found
in workflow.tag_conf.
"""
self.log.info("%s: Creating manifest list", session.registry)
# Extract information about the manifests that we will group - we get the
# size and content type of the manifest by querying the registry
manifests = []
for platform, worker_image in worker_digests.items():
repository = worker_image['repository']
digest = worker_image['digest']
media_type = get_manifest_media_type(worker_image['version'])
if media_type not in self.manifest_media_types:
continue
content, _, media_type, size = self.get_manifest(session, repository, digest)
manifests.append({
'content': content,
'repository': repository,
'digest': digest,
'size': size,
'media_type': media_type,
'architecture': self.goarch.get(platform, platform),
})
list_type, list_json = self.build_list(manifests)
self.log.info("%s: Created manifest, Content-Type=%s\n%s", session.registry,
list_type, list_json)
# Now push the manifest list to the registry once per each tag
self.log.info("%s: Tagging manifest list", session.registry)
for image in self.workflow.tag_conf.images:
target_repo = image.to_str(registry=False, tag=False)
# We have to call store_manifest_in_repository directly for each
# referenced manifest, since they potentially come from different repos
for manifest in manifests:
self.store_manifest_in_repository(session,
manifest['content'],
manifest['media_type'],
manifest['repository'],
target_repo,
digest=manifest['digest'])
self.store_manifest_in_repository(session, list_json, list_type,
target_repo, target_repo, tag=image.tag)
# Get the digest of the manifest list using one of the tags
registry_image = self.workflow.tag_conf.unique_images[0]
_, digest_str, _, _ = self.get_manifest(session,
registry_image.to_str(registry=False, tag=False),
registry_image.tag)
if list_type == MEDIA_TYPE_OCI_V1_INDEX:
digest = ManifestDigest(oci_index=digest_str)
else:
digest = ManifestDigest(v2_list=digest_str)
# And store the manifest list in the push_conf
push_conf_registry = self.workflow.push_conf.add_docker_registry(session.registry,
insecure=session.insecure)
for image in self.workflow.tag_conf.images:
push_conf_registry.digests[image.tag] = digest
self.log.info("%s: Manifest list digest is %s", session.registry, digest_str)
return registry_image.get_repo(explicit_namespace=False), digest | [
"def",
"group_manifests_and_tag",
"(",
"self",
",",
"session",
",",
"worker_digests",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"%s: Creating manifest list\"",
",",
"session",
".",
"registry",
")",
"# Extract information about the manifests that we will group - we... | Creates a manifest list or OCI image index that groups the different manifests
in worker_digests, then tags the result with with all the configured tags found
in workflow.tag_conf. | [
"Creates",
"a",
"manifest",
"list",
"or",
"OCI",
"image",
"index",
"that",
"groups",
"the",
"different",
"manifests",
"in",
"worker_digests",
"then",
"tags",
"the",
"result",
"with",
"with",
"all",
"the",
"configured",
"tags",
"found",
"in",
"workflow",
".",
... | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L246-L312 | train | 28,513 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | GroupManifestsPlugin.tag_manifest_into_registry | def tag_manifest_into_registry(self, session, worker_digest):
"""
Tags the manifest identified by worker_digest into session.registry with all the
configured tags found in workflow.tag_conf.
"""
self.log.info("%s: Tagging manifest", session.registry)
digest = worker_digest['digest']
source_repo = worker_digest['repository']
image_manifest, _, media_type, _ = self.get_manifest(session, source_repo, digest)
if media_type == MEDIA_TYPE_DOCKER_V2_SCHEMA2:
digests = ManifestDigest(v1=digest)
elif media_type == MEDIA_TYPE_OCI_V1:
digests = ManifestDigest(oci=digest)
else:
raise RuntimeError("Unexpected media type found in worker repository: {}"
.format(media_type))
push_conf_registry = self.workflow.push_conf.add_docker_registry(session.registry,
insecure=session.insecure)
for image in self.workflow.tag_conf.images:
target_repo = image.to_str(registry=False, tag=False)
self.store_manifest_in_repository(session, image_manifest, media_type,
source_repo, target_repo, tag=image.tag)
# add a tag for any plugins running later that expect it
push_conf_registry.digests[image.tag] = digests | python | def tag_manifest_into_registry(self, session, worker_digest):
"""
Tags the manifest identified by worker_digest into session.registry with all the
configured tags found in workflow.tag_conf.
"""
self.log.info("%s: Tagging manifest", session.registry)
digest = worker_digest['digest']
source_repo = worker_digest['repository']
image_manifest, _, media_type, _ = self.get_manifest(session, source_repo, digest)
if media_type == MEDIA_TYPE_DOCKER_V2_SCHEMA2:
digests = ManifestDigest(v1=digest)
elif media_type == MEDIA_TYPE_OCI_V1:
digests = ManifestDigest(oci=digest)
else:
raise RuntimeError("Unexpected media type found in worker repository: {}"
.format(media_type))
push_conf_registry = self.workflow.push_conf.add_docker_registry(session.registry,
insecure=session.insecure)
for image in self.workflow.tag_conf.images:
target_repo = image.to_str(registry=False, tag=False)
self.store_manifest_in_repository(session, image_manifest, media_type,
source_repo, target_repo, tag=image.tag)
# add a tag for any plugins running later that expect it
push_conf_registry.digests[image.tag] = digests | [
"def",
"tag_manifest_into_registry",
"(",
"self",
",",
"session",
",",
"worker_digest",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"%s: Tagging manifest\"",
",",
"session",
".",
"registry",
")",
"digest",
"=",
"worker_digest",
"[",
"'digest'",
"]",
"sou... | Tags the manifest identified by worker_digest into session.registry with all the
configured tags found in workflow.tag_conf. | [
"Tags",
"the",
"manifest",
"identified",
"by",
"worker_digest",
"into",
"session",
".",
"registry",
"with",
"all",
"the",
"configured",
"tags",
"found",
"in",
"workflow",
".",
"tag_conf",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L314-L341 | train | 28,514 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_koji_parent.py | KojiParentPlugin.detect_parent_image_nvr | def detect_parent_image_nvr(self, image_name, inspect_data=None):
"""
Look for the NVR labels, if any, in the image.
:return NVR string if labels found, otherwise None
"""
if inspect_data is None:
inspect_data = self.workflow.builder.parent_image_inspect(image_name)
labels = Labels(inspect_data[INSPECT_CONFIG].get('Labels', {}))
label_names = [Labels.LABEL_TYPE_COMPONENT, Labels.LABEL_TYPE_VERSION,
Labels.LABEL_TYPE_RELEASE]
label_values = []
for lbl_name in label_names:
try:
_, lbl_value = labels.get_name_and_value(lbl_name)
label_values.append(lbl_value)
except KeyError:
self.log.info("Failed to find label '%s' in parent image '%s'.",
labels.get_name(lbl_name), image_name)
if len(label_values) != len(label_names): # don't have all the necessary labels
self.log.info("Image '%s' NVR missing; not searching for Koji build.", image_name)
return None
return '-'.join(label_values) | python | def detect_parent_image_nvr(self, image_name, inspect_data=None):
"""
Look for the NVR labels, if any, in the image.
:return NVR string if labels found, otherwise None
"""
if inspect_data is None:
inspect_data = self.workflow.builder.parent_image_inspect(image_name)
labels = Labels(inspect_data[INSPECT_CONFIG].get('Labels', {}))
label_names = [Labels.LABEL_TYPE_COMPONENT, Labels.LABEL_TYPE_VERSION,
Labels.LABEL_TYPE_RELEASE]
label_values = []
for lbl_name in label_names:
try:
_, lbl_value = labels.get_name_and_value(lbl_name)
label_values.append(lbl_value)
except KeyError:
self.log.info("Failed to find label '%s' in parent image '%s'.",
labels.get_name(lbl_name), image_name)
if len(label_values) != len(label_names): # don't have all the necessary labels
self.log.info("Image '%s' NVR missing; not searching for Koji build.", image_name)
return None
return '-'.join(label_values) | [
"def",
"detect_parent_image_nvr",
"(",
"self",
",",
"image_name",
",",
"inspect_data",
"=",
"None",
")",
":",
"if",
"inspect_data",
"is",
"None",
":",
"inspect_data",
"=",
"self",
".",
"workflow",
".",
"builder",
".",
"parent_image_inspect",
"(",
"image_name",
... | Look for the NVR labels, if any, in the image.
:return NVR string if labels found, otherwise None | [
"Look",
"for",
"the",
"NVR",
"labels",
"if",
"any",
"in",
"the",
"image",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_koji_parent.py#L98-L125 | train | 28,515 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_koji_parent.py | KojiParentPlugin.wait_for_parent_image_build | def wait_for_parent_image_build(self, nvr):
"""
Given image NVR, wait for the build that produced it to show up in koji.
If it doesn't within the timeout, raise an error.
:return build info dict with 'nvr' and 'id' keys
"""
self.log.info('Waiting for Koji build for parent image %s', nvr)
poll_start = time.time()
while time.time() - poll_start < self.poll_timeout:
build = self.koji_session.getBuild(nvr)
if build:
self.log.info('Parent image Koji build found with id %s', build.get('id'))
if build['state'] != koji.BUILD_STATES['COMPLETE']:
exc_msg = ('Parent image Koji build for {} with id {} state is not COMPLETE.')
raise KojiParentBuildMissing(exc_msg.format(nvr, build.get('id')))
return build
time.sleep(self.poll_interval)
raise KojiParentBuildMissing('Parent image Koji build NOT found for {}!'.format(nvr)) | python | def wait_for_parent_image_build(self, nvr):
"""
Given image NVR, wait for the build that produced it to show up in koji.
If it doesn't within the timeout, raise an error.
:return build info dict with 'nvr' and 'id' keys
"""
self.log.info('Waiting for Koji build for parent image %s', nvr)
poll_start = time.time()
while time.time() - poll_start < self.poll_timeout:
build = self.koji_session.getBuild(nvr)
if build:
self.log.info('Parent image Koji build found with id %s', build.get('id'))
if build['state'] != koji.BUILD_STATES['COMPLETE']:
exc_msg = ('Parent image Koji build for {} with id {} state is not COMPLETE.')
raise KojiParentBuildMissing(exc_msg.format(nvr, build.get('id')))
return build
time.sleep(self.poll_interval)
raise KojiParentBuildMissing('Parent image Koji build NOT found for {}!'.format(nvr)) | [
"def",
"wait_for_parent_image_build",
"(",
"self",
",",
"nvr",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Waiting for Koji build for parent image %s'",
",",
"nvr",
")",
"poll_start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(... | Given image NVR, wait for the build that produced it to show up in koji.
If it doesn't within the timeout, raise an error.
:return build info dict with 'nvr' and 'id' keys | [
"Given",
"image",
"NVR",
"wait",
"for",
"the",
"build",
"that",
"produced",
"it",
"to",
"show",
"up",
"in",
"koji",
".",
"If",
"it",
"doesn",
"t",
"within",
"the",
"timeout",
"raise",
"an",
"error",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_koji_parent.py#L127-L146 | train | 28,516 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_koji_parent.py | KojiParentPlugin.make_result | def make_result(self):
"""Construct the result dict to be preserved in the build metadata."""
result = {}
if self._base_image_build:
result[BASE_IMAGE_KOJI_BUILD] = self._base_image_build
if self._parent_builds:
result[PARENT_IMAGES_KOJI_BUILDS] = self._parent_builds
return result if result else None | python | def make_result(self):
"""Construct the result dict to be preserved in the build metadata."""
result = {}
if self._base_image_build:
result[BASE_IMAGE_KOJI_BUILD] = self._base_image_build
if self._parent_builds:
result[PARENT_IMAGES_KOJI_BUILDS] = self._parent_builds
return result if result else None | [
"def",
"make_result",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"if",
"self",
".",
"_base_image_build",
":",
"result",
"[",
"BASE_IMAGE_KOJI_BUILD",
"]",
"=",
"self",
".",
"_base_image_build",
"if",
"self",
".",
"_parent_builds",
":",
"result",
"[",
... | Construct the result dict to be preserved in the build metadata. | [
"Construct",
"the",
"result",
"dict",
"to",
"be",
"preserved",
"in",
"the",
"build",
"metadata",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_koji_parent.py#L148-L155 | train | 28,517 |
projectatomic/atomic-reactor | atomic_reactor/util.py | wait_for_command | def wait_for_command(logs_generator):
"""
Create a CommandResult from given iterator
:return: CommandResult
"""
logger.info("wait_for_command")
cr = CommandResult()
for item in logs_generator:
cr.parse_item(item)
logger.info("no more logs")
return cr | python | def wait_for_command(logs_generator):
"""
Create a CommandResult from given iterator
:return: CommandResult
"""
logger.info("wait_for_command")
cr = CommandResult()
for item in logs_generator:
cr.parse_item(item)
logger.info("no more logs")
return cr | [
"def",
"wait_for_command",
"(",
"logs_generator",
")",
":",
"logger",
".",
"info",
"(",
"\"wait_for_command\"",
")",
"cr",
"=",
"CommandResult",
"(",
")",
"for",
"item",
"in",
"logs_generator",
":",
"cr",
".",
"parse_item",
"(",
"item",
")",
"logger",
".",
... | Create a CommandResult from given iterator
:return: CommandResult | [
"Create",
"a",
"CommandResult",
"from",
"given",
"iterator"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L290-L302 | train | 28,518 |
projectatomic/atomic-reactor | atomic_reactor/util.py | print_version_of_tools | def print_version_of_tools():
"""
print versions of used tools to logger
"""
logger.info("Using these tools:")
for tool in get_version_of_tools():
logger.info("%s-%s at %s", tool["name"], tool["version"], tool["path"]) | python | def print_version_of_tools():
"""
print versions of used tools to logger
"""
logger.info("Using these tools:")
for tool in get_version_of_tools():
logger.info("%s-%s at %s", tool["name"], tool["version"], tool["path"]) | [
"def",
"print_version_of_tools",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Using these tools:\"",
")",
"for",
"tool",
"in",
"get_version_of_tools",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"%s-%s at %s\"",
",",
"tool",
"[",
"\"name\"",
"]",
",",
"too... | print versions of used tools to logger | [
"print",
"versions",
"of",
"used",
"tools",
"to",
"logger"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L566-L572 | train | 28,519 |
projectatomic/atomic-reactor | atomic_reactor/util.py | guess_manifest_media_type | def guess_manifest_media_type(content):
"""
Guess the media type for the given manifest content
:param content: JSON content of manifest (bytes)
:return: media type (str), or None if unable to guess
"""
encoding = guess_json_utf(content)
try:
manifest = json.loads(content.decode(encoding))
except (ValueError, # Not valid JSON
TypeError, # Not an object
UnicodeDecodeError): # Unable to decode the bytes
logger.exception("Unable to decode JSON")
logger.debug("response content (%s): %r", encoding, content)
return None
try:
return manifest['mediaType']
except KeyError:
# no mediaType key
if manifest.get('schemaVersion') == 1:
return get_manifest_media_type('v1')
logger.warning("no mediaType or schemaVersion=1 in manifest, keys: %s",
manifest.keys()) | python | def guess_manifest_media_type(content):
"""
Guess the media type for the given manifest content
:param content: JSON content of manifest (bytes)
:return: media type (str), or None if unable to guess
"""
encoding = guess_json_utf(content)
try:
manifest = json.loads(content.decode(encoding))
except (ValueError, # Not valid JSON
TypeError, # Not an object
UnicodeDecodeError): # Unable to decode the bytes
logger.exception("Unable to decode JSON")
logger.debug("response content (%s): %r", encoding, content)
return None
try:
return manifest['mediaType']
except KeyError:
# no mediaType key
if manifest.get('schemaVersion') == 1:
return get_manifest_media_type('v1')
logger.warning("no mediaType or schemaVersion=1 in manifest, keys: %s",
manifest.keys()) | [
"def",
"guess_manifest_media_type",
"(",
"content",
")",
":",
"encoding",
"=",
"guess_json_utf",
"(",
"content",
")",
"try",
":",
"manifest",
"=",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
"encoding",
")",
")",
"except",
"(",
"ValueError",
... | Guess the media type for the given manifest content
:param content: JSON content of manifest (bytes)
:return: media type (str), or None if unable to guess | [
"Guess",
"the",
"media",
"type",
"for",
"the",
"given",
"manifest",
"content"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L858-L883 | train | 28,520 |
projectatomic/atomic-reactor | atomic_reactor/util.py | manifest_is_media_type | def manifest_is_media_type(response, media_type):
"""
Attempt to confirm the returned manifest is of a given media type
:param response: a requests.Response
:param media_type: media_type (str), or None to confirm
the media type cannot be guessed
"""
try:
received_media_type = response.headers['Content-Type']
except KeyError:
# Guess media type from content
logger.debug("No Content-Type header; inspecting content")
received_media_type = guess_manifest_media_type(response.content)
logger.debug("guessed media type: %s", received_media_type)
if received_media_type is None:
return media_type is None
# Only compare prefix as response may use +prettyjws suffix
# which is the case for signed manifest
response_h_prefix = received_media_type.rsplit('+', 1)[0]
request_h_prefix = media_type.rsplit('+', 1)[0]
return response_h_prefix == request_h_prefix | python | def manifest_is_media_type(response, media_type):
"""
Attempt to confirm the returned manifest is of a given media type
:param response: a requests.Response
:param media_type: media_type (str), or None to confirm
the media type cannot be guessed
"""
try:
received_media_type = response.headers['Content-Type']
except KeyError:
# Guess media type from content
logger.debug("No Content-Type header; inspecting content")
received_media_type = guess_manifest_media_type(response.content)
logger.debug("guessed media type: %s", received_media_type)
if received_media_type is None:
return media_type is None
# Only compare prefix as response may use +prettyjws suffix
# which is the case for signed manifest
response_h_prefix = received_media_type.rsplit('+', 1)[0]
request_h_prefix = media_type.rsplit('+', 1)[0]
return response_h_prefix == request_h_prefix | [
"def",
"manifest_is_media_type",
"(",
"response",
",",
"media_type",
")",
":",
"try",
":",
"received_media_type",
"=",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"except",
"KeyError",
":",
"# Guess media type from content",
"logger",
".",
"debug",
"(",
... | Attempt to confirm the returned manifest is of a given media type
:param response: a requests.Response
:param media_type: media_type (str), or None to confirm
the media type cannot be guessed | [
"Attempt",
"to",
"confirm",
"the",
"returned",
"manifest",
"is",
"of",
"a",
"given",
"media",
"type"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L886-L909 | train | 28,521 |
projectatomic/atomic-reactor | atomic_reactor/util.py | get_manifest_list | def get_manifest_list(image, registry, insecure=False, dockercfg_path=None):
"""Return manifest list for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:return: response, or None, with manifest list
"""
version = 'v2_list'
registry_session = RegistrySession(registry, insecure=insecure, dockercfg_path=dockercfg_path)
response, _ = get_manifest(image, registry_session, version)
return response | python | def get_manifest_list(image, registry, insecure=False, dockercfg_path=None):
"""Return manifest list for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:return: response, or None, with manifest list
"""
version = 'v2_list'
registry_session = RegistrySession(registry, insecure=insecure, dockercfg_path=dockercfg_path)
response, _ = get_manifest(image, registry_session, version)
return response | [
"def",
"get_manifest_list",
"(",
"image",
",",
"registry",
",",
"insecure",
"=",
"False",
",",
"dockercfg_path",
"=",
"None",
")",
":",
"version",
"=",
"'v2_list'",
"registry_session",
"=",
"RegistrySession",
"(",
"registry",
",",
"insecure",
"=",
"insecure",
... | Return manifest list for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:return: response, or None, with manifest list | [
"Return",
"manifest",
"list",
"for",
"image",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1004-L1018 | train | 28,522 |
projectatomic/atomic-reactor | atomic_reactor/util.py | get_all_manifests | def get_all_manifests(image, registry, insecure=False, dockercfg_path=None,
versions=('v1', 'v2', 'v2_list')):
"""Return manifest digests for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:param versions: tuple, for which manifest schema versions to fetch manifests
:return: dict of successful responses, with versions as keys
"""
digests = {}
registry_session = RegistrySession(registry, insecure=insecure, dockercfg_path=dockercfg_path)
for version in versions:
response, _ = get_manifest(image, registry_session, version)
if response:
digests[version] = response
return digests | python | def get_all_manifests(image, registry, insecure=False, dockercfg_path=None,
versions=('v1', 'v2', 'v2_list')):
"""Return manifest digests for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:param versions: tuple, for which manifest schema versions to fetch manifests
:return: dict of successful responses, with versions as keys
"""
digests = {}
registry_session = RegistrySession(registry, insecure=insecure, dockercfg_path=dockercfg_path)
for version in versions:
response, _ = get_manifest(image, registry_session, version)
if response:
digests[version] = response
return digests | [
"def",
"get_all_manifests",
"(",
"image",
",",
"registry",
",",
"insecure",
"=",
"False",
",",
"dockercfg_path",
"=",
"None",
",",
"versions",
"=",
"(",
"'v1'",
",",
"'v2'",
",",
"'v2_list'",
")",
")",
":",
"digests",
"=",
"{",
"}",
"registry_session",
"... | Return manifest digests for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:param versions: tuple, for which manifest schema versions to fetch manifests
:return: dict of successful responses, with versions as keys | [
"Return",
"manifest",
"digests",
"for",
"image",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1021-L1041 | train | 28,523 |
projectatomic/atomic-reactor | atomic_reactor/util.py | get_inspect_for_image | def get_inspect_for_image(image, registry, insecure=False, dockercfg_path=None):
"""Return inspect for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:return: dict of inspected image
"""
all_man_digests = get_all_manifests(image, registry, insecure=insecure,
dockercfg_path=dockercfg_path)
blob_config = None
config_digest = None
image_inspect = {}
# we have manifest list (get digest for 1st platform)
if 'v2_list' in all_man_digests:
man_list_json = all_man_digests['v2_list'].json()
if man_list_json['manifests'][0]['mediaType'] != MEDIA_TYPE_DOCKER_V2_SCHEMA2:
raise RuntimeError('Image {image_name}: v2 schema 1 '
'in manifest list'.format(image_name=image))
v2_digest = man_list_json['manifests'][0]['digest']
blob_config, config_digest = get_config_and_id_from_registry(image, registry, v2_digest,
insecure=insecure,
version='v2',
dockercfg_path=dockercfg_path)
# get config for v2 digest
elif 'v2' in all_man_digests:
blob_config, config_digest = get_config_and_id_from_registry(image, registry, image.tag,
insecure=insecure,
version='v2',
dockercfg_path=dockercfg_path)
# read config from v1
elif 'v1' in all_man_digests:
v1_json = all_man_digests['v1'].json()
if PY2:
blob_config = json.loads(v1_json['history'][0]['v1Compatibility'].decode('utf-8'))
else:
blob_config = json.loads(v1_json['history'][0]['v1Compatibility'])
else:
raise RuntimeError("Image {image_name} not found: No v2 schema 1 image, or v2 schema 2 "
"image or list, found".format(image_name=image))
# dictionary to convert config keys to inspect keys
config_2_inspect = {
'created': 'Created',
'os': 'Os',
'container_config': 'ContainerConfig',
'architecture': 'Architecture',
'docker_version': 'DockerVersion',
'config': 'Config',
}
if not blob_config:
raise RuntimeError("Image {image_name}: Couldn't get inspect data "
"from digest config".format(image_name=image))
# set Id, which isn't in config blob, won't be set for v1, as for that image has to be pulled
image_inspect['Id'] = config_digest
# only v2 has rootfs, not v1
if 'rootfs' in blob_config:
image_inspect['RootFS'] = blob_config['rootfs']
for old_key, new_key in config_2_inspect.items():
image_inspect[new_key] = blob_config[old_key]
return image_inspect | python | def get_inspect_for_image(image, registry, insecure=False, dockercfg_path=None):
"""Return inspect for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:return: dict of inspected image
"""
all_man_digests = get_all_manifests(image, registry, insecure=insecure,
dockercfg_path=dockercfg_path)
blob_config = None
config_digest = None
image_inspect = {}
# we have manifest list (get digest for 1st platform)
if 'v2_list' in all_man_digests:
man_list_json = all_man_digests['v2_list'].json()
if man_list_json['manifests'][0]['mediaType'] != MEDIA_TYPE_DOCKER_V2_SCHEMA2:
raise RuntimeError('Image {image_name}: v2 schema 1 '
'in manifest list'.format(image_name=image))
v2_digest = man_list_json['manifests'][0]['digest']
blob_config, config_digest = get_config_and_id_from_registry(image, registry, v2_digest,
insecure=insecure,
version='v2',
dockercfg_path=dockercfg_path)
# get config for v2 digest
elif 'v2' in all_man_digests:
blob_config, config_digest = get_config_and_id_from_registry(image, registry, image.tag,
insecure=insecure,
version='v2',
dockercfg_path=dockercfg_path)
# read config from v1
elif 'v1' in all_man_digests:
v1_json = all_man_digests['v1'].json()
if PY2:
blob_config = json.loads(v1_json['history'][0]['v1Compatibility'].decode('utf-8'))
else:
blob_config = json.loads(v1_json['history'][0]['v1Compatibility'])
else:
raise RuntimeError("Image {image_name} not found: No v2 schema 1 image, or v2 schema 2 "
"image or list, found".format(image_name=image))
# dictionary to convert config keys to inspect keys
config_2_inspect = {
'created': 'Created',
'os': 'Os',
'container_config': 'ContainerConfig',
'architecture': 'Architecture',
'docker_version': 'DockerVersion',
'config': 'Config',
}
if not blob_config:
raise RuntimeError("Image {image_name}: Couldn't get inspect data "
"from digest config".format(image_name=image))
# set Id, which isn't in config blob, won't be set for v1, as for that image has to be pulled
image_inspect['Id'] = config_digest
# only v2 has rootfs, not v1
if 'rootfs' in blob_config:
image_inspect['RootFS'] = blob_config['rootfs']
for old_key, new_key in config_2_inspect.items():
image_inspect[new_key] = blob_config[old_key]
return image_inspect | [
"def",
"get_inspect_for_image",
"(",
"image",
",",
"registry",
",",
"insecure",
"=",
"False",
",",
"dockercfg_path",
"=",
"None",
")",
":",
"all_man_digests",
"=",
"get_all_manifests",
"(",
"image",
",",
"registry",
",",
"insecure",
"=",
"insecure",
",",
"dock... | Return inspect for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirname of .dockercfg location
:return: dict of inspected image | [
"Return",
"inspect",
"for",
"image",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1044-L1113 | train | 28,524 |
projectatomic/atomic-reactor | atomic_reactor/util.py | df_parser | def df_parser(df_path, workflow=None, cache_content=False, env_replace=True, parent_env=None):
"""
Wrapper for dockerfile_parse's DockerfileParser that takes into account
parent_env inheritance.
:param df_path: string, path to Dockerfile (normally in DockerBuildWorkflow instance)
:param workflow: DockerBuildWorkflow object instance, used to find parent image information
:param cache_content: bool, tells DockerfileParser to cache Dockerfile content
:param env_replace: bool, replace ENV declarations as part of DockerfileParser evaluation
:param parent_env: dict, parent ENV key:value pairs to be inherited
:return: DockerfileParser object instance
"""
p_env = {}
if parent_env:
# If parent_env passed in, just use that
p_env = parent_env
elif workflow:
# If parent_env is not provided, but workflow is then attempt to inspect
# the workflow for the parent_env
try:
parent_config = workflow.builder.base_image_inspect[INSPECT_CONFIG]
except (AttributeError, TypeError, KeyError):
logger.debug("base image unable to be inspected")
else:
try:
tmp_env = parent_config["Env"]
logger.debug("Parent Config ENV: %s" % tmp_env)
if isinstance(tmp_env, dict):
p_env = tmp_env
elif isinstance(tmp_env, list):
try:
for key_val in tmp_env:
key, val = key_val.split("=", 1)
p_env[key] = val
except ValueError:
logger.debug("Unable to parse all of Parent Config ENV")
except KeyError:
logger.debug("Parent Environment not found, not applied to Dockerfile")
try:
dfparser = DockerfileParser(
df_path,
cache_content=cache_content,
env_replace=env_replace,
parent_env=p_env
)
except TypeError:
logger.debug("Old version of dockerfile-parse detected, unable to set inherited parent "
"ENVs")
dfparser = DockerfileParser(
df_path,
cache_content=cache_content,
env_replace=env_replace,
)
return dfparser | python | def df_parser(df_path, workflow=None, cache_content=False, env_replace=True, parent_env=None):
"""
Wrapper for dockerfile_parse's DockerfileParser that takes into account
parent_env inheritance.
:param df_path: string, path to Dockerfile (normally in DockerBuildWorkflow instance)
:param workflow: DockerBuildWorkflow object instance, used to find parent image information
:param cache_content: bool, tells DockerfileParser to cache Dockerfile content
:param env_replace: bool, replace ENV declarations as part of DockerfileParser evaluation
:param parent_env: dict, parent ENV key:value pairs to be inherited
:return: DockerfileParser object instance
"""
p_env = {}
if parent_env:
# If parent_env passed in, just use that
p_env = parent_env
elif workflow:
# If parent_env is not provided, but workflow is then attempt to inspect
# the workflow for the parent_env
try:
parent_config = workflow.builder.base_image_inspect[INSPECT_CONFIG]
except (AttributeError, TypeError, KeyError):
logger.debug("base image unable to be inspected")
else:
try:
tmp_env = parent_config["Env"]
logger.debug("Parent Config ENV: %s" % tmp_env)
if isinstance(tmp_env, dict):
p_env = tmp_env
elif isinstance(tmp_env, list):
try:
for key_val in tmp_env:
key, val = key_val.split("=", 1)
p_env[key] = val
except ValueError:
logger.debug("Unable to parse all of Parent Config ENV")
except KeyError:
logger.debug("Parent Environment not found, not applied to Dockerfile")
try:
dfparser = DockerfileParser(
df_path,
cache_content=cache_content,
env_replace=env_replace,
parent_env=p_env
)
except TypeError:
logger.debug("Old version of dockerfile-parse detected, unable to set inherited parent "
"ENVs")
dfparser = DockerfileParser(
df_path,
cache_content=cache_content,
env_replace=env_replace,
)
return dfparser | [
"def",
"df_parser",
"(",
"df_path",
",",
"workflow",
"=",
"None",
",",
"cache_content",
"=",
"False",
",",
"env_replace",
"=",
"True",
",",
"parent_env",
"=",
"None",
")",
":",
"p_env",
"=",
"{",
"}",
"if",
"parent_env",
":",
"# If parent_env passed in, just... | Wrapper for dockerfile_parse's DockerfileParser that takes into account
parent_env inheritance.
:param df_path: string, path to Dockerfile (normally in DockerBuildWorkflow instance)
:param workflow: DockerBuildWorkflow object instance, used to find parent image information
:param cache_content: bool, tells DockerfileParser to cache Dockerfile content
:param env_replace: bool, replace ENV declarations as part of DockerfileParser evaluation
:param parent_env: dict, parent ENV key:value pairs to be inherited
:return: DockerfileParser object instance | [
"Wrapper",
"for",
"dockerfile_parse",
"s",
"DockerfileParser",
"that",
"takes",
"into",
"account",
"parent_env",
"inheritance",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1171-L1235 | train | 28,525 |
projectatomic/atomic-reactor | atomic_reactor/util.py | are_plugins_in_order | def are_plugins_in_order(plugins_conf, *plugins_names):
"""Check if plugins are configured in given order."""
all_plugins_names = [plugin['name'] for plugin in plugins_conf or []]
start_index = 0
for plugin_name in plugins_names:
try:
start_index = all_plugins_names.index(plugin_name, start_index)
except ValueError:
return False
return True | python | def are_plugins_in_order(plugins_conf, *plugins_names):
"""Check if plugins are configured in given order."""
all_plugins_names = [plugin['name'] for plugin in plugins_conf or []]
start_index = 0
for plugin_name in plugins_names:
try:
start_index = all_plugins_names.index(plugin_name, start_index)
except ValueError:
return False
return True | [
"def",
"are_plugins_in_order",
"(",
"plugins_conf",
",",
"*",
"plugins_names",
")",
":",
"all_plugins_names",
"=",
"[",
"plugin",
"[",
"'name'",
"]",
"for",
"plugin",
"in",
"plugins_conf",
"or",
"[",
"]",
"]",
"start_index",
"=",
"0",
"for",
"plugin_name",
"... | Check if plugins are configured in given order. | [
"Check",
"if",
"plugins",
"are",
"configured",
"in",
"given",
"order",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1238-L1247 | train | 28,526 |
projectatomic/atomic-reactor | atomic_reactor/util.py | get_parent_image_koji_data | def get_parent_image_koji_data(workflow):
"""Transform koji_parent plugin results into metadata dict."""
koji_parent = workflow.prebuild_results.get(PLUGIN_KOJI_PARENT_KEY) or {}
image_metadata = {}
parents = {}
for img, build in (koji_parent.get(PARENT_IMAGES_KOJI_BUILDS) or {}).items():
if not build:
parents[str(img)] = None
else:
parents[str(img)] = {key: val for key, val in build.items() if key in ('id', 'nvr')}
image_metadata[PARENT_IMAGE_BUILDS_KEY] = parents
# ordered list of parent images
image_metadata[PARENT_IMAGES_KEY] = workflow.builder.parents_ordered
# don't add parent image id key for scratch
if workflow.builder.base_from_scratch:
return image_metadata
base_info = koji_parent.get(BASE_IMAGE_KOJI_BUILD) or {}
parent_id = base_info.get('id')
if parent_id is not None:
try:
parent_id = int(parent_id)
except ValueError:
logger.exception("invalid koji parent id %r", parent_id)
else:
image_metadata[BASE_IMAGE_BUILD_ID_KEY] = parent_id
return image_metadata | python | def get_parent_image_koji_data(workflow):
"""Transform koji_parent plugin results into metadata dict."""
koji_parent = workflow.prebuild_results.get(PLUGIN_KOJI_PARENT_KEY) or {}
image_metadata = {}
parents = {}
for img, build in (koji_parent.get(PARENT_IMAGES_KOJI_BUILDS) or {}).items():
if not build:
parents[str(img)] = None
else:
parents[str(img)] = {key: val for key, val in build.items() if key in ('id', 'nvr')}
image_metadata[PARENT_IMAGE_BUILDS_KEY] = parents
# ordered list of parent images
image_metadata[PARENT_IMAGES_KEY] = workflow.builder.parents_ordered
# don't add parent image id key for scratch
if workflow.builder.base_from_scratch:
return image_metadata
base_info = koji_parent.get(BASE_IMAGE_KOJI_BUILD) or {}
parent_id = base_info.get('id')
if parent_id is not None:
try:
parent_id = int(parent_id)
except ValueError:
logger.exception("invalid koji parent id %r", parent_id)
else:
image_metadata[BASE_IMAGE_BUILD_ID_KEY] = parent_id
return image_metadata | [
"def",
"get_parent_image_koji_data",
"(",
"workflow",
")",
":",
"koji_parent",
"=",
"workflow",
".",
"prebuild_results",
".",
"get",
"(",
"PLUGIN_KOJI_PARENT_KEY",
")",
"or",
"{",
"}",
"image_metadata",
"=",
"{",
"}",
"parents",
"=",
"{",
"}",
"for",
"img",
... | Transform koji_parent plugin results into metadata dict. | [
"Transform",
"koji_parent",
"plugin",
"results",
"into",
"metadata",
"dict",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1361-L1390 | train | 28,527 |
projectatomic/atomic-reactor | atomic_reactor/util.py | Dockercfg.unpack_auth_b64 | def unpack_auth_b64(self, docker_registry):
"""Decode and unpack base64 'auth' credentials from config file.
:param docker_registry: str, registry reference in config file
:return: namedtuple, UnpackedAuth (or None if no 'auth' is available)
"""
UnpackedAuth = namedtuple('UnpackedAuth', ['raw_str', 'username', 'password'])
credentials = self.get_credentials(docker_registry)
auth_b64 = credentials.get('auth')
if auth_b64:
raw_str = b64decode(auth_b64).decode('utf-8')
unpacked_credentials = raw_str.split(':', 1)
if len(unpacked_credentials) == 2:
return UnpackedAuth(raw_str, *unpacked_credentials)
else:
raise ValueError("Failed to parse 'auth' in '%s'" % self.json_secret_path) | python | def unpack_auth_b64(self, docker_registry):
"""Decode and unpack base64 'auth' credentials from config file.
:param docker_registry: str, registry reference in config file
:return: namedtuple, UnpackedAuth (or None if no 'auth' is available)
"""
UnpackedAuth = namedtuple('UnpackedAuth', ['raw_str', 'username', 'password'])
credentials = self.get_credentials(docker_registry)
auth_b64 = credentials.get('auth')
if auth_b64:
raw_str = b64decode(auth_b64).decode('utf-8')
unpacked_credentials = raw_str.split(':', 1)
if len(unpacked_credentials) == 2:
return UnpackedAuth(raw_str, *unpacked_credentials)
else:
raise ValueError("Failed to parse 'auth' in '%s'" % self.json_secret_path) | [
"def",
"unpack_auth_b64",
"(",
"self",
",",
"docker_registry",
")",
":",
"UnpackedAuth",
"=",
"namedtuple",
"(",
"'UnpackedAuth'",
",",
"[",
"'raw_str'",
",",
"'username'",
",",
"'password'",
"]",
")",
"credentials",
"=",
"self",
".",
"get_credentials",
"(",
"... | Decode and unpack base64 'auth' credentials from config file.
:param docker_registry: str, registry reference in config file
:return: namedtuple, UnpackedAuth (or None if no 'auth' is available) | [
"Decode",
"and",
"unpack",
"base64",
"auth",
"credentials",
"from",
"config",
"file",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L689-L705 | train | 28,528 |
projectatomic/atomic-reactor | atomic_reactor/util.py | ManifestDigest.default | def default(self):
"""Return the default manifest schema version.
Depending on the docker version, <= 1.9, used to push
the image to the registry, v2 schema may not be available.
In such case, the v1 schema should be used when interacting
with the registry. An OCI digest will only be present when
the manifest was pushed as an OCI digest.
"""
return self.v2_list or self.oci_index or self.oci or self.v2 or self.v1 | python | def default(self):
"""Return the default manifest schema version.
Depending on the docker version, <= 1.9, used to push
the image to the registry, v2 schema may not be available.
In such case, the v1 schema should be used when interacting
with the registry. An OCI digest will only be present when
the manifest was pushed as an OCI digest.
"""
return self.v2_list or self.oci_index or self.oci or self.v2 or self.v1 | [
"def",
"default",
"(",
"self",
")",
":",
"return",
"self",
".",
"v2_list",
"or",
"self",
".",
"oci_index",
"or",
"self",
".",
"oci",
"or",
"self",
".",
"v2",
"or",
"self",
".",
"v1"
] | Return the default manifest schema version.
Depending on the docker version, <= 1.9, used to push
the image to the registry, v2 schema may not be available.
In such case, the v1 schema should be used when interacting
with the registry. An OCI digest will only be present when
the manifest was pushed as an OCI digest. | [
"Return",
"the",
"default",
"manifest",
"schema",
"version",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L779-L788 | train | 28,529 |
projectatomic/atomic-reactor | atomic_reactor/util.py | OSBSLogs.get_log_files | def get_log_files(self, osbs, build_id):
"""
Build list of log files
:return: list, of log files
"""
logs = None
output = []
# Collect logs from server
try:
logs = osbs.get_orchestrator_build_logs(build_id)
except OsbsException as ex:
self.log.error("unable to get build logs: %r", ex)
return output
except TypeError:
# Older osbs-client has no get_orchestrator_build_logs
self.log.error("OSBS client does not support get_orchestrator_build_logs")
return output
platform_logs = {}
for entry in logs:
platform = entry.platform
if platform not in platform_logs:
filename = 'orchestrator' if platform is None else platform
platform_logs[platform] = NamedTemporaryFile(prefix="%s-%s" %
(build_id, filename),
suffix=".log", mode='r+b')
platform_logs[platform].write((entry.line + '\n').encode('utf-8'))
for platform, logfile in platform_logs.items():
logfile.flush()
filename = 'orchestrator' if platform is None else platform
metadata = self.get_log_metadata(logfile.name, "%s.log" % filename)
output.append(Output(file=logfile, metadata=metadata))
return output | python | def get_log_files(self, osbs, build_id):
"""
Build list of log files
:return: list, of log files
"""
logs = None
output = []
# Collect logs from server
try:
logs = osbs.get_orchestrator_build_logs(build_id)
except OsbsException as ex:
self.log.error("unable to get build logs: %r", ex)
return output
except TypeError:
# Older osbs-client has no get_orchestrator_build_logs
self.log.error("OSBS client does not support get_orchestrator_build_logs")
return output
platform_logs = {}
for entry in logs:
platform = entry.platform
if platform not in platform_logs:
filename = 'orchestrator' if platform is None else platform
platform_logs[platform] = NamedTemporaryFile(prefix="%s-%s" %
(build_id, filename),
suffix=".log", mode='r+b')
platform_logs[platform].write((entry.line + '\n').encode('utf-8'))
for platform, logfile in platform_logs.items():
logfile.flush()
filename = 'orchestrator' if platform is None else platform
metadata = self.get_log_metadata(logfile.name, "%s.log" % filename)
output.append(Output(file=logfile, metadata=metadata))
return output | [
"def",
"get_log_files",
"(",
"self",
",",
"osbs",
",",
"build_id",
")",
":",
"logs",
"=",
"None",
"output",
"=",
"[",
"]",
"# Collect logs from server",
"try",
":",
"logs",
"=",
"osbs",
".",
"get_orchestrator_build_logs",
"(",
"build_id",
")",
"except",
"Osb... | Build list of log files
:return: list, of log files | [
"Build",
"list",
"of",
"log",
"files"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1412-L1449 | train | 28,530 |
projectatomic/atomic-reactor | atomic_reactor/util.py | DigestCollector.update_image_digest | def update_image_digest(self, image, platform, digest):
"""Update parent image digest for specific platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:param str digest: digest of the specified image (sha256:...)
"""
image_name_tag = self._key(image)
image_name = image.to_str(tag=False)
name_digest = '{}@{}'.format(image_name, digest)
image_digests = self._images_digests.setdefault(image_name_tag, {})
image_digests[platform] = name_digest | python | def update_image_digest(self, image, platform, digest):
"""Update parent image digest for specific platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:param str digest: digest of the specified image (sha256:...)
"""
image_name_tag = self._key(image)
image_name = image.to_str(tag=False)
name_digest = '{}@{}'.format(image_name, digest)
image_digests = self._images_digests.setdefault(image_name_tag, {})
image_digests[platform] = name_digest | [
"def",
"update_image_digest",
"(",
"self",
",",
"image",
",",
"platform",
",",
"digest",
")",
":",
"image_name_tag",
"=",
"self",
".",
"_key",
"(",
"image",
")",
"image_name",
"=",
"image",
".",
"to_str",
"(",
"tag",
"=",
"False",
")",
"name_digest",
"="... | Update parent image digest for specific platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:param str digest: digest of the specified image (sha256:...) | [
"Update",
"parent",
"image",
"digest",
"for",
"specific",
"platform"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1537-L1550 | train | 28,531 |
projectatomic/atomic-reactor | atomic_reactor/util.py | DigestCollector.get_image_digests | def get_image_digests(self, image):
"""Get platform digests of specified image
:param ImageName image: image
:raises KeyError: when image is not found
:rtype: dict
:return: mapping platform:digest of the specified image
"""
image_name_tag = self._key(image)
image_digests = self._images_digests.get(image_name_tag)
if image_digests is None:
raise KeyError('Image {} has no digest records'.format(image_name_tag))
return image_digests | python | def get_image_digests(self, image):
"""Get platform digests of specified image
:param ImageName image: image
:raises KeyError: when image is not found
:rtype: dict
:return: mapping platform:digest of the specified image
"""
image_name_tag = self._key(image)
image_digests = self._images_digests.get(image_name_tag)
if image_digests is None:
raise KeyError('Image {} has no digest records'.format(image_name_tag))
return image_digests | [
"def",
"get_image_digests",
"(",
"self",
",",
"image",
")",
":",
"image_name_tag",
"=",
"self",
".",
"_key",
"(",
"image",
")",
"image_digests",
"=",
"self",
".",
"_images_digests",
".",
"get",
"(",
"image_name_tag",
")",
"if",
"image_digests",
"is",
"None",... | Get platform digests of specified image
:param ImageName image: image
:raises KeyError: when image is not found
:rtype: dict
:return: mapping platform:digest of the specified image | [
"Get",
"platform",
"digests",
"of",
"specified",
"image"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1552-L1564 | train | 28,532 |
projectatomic/atomic-reactor | atomic_reactor/util.py | DigestCollector.get_image_platform_digest | def get_image_platform_digest(self, image, platform):
"""Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest of the specified image (fedora@sha256:...)
"""
image_digests = self.get_image_digests(image)
digest = image_digests.get(platform)
if digest is None:
raise KeyError(
'Image {} has no digest record for platform {}'.format(image, platform)
)
return digest | python | def get_image_platform_digest(self, image, platform):
"""Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest of the specified image (fedora@sha256:...)
"""
image_digests = self.get_image_digests(image)
digest = image_digests.get(platform)
if digest is None:
raise KeyError(
'Image {} has no digest record for platform {}'.format(image, platform)
)
return digest | [
"def",
"get_image_platform_digest",
"(",
"self",
",",
"image",
",",
"platform",
")",
":",
"image_digests",
"=",
"self",
".",
"get_image_digests",
"(",
"image",
")",
"digest",
"=",
"image_digests",
".",
"get",
"(",
"platform",
")",
"if",
"digest",
"is",
"None... | Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest of the specified image (fedora@sha256:...) | [
"Get",
"digest",
"of",
"specified",
"image",
"and",
"platform"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1566-L1582 | train | 28,533 |
projectatomic/atomic-reactor | atomic_reactor/rpm_util.py | rpm_qf_args | def rpm_qf_args(tags=None, separator=';'):
"""
Return the arguments to pass to rpm to list RPMs in the format expected
by parse_rpm_output.
"""
if tags is None:
tags = image_component_rpm_tags
fmt = separator.join(["%%{%s}" % tag for tag in tags])
return r"-qa --qf '{0}\n'".format(fmt) | python | def rpm_qf_args(tags=None, separator=';'):
"""
Return the arguments to pass to rpm to list RPMs in the format expected
by parse_rpm_output.
"""
if tags is None:
tags = image_component_rpm_tags
fmt = separator.join(["%%{%s}" % tag for tag in tags])
return r"-qa --qf '{0}\n'".format(fmt) | [
"def",
"rpm_qf_args",
"(",
"tags",
"=",
"None",
",",
"separator",
"=",
"';'",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"image_component_rpm_tags",
"fmt",
"=",
"separator",
".",
"join",
"(",
"[",
"\"%%{%s}\"",
"%",
"tag",
"for",
"tag",
"i... | Return the arguments to pass to rpm to list RPMs in the format expected
by parse_rpm_output. | [
"Return",
"the",
"arguments",
"to",
"pass",
"to",
"rpm",
"to",
"list",
"RPMs",
"in",
"the",
"format",
"expected",
"by",
"parse_rpm_output",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/rpm_util.py#L23-L33 | train | 28,534 |
projectatomic/atomic-reactor | atomic_reactor/rpm_util.py | parse_rpm_output | def parse_rpm_output(output, tags=None, separator=';'):
"""
Parse output of the rpm query.
:param output: list, decoded output (str) from the rpm subprocess
:param tags: list, str fields used for query output
:return: list, dicts describing each rpm package
"""
if tags is None:
tags = image_component_rpm_tags
def field(tag):
"""
Get a field value by name
"""
try:
value = fields[tags.index(tag)]
except ValueError:
return None
if value == '(none)':
return None
return value
components = []
sigmarker = 'Key ID '
for rpm in output:
fields = rpm.rstrip('\n').split(separator)
if len(fields) < len(tags):
continue
signature = field('SIGPGP:pgpsig') or field('SIGGPG:pgpsig')
if signature:
parts = signature.split(sigmarker, 1)
if len(parts) > 1:
signature = parts[1]
component_rpm = {
'type': 'rpm',
'name': field('NAME'),
'version': field('VERSION'),
'release': field('RELEASE'),
'arch': field('ARCH'),
'sigmd5': field('SIGMD5'),
'signature': signature,
}
# Special handling for epoch as it must be an integer or None
epoch = field('EPOCH')
if epoch is not None:
epoch = int(epoch)
component_rpm['epoch'] = epoch
if component_rpm['name'] != 'gpg-pubkey':
components.append(component_rpm)
return components | python | def parse_rpm_output(output, tags=None, separator=';'):
"""
Parse output of the rpm query.
:param output: list, decoded output (str) from the rpm subprocess
:param tags: list, str fields used for query output
:return: list, dicts describing each rpm package
"""
if tags is None:
tags = image_component_rpm_tags
def field(tag):
"""
Get a field value by name
"""
try:
value = fields[tags.index(tag)]
except ValueError:
return None
if value == '(none)':
return None
return value
components = []
sigmarker = 'Key ID '
for rpm in output:
fields = rpm.rstrip('\n').split(separator)
if len(fields) < len(tags):
continue
signature = field('SIGPGP:pgpsig') or field('SIGGPG:pgpsig')
if signature:
parts = signature.split(sigmarker, 1)
if len(parts) > 1:
signature = parts[1]
component_rpm = {
'type': 'rpm',
'name': field('NAME'),
'version': field('VERSION'),
'release': field('RELEASE'),
'arch': field('ARCH'),
'sigmd5': field('SIGMD5'),
'signature': signature,
}
# Special handling for epoch as it must be an integer or None
epoch = field('EPOCH')
if epoch is not None:
epoch = int(epoch)
component_rpm['epoch'] = epoch
if component_rpm['name'] != 'gpg-pubkey':
components.append(component_rpm)
return components | [
"def",
"parse_rpm_output",
"(",
"output",
",",
"tags",
"=",
"None",
",",
"separator",
"=",
"';'",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"image_component_rpm_tags",
"def",
"field",
"(",
"tag",
")",
":",
"\"\"\"\n Get a field value by na... | Parse output of the rpm query.
:param output: list, decoded output (str) from the rpm subprocess
:param tags: list, str fields used for query output
:return: list, dicts describing each rpm package | [
"Parse",
"output",
"of",
"the",
"rpm",
"query",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/rpm_util.py#L36-L95 | train | 28,535 |
projectatomic/atomic-reactor | atomic_reactor/koji_util.py | koji_login | def koji_login(session,
proxyuser=None,
ssl_certs_dir=None,
krb_principal=None,
krb_keytab=None):
"""
Choose the correct login method based on the available credentials,
and call that method on the provided session object.
:param session: koji.ClientSession instance
:param proxyuser: str, proxy user
:param ssl_certs_dir: str, path to "cert" (required), and "serverca" (optional)
:param krb_principal: str, name of Kerberos principal
:param krb_keytab: str, Kerberos keytab
:return: None
"""
kwargs = {}
if proxyuser:
kwargs['proxyuser'] = proxyuser
if ssl_certs_dir:
# Use certificates
logger.info("Using SSL certificates for Koji authentication")
kwargs['cert'] = os.path.join(ssl_certs_dir, 'cert')
# serverca is not required in newer versions of koji, but if set
# koji will always ensure file exists
# NOTE: older versions of koji may require this to be set, in
# that case, make sure serverca is passed in
serverca_path = os.path.join(ssl_certs_dir, 'serverca')
if os.path.exists(serverca_path):
kwargs['serverca'] = serverca_path
# Older versions of koji actually require this parameter, even though
# it's completely ignored.
kwargs['ca'] = None
result = session.ssl_login(**kwargs)
else:
# Use Kerberos
logger.info("Using Kerberos for Koji authentication")
if krb_principal and krb_keytab:
kwargs['principal'] = krb_principal
kwargs['keytab'] = krb_keytab
result = session.krb_login(**kwargs)
if not result:
raise RuntimeError('Unable to perform Koji authentication')
return result | python | def koji_login(session,
proxyuser=None,
ssl_certs_dir=None,
krb_principal=None,
krb_keytab=None):
"""
Choose the correct login method based on the available credentials,
and call that method on the provided session object.
:param session: koji.ClientSession instance
:param proxyuser: str, proxy user
:param ssl_certs_dir: str, path to "cert" (required), and "serverca" (optional)
:param krb_principal: str, name of Kerberos principal
:param krb_keytab: str, Kerberos keytab
:return: None
"""
kwargs = {}
if proxyuser:
kwargs['proxyuser'] = proxyuser
if ssl_certs_dir:
# Use certificates
logger.info("Using SSL certificates for Koji authentication")
kwargs['cert'] = os.path.join(ssl_certs_dir, 'cert')
# serverca is not required in newer versions of koji, but if set
# koji will always ensure file exists
# NOTE: older versions of koji may require this to be set, in
# that case, make sure serverca is passed in
serverca_path = os.path.join(ssl_certs_dir, 'serverca')
if os.path.exists(serverca_path):
kwargs['serverca'] = serverca_path
# Older versions of koji actually require this parameter, even though
# it's completely ignored.
kwargs['ca'] = None
result = session.ssl_login(**kwargs)
else:
# Use Kerberos
logger.info("Using Kerberos for Koji authentication")
if krb_principal and krb_keytab:
kwargs['principal'] = krb_principal
kwargs['keytab'] = krb_keytab
result = session.krb_login(**kwargs)
if not result:
raise RuntimeError('Unable to perform Koji authentication')
return result | [
"def",
"koji_login",
"(",
"session",
",",
"proxyuser",
"=",
"None",
",",
"ssl_certs_dir",
"=",
"None",
",",
"krb_principal",
"=",
"None",
",",
"krb_keytab",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"proxyuser",
":",
"kwargs",
"[",
"'proxyuse... | Choose the correct login method based on the available credentials,
and call that method on the provided session object.
:param session: koji.ClientSession instance
:param proxyuser: str, proxy user
:param ssl_certs_dir: str, path to "cert" (required), and "serverca" (optional)
:param krb_principal: str, name of Kerberos principal
:param krb_keytab: str, Kerberos keytab
:return: None | [
"Choose",
"the",
"correct",
"login",
"method",
"based",
"on",
"the",
"available",
"credentials",
"and",
"call",
"that",
"method",
"on",
"the",
"provided",
"session",
"object",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/koji_util.py#L75-L126 | train | 28,536 |
projectatomic/atomic-reactor | atomic_reactor/koji_util.py | create_koji_session | def create_koji_session(hub_url, auth_info=None):
"""
Creates and returns a Koji session. If auth_info
is provided, the session will be authenticated.
:param hub_url: str, Koji hub URL
:param auth_info: dict, authentication parameters used for koji_login
:return: koji.ClientSession instance
"""
session = KojiSessionWrapper(koji.ClientSession(hub_url, opts={'krb_rdns': False}))
if auth_info is not None:
koji_login(session, **auth_info)
return session | python | def create_koji_session(hub_url, auth_info=None):
"""
Creates and returns a Koji session. If auth_info
is provided, the session will be authenticated.
:param hub_url: str, Koji hub URL
:param auth_info: dict, authentication parameters used for koji_login
:return: koji.ClientSession instance
"""
session = KojiSessionWrapper(koji.ClientSession(hub_url, opts={'krb_rdns': False}))
if auth_info is not None:
koji_login(session, **auth_info)
return session | [
"def",
"create_koji_session",
"(",
"hub_url",
",",
"auth_info",
"=",
"None",
")",
":",
"session",
"=",
"KojiSessionWrapper",
"(",
"koji",
".",
"ClientSession",
"(",
"hub_url",
",",
"opts",
"=",
"{",
"'krb_rdns'",
":",
"False",
"}",
")",
")",
"if",
"auth_in... | Creates and returns a Koji session. If auth_info
is provided, the session will be authenticated.
:param hub_url: str, Koji hub URL
:param auth_info: dict, authentication parameters used for koji_login
:return: koji.ClientSession instance | [
"Creates",
"and",
"returns",
"a",
"Koji",
"session",
".",
"If",
"auth_info",
"is",
"provided",
"the",
"session",
"will",
"be",
"authenticated",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/koji_util.py#L129-L143 | train | 28,537 |
projectatomic/atomic-reactor | atomic_reactor/koji_util.py | stream_task_output | def stream_task_output(session, task_id, file_name,
blocksize=DEFAULT_DOWNLOAD_BLOCK_SIZE):
"""
Generator to download file from task without loading the whole
file into memory.
"""
logger.debug('Streaming {} from task {}'.format(file_name, task_id))
offset = 0
contents = '[PLACEHOLDER]'
while contents:
contents = session.downloadTaskOutput(task_id, file_name, offset,
blocksize)
offset += len(contents)
if contents:
yield contents
logger.debug('Finished streaming {} from task {}'.format(file_name, task_id)) | python | def stream_task_output(session, task_id, file_name,
blocksize=DEFAULT_DOWNLOAD_BLOCK_SIZE):
"""
Generator to download file from task without loading the whole
file into memory.
"""
logger.debug('Streaming {} from task {}'.format(file_name, task_id))
offset = 0
contents = '[PLACEHOLDER]'
while contents:
contents = session.downloadTaskOutput(task_id, file_name, offset,
blocksize)
offset += len(contents)
if contents:
yield contents
logger.debug('Finished streaming {} from task {}'.format(file_name, task_id)) | [
"def",
"stream_task_output",
"(",
"session",
",",
"task_id",
",",
"file_name",
",",
"blocksize",
"=",
"DEFAULT_DOWNLOAD_BLOCK_SIZE",
")",
":",
"logger",
".",
"debug",
"(",
"'Streaming {} from task {}'",
".",
"format",
"(",
"file_name",
",",
"task_id",
")",
")",
... | Generator to download file from task without loading the whole
file into memory. | [
"Generator",
"to",
"download",
"file",
"from",
"task",
"without",
"loading",
"the",
"whole",
"file",
"into",
"memory",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/koji_util.py#L167-L183 | train | 28,538 |
projectatomic/atomic-reactor | atomic_reactor/yum_util.py | YumRepo.filename | def filename(self):
'''Returns the filename to be used for saving the repo file.
The filename is derived from the repo url by injecting a suffix
after the name and before the file extension. This suffix is a
partial md5 checksum of the full repourl. This avoids multiple
repos from being written to the same file.
'''
urlpath = unquote(urlsplit(self.repourl, allow_fragments=False).path)
basename = os.path.basename(urlpath)
if not basename.endswith(REPO_SUFFIX):
basename += REPO_SUFFIX
if self.add_hash:
suffix = '-' + md5(self.repourl.encode('utf-8')).hexdigest()[:5]
else:
suffix = ''
final_name = suffix.join(os.path.splitext(basename))
return final_name | python | def filename(self):
'''Returns the filename to be used for saving the repo file.
The filename is derived from the repo url by injecting a suffix
after the name and before the file extension. This suffix is a
partial md5 checksum of the full repourl. This avoids multiple
repos from being written to the same file.
'''
urlpath = unquote(urlsplit(self.repourl, allow_fragments=False).path)
basename = os.path.basename(urlpath)
if not basename.endswith(REPO_SUFFIX):
basename += REPO_SUFFIX
if self.add_hash:
suffix = '-' + md5(self.repourl.encode('utf-8')).hexdigest()[:5]
else:
suffix = ''
final_name = suffix.join(os.path.splitext(basename))
return final_name | [
"def",
"filename",
"(",
"self",
")",
":",
"urlpath",
"=",
"unquote",
"(",
"urlsplit",
"(",
"self",
".",
"repourl",
",",
"allow_fragments",
"=",
"False",
")",
".",
"path",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"urlpath",
")",
... | Returns the filename to be used for saving the repo file.
The filename is derived from the repo url by injecting a suffix
after the name and before the file extension. This suffix is a
partial md5 checksum of the full repourl. This avoids multiple
repos from being written to the same file. | [
"Returns",
"the",
"filename",
"to",
"be",
"used",
"for",
"saving",
"the",
"repo",
"file",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/yum_util.py#L48-L65 | train | 28,539 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_compare_components.py | filter_components_by_name | def filter_components_by_name(name, components_list, type_=T_RPM):
"""Generator filters components from components_list by name"""
for components in components_list:
for component in components:
if component['type'] == type_ and component['name'] == name:
yield component | python | def filter_components_by_name(name, components_list, type_=T_RPM):
"""Generator filters components from components_list by name"""
for components in components_list:
for component in components:
if component['type'] == type_ and component['name'] == name:
yield component | [
"def",
"filter_components_by_name",
"(",
"name",
",",
"components_list",
",",
"type_",
"=",
"T_RPM",
")",
":",
"for",
"components",
"in",
"components_list",
":",
"for",
"component",
"in",
"components",
":",
"if",
"component",
"[",
"'type'",
"]",
"==",
"type_",... | Generator filters components from components_list by name | [
"Generator",
"filters",
"components",
"from",
"components_list",
"by",
"name"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_compare_components.py#L22-L27 | train | 28,540 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_compare_components.py | CompareComponentsPlugin.get_component_list_from_workers | def get_component_list_from_workers(self, worker_metadatas):
"""
Find the component lists from each worker build.
The components that are interesting are under the 'output' key. The
buildhost's components are ignored.
Inside the 'output' key are various 'instances'. The only 'instance'
with a 'component list' is the 'docker-image' instance. The 'log'
instances are ignored for now.
Reference plugin post_koji_upload for details on how this is created.
:return: list of component lists
"""
comp_list = []
for platform in sorted(worker_metadatas.keys()):
for instance in worker_metadatas[platform]['output']:
if instance['type'] == 'docker-image':
if 'components' not in instance or not instance['components']:
self.log.warn("Missing 'components' key in 'output' metadata instance: %s",
instance)
continue
comp_list.append(instance['components'])
return comp_list | python | def get_component_list_from_workers(self, worker_metadatas):
"""
Find the component lists from each worker build.
The components that are interesting are under the 'output' key. The
buildhost's components are ignored.
Inside the 'output' key are various 'instances'. The only 'instance'
with a 'component list' is the 'docker-image' instance. The 'log'
instances are ignored for now.
Reference plugin post_koji_upload for details on how this is created.
:return: list of component lists
"""
comp_list = []
for platform in sorted(worker_metadatas.keys()):
for instance in worker_metadatas[platform]['output']:
if instance['type'] == 'docker-image':
if 'components' not in instance or not instance['components']:
self.log.warn("Missing 'components' key in 'output' metadata instance: %s",
instance)
continue
comp_list.append(instance['components'])
return comp_list | [
"def",
"get_component_list_from_workers",
"(",
"self",
",",
"worker_metadatas",
")",
":",
"comp_list",
"=",
"[",
"]",
"for",
"platform",
"in",
"sorted",
"(",
"worker_metadatas",
".",
"keys",
"(",
")",
")",
":",
"for",
"instance",
"in",
"worker_metadatas",
"[",... | Find the component lists from each worker build.
The components that are interesting are under the 'output' key. The
buildhost's components are ignored.
Inside the 'output' key are various 'instances'. The only 'instance'
with a 'component list' is the 'docker-image' instance. The 'log'
instances are ignored for now.
Reference plugin post_koji_upload for details on how this is created.
:return: list of component lists | [
"Find",
"the",
"component",
"lists",
"from",
"each",
"worker",
"build",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_compare_components.py#L51-L77 | train | 28,541 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.get_rpms | def get_rpms(self):
"""
Build a list of installed RPMs in the format required for the
metadata.
"""
tags = [
'NAME',
'VERSION',
'RELEASE',
'ARCH',
'EPOCH',
'SIGMD5',
'SIGPGP:pgpsig',
'SIGGPG:pgpsig',
]
cmd = "/bin/rpm " + rpm_qf_args(tags)
try:
# py3
(status, output) = subprocess.getstatusoutput(cmd)
except AttributeError:
# py2
with open('/dev/null', 'r+') as devnull:
p = subprocess.Popen(cmd,
shell=True,
stdin=devnull,
stdout=subprocess.PIPE,
stderr=devnull)
(stdout, stderr) = p.communicate()
status = p.wait()
output = stdout.decode()
if status != 0:
self.log.debug("%s: stderr output: %s", cmd, stderr)
raise RuntimeError("%s: exit code %s" % (cmd, status))
return parse_rpm_output(output.splitlines(), tags) | python | def get_rpms(self):
"""
Build a list of installed RPMs in the format required for the
metadata.
"""
tags = [
'NAME',
'VERSION',
'RELEASE',
'ARCH',
'EPOCH',
'SIGMD5',
'SIGPGP:pgpsig',
'SIGGPG:pgpsig',
]
cmd = "/bin/rpm " + rpm_qf_args(tags)
try:
# py3
(status, output) = subprocess.getstatusoutput(cmd)
except AttributeError:
# py2
with open('/dev/null', 'r+') as devnull:
p = subprocess.Popen(cmd,
shell=True,
stdin=devnull,
stdout=subprocess.PIPE,
stderr=devnull)
(stdout, stderr) = p.communicate()
status = p.wait()
output = stdout.decode()
if status != 0:
self.log.debug("%s: stderr output: %s", cmd, stderr)
raise RuntimeError("%s: exit code %s" % (cmd, status))
return parse_rpm_output(output.splitlines(), tags) | [
"def",
"get_rpms",
"(",
"self",
")",
":",
"tags",
"=",
"[",
"'NAME'",
",",
"'VERSION'",
",",
"'RELEASE'",
",",
"'ARCH'",
",",
"'EPOCH'",
",",
"'SIGMD5'",
",",
"'SIGPGP:pgpsig'",
",",
"'SIGGPG:pgpsig'",
",",
"]",
"cmd",
"=",
"\"/bin/rpm \"",
"+",
"rpm_qf_ar... | Build a list of installed RPMs in the format required for the
metadata. | [
"Build",
"a",
"list",
"of",
"installed",
"RPMs",
"in",
"the",
"format",
"required",
"for",
"the",
"metadata",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L142-L180 | train | 28,542 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.get_output_metadata | def get_output_metadata(self, path, filename):
"""
Describe a file by its metadata.
:return: dict
"""
checksums = get_checksums(path, ['md5'])
metadata = {'filename': filename,
'filesize': os.path.getsize(path),
'checksum': checksums['md5sum'],
'checksum_type': 'md5'}
if self.metadata_only:
metadata['metadata_only'] = True
return metadata | python | def get_output_metadata(self, path, filename):
"""
Describe a file by its metadata.
:return: dict
"""
checksums = get_checksums(path, ['md5'])
metadata = {'filename': filename,
'filesize': os.path.getsize(path),
'checksum': checksums['md5sum'],
'checksum_type': 'md5'}
if self.metadata_only:
metadata['metadata_only'] = True
return metadata | [
"def",
"get_output_metadata",
"(",
"self",
",",
"path",
",",
"filename",
")",
":",
"checksums",
"=",
"get_checksums",
"(",
"path",
",",
"[",
"'md5'",
"]",
")",
"metadata",
"=",
"{",
"'filename'",
":",
"filename",
",",
"'filesize'",
":",
"os",
".",
"path"... | Describe a file by its metadata.
:return: dict | [
"Describe",
"a",
"file",
"by",
"its",
"metadata",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L182-L198 | train | 28,543 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.get_builder_image_id | def get_builder_image_id(self):
"""
Find out the docker ID of the buildroot image we are in.
"""
try:
buildroot_tag = os.environ["OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE"]
except KeyError:
return ''
try:
pod = self.osbs.get_pod_for_build(self.build_id)
all_images = pod.get_container_image_ids()
except OsbsException as ex:
self.log.error("unable to find image id: %r", ex)
return buildroot_tag
try:
return all_images[buildroot_tag]
except KeyError:
self.log.error("Unable to determine buildroot image ID for %s",
buildroot_tag)
return buildroot_tag | python | def get_builder_image_id(self):
"""
Find out the docker ID of the buildroot image we are in.
"""
try:
buildroot_tag = os.environ["OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE"]
except KeyError:
return ''
try:
pod = self.osbs.get_pod_for_build(self.build_id)
all_images = pod.get_container_image_ids()
except OsbsException as ex:
self.log.error("unable to find image id: %r", ex)
return buildroot_tag
try:
return all_images[buildroot_tag]
except KeyError:
self.log.error("Unable to determine buildroot image ID for %s",
buildroot_tag)
return buildroot_tag | [
"def",
"get_builder_image_id",
"(",
"self",
")",
":",
"try",
":",
"buildroot_tag",
"=",
"os",
".",
"environ",
"[",
"\"OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE\"",
"]",
"except",
"KeyError",
":",
"return",
"''",
"try",
":",
"pod",
"=",
"self",
".",
"osbs",
".",
"get... | Find out the docker ID of the buildroot image we are in. | [
"Find",
"out",
"the",
"docker",
"ID",
"of",
"the",
"buildroot",
"image",
"we",
"are",
"in",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L200-L222 | train | 28,544 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.get_image_components | def get_image_components(self):
"""
Re-package the output of the rpmqa plugin into the format required
for the metadata.
"""
output = self.workflow.image_components
if output is None:
self.log.error("%s plugin did not run!",
PostBuildRPMqaPlugin.key)
output = []
return output | python | def get_image_components(self):
"""
Re-package the output of the rpmqa plugin into the format required
for the metadata.
"""
output = self.workflow.image_components
if output is None:
self.log.error("%s plugin did not run!",
PostBuildRPMqaPlugin.key)
output = []
return output | [
"def",
"get_image_components",
"(",
"self",
")",
":",
"output",
"=",
"self",
".",
"workflow",
".",
"image_components",
"if",
"output",
"is",
"None",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"%s plugin did not run!\"",
",",
"PostBuildRPMqaPlugin",
".",
"ke... | Re-package the output of the rpmqa plugin into the format required
for the metadata. | [
"Re",
"-",
"package",
"the",
"output",
"of",
"the",
"rpmqa",
"plugin",
"into",
"the",
"format",
"required",
"for",
"the",
"metadata",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L309-L321 | train | 28,545 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.get_digests | def get_digests(self):
"""
Returns a map of images to their digests
"""
try:
pulp = get_manifests_in_pulp_repository(self.workflow)
except KeyError:
pulp = None
digests = {} # repository -> digests
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
image_digests = registry.digests[image_str]
if pulp is None:
digest_list = [image_digests.default]
else:
# If Pulp is enabled, only report digests that
# were synced into Pulp. This may not be all
# of them, depending on whether Pulp has
# schema 2 support.
digest_list = [digest for digest in (image_digests.v1,
image_digests.v2)
if digest in pulp]
digests[image.to_str(registry=False)] = digest_list
return digests | python | def get_digests(self):
"""
Returns a map of images to their digests
"""
try:
pulp = get_manifests_in_pulp_repository(self.workflow)
except KeyError:
pulp = None
digests = {} # repository -> digests
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
image_digests = registry.digests[image_str]
if pulp is None:
digest_list = [image_digests.default]
else:
# If Pulp is enabled, only report digests that
# were synced into Pulp. This may not be all
# of them, depending on whether Pulp has
# schema 2 support.
digest_list = [digest for digest in (image_digests.v1,
image_digests.v2)
if digest in pulp]
digests[image.to_str(registry=False)] = digest_list
return digests | [
"def",
"get_digests",
"(",
"self",
")",
":",
"try",
":",
"pulp",
"=",
"get_manifests_in_pulp_repository",
"(",
"self",
".",
"workflow",
")",
"except",
"KeyError",
":",
"pulp",
"=",
"None",
"digests",
"=",
"{",
"}",
"# repository -> digests",
"for",
"registry",... | Returns a map of images to their digests | [
"Returns",
"a",
"map",
"of",
"images",
"to",
"their",
"digests"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L351-L380 | train | 28,546 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.get_repositories | def get_repositories(self, digests):
"""
Build the repositories metadata
:param digests: dict, image -> digests
"""
if self.workflow.push_conf.pulp_registries:
# If pulp was used, only report pulp images
registries = self.workflow.push_conf.pulp_registries
else:
# Otherwise report all the images we pushed
registries = self.workflow.push_conf.all_registries
output_images = []
for registry in registries:
image = self.pullspec_image.copy()
image.registry = registry.uri
pullspec = image.to_str()
output_images.append(pullspec)
digest_list = digests.get(image.to_str(registry=False), ())
for digest in digest_list:
digest_pullspec = image.to_str(tag=False) + "@" + digest
output_images.append(digest_pullspec)
return output_images | python | def get_repositories(self, digests):
"""
Build the repositories metadata
:param digests: dict, image -> digests
"""
if self.workflow.push_conf.pulp_registries:
# If pulp was used, only report pulp images
registries = self.workflow.push_conf.pulp_registries
else:
# Otherwise report all the images we pushed
registries = self.workflow.push_conf.all_registries
output_images = []
for registry in registries:
image = self.pullspec_image.copy()
image.registry = registry.uri
pullspec = image.to_str()
output_images.append(pullspec)
digest_list = digests.get(image.to_str(registry=False), ())
for digest in digest_list:
digest_pullspec = image.to_str(tag=False) + "@" + digest
output_images.append(digest_pullspec)
return output_images | [
"def",
"get_repositories",
"(",
"self",
",",
"digests",
")",
":",
"if",
"self",
".",
"workflow",
".",
"push_conf",
".",
"pulp_registries",
":",
"# If pulp was used, only report pulp images",
"registries",
"=",
"self",
".",
"workflow",
".",
"push_conf",
".",
"pulp_... | Build the repositories metadata
:param digests: dict, image -> digests | [
"Build",
"the",
"repositories",
"metadata"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L382-L408 | train | 28,547 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_promote.py | KojiPromotePlugin.upload_file | def upload_file(self, session, output, serverdir):
"""
Upload a file to koji
:return: str, pathname on server
"""
name = output.metadata['filename']
self.log.debug("uploading %r to %r as %r",
output.file.name, serverdir, name)
kwargs = {}
if self.blocksize is not None:
kwargs['blocksize'] = self.blocksize
self.log.debug("using blocksize %d", self.blocksize)
upload_logger = KojiUploadLogger(self.log)
session.uploadWrapper(output.file.name, serverdir, name=name,
callback=upload_logger.callback, **kwargs)
path = os.path.join(serverdir, name)
self.log.debug("uploaded %r", path)
return path | python | def upload_file(self, session, output, serverdir):
"""
Upload a file to koji
:return: str, pathname on server
"""
name = output.metadata['filename']
self.log.debug("uploading %r to %r as %r",
output.file.name, serverdir, name)
kwargs = {}
if self.blocksize is not None:
kwargs['blocksize'] = self.blocksize
self.log.debug("using blocksize %d", self.blocksize)
upload_logger = KojiUploadLogger(self.log)
session.uploadWrapper(output.file.name, serverdir, name=name,
callback=upload_logger.callback, **kwargs)
path = os.path.join(serverdir, name)
self.log.debug("uploaded %r", path)
return path | [
"def",
"upload_file",
"(",
"self",
",",
"session",
",",
"output",
",",
"serverdir",
")",
":",
"name",
"=",
"output",
".",
"metadata",
"[",
"'filename'",
"]",
"self",
".",
"log",
".",
"debug",
"(",
"\"uploading %r to %r as %r\"",
",",
"output",
".",
"file",... | Upload a file to koji
:return: str, pathname on server | [
"Upload",
"a",
"file",
"to",
"koji"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_promote.py#L642-L662 | train | 28,548 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_verify_media_types.py | VerifyMediaTypesPlugin.get_manifest_list_only_expectation | def get_manifest_list_only_expectation(self):
"""
Get expectation for manifest list only
:return: bool, expect manifest list only?
"""
if not self.workflow.postbuild_results.get(PLUGIN_GROUP_MANIFESTS_KEY):
self.log.debug('Cannot check if only manifest list digest should be returned '
'because group manifests plugin did not run')
return False
platforms = get_platforms(self.workflow)
if not platforms:
self.log.debug('Cannot check if only manifest list digest should be returned '
'because we have no platforms list')
return False
try:
platform_to_goarch = get_platform_to_goarch_mapping(self.workflow)
except KeyError:
self.log.debug('Cannot check if only manifest list digest should be returned '
'because there are no platform descriptors')
return False
for plat in platforms:
if platform_to_goarch[plat] == 'amd64':
self.log.debug('amd64 was built, all media types available')
return False
self.log.debug('amd64 was not built, only manifest list digest is available')
return True | python | def get_manifest_list_only_expectation(self):
"""
Get expectation for manifest list only
:return: bool, expect manifest list only?
"""
if not self.workflow.postbuild_results.get(PLUGIN_GROUP_MANIFESTS_KEY):
self.log.debug('Cannot check if only manifest list digest should be returned '
'because group manifests plugin did not run')
return False
platforms = get_platforms(self.workflow)
if not platforms:
self.log.debug('Cannot check if only manifest list digest should be returned '
'because we have no platforms list')
return False
try:
platform_to_goarch = get_platform_to_goarch_mapping(self.workflow)
except KeyError:
self.log.debug('Cannot check if only manifest list digest should be returned '
'because there are no platform descriptors')
return False
for plat in platforms:
if platform_to_goarch[plat] == 'amd64':
self.log.debug('amd64 was built, all media types available')
return False
self.log.debug('amd64 was not built, only manifest list digest is available')
return True | [
"def",
"get_manifest_list_only_expectation",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"workflow",
".",
"postbuild_results",
".",
"get",
"(",
"PLUGIN_GROUP_MANIFESTS_KEY",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Cannot check if only manifest list d... | Get expectation for manifest list only
:return: bool, expect manifest list only? | [
"Get",
"expectation",
"for",
"manifest",
"list",
"only"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_verify_media_types.py#L121-L151 | train | 28,549 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin.run | def run(self):
"""
Pull parent images and retag them uniquely for this build.
"""
build_json = get_build_json()
current_platform = platform.processor() or 'x86_64'
self.manifest_list_cache = {}
organization = get_registries_organization(self.workflow)
for nonce, parent in enumerate(sorted(self.workflow.builder.parent_images.keys(),
key=str)):
if base_image_is_custom(parent.to_str()):
continue
image = parent
is_base_image = False
# original_base_image is an ImageName, so compare parent as an ImageName also
if image == self.workflow.builder.original_base_image:
is_base_image = True
image = self._resolve_base_image(build_json)
image = self._ensure_image_registry(image)
if organization:
image.enclose(organization)
parent.enclose(organization)
if self.check_platforms:
# run only at orchestrator
self._validate_platforms_in_image(image)
self._collect_image_digests(image)
# try to stay with digests
image_with_digest = self._get_image_with_digest(image, current_platform)
if image_with_digest is None:
self.log.warning("Cannot resolve platform '%s' specific digest for image '%s'",
current_platform, image)
else:
self.log.info("Replacing image '%s' with '%s'", image, image_with_digest)
image = image_with_digest
if self.check_platforms:
new_arch_image = self._get_image_for_different_arch(image, current_platform)
if new_arch_image:
image = new_arch_image
if self.inspect_only:
new_image = image
else:
new_image = self._pull_and_tag_image(image, build_json, str(nonce))
self.workflow.builder.recreate_parent_images()
self.workflow.builder.parent_images[parent] = new_image
if is_base_image:
if organization:
# we want to be sure we have original_base_image enclosed as well
self.workflow.builder.original_base_image.enclose(organization)
self.workflow.builder.set_base_image(
str(new_image), insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path
)
self.workflow.builder.parents_pulled = not self.inspect_only
self.workflow.builder.base_image_insecure = self.parent_registry_insecure | python | def run(self):
"""
Pull parent images and retag them uniquely for this build.
"""
build_json = get_build_json()
current_platform = platform.processor() or 'x86_64'
self.manifest_list_cache = {}
organization = get_registries_organization(self.workflow)
for nonce, parent in enumerate(sorted(self.workflow.builder.parent_images.keys(),
key=str)):
if base_image_is_custom(parent.to_str()):
continue
image = parent
is_base_image = False
# original_base_image is an ImageName, so compare parent as an ImageName also
if image == self.workflow.builder.original_base_image:
is_base_image = True
image = self._resolve_base_image(build_json)
image = self._ensure_image_registry(image)
if organization:
image.enclose(organization)
parent.enclose(organization)
if self.check_platforms:
# run only at orchestrator
self._validate_platforms_in_image(image)
self._collect_image_digests(image)
# try to stay with digests
image_with_digest = self._get_image_with_digest(image, current_platform)
if image_with_digest is None:
self.log.warning("Cannot resolve platform '%s' specific digest for image '%s'",
current_platform, image)
else:
self.log.info("Replacing image '%s' with '%s'", image, image_with_digest)
image = image_with_digest
if self.check_platforms:
new_arch_image = self._get_image_for_different_arch(image, current_platform)
if new_arch_image:
image = new_arch_image
if self.inspect_only:
new_image = image
else:
new_image = self._pull_and_tag_image(image, build_json, str(nonce))
self.workflow.builder.recreate_parent_images()
self.workflow.builder.parent_images[parent] = new_image
if is_base_image:
if organization:
# we want to be sure we have original_base_image enclosed as well
self.workflow.builder.original_base_image.enclose(organization)
self.workflow.builder.set_base_image(
str(new_image), insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path
)
self.workflow.builder.parents_pulled = not self.inspect_only
self.workflow.builder.base_image_insecure = self.parent_registry_insecure | [
"def",
"run",
"(",
"self",
")",
":",
"build_json",
"=",
"get_build_json",
"(",
")",
"current_platform",
"=",
"platform",
".",
"processor",
"(",
")",
"or",
"'x86_64'",
"self",
".",
"manifest_list_cache",
"=",
"{",
"}",
"organization",
"=",
"get_registries_organ... | Pull parent images and retag them uniquely for this build. | [
"Pull",
"parent",
"images",
"and",
"retag",
"them",
"uniquely",
"for",
"this",
"build",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L70-L132 | train | 28,550 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin._get_image_for_different_arch | def _get_image_for_different_arch(self, image, platform):
"""Get image from random arch
This is a workaround for aarch64 platform, because orchestrator cannot
get this arch from manifests lists so we have to provide digest of a
random platform to get image metadata for orchestrator.
For standard platforms like x86_64, ppc64le, ... this method returns
the corresponding digest
"""
parents_digests = self.workflow.builder.parent_images_digests
try:
digests = parents_digests.get_image_digests(image)
except KeyError:
return None
if not digests:
return None
platform_digest = digests.get(platform)
if platform_digest is None:
# exact match is not found, get random platform
platform_digest = tuple(digests.values())[0]
new_image = ImageName.parse(platform_digest)
return new_image | python | def _get_image_for_different_arch(self, image, platform):
"""Get image from random arch
This is a workaround for aarch64 platform, because orchestrator cannot
get this arch from manifests lists so we have to provide digest of a
random platform to get image metadata for orchestrator.
For standard platforms like x86_64, ppc64le, ... this method returns
the corresponding digest
"""
parents_digests = self.workflow.builder.parent_images_digests
try:
digests = parents_digests.get_image_digests(image)
except KeyError:
return None
if not digests:
return None
platform_digest = digests.get(platform)
if platform_digest is None:
# exact match is not found, get random platform
platform_digest = tuple(digests.values())[0]
new_image = ImageName.parse(platform_digest)
return new_image | [
"def",
"_get_image_for_different_arch",
"(",
"self",
",",
"image",
",",
"platform",
")",
":",
"parents_digests",
"=",
"self",
".",
"workflow",
".",
"builder",
".",
"parent_images_digests",
"try",
":",
"digests",
"=",
"parents_digests",
".",
"get_image_digests",
"(... | Get image from random arch
This is a workaround for aarch64 platform, because orchestrator cannot
get this arch from manifests lists so we have to provide digest of a
random platform to get image metadata for orchestrator.
For standard platforms like x86_64, ppc64le, ... this method returns
the corresponding digest | [
"Get",
"image",
"from",
"random",
"arch"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L190-L215 | train | 28,551 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin._resolve_base_image | def _resolve_base_image(self, build_json):
"""If this is an auto-rebuild, adjust the base image to use the triggering build"""
spec = build_json.get("spec")
try:
image_id = spec['triggeredBy'][0]['imageChangeBuild']['imageID']
except (TypeError, KeyError, IndexError):
# build not marked for auto-rebuilds; use regular base image
base_image = self.workflow.builder.base_image
self.log.info("using %s as base image.", base_image)
else:
# build has auto-rebuilds enabled
self.log.info("using %s from build spec[triggeredBy] as base image.", image_id)
base_image = ImageName.parse(image_id) # any exceptions will propagate
return base_image | python | def _resolve_base_image(self, build_json):
"""If this is an auto-rebuild, adjust the base image to use the triggering build"""
spec = build_json.get("spec")
try:
image_id = spec['triggeredBy'][0]['imageChangeBuild']['imageID']
except (TypeError, KeyError, IndexError):
# build not marked for auto-rebuilds; use regular base image
base_image = self.workflow.builder.base_image
self.log.info("using %s as base image.", base_image)
else:
# build has auto-rebuilds enabled
self.log.info("using %s from build spec[triggeredBy] as base image.", image_id)
base_image = ImageName.parse(image_id) # any exceptions will propagate
return base_image | [
"def",
"_resolve_base_image",
"(",
"self",
",",
"build_json",
")",
":",
"spec",
"=",
"build_json",
".",
"get",
"(",
"\"spec\"",
")",
"try",
":",
"image_id",
"=",
"spec",
"[",
"'triggeredBy'",
"]",
"[",
"0",
"]",
"[",
"'imageChangeBuild'",
"]",
"[",
"'ima... | If this is an auto-rebuild, adjust the base image to use the triggering build | [
"If",
"this",
"is",
"an",
"auto",
"-",
"rebuild",
"adjust",
"the",
"base",
"image",
"to",
"use",
"the",
"triggering",
"build"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L217-L231 | train | 28,552 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin._ensure_image_registry | def _ensure_image_registry(self, image):
"""If plugin configured with a parent registry, ensure the image uses it"""
image_with_registry = image.copy()
if self.parent_registry:
# if registry specified in Dockerfile image, ensure it's the one allowed by config
if image.registry and image.registry != self.parent_registry:
error = (
"Registry specified in dockerfile image doesn't match configured one. "
"Dockerfile: '%s'; expected registry: '%s'"
% (image, self.parent_registry))
self.log.error("%s", error)
raise RuntimeError(error)
image_with_registry.registry = self.parent_registry
return image_with_registry | python | def _ensure_image_registry(self, image):
"""If plugin configured with a parent registry, ensure the image uses it"""
image_with_registry = image.copy()
if self.parent_registry:
# if registry specified in Dockerfile image, ensure it's the one allowed by config
if image.registry and image.registry != self.parent_registry:
error = (
"Registry specified in dockerfile image doesn't match configured one. "
"Dockerfile: '%s'; expected registry: '%s'"
% (image, self.parent_registry))
self.log.error("%s", error)
raise RuntimeError(error)
image_with_registry.registry = self.parent_registry
return image_with_registry | [
"def",
"_ensure_image_registry",
"(",
"self",
",",
"image",
")",
":",
"image_with_registry",
"=",
"image",
".",
"copy",
"(",
")",
"if",
"self",
".",
"parent_registry",
":",
"# if registry specified in Dockerfile image, ensure it's the one allowed by config",
"if",
"image"... | If plugin configured with a parent registry, ensure the image uses it | [
"If",
"plugin",
"configured",
"with",
"a",
"parent",
"registry",
"ensure",
"the",
"image",
"uses",
"it"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L233-L248 | train | 28,553 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin._pull_and_tag_image | def _pull_and_tag_image(self, image, build_json, nonce):
"""Docker pull the image and tag it uniquely for use by this build"""
image = image.copy()
first_library_exc = None
for _ in range(20):
# retry until pull and tag is successful or definitively fails.
# should never require 20 retries but there's a race condition at work.
# just in case something goes wildly wrong, limit to 20 so it terminates.
try:
self.tasker.pull_image(image, insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path)
self.workflow.pulled_base_images.add(image.to_str())
except RetryGeneratorException as exc:
# getting here means the pull itself failed. we may want to retry if the
# image being pulled lacks a namespace, like e.g. "rhel7". we cannot count
# on the registry mapping this into the docker standard "library/rhel7" so
# need to retry with that.
if first_library_exc:
# we already tried and failed; report the first failure.
raise first_library_exc
if image.namespace:
# already namespaced, do not retry with "library/", just fail.
raise
self.log.info("'%s' not found", image.to_str())
image.namespace = 'library'
self.log.info("trying '%s'", image.to_str())
first_library_exc = exc # report first failure if retry also fails
continue
# Attempt to tag it using a unique ID. We might have to retry
# if another build with the same parent image is finishing up
# and removing images it pulled.
# Use the OpenShift build name as the unique ID
unique_id = build_json['metadata']['name']
new_image = ImageName(repo=unique_id, tag=nonce)
try:
self.log.info("tagging pulled image")
response = self.tasker.tag_image(image, new_image)
self.workflow.pulled_base_images.add(response)
self.log.debug("image '%s' is available as '%s'", image, new_image)
return new_image
except docker.errors.NotFound:
# If we get here, some other build raced us to remove
# the parent image, and that build won.
# Retry the pull immediately.
self.log.info("re-pulling removed image")
continue
# Failed to tag it after 20 tries
self.log.error("giving up trying to pull image")
raise RuntimeError("too many attempts to pull and tag image") | python | def _pull_and_tag_image(self, image, build_json, nonce):
"""Docker pull the image and tag it uniquely for use by this build"""
image = image.copy()
first_library_exc = None
for _ in range(20):
# retry until pull and tag is successful or definitively fails.
# should never require 20 retries but there's a race condition at work.
# just in case something goes wildly wrong, limit to 20 so it terminates.
try:
self.tasker.pull_image(image, insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path)
self.workflow.pulled_base_images.add(image.to_str())
except RetryGeneratorException as exc:
# getting here means the pull itself failed. we may want to retry if the
# image being pulled lacks a namespace, like e.g. "rhel7". we cannot count
# on the registry mapping this into the docker standard "library/rhel7" so
# need to retry with that.
if first_library_exc:
# we already tried and failed; report the first failure.
raise first_library_exc
if image.namespace:
# already namespaced, do not retry with "library/", just fail.
raise
self.log.info("'%s' not found", image.to_str())
image.namespace = 'library'
self.log.info("trying '%s'", image.to_str())
first_library_exc = exc # report first failure if retry also fails
continue
# Attempt to tag it using a unique ID. We might have to retry
# if another build with the same parent image is finishing up
# and removing images it pulled.
# Use the OpenShift build name as the unique ID
unique_id = build_json['metadata']['name']
new_image = ImageName(repo=unique_id, tag=nonce)
try:
self.log.info("tagging pulled image")
response = self.tasker.tag_image(image, new_image)
self.workflow.pulled_base_images.add(response)
self.log.debug("image '%s' is available as '%s'", image, new_image)
return new_image
except docker.errors.NotFound:
# If we get here, some other build raced us to remove
# the parent image, and that build won.
# Retry the pull immediately.
self.log.info("re-pulling removed image")
continue
# Failed to tag it after 20 tries
self.log.error("giving up trying to pull image")
raise RuntimeError("too many attempts to pull and tag image") | [
"def",
"_pull_and_tag_image",
"(",
"self",
",",
"image",
",",
"build_json",
",",
"nonce",
")",
":",
"image",
"=",
"image",
".",
"copy",
"(",
")",
"first_library_exc",
"=",
"None",
"for",
"_",
"in",
"range",
"(",
"20",
")",
":",
"# retry until pull and tag ... | Docker pull the image and tag it uniquely for use by this build | [
"Docker",
"pull",
"the",
"image",
"and",
"tag",
"it",
"uniquely",
"for",
"use",
"by",
"this",
"build"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L250-L303 | train | 28,554 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin._get_manifest_list | def _get_manifest_list(self, image):
"""try to figure out manifest list"""
if image in self.manifest_list_cache:
return self.manifest_list_cache[image]
manifest_list = get_manifest_list(image, image.registry,
insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path)
if '@sha256:' in str(image) and not manifest_list:
# we want to adjust the tag only for manifest list fetching
image = image.copy()
try:
config_blob = get_config_from_registry(
image, image.registry, image.tag, insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path
)
except (HTTPError, RetryError, Timeout) as ex:
self.log.warning('Unable to fetch config for %s, got error %s',
image, ex.response.status_code)
raise RuntimeError('Unable to fetch config for base image')
release = config_blob['config']['Labels']['release']
version = config_blob['config']['Labels']['version']
docker_tag = "%s-%s" % (version, release)
image.tag = docker_tag
manifest_list = get_manifest_list(image, image.registry,
insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path)
self.manifest_list_cache[image] = manifest_list
return self.manifest_list_cache[image] | python | def _get_manifest_list(self, image):
"""try to figure out manifest list"""
if image in self.manifest_list_cache:
return self.manifest_list_cache[image]
manifest_list = get_manifest_list(image, image.registry,
insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path)
if '@sha256:' in str(image) and not manifest_list:
# we want to adjust the tag only for manifest list fetching
image = image.copy()
try:
config_blob = get_config_from_registry(
image, image.registry, image.tag, insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path
)
except (HTTPError, RetryError, Timeout) as ex:
self.log.warning('Unable to fetch config for %s, got error %s',
image, ex.response.status_code)
raise RuntimeError('Unable to fetch config for base image')
release = config_blob['config']['Labels']['release']
version = config_blob['config']['Labels']['version']
docker_tag = "%s-%s" % (version, release)
image.tag = docker_tag
manifest_list = get_manifest_list(image, image.registry,
insecure=self.parent_registry_insecure,
dockercfg_path=self.parent_registry_dockercfg_path)
self.manifest_list_cache[image] = manifest_list
return self.manifest_list_cache[image] | [
"def",
"_get_manifest_list",
"(",
"self",
",",
"image",
")",
":",
"if",
"image",
"in",
"self",
".",
"manifest_list_cache",
":",
"return",
"self",
".",
"manifest_list_cache",
"[",
"image",
"]",
"manifest_list",
"=",
"get_manifest_list",
"(",
"image",
",",
"imag... | try to figure out manifest list | [
"try",
"to",
"figure",
"out",
"manifest",
"list"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L305-L336 | train | 28,555 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_pull_base_image.py | PullBaseImagePlugin._validate_platforms_in_image | def _validate_platforms_in_image(self, image):
"""Ensure that the image provides all platforms expected for the build."""
expected_platforms = get_platforms(self.workflow)
if not expected_platforms:
self.log.info('Skipping validation of available platforms '
'because expected platforms are unknown')
return
if len(expected_platforms) == 1:
self.log.info('Skipping validation of available platforms for base image '
'because this is a single platform build')
return
if not image.registry:
self.log.info('Cannot validate available platforms for base image '
'because base image registry is not defined')
return
try:
platform_to_arch = get_platform_to_goarch_mapping(self.workflow)
except KeyError:
self.log.info('Cannot validate available platforms for base image '
'because platform descriptors are not defined')
return
manifest_list = self._get_manifest_list(image)
if not manifest_list:
raise RuntimeError('Unable to fetch manifest list for base image')
all_manifests = manifest_list.json()['manifests']
manifest_list_arches = set(
manifest['platform']['architecture'] for manifest in all_manifests)
expected_arches = set(
platform_to_arch[platform] for platform in expected_platforms)
self.log.info('Manifest list arches: %s, expected arches: %s',
manifest_list_arches, expected_arches)
assert manifest_list_arches >= expected_arches, \
'Missing arches in manifest list for base image'
self.log.info('Base image is a manifest list for all required platforms') | python | def _validate_platforms_in_image(self, image):
"""Ensure that the image provides all platforms expected for the build."""
expected_platforms = get_platforms(self.workflow)
if not expected_platforms:
self.log.info('Skipping validation of available platforms '
'because expected platforms are unknown')
return
if len(expected_platforms) == 1:
self.log.info('Skipping validation of available platforms for base image '
'because this is a single platform build')
return
if not image.registry:
self.log.info('Cannot validate available platforms for base image '
'because base image registry is not defined')
return
try:
platform_to_arch = get_platform_to_goarch_mapping(self.workflow)
except KeyError:
self.log.info('Cannot validate available platforms for base image '
'because platform descriptors are not defined')
return
manifest_list = self._get_manifest_list(image)
if not manifest_list:
raise RuntimeError('Unable to fetch manifest list for base image')
all_manifests = manifest_list.json()['manifests']
manifest_list_arches = set(
manifest['platform']['architecture'] for manifest in all_manifests)
expected_arches = set(
platform_to_arch[platform] for platform in expected_platforms)
self.log.info('Manifest list arches: %s, expected arches: %s',
manifest_list_arches, expected_arches)
assert manifest_list_arches >= expected_arches, \
'Missing arches in manifest list for base image'
self.log.info('Base image is a manifest list for all required platforms') | [
"def",
"_validate_platforms_in_image",
"(",
"self",
",",
"image",
")",
":",
"expected_platforms",
"=",
"get_platforms",
"(",
"self",
".",
"workflow",
")",
"if",
"not",
"expected_platforms",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Skipping validation of availa... | Ensure that the image provides all platforms expected for the build. | [
"Ensure",
"that",
"the",
"image",
"provides",
"all",
"platforms",
"expected",
"for",
"the",
"build",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L338-L379 | train | 28,556 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_pulp_sync.py | PulpSyncPlugin.get_dockercfg_credentials | def get_dockercfg_credentials(self, docker_registry):
"""
Read the .dockercfg file and return an empty dict, or else a dict
with keys 'basic_auth_username' and 'basic_auth_password'.
"""
if not self.registry_secret_path:
return {}
dockercfg = Dockercfg(self.registry_secret_path)
registry_creds = dockercfg.get_credentials(docker_registry)
if 'username' not in registry_creds:
return {}
return {
'basic_auth_username': registry_creds['username'],
'basic_auth_password': registry_creds['password'],
} | python | def get_dockercfg_credentials(self, docker_registry):
"""
Read the .dockercfg file and return an empty dict, or else a dict
with keys 'basic_auth_username' and 'basic_auth_password'.
"""
if not self.registry_secret_path:
return {}
dockercfg = Dockercfg(self.registry_secret_path)
registry_creds = dockercfg.get_credentials(docker_registry)
if 'username' not in registry_creds:
return {}
return {
'basic_auth_username': registry_creds['username'],
'basic_auth_password': registry_creds['password'],
} | [
"def",
"get_dockercfg_credentials",
"(",
"self",
",",
"docker_registry",
")",
":",
"if",
"not",
"self",
".",
"registry_secret_path",
":",
"return",
"{",
"}",
"dockercfg",
"=",
"Dockercfg",
"(",
"self",
".",
"registry_secret_path",
")",
"registry_creds",
"=",
"do... | Read the .dockercfg file and return an empty dict, or else a dict
with keys 'basic_auth_username' and 'basic_auth_password'. | [
"Read",
"the",
".",
"dockercfg",
"file",
"and",
"return",
"an",
"empty",
"dict",
"or",
"else",
"a",
"dict",
"with",
"keys",
"basic_auth_username",
"and",
"basic_auth_password",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_pulp_sync.py#L170-L186 | train | 28,557 |
projectatomic/atomic-reactor | atomic_reactor/odcs_util.py | ODCSClient.start_compose | def start_compose(self, source_type, source, packages=None, sigkeys=None, arches=None,
flags=None, multilib_arches=None, multilib_method=None,
modular_koji_tags=None):
"""Start a new ODCS compose
:param source_type: str, the type of compose to request (tag, module, pulp)
:param source: str, if source_type "tag" is used, the name of the Koji tag
to use when retrieving packages to include in compose;
if source_type "module", white-space separated NAME-STREAM or
NAME-STREAM-VERSION list of modules to include in compose;
if source_type "pulp", white-space separated list of context-sets
to include in compose
:param packages: list<str>, packages which should be included in a compose. Only
relevant when source_type "tag" is used.
:param sigkeys: list<str>, IDs of signature keys. Only packages signed by one of
these keys will be included in a compose.
:param arches: list<str>, List of additional Koji arches to build this compose for.
By default, the compose is built only for "x86_64" arch.
:param multilib_arches: list<str>, List of Koji arches to build as multilib in this
compose. By default, no arches are built as multilib.
:param multilib_method: list<str>, list of methods to determine which packages should
be included in a multilib compose. Defaults to none, but the value
of ['devel', 'runtime] will be passed to ODCS if multilib_arches is
not empty and no mulitlib_method value is provided.
:param modular_koji_tags: list<str>, the koji tags which are tagged to builds from the
modular Koji Content Generator. Builds with matching tags will be
included in the compose.
:return: dict, status of compose being created by request.
"""
body = {
'source': {
'type': source_type,
'source': source
}
}
if source_type == "tag":
body['source']['packages'] = packages or []
if sigkeys is not None:
body['source']['sigkeys'] = sigkeys
if flags is not None:
body['flags'] = flags
if arches is not None:
body['arches'] = arches
if multilib_arches:
body['multilib_arches'] = multilib_arches
body['multilib_method'] = multilib_method or MULTILIB_METHOD_DEFAULT
if source_type == "module" and modular_koji_tags:
body['modular_koji_tags'] = modular_koji_tags
logger.info("Starting compose: %s", body)
response = self.session.post('{}composes/'.format(self.url),
json=body)
response.raise_for_status()
return response.json() | python | def start_compose(self, source_type, source, packages=None, sigkeys=None, arches=None,
flags=None, multilib_arches=None, multilib_method=None,
modular_koji_tags=None):
"""Start a new ODCS compose
:param source_type: str, the type of compose to request (tag, module, pulp)
:param source: str, if source_type "tag" is used, the name of the Koji tag
to use when retrieving packages to include in compose;
if source_type "module", white-space separated NAME-STREAM or
NAME-STREAM-VERSION list of modules to include in compose;
if source_type "pulp", white-space separated list of context-sets
to include in compose
:param packages: list<str>, packages which should be included in a compose. Only
relevant when source_type "tag" is used.
:param sigkeys: list<str>, IDs of signature keys. Only packages signed by one of
these keys will be included in a compose.
:param arches: list<str>, List of additional Koji arches to build this compose for.
By default, the compose is built only for "x86_64" arch.
:param multilib_arches: list<str>, List of Koji arches to build as multilib in this
compose. By default, no arches are built as multilib.
:param multilib_method: list<str>, list of methods to determine which packages should
be included in a multilib compose. Defaults to none, but the value
of ['devel', 'runtime] will be passed to ODCS if multilib_arches is
not empty and no mulitlib_method value is provided.
:param modular_koji_tags: list<str>, the koji tags which are tagged to builds from the
modular Koji Content Generator. Builds with matching tags will be
included in the compose.
:return: dict, status of compose being created by request.
"""
body = {
'source': {
'type': source_type,
'source': source
}
}
if source_type == "tag":
body['source']['packages'] = packages or []
if sigkeys is not None:
body['source']['sigkeys'] = sigkeys
if flags is not None:
body['flags'] = flags
if arches is not None:
body['arches'] = arches
if multilib_arches:
body['multilib_arches'] = multilib_arches
body['multilib_method'] = multilib_method or MULTILIB_METHOD_DEFAULT
if source_type == "module" and modular_koji_tags:
body['modular_koji_tags'] = modular_koji_tags
logger.info("Starting compose: %s", body)
response = self.session.post('{}composes/'.format(self.url),
json=body)
response.raise_for_status()
return response.json() | [
"def",
"start_compose",
"(",
"self",
",",
"source_type",
",",
"source",
",",
"packages",
"=",
"None",
",",
"sigkeys",
"=",
"None",
",",
"arches",
"=",
"None",
",",
"flags",
"=",
"None",
",",
"multilib_arches",
"=",
"None",
",",
"multilib_method",
"=",
"N... | Start a new ODCS compose
:param source_type: str, the type of compose to request (tag, module, pulp)
:param source: str, if source_type "tag" is used, the name of the Koji tag
to use when retrieving packages to include in compose;
if source_type "module", white-space separated NAME-STREAM or
NAME-STREAM-VERSION list of modules to include in compose;
if source_type "pulp", white-space separated list of context-sets
to include in compose
:param packages: list<str>, packages which should be included in a compose. Only
relevant when source_type "tag" is used.
:param sigkeys: list<str>, IDs of signature keys. Only packages signed by one of
these keys will be included in a compose.
:param arches: list<str>, List of additional Koji arches to build this compose for.
By default, the compose is built only for "x86_64" arch.
:param multilib_arches: list<str>, List of Koji arches to build as multilib in this
compose. By default, no arches are built as multilib.
:param multilib_method: list<str>, list of methods to determine which packages should
be included in a multilib compose. Defaults to none, but the value
of ['devel', 'runtime] will be passed to ODCS if multilib_arches is
not empty and no mulitlib_method value is provided.
:param modular_koji_tags: list<str>, the koji tags which are tagged to builds from the
modular Koji Content Generator. Builds with matching tags will be
included in the compose.
:return: dict, status of compose being created by request. | [
"Start",
"a",
"new",
"ODCS",
"compose"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/odcs_util.py#L49-L109 | train | 28,558 |
projectatomic/atomic-reactor | atomic_reactor/odcs_util.py | ODCSClient.renew_compose | def renew_compose(self, compose_id):
"""Renew, or extend, existing compose
If the compose has already been removed, ODCS creates a new compose.
Otherwise, it extends the time_to_expire of existing compose. In most
cases, caller should assume the compose ID will change.
:param compose_id: int, compose ID to renew
:return: dict, status of compose being renewed.
"""
logger.info("Renewing compose %d", compose_id)
response = self.session.patch('{}composes/{}'.format(self.url, compose_id))
response.raise_for_status()
response_json = response.json()
compose_id = response_json['id']
logger.info("Renewed compose is %d", compose_id)
return response_json | python | def renew_compose(self, compose_id):
"""Renew, or extend, existing compose
If the compose has already been removed, ODCS creates a new compose.
Otherwise, it extends the time_to_expire of existing compose. In most
cases, caller should assume the compose ID will change.
:param compose_id: int, compose ID to renew
:return: dict, status of compose being renewed.
"""
logger.info("Renewing compose %d", compose_id)
response = self.session.patch('{}composes/{}'.format(self.url, compose_id))
response.raise_for_status()
response_json = response.json()
compose_id = response_json['id']
logger.info("Renewed compose is %d", compose_id)
return response_json | [
"def",
"renew_compose",
"(",
"self",
",",
"compose_id",
")",
":",
"logger",
".",
"info",
"(",
"\"Renewing compose %d\"",
",",
"compose_id",
")",
"response",
"=",
"self",
".",
"session",
".",
"patch",
"(",
"'{}composes/{}'",
".",
"format",
"(",
"self",
".",
... | Renew, or extend, existing compose
If the compose has already been removed, ODCS creates a new compose.
Otherwise, it extends the time_to_expire of existing compose. In most
cases, caller should assume the compose ID will change.
:param compose_id: int, compose ID to renew
:return: dict, status of compose being renewed. | [
"Renew",
"or",
"extend",
"existing",
"compose"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/odcs_util.py#L111-L128 | train | 28,559 |
projectatomic/atomic-reactor | atomic_reactor/odcs_util.py | ODCSClient.wait_for_compose | def wait_for_compose(self, compose_id,
burst_retry=1,
burst_length=30,
slow_retry=10,
timeout=1800):
"""Wait for compose request to finalize
:param compose_id: int, compose ID to wait for
:param burst_retry: int, seconds to wait between retries prior to exceeding
the burst length
:param burst_length: int, seconds to switch to slower retry period
:param slow_retry: int, seconds to wait between retries after exceeding
the burst length
:param timeout: int, when to give up waiting for compose request
:return: dict, updated status of compose.
:raise RuntimeError: if state_name becomes 'failed'
"""
logger.debug("Getting compose information for information for compose_id={}"
.format(compose_id))
url = '{}composes/{}'.format(self.url, compose_id)
start_time = time.time()
while True:
response = self.session.get(url)
response.raise_for_status()
response_json = response.json()
if response_json['state_name'] == 'failed':
state_reason = response_json.get('state_reason', 'Unknown')
logger.error(dedent("""\
Compose %s failed: %s
Details: %s
"""), compose_id, state_reason, json.dumps(response_json, indent=4))
raise RuntimeError('Failed request for compose_id={}: {}'
.format(compose_id, state_reason))
if response_json['state_name'] not in ['wait', 'generating']:
logger.debug("Retrieved compose information for compose_id={}: {}"
.format(compose_id, json.dumps(response_json, indent=4)))
return response_json
elapsed = time.time() - start_time
if elapsed > timeout:
raise RuntimeError("Retrieving %s timed out after %s seconds" %
(url, timeout))
else:
logger.debug("Retrying request compose_id={}, elapsed_time={}"
.format(compose_id, elapsed))
if elapsed > burst_length:
time.sleep(slow_retry)
else:
time.sleep(burst_retry) | python | def wait_for_compose(self, compose_id,
burst_retry=1,
burst_length=30,
slow_retry=10,
timeout=1800):
"""Wait for compose request to finalize
:param compose_id: int, compose ID to wait for
:param burst_retry: int, seconds to wait between retries prior to exceeding
the burst length
:param burst_length: int, seconds to switch to slower retry period
:param slow_retry: int, seconds to wait between retries after exceeding
the burst length
:param timeout: int, when to give up waiting for compose request
:return: dict, updated status of compose.
:raise RuntimeError: if state_name becomes 'failed'
"""
logger.debug("Getting compose information for information for compose_id={}"
.format(compose_id))
url = '{}composes/{}'.format(self.url, compose_id)
start_time = time.time()
while True:
response = self.session.get(url)
response.raise_for_status()
response_json = response.json()
if response_json['state_name'] == 'failed':
state_reason = response_json.get('state_reason', 'Unknown')
logger.error(dedent("""\
Compose %s failed: %s
Details: %s
"""), compose_id, state_reason, json.dumps(response_json, indent=4))
raise RuntimeError('Failed request for compose_id={}: {}'
.format(compose_id, state_reason))
if response_json['state_name'] not in ['wait', 'generating']:
logger.debug("Retrieved compose information for compose_id={}: {}"
.format(compose_id, json.dumps(response_json, indent=4)))
return response_json
elapsed = time.time() - start_time
if elapsed > timeout:
raise RuntimeError("Retrieving %s timed out after %s seconds" %
(url, timeout))
else:
logger.debug("Retrying request compose_id={}, elapsed_time={}"
.format(compose_id, elapsed))
if elapsed > burst_length:
time.sleep(slow_retry)
else:
time.sleep(burst_retry) | [
"def",
"wait_for_compose",
"(",
"self",
",",
"compose_id",
",",
"burst_retry",
"=",
"1",
",",
"burst_length",
"=",
"30",
",",
"slow_retry",
"=",
"10",
",",
"timeout",
"=",
"1800",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting compose information for inform... | Wait for compose request to finalize
:param compose_id: int, compose ID to wait for
:param burst_retry: int, seconds to wait between retries prior to exceeding
the burst length
:param burst_length: int, seconds to switch to slower retry period
:param slow_retry: int, seconds to wait between retries after exceeding
the burst length
:param timeout: int, when to give up waiting for compose request
:return: dict, updated status of compose.
:raise RuntimeError: if state_name becomes 'failed' | [
"Wait",
"for",
"compose",
"request",
"to",
"finalize"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/odcs_util.py#L130-L182 | train | 28,560 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_hide_files.py | HideFilesPlugin._find_stages | def _find_stages(self):
"""Find limits of each Dockerfile stage"""
stages = []
end = last_user_found = None
for part in reversed(self.dfp.structure):
if end is None:
end = part
if part['instruction'] == 'USER' and not last_user_found:
# we will reuse the line verbatim
last_user_found = part['content']
if part['instruction'] == 'FROM':
stages.insert(0, {'from_structure': part,
'end_structure': end,
'stage_user': last_user_found})
end = last_user_found = None
return stages | python | def _find_stages(self):
"""Find limits of each Dockerfile stage"""
stages = []
end = last_user_found = None
for part in reversed(self.dfp.structure):
if end is None:
end = part
if part['instruction'] == 'USER' and not last_user_found:
# we will reuse the line verbatim
last_user_found = part['content']
if part['instruction'] == 'FROM':
stages.insert(0, {'from_structure': part,
'end_structure': end,
'stage_user': last_user_found})
end = last_user_found = None
return stages | [
"def",
"_find_stages",
"(",
"self",
")",
":",
"stages",
"=",
"[",
"]",
"end",
"=",
"last_user_found",
"=",
"None",
"for",
"part",
"in",
"reversed",
"(",
"self",
".",
"dfp",
".",
"structure",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"pa... | Find limits of each Dockerfile stage | [
"Find",
"limits",
"of",
"each",
"Dockerfile",
"stage"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_hide_files.py#L55-L73 | train | 28,561 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_store_metadata_in_osv3.py | StoreMetadataInOSv3Plugin.get_digests | def get_digests(self):
"""
Returns a map of repositories to digests
"""
digests = {} # repository -> digest
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
digest = registry.digests[image_str]
digests[image.to_str(registry=False)] = digest
return digests | python | def get_digests(self):
"""
Returns a map of repositories to digests
"""
digests = {} # repository -> digest
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
digest = registry.digests[image_str]
digests[image.to_str(registry=False)] = digest
return digests | [
"def",
"get_digests",
"(",
"self",
")",
":",
"digests",
"=",
"{",
"}",
"# repository -> digest",
"for",
"registry",
"in",
"self",
".",
"workflow",
".",
"push_conf",
".",
"docker_registries",
":",
"for",
"image",
"in",
"self",
".",
"workflow",
".",
"tag_conf"... | Returns a map of repositories to digests | [
"Returns",
"a",
"map",
"of",
"repositories",
"to",
"digests"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_store_metadata_in_osv3.py#L76-L89 | train | 28,562 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_store_metadata_in_osv3.py | StoreMetadataInOSv3Plugin._get_registries | def _get_registries(self):
"""
Return a list of registries that this build updated
For orchestrator it should attempt to filter out non-pulp registries, on worker - return
all registries
"""
if self.workflow.buildstep_result.get(PLUGIN_BUILD_ORCHESTRATE_KEY):
registries = self.workflow.push_conf.pulp_registries
if not registries:
registries = self.workflow.push_conf.all_registries
return registries
else:
return self.workflow.push_conf.all_registries | python | def _get_registries(self):
"""
Return a list of registries that this build updated
For orchestrator it should attempt to filter out non-pulp registries, on worker - return
all registries
"""
if self.workflow.buildstep_result.get(PLUGIN_BUILD_ORCHESTRATE_KEY):
registries = self.workflow.push_conf.pulp_registries
if not registries:
registries = self.workflow.push_conf.all_registries
return registries
else:
return self.workflow.push_conf.all_registries | [
"def",
"_get_registries",
"(",
"self",
")",
":",
"if",
"self",
".",
"workflow",
".",
"buildstep_result",
".",
"get",
"(",
"PLUGIN_BUILD_ORCHESTRATE_KEY",
")",
":",
"registries",
"=",
"self",
".",
"workflow",
".",
"push_conf",
".",
"pulp_registries",
"if",
"not... | Return a list of registries that this build updated
For orchestrator it should attempt to filter out non-pulp registries, on worker - return
all registries | [
"Return",
"a",
"list",
"of",
"registries",
"that",
"this",
"build",
"updated"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_store_metadata_in_osv3.py#L91-L104 | train | 28,563 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_koji_upload.py | KojiUploadPlugin.get_repositories_and_digests | def get_repositories_and_digests(self):
"""
Returns a map of images to their repositories and a map of media types to each digest
it creates a map of images to digests, which is need to create the image->repository
map and uses the same loop structure as media_types->digest, but the image->digest
map isn't needed after we have the image->repository map and can be discarded.
"""
digests = {} # image -> digests
typed_digests = {} # media_type -> digests
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
image_digests = registry.digests[image_str]
if self.report_multiple_digests and get_pulp(self.workflow, None):
digest_list = [digest for digest in (image_digests.v1,
image_digests.v2)
if digest]
else:
digest_list = [self.select_digest(image_digests)]
digests[image.to_str(registry=False)] = digest_list
for digest_version in image_digests.content_type:
if digest_version not in image_digests:
continue
if not get_pulp(self.workflow, None) and digest_version == 'v1':
continue
digest_type = get_manifest_media_type(digest_version)
typed_digests[digest_type] = image_digests[digest_version]
if self.workflow.push_conf.pulp_registries:
# If pulp was used, only report pulp images
registries = self.workflow.push_conf.pulp_registries
else:
# Otherwise report all the images we pushed
registries = self.workflow.push_conf.all_registries
repositories = []
for registry in registries:
image = self.pullspec_image.copy()
image.registry = registry.uri
pullspec = image.to_str()
repositories.append(pullspec)
digest_list = digests.get(image.to_str(registry=False), ())
for digest in digest_list:
digest_pullspec = image.to_str(tag=False) + "@" + digest
repositories.append(digest_pullspec)
return repositories, typed_digests | python | def get_repositories_and_digests(self):
"""
Returns a map of images to their repositories and a map of media types to each digest
it creates a map of images to digests, which is need to create the image->repository
map and uses the same loop structure as media_types->digest, but the image->digest
map isn't needed after we have the image->repository map and can be discarded.
"""
digests = {} # image -> digests
typed_digests = {} # media_type -> digests
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
image_digests = registry.digests[image_str]
if self.report_multiple_digests and get_pulp(self.workflow, None):
digest_list = [digest for digest in (image_digests.v1,
image_digests.v2)
if digest]
else:
digest_list = [self.select_digest(image_digests)]
digests[image.to_str(registry=False)] = digest_list
for digest_version in image_digests.content_type:
if digest_version not in image_digests:
continue
if not get_pulp(self.workflow, None) and digest_version == 'v1':
continue
digest_type = get_manifest_media_type(digest_version)
typed_digests[digest_type] = image_digests[digest_version]
if self.workflow.push_conf.pulp_registries:
# If pulp was used, only report pulp images
registries = self.workflow.push_conf.pulp_registries
else:
# Otherwise report all the images we pushed
registries = self.workflow.push_conf.all_registries
repositories = []
for registry in registries:
image = self.pullspec_image.copy()
image.registry = registry.uri
pullspec = image.to_str()
repositories.append(pullspec)
digest_list = digests.get(image.to_str(registry=False), ())
for digest in digest_list:
digest_pullspec = image.to_str(tag=False) + "@" + digest
repositories.append(digest_pullspec)
return repositories, typed_digests | [
"def",
"get_repositories_and_digests",
"(",
"self",
")",
":",
"digests",
"=",
"{",
"}",
"# image -> digests",
"typed_digests",
"=",
"{",
"}",
"# media_type -> digests",
"for",
"registry",
"in",
"self",
".",
"workflow",
".",
"push_conf",
".",
"docker_registries",
"... | Returns a map of images to their repositories and a map of media types to each digest
it creates a map of images to digests, which is need to create the image->repository
map and uses the same loop structure as media_types->digest, but the image->digest
map isn't needed after we have the image->repository map and can be discarded. | [
"Returns",
"a",
"map",
"of",
"images",
"to",
"their",
"repositories",
"and",
"a",
"map",
"of",
"media",
"types",
"to",
"each",
"digest"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_koji_upload.py#L329-L378 | train | 28,564 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_koji_upload.py | KojiUploadPlugin.update_buildroot_koji | def update_buildroot_koji(self, buildroot, output):
"""
put the final koji information in the buildroot under extra.osbs
"""
docker = output[1]['extra']['docker']
name = ''
for tag in docker['tags']:
for repo in docker['repositories']:
if tag in repo:
iname = ImageName.parse(repo)
name = iname.to_str(registry=False)
break
buildroot['extra']['osbs']['koji'] = {
'build_name': name,
'builder_image_id': docker.get('digests', {})
} | python | def update_buildroot_koji(self, buildroot, output):
"""
put the final koji information in the buildroot under extra.osbs
"""
docker = output[1]['extra']['docker']
name = ''
for tag in docker['tags']:
for repo in docker['repositories']:
if tag in repo:
iname = ImageName.parse(repo)
name = iname.to_str(registry=False)
break
buildroot['extra']['osbs']['koji'] = {
'build_name': name,
'builder_image_id': docker.get('digests', {})
} | [
"def",
"update_buildroot_koji",
"(",
"self",
",",
"buildroot",
",",
"output",
")",
":",
"docker",
"=",
"output",
"[",
"1",
"]",
"[",
"'extra'",
"]",
"[",
"'docker'",
"]",
"name",
"=",
"''",
"for",
"tag",
"in",
"docker",
"[",
"'tags'",
"]",
":",
"for"... | put the final koji information in the buildroot under extra.osbs | [
"put",
"the",
"final",
"koji",
"information",
"in",
"the",
"buildroot",
"under",
"extra",
".",
"osbs"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_koji_upload.py#L469-L486 | train | 28,565 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_koji_upload.py | KojiUploadPlugin.get_metadata | def get_metadata(self):
"""
Build the metadata needed for importing the build
:return: tuple, the metadata and the list of Output instances
"""
try:
metadata = get_build_json()["metadata"]
self.build_id = metadata["name"]
except KeyError:
self.log.error("No build metadata")
raise
for image in self.workflow.tag_conf.unique_images:
self.pullspec_image = image
break
for image in self.workflow.tag_conf.primary_images:
# dash at first/last postition does not count
if '-' in image.tag[1:-1]:
self.pullspec_image = image
break
if not self.pullspec_image:
raise RuntimeError('Unable to determine pullspec_image')
metadata_version = 0
buildroot = self.get_buildroot(build_id=self.build_id)
output_files = self.get_output(buildroot['id'])
output = [output.metadata for output in output_files]
koji_metadata = {
'metadata_version': metadata_version,
'buildroots': [buildroot],
'output': output,
}
self.update_buildroot_koji(buildroot, output)
return koji_metadata, output_files | python | def get_metadata(self):
"""
Build the metadata needed for importing the build
:return: tuple, the metadata and the list of Output instances
"""
try:
metadata = get_build_json()["metadata"]
self.build_id = metadata["name"]
except KeyError:
self.log.error("No build metadata")
raise
for image in self.workflow.tag_conf.unique_images:
self.pullspec_image = image
break
for image in self.workflow.tag_conf.primary_images:
# dash at first/last postition does not count
if '-' in image.tag[1:-1]:
self.pullspec_image = image
break
if not self.pullspec_image:
raise RuntimeError('Unable to determine pullspec_image')
metadata_version = 0
buildroot = self.get_buildroot(build_id=self.build_id)
output_files = self.get_output(buildroot['id'])
output = [output.metadata for output in output_files]
koji_metadata = {
'metadata_version': metadata_version,
'buildroots': [buildroot],
'output': output,
}
self.update_buildroot_koji(buildroot, output)
return koji_metadata, output_files | [
"def",
"get_metadata",
"(",
"self",
")",
":",
"try",
":",
"metadata",
"=",
"get_build_json",
"(",
")",
"[",
"\"metadata\"",
"]",
"self",
".",
"build_id",
"=",
"metadata",
"[",
"\"name\"",
"]",
"except",
"KeyError",
":",
"self",
".",
"log",
".",
"error",
... | Build the metadata needed for importing the build
:return: tuple, the metadata and the list of Output instances | [
"Build",
"the",
"metadata",
"needed",
"for",
"importing",
"the",
"build"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_koji_upload.py#L488-L527 | train | 28,566 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_delete_from_registry.py | DeleteFromRegistryPlugin.get_worker_digests | def get_worker_digests(self):
"""
If we are being called from an orchestrator build, collect the worker
node data and recreate the data locally.
"""
try:
builds = self.workflow.build_result.annotations['worker-builds']
except(TypeError, KeyError):
# This annotation is only set for the orchestrator build.
# It's not present, so this is a worker build.
return {}
worker_digests = {}
for plat, annotation in builds.items():
digests = annotation['digests']
self.log.debug("build %s has digests: %s", plat, digests)
for digest in digests:
reg = registry_hostname(digest['registry'])
worker_digests.setdefault(reg, [])
worker_digests[reg].append(digest)
return worker_digests | python | def get_worker_digests(self):
"""
If we are being called from an orchestrator build, collect the worker
node data and recreate the data locally.
"""
try:
builds = self.workflow.build_result.annotations['worker-builds']
except(TypeError, KeyError):
# This annotation is only set for the orchestrator build.
# It's not present, so this is a worker build.
return {}
worker_digests = {}
for plat, annotation in builds.items():
digests = annotation['digests']
self.log.debug("build %s has digests: %s", plat, digests)
for digest in digests:
reg = registry_hostname(digest['registry'])
worker_digests.setdefault(reg, [])
worker_digests[reg].append(digest)
return worker_digests | [
"def",
"get_worker_digests",
"(",
"self",
")",
":",
"try",
":",
"builds",
"=",
"self",
".",
"workflow",
".",
"build_result",
".",
"annotations",
"[",
"'worker-builds'",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"# This annotation is only set fo... | If we are being called from an orchestrator build, collect the worker
node data and recreate the data locally. | [
"If",
"we",
"are",
"being",
"called",
"from",
"an",
"orchestrator",
"build",
"collect",
"the",
"worker",
"node",
"data",
"and",
"recreate",
"the",
"data",
"locally",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_delete_from_registry.py#L111-L134 | train | 28,567 |
projectatomic/atomic-reactor | atomic_reactor/build.py | BuildResult.make_remote_image_result | def make_remote_image_result(annotations=None, labels=None):
"""Instantiate BuildResult for image not built locally."""
return BuildResult(image_id=BuildResult.REMOTE_IMAGE,
annotations=annotations, labels=labels) | python | def make_remote_image_result(annotations=None, labels=None):
"""Instantiate BuildResult for image not built locally."""
return BuildResult(image_id=BuildResult.REMOTE_IMAGE,
annotations=annotations, labels=labels) | [
"def",
"make_remote_image_result",
"(",
"annotations",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"return",
"BuildResult",
"(",
"image_id",
"=",
"BuildResult",
".",
"REMOTE_IMAGE",
",",
"annotations",
"=",
"annotations",
",",
"labels",
"=",
"labels",
"... | Instantiate BuildResult for image not built locally. | [
"Instantiate",
"BuildResult",
"for",
"image",
"not",
"built",
"locally",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/build.py#L93-L96 | train | 28,568 |
projectatomic/atomic-reactor | atomic_reactor/build.py | InsideBuilder.base_image_inspect | def base_image_inspect(self):
"""
inspect base image
:return: dict
"""
if self._base_image_inspect is None:
if self.base_from_scratch:
self._base_image_inspect = {}
elif self.parents_pulled or self.custom_base_image:
try:
self._base_image_inspect = self.tasker.inspect_image(self.base_image)
except docker.errors.NotFound:
# If the base image cannot be found throw KeyError -
# as this property should behave like a dict
raise KeyError("Unprocessed base image Dockerfile cannot be inspected")
else:
self._base_image_inspect =\
atomic_reactor.util.get_inspect_for_image(self.base_image,
self.base_image.registry,
self.base_image_insecure,
self.base_image_dockercfg_path)
base_image_str = str(self.base_image)
if base_image_str not in self._parent_images_inspect:
self._parent_images_inspect[base_image_str] = self._base_image_inspect
return self._base_image_inspect | python | def base_image_inspect(self):
"""
inspect base image
:return: dict
"""
if self._base_image_inspect is None:
if self.base_from_scratch:
self._base_image_inspect = {}
elif self.parents_pulled or self.custom_base_image:
try:
self._base_image_inspect = self.tasker.inspect_image(self.base_image)
except docker.errors.NotFound:
# If the base image cannot be found throw KeyError -
# as this property should behave like a dict
raise KeyError("Unprocessed base image Dockerfile cannot be inspected")
else:
self._base_image_inspect =\
atomic_reactor.util.get_inspect_for_image(self.base_image,
self.base_image.registry,
self.base_image_insecure,
self.base_image_dockercfg_path)
base_image_str = str(self.base_image)
if base_image_str not in self._parent_images_inspect:
self._parent_images_inspect[base_image_str] = self._base_image_inspect
return self._base_image_inspect | [
"def",
"base_image_inspect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_base_image_inspect",
"is",
"None",
":",
"if",
"self",
".",
"base_from_scratch",
":",
"self",
".",
"_base_image_inspect",
"=",
"{",
"}",
"elif",
"self",
".",
"parents_pulled",
"or",
"sel... | inspect base image
:return: dict | [
"inspect",
"base",
"image"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/build.py#L269-L298 | train | 28,569 |
projectatomic/atomic-reactor | atomic_reactor/build.py | InsideBuilder.parent_image_inspect | def parent_image_inspect(self, image):
"""
inspect parent image
:return: dict
"""
image_name = ImageName.parse(image)
if image_name not in self._parent_images_inspect:
if self.parents_pulled:
self._parent_images_inspect[image_name] = self.tasker.inspect_image(image)
else:
self._parent_images_inspect[image_name] =\
atomic_reactor.util.get_inspect_for_image(image_name,
image_name.registry,
self.base_image_insecure,
self.base_image_dockercfg_path)
return self._parent_images_inspect[image_name] | python | def parent_image_inspect(self, image):
"""
inspect parent image
:return: dict
"""
image_name = ImageName.parse(image)
if image_name not in self._parent_images_inspect:
if self.parents_pulled:
self._parent_images_inspect[image_name] = self.tasker.inspect_image(image)
else:
self._parent_images_inspect[image_name] =\
atomic_reactor.util.get_inspect_for_image(image_name,
image_name.registry,
self.base_image_insecure,
self.base_image_dockercfg_path)
return self._parent_images_inspect[image_name] | [
"def",
"parent_image_inspect",
"(",
"self",
",",
"image",
")",
":",
"image_name",
"=",
"ImageName",
".",
"parse",
"(",
"image",
")",
"if",
"image_name",
"not",
"in",
"self",
".",
"_parent_images_inspect",
":",
"if",
"self",
".",
"parents_pulled",
":",
"self"... | inspect parent image
:return: dict | [
"inspect",
"parent",
"image"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/build.py#L300-L317 | train | 28,570 |
projectatomic/atomic-reactor | atomic_reactor/build.py | InsideBuilder.inspect_built_image | def inspect_built_image(self):
"""
inspect built image
:return: dict
"""
logger.info("inspecting built image '%s'", self.image_id)
self.ensure_is_built()
# dict with lots of data, see man docker-inspect
inspect_data = self.tasker.inspect_image(self.image_id)
return inspect_data | python | def inspect_built_image(self):
"""
inspect built image
:return: dict
"""
logger.info("inspecting built image '%s'", self.image_id)
self.ensure_is_built()
# dict with lots of data, see man docker-inspect
inspect_data = self.tasker.inspect_image(self.image_id)
return inspect_data | [
"def",
"inspect_built_image",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"inspecting built image '%s'\"",
",",
"self",
".",
"image_id",
")",
"self",
".",
"ensure_is_built",
"(",
")",
"# dict with lots of data, see man docker-inspect",
"inspect_data",
"=",
"s... | inspect built image
:return: dict | [
"inspect",
"built",
"image"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/build.py#L319-L329 | train | 28,571 |
projectatomic/atomic-reactor | atomic_reactor/build.py | InsideBuilder.get_base_image_info | def get_base_image_info(self):
"""
query docker about base image
:return dict
"""
if self.base_from_scratch:
return
logger.info("getting information about base image '%s'", self.base_image)
image_info = self.tasker.get_image_info_by_image_name(self.base_image)
items_count = len(image_info)
if items_count == 1:
return image_info[0]
elif items_count <= 0:
logger.error("image '%s' not found", self.base_image)
raise RuntimeError("image '%s' not found" % self.base_image)
else:
logger.error("multiple (%d) images found for image '%s'", items_count,
self.base_image)
raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
self.base_image)) | python | def get_base_image_info(self):
"""
query docker about base image
:return dict
"""
if self.base_from_scratch:
return
logger.info("getting information about base image '%s'", self.base_image)
image_info = self.tasker.get_image_info_by_image_name(self.base_image)
items_count = len(image_info)
if items_count == 1:
return image_info[0]
elif items_count <= 0:
logger.error("image '%s' not found", self.base_image)
raise RuntimeError("image '%s' not found" % self.base_image)
else:
logger.error("multiple (%d) images found for image '%s'", items_count,
self.base_image)
raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
self.base_image)) | [
"def",
"get_base_image_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"base_from_scratch",
":",
"return",
"logger",
".",
"info",
"(",
"\"getting information about base image '%s'\"",
",",
"self",
".",
"base_image",
")",
"image_info",
"=",
"self",
".",
"tasker",
... | query docker about base image
:return dict | [
"query",
"docker",
"about",
"base",
"image"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/build.py#L331-L351 | train | 28,572 |
projectatomic/atomic-reactor | atomic_reactor/build.py | InsideBuilder.get_built_image_info | def get_built_image_info(self):
"""
query docker about built image
:return dict
"""
logger.info("getting information about built image '%s'", self.image)
image_info = self.tasker.get_image_info_by_image_name(self.image)
items_count = len(image_info)
if items_count == 1:
return image_info[0]
elif items_count <= 0:
logger.error("image '%s' not found", self.image)
raise RuntimeError("image '%s' not found" % self.image)
else:
logger.error("multiple (%d) images found for image '%s'", items_count, self.image)
raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
self.image)) | python | def get_built_image_info(self):
"""
query docker about built image
:return dict
"""
logger.info("getting information about built image '%s'", self.image)
image_info = self.tasker.get_image_info_by_image_name(self.image)
items_count = len(image_info)
if items_count == 1:
return image_info[0]
elif items_count <= 0:
logger.error("image '%s' not found", self.image)
raise RuntimeError("image '%s' not found" % self.image)
else:
logger.error("multiple (%d) images found for image '%s'", items_count, self.image)
raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
self.image)) | [
"def",
"get_built_image_info",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"getting information about built image '%s'\"",
",",
"self",
".",
"image",
")",
"image_info",
"=",
"self",
".",
"tasker",
".",
"get_image_info_by_image_name",
"(",
"self",
".",
"im... | query docker about built image
:return dict | [
"query",
"docker",
"about",
"built",
"image"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/build.py#L353-L370 | train | 28,573 |
projectatomic/atomic-reactor | atomic_reactor/inner.py | build_inside | def build_inside(input_method, input_args=None, substitutions=None):
"""
use requested input plugin to load configuration and then initiate build
"""
def process_keyvals(keyvals):
""" ["key=val", "x=y"] -> {"key": "val", "x": "y"} """
keyvals = keyvals or []
processed_keyvals = {}
for arg in keyvals:
key, value = arg.split("=", 1)
processed_keyvals[key] = value
return processed_keyvals
main = __name__.split('.', 1)[0]
log_encoding = get_logging_encoding(main)
logger.info("log encoding: %s", log_encoding)
if not input_method:
raise RuntimeError("No input method specified!")
logger.debug("getting build json from input %s", input_method)
cleaned_input_args = process_keyvals(input_args)
cleaned_input_args['substitutions'] = process_keyvals(substitutions)
input_runner = InputPluginsRunner([{'name': input_method,
'args': cleaned_input_args}])
build_json = input_runner.run()[input_method]
if isinstance(build_json, Exception):
raise RuntimeError("Input plugin raised exception: {}".format(build_json))
logger.debug("build json: %s", build_json)
if not build_json:
raise RuntimeError("No valid build json!")
if not isinstance(build_json, dict):
raise RuntimeError("Input plugin did not return valid build json: {}".format(build_json))
dbw = DockerBuildWorkflow(**build_json)
try:
build_result = dbw.build_docker_image()
except Exception as e:
logger.error('image build failed: %s', e)
raise
else:
if not build_result or build_result.is_failed():
raise RuntimeError("no image built")
else:
logger.info("build has finished successfully \\o/") | python | def build_inside(input_method, input_args=None, substitutions=None):
"""
use requested input plugin to load configuration and then initiate build
"""
def process_keyvals(keyvals):
""" ["key=val", "x=y"] -> {"key": "val", "x": "y"} """
keyvals = keyvals or []
processed_keyvals = {}
for arg in keyvals:
key, value = arg.split("=", 1)
processed_keyvals[key] = value
return processed_keyvals
main = __name__.split('.', 1)[0]
log_encoding = get_logging_encoding(main)
logger.info("log encoding: %s", log_encoding)
if not input_method:
raise RuntimeError("No input method specified!")
logger.debug("getting build json from input %s", input_method)
cleaned_input_args = process_keyvals(input_args)
cleaned_input_args['substitutions'] = process_keyvals(substitutions)
input_runner = InputPluginsRunner([{'name': input_method,
'args': cleaned_input_args}])
build_json = input_runner.run()[input_method]
if isinstance(build_json, Exception):
raise RuntimeError("Input plugin raised exception: {}".format(build_json))
logger.debug("build json: %s", build_json)
if not build_json:
raise RuntimeError("No valid build json!")
if not isinstance(build_json, dict):
raise RuntimeError("Input plugin did not return valid build json: {}".format(build_json))
dbw = DockerBuildWorkflow(**build_json)
try:
build_result = dbw.build_docker_image()
except Exception as e:
logger.error('image build failed: %s', e)
raise
else:
if not build_result or build_result.is_failed():
raise RuntimeError("no image built")
else:
logger.info("build has finished successfully \\o/") | [
"def",
"build_inside",
"(",
"input_method",
",",
"input_args",
"=",
"None",
",",
"substitutions",
"=",
"None",
")",
":",
"def",
"process_keyvals",
"(",
"keyvals",
")",
":",
"\"\"\" [\"key=val\", \"x=y\"] -> {\"key\": \"val\", \"x\": \"y\"} \"\"\"",
"keyvals",
"=",
"keyv... | use requested input plugin to load configuration and then initiate build | [
"use",
"requested",
"input",
"plugin",
"to",
"load",
"configuration",
"and",
"then",
"initiate",
"build"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/inner.py#L531-L578 | train | 28,574 |
projectatomic/atomic-reactor | atomic_reactor/inner.py | FSWatcher.run | def run(self):
""" Overrides parent method to implement thread's functionality. """
while True: # make sure to run at least once before exiting
with self._lock:
self._update(self._data)
if self._done:
break
time.sleep(1) | python | def run(self):
""" Overrides parent method to implement thread's functionality. """
while True: # make sure to run at least once before exiting
with self._lock:
self._update(self._data)
if self._done:
break
time.sleep(1) | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"# make sure to run at least once before exiting",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_update",
"(",
"self",
".",
"_data",
")",
"if",
"self",
".",
"_done",
":",
"break",
"time",
".",
... | Overrides parent method to implement thread's functionality. | [
"Overrides",
"parent",
"method",
"to",
"implement",
"thread",
"s",
"functionality",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/inner.py#L272-L279 | train | 28,575 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_reactor_config.py | get_config | def get_config(workflow):
"""
Obtain configuration object
Does not fail
:return: ReactorConfig instance
"""
try:
workspace = workflow.plugin_workspace[ReactorConfigPlugin.key]
return workspace[WORKSPACE_CONF_KEY]
except KeyError:
# The plugin did not run or was not successful: use defaults
conf = ReactorConfig()
workspace = workflow.plugin_workspace.get(ReactorConfigPlugin.key, {})
workspace[WORKSPACE_CONF_KEY] = conf
workflow.plugin_workspace[ReactorConfigPlugin.key] = workspace
return conf | python | def get_config(workflow):
"""
Obtain configuration object
Does not fail
:return: ReactorConfig instance
"""
try:
workspace = workflow.plugin_workspace[ReactorConfigPlugin.key]
return workspace[WORKSPACE_CONF_KEY]
except KeyError:
# The plugin did not run or was not successful: use defaults
conf = ReactorConfig()
workspace = workflow.plugin_workspace.get(ReactorConfigPlugin.key, {})
workspace[WORKSPACE_CONF_KEY] = conf
workflow.plugin_workspace[ReactorConfigPlugin.key] = workspace
return conf | [
"def",
"get_config",
"(",
"workflow",
")",
":",
"try",
":",
"workspace",
"=",
"workflow",
".",
"plugin_workspace",
"[",
"ReactorConfigPlugin",
".",
"key",
"]",
"return",
"workspace",
"[",
"WORKSPACE_CONF_KEY",
"]",
"except",
"KeyError",
":",
"# The plugin did not ... | Obtain configuration object
Does not fail
:return: ReactorConfig instance | [
"Obtain",
"configuration",
"object",
"Does",
"not",
"fail"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_reactor_config.py#L26-L42 | train | 28,576 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_reactor_config.py | ReactorConfigPlugin.run | def run(self):
"""
Run the plugin
Parse and validate config.
Store in workflow workspace for later retrieval.
"""
if self.reactor_config_map:
self.log.info("reading config from REACTOR_CONFIG env variable")
conf = read_yaml(self.reactor_config_map, 'schemas/config.json')
else:
config_filename = os.path.join(self.config_path, self.basename)
self.log.info("reading config from %s", config_filename)
conf = read_yaml_from_file_path(config_filename, 'schemas/config.json')
reactor_conf = ReactorConfig(conf)
workspace = self.workflow.plugin_workspace.setdefault(self.key, {})
workspace[WORKSPACE_CONF_KEY] = reactor_conf
self.log.info("reading config content %s", reactor_conf.conf)
# need to stash this on the workflow for access in a place that can't import this module
self.workflow.default_image_build_method = get_default_image_build_method(self.workflow) | python | def run(self):
"""
Run the plugin
Parse and validate config.
Store in workflow workspace for later retrieval.
"""
if self.reactor_config_map:
self.log.info("reading config from REACTOR_CONFIG env variable")
conf = read_yaml(self.reactor_config_map, 'schemas/config.json')
else:
config_filename = os.path.join(self.config_path, self.basename)
self.log.info("reading config from %s", config_filename)
conf = read_yaml_from_file_path(config_filename, 'schemas/config.json')
reactor_conf = ReactorConfig(conf)
workspace = self.workflow.plugin_workspace.setdefault(self.key, {})
workspace[WORKSPACE_CONF_KEY] = reactor_conf
self.log.info("reading config content %s", reactor_conf.conf)
# need to stash this on the workflow for access in a place that can't import this module
self.workflow.default_image_build_method = get_default_image_build_method(self.workflow) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"reactor_config_map",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"reading config from REACTOR_CONFIG env variable\"",
")",
"conf",
"=",
"read_yaml",
"(",
"self",
".",
"reactor_config_map",
",",
"'schemas/... | Run the plugin
Parse and validate config.
Store in workflow workspace for later retrieval. | [
"Run",
"the",
"plugin"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_reactor_config.py#L507-L528 | train | 28,577 |
projectatomic/atomic-reactor | atomic_reactor/core.py | BuildContainerFactory._check_build_input | def _check_build_input(self, image, args_path):
"""
Internal method, validate provided args.
:param image: str
:param args_path: str, path dir which is mounter inside container
:return: None
:raises RuntimeError
"""
try:
with open(os.path.join(args_path, BUILD_JSON)) as json_args:
logger.debug("build input: image = '%s', args = '%s'", image, json_args.read())
except (IOError, OSError) as ex:
logger.error("unable to open json arguments: %r", ex)
raise RuntimeError("Unable to open json arguments: %r" % ex)
if not self.tasker.image_exists(image):
logger.error("provided build image doesn't exist: '%s'", image)
raise RuntimeError("Provided build image doesn't exist: '%s'" % image) | python | def _check_build_input(self, image, args_path):
"""
Internal method, validate provided args.
:param image: str
:param args_path: str, path dir which is mounter inside container
:return: None
:raises RuntimeError
"""
try:
with open(os.path.join(args_path, BUILD_JSON)) as json_args:
logger.debug("build input: image = '%s', args = '%s'", image, json_args.read())
except (IOError, OSError) as ex:
logger.error("unable to open json arguments: %r", ex)
raise RuntimeError("Unable to open json arguments: %r" % ex)
if not self.tasker.image_exists(image):
logger.error("provided build image doesn't exist: '%s'", image)
raise RuntimeError("Provided build image doesn't exist: '%s'" % image) | [
"def",
"_check_build_input",
"(",
"self",
",",
"image",
",",
"args_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args_path",
",",
"BUILD_JSON",
")",
")",
"as",
"json_args",
":",
"logger",
".",
"debug",
"(",
"... | Internal method, validate provided args.
:param image: str
:param args_path: str, path dir which is mounter inside container
:return: None
:raises RuntimeError | [
"Internal",
"method",
"validate",
"provided",
"args",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L80-L98 | train | 28,578 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.build_image_from_path | def build_image_from_path(self, path, image, use_cache=False, remove_im=True):
"""
build image from provided path and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param path: str
:param image: ImageName, name of the resulting image
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:param remove_im: bool, remove intermediate containers produced during docker build
:return: generator
"""
logger.info("building image '%s' from path '%s'", image, path)
response = self.d.build(path=path, tag=image.to_str(),
nocache=not use_cache, decode=True,
rm=remove_im, forcerm=True, pull=False) # returns generator
return response | python | def build_image_from_path(self, path, image, use_cache=False, remove_im=True):
"""
build image from provided path and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param path: str
:param image: ImageName, name of the resulting image
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:param remove_im: bool, remove intermediate containers produced during docker build
:return: generator
"""
logger.info("building image '%s' from path '%s'", image, path)
response = self.d.build(path=path, tag=image.to_str(),
nocache=not use_cache, decode=True,
rm=remove_im, forcerm=True, pull=False) # returns generator
return response | [
"def",
"build_image_from_path",
"(",
"self",
",",
"path",
",",
"image",
",",
"use_cache",
"=",
"False",
",",
"remove_im",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"\"building image '%s' from path '%s'\"",
",",
"image",
",",
"path",
")",
"response",
... | build image from provided path and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param path: str
:param image: ImageName, name of the resulting image
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:param remove_im: bool, remove intermediate containers produced during docker build
:return: generator | [
"build",
"image",
"from",
"provided",
"path",
"and",
"tag",
"it"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L346-L364 | train | 28,579 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.build_image_from_git | def build_image_from_git(self, url, image, git_path=None, git_commit=None,
copy_dockerfile_to=None,
stream=False, use_cache=False):
"""
build image from provided url and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param url: str
:param image: ImageName, name of the resulting image
:param git_path: str, path to dockerfile within gitrepo
:param copy_dockerfile_to: str, copy dockerfile to provided path
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:return: generator
"""
logger.info("building image '%s' from git repo '%s' specified as URL '%s'",
image, git_path, url)
logger.info("will copy Dockerfile to '%s'", copy_dockerfile_to)
temp_dir = tempfile.mkdtemp()
response = None
try:
clone_git_repo(url, temp_dir, git_commit)
build_file_path, build_file_dir = figure_out_build_file(temp_dir, git_path)
if copy_dockerfile_to: # TODO: pre build plugin
shutil.copyfile(build_file_path, copy_dockerfile_to)
response = self.build_image_from_path(build_file_dir, image, use_cache=use_cache)
finally:
try:
shutil.rmtree(temp_dir)
except (IOError, OSError) as ex:
# no idea why this is happening
logger.warning("Failed to remove dir '%s': %r", temp_dir, ex)
logger.info("build finished")
return response | python | def build_image_from_git(self, url, image, git_path=None, git_commit=None,
copy_dockerfile_to=None,
stream=False, use_cache=False):
"""
build image from provided url and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param url: str
:param image: ImageName, name of the resulting image
:param git_path: str, path to dockerfile within gitrepo
:param copy_dockerfile_to: str, copy dockerfile to provided path
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:return: generator
"""
logger.info("building image '%s' from git repo '%s' specified as URL '%s'",
image, git_path, url)
logger.info("will copy Dockerfile to '%s'", copy_dockerfile_to)
temp_dir = tempfile.mkdtemp()
response = None
try:
clone_git_repo(url, temp_dir, git_commit)
build_file_path, build_file_dir = figure_out_build_file(temp_dir, git_path)
if copy_dockerfile_to: # TODO: pre build plugin
shutil.copyfile(build_file_path, copy_dockerfile_to)
response = self.build_image_from_path(build_file_dir, image, use_cache=use_cache)
finally:
try:
shutil.rmtree(temp_dir)
except (IOError, OSError) as ex:
# no idea why this is happening
logger.warning("Failed to remove dir '%s': %r", temp_dir, ex)
logger.info("build finished")
return response | [
"def",
"build_image_from_git",
"(",
"self",
",",
"url",
",",
"image",
",",
"git_path",
"=",
"None",
",",
"git_commit",
"=",
"None",
",",
"copy_dockerfile_to",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"use_cache",
"=",
"False",
")",
":",
"logger",
"... | build image from provided url and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param url: str
:param image: ImageName, name of the resulting image
:param git_path: str, path to dockerfile within gitrepo
:param copy_dockerfile_to: str, copy dockerfile to provided path
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:return: generator | [
"build",
"image",
"from",
"provided",
"url",
"and",
"tag",
"it"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L366-L401 | train | 28,580 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.run | def run(self, image, command=None, create_kwargs=None, start_kwargs=None,
volume_bindings=None, privileged=None):
"""
create container from provided image and start it
for more info, see documentation of REST API calls:
* containers/{}/start
* container/create
:param image: ImageName or string, name or id of the image
:param command: str
:param create_kwargs: dict, kwargs for docker.create_container
:param start_kwargs: dict, kwargs for docker.start
:return: str, container id
"""
logger.info("creating container from image '%s' and running it", image)
create_kwargs = create_kwargs or {}
if 'host_config' not in create_kwargs:
conf = {}
if volume_bindings is not None:
conf['binds'] = volume_bindings
if privileged is not None:
conf['privileged'] = privileged
create_kwargs['host_config'] = self.d.create_host_config(**conf)
start_kwargs = start_kwargs or {}
logger.debug("image = '%s', command = '%s', create_kwargs = '%s', start_kwargs = '%s'",
image, command, create_kwargs, start_kwargs)
if isinstance(image, ImageName):
image = image.to_str()
container_dict = self.d.create_container(image, command=command, **create_kwargs)
container_id = container_dict['Id']
logger.debug("container_id = '%s'", container_id)
self.d.start(container_id, **start_kwargs) # returns None
return container_id | python | def run(self, image, command=None, create_kwargs=None, start_kwargs=None,
volume_bindings=None, privileged=None):
"""
create container from provided image and start it
for more info, see documentation of REST API calls:
* containers/{}/start
* container/create
:param image: ImageName or string, name or id of the image
:param command: str
:param create_kwargs: dict, kwargs for docker.create_container
:param start_kwargs: dict, kwargs for docker.start
:return: str, container id
"""
logger.info("creating container from image '%s' and running it", image)
create_kwargs = create_kwargs or {}
if 'host_config' not in create_kwargs:
conf = {}
if volume_bindings is not None:
conf['binds'] = volume_bindings
if privileged is not None:
conf['privileged'] = privileged
create_kwargs['host_config'] = self.d.create_host_config(**conf)
start_kwargs = start_kwargs or {}
logger.debug("image = '%s', command = '%s', create_kwargs = '%s', start_kwargs = '%s'",
image, command, create_kwargs, start_kwargs)
if isinstance(image, ImageName):
image = image.to_str()
container_dict = self.d.create_container(image, command=command, **create_kwargs)
container_id = container_dict['Id']
logger.debug("container_id = '%s'", container_id)
self.d.start(container_id, **start_kwargs) # returns None
return container_id | [
"def",
"run",
"(",
"self",
",",
"image",
",",
"command",
"=",
"None",
",",
"create_kwargs",
"=",
"None",
",",
"start_kwargs",
"=",
"None",
",",
"volume_bindings",
"=",
"None",
",",
"privileged",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"cre... | create container from provided image and start it
for more info, see documentation of REST API calls:
* containers/{}/start
* container/create
:param image: ImageName or string, name or id of the image
:param command: str
:param create_kwargs: dict, kwargs for docker.create_container
:param start_kwargs: dict, kwargs for docker.start
:return: str, container id | [
"create",
"container",
"from",
"provided",
"image",
"and",
"start",
"it"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L403-L440 | train | 28,581 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.commit_container | def commit_container(self, container_id, image=None, message=None):
"""
create image from provided container
:param container_id: str
:param image: ImageName
:param message: str
:return: image_id
"""
logger.info("committing container '%s'", container_id)
logger.debug("container_id = '%s', image = '%s', message = '%s'",
container_id, image, message)
tag = None
if image:
tag = image.tag
image = image.to_str(tag=False)
response = self.d.commit(container_id, repository=image, tag=tag, message=message)
logger.debug("response = '%s'", response)
try:
return response['Id']
except KeyError:
logger.error("ID missing from commit response")
raise RuntimeError("ID missing from commit response") | python | def commit_container(self, container_id, image=None, message=None):
"""
create image from provided container
:param container_id: str
:param image: ImageName
:param message: str
:return: image_id
"""
logger.info("committing container '%s'", container_id)
logger.debug("container_id = '%s', image = '%s', message = '%s'",
container_id, image, message)
tag = None
if image:
tag = image.tag
image = image.to_str(tag=False)
response = self.d.commit(container_id, repository=image, tag=tag, message=message)
logger.debug("response = '%s'", response)
try:
return response['Id']
except KeyError:
logger.error("ID missing from commit response")
raise RuntimeError("ID missing from commit response") | [
"def",
"commit_container",
"(",
"self",
",",
"container_id",
",",
"image",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"committing container '%s'\"",
",",
"container_id",
")",
"logger",
".",
"debug",
"(",
"\"container_id =... | create image from provided container
:param container_id: str
:param image: ImageName
:param message: str
:return: image_id | [
"create",
"image",
"from",
"provided",
"container"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L442-L464 | train | 28,582 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.pull_image | def pull_image(self, image, insecure=False, dockercfg_path=None):
"""
pull provided image from registry
:param image_name: ImageName, image to pull
:param insecure: bool, allow connecting to registry over plain http
:param dockercfg_path: str, path to dockercfg
:return: str, image (reg.om/img:v1)
"""
logger.info("pulling image '%s' from registry", image)
logger.debug("image = '%s', insecure = '%s'", image, insecure)
tag = image.tag
if dockercfg_path:
self.login(registry=image.registry, docker_secret_path=dockercfg_path)
try:
command_result = self.retry_generator(self.d.pull,
image.to_str(tag=False),
tag=tag, insecure_registry=insecure,
decode=True, stream=True)
except TypeError:
# because changing api is fun
command_result = self.retry_generator(self.d.pull,
image.to_str(tag=False),
tag=tag, decode=True, stream=True)
self.last_logs = command_result.logs
return image.to_str() | python | def pull_image(self, image, insecure=False, dockercfg_path=None):
"""
pull provided image from registry
:param image_name: ImageName, image to pull
:param insecure: bool, allow connecting to registry over plain http
:param dockercfg_path: str, path to dockercfg
:return: str, image (reg.om/img:v1)
"""
logger.info("pulling image '%s' from registry", image)
logger.debug("image = '%s', insecure = '%s'", image, insecure)
tag = image.tag
if dockercfg_path:
self.login(registry=image.registry, docker_secret_path=dockercfg_path)
try:
command_result = self.retry_generator(self.d.pull,
image.to_str(tag=False),
tag=tag, insecure_registry=insecure,
decode=True, stream=True)
except TypeError:
# because changing api is fun
command_result = self.retry_generator(self.d.pull,
image.to_str(tag=False),
tag=tag, decode=True, stream=True)
self.last_logs = command_result.logs
return image.to_str() | [
"def",
"pull_image",
"(",
"self",
",",
"image",
",",
"insecure",
"=",
"False",
",",
"dockercfg_path",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"pulling image '%s' from registry\"",
",",
"image",
")",
"logger",
".",
"debug",
"(",
"\"image = '%s', in... | pull provided image from registry
:param image_name: ImageName, image to pull
:param insecure: bool, allow connecting to registry over plain http
:param dockercfg_path: str, path to dockercfg
:return: str, image (reg.om/img:v1) | [
"pull",
"provided",
"image",
"from",
"registry"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L522-L549 | train | 28,583 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.tag_image | def tag_image(self, image, target_image, force=False):
"""
tag provided image with specified image_name, registry and tag
:param image: str or ImageName, image to tag
:param target_image: ImageName, new name for the image
:param force: bool, force tag the image?
:return: str, image (reg.om/img:v1)
"""
logger.info("tagging image '%s' as '%s'", image, target_image)
logger.debug("image = '%s', target_image_name = '%s'", image, target_image)
if not isinstance(image, ImageName):
image = ImageName.parse(image)
if image != target_image:
response = self.d.tag(
image.to_str(),
target_image.to_str(tag=False),
tag=target_image.tag,
force=force) # returns True/False
if not response:
logger.error("failed to tag image")
raise RuntimeError("Failed to tag image '%s': target_image = '%s'" %
image.to_str(), target_image)
else:
logger.debug('image already tagged correctly, nothing to do')
return target_image.to_str() | python | def tag_image(self, image, target_image, force=False):
"""
tag provided image with specified image_name, registry and tag
:param image: str or ImageName, image to tag
:param target_image: ImageName, new name for the image
:param force: bool, force tag the image?
:return: str, image (reg.om/img:v1)
"""
logger.info("tagging image '%s' as '%s'", image, target_image)
logger.debug("image = '%s', target_image_name = '%s'", image, target_image)
if not isinstance(image, ImageName):
image = ImageName.parse(image)
if image != target_image:
response = self.d.tag(
image.to_str(),
target_image.to_str(tag=False),
tag=target_image.tag,
force=force) # returns True/False
if not response:
logger.error("failed to tag image")
raise RuntimeError("Failed to tag image '%s': target_image = '%s'" %
image.to_str(), target_image)
else:
logger.debug('image already tagged correctly, nothing to do')
return target_image.to_str() | [
"def",
"tag_image",
"(",
"self",
",",
"image",
",",
"target_image",
",",
"force",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"tagging image '%s' as '%s'\"",
",",
"image",
",",
"target_image",
")",
"logger",
".",
"debug",
"(",
"\"image = '%s', target... | tag provided image with specified image_name, registry and tag
:param image: str or ImageName, image to tag
:param target_image: ImageName, new name for the image
:param force: bool, force tag the image?
:return: str, image (reg.om/img:v1) | [
"tag",
"provided",
"image",
"with",
"specified",
"image_name",
"registry",
"and",
"tag"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L551-L577 | train | 28,584 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.login | def login(self, registry, docker_secret_path):
"""
login to docker registry
:param registry: registry name
:param docker_secret_path: path to docker config directory
"""
logger.info("logging in: registry '%s', secret path '%s'", registry, docker_secret_path)
# Docker-py needs username
dockercfg = Dockercfg(docker_secret_path)
credentials = dockercfg.get_credentials(registry)
unpacked_auth = dockercfg.unpack_auth_b64(registry)
username = credentials.get('username')
if unpacked_auth:
username = unpacked_auth.username
if not username:
raise RuntimeError("Failed to extract a username from '%s'" % dockercfg)
logger.info("found username %s for registry %s", username, registry)
response = self.d.login(registry=registry, username=username,
dockercfg_path=dockercfg.json_secret_path)
if not response:
raise RuntimeError("Failed to login to '%s' with config '%s'" % (registry, dockercfg))
if u'Status' in response and response[u'Status'] == u'Login Succeeded':
logger.info("login succeeded")
else:
if not(isinstance(response, dict) and 'password' in response.keys()):
# for some reason docker-py returns the contents of the dockercfg - we shouldn't
# be displaying that
logger.debug("response: %r", response) | python | def login(self, registry, docker_secret_path):
"""
login to docker registry
:param registry: registry name
:param docker_secret_path: path to docker config directory
"""
logger.info("logging in: registry '%s', secret path '%s'", registry, docker_secret_path)
# Docker-py needs username
dockercfg = Dockercfg(docker_secret_path)
credentials = dockercfg.get_credentials(registry)
unpacked_auth = dockercfg.unpack_auth_b64(registry)
username = credentials.get('username')
if unpacked_auth:
username = unpacked_auth.username
if not username:
raise RuntimeError("Failed to extract a username from '%s'" % dockercfg)
logger.info("found username %s for registry %s", username, registry)
response = self.d.login(registry=registry, username=username,
dockercfg_path=dockercfg.json_secret_path)
if not response:
raise RuntimeError("Failed to login to '%s' with config '%s'" % (registry, dockercfg))
if u'Status' in response and response[u'Status'] == u'Login Succeeded':
logger.info("login succeeded")
else:
if not(isinstance(response, dict) and 'password' in response.keys()):
# for some reason docker-py returns the contents of the dockercfg - we shouldn't
# be displaying that
logger.debug("response: %r", response) | [
"def",
"login",
"(",
"self",
",",
"registry",
",",
"docker_secret_path",
")",
":",
"logger",
".",
"info",
"(",
"\"logging in: registry '%s', secret path '%s'\"",
",",
"registry",
",",
"docker_secret_path",
")",
"# Docker-py needs username",
"dockercfg",
"=",
"Dockercfg"... | login to docker registry
:param registry: registry name
:param docker_secret_path: path to docker config directory | [
"login",
"to",
"docker",
"registry"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L579-L609 | train | 28,585 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.push_image | def push_image(self, image, insecure=False):
"""
push provided image to registry
:param image: ImageName
:param insecure: bool, allow connecting to registry over plain http
:return: str, logs from push
"""
logger.info("pushing image '%s'", image)
logger.debug("image: '%s', insecure: '%s'", image, insecure)
try:
# push returns string composed of newline separated jsons; exactly what 'docker push'
# outputs
command_result = self.retry_generator(self.d.push,
image.to_str(tag=False),
tag=image.tag, insecure_registry=insecure,
decode=True, stream=True)
except TypeError:
# because changing api is fun
command_result = self.retry_generator(self.d.push,
image.to_str(tag=False),
tag=image.tag, decode=True, stream=True)
self.last_logs = command_result.logs
return command_result.parsed_logs | python | def push_image(self, image, insecure=False):
"""
push provided image to registry
:param image: ImageName
:param insecure: bool, allow connecting to registry over plain http
:return: str, logs from push
"""
logger.info("pushing image '%s'", image)
logger.debug("image: '%s', insecure: '%s'", image, insecure)
try:
# push returns string composed of newline separated jsons; exactly what 'docker push'
# outputs
command_result = self.retry_generator(self.d.push,
image.to_str(tag=False),
tag=image.tag, insecure_registry=insecure,
decode=True, stream=True)
except TypeError:
# because changing api is fun
command_result = self.retry_generator(self.d.push,
image.to_str(tag=False),
tag=image.tag, decode=True, stream=True)
self.last_logs = command_result.logs
return command_result.parsed_logs | [
"def",
"push_image",
"(",
"self",
",",
"image",
",",
"insecure",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"pushing image '%s'\"",
",",
"image",
")",
"logger",
".",
"debug",
"(",
"\"image: '%s', insecure: '%s'\"",
",",
"image",
",",
"insecure",
"... | push provided image to registry
:param image: ImageName
:param insecure: bool, allow connecting to registry over plain http
:return: str, logs from push | [
"push",
"provided",
"image",
"to",
"registry"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L611-L635 | train | 28,586 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.tag_and_push_image | def tag_and_push_image(self, image, target_image, insecure=False, force=False,
dockercfg=None):
"""
tag provided image and push it to registry
:param image: str or ImageName, image id or name
:param target_image: ImageName, img
:param insecure: bool, allow connecting to registry over plain http
:param force: bool, force the tag?
:param dockercfg: path to docker config
:return: str, image (reg.com/img:v1)
"""
logger.info("tagging and pushing image '%s' as '%s'", image, target_image)
logger.debug("image = '%s', target_image = '%s'", image, target_image)
self.tag_image(image, target_image, force=force)
if dockercfg:
self.login(registry=target_image.registry, docker_secret_path=dockercfg)
return self.push_image(target_image, insecure=insecure) | python | def tag_and_push_image(self, image, target_image, insecure=False, force=False,
dockercfg=None):
"""
tag provided image and push it to registry
:param image: str or ImageName, image id or name
:param target_image: ImageName, img
:param insecure: bool, allow connecting to registry over plain http
:param force: bool, force the tag?
:param dockercfg: path to docker config
:return: str, image (reg.com/img:v1)
"""
logger.info("tagging and pushing image '%s' as '%s'", image, target_image)
logger.debug("image = '%s', target_image = '%s'", image, target_image)
self.tag_image(image, target_image, force=force)
if dockercfg:
self.login(registry=target_image.registry, docker_secret_path=dockercfg)
return self.push_image(target_image, insecure=insecure) | [
"def",
"tag_and_push_image",
"(",
"self",
",",
"image",
",",
"target_image",
",",
"insecure",
"=",
"False",
",",
"force",
"=",
"False",
",",
"dockercfg",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"tagging and pushing image '%s' as '%s'\"",
",",
"ima... | tag provided image and push it to registry
:param image: str or ImageName, image id or name
:param target_image: ImageName, img
:param insecure: bool, allow connecting to registry over plain http
:param force: bool, force the tag?
:param dockercfg: path to docker config
:return: str, image (reg.com/img:v1) | [
"tag",
"provided",
"image",
"and",
"push",
"it",
"to",
"registry"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L637-L654 | train | 28,587 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.remove_image | def remove_image(self, image_id, force=False, noprune=False):
"""
remove provided image from filesystem
:param image_id: str or ImageName
:param noprune: bool, keep untagged parents?
:param force: bool, force remove -- just trash it no matter what
:return: None
"""
logger.info("removing image '%s' from filesystem", image_id)
logger.debug("image_id = '%s'", image_id)
if isinstance(image_id, ImageName):
image_id = image_id.to_str()
self.d.remove_image(image_id, force=force, noprune=noprune) | python | def remove_image(self, image_id, force=False, noprune=False):
"""
remove provided image from filesystem
:param image_id: str or ImageName
:param noprune: bool, keep untagged parents?
:param force: bool, force remove -- just trash it no matter what
:return: None
"""
logger.info("removing image '%s' from filesystem", image_id)
logger.debug("image_id = '%s'", image_id)
if isinstance(image_id, ImageName):
image_id = image_id.to_str()
self.d.remove_image(image_id, force=force, noprune=noprune) | [
"def",
"remove_image",
"(",
"self",
",",
"image_id",
",",
"force",
"=",
"False",
",",
"noprune",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"removing image '%s' from filesystem\"",
",",
"image_id",
")",
"logger",
".",
"debug",
"(",
"\"image_id = '%s... | remove provided image from filesystem
:param image_id: str or ImageName
:param noprune: bool, keep untagged parents?
:param force: bool, force remove -- just trash it no matter what
:return: None | [
"remove",
"provided",
"image",
"from",
"filesystem"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L670-L683 | train | 28,588 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.remove_container | def remove_container(self, container_id, force=False):
"""
remove provided container from filesystem
:param container_id: str
:param force: bool, remove forcefully?
:return: None
"""
logger.info("removing container '%s' from filesystem", container_id)
logger.debug("container_id = '%s'", container_id)
self.d.remove_container(container_id, force=force) | python | def remove_container(self, container_id, force=False):
"""
remove provided container from filesystem
:param container_id: str
:param force: bool, remove forcefully?
:return: None
"""
logger.info("removing container '%s' from filesystem", container_id)
logger.debug("container_id = '%s'", container_id)
self.d.remove_container(container_id, force=force) | [
"def",
"remove_container",
"(",
"self",
",",
"container_id",
",",
"force",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"removing container '%s' from filesystem\"",
",",
"container_id",
")",
"logger",
".",
"debug",
"(",
"\"container_id = '%s'\"",
",",
"co... | remove provided container from filesystem
:param container_id: str
:param force: bool, remove forcefully?
:return: None | [
"remove",
"provided",
"container",
"from",
"filesystem"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L685-L695 | train | 28,589 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.image_exists | def image_exists(self, image_id):
"""
does provided image exists?
:param image_id: str or ImageName
:return: True if exists, False if not
"""
logger.info("checking whether image '%s' exists", image_id)
logger.debug("image_id = '%s'", image_id)
try:
response = self.d.inspect_image(image_id)
except APIError as ex:
logger.warning(repr(ex))
response = False
else:
response = response is not None
logger.debug("image exists: %s", response)
return response | python | def image_exists(self, image_id):
"""
does provided image exists?
:param image_id: str or ImageName
:return: True if exists, False if not
"""
logger.info("checking whether image '%s' exists", image_id)
logger.debug("image_id = '%s'", image_id)
try:
response = self.d.inspect_image(image_id)
except APIError as ex:
logger.warning(repr(ex))
response = False
else:
response = response is not None
logger.debug("image exists: %s", response)
return response | [
"def",
"image_exists",
"(",
"self",
",",
"image_id",
")",
":",
"logger",
".",
"info",
"(",
"\"checking whether image '%s' exists\"",
",",
"image_id",
")",
"logger",
".",
"debug",
"(",
"\"image_id = '%s'\"",
",",
"image_id",
")",
"try",
":",
"response",
"=",
"s... | does provided image exists?
:param image_id: str or ImageName
:return: True if exists, False if not | [
"does",
"provided",
"image",
"exists?"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L729-L746 | train | 28,590 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.get_volumes_for_container | def get_volumes_for_container(self, container_id, skip_empty_source=True):
"""
get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names
"""
logger.info("listing volumes for container '%s'", container_id)
inspect_output = self.d.inspect_container(container_id)
volumes = inspect_output['Mounts'] or []
volume_names = [x['Name'] for x in volumes]
if skip_empty_source:
# Don't show volumes which are not on the filesystem
volume_names = [x['Name'] for x in volumes if x['Source'] != ""]
logger.debug("volumes = %s", volume_names)
return volume_names | python | def get_volumes_for_container(self, container_id, skip_empty_source=True):
"""
get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names
"""
logger.info("listing volumes for container '%s'", container_id)
inspect_output = self.d.inspect_container(container_id)
volumes = inspect_output['Mounts'] or []
volume_names = [x['Name'] for x in volumes]
if skip_empty_source:
# Don't show volumes which are not on the filesystem
volume_names = [x['Name'] for x in volumes if x['Source'] != ""]
logger.debug("volumes = %s", volume_names)
return volume_names | [
"def",
"get_volumes_for_container",
"(",
"self",
",",
"container_id",
",",
"skip_empty_source",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"\"listing volumes for container '%s'\"",
",",
"container_id",
")",
"inspect_output",
"=",
"self",
".",
"d",
".",
"in... | get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names | [
"get",
"a",
"list",
"of",
"volumes",
"mounter",
"in",
"a",
"container"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L764-L782 | train | 28,591 |
projectatomic/atomic-reactor | atomic_reactor/core.py | DockerTasker.remove_volume | def remove_volume(self, volume_name):
"""
remove a volume by its name
:param volume_name: str
:return None
"""
logger.info("removing volume '%s'", volume_name)
try:
self.d.remove_volume(volume_name)
except APIError as ex:
if ex.response.status_code == requests.codes.CONFLICT:
logger.debug("ignoring a conflict when removing volume %s", volume_name)
else:
raise ex | python | def remove_volume(self, volume_name):
"""
remove a volume by its name
:param volume_name: str
:return None
"""
logger.info("removing volume '%s'", volume_name)
try:
self.d.remove_volume(volume_name)
except APIError as ex:
if ex.response.status_code == requests.codes.CONFLICT:
logger.debug("ignoring a conflict when removing volume %s", volume_name)
else:
raise ex | [
"def",
"remove_volume",
"(",
"self",
",",
"volume_name",
")",
":",
"logger",
".",
"info",
"(",
"\"removing volume '%s'\"",
",",
"volume_name",
")",
"try",
":",
"self",
".",
"d",
".",
"remove_volume",
"(",
"volume_name",
")",
"except",
"APIError",
"as",
"ex",... | remove a volume by its name
:param volume_name: str
:return None | [
"remove",
"a",
"volume",
"by",
"its",
"name"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L784-L798 | train | 28,592 |
projectatomic/atomic-reactor | atomic_reactor/plugins/input_env.py | EnvInputPlugin.run | def run(self):
"""
get json with build config from environment variable
"""
env_name = self.env_name or BUILD_JSON_ENV
try:
build_cfg_json = os.environ[env_name]
except KeyError:
self.log.error("build config not found in env variable '%s'", env_name)
return None
else:
try:
return self.substitute_configuration(json.loads(build_cfg_json))
except ValueError:
self.log.error("couldn't load build config: invalid json")
return None | python | def run(self):
"""
get json with build config from environment variable
"""
env_name = self.env_name or BUILD_JSON_ENV
try:
build_cfg_json = os.environ[env_name]
except KeyError:
self.log.error("build config not found in env variable '%s'", env_name)
return None
else:
try:
return self.substitute_configuration(json.loads(build_cfg_json))
except ValueError:
self.log.error("couldn't load build config: invalid json")
return None | [
"def",
"run",
"(",
"self",
")",
":",
"env_name",
"=",
"self",
".",
"env_name",
"or",
"BUILD_JSON_ENV",
"try",
":",
"build_cfg_json",
"=",
"os",
".",
"environ",
"[",
"env_name",
"]",
"except",
"KeyError",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"b... | get json with build config from environment variable | [
"get",
"json",
"with",
"build",
"config",
"from",
"environment",
"variable"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/input_env.py#L31-L46 | train | 28,593 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_add_filesystem.py | AddFilesystemPlugin.get_default_image_build_conf | def get_default_image_build_conf(self):
"""Create a default image build config
:rtype: ConfigParser
:return: Initialized config with defaults
"""
target = self.koji_target
vcs_info = self.workflow.source.get_vcs_info()
ksurl = '{}#{}'.format(vcs_info.vcs_url, vcs_info.vcs_ref)
base_urls = []
for repo in self.repos:
for url in self.extract_base_url(repo):
# Imagefactory only supports $arch variable.
url = url.replace('$basearch', '$arch')
base_urls.append(url)
install_tree = base_urls[0] if base_urls else ''
repo = ','.join(base_urls)
kwargs = {
'target': target,
'ksurl': ksurl,
'install_tree': install_tree,
'repo': repo,
}
config_fp = StringIO(self.DEFAULT_IMAGE_BUILD_CONF.format(**kwargs))
config = ConfigParser()
config.readfp(config_fp)
self.update_config_from_dockerfile(config)
return config | python | def get_default_image_build_conf(self):
"""Create a default image build config
:rtype: ConfigParser
:return: Initialized config with defaults
"""
target = self.koji_target
vcs_info = self.workflow.source.get_vcs_info()
ksurl = '{}#{}'.format(vcs_info.vcs_url, vcs_info.vcs_ref)
base_urls = []
for repo in self.repos:
for url in self.extract_base_url(repo):
# Imagefactory only supports $arch variable.
url = url.replace('$basearch', '$arch')
base_urls.append(url)
install_tree = base_urls[0] if base_urls else ''
repo = ','.join(base_urls)
kwargs = {
'target': target,
'ksurl': ksurl,
'install_tree': install_tree,
'repo': repo,
}
config_fp = StringIO(self.DEFAULT_IMAGE_BUILD_CONF.format(**kwargs))
config = ConfigParser()
config.readfp(config_fp)
self.update_config_from_dockerfile(config)
return config | [
"def",
"get_default_image_build_conf",
"(",
"self",
")",
":",
"target",
"=",
"self",
".",
"koji_target",
"vcs_info",
"=",
"self",
".",
"workflow",
".",
"source",
".",
"get_vcs_info",
"(",
")",
"ksurl",
"=",
"'{}#{}'",
".",
"format",
"(",
"vcs_info",
".",
"... | Create a default image build config
:rtype: ConfigParser
:return: Initialized config with defaults | [
"Create",
"a",
"default",
"image",
"build",
"config"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_add_filesystem.py#L146-L181 | train | 28,594 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_add_filesystem.py | AddFilesystemPlugin.update_config_from_dockerfile | def update_config_from_dockerfile(self, config):
"""Updates build config with values from the Dockerfile
Updates:
* set "name" from LABEL com.redhat.component (if exists)
* set "version" from LABEL version (if exists)
:param config: ConfigParser object
"""
labels = Labels(df_parser(self.workflow.builder.df_path).labels)
for config_key, label in (
('name', Labels.LABEL_TYPE_COMPONENT),
('version', Labels.LABEL_TYPE_VERSION),
):
try:
_, value = labels.get_name_and_value(label)
except KeyError:
pass
else:
config.set('image-build', config_key, value) | python | def update_config_from_dockerfile(self, config):
"""Updates build config with values from the Dockerfile
Updates:
* set "name" from LABEL com.redhat.component (if exists)
* set "version" from LABEL version (if exists)
:param config: ConfigParser object
"""
labels = Labels(df_parser(self.workflow.builder.df_path).labels)
for config_key, label in (
('name', Labels.LABEL_TYPE_COMPONENT),
('version', Labels.LABEL_TYPE_VERSION),
):
try:
_, value = labels.get_name_and_value(label)
except KeyError:
pass
else:
config.set('image-build', config_key, value) | [
"def",
"update_config_from_dockerfile",
"(",
"self",
",",
"config",
")",
":",
"labels",
"=",
"Labels",
"(",
"df_parser",
"(",
"self",
".",
"workflow",
".",
"builder",
".",
"df_path",
")",
".",
"labels",
")",
"for",
"config_key",
",",
"label",
"in",
"(",
... | Updates build config with values from the Dockerfile
Updates:
* set "name" from LABEL com.redhat.component (if exists)
* set "version" from LABEL version (if exists)
:param config: ConfigParser object | [
"Updates",
"build",
"config",
"with",
"values",
"from",
"the",
"Dockerfile"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_add_filesystem.py#L183-L202 | train | 28,595 |
projectatomic/atomic-reactor | atomic_reactor/plugin.py | PluginsRunner.load_plugins | def load_plugins(self, plugin_class_name):
"""
load all available plugins
:param plugin_class_name: str, name of plugin class (e.g. 'PreBuildPlugin')
:return: dict, bindings for plugins of the plugin_class_name class
"""
# imp.findmodule('atomic_reactor') doesn't work
plugins_dir = os.path.join(os.path.dirname(__file__), 'plugins')
logger.debug("loading plugins from dir '%s'", plugins_dir)
files = [os.path.join(plugins_dir, f)
for f in os.listdir(plugins_dir)
if f.endswith(".py")]
if self.plugin_files:
logger.debug("loading additional plugins from files '%s'", self.plugin_files)
files += self.plugin_files
plugin_class = globals()[plugin_class_name]
plugin_classes = {}
for f in files:
module_name = os.path.basename(f).rsplit('.', 1)[0]
# Do not reload plugins
if module_name in sys.modules:
f_module = sys.modules[module_name]
else:
try:
logger.debug("load file '%s'", f)
f_module = imp.load_source(module_name, f)
except (IOError, OSError, ImportError, SyntaxError) as ex:
logger.warning("can't load module '%s': %r", f, ex)
continue
for name in dir(f_module):
binding = getattr(f_module, name, None)
try:
# if you try to compare binding and PostBuildPlugin, python won't match them
# if you call this script directly b/c:
# ! <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class
# '__main__.PostBuildPlugin'>
# but
# <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class
# 'atomic_reactor.plugin.PostBuildPlugin'>
is_sub = issubclass(binding, plugin_class)
except TypeError:
is_sub = False
if binding and is_sub and plugin_class.__name__ != binding.__name__:
plugin_classes[binding.key] = binding
return plugin_classes | python | def load_plugins(self, plugin_class_name):
"""
load all available plugins
:param plugin_class_name: str, name of plugin class (e.g. 'PreBuildPlugin')
:return: dict, bindings for plugins of the plugin_class_name class
"""
# imp.findmodule('atomic_reactor') doesn't work
plugins_dir = os.path.join(os.path.dirname(__file__), 'plugins')
logger.debug("loading plugins from dir '%s'", plugins_dir)
files = [os.path.join(plugins_dir, f)
for f in os.listdir(plugins_dir)
if f.endswith(".py")]
if self.plugin_files:
logger.debug("loading additional plugins from files '%s'", self.plugin_files)
files += self.plugin_files
plugin_class = globals()[plugin_class_name]
plugin_classes = {}
for f in files:
module_name = os.path.basename(f).rsplit('.', 1)[0]
# Do not reload plugins
if module_name in sys.modules:
f_module = sys.modules[module_name]
else:
try:
logger.debug("load file '%s'", f)
f_module = imp.load_source(module_name, f)
except (IOError, OSError, ImportError, SyntaxError) as ex:
logger.warning("can't load module '%s': %r", f, ex)
continue
for name in dir(f_module):
binding = getattr(f_module, name, None)
try:
# if you try to compare binding and PostBuildPlugin, python won't match them
# if you call this script directly b/c:
# ! <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class
# '__main__.PostBuildPlugin'>
# but
# <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class
# 'atomic_reactor.plugin.PostBuildPlugin'>
is_sub = issubclass(binding, plugin_class)
except TypeError:
is_sub = False
if binding and is_sub and plugin_class.__name__ != binding.__name__:
plugin_classes[binding.key] = binding
return plugin_classes | [
"def",
"load_plugins",
"(",
"self",
",",
"plugin_class_name",
")",
":",
"# imp.findmodule('atomic_reactor') doesn't work",
"plugins_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'plugins'",
")",
... | load all available plugins
:param plugin_class_name: str, name of plugin class (e.g. 'PreBuildPlugin')
:return: dict, bindings for plugins of the plugin_class_name class | [
"load",
"all",
"available",
"plugins"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugin.py#L129-L174 | train | 28,596 |
projectatomic/atomic-reactor | atomic_reactor/plugin.py | PluginsRunner.get_available_plugins | def get_available_plugins(self):
"""
check requested plugins availability
and handle missing plugins
:return: list of namedtuples, runnable plugins data
"""
available_plugins = []
PluginData = namedtuple('PluginData', 'name, plugin_class, conf, is_allowed_to_fail')
for plugin_request in self.plugins_conf:
plugin_name = plugin_request['name']
try:
plugin_class = self.plugin_classes[plugin_name]
except KeyError:
if plugin_request.get('required', True):
msg = ("no such plugin: '%s', did you set "
"the correct plugin type?") % plugin_name
exc = PluginFailedException(msg)
self.on_plugin_failed(plugin_name, exc)
logger.error(msg)
raise exc
else:
# This plugin is marked as not being required
logger.warning("plugin '%s' requested but not available",
plugin_name)
continue
plugin_is_allowed_to_fail = plugin_request.get('is_allowed_to_fail',
getattr(plugin_class,
"is_allowed_to_fail", True))
plugin_conf = plugin_request.get("args", {})
plugin = PluginData(plugin_name,
plugin_class,
plugin_conf,
plugin_is_allowed_to_fail)
available_plugins.append(plugin)
return available_plugins | python | def get_available_plugins(self):
"""
check requested plugins availability
and handle missing plugins
:return: list of namedtuples, runnable plugins data
"""
available_plugins = []
PluginData = namedtuple('PluginData', 'name, plugin_class, conf, is_allowed_to_fail')
for plugin_request in self.plugins_conf:
plugin_name = plugin_request['name']
try:
plugin_class = self.plugin_classes[plugin_name]
except KeyError:
if plugin_request.get('required', True):
msg = ("no such plugin: '%s', did you set "
"the correct plugin type?") % plugin_name
exc = PluginFailedException(msg)
self.on_plugin_failed(plugin_name, exc)
logger.error(msg)
raise exc
else:
# This plugin is marked as not being required
logger.warning("plugin '%s' requested but not available",
plugin_name)
continue
plugin_is_allowed_to_fail = plugin_request.get('is_allowed_to_fail',
getattr(plugin_class,
"is_allowed_to_fail", True))
plugin_conf = plugin_request.get("args", {})
plugin = PluginData(plugin_name,
plugin_class,
plugin_conf,
plugin_is_allowed_to_fail)
available_plugins.append(plugin)
return available_plugins | [
"def",
"get_available_plugins",
"(",
"self",
")",
":",
"available_plugins",
"=",
"[",
"]",
"PluginData",
"=",
"namedtuple",
"(",
"'PluginData'",
",",
"'name, plugin_class, conf, is_allowed_to_fail'",
")",
"for",
"plugin_request",
"in",
"self",
".",
"plugins_conf",
":"... | check requested plugins availability
and handle missing plugins
:return: list of namedtuples, runnable plugins data | [
"check",
"requested",
"plugins",
"availability",
"and",
"handle",
"missing",
"plugins"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugin.py#L196-L231 | train | 28,597 |
projectatomic/atomic-reactor | atomic_reactor/plugin.py | PluginsRunner.run | def run(self, keep_going=False, buildstep_phase=False):
"""
run all requested plugins
:param keep_going: bool, whether to keep going after unexpected
failure (only used for exit plugins)
:param buildstep_phase: bool, when True remaining plugins will
not be executed after a plugin completes
(only used for build-step plugins)
"""
failed_msgs = []
plugin_successful = False
plugin_response = None
available_plugins = self.available_plugins
for plugin in available_plugins:
plugin_successful = False
logger.debug("running plugin '%s'", plugin.name)
start_time = datetime.datetime.now()
plugin_response = None
skip_response = False
try:
plugin_instance = self.create_instance_from_plugin(plugin.plugin_class,
plugin.conf)
self.save_plugin_timestamp(plugin.plugin_class.key, start_time)
plugin_response = plugin_instance.run()
plugin_successful = True
if buildstep_phase:
assert isinstance(plugin_response, BuildResult)
if plugin_response.is_failed():
logger.error("Build step plugin %s failed: %s",
plugin.plugin_class.key,
plugin_response.fail_reason)
self.on_plugin_failed(plugin.plugin_class.key,
plugin_response.fail_reason)
plugin_successful = False
self.plugins_results[plugin.plugin_class.key] = plugin_response
break
except AutoRebuildCanceledException as ex:
# if auto rebuild is canceled, then just reraise
# NOTE: We need to catch and reraise explicitly, so that the below except clause
# doesn't catch this and make PluginFailedException out of it in the end
# (calling methods would then need to parse exception message to see if
# AutoRebuildCanceledException was raised here)
raise
except InappropriateBuildStepError:
logger.debug('Build step %s is not appropriate', plugin.plugin_class.key)
# don't put None, in results for InappropriateBuildStepError
skip_response = True
if not buildstep_phase:
raise
except Exception as ex:
msg = "plugin '%s' raised an exception: %r" % (plugin.plugin_class.key, ex)
logger.debug(traceback.format_exc())
if not plugin.is_allowed_to_fail:
self.on_plugin_failed(plugin.plugin_class.key, ex)
if plugin.is_allowed_to_fail or keep_going:
logger.warning(msg)
logger.info("error is not fatal, continuing...")
if not plugin.is_allowed_to_fail:
failed_msgs.append(msg)
else:
logger.error(msg)
raise PluginFailedException(msg)
plugin_response = ex
try:
if start_time:
finish_time = datetime.datetime.now()
duration = finish_time - start_time
seconds = duration.total_seconds()
logger.debug("plugin '%s' finished in %ds", plugin.name, seconds)
self.save_plugin_duration(plugin.plugin_class.key, seconds)
except Exception:
logger.exception("failed to save plugin duration")
if not skip_response:
self.plugins_results[plugin.plugin_class.key] = plugin_response
if plugin_successful and buildstep_phase:
logger.debug('stopping further execution of plugins '
'after first successful plugin')
break
if len(failed_msgs) == 1:
raise PluginFailedException(failed_msgs[0])
elif len(failed_msgs) > 1:
raise PluginFailedException("Multiple plugins raised an exception: " +
str(failed_msgs))
if not plugin_successful and buildstep_phase and not plugin_response:
self.on_plugin_failed("BuildStepPlugin", "No appropriate build step")
raise PluginFailedException("No appropriate build step")
return self.plugins_results | python | def run(self, keep_going=False, buildstep_phase=False):
"""
run all requested plugins
:param keep_going: bool, whether to keep going after unexpected
failure (only used for exit plugins)
:param buildstep_phase: bool, when True remaining plugins will
not be executed after a plugin completes
(only used for build-step plugins)
"""
failed_msgs = []
plugin_successful = False
plugin_response = None
available_plugins = self.available_plugins
for plugin in available_plugins:
plugin_successful = False
logger.debug("running plugin '%s'", plugin.name)
start_time = datetime.datetime.now()
plugin_response = None
skip_response = False
try:
plugin_instance = self.create_instance_from_plugin(plugin.plugin_class,
plugin.conf)
self.save_plugin_timestamp(plugin.plugin_class.key, start_time)
plugin_response = plugin_instance.run()
plugin_successful = True
if buildstep_phase:
assert isinstance(plugin_response, BuildResult)
if plugin_response.is_failed():
logger.error("Build step plugin %s failed: %s",
plugin.plugin_class.key,
plugin_response.fail_reason)
self.on_plugin_failed(plugin.plugin_class.key,
plugin_response.fail_reason)
plugin_successful = False
self.plugins_results[plugin.plugin_class.key] = plugin_response
break
except AutoRebuildCanceledException as ex:
# if auto rebuild is canceled, then just reraise
# NOTE: We need to catch and reraise explicitly, so that the below except clause
# doesn't catch this and make PluginFailedException out of it in the end
# (calling methods would then need to parse exception message to see if
# AutoRebuildCanceledException was raised here)
raise
except InappropriateBuildStepError:
logger.debug('Build step %s is not appropriate', plugin.plugin_class.key)
# don't put None, in results for InappropriateBuildStepError
skip_response = True
if not buildstep_phase:
raise
except Exception as ex:
msg = "plugin '%s' raised an exception: %r" % (plugin.plugin_class.key, ex)
logger.debug(traceback.format_exc())
if not plugin.is_allowed_to_fail:
self.on_plugin_failed(plugin.plugin_class.key, ex)
if plugin.is_allowed_to_fail or keep_going:
logger.warning(msg)
logger.info("error is not fatal, continuing...")
if not plugin.is_allowed_to_fail:
failed_msgs.append(msg)
else:
logger.error(msg)
raise PluginFailedException(msg)
plugin_response = ex
try:
if start_time:
finish_time = datetime.datetime.now()
duration = finish_time - start_time
seconds = duration.total_seconds()
logger.debug("plugin '%s' finished in %ds", plugin.name, seconds)
self.save_plugin_duration(plugin.plugin_class.key, seconds)
except Exception:
logger.exception("failed to save plugin duration")
if not skip_response:
self.plugins_results[plugin.plugin_class.key] = plugin_response
if plugin_successful and buildstep_phase:
logger.debug('stopping further execution of plugins '
'after first successful plugin')
break
if len(failed_msgs) == 1:
raise PluginFailedException(failed_msgs[0])
elif len(failed_msgs) > 1:
raise PluginFailedException("Multiple plugins raised an exception: " +
str(failed_msgs))
if not plugin_successful and buildstep_phase and not plugin_response:
self.on_plugin_failed("BuildStepPlugin", "No appropriate build step")
raise PluginFailedException("No appropriate build step")
return self.plugins_results | [
"def",
"run",
"(",
"self",
",",
"keep_going",
"=",
"False",
",",
"buildstep_phase",
"=",
"False",
")",
":",
"failed_msgs",
"=",
"[",
"]",
"plugin_successful",
"=",
"False",
"plugin_response",
"=",
"None",
"available_plugins",
"=",
"self",
".",
"available_plugi... | run all requested plugins
:param keep_going: bool, whether to keep going after unexpected
failure (only used for exit plugins)
:param buildstep_phase: bool, when True remaining plugins will
not be executed after a plugin completes
(only used for build-step plugins) | [
"run",
"all",
"requested",
"plugins"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugin.py#L233-L331 | train | 28,598 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_sendmail.py | SendMailPlugin._should_send | def _should_send(self, rebuild, success, auto_canceled, manual_canceled):
"""Return True if any state in `self.send_on` meets given conditions, thus meaning
that a notification mail should be sent.
"""
should_send = False
should_send_mapping = {
self.MANUAL_SUCCESS: not rebuild and success,
self.MANUAL_FAIL: not rebuild and not success,
self.MANUAL_CANCELED: not rebuild and manual_canceled,
self.AUTO_SUCCESS: rebuild and success,
self.AUTO_FAIL: rebuild and not success,
self.AUTO_CANCELED: rebuild and auto_canceled
}
for state in self.send_on:
should_send |= should_send_mapping[state]
return should_send | python | def _should_send(self, rebuild, success, auto_canceled, manual_canceled):
"""Return True if any state in `self.send_on` meets given conditions, thus meaning
that a notification mail should be sent.
"""
should_send = False
should_send_mapping = {
self.MANUAL_SUCCESS: not rebuild and success,
self.MANUAL_FAIL: not rebuild and not success,
self.MANUAL_CANCELED: not rebuild and manual_canceled,
self.AUTO_SUCCESS: rebuild and success,
self.AUTO_FAIL: rebuild and not success,
self.AUTO_CANCELED: rebuild and auto_canceled
}
for state in self.send_on:
should_send |= should_send_mapping[state]
return should_send | [
"def",
"_should_send",
"(",
"self",
",",
"rebuild",
",",
"success",
",",
"auto_canceled",
",",
"manual_canceled",
")",
":",
"should_send",
"=",
"False",
"should_send_mapping",
"=",
"{",
"self",
".",
"MANUAL_SUCCESS",
":",
"not",
"rebuild",
"and",
"success",
",... | Return True if any state in `self.send_on` meets given conditions, thus meaning
that a notification mail should be sent. | [
"Return",
"True",
"if",
"any",
"state",
"in",
"self",
".",
"send_on",
"meets",
"given",
"conditions",
"thus",
"meaning",
"that",
"a",
"notification",
"mail",
"should",
"be",
"sent",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_sendmail.py#L203-L220 | train | 28,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.