Search is not available for this dataset
text
stringlengths
75
104k
def build_action(name=None, image_uri=None, commands=None, entrypoint=None, environment=None, pid_namespace=None, flags=None, port_mappings=None, mounts=None, labels=N...
def lookup_job_tasks(self, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create...
def get_provider(args, resources): """Returns a provider for job submission requests.""" provider = getattr(args, 'provider', 'google') if provider == 'google': return google.GoogleJobProvider( getattr(args, 'verbose', False), getattr(args, 'dry_run', False), args.project) elif provider ==...
def create_parser(prog): """Create an argument parser, adding in the list of providers.""" parser = argparse.ArgumentParser(prog=prog, formatter_class=DsubHelpFormatter) parser.add_argument( '--provider', default='google-v2', choices=['local', 'google', 'google-v2', 'test-fails'], help=""...
def parse_args(parser, provider_required_args, argv): """Add provider required arguments epilog message, parse, and validate.""" # Add the provider required arguments epilog message epilog = 'Provider-required arguments:\n' for provider in provider_required_args: epilog += ' %s: %s\n' % (provider, provide...
def get_dstat_provider_args(provider, project): """A string with the arguments to point dstat to the same provider+project.""" provider_name = get_provider_name(provider) args = [] if provider_name == 'google': args.append('--project %s' % project) elif provider_name == 'google-v2': args.append('--pr...
def _format_task_uri(fmt, job_metadata, task_metadata): """Returns a URI with placeholders replaced by metadata values.""" values = { 'job-id': None, 'task-id': 'task', 'job-name': None, 'user-id': None, 'task-attempt': None } for key in values: values[key] = task_metadata.get...
def format_logging_uri(uri, job_metadata, task_metadata): """Inserts task metadata into the logging URI. The core behavior is inspired by the Google Pipelines API: (1) If a the uri ends in ".log", then that is the logging path. (2) Otherwise, the uri is treated as "directory" for logs and a filename ...
def _google_v2_parse_arguments(args): """Validated google-v2 arguments.""" if (args.zones and args.regions) or (not args.zones and not args.regions): raise ValueError('Exactly one of --regions and --zones must be specified') if args.machine_type and (args.min_cores or args.min_ram): raise ValueError( ...
def _parse_arguments(prog, argv): """Parses command line arguments. Args: prog: The path of the program (dsub.py) or an alternate program name to display in usage. argv: The list of program arguments to parse. Returns: A Namespace of parsed arguments. """ # Handle version flag and exit if it...
def _get_job_resources(args): """Extract job-global resources requirements from input args. Args: args: parsed command-line arguments Returns: Resources object containing the requested resources for the job """ logging = param_util.build_logging_param( args.logging) if args.logging else None ...
def _get_job_metadata(provider, user_id, job_name, script, task_ids, user_project, unique_job_id): """Allow provider to extract job-specific metadata from command-line args. Args: provider: job service provider user_id: user submitting the job job_name: name for the job script...
def _resolve_task_logging(job_metadata, job_resources, task_descriptors): """Resolve the logging path from job and task properties. Args: job_metadata: Job metadata, such as job-id, job-name, and user-id. job_resources: Resources specified such as ram, cpu, and logging path. task_descriptors: Task meta...
def _wait_after(provider, job_ids, poll_interval, stop_on_failure): """Print status info as we wait for those jobs. Blocks until either all of the listed jobs succeed, or one of them fails. Args: provider: job service provider job_ids: a set of job IDs (string) to wait for poll_interval: integer s...
def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor): """Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running and there are no tasks elig...
def _retry_task(provider, job_descriptor, task_id, task_attempt): """Retry task_id (numeric id) assigning it task_attempt.""" td_orig = job_descriptor.find_task_descriptor(task_id) new_task_descriptors = [ job_model.TaskDescriptor({ 'task-id': task_id, 'task-attempt': task_attempt ...
def _dominant_task_for_jobs(tasks): """A list with, for each job, its dominant task. The dominant task is the one that exemplifies its job's status. It is either: - the first (FAILURE or CANCELED) task, or if none - the first RUNNING task, or if none - the first SUCCESS task. Args: tasks: a list of ...
def _group_tasks_by_jobid(tasks): """A defaultdict with, for each job, a list of its tasks.""" ret = collections.defaultdict(list) for t in tasks: ret[t.get_field('job-id')].append(t) return ret
def _importance_of_task(task): """Tuple (importance, end-time). Smaller values are more important.""" # The status of a job is going to be determined by the roll-up of its tasks. # A FAILURE or CANCELED task means the job has FAILED. # If none, then any RUNNING task, the job is still RUNNING. # If none, then ...
def _wait_for_any_job(provider, job_ids, poll_interval): """Waits until any of the listed jobs is not running. In particular, if any of the jobs sees one of its tasks fail, we count the whole job as failing (but do not terminate the remaining tasks ourselves). Args: provider: job service provider jo...
def _validate_job_and_task_arguments(job_params, task_descriptors): """Validates that job and task argument names do not overlap.""" if not task_descriptors: return task_params = task_descriptors[0].task_params # The use case for specifying a label or env/input/output parameter on # the command-line an...
def run_main(args): """Execute job/task submission from command-line arguments.""" if args.command and args.script: raise ValueError('Cannot supply both a --command and --script flag') provider_base.check_for_unsupported_flag(args) # Set up job parameters and job data from a tasks file or flags. input_...
def run(provider, job_resources, job_params, task_descriptors, name=None, dry_run=False, command=None, script=None, user=None, user_project=None, wait=False, retries=0, poll_interval=10, after=None, skip=Fals...
def _name_for_command(command): r"""Craft a simple command name from the command. The best command strings for this are going to be those where a simple command was given; we will use the command to derive the name. We won't always be able to figure something out and the caller should just specify a "--name...
def _local_uri_rewriter(raw_uri): """Rewrite local file URIs as required by the rewrite_uris method. Local file paths, unlike GCS paths, may have their raw URI simplified by os.path.normpath which collapses extraneous indirect characters. >>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt') ('/tmp/B_PA...
def _get_filtered_mounts(mounts, mount_param_type): """Helper function to return an appropriate set of mount parameters.""" return set([mount for mount in mounts if isinstance(mount, mount_param_type)])
def build_logging_param(logging_uri, util_class=OutputFileParamUtil): """Convenience function simplifies construction of the logging uri.""" if not logging_uri: return job_model.LoggingParam(None, None) recursive = not logging_uri.endswith('.log') oututil = util_class('') _, uri, provider = oututil.parse_...
def split_pair(pair_string, separator, nullable_idx=1): """Split a string into a pair, which can have one empty value. Args: pair_string: The string to be split. separator: The separator to be used for splitting. nullable_idx: The location to be set to null if the separator is not in the ...
def parse_tasks_file_header(header, input_file_param_util, output_file_param_util): """Parse the header from the tasks file into env, input, output definitions. Elements are formatted similar to their equivalent command-line arguments, but with associated values coming from the data r...
def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util, output_file_param_util): """Parses task parameters from a TSV. Args: tasks: Dict containing the path to a TSV file and task numbers to run variables, input, and output parameters as column headings....
def parse_pair_args(labels, argclass): """Parse flags of key=value pairs and return a list of argclass. For pair variables, we need to: * split the input into name=value pairs (value optional) * Create the EnvParam object Args: labels: list of 'key' or 'key=value' strings. argclass: Container ...
def args_to_job_params(envs, labels, inputs, inputs_recursive, outputs, outputs_recursive, mounts, input_file_param_util, output_file_param_util, mount_param_util): """Parse env, input, and output parameters into a job parameters and data. Passing arguments on the comm...
def validate_submit_args_or_fail(job_descriptor, provider_name, input_providers, output_providers, logging_providers): """Validate that arguments passed to submit_job have valid file providers. This utility function takes resources and task data args from `submit_job` in the base...
def handle_version_flag(): """If the --version flag is passed, print version to stdout and exit. Within dsub commands, --version should be the highest priority flag. This function supplies a repeatable and DRY way of checking for the version flag and printing the version. Callers still need to define a version...
def age_to_create_time(age, from_time=None): """Compute the create time (UTC) for the list filter. If the age is an integer value it is treated as a UTC date. Otherwise the value must be of the form "<integer><unit>" where supported units are s, m, h, d, w (seconds, minutes, hours, days, weeks). Args: a...
def _interval_to_seconds(interval, valid_units='smhdw'): """Convert the timeout duration to seconds. The value must be of the form "<integer><unit>" where supported units are s, m, h, d, w (seconds, minutes, hours, days, weeks). Args: interval: A "<integer><unit>" string. valid_units: A list of suppor...
def get_variable_name(self, name): """Produce a default variable name if none is specified.""" if not name: name = '%s%s' % (self._auto_prefix, self._auto_index) self._auto_index += 1 return name
def rewrite_uris(self, raw_uri, file_provider): """Accept a raw uri and return rewritten versions. This function returns a normalized URI and a docker path. The normalized URI may have minor alterations meant to disambiguate and prepare for use by shell utilities that may require a specific format. ...
def parse_file_provider(uri): """Find the file provider for a URI.""" providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL} # URI scheme detector uses a range up to 30 since none of the IANA # registered schemes are longer than this. provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29...
def _validate_paths_or_fail(uri, recursive): """Do basic validation of the uri, return the path and filename.""" path, filename = os.path.split(uri) # dsub could support character ranges ([0-9]) with some more work, but for # now we assume that basic asterisk wildcards are sufficient. Reject any URI ...
def parse_uri(self, raw_uri, recursive): """Return a valid docker_path, uri, and file provider from a flag value.""" # Assume recursive URIs are directory paths. if recursive: raw_uri = directory_fmt(raw_uri) # Get the file provider, validate the raw URI, and rewrite the path # component of th...
def make_param(self, name, raw_uri, recursive): """Return a *FileParam given an input uri.""" if not raw_uri: return self.param_class(name, None, None, None, recursive, None) docker_path, uri_parts, provider = self.parse_uri(raw_uri, recursive) return self.param_class(name, raw_uri, docker_path, u...
def _parse_image_uri(self, raw_uri): """Return a valid docker_path from a Google Persistent Disk url.""" # The string replace is so we don't have colons and double slashes in the # mount path. The idea is the resulting mount path would look like: # /mnt/data/mount/http/www.googleapis.com/compute/v1/proj...
def _parse_local_mount_uri(self, raw_uri): """Return a valid docker_path for a local file path.""" raw_uri = directory_fmt(raw_uri) _, docker_path = _local_uri_rewriter(raw_uri) local_path = docker_path[len('file'):] docker_uri = os.path.join(self._relative_path, docker_path) return local_path, ...
def _parse_gcs_uri(self, raw_uri): """Return a valid docker_path for a GCS bucket.""" # Assume URI is a directory path. raw_uri = directory_fmt(raw_uri) _, docker_path = _gcs_uri_rewriter(raw_uri) docker_uri = os.path.join(self._relative_path, docker_path) return docker_uri
def make_param(self, name, raw_uri, disk_size): """Return a MountParam given a GCS bucket, disk image or local path.""" if raw_uri.startswith('https://www.googleapis.com/compute'): # Full Image URI should look something like: # https://www.googleapis.com/compute/v1/projects/<project>/global/images/ ...
def validate_param_name(name, param_type): """Validate that the name follows posix conventions for env variables.""" # http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_235 # # 3.235 Name # In the shell command language, a word consisting solely of underscores, # digits, and alp...
def validate_bucket_name(bucket): """Validate that the name is a valid GCS bucket.""" if not bucket.startswith('gs://'): raise ValueError( 'Invalid bucket path "%s". Must start with "gs://".' % bucket) bucket_name = bucket[len('gs://'):] if not re.search(r'^\w[\w_\.-]{1,61}\w$', bucket_name): ra...
def convert_to_label_chars(s): """Turn the specified name and value into a valid Google label.""" # We want the results to be user-friendly, not just functional. # So we can't base-64 encode it. # * If upper-case: lower-case it # * If the char is not a standard letter or digit. make it a dash # March ...
def ensure_task_params_are_complete(task_descriptors): """For each task, ensure that each task param entry is not None.""" for task_desc in task_descriptors: for param in [ 'labels', 'envs', 'inputs', 'outputs', 'input-recursives', 'output-recursives' ]: if not task_desc.task_params.ge...
def _remove_empty_items(d, required): """Return a new dict with any empty items removed. Note that this is not a deep check. If d contains a dictionary which itself contains empty items, those are never checked. This method exists to make to_serializable() functions cleaner. We could revisit this some day, ...
def task_view_generator(job_descriptor): """Generator that yields a task-specific view of the job. This generator exists to make it easy for callers to iterate over the tasks in a JobDescriptor. Each pass yields a new JobDescriptor with a single task. Args: job_descriptor: A JobDescriptor with 1 or more t...
def numeric_task_id(task_id): """Converts a task-id to the numeric task-id. Args: task_id: task-id in either task-n or n format Returns: n """ # This function exists to support the legacy "task-id" format in the "google" # provider. Google labels originally could not be numeric. When the google ...
def _validate_label(cls, name, value): """Raise ValueError if the label is invalid.""" # Rules for labels are described in: # https://cloud.google.com/compute/docs/labeling-resources#restrictions # * Keys and values cannot be longer than 63 characters each. # * Keys and values can only contain low...
def to_serializable(self): """Return a dict populated for serialization (as YAML/JSON).""" task_metadata = self.task_metadata task_params = self.task_params task_resources = self.task_resources # The only required field is the task-id, even if it is None task_id = None if task_metadata.get...
def to_serializable(self): """Return a dict populated for serialization (as YAML/JSON).""" job_metadata = self.job_metadata job_resources = self.job_resources job_params = self.job_params task_descriptors = self.task_descriptors job = { 'job-id': job_metadata.get('job-id'), 'jo...
def _from_yaml_v0(cls, job): """Populate a JobDescriptor from the local provider's original meta.yaml. The local job provider had the first incarnation of a YAML file for each task. That idea was extended here in the JobDescriptor and the local provider adopted the JobDescriptor.to_yaml() call to write...
def from_yaml(cls, yaml_string): """Populate and return a JobDescriptor from a YAML string.""" try: job = yaml.full_load(yaml_string) except AttributeError: # For installations that cannot update their PyYAML version job = yaml.load(yaml_string) # If the YAML does not contain a top-le...
def find_task_descriptor(self, task_id): """Returns the task_descriptor corresponding to task_id.""" # It is not guaranteed that the index will be task_id - 1 when --tasks is # used with a min/max range. for task_descriptor in self.task_descriptors: if task_descriptor.task_metadata.get('task-id')...
def get_file_environment_variables(file_params): """Return a dictionary of environment variables for the user container.""" env = {} for param in file_params: # We have no cases where the environment variable provided to user # scripts have a trailing slash, so be sure to always strip it. # The case t...
def build_recursive_localize_env(destination, inputs): """Return a multi-line string with export statements for the variables. Arguments: destination: Folder where the data will be put. For example /mnt/data inputs: a list of InputFileParam Returns: a multi-line string with a shell ...
def build_recursive_localize_command(destination, inputs, file_provider): """Return a multi-line string with a shell script to copy recursively. Arguments: destination: Folder where to put the data. For example /mnt/data inputs: a list of InputFileParam file_provider: file provider str...
def build_recursive_gcs_delocalize_env(source, outputs): """Return a multi-line string with export statements for the variables. Arguments: source: Folder with the data. For example /mnt/data outputs: a list of OutputFileParam Returns: a multi-line string with a shell script that sets en...
def build_recursive_delocalize_command(source, outputs, file_provider): """Return a multi-line string with a shell script to copy recursively. Arguments: source: Folder with the data. For example /mnt/data outputs: a list of OutputFileParam. file_provider: file provider string used to filte...
def build_mount_env(source, mounts): """Return a multi-line string with export statements for the variables. Arguments: source: Folder with the data. For example /mnt/data mounts: a list of MountParam Returns: a multi-line string with a shell script that sets environment variables corresponding ...
def get_job_and_task_param(job_params, task_params, field): """Returns a dict combining the field for job and task params.""" return job_params.get(field, set()) | task_params.get(field, set())
def _parse_arguments(): """Parses command line arguments. Returns: A Namespace of parsed arguments. """ # Handle version flag and exit if it was passed. param_util.handle_version_flag() parser = provider_base.create_parser(sys.argv[0]) parser.add_argument( '--version', '-v', default=False, he...
def _emit_search_criteria(user_ids, job_ids, task_ids, labels): """Print the filters used to delete tasks. Use raw flags as arguments.""" print('Delete running jobs:') print(' user:') print(' %s\n' % user_ids) print(' job-id:') print(' %s\n' % job_ids) if task_ids: print(' task-id:') prin...
def ddel_tasks(provider, user_ids=None, job_ids=None, task_ids=None, labels=None, create_time_min=None, create_time_max=None): """Kill jobs or job tasks. This function separates ddel logic from flag parsing and user output. U...
def get_action_by_id(op, action_id): """Return the operation's array of actions.""" actions = get_actions(op) if actions and 1 <= action_id < len(actions): return actions[action_id - 1]
def _get_action_by_name(op, name): """Return the value for the specified action.""" actions = get_actions(op) for action in actions: if action.get('name') == name: return action
def get_action_environment(op, name): """Return the environment for the operation.""" action = _get_action_by_name(op, name) if action: return action.get('environment')
def get_action_image(op, name): """Return the image for the operation.""" action = _get_action_by_name(op, name) if action: return action.get('imageUri')
def get_failed_events(op): """Return the events (if any) with a non-zero exitStatus.""" events = get_events(op) if events: return [ e for e in events if int(e.get('details', {}).get('exitStatus', 0)) != 0 ] return None
def get_event_of_type(op, event_type): """Return all events of a particular type.""" events = get_events(op) if not events: return None return [e for e in events if e.get('details', {}).get('@type') == event_type]
def get_last_update(op): """Return the most recent timestamp in the operation.""" last_update = get_end_time(op) if not last_update: last_event = get_last_event(op) if last_event: last_update = last_event['timestamp'] if not last_update: last_update = get_create_time(op) return last_updat...
def is_dsub_operation(op): """Determine if a pipelines operation is a dsub request. We don't have a rigorous way to identify an operation as being submitted by dsub. Our best option is to check for certain fields that have always been part of dsub operations. - labels: job-id, job-name, and user-id have alw...
def _prepare_summary_table(rows): """Create a new table that is a summary of the input rows. All with the same (job-name or job-id, status) go together. Args: rows: the input rows, a list of dictionaries. Returns: A new row set of summary information. """ if not rows: return [] # We either ...
def _prepare_row(task, full, summary): """return a dict with the task's info (more if "full" is set).""" # Would like to include the Job ID in the default set of columns, but # it is a long value and would leave little room for status and update time. row_spec = collections.namedtuple('row_spec', ...
def _parse_arguments(): """Parses command line arguments. Returns: A Namespace of parsed arguments. """ # Handle version flag and exit if it was passed. param_util.handle_version_flag() parser = provider_base.create_parser(sys.argv[0]) parser.add_argument( '--version', '-v', default=False, he...
def dstat_job_producer(provider, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, ...
def lookup_job_tasks(provider, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create_time_min=No...
def prepare_output(self, row): """Convert types of task fields.""" date_fields = ['last-update', 'create-time', 'start-time', 'end-time'] int_fields = ['task-attempt'] for col in date_fields: if col in row: row[col] = self.default_format_date(row[col]) for col in int_fields: if...
def trim_display_field(self, value, max_length): """Return a value for display; if longer than max length, use ellipsis.""" if not value: return '' if len(value) > max_length: return value[:max_length - 3] + '...' return value
def format_pairs(self, values): """Returns a string of comma-delimited key=value pairs.""" return ', '.join( '%s=%s' % (key, value) for key, value in sorted(values.items()))
def string_presenter(self, dumper, data): """Presenter to force yaml.dump to use multi-line string style.""" if '\n' in data: return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return dumper.represent_scalar('tag:yaml.org,2002:str', data)
def get_zones(input_list): """Returns a list of zones based on any wildcard input. This function is intended to provide an easy method for producing a list of desired zones for a pipeline to run in. The Pipelines API default zone list is "any zone". The problem with "any zone" is that it can lead to incurri...
def build_pipeline_labels(job_metadata, task_metadata, task_id_pattern=None): """Build a set() of standard job and task labels. Args: job_metadata: Job metadata, such as job-id, job-name, and user-id. task_metadata: Task metadata, such as the task-id. task_id_pattern: A pattern for the task-id value, s...
def prepare_job_metadata(script, job_name, user_id, create_time): """Returns a dictionary of metadata fields for the job.""" # The name of the pipeline gets set into the ephemeralPipeline.name as-is. # The default name of the pipeline is the script name # The name of the job is derived from the job_name and ge...
def parse_rfc3339_utc_string(rfc3339_utc_string): """Converts a datestamp from RFC3339 UTC to a datetime. Args: rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format Returns: A datetime. """ # The timestamp from the Google Operations are all in RFC3339 format, but # they are sometime...
def get_operation_full_job_id(op): """Returns the job-id or job-id.task-id for the operation.""" job_id = op.get_field('job-id') task_id = op.get_field('task-id') if task_id: return '%s.%s' % (job_id, task_id) else: return job_id
def _cancel_batch(batch_fn, cancel_fn, ops): """Cancel a batch of operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages. """ # We define an in...
def cancel(batch_fn, cancel_fn, ops): """Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages. """ # Canceling many operations one-by-...
def retry_api_check(exception): """Return True if we should retry. False otherwise. Args: exception: An exception to test for transience. Returns: True if we should retry. False otherwise. """ if isinstance(exception, apiclient.errors.HttpError): if exception.resp.status in TRANSIENT_HTTP_ERROR_...
def retry_auth_check(exception): """Specific check for auth error codes. Return True if we should retry. False otherwise. Args: exception: An exception to test for transience. Returns: True if we should retry. False otherwise. """ if isinstance(exception, apiclient.errors.HttpError): if exc...
def setup_service(api_name, api_version, credentials=None): """Configures genomics API client. Args: api_name: Name of the Google API (for example: "genomics") api_version: Version of the API (for example: "v2alpha1") credentials: Credentials to be used for the gcloud API calls. Returns: A confi...
def execute(api): """Executes operation. Args: api: The base API object Returns: A response body object """ try: return api.execute() except Exception as exception: now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') _print_error('%s: Exception %s: %s' % (now, ...
def _eval_arg_type(arg_type, T=Any, arg=None, sig=None): """Returns a type from a snippit of python source. Should normally be something just like 'str' or 'Object'. arg_type the source to be evaluated T the default type arg context...
def jsonify_status_code(status_code, *args, **kw): """Returns a jsonified response with the specified HTTP status code. The positional and keyword arguments are passed directly to the :func:`flask.jsonify` function which creates the response. """ is_batch = kw.pop('is_batch', False) if is_batch...
def register(self, app, options, first_registration=False): """Called by :meth:`Flask.register_blueprint` to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments from :func:`~flask.Flask.register_blueprint` are directly for...