PK!jo;;cc_core/__init__.pyfrom cc_core.version import VERSION __version__ = VERSION PK!cc_core/agent/__init__.pyPK!8RRcc_core/agent/__main__.pyfrom cc_core.agent.main import main if __name__ == '__main__': exit(main()) PK!#cc_core/agent/connected/__init__.pyPK!o{\\#cc_core/agent/connected/__main__.pyfrom cc_core.agent.connected.main import main if __name__ == '__main__': exit(main()) PK!L(ffcc_core/agent/connected/main.pyimport os import tempfile import requests from argparse import ArgumentParser from cc_core.commons.red import inputs_to_job, red_validation from cc_core.commons.input_references import create_inputs_to_reference from cc_core.commons.red import ConnectorManager, import_and_validate_connectors, receive, send from cc_core.commons.templates import inspect_templates_and_secrets, fill_template from cc_core.commons.cwl import cwl_to_command, cwl_input_directories, cwl_input_directories_check from cc_core.commons.cwl import cwl_input_files, cwl_output_files, cwl_input_file_check, cwl_output_file_check from cc_core.commons.shell import execute, shell_result_check from cc_core.commons.exceptions import exception_format from cc_core.commons.mnt_core import restore_original_environment DESCRIPTION = 'In order to run an application container with Curious Containers, CC-Agency will launch ccagent in ' \ 'connected mode. The agent sends the container\'s internal status to the server and receives ' \ 'instructions.' def attach_args(parser): parser.add_argument( 'callback_url', action='store', type=str, metavar='CALLBACK_URL', help='An individual CALLBACK_URL is generated by CC-Server for the corresponding agent.' ) parser.add_argument( '--inspect', action='store_true', help='The agent will only perform one callback to inspect if CC-Agency is reachable via the network.' ) def main(): parser = ArgumentParser(description=DESCRIPTION) attach_args(parser) args = parser.parse_args() run(**args.__dict__) return 0 def run(callback_url, inspect): if inspect: r = requests.get(callback_url) r.raise_for_status() return r = requests.get(callback_url) r.raise_for_status() red_data = r.json() tmp_dir = tempfile.mkdtemp() os.chdir(tempfile.mkdtemp()) result = { 'command': None, 'inputFiles': None, 'process': None, 'outputFiles': None, 'debugInfo': None, 'state': 'succeeded' } secret_values = None try: restore_original_environment() red_validation(red_data, False) _, secret_values, _ = inspect_templates_and_secrets(red_data, None, True) red_data = fill_template(red_data, None, False, True) connector_manager = ConnectorManager() import_and_validate_connectors(connector_manager, red_data, False) job_data = inputs_to_job(red_data, tmp_dir) command = cwl_to_command(red_data['cli'], job_data) result['command'] = command receive(connector_manager, red_data, tmp_dir) input_files = cwl_input_files(red_data['cli'], job_data) result['inputFiles'] = input_files cwl_input_file_check(input_files) input_directories = cwl_input_directories(red_data['cli'], job_data) result['inputDirectories'] = input_directories cwl_input_directories_check(input_directories) process_data = execute(command) result['process'] = process_data shell_result_check(process_data) inputs_to_reference = create_inputs_to_reference(job_data, input_files, input_directories) output_files = cwl_output_files(red_data['cli'], inputs_to_reference, output_dir=None) result['outputFiles'] = output_files cwl_output_file_check(output_files) send(connector_manager, output_files, red_data) except Exception: result['debugInfo'] = exception_format(secret_values=secret_values) result['state'] = 'failed' r = requests.post(callback_url, json=result) r.raise_for_status() PK!cc_core/agent/cwl/__init__.pyPK!uVVcc_core/agent/cwl/__main__.pyfrom cc_core.agent.cwl.main import main if __name__ == '__main__': exit(main()) PK!^#UUcc_core/agent/cwl/main.pyimport os import shutil import tempfile from argparse import ArgumentParser from cc_core.commons.files import load_and_read, dump_print, move_files from cc_core.commons.cwl import cwl_to_command, cwl_validation from cc_core.commons.cwl import cwl_input_files, cwl_output_files, cwl_input_file_check, cwl_output_file_check from cc_core.commons.cwl import cwl_input_directories, cwl_input_directories_check from cc_core.commons.input_references import create_inputs_to_reference from cc_core.commons.shell import execute, shell_result_check from cc_core.commons.exceptions import exception_format, print_exception from cc_core.commons.mnt_core import restore_original_environment DESCRIPTION = 'Run a CommandLineTool as described in a CWLFILE and its corresponding JOBFILE.' def attach_args(parser): parser.add_argument( 'cwl_file', action='store', type=str, metavar='CWLFILE', help='CWLFILE containing a CLI description (json/yaml) as local PATH or http URL.' ) parser.add_argument( 'job_file', action='store', type=str, metavar='JOBFILE', help='JOBFILE in the CWL job format (json/yaml) as local PATH or http URL.' ) parser.add_argument( '-d', '--debug', action='store_true', help='Write debug info, including detailed exceptions, to stdout.' ) parser.add_argument( '--format', action='store', type=str, metavar='FORMAT', choices=['json', 'yaml', 'yml'], default='yaml', help='Specify FORMAT for generated data as one of [json, yaml, yml]. Default is yaml.' ) parser.add_argument( '--leave-directories', action='store_true', help='Leave temporary inputs and working directories.' ) def main(): parser = ArgumentParser(description=DESCRIPTION) attach_args(parser) args = parser.parse_args() result = run(**args.__dict__) format = args.__dict__['format'] debug = args.__dict__['debug'] if debug: dump_print(result, format) if result['state'] == 'succeeded': return 0 return 1 def run(cwl_file, job_file, leave_directories, **_): result = { 'command': None, 'inputFiles': None, 'inputDirectories': None, 'process': None, 'outputFiles': None, 'outputDirectories': None, 'debugInfo': None, 'state': 'succeeded' } tmp_working_dir = tempfile.mkdtemp() cwd = os.getcwd() try: restore_original_environment() cwl_data = load_and_read(cwl_file, 'CWLFILE') job_data = load_and_read(job_file, 'JOBFILE') cwl_validation(cwl_data, job_data) input_dir = os.path.split(os.path.expanduser(job_file))[0] command = cwl_to_command(cwl_data, job_data, input_dir=input_dir) result['command'] = command input_files = cwl_input_files(cwl_data, job_data, input_dir=input_dir) result['inputFiles'] = input_files cwl_input_file_check(input_files) input_directories = cwl_input_directories(cwl_data, job_data, input_dir=input_dir) result['inputDirectories'] = input_directories cwl_input_directories_check(input_directories) os.chdir(tmp_working_dir) process_data = execute(command) os.chdir(cwd) result['process'] = process_data shell_result_check(process_data) inputs_to_reference = create_inputs_to_reference(job_data, input_files, input_directories) output_files = cwl_output_files(cwl_data, inputs_to_reference, output_dir=tmp_working_dir) result['outputFiles'] = output_files cwl_output_file_check(output_files) move_files(output_files) except Exception as e: result['debugInfo'] = exception_format() result['state'] = 'failed' print_exception(e) finally: if not leave_directories: shutil.rmtree(tmp_working_dir) return result PK!O󷭄cc_core/agent/main.pyimport sys from collections import OrderedDict from argparse import ArgumentParser from cc_core.version import VERSION from cc_core.agent.connected.main import main as connected_main from cc_core.agent.red.main import main as red_main from cc_core.agent.cwl.main import main as cwl_main from cc_core.agent.connected.main import DESCRIPTION as CONNECTED_DESCRIPTION from cc_core.agent.red.main import DESCRIPTION as RED_DESCRIPTION from cc_core.agent.cwl.main import DESCRIPTION as CWL_DESCRIPTION SCRIPT_NAME = 'ccagent' DESCRIPTION = 'CC-Agent Copyright (C) 2018 Christoph Jansen. This software is distributed under the AGPL-3.0 ' \ 'LICENSE and is part of the Curious Containers project (https://curious-containers.github.io/).' MODES = OrderedDict([ ('cwl', {'main': cwl_main, 'description': CWL_DESCRIPTION}), ('red', {'main': red_main, 'description': RED_DESCRIPTION}), ('connected', {'main': connected_main, 'description': CONNECTED_DESCRIPTION}) ]) def main(): sys.argv[0] = SCRIPT_NAME parser = ArgumentParser(description=DESCRIPTION) parser.add_argument( '-v', '--version', action='version', version=VERSION ) subparsers = parser.add_subparsers(title='modes') sub_parser = None for key, val in MODES.items(): sub_parser = subparsers.add_parser(key, help=val['description'], add_help=False) if len(sys.argv) < 2: parser.print_help() exit() _ = parser.parse_known_args() sub_args = sub_parser.parse_known_args() mode = MODES[sub_args[1][0]]['main'] sys.argv[0] = '{} {}'.format(SCRIPT_NAME, sys.argv[1]) del sys.argv[1] exit(mode()) PK!cc_core/agent/red/__init__.pyPK!x|xKVVcc_core/agent/red/__main__.pyfrom cc_core.agent.red.main import main if __name__ == '__main__': exit(main()) PK!RRcc_core/agent/red/main.pyimport os import shutil import tempfile from argparse import ArgumentParser from cc_core.commons.files import load_and_read, dump_print, move_files from cc_core.commons.input_references import create_inputs_to_reference from cc_core.commons.red import inputs_to_job, convert_batch_experiment, cleanup from cc_core.commons.red import red_validation, ConnectorManager, import_and_validate_connectors, receive, send from cc_core.commons.cwl import cwl_to_command, cwl_input_directories, cwl_input_directories_check from cc_core.commons.cwl import cwl_input_files, cwl_output_files, cwl_input_file_check, cwl_output_file_check from cc_core.commons.shell import execute, shell_result_check from cc_core.commons.exceptions import exception_format, RedValidationError, print_exception, ArgumentError from cc_core.commons.templates import fill_validation, inspect_templates_and_secrets, fill_template from cc_core.commons.mnt_core import restore_original_environment DESCRIPTION = 'Run an experiment as described in a REDFILE.' def attach_args(parser): parser.add_argument( 'red_file', action='store', type=str, metavar='REDFILE', help='REDFILE (json or yaml) containing an experiment description as local PATH or http URL.' ) parser.add_argument( '-v', '--variables', action='store', type=str, metavar='VARFILE', help='VARFILE (json or yaml) containing key-value pairs for variables in REDFILE as ' 'local PATH or http URL.' ) parser.add_argument( '-b', '--batch', action='store', type=int, metavar='INDEX', help='If the RED FILE contains batches, the INDEX of a batch, starting with 0, must be passed.' ) parser.add_argument( '-o', '--outputs', action='store_true', help='Enable connectors specified in the RED FILE outputs section.' ) parser.add_argument( '-d', '--debug', action='store_true', help='Write debug info, including detailed exceptions, to stdout.' ) parser.add_argument( '--format', action='store', type=str, metavar='FORMAT', choices=['json', 'yaml', 'yml'], default='yaml', help='Specify FORMAT for generated data as one of [json, yaml, yml]. Default is yaml.' ) parser.add_argument( '--leave-directories', action='store_true', help='Leave temporary inputs and working directories.' ) def main(): parser = ArgumentParser(description=DESCRIPTION) attach_args(parser) args = parser.parse_args() result = run(**args.__dict__) debug = args.__dict__['debug'] if debug: format = args.__dict__['format'] dump_print(result, format) if result['state'] == 'succeeded': return 0 return 1 def run(red_file, variables, batch, outputs, leave_directories, **_): result = { 'command': None, 'inputFiles': None, 'process': None, 'outputFiles': None, 'debugInfo': None, 'state': 'succeeded' } tmp_inputs_dir = tempfile.mkdtemp() tmp_working_dir = tempfile.mkdtemp() cwd = os.getcwd() secret_values = None connector_manager = None red_data = None try: restore_original_environment() red_data = load_and_read(red_file, 'REDFILE') ignore_outputs = not outputs red_validation(red_data, ignore_outputs) # delete unused keys to avoid unnecessary variables handling if 'execution' in red_data: del red_data['execution'] if 'container' in red_data: del red_data['container'] variables_data = None if variables: variables_data = load_and_read(variables, 'VARFILE') fill_validation(variables_data) red_data = convert_batch_experiment(red_data, batch) if not outputs and 'outputs' in red_data: del red_data['outputs'] if outputs and 'outputs' not in red_data: raise ArgumentError('-o/--outputs argument is set, \ but no outputs section with RED connector settings is defined in REDFILE') template_keys_and_values, secret_values, _ = inspect_templates_and_secrets(red_data, variables_data, True) red_data = fill_template(red_data, template_keys_and_values, False, True) connector_manager = ConnectorManager() import_and_validate_connectors(connector_manager, red_data, ignore_outputs) job_data = inputs_to_job(red_data, tmp_inputs_dir) command = cwl_to_command(red_data['cli'], job_data) result['command'] = command receive(connector_manager, red_data, tmp_inputs_dir) input_files = cwl_input_files(red_data['cli'], job_data) result['inputFiles'] = input_files cwl_input_file_check(input_files) input_directories = cwl_input_directories(red_data['cli'], job_data) result['inputDirectories'] = input_directories cwl_input_directories_check(input_directories) os.chdir(tmp_working_dir) process_data = execute(command) os.chdir(cwd) result['process'] = process_data shell_result_check(process_data) inputs_to_reference = create_inputs_to_reference(job_data, input_files, input_directories) output_files = cwl_output_files(red_data['cli'], inputs_to_reference, output_dir=tmp_working_dir) result['outputFiles'] = output_files cwl_output_file_check(output_files) if outputs: if red_data.get('outputs'): send(connector_manager, output_files, red_data) else: move_files(output_files) except RedValidationError as e: result['debugInfo'] = exception_format(secret_values=secret_values) result['state'] = 'failed' print_exception(e, secret_values) except Exception as e: result['debugInfo'] = exception_format(secret_values=secret_values) result['state'] = 'failed' print_exception(e, secret_values) finally: if not leave_directories: if connector_manager and red_data: cleanup(connector_manager, red_data, tmp_inputs_dir) shutil.rmtree(tmp_working_dir) return result PK!cc_core/commons/__init__.pyPK!-r))cc_core/commons/cli_modes.pyimport sys from argparse import ArgumentParser def cli_modes(script_name, title, description, modes, version=None): sys.argv[0] = script_name parser = ArgumentParser(description=description) if version: parser.add_argument( '-v', '--version', action='version', version=version ) subparsers = parser.add_subparsers(title=title) sub_parser = None for key, val in modes.items(): sub_parser = subparsers.add_parser(key, help=val['description'], add_help=False) if len(sys.argv) < 2: parser.print_help() exit() _ = parser.parse_known_args() sub_args = sub_parser.parse_known_args() mode = modes[sub_args[1][0]]['main'] sys.argv[0] = '{} {}'.format(script_name, sys.argv[1]) del sys.argv[1] exit(mode()) PK!7ıMMcc_core/commons/cwl.pyimport os import jsonschema from glob import glob from jsonschema import ValidationError from urllib.parse import urlparse from shutil import which from operator import itemgetter from cc_core.commons.exceptions import exception_format from cc_core.commons.exceptions import CWLSpecificationError, JobSpecificationError, FileError, DirectoryError from cc_core.commons.input_references import resolve_input_references from cc_core.commons.schemas.cwl import cwl_schema, cwl_job_schema, cwl_job_listing_schema, URL_SCHEME_IDENTIFIER ARGUMENT_TYPE_MAPPING = { 'string': str, 'int': int, 'long': int, 'float': float, 'double': float, 'boolean': bool, 'File': dict, 'Directory': dict } def _assert_type(key, cwl_type, arg): pyt = ARGUMENT_TYPE_MAPPING.get(cwl_type) if pyt is None: raise CWLSpecificationError('argument "{}" has unknown type "{}"'.format(key, cwl_type)) if not isinstance(arg, pyt): raise JobSpecificationError('"{}" argument "{}" has not been parsed to "{}"'.format(cwl_type, key, pyt)) def location(key, arg_item): if arg_item.get(URL_SCHEME_IDENTIFIER): return os.path.abspath(os.path.expanduser(arg_item[URL_SCHEME_IDENTIFIER])) p = arg_item['location'] scheme = urlparse(p).scheme if scheme != 'file': raise JobSpecificationError('argument "{}" uses url scheme "{}" ' 'other than "{}"'.format(key, scheme, 'file')) return os.path.expanduser(p[5:]) def _arg_item_to_string(key, arg_item, input_dir): if isinstance(arg_item, dict): file_path = location(key, arg_item) if input_dir and not os.path.isabs(file_path): file_path = os.path.join(input_dir, file_path) return file_path return str(arg_item) def _input_file_description(key, arg_item, input_dir): description = { 'path': None, 'size': None, 'debugInfo': None, 'nameroot': None, 'nameext': None, 'dirname': None } try: file_path = location(key, arg_item) if input_dir and not os.path.isabs(file_path): file_path = os.path.join(os.path.expanduser(input_dir), file_path) description['path'] = file_path if not os.path.exists(file_path): raise FileError('path does not exist') if not os.path.isfile(file_path): raise FileError('path is not a file') description['size'] = os.path.getsize(file_path) / (1024 * 1024) basename = os.path.basename(file_path) (nameroot, nameext) = os.path.splitext(basename) dirname = os.path.dirname(file_path) description['basename'] = basename description['nameroot'] = nameroot description['nameext'] = nameext description['dirname'] = dirname except: description['debugInfo'] = exception_format() return description def _input_directory_description(input_identifier, arg_item, input_dir): """ Produces a directory description. A directory description is a dictionary containing the following information. - 'path': An array containing the paths to the specified directories. - 'debugInfo': A field to possibly provide debug information. - 'found': A boolean that indicates, if the directory exists in the local filesystem. - 'listing': A listing that shows which files are in the given directory. This could be None. :param input_identifier: The input identifier in the cwl description file :param arg_item: The corresponding job information :param input_dir: TODO :return: A directory description :raise DirectoryError: If the given directory does not exist or is not a directory. """ description = { 'path': None, 'found': False, 'debugInfo': None, 'listing': None, 'basename': None } try: path = location(input_identifier, arg_item) if input_dir and not os.path.isabs(path): path = os.path.join(os.path.expanduser(input_dir), path) description['path'] = path if not os.path.exists(path): raise DirectoryError('path does not exist') if not os.path.isdir(path): raise DirectoryError('path is not a directory') description['listing'] = arg_item.get('listing') description['basename'] = os.path.basename(path) description['found'] = True except: description['debugInfo'] = exception_format() return description def cwl_input_file_check(input_files): missing_files = [] for key, val in input_files.items(): if val['files'] is None: if not val['isOptional']: missing_files.append(key) continue for f in val['files']: if f['size'] is None: missing_files.append(key) continue if missing_files: raise FileError('missing input files {}'.format(missing_files)) def _check_input_directory_listing(base_directory, listing): """ Raises an DirectoryError if files or directories, given in the listing, could not be found in the local filesystem. :param base_directory: The path to the directory to check :param listing: A listing given as dictionary :raise DirectoryError: If the given base directory does not contain all of the subdirectories and subfiles given in the listing. """ for sub in listing: path = os.path.join(base_directory, sub['basename']) if sub['class'] == 'File': if not os.path.isfile(path): raise DirectoryError('File \'{}\' not found but specified in listing.'.format(path)) if sub['class'] == 'Directory': if not os.path.isdir(path): raise DirectoryError('Directory \'{}\' not found but specified in listing'.format(path)) sub_listing = sub.get('listing') if sub_listing: _check_input_directory_listing(path, sub_listing) def cwl_input_directories_check(input_directories): missing_directories = [] for key, val in input_directories.items(): directories = val['directories'] if directories is None and not val['isOptional']: missing_directories.append(key) continue for f in directories: if not f['found']: missing_directories.append(key) continue listing = f.get('listing') if listing: _check_input_directory_listing(f['path'], listing) if missing_directories: raise DirectoryError('missing input directories {}'.format(missing_directories)) def cwl_output_file_check(output_files): missing_files = [] for key, val in output_files.items(): if val['size'] is None and not val['isOptional']: missing_files.append(key) if missing_files: raise FileError('missing output files {}'.format(missing_files)) def cwl_output_directory_check(output_directories): missing_directories = [] for key, val in output_directories.items(): if not val['found'] and not val['isOptional']: missing_directories.append(key) if missing_directories: raise DirectoryError('missing output directories {}'.format(missing_directories)) def parse_cwl_type(cwl_type_string): """ Parses cwl type information from a cwl type string. Examples: - "File[]" -> {'type': 'File', 'isArray': True, 'isOptional': False} - "int?" -> {'type': 'int', 'isArray': False, 'isOptional': True} :param cwl_type_string: The cwl type string to extract information from :return: A dictionary containing information about the parsed cwl type string """ is_optional = cwl_type_string.endswith('?') if is_optional: cwl_type_string = cwl_type_string[:-1] is_array = cwl_type_string.endswith('[]') if is_array: cwl_type_string = cwl_type_string[:-2] return {'type': cwl_type_string, 'isArray': is_array, 'isOptional': is_optional} def cwl_input_files(cwl_data, job_data, input_dir=None): results = {} for key, val in cwl_data['inputs'].items(): cwl_type = parse_cwl_type(val['type']) (is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type) if cwl_type == 'File': result = { 'isOptional': is_optional, 'isArray': is_array, 'files': None } if key in job_data: arg = job_data[key] if is_array: result['files'] = [_input_file_description(key, i, input_dir) for i in arg] else: result['files'] = [_input_file_description(key, arg, input_dir)] results[key] = result return results def cwl_input_directories(cwl_data, job_data, input_dir=None): """ Searches for Directories and in the cwl data and produces a dictionary containing input file information. :param cwl_data: The cwl data as dictionary :param job_data: The job data as dictionary :param input_dir: TODO :return: Returns the a dictionary containing information about input files. The keys of this dictionary are the input/output identifiers of the files specified in the cwl description. The corresponding value is a dictionary again with the following keys and values: - 'isOptional': A bool indicating whether this input directory is optional - 'isArray': A bool indicating whether this could be a list of directories - 'files': A list of input file descriptions A input file description is a dictionary containing the following information - 'path': The path to the specified directory - 'debugInfo': A field to possibly provide debug information """ results = {} for input_identifier, input_data in cwl_data['inputs'].items(): cwl_type = parse_cwl_type(input_data['type']) (is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type) if cwl_type == 'Directory': result = { 'isOptional': is_optional, 'isArray': is_array, 'directories': None } if input_identifier in job_data: arg = job_data[input_identifier] if is_array: result['directories'] = [_input_directory_description(input_identifier, i, input_dir) for i in arg] else: result['directories'] = [_input_directory_description(input_identifier, arg, input_dir)] results[input_identifier] = result return results def cwl_output_files(cwl_data, inputs_to_reference, output_dir=None): """ Returns a dictionary containing information about the output files given in cwl_data. :param cwl_data: The cwl data from where to extract the output file information. :param inputs_to_reference: Inputs which are used to resolve input references. :param output_dir: Path to the directory where output files are expected. :return: A dictionary containing information about every output file. """ results = {} for key, val in cwl_data['outputs'].items(): cwl_type = parse_cwl_type(val['type']) (is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type) if not cwl_type == 'File': continue result = { 'isOptional': is_optional, 'path': None, 'size': None, 'debugInfo': None } glob_path = os.path.expanduser(val['outputBinding']['glob']) if output_dir and not os.path.isabs(glob_path): glob_path = os.path.join(os.path.expanduser(output_dir), glob_path) glob_path = resolve_input_references(glob_path, inputs_to_reference) matches = glob(glob_path) try: if len(matches) != 1: raise FileError('glob path "{}" does not match exactly one file'.format(glob_path)) file_path = matches[0] result['path'] = file_path if not os.path.isfile(file_path): raise FileError('path is not a file') result['size'] = os.path.getsize(file_path) / (1024 * 1024) except: result['debugInfo'] = exception_format() results[key] = result return results def cwl_output_directories(cwl_data, output_dir=None): results = {} for key, val in cwl_data['outputs'].items(): cwl_type = parse_cwl_type(val['type']) (is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type) if not cwl_type == 'Directory': continue result = { 'isOptional': is_optional, 'path': None, 'debugInfo': None, 'found': False } glob_path = os.path.expanduser(val['outputBinding']['glob']) if output_dir and not os.path.isabs(glob_path): glob_path = os.path.join(os.path.expanduser(output_dir), glob_path) matches = glob(glob_path) try: if len(matches) != 1: raise DirectoryError('glob path "{}" does not match exactly one directory'.format(glob_path)) file_path = matches[0] result['path'] = file_path if not os.path.isdir(file_path): raise DirectoryError('path is not a directory') result['found'] = True except: result['debugInfo'] = exception_format() results[key] = result return results def cwl_validation(cwl_data, job_data, docker_requirement=False): try: jsonschema.validate(cwl_data, cwl_schema) except ValidationError as e: raise CWLSpecificationError('CWLFILE does not comply with jsonschema: {}'.format(e.context)) try: jsonschema.validate(job_data, cwl_job_schema) except ValidationError as e: raise JobSpecificationError('JOBFILE does not comply with jsonschema: {}'.format(e.context)) # validate listings for input_key, input_value in job_data.items(): if isinstance(input_value, dict): listing = input_value.get('listing') if listing: try: jsonschema.validate(listing, cwl_job_listing_schema) except ValidationError as e: raise JobSpecificationError('listing of \'{}\' does not comply with jsonschema:\n{}' .format(input_key, e.context)) for key, val in job_data.items(): if key not in cwl_data['inputs']: raise JobSpecificationError('job argument "{}" is not specified in cwl'.format(key)) if docker_requirement: if not cwl_data.get('requirements'): raise CWLSpecificationError('cwl does not contain DockerRequirement') if not cwl_data['requirements'].get('DockerRequirement'): raise CWLSpecificationError('DockerRequirement is missing in cwl') def cwl_to_command(cwl_data, job_data, input_dir=None, check_executable=True): base_command = cwl_data['baseCommand'] if isinstance(base_command, list): if len(base_command) < 1: raise CWLSpecificationError('invalid baseCommand "{}"'.format(base_command)) executable = base_command[0].strip() subcommands = base_command[1:] else: executable = base_command.strip() subcommands = [] if check_executable: if not which(executable): raise CWLSpecificationError('invalid executable "{}"'.format(executable)) command = [executable] + subcommands prefixed_arguments = [] positional_arguments = [] for key, val in cwl_data['inputs'].items(): cwl_type = val['type'] is_optional = cwl_type.endswith('?') if is_optional: cwl_type = cwl_type[:-1] is_array = cwl_type.endswith('[]') if is_array: cwl_type = cwl_type[:-2] is_positional = val['inputBinding'].get('position') is not None if not is_positional: if not val['inputBinding'].get('prefix'): raise CWLSpecificationError('non-positional argument "{}" requires prefix'.format(key)) if key not in job_data: if is_optional: continue raise JobSpecificationError('required argument "{}" is missing'.format(key)) arg = job_data[key] if is_array: if not isinstance(arg, list): raise JobSpecificationError('array argument "{}" has not been parsed to list'.format(key)) try: for e in arg: _assert_type(key, cwl_type, e) except: raise JobSpecificationError( '"{}" array argument "{}" contains elements of wrong type'.format(cwl_type, key) ) else: _assert_type(key, cwl_type, arg) if is_array: if val['inputBinding'].get('prefix'): prefix = val['inputBinding'].get('prefix') if val['inputBinding'].get('separate', True): arg = '{} {}'.format(prefix, ' '.join([_arg_item_to_string(key, i, input_dir) for i in arg])) elif val['inputBinding'].get('itemSeparator'): item_sep = val['inputBinding']['itemSeparator'] arg = '{}{}'.format(prefix, item_sep.join([_arg_item_to_string(key, i, input_dir) for i in arg])) else: arg = ' '.join(['{}{}'.format(prefix, _arg_item_to_string(key, i, input_dir)) for i in arg]) else: item_sep = val['inputBinding'].get('itemSeparator') if not item_sep: item_sep = ' ' arg = item_sep.join([_arg_item_to_string(key, i, input_dir) for i in arg]) elif val['inputBinding'].get('prefix'): prefix = val['inputBinding']['prefix'] separate = val['inputBinding'].get('separate', True) if separate: if cwl_type == 'boolean': if arg: arg = prefix else: continue else: arg = '{} {}'.format(prefix, _arg_item_to_string(key, arg, input_dir)) else: arg = '{}{}'.format(prefix, _arg_item_to_string(key, arg, input_dir)) if is_positional: pos = val['inputBinding']['position'] additional = pos + 1 - len(positional_arguments) positional_arguments += [None for _ in range(additional)] if positional_arguments[pos] is not None: raise CWLSpecificationError('multiple positional arguments exist for position "{}"'.format(pos)) positional_arguments[pos] = {'arg': _arg_item_to_string(key, arg, input_dir), 'is_array': is_array} else: prefixed_arguments.append(arg) positional_arguments = [p for p in positional_arguments if p is not None] first_array_index = len(positional_arguments) for i, p in enumerate(positional_arguments): if p['is_array']: first_array_index = i break front_positional_arguments = positional_arguments[:first_array_index] back_positional_arguments = positional_arguments[first_array_index:] command += [p['arg'] for p in front_positional_arguments] command += prefixed_arguments command += [p['arg'] for p in back_positional_arguments] return ' '.join([str(c) for c in command]) PK!h`cc_core/commons/engines.pyimport jsonschema from jsonschema.exceptions import ValidationError from cc_core.commons.exceptions import EngineError from cc_core.commons.schemas.engines.container import container_engines from cc_core.commons.schemas.engines.execution import execution_engines ENGINES = { 'container': container_engines, 'execution': execution_engines } DEFAULT_DOCKER_RUNTIME = 'runc' NVIDIA_DOCKER_RUNTIME = 'nvidia' def engine_validation(red_data, engine_type, supported, optional=False): if engine_type not in ENGINES: raise EngineError('invalid engine type "{}"'.format(engine_type)) if engine_type not in red_data: if optional: return raise EngineError('engine type "{}" required in RED_FILE'.format(engine_type)) engine = red_data[engine_type]['engine'] settings = red_data[engine_type]['settings'] if engine not in supported: raise EngineError('{}-engine "{}" not supported'.format(engine_type, engine)) if engine not in ENGINES[engine_type]: raise EngineError('no schema available for {}-engine "{}" in cc_core'.format(engine_type, engine)) schema = ENGINES[engine_type][engine] try: jsonschema.validate(settings, schema) except ValidationError as e: raise EngineError('{}-engine "{}" does not comply with jsonschema: {}'.format(engine_type, engine, e.context)) def engine_to_runtime(engine): """ Returns the docker runtime string depending on which engine is present :param engine: On of 'docker' or 'nvidia-docker' :return: 'nvidia' for engine=='nvidia-docker', otherwise 'runc' """ runtime = DEFAULT_DOCKER_RUNTIME if engine == 'nvidia-docker': runtime = NVIDIA_DOCKER_RUNTIME return runtime PK!Pcc_core/commons/exceptions.pyimport sys import re from traceback import format_exc def _hide_secret_values(text, secret_values): if secret_values: return re.sub('|'.join(secret_values), '********', text) return text def _lstrip_quarter(s): len_s = len(s) s = s.lstrip() len_s_strip = len(s) quarter = (len_s - len_s_strip) // 4 return ' ' * quarter + s def exception_format(secret_values=None): exc_text = format_exc() exc_text = _hide_secret_values(exc_text, secret_values) return [_lstrip_quarter(l.replace('"', '').replace("'", '').rstrip()) for l in exc_text.split('\n') if l] def brief_exception_text(exception, secret_values): """ Returns the Exception class and the message of the exception as string. :param exception: The exception to format :param secret_values: Values to hide in output """ exception_text = _hide_secret_values(str(exception), secret_values) return '[{}]\n{}'.format(type(exception).__name__, exception_text) def print_exception(exception, secret_values=None): """ Prints the exception message and the name of the exception class to stderr. :param exception: The exception to print :param secret_values: Values to hide in output """ print(brief_exception_text(exception, secret_values), file=sys.stderr) class InvalidInputReference(Exception): pass class ArgumentError(Exception): pass class AgentError(Exception): pass class EngineError(Exception): pass class FileError(Exception): pass class DirectoryError(Exception): pass class JobExecutionError(Exception): pass class CWLSpecificationError(Exception): pass class JobSpecificationError(Exception): pass class RedSpecificationError(Exception): pass class RedValidationError(Exception): pass class RedVariablesError(Exception): pass class ConnectorError(Exception): pass class AccessValidationError(Exception): pass class AccessError(Exception): pass PK!(Xcc_core/commons/files.pyimport os import stat import sys import json import requests import textwrap import shutil from urllib.parse import urlparse from ruamel.yaml import YAML from cc_core.commons.exceptions import AgentError JSON_INDENT = 4 yaml = YAML(typ='safe') yaml.default_flow_style = False WRITE_PERMISSIONS = stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH def move_files(output_files): for key, val in output_files.items(): path = val['path'] _, ext = os.path.splitext(path) file_name = ''.join([key, ext]) try: shutil.move(path, file_name) except PermissionError: if os.path.exists(file_name): raise PermissionError('Cannot write output file "{}", because it already exists.\n' 'You may have used an output directory that still contains read-only files?' .format(file_name)) else: raise PermissionError('Cannot write output file "{}", because of insufficient permissions.\n' 'Maybe check write permissions of the output directory.'.format(file_name)) def load_and_read(location, var_name): if not location: return None raw_data = load(location, var_name) return read(raw_data, var_name) def is_local(location): scheme = urlparse(location).scheme if scheme == 'http' or scheme == 'https': return False return True def load(location, var_name): scheme = urlparse(location).scheme if scheme == 'path': return _local(location[5:], var_name) if scheme == '': return _local(location, var_name) if scheme == 'http' or scheme == 'https': return _http(location, var_name) raise AgentError('argument "{}" has unknown url scheme'.format(location)) def read(raw_data, var_name): try: data = json.loads(raw_data) except: try: data = yaml.load(raw_data) except: raise AgentError('data for argument "{}" is neither json nor yaml formatted.\ndata: {}' .format(var_name, raw_data)) if not isinstance(data, dict): raise AgentError('data for argument "{}" does not contain a dictionary.\ndata: "{}"'.format(var_name, data)) return data def file_extension(dump_format): if dump_format == 'json': return dump_format if dump_format in ['yaml', 'yml']: return 'yml' raise AgentError('invalid dump format "{}"'.format(dump_format)) def dump(stream, dump_format, file_name): if dump_format == 'json': with open(file_name, 'w') as f: json.dump(stream, f, indent=JSON_INDENT) elif dump_format in ['yaml', 'yml']: with open(file_name, 'w') as f: yaml.dump(stream, f) else: raise AgentError('invalid dump format "{}"'.format(dump_format)) def dump_print(stream, dump_format, error=False): if dump_format == 'json': if error: print(json.dumps(stream, indent=JSON_INDENT), file=sys.stderr) else: print(json.dumps(stream, indent=JSON_INDENT)) elif dump_format in ['yaml', 'yml']: if error: yaml.dump(stream, sys.stderr) else: yaml.dump(stream, sys.stdout) elif dump_format != 'none': raise AgentError('invalid dump format "{}"'.format(dump_format)) def wrapped_print(blocks, error=False): if error: for block in blocks: print(textwrap.fill(block), file=sys.stderr) else: for block in blocks: print(textwrap.fill(block)) def _http(location, var_name): try: r = requests.get(location) r.raise_for_status() except: raise AgentError('file for argument "{}" could not be loaded via http'.format(var_name)) return r.text def _local(location, var_name): try: with open(os.path.expanduser(location)) as f: return f.read() except: raise AgentError('file for argument "{}" could not be loaded from file system'.format(var_name)) def for_each_file(base_dir, func): """ Calls func(filename) for every file under base_dir. :param base_dir: A directory containing files :param func: The function to call with every file. """ for dir_path, _, file_names in os.walk(base_dir): for filename in file_names: func(os.path.join(dir_path, filename)) def make_file_read_only(file_path): """ Removes the write permissions for the given file for owner, groups and others. :param file_path: The file whose privileges are revoked. :raise FileNotFoundError: If the given file does not exist. """ old_permissions = os.stat(file_path).st_mode os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS) PK!+o6GGcc_core/commons/gpu_info.pyclass InsufficientGPUError(Exception): pass class GPUDevice: """ Represents a GPU Device """ def __init__(self, device_id, vram): """ :param vram: The vram of this GPU in bytes """ self.device_id = device_id self.vram = vram class GPURequirement: """ Represents a GPU Requirement """ def __init__(self, min_vram=None): """ :param min_vram: The minimal vram needed for this device in bytes If None, no vram limitation is used. """ self.min_vram = min_vram def is_sufficient(self, device): """ Returns whether the device is sufficient for this requirement. :param device: A GPUDevice instance. :type device: GPUDevice :return: True if the requirement is fulfilled otherwise False """ sufficient = True if (self.min_vram is not None) and (device.vram < self.min_vram): sufficient = False return sufficient def get_cuda_devices(): """ Imports pycuda at runtime and reads GPU information. :return: A list of available cuda GPUs. """ devices = [] try: import pycuda.autoinit import pycuda.driver as cuda for device_id in range(cuda.Device.count()): vram = cuda.Device(device_id).total_memory() devices.append(GPUDevice(device_id, vram)) except ImportError: raise InsufficientGPUError('No Nvidia-GPUs could be found, because "pycuda" could not be imported.') return devices def no_devices(): """ Returns an empty list :return: [] """ return [] """ maps docker engines to functions returning gpu devices """ DEVICE_INFORMATION_MAP = { 'docker': no_devices, 'nvidia-docker': get_cuda_devices } def get_devices(engine): """ Returns GPU device information. :param engine: The used docker engine. :return: A list of available devices """ if engine in DEVICE_INFORMATION_MAP: return DEVICE_INFORMATION_MAP[engine]() else: return [] def search_device(requirement, devices): """ Returns a sufficient device or None :param requirement: The requirement to fulfill :param devices: The list of available devices :return: A device from the list """ for device in devices: if requirement.is_sufficient(device): return device return None def match_gpus(available_devices, requirements): """ Determines sufficient GPUs for the given requirements and returns a list of GPUDevices. If there aren't sufficient GPUs a InsufficientGPUException is thrown. :param available_devices: A list of GPUDevices :param requirements: A list of GPURequirements :return: A list of sufficient devices """ if not requirements: return [] if not available_devices: raise InsufficientGPUError("No GPU devices available, but {} devices required.".format(len(requirements))) available_devices = available_devices.copy() used_devices = [] for req in requirements: dev = search_device(req, available_devices) if dev: used_devices.append(dev) available_devices.remove(dev) else: raise InsufficientGPUError("Not all GPU requirements could be fulfilled.") return used_devices def get_gpu_requirements(gpus_reqs): """ Extracts the GPU from a dictionary requirements as list of GPURequirements. :param gpus_reqs: A dictionary {'count': } or a list [{min_vram: }, {min_vram: }, ...] :return: A list of GPURequirements """ requirements = [] if gpus_reqs: if type(gpus_reqs) is dict: count = gpus_reqs.get('count') if count: for i in range(count): requirements.append(GPURequirement()) elif type(gpus_reqs) is list: for gpu_req in gpus_reqs: requirements.append(GPURequirement(min_vram=gpu_req['minVram'])) return requirements else: # If no requirements are supplied return [] def set_nvidia_environment_variables(environment, gpu_ids): """ Updates a dictionary containing environment variables to setup Nvidia-GPUs. :param environment: The environment variables to update :param gpu_ids: A list of GPU ids """ if gpu_ids: nvidia_visible_devices = "" for gpu_id in gpu_ids: nvidia_visible_devices += "{},".format(gpu_id) environment["NVIDIA_VISIBLE_DEVICES"] = nvidia_visible_devices PK!弰))#cc_core/commons/input_references.pyfrom copy import deepcopy from cc_core.commons.exceptions import InvalidInputReference ATTRIBUTE_SEPARATOR_SYMBOLS = ['.', '["', '"]', '[\'', '\']'] INPUT_REFERENCE_START = '$(' INPUT_REFERENCE_END = ')' def _get_dict_element(d, l): """ Uses the keys in list l to get recursive values in d. Like return d[l[0]] [l[1]] [l[2]]... :param d: A dictionary :param l: A list of keys :return: The last value of d, after inserting all keys in l. """ for e in l: d = d[e] return d def create_inputs_to_reference(job_data, input_files, input_directories): """ Creates a dictionary with the summarized information in job_data, input_files and input_directories :param job_data: The job data specifying input parameters other than files and directories. :param input_files: A dictionary describing the input files. :param input_directories: A dictionary describing the input directories. :return: A summarized dictionary containing information about all given inputs. """ return {**deepcopy(job_data), **deepcopy(input_files), **deepcopy(input_directories)} def _partition_all_internal(s, sep): """ Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. :param s: The string to split. :param sep: A separator string. :return: A list of parts split by sep """ parts = list(s.partition(sep)) # if sep found if parts[1] == sep: new_parts = partition_all(parts[2], sep) parts.pop() parts.extend(new_parts) return [p for p in parts if p] else: if parts[0]: return [parts[0]] else: return [] def partition_all(s, sep): """ Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. If sep is a list, all separators are evaluated. :param s: The string to split. :param sep: A separator string or a list of separator strings. :return: A list of parts split by sep """ if isinstance(sep, list): parts = _partition_all_internal(s, sep[0]) sep = sep[1:] for s in sep: tmp = [] for p in parts: tmp.extend(_partition_all_internal(p, s)) parts = tmp return parts else: return _partition_all_internal(s, sep) def split_input_references(to_split): """ Returns the given string in normal strings and unresolved input references. An input reference is identified as something of the following form $(...). Example: split_input_reference("a$(b)cde()$(fg)") == ["a", "$(b)", "cde()", "$(fg)"] :param to_split: The string to split :raise InvalidInputReference: If an input reference is not closed and a new reference starts or the string ends. :return: A list of normal strings and unresolved input references. """ parts = partition_all(to_split, [INPUT_REFERENCE_START, INPUT_REFERENCE_END]) result = [] part = [] in_reference = False for p in parts: if in_reference: if p == INPUT_REFERENCE_START: raise InvalidInputReference('A new input reference has been started, although the old input reference' 'has not yet been completed.\n{}'.format(to_split)) elif p == ")": part.append(")") result.append(''.join(part)) part = [] in_reference = False else: part.append(p) else: if p == INPUT_REFERENCE_START: if part: result.append(''.join(part)) part = [INPUT_REFERENCE_START] in_reference = True else: part.append(p) if in_reference: raise InvalidInputReference('Input reference not closed.\n{}'.format(to_split)) elif part: result.append(''.join(part)) return result def is_input_reference(s): """ Returns True, if s is an input reference. :param s: The string to check if it starts with INPUT_REFERENCE_START and ends with INPUT_REFERENCE_END. :return: True, if s is an input reference otherwise False """ return s.startswith(INPUT_REFERENCE_START) and s.endswith(INPUT_REFERENCE_END) def split_all(reference, sep): """ Splits a given string at a given separator or list of separators. :param reference: The reference to split. :param sep: Separator string or list of separator strings. :return: A list of split strings """ parts = partition_all(reference, sep) return [p for p in parts if p not in sep] def _resolve_file(attributes, input_file, input_identifier, input_reference): """ Returns the attributes in demand of the input file. :param attributes: A list of attributes to get from the input_file. :param input_file: The file from which to get the attributes. :param input_identifier: The input identifier of the given file. :param input_reference: The reference string :return: The attribute in demand """ if input_file['isArray']: raise InvalidInputReference('Input References to Arrays of input files are currently not supported.\n' '"{}" is an array of files and can not be resolved for input references:' '\n{}'.format(input_identifier, input_reference)) single_file = input_file['files'][0] try: return _get_dict_element(single_file, attributes) except KeyError: raise InvalidInputReference('Could not get attributes "{}" from input file "{}", needed in input reference:' '\n{}'.format(attributes, input_identifier, input_reference)) def _resolve_directory(attributes, input_directory, input_identifier, input_reference): """ Returns the attributes in demand of the input directory. :param attributes: A list of attributes to get from the input directory. :param input_directory: The directory from which to get the attributes. :param input_identifier: The input identifier of the given directory. :param input_reference: The reference string :return: The attribute in demand """ if input_directory['isArray']: raise InvalidInputReference('Input References to Arrays of input directories are currently not supported.\n' 'input directory "{}" is an array of directories and can not be resolved for input' 'references:\n{}'.format(input_identifier, input_reference)) single_directory = input_directory['directories'][0] try: return _get_dict_element(single_directory, attributes) except KeyError: raise InvalidInputReference('Could not get attributes "{}" from input directory "{}", needed in input' 'reference:\n{}'.format(attributes, input_identifier, input_reference)) def resolve_input_reference(reference, inputs_to_reference): """ Replaces a given input_reference by a string extracted from inputs_to_reference. :param reference: The input reference to resolve. :param inputs_to_reference: A dictionary containing information about the given inputs. :raise InvalidInputReference: If the given input reference could not be resolved. :return: A string which is the resolved input reference. """ if not reference.startswith('{}inputs.'.format(INPUT_REFERENCE_START)): raise InvalidInputReference('An input reference must have the following form' '"$(inputs.[.]".\n' 'The invalid reference is: "{}"'.format(reference)) # remove "$(inputs." and ")" reference = reference[2:-1] parts = split_all(reference, ATTRIBUTE_SEPARATOR_SYMBOLS) if len(parts) < 2: raise InvalidInputReference('InputReference should at least contain "$(inputs.identifier)". The following input' 'reference does not comply with it:\n{}'.format(reference)) elif parts[0] != "inputs": raise InvalidInputReference('InputReference should at least contain "$(inputs.identifier)". The following input' ' reference does not comply with it:\n$({})'.format(reference)) else: input_identifier = parts[1] input_to_reference = inputs_to_reference.get(input_identifier) if input_to_reference is None: raise InvalidInputReference('Input identifier "{}" not found in inputs, but needed in input reference:\n{}' .format(input_identifier, reference)) elif isinstance(input_to_reference, dict): if 'files' in input_to_reference: return _resolve_file(parts[2:], input_to_reference, input_identifier, reference) elif 'directories' in input_to_reference: return _resolve_directory(parts[2:], input_to_reference, input_identifier, reference) else: raise InvalidInputReference('Unknown input type for input identifier "{}"'.format(input_identifier)) else: if len(parts) > 2: raise InvalidInputReference('Attribute "{}" of input reference "{}" could not be resolved' .format(parts[2], reference)) else: return parts[1] def resolve_input_references(to_resolve, inputs_to_reference): """ Resolves input references given in the string to_resolve by using the inputs_to_reference. See http://www.commonwl.org/user_guide/06-params/index.html for more information. Example: "$(inputs.my_file.nameroot).md" -> "filename.md" :param to_resolve: The path to match :param inputs_to_reference: Inputs which are used to resolve input references like $(inputs.my_input_file.basename). :return: A string in which the input references are replaced with actual values. """ splitted = split_input_references(to_resolve) result = [] for part in splitted: if is_input_reference(part): result.append(str(resolve_input_reference(part, inputs_to_reference))) else: result.append(part) return ''.join(result) PK!4$$cc_core/commons/mnt_core.pyimport os import sys import inspect import pkgutil from subprocess import Popen, PIPE CC_DIR = 'cc' MOD_DIR = os.path.join(CC_DIR, 'mod') LIB_DIR = os.path.join(CC_DIR, 'lib') def module_dependencies(modules): # additional modules modules = modules[:] try: import runpy modules.append(runpy) except ImportError: pass try: import keyword modules.append(keyword) except ImportError: pass try: import opcode modules.append(opcode) except ImportError: pass try: import sysconfig modules.append(sysconfig) except ImportError: pass try: import _sysconfigdata modules.append(_sysconfigdata) except ImportError: pass try: import _sysconfigdata_m modules.append(_sysconfigdata_m) except ImportError: pass # find modules recursively d = {} for m in modules: if not inspect.ismodule(m): raise Exception('Not a module: {}'.format(m)) try: source_path = inspect.getabsfile(m) except Exception: source_path = None d[m] = (False, source_path) _module_dependencies(d) source_paths = [source_path for _, (_, source_path) in d.items() if source_path is not None] # get packages of found modules all_packages = set([module_name for _, module_name, is_pkg in pkgutil.walk_packages(sys.path) if is_pkg]) required_packages = [m.__package__ for m in d if hasattr(m, '__package__') and m.__package__ in all_packages] # guess more package names for m in d: if hasattr(m, '__name__') and isinstance(m.__name__, str): split_name = m.__name__.split('.') for i in range(len(split_name) + 1): part = '.'.join(split_name[:i]) if part in all_packages: required_packages.append(part) required_packages = list(set(required_packages)) # get additional files (data or hidden modules) from packages site_source_dir = None for sys_path in sys.path: for loader, module_name, is_pkg in pkgutil.walk_packages([sys_path]): found_module = loader.find_module(module_name) try: source_path = inspect.getabsfile(found_module) except TypeError: module_dir = os.path.join(*module_name.split('.')) source_path = os.path.join(sys_path, module_dir) if os.path.isdir(source_path): source_dir = source_path else: source_dir, _ = os.path.split(source_path) if module_name == 'site': site_source_dir = source_dir if not (is_pkg and module_name in required_packages): continue for dir_path, _, file_names in os.walk(source_dir): is_pycache = False front = dir_path while True: front, back = os.path.split(front) if back == '__pycache__': is_pycache = True break elif not back: break if is_pycache: continue for file_name in file_names: source_paths.append(os.path.join(dir_path, file_name)) if site_source_dir is not None: source_paths += _site_files(site_source_dir) source_paths = list(set(source_paths)) # get C dependencies by filename c_source_paths = [source_path for source_path in source_paths if source_path.endswith('.so')] return source_paths, c_source_paths def _module_dependencies(d): candidates = {} for m, (checked, sp) in d.items(): if checked: continue d[m] = (True, sp) for key, obj in m.__dict__.items(): if not inspect.ismodule(obj): obj = inspect.getmodule(obj) if obj is None: continue if obj in d: continue try: source_path = inspect.getabsfile(obj) except Exception: source_path = None candidates[obj] = (False, source_path) for m, t in candidates.items(): d[m] = t for m, (checked, sp) in d.items(): if not checked: _module_dependencies(d) break def restore_original_environment(): for envvar in ['LD_LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME']: envvar_bak = '{}_BAK'.format(envvar) if envvar_bak in os.environ: os.environ[envvar] = os.environ[envvar_bak] del os.environ[envvar_bak] if not os.environ[envvar]: del os.environ[envvar] def interpreter_command(): return [ 'LD_LIBRARY_PATH_BAK=${LD_LIBRARY_PATH}', 'PYTHONPATH_BAK=${PYTHONPATH}', 'PYTHONHOME_BAK=${PYTHONHOME}', 'LD_LIBRARY_PATH={}'.format(os.path.join('/', LIB_DIR)), 'PYTHONPATH={}'.format( os.path.join('/', MOD_DIR) ), 'PYTHONHOME={}'.format(os.path.join('/', MOD_DIR)), os.path.join('/', LIB_DIR, 'ld.so'), os.path.join('/', LIB_DIR, 'python') ] def _site_files(site_source_dir): file_names = ['orig-prefix.txt', 'no-global-site-packages.txt'] result = [] for file_name in file_names: file_path = os.path.join(site_source_dir, file_name) if os.path.exists(file_path): result.append(file_path) return result def ldd(file_path): sp = Popen('ldd "{}"'.format(file_path), stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True) std_out, std_err = sp.communicate() return_code = sp.returncode if return_code != 0: raise Exception('External program ldd returned exit code {}: {}'.format(return_code, std_err)) result = {} for line in std_out.split('\n'): line = line.strip() if '=>' in line: name, path = line.split('=>') name = name.strip() if os.path.isabs(name): continue path = path.strip() path = path.split('(')[0].strip() result[name] = path elif line.startswith('/') and 'ld' in line: path = line.split('(')[0].strip() result['ld.so'] = path return result def interpreter_dependencies(c_source_paths): candidates = {} for source_path in c_source_paths: links = ldd(source_path) candidates = {**candidates, **links} d = {'python': (sys.executable, False)} for name, path in candidates.items(): if name not in d: d[name] = (path, False) _interpreter_dependencies(d) deps = {name: path for name, (path, _) in d.items()} libc_dir = _libc_dir(deps) if libc_dir is not None: additional_dependencies = _additional_dependencies_from(libc_dir) deps = {**deps, **additional_dependencies} return deps def _libc_dir(deps): for name, path in deps.items(): file_dir, file_name = os.path.split(path) if file_name.startswith('libc.so'): return file_dir def _additional_dependencies_from(libc_dir): file_patterns = ['libnss_dns.so', 'libresolv.so'] result = {} for file_name in os.listdir(libc_dir): file_path = os.path.join(libc_dir, file_name) if not os.path.isfile(file_path): continue for file_pattern in file_patterns: if file_name.startswith(file_pattern): result[file_name] = file_path return result def _interpreter_dependencies(d): candidates = {} for name, (path, checked) in d.items(): if checked: continue d[name] = (path, True) links = ldd(path) candidates = {**candidates, **links} found_new = False for name, path in candidates.items(): if name not in d: d[name] = (path, False) found_new = True if found_new: _interpreter_dependencies(d) def _dir_path_len(dir_path): i = 0 while True: front, back = os.path.split(dir_path) dir_path = front if not back: break i += 1 return i def module_destinations(source_paths, prefix='/'): sys_paths = [os.path.abspath(p) for p in sys.path if os.path.isdir(p)] mod_dir = os.path.join(prefix, MOD_DIR) result = [] for source_path in source_paths: common_path_size = -1 common_path = None for sys_path in sys_paths: cp = os.path.commonpath([source_path, sys_path]) cp_size = _dir_path_len(cp) if cp_size > common_path_size: common_path_size = cp_size common_path = cp rel_source_path = source_path[len(common_path):].lstrip('/') result.append([ os.path.realpath(source_path), os.path.join(mod_dir, rel_source_path) ]) return result def interpreter_destinations(dependencies, prefix='/'): lib_dir = os.path.join(prefix, LIB_DIR) result = [] for name, path in dependencies.items(): result.append([ os.path.realpath(path), os.path.join(lib_dir, name) ]) return result PK![:NNcc_core/commons/red.pyimport json import os import jsonschema import tempfile from jsonschema.exceptions import ValidationError from cc_core.commons.files import make_file_read_only, for_each_file from cc_core.commons.schemas.cwl import cwl_job_listing_schema from cc_core.commons.shell import execute from cc_core.version import RED_VERSION from cc_core.commons.cwl import URL_SCHEME_IDENTIFIER from cc_core.commons.schemas.red import red_schema from cc_core.commons.exceptions import ConnectorError, AccessValidationError, AccessError, ArgumentError, \ RedValidationError from cc_core.commons.exceptions import RedSpecificationError SEND_RECEIVE_SPEC_ARGS = ['access', 'internal'] SEND_RECEIVE_SPEC_KWARGS = [] SEND_RECEIVE_VALIDATE_SPEC_ARGS = ['access'] SEND_RECEIVE_VALIDATE_SPEC_KWARGS = [] SEND_RECEIVE_DIRECTORY_SPEC_ARGS = ['access', 'internal', 'listing'] SEND_RECEIVE_DIRECTORY_SPEC_KWARGS = [] SEND_RECEIVE_DIRECTORY_VALIDATE_SPEC_ARGS = ['access'] SEND_RECEIVE_DIRECTORY_VALIDATE_SPEC_KWARGS = [] class ConnectorManager: def __init__(self): self._successfully_received = [] @staticmethod def _cdata(connector_data): return connector_data['command'], connector_data['access'] @staticmethod def _execute_connector(connector_command, top_level_argument, *file_contents, listing=None): """ Executes a connector by executing the given connector_command. The content of args will be the content of the files handed to the connector cli. :param connector_command: The connector command to execute. :param top_level_argument: The top level command line argument for the connector cli. (Like 'receive' or 'send_validate') :param file_contents: A dict of information handed over to the connector cli. :param listing: A listing to provide to the connector cli. Will be ignored if None. :return: A tuple containing the return code of the connector and the stderr of the command as str. """ # create temp_files for every file_content temp_files = [] for file_content in file_contents: if file_content is None: continue tmp_file = tempfile.NamedTemporaryFile('w') json.dump(file_content, tmp_file) tmp_file.flush() temp_files.append(tmp_file) tmp_listing_file = None if listing: tmp_listing_file = tempfile.NamedTemporaryFile('w') json.dump(listing, tmp_listing_file) tmp_listing_file.flush() command = [connector_command, top_level_argument] command.extend([t.name for t in temp_files]) if tmp_listing_file: command.append('--listing {}'.format(tmp_listing_file.name)) result = execute(' '.join(command)) # close temp_files for temp_file in temp_files: temp_file.close() if tmp_listing_file: tmp_listing_file.close() return result['returnCode'], result['stdErr'] def receive_validate(self, connector_data, input_key): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'receive-validate', access) if return_code != 0: raise AccessValidationError('invalid access data for input file "{}". Failed with the following message:\n' '{}'.format(input_key, str(std_err))) def receive_directory_validate(self, connector_data, input_key): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'receive-directory-validate', access) if return_code != 0: raise AccessValidationError('invalid access data for input directory "{}". Failed with the following ' 'message:\n{}'.format(input_key, str(std_err))) def send_validate(self, connector_data, output_key): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'send-validate', access) if return_code != 0: raise AccessValidationError('invalid access data for output file "{}". Failed with the following message:\n' '{}'.format(output_key, str(std_err))) def send_directory_validate(self, connector_data, output_key): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'send-directory-validate', access) if return_code != 0: raise AccessValidationError('invalid access data for output directory "{}". Failed with the following ' 'message:\n{}'.format(output_key, str(std_err))) def receive(self, connector_data, input_key, internal): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'receive', access, internal) if return_code != 0: raise AccessError('invalid access data for input file "{}". Failed with the following message:\n' '{}'.format(input_key, str(std_err))) else: self._successfully_received.append(input_key) make_file_read_only(internal[URL_SCHEME_IDENTIFIER]) @staticmethod def directory_listing_content_check(directory_path, listing): """ Checks if a given listing is present under the given directory path. :param directory_path: The path to the base directory :param listing: The listing to check :return: None if no errors could be found, otherwise a string describing the error """ if listing: for sub in listing: path = os.path.join(directory_path, sub['basename']) if sub['class'] == 'File': if not os.path.isfile(path): return 'listing contains "{}" but this file could not be found on disk.'.format(path) elif sub['class'] == 'Directory': if not os.path.isdir(path): return 'listing contains "{}" but this directory could not be found on disk'.format(path) listing = sub.get('listing') if listing: return ConnectorManager.directory_listing_content_check(path, listing) return None def receive_directory(self, connector_data, input_key, internal, listing=None): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'receive-directory', access, internal, listing=listing) if return_code != 0: raise AccessError('invalid access data for input directory "{}". Failed with the following ' 'message:\n{}'.format(input_key, str(std_err))) else: self._successfully_received.append(input_key) directory_path = internal[URL_SCHEME_IDENTIFIER] error = ConnectorManager.directory_listing_content_check(directory_path, listing) if error: raise ConnectorError('The listing of input directory "{}" is not fulfilled:\n{}'.format(input_key, error)) for_each_file(directory_path, make_file_read_only) def send(self, connector_data, output_key, internal): connector_command, access = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'send', access, internal) if return_code != 0: raise AccessValidationError('invalid access data for output file "{}". Failed with the following message:\n' '{}'.format(output_key, str(std_err))) def receive_cleanup(self, connector_data, input_key, internal): if input_key not in self._successfully_received: return connector_command, _ = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'receive-cleanup', internal) if return_code != 0: raise AccessError('cleanup for input file "{}" failed:\n' '{}'.format(input_key, str(std_err))) def receive_directory_cleanup(self, connector_data, input_key, internal): if input_key not in self._successfully_received: return connector_command, _ = self._cdata(connector_data) return_code, std_err = ConnectorManager._execute_connector(connector_command, 'receive-directory-cleanup', internal) if return_code != 0: raise AccessError('cleanup for input directory "{}" failed:\n' '{}'.format(input_key, str(std_err))) def _red_listing_validation(key, listing): """ Raises an RedValidationError, if the given listing does not comply with cwl_job_listing_schema. If listing is None or an empty list, no exception is thrown. :param key: The input key to build an error message if needed. :param listing: The listing to validate :raise RedValidationError: If the given listing does not comply with cwl_job_listing_schema """ if listing: try: jsonschema.validate(listing, cwl_job_listing_schema) except ValidationError as e: raise RedValidationError('REDFILE listing of input "{}" does not comply with jsonschema: {}' .format(key, e.context)) def red_get_mount_connectors_from_inputs(inputs): keys = [] for input_key, arg in inputs.items(): arg_items = [] if isinstance(arg, dict): arg_items.append(arg) elif isinstance(arg, list): arg_items += [i for i in arg if isinstance(i, dict)] for i in arg_items: connector_data = i['connector'] if connector_data.get('mount'): keys.append(input_key) return keys def red_get_mount_connectors_from_outputs(outputs): keys = [] for output_key, arg in outputs.items(): if not isinstance(arg, dict): continue connector_data = arg['connector'] if connector_data.get('mount'): keys.append(output_key) return keys def red_get_mount_connectors(red_data, ignore_outputs): """ Returns a list of mounting connectors :param red_data: The red data to be searched :param ignore_outputs: If outputs should be ignored :return: A list of connectors with active mount option. """ keys = [] batches = red_data.get('batches') inputs = red_data.get('inputs') if batches: for batch in batches: keys.extend(red_get_mount_connectors_from_inputs(batch['inputs'])) elif inputs: keys.extend(red_get_mount_connectors_from_inputs(inputs)) if not ignore_outputs: outputs = red_data.get('outputs') if batches: for batch in batches: batch_outputs = batch.get('outputs') if batch_outputs: keys.extend(red_get_mount_connectors_from_outputs(batch_outputs)) elif outputs: keys.extend(red_get_mount_connectors_from_outputs(outputs)) return keys def red_validation(red_data, ignore_outputs, container_requirement=False): try: jsonschema.validate(red_data, red_schema) except ValidationError as e: raise RedValidationError('REDFILE does not comply with jsonschema: {}'.format(e.context)) if not red_data['redVersion'] == RED_VERSION: raise RedSpecificationError( 'red version "{}" specified in REDFILE is not compatible with red version "{}" of cc-faice'.format( red_data['redVersion'], RED_VERSION ) ) if 'batches' in red_data: for batch in red_data['batches']: for key, val in batch['inputs'].items(): if key not in red_data['cli']['inputs']: raise RedSpecificationError('red inputs argument "{}" is not specified in cwl'.format(key)) if isinstance(val, dict) and 'listing' in val: _red_listing_validation(key, val['listing']) if not ignore_outputs and batch.get('outputs'): for key, val in batch['outputs'].items(): if key not in red_data['cli']['outputs']: raise RedSpecificationError('red outputs argument "{}" is not specified in cwl'.format(key)) else: for key, val in red_data['inputs'].items(): if key not in red_data['cli']['inputs']: raise RedSpecificationError('red inputs argument "{}" is not specified in cwl'.format(key)) if isinstance(val, dict) and 'listing' in val: _red_listing_validation(key, val['listing']) if not ignore_outputs and red_data.get('outputs'): for key, val in red_data['outputs'].items(): if key not in red_data['cli']['outputs']: raise RedSpecificationError('red outputs argument "{}" is not specified in cwl'.format(key)) if container_requirement: if not red_data.get('container'): raise RedSpecificationError('container engine description is missing in REDFILE') def convert_batch_experiment(red_data, batch): if 'batches' not in red_data: return red_data if batch is None: raise ArgumentError('batches are specified in REDFILE, but --batch argument is missing') try: batch_data = red_data['batches'][batch] except: raise ArgumentError('invalid batch index provided by --batch argument') result = {key: val for key, val in red_data.items() if not key == 'batches'} result['inputs'] = batch_data['inputs'] if batch_data.get('outputs'): result['outputs'] = batch_data['outputs'] return result def import_and_validate_connectors(connector_manager, red_data, ignore_outputs): for input_key, arg in red_data['inputs'].items(): arg_items = [] if isinstance(arg, dict): arg_items.append(arg) elif isinstance(arg, list): arg_items += [i for i in arg if isinstance(i, dict)] for i in arg_items: connector_class = i['class'] connector_data = i['connector'] if connector_class == 'File': connector_manager.receive_validate(connector_data, input_key) elif connector_class == 'Directory': connector_manager.receive_directory_validate(connector_data, input_key) else: raise ConnectorError('Unsupported class for connector object: "{}"'.format(connector_class)) if not ignore_outputs and red_data.get('outputs'): for output_key, arg in red_data['outputs'].items(): if not isinstance(arg, dict): continue connector_data = arg['connector'] connector_manager.send_validate(connector_data, output_key) def inputs_to_job(red_data, tmp_dir): job = {} for key, arg in red_data['inputs'].items(): val = arg if isinstance(arg, list): val = [] for index, i in enumerate(arg): if isinstance(i, dict): path = os.path.join(tmp_dir, '{}_{}'.format(key, index)) val.append({ 'class': i['class'], URL_SCHEME_IDENTIFIER: path }) else: val.append(i) elif isinstance(arg, dict): path = os.path.join(tmp_dir, key) val = { 'class': arg['class'], URL_SCHEME_IDENTIFIER: path } job[key] = val return job def receive(connector_manager, red_data, tmp_dir): for key, arg in red_data['inputs'].items(): val = arg if isinstance(arg, list): for index, i in enumerate(arg): if not isinstance(i, dict): continue # connector_class should be one of 'File' or 'Directory' connector_class = i['class'] input_key = '{}_{}'.format(key, index) path = os.path.join(tmp_dir, input_key) connector_data = i['connector'] internal = {URL_SCHEME_IDENTIFIER: path} if connector_class == 'File': connector_manager.receive(connector_data, input_key, internal) elif connector_class == 'Directory': listing = i.get('listing') connector_manager.receive_directory(connector_data, input_key, internal, listing) elif isinstance(arg, dict): # connector_class should be one of 'File' or 'Directory' connector_class = arg['class'] input_key = key path = os.path.join(tmp_dir, input_key) connector_data = val['connector'] internal = {URL_SCHEME_IDENTIFIER: path} if connector_class == 'File': connector_manager.receive(connector_data, input_key, internal) elif connector_class == 'Directory': listing = arg.get('listing') connector_manager.receive_directory(connector_data, input_key, internal, listing) def cleanup(connector_manager, red_data, tmp_dir): """ Invokes the cleanup functions for all inputs. """ for key, arg in red_data['inputs'].items(): val = arg if isinstance(arg, list): for index, i in enumerate(arg): if not isinstance(i, dict): continue # connector_class should be one of 'File' or 'Directory' connector_class = i['class'] input_key = '{}_{}'.format(key, index) path = os.path.join(tmp_dir, input_key) connector_data = i['connector'] internal = {URL_SCHEME_IDENTIFIER: path} if connector_class == 'File': connector_manager.receive_cleanup(connector_data, input_key, internal) elif connector_class == 'Directory': connector_manager.receive_directory_cleanup(connector_data, input_key, internal) elif isinstance(arg, dict): # connector_class should be one of 'File' or 'Directory' connector_class = arg['class'] input_key = key path = os.path.join(tmp_dir, input_key) connector_data = val['connector'] internal = {URL_SCHEME_IDENTIFIER: path} if connector_class == 'File': connector_manager.receive_cleanup(connector_data, input_key, internal) elif connector_class == 'Directory': connector_manager.receive_directory_cleanup(connector_data, input_key, internal) try: os.rmdir(tmp_dir) except (OSError, FileNotFoundError): # Maybe, raise a warning here, because not all connectors have cleaned up their contents correctly. pass def send(connector_manager, output_files, red_data, agency_data=None): for key, arg in red_data['outputs'].items(): path = output_files[key][URL_SCHEME_IDENTIFIER] internal = { URL_SCHEME_IDENTIFIER: path, 'agencyData': agency_data } connector_data = arg['connector'] connector_manager.send(connector_data, key, internal) PK!G.cc_core/commons/schema_map.pyfrom collections import OrderedDict from cc_core.commons.schemas.red import red_schema, fill_schema from cc_core.commons.schemas.cwl import cwl_schema, cwl_job_schema, cwl_job_listing_schema from cc_core.commons.schemas.engines.container import container_engines from cc_core.commons.schemas.engines.execution import execution_engines schemas = OrderedDict([ ('cwl', cwl_schema), ('cwl-job', cwl_job_schema), ('red', red_schema), ('fill', fill_schema), ('listing', cwl_job_listing_schema) ]) for e, s in container_engines.items(): schemas['red-engine-container-{}'.format(e)] = s for e, s in execution_engines.items(): schemas['red-engine-execution-{}'.format(e)] = s PK!#cc_core/commons/schemas/__init__.pyPK!R !cc_core/commons/schemas/common.pypattern_key = '^[a-zA-Z0-9_-]+$' auth_schema = { 'oneOf': [{ 'type': 'object', 'properties': { 'username': {'type': 'string'}, 'password': {'type': 'string'} }, 'additionalProperties': False, 'required': ['username', 'password'] }, { 'type': 'object', 'properties': { '_username': {'type': 'string'}, 'password': {'type': 'string'} }, 'additionalProperties': False, 'required': ['_username', 'password'] }, { 'type': 'object', 'properties': { 'username': {'type': 'string'}, '_password': {'type': 'string'} }, 'additionalProperties': False, 'required': ['username', '_password'] }, { 'type': 'object', 'properties': { '_username': {'type': 'string'}, '_password': {'type': 'string'} }, 'additionalProperties': False, 'required': ['_username', '_password'] }] } PK!0:{wZZcc_core/commons/schemas/cwl.pyfrom cc_core.commons.schemas.common import pattern_key URL_SCHEME_IDENTIFIER = 'path' CWL_INPUT_TYPES = ['File', 'Directory', 'string', 'int', 'long', 'float', 'double', 'boolean'] CWL_INPUT_TYPES += ['{}[]'.format(t) for t in CWL_INPUT_TYPES[:-1]] CWL_INPUT_TYPES += ['{}?'.format(t) for t in CWL_INPUT_TYPES[:]] CWL_OUTPUT_TYPES = ['File', 'Directory'] CWL_OUTPUT_TYPES += ['{}?'.format(t) for t in CWL_OUTPUT_TYPES[:]] cwl_schema = { 'type': 'object', 'properties': { 'cwlVersion': {'type': ['string', 'number']}, 'class': {'enum': ['CommandLineTool']}, 'baseCommand': { 'oneOf': [ {'type': 'string'}, { 'type': 'array', 'items': {'type': 'string'} } ] }, 'doc': {'type': 'string'}, 'requirements': { 'type': 'object', 'properties': { 'DockerRequirement': { 'type': 'object', 'properties': { 'dockerPull': {'type': 'string'} }, 'additionalProperties': False, 'required': ['dockerPull'] } }, 'additionalProperties': False }, 'inputs': { 'type': 'object', 'patternProperties': { pattern_key: { 'type': 'object', 'properties': { 'type': {'enum': CWL_INPUT_TYPES}, 'inputBinding': { 'type': 'object', 'properties': { 'prefix': {'type': 'string'}, 'separate': {'type': 'boolean'}, 'position': {'type': 'integer', 'minimum': 0}, 'itemSeparator': {'type': 'string'} }, 'additionalProperties': False, }, 'doc': {'type': 'string'} }, 'additionalProperties': False, 'required': ['type', 'inputBinding'] } } }, 'outputs': { 'type': 'object', 'patternProperties': { pattern_key: { 'type': 'object', 'properties': { 'type': {'enum': CWL_OUTPUT_TYPES}, 'outputBinding': { 'type': 'object', 'properties': { 'glob': {'type': 'string'}, }, 'additionalProperties': False, 'required': ['glob'] }, 'doc': {'type': 'string'} }, 'additionalProperties': False, 'required': ['type', 'outputBinding'] } } } }, 'additionalProperties': False, 'required': ['cwlVersion', 'class', 'baseCommand', 'inputs', 'outputs'] } _file_location_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['File']}, 'location': {'type': 'string'} }, 'additionalProperties': False, 'required': ['class', 'location'] } _file_path_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['File']}, URL_SCHEME_IDENTIFIER: {'type': 'string'} }, 'additionalProperties': False, 'required': ['class', URL_SCHEME_IDENTIFIER] } _directory_location_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['Directory']}, 'location': {'type': 'string'}, 'listing': {'type': 'array'} }, 'additionalProperties': False, 'required': ['class', 'location'] } _directory_path_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['Directory']}, URL_SCHEME_IDENTIFIER: {'type': 'string'}, 'listing': {'type': 'array'} }, 'additionalProperties': False, 'required': ['class', URL_SCHEME_IDENTIFIER] } cwl_job_schema = { 'type': 'object', 'patternProperties': { pattern_key: { 'anyOf': [ {'type': 'string'}, {'type': 'number'}, {'type': 'boolean'}, _file_location_schema, _file_path_schema, _directory_location_schema, _directory_path_schema, { 'type': 'array', 'items': { 'oneOf': [ {'type': 'string'}, {'type': 'number'}, _file_location_schema, _file_path_schema, _directory_location_schema, _directory_path_schema ] } } ] } } } listing_sub_file_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['File']}, 'basename': {'type': 'string'}, }, 'required': ['class', 'basename'], 'additionalProperties': False } listing_sub_directory_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['Directory']}, 'basename': {'type': 'string'}, 'listing': {'$ref': '#/'} }, 'additionalProperties': False, 'required': ['class', 'basename'] } # WARNING: Do not embed this schema into another schema, # because this breaks the '$ref' in listing_sub_directory_schema cwl_job_listing_schema = { 'type': 'array', 'items': { 'oneOf': [listing_sub_file_schema, listing_sub_directory_schema] } } PK!+cc_core/commons/schemas/engines/__init__.pyPK!Pk,cc_core/commons/schemas/engines/container.pyfrom cc_core.commons.schemas.common import auth_schema MIN_RAM_LIMIT = 256 gpus_schema = { 'oneOf': [{ 'type': 'array', 'items': { 'type': 'object', 'properties': { 'minVram': {'type': 'integer', 'minimum': MIN_RAM_LIMIT} }, 'additionalProperties': False } }, { 'type': 'object', 'properties': { 'count': {'type': 'integer'} }, 'additionalProperties': False, 'required': ['count'] }] } image_schema = { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'url': {'type': 'string'}, 'auth': auth_schema, 'source': { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'url': {'type': 'string'} }, 'additionalProperties': False, 'required': ['url'] } }, 'additionalProperties': False, 'required': ['url'] } docker_schema = { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'version': {'type': 'string'}, 'image': image_schema, 'ram': {'type': 'integer', 'minimum': MIN_RAM_LIMIT} }, 'additionalProperties': False, 'required': ['image'] } nvidia_docker_schema = { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'version': {'type': 'string'}, 'image': image_schema, 'gpus': gpus_schema, 'ram': {'type': 'integer', 'minimum': MIN_RAM_LIMIT} }, 'additionalProperties': False, 'required': ['image', 'gpus'] } container_engines = { 'docker': docker_schema, 'nvidia-docker': nvidia_docker_schema } PK!,4,cc_core/commons/schemas/engines/execution.pyfrom cc_core.commons.schemas.common import auth_schema ccfaice_schema = { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'insecure': {'type': 'boolean'} }, 'additionalProperties': False } ccagency_schema = { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'access': { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'url': {'type': 'string'}, 'auth': auth_schema }, 'additionalProperties': False, 'required': ['url'] }, 'retryIfFailed': {'type': 'boolean'}, 'batchConcurrencyLimit': {'type': 'integer', 'minimum': 1} # disablePull might be data breach, if another users image has been pulled to host already # 'disablePull': {'type': 'boolean'} }, 'additionalProperties': False } execution_engines = { 'ccfaice': ccfaice_schema, 'ccagency': ccagency_schema } PK!;M  cc_core/commons/schemas/red.pyimport copy from cc_core.commons.schemas.common import pattern_key from cc_core.commons.schemas.cwl import cwl_schema _connector_schema = { 'type': 'object', 'properties': { 'command': {'type': 'string'}, 'access': {'type': 'object'}, 'mount': {'type': 'boolean'} }, 'additionalProperties': False, 'required': ['command', 'access'] } _file_schema = { 'type': 'object', 'properties': { 'class': {'enum': ['File']}, 'connector': _connector_schema }, 'additionalProperties': False, 'required': ['class', 'connector'] } _directory_schema = copy.deepcopy(_file_schema) _directory_schema['properties']['class']['enum'] = ['Directory'] _directory_schema['properties']['listing'] = {'type': 'array'} _inputs_schema = { 'type': 'object', 'patternProperties': { pattern_key: { 'anyOf': [ {'type': 'string'}, {'type': 'number'}, {'type': 'boolean'}, { 'type': 'array', 'items': { 'oneOf': [ {'type': 'string'}, {'type': 'number'}, _file_schema, _directory_schema ] } }, _file_schema, _directory_schema ] } }, 'additionalProperties': False } _outputs_schema = { 'type': 'object', 'patternProperties': { pattern_key: { 'type': 'object', 'properties': { 'class': {'enum': ['File']}, 'connector': _connector_schema }, 'additionalProperties': False, 'required': ['class', 'connector'] } }, 'additionalProperties': False } _engine_schema = { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'engine': {'type': 'string'}, 'settings': {'type': 'object'} }, 'additionalProperties': False, 'required': ['engine', 'settings'] } # Reproducible Experiment Description (RED) red_schema = { 'oneOf': [{ 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'redVersion': {'type': 'string'}, 'cli': cwl_schema, 'inputs': _inputs_schema, 'outputs': _outputs_schema, 'container': _engine_schema, 'execution': _engine_schema }, 'additionalProperties': False, 'required': ['redVersion', 'cli', 'inputs'] }, { 'type': 'object', 'properties': { 'doc': {'type': 'string'}, 'redVersion': {'type': 'string'}, 'cli': cwl_schema, 'batches': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'inputs': _inputs_schema, 'outputs': _outputs_schema }, 'additionalProperties': False, 'required': ['inputs'] } }, 'container': _engine_schema, 'execution': _engine_schema }, 'additionalProperties': False, 'required': ['redVersion', 'cli', 'batches'] }] } fill_schema = { 'type': 'object', 'patternProperties': { pattern_key: {'type': 'string'} }, 'additionalProperties': False } PK!Xq_ cc_core/commons/shell.pyimport os from subprocess import Popen, PIPE from threading import Thread from psutil import Process from time import sleep from threading import Lock from time import time from cc_core.commons.exceptions import JobExecutionError SUPERVISION_INTERVAL_SECONDS = 1 def prepare_outdir(outdir): """ Creates the output directory if not existing. If outdir is None or if no output_files are provided nothing happens. :param outdir: The output directory to create. """ if outdir: outdir = os.path.expanduser(outdir) if not os.path.isdir(outdir): try: os.makedirs(outdir) except os.error as e: raise JobExecutionError('Failed to create outdir "{}".\n{}'.format(outdir, str(e))) def execute(command): try: sp = Popen(command, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, encoding='utf-8') except TypeError: sp = Popen(command, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True) monitor = ProcessMonitor(sp) t = Thread(target=monitor.start) t.start() std_out, std_err = sp.communicate() return_code = sp.returncode monitoring_data = monitor.result() return { 'stdOut': [l for l in std_out.split(os.linesep) if l], 'stdErr': [l for l in std_err.split(os.linesep) if l], 'returnCode': return_code, 'monitoring': monitoring_data } def shell_result_check(process_data): if process_data['returnCode'] != 0: raise JobExecutionError('process returned non-zero exit code "{}"\nProcess stderr:\n{}' .format(process_data['returnCode'], process_data['stdErr'])) class ProcessMonitor: def __init__(self, process): self.process = process self.max_vms_memory = 0 self.max_rss_memory = 0 self.lock = Lock() self.timestamp = time() def start(self): # source: http://stackoverflow.com/a/13607392 while True: try: pp = Process(self.process.pid) processes = list(pp.children(recursive=True)) processes.append(pp) vms_memory = 0 rss_memory = 0 for p in processes: try: mem_info = p.memory_info() rss_memory += mem_info[0] vms_memory += mem_info[1] except: pass with self.lock: self.max_vms_memory = max(self.max_vms_memory, vms_memory) self.max_rss_memory = max(self.max_rss_memory, rss_memory) except: break sleep(SUPERVISION_INTERVAL_SECONDS) def result(self): with self.lock: return { 'maxVMSMemory': self.max_vms_memory / (1024 * 1024), 'maxRSSMemory': self.max_rss_memory / (1024 * 1024), 'wallTime': time() - self.timestamp } PK!2ޭcc_core/commons/templates.pyimport jsonschema from getpass import getpass from collections import OrderedDict from cc_core.commons.files import wrapped_print from cc_core.commons.schemas.red import fill_schema from cc_core.commons.exceptions import RedValidationError, RedVariablesError def fill_validation(fill_data): try: jsonschema.validate(fill_data, fill_schema) except Exception: raise RedValidationError('FILL_FILE does not comply with jsonschema') def _find_undeclared_recursively(data, template_key_is_protected, protected_values, allowed_section): if isinstance(data, dict): for key, val in data.items(): if allowed_section and key.startswith('_'): if len(key) == 1: raise RedValidationError('dict key _ is invalid') if key[1:] in data: raise RedValidationError('key {} and key {} cannot be in one dict'.format(key, key[1:])) if not isinstance(val, str): raise RedValidationError('protecting dict keys with _ is only valid for string values') if val.startswith('{{') and val.endswith('}}'): if len(val) == 4: raise RedValidationError('string template value inside double curly braces must not be empty') template_key_is_protected[val[2:-2]] = True else: protected_values.update([val]) elif allowed_section and key == 'password': if not isinstance(val, str): raise RedValidationError('dict key password is only valid for string value') if val.startswith('{{') and val.endswith('}}'): if len(val) == 4: raise RedValidationError('string template value inside double curly braces must not be empty') template_key_is_protected[val[2:-2]] = True else: protected_values.update([val]) elif key in ['access', 'auth']: _find_undeclared_recursively(val, template_key_is_protected, protected_values, True) else: _find_undeclared_recursively(val, template_key_is_protected, protected_values, allowed_section) elif isinstance(data, list): for val in data: _find_undeclared_recursively(val, template_key_is_protected, protected_values, allowed_section) elif isinstance(data, str): if data.startswith('{{') and data.endswith('}}'): if len(data) == 4: raise RedValidationError('string template value inside double curly braces must not be empty') template_key = data[2:-2] if template_key not in template_key_is_protected: template_key_is_protected[template_key] = False def inspect_templates_and_secrets(data, fill_data, non_interactive): template_key_is_protected = OrderedDict() protected_values = set() _find_undeclared_recursively(data, template_key_is_protected, protected_values, False) template_keys_and_values = {} undeclared_template_key_is_protected = {} fill_data = fill_data or {} for key, is_protected in template_key_is_protected.items(): if key in fill_data: value = fill_data[key] template_keys_and_values[key] = value if is_protected: protected_values.update([value]) else: undeclared_template_key_is_protected[key] = is_protected incomplete_variables_file = False if undeclared_template_key_is_protected: if non_interactive: raise RedVariablesError('RED_FILE contains undeclared template variables: {}'.format( list(undeclared_template_key_is_protected.keys()) )) incomplete_variables_file = True out = [ 'RED_FILE contains the following undeclared template variables:' ] out += [ '{} (protected)'.format(key) if is_protected else '{}'.format(key) for key, is_protected in undeclared_template_key_is_protected.items() ] out += [ '', 'Set variables interactively...', '' ] wrapped_print(out) for key, is_protected in undeclared_template_key_is_protected.items(): if is_protected: value = getpass('{} (protected): '.format(key)) template_keys_and_values[key] = value protected_values.update([value]) else: value = input('{}: '.format(key)) template_keys_and_values[key] = value return template_keys_and_values, protected_values, incomplete_variables_file def _fill_recursively(data, template_keys_and_values, allowed_section, remove_underscores): if isinstance(data, dict): result = {} for key, val in data.items(): if allowed_section and remove_underscores and key.startswith('_'): result[key[1:]] = _fill_recursively(val, template_keys_and_values, allowed_section, remove_underscores) elif key in ['access', 'auth']: result[key] = _fill_recursively(val, template_keys_and_values, True, remove_underscores) else: result[key] = _fill_recursively(val, template_keys_and_values, allowed_section, remove_underscores) return result elif isinstance(data, list): return [_fill_recursively(val, template_keys_and_values, allowed_section, remove_underscores) for val in data] elif isinstance(data, str): if data.startswith('{{') and data.endswith('}}'): return template_keys_and_values[data[2:-2]] return data def fill_template(data, template_keys_and_values, allowed_section, remove_underscores): return _fill_recursively(data, template_keys_and_values, allowed_section, remove_underscores) PK!cc_core/version.pyRED_VERSION = '6' CC_VERSION = '1' PACKAGE_VERSION = '1' VERSION = '{}.{}.{}'.format(RED_VERSION, CC_VERSION, PACKAGE_VERSION) PK!Hi/3(cc_core-6.1.1.dist-info/entry_points.txtN+I/N.,()JNNLO+MNO/Jr3@PK!ۆۆcc_core-6.1.1.dist-info/LICENSE GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . PK!HnHTUcc_core-6.1.1.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H cc_core-6.1.1.dist-info/METADATAT]oH}R^@TKvIٮZ0i<38k;IU}szpÿ:itX7 #"bh.o =DaLvrn=-!.4hϥ&0|E}|/t RFö=Ϥ?X0b+JWruR*w՟7` U:he԰_ ş30̉)E~gBř`!jGrX'>5ZS~0̞Ym#p6%[!-py y[g}R3J$}"x3Q^Vr-[H &t{ƵfgRR`"DuӛY͈7#oF Wg)߱Az|閻ˬt9-1x+:u"[beUa^v`q{h=NN0ښC>%:ae^.TX. M~>46-]b:N=&AU$i-^ߗĈTP6~ xr#q>dW==f&T/(ɞ݆v'>@JCMեI@dP7rEas"FD\IMj+1h :#\>iL<:&-t(Vk;NsTRC r+RhĜǣx6Pt7atPa!fb={MfagϠY!R/PK!HeH  cc_core-6.1.1.dist-info/RECORDX~` %,ރ~T}u$ՋoEA o)u;0f!%jI+MoÖ}a2s >8G7)Lf#y Jf l@\وͲƵSzW ͬYt Wy ~MPzR:ik]k8<ٷ/m8 ~,rxRx; CV6KDJL^גs_7 ^!L.yڎQ*CJP"rO[()HدW0Hex́Icrc?S_3i;m2 Zg"ؽ (__h}u|(F$2\.ng޵=O'lj^`І?KϧA;49C<u{}/>?Ziv NnǖBW-7Vu#@Q[m3?Qu{"u(֚khf|UNI̒2]É4f\Ő(~g 8q&VH wxEsbO&+hkB'0Mc/nҼPұZAlF_̬5vY`oQMz„>rc\8G|&'ŝ{#@FML(1]ُr?T3CК Eg9He;Q8L}a?n$kQrJu."l[IV'#>#󦛧`x^`8R\jH6yrRɩ.ҳO.qW !u3x=j 8:V1!\P K3klLWh }ܣףLY'H"Յ$,[LxE b$~eq>{--:&Wy%Tգ }D-v%-vfxGBca⋔ӞȰ~ݪh jp2(Nc,^[jjtiZw ^w9;(-ߑY64P ߀S\wU8}34]RIku KKX>==F_a\YչI1˒\s] Pj6]0c@|8M٫i؃͛i6m$YC$]-&n96Ӣ xRL8KQ~85,$nδHIs|<]WAo"Yp92K' jjdW1ouCQG|^(̓`3