sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _find_files(directory): """ Find XML files in the directory """ pattern = "{directory}/*.xml".format( directory=directory, ) files = glob(pattern) return files
Find XML files in the directory
entailment
def workbench_scenarios(cls): """ Gather scenarios to be displayed in the workbench """ module = cls.__module__ module = module.split('.')[0] directory = pkg_resources.resource_filename(module, 'scenarios') files = _find_files(directory) scenarios = _read_files(files) return scenarios
Gather scenarios to be displayed in the workbench
entailment
def _set_session(): """ Sets global __SESSION and __USER_ID if they haven't been set """ global __SESSION global __USER_ID if __SESSION is None: try: __SESSION = AuthorizedSession(google.auth.default(['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'])[0]) health() __USER_ID = id_token.verify_oauth2_token(__SESSION.credentials.id_token, Request(session=__SESSION))['email'] except (DefaultCredentialsError, RefreshError) as gae: if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): raise logging.warning("Unable to determine/refresh application credentials") try: subprocess.check_call(['gcloud', 'auth', 'application-default', 'login', '--no-launch-browser']) __SESSION = AuthorizedSession(google.auth.default(['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'])[0]) except subprocess.CalledProcessError as cpe: if cpe.returncode < 0: logging.exception("%s was terminated by signal %d", cpe.cmd, -cpe.returncode) else: logging.exception("%s returned %d", cpe.cmd, cpe.returncode) raise gae
Sets global __SESSION and __USER_ID if they haven't been set
entailment
def _fiss_agent_header(headers=None): """ Return request headers for fiss. Inserts FISS as the User-Agent. Initializes __SESSION if it hasn't been set. Args: headers (dict): Include additional headers as key-value pairs """ _set_session() fiss_headers = {"User-Agent" : FISS_USER_AGENT} if headers is not None: fiss_headers.update(headers) return fiss_headers
Return request headers for fiss. Inserts FISS as the User-Agent. Initializes __SESSION if it hasn't been set. Args: headers (dict): Include additional headers as key-value pairs
entailment
def _check_response_code(response, codes): """ Throws an exception if the http response is not expected. Can check single integer or list of valid responses. Example usage: >>> r = api.get_workspace("broad-firecloud-testing", "Fake-Bucket") >>> _check_response_code(r, 200) ... FireCloudServerError ... """ if type(codes) == int: codes = [codes] if response.status_code not in codes: raise FireCloudServerError(response.status_code, response.content)
Throws an exception if the http response is not expected. Can check single integer or list of valid responses. Example usage: >>> r = api.get_workspace("broad-firecloud-testing", "Fake-Bucket") >>> _check_response_code(r, 200) ... FireCloudServerError ...
entailment
def list_entity_types(namespace, workspace): """List the entity types present in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Entities/getEntityTypes """ headers = _fiss_agent_header({"Content-type": "application/json"}) uri = "workspaces/{0}/{1}/entities".format(namespace, workspace) return __get(uri, headers=headers)
List the entity types present in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Entities/getEntityTypes
entailment
def upload_entities(namespace, workspace, entity_data): """Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities """ body = urlencode({"entities" : entity_data}) headers = _fiss_agent_header({ 'Content-type': "application/x-www-form-urlencoded" }) uri = "workspaces/{0}/{1}/importEntities".format(namespace, workspace) return __post(uri, headers=headers, data=body)
Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities
entailment
def upload_entities_tsv(namespace, workspace, entities_tsv): """Upload entities from a tsv loadfile. File-based wrapper for api.upload_entities(). A loadfile is a tab-separated text file with a header row describing entity type and attribute names, followed by rows of entities and their attribute values. Ex: entity:participant_id age alive participant_23 25 Y participant_27 35 N Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entities_tsv (file): FireCloud loadfile, see format above """ if isinstance(entities_tsv, string_types): with open(entities_tsv, "r") as tsv: entity_data = tsv.read() elif isinstance(entities_tsv, io.StringIO): entity_data = entities_tsv.getvalue() else: raise ValueError('Unsupported input type.') return upload_entities(namespace, workspace, entity_data)
Upload entities from a tsv loadfile. File-based wrapper for api.upload_entities(). A loadfile is a tab-separated text file with a header row describing entity type and attribute names, followed by rows of entities and their attribute values. Ex: entity:participant_id age alive participant_23 25 Y participant_27 35 N Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entities_tsv (file): FireCloud loadfile, see format above
entailment
def copy_entities(from_namespace, from_workspace, to_namespace, to_workspace, etype, enames, link_existing_entities=False): """Copy entities between workspaces Args: from_namespace (str): project (namespace) to which source workspace belongs from_workspace (str): Source workspace name to_namespace (str): project (namespace) to which target workspace belongs to_workspace (str): Target workspace name etype (str): Entity type enames (list(str)): List of entity names to copy link_existing_entities (boolean): Link all soft conflicts to the entities that already exist. Swagger: https://api.firecloud.org/#!/Entities/copyEntities """ uri = "workspaces/{0}/{1}/entities/copy".format(to_namespace, to_workspace) body = { "sourceWorkspace": { "namespace": from_namespace, "name": from_workspace }, "entityType": etype, "entityNames": enames } return __post(uri, json=body, params={'linkExistingEntities': str(link_existing_entities).lower()})
Copy entities between workspaces Args: from_namespace (str): project (namespace) to which source workspace belongs from_workspace (str): Source workspace name to_namespace (str): project (namespace) to which target workspace belongs to_workspace (str): Target workspace name etype (str): Entity type enames (list(str)): List of entity names to copy link_existing_entities (boolean): Link all soft conflicts to the entities that already exist. Swagger: https://api.firecloud.org/#!/Entities/copyEntities
entailment
def get_entities(namespace, workspace, etype): """List entities of given type in a workspace. Response content will be in JSON format. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type Swagger: https://api.firecloud.org/#!/Entities/getEntities """ uri = "workspaces/{0}/{1}/entities/{2}".format(namespace, workspace, etype) return __get(uri)
List entities of given type in a workspace. Response content will be in JSON format. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type Swagger: https://api.firecloud.org/#!/Entities/getEntities
entailment
def get_entities_tsv(namespace, workspace, etype): """List entities of given type in a workspace as a TSV. Identical to get_entities(), but the response is a TSV. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type Swagger: https://api.firecloud.org/#!/Entities/browserDownloadEntitiesTSV """ uri = "workspaces/{0}/{1}/entities/{2}/tsv".format(namespace, workspace, etype) return __get(uri)
List entities of given type in a workspace as a TSV. Identical to get_entities(), but the response is a TSV. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type Swagger: https://api.firecloud.org/#!/Entities/browserDownloadEntitiesTSV
entailment
def get_entity(namespace, workspace, etype, ename): """Request entity information. Gets entity metadata and attributes. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type ename (str): The entity's unique id Swagger: https://api.firecloud.org/#!/Entities/getEntity """ uri = "workspaces/{0}/{1}/entities/{2}/{3}".format(namespace, workspace, etype, ename) return __get(uri)
Request entity information. Gets entity metadata and attributes. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type ename (str): The entity's unique id Swagger: https://api.firecloud.org/#!/Entities/getEntity
entailment
def delete_entities(namespace, workspace, json_body): """Delete entities in a workspace. Note: This action is not reversible. Be careful! Args: namespace (str): project to which workspace belongs workspace (str): Workspace name json_body: [ { "entityType": "string", "entityName": "string" } ] Swagger: https://api.firecloud.org/#!/Entities/deleteEntities """ uri = "workspaces/{0}/{1}/entities/delete".format(namespace, workspace) return __post(uri, json=json_body)
Delete entities in a workspace. Note: This action is not reversible. Be careful! Args: namespace (str): project to which workspace belongs workspace (str): Workspace name json_body: [ { "entityType": "string", "entityName": "string" } ] Swagger: https://api.firecloud.org/#!/Entities/deleteEntities
entailment
def delete_entity_type(namespace, workspace, etype, ename): """Delete entities in a workspace. Note: This action is not reversible. Be careful! Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type ename (str, or iterable of str): unique entity id(s) Swagger: https://api.firecloud.org/#!/Entities/deleteEntities """ uri = "workspaces/{0}/{1}/entities/delete".format(namespace, workspace) if isinstance(ename, string_types): body = [{"entityType":etype, "entityName":ename}] elif isinstance(ename, Iterable): body = [{"entityType":etype, "entityName":i} for i in ename] return __post(uri, json=body)
Delete entities in a workspace. Note: This action is not reversible. Be careful! Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type ename (str, or iterable of str): unique entity id(s) Swagger: https://api.firecloud.org/#!/Entities/deleteEntities
entailment
def get_entities_query(namespace, workspace, etype, page=1, page_size=100, sort_direction="asc", filter_terms=None): """Paginated version of get_entities_with_type. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Entities/entityQuery """ # Initial parameters for pagination params = { "page" : page, "pageSize" : page_size, "sortDirection" : sort_direction } if filter_terms: params['filterTerms'] = filter_terms uri = "workspaces/{0}/{1}/entityQuery/{2}".format(namespace,workspace,etype) return __get(uri, params=params)
Paginated version of get_entities_with_type. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Entities/entityQuery
entailment
def update_entity(namespace, workspace, etype, ename, updates): """ Update entity attributes in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type ename (str): Entity name updates (list(dict)): List of updates to entity from _attr_set, e.g. Swagger: https://api.firecloud.org/#!/Entities/update_entity """ headers = _fiss_agent_header({"Content-type": "application/json"}) uri = "{0}workspaces/{1}/{2}/entities/{3}/{4}".format(fcconfig.root_url, namespace, workspace, etype, ename) # FIXME: create __patch method, akin to __get, __delete etc return __SESSION.patch(uri, headers=headers, json=updates)
Update entity attributes in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name etype (str): Entity type ename (str): Entity name updates (list(dict)): List of updates to entity from _attr_set, e.g. Swagger: https://api.firecloud.org/#!/Entities/update_entity
entailment
def list_workspace_configs(namespace, workspace, allRepos=False): """List method configurations in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Method_Configurations/listWorkspaceMethodConfigs DUPLICATE: https://api.firecloud.org/#!/Workspaces/listWorkspaceMethodConfigs """ uri = "workspaces/{0}/{1}/methodconfigs".format(namespace, workspace) return __get(uri, params={'allRepos': allRepos})
List method configurations in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Method_Configurations/listWorkspaceMethodConfigs DUPLICATE: https://api.firecloud.org/#!/Workspaces/listWorkspaceMethodConfigs
entailment
def create_workspace_config(namespace, workspace, body): """Create method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name body (json) : a filled-in JSON object for the new method config (e.g. see return value of get_workspace_config) Swagger: https://api.firecloud.org/#!/Method_Configurations/postWorkspaceMethodConfig DUPLICATE: https://api.firecloud.org/#!/Workspaces/postWorkspaceMethodConfig """ #json_body = { # "namespace" : mnamespace, # "name" : method, # "rootEntityType" : root_etype, # "inputs" : {}, # "outputs" : {}, # "prerequisites" : {} #} uri = "workspaces/{0}/{1}/methodconfigs".format(namespace, workspace) return __post(uri, json=body)
Create method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name body (json) : a filled-in JSON object for the new method config (e.g. see return value of get_workspace_config) Swagger: https://api.firecloud.org/#!/Method_Configurations/postWorkspaceMethodConfig DUPLICATE: https://api.firecloud.org/#!/Workspaces/postWorkspaceMethodConfig
entailment
def delete_workspace_config(namespace, workspace, cnamespace, config): """Delete method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespace (str): Method namespace method (str): Method name Swagger: https://api.firecloud.org/#!/Method_Configurations/deleteWorkspaceMethodConfig """ uri = "workspaces/{0}/{1}/method_configs/{2}/{3}".format(namespace, workspace, cnamespace, config) return __delete(uri)
Delete method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespace (str): Method namespace method (str): Method name Swagger: https://api.firecloud.org/#!/Method_Configurations/deleteWorkspaceMethodConfig
entailment
def get_workspace_config(namespace, workspace, cnamespace, config): """Get method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Config namespace config (str): Config name Swagger: https://api.firecloud.org/#!/Method_Configurations/getWorkspaceMethodConfig """ uri = "workspaces/{0}/{1}/method_configs/{2}/{3}".format(namespace, workspace, cnamespace, config) return __get(uri)
Get method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Config namespace config (str): Config name Swagger: https://api.firecloud.org/#!/Method_Configurations/getWorkspaceMethodConfig
entailment
def overwrite_workspace_config(namespace, workspace, cnamespace, configname, body): """Add or overwrite method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Configuration namespace configname (str): Configuration name body (json): new body (definition) of the method config Swagger: https://api.firecloud.org/#!/Method_Configurations/overwriteWorkspaceMethodConfig """ headers = _fiss_agent_header({"Content-type": "application/json"}) uri = "workspaces/{0}/{1}/method_configs/{2}/{3}".format(namespace, workspace, cnamespace, configname) return __put(uri, headers=headers, json=body)
Add or overwrite method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Configuration namespace configname (str): Configuration name body (json): new body (definition) of the method config Swagger: https://api.firecloud.org/#!/Method_Configurations/overwriteWorkspaceMethodConfig
entailment
def update_workspace_config(namespace, workspace, cnamespace, configname, body): """Update method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Configuration namespace configname (str): Configuration name body (json): new body (definition) of the method config Swagger: https://api.firecloud.org/#!/Method_Configurations/updateWorkspaceMethodConfig """ uri = "workspaces/{0}/{1}/method_configs/{2}/{3}".format(namespace, workspace, cnamespace, configname) return __post(uri, json=body)
Update method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Configuration namespace configname (str): Configuration name body (json): new body (definition) of the method config Swagger: https://api.firecloud.org/#!/Method_Configurations/updateWorkspaceMethodConfig
entailment
def validate_config(namespace, workspace, cnamespace, config): """Get syntax validation for a configuration. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Configuration namespace config (str): Configuration name Swagger: https://api.firecloud.org/#!/Method_Configurations/validate_method_configuration """ uri = "workspaces/{0}/{1}/method_configs/{2}/{3}/validate".format(namespace, workspace, cnamespace, config) return __get(uri)
Get syntax validation for a configuration. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Configuration namespace config (str): Configuration name Swagger: https://api.firecloud.org/#!/Method_Configurations/validate_method_configuration
entailment
def rename_workspace_config(namespace, workspace, cnamespace, config, new_namespace, new_name): """Rename a method configuration in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespace (str): Config namespace config (str): Config name new_namespace (str): Updated config namespace new_name (str): Updated method name Swagger: https://api.firecloud.org/#!/Method_Configurations/renameWorkspaceMethodConfig """ body = { "namespace" : new_namespace, "name" : new_name, # I have no idea why this is required by FC, but it is... "workspaceName" : { "namespace" : namespace, "name" : workspace } } uri = "workspaces/{0}/{1}/method_configs/{2}/{3}/rename".format(namespace, workspace, cnamespace, config) return __post(uri, json=body)
Rename a method configuration in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespace (str): Config namespace config (str): Config name new_namespace (str): Updated config namespace new_name (str): Updated method name Swagger: https://api.firecloud.org/#!/Method_Configurations/renameWorkspaceMethodConfig
entailment
def copy_config_from_repo(namespace, workspace, from_cnamespace, from_config, from_snapshot_id, to_cnamespace, to_config): """Copy a method config from the methods repository to a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name from_cnamespace (str): Source configuration namespace from_config (str): Source configuration name from_snapshot_id (int): Source configuration snapshot_id to_cnamespace (str): Target configuration namespace to_config (str): Target configuration name Swagger: https://api.firecloud.org/#!/Method_Configurations/copyFromMethodRepo DUPLICATE: https://api.firecloud.org/#!/Method_Repository/copyFromMethodRepo """ body = { "configurationNamespace" : from_cnamespace, "configurationName" : from_config, "configurationSnapshotId" : from_snapshot_id, "destinationNamespace" : to_cnamespace, "destinationName" : to_config } uri = "workspaces/{0}/{1}/method_configs/copyFromMethodRepo".format( namespace, workspace) return __post(uri, json=body)
Copy a method config from the methods repository to a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name from_cnamespace (str): Source configuration namespace from_config (str): Source configuration name from_snapshot_id (int): Source configuration snapshot_id to_cnamespace (str): Target configuration namespace to_config (str): Target configuration name Swagger: https://api.firecloud.org/#!/Method_Configurations/copyFromMethodRepo DUPLICATE: https://api.firecloud.org/#!/Method_Repository/copyFromMethodRepo
entailment
def copy_config_to_repo(namespace, workspace, from_cnamespace, from_config, to_cnamespace, to_config): """Copy a method config from a workspace to the methods repository. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name from_cnamespace (str): Source configuration namespace from_config (str): Source configuration name to_cnamespace (str): Target configuration namespace to_config (str): Target configuration name Swagger: https://api.firecloud.org/#!/Method_Configurations/copyToMethodRepo DUPLICATE: https://api.firecloud.org/#!/Method_Repository/copyToMethodRepo """ body = { "configurationNamespace" : to_cnamespace, "configurationName" : to_config, "sourceNamespace" : from_cnamespace, "sourceName" : from_config } uri = "workspaces/{0}/{1}/method_configs/copyToMethodRepo".format( namespace, workspace) return __post(uri, json=body)
Copy a method config from a workspace to the methods repository. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name from_cnamespace (str): Source configuration namespace from_config (str): Source configuration name to_cnamespace (str): Target configuration namespace to_config (str): Target configuration name Swagger: https://api.firecloud.org/#!/Method_Configurations/copyToMethodRepo DUPLICATE: https://api.firecloud.org/#!/Method_Repository/copyToMethodRepo
entailment
def list_repository_methods(namespace=None, name=None, snapshotId=None): """List method(s) in the methods repository. Args: namespace (str): Method Repository namespace name (str): method name snapshotId (int): method snapshot ID Swagger: https://api.firecloud.org/#!/Method_Repository/listMethodRepositoryMethods """ params = {k:v for (k,v) in locals().items() if v is not None} return __get("methods", params=params)
List method(s) in the methods repository. Args: namespace (str): Method Repository namespace name (str): method name snapshotId (int): method snapshot ID Swagger: https://api.firecloud.org/#!/Method_Repository/listMethodRepositoryMethods
entailment
def get_config_template(namespace, method, version): """Get the configuration template for a method. The method should exist in the methods repository. Args: namespace (str): Method's namespace method (str): method name version (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/createMethodTemplate """ body = { "methodNamespace" : namespace, "methodName" : method, "methodVersion" : int(version) } return __post("template", json=body)
Get the configuration template for a method. The method should exist in the methods repository. Args: namespace (str): Method's namespace method (str): method name version (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/createMethodTemplate
entailment
def get_inputs_outputs(namespace, method, snapshot_id): """Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getMethodIO """ body = { "methodNamespace" : namespace, "methodName" : method, "methodVersion" : snapshot_id } return __post("inputsOutputs", json=body)
Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getMethodIO
entailment
def get_repository_config(namespace, config, snapshot_id): """Get a method configuration from the methods repository. Args: namespace (str): Methods namespace config (str): config name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getMethodRepositoryConfiguration """ uri = "configurations/{0}/{1}/{2}".format(namespace, config, snapshot_id) return __get(uri)
Get a method configuration from the methods repository. Args: namespace (str): Methods namespace config (str): config name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getMethodRepositoryConfiguration
entailment
def get_repository_method(namespace, method, snapshot_id, wdl_only=False): """Get a method definition from the method repository. Args: namespace (str): Methods namespace method (str): method name version (int): snapshot_id of the method wdl_only (bool): Exclude metadata Swagger: https://api.firecloud.org/#!/Method_Repository/get_api_methods_namespace_name_snapshotId """ uri = "methods/{0}/{1}/{2}?onlyPayload={3}".format(namespace, method, snapshot_id, str(wdl_only).lower()) return __get(uri)
Get a method definition from the method repository. Args: namespace (str): Methods namespace method (str): method name version (int): snapshot_id of the method wdl_only (bool): Exclude metadata Swagger: https://api.firecloud.org/#!/Method_Repository/get_api_methods_namespace_name_snapshotId
entailment
def update_repository_method(namespace, method, synopsis, wdl, doc=None, comment=""): """Create/Update workflow definition. FireCloud will create a new snapshot_id for the given workflow. Args: namespace (str): Methods namespace method (str): method name synopsis (str): short (<80 char) description of method wdl (file): Workflow Description Language file doc (file): (Optional) Additional documentation comment (str): (Optional) Comment specific to this snapshot Swagger: https://api.firecloud.org/#!/Method_Repository/post_api_methods """ with open(wdl, 'r') as wf: wdl_payload = wf.read() if doc is not None: with open (doc, 'r') as df: doc = df.read() body = { "namespace": namespace, "name": method, "entityType": "Workflow", "payload": wdl_payload, "documentation": doc, "synopsis": synopsis, "snapshotComment": comment } return __post("methods", json={key: value for key, value in body.items() if value})
Create/Update workflow definition. FireCloud will create a new snapshot_id for the given workflow. Args: namespace (str): Methods namespace method (str): method name synopsis (str): short (<80 char) description of method wdl (file): Workflow Description Language file doc (file): (Optional) Additional documentation comment (str): (Optional) Comment specific to this snapshot Swagger: https://api.firecloud.org/#!/Method_Repository/post_api_methods
entailment
def delete_repository_method(namespace, name, snapshot_id): """Redacts a method and all of its associated configurations. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_methods_namespace_name_snapshotId """ uri = "methods/{0}/{1}/{2}".format(namespace, name, snapshot_id) return __delete(uri)
Redacts a method and all of its associated configurations. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_methods_namespace_name_snapshotId
entailment
def delete_repository_config(namespace, name, snapshot_id): """Redacts a configuration and all of its associated configurations. The configuration should exist in the methods repository. Args: namespace (str): configuration namespace configuration (str): configuration name snapshot_id (int): snapshot_id of the configuration Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_configurations_namespace_name_snapshotId """ uri = "configurations/{0}/{1}/{2}".format(namespace, name, snapshot_id) return __delete(uri)
Redacts a configuration and all of its associated configurations. The configuration should exist in the methods repository. Args: namespace (str): configuration namespace configuration (str): configuration name snapshot_id (int): snapshot_id of the configuration Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_configurations_namespace_name_snapshotId
entailment
def get_repository_method_acl(namespace, method, snapshot_id): """Get permissions for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name version (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getMethodACL """ uri = "methods/{0}/{1}/{2}/permissions".format(namespace,method,snapshot_id) return __get(uri)
Get permissions for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name version (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getMethodACL
entailment
def update_repository_method_acl(namespace, method, snapshot_id, acl_updates): """Set method permissions. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method acl_updates (list(dict)): List of access control updates Swagger: https://api.firecloud.org/#!/Method_Repository/setMethodACL """ uri = "methods/{0}/{1}/{2}/permissions".format(namespace,method,snapshot_id) return __post(uri, json=acl_updates)
Set method permissions. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method acl_updates (list(dict)): List of access control updates Swagger: https://api.firecloud.org/#!/Method_Repository/setMethodACL
entailment
def get_repository_config_acl(namespace, config, snapshot_id): """Get configuration permissions. The configuration should exist in the methods repository. Args: namespace (str): Configuration namespace config (str): Configuration name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getConfigACL """ uri = "configurations/{0}/{1}/{2}/permissions".format(namespace, config, snapshot_id) return __get(uri)
Get configuration permissions. The configuration should exist in the methods repository. Args: namespace (str): Configuration namespace config (str): Configuration name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Repository/getConfigACL
entailment
def update_repository_config_acl(namespace, config, snapshot_id, acl_updates): """Set configuration permissions. The configuration should exist in the methods repository. Args: namespace (str): Configuration namespace config (str): Configuration name snapshot_id (int): snapshot_id of the method acl_updates (list(dict)): List of access control updates Swagger: https://api.firecloud.org/#!/Method_Repository/setConfigACL """ uri = "configurations/{0}/{1}/{2}/permissions".format(namespace, config, snapshot_id) return __post(uri, json=acl_updates)
Set configuration permissions. The configuration should exist in the methods repository. Args: namespace (str): Configuration namespace config (str): Configuration name snapshot_id (int): snapshot_id of the method acl_updates (list(dict)): List of access control updates Swagger: https://api.firecloud.org/#!/Method_Repository/setConfigACL
entailment
def create_submission(wnamespace, workspace, cnamespace, config, entity, etype, expression=None, use_callcache=True): """Submit job in FireCloud workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Method configuration namespace config (str): Method configuration name entity (str): Entity to submit job on. Should be the same type as the root entity type of the method config, unless an expression is used etype (str): Entity type of root_entity expression (str): Instead of using entity as the root entity, evaluate the root entity from this expression. use_callcache (bool): use call cache if applicable (default: true) Swagger: https://api.firecloud.org/#!/Submissions/createSubmission """ uri = "workspaces/{0}/{1}/submissions".format(wnamespace, workspace) body = { "methodConfigurationNamespace" : cnamespace, "methodConfigurationName" : config, "entityType" : etype, "entityName" : entity, "useCallCache" : use_callcache } if expression: body['expression'] = expression return __post(uri, json=body)
Submit job in FireCloud workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Method configuration namespace config (str): Method configuration name entity (str): Entity to submit job on. Should be the same type as the root entity type of the method config, unless an expression is used etype (str): Entity type of root_entity expression (str): Instead of using entity as the root entity, evaluate the root entity from this expression. use_callcache (bool): use call cache if applicable (default: true) Swagger: https://api.firecloud.org/#!/Submissions/createSubmission
entailment
def abort_submission(namespace, workspace, submission_id): """Abort running job in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier Swagger: https://api.firecloud.org/#!/Submissions/deleteSubmission """ uri = "workspaces/{0}/{1}/submissions/{2}".format(namespace, workspace, submission_id) return __delete(uri)
Abort running job in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier Swagger: https://api.firecloud.org/#!/Submissions/deleteSubmission
entailment
def get_submission(namespace, workspace, submission_id): """Request submission information. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier Swagger: https://api.firecloud.org/#!/Submissions/monitorSubmission """ uri = "workspaces/{0}/{1}/submissions/{2}".format(namespace, workspace, submission_id) return __get(uri)
Request submission information. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier Swagger: https://api.firecloud.org/#!/Submissions/monitorSubmission
entailment
def get_workflow_metadata(namespace, workspace, submission_id, workflow_id): """Request the metadata for a workflow in a submission. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier workflow_id (str): Workflow's unique identifier. Swagger: https://api.firecloud.org/#!/Submissions/workflowMetadata """ uri = "workspaces/{0}/{1}/submissions/{2}/workflows/{3}".format(namespace, workspace, submission_id, workflow_id) return __get(uri)
Request the metadata for a workflow in a submission. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier workflow_id (str): Workflow's unique identifier. Swagger: https://api.firecloud.org/#!/Submissions/workflowMetadata
entailment
def get_workflow_outputs(namespace, workspace, submission_id, workflow_id): """Request the outputs for a workflow in a submission. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier workflow_id (str): Workflow's unique identifier. Swagger: https://api.firecloud.org/#!/Submissions/workflowOutputsInSubmission """ uri = "workspaces/{0}/{1}/".format(namespace, workspace) uri += "submissions/{0}/workflows/{1}/outputs".format(submission_id, workflow_id) return __get(uri)
Request the outputs for a workflow in a submission. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name submission_id (str): Submission's unique identifier workflow_id (str): Workflow's unique identifier. Swagger: https://api.firecloud.org/#!/Submissions/workflowOutputsInSubmission
entailment
def create_workspace(namespace, name, authorizationDomain="", attributes=None): """Create a new FireCloud Workspace. Args: namespace (str): project to which workspace belongs name (str): Workspace name protected (bool): If True, this workspace is protected by dbGaP credentials. This option is only available if your FireCloud account is linked to your NIH account. attributes (dict): Workspace attributes as key value pairs Swagger: https://api.firecloud.org/#!/Workspaces/createWorkspace """ if not attributes: attributes = dict() body = { "namespace": namespace, "name": name, "attributes": attributes } if authorizationDomain: authDomain = [{"membersGroupName": authorizationDomain}] else: authDomain = [] body["authorizationDomain"] = authDomain return __post("workspaces", json=body)
Create a new FireCloud Workspace. Args: namespace (str): project to which workspace belongs name (str): Workspace name protected (bool): If True, this workspace is protected by dbGaP credentials. This option is only available if your FireCloud account is linked to your NIH account. attributes (dict): Workspace attributes as key value pairs Swagger: https://api.firecloud.org/#!/Workspaces/createWorkspace
entailment
def update_workspace_acl(namespace, workspace, acl_updates, invite_users_not_found=False): """Update workspace access control list. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name acl_updates (list(dict)): Acl updates as dicts with two keys: "email" - Firecloud user email "accessLevel" - one of "OWNER", "READER", "WRITER", "NO ACCESS" Example: {"email":"user1@mail.com", "accessLevel":"WRITER"} invite_users_not_found (bool): true to invite unregistered users, false to ignore Swagger: https://api.firecloud.org/#!/Workspaces/updateWorkspaceACL """ uri = "{0}workspaces/{1}/{2}/acl?inviteUsersNotFound={3}".format(fcconfig.root_url, namespace, workspace, str(invite_users_not_found).lower()) headers = _fiss_agent_header({"Content-type": "application/json"}) # FIXME: create __patch method, akin to __get, __delete etc return __SESSION.patch(uri, headers=headers, data=json.dumps(acl_updates))
Update workspace access control list. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name acl_updates (list(dict)): Acl updates as dicts with two keys: "email" - Firecloud user email "accessLevel" - one of "OWNER", "READER", "WRITER", "NO ACCESS" Example: {"email":"user1@mail.com", "accessLevel":"WRITER"} invite_users_not_found (bool): true to invite unregistered users, false to ignore Swagger: https://api.firecloud.org/#!/Workspaces/updateWorkspaceACL
entailment
def clone_workspace(from_namespace, from_workspace, to_namespace, to_workspace, authorizationDomain=""): """Clone a FireCloud workspace. A clone is a shallow copy of a FireCloud workspace, enabling easy sharing of data, such as TCGA data, without duplication. Args: from_namespace (str): project (namespace) to which source workspace belongs from_workspace (str): Source workspace's name to_namespace (str): project to which target workspace belongs to_workspace (str): Target workspace's name authorizationDomain: (str) required authorization domains Swagger: https://api.firecloud.org/#!/Workspaces/cloneWorkspace """ if authorizationDomain: if isinstance(authorizationDomain, string_types): authDomain = [{"membersGroupName": authorizationDomain}] else: authDomain = [{"membersGroupName": authDomain} for authDomain in authorizationDomain] else: authDomain = [] body = { "namespace": to_namespace, "name": to_workspace, "attributes": dict(), "authorizationDomain": authDomain, } uri = "workspaces/{0}/{1}/clone".format(from_namespace, from_workspace) return __post(uri, json=body)
Clone a FireCloud workspace. A clone is a shallow copy of a FireCloud workspace, enabling easy sharing of data, such as TCGA data, without duplication. Args: from_namespace (str): project (namespace) to which source workspace belongs from_workspace (str): Source workspace's name to_namespace (str): project to which target workspace belongs to_workspace (str): Target workspace's name authorizationDomain: (str) required authorization domains Swagger: https://api.firecloud.org/#!/Workspaces/cloneWorkspace
entailment
def update_workspace_attributes(namespace, workspace, attrs): """Update or remove workspace attributes. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name attrs (list(dict)): List of update operations for workspace attributes. Use the helper dictionary construction functions to create these: _attr_set() : Set/Update attribute _attr_rem() : Remove attribute _attr_ladd() : Add list member to attribute _attr_lrem() : Remove list member from attribute Swagger: https://api.firecloud.org/#!/Workspaces/updateAttributes """ headers = _fiss_agent_header({"Content-type": "application/json"}) uri = "{0}workspaces/{1}/{2}/updateAttributes".format(fcconfig.root_url, namespace, workspace) body = json.dumps(attrs) # FIXME: create __patch method, akin to __get, __delete etc return __SESSION.patch(uri, headers=headers, data=body)
Update or remove workspace attributes. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name attrs (list(dict)): List of update operations for workspace attributes. Use the helper dictionary construction functions to create these: _attr_set() : Set/Update attribute _attr_rem() : Remove attribute _attr_ladd() : Add list member to attribute _attr_lrem() : Remove list member from attribute Swagger: https://api.firecloud.org/#!/Workspaces/updateAttributes
entailment
def add_user_to_group(group, role, email): """Add a user to a group the caller owns Args: group (str): Group name role (str) : Role of user for group; either 'member' or 'admin' email (str): Email of user or group to add Swagger: https://api.firecloud.org/#!/Groups/addUserToGroup """ uri = "groups/{0}/{1}/{2}".format(group, role, email) return __put(uri)
Add a user to a group the caller owns Args: group (str): Group name role (str) : Role of user for group; either 'member' or 'admin' email (str): Email of user or group to add Swagger: https://api.firecloud.org/#!/Groups/addUserToGroup
entailment
def remove_user_from_group(group, role, email): """Remove a user from a group the caller owns Args: group (str): Group name role (str) : Role of user for group; either 'member' or 'admin' email (str): Email of user or group to remove Swagger: https://api.firecloud.org/#!/Groups/removeUserFromGroup """ uri = "groups/{0}/{1}/{2}".format(group, role, email) return __delete(uri)
Remove a user from a group the caller owns Args: group (str): Group name role (str) : Role of user for group; either 'member' or 'admin' email (str): Email of user or group to remove Swagger: https://api.firecloud.org/#!/Groups/removeUserFromGroup
entailment
def register_commands(self, subparsers): """ Add commands to a list of subparsers. This will be called by Fissfc to add additional command targets from this plugin. Each command added should follow the pattern: parser = subparsers.add_parser('cmd', ...) parser.add_argument(...) ... parser.set_defaults(func=do_my_cmd) where do_my_cmd is a function that takes one argument "args": def do_my_cmd(args): pass """ #print_("DEV PLUGIN: Loaded commands") prsr = subparsers.add_parser( 'upload', description='Copy the file or directory into the given') prsr.add_argument('workspace', help='Workspace name') prsr.add_argument('source', help='File or directory to upload') prsr.add_argument('-s', '--show', action='store_true', help="Show the gsutil command, but don't run it") dest_help = 'Destination relative to the bucket root. ' dest_help += 'If omitted the file will be placed in the root directory' prsr.add_argument('-d', '--destination', help=dest_help) prsr.set_defaults(func=upload)
Add commands to a list of subparsers. This will be called by Fissfc to add additional command targets from this plugin. Each command added should follow the pattern: parser = subparsers.add_parser('cmd', ...) parser.add_argument(...) ... parser.set_defaults(func=do_my_cmd) where do_my_cmd is a function that takes one argument "args": def do_my_cmd(args): pass
entailment
def new(namespace, name, wdl, synopsis, documentation=None, api_url=fapi.PROD_API_ROOT): """Create new FireCloud method. If the namespace + name already exists, a new snapshot is created. Args: namespace (str): Method namespace for this method name (str): Method name wdl (file): WDL description synopsis (str): Short description of task documentation (file): Extra documentation for method """ r = fapi.update_workflow(namespace, name, synopsis, wdl, documentation, api_url) fapi._check_response_code(r, 201) d = r.json() return Method(namespace, name, d["snapshotId"])
Create new FireCloud method. If the namespace + name already exists, a new snapshot is created. Args: namespace (str): Method namespace for this method name (str): Method name wdl (file): WDL description synopsis (str): Short description of task documentation (file): Extra documentation for method
entailment
def template(self): """Return a method template for this method.""" r = fapi.get_config_template(self.namespace, self.name, self.snapshot_id, self.api_url) fapi._check_response_code(r, 200) return r.json()
Return a method template for this method.
entailment
def inputs_outputs(self): """Get information on method inputs & outputs.""" r = fapi.get_inputs_outputs(self.namespace, self.name, self.snapshot_id, self.api_url) fapi._check_response_code(r, 200) return r.json()
Get information on method inputs & outputs.
entailment
def acl(self): """Get the access control list for this method.""" r = fapi.get_repository_method_acl( self.namespace, self.name, self.snapshot_id, self.api_url) fapi._check_response_code(r, 200) return r.json()
Get the access control list for this method.
entailment
def set_acl(self, role, users): """Set permissions for this method. Args: role (str): Access level one of {one of "OWNER", "READER", "WRITER", "NO ACCESS"} users (list(str)): List of users to give role to """ acl_updates = [{"user": user, "role": role} for user in users] r = fapi.update_repository_method_acl( self.namespace, self.name, self.snapshot_id, acl_updates, self.api_url ) fapi._check_response_code(r, 200)
Set permissions for this method. Args: role (str): Access level one of {one of "OWNER", "READER", "WRITER", "NO ACCESS"} users (list(str)): List of users to give role to
entailment
def __ensure_gcloud(): """The *NIX installer is not guaranteed to add the google cloud sdk to the user's PATH (the Windows installer does). This ensures that if the default directory for the executables exists, it is added to the PATH for the duration of this package's use.""" if which('gcloud') is None: gcloud_path = os.path.join(os.path.expanduser('~'), 'google-cloud-sdk', 'bin') env_path = os.getenv('PATH') if os.path.isdir(gcloud_path): if env_path is not None: os.environ['PATH'] = gcloud_path + os.pathsep + env_path else: os.environ['PATH'] = gcloud_path
The *NIX installer is not guaranteed to add the google cloud sdk to the user's PATH (the Windows installer does). This ensures that if the default directory for the executables exists, it is added to the PATH for the duration of this package's use.
entailment
def config_parse(files=None, config=None, config_profile=".fissconfig", **kwargs): ''' Read initial configuration state, from named config files; store this state within a config dictionary (which may be nested) whose keys may also be referenced as attributes (safely, defaulting to None if unset). A config object may be passed in, as a way of accumulating or overwriting configuration state; if one is NOT passed, the default config obj is used ''' local_config = config config = __fcconfig cfgparser = configparser.SafeConfigParser() filenames = list() # Give personal/user followed by current working directory configuration the first say filenames.append(os.path.join(os.path.expanduser('~'), config_profile)) filenames.append(os.path.join(os.getcwd(), config_profile)) if files: if isinstance(files, string_types): filenames.append(files) elif isinstance(files, Iterable): for f in files: if isinstance(f, IOBase): f = f.name filenames.append(f) cfgparser.read(filenames) # [DEFAULT] defines common variables for interpolation/substitution in # other sections, and are stored at the root level of the config object for keyval in cfgparser.items('DEFAULT'): #print("config_parse: adding config variable %s=%s" % (keyval[0], str(keyval[1]))) __fcconfig[keyval[0]] = keyval[1] for section in cfgparser.sections(): config[section] = attrdict() for option in cfgparser.options(section): # DEFAULT vars ALSO behave as though they were defined in every # section, but we purposely skip them here so that each section # reflects only the options explicitly defined in that section if not config[option]: config[section][option] = cfgparser.get(section, option) config.verbosity = int(config.verbosity) if not config.root_url.endswith('/'): config.root_url += '/' if os.path.isfile(config.credentials): os.environ[environment_vars.CREDENTIALS] = config.credentials # if local_config override options with passed options if local_config is not None: for key, value in local_config.items(): config[key] = value # if any explict config options are passed override. for key, value in kwargs.items(): config[key] = value return config
Read initial configuration state, from named config files; store this state within a config dictionary (which may be nested) whose keys may also be referenced as attributes (safely, defaulting to None if unset). A config object may be passed in, as a way of accumulating or overwriting configuration state; if one is NOT passed, the default config obj is used
entailment
def new(namespace, name, protected=False, attributes=dict(), api_url=fapi.PROD_API_ROOT): """Create a new FireCloud workspace. Returns: Workspace: A new FireCloud workspace Raises: FireCloudServerError: API call failed. """ r = fapi.create_workspace(namespace, name, protected, attributes, api_url) fapi._check_response_code(r, 201) return Workspace(namespace, name, api_url)
Create a new FireCloud workspace. Returns: Workspace: A new FireCloud workspace Raises: FireCloudServerError: API call failed.
entailment
def refresh(self): """Reload workspace metadata from firecloud. Workspace metadata is cached in the data attribute of a Workspace, and may become stale, requiring a refresh(). """ r = fapi.get_workspace(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) self.data = r.json() return self
Reload workspace metadata from firecloud. Workspace metadata is cached in the data attribute of a Workspace, and may become stale, requiring a refresh().
entailment
def delete(self): """Delete the workspace from FireCloud. Note: This action cannot be undone. Be careful! """ r = fapi.delete_workspace(self.namespace, self.name) fapi._check_response_code(r, 202)
Delete the workspace from FireCloud. Note: This action cannot be undone. Be careful!
entailment
def lock(self): """Lock this Workspace. This causes the workspace to behave in a read-only way, regardless of access permissions. """ r = fapi.lock_workspace(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 204) self.data['workspace']['isLocked'] = True return self
Lock this Workspace. This causes the workspace to behave in a read-only way, regardless of access permissions.
entailment
def unlock(self): """Unlock this Workspace.""" r = fapi.unlock_workspace(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 204) self.data['workspace']['isLocked'] = False return self
Unlock this Workspace.
entailment
def update_attribute(self, attr, value): """Set the value of a workspace attribute.""" update = [fapi._attr_up(attr, value)] r = fapi.update_workspace_attributes(self.namespace, self.name, update, self.api_url) fapi._check_response_code(r, 200)
Set the value of a workspace attribute.
entailment
def remove_attribute(self, attr): """Remove attribute from a workspace. Args: attr (str): attribute name """ update = [fapi._attr_rem(attr)] r = fapi.update_workspace_attributes(self.namespace, self.name, update, self.api_url) self.data["workspace"]["attributes"].pop(attr, None) fapi._check_response_code(r, 200)
Remove attribute from a workspace. Args: attr (str): attribute name
entailment
def import_tsv(self, tsv_file): """Upload entity data to workspace from tsv loadfile. Args: tsv_file (file): Tab-delimited file of entity data """ r = fapi.upload_entities_tsv(self.namespace, self.name, self.tsv_file, self.api_url) fapi._check_response_code(r, 201)
Upload entity data to workspace from tsv loadfile. Args: tsv_file (file): Tab-delimited file of entity data
entailment
def get_entity(self, etype, entity_id): """Return entity in this workspace. Args: etype (str): Entity type entity_id (str): Entity name/unique id """ r = fapi.get_entity(self.namespace, self.name, etype, entity_id, self.api_url) fapi._check_response_code(r, 200) dresp = r.json() return Entity(etype, entity_id, dresp['attributes'])
Return entity in this workspace. Args: etype (str): Entity type entity_id (str): Entity name/unique id
entailment
def delete_entity(self, etype, entity_id): """Delete an entity in this workspace. Args: etype (str): Entity type entity_id (str): Entity name/unique id """ r = fapi.delete_entity(self.namespace, self.name, etype, entity_id, self.api_url) fapi._check_response_code(r, 202)
Delete an entity in this workspace. Args: etype (str): Entity type entity_id (str): Entity name/unique id
entailment
def import_entities(self, entities): """Upload entity objects. Args: entities: iterable of firecloud.Entity objects. """ edata = Entity.create_payload(entities) r = fapi.upload_entities(self.namespace, self.name, edata, self.api_url) fapi._check_response_code(r, 201)
Upload entity objects. Args: entities: iterable of firecloud.Entity objects.
entailment
def create_set(self, set_id, etype, entities): """Create a set of entities and upload to FireCloud. Args etype (str): one of {"sample, "pair", "participant"} entities: iterable of firecloud.Entity objects. """ if etype not in {"sample", "pair", "participant"}: raise ValueError("Unsupported entity type:" + str(etype)) payload = "membership:" + etype + "_set_id\t" + etype + "_id\n" for e in entities: if e.etype != etype: msg = "Entity type '" + e.etype + "' does not match " msg += "set type '" + etype + "'" raise ValueError(msg) payload += set_id + '\t' + e.entity_id + '\n' r = fapi.upload_entities(self.namespace, self.name, payload, self.api_url) fapi._check_response_code(r, 201)
Create a set of entities and upload to FireCloud. Args etype (str): one of {"sample, "pair", "participant"} entities: iterable of firecloud.Entity objects.
entailment
def submissions(self): """List job submissions in workspace.""" r = fapi.get_submissions(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) return r.json()
List job submissions in workspace.
entailment
def entity_types(self): """List entity types in workspace.""" r = fapi.get_entity_types(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) return r.json().keys()
List entity types in workspace.
entailment
def entities(self): """List all entities in workspace.""" r = fapi.get_entities_with_type(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) edicts = r.json() return [Entity(e['entityType'], e['name'], e['attributes']) for e in edicts]
List all entities in workspace.
entailment
def __get_entities(self, etype): """Helper to get entities for a given type.""" r = fapi.get_entities(self.namespace, self.name, etype, self.api_url) fapi._check_response_code(r, 200) return [Entity(e['entityType'], e['name'], e['attributes']) for e in r.json()]
Helper to get entities for a given type.
entailment
def copy_entities(self, from_namespace, from_workspace, etype, enames): """Copy entities from another workspace. Args: from_namespace (str): Source workspace namespace from_workspace (str): Source workspace name etype (str): Entity type enames (list(str)): List of entity names to copy """ r = fapi.copy_entities(from_namespace, from_workspace, self.namespace, self.name, etype, enames, self.api_url) fapi._check_response_code(r, 201)
Copy entities from another workspace. Args: from_namespace (str): Source workspace namespace from_workspace (str): Source workspace name etype (str): Entity type enames (list(str)): List of entity names to copy
entailment
def configs(self): """Get method configurations in a workspace.""" raise NotImplementedError r = fapi.get_configs(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) cdata = r.json() configs = [] for c in cdata: cnamespace = c['namespace'] cname = c['name'] root_etype = c['rootEntityType'] method_namespace = c['methodRepoMethod']['methodNamespace'] method_name = c['methodRepoMethod']['methodName'] method_version = c['methodRepoMethod']['methodVersion']
Get method configurations in a workspace.
entailment
def acl(self): """Get the access control list for this workspace.""" r = fapi.get_workspace_acl(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) return r.json()
Get the access control list for this workspace.
entailment
def clone(self, to_namespace, to_name): """Clone this workspace. Args: to_namespace (str): Target workspace namespace to_name (str): Target workspace name """ r = fapi.clone_workspace(self.namespace, self.name, to_namespace, to_name, self.api_url) fapi._check_response_code(r, 201) return Workspace(to_namespace, to_name, self.api_url)
Clone this workspace. Args: to_namespace (str): Target workspace namespace to_name (str): Target workspace name
entailment
def supervise(project, workspace, namespace, workflow, sample_sets, recovery_file): """ Supervise submission of jobs from a Firehose-style workflow of workflows""" # Get arguments logging.info("Initializing FireCloud Supervisor...") logging.info("Saving recovery checkpoints to " + recovery_file) # Parse workflow description # these three objects must be saved in order to recover the supervisor args = { 'project' : project, 'workspace': workspace, 'namespace': namespace, 'workflow' : workflow, 'sample_sets': sample_sets } monitor_data, dependencies = init_supervisor_data(workflow, sample_sets) recovery_data = { 'args' : args, 'monitor_data' : monitor_data, 'dependencies' : dependencies } # Monitor loop. Keep going until all nodes have been evaluated supervise_until_complete(monitor_data, dependencies, args, recovery_file)
Supervise submission of jobs from a Firehose-style workflow of workflows
entailment
def init_supervisor_data(dotfile, sample_sets): """ Parse a workflow description written in DOT (like Firehose)""" with open(dotfile) as wf: graph_data = wf.read() graph = pydot.graph_from_dot_data(graph_data)[0] nodes = [n.get_name().strip('"') for n in graph.get_nodes()] monitor_data = dict() dependencies = {n:[] for n in nodes} # Initialize empty list of dependencies for n in nodes: monitor_data[n] = dict() for sset in sample_sets: monitor_data[n][sset] = { 'state' : "Not Started", 'evaluated' : False, 'succeeded' : False } edges = graph.get_edges() # Iterate over the edges, and get the dependency information for each node for e in edges: source = e.get_source().strip('"') dest = e.get_destination().strip('"') dep = e.get_attributes() dep['upstream_task'] = source dependencies[dest].append(dep) return monitor_data, dependencies
Parse a workflow description written in DOT (like Firehose)
entailment
def validate_monitor_tasks(dependencies, args): """ Validate that all entries in the supervisor are valid task configurations and that all permissions requirements are satisfied. """ # Make a list of all task configurations needed to supervise sup_configs = sorted(dependencies.keys()) try: logging.info("Validating supervisor data...") # Make an api call to list task configurations in the workspace r = fapi.list_workspace_configs(args['project'], args['workspace']) fapi._check_response_code(r, 200) space_configs = r.json() # Make a dict for easy lookup later space_configs = { c["name"]: c for c in space_configs} # Also make an api call to list methods you have view permissions for r = fapi.list_repository_methods() fapi._check_response_code(r, 200) repo_methods = r.json() ## Put in a form that is more easily searchable: namespace/name:snapshot repo_methods = {m['namespace'] + '/' + m['name'] + ':' + str(m['snapshotId']) for m in repo_methods if m['entityType'] == 'Workflow'} valid = True for config in sup_configs: # ensure config exists in the workspace if config not in space_configs: logging.error("No task configuration for " + config + " found in " + args['project'] + "/" + args['workspace']) valid = False else: # Check access permissions for the referenced method m = space_configs[config]['methodRepoMethod'] ref_method = m['methodNamespace'] + "/" + m['methodName'] + ":" + str(m['methodVersion']) if ref_method not in repo_methods: logging.error(config+ " -- You don't have permisson to run the referenced method: " + ref_method) valid = False except Exception as e: logging.error("Exception occurred while validating supervisor: " + str(e)) raise return False return valid
Validate that all entries in the supervisor are valid task configurations and that all permissions requirements are satisfied.
entailment
def recover_and_supervise(recovery_file): """ Retrieve monitor data from recovery_file and resume monitoring """ try: logging.info("Attempting to recover Supervisor data from " + recovery_file) with open(recovery_file) as rf: recovery_data = json.load(rf) monitor_data = recovery_data['monitor_data'] dependencies = recovery_data['dependencies'] args = recovery_data['args'] except: logging.error("Could not recover monitor data, exiting...") return 1 logging.info("Data successfully loaded, resuming Supervisor") supervise_until_complete(monitor_data, dependencies, args, recovery_file)
Retrieve monitor data from recovery_file and resume monitoring
entailment
def supervise_until_complete(monitor_data, dependencies, args, recovery_file): """ Supervisor loop. Loop forever until all tasks are evaluated or completed """ project = args['project'] workspace = args['workspace'] namespace = args['namespace'] sample_sets = args['sample_sets'] recovery_data = {'args': args} if not validate_monitor_tasks(dependencies, args): logging.error("Errors found, aborting...") return while True: # There are 4 possible states for each node: # 1. Not Started -- In this state, check all the dependencies for the # node (possibly 0). If all of them have been evaluated, and the # satisfiedMode is met, start the task, change to "Running". if # satisfiedMode is not met, change to "Evaluated" # # 2. Running -- Submitted in FC. Check the submission endpoint, and # if it has completed, change to "Completed", set evaluated=True, # and whether the task succeeded # Otherwise, do nothing # # 3. Completed -- Job ran in FC and either succeeded or failed. Do nothing # 4. Evaluated -- All dependencies evaluated, but this task did not run # do nothing # Keep a tab of the number of jobs in each category running = 0 waiting = 0 completed = 0 # Get the submissions r = fapi.list_submissions(project, workspace) sub_list = r.json() #TODO: filter this list by submission time first? sub_lookup = {s["submissionId"]: s for s in sub_list} # Keys of dependencies is the list of tasks to run for n in dependencies: for sset in sample_sets: task_data = monitor_data[n][sset] if task_data['state'] == "Not Started": # See if all of the dependencies have been evaluated upstream_evaluated = True for dep in dependencies[n]: # Look up the status of the task upstream_task_data = monitor_data[dep['upstream_task']][sset] if not upstream_task_data.get('evaluated'): upstream_evaluated = False # if all of the dependencies have been evaluated, we can evaluate # this node if upstream_evaluated: # Now check the satisfied Mode of all the dependencies should_run = True for dep in dependencies[n]: upstream_task_data = monitor_data[dep['upstream_task']][sset] mode = dep['satisfiedMode'] # Task must have succeeded for OnComplete if mode == '"OnComplete"' and not upstream_task_data['succeeded']: should_run = False # 'Always' and 'Optional' run once the deps have been # evaluated if should_run: # Submit the workflow to FC fc_config = n logging.info("Starting workflow " + fc_config + " on " + sset) # How to handle errors at this step? for retry in range(3): r = fapi.create_submission( project, workspace, namespace, fc_config, sset, etype="sample_set", expression=None ) if r.status_code == 201: task_data['submissionId'] = r.json()['submissionId'] task_data['state'] = "Running" running += 1 break else: # There was an error, under certain circumstances retry logging.debug("Create_submission for " + fc_config + "failed on " + sset + " with the following response:" + r.content + "\nRetrying...") else: # None of the attempts above succeeded, log an error, mark as failed logging.error("Maximum retries exceeded") task_data['state'] = 'Completed' task_data['evaluated'] = True task_data['succeeded'] = False else: # This task will never be able to run, mark evaluated task_data['state'] = "Evaluated" task_data['evaluated'] = True completed += 1 else: waiting += 1 elif task_data['state'] == "Running": submission = sub_lookup[task_data['submissionId']] status = submission['status'] if status == "Done": # Look at the individual workflows to see if there were # failures logging.info("Workflow " + n + " completed for " + sset) success = 'Failed' not in submission['workflowStatuses'] task_data['evaluated'] = True task_data['succeeded'] = success task_data['state'] = "Completed" completed += 1 else: # Submission isn't done, don't do anything running += 1 else: # Either Completed or evaluated completed += 1 # Save the state of the monitor for recovery purposes # Have to do this for every workflow + sample_set so we don't lose track of any recovery_data['monitor_data'] = monitor_data recovery_data['dependencies'] = dependencies with open(recovery_file, 'w') as rf: json.dump(recovery_data, rf) logging.info("{0} Waiting, {1} Running, {2} Completed".format(waiting, running, completed)) # If all tasks have been evaluated, we are done if all(monitor_data[n][sset]['evaluated'] for n in monitor_data for sset in monitor_data[n]): logging.info("DONE.") break time.sleep(30)
Supervisor loop. Loop forever until all tasks are evaluated or completed
entailment
def space_list(args): ''' List accessible workspaces, in TSV form: <namespace><TAB>workspace''' r = fapi.list_workspaces() fapi._check_response_code(r, 200) spaces = [] project = args.project if project: project = re.compile('^' + project) for space in r.json(): ns = space['workspace']['namespace'] if project and not project.match(ns): continue ws = space['workspace']['name'] spaces.append(ns + '\t' + ws) # Sort for easier downstream viewing, ignoring case return sorted(spaces, key=lambda s: s.lower())
List accessible workspaces, in TSV form: <namespace><TAB>workspace
entailment
def space_exists(args): """ Determine if the named space exists in the given project (namespace)""" # The return value is the INVERSE of UNIX exit status semantics, (where # 0 = good/true, 1 = bad/false), so to check existence in UNIX one would do # if ! fissfc space_exists blah ; then # ... # fi try: r = fapi.get_workspace(args.project, args.workspace) fapi._check_response_code(r, 200) exists = True except FireCloudServerError as e: if e.code == 404: exists = False else: raise if fcconfig.verbosity: result = "DOES NOT" if not exists else "DOES" eprint('Space <%s> %s exist in project <%s>' % (args.workspace, result, args.project)) return exists
Determine if the named space exists in the given project (namespace)
entailment
def space_lock(args): """ Lock a workspace """ r = fapi.lock_workspace(args.project, args.workspace) fapi._check_response_code(r, 204) if fcconfig.verbosity: eprint('Locked workspace {0}/{1}'.format(args.project, args.workspace)) return 0
Lock a workspace
entailment
def space_unlock(args): """ Unlock a workspace """ r = fapi.unlock_workspace(args.project, args.workspace) fapi._check_response_code(r, 204) if fcconfig.verbosity: eprint('Unlocked workspace {0}/{1}'.format(args.project,args.workspace)) return 0
Unlock a workspace
entailment
def space_new(args): """ Create a new workspace. """ r = fapi.create_workspace(args.project, args.workspace, args.authdomain, dict()) fapi._check_response_code(r, 201) if fcconfig.verbosity: eprint(r.content) return 0
Create a new workspace.
entailment
def space_info(args): """ Get metadata for a workspace. """ r = fapi.get_workspace(args.project, args.workspace) fapi._check_response_code(r, 200) return r.text
Get metadata for a workspace.
entailment
def space_delete(args): """ Delete a workspace. """ message = "WARNING: this will delete workspace: \n\t{0}/{1}".format( args.project, args.workspace) if not args.yes and not _confirm_prompt(message): return 0 r = fapi.delete_workspace(args.project, args.workspace) fapi._check_response_code(r, [200, 202, 204, 404]) if fcconfig.verbosity: print('Deleted workspace {0}/{1}'.format(args.project, args.workspace)) return 0
Delete a workspace.
entailment
def space_clone(args): """ Replicate a workspace """ # FIXME: add --deep copy option (shallow by default) # add aliasing capability, then make space_copy alias if not args.to_workspace: args.to_workspace = args.workspace if not args.to_project: args.to_project = args.project if (args.project == args.to_project and args.workspace == args.to_workspace): eprint("Error: destination project and namespace must differ from" " cloned workspace") return 1 r = fapi.clone_workspace(args.project, args.workspace, args.to_project, args.to_workspace) fapi._check_response_code(r, 201) if fcconfig.verbosity: msg = "{}/{} successfully cloned to {}/{}".format( args.project, args.workspace, args.to_project, args.to_workspace) print(msg) return 0
Replicate a workspace
entailment
def space_acl(args): ''' Retrieve access control list for a workspace''' r = fapi.get_workspace_acl(args.project, args.workspace) fapi._check_response_code(r, 200) result = dict() for user, info in sorted(r.json()['acl'].items()): result[user] = info['accessLevel'] return result
Retrieve access control list for a workspace
entailment
def space_set_acl(args): """ Assign an ACL role to list of users for a workspace """ acl_updates = [{"email": user, "accessLevel": args.role} for user in args.users] r = fapi.update_workspace_acl(args.project, args.workspace, acl_updates) fapi._check_response_code(r, 200) errors = r.json()['usersNotFound'] if len(errors): eprint("Unable to assign role for unrecognized users:") for user in errors: eprint("\t{0}".format(user['email'])) return 1 if fcconfig.verbosity: print("Successfully updated {0} role(s)".format(len(acl_updates))) return 0
Assign an ACL role to list of users for a workspace
entailment
def space_search(args): """ Search for workspaces matching certain criteria """ r = fapi.list_workspaces() fapi._check_response_code(r, 200) # Parse the JSON for workspace + namespace; then filter by # search terms: each term is treated as a regular expression workspaces = r.json() extra_terms = [] if args.bucket: workspaces = [w for w in workspaces if re.search(args.bucket, w['workspace']['bucketName'])] extra_terms.append('bucket') # FIXME: add more filter terms pretty_spaces = [] for space in workspaces: ns = space['workspace']['namespace'] ws = space['workspace']['name'] pspace = ns + '/' + ws # Always show workspace storage id pspace += '\t' + space['workspace']['bucketName'] pretty_spaces.append(pspace) # Sort for easier viewing, ignore case return sorted(pretty_spaces, key=lambda s: s.lower())
Search for workspaces matching certain criteria
entailment
def entity_import(args): """ Upload an entity loadfile. """ project = args.project workspace = args.workspace chunk_size = args.chunk_size with open(args.tsvfile) as tsvf: headerline = tsvf.readline().strip() entity_data = [l.rstrip('\n') for l in tsvf] return _batch_load(project, workspace, headerline, entity_data, chunk_size)
Upload an entity loadfile.
entailment
def set_export(args): '''Return a list of lines in TSV form that would suffice to reconstitute a container (set) entity, if passed to entity_import. The first line in the list is the header, and subsequent lines are the container members. ''' r = fapi.get_entity(args.project, args.workspace, args.entity_type, args.entity) fapi._check_response_code(r, 200) set_type = args.entity_type set_name = args.entity member_type = set_type.split('_')[0] members = r.json()['attributes'][member_type+'s']['items'] result = ["membership:{}_id\t{}_id".format(set_type, member_type)] result += ["%s\t%s" % (set_name, m['entityName']) for m in members ] return result
Return a list of lines in TSV form that would suffice to reconstitute a container (set) entity, if passed to entity_import. The first line in the list is the header, and subsequent lines are the container members.
entailment
def entity_types(args): """ List entity types in a workspace """ r = fapi.list_entity_types(args.project, args.workspace) fapi._check_response_code(r, 200) return r.json().keys()
List entity types in a workspace
entailment
def entity_list(args): """ List entities in a workspace. """ r = fapi.get_entities_with_type(args.project, args.workspace) fapi._check_response_code(r, 200) return [ '{0}\t{1}'.format(e['entityType'], e['name']) for e in r.json() ]
List entities in a workspace.
entailment
def participant_list(args): ''' List participants within a container''' # Case 1: retrieve participants within a named data entity if args.entity_type and args.entity: # Edge case: caller asked for participant within participant (itself) if args.entity_type == 'participant': return [ args.entity.strip() ] # Otherwise retrieve the container entity r = fapi.get_entity(args.project, args.workspace, args.entity_type, args.entity) fapi._check_response_code(r, 200) participants = r.json()['attributes']["participants"]['items'] return [ participant['entityName'] for participant in participants ] # Case 2: retrieve all participants within a workspace return __get_entities(args, "participant", page_size=2000)
List participants within a container
entailment
def pair_list(args): ''' List pairs within a container. ''' # Case 1: retrieve pairs within a named data entity if args.entity_type and args.entity: # Edge case: caller asked for pair within a pair (itself) if args.entity_type == 'pair': return [ args.entity.strip() ] # Edge case: pairs for a participant, which has to be done hard way # by iteratiing over all samples (see firecloud/discussion/9648) elif args.entity_type == 'participant': entities = _entity_paginator(args.project, args.workspace, 'pair', page_size=2000) return [ e['name'] for e in entities if e['attributes']['participant']['entityName'] == args.entity] # Otherwise retrieve the container entity r = fapi.get_entity(args.project, args.workspace, args.entity_type, args.entity) fapi._check_response_code(r, 200) pairs = r.json()['attributes']["pairs"]['items'] return [ pair['entityName'] for pair in pairs] # Case 2: retrieve all pairs within a workspace return __get_entities(args, "pair", page_size=2000)
List pairs within a container.
entailment
def sample_list(args): ''' List samples within a container. ''' # Case 1: retrieve samples within a named data entity if args.entity_type and args.entity: # Edge case: caller asked for samples within a sample (itself) if args.entity_type == 'sample': return [ args.entity.strip() ] # Edge case: samples for a participant, which has to be done hard way # by iteratiing over all samples (see firecloud/discussion/9648) elif args.entity_type == 'participant': samples = _entity_paginator(args.project, args.workspace, 'sample', page_size=2000) return [ e['name'] for e in samples if e['attributes']['participant']['entityName'] == args.entity] # Otherwise retrieve the container entity r = fapi.get_entity(args.project, args.workspace, args.entity_type, args.entity) fapi._check_response_code(r, 200) if args.entity_type == 'pair': pair = r.json()['attributes'] samples = [ pair['case_sample'], pair['control_sample'] ] else: samples = r.json()['attributes']["samples"]['items'] return [ sample['entityName'] for sample in samples ] # Case 2: retrieve all samples within a workspace return __get_entities(args, "sample", page_size=2000)
List samples within a container.
entailment