docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Given data and a jsonschema, let's validate it.
This happens for tasks and chain of trust artifacts.
Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of the json, for exception messages.
Defaults to "... | def validate_json_schema(data, schema, name="task"):
try:
jsonschema.validate(data, schema)
except jsonschema.exceptions.ValidationError as exc:
raise ScriptWorkerTaskException(
"Can't validate {} schema!\n{}".format(name, str(exc)),
exit_code=STATUSES['malformed-pay... | 543,803 |
Validate the task definition.
Args:
context (scriptworker.context.Context): the scriptworker context. It must contain a task and
the config pointing to the schema file
schema_key: the key in `context.config` where the path to the schema file is. Key can contain
dots (e.g.: '... | def validate_task_schema(context, schema_key='schema_file'):
schema_path = context.config
schema_keys = schema_key.split('.')
for key in schema_keys:
schema_path = schema_path[key]
task_schema = load_json_or_yaml(schema_path, is_path=True)
log.debug('Task is validated against this sche... | 543,804 |
Constructor.
Args:
process (Process): task process | def __init__(self, process: Process):
self.process = process
self.stopped_due_to_worker_shutdown = False | 543,811 |
Create an ed25519 private key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PrivateKey: the private key | def ed25519_private_key_from_string(string):
try:
return Ed25519PrivateKey.from_private_bytes(
base64.b64decode(string)
)
except (UnsupportedAlgorithm, Base64Error) as exc:
raise ScriptWorkerEd25519Error("Can't create Ed25519PrivateKey: {}!".format(str(exc))) | 543,813 |
Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key | def ed25519_public_key_from_string(string):
try:
return Ed25519PublicKey.from_public_bytes(
base64.b64decode(string)
)
except (UnsupportedAlgorithm, Base64Error) as exc:
raise ScriptWorkerEd25519Error("Can't create Ed25519PublicKey: {}!".format(str(exc))) | 543,814 |
Create an ed25519 key from the contents of ``path``.
``path`` is a filepath containing a base64-encoded ed25519 key seed.
Args:
fn (callable): the function to call with the contents from ``path``
path (str): the file path to the base64-encoded key seed.
Returns:
obj: the appropria... | def _ed25519_key_from_file(fn, path):
try:
return fn(read_from_file(path, exception=ScriptWorkerEd25519Error))
except ScriptWorkerException as exc:
raise ScriptWorkerEd25519Error("Failed calling {} for {}: {}!".format(fn, path, str(exc))) | 543,815 |
Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str | def ed25519_private_key_to_string(key):
return base64.b64encode(key.private_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PrivateFormat.Raw,
encryption_algorithm=serialization.NoEncryption()
), None).decode('utf-8') | 543,816 |
Convert an ed25519 public key to a base64-encoded string.
Args:
key (Ed25519PublicKey): the key to write to the file.
Returns:
str: the key representation as a str | def ed25519_public_key_to_string(key):
return base64.b64encode(key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw,
), None).decode('utf-8') | 543,817 |
Verify that ``signature`` comes from ``public_key`` and ``contents``.
Args:
public_key (Ed25519PublicKey): the key to verify the signature
contents (bytes): the contents that was signed
signature (bytes): the signature to verify
message (str): the error message to raise.
Raises... | def verify_ed25519_signature(public_key, contents, signature, message):
try:
public_key.verify(signature, contents)
except InvalidSignature as exc:
raise ScriptWorkerEd25519Error(message % {'exc': str(exc)}) | 543,818 |
Verify an ed25519 signature from the command line.
Args:
args (list, optional): the commandline args to parse. If ``None``, use
``sys.argv[1:]``. Defaults to ``None``.
exception (Exception, optional): the exception to raise on failure.
Defaults to ``SystemExit``. | def verify_ed25519_signature_cmdln(args=None, exception=SystemExit):
args = args or sys.argv[1:]
parser = argparse.ArgumentParser(
description=)
parser.add_argument('--pubkey', help='path to a base64-encoded ed25519 pubkey, optional')
parser.add_argument('file_path')
parser.add_argument... | 543,819 |
Return a mapping of exit codes to status strings.
Args:
context (scriptworker.context.Context): the scriptworker context
Returns:
dict: the mapping of exit codes to status strings. | def get_reversed_statuses(context):
_rev = {v: k for k, v in STATUSES.items()}
_rev.update(dict(context.config['reversed_statuses']))
return _rev | 543,820 |
Get the repo for a task.
Args:
task (ChainOfTrust or LinkOfTrust): the trust object to inspect
source_env_prefix (str): The environment variable prefix that is used
to get repository information.
Returns:
str: the source url.
None: if not defined for this task. | def get_repo(task, source_env_prefix):
repo = _extract_from_env_in_payload(task, source_env_prefix + '_HEAD_REPOSITORY')
if repo is not None:
repo = repo.rstrip('/')
return repo | 543,821 |
Get what Github pull request created the graph.
Args:
obj (ChainOfTrust or LinkOfTrust): the trust object to inspect
source_env_prefix (str): The environment variable prefix that is used
to get repository information.
Returns:
int: the pull request number.
None: if ... | def get_pull_request_number(task, source_env_prefix):
pull_request = _extract_from_env_in_payload(task, source_env_prefix + '_PULL_REQUEST_NUMBER')
if pull_request is not None:
pull_request = int(pull_request)
return pull_request | 543,822 |
Given vcs rules and a source_url, return the project.
The project is in the path, but is the repo name.
`releases/mozilla-beta` is the path; `mozilla-beta` is the project.
Args:
valid_vcs_rules (tuple of frozendicts): the valid vcs rules, per
``match_url_regex``.
source_url (st... | def get_and_check_project(valid_vcs_rules, source_url):
project_path = match_url_regex(valid_vcs_rules, source_url, match_url_path_callback)
if project_path is None:
raise ValueError("Unknown repo for source url {}!".format(source_url))
project = project_path.split('/')[-1]
return project | 543,823 |
Given a parent task, return the reason the parent task was spawned.
``.taskcluster.yml`` uses this to know whether to spawn an action,
cron, or decision task definition. ``tasks_for`` must be a valid one defined in the context.
Args:
task (dict): the task definition.
msg_prefix (str): the... | def get_and_check_tasks_for(context, task, msg_prefix=''):
tasks_for = task['extra']['tasks_for']
if tasks_for not in context.config['valid_tasks_for']:
raise ValueError(
'{}Unknown tasks_for: {}'.format(msg_prefix, tasks_for)
)
return tasks_for | 543,824 |
Given a parent task, return the repo scope for the task.
Background in https://bugzilla.mozilla.org/show_bug.cgi?id=1459705#c3
Args:
task (dict): the task definition.
Raises:
ValueError: on too many `repo_scope`s (we allow for 1 or 0).
Returns:
str: the ``repo_scope``
... | def get_repo_scope(task, name):
repo_scopes = []
for scope in task['scopes']:
if REPO_SCOPE_REGEX.match(scope):
repo_scopes.append(scope)
if len(repo_scopes) > 1:
raise ValueError(
"{}: Too many repo_scopes: {}!".format(name, repo_scopes)
)
if repo_sc... | 543,825 |
Determine if a task is a try or a pull-request-like task (restricted privs).
Checks are the ones done in ``is_try`` and ``is_pull_request``
Args:
context (scriptworker.context.Context): the scriptworker context.
task (dict): the task definition to check.
Returns:
bool: True if it'... | async def is_try_or_pull_request(context, task):
if is_github_task(task):
return await is_pull_request(context, task)
else:
return is_try(task, context.config['source_env_prefix']) | 543,828 |
Determine if a task is related to GitHub.
This function currently looks into the ``schedulerId``, ``extra.tasks_for``, and
``metadata.source``.
Args:
task (dict): the task definition to check.
Returns:
bool: True if a piece of data refers to GitHub | def is_github_task(task):
return any((
# XXX Cron tasks don't usually define 'taskcluster-github' as their schedulerId as they
# are scheduled within another Taskcluster task.
task.get('schedulerId') == 'taskcluster-github',
# XXX Same here, cron tasks don't start with github
... | 543,829 |
Given a `claim_task` json dict, prepare the `context` and `work_dir`.
Set `context.claim_task`, and write a `work_dir/current_task_info.json`
Args:
context (scriptworker.context.Context): the scriptworker context.
claim_task (dict): the claim_task dict.
Returns:
dict: the contents... | def prepare_to_run_task(context, claim_task):
current_task_info = {}
context.claim_task = claim_task
current_task_info['taskId'] = get_task_id(claim_task)
current_task_info['runId'] = get_run_id(claim_task)
log.info("Going to run taskId {taskId} runId {runId}!".format(
**current_task_in... | 543,831 |
Run the task, sending stdout+stderr to files.
https://github.com/python/asyncio/blob/master/examples/subprocess_shell.py
Args:
context (scriptworker.context.Context): the scriptworker context.
to_cancellable_process (types.Callable): tracks the process so that it can be stopped if the worker i... | async def run_task(context, to_cancellable_process):
kwargs = { # pragma: no branch
'stdout': PIPE,
'stderr': PIPE,
'stdin': None,
'close_fds': True,
'preexec_fn': lambda: os.setsid(),
}
subprocess = await asyncio.create_subprocess_exec(*context.config['task_sc... | 543,832 |
Mark the task as completed in the queue.
Decide whether to call reportCompleted, reportFailed, or reportException
based on the exit status of the script.
If the task has expired or been cancelled, we'll get a 409 status.
Args:
context (scriptworker.context.Context): the scriptworker context.
... | async def complete_task(context, result):
args = [get_task_id(context.claim_task), get_run_id(context.claim_task)]
reversed_statuses = get_reversed_statuses(context)
try:
if result == 0:
log.info("Reporting task complete...")
response = await context.temp_queue.reportCom... | 543,834 |
Find and claim the next pending task in the queue, if any.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: a dict containing a list of the task definitions of the tasks claimed. | async def claim_work(context):
log.debug("Calling claimWork...")
payload = {
'workerGroup': context.config['worker_group'],
'workerId': context.config['worker_id'],
# Hardcode one task at a time. Make this a pref if we allow for
# parallel tasks in multiple `work_dir`s.
... | 543,835 |
Raise a CoTError if errors.
Helper function because I had this code block everywhere.
Args:
errors (list): the error errors
level (int, optional): the log level to use. Defaults to logging.CRITICAL
Raises:
CoTError: if errors is non-empty | def raise_on_errors(errors, level=logging.CRITICAL):
if errors:
log.log(level, "\n".join(errors))
raise CoTError("\n".join(errors)) | 543,836 |
Guess the task type of the task.
Args:
name (str): the name of the task.
Returns:
str: the task_type.
Raises:
CoTError: on invalid task_type. | def guess_task_type(name, task_defn):
parts = name.split(':')
task_type = parts[-1]
if task_type == 'parent':
if is_action(task_defn):
task_type = 'action'
else:
task_type = 'decision'
if task_type not in get_valid_task_types():
raise CoTError(
... | 543,838 |
Given a task, make sure the task was not defined as interactive.
* ``task.payload.features.interactive`` must be absent or False.
* ``task.payload.env.TASKCLUSTER_INTERACTIVE`` must be absent or False.
Args:
link (LinkOfTrust): the task link we're checking.
Returns:
list: the list of ... | def check_interactive_docker_worker(link):
errors = []
log.info("Checking for {} {} interactive docker-worker".format(link.name, link.task_id))
try:
if link.task['payload']['features'].get('interactive'):
errors.append("{} is interactive: task.payload.features.interactive!".format(l... | 543,840 |
Verify that built docker shas match the artifact.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking.
Raises:
CoTError: on failure. | def verify_docker_image_sha(chain, link):
cot = link.cot
task = link.task
errors = []
if isinstance(task['payload'].get('image'), dict):
# Using pre-built image from docker-image task
docker_image_task_id = task['extra']['chainOfTrust']['inputs']['docker-image']
log.debug("... | 543,841 |
Find the taskIds of the chain of trust dependencies of a given task.
Args:
task (dict): the task definition to inspect.
task_name (str): the name of the task, for logging and naming children.
task_id (str): the taskId of the task.
Returns:
list: tuples associating dependent tas... | def find_sorted_task_dependencies(task, task_name, task_id):
log.info("find_sorted_task_dependencies {} {}".format(task_name, task_id))
cot_input_dependencies = [
_craft_dependency_tuple(task_name, task_type, task_id)
for task_type, task_id in task['extra'].get('chainOfTrust', {}).get('inp... | 543,842 |
Recursively build the task dependencies of a task.
Args:
chain (ChainOfTrust): the chain of trust to add to.
task (dict): the task definition to operate on.
name (str): the name of the task to operate on.
my_task_id (str): the taskId of the task to operate on.
Raises:
C... | async def build_task_dependencies(chain, task, name, my_task_id):
log.info("build_task_dependencies {} {}".format(name, my_task_id))
if name.count(':') > chain.context.config['max_chain_length']:
raise CoTError("Too deep recursion!\n{}".format(name))
sorted_dependencies = find_sorted_task_depen... | 543,843 |
Download the signed chain of trust artifacts.
Args:
chain (ChainOfTrust): the chain of trust to add to.
Raises:
BaseDownloadError: on failure. | async def download_cot(chain):
artifact_tasks = []
# only deal with chain.links, which are previously finished tasks with
# signed chain of trust artifacts. ``chain.task`` is the current running
# task, and will not have a signed chain of trust artifact yet.
for link in chain.links:
ta... | 543,844 |
Download an artifact and verify its SHA against the chain of trust.
Args:
chain (ChainOfTrust): the chain of trust object
task_id (str): the task ID to download from
path (str): the relative path to the artifact to download
Returns:
str: the full path of the downloaded artifact... | async def download_cot_artifact(chain, task_id, path):
link = chain.get_link(task_id)
log.debug("Verifying {} is in {} cot artifacts...".format(path, task_id))
if not link.cot:
log.warning('Chain of Trust for "{}" in {} does not exist. See above log for more details. \
Skipping download of this... | 543,845 |
Call ``download_cot_artifact`` in parallel for each "upstreamArtifacts".
Optional artifacts are allowed to not be downloaded.
Args:
chain (ChainOfTrust): the chain of trust object
Returns:
list: list of full paths to downloaded artifacts. Failed optional artifacts
aren't returned
... | async def download_cot_artifacts(chain):
upstream_artifacts = chain.task['payload'].get('upstreamArtifacts', [])
all_artifacts_per_task_id = get_all_artifacts_per_task_id(chain, upstream_artifacts)
mandatory_artifact_tasks = []
optional_artifact_tasks = []
for task_id, paths in all_artifacts_p... | 543,846 |
Tells whether an artifact is flagged as optional or not.
Args:
chain (ChainOfTrust): the chain of trust object
task_id (str): the id of the aforementioned task
Returns:
bool: True if artifact is optional | def is_artifact_optional(chain, task_id, path):
upstream_artifacts = chain.task['payload'].get('upstreamArtifacts', [])
optional_artifacts_per_task_id = get_optional_artifacts_per_task_id(upstream_artifacts)
return path in optional_artifacts_per_task_id.get(task_id, []) | 543,847 |
Return every artifact to download, including the Chain Of Trust Artifacts.
Args:
chain (ChainOfTrust): the chain of trust object
upstream_artifacts: the list of upstream artifact definitions
Returns:
dict: sorted list of paths to downloaded artifacts ordered by taskId | def get_all_artifacts_per_task_id(chain, upstream_artifacts):
all_artifacts_per_task_id = {}
for link in chain.links:
# Download task-graph.json for decision+action task cot verification
if link.task_type in PARENT_TASK_TYPES:
add_enumerable_item_to_dict(
dict_=a... | 543,848 |
Verify the ed25519 signatures of the chain of trust artifacts populated in ``download_cot``.
Populate each link.cot with the chain of trust json body.
Args:
chain (ChainOfTrust): the chain of trust to add to.
Raises:
(CoTError, ScriptWorkerEd25519Error): on signature verification failure. | def verify_link_ed25519_cot_signature(chain, link, unsigned_path, signature_path):
if chain.context.config['verify_cot_signature']:
log.debug("Verifying the {} {} {} ed25519 chain of trust signature".format(
link.name, link.task_id, link.worker_impl
))
signature = read_from_... | 543,849 |
Verify the signatures of the chain of trust artifacts populated in ``download_cot``.
Populate each link.cot with the chain of trust json body.
Args:
chain (ChainOfTrust): the chain of trust to add to.
Raises:
CoTError: on failure. | def verify_cot_signatures(chain):
for link in chain.links:
unsigned_path = link.get_artifact_full_path('public/chain-of-trust.json')
ed25519_signature_path = link.get_artifact_full_path('public/chain-of-trust.json.sig')
verify_link_ed25519_cot_signature(chain, link, unsigned_path, ed255... | 543,850 |
Compare the runtime task definition against the decision task graph.
Args:
chain (ChainOfTrust): the chain we're operating on.
decision_link (LinkOfTrust): the decision task link
task_link (LinkOfTrust): the task link we're testing
Raises:
CoTError: on failure. | def verify_link_in_task_graph(chain, decision_link, task_link):
log.info("Verifying the {} {} task definition is part of the {} {} task graph...".format(
task_link.name, task_link.task_id, decision_link.name, decision_link.task_id
))
if task_link.task_id in decision_link.task_graph:
gra... | 543,853 |
Get pushlog info for a decision LinkOfTrust.
Args:
decision_link (LinkOfTrust): the decision link to get pushlog info about.
Returns:
dict: pushlog info. | async def get_pushlog_info(decision_link):
source_env_prefix = decision_link.context.config['source_env_prefix']
repo = get_repo(decision_link.task, source_env_prefix)
rev = get_revision(decision_link.task, source_env_prefix)
context = decision_link.context
pushlog_url = context.config['pushlog... | 543,854 |
Get the in-tree json-e template for a given link.
By convention, this template is SOURCE_REPO/.taskcluster.yml.
Args:
link (LinkOfTrust): the parent link to get the source url from.
Raises:
CoTError: on non-yaml `source_url`
KeyError: on non-well-formed source template
Return... | async def get_in_tree_template(link):
context = link.context
source_url = get_source_url(link)
if not source_url.endswith(('.yml', '.yaml')):
raise CoTError("{} source url {} doesn't end in .yml or .yaml!".format(
link.name, source_url
))
tmpl = await load_json_or_yaml_f... | 543,865 |
Get the appropriate json-e context and template for an action task.
Args:
chain (ChainOfTrust): the chain of trust.
parent_link (LinkOfTrust): the parent link to test.
decision_link (LinkOfTrust): the parent link's decision task link.
tasks_for (str): the reason the parent link was ... | async def get_action_context_and_template(chain, parent_link, decision_link):
actions_path = decision_link.get_artifact_full_path('public/actions.json')
all_actions = load_json_or_yaml(actions_path, is_path=True)['actions']
action_name = get_action_callback_name(parent_link.task)
action_defn = _get... | 543,869 |
Get the appropriate json-e context and template for any parent task.
Args:
chain (ChainOfTrust): the chain of trust.
parent_link (LinkOfTrust): the parent link to test.
decision_link (LinkOfTrust): the parent link's decision task link.
tasks_for (str): the reason the parent link was... | async def get_jsone_context_and_template(chain, parent_link, decision_link, tasks_for):
if tasks_for == 'action':
jsone_context, tmpl = await get_action_context_and_template(
chain, parent_link, decision_link
)
else:
tmpl = await get_in_tree_template(decision_link)
... | 543,870 |
Compare the json-e rebuilt task definition vs the runtime definition.
Args:
parent_link (LinkOfTrust): the parent link to test.
rebuilt_definitions (dict): the rebuilt task definitions.
Raises:
CoTError: on failure. | def compare_jsone_task_definition(parent_link, rebuilt_definitions):
diffs = []
for compare_definition in rebuilt_definitions['tasks']:
# Rebuilt decision tasks have an extra `taskId`; remove
if 'taskId' in compare_definition:
del(compare_definition['taskId'])
# remove k... | 543,873 |
Verify the docker image Link.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking. | async def verify_docker_image_task(chain, link):
errors = []
# workerType
worker_type = get_worker_type(link.task)
if worker_type not in chain.context.config['valid_docker_image_worker_types']:
errors.append("{} is not a valid docker-image workerType!".format(worker_type))
raise_on_erro... | 543,875 |
Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of links.
Raises:
CoTError: on failure. | def check_num_tasks(chain, task_count):
errors = []
# hardcode for now. If we need a different set of constraints, either
# go by cot_product settings or by task_count['docker-image'] + 1
min_decision_tasks = 1
if task_count['decision'] < min_decision_tasks:
errors.append("{} decision ... | 543,876 |
Verify the task type (e.g. decision, build) of each link in the chain.
Args:
chain (ChainOfTrust): the chain we're operating on
Returns:
dict: mapping task type to the number of links. | async def verify_task_types(chain):
valid_task_types = get_valid_task_types()
task_count = {}
for obj in chain.get_all_links_in_chain():
task_type = obj.task_type
log.info("Verifying {} {} as a {} task...".format(obj.name, obj.task_id, task_type))
task_count.setdefault(task_type... | 543,877 |
Docker-worker specific checks.
Args:
chain (ChainOfTrust): the chain we're operating on
link (ChainOfTrust or LinkOfTrust): the trust object for the signing task.
Raises:
CoTError: on failure. | async def verify_docker_worker_task(chain, link):
if chain != link:
# These two checks will die on `link.cot` if `link` is a ChainOfTrust
# object (e.g., the task we're running `verify_cot` against is a
# docker-worker task). So only run these tests if they are not the chain
# o... | 543,878 |
Verify the signing trust object.
Currently the only check is to make sure it was run on a scriptworker.
Args:
chain (ChainOfTrust): the chain we're operating on
obj (ChainOfTrust or LinkOfTrust): the trust object for the signing task. | async def verify_scriptworker_task(chain, obj):
errors = []
if obj.worker_impl != "scriptworker":
errors.append("{} {} must be run from scriptworker!".format(obj.name, obj.task_id))
raise_on_errors(errors) | 543,879 |
Verify the task type (e.g. decision, build) of each link in the chain.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure | async def verify_worker_impls(chain):
valid_worker_impls = get_valid_worker_impls()
for obj in chain.get_all_links_in_chain():
worker_impl = obj.worker_impl
log.info("Verifying {} {} as a {} task...".format(obj.name, obj.task_id, worker_impl))
# Run tests synchronously for now. We ... | 543,880 |
Verify ``url`` is a part of ``repo``.
We were using ``startswith()`` for a while, which isn't a good comparison.
This function allows us to ``urlparse`` and compare host and path.
Args:
repo (str): the repo url
url (str): the url to verify is part of the repo
Returns:
bool: ``... | def verify_repo_matches_url(repo, url):
repo_parts = urlparse(repo)
url_parts = urlparse(url)
errors = []
repo_path_parts = repo_parts.path.split('/')
url_path_parts = url_parts.path.split('/')
if repo_parts.hostname != url_parts.hostname:
errors.append("verify_repo_matches_url: Hos... | 543,881 |
Get the source url for a Trust object.
Args:
obj (ChainOfTrust or LinkOfTrust): the trust object to inspect
Raises:
CoTError: if repo and source are defined and don't match
Returns:
str: the source url. | def get_source_url(obj):
source_env_prefix = obj.context.config['source_env_prefix']
task = obj.task
log.debug("Getting source url for {} {}...".format(obj.name, obj.task_id))
repo = get_repo(obj.task, source_env_prefix=source_env_prefix)
source = task['metadata']['source']
if repo and not ... | 543,882 |
Trace the chain back to the tree.
task.metadata.source: "https://hg.mozilla.org/projects/date//file/a80373508881bfbff67a2a49297c328ff8052572/taskcluster/ci/build"
task.payload.env.GECKO_HEAD_REPOSITORY "https://hg.mozilla.org/projects/date/"
Args:
chain (ChainOfTrust): the chain we're operating on... | async def trace_back_to_tree(chain):
errors = []
repos = {}
restricted_privs = None
rules = {}
for my_key, config_key in {
'scopes': 'cot_restricted_scopes',
'trees': 'cot_restricted_trees'
}.items():
rules[my_key] = chain.context.config[config_key]
# a repo_pat... | 543,883 |
Build and verify the chain of trust.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure | async def verify_chain_of_trust(chain):
log_path = os.path.join(chain.context.config["task_log_dir"], "chain_of_trust.log")
scriptworker_log = logging.getLogger('scriptworker')
with contextual_log_handler(
chain.context, path=log_path, log_obj=scriptworker_log,
formatter=AuditLogFormatt... | 543,884 |
Test the chain of trust from the commandline, for debugging purposes.
Args:
args (list, optional): the commandline args to parse. If None, use
``sys.argv[1:]`` . Defaults to None.
event_loop (asyncio.events.AbstractEventLoop): the event loop to use.
If ``None``, use ``asy... | def verify_cot_cmdln(args=None, event_loop=None):
args = args or sys.argv[1:]
parser = argparse.ArgumentParser(
description=)
parser.add_argument('task_id', help='the task id to test')
parser.add_argument('--task-type', help='the task type to test',
choices=sorted(ge... | 543,886 |
Initialize ChainOfTrust.
Args:
context (scriptworker.context.Context): the scriptworker context
name (str): the name of the task (e.g., signing)
task_id (str, optional): the task_id of the task. If None, use
``get_task_id(context.claim_task)``. Defaults to ... | def __init__(self, context, name, task_id=None):
self.name = name
self.context = context
self.task_id = task_id or get_task_id(context.claim_task)
self.task = context.task
self.task_type = guess_task_type(name, self.task)
self.worker_impl = guess_worker_impl(self... | 543,887 |
Get a ``LinkOfTrust`` by task id.
Args:
task_id (str): the task id to find.
Returns:
LinkOfTrust: the link matching the task id.
Raises:
CoTError: if no ``LinkOfTrust`` matches. | def get_link(self, task_id):
links = [x for x in self.links if x.task_id == task_id]
if len(links) != 1:
raise CoTError("No single Link matches task_id {}!\n{}".format(task_id, self.dependent_task_ids()))
return links[0] | 543,889 |
Initialize ChainOfTrust.
Args:
context (scriptworker.context.Context): the scriptworker context
name (str): the name of the task (e.g., signing)
task_id (str): the task_id of the task | def __init__(self, context, name, task_id):
self.name = name
self.context = context
self.task_id = task_id | 543,891 |
Translate a version tuple into a string.
Specify the __version__ as a tuple for more precise comparisons, and
translate it to __version_string__ for when that's needed.
This function exists primarily for easier unit testing.
Args:
version (Tuple[int, int, int, str]): three ints and an optional ... | def get_version_string(version):
version_len = len(version)
if version_len == 3:
version_string = '%d.%d.%d' % version
elif version_len == 4:
version_string = '%d.%d.%d-%s' % version
else:
raise Exception(
'Version tuple is non-semver-compliant {} length!'.format... | 543,896 |
Write the version info to ../version.json, for setup.py.
Args:
name (Optional[str]): this is for the ``write_version(name=__name__)``
below. That's one way to both follow the
``if __name__ == '__main__':`` convention but also allow for full
coverage without ignoring parts of the file... | def write_version(name=None, path=None):
# Written like this for coverage purposes.
# http://stackoverflow.com/questions/5850268/how-to-test-or-mock-if-name-main-contents/27084447#27084447
if name in (None, '__main__'):
path = path or os.path.join(os.path.dirname(os.path.dirname(os.path.abspath... | 543,897 |
Recursively convert `value`'s tuple values into lists, and frozendicts into dicts.
Args:
values (frozendict/tuple): the frozendict/tuple.
Returns:
values (dict/list): the unfrozen copy. | def get_unfrozen_copy(values):
if isinstance(values, (frozendict, dict)):
return {key: get_unfrozen_copy(value) for key, value in values.items()}
elif isinstance(values, (list, tuple)):
return [get_unfrozen_copy(value) for value in values]
# Nothing to unfreeze.
return values | 543,898 |
Get credentials from CREDS_FILES or the environment.
This looks at the CREDS_FILES in order, and falls back to the environment.
Args:
key (str, optional): each CREDS_FILE is a json dict. This key's value
contains the credentials. Defaults to 'credentials'.
Returns:
dict: the... | def read_worker_creds(key="credentials"):
for path in CREDS_FILES:
if not os.path.exists(path):
continue
contents = load_json_or_yaml(path, is_path=True, exception=None)
if contents.get(key):
return contents[key]
else:
if key == "credentials" and os.e... | 543,899 |
Validate the config against DEFAULT_CONFIG.
Any unknown keys or wrong types will add error messages.
Args:
config (dict): the running config.
path (str): the path to the config file, used in error messages.
Returns:
list: the error messages found when validating the config. | def check_config(config, path):
messages = []
config_copy = get_frozen_copy(config)
missing_keys = set(DEFAULT_CONFIG.keys()) - set(config_copy.keys())
if missing_keys:
messages.append("Missing config keys {}!".format(missing_keys))
for key, value in config_copy.items():
if ke... | 543,900 |
Apply config values that are keyed by `cot_product`.
This modifies the passed in configuration.
Args:
config dict: the config to apply cot_product keying too
Returns: dict | def apply_product_config(config):
cot_product = config['cot_product']
for key in config:
if isinstance(config[key], Mapping) and 'by-cot-product' in config[key]:
try:
config[key] = config[key]['by-cot-product'][cot_product]
except KeyError:
r... | 543,901 |
Create a config from DEFAULT_CONFIG, arguments, and config file.
Then validate it and freeze it.
Args:
config_path (str, optional): the path to the config file. Defaults to
"scriptworker.yaml"
Returns:
tuple: (config frozendict, credentials dict)
Raises:
SystemEx... | def create_config(config_path="scriptworker.yaml"):
if not os.path.exists(config_path):
print("{} doesn't exist! Exiting...".format(config_path), file=sys.stderr)
sys.exit(1)
with open(config_path, "r", encoding="utf-8") as fh:
secrets = safe_load(fh)
config = dict(deepcopy(DEFA... | 543,902 |
Create a Context object from args.
Args:
args (list): the commandline args. Generally sys.argv
Returns:
tuple: ``scriptworker.context.Context`` with populated config, and
credentials frozendict | def get_context_from_cmdln(args, desc="Run scriptworker"):
context = Context()
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
"config_path", type=str, nargs="?", default="scriptworker.yaml",
help="the path to the config file"
)
parsed_args = parser.parse... | 543,903 |
Generate the artifact relative paths and shas for the chain of trust.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: a dictionary of {"path/to/artifact": {"hash_alg": "..."}, ...} | def get_cot_artifacts(context):
artifacts = {}
filepaths = filepaths_in_dir(context.config['artifact_dir'])
hash_alg = context.config['chain_of_trust_hash_algorithm']
for filepath in sorted(filepaths):
path = os.path.join(context.config['artifact_dir'], filepath)
sha = get_hash(path... | 543,904 |
Generate the chain of trust dictionary.
This is the unsigned and unformatted chain of trust artifact contents.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: the unsignd and unformatted chain of trust artifact contents.
Raises:
ScriptWo... | def generate_cot_body(context):
try:
cot = {
'artifacts': get_cot_artifacts(context),
'chainOfTrustVersion': 1,
'runId': context.claim_task['runId'],
'task': context.task,
'taskId': context.claim_task['status']['taskId'],
'workerGr... | 543,905 |
Format and sign the cot body, and write to disk.
Args:
context (scriptworker.context.Context): the scriptworker context.
parent_path (str, optional): The directory to write the chain of trust
artifacts to. If None, this is ``artifact_dir/public/``.
Defaults to None.
Re... | def generate_cot(context, parent_path=None):
body = generate_cot_body(context)
schema = load_json_or_yaml(
context.config['cot_schema_path'], is_path=True,
exception=ScriptWorkerException,
message="Can't read schema file {}: %(exc)s".format(context.config['cot_schema_path'])
)
... | 543,906 |
Given an URL, return the repo name and who owns it.
Args:
url (str): The URL to the GitHub repository
Raises:
ValueError: on url that aren't from github
Returns:
str, str: the owner of the repository, the repository name | def extract_github_repo_owner_and_name(url):
_check_github_url_is_supported(url)
parts = get_parts_of_url_path(url)
repo_owner = parts[0]
repo_name = parts[1]
return repo_owner, _strip_trailing_dot_git(repo_name) | 543,907 |
Given an URL, return the repo name and who owns it.
Args:
url (str): The URL to the GitHub repository
Raises:
ValueError: on url that aren't from github or when the revision cannot be extracted
Returns:
str, str: the owner of the repository, the repository name | def extract_github_repo_and_revision_from_source_url(url):
_check_github_url_is_supported(url)
parts = get_parts_of_url_path(url)
repo_name = parts[1]
try:
revision = parts[3]
except IndexError:
raise ValueError('Revision cannot be extracted from url: {}'.format(url))
end_... | 543,908 |
Given a repo_owner, check if it matches the one configured to be the official one.
Args:
context (scriptworker.context.Context): the scriptworker context.
repo_owner (str): the repo_owner to verify
Raises:
scriptworker.exceptions.ConfigError: when no official owner was defined
Ret... | def is_github_repo_owner_the_official_one(context, repo_owner):
official_repo_owner = context.config['official_github_repos_owner']
if not official_repo_owner:
raise ConfigError(
'This worker does not have a defined owner for official GitHub repositories. '
'Given "official_... | 543,909 |
Build the GitHub API URL which points to the definition of the repository.
Args:
owner (str): the owner's GitHub username
repo_name (str): the name of the repository
token (str): the GitHub API token
Returns:
dict: a representation of the repo definition | def __init__(self, owner, repo_name, token=''):
self._github_repository = GitHub(token=token).repository(owner, repo_name) | 543,910 |
Fetch the commit hash that was tagged with ``tag_name``.
Args:
tag_name (str): the name of the tag
Returns:
str: the commit hash linked by the tag | def get_tag_hash(self, tag_name):
tag_object = get_single_item_from_sequence(
sequence=self._github_repository.tags(),
condition=lambda tag: tag.name == tag_name,
no_item_error_message='No tag "{}" exist'.format(tag_name),
too_many_item_error_message='Too... | 543,911 |
Tell if a commit was landed on the repository or if it just comes from a pull request.
Args:
context (scriptworker.context.Context): the scriptworker context.
revision (str): the commit hash or the tag name.
Returns:
bool: True if the commit is present in one of the... | async def has_commit_landed_on_repository(self, context, revision):
# Revision may be a tag name. `branch_commits` doesn't work on tags
if not _is_git_full_hash(revision):
revision = self.get_tag_hash(tag_name=revision)
repo = self._github_repository.html_url
url =... | 543,912 |
Log from a subprocess PIPE.
Args:
pipe (filehandle): subprocess process STDOUT or STDERR
filehandles (list of filehandles, optional): the filehandle(s) to write
to. If empty, don't write to a separate file. Defaults to ().
level (int, optional): the level to log to. Defaults ... | async def pipe_to_log(pipe, filehandles=(), level=logging.INFO):
while True:
line = await pipe.readline()
if line:
line = to_unicode(line)
log.log(level, line.rstrip())
for filehandle in filehandles:
print(line, file=filehandle, end="")
... | 543,914 |
Open the log and error filehandles.
Args:
context (scriptworker.context.Context): the scriptworker context.
Yields:
log filehandle | def get_log_filehandle(context):
log_file_name = get_log_filename(context)
makedirs(context.config['task_log_dir'])
with open(log_file_name, "w", encoding="utf-8") as filehandle:
yield filehandle | 543,915 |
Compress artifacts with GZip if they're known to be supported.
This replaces the artifact given by a gzip binary.
Args:
artifact_path (str): the path to compress
Returns:
content_type, content_encoding (tuple): Type and encoding of the file. Encoding equals 'gzip' if compressed. | def compress_artifact_if_supported(artifact_path):
content_type, encoding = guess_content_type_and_encoding(artifact_path)
log.debug('"{}" is encoded with "{}" and has mime/type "{}"'.format(artifact_path, encoding, content_type))
if encoding is None and content_type in _GZIP_SUPPORTED_CONTENT_TYPE:
... | 543,918 |
Guess the content type of a path, using ``mimetypes``.
Falls back to "application/binary" if no content type is found.
Args:
path (str): the path to guess the mimetype of
Returns:
str: the content type of the file | def guess_content_type_and_encoding(path):
for ext, content_type in _EXTENSION_TO_MIME_TYPE.items():
if path.endswith(ext):
return content_type
content_type, encoding = mimetypes.guess_type(path)
content_type = content_type or "application/binary"
return content_type, encoding | 543,919 |
Retry create_artifact() calls.
Args:
*args: the args to pass on to create_artifact
**kwargs: the args to pass on to create_artifact | async def retry_create_artifact(*args, **kwargs):
await retry_async(
create_artifact,
retry_exceptions=(
ScriptWorkerRetryException,
aiohttp.ClientError
),
args=args,
kwargs=kwargs
) | 543,920 |
Get a TaskCluster artifact url.
Args:
context (scriptworker.context.Context): the scriptworker context
task_id (str): the task id of the task that published the artifact
path (str): the relative path of the artifact
Returns:
str: the artifact url
Raises:
TaskCluste... | def get_artifact_url(context, task_id, path):
if path.startswith("public/"):
url = context.queue.buildUrl('getLatestArtifact', task_id, path)
else:
url = context.queue.buildSignedUrl(
'getLatestArtifact', task_id, path,
# XXX Can set expiration kwarg in (int) seconds... | 543,923 |
List the downloaded upstream artifacts.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict, dict: lists of the paths to upstream artifacts, sorted by task_id.
First dict represents the existing upstream artifacts. The second one
maps t... | def get_upstream_artifacts_full_paths_per_task_id(context):
upstream_artifacts = context.task['payload']['upstreamArtifacts']
task_ids_and_relative_paths = [
(artifact_definition['taskId'], artifact_definition['paths'])
for artifact_definition in upstream_artifacts
]
optional_artif... | 543,925 |
Return the full path where an upstream artifact is located on disk.
Args:
context (scriptworker.context.Context): the scriptworker context.
task_id (str): the task id of the task that published the artifact
path (str): the relative path of the artifact
Returns:
str: absolute pa... | def get_and_check_single_upstream_artifact_full_path(context, task_id, path):
abs_path = get_single_upstream_artifact_full_path(context, task_id, path)
if not os.path.exists(abs_path):
raise ScriptWorkerTaskException(
'upstream artifact with path: {}, does not exist'.format(abs_path)
... | 543,926 |
Return every optional artifact defined in ``upstream_artifacts``, ordered by taskId.
Args:
upstream_artifacts: the list of upstream artifact definitions
Returns:
dict: list of paths to downloaded artifacts ordered by taskId | def get_optional_artifacts_per_task_id(upstream_artifacts):
# A given taskId might be defined many times in upstreamArtifacts. Thus, we can't
# use a dict comprehension
optional_artifacts_per_task_id = {}
for artifact_definition in upstream_artifacts:
if artifact_definition.get('optional',... | 543,928 |
Convert a LDAP-style datetime to a Python aware object.
See https://tools.ietf.org/html/rfc4517#section-3.3.13 for details.
Args:
value (str): the datetime to parse | def datetime_from_ldap(value):
if not value:
return None
match = LDAP_DATETIME_RE.match(value)
if not match:
return None
groups = match.groupdict()
if groups['microsecond']:
groups['microsecond'] = groups['microsecond'].ljust(6, '0')[:6]
tzinfo = groups.pop('tzinfo')... | 544,084 |
Sets the custom properties for given row(s).
Can accept a single row or an iterable of rows.
Sets the given custom properties for all specified rows.
Args:
rows: The row, or rows, to set the custom properties for.
custom_properties: A string to string dictionary of custom properties to
s... | def SetRowsCustomProperties(self, rows, custom_properties):
if not hasattr(rows, "__iter__"):
rows = [rows]
for row in rows:
self.__data[row] = (self.__data[row][0], custom_properties) | 544,375 |
Loads new rows to the data table, clearing existing rows.
May also set the custom_properties for the added rows. The given custom
properties dictionary specifies the dictionary that will be used for *all*
given rows.
Args:
data: The rows that the table will contain.
custom_properties: A di... | def LoadData(self, data, custom_properties=None):
self.__data = []
self.AppendData(data, custom_properties) | 544,376 |
Returns a file in tab-separated-format readable by MS Excel.
Returns a file in UTF-16 little endian encoding, with tabs separating the
values.
Args:
columns_order: Delegated to ToCsv.
order_by: Delegated to ToCsv.
Returns:
A tab-separated little endian UTF16 file representing the ta... | def ToTsvExcel(self, columns_order=None, order_by=()):
csv_result = self.ToCsv(columns_order, order_by, separator="\t")
if not isinstance(csv_result, six.text_type):
csv_result = csv_result.decode("utf-8")
return csv_result.encode("UTF-16LE") | 544,383 |
Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column IDs must be present.
order_by: Optional. Specifies the name of ... | def _ToJSonObj(self, columns_order=None, order_by=()):
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
# Creating the column JSON objects
col_objs = []
for col_id in columns_order:
col_obj... | 544,384 |
Fold a string within a maximum width.
Parameters:
input_string:
The string of data to go into the cell
max_width:
Maximum width of cell. Data is folded into multiple lines to
fit into this width.
Return:
String representing the folded string | def fold_string(input_string, max_width):
new_string = input_string
if isinstance(input_string, six.string_types):
if max_width < len(input_string):
# use textwrap to fold the string
new_string = textwrap.fill(input_string, max_width)
return new_string | 545,262 |
Determine CIM_ReferenceProfile Antecedent/Dependent direction from
server data and a list of known autonomous and/or component profiles
using the algorithm defined for the _server. This is the prototype for
the code that was reimplemented in pywbem.
Parameters:
org_vm
possible_autono... | def determine_reference_direction_fast(nickname, server,
possible_autonomous_profiles=None,
possible_component_profiles=None):
def _determine_type(profilepaths, v0_dict, v1_dict, autonomous):
if not profilepaths:
... | 545,278 |
Print information on a profile defined by profile_instance.
Parameters:
org_vm: The value mapping for CIMRegisterdProfile and
RegisteredOrganization so that the value and not value mapping
is displayed.
profile_instance: instance of a profile to be printed | def print_profile_info(org_vm, profile_instance):
org = org_vm.tovalues(profile_instance['RegisteredOrganization'])
name = profile_instance['RegisteredName']
vers = profile_instance['RegisteredVersion']
print(" %s %s Profile %s" % (org, name, vers)) | 545,297 |
Get the :class:`~pywbem.OperationStatistic` object for an operation
name or create a new object if an object for that name does not exist.
Parameters:
name (string):
Name of the operation.
Returns:
:class:`~pywbem.OperationStatistic`: The operation statistic f... | def get_op_statistic(self, name):
if not self.enabled:
return self._disabled_stats
if name not in self._op_stats:
self._op_stats[name] = OperationStatistic(self, name)
return self._op_stats[name] | 545,342 |
Generate a Python Provider template.
Parameters:
cc - A CIMClass to generate code for.
Returns a two-tuple containing the Python provider code stubs, and
the provider registration MOF. | def codegen(cc):
import inspect
def format_desc(obj, indent):
linelen = 75 - indent
if isinstance(obj, six.string_types):
raw = obj
else:
try:
raw = obj.qualifiers['description'].value
except KeyError:
return ''
... | 545,430 |
Validate whether a CIM namespace exists in the mock repository.
Parameters:
namespace (:term:`string`):
The name of the CIM namespace in the mock repository. Must not be
`None`.
Raises:
:exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does
... | def _validate_namespace(self, namespace):
if namespace not in self.namespaces:
raise CIMError(
CIM_ERR_INVALID_NAMESPACE,
_format("Namespace does not exist in mock repository: {0!A}",
namespace)) | 545,539 |
Find an instance in the instance repo by iname and return the
index of that instance.
Parameters:
iname: CIMInstancename to find
instance_repo: the instance repo to search
Return (None, None if not found. Otherwise return tuple of
index, instance
R... | def _find_instance(iname, instance_repo):
rtn_inst = None
rtn_index = None
for index, inst in enumerate(instance_repo):
if iname == inst.path:
if rtn_inst is not None:
# TODO:ks Future Remove dup test since we should be
... | 545,548 |
Add a callback function to the listener.
The callback function will be called for each indication this listener
receives from any WBEM server.
If the callback function is already known to the listener, it will not
be added.
Parameters:
callback (:func:`~pywbem.callb... | def add_callback(self, callback):
if callback not in self._callbacks:
self._callbacks.append(callback) | 545,607 |
Return the value of a particular property of this CIM instance,
or a default value.
*New in pywbem 0.8.*
Parameters:
key (:term:`string`):
Name of the property (in any lexical case).
default (:term:`CIM data type`):
Default value that is returned i... | def get(self, key, default=None):
prop = self.properties.get(key, None)
return default if prop is None else prop.value | 545,651 |
Return a MOF string with the declaration of this CIM method for use in
a CIM class declaration.
The order of parameters and qualifiers is preserved.
Parameters:
indent (:term:`integer`): Number of spaces to indent each line of
the returned string, counted in the line wit... | def tomof(self, indent=0, maxline=MAX_MOF_LINE):
mof = []
if self.qualifiers:
mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT,
maxline))
mof.append(_indent_str(indent))
# return_type is ensured not to be N... | 545,685 |
Perform an extrinsic CIM-XML method call.
Parameters:
methodname (string): CIM method name.
objectname (string or CIMInstanceName or CIMClassName):
Target object. Strings are interpreted as class names.
Params: CIM method input parameters, for details see InvokeMeth... | def _methodcall(self, methodname, objectname, Params=None, **params):
if isinstance(objectname, (CIMInstanceName, CIMClassName)):
localobject = objectname.copy()
if localobject.namespace is None:
localobject.namespace = self.default_namespace
localob... | 545,739 |
Internal method to get the server object, given a server_id.
Parameters:
server_id (:term:`string`):
The server ID of the WBEM server, returned by
:meth:`~pywbem.WBEMSubscriptionManager.add_server`.
Returns:
server (:class:`~pywbem.WBEMServer`):
... | def _get_server(self, server_id):
if server_id not in self._servers:
raise ValueError(
_format("WBEM server {0!A} not known by subscription manager",
server_id))
return self._servers[server_id] | 545,982 |
Initialize the connection.
Parameters:
conn (BaseRepositoryConnection):
The underlying repository connection.
`None` means that there is no underlying repository and all
operations performed through this object will fail. | def __init__(self, faked_conn_object):
super(_MockMOFWBEMConnection, self).__init__(conn=faked_conn_object)
# Reassign the variables the represent the repository to the
# faked_conn_object so that we have a common repository
self.qualifiers = faked_conn_object.qualifiers
... | 546,001 |
:param tasker: DockerTasker instance
:param workflow: DockerBuildWorkflow instance
:param registries: dict, keys are docker registries, values are dicts containing
per-registry parameters.
Params:
* "secret" optional strin... | def __init__(self, tasker, workflow, registries=None):
super(DeleteFromRegistryPlugin, self).__init__(tasker, workflow)
self.registries = get_registries(self.workflow, deepcopy(registries or {})) | 546,378 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.