partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
get_enrich
Execute the enrich phase for a given backend section :param config: a Mordred config object :param backend_section: the backend section where the enrich phase is executed
utils/micro.py
def get_enrich(config, backend_section): """Execute the enrich phase for a given backend section :param config: a Mordred config object :param backend_section: the backend section where the enrich phase is executed """ TaskProjects(config).execute() task = TaskEnrich(config, backend_section=backend_section) try: task.execute() logging.info("Loading enriched data finished!") except Exception as e: logging.error(str(e)) sys.exit(-1)
def get_enrich(config, backend_section): """Execute the enrich phase for a given backend section :param config: a Mordred config object :param backend_section: the backend section where the enrich phase is executed """ TaskProjects(config).execute() task = TaskEnrich(config, backend_section=backend_section) try: task.execute() logging.info("Loading enriched data finished!") except Exception as e: logging.error(str(e)) sys.exit(-1)
[ "Execute", "the", "enrich", "phase", "for", "a", "given", "backend", "section" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L104-L118
[ "def", "get_enrich", "(", "config", ",", "backend_section", ")", ":", "TaskProjects", "(", "config", ")", ".", "execute", "(", ")", "task", "=", "TaskEnrich", "(", "config", ",", "backend_section", "=", "backend_section", ")", "try", ":", "task", ".", "execute", "(", ")", "logging", ".", "info", "(", "\"Loading enriched data finished!\"", ")", "except", "Exception", "as", "e", ":", "logging", ".", "error", "(", "str", "(", "e", ")", ")", "sys", ".", "exit", "(", "-", "1", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
get_panels
Execute the panels phase :param config: a Mordred config object
utils/micro.py
def get_panels(config): """Execute the panels phase :param config: a Mordred config object """ task = TaskPanels(config) task.execute() task = TaskPanelsMenu(config) task.execute() logging.info("Panels creation finished!")
def get_panels(config): """Execute the panels phase :param config: a Mordred config object """ task = TaskPanels(config) task.execute() task = TaskPanelsMenu(config) task.execute() logging.info("Panels creation finished!")
[ "Execute", "the", "panels", "phase" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L121-L133
[ "def", "get_panels", "(", "config", ")", ":", "task", "=", "TaskPanels", "(", "config", ")", "task", ".", "execute", "(", ")", "task", "=", "TaskPanelsMenu", "(", "config", ")", "task", ".", "execute", "(", ")", "logging", ".", "info", "(", "\"Panels creation finished!\"", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
config_logging
Config logging level output output
utils/micro.py
def config_logging(debug): """Config logging level output output""" if debug: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') logging.debug("Debug mode activated") else: logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
def config_logging(debug): """Config logging level output output""" if debug: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') logging.debug("Debug mode activated") else: logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
[ "Config", "logging", "level", "output", "output" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L136-L143
[ "def", "config_logging", "(", "debug", ")", ":", "if", "debug", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ",", "format", "=", "'%(asctime)s %(message)s'", ")", "logging", ".", "debug", "(", "\"Debug mode activated\"", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(asctime)s %(message)s'", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
get_params_parser
Parse command line arguments
utils/micro.py
def get_params_parser(): """Parse command line arguments""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-g', '--debug', dest='debug', action='store_true', help=argparse.SUPPRESS) parser.add_argument("--arthur", action='store_true', dest='arthur', help="Enable arthur to collect raw data") parser.add_argument("--raw", action='store_true', dest='raw', help="Activate raw task") parser.add_argument("--enrich", action='store_true', dest='enrich', help="Activate enrich task") parser.add_argument("--identities", action='store_true', dest='identities', help="Activate merge identities task") parser.add_argument("--panels", action='store_true', dest='panels', help="Activate panels task") parser.add_argument("--cfg", dest='cfg_path', help="Configuration file path") parser.add_argument("--backends", dest='backend_sections', default=[], nargs='*', help="Backend sections to execute") if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser
def get_params_parser(): """Parse command line arguments""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-g', '--debug', dest='debug', action='store_true', help=argparse.SUPPRESS) parser.add_argument("--arthur", action='store_true', dest='arthur', help="Enable arthur to collect raw data") parser.add_argument("--raw", action='store_true', dest='raw', help="Activate raw task") parser.add_argument("--enrich", action='store_true', dest='enrich', help="Activate enrich task") parser.add_argument("--identities", action='store_true', dest='identities', help="Activate merge identities task") parser.add_argument("--panels", action='store_true', dest='panels', help="Activate panels task") parser.add_argument("--cfg", dest='cfg_path', help="Configuration file path") parser.add_argument("--backends", dest='backend_sections', default=[], nargs='*', help="Backend sections to execute") if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser
[ "Parse", "command", "line", "arguments" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L146-L174
[ "def", "get_params_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "'-g'", ",", "'--debug'", ",", "dest", "=", "'debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "argparse", ".", "SUPPRESS", ")", "parser", ".", "add_argument", "(", "\"--arthur\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'arthur'", ",", "help", "=", "\"Enable arthur to collect raw data\"", ")", "parser", ".", "add_argument", "(", "\"--raw\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'raw'", ",", "help", "=", "\"Activate raw task\"", ")", "parser", ".", "add_argument", "(", "\"--enrich\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'enrich'", ",", "help", "=", "\"Activate enrich task\"", ")", "parser", ".", "add_argument", "(", "\"--identities\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'identities'", ",", "help", "=", "\"Activate merge identities task\"", ")", "parser", ".", "add_argument", "(", "\"--panels\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'panels'", ",", "help", "=", "\"Activate panels task\"", ")", "parser", ".", "add_argument", "(", "\"--cfg\"", ",", "dest", "=", "'cfg_path'", ",", "help", "=", "\"Configuration file path\"", ")", "parser", ".", "add_argument", "(", "\"--backends\"", ",", "dest", "=", "'backend_sections'", ",", "default", "=", "[", "]", ",", "nargs", "=", "'*'", ",", "help", "=", "\"Backend sections to execute\"", ")", "if", "len", "(", "sys", ".", "argv", ")", "==", "1", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "return", "parser" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
get_params
Get params to execute the micro-mordred
utils/micro.py
def get_params(): """Get params to execute the micro-mordred""" parser = get_params_parser() args = parser.parse_args() if not args.raw and not args.enrich and not args.identities and not args.panels: print("No tasks enabled") sys.exit(1) return args
def get_params(): """Get params to execute the micro-mordred""" parser = get_params_parser() args = parser.parse_args() if not args.raw and not args.enrich and not args.identities and not args.panels: print("No tasks enabled") sys.exit(1) return args
[ "Get", "params", "to", "execute", "the", "micro", "-", "mordred" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L177-L187
[ "def", "get_params", "(", ")", ":", "parser", "=", "get_params_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "args", ".", "raw", "and", "not", "args", ".", "enrich", "and", "not", "args", ".", "identities", "and", "not", "args", ".", "panels", ":", "print", "(", "\"No tasks enabled\"", ")", "sys", ".", "exit", "(", "1", ")", "return", "args" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanels.__kibiter_version
Get the kibiter vesion. :param major: major Elasticsearch version
sirmordred/task_panels.py
def __kibiter_version(self): """ Get the kibiter vesion. :param major: major Elasticsearch version """ version = None es_url = self.conf['es_enrichment']['url'] config_url = '.kibana/config/_search' url = urijoin(es_url, config_url) version = None try: res = self.grimoire_con.get(url) res.raise_for_status() version = res.json()['hits']['hits'][0]['_id'] logger.debug("Kibiter version: %s", version) except requests.exceptions.HTTPError: logger.warning("Can not find Kibiter version") return version
def __kibiter_version(self): """ Get the kibiter vesion. :param major: major Elasticsearch version """ version = None es_url = self.conf['es_enrichment']['url'] config_url = '.kibana/config/_search' url = urijoin(es_url, config_url) version = None try: res = self.grimoire_con.get(url) res.raise_for_status() version = res.json()['hits']['hits'][0]['_id'] logger.debug("Kibiter version: %s", version) except requests.exceptions.HTTPError: logger.warning("Can not find Kibiter version") return version
[ "Get", "the", "kibiter", "vesion", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L232-L251
[ "def", "__kibiter_version", "(", "self", ")", ":", "version", "=", "None", "es_url", "=", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "config_url", "=", "'.kibana/config/_search'", "url", "=", "urijoin", "(", "es_url", ",", "config_url", ")", "version", "=", "None", "try", ":", "res", "=", "self", ".", "grimoire_con", ".", "get", "(", "url", ")", "res", ".", "raise_for_status", "(", ")", "version", "=", "res", ".", "json", "(", ")", "[", "'hits'", "]", "[", "'hits'", "]", "[", "0", "]", "[", "'_id'", "]", "logger", ".", "debug", "(", "\"Kibiter version: %s\"", ",", "version", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "warning", "(", "\"Can not find Kibiter version\"", ")", "return", "version" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanels.create_dashboard
Upload a panel to Elasticsearch if it does not exist yet. If a list of data sources is specified, upload only those elements (visualizations, searches) that match that data source. :param panel_file: file name of panel (dashobard) to upload :param data_sources: list of data sources :param strict: only upload a dashboard if it is newer than the one already existing
sirmordred/task_panels.py
def create_dashboard(self, panel_file, data_sources=None, strict=True): """Upload a panel to Elasticsearch if it does not exist yet. If a list of data sources is specified, upload only those elements (visualizations, searches) that match that data source. :param panel_file: file name of panel (dashobard) to upload :param data_sources: list of data sources :param strict: only upload a dashboard if it is newer than the one already existing """ es_enrich = self.conf['es_enrichment']['url'] kibana_url = self.conf['panels']['kibiter_url'] mboxes_sources = set(['pipermail', 'hyperkitty', 'groupsio', 'nntp']) if data_sources and any(x in data_sources for x in mboxes_sources): data_sources = list(data_sources) data_sources.append('mbox') if data_sources and ('supybot' in data_sources): data_sources = list(data_sources) data_sources.append('irc') if data_sources and 'google_hits' in data_sources: data_sources = list(data_sources) data_sources.append('googlehits') if data_sources and 'stackexchange' in data_sources: # stackexchange is called stackoverflow in panels data_sources = list(data_sources) data_sources.append('stackoverflow') if data_sources and 'phabricator' in data_sources: data_sources = list(data_sources) data_sources.append('maniphest') try: import_dashboard(es_enrich, kibana_url, panel_file, data_sources=data_sources, strict=strict) except ValueError: logger.error("%s does not include release field. Not loading the panel.", panel_file) except RuntimeError: logger.error("Can not load the panel %s", panel_file)
def create_dashboard(self, panel_file, data_sources=None, strict=True): """Upload a panel to Elasticsearch if it does not exist yet. If a list of data sources is specified, upload only those elements (visualizations, searches) that match that data source. :param panel_file: file name of panel (dashobard) to upload :param data_sources: list of data sources :param strict: only upload a dashboard if it is newer than the one already existing """ es_enrich = self.conf['es_enrichment']['url'] kibana_url = self.conf['panels']['kibiter_url'] mboxes_sources = set(['pipermail', 'hyperkitty', 'groupsio', 'nntp']) if data_sources and any(x in data_sources for x in mboxes_sources): data_sources = list(data_sources) data_sources.append('mbox') if data_sources and ('supybot' in data_sources): data_sources = list(data_sources) data_sources.append('irc') if data_sources and 'google_hits' in data_sources: data_sources = list(data_sources) data_sources.append('googlehits') if data_sources and 'stackexchange' in data_sources: # stackexchange is called stackoverflow in panels data_sources = list(data_sources) data_sources.append('stackoverflow') if data_sources and 'phabricator' in data_sources: data_sources = list(data_sources) data_sources.append('maniphest') try: import_dashboard(es_enrich, kibana_url, panel_file, data_sources=data_sources, strict=strict) except ValueError: logger.error("%s does not include release field. Not loading the panel.", panel_file) except RuntimeError: logger.error("Can not load the panel %s", panel_file)
[ "Upload", "a", "panel", "to", "Elasticsearch", "if", "it", "does", "not", "exist", "yet", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L338-L374
[ "def", "create_dashboard", "(", "self", ",", "panel_file", ",", "data_sources", "=", "None", ",", "strict", "=", "True", ")", ":", "es_enrich", "=", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "kibana_url", "=", "self", ".", "conf", "[", "'panels'", "]", "[", "'kibiter_url'", "]", "mboxes_sources", "=", "set", "(", "[", "'pipermail'", ",", "'hyperkitty'", ",", "'groupsio'", ",", "'nntp'", "]", ")", "if", "data_sources", "and", "any", "(", "x", "in", "data_sources", "for", "x", "in", "mboxes_sources", ")", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'mbox'", ")", "if", "data_sources", "and", "(", "'supybot'", "in", "data_sources", ")", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'irc'", ")", "if", "data_sources", "and", "'google_hits'", "in", "data_sources", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'googlehits'", ")", "if", "data_sources", "and", "'stackexchange'", "in", "data_sources", ":", "# stackexchange is called stackoverflow in panels", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'stackoverflow'", ")", "if", "data_sources", "and", "'phabricator'", "in", "data_sources", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'maniphest'", ")", "try", ":", "import_dashboard", "(", "es_enrich", ",", "kibana_url", ",", "panel_file", ",", "data_sources", "=", "data_sources", ",", "strict", "=", "strict", ")", "except", "ValueError", ":", "logger", ".", "error", "(", "\"%s does not include release field. Not loading the panel.\"", ",", "panel_file", ")", "except", "RuntimeError", ":", "logger", ".", "error", "(", "\"Can not load the panel %s\"", ",", "panel_file", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanelsMenu.__upload_title
Upload to Kibiter the title for the dashboard. The title is shown on top of the dashboard menu, and is Usually the name of the project being dashboarded. This is done only for Kibiter 6.x. :param kibiter_major: major version of kibiter
sirmordred/task_panels.py
def __upload_title(self, kibiter_major): """Upload to Kibiter the title for the dashboard. The title is shown on top of the dashboard menu, and is Usually the name of the project being dashboarded. This is done only for Kibiter 6.x. :param kibiter_major: major version of kibiter """ if kibiter_major == "6": resource = ".kibana/doc/projectname" data = {"projectname": {"name": self.project_name}} mapping_resource = ".kibana/_mapping/doc" mapping = {"dynamic": "true"} url = urijoin(self.conf['es_enrichment']['url'], resource) mapping_url = urijoin(self.conf['es_enrichment']['url'], mapping_resource) logger.debug("Adding mapping for dashboard title") res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create mapping for dashboard title.") logger.error(res.json()) logger.debug("Uploading dashboard title") res = self.grimoire_con.post(url, data=json.dumps(data), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create dashboard title.") logger.error(res.json())
def __upload_title(self, kibiter_major): """Upload to Kibiter the title for the dashboard. The title is shown on top of the dashboard menu, and is Usually the name of the project being dashboarded. This is done only for Kibiter 6.x. :param kibiter_major: major version of kibiter """ if kibiter_major == "6": resource = ".kibana/doc/projectname" data = {"projectname": {"name": self.project_name}} mapping_resource = ".kibana/_mapping/doc" mapping = {"dynamic": "true"} url = urijoin(self.conf['es_enrichment']['url'], resource) mapping_url = urijoin(self.conf['es_enrichment']['url'], mapping_resource) logger.debug("Adding mapping for dashboard title") res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create mapping for dashboard title.") logger.error(res.json()) logger.debug("Uploading dashboard title") res = self.grimoire_con.post(url, data=json.dumps(data), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create dashboard title.") logger.error(res.json())
[ "Upload", "to", "Kibiter", "the", "title", "for", "the", "dashboard", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L481-L517
[ "def", "__upload_title", "(", "self", ",", "kibiter_major", ")", ":", "if", "kibiter_major", "==", "\"6\"", ":", "resource", "=", "\".kibana/doc/projectname\"", "data", "=", "{", "\"projectname\"", ":", "{", "\"name\"", ":", "self", ".", "project_name", "}", "}", "mapping_resource", "=", "\".kibana/_mapping/doc\"", "mapping", "=", "{", "\"dynamic\"", ":", "\"true\"", "}", "url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "resource", ")", "mapping_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "mapping_resource", ")", "logger", ".", "debug", "(", "\"Adding mapping for dashboard title\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "put", "(", "mapping_url", ",", "data", "=", "json", ".", "dumps", "(", "mapping", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create mapping for dashboard title.\"", ")", "logger", ".", "error", "(", "res", ".", "json", "(", ")", ")", "logger", ".", "debug", "(", "\"Uploading dashboard title\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create dashboard title.\"", ")", "logger", ".", "error", "(", "res", ".", "json", "(", ")", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanelsMenu.__create_dashboard_menu
Create the menu definition to access the panels in a dashboard. :param menu: dashboard menu to upload :param kibiter_major: major version of kibiter
sirmordred/task_panels.py
def __create_dashboard_menu(self, dash_menu, kibiter_major): """Create the menu definition to access the panels in a dashboard. :param menu: dashboard menu to upload :param kibiter_major: major version of kibiter """ logger.info("Adding dashboard menu") if kibiter_major == "6": menu_resource = ".kibana/doc/metadashboard" mapping_resource = ".kibana/_mapping/doc" mapping = {"dynamic": "true"} menu = {'metadashboard': dash_menu} else: menu_resource = ".kibana/metadashboard/main" mapping_resource = ".kibana/_mapping/metadashboard" mapping = {"dynamic": "true"} menu = dash_menu menu_url = urijoin(self.conf['es_enrichment']['url'], menu_resource) mapping_url = urijoin(self.conf['es_enrichment']['url'], mapping_resource) logger.debug("Adding mapping for metadashboard") res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create mapping for Kibiter menu.") res = self.grimoire_con.post(menu_url, data=json.dumps(menu), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create Kibiter menu.") logger.error(res.json()) raise
def __create_dashboard_menu(self, dash_menu, kibiter_major): """Create the menu definition to access the panels in a dashboard. :param menu: dashboard menu to upload :param kibiter_major: major version of kibiter """ logger.info("Adding dashboard menu") if kibiter_major == "6": menu_resource = ".kibana/doc/metadashboard" mapping_resource = ".kibana/_mapping/doc" mapping = {"dynamic": "true"} menu = {'metadashboard': dash_menu} else: menu_resource = ".kibana/metadashboard/main" mapping_resource = ".kibana/_mapping/metadashboard" mapping = {"dynamic": "true"} menu = dash_menu menu_url = urijoin(self.conf['es_enrichment']['url'], menu_resource) mapping_url = urijoin(self.conf['es_enrichment']['url'], mapping_resource) logger.debug("Adding mapping for metadashboard") res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create mapping for Kibiter menu.") res = self.grimoire_con.post(menu_url, data=json.dumps(menu), headers=ES6_HEADER) try: res.raise_for_status() except requests.exceptions.HTTPError: logger.error("Couldn't create Kibiter menu.") logger.error(res.json()) raise
[ "Create", "the", "menu", "definition", "to", "access", "the", "panels", "in", "a", "dashboard", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L519-L555
[ "def", "__create_dashboard_menu", "(", "self", ",", "dash_menu", ",", "kibiter_major", ")", ":", "logger", ".", "info", "(", "\"Adding dashboard menu\"", ")", "if", "kibiter_major", "==", "\"6\"", ":", "menu_resource", "=", "\".kibana/doc/metadashboard\"", "mapping_resource", "=", "\".kibana/_mapping/doc\"", "mapping", "=", "{", "\"dynamic\"", ":", "\"true\"", "}", "menu", "=", "{", "'metadashboard'", ":", "dash_menu", "}", "else", ":", "menu_resource", "=", "\".kibana/metadashboard/main\"", "mapping_resource", "=", "\".kibana/_mapping/metadashboard\"", "mapping", "=", "{", "\"dynamic\"", ":", "\"true\"", "}", "menu", "=", "dash_menu", "menu_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "menu_resource", ")", "mapping_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "mapping_resource", ")", "logger", ".", "debug", "(", "\"Adding mapping for metadashboard\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "put", "(", "mapping_url", ",", "data", "=", "json", ".", "dumps", "(", "mapping", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create mapping for Kibiter menu.\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "post", "(", "menu_url", ",", "data", "=", "json", ".", "dumps", "(", "menu", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create Kibiter menu.\"", ")", "logger", ".", "error", "(", "res", ".", "json", "(", ")", ")", "raise" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanelsMenu.__remove_dashboard_menu
Remove existing menu for dashboard, if any. Usually, we remove the menu before creating a new one. :param kibiter_major: major version of kibiter
sirmordred/task_panels.py
def __remove_dashboard_menu(self, kibiter_major): """Remove existing menu for dashboard, if any. Usually, we remove the menu before creating a new one. :param kibiter_major: major version of kibiter """ logger.info("Removing old dashboard menu, if any") if kibiter_major == "6": metadashboard = ".kibana/doc/metadashboard" else: metadashboard = ".kibana/metadashboard/main" menu_url = urijoin(self.conf['es_enrichment']['url'], metadashboard) self.grimoire_con.delete(menu_url)
def __remove_dashboard_menu(self, kibiter_major): """Remove existing menu for dashboard, if any. Usually, we remove the menu before creating a new one. :param kibiter_major: major version of kibiter """ logger.info("Removing old dashboard menu, if any") if kibiter_major == "6": metadashboard = ".kibana/doc/metadashboard" else: metadashboard = ".kibana/metadashboard/main" menu_url = urijoin(self.conf['es_enrichment']['url'], metadashboard) self.grimoire_con.delete(menu_url)
[ "Remove", "existing", "menu", "for", "dashboard", "if", "any", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L557-L570
[ "def", "__remove_dashboard_menu", "(", "self", ",", "kibiter_major", ")", ":", "logger", ".", "info", "(", "\"Removing old dashboard menu, if any\"", ")", "if", "kibiter_major", "==", "\"6\"", ":", "metadashboard", "=", "\".kibana/doc/metadashboard\"", "else", ":", "metadashboard", "=", "\".kibana/metadashboard/main\"", "menu_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "metadashboard", ")", "self", ".", "grimoire_con", ".", "delete", "(", "menu_url", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanelsMenu.__get_menu_entries
Get the menu entries from the panel definition
sirmordred/task_panels.py
def __get_menu_entries(self, kibiter_major): """ Get the menu entries from the panel definition """ menu_entries = [] for entry in self.panels_menu: if entry['source'] not in self.data_sources: continue parent_menu_item = { 'name': entry['name'], 'title': entry['name'], 'description': "", 'type': "menu", 'dashboards': [] } for subentry in entry['menu']: try: dash_name = get_dashboard_name(subentry['panel']) except FileNotFoundError: logging.error("Can't open dashboard file %s", subentry['panel']) continue # The name for the entry is in self.panels_menu child_item = { "name": subentry['name'], "title": subentry['name'], "description": "", "type": "entry", "panel_id": dash_name } parent_menu_item['dashboards'].append(child_item) menu_entries.append(parent_menu_item) return menu_entries
def __get_menu_entries(self, kibiter_major): """ Get the menu entries from the panel definition """ menu_entries = [] for entry in self.panels_menu: if entry['source'] not in self.data_sources: continue parent_menu_item = { 'name': entry['name'], 'title': entry['name'], 'description': "", 'type': "menu", 'dashboards': [] } for subentry in entry['menu']: try: dash_name = get_dashboard_name(subentry['panel']) except FileNotFoundError: logging.error("Can't open dashboard file %s", subentry['panel']) continue # The name for the entry is in self.panels_menu child_item = { "name": subentry['name'], "title": subentry['name'], "description": "", "type": "entry", "panel_id": dash_name } parent_menu_item['dashboards'].append(child_item) menu_entries.append(parent_menu_item) return menu_entries
[ "Get", "the", "menu", "entries", "from", "the", "panel", "definition" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L572-L602
[ "def", "__get_menu_entries", "(", "self", ",", "kibiter_major", ")", ":", "menu_entries", "=", "[", "]", "for", "entry", "in", "self", ".", "panels_menu", ":", "if", "entry", "[", "'source'", "]", "not", "in", "self", ".", "data_sources", ":", "continue", "parent_menu_item", "=", "{", "'name'", ":", "entry", "[", "'name'", "]", ",", "'title'", ":", "entry", "[", "'name'", "]", ",", "'description'", ":", "\"\"", ",", "'type'", ":", "\"menu\"", ",", "'dashboards'", ":", "[", "]", "}", "for", "subentry", "in", "entry", "[", "'menu'", "]", ":", "try", ":", "dash_name", "=", "get_dashboard_name", "(", "subentry", "[", "'panel'", "]", ")", "except", "FileNotFoundError", ":", "logging", ".", "error", "(", "\"Can't open dashboard file %s\"", ",", "subentry", "[", "'panel'", "]", ")", "continue", "# The name for the entry is in self.panels_menu", "child_item", "=", "{", "\"name\"", ":", "subentry", "[", "'name'", "]", ",", "\"title\"", ":", "subentry", "[", "'name'", "]", ",", "\"description\"", ":", "\"\"", ",", "\"type\"", ":", "\"entry\"", ",", "\"panel_id\"", ":", "dash_name", "}", "parent_menu_item", "[", "'dashboards'", "]", ".", "append", "(", "child_item", ")", "menu_entries", ".", "append", "(", "parent_menu_item", ")", "return", "menu_entries" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskPanelsMenu.__get_dash_menu
Order the dashboard menu
sirmordred/task_panels.py
def __get_dash_menu(self, kibiter_major): """Order the dashboard menu""" # omenu = OrderedDict() omenu = [] # Start with Overview omenu.append(self.menu_panels_common['Overview']) # Now the data _getsources ds_menu = self.__get_menu_entries(kibiter_major) # Remove the kafka and community menus, they will be included at the end kafka_menu = None community_menu = None found_kafka = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == KAFKA_NAME] if found_kafka: kafka_menu = ds_menu.pop(found_kafka[0]) found_community = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == COMMUNITY_NAME] if found_community: community_menu = ds_menu.pop(found_community[0]) ds_menu.sort(key=operator.itemgetter('name')) omenu += ds_menu # If kafka and community are present add them before the Data Status and About if kafka_menu: omenu.append(kafka_menu) if community_menu: omenu.append(community_menu) # At the end Data Status, About omenu.append(self.menu_panels_common['Data Status']) omenu.append(self.menu_panels_common['About']) logger.debug("Menu for panels: %s", json.dumps(ds_menu, indent=4)) return omenu
def __get_dash_menu(self, kibiter_major): """Order the dashboard menu""" # omenu = OrderedDict() omenu = [] # Start with Overview omenu.append(self.menu_panels_common['Overview']) # Now the data _getsources ds_menu = self.__get_menu_entries(kibiter_major) # Remove the kafka and community menus, they will be included at the end kafka_menu = None community_menu = None found_kafka = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == KAFKA_NAME] if found_kafka: kafka_menu = ds_menu.pop(found_kafka[0]) found_community = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == COMMUNITY_NAME] if found_community: community_menu = ds_menu.pop(found_community[0]) ds_menu.sort(key=operator.itemgetter('name')) omenu += ds_menu # If kafka and community are present add them before the Data Status and About if kafka_menu: omenu.append(kafka_menu) if community_menu: omenu.append(community_menu) # At the end Data Status, About omenu.append(self.menu_panels_common['Data Status']) omenu.append(self.menu_panels_common['About']) logger.debug("Menu for panels: %s", json.dumps(ds_menu, indent=4)) return omenu
[ "Order", "the", "dashboard", "menu" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L604-L642
[ "def", "__get_dash_menu", "(", "self", ",", "kibiter_major", ")", ":", "# omenu = OrderedDict()", "omenu", "=", "[", "]", "# Start with Overview", "omenu", ".", "append", "(", "self", ".", "menu_panels_common", "[", "'Overview'", "]", ")", "# Now the data _getsources", "ds_menu", "=", "self", ".", "__get_menu_entries", "(", "kibiter_major", ")", "# Remove the kafka and community menus, they will be included at the end", "kafka_menu", "=", "None", "community_menu", "=", "None", "found_kafka", "=", "[", "pos", "for", "pos", ",", "menu", "in", "enumerate", "(", "ds_menu", ")", "if", "menu", "[", "'name'", "]", "==", "KAFKA_NAME", "]", "if", "found_kafka", ":", "kafka_menu", "=", "ds_menu", ".", "pop", "(", "found_kafka", "[", "0", "]", ")", "found_community", "=", "[", "pos", "for", "pos", ",", "menu", "in", "enumerate", "(", "ds_menu", ")", "if", "menu", "[", "'name'", "]", "==", "COMMUNITY_NAME", "]", "if", "found_community", ":", "community_menu", "=", "ds_menu", ".", "pop", "(", "found_community", "[", "0", "]", ")", "ds_menu", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "'name'", ")", ")", "omenu", "+=", "ds_menu", "# If kafka and community are present add them before the Data Status and About", "if", "kafka_menu", ":", "omenu", ".", "append", "(", "kafka_menu", ")", "if", "community_menu", ":", "omenu", ".", "append", "(", "community_menu", ")", "# At the end Data Status, About", "omenu", ".", "append", "(", "self", ".", "menu_panels_common", "[", "'Data Status'", "]", ")", "omenu", ".", "append", "(", "self", ".", "menu_panels_common", "[", "'About'", "]", ")", "logger", ".", "debug", "(", "\"Menu for panels: %s\"", ",", "json", ".", "dumps", "(", "ds_menu", ",", "indent", "=", "4", ")", ")", "return", "omenu" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_mbox
Compose projects.json only for mbox, but using the mailing_lists lists change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev' to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox :param projects: projects.json :return: projects.json with mbox
sirmordred/eclipse_projects_lib.py
def compose_mbox(projects): """ Compose projects.json only for mbox, but using the mailing_lists lists change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev' to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox :param projects: projects.json :return: projects.json with mbox """ mbox_archives = '/home/bitergia/mboxes' mailing_lists_projects = [project for project in projects if 'mailing_lists' in projects[project]] for mailing_lists in mailing_lists_projects: projects[mailing_lists]['mbox'] = [] for mailing_list in projects[mailing_lists]['mailing_lists']: if 'listinfo' in mailing_list: name = mailing_list.split('listinfo/')[1] elif 'mailing-list' in mailing_list: name = mailing_list.split('mailing-list/')[1] else: name = mailing_list.split('@')[0] list_new = "%s %s/%s.mbox/%s.mbox" % (name, mbox_archives, name, name) projects[mailing_lists]['mbox'].append(list_new) return projects
def compose_mbox(projects): """ Compose projects.json only for mbox, but using the mailing_lists lists change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev' to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox :param projects: projects.json :return: projects.json with mbox """ mbox_archives = '/home/bitergia/mboxes' mailing_lists_projects = [project for project in projects if 'mailing_lists' in projects[project]] for mailing_lists in mailing_lists_projects: projects[mailing_lists]['mbox'] = [] for mailing_list in projects[mailing_lists]['mailing_lists']: if 'listinfo' in mailing_list: name = mailing_list.split('listinfo/')[1] elif 'mailing-list' in mailing_list: name = mailing_list.split('mailing-list/')[1] else: name = mailing_list.split('@')[0] list_new = "%s %s/%s.mbox/%s.mbox" % (name, mbox_archives, name, name) projects[mailing_lists]['mbox'].append(list_new) return projects
[ "Compose", "projects", ".", "json", "only", "for", "mbox", "but", "using", "the", "mailing_lists", "lists" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L27-L52
[ "def", "compose_mbox", "(", "projects", ")", ":", "mbox_archives", "=", "'/home/bitergia/mboxes'", "mailing_lists_projects", "=", "[", "project", "for", "project", "in", "projects", "if", "'mailing_lists'", "in", "projects", "[", "project", "]", "]", "for", "mailing_lists", "in", "mailing_lists_projects", ":", "projects", "[", "mailing_lists", "]", "[", "'mbox'", "]", "=", "[", "]", "for", "mailing_list", "in", "projects", "[", "mailing_lists", "]", "[", "'mailing_lists'", "]", ":", "if", "'listinfo'", "in", "mailing_list", ":", "name", "=", "mailing_list", ".", "split", "(", "'listinfo/'", ")", "[", "1", "]", "elif", "'mailing-list'", "in", "mailing_list", ":", "name", "=", "mailing_list", ".", "split", "(", "'mailing-list/'", ")", "[", "1", "]", "else", ":", "name", "=", "mailing_list", ".", "split", "(", "'@'", ")", "[", "0", "]", "list_new", "=", "\"%s %s/%s.mbox/%s.mbox\"", "%", "(", "name", ",", "mbox_archives", ",", "name", ",", "name", ")", "projects", "[", "mailing_lists", "]", "[", "'mbox'", "]", ".", "append", "(", "list_new", ")", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_gerrit
Compose projects.json for gerrit, but using the git lists change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git' to: 'git.eclipse.org_xwt/org.eclipse.xwt :param projects: projects.json :return: projects.json with gerrit
sirmordred/eclipse_projects_lib.py
def compose_gerrit(projects): """ Compose projects.json for gerrit, but using the git lists change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git' to: 'git.eclipse.org_xwt/org.eclipse.xwt :param projects: projects.json :return: projects.json with gerrit """ git_projects = [project for project in projects if 'git' in projects[project]] for project in git_projects: repos = [repo for repo in projects[project]['git'] if 'gitroot' in repo] if len(repos) > 0: projects[project]['gerrit'] = [] for repo in repos: gerrit_project = repo.replace("http://git.eclipse.org/gitroot/", "") gerrit_project = gerrit_project.replace(".git", "") projects[project]['gerrit'].append("git.eclipse.org_" + gerrit_project) return projects
def compose_gerrit(projects): """ Compose projects.json for gerrit, but using the git lists change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git' to: 'git.eclipse.org_xwt/org.eclipse.xwt :param projects: projects.json :return: projects.json with gerrit """ git_projects = [project for project in projects if 'git' in projects[project]] for project in git_projects: repos = [repo for repo in projects[project]['git'] if 'gitroot' in repo] if len(repos) > 0: projects[project]['gerrit'] = [] for repo in repos: gerrit_project = repo.replace("http://git.eclipse.org/gitroot/", "") gerrit_project = gerrit_project.replace(".git", "") projects[project]['gerrit'].append("git.eclipse.org_" + gerrit_project) return projects
[ "Compose", "projects", ".", "json", "for", "gerrit", "but", "using", "the", "git", "lists" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L55-L74
[ "def", "compose_gerrit", "(", "projects", ")", ":", "git_projects", "=", "[", "project", "for", "project", "in", "projects", "if", "'git'", "in", "projects", "[", "project", "]", "]", "for", "project", "in", "git_projects", ":", "repos", "=", "[", "repo", "for", "repo", "in", "projects", "[", "project", "]", "[", "'git'", "]", "if", "'gitroot'", "in", "repo", "]", "if", "len", "(", "repos", ")", ">", "0", ":", "projects", "[", "project", "]", "[", "'gerrit'", "]", "=", "[", "]", "for", "repo", "in", "repos", ":", "gerrit_project", "=", "repo", ".", "replace", "(", "\"http://git.eclipse.org/gitroot/\"", ",", "\"\"", ")", "gerrit_project", "=", "gerrit_project", ".", "replace", "(", "\".git\"", ",", "\"\"", ")", "projects", "[", "project", "]", "[", "'gerrit'", "]", ".", "append", "(", "\"git.eclipse.org_\"", "+", "gerrit_project", ")", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_git
Compose projects.json for git We need to replace '/c/' by '/gitroot/' for instance change: 'http://git.eclipse.org/c/xwt/org.eclipse.xwt.git' to: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git' :param projects: projects.json :param data: eclipse JSON :return: projects.json with git
sirmordred/eclipse_projects_lib.py
def compose_git(projects, data): """ Compose projects.json for git We need to replace '/c/' by '/gitroot/' for instance change: 'http://git.eclipse.org/c/xwt/org.eclipse.xwt.git' to: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git' :param projects: projects.json :param data: eclipse JSON :return: projects.json with git """ for p in [project for project in data if len(data[project]['source_repo']) > 0]: repos = [] for url in data[p]['source_repo']: if len(url['url'].split()) > 1: # Error at upstream the project 'tools.corrosion' repo = url['url'].split()[1].replace('/c/', '/gitroot/') else: repo = url['url'].replace('/c/', '/gitroot/') if repo not in repos: repos.append(repo) projects[p]['git'] = repos return projects
def compose_git(projects, data): """ Compose projects.json for git We need to replace '/c/' by '/gitroot/' for instance change: 'http://git.eclipse.org/c/xwt/org.eclipse.xwt.git' to: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git' :param projects: projects.json :param data: eclipse JSON :return: projects.json with git """ for p in [project for project in data if len(data[project]['source_repo']) > 0]: repos = [] for url in data[p]['source_repo']: if len(url['url'].split()) > 1: # Error at upstream the project 'tools.corrosion' repo = url['url'].split()[1].replace('/c/', '/gitroot/') else: repo = url['url'].replace('/c/', '/gitroot/') if repo not in repos: repos.append(repo) projects[p]['git'] = repos return projects
[ "Compose", "projects", ".", "json", "for", "git" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L77-L102
[ "def", "compose_git", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'source_repo'", "]", ")", ">", "0", "]", ":", "repos", "=", "[", "]", "for", "url", "in", "data", "[", "p", "]", "[", "'source_repo'", "]", ":", "if", "len", "(", "url", "[", "'url'", "]", ".", "split", "(", ")", ")", ">", "1", ":", "# Error at upstream the project 'tools.corrosion'", "repo", "=", "url", "[", "'url'", "]", ".", "split", "(", ")", "[", "1", "]", ".", "replace", "(", "'/c/'", ",", "'/gitroot/'", ")", "else", ":", "repo", "=", "url", "[", "'url'", "]", ".", "replace", "(", "'/c/'", ",", "'/gitroot/'", ")", "if", "repo", "not", "in", "repos", ":", "repos", ".", "append", "(", "repo", ")", "projects", "[", "p", "]", "[", "'git'", "]", "=", "repos", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_mailing_lists
Compose projects.json for mailing lists At upstream has two different key for mailing list: 'mailings_lists' and 'dev_list' The key 'mailing_lists' is an array with mailing lists The key 'dev_list' is a dict with only one mailing list :param projects: projects.json :param data: eclipse JSON :return: projects.json with mailing_lists
sirmordred/eclipse_projects_lib.py
def compose_mailing_lists(projects, data): """ Compose projects.json for mailing lists At upstream has two different key for mailing list: 'mailings_lists' and 'dev_list' The key 'mailing_lists' is an array with mailing lists The key 'dev_list' is a dict with only one mailing list :param projects: projects.json :param data: eclipse JSON :return: projects.json with mailing_lists """ for p in [project for project in data if len(data[project]['mailing_lists']) > 0]: if 'mailing_lists' not in projects[p]: projects[p]['mailing_lists'] = [] urls = [url['url'].replace('mailto:', '') for url in data[p]['mailing_lists'] if url['url'] not in projects[p]['mailing_lists']] projects[p]['mailing_lists'] += urls for p in [project for project in data if len(data[project]['dev_list']) > 0]: if 'mailing_lists' not in projects[p]: projects[p]['mailing_lists'] = [] mailing_list = data[p]['dev_list']['url'].replace('mailto:', '') projects[p]['mailing_lists'].append(mailing_list) return projects
def compose_mailing_lists(projects, data): """ Compose projects.json for mailing lists At upstream has two different key for mailing list: 'mailings_lists' and 'dev_list' The key 'mailing_lists' is an array with mailing lists The key 'dev_list' is a dict with only one mailing list :param projects: projects.json :param data: eclipse JSON :return: projects.json with mailing_lists """ for p in [project for project in data if len(data[project]['mailing_lists']) > 0]: if 'mailing_lists' not in projects[p]: projects[p]['mailing_lists'] = [] urls = [url['url'].replace('mailto:', '') for url in data[p]['mailing_lists'] if url['url'] not in projects[p]['mailing_lists']] projects[p]['mailing_lists'] += urls for p in [project for project in data if len(data[project]['dev_list']) > 0]: if 'mailing_lists' not in projects[p]: projects[p]['mailing_lists'] = [] mailing_list = data[p]['dev_list']['url'].replace('mailto:', '') projects[p]['mailing_lists'].append(mailing_list) return projects
[ "Compose", "projects", ".", "json", "for", "mailing", "lists" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L105-L131
[ "def", "compose_mailing_lists", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'mailing_lists'", "]", ")", ">", "0", "]", ":", "if", "'mailing_lists'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "=", "[", "]", "urls", "=", "[", "url", "[", "'url'", "]", ".", "replace", "(", "'mailto:'", ",", "''", ")", "for", "url", "in", "data", "[", "p", "]", "[", "'mailing_lists'", "]", "if", "url", "[", "'url'", "]", "not", "in", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "]", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "+=", "urls", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'dev_list'", "]", ")", ">", "0", "]", ":", "if", "'mailing_lists'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "=", "[", "]", "mailing_list", "=", "data", "[", "p", "]", "[", "'dev_list'", "]", "[", "'url'", "]", ".", "replace", "(", "'mailto:'", ",", "''", ")", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", ".", "append", "(", "mailing_list", ")", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_github
Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github
sirmordred/eclipse_projects_lib.py
def compose_github(projects, data): """ Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github """ for p in [project for project in data if len(data[project]['github_repos']) > 0]: if 'github' not in projects[p]: projects[p]['github'] = [] urls = [url['url'] for url in data[p]['github_repos'] if url['url'] not in projects[p]['github']] projects[p]['github'] += urls return projects
def compose_github(projects, data): """ Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github """ for p in [project for project in data if len(data[project]['github_repos']) > 0]: if 'github' not in projects[p]: projects[p]['github'] = [] urls = [url['url'] for url in data[p]['github_repos'] if url['url'] not in projects[p]['github']] projects[p]['github'] += urls return projects
[ "Compose", "projects", ".", "json", "for", "github" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L134-L149
[ "def", "compose_github", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'github_repos'", "]", ")", ">", "0", "]", ":", "if", "'github'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'github'", "]", "=", "[", "]", "urls", "=", "[", "url", "[", "'url'", "]", "for", "url", "in", "data", "[", "p", "]", "[", "'github_repos'", "]", "if", "url", "[", "'url'", "]", "not", "in", "projects", "[", "p", "]", "[", "'github'", "]", "]", "projects", "[", "p", "]", "[", "'github'", "]", "+=", "urls", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_bugzilla
Compose projects.json for bugzilla :param projects: projects.json :param data: eclipse JSON :return: projects.json with bugzilla
sirmordred/eclipse_projects_lib.py
def compose_bugzilla(projects, data): """ Compose projects.json for bugzilla :param projects: projects.json :param data: eclipse JSON :return: projects.json with bugzilla """ for p in [project for project in data if len(data[project]['bugzilla']) > 0]: if 'bugzilla' not in projects[p]: projects[p]['bugzilla'] = [] urls = [url['query_url'] for url in data[p]['bugzilla'] if url['query_url'] not in projects[p]['bugzilla']] projects[p]['bugzilla'] += urls return projects
def compose_bugzilla(projects, data): """ Compose projects.json for bugzilla :param projects: projects.json :param data: eclipse JSON :return: projects.json with bugzilla """ for p in [project for project in data if len(data[project]['bugzilla']) > 0]: if 'bugzilla' not in projects[p]: projects[p]['bugzilla'] = [] urls = [url['query_url'] for url in data[p]['bugzilla'] if url['query_url'] not in projects[p]['bugzilla']] projects[p]['bugzilla'] += urls return projects
[ "Compose", "projects", ".", "json", "for", "bugzilla" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L152-L167
[ "def", "compose_bugzilla", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'bugzilla'", "]", ")", ">", "0", "]", ":", "if", "'bugzilla'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'bugzilla'", "]", "=", "[", "]", "urls", "=", "[", "url", "[", "'query_url'", "]", "for", "url", "in", "data", "[", "p", "]", "[", "'bugzilla'", "]", "if", "url", "[", "'query_url'", "]", "not", "in", "projects", "[", "p", "]", "[", "'bugzilla'", "]", "]", "projects", "[", "p", "]", "[", "'bugzilla'", "]", "+=", "urls", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_title
Compose the projects JSON file only with the projects name :param projects: projects.json :param data: eclipse JSON with the origin format :return: projects.json with titles
sirmordred/eclipse_projects_lib.py
def compose_title(projects, data): """ Compose the projects JSON file only with the projects name :param projects: projects.json :param data: eclipse JSON with the origin format :return: projects.json with titles """ for project in data: projects[project] = { 'meta': { 'title': data[project]['title'] } } return projects
def compose_title(projects, data): """ Compose the projects JSON file only with the projects name :param projects: projects.json :param data: eclipse JSON with the origin format :return: projects.json with titles """ for project in data: projects[project] = { 'meta': { 'title': data[project]['title'] } } return projects
[ "Compose", "the", "projects", "JSON", "file", "only", "with", "the", "projects", "name" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L170-L183
[ "def", "compose_title", "(", "projects", ",", "data", ")", ":", "for", "project", "in", "data", ":", "projects", "[", "project", "]", "=", "{", "'meta'", ":", "{", "'title'", ":", "data", "[", "project", "]", "[", "'title'", "]", "}", "}", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
compose_projects_json
Compose projects.json with all data sources :param projects: projects.json :param data: eclipse JSON :return: projects.json with all data sources
sirmordred/eclipse_projects_lib.py
def compose_projects_json(projects, data): """ Compose projects.json with all data sources :param projects: projects.json :param data: eclipse JSON :return: projects.json with all data sources """ projects = compose_git(projects, data) projects = compose_mailing_lists(projects, data) projects = compose_bugzilla(projects, data) projects = compose_github(projects, data) projects = compose_gerrit(projects) projects = compose_mbox(projects) return projects
def compose_projects_json(projects, data): """ Compose projects.json with all data sources :param projects: projects.json :param data: eclipse JSON :return: projects.json with all data sources """ projects = compose_git(projects, data) projects = compose_mailing_lists(projects, data) projects = compose_bugzilla(projects, data) projects = compose_github(projects, data) projects = compose_gerrit(projects) projects = compose_mbox(projects) return projects
[ "Compose", "projects", ".", "json", "with", "all", "data", "sources" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L186-L200
[ "def", "compose_projects_json", "(", "projects", ",", "data", ")", ":", "projects", "=", "compose_git", "(", "projects", ",", "data", ")", "projects", "=", "compose_mailing_lists", "(", "projects", ",", "data", ")", "projects", "=", "compose_bugzilla", "(", "projects", ",", "data", ")", "projects", "=", "compose_github", "(", "projects", ",", "data", ")", "projects", "=", "compose_gerrit", "(", "projects", ")", "projects", "=", "compose_mbox", "(", "projects", ")", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskEnrich.__autorefresh_studies
Execute autorefresh for areas of code study if configured
sirmordred/task_enrich.py
def __autorefresh_studies(self, cfg): """Execute autorefresh for areas of code study if configured""" if 'studies' not in self.conf[self.backend_section] or \ 'enrich_areas_of_code:git' not in self.conf[self.backend_section]['studies']: logger.debug("Not doing autorefresh for studies, Areas of Code study is not active.") return aoc_index = self.conf['enrich_areas_of_code:git'].get('out_index', GitEnrich.GIT_AOC_ENRICHED) # if `out_index` exists but has no value, use default if not aoc_index: aoc_index = GitEnrich.GIT_AOC_ENRICHED logger.debug("Autorefresh for Areas of Code study index: %s", aoc_index) es = Elasticsearch([self.conf['es_enrichment']['url']], timeout=100, verify_certs=self._get_enrich_backend().elastic.requests.verify) if not es.indices.exists(index=aoc_index): logger.debug("Not doing autorefresh, index doesn't exist for Areas of Code study") return logger.debug("Doing autorefresh for Areas of Code study") # Create a GitEnrich backend tweaked to work with AOC index aoc_backend = GitEnrich(self.db_sh, None, cfg['projects']['projects_file'], self.db_user, self.db_password, self.db_host) aoc_backend.mapping = None aoc_backend.roles = ['author'] elastic_enrich = get_elastic(self.conf['es_enrichment']['url'], aoc_index, clean=False, backend=aoc_backend) aoc_backend.set_elastic(elastic_enrich) self.__autorefresh(aoc_backend, studies=True)
def __autorefresh_studies(self, cfg): """Execute autorefresh for areas of code study if configured""" if 'studies' not in self.conf[self.backend_section] or \ 'enrich_areas_of_code:git' not in self.conf[self.backend_section]['studies']: logger.debug("Not doing autorefresh for studies, Areas of Code study is not active.") return aoc_index = self.conf['enrich_areas_of_code:git'].get('out_index', GitEnrich.GIT_AOC_ENRICHED) # if `out_index` exists but has no value, use default if not aoc_index: aoc_index = GitEnrich.GIT_AOC_ENRICHED logger.debug("Autorefresh for Areas of Code study index: %s", aoc_index) es = Elasticsearch([self.conf['es_enrichment']['url']], timeout=100, verify_certs=self._get_enrich_backend().elastic.requests.verify) if not es.indices.exists(index=aoc_index): logger.debug("Not doing autorefresh, index doesn't exist for Areas of Code study") return logger.debug("Doing autorefresh for Areas of Code study") # Create a GitEnrich backend tweaked to work with AOC index aoc_backend = GitEnrich(self.db_sh, None, cfg['projects']['projects_file'], self.db_user, self.db_password, self.db_host) aoc_backend.mapping = None aoc_backend.roles = ['author'] elastic_enrich = get_elastic(self.conf['es_enrichment']['url'], aoc_index, clean=False, backend=aoc_backend) aoc_backend.set_elastic(elastic_enrich) self.__autorefresh(aoc_backend, studies=True)
[ "Execute", "autorefresh", "for", "areas", "of", "code", "study", "if", "configured" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_enrich.py#L268-L302
[ "def", "__autorefresh_studies", "(", "self", ",", "cfg", ")", ":", "if", "'studies'", "not", "in", "self", ".", "conf", "[", "self", ".", "backend_section", "]", "or", "'enrich_areas_of_code:git'", "not", "in", "self", ".", "conf", "[", "self", ".", "backend_section", "]", "[", "'studies'", "]", ":", "logger", ".", "debug", "(", "\"Not doing autorefresh for studies, Areas of Code study is not active.\"", ")", "return", "aoc_index", "=", "self", ".", "conf", "[", "'enrich_areas_of_code:git'", "]", ".", "get", "(", "'out_index'", ",", "GitEnrich", ".", "GIT_AOC_ENRICHED", ")", "# if `out_index` exists but has no value, use default", "if", "not", "aoc_index", ":", "aoc_index", "=", "GitEnrich", ".", "GIT_AOC_ENRICHED", "logger", ".", "debug", "(", "\"Autorefresh for Areas of Code study index: %s\"", ",", "aoc_index", ")", "es", "=", "Elasticsearch", "(", "[", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "]", ",", "timeout", "=", "100", ",", "verify_certs", "=", "self", ".", "_get_enrich_backend", "(", ")", ".", "elastic", ".", "requests", ".", "verify", ")", "if", "not", "es", ".", "indices", ".", "exists", "(", "index", "=", "aoc_index", ")", ":", "logger", ".", "debug", "(", "\"Not doing autorefresh, index doesn't exist for Areas of Code study\"", ")", "return", "logger", ".", "debug", "(", "\"Doing autorefresh for Areas of Code study\"", ")", "# Create a GitEnrich backend tweaked to work with AOC index", "aoc_backend", "=", "GitEnrich", "(", "self", ".", "db_sh", ",", "None", ",", "cfg", "[", "'projects'", "]", "[", "'projects_file'", "]", ",", "self", ".", "db_user", ",", "self", ".", "db_password", ",", "self", ".", "db_host", ")", "aoc_backend", ".", "mapping", "=", "None", "aoc_backend", ".", "roles", "=", "[", "'author'", "]", "elastic_enrich", "=", "get_elastic", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "aoc_index", ",", "clean", "=", "False", ",", "backend", "=", "aoc_backend", ")", "aoc_backend", ".", "set_elastic", "(", "elastic_enrich", ")", "self", ".", "__autorefresh", "(", "aoc_backend", ",", "studies", "=", "True", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskEnrich.__studies
Execute the studies configured for the current backend
sirmordred/task_enrich.py
def __studies(self, retention_time): """ Execute the studies configured for the current backend """ cfg = self.config.get_conf() if 'studies' not in cfg[self.backend_section] or not \ cfg[self.backend_section]['studies']: logger.debug('No studies for %s' % self.backend_section) return studies = [study for study in cfg[self.backend_section]['studies'] if study.strip() != ""] if not studies: logger.debug('No studies for %s' % self.backend_section) return logger.debug("Executing studies for %s: %s" % (self.backend_section, studies)) time.sleep(2) # Wait so enrichment has finished in ES enrich_backend = self._get_enrich_backend() ocean_backend = self._get_ocean_backend(enrich_backend) active_studies = [] all_studies = enrich_backend.studies all_studies_names = [study.__name__ for study in enrich_backend.studies] # Time to check that configured studies are valid logger.debug("All studies in %s: %s", self.backend_section, all_studies_names) logger.debug("Configured studies %s", studies) cfg_studies_types = [study.split(":")[0] for study in studies] if not set(cfg_studies_types).issubset(set(all_studies_names)): logger.error('Wrong studies names for %s: %s', self.backend_section, studies) raise RuntimeError('Wrong studies names ', self.backend_section, studies) for study in enrich_backend.studies: if study.__name__ in cfg_studies_types: active_studies.append(study) enrich_backend.studies = active_studies print("Executing for %s the studies %s" % (self.backend_section, [study for study in studies])) studies_args = self.__load_studies() do_studies(ocean_backend, enrich_backend, studies_args, retention_time=retention_time) # Return studies to its original value enrich_backend.studies = all_studies
def __studies(self, retention_time): """ Execute the studies configured for the current backend """ cfg = self.config.get_conf() if 'studies' not in cfg[self.backend_section] or not \ cfg[self.backend_section]['studies']: logger.debug('No studies for %s' % self.backend_section) return studies = [study for study in cfg[self.backend_section]['studies'] if study.strip() != ""] if not studies: logger.debug('No studies for %s' % self.backend_section) return logger.debug("Executing studies for %s: %s" % (self.backend_section, studies)) time.sleep(2) # Wait so enrichment has finished in ES enrich_backend = self._get_enrich_backend() ocean_backend = self._get_ocean_backend(enrich_backend) active_studies = [] all_studies = enrich_backend.studies all_studies_names = [study.__name__ for study in enrich_backend.studies] # Time to check that configured studies are valid logger.debug("All studies in %s: %s", self.backend_section, all_studies_names) logger.debug("Configured studies %s", studies) cfg_studies_types = [study.split(":")[0] for study in studies] if not set(cfg_studies_types).issubset(set(all_studies_names)): logger.error('Wrong studies names for %s: %s', self.backend_section, studies) raise RuntimeError('Wrong studies names ', self.backend_section, studies) for study in enrich_backend.studies: if study.__name__ in cfg_studies_types: active_studies.append(study) enrich_backend.studies = active_studies print("Executing for %s the studies %s" % (self.backend_section, [study for study in studies])) studies_args = self.__load_studies() do_studies(ocean_backend, enrich_backend, studies_args, retention_time=retention_time) # Return studies to its original value enrich_backend.studies = all_studies
[ "Execute", "the", "studies", "configured", "for", "the", "current", "backend" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_enrich.py#L304-L347
[ "def", "__studies", "(", "self", ",", "retention_time", ")", ":", "cfg", "=", "self", ".", "config", ".", "get_conf", "(", ")", "if", "'studies'", "not", "in", "cfg", "[", "self", ".", "backend_section", "]", "or", "not", "cfg", "[", "self", ".", "backend_section", "]", "[", "'studies'", "]", ":", "logger", ".", "debug", "(", "'No studies for %s'", "%", "self", ".", "backend_section", ")", "return", "studies", "=", "[", "study", "for", "study", "in", "cfg", "[", "self", ".", "backend_section", "]", "[", "'studies'", "]", "if", "study", ".", "strip", "(", ")", "!=", "\"\"", "]", "if", "not", "studies", ":", "logger", ".", "debug", "(", "'No studies for %s'", "%", "self", ".", "backend_section", ")", "return", "logger", ".", "debug", "(", "\"Executing studies for %s: %s\"", "%", "(", "self", ".", "backend_section", ",", "studies", ")", ")", "time", ".", "sleep", "(", "2", ")", "# Wait so enrichment has finished in ES", "enrich_backend", "=", "self", ".", "_get_enrich_backend", "(", ")", "ocean_backend", "=", "self", ".", "_get_ocean_backend", "(", "enrich_backend", ")", "active_studies", "=", "[", "]", "all_studies", "=", "enrich_backend", ".", "studies", "all_studies_names", "=", "[", "study", ".", "__name__", "for", "study", "in", "enrich_backend", ".", "studies", "]", "# Time to check that configured studies are valid", "logger", ".", "debug", "(", "\"All studies in %s: %s\"", ",", "self", ".", "backend_section", ",", "all_studies_names", ")", "logger", ".", "debug", "(", "\"Configured studies %s\"", ",", "studies", ")", "cfg_studies_types", "=", "[", "study", ".", "split", "(", "\":\"", ")", "[", "0", "]", "for", "study", "in", "studies", "]", "if", "not", "set", "(", "cfg_studies_types", ")", ".", "issubset", "(", "set", "(", "all_studies_names", ")", ")", ":", "logger", ".", "error", "(", "'Wrong studies names for %s: %s'", ",", "self", ".", "backend_section", ",", "studies", ")", "raise", "RuntimeError", "(", "'Wrong studies names '", ",", "self", ".", "backend_section", ",", "studies", ")", "for", "study", "in", "enrich_backend", ".", "studies", ":", "if", "study", ".", "__name__", "in", "cfg_studies_types", ":", "active_studies", ".", "append", "(", "study", ")", "enrich_backend", ".", "studies", "=", "active_studies", "print", "(", "\"Executing for %s the studies %s\"", "%", "(", "self", ".", "backend_section", ",", "[", "study", "for", "study", "in", "studies", "]", ")", ")", "studies_args", "=", "self", ".", "__load_studies", "(", ")", "do_studies", "(", "ocean_backend", ",", "enrich_backend", ",", "studies_args", ",", "retention_time", "=", "retention_time", ")", "# Return studies to its original value", "enrich_backend", ".", "studies", "=", "all_studies" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskEnrich.retain_identities
Retain the identities in SortingHat based on the `retention_time` value declared in the setup.cfg. :param retention_time: maximum number of minutes wrt the current date to retain the SortingHat data
sirmordred/task_enrich.py
def retain_identities(self, retention_time): """Retain the identities in SortingHat based on the `retention_time` value declared in the setup.cfg. :param retention_time: maximum number of minutes wrt the current date to retain the SortingHat data """ enrich_es = self.conf['es_enrichment']['url'] sortinghat_db = self.db current_data_source = self.get_backend(self.backend_section) active_data_sources = self.config.get_active_data_sources() if retention_time is None: logger.debug("[identities retention] Retention policy disabled, no identities will be deleted.") return if retention_time <= 0: logger.debug("[identities retention] Retention time must be greater than 0.") return retain_identities(retention_time, enrich_es, sortinghat_db, current_data_source, active_data_sources)
def retain_identities(self, retention_time): """Retain the identities in SortingHat based on the `retention_time` value declared in the setup.cfg. :param retention_time: maximum number of minutes wrt the current date to retain the SortingHat data """ enrich_es = self.conf['es_enrichment']['url'] sortinghat_db = self.db current_data_source = self.get_backend(self.backend_section) active_data_sources = self.config.get_active_data_sources() if retention_time is None: logger.debug("[identities retention] Retention policy disabled, no identities will be deleted.") return if retention_time <= 0: logger.debug("[identities retention] Retention time must be greater than 0.") return retain_identities(retention_time, enrich_es, sortinghat_db, current_data_source, active_data_sources)
[ "Retain", "the", "identities", "in", "SortingHat", "based", "on", "the", "retention_time", "value", "declared", "in", "the", "setup", ".", "cfg", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_enrich.py#L349-L368
[ "def", "retain_identities", "(", "self", ",", "retention_time", ")", ":", "enrich_es", "=", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "sortinghat_db", "=", "self", ".", "db", "current_data_source", "=", "self", ".", "get_backend", "(", "self", ".", "backend_section", ")", "active_data_sources", "=", "self", ".", "config", ".", "get_active_data_sources", "(", ")", "if", "retention_time", "is", "None", ":", "logger", ".", "debug", "(", "\"[identities retention] Retention policy disabled, no identities will be deleted.\"", ")", "return", "if", "retention_time", "<=", "0", ":", "logger", ".", "debug", "(", "\"[identities retention] Retention time must be greater than 0.\"", ")", "return", "retain_identities", "(", "retention_time", ",", "enrich_es", ",", "sortinghat_db", ",", "current_data_source", ",", "active_data_sources", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskProjects.get_repos_by_backend_section
return list with the repositories for a backend_section
sirmordred/task_projects.py
def get_repos_by_backend_section(cls, backend_section, raw=True): """ return list with the repositories for a backend_section """ repos = [] projects = TaskProjects.get_projects() for pro in projects: if backend_section in projects[pro]: # if the projects.json doesn't contain the `unknown` project, add the repos in the bck section if cls.GLOBAL_PROJECT not in projects: repos += projects[pro][backend_section] else: # if the projects.json contains the `unknown` project # in the case of the collection phase if raw: # if the current project is not `unknown` if pro != cls.GLOBAL_PROJECT: # if the bck section is not in the `unknown` project, add the repos in the bck section if backend_section not in projects[cls.GLOBAL_PROJECT]: repos += projects[pro][backend_section] # if the backend section is in the `unknown` project, # add the repo in the bck section under `unknown` elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]: repos += projects[cls.GLOBAL_PROJECT][backend_section] # if the current project is `unknown` else: # if the backend section is only in the `unknown` project, # add the repo in the bck section under `unknown` not_in_unknown = [projects[pro] for pro in projects if pro != cls.GLOBAL_PROJECT][0] if backend_section not in not_in_unknown: repos += projects[cls.GLOBAL_PROJECT][backend_section] # in the case of the enrichment phase else: # if the current project is not `unknown` if pro != cls.GLOBAL_PROJECT: # if the bck section is not in the `unknown` project, add the repos in the bck section if backend_section not in projects[cls.GLOBAL_PROJECT]: repos += projects[pro][backend_section] # if the backend section is in the `unknown` project, add the repos in the bck section elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]: repos += projects[pro][backend_section] # if the current project is `unknown` else: # if the backend section is only in the `unknown` project, # add the repo in the bck section under `unknown` not_in_unknown_prj = [projects[prj] for prj in projects if prj != cls.GLOBAL_PROJECT] not_in_unknown_sections = list(set([section for prj in not_in_unknown_prj for section in list(prj.keys())])) if backend_section not in not_in_unknown_sections: repos += projects[pro][backend_section] logger.debug("List of repos for %s: %s (raw=%s)", backend_section, repos, raw) # avoid duplicated repos repos = list(set(repos)) return repos
def get_repos_by_backend_section(cls, backend_section, raw=True): """ return list with the repositories for a backend_section """ repos = [] projects = TaskProjects.get_projects() for pro in projects: if backend_section in projects[pro]: # if the projects.json doesn't contain the `unknown` project, add the repos in the bck section if cls.GLOBAL_PROJECT not in projects: repos += projects[pro][backend_section] else: # if the projects.json contains the `unknown` project # in the case of the collection phase if raw: # if the current project is not `unknown` if pro != cls.GLOBAL_PROJECT: # if the bck section is not in the `unknown` project, add the repos in the bck section if backend_section not in projects[cls.GLOBAL_PROJECT]: repos += projects[pro][backend_section] # if the backend section is in the `unknown` project, # add the repo in the bck section under `unknown` elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]: repos += projects[cls.GLOBAL_PROJECT][backend_section] # if the current project is `unknown` else: # if the backend section is only in the `unknown` project, # add the repo in the bck section under `unknown` not_in_unknown = [projects[pro] for pro in projects if pro != cls.GLOBAL_PROJECT][0] if backend_section not in not_in_unknown: repos += projects[cls.GLOBAL_PROJECT][backend_section] # in the case of the enrichment phase else: # if the current project is not `unknown` if pro != cls.GLOBAL_PROJECT: # if the bck section is not in the `unknown` project, add the repos in the bck section if backend_section not in projects[cls.GLOBAL_PROJECT]: repos += projects[pro][backend_section] # if the backend section is in the `unknown` project, add the repos in the bck section elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]: repos += projects[pro][backend_section] # if the current project is `unknown` else: # if the backend section is only in the `unknown` project, # add the repo in the bck section under `unknown` not_in_unknown_prj = [projects[prj] for prj in projects if prj != cls.GLOBAL_PROJECT] not_in_unknown_sections = list(set([section for prj in not_in_unknown_prj for section in list(prj.keys())])) if backend_section not in not_in_unknown_sections: repos += projects[pro][backend_section] logger.debug("List of repos for %s: %s (raw=%s)", backend_section, repos, raw) # avoid duplicated repos repos = list(set(repos)) return repos
[ "return", "list", "with", "the", "repositories", "for", "a", "backend_section" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_projects.py#L71-L126
[ "def", "get_repos_by_backend_section", "(", "cls", ",", "backend_section", ",", "raw", "=", "True", ")", ":", "repos", "=", "[", "]", "projects", "=", "TaskProjects", ".", "get_projects", "(", ")", "for", "pro", "in", "projects", ":", "if", "backend_section", "in", "projects", "[", "pro", "]", ":", "# if the projects.json doesn't contain the `unknown` project, add the repos in the bck section", "if", "cls", ".", "GLOBAL_PROJECT", "not", "in", "projects", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "else", ":", "# if the projects.json contains the `unknown` project", "# in the case of the collection phase", "if", "raw", ":", "# if the current project is not `unknown`", "if", "pro", "!=", "cls", ".", "GLOBAL_PROJECT", ":", "# if the bck section is not in the `unknown` project, add the repos in the bck section", "if", "backend_section", "not", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "# if the backend section is in the `unknown` project,", "# add the repo in the bck section under `unknown`", "elif", "backend_section", "in", "projects", "[", "pro", "]", "and", "backend_section", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", "[", "backend_section", "]", "# if the current project is `unknown`", "else", ":", "# if the backend section is only in the `unknown` project,", "# add the repo in the bck section under `unknown`", "not_in_unknown", "=", "[", "projects", "[", "pro", "]", "for", "pro", "in", "projects", "if", "pro", "!=", "cls", ".", "GLOBAL_PROJECT", "]", "[", "0", "]", "if", "backend_section", "not", "in", "not_in_unknown", ":", "repos", "+=", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", "[", "backend_section", "]", "# in the case of the enrichment phase", "else", ":", "# if the current project is not `unknown`", "if", "pro", "!=", "cls", ".", "GLOBAL_PROJECT", ":", "# if the bck section is not in the `unknown` project, add the repos in the bck section", "if", "backend_section", "not", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "# if the backend section is in the `unknown` project, add the repos in the bck section", "elif", "backend_section", "in", "projects", "[", "pro", "]", "and", "backend_section", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "# if the current project is `unknown`", "else", ":", "# if the backend section is only in the `unknown` project,", "# add the repo in the bck section under `unknown`", "not_in_unknown_prj", "=", "[", "projects", "[", "prj", "]", "for", "prj", "in", "projects", "if", "prj", "!=", "cls", ".", "GLOBAL_PROJECT", "]", "not_in_unknown_sections", "=", "list", "(", "set", "(", "[", "section", "for", "prj", "in", "not_in_unknown_prj", "for", "section", "in", "list", "(", "prj", ".", "keys", "(", ")", ")", "]", ")", ")", "if", "backend_section", "not", "in", "not_in_unknown_sections", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "logger", ".", "debug", "(", "\"List of repos for %s: %s (raw=%s)\"", ",", "backend_section", ",", "repos", ",", "raw", ")", "# avoid duplicated repos", "repos", "=", "list", "(", "set", "(", "repos", ")", ")", "return", "repos" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
TaskProjects.convert_from_eclipse
Convert from eclipse projects format to grimoire projects json format
sirmordred/task_projects.py
def convert_from_eclipse(self, eclipse_projects): """ Convert from eclipse projects format to grimoire projects json format """ projects = {} # We need the global project for downloading the full Bugzilla and Gerrit projects['unknown'] = { "gerrit": ["git.eclipse.org"], "bugzilla": ["https://bugs.eclipse.org/bugs/"] } projects = compose_title(projects, eclipse_projects) projects = compose_projects_json(projects, eclipse_projects) return projects
def convert_from_eclipse(self, eclipse_projects): """ Convert from eclipse projects format to grimoire projects json format """ projects = {} # We need the global project for downloading the full Bugzilla and Gerrit projects['unknown'] = { "gerrit": ["git.eclipse.org"], "bugzilla": ["https://bugs.eclipse.org/bugs/"] } projects = compose_title(projects, eclipse_projects) projects = compose_projects_json(projects, eclipse_projects) return projects
[ "Convert", "from", "eclipse", "projects", "format", "to", "grimoire", "projects", "json", "format" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_projects.py#L172-L186
[ "def", "convert_from_eclipse", "(", "self", ",", "eclipse_projects", ")", ":", "projects", "=", "{", "}", "# We need the global project for downloading the full Bugzilla and Gerrit", "projects", "[", "'unknown'", "]", "=", "{", "\"gerrit\"", ":", "[", "\"git.eclipse.org\"", "]", ",", "\"bugzilla\"", ":", "[", "\"https://bugs.eclipse.org/bugs/\"", "]", "}", "projects", "=", "compose_title", "(", "projects", ",", "eclipse_projects", ")", "projects", "=", "compose_projects_json", "(", "projects", ",", "eclipse_projects", ")", "return", "projects" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
Config.general_params
Define all the possible config params
sirmordred/config.py
def general_params(cls): """ Define all the possible config params """ params = {} # GENERAL CONFIG params_general = { "general": { "min_update_delay": { "optional": True, "default": 60, "type": int, "description": "Short delay between tasks (collect, enrich ...)" }, "update": { "optional": False, "default": False, "type": bool, "description": "Execute the tasks in loop" }, "short_name": { "optional": False, "default": "Short name", "type": str, "description": "Short name of the project" }, "debug": { "optional": False, "default": True, "type": bool, "description": "Debug mode (logging mainly)" }, "logs_dir": { "optional": False, "default": "logs", "type": str, "description": "Directory with the logs of sirmordred" }, "log_handler": { "optional": True, "default": "file", "type": str, "description": "use rotate for rotating the logs automatically" }, "log_max_bytes": { "optional": True, "default": 104857600, # 100MB "type": int, "description": "Max number of bytes per log file" }, "log_backup_count": { "optional": True, "default": 5, "type": int, "description": "Number of rotate logs files to preserve" }, "bulk_size": { "optional": True, "default": 1000, "type": int, "description": "Number of items to write in Elasticsearch using bulk operations" }, "scroll_size": { "optional": True, "default": 100, "type": int, "description": "Number of items to read from Elasticsearch when scrolling" }, "aliases_file": { "optional": True, "default": ALIASES_JSON, "type": str, "description": "JSON file to define aliases for raw and enriched indexes" }, "menu_file": { "optional": True, "default": MENU_YAML, "type": str, "description": "YAML file to define the menus to be shown in Kibiter" }, "retention_time": { "optional": True, "default": None, "type": int, "description": "The maximum number of minutes wrt the current date to retain the data" } } } params_projects = { "projects": { "projects_file": { "optional": True, "default": PROJECTS_JSON, "type": str, "description": "Projects file path with repositories to be collected group by projects" }, "projects_url": { "optional": True, "default": None, "type": str, "description": "Projects file URL" }, "load_eclipse": { "optional": True, "default": False, "type": bool, "description": "Load the projects from Eclipse" } } } params_phases = { "phases": { "collection": { "optional": False, "default": True, "type": bool, "description": "Activate collection of items" }, "enrichment": { "optional": False, "default": True, "type": bool, "description": "Activate enrichment of items" }, "identities": { "optional": False, "default": True, "type": bool, "description": "Do the identities tasks" }, "panels": { "optional": False, "default": True, "type": bool, "description": "Load panels, create alias and other tasks related" }, "track_items": { "optional": True, "default": False, "type": bool, "description": "Track specific items from a gerrit repository" }, "report": { "optional": True, "default": False, "type": bool, "description": "Generate the PDF report for a project (alpha)" } } } general_config_params = [params_general, params_projects, params_phases] for section_params in general_config_params: params.update(section_params) # Config provided by tasks params_collection = { "es_collection": { "password": { "optional": True, "default": None, "type": str, "description": "Password for connection to Elasticsearch" }, "user": { "optional": True, "default": None, "type": str, "description": "User for connection to Elasticsearch" }, "url": { "optional": False, "default": "http://172.17.0.1:9200", "type": str, "description": "Elasticsearch URL" }, "arthur": { "optional": True, "default": False, "type": bool, "description": "Use arthur for collecting items from perceval" }, "arthur_url": { "optional": True, "default": None, "type": str, "description": "URL for the arthur service" }, "redis_url": { "optional": True, "default": None, "type": str, "description": "URL for the redis service" } } } params_enrichment = { "es_enrichment": { "url": { "optional": False, "default": "http://172.17.0.1:9200", "type": str, "description": "Elasticsearch URL" }, "autorefresh": { "optional": True, "default": True, "type": bool, "description": "Execute the autorefresh of identities" }, "autorefresh_interval": { "optional": True, "default": 2, "type": int, "description": "Set time interval (days) for autorefresh identities" }, "user": { "optional": True, "default": None, "type": str, "description": "User for connection to Elasticsearch" }, "password": { "optional": True, "default": None, "type": str, "description": "Password for connection to Elasticsearch" } } } params_panels = { "panels": { "strict": { "optional": True, "default": True, "type": bool, "description": "Enable strict panels loading" }, "kibiter_time_from": { "optional": True, "default": "now-90d", "type": str, "description": "Default time interval for Kibiter" }, "kibiter_default_index": { "optional": True, "default": "git", "type": str, "description": "Default index pattern for Kibiter" }, "kibiter_url": { "optional": False, "default": None, "type": str, "description": "Kibiter URL" }, "kibiter_version": { "optional": True, "default": None, "type": str, "description": "Kibiter version" }, "community": { "optional": True, "default": True, "type": bool, "description": "Enable community structure menu" }, "kafka": { "optional": True, "default": False, "type": bool, "description": "Enable kafka menu" }, "github-repos": { "optional": True, "default": False, "type": bool, "description": "Enable GitHub repo stats menu" }, "gitlab-issues": { "optional": True, "default": False, "type": bool, "description": "Enable GitLab issues menu" }, "gitlab-merges": { "optional": True, "default": False, "type": bool, "description": "Enable GitLab merge requests menu" }, "mattermost": { "optional": True, "default": False, "type": bool, "description": "Enable Mattermost menu" } } } params_report = { "report": { "start_date": { "optional": False, "default": "1970-01-01", "type": str, "description": "Start date for the report" }, "end_date": { "optional": False, "default": "2100-01-01", "type": str, "description": "End date for the report" }, "interval": { "optional": False, "default": "quarter", "type": str, "description": "Interval for the report" }, "config_file": { "optional": False, "default": "report.cfg", "type": str, "description": "Config file for the report" }, "data_dir": { "optional": False, "default": "report_data", "type": str, "description": "Directory in which to store the report data" }, "filters": { "optional": True, "default": [], "type": list, "description": "General filters to be applied to all queries" }, "offset": { "optional": True, "default": None, "type": str, "description": "Date offset to be applied to start and end" } } } params_sortinghat = { "sortinghat": { "affiliate": { "optional": False, "default": "True", "type": bool, "description": "Affiliate identities to organizations" }, "unaffiliated_group": { "optional": False, "default": "Unknown", "type": str, "description": "Name of the organization for unaffiliated identities" }, "matching": { "optional": False, "default": ["email"], "type": list, "description": "Algorithm for matching identities in Sortinghat" }, "sleep_for": { "optional": False, "default": 3600, "type": int, "description": "Delay between task identities executions" }, "database": { "optional": False, "default": "sortinghat_db", "type": str, "description": "Name of the Sortinghat database" }, "host": { "optional": False, "default": "mariadb", "type": str, "description": "Host with the Sortinghat database" }, "user": { "optional": False, "default": "root", "type": str, "description": "User to access the Sortinghat database" }, "password": { "optional": False, "default": "", "type": str, "description": "Password to access the Sortinghat database" }, "autoprofile": { "optional": False, "default": ["customer", "git", "github"], "type": list, "description": "Order in which to get the identities information for filling the profile" }, "load_orgs": { "optional": True, "default": False, "type": bool, "deprecated": "Load organizations in Sortinghat database", "description": "" }, "identities_format": { "optional": True, "default": "sortinghat", "type": str, "description": "Format of the identities data to be loaded" }, "strict_mapping": { "optional": True, "default": True, "type": bool, "description": "rigorous check of values in identities matching " "(i.e, well formed email addresses)" }, "reset_on_load": { "optional": True, "default": False, "type": bool, "description": "Unmerge and remove affiliations for all identities on load" }, "orgs_file": { "optional": True, "default": None, "type": str, "description": "File path with the organizations to be loaded in Sortinghat" }, "identities_file": { "optional": True, "default": [], "type": list, "description": "File path with the identities to be loaded in Sortinghat" }, "identities_export_url": { "optional": True, "default": None, "type": str, "description": "URL in which to export the identities in Sortinghat" }, "identities_api_token": { "optional": True, "default": None, "type": str, "description": "API token for remote operation with GitHub and Gitlab" }, "bots_names": { "optional": True, "default": [], "type": list, "description": "Name of the identities to be marked as bots" }, "no_bots_names": { "optional": True, "default": [], "type": list, "description": "Name of the identities to be unmarked as bots" }, "autogender": { "optional": True, "default": False, "type": bool, "description": "Add gender to the profiles (executes autogender)" } } } params_track_items = { "track_items": { "project": { "optional": False, "default": "TrackProject", "type": str, "description": "Gerrit project to track" }, "upstream_raw_es_url": { "optional": False, "default": "", "type": str, "description": "URL with the file with the gerrit reviews to track" }, "raw_index_gerrit": { "optional": False, "default": "", "type": str, "description": "Name of the gerrit raw index" }, "raw_index_git": { "optional": False, "default": "", "type": str, "description": "Name of the git raw index" } } } tasks_config_params = [params_collection, params_enrichment, params_panels, params_report, params_sortinghat, params_track_items] for section_params in tasks_config_params: params.update(section_params) return params
def general_params(cls): """ Define all the possible config params """ params = {} # GENERAL CONFIG params_general = { "general": { "min_update_delay": { "optional": True, "default": 60, "type": int, "description": "Short delay between tasks (collect, enrich ...)" }, "update": { "optional": False, "default": False, "type": bool, "description": "Execute the tasks in loop" }, "short_name": { "optional": False, "default": "Short name", "type": str, "description": "Short name of the project" }, "debug": { "optional": False, "default": True, "type": bool, "description": "Debug mode (logging mainly)" }, "logs_dir": { "optional": False, "default": "logs", "type": str, "description": "Directory with the logs of sirmordred" }, "log_handler": { "optional": True, "default": "file", "type": str, "description": "use rotate for rotating the logs automatically" }, "log_max_bytes": { "optional": True, "default": 104857600, # 100MB "type": int, "description": "Max number of bytes per log file" }, "log_backup_count": { "optional": True, "default": 5, "type": int, "description": "Number of rotate logs files to preserve" }, "bulk_size": { "optional": True, "default": 1000, "type": int, "description": "Number of items to write in Elasticsearch using bulk operations" }, "scroll_size": { "optional": True, "default": 100, "type": int, "description": "Number of items to read from Elasticsearch when scrolling" }, "aliases_file": { "optional": True, "default": ALIASES_JSON, "type": str, "description": "JSON file to define aliases for raw and enriched indexes" }, "menu_file": { "optional": True, "default": MENU_YAML, "type": str, "description": "YAML file to define the menus to be shown in Kibiter" }, "retention_time": { "optional": True, "default": None, "type": int, "description": "The maximum number of minutes wrt the current date to retain the data" } } } params_projects = { "projects": { "projects_file": { "optional": True, "default": PROJECTS_JSON, "type": str, "description": "Projects file path with repositories to be collected group by projects" }, "projects_url": { "optional": True, "default": None, "type": str, "description": "Projects file URL" }, "load_eclipse": { "optional": True, "default": False, "type": bool, "description": "Load the projects from Eclipse" } } } params_phases = { "phases": { "collection": { "optional": False, "default": True, "type": bool, "description": "Activate collection of items" }, "enrichment": { "optional": False, "default": True, "type": bool, "description": "Activate enrichment of items" }, "identities": { "optional": False, "default": True, "type": bool, "description": "Do the identities tasks" }, "panels": { "optional": False, "default": True, "type": bool, "description": "Load panels, create alias and other tasks related" }, "track_items": { "optional": True, "default": False, "type": bool, "description": "Track specific items from a gerrit repository" }, "report": { "optional": True, "default": False, "type": bool, "description": "Generate the PDF report for a project (alpha)" } } } general_config_params = [params_general, params_projects, params_phases] for section_params in general_config_params: params.update(section_params) # Config provided by tasks params_collection = { "es_collection": { "password": { "optional": True, "default": None, "type": str, "description": "Password for connection to Elasticsearch" }, "user": { "optional": True, "default": None, "type": str, "description": "User for connection to Elasticsearch" }, "url": { "optional": False, "default": "http://172.17.0.1:9200", "type": str, "description": "Elasticsearch URL" }, "arthur": { "optional": True, "default": False, "type": bool, "description": "Use arthur for collecting items from perceval" }, "arthur_url": { "optional": True, "default": None, "type": str, "description": "URL for the arthur service" }, "redis_url": { "optional": True, "default": None, "type": str, "description": "URL for the redis service" } } } params_enrichment = { "es_enrichment": { "url": { "optional": False, "default": "http://172.17.0.1:9200", "type": str, "description": "Elasticsearch URL" }, "autorefresh": { "optional": True, "default": True, "type": bool, "description": "Execute the autorefresh of identities" }, "autorefresh_interval": { "optional": True, "default": 2, "type": int, "description": "Set time interval (days) for autorefresh identities" }, "user": { "optional": True, "default": None, "type": str, "description": "User for connection to Elasticsearch" }, "password": { "optional": True, "default": None, "type": str, "description": "Password for connection to Elasticsearch" } } } params_panels = { "panels": { "strict": { "optional": True, "default": True, "type": bool, "description": "Enable strict panels loading" }, "kibiter_time_from": { "optional": True, "default": "now-90d", "type": str, "description": "Default time interval for Kibiter" }, "kibiter_default_index": { "optional": True, "default": "git", "type": str, "description": "Default index pattern for Kibiter" }, "kibiter_url": { "optional": False, "default": None, "type": str, "description": "Kibiter URL" }, "kibiter_version": { "optional": True, "default": None, "type": str, "description": "Kibiter version" }, "community": { "optional": True, "default": True, "type": bool, "description": "Enable community structure menu" }, "kafka": { "optional": True, "default": False, "type": bool, "description": "Enable kafka menu" }, "github-repos": { "optional": True, "default": False, "type": bool, "description": "Enable GitHub repo stats menu" }, "gitlab-issues": { "optional": True, "default": False, "type": bool, "description": "Enable GitLab issues menu" }, "gitlab-merges": { "optional": True, "default": False, "type": bool, "description": "Enable GitLab merge requests menu" }, "mattermost": { "optional": True, "default": False, "type": bool, "description": "Enable Mattermost menu" } } } params_report = { "report": { "start_date": { "optional": False, "default": "1970-01-01", "type": str, "description": "Start date for the report" }, "end_date": { "optional": False, "default": "2100-01-01", "type": str, "description": "End date for the report" }, "interval": { "optional": False, "default": "quarter", "type": str, "description": "Interval for the report" }, "config_file": { "optional": False, "default": "report.cfg", "type": str, "description": "Config file for the report" }, "data_dir": { "optional": False, "default": "report_data", "type": str, "description": "Directory in which to store the report data" }, "filters": { "optional": True, "default": [], "type": list, "description": "General filters to be applied to all queries" }, "offset": { "optional": True, "default": None, "type": str, "description": "Date offset to be applied to start and end" } } } params_sortinghat = { "sortinghat": { "affiliate": { "optional": False, "default": "True", "type": bool, "description": "Affiliate identities to organizations" }, "unaffiliated_group": { "optional": False, "default": "Unknown", "type": str, "description": "Name of the organization for unaffiliated identities" }, "matching": { "optional": False, "default": ["email"], "type": list, "description": "Algorithm for matching identities in Sortinghat" }, "sleep_for": { "optional": False, "default": 3600, "type": int, "description": "Delay between task identities executions" }, "database": { "optional": False, "default": "sortinghat_db", "type": str, "description": "Name of the Sortinghat database" }, "host": { "optional": False, "default": "mariadb", "type": str, "description": "Host with the Sortinghat database" }, "user": { "optional": False, "default": "root", "type": str, "description": "User to access the Sortinghat database" }, "password": { "optional": False, "default": "", "type": str, "description": "Password to access the Sortinghat database" }, "autoprofile": { "optional": False, "default": ["customer", "git", "github"], "type": list, "description": "Order in which to get the identities information for filling the profile" }, "load_orgs": { "optional": True, "default": False, "type": bool, "deprecated": "Load organizations in Sortinghat database", "description": "" }, "identities_format": { "optional": True, "default": "sortinghat", "type": str, "description": "Format of the identities data to be loaded" }, "strict_mapping": { "optional": True, "default": True, "type": bool, "description": "rigorous check of values in identities matching " "(i.e, well formed email addresses)" }, "reset_on_load": { "optional": True, "default": False, "type": bool, "description": "Unmerge and remove affiliations for all identities on load" }, "orgs_file": { "optional": True, "default": None, "type": str, "description": "File path with the organizations to be loaded in Sortinghat" }, "identities_file": { "optional": True, "default": [], "type": list, "description": "File path with the identities to be loaded in Sortinghat" }, "identities_export_url": { "optional": True, "default": None, "type": str, "description": "URL in which to export the identities in Sortinghat" }, "identities_api_token": { "optional": True, "default": None, "type": str, "description": "API token for remote operation with GitHub and Gitlab" }, "bots_names": { "optional": True, "default": [], "type": list, "description": "Name of the identities to be marked as bots" }, "no_bots_names": { "optional": True, "default": [], "type": list, "description": "Name of the identities to be unmarked as bots" }, "autogender": { "optional": True, "default": False, "type": bool, "description": "Add gender to the profiles (executes autogender)" } } } params_track_items = { "track_items": { "project": { "optional": False, "default": "TrackProject", "type": str, "description": "Gerrit project to track" }, "upstream_raw_es_url": { "optional": False, "default": "", "type": str, "description": "URL with the file with the gerrit reviews to track" }, "raw_index_gerrit": { "optional": False, "default": "", "type": str, "description": "Name of the gerrit raw index" }, "raw_index_git": { "optional": False, "default": "", "type": str, "description": "Name of the git raw index" } } } tasks_config_params = [params_collection, params_enrichment, params_panels, params_report, params_sortinghat, params_track_items] for section_params in tasks_config_params: params.update(section_params) return params
[ "Define", "all", "the", "possible", "config", "params" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/config.py#L92-L606
[ "def", "general_params", "(", "cls", ")", ":", "params", "=", "{", "}", "# GENERAL CONFIG", "params_general", "=", "{", "\"general\"", ":", "{", "\"min_update_delay\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "60", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Short delay between tasks (collect, enrich ...)\"", "}", ",", "\"update\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Execute the tasks in loop\"", "}", ",", "\"short_name\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"Short name\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Short name of the project\"", "}", ",", "\"debug\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Debug mode (logging mainly)\"", "}", ",", "\"logs_dir\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"logs\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Directory with the logs of sirmordred\"", "}", ",", "\"log_handler\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "\"file\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"use rotate for rotating the logs automatically\"", "}", ",", "\"log_max_bytes\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "104857600", ",", "# 100MB", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Max number of bytes per log file\"", "}", ",", "\"log_backup_count\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "5", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Number of rotate logs files to preserve\"", "}", ",", "\"bulk_size\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "1000", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Number of items to write in Elasticsearch using bulk operations\"", "}", ",", "\"scroll_size\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "100", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Number of items to read from Elasticsearch when scrolling\"", "}", ",", "\"aliases_file\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "ALIASES_JSON", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"JSON file to define aliases for raw and enriched indexes\"", "}", ",", "\"menu_file\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "MENU_YAML", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"YAML file to define the menus to be shown in Kibiter\"", "}", ",", "\"retention_time\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"The maximum number of minutes wrt the current date to retain the data\"", "}", "}", "}", "params_projects", "=", "{", "\"projects\"", ":", "{", "\"projects_file\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "PROJECTS_JSON", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Projects file path with repositories to be collected group by projects\"", "}", ",", "\"projects_url\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Projects file URL\"", "}", ",", "\"load_eclipse\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Load the projects from Eclipse\"", "}", "}", "}", "params_phases", "=", "{", "\"phases\"", ":", "{", "\"collection\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Activate collection of items\"", "}", ",", "\"enrichment\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Activate enrichment of items\"", "}", ",", "\"identities\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Do the identities tasks\"", "}", ",", "\"panels\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Load panels, create alias and other tasks related\"", "}", ",", "\"track_items\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Track specific items from a gerrit repository\"", "}", ",", "\"report\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Generate the PDF report for a project (alpha)\"", "}", "}", "}", "general_config_params", "=", "[", "params_general", ",", "params_projects", ",", "params_phases", "]", "for", "section_params", "in", "general_config_params", ":", "params", ".", "update", "(", "section_params", ")", "# Config provided by tasks", "params_collection", "=", "{", "\"es_collection\"", ":", "{", "\"password\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Password for connection to Elasticsearch\"", "}", ",", "\"user\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"User for connection to Elasticsearch\"", "}", ",", "\"url\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"http://172.17.0.1:9200\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Elasticsearch URL\"", "}", ",", "\"arthur\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Use arthur for collecting items from perceval\"", "}", ",", "\"arthur_url\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"URL for the arthur service\"", "}", ",", "\"redis_url\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"URL for the redis service\"", "}", "}", "}", "params_enrichment", "=", "{", "\"es_enrichment\"", ":", "{", "\"url\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"http://172.17.0.1:9200\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Elasticsearch URL\"", "}", ",", "\"autorefresh\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Execute the autorefresh of identities\"", "}", ",", "\"autorefresh_interval\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "2", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Set time interval (days) for autorefresh identities\"", "}", ",", "\"user\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"User for connection to Elasticsearch\"", "}", ",", "\"password\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Password for connection to Elasticsearch\"", "}", "}", "}", "params_panels", "=", "{", "\"panels\"", ":", "{", "\"strict\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable strict panels loading\"", "}", ",", "\"kibiter_time_from\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "\"now-90d\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Default time interval for Kibiter\"", "}", ",", "\"kibiter_default_index\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "\"git\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Default index pattern for Kibiter\"", "}", ",", "\"kibiter_url\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Kibiter URL\"", "}", ",", "\"kibiter_version\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Kibiter version\"", "}", ",", "\"community\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable community structure menu\"", "}", ",", "\"kafka\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable kafka menu\"", "}", ",", "\"github-repos\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable GitHub repo stats menu\"", "}", ",", "\"gitlab-issues\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable GitLab issues menu\"", "}", ",", "\"gitlab-merges\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable GitLab merge requests menu\"", "}", ",", "\"mattermost\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Enable Mattermost menu\"", "}", "}", "}", "params_report", "=", "{", "\"report\"", ":", "{", "\"start_date\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"1970-01-01\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Start date for the report\"", "}", ",", "\"end_date\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"2100-01-01\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"End date for the report\"", "}", ",", "\"interval\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"quarter\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Interval for the report\"", "}", ",", "\"config_file\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"report.cfg\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Config file for the report\"", "}", ",", "\"data_dir\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"report_data\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Directory in which to store the report data\"", "}", ",", "\"filters\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "[", "]", ",", "\"type\"", ":", "list", ",", "\"description\"", ":", "\"General filters to be applied to all queries\"", "}", ",", "\"offset\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Date offset to be applied to start and end\"", "}", "}", "}", "params_sortinghat", "=", "{", "\"sortinghat\"", ":", "{", "\"affiliate\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"True\"", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Affiliate identities to organizations\"", "}", ",", "\"unaffiliated_group\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"Unknown\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Name of the organization for unaffiliated identities\"", "}", ",", "\"matching\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "[", "\"email\"", "]", ",", "\"type\"", ":", "list", ",", "\"description\"", ":", "\"Algorithm for matching identities in Sortinghat\"", "}", ",", "\"sleep_for\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "3600", ",", "\"type\"", ":", "int", ",", "\"description\"", ":", "\"Delay between task identities executions\"", "}", ",", "\"database\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"sortinghat_db\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Name of the Sortinghat database\"", "}", ",", "\"host\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"mariadb\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Host with the Sortinghat database\"", "}", ",", "\"user\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"root\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"User to access the Sortinghat database\"", "}", ",", "\"password\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Password to access the Sortinghat database\"", "}", ",", "\"autoprofile\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "[", "\"customer\"", ",", "\"git\"", ",", "\"github\"", "]", ",", "\"type\"", ":", "list", ",", "\"description\"", ":", "\"Order in which to get the identities information for filling the profile\"", "}", ",", "\"load_orgs\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"deprecated\"", ":", "\"Load organizations in Sortinghat database\"", ",", "\"description\"", ":", "\"\"", "}", ",", "\"identities_format\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "\"sortinghat\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Format of the identities data to be loaded\"", "}", ",", "\"strict_mapping\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "True", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"rigorous check of values in identities matching \"", "\"(i.e, well formed email addresses)\"", "}", ",", "\"reset_on_load\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Unmerge and remove affiliations for all identities on load\"", "}", ",", "\"orgs_file\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"File path with the organizations to be loaded in Sortinghat\"", "}", ",", "\"identities_file\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "[", "]", ",", "\"type\"", ":", "list", ",", "\"description\"", ":", "\"File path with the identities to be loaded in Sortinghat\"", "}", ",", "\"identities_export_url\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"URL in which to export the identities in Sortinghat\"", "}", ",", "\"identities_api_token\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "None", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"API token for remote operation with GitHub and Gitlab\"", "}", ",", "\"bots_names\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "[", "]", ",", "\"type\"", ":", "list", ",", "\"description\"", ":", "\"Name of the identities to be marked as bots\"", "}", ",", "\"no_bots_names\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "[", "]", ",", "\"type\"", ":", "list", ",", "\"description\"", ":", "\"Name of the identities to be unmarked as bots\"", "}", ",", "\"autogender\"", ":", "{", "\"optional\"", ":", "True", ",", "\"default\"", ":", "False", ",", "\"type\"", ":", "bool", ",", "\"description\"", ":", "\"Add gender to the profiles (executes autogender)\"", "}", "}", "}", "params_track_items", "=", "{", "\"track_items\"", ":", "{", "\"project\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"TrackProject\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Gerrit project to track\"", "}", ",", "\"upstream_raw_es_url\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"URL with the file with the gerrit reviews to track\"", "}", ",", "\"raw_index_gerrit\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Name of the gerrit raw index\"", "}", ",", "\"raw_index_git\"", ":", "{", "\"optional\"", ":", "False", ",", "\"default\"", ":", "\"\"", ",", "\"type\"", ":", "str", ",", "\"description\"", ":", "\"Name of the git raw index\"", "}", "}", "}", "tasks_config_params", "=", "[", "params_collection", ",", "params_enrichment", ",", "params_panels", ",", "params_report", ",", "params_sortinghat", ",", "params_track_items", "]", "for", "section_params", "in", "tasks_config_params", ":", "params", ".", "update", "(", "section_params", ")", "return", "params" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
Config.set_param
Change a param in the config
sirmordred/config.py
def set_param(self, section, param, value): """ Change a param in the config """ if section not in self.conf or param not in self.conf[section]: logger.error('Config section %s and param %s not exists', section, param) else: self.conf[section][param] = value
def set_param(self, section, param, value): """ Change a param in the config """ if section not in self.conf or param not in self.conf[section]: logger.error('Config section %s and param %s not exists', section, param) else: self.conf[section][param] = value
[ "Change", "a", "param", "in", "the", "config" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/config.py#L649-L654
[ "def", "set_param", "(", "self", ",", "section", ",", "param", ",", "value", ")", ":", "if", "section", "not", "in", "self", ".", "conf", "or", "param", "not", "in", "self", ".", "conf", "[", "section", "]", ":", "logger", ".", "error", "(", "'Config section %s and param %s not exists'", ",", "section", ",", "param", ")", "else", ":", "self", ".", "conf", "[", "section", "]", "[", "param", "]", "=", "value" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
Config._add_to_conf
Add new configuration to self.conf. Adds configuration parameters in new_con to self.conf. If they already existed in conf, overwrite them. :param new_conf: new configuration, to add
sirmordred/config.py
def _add_to_conf(self, new_conf): """Add new configuration to self.conf. Adds configuration parameters in new_con to self.conf. If they already existed in conf, overwrite them. :param new_conf: new configuration, to add """ for section in new_conf: if section not in self.conf: self.conf[section] = new_conf[section] else: for param in new_conf[section]: self.conf[section][param] = new_conf[section][param]
def _add_to_conf(self, new_conf): """Add new configuration to self.conf. Adds configuration parameters in new_con to self.conf. If they already existed in conf, overwrite them. :param new_conf: new configuration, to add """ for section in new_conf: if section not in self.conf: self.conf[section] = new_conf[section] else: for param in new_conf[section]: self.conf[section][param] = new_conf[section][param]
[ "Add", "new", "configuration", "to", "self", ".", "conf", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/config.py#L782-L796
[ "def", "_add_to_conf", "(", "self", ",", "new_conf", ")", ":", "for", "section", "in", "new_conf", ":", "if", "section", "not", "in", "self", ".", "conf", ":", "self", ".", "conf", "[", "section", "]", "=", "new_conf", "[", "section", "]", "else", ":", "for", "param", "in", "new_conf", "[", "section", "]", ":", "self", ".", "conf", "[", "section", "]", "[", "param", "]", "=", "new_conf", "[", "section", "]", "[", "param", "]" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
Task.es_version
Get Elasticsearch version. Get the version of Elasticsearch. This is useful because Elasticsearch and Kibiter are paired (same major version for 5, 6). :param url: Elasticseearch url hosting Kibiter indices :returns: major version, as string
sirmordred/task.py
def es_version(self, url): """Get Elasticsearch version. Get the version of Elasticsearch. This is useful because Elasticsearch and Kibiter are paired (same major version for 5, 6). :param url: Elasticseearch url hosting Kibiter indices :returns: major version, as string """ try: res = self.grimoire_con.get(url) res.raise_for_status() major = res.json()['version']['number'].split(".")[0] except Exception: logger.error("Error retrieving Elasticsearch version: " + url) raise return major
def es_version(self, url): """Get Elasticsearch version. Get the version of Elasticsearch. This is useful because Elasticsearch and Kibiter are paired (same major version for 5, 6). :param url: Elasticseearch url hosting Kibiter indices :returns: major version, as string """ try: res = self.grimoire_con.get(url) res.raise_for_status() major = res.json()['version']['number'].split(".")[0] except Exception: logger.error("Error retrieving Elasticsearch version: " + url) raise return major
[ "Get", "Elasticsearch", "version", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task.py#L237-L254
[ "def", "es_version", "(", "self", ",", "url", ")", ":", "try", ":", "res", "=", "self", ".", "grimoire_con", ".", "get", "(", "url", ")", "res", ".", "raise_for_status", "(", ")", "major", "=", "res", ".", "json", "(", ")", "[", "'version'", "]", "[", "'number'", "]", ".", "split", "(", "\".\"", ")", "[", "0", "]", "except", "Exception", ":", "logger", ".", "error", "(", "\"Error retrieving Elasticsearch version: \"", "+", "url", ")", "raise", "return", "major" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
SirMordred.execute_nonstop_tasks
Just a wrapper to the execute_batch_tasks method
sirmordred/sirmordred.py
def execute_nonstop_tasks(self, tasks_cls): """ Just a wrapper to the execute_batch_tasks method """ self.execute_batch_tasks(tasks_cls, self.conf['sortinghat']['sleep_for'], self.conf['general']['min_update_delay'], False)
def execute_nonstop_tasks(self, tasks_cls): """ Just a wrapper to the execute_batch_tasks method """ self.execute_batch_tasks(tasks_cls, self.conf['sortinghat']['sleep_for'], self.conf['general']['min_update_delay'], False)
[ "Just", "a", "wrapper", "to", "the", "execute_batch_tasks", "method" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L194-L200
[ "def", "execute_nonstop_tasks", "(", "self", ",", "tasks_cls", ")", ":", "self", ".", "execute_batch_tasks", "(", "tasks_cls", ",", "self", ".", "conf", "[", "'sortinghat'", "]", "[", "'sleep_for'", "]", ",", "self", ".", "conf", "[", "'general'", "]", "[", "'min_update_delay'", "]", ",", "False", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
SirMordred.execute_batch_tasks
Start a task manager per backend to complete the tasks. :param task_cls: list of tasks classes to be executed :param big_delay: seconds before global tasks are executed, should be days usually :param small_delay: seconds before backend tasks are executed, should be minutes :param wait_for_threads: boolean to set when threads are infinite or should be synchronized in a meeting point
sirmordred/sirmordred.py
def execute_batch_tasks(self, tasks_cls, big_delay=0, small_delay=0, wait_for_threads=True): """ Start a task manager per backend to complete the tasks. :param task_cls: list of tasks classes to be executed :param big_delay: seconds before global tasks are executed, should be days usually :param small_delay: seconds before backend tasks are executed, should be minutes :param wait_for_threads: boolean to set when threads are infinite or should be synchronized in a meeting point """ def _split_tasks(tasks_cls): """ we internally distinguish between tasks executed by backend and tasks executed with no specific backend. """ backend_t = [] global_t = [] for t in tasks_cls: if t.is_backend_task(t): backend_t.append(t) else: global_t.append(t) return backend_t, global_t backend_tasks, global_tasks = _split_tasks(tasks_cls) logger.debug('backend_tasks = %s' % (backend_tasks)) logger.debug('global_tasks = %s' % (global_tasks)) threads = [] # stopper won't be set unless wait_for_threads is True stopper = threading.Event() # launching threads for tasks by backend if len(backend_tasks) > 0: repos_backend = self._get_repos_by_backend() for backend in repos_backend: # Start new Threads and add them to the threads list to complete t = TasksManager(backend_tasks, backend, stopper, self.config, small_delay) threads.append(t) t.start() # launch thread for global tasks if len(global_tasks) > 0: # FIXME timer is applied to all global_tasks, does it make sense? # All tasks are executed in the same thread sequentially gt = TasksManager(global_tasks, "Global tasks", stopper, self.config, big_delay) threads.append(gt) gt.start() if big_delay > 0: when = datetime.now() + timedelta(seconds=big_delay) when_str = when.strftime('%a, %d %b %Y %H:%M:%S %Z') logger.info("%s will be executed on %s" % (global_tasks, when_str)) if wait_for_threads: time.sleep(1) # Give enough time create and run all threads stopper.set() # All threads must stop in the next iteration # Wait for all threads to complete for t in threads: t.join() # Checking for exceptions in threads to log them self.__check_queue_for_errors() logger.debug("[thread:main] All threads (and their tasks) are finished")
def execute_batch_tasks(self, tasks_cls, big_delay=0, small_delay=0, wait_for_threads=True): """ Start a task manager per backend to complete the tasks. :param task_cls: list of tasks classes to be executed :param big_delay: seconds before global tasks are executed, should be days usually :param small_delay: seconds before backend tasks are executed, should be minutes :param wait_for_threads: boolean to set when threads are infinite or should be synchronized in a meeting point """ def _split_tasks(tasks_cls): """ we internally distinguish between tasks executed by backend and tasks executed with no specific backend. """ backend_t = [] global_t = [] for t in tasks_cls: if t.is_backend_task(t): backend_t.append(t) else: global_t.append(t) return backend_t, global_t backend_tasks, global_tasks = _split_tasks(tasks_cls) logger.debug('backend_tasks = %s' % (backend_tasks)) logger.debug('global_tasks = %s' % (global_tasks)) threads = [] # stopper won't be set unless wait_for_threads is True stopper = threading.Event() # launching threads for tasks by backend if len(backend_tasks) > 0: repos_backend = self._get_repos_by_backend() for backend in repos_backend: # Start new Threads and add them to the threads list to complete t = TasksManager(backend_tasks, backend, stopper, self.config, small_delay) threads.append(t) t.start() # launch thread for global tasks if len(global_tasks) > 0: # FIXME timer is applied to all global_tasks, does it make sense? # All tasks are executed in the same thread sequentially gt = TasksManager(global_tasks, "Global tasks", stopper, self.config, big_delay) threads.append(gt) gt.start() if big_delay > 0: when = datetime.now() + timedelta(seconds=big_delay) when_str = when.strftime('%a, %d %b %Y %H:%M:%S %Z') logger.info("%s will be executed on %s" % (global_tasks, when_str)) if wait_for_threads: time.sleep(1) # Give enough time create and run all threads stopper.set() # All threads must stop in the next iteration # Wait for all threads to complete for t in threads: t.join() # Checking for exceptions in threads to log them self.__check_queue_for_errors() logger.debug("[thread:main] All threads (and their tasks) are finished")
[ "Start", "a", "task", "manager", "per", "backend", "to", "complete", "the", "tasks", "." ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L202-L267
[ "def", "execute_batch_tasks", "(", "self", ",", "tasks_cls", ",", "big_delay", "=", "0", ",", "small_delay", "=", "0", ",", "wait_for_threads", "=", "True", ")", ":", "def", "_split_tasks", "(", "tasks_cls", ")", ":", "\"\"\"\n we internally distinguish between tasks executed by backend\n and tasks executed with no specific backend. \"\"\"", "backend_t", "=", "[", "]", "global_t", "=", "[", "]", "for", "t", "in", "tasks_cls", ":", "if", "t", ".", "is_backend_task", "(", "t", ")", ":", "backend_t", ".", "append", "(", "t", ")", "else", ":", "global_t", ".", "append", "(", "t", ")", "return", "backend_t", ",", "global_t", "backend_tasks", ",", "global_tasks", "=", "_split_tasks", "(", "tasks_cls", ")", "logger", ".", "debug", "(", "'backend_tasks = %s'", "%", "(", "backend_tasks", ")", ")", "logger", ".", "debug", "(", "'global_tasks = %s'", "%", "(", "global_tasks", ")", ")", "threads", "=", "[", "]", "# stopper won't be set unless wait_for_threads is True", "stopper", "=", "threading", ".", "Event", "(", ")", "# launching threads for tasks by backend", "if", "len", "(", "backend_tasks", ")", ">", "0", ":", "repos_backend", "=", "self", ".", "_get_repos_by_backend", "(", ")", "for", "backend", "in", "repos_backend", ":", "# Start new Threads and add them to the threads list to complete", "t", "=", "TasksManager", "(", "backend_tasks", ",", "backend", ",", "stopper", ",", "self", ".", "config", ",", "small_delay", ")", "threads", ".", "append", "(", "t", ")", "t", ".", "start", "(", ")", "# launch thread for global tasks", "if", "len", "(", "global_tasks", ")", ">", "0", ":", "# FIXME timer is applied to all global_tasks, does it make sense?", "# All tasks are executed in the same thread sequentially", "gt", "=", "TasksManager", "(", "global_tasks", ",", "\"Global tasks\"", ",", "stopper", ",", "self", ".", "config", ",", "big_delay", ")", "threads", ".", "append", "(", "gt", ")", "gt", ".", "start", "(", ")", "if", "big_delay", ">", "0", ":", "when", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "big_delay", ")", "when_str", "=", "when", ".", "strftime", "(", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "logger", ".", "info", "(", "\"%s will be executed on %s\"", "%", "(", "global_tasks", ",", "when_str", ")", ")", "if", "wait_for_threads", ":", "time", ".", "sleep", "(", "1", ")", "# Give enough time create and run all threads", "stopper", ".", "set", "(", ")", "# All threads must stop in the next iteration", "# Wait for all threads to complete", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "# Checking for exceptions in threads to log them", "self", ".", "__check_queue_for_errors", "(", ")", "logger", ".", "debug", "(", "\"[thread:main] All threads (and their tasks) are finished\"", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
SirMordred.__execute_initial_load
Tasks that should be done just one time
sirmordred/sirmordred.py
def __execute_initial_load(self): """ Tasks that should be done just one time """ if self.conf['phases']['panels']: tasks_cls = [TaskPanels, TaskPanelsMenu] self.execute_tasks(tasks_cls) if self.conf['phases']['identities']: tasks_cls = [TaskInitSortingHat] self.execute_tasks(tasks_cls) logger.info("Loading projects") tasks_cls = [TaskProjects] self.execute_tasks(tasks_cls) logger.info("Done") return
def __execute_initial_load(self): """ Tasks that should be done just one time """ if self.conf['phases']['panels']: tasks_cls = [TaskPanels, TaskPanelsMenu] self.execute_tasks(tasks_cls) if self.conf['phases']['identities']: tasks_cls = [TaskInitSortingHat] self.execute_tasks(tasks_cls) logger.info("Loading projects") tasks_cls = [TaskProjects] self.execute_tasks(tasks_cls) logger.info("Done") return
[ "Tasks", "that", "should", "be", "done", "just", "one", "time" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L280-L297
[ "def", "__execute_initial_load", "(", "self", ")", ":", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'panels'", "]", ":", "tasks_cls", "=", "[", "TaskPanels", ",", "TaskPanelsMenu", "]", "self", ".", "execute_tasks", "(", "tasks_cls", ")", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'identities'", "]", ":", "tasks_cls", "=", "[", "TaskInitSortingHat", "]", "self", ".", "execute_tasks", "(", "tasks_cls", ")", "logger", ".", "info", "(", "\"Loading projects\"", ")", "tasks_cls", "=", "[", "TaskProjects", "]", "self", ".", "execute_tasks", "(", "tasks_cls", ")", "logger", ".", "info", "(", "\"Done\"", ")", "return" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
SirMordred.start
This method defines the workflow of SirMordred. So it calls to: - initialize the databases - execute the different phases for the first iteration (collection, identities, enrichment) - start the collection and enrichment in parallel by data source - start also the Sorting Hat merge
sirmordred/sirmordred.py
def start(self): """ This method defines the workflow of SirMordred. So it calls to: - initialize the databases - execute the different phases for the first iteration (collection, identities, enrichment) - start the collection and enrichment in parallel by data source - start also the Sorting Hat merge """ # logger.debug("Starting SirMordred engine ...") logger.info("") logger.info("----------------------------") logger.info("Starting SirMordred engine ...") logger.info("- - - - - - - - - - - - - - ") # check we have access to the needed ES if not self.check_es_access(): print('Can not access Elasticsearch service. Exiting sirmordred ...') sys.exit(1) # If arthur is configured check that it is working if self.conf['es_collection']['arthur']: if not self.check_redis_access(): print('Can not access redis service. Exiting sirmordred ...') sys.exit(1) if not self.check_arthur_access(): print('Can not access arthur service. Exiting sirmordred ...') sys.exit(1) # If bestiary is configured check that it is working if self.conf['projects']['projects_url']: if not self.check_bestiary_access(): print('Can not access bestiary service. Exiting sirmordred ...') sys.exit(1) # Initial round: panels and projects loading self.__execute_initial_load() # Tasks to be executed during updating process all_tasks_cls = [] all_tasks_cls.append(TaskProjects) # projects update is always needed if self.conf['phases']['collection']: if not self.conf['es_collection']['arthur']: all_tasks_cls.append(TaskRawDataCollection) else: all_tasks_cls.append(TaskRawDataArthurCollection) if self.conf['phases']['identities']: # load identities and orgs periodically for updates all_tasks_cls.append(TaskIdentitiesLoad) all_tasks_cls.append(TaskIdentitiesMerge) all_tasks_cls.append(TaskIdentitiesExport) # This is done in enrichement before doing the enrich # if self.conf['phases']['collection']: # all_tasks_cls.append(TaskIdentitiesCollection) if self.conf['phases']['enrichment']: all_tasks_cls.append(TaskEnrich) if self.conf['phases']['track_items']: all_tasks_cls.append(TaskTrackItems) if self.conf['phases']['report']: all_tasks_cls.append(TaskReport) # this is the main loop, where the execution should spend # most of its time while True: if not all_tasks_cls: logger.warning("No tasks to execute.") break try: if not self.conf['general']['update']: self.execute_batch_tasks(all_tasks_cls, self.conf['sortinghat']['sleep_for'], self.conf['general']['min_update_delay']) self.execute_batch_tasks(all_tasks_cls, self.conf['sortinghat']['sleep_for'], self.conf['general']['min_update_delay']) break else: self.execute_nonstop_tasks(all_tasks_cls) # FIXME this point is never reached so despite the exception is # handled and the error is shown, the traceback is not printed except DataCollectionError as e: logger.error(str(e)) var = traceback.format_exc() logger.error(var) except DataEnrichmentError as e: logger.error(str(e)) var = traceback.format_exc() logger.error(var) logger.info("Finished SirMordred engine ...")
def start(self): """ This method defines the workflow of SirMordred. So it calls to: - initialize the databases - execute the different phases for the first iteration (collection, identities, enrichment) - start the collection and enrichment in parallel by data source - start also the Sorting Hat merge """ # logger.debug("Starting SirMordred engine ...") logger.info("") logger.info("----------------------------") logger.info("Starting SirMordred engine ...") logger.info("- - - - - - - - - - - - - - ") # check we have access to the needed ES if not self.check_es_access(): print('Can not access Elasticsearch service. Exiting sirmordred ...') sys.exit(1) # If arthur is configured check that it is working if self.conf['es_collection']['arthur']: if not self.check_redis_access(): print('Can not access redis service. Exiting sirmordred ...') sys.exit(1) if not self.check_arthur_access(): print('Can not access arthur service. Exiting sirmordred ...') sys.exit(1) # If bestiary is configured check that it is working if self.conf['projects']['projects_url']: if not self.check_bestiary_access(): print('Can not access bestiary service. Exiting sirmordred ...') sys.exit(1) # Initial round: panels and projects loading self.__execute_initial_load() # Tasks to be executed during updating process all_tasks_cls = [] all_tasks_cls.append(TaskProjects) # projects update is always needed if self.conf['phases']['collection']: if not self.conf['es_collection']['arthur']: all_tasks_cls.append(TaskRawDataCollection) else: all_tasks_cls.append(TaskRawDataArthurCollection) if self.conf['phases']['identities']: # load identities and orgs periodically for updates all_tasks_cls.append(TaskIdentitiesLoad) all_tasks_cls.append(TaskIdentitiesMerge) all_tasks_cls.append(TaskIdentitiesExport) # This is done in enrichement before doing the enrich # if self.conf['phases']['collection']: # all_tasks_cls.append(TaskIdentitiesCollection) if self.conf['phases']['enrichment']: all_tasks_cls.append(TaskEnrich) if self.conf['phases']['track_items']: all_tasks_cls.append(TaskTrackItems) if self.conf['phases']['report']: all_tasks_cls.append(TaskReport) # this is the main loop, where the execution should spend # most of its time while True: if not all_tasks_cls: logger.warning("No tasks to execute.") break try: if not self.conf['general']['update']: self.execute_batch_tasks(all_tasks_cls, self.conf['sortinghat']['sleep_for'], self.conf['general']['min_update_delay']) self.execute_batch_tasks(all_tasks_cls, self.conf['sortinghat']['sleep_for'], self.conf['general']['min_update_delay']) break else: self.execute_nonstop_tasks(all_tasks_cls) # FIXME this point is never reached so despite the exception is # handled and the error is shown, the traceback is not printed except DataCollectionError as e: logger.error(str(e)) var = traceback.format_exc() logger.error(var) except DataEnrichmentError as e: logger.error(str(e)) var = traceback.format_exc() logger.error(var) logger.info("Finished SirMordred engine ...")
[ "This", "method", "defines", "the", "workflow", "of", "SirMordred", ".", "So", "it", "calls", "to", ":", "-", "initialize", "the", "databases", "-", "execute", "the", "different", "phases", "for", "the", "first", "iteration", "(", "collection", "identities", "enrichment", ")", "-", "start", "the", "collection", "and", "enrichment", "in", "parallel", "by", "data", "source", "-", "start", "also", "the", "Sorting", "Hat", "merge" ]
chaoss/grimoirelab-sirmordred
python
https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L299-L395
[ "def", "start", "(", "self", ")", ":", "# logger.debug(\"Starting SirMordred engine ...\")", "logger", ".", "info", "(", "\"\"", ")", "logger", ".", "info", "(", "\"----------------------------\"", ")", "logger", ".", "info", "(", "\"Starting SirMordred engine ...\"", ")", "logger", ".", "info", "(", "\"- - - - - - - - - - - - - - \"", ")", "# check we have access to the needed ES", "if", "not", "self", ".", "check_es_access", "(", ")", ":", "print", "(", "'Can not access Elasticsearch service. Exiting sirmordred ...'", ")", "sys", ".", "exit", "(", "1", ")", "# If arthur is configured check that it is working", "if", "self", ".", "conf", "[", "'es_collection'", "]", "[", "'arthur'", "]", ":", "if", "not", "self", ".", "check_redis_access", "(", ")", ":", "print", "(", "'Can not access redis service. Exiting sirmordred ...'", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "self", ".", "check_arthur_access", "(", ")", ":", "print", "(", "'Can not access arthur service. Exiting sirmordred ...'", ")", "sys", ".", "exit", "(", "1", ")", "# If bestiary is configured check that it is working", "if", "self", ".", "conf", "[", "'projects'", "]", "[", "'projects_url'", "]", ":", "if", "not", "self", ".", "check_bestiary_access", "(", ")", ":", "print", "(", "'Can not access bestiary service. Exiting sirmordred ...'", ")", "sys", ".", "exit", "(", "1", ")", "# Initial round: panels and projects loading", "self", ".", "__execute_initial_load", "(", ")", "# Tasks to be executed during updating process", "all_tasks_cls", "=", "[", "]", "all_tasks_cls", ".", "append", "(", "TaskProjects", ")", "# projects update is always needed", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'collection'", "]", ":", "if", "not", "self", ".", "conf", "[", "'es_collection'", "]", "[", "'arthur'", "]", ":", "all_tasks_cls", ".", "append", "(", "TaskRawDataCollection", ")", "else", ":", "all_tasks_cls", ".", "append", "(", "TaskRawDataArthurCollection", ")", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'identities'", "]", ":", "# load identities and orgs periodically for updates", "all_tasks_cls", ".", "append", "(", "TaskIdentitiesLoad", ")", "all_tasks_cls", ".", "append", "(", "TaskIdentitiesMerge", ")", "all_tasks_cls", ".", "append", "(", "TaskIdentitiesExport", ")", "# This is done in enrichement before doing the enrich", "# if self.conf['phases']['collection']:", "# all_tasks_cls.append(TaskIdentitiesCollection)", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'enrichment'", "]", ":", "all_tasks_cls", ".", "append", "(", "TaskEnrich", ")", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'track_items'", "]", ":", "all_tasks_cls", ".", "append", "(", "TaskTrackItems", ")", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'report'", "]", ":", "all_tasks_cls", ".", "append", "(", "TaskReport", ")", "# this is the main loop, where the execution should spend", "# most of its time", "while", "True", ":", "if", "not", "all_tasks_cls", ":", "logger", ".", "warning", "(", "\"No tasks to execute.\"", ")", "break", "try", ":", "if", "not", "self", ".", "conf", "[", "'general'", "]", "[", "'update'", "]", ":", "self", ".", "execute_batch_tasks", "(", "all_tasks_cls", ",", "self", ".", "conf", "[", "'sortinghat'", "]", "[", "'sleep_for'", "]", ",", "self", ".", "conf", "[", "'general'", "]", "[", "'min_update_delay'", "]", ")", "self", ".", "execute_batch_tasks", "(", "all_tasks_cls", ",", "self", ".", "conf", "[", "'sortinghat'", "]", "[", "'sleep_for'", "]", ",", "self", ".", "conf", "[", "'general'", "]", "[", "'min_update_delay'", "]", ")", "break", "else", ":", "self", ".", "execute_nonstop_tasks", "(", "all_tasks_cls", ")", "# FIXME this point is never reached so despite the exception is", "# handled and the error is shown, the traceback is not printed", "except", "DataCollectionError", "as", "e", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "var", "=", "traceback", ".", "format_exc", "(", ")", "logger", ".", "error", "(", "var", ")", "except", "DataEnrichmentError", "as", "e", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "var", "=", "traceback", ".", "format_exc", "(", ")", "logger", ".", "error", "(", "var", ")", "logger", ".", "info", "(", "\"Finished SirMordred engine ...\"", ")" ]
d6ac94d28d707fae23170064d078f1edf937d13e
valid
Sultan.run
After building your commands, call `run()` to have your code executed.
src/sultan/api.py
def run(self, halt_on_nonzero=True, quiet=False, q=False, streaming=False): """ After building your commands, call `run()` to have your code executed. """ commands = str(self) if not (quiet or q): self._echo.cmd(commands) env = self._context[0].get('env', {}) if len(self._context) > 0 else os.environ executable = self.current_context.get('executable') try: process = subprocess.Popen(commands, bufsize=1, shell=True, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable=executable, universal_newlines=True) result = Result(process, commands, self._context, streaming, halt_on_nonzero=halt_on_nonzero) except Exception as e: result = Result(None, commands, self._context, exception=e) result.dump_exception() if halt_on_nonzero: raise e finally: self.clear() return result
def run(self, halt_on_nonzero=True, quiet=False, q=False, streaming=False): """ After building your commands, call `run()` to have your code executed. """ commands = str(self) if not (quiet or q): self._echo.cmd(commands) env = self._context[0].get('env', {}) if len(self._context) > 0 else os.environ executable = self.current_context.get('executable') try: process = subprocess.Popen(commands, bufsize=1, shell=True, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable=executable, universal_newlines=True) result = Result(process, commands, self._context, streaming, halt_on_nonzero=halt_on_nonzero) except Exception as e: result = Result(None, commands, self._context, exception=e) result.dump_exception() if halt_on_nonzero: raise e finally: self.clear() return result
[ "After", "building", "your", "commands", "call", "run", "()", "to", "have", "your", "code", "executed", "." ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/api.py#L192-L223
[ "def", "run", "(", "self", ",", "halt_on_nonzero", "=", "True", ",", "quiet", "=", "False", ",", "q", "=", "False", ",", "streaming", "=", "False", ")", ":", "commands", "=", "str", "(", "self", ")", "if", "not", "(", "quiet", "or", "q", ")", ":", "self", ".", "_echo", ".", "cmd", "(", "commands", ")", "env", "=", "self", ".", "_context", "[", "0", "]", ".", "get", "(", "'env'", ",", "{", "}", ")", "if", "len", "(", "self", ".", "_context", ")", ">", "0", "else", "os", ".", "environ", "executable", "=", "self", ".", "current_context", ".", "get", "(", "'executable'", ")", "try", ":", "process", "=", "subprocess", ".", "Popen", "(", "commands", ",", "bufsize", "=", "1", ",", "shell", "=", "True", ",", "env", "=", "env", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "executable", "=", "executable", ",", "universal_newlines", "=", "True", ")", "result", "=", "Result", "(", "process", ",", "commands", ",", "self", ".", "_context", ",", "streaming", ",", "halt_on_nonzero", "=", "halt_on_nonzero", ")", "except", "Exception", "as", "e", ":", "result", "=", "Result", "(", "None", ",", "commands", ",", "self", ".", "_context", ",", "exception", "=", "e", ")", "result", ".", "dump_exception", "(", ")", "if", "halt_on_nonzero", ":", "raise", "e", "finally", ":", "self", ".", "clear", "(", ")", "return", "result" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
Config.validate_config
Validates the provided config to make sure all the required fields are there.
src/sultan/api.py
def validate_config(self): ''' Validates the provided config to make sure all the required fields are there. ''' # first ensure that all the required fields are there for key, key_config in self.params_map.items(): if key_config['required']: if key not in self.config: raise ValueError("Invalid Configuration! Required parameter '%s' was not provided to Sultan.") # second ensure that the fields that were pased were actually fields that # can be used for key in self.config.keys(): if key not in self.params_map: raise ValueError("Invalid Configuration! The parameter '%s' provided is not used by Sultan!" % key)
def validate_config(self): ''' Validates the provided config to make sure all the required fields are there. ''' # first ensure that all the required fields are there for key, key_config in self.params_map.items(): if key_config['required']: if key not in self.config: raise ValueError("Invalid Configuration! Required parameter '%s' was not provided to Sultan.") # second ensure that the fields that were pased were actually fields that # can be used for key in self.config.keys(): if key not in self.params_map: raise ValueError("Invalid Configuration! The parameter '%s' provided is not used by Sultan!" % key)
[ "Validates", "the", "provided", "config", "to", "make", "sure", "all", "the", "required", "fields", "are", "there", "." ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/api.py#L505-L520
[ "def", "validate_config", "(", "self", ")", ":", "# first ensure that all the required fields are there", "for", "key", ",", "key_config", "in", "self", ".", "params_map", ".", "items", "(", ")", ":", "if", "key_config", "[", "'required'", "]", ":", "if", "key", "not", "in", "self", ".", "config", ":", "raise", "ValueError", "(", "\"Invalid Configuration! Required parameter '%s' was not provided to Sultan.\"", ")", "# second ensure that the fields that were pased were actually fields that", "# can be used", "for", "key", "in", "self", ".", "config", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "self", ".", "params_map", ":", "raise", "ValueError", "(", "\"Invalid Configuration! The parameter '%s' provided is not used by Sultan!\"", "%", "key", ")" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
Result.stdout
Converts stdout string to a list.
src/sultan/result.py
def stdout(self): """ Converts stdout string to a list. """ if self._streaming: stdout = [] while not self.__stdout.empty(): try: line = self.__stdout.get_nowait() stdout.append(line) except: pass else: stdout = self.__stdout return stdout
def stdout(self): """ Converts stdout string to a list. """ if self._streaming: stdout = [] while not self.__stdout.empty(): try: line = self.__stdout.get_nowait() stdout.append(line) except: pass else: stdout = self.__stdout return stdout
[ "Converts", "stdout", "string", "to", "a", "list", "." ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L152-L166
[ "def", "stdout", "(", "self", ")", ":", "if", "self", ".", "_streaming", ":", "stdout", "=", "[", "]", "while", "not", "self", ".", "__stdout", ".", "empty", "(", ")", ":", "try", ":", "line", "=", "self", ".", "__stdout", ".", "get_nowait", "(", ")", "stdout", ".", "append", "(", "line", ")", "except", ":", "pass", "else", ":", "stdout", "=", "self", ".", "__stdout", "return", "stdout" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
Result.stderr
Converts stderr string to a list.
src/sultan/result.py
def stderr(self): """ Converts stderr string to a list. """ if self._streaming: stderr = [] while not self.__stderr.empty(): try: line = self.__stderr.get_nowait() stderr.append(line) except: pass else: stderr = self.__stderr return stderr
def stderr(self): """ Converts stderr string to a list. """ if self._streaming: stderr = [] while not self.__stderr.empty(): try: line = self.__stderr.get_nowait() stderr.append(line) except: pass else: stderr = self.__stderr return stderr
[ "Converts", "stderr", "string", "to", "a", "list", "." ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L169-L183
[ "def", "stderr", "(", "self", ")", ":", "if", "self", ".", "_streaming", ":", "stderr", "=", "[", "]", "while", "not", "self", ".", "__stderr", ".", "empty", "(", ")", ":", "try", ":", "line", "=", "self", ".", "__stderr", ".", "get_nowait", "(", ")", "stderr", ".", "append", "(", "line", ")", "except", ":", "pass", "else", ":", "stderr", "=", "self", ".", "__stderr", "return", "stderr" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
Result.print_stdout
Prints the stdout to console - if there is any stdout, otherwise does nothing. :param always_print: print the stdout, even if there is nothing in the buffer (default: false)
src/sultan/result.py
def print_stdout(self, always_print=False): """ Prints the stdout to console - if there is any stdout, otherwise does nothing. :param always_print: print the stdout, even if there is nothing in the buffer (default: false) """ if self.__stdout or always_print: self.__echo.info("--{ STDOUT }---" + "-" * 100) self.__format_lines_info(self.stdout) self.__echo.info("---------------" + "-" * 100)
def print_stdout(self, always_print=False): """ Prints the stdout to console - if there is any stdout, otherwise does nothing. :param always_print: print the stdout, even if there is nothing in the buffer (default: false) """ if self.__stdout or always_print: self.__echo.info("--{ STDOUT }---" + "-" * 100) self.__format_lines_info(self.stdout) self.__echo.info("---------------" + "-" * 100)
[ "Prints", "the", "stdout", "to", "console", "-", "if", "there", "is", "any", "stdout", "otherwise", "does", "nothing", ".", ":", "param", "always_print", ":", "print", "the", "stdout", "even", "if", "there", "is", "nothing", "in", "the", "buffer", "(", "default", ":", "false", ")" ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L225-L233
[ "def", "print_stdout", "(", "self", ",", "always_print", "=", "False", ")", ":", "if", "self", ".", "__stdout", "or", "always_print", ":", "self", ".", "__echo", ".", "info", "(", "\"--{ STDOUT }---\"", "+", "\"-\"", "*", "100", ")", "self", ".", "__format_lines_info", "(", "self", ".", "stdout", ")", "self", ".", "__echo", ".", "info", "(", "\"---------------\"", "+", "\"-\"", "*", "100", ")" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
Result.print_stderr
Prints the stderr to console - if there is any stdout, otherwise does nothing. :param always_print: print the stderr, even if there is nothing in the buffer (default: false)
src/sultan/result.py
def print_stderr(self, always_print=False): """ Prints the stderr to console - if there is any stdout, otherwise does nothing. :param always_print: print the stderr, even if there is nothing in the buffer (default: false) """ if self.__stderr or always_print: self.__echo.critical("--{ STDERR }---" + "-" * 100) self.__format_lines_error(self.stderr) self.__echo.critical("---------------" + "-" * 100)
def print_stderr(self, always_print=False): """ Prints the stderr to console - if there is any stdout, otherwise does nothing. :param always_print: print the stderr, even if there is nothing in the buffer (default: false) """ if self.__stderr or always_print: self.__echo.critical("--{ STDERR }---" + "-" * 100) self.__format_lines_error(self.stderr) self.__echo.critical("---------------" + "-" * 100)
[ "Prints", "the", "stderr", "to", "console", "-", "if", "there", "is", "any", "stdout", "otherwise", "does", "nothing", ".", ":", "param", "always_print", ":", "print", "the", "stderr", "even", "if", "there", "is", "nothing", "in", "the", "buffer", "(", "default", ":", "false", ")" ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L235-L243
[ "def", "print_stderr", "(", "self", ",", "always_print", "=", "False", ")", ":", "if", "self", ".", "__stderr", "or", "always_print", ":", "self", ".", "__echo", ".", "critical", "(", "\"--{ STDERR }---\"", "+", "\"-\"", "*", "100", ")", "self", ".", "__format_lines_error", "(", "self", ".", "stderr", ")", "self", ".", "__echo", ".", "critical", "(", "\"---------------\"", "+", "\"-\"", "*", "100", ")" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
Result.print_traceback
Prints the traceback to console - if there is any traceback, otherwise does nothing. :param always_print: print the traceback, even if there is nothing in the buffer (default: false)
src/sultan/result.py
def print_traceback(self, always_print=False): """ Prints the traceback to console - if there is any traceback, otherwise does nothing. :param always_print: print the traceback, even if there is nothing in the buffer (default: false) """ if self._exception or always_print: self.__echo.critical("--{ TRACEBACK }" + "-" * 100) self.__format_lines_error(self.traceback) self.__echo.critical("---------------" + "-" * 100)
def print_traceback(self, always_print=False): """ Prints the traceback to console - if there is any traceback, otherwise does nothing. :param always_print: print the traceback, even if there is nothing in the buffer (default: false) """ if self._exception or always_print: self.__echo.critical("--{ TRACEBACK }" + "-" * 100) self.__format_lines_error(self.traceback) self.__echo.critical("---------------" + "-" * 100)
[ "Prints", "the", "traceback", "to", "console", "-", "if", "there", "is", "any", "traceback", "otherwise", "does", "nothing", ".", ":", "param", "always_print", ":", "print", "the", "traceback", "even", "if", "there", "is", "nothing", "in", "the", "buffer", "(", "default", ":", "false", ")" ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L245-L253
[ "def", "print_traceback", "(", "self", ",", "always_print", "=", "False", ")", ":", "if", "self", ".", "_exception", "or", "always_print", ":", "self", ".", "__echo", ".", "critical", "(", "\"--{ TRACEBACK }\"", "+", "\"-\"", "*", "100", ")", "self", ".", "__format_lines_error", "(", "self", ".", "traceback", ")", "self", ".", "__echo", ".", "critical", "(", "\"---------------\"", "+", "\"-\"", "*", "100", ")" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
LevelFormatter.format
Customize the message format based on the log level.
src/sultan/echo/colorlog/colorlog.py
def format(self, record): """Customize the message format based on the log level.""" if isinstance(self.fmt, dict): self._fmt = self.fmt[record.levelname] if sys.version_info > (3, 2): # Update self._style because we've changed self._fmt # (code based on stdlib's logging.Formatter.__init__()) if self.style not in logging._STYLES: raise ValueError('Style must be one of: %s' % ','.join( list(logging._STYLES.keys()))) self._style = logging._STYLES[self.style][0](self._fmt) if sys.version_info > (2, 7): message = super(LevelFormatter, self).format(record) else: message = ColoredFormatter.format(self, record) return message
def format(self, record): """Customize the message format based on the log level.""" if isinstance(self.fmt, dict): self._fmt = self.fmt[record.levelname] if sys.version_info > (3, 2): # Update self._style because we've changed self._fmt # (code based on stdlib's logging.Formatter.__init__()) if self.style not in logging._STYLES: raise ValueError('Style must be one of: %s' % ','.join( list(logging._STYLES.keys()))) self._style = logging._STYLES[self.style][0](self._fmt) if sys.version_info > (2, 7): message = super(LevelFormatter, self).format(record) else: message = ColoredFormatter.format(self, record) return message
[ "Customize", "the", "message", "format", "based", "on", "the", "log", "level", "." ]
aeroxis/sultan
python
https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/echo/colorlog/colorlog.py#L182-L199
[ "def", "format", "(", "self", ",", "record", ")", ":", "if", "isinstance", "(", "self", ".", "fmt", ",", "dict", ")", ":", "self", ".", "_fmt", "=", "self", ".", "fmt", "[", "record", ".", "levelname", "]", "if", "sys", ".", "version_info", ">", "(", "3", ",", "2", ")", ":", "# Update self._style because we've changed self._fmt", "# (code based on stdlib's logging.Formatter.__init__())", "if", "self", ".", "style", "not", "in", "logging", ".", "_STYLES", ":", "raise", "ValueError", "(", "'Style must be one of: %s'", "%", "','", ".", "join", "(", "list", "(", "logging", ".", "_STYLES", ".", "keys", "(", ")", ")", ")", ")", "self", ".", "_style", "=", "logging", ".", "_STYLES", "[", "self", ".", "style", "]", "[", "0", "]", "(", "self", ".", "_fmt", ")", "if", "sys", ".", "version_info", ">", "(", "2", ",", "7", ")", ":", "message", "=", "super", "(", "LevelFormatter", ",", "self", ")", ".", "format", "(", "record", ")", "else", ":", "message", "=", "ColoredFormatter", ".", "format", "(", "self", ",", "record", ")", "return", "message" ]
65b4271a161d6c19a9eb0170b5a95832a139ab7f
valid
replace_print
Sys.out replacer, by default with stderr. Use it like this: with replace_print_with(fileobj): print "hello" # writes to the file print "done" # prints to stdout Args: fileobj: a file object to replace stdout. Yields: The printer.
dsub/lib/dsub_util.py
def replace_print(fileobj=sys.stderr): """Sys.out replacer, by default with stderr. Use it like this: with replace_print_with(fileobj): print "hello" # writes to the file print "done" # prints to stdout Args: fileobj: a file object to replace stdout. Yields: The printer. """ printer = _Printer(fileobj) previous_stdout = sys.stdout sys.stdout = printer try: yield printer finally: sys.stdout = previous_stdout
def replace_print(fileobj=sys.stderr): """Sys.out replacer, by default with stderr. Use it like this: with replace_print_with(fileobj): print "hello" # writes to the file print "done" # prints to stdout Args: fileobj: a file object to replace stdout. Yields: The printer. """ printer = _Printer(fileobj) previous_stdout = sys.stdout sys.stdout = printer try: yield printer finally: sys.stdout = previous_stdout
[ "Sys", ".", "out", "replacer", "by", "default", "with", "stderr", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L55-L76
[ "def", "replace_print", "(", "fileobj", "=", "sys", ".", "stderr", ")", ":", "printer", "=", "_Printer", "(", "fileobj", ")", "previous_stdout", "=", "sys", ".", "stdout", "sys", ".", "stdout", "=", "printer", "try", ":", "yield", "printer", "finally", ":", "sys", ".", "stdout", "=", "previous_stdout" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
compact_interval_string
Compact a list of integers into a comma-separated string of intervals. Args: value_list: A list of sortable integers such as a list of numbers Returns: A compact string representation, such as "1-5,8,12-15"
dsub/lib/dsub_util.py
def compact_interval_string(value_list): """Compact a list of integers into a comma-separated string of intervals. Args: value_list: A list of sortable integers such as a list of numbers Returns: A compact string representation, such as "1-5,8,12-15" """ if not value_list: return '' value_list.sort() # Start by simply building up a list of separate contiguous intervals interval_list = [] curr = [] for val in value_list: if curr and (val > curr[-1] + 1): interval_list.append((curr[0], curr[-1])) curr = [val] else: curr.append(val) if curr: interval_list.append((curr[0], curr[-1])) # For each interval collapse it down to "first, last" or just "first" if # if first == last. return ','.join([ '{}-{}'.format(pair[0], pair[1]) if pair[0] != pair[1] else str(pair[0]) for pair in interval_list ])
def compact_interval_string(value_list): """Compact a list of integers into a comma-separated string of intervals. Args: value_list: A list of sortable integers such as a list of numbers Returns: A compact string representation, such as "1-5,8,12-15" """ if not value_list: return '' value_list.sort() # Start by simply building up a list of separate contiguous intervals interval_list = [] curr = [] for val in value_list: if curr and (val > curr[-1] + 1): interval_list.append((curr[0], curr[-1])) curr = [val] else: curr.append(val) if curr: interval_list.append((curr[0], curr[-1])) # For each interval collapse it down to "first, last" or just "first" if # if first == last. return ','.join([ '{}-{}'.format(pair[0], pair[1]) if pair[0] != pair[1] else str(pair[0]) for pair in interval_list ])
[ "Compact", "a", "list", "of", "integers", "into", "a", "comma", "-", "separated", "string", "of", "intervals", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L94-L127
[ "def", "compact_interval_string", "(", "value_list", ")", ":", "if", "not", "value_list", ":", "return", "''", "value_list", ".", "sort", "(", ")", "# Start by simply building up a list of separate contiguous intervals", "interval_list", "=", "[", "]", "curr", "=", "[", "]", "for", "val", "in", "value_list", ":", "if", "curr", "and", "(", "val", ">", "curr", "[", "-", "1", "]", "+", "1", ")", ":", "interval_list", ".", "append", "(", "(", "curr", "[", "0", "]", ",", "curr", "[", "-", "1", "]", ")", ")", "curr", "=", "[", "val", "]", "else", ":", "curr", ".", "append", "(", "val", ")", "if", "curr", ":", "interval_list", ".", "append", "(", "(", "curr", "[", "0", "]", ",", "curr", "[", "-", "1", "]", ")", ")", "# For each interval collapse it down to \"first, last\" or just \"first\" if", "# if first == last.", "return", "','", ".", "join", "(", "[", "'{}-{}'", ".", "format", "(", "pair", "[", "0", "]", ",", "pair", "[", "1", "]", ")", "if", "pair", "[", "0", "]", "!=", "pair", "[", "1", "]", "else", "str", "(", "pair", "[", "0", "]", ")", "for", "pair", "in", "interval_list", "]", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_get_storage_service
Get a storage client using the provided credentials or defaults.
dsub/lib/dsub_util.py
def _get_storage_service(credentials): """Get a storage client using the provided credentials or defaults.""" if credentials is None: credentials = oauth2client.client.GoogleCredentials.get_application_default( ) return discovery.build('storage', 'v1', credentials=credentials)
def _get_storage_service(credentials): """Get a storage client using the provided credentials or defaults.""" if credentials is None: credentials = oauth2client.client.GoogleCredentials.get_application_default( ) return discovery.build('storage', 'v1', credentials=credentials)
[ "Get", "a", "storage", "client", "using", "the", "provided", "credentials", "or", "defaults", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L130-L135
[ "def", "_get_storage_service", "(", "credentials", ")", ":", "if", "credentials", "is", "None", ":", "credentials", "=", "oauth2client", ".", "client", ".", "GoogleCredentials", ".", "get_application_default", "(", ")", "return", "discovery", ".", "build", "(", "'storage'", ",", "'v1'", ",", "credentials", "=", "credentials", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_retry_storage_check
Return True if we should retry, False otherwise.
dsub/lib/dsub_util.py
def _retry_storage_check(exception): """Return True if we should retry, False otherwise.""" now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') print_error( '%s: Exception %s: %s' % (now, type(exception).__name__, str(exception))) return isinstance(exception, oauth2client.client.AccessTokenRefreshError)
def _retry_storage_check(exception): """Return True if we should retry, False otherwise.""" now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') print_error( '%s: Exception %s: %s' % (now, type(exception).__name__, str(exception))) return isinstance(exception, oauth2client.client.AccessTokenRefreshError)
[ "Return", "True", "if", "we", "should", "retry", "False", "otherwise", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L138-L143
[ "def", "_retry_storage_check", "(", "exception", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S.%f'", ")", "print_error", "(", "'%s: Exception %s: %s'", "%", "(", "now", ",", "type", "(", "exception", ")", ".", "__name__", ",", "str", "(", "exception", ")", ")", ")", "return", "isinstance", "(", "exception", ",", "oauth2client", ".", "client", ".", "AccessTokenRefreshError", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_load_file_from_gcs
Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string.
dsub/lib/dsub_util.py
def _load_file_from_gcs(gcs_file_path, credentials=None): """Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string. """ gcs_service = _get_storage_service(credentials) bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1) request = gcs_service.objects().get_media( bucket=bucket_name, object=object_name) file_handle = io.BytesIO() downloader = MediaIoBaseDownload(file_handle, request, chunksize=1024 * 1024) done = False while not done: _, done = _downloader_next_chunk(downloader) filevalue = file_handle.getvalue() if not isinstance(filevalue, six.string_types): filevalue = filevalue.decode() return six.StringIO(filevalue)
def _load_file_from_gcs(gcs_file_path, credentials=None): """Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string. """ gcs_service = _get_storage_service(credentials) bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1) request = gcs_service.objects().get_media( bucket=bucket_name, object=object_name) file_handle = io.BytesIO() downloader = MediaIoBaseDownload(file_handle, request, chunksize=1024 * 1024) done = False while not done: _, done = _downloader_next_chunk(downloader) filevalue = file_handle.getvalue() if not isinstance(filevalue, six.string_types): filevalue = filevalue.decode() return six.StringIO(filevalue)
[ "Load", "context", "from", "a", "text", "file", "in", "gcs", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L158-L182
[ "def", "_load_file_from_gcs", "(", "gcs_file_path", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "object_name", "=", "gcs_file_path", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "get_media", "(", "bucket", "=", "bucket_name", ",", "object", "=", "object_name", ")", "file_handle", "=", "io", ".", "BytesIO", "(", ")", "downloader", "=", "MediaIoBaseDownload", "(", "file_handle", ",", "request", ",", "chunksize", "=", "1024", "*", "1024", ")", "done", "=", "False", "while", "not", "done", ":", "_", ",", "done", "=", "_downloader_next_chunk", "(", "downloader", ")", "filevalue", "=", "file_handle", ".", "getvalue", "(", ")", "if", "not", "isinstance", "(", "filevalue", ",", "six", ".", "string_types", ")", ":", "filevalue", "=", "filevalue", ".", "decode", "(", ")", "return", "six", ".", "StringIO", "(", "filevalue", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
load_file
Load a file from either local or gcs. Args: file_path: The target file path, which should have the prefix 'gs://' if to be loaded from gcs. credentials: Optional credential to be used to load the file from gcs. Returns: A python File object if loading file from local or a StringIO object if loading from gcs.
dsub/lib/dsub_util.py
def load_file(file_path, credentials=None): """Load a file from either local or gcs. Args: file_path: The target file path, which should have the prefix 'gs://' if to be loaded from gcs. credentials: Optional credential to be used to load the file from gcs. Returns: A python File object if loading file from local or a StringIO object if loading from gcs. """ if file_path.startswith('gs://'): return _load_file_from_gcs(file_path, credentials) else: return open(file_path, 'r')
def load_file(file_path, credentials=None): """Load a file from either local or gcs. Args: file_path: The target file path, which should have the prefix 'gs://' if to be loaded from gcs. credentials: Optional credential to be used to load the file from gcs. Returns: A python File object if loading file from local or a StringIO object if loading from gcs. """ if file_path.startswith('gs://'): return _load_file_from_gcs(file_path, credentials) else: return open(file_path, 'r')
[ "Load", "a", "file", "from", "either", "local", "or", "gcs", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L185-L200
[ "def", "load_file", "(", "file_path", ",", "credentials", "=", "None", ")", ":", "if", "file_path", ".", "startswith", "(", "'gs://'", ")", ":", "return", "_load_file_from_gcs", "(", "file_path", ",", "credentials", ")", "else", ":", "return", "open", "(", "file_path", ",", "'r'", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_file_exists_in_gcs
Check whether the file exists, in GCS. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there.
dsub/lib/dsub_util.py
def _file_exists_in_gcs(gcs_file_path, credentials=None): """Check whether the file exists, in GCS. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there. """ gcs_service = _get_storage_service(credentials) bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1) request = gcs_service.objects().get( bucket=bucket_name, object=object_name, projection='noAcl') try: request.execute() return True except errors.HttpError: return False
def _file_exists_in_gcs(gcs_file_path, credentials=None): """Check whether the file exists, in GCS. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there. """ gcs_service = _get_storage_service(credentials) bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1) request = gcs_service.objects().get( bucket=bucket_name, object=object_name, projection='noAcl') try: request.execute() return True except errors.HttpError: return False
[ "Check", "whether", "the", "file", "exists", "in", "GCS", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L211-L230
[ "def", "_file_exists_in_gcs", "(", "gcs_file_path", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "object_name", "=", "gcs_file_path", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "get", "(", "bucket", "=", "bucket_name", ",", "object", "=", "object_name", ",", "projection", "=", "'noAcl'", ")", "try", ":", "request", ".", "execute", "(", ")", "return", "True", "except", "errors", ".", "HttpError", ":", "return", "False" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
file_exists
Check whether the file exists, on local disk or GCS. Args: file_path: The target file path; should have the 'gs://' prefix if in gcs. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there.
dsub/lib/dsub_util.py
def file_exists(file_path, credentials=None): """Check whether the file exists, on local disk or GCS. Args: file_path: The target file path; should have the 'gs://' prefix if in gcs. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there. """ if file_path.startswith('gs://'): return _file_exists_in_gcs(file_path, credentials) else: return os.path.isfile(file_path)
def file_exists(file_path, credentials=None): """Check whether the file exists, on local disk or GCS. Args: file_path: The target file path; should have the 'gs://' prefix if in gcs. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there. """ if file_path.startswith('gs://'): return _file_exists_in_gcs(file_path, credentials) else: return os.path.isfile(file_path)
[ "Check", "whether", "the", "file", "exists", "on", "local", "disk", "or", "GCS", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L233-L246
[ "def", "file_exists", "(", "file_path", ",", "credentials", "=", "None", ")", ":", "if", "file_path", ".", "startswith", "(", "'gs://'", ")", ":", "return", "_file_exists_in_gcs", "(", "file_path", ",", "credentials", ")", "else", ":", "return", "os", ".", "path", ".", "isfile", "(", "file_path", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_prefix_exists_in_gcs
Check whether there is a GCS object whose name starts with the prefix. Since GCS doesn't actually have folders, this is how we check instead. Args: gcs_prefix: The path; should start with 'gs://'. credentials: Optional credential to be used to load the file from gcs. Returns: True if the prefix matches at least one object in GCS. Raises: errors.HttpError: if it can't talk to the server
dsub/lib/dsub_util.py
def _prefix_exists_in_gcs(gcs_prefix, credentials=None): """Check whether there is a GCS object whose name starts with the prefix. Since GCS doesn't actually have folders, this is how we check instead. Args: gcs_prefix: The path; should start with 'gs://'. credentials: Optional credential to be used to load the file from gcs. Returns: True if the prefix matches at least one object in GCS. Raises: errors.HttpError: if it can't talk to the server """ gcs_service = _get_storage_service(credentials) bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1) # documentation in # https://cloud.google.com/storage/docs/json_api/v1/objects/list request = gcs_service.objects().list( bucket=bucket_name, prefix=prefix, maxResults=1) response = request.execute() return response.get('items', None)
def _prefix_exists_in_gcs(gcs_prefix, credentials=None): """Check whether there is a GCS object whose name starts with the prefix. Since GCS doesn't actually have folders, this is how we check instead. Args: gcs_prefix: The path; should start with 'gs://'. credentials: Optional credential to be used to load the file from gcs. Returns: True if the prefix matches at least one object in GCS. Raises: errors.HttpError: if it can't talk to the server """ gcs_service = _get_storage_service(credentials) bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1) # documentation in # https://cloud.google.com/storage/docs/json_api/v1/objects/list request = gcs_service.objects().list( bucket=bucket_name, prefix=prefix, maxResults=1) response = request.execute() return response.get('items', None)
[ "Check", "whether", "there", "is", "a", "GCS", "object", "whose", "name", "starts", "with", "the", "prefix", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L257-L280
[ "def", "_prefix_exists_in_gcs", "(", "gcs_prefix", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "prefix", "=", "gcs_prefix", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "# documentation in", "# https://cloud.google.com/storage/docs/json_api/v1/objects/list", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "list", "(", "bucket", "=", "bucket_name", ",", "prefix", "=", "prefix", ",", "maxResults", "=", "1", ")", "response", "=", "request", ".", "execute", "(", ")", "return", "response", ".", "get", "(", "'items'", ",", "None", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
simple_pattern_exists_in_gcs
True iff an object exists matching the input GCS pattern. The GCS pattern must be a full object reference or a "simple pattern" that conforms to the dsub input and output parameter restrictions: * No support for **, ? wildcards or [] character ranges * Wildcards may only appear in the file name Args: file_pattern: eg. 'gs://foo/ba*' credentials: Optional credential to be used to load the file from gcs. Raises: ValueError: if file_pattern breaks the rules. Returns: True iff a file exists that matches that pattern.
dsub/lib/dsub_util.py
def simple_pattern_exists_in_gcs(file_pattern, credentials=None): """True iff an object exists matching the input GCS pattern. The GCS pattern must be a full object reference or a "simple pattern" that conforms to the dsub input and output parameter restrictions: * No support for **, ? wildcards or [] character ranges * Wildcards may only appear in the file name Args: file_pattern: eg. 'gs://foo/ba*' credentials: Optional credential to be used to load the file from gcs. Raises: ValueError: if file_pattern breaks the rules. Returns: True iff a file exists that matches that pattern. """ if '*' not in file_pattern: return _file_exists_in_gcs(file_pattern, credentials) if not file_pattern.startswith('gs://'): raise ValueError('file name must start with gs://') gcs_service = _get_storage_service(credentials) bucket_name, prefix = file_pattern[len('gs://'):].split('/', 1) if '*' in bucket_name: raise ValueError('Wildcards may not appear in the bucket name') # There is a '*' in prefix because we checked there's one in file_pattern # and there isn't one in bucket_name. Hence it must be in prefix. assert '*' in prefix prefix_no_wildcard = prefix[:prefix.index('*')] request = gcs_service.objects().list( bucket=bucket_name, prefix=prefix_no_wildcard) response = request.execute() if 'items' not in response: return False items_list = [i['name'] for i in response['items']] return any(fnmatch.fnmatch(i, prefix) for i in items_list)
def simple_pattern_exists_in_gcs(file_pattern, credentials=None): """True iff an object exists matching the input GCS pattern. The GCS pattern must be a full object reference or a "simple pattern" that conforms to the dsub input and output parameter restrictions: * No support for **, ? wildcards or [] character ranges * Wildcards may only appear in the file name Args: file_pattern: eg. 'gs://foo/ba*' credentials: Optional credential to be used to load the file from gcs. Raises: ValueError: if file_pattern breaks the rules. Returns: True iff a file exists that matches that pattern. """ if '*' not in file_pattern: return _file_exists_in_gcs(file_pattern, credentials) if not file_pattern.startswith('gs://'): raise ValueError('file name must start with gs://') gcs_service = _get_storage_service(credentials) bucket_name, prefix = file_pattern[len('gs://'):].split('/', 1) if '*' in bucket_name: raise ValueError('Wildcards may not appear in the bucket name') # There is a '*' in prefix because we checked there's one in file_pattern # and there isn't one in bucket_name. Hence it must be in prefix. assert '*' in prefix prefix_no_wildcard = prefix[:prefix.index('*')] request = gcs_service.objects().list( bucket=bucket_name, prefix=prefix_no_wildcard) response = request.execute() if 'items' not in response: return False items_list = [i['name'] for i in response['items']] return any(fnmatch.fnmatch(i, prefix) for i in items_list)
[ "True", "iff", "an", "object", "exists", "matching", "the", "input", "GCS", "pattern", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L298-L335
[ "def", "simple_pattern_exists_in_gcs", "(", "file_pattern", ",", "credentials", "=", "None", ")", ":", "if", "'*'", "not", "in", "file_pattern", ":", "return", "_file_exists_in_gcs", "(", "file_pattern", ",", "credentials", ")", "if", "not", "file_pattern", ".", "startswith", "(", "'gs://'", ")", ":", "raise", "ValueError", "(", "'file name must start with gs://'", ")", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "prefix", "=", "file_pattern", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "if", "'*'", "in", "bucket_name", ":", "raise", "ValueError", "(", "'Wildcards may not appear in the bucket name'", ")", "# There is a '*' in prefix because we checked there's one in file_pattern", "# and there isn't one in bucket_name. Hence it must be in prefix.", "assert", "'*'", "in", "prefix", "prefix_no_wildcard", "=", "prefix", "[", ":", "prefix", ".", "index", "(", "'*'", ")", "]", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "list", "(", "bucket", "=", "bucket_name", ",", "prefix", "=", "prefix_no_wildcard", ")", "response", "=", "request", ".", "execute", "(", ")", "if", "'items'", "not", "in", "response", ":", "return", "False", "items_list", "=", "[", "i", "[", "'name'", "]", "for", "i", "in", "response", "[", "'items'", "]", "]", "return", "any", "(", "fnmatch", ".", "fnmatch", "(", "i", ",", "prefix", ")", "for", "i", "in", "items_list", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
outputs_are_present
True if each output contains at least one file or no output specified.
dsub/lib/dsub_util.py
def outputs_are_present(outputs): """True if each output contains at least one file or no output specified.""" # outputs are OutputFileParam (see param_util.py) # If outputs contain a pattern, then there is no way for `dsub` to verify # that *all* output is present. The best that `dsub` can do is to verify # that *some* output was created for each such parameter. for o in outputs: if not o.value: continue if o.recursive: if not folder_exists(o.value): return False else: if not simple_pattern_exists_in_gcs(o.value): return False return True
def outputs_are_present(outputs): """True if each output contains at least one file or no output specified.""" # outputs are OutputFileParam (see param_util.py) # If outputs contain a pattern, then there is no way for `dsub` to verify # that *all* output is present. The best that `dsub` can do is to verify # that *some* output was created for each such parameter. for o in outputs: if not o.value: continue if o.recursive: if not folder_exists(o.value): return False else: if not simple_pattern_exists_in_gcs(o.value): return False return True
[ "True", "if", "each", "output", "contains", "at", "least", "one", "file", "or", "no", "output", "specified", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L338-L354
[ "def", "outputs_are_present", "(", "outputs", ")", ":", "# outputs are OutputFileParam (see param_util.py)", "# If outputs contain a pattern, then there is no way for `dsub` to verify", "# that *all* output is present. The best that `dsub` can do is to verify", "# that *some* output was created for each such parameter.", "for", "o", "in", "outputs", ":", "if", "not", "o", ".", "value", ":", "continue", "if", "o", ".", "recursive", ":", "if", "not", "folder_exists", "(", "o", ".", "value", ")", ":", "return", "False", "else", ":", "if", "not", "simple_pattern_exists_in_gcs", "(", "o", ".", "value", ")", ":", "return", "False", "return", "True" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Pipelines._build_pipeline_input_file_param
Return a dict object representing a pipeline input argument.
dsub/providers/google.py
def _build_pipeline_input_file_param(cls, var_name, docker_path): """Return a dict object representing a pipeline input argument.""" # If the filename contains a wildcard, then the target Docker path must # be a directory in order to ensure consistency whether the source pattern # contains 1 or multiple files. # # In that case, we set the docker_path to explicitly have a trailing slash # (for the Pipelines API "gsutil cp" handling, and then override the # associated var_name environment variable in the generated Docker command. path, filename = os.path.split(docker_path) if '*' in filename: return cls._build_pipeline_file_param(var_name, path + '/') else: return cls._build_pipeline_file_param(var_name, docker_path)
def _build_pipeline_input_file_param(cls, var_name, docker_path): """Return a dict object representing a pipeline input argument.""" # If the filename contains a wildcard, then the target Docker path must # be a directory in order to ensure consistency whether the source pattern # contains 1 or multiple files. # # In that case, we set the docker_path to explicitly have a trailing slash # (for the Pipelines API "gsutil cp" handling, and then override the # associated var_name environment variable in the generated Docker command. path, filename = os.path.split(docker_path) if '*' in filename: return cls._build_pipeline_file_param(var_name, path + '/') else: return cls._build_pipeline_file_param(var_name, docker_path)
[ "Return", "a", "dict", "object", "representing", "a", "pipeline", "input", "argument", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L132-L147
[ "def", "_build_pipeline_input_file_param", "(", "cls", ",", "var_name", ",", "docker_path", ")", ":", "# If the filename contains a wildcard, then the target Docker path must", "# be a directory in order to ensure consistency whether the source pattern", "# contains 1 or multiple files.", "#", "# In that case, we set the docker_path to explicitly have a trailing slash", "# (for the Pipelines API \"gsutil cp\" handling, and then override the", "# associated var_name environment variable in the generated Docker command.", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "docker_path", ")", "if", "'*'", "in", "filename", ":", "return", "cls", ".", "_build_pipeline_file_param", "(", "var_name", ",", "path", "+", "'/'", ")", "else", ":", "return", "cls", ".", "_build_pipeline_file_param", "(", "var_name", ",", "docker_path", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Pipelines._build_pipeline_docker_command
Return a multi-line string of the full pipeline docker command.
dsub/providers/google.py
def _build_pipeline_docker_command(cls, script_name, inputs, outputs, envs): """Return a multi-line string of the full pipeline docker command.""" # We upload the user script as an environment argument # and write it to SCRIPT_DIR (preserving its local file name). # # The docker_command: # * writes the script body to a file # * installs gcloud if there are recursive copies to do # * sets environment variables for inputs with wildcards # * sets environment variables for recursive input directories # * recursively copies input directories # * creates output directories # * sets environment variables for recursive output directories # * sets the DATA_ROOT environment variable to /mnt/data # * sets the working directory to ${DATA_ROOT} # * executes the user script # * recursively copies output directories recursive_input_dirs = [ var for var in inputs if var.recursive and var.value ] recursive_output_dirs = [ var for var in outputs if var.recursive and var.value ] install_cloud_sdk = '' if recursive_input_dirs or recursive_output_dirs: install_cloud_sdk = INSTALL_CLOUD_SDK export_input_dirs = '' copy_input_dirs = '' if recursive_input_dirs: export_input_dirs = providers_util.build_recursive_localize_env( providers_util.DATA_MOUNT_POINT, inputs) copy_input_dirs = providers_util.build_recursive_localize_command( providers_util.DATA_MOUNT_POINT, inputs, job_model.P_GCS) export_output_dirs = '' copy_output_dirs = '' if recursive_output_dirs: export_output_dirs = providers_util.build_recursive_gcs_delocalize_env( providers_util.DATA_MOUNT_POINT, outputs) copy_output_dirs = providers_util.build_recursive_delocalize_command( providers_util.DATA_MOUNT_POINT, outputs, job_model.P_GCS) docker_paths = [ var.docker_path if var.recursive else os.path.dirname(var.docker_path) for var in outputs if var.value ] mkdirs = '\n'.join([ 'mkdir -p {0}/{1}'.format(providers_util.DATA_MOUNT_POINT, path) for path in docker_paths ]) inputs_with_wildcards = [ var for var in inputs if not var.recursive and var.docker_path and '*' in os.path.basename(var.docker_path) ] export_inputs_with_wildcards = '\n'.join([ 'export {0}="{1}/{2}"'.format(var.name, providers_util.DATA_MOUNT_POINT, var.docker_path) for var in inputs_with_wildcards ]) export_empty_envs = '\n'.join([ 'export {0}=""'.format(var.name) for var in envs | inputs | outputs if not var.value ]) return DOCKER_COMMAND.format( mk_runtime_dirs=MK_RUNTIME_DIRS_COMMAND, script_path='%s/%s' % (providers_util.SCRIPT_DIR, script_name), install_cloud_sdk=install_cloud_sdk, export_inputs_with_wildcards=export_inputs_with_wildcards, export_input_dirs=export_input_dirs, copy_input_dirs=copy_input_dirs, mk_output_dirs=mkdirs, export_output_dirs=export_output_dirs, export_empty_envs=export_empty_envs, tmpdir=providers_util.TMP_DIR, working_dir=providers_util.WORKING_DIR, copy_output_dirs=copy_output_dirs)
def _build_pipeline_docker_command(cls, script_name, inputs, outputs, envs): """Return a multi-line string of the full pipeline docker command.""" # We upload the user script as an environment argument # and write it to SCRIPT_DIR (preserving its local file name). # # The docker_command: # * writes the script body to a file # * installs gcloud if there are recursive copies to do # * sets environment variables for inputs with wildcards # * sets environment variables for recursive input directories # * recursively copies input directories # * creates output directories # * sets environment variables for recursive output directories # * sets the DATA_ROOT environment variable to /mnt/data # * sets the working directory to ${DATA_ROOT} # * executes the user script # * recursively copies output directories recursive_input_dirs = [ var for var in inputs if var.recursive and var.value ] recursive_output_dirs = [ var for var in outputs if var.recursive and var.value ] install_cloud_sdk = '' if recursive_input_dirs or recursive_output_dirs: install_cloud_sdk = INSTALL_CLOUD_SDK export_input_dirs = '' copy_input_dirs = '' if recursive_input_dirs: export_input_dirs = providers_util.build_recursive_localize_env( providers_util.DATA_MOUNT_POINT, inputs) copy_input_dirs = providers_util.build_recursive_localize_command( providers_util.DATA_MOUNT_POINT, inputs, job_model.P_GCS) export_output_dirs = '' copy_output_dirs = '' if recursive_output_dirs: export_output_dirs = providers_util.build_recursive_gcs_delocalize_env( providers_util.DATA_MOUNT_POINT, outputs) copy_output_dirs = providers_util.build_recursive_delocalize_command( providers_util.DATA_MOUNT_POINT, outputs, job_model.P_GCS) docker_paths = [ var.docker_path if var.recursive else os.path.dirname(var.docker_path) for var in outputs if var.value ] mkdirs = '\n'.join([ 'mkdir -p {0}/{1}'.format(providers_util.DATA_MOUNT_POINT, path) for path in docker_paths ]) inputs_with_wildcards = [ var for var in inputs if not var.recursive and var.docker_path and '*' in os.path.basename(var.docker_path) ] export_inputs_with_wildcards = '\n'.join([ 'export {0}="{1}/{2}"'.format(var.name, providers_util.DATA_MOUNT_POINT, var.docker_path) for var in inputs_with_wildcards ]) export_empty_envs = '\n'.join([ 'export {0}=""'.format(var.name) for var in envs | inputs | outputs if not var.value ]) return DOCKER_COMMAND.format( mk_runtime_dirs=MK_RUNTIME_DIRS_COMMAND, script_path='%s/%s' % (providers_util.SCRIPT_DIR, script_name), install_cloud_sdk=install_cloud_sdk, export_inputs_with_wildcards=export_inputs_with_wildcards, export_input_dirs=export_input_dirs, copy_input_dirs=copy_input_dirs, mk_output_dirs=mkdirs, export_output_dirs=export_output_dirs, export_empty_envs=export_empty_envs, tmpdir=providers_util.TMP_DIR, working_dir=providers_util.WORKING_DIR, copy_output_dirs=copy_output_dirs)
[ "Return", "a", "multi", "-", "line", "string", "of", "the", "full", "pipeline", "docker", "command", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L161-L245
[ "def", "_build_pipeline_docker_command", "(", "cls", ",", "script_name", ",", "inputs", ",", "outputs", ",", "envs", ")", ":", "# We upload the user script as an environment argument", "# and write it to SCRIPT_DIR (preserving its local file name).", "#", "# The docker_command:", "# * writes the script body to a file", "# * installs gcloud if there are recursive copies to do", "# * sets environment variables for inputs with wildcards", "# * sets environment variables for recursive input directories", "# * recursively copies input directories", "# * creates output directories", "# * sets environment variables for recursive output directories", "# * sets the DATA_ROOT environment variable to /mnt/data", "# * sets the working directory to ${DATA_ROOT}", "# * executes the user script", "# * recursively copies output directories", "recursive_input_dirs", "=", "[", "var", "for", "var", "in", "inputs", "if", "var", ".", "recursive", "and", "var", ".", "value", "]", "recursive_output_dirs", "=", "[", "var", "for", "var", "in", "outputs", "if", "var", ".", "recursive", "and", "var", ".", "value", "]", "install_cloud_sdk", "=", "''", "if", "recursive_input_dirs", "or", "recursive_output_dirs", ":", "install_cloud_sdk", "=", "INSTALL_CLOUD_SDK", "export_input_dirs", "=", "''", "copy_input_dirs", "=", "''", "if", "recursive_input_dirs", ":", "export_input_dirs", "=", "providers_util", ".", "build_recursive_localize_env", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "inputs", ")", "copy_input_dirs", "=", "providers_util", ".", "build_recursive_localize_command", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "inputs", ",", "job_model", ".", "P_GCS", ")", "export_output_dirs", "=", "''", "copy_output_dirs", "=", "''", "if", "recursive_output_dirs", ":", "export_output_dirs", "=", "providers_util", ".", "build_recursive_gcs_delocalize_env", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "outputs", ")", "copy_output_dirs", "=", "providers_util", ".", "build_recursive_delocalize_command", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "outputs", ",", "job_model", ".", "P_GCS", ")", "docker_paths", "=", "[", "var", ".", "docker_path", "if", "var", ".", "recursive", "else", "os", ".", "path", ".", "dirname", "(", "var", ".", "docker_path", ")", "for", "var", "in", "outputs", "if", "var", ".", "value", "]", "mkdirs", "=", "'\\n'", ".", "join", "(", "[", "'mkdir -p {0}/{1}'", ".", "format", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "path", ")", "for", "path", "in", "docker_paths", "]", ")", "inputs_with_wildcards", "=", "[", "var", "for", "var", "in", "inputs", "if", "not", "var", ".", "recursive", "and", "var", ".", "docker_path", "and", "'*'", "in", "os", ".", "path", ".", "basename", "(", "var", ".", "docker_path", ")", "]", "export_inputs_with_wildcards", "=", "'\\n'", ".", "join", "(", "[", "'export {0}=\"{1}/{2}\"'", ".", "format", "(", "var", ".", "name", ",", "providers_util", ".", "DATA_MOUNT_POINT", ",", "var", ".", "docker_path", ")", "for", "var", "in", "inputs_with_wildcards", "]", ")", "export_empty_envs", "=", "'\\n'", ".", "join", "(", "[", "'export {0}=\"\"'", ".", "format", "(", "var", ".", "name", ")", "for", "var", "in", "envs", "|", "inputs", "|", "outputs", "if", "not", "var", ".", "value", "]", ")", "return", "DOCKER_COMMAND", ".", "format", "(", "mk_runtime_dirs", "=", "MK_RUNTIME_DIRS_COMMAND", ",", "script_path", "=", "'%s/%s'", "%", "(", "providers_util", ".", "SCRIPT_DIR", ",", "script_name", ")", ",", "install_cloud_sdk", "=", "install_cloud_sdk", ",", "export_inputs_with_wildcards", "=", "export_inputs_with_wildcards", ",", "export_input_dirs", "=", "export_input_dirs", ",", "copy_input_dirs", "=", "copy_input_dirs", ",", "mk_output_dirs", "=", "mkdirs", ",", "export_output_dirs", "=", "export_output_dirs", ",", "export_empty_envs", "=", "export_empty_envs", ",", "tmpdir", "=", "providers_util", ".", "TMP_DIR", ",", "working_dir", "=", "providers_util", ".", "WORKING_DIR", ",", "copy_output_dirs", "=", "copy_output_dirs", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Pipelines.build_pipeline
Builds a pipeline configuration for execution. Args: project: string name of project. zones: list of zone names for jobs to be run at. min_cores: int number of CPU cores required per job. min_ram: int GB of RAM required per job. disk_size: int GB of disk to attach under /mnt/data. boot_disk_size: int GB of disk for boot. preemptible: use a preemptible VM for the job accelerator_type: string GCE defined accelerator type. accelerator_count: int number of accelerators of the specified type to attach. image: string Docker image name in which to run. script_name: file name of the script to run. envs: list of EnvParam objects specifying environment variables to set within each job. inputs: list of FileParam objects specifying input variables to set within each job. outputs: list of FileParam objects specifying output variables to set within each job. pipeline_name: string name of pipeline. Returns: A nested dictionary with one entry under the key ephemeralPipeline containing the pipeline configuration.
dsub/providers/google.py
def build_pipeline(cls, project, zones, min_cores, min_ram, disk_size, boot_disk_size, preemptible, accelerator_type, accelerator_count, image, script_name, envs, inputs, outputs, pipeline_name): """Builds a pipeline configuration for execution. Args: project: string name of project. zones: list of zone names for jobs to be run at. min_cores: int number of CPU cores required per job. min_ram: int GB of RAM required per job. disk_size: int GB of disk to attach under /mnt/data. boot_disk_size: int GB of disk for boot. preemptible: use a preemptible VM for the job accelerator_type: string GCE defined accelerator type. accelerator_count: int number of accelerators of the specified type to attach. image: string Docker image name in which to run. script_name: file name of the script to run. envs: list of EnvParam objects specifying environment variables to set within each job. inputs: list of FileParam objects specifying input variables to set within each job. outputs: list of FileParam objects specifying output variables to set within each job. pipeline_name: string name of pipeline. Returns: A nested dictionary with one entry under the key ephemeralPipeline containing the pipeline configuration. """ if min_cores is None: min_cores = job_model.DEFAULT_MIN_CORES if min_ram is None: min_ram = job_model.DEFAULT_MIN_RAM if disk_size is None: disk_size = job_model.DEFAULT_DISK_SIZE if boot_disk_size is None: boot_disk_size = job_model.DEFAULT_BOOT_DISK_SIZE if preemptible is None: preemptible = job_model.DEFAULT_PREEMPTIBLE # Format the docker command docker_command = cls._build_pipeline_docker_command(script_name, inputs, outputs, envs) # Pipelines inputParameters can be both simple name/value pairs which get # set as environment variables, as well as input file paths which the # Pipelines controller will automatically localize to the Pipeline VM. # In the ephemeralPipeline object, the inputParameters are only defined; # the values are passed in the pipelineArgs. # Pipelines outputParameters are only output file paths, which the # Pipelines controller can automatically de-localize after the docker # command completes. # The Pipelines API does not support recursive copy of file parameters, # so it is implemented within the dsub-generated pipeline. # Any inputs or outputs marked as "recursive" are completely omitted here; # their environment variables will be set in the docker command, and # recursive copy code will be generated there as well. # The Pipelines API does not accept empty environment variables. Set them to # empty in DOCKER_COMMAND instead. input_envs = [{ 'name': SCRIPT_VARNAME }] + [{ 'name': env.name } for env in envs if env.value] input_files = [ cls._build_pipeline_input_file_param(var.name, var.docker_path) for var in inputs if not var.recursive and var.value ] # Outputs are an array of file parameters output_files = [ cls._build_pipeline_file_param(var.name, var.docker_path) for var in outputs if not var.recursive and var.value ] # The ephemeralPipeline provides the template for the pipeline. # pyformat: disable return { 'ephemeralPipeline': { 'projectId': project, 'name': pipeline_name, # Define the resources needed for this pipeline. 'resources': { 'minimumCpuCores': min_cores, 'minimumRamGb': min_ram, 'bootDiskSizeGb': boot_disk_size, 'preemptible': preemptible, 'zones': google_base.get_zones(zones), 'acceleratorType': accelerator_type, 'acceleratorCount': accelerator_count, # Create a data disk that is attached to the VM and destroyed # when the pipeline terminates. 'disks': [{ 'name': 'datadisk', 'autoDelete': True, 'sizeGb': disk_size, 'mountPoint': providers_util.DATA_MOUNT_POINT, }], }, 'inputParameters': input_envs + input_files, 'outputParameters': output_files, 'docker': { 'imageName': image, 'cmd': docker_command, } } }
def build_pipeline(cls, project, zones, min_cores, min_ram, disk_size, boot_disk_size, preemptible, accelerator_type, accelerator_count, image, script_name, envs, inputs, outputs, pipeline_name): """Builds a pipeline configuration for execution. Args: project: string name of project. zones: list of zone names for jobs to be run at. min_cores: int number of CPU cores required per job. min_ram: int GB of RAM required per job. disk_size: int GB of disk to attach under /mnt/data. boot_disk_size: int GB of disk for boot. preemptible: use a preemptible VM for the job accelerator_type: string GCE defined accelerator type. accelerator_count: int number of accelerators of the specified type to attach. image: string Docker image name in which to run. script_name: file name of the script to run. envs: list of EnvParam objects specifying environment variables to set within each job. inputs: list of FileParam objects specifying input variables to set within each job. outputs: list of FileParam objects specifying output variables to set within each job. pipeline_name: string name of pipeline. Returns: A nested dictionary with one entry under the key ephemeralPipeline containing the pipeline configuration. """ if min_cores is None: min_cores = job_model.DEFAULT_MIN_CORES if min_ram is None: min_ram = job_model.DEFAULT_MIN_RAM if disk_size is None: disk_size = job_model.DEFAULT_DISK_SIZE if boot_disk_size is None: boot_disk_size = job_model.DEFAULT_BOOT_DISK_SIZE if preemptible is None: preemptible = job_model.DEFAULT_PREEMPTIBLE # Format the docker command docker_command = cls._build_pipeline_docker_command(script_name, inputs, outputs, envs) # Pipelines inputParameters can be both simple name/value pairs which get # set as environment variables, as well as input file paths which the # Pipelines controller will automatically localize to the Pipeline VM. # In the ephemeralPipeline object, the inputParameters are only defined; # the values are passed in the pipelineArgs. # Pipelines outputParameters are only output file paths, which the # Pipelines controller can automatically de-localize after the docker # command completes. # The Pipelines API does not support recursive copy of file parameters, # so it is implemented within the dsub-generated pipeline. # Any inputs or outputs marked as "recursive" are completely omitted here; # their environment variables will be set in the docker command, and # recursive copy code will be generated there as well. # The Pipelines API does not accept empty environment variables. Set them to # empty in DOCKER_COMMAND instead. input_envs = [{ 'name': SCRIPT_VARNAME }] + [{ 'name': env.name } for env in envs if env.value] input_files = [ cls._build_pipeline_input_file_param(var.name, var.docker_path) for var in inputs if not var.recursive and var.value ] # Outputs are an array of file parameters output_files = [ cls._build_pipeline_file_param(var.name, var.docker_path) for var in outputs if not var.recursive and var.value ] # The ephemeralPipeline provides the template for the pipeline. # pyformat: disable return { 'ephemeralPipeline': { 'projectId': project, 'name': pipeline_name, # Define the resources needed for this pipeline. 'resources': { 'minimumCpuCores': min_cores, 'minimumRamGb': min_ram, 'bootDiskSizeGb': boot_disk_size, 'preemptible': preemptible, 'zones': google_base.get_zones(zones), 'acceleratorType': accelerator_type, 'acceleratorCount': accelerator_count, # Create a data disk that is attached to the VM and destroyed # when the pipeline terminates. 'disks': [{ 'name': 'datadisk', 'autoDelete': True, 'sizeGb': disk_size, 'mountPoint': providers_util.DATA_MOUNT_POINT, }], }, 'inputParameters': input_envs + input_files, 'outputParameters': output_files, 'docker': { 'imageName': image, 'cmd': docker_command, } } }
[ "Builds", "a", "pipeline", "configuration", "for", "execution", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L248-L367
[ "def", "build_pipeline", "(", "cls", ",", "project", ",", "zones", ",", "min_cores", ",", "min_ram", ",", "disk_size", ",", "boot_disk_size", ",", "preemptible", ",", "accelerator_type", ",", "accelerator_count", ",", "image", ",", "script_name", ",", "envs", ",", "inputs", ",", "outputs", ",", "pipeline_name", ")", ":", "if", "min_cores", "is", "None", ":", "min_cores", "=", "job_model", ".", "DEFAULT_MIN_CORES", "if", "min_ram", "is", "None", ":", "min_ram", "=", "job_model", ".", "DEFAULT_MIN_RAM", "if", "disk_size", "is", "None", ":", "disk_size", "=", "job_model", ".", "DEFAULT_DISK_SIZE", "if", "boot_disk_size", "is", "None", ":", "boot_disk_size", "=", "job_model", ".", "DEFAULT_BOOT_DISK_SIZE", "if", "preemptible", "is", "None", ":", "preemptible", "=", "job_model", ".", "DEFAULT_PREEMPTIBLE", "# Format the docker command", "docker_command", "=", "cls", ".", "_build_pipeline_docker_command", "(", "script_name", ",", "inputs", ",", "outputs", ",", "envs", ")", "# Pipelines inputParameters can be both simple name/value pairs which get", "# set as environment variables, as well as input file paths which the", "# Pipelines controller will automatically localize to the Pipeline VM.", "# In the ephemeralPipeline object, the inputParameters are only defined;", "# the values are passed in the pipelineArgs.", "# Pipelines outputParameters are only output file paths, which the", "# Pipelines controller can automatically de-localize after the docker", "# command completes.", "# The Pipelines API does not support recursive copy of file parameters,", "# so it is implemented within the dsub-generated pipeline.", "# Any inputs or outputs marked as \"recursive\" are completely omitted here;", "# their environment variables will be set in the docker command, and", "# recursive copy code will be generated there as well.", "# The Pipelines API does not accept empty environment variables. Set them to", "# empty in DOCKER_COMMAND instead.", "input_envs", "=", "[", "{", "'name'", ":", "SCRIPT_VARNAME", "}", "]", "+", "[", "{", "'name'", ":", "env", ".", "name", "}", "for", "env", "in", "envs", "if", "env", ".", "value", "]", "input_files", "=", "[", "cls", ".", "_build_pipeline_input_file_param", "(", "var", ".", "name", ",", "var", ".", "docker_path", ")", "for", "var", "in", "inputs", "if", "not", "var", ".", "recursive", "and", "var", ".", "value", "]", "# Outputs are an array of file parameters", "output_files", "=", "[", "cls", ".", "_build_pipeline_file_param", "(", "var", ".", "name", ",", "var", ".", "docker_path", ")", "for", "var", "in", "outputs", "if", "not", "var", ".", "recursive", "and", "var", ".", "value", "]", "# The ephemeralPipeline provides the template for the pipeline.", "# pyformat: disable", "return", "{", "'ephemeralPipeline'", ":", "{", "'projectId'", ":", "project", ",", "'name'", ":", "pipeline_name", ",", "# Define the resources needed for this pipeline.", "'resources'", ":", "{", "'minimumCpuCores'", ":", "min_cores", ",", "'minimumRamGb'", ":", "min_ram", ",", "'bootDiskSizeGb'", ":", "boot_disk_size", ",", "'preemptible'", ":", "preemptible", ",", "'zones'", ":", "google_base", ".", "get_zones", "(", "zones", ")", ",", "'acceleratorType'", ":", "accelerator_type", ",", "'acceleratorCount'", ":", "accelerator_count", ",", "# Create a data disk that is attached to the VM and destroyed", "# when the pipeline terminates.", "'disks'", ":", "[", "{", "'name'", ":", "'datadisk'", ",", "'autoDelete'", ":", "True", ",", "'sizeGb'", ":", "disk_size", ",", "'mountPoint'", ":", "providers_util", ".", "DATA_MOUNT_POINT", ",", "}", "]", ",", "}", ",", "'inputParameters'", ":", "input_envs", "+", "input_files", ",", "'outputParameters'", ":", "output_files", ",", "'docker'", ":", "{", "'imageName'", ":", "image", ",", "'cmd'", ":", "docker_command", ",", "}", "}", "}" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Pipelines.build_pipeline_args
Builds pipeline args for execution. Args: project: string name of project. script: Body of the script to execute. job_params: dictionary of values for labels, envs, inputs, and outputs for this job. task_params: dictionary of values for labels, envs, inputs, and outputs for this task. reserved_labels: dictionary of reserved labels (e.g. task-id, task-attempt) preemptible: use a preemptible VM for the job logging_uri: path for job logging output. scopes: list of scope. keep_alive: Seconds to keep VM alive on failure Returns: A nested dictionary with one entry under the key pipelineArgs containing the pipeline arguments.
dsub/providers/google.py
def build_pipeline_args(cls, project, script, job_params, task_params, reserved_labels, preemptible, logging_uri, scopes, keep_alive): """Builds pipeline args for execution. Args: project: string name of project. script: Body of the script to execute. job_params: dictionary of values for labels, envs, inputs, and outputs for this job. task_params: dictionary of values for labels, envs, inputs, and outputs for this task. reserved_labels: dictionary of reserved labels (e.g. task-id, task-attempt) preemptible: use a preemptible VM for the job logging_uri: path for job logging output. scopes: list of scope. keep_alive: Seconds to keep VM alive on failure Returns: A nested dictionary with one entry under the key pipelineArgs containing the pipeline arguments. """ # For the Pipelines API, envs and file inputs are all "inputs". inputs = {} inputs.update({SCRIPT_VARNAME: script}) inputs.update({ var.name: var.value for var in job_params['envs'] | task_params['envs'] if var.value }) inputs.update({ var.name: var.uri for var in job_params['inputs'] | task_params['inputs'] if not var.recursive and var.value }) # Remove wildcard references for non-recursive output. When the pipelines # controller generates a delocalize call, it must point to a bare directory # for patterns. The output param OUTFILE=gs://bucket/path/*.bam should # delocalize with a call similar to: # gsutil cp /mnt/data/output/gs/bucket/path/*.bam gs://bucket/path/ outputs = {} for var in job_params['outputs'] | task_params['outputs']: if var.recursive or not var.value: continue if '*' in var.uri.basename: outputs[var.name] = var.uri.path else: outputs[var.name] = var.uri labels = {} labels.update({ label.name: label.value if label.value else '' for label in (reserved_labels | job_params['labels'] | task_params['labels']) }) # pyformat: disable args = { 'pipelineArgs': { 'projectId': project, 'resources': { 'preemptible': preemptible, }, 'inputs': inputs, 'outputs': outputs, 'labels': labels, 'serviceAccount': { 'email': 'default', 'scopes': scopes, }, # Pass the user-specified GCS destination for pipeline logging. 'logging': { 'gcsPath': logging_uri }, } } # pyformat: enable if keep_alive: args['pipelineArgs'][ 'keep_vm_alive_on_failure_duration'] = '%ss' % keep_alive return args
def build_pipeline_args(cls, project, script, job_params, task_params, reserved_labels, preemptible, logging_uri, scopes, keep_alive): """Builds pipeline args for execution. Args: project: string name of project. script: Body of the script to execute. job_params: dictionary of values for labels, envs, inputs, and outputs for this job. task_params: dictionary of values for labels, envs, inputs, and outputs for this task. reserved_labels: dictionary of reserved labels (e.g. task-id, task-attempt) preemptible: use a preemptible VM for the job logging_uri: path for job logging output. scopes: list of scope. keep_alive: Seconds to keep VM alive on failure Returns: A nested dictionary with one entry under the key pipelineArgs containing the pipeline arguments. """ # For the Pipelines API, envs and file inputs are all "inputs". inputs = {} inputs.update({SCRIPT_VARNAME: script}) inputs.update({ var.name: var.value for var in job_params['envs'] | task_params['envs'] if var.value }) inputs.update({ var.name: var.uri for var in job_params['inputs'] | task_params['inputs'] if not var.recursive and var.value }) # Remove wildcard references for non-recursive output. When the pipelines # controller generates a delocalize call, it must point to a bare directory # for patterns. The output param OUTFILE=gs://bucket/path/*.bam should # delocalize with a call similar to: # gsutil cp /mnt/data/output/gs/bucket/path/*.bam gs://bucket/path/ outputs = {} for var in job_params['outputs'] | task_params['outputs']: if var.recursive or not var.value: continue if '*' in var.uri.basename: outputs[var.name] = var.uri.path else: outputs[var.name] = var.uri labels = {} labels.update({ label.name: label.value if label.value else '' for label in (reserved_labels | job_params['labels'] | task_params['labels']) }) # pyformat: disable args = { 'pipelineArgs': { 'projectId': project, 'resources': { 'preemptible': preemptible, }, 'inputs': inputs, 'outputs': outputs, 'labels': labels, 'serviceAccount': { 'email': 'default', 'scopes': scopes, }, # Pass the user-specified GCS destination for pipeline logging. 'logging': { 'gcsPath': logging_uri }, } } # pyformat: enable if keep_alive: args['pipelineArgs'][ 'keep_vm_alive_on_failure_duration'] = '%ss' % keep_alive return args
[ "Builds", "pipeline", "args", "for", "execution", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L371-L455
[ "def", "build_pipeline_args", "(", "cls", ",", "project", ",", "script", ",", "job_params", ",", "task_params", ",", "reserved_labels", ",", "preemptible", ",", "logging_uri", ",", "scopes", ",", "keep_alive", ")", ":", "# For the Pipelines API, envs and file inputs are all \"inputs\".", "inputs", "=", "{", "}", "inputs", ".", "update", "(", "{", "SCRIPT_VARNAME", ":", "script", "}", ")", "inputs", ".", "update", "(", "{", "var", ".", "name", ":", "var", ".", "value", "for", "var", "in", "job_params", "[", "'envs'", "]", "|", "task_params", "[", "'envs'", "]", "if", "var", ".", "value", "}", ")", "inputs", ".", "update", "(", "{", "var", ".", "name", ":", "var", ".", "uri", "for", "var", "in", "job_params", "[", "'inputs'", "]", "|", "task_params", "[", "'inputs'", "]", "if", "not", "var", ".", "recursive", "and", "var", ".", "value", "}", ")", "# Remove wildcard references for non-recursive output. When the pipelines", "# controller generates a delocalize call, it must point to a bare directory", "# for patterns. The output param OUTFILE=gs://bucket/path/*.bam should", "# delocalize with a call similar to:", "# gsutil cp /mnt/data/output/gs/bucket/path/*.bam gs://bucket/path/", "outputs", "=", "{", "}", "for", "var", "in", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", ":", "if", "var", ".", "recursive", "or", "not", "var", ".", "value", ":", "continue", "if", "'*'", "in", "var", ".", "uri", ".", "basename", ":", "outputs", "[", "var", ".", "name", "]", "=", "var", ".", "uri", ".", "path", "else", ":", "outputs", "[", "var", ".", "name", "]", "=", "var", ".", "uri", "labels", "=", "{", "}", "labels", ".", "update", "(", "{", "label", ".", "name", ":", "label", ".", "value", "if", "label", ".", "value", "else", "''", "for", "label", "in", "(", "reserved_labels", "|", "job_params", "[", "'labels'", "]", "|", "task_params", "[", "'labels'", "]", ")", "}", ")", "# pyformat: disable", "args", "=", "{", "'pipelineArgs'", ":", "{", "'projectId'", ":", "project", ",", "'resources'", ":", "{", "'preemptible'", ":", "preemptible", ",", "}", ",", "'inputs'", ":", "inputs", ",", "'outputs'", ":", "outputs", ",", "'labels'", ":", "labels", ",", "'serviceAccount'", ":", "{", "'email'", ":", "'default'", ",", "'scopes'", ":", "scopes", ",", "}", ",", "# Pass the user-specified GCS destination for pipeline logging.", "'logging'", ":", "{", "'gcsPath'", ":", "logging_uri", "}", ",", "}", "}", "# pyformat: enable", "if", "keep_alive", ":", "args", "[", "'pipelineArgs'", "]", "[", "'keep_vm_alive_on_failure_duration'", "]", "=", "'%ss'", "%", "keep_alive", "return", "args" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Operations._datetime_to_utc_int
Convert the integer UTC time value into a local datetime.
dsub/providers/google.py
def _datetime_to_utc_int(date): """Convert the integer UTC time value into a local datetime.""" if date is None: return None # Convert localized datetime to a UTC integer epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc) return (date - epoch).total_seconds()
def _datetime_to_utc_int(date): """Convert the integer UTC time value into a local datetime.""" if date is None: return None # Convert localized datetime to a UTC integer epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc) return (date - epoch).total_seconds()
[ "Convert", "the", "integer", "UTC", "time", "value", "into", "a", "local", "datetime", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L466-L473
[ "def", "_datetime_to_utc_int", "(", "date", ")", ":", "if", "date", "is", "None", ":", "return", "None", "# Convert localized datetime to a UTC integer", "epoch", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ",", "pytz", ".", "utc", ")", "return", "(", "date", "-", "epoch", ")", ".", "total_seconds", "(", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Operations.get_filter
Return a filter string for operations.list().
dsub/providers/google.py
def get_filter(project, status=None, user_id=None, job_id=None, job_name=None, labels=None, task_id=None, task_attempt=None, create_time_min=None, create_time_max=None): """Return a filter string for operations.list().""" ops_filter = ['projectId = %s' % project] if status and status != '*': ops_filter.append('status = %s' % status) if user_id != '*': ops_filter.append('labels.user-id = %s' % user_id) if job_id != '*': ops_filter.append('labels.job-id = %s' % job_id) if job_name != '*': ops_filter.append('labels.job-name = %s' % job_name) if task_id != '*': ops_filter.append('labels.task-id = %s' % task_id) if task_attempt != '*': ops_filter.append('labels.task-attempt = %s' % task_attempt) # Even though labels are nominally 'arbitrary strings' they are trusted # since param_util restricts the character set. if labels: for l in labels: ops_filter.append('labels.%s = %s' % (l.name, l.value)) epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc) if create_time_min: create_time_min_utc_int = (create_time_min - epoch).total_seconds() ops_filter.append('createTime >= %d' % create_time_min_utc_int) if create_time_max: create_time_max_utc_int = (create_time_max - epoch).total_seconds() ops_filter.append('createTime <= %d' % create_time_max_utc_int) return ' AND '.join(ops_filter)
def get_filter(project, status=None, user_id=None, job_id=None, job_name=None, labels=None, task_id=None, task_attempt=None, create_time_min=None, create_time_max=None): """Return a filter string for operations.list().""" ops_filter = ['projectId = %s' % project] if status and status != '*': ops_filter.append('status = %s' % status) if user_id != '*': ops_filter.append('labels.user-id = %s' % user_id) if job_id != '*': ops_filter.append('labels.job-id = %s' % job_id) if job_name != '*': ops_filter.append('labels.job-name = %s' % job_name) if task_id != '*': ops_filter.append('labels.task-id = %s' % task_id) if task_attempt != '*': ops_filter.append('labels.task-attempt = %s' % task_attempt) # Even though labels are nominally 'arbitrary strings' they are trusted # since param_util restricts the character set. if labels: for l in labels: ops_filter.append('labels.%s = %s' % (l.name, l.value)) epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc) if create_time_min: create_time_min_utc_int = (create_time_min - epoch).total_seconds() ops_filter.append('createTime >= %d' % create_time_min_utc_int) if create_time_max: create_time_max_utc_int = (create_time_max - epoch).total_seconds() ops_filter.append('createTime <= %d' % create_time_max_utc_int) return ' AND '.join(ops_filter)
[ "Return", "a", "filter", "string", "for", "operations", ".", "list", "()", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L476-L517
[ "def", "get_filter", "(", "project", ",", "status", "=", "None", ",", "user_id", "=", "None", ",", "job_id", "=", "None", ",", "job_name", "=", "None", ",", "labels", "=", "None", ",", "task_id", "=", "None", ",", "task_attempt", "=", "None", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ")", ":", "ops_filter", "=", "[", "'projectId = %s'", "%", "project", "]", "if", "status", "and", "status", "!=", "'*'", ":", "ops_filter", ".", "append", "(", "'status = %s'", "%", "status", ")", "if", "user_id", "!=", "'*'", ":", "ops_filter", ".", "append", "(", "'labels.user-id = %s'", "%", "user_id", ")", "if", "job_id", "!=", "'*'", ":", "ops_filter", ".", "append", "(", "'labels.job-id = %s'", "%", "job_id", ")", "if", "job_name", "!=", "'*'", ":", "ops_filter", ".", "append", "(", "'labels.job-name = %s'", "%", "job_name", ")", "if", "task_id", "!=", "'*'", ":", "ops_filter", ".", "append", "(", "'labels.task-id = %s'", "%", "task_id", ")", "if", "task_attempt", "!=", "'*'", ":", "ops_filter", ".", "append", "(", "'labels.task-attempt = %s'", "%", "task_attempt", ")", "# Even though labels are nominally 'arbitrary strings' they are trusted", "# since param_util restricts the character set.", "if", "labels", ":", "for", "l", "in", "labels", ":", "ops_filter", ".", "append", "(", "'labels.%s = %s'", "%", "(", "l", ".", "name", ",", "l", ".", "value", ")", ")", "epoch", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ",", "pytz", ".", "utc", ")", "if", "create_time_min", ":", "create_time_min_utc_int", "=", "(", "create_time_min", "-", "epoch", ")", ".", "total_seconds", "(", ")", "ops_filter", ".", "append", "(", "'createTime >= %d'", "%", "create_time_min_utc_int", ")", "if", "create_time_max", ":", "create_time_max_utc_int", "=", "(", "create_time_max", "-", "epoch", ")", ".", "total_seconds", "(", ")", "ops_filter", ".", "append", "(", "'createTime <= %d'", "%", "create_time_max_utc_int", ")", "return", "' AND '", ".", "join", "(", "ops_filter", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Operations.is_dsub_operation
Determine if a pipelines operation is a dsub request. We don't have a rigorous way to identify an operation as being submitted by dsub. Our best option is to check for certain fields that have always been part of dsub operations. - labels: job-id, job-name, and user-id have always existed - envs: _SCRIPT has always existed. In order to keep a simple heuristic this test only uses labels. Args: op: a pipelines operation. Returns: Boolean, true if the pipeline run was generated by dsub.
dsub/providers/google.py
def is_dsub_operation(cls, op): """Determine if a pipelines operation is a dsub request. We don't have a rigorous way to identify an operation as being submitted by dsub. Our best option is to check for certain fields that have always been part of dsub operations. - labels: job-id, job-name, and user-id have always existed - envs: _SCRIPT has always existed. In order to keep a simple heuristic this test only uses labels. Args: op: a pipelines operation. Returns: Boolean, true if the pipeline run was generated by dsub. """ if not cls.is_pipelines_operation(op): return False for name in ['job-id', 'job-name', 'user-id']: if not cls.get_operation_label(op, name): return False return True
def is_dsub_operation(cls, op): """Determine if a pipelines operation is a dsub request. We don't have a rigorous way to identify an operation as being submitted by dsub. Our best option is to check for certain fields that have always been part of dsub operations. - labels: job-id, job-name, and user-id have always existed - envs: _SCRIPT has always existed. In order to keep a simple heuristic this test only uses labels. Args: op: a pipelines operation. Returns: Boolean, true if the pipeline run was generated by dsub. """ if not cls.is_pipelines_operation(op): return False for name in ['job-id', 'job-name', 'user-id']: if not cls.get_operation_label(op, name): return False return True
[ "Determine", "if", "a", "pipelines", "operation", "is", "a", "dsub", "request", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L544-L568
[ "def", "is_dsub_operation", "(", "cls", ",", "op", ")", ":", "if", "not", "cls", ".", "is_pipelines_operation", "(", "op", ")", ":", "return", "False", "for", "name", "in", "[", "'job-id'", ",", "'job-name'", ",", "'user-id'", "]", ":", "if", "not", "cls", ".", "get_operation_label", "(", "op", ",", "name", ")", ":", "return", "False", "return", "True" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_Operations.list
Gets the list of operations for the specified filter. Args: service: Google Genomics API service object ops_filter: string filter of operations to return page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) Yields: Operations matching the filter criteria.
dsub/providers/google.py
def list(cls, service, ops_filter, page_size=0): """Gets the list of operations for the specified filter. Args: service: Google Genomics API service object ops_filter: string filter of operations to return page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) Yields: Operations matching the filter criteria. """ page_token = None more_operations = True documented_default_page_size = 256 documented_max_page_size = 2048 if not page_size: page_size = documented_default_page_size page_size = min(page_size, documented_max_page_size) while more_operations: api = service.operations().list( name='operations', filter=ops_filter, pageToken=page_token, pageSize=page_size) response = google_base.Api.execute(api) ops = response.get('operations', []) for op in ops: if cls.is_dsub_operation(op): yield GoogleOperation(op) page_token = response.get('nextPageToken') more_operations = bool(page_token)
def list(cls, service, ops_filter, page_size=0): """Gets the list of operations for the specified filter. Args: service: Google Genomics API service object ops_filter: string filter of operations to return page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) Yields: Operations matching the filter criteria. """ page_token = None more_operations = True documented_default_page_size = 256 documented_max_page_size = 2048 if not page_size: page_size = documented_default_page_size page_size = min(page_size, documented_max_page_size) while more_operations: api = service.operations().list( name='operations', filter=ops_filter, pageToken=page_token, pageSize=page_size) response = google_base.Api.execute(api) ops = response.get('operations', []) for op in ops: if cls.is_dsub_operation(op): yield GoogleOperation(op) page_token = response.get('nextPageToken') more_operations = bool(page_token)
[ "Gets", "the", "list", "of", "operations", "for", "the", "specified", "filter", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L571-L607
[ "def", "list", "(", "cls", ",", "service", ",", "ops_filter", ",", "page_size", "=", "0", ")", ":", "page_token", "=", "None", "more_operations", "=", "True", "documented_default_page_size", "=", "256", "documented_max_page_size", "=", "2048", "if", "not", "page_size", ":", "page_size", "=", "documented_default_page_size", "page_size", "=", "min", "(", "page_size", ",", "documented_max_page_size", ")", "while", "more_operations", ":", "api", "=", "service", ".", "operations", "(", ")", ".", "list", "(", "name", "=", "'operations'", ",", "filter", "=", "ops_filter", ",", "pageToken", "=", "page_token", ",", "pageSize", "=", "page_size", ")", "response", "=", "google_base", ".", "Api", ".", "execute", "(", "api", ")", "ops", "=", "response", ".", "get", "(", "'operations'", ",", "[", "]", ")", "for", "op", "in", "ops", ":", "if", "cls", ".", "is_dsub_operation", "(", "op", ")", ":", "yield", "GoogleOperation", "(", "op", ")", "page_token", "=", "response", ".", "get", "(", "'nextPageToken'", ")", "more_operations", "=", "bool", "(", "page_token", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleJobProvider.prepare_job_metadata
Returns a dictionary of metadata fields for the job.
dsub/providers/google.py
def prepare_job_metadata(self, script, job_name, user_id, create_time): """Returns a dictionary of metadata fields for the job.""" return google_base.prepare_job_metadata(script, job_name, user_id, create_time)
def prepare_job_metadata(self, script, job_name, user_id, create_time): """Returns a dictionary of metadata fields for the job.""" return google_base.prepare_job_metadata(script, job_name, user_id, create_time)
[ "Returns", "a", "dictionary", "of", "metadata", "fields", "for", "the", "job", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L638-L641
[ "def", "prepare_job_metadata", "(", "self", ",", "script", ",", "job_name", ",", "user_id", ",", "create_time", ")", ":", "return", "google_base", ".", "prepare_job_metadata", "(", "script", ",", "job_name", ",", "user_id", ",", "create_time", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleJobProvider._build_pipeline_request
Returns a Pipeline objects for the job.
dsub/providers/google.py
def _build_pipeline_request(self, task_view): """Returns a Pipeline objects for the job.""" job_metadata = task_view.job_metadata job_params = task_view.job_params job_resources = task_view.job_resources task_metadata = task_view.task_descriptors[0].task_metadata task_params = task_view.task_descriptors[0].task_params task_resources = task_view.task_descriptors[0].task_resources script = task_view.job_metadata['script'] reserved_labels = google_base.build_pipeline_labels( job_metadata, task_metadata, task_id_pattern='task-%d') # Build the ephemeralPipeline for this job. # The ephemeralPipeline definition changes for each job because file # parameters localCopy.path changes based on the remote_uri. pipeline = _Pipelines.build_pipeline( project=self._project, zones=job_resources.zones, min_cores=job_resources.min_cores, min_ram=job_resources.min_ram, disk_size=job_resources.disk_size, boot_disk_size=job_resources.boot_disk_size, preemptible=job_resources.preemptible, accelerator_type=job_resources.accelerator_type, accelerator_count=job_resources.accelerator_count, image=job_resources.image, script_name=script.name, envs=job_params['envs'] | task_params['envs'], inputs=job_params['inputs'] | task_params['inputs'], outputs=job_params['outputs'] | task_params['outputs'], pipeline_name=job_metadata['pipeline-name']) # Build the pipelineArgs for this job. logging_uri = task_resources.logging_path.uri scopes = job_resources.scopes or google_base.DEFAULT_SCOPES pipeline.update( _Pipelines.build_pipeline_args(self._project, script.value, job_params, task_params, reserved_labels, job_resources.preemptible, logging_uri, scopes, job_resources.keep_alive)) return pipeline
def _build_pipeline_request(self, task_view): """Returns a Pipeline objects for the job.""" job_metadata = task_view.job_metadata job_params = task_view.job_params job_resources = task_view.job_resources task_metadata = task_view.task_descriptors[0].task_metadata task_params = task_view.task_descriptors[0].task_params task_resources = task_view.task_descriptors[0].task_resources script = task_view.job_metadata['script'] reserved_labels = google_base.build_pipeline_labels( job_metadata, task_metadata, task_id_pattern='task-%d') # Build the ephemeralPipeline for this job. # The ephemeralPipeline definition changes for each job because file # parameters localCopy.path changes based on the remote_uri. pipeline = _Pipelines.build_pipeline( project=self._project, zones=job_resources.zones, min_cores=job_resources.min_cores, min_ram=job_resources.min_ram, disk_size=job_resources.disk_size, boot_disk_size=job_resources.boot_disk_size, preemptible=job_resources.preemptible, accelerator_type=job_resources.accelerator_type, accelerator_count=job_resources.accelerator_count, image=job_resources.image, script_name=script.name, envs=job_params['envs'] | task_params['envs'], inputs=job_params['inputs'] | task_params['inputs'], outputs=job_params['outputs'] | task_params['outputs'], pipeline_name=job_metadata['pipeline-name']) # Build the pipelineArgs for this job. logging_uri = task_resources.logging_path.uri scopes = job_resources.scopes or google_base.DEFAULT_SCOPES pipeline.update( _Pipelines.build_pipeline_args(self._project, script.value, job_params, task_params, reserved_labels, job_resources.preemptible, logging_uri, scopes, job_resources.keep_alive)) return pipeline
[ "Returns", "a", "Pipeline", "objects", "for", "the", "job", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L643-L686
[ "def", "_build_pipeline_request", "(", "self", ",", "task_view", ")", ":", "job_metadata", "=", "task_view", ".", "job_metadata", "job_params", "=", "task_view", ".", "job_params", "job_resources", "=", "task_view", ".", "job_resources", "task_metadata", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_metadata", "task_params", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_params", "task_resources", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_resources", "script", "=", "task_view", ".", "job_metadata", "[", "'script'", "]", "reserved_labels", "=", "google_base", ".", "build_pipeline_labels", "(", "job_metadata", ",", "task_metadata", ",", "task_id_pattern", "=", "'task-%d'", ")", "# Build the ephemeralPipeline for this job.", "# The ephemeralPipeline definition changes for each job because file", "# parameters localCopy.path changes based on the remote_uri.", "pipeline", "=", "_Pipelines", ".", "build_pipeline", "(", "project", "=", "self", ".", "_project", ",", "zones", "=", "job_resources", ".", "zones", ",", "min_cores", "=", "job_resources", ".", "min_cores", ",", "min_ram", "=", "job_resources", ".", "min_ram", ",", "disk_size", "=", "job_resources", ".", "disk_size", ",", "boot_disk_size", "=", "job_resources", ".", "boot_disk_size", ",", "preemptible", "=", "job_resources", ".", "preemptible", ",", "accelerator_type", "=", "job_resources", ".", "accelerator_type", ",", "accelerator_count", "=", "job_resources", ".", "accelerator_count", ",", "image", "=", "job_resources", ".", "image", ",", "script_name", "=", "script", ".", "name", ",", "envs", "=", "job_params", "[", "'envs'", "]", "|", "task_params", "[", "'envs'", "]", ",", "inputs", "=", "job_params", "[", "'inputs'", "]", "|", "task_params", "[", "'inputs'", "]", ",", "outputs", "=", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", ",", "pipeline_name", "=", "job_metadata", "[", "'pipeline-name'", "]", ")", "# Build the pipelineArgs for this job.", "logging_uri", "=", "task_resources", ".", "logging_path", ".", "uri", "scopes", "=", "job_resources", ".", "scopes", "or", "google_base", ".", "DEFAULT_SCOPES", "pipeline", ".", "update", "(", "_Pipelines", ".", "build_pipeline_args", "(", "self", ".", "_project", ",", "script", ".", "value", ",", "job_params", ",", "task_params", ",", "reserved_labels", ",", "job_resources", ".", "preemptible", ",", "logging_uri", ",", "scopes", ",", "job_resources", ".", "keep_alive", ")", ")", "return", "pipeline" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleJobProvider.lookup_job_tasks
Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings are 'RUNNING', 'SUCCESS', 'FAILURE', or 'CANCELED'. user_ids: a list of ids for the user(s) who launched the job. job_ids: a list of job ids to return. job_names: a list of job names to return. task_ids: a list of specific tasks within the specified job(s) to return. task_attempts: a list of specific attempts within the specified tasks(s) to return. labels: a list of LabelParam with user-added labels. All labels must match the task being fetched. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the page size to use for each query to the pipelins API. Raises: ValueError: if both a job id list and a job name list are provided Yeilds: Genomics API Operations objects.
dsub/providers/google.py
def lookup_job_tasks(self, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create_time_min=None, create_time_max=None, max_tasks=0, page_size=0): """Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings are 'RUNNING', 'SUCCESS', 'FAILURE', or 'CANCELED'. user_ids: a list of ids for the user(s) who launched the job. job_ids: a list of job ids to return. job_names: a list of job names to return. task_ids: a list of specific tasks within the specified job(s) to return. task_attempts: a list of specific attempts within the specified tasks(s) to return. labels: a list of LabelParam with user-added labels. All labels must match the task being fetched. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the page size to use for each query to the pipelins API. Raises: ValueError: if both a job id list and a job name list are provided Yeilds: Genomics API Operations objects. """ # Server-side, we can filter on status, job_id, user_id, task_id, but there # is no OR filter (only AND), so we can't handle lists server side. # Therefore we construct a set of queries for each possible combination of # these criteria. statuses = statuses if statuses else {'*'} user_ids = user_ids if user_ids else {'*'} job_ids = job_ids if job_ids else {'*'} job_names = job_names if job_names else {'*'} task_ids = task_ids if task_ids else {'*'} task_attempts = task_attempts if task_attempts else {'*'} # The task-id label value of "task-n" instead of just "n" is a hold-over # from early label value character restrictions. # Accept both forms, "task-n" and "n", for lookups by task-id. task_ids = {'task-{}'.format(t) if t.isdigit() else t for t in task_ids} if job_ids != {'*'} and job_names != {'*'}: raise ValueError( 'Filtering by both job IDs and job names is not supported') # AND filter rule arguments. labels = labels if labels else set() # The results of all these queries need to be sorted by create-time # (descending). To accomplish this, each query stream (already sorted by # create-time) is added to a SortedGeneratorIterator which is a wrapper # around a PriorityQueue of iterators (sorted by each stream's newest task's # create-time). A sorted list can then be built by stepping through this # iterator and adding tasks until none are left or we hit max_tasks. now = datetime.now() def _desc_date_sort_key(t): return now - dsub_util.replace_timezone(t.get_field('create-time'), None) query_queue = sorting_util.SortedGeneratorIterator(key=_desc_date_sort_key) for status, job_id, job_name, user_id, task_id, task_attempt in ( itertools.product(statuses, job_ids, job_names, user_ids, task_ids, task_attempts)): ops_filter = _Operations.get_filter( self._project, status=status, user_id=user_id, job_id=job_id, job_name=job_name, labels=labels, task_id=task_id, task_attempt=task_attempt, create_time_min=create_time_min, create_time_max=create_time_max) # The pipelines API returns operations sorted by create-time date. We can # use this sorting guarantee to merge-sort the streams together and only # retrieve more tasks as needed. stream = _Operations.list(self._service, ops_filter, page_size=page_size) query_queue.add_generator(stream) tasks_yielded = 0 for task in query_queue: yield task tasks_yielded += 1 if 0 < max_tasks <= tasks_yielded: break
def lookup_job_tasks(self, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create_time_min=None, create_time_max=None, max_tasks=0, page_size=0): """Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings are 'RUNNING', 'SUCCESS', 'FAILURE', or 'CANCELED'. user_ids: a list of ids for the user(s) who launched the job. job_ids: a list of job ids to return. job_names: a list of job names to return. task_ids: a list of specific tasks within the specified job(s) to return. task_attempts: a list of specific attempts within the specified tasks(s) to return. labels: a list of LabelParam with user-added labels. All labels must match the task being fetched. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the page size to use for each query to the pipelins API. Raises: ValueError: if both a job id list and a job name list are provided Yeilds: Genomics API Operations objects. """ # Server-side, we can filter on status, job_id, user_id, task_id, but there # is no OR filter (only AND), so we can't handle lists server side. # Therefore we construct a set of queries for each possible combination of # these criteria. statuses = statuses if statuses else {'*'} user_ids = user_ids if user_ids else {'*'} job_ids = job_ids if job_ids else {'*'} job_names = job_names if job_names else {'*'} task_ids = task_ids if task_ids else {'*'} task_attempts = task_attempts if task_attempts else {'*'} # The task-id label value of "task-n" instead of just "n" is a hold-over # from early label value character restrictions. # Accept both forms, "task-n" and "n", for lookups by task-id. task_ids = {'task-{}'.format(t) if t.isdigit() else t for t in task_ids} if job_ids != {'*'} and job_names != {'*'}: raise ValueError( 'Filtering by both job IDs and job names is not supported') # AND filter rule arguments. labels = labels if labels else set() # The results of all these queries need to be sorted by create-time # (descending). To accomplish this, each query stream (already sorted by # create-time) is added to a SortedGeneratorIterator which is a wrapper # around a PriorityQueue of iterators (sorted by each stream's newest task's # create-time). A sorted list can then be built by stepping through this # iterator and adding tasks until none are left or we hit max_tasks. now = datetime.now() def _desc_date_sort_key(t): return now - dsub_util.replace_timezone(t.get_field('create-time'), None) query_queue = sorting_util.SortedGeneratorIterator(key=_desc_date_sort_key) for status, job_id, job_name, user_id, task_id, task_attempt in ( itertools.product(statuses, job_ids, job_names, user_ids, task_ids, task_attempts)): ops_filter = _Operations.get_filter( self._project, status=status, user_id=user_id, job_id=job_id, job_name=job_name, labels=labels, task_id=task_id, task_attempt=task_attempt, create_time_min=create_time_min, create_time_max=create_time_max) # The pipelines API returns operations sorted by create-time date. We can # use this sorting guarantee to merge-sort the streams together and only # retrieve more tasks as needed. stream = _Operations.list(self._service, ops_filter, page_size=page_size) query_queue.add_generator(stream) tasks_yielded = 0 for task in query_queue: yield task tasks_yielded += 1 if 0 < max_tasks <= tasks_yielded: break
[ "Yields", "operations", "based", "on", "the", "input", "criteria", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L754-L859
[ "def", "lookup_job_tasks", "(", "self", ",", "statuses", ",", "user_ids", "=", "None", ",", "job_ids", "=", "None", ",", "job_names", "=", "None", ",", "task_ids", "=", "None", ",", "task_attempts", "=", "None", ",", "labels", "=", "None", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ",", "max_tasks", "=", "0", ",", "page_size", "=", "0", ")", ":", "# Server-side, we can filter on status, job_id, user_id, task_id, but there", "# is no OR filter (only AND), so we can't handle lists server side.", "# Therefore we construct a set of queries for each possible combination of", "# these criteria.", "statuses", "=", "statuses", "if", "statuses", "else", "{", "'*'", "}", "user_ids", "=", "user_ids", "if", "user_ids", "else", "{", "'*'", "}", "job_ids", "=", "job_ids", "if", "job_ids", "else", "{", "'*'", "}", "job_names", "=", "job_names", "if", "job_names", "else", "{", "'*'", "}", "task_ids", "=", "task_ids", "if", "task_ids", "else", "{", "'*'", "}", "task_attempts", "=", "task_attempts", "if", "task_attempts", "else", "{", "'*'", "}", "# The task-id label value of \"task-n\" instead of just \"n\" is a hold-over", "# from early label value character restrictions.", "# Accept both forms, \"task-n\" and \"n\", for lookups by task-id.", "task_ids", "=", "{", "'task-{}'", ".", "format", "(", "t", ")", "if", "t", ".", "isdigit", "(", ")", "else", "t", "for", "t", "in", "task_ids", "}", "if", "job_ids", "!=", "{", "'*'", "}", "and", "job_names", "!=", "{", "'*'", "}", ":", "raise", "ValueError", "(", "'Filtering by both job IDs and job names is not supported'", ")", "# AND filter rule arguments.", "labels", "=", "labels", "if", "labels", "else", "set", "(", ")", "# The results of all these queries need to be sorted by create-time", "# (descending). To accomplish this, each query stream (already sorted by", "# create-time) is added to a SortedGeneratorIterator which is a wrapper", "# around a PriorityQueue of iterators (sorted by each stream's newest task's", "# create-time). A sorted list can then be built by stepping through this", "# iterator and adding tasks until none are left or we hit max_tasks.", "now", "=", "datetime", ".", "now", "(", ")", "def", "_desc_date_sort_key", "(", "t", ")", ":", "return", "now", "-", "dsub_util", ".", "replace_timezone", "(", "t", ".", "get_field", "(", "'create-time'", ")", ",", "None", ")", "query_queue", "=", "sorting_util", ".", "SortedGeneratorIterator", "(", "key", "=", "_desc_date_sort_key", ")", "for", "status", ",", "job_id", ",", "job_name", ",", "user_id", ",", "task_id", ",", "task_attempt", "in", "(", "itertools", ".", "product", "(", "statuses", ",", "job_ids", ",", "job_names", ",", "user_ids", ",", "task_ids", ",", "task_attempts", ")", ")", ":", "ops_filter", "=", "_Operations", ".", "get_filter", "(", "self", ".", "_project", ",", "status", "=", "status", ",", "user_id", "=", "user_id", ",", "job_id", "=", "job_id", ",", "job_name", "=", "job_name", ",", "labels", "=", "labels", ",", "task_id", "=", "task_id", ",", "task_attempt", "=", "task_attempt", ",", "create_time_min", "=", "create_time_min", ",", "create_time_max", "=", "create_time_max", ")", "# The pipelines API returns operations sorted by create-time date. We can", "# use this sorting guarantee to merge-sort the streams together and only", "# retrieve more tasks as needed.", "stream", "=", "_Operations", ".", "list", "(", "self", ".", "_service", ",", "ops_filter", ",", "page_size", "=", "page_size", ")", "query_queue", ".", "add_generator", "(", "stream", ")", "tasks_yielded", "=", "0", "for", "task", "in", "query_queue", ":", "yield", "task", "tasks_yielded", "+=", "1", "if", "0", "<", "max_tasks", "<=", "tasks_yielded", ":", "break" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleJobProvider.delete_jobs
Kills the operations associated with the specified job or job.task. Args: user_ids: List of user ids who "own" the job(s) to cancel. job_ids: List of job_ids to cancel. task_ids: List of task-ids to cancel. labels: List of LabelParam, each must match the job(s) to be canceled. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. Returns: A list of tasks canceled and a list of error messages.
dsub/providers/google.py
def delete_jobs(self, user_ids, job_ids, task_ids, labels, create_time_min=None, create_time_max=None): """Kills the operations associated with the specified job or job.task. Args: user_ids: List of user ids who "own" the job(s) to cancel. job_ids: List of job_ids to cancel. task_ids: List of task-ids to cancel. labels: List of LabelParam, each must match the job(s) to be canceled. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. Returns: A list of tasks canceled and a list of error messages. """ # Look up the job(s) tasks = list( self.lookup_job_tasks( {'RUNNING'}, user_ids=user_ids, job_ids=job_ids, task_ids=task_ids, labels=labels, create_time_min=create_time_min, create_time_max=create_time_max)) print('Found %d tasks to delete.' % len(tasks)) return google_base.cancel(self._service.new_batch_http_request, self._service.operations().cancel, tasks)
def delete_jobs(self, user_ids, job_ids, task_ids, labels, create_time_min=None, create_time_max=None): """Kills the operations associated with the specified job or job.task. Args: user_ids: List of user ids who "own" the job(s) to cancel. job_ids: List of job_ids to cancel. task_ids: List of task-ids to cancel. labels: List of LabelParam, each must match the job(s) to be canceled. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. Returns: A list of tasks canceled and a list of error messages. """ # Look up the job(s) tasks = list( self.lookup_job_tasks( {'RUNNING'}, user_ids=user_ids, job_ids=job_ids, task_ids=task_ids, labels=labels, create_time_min=create_time_min, create_time_max=create_time_max)) print('Found %d tasks to delete.' % len(tasks)) return google_base.cancel(self._service.new_batch_http_request, self._service.operations().cancel, tasks)
[ "Kills", "the", "operations", "associated", "with", "the", "specified", "job", "or", "job", ".", "task", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L861-L897
[ "def", "delete_jobs", "(", "self", ",", "user_ids", ",", "job_ids", ",", "task_ids", ",", "labels", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ")", ":", "# Look up the job(s)", "tasks", "=", "list", "(", "self", ".", "lookup_job_tasks", "(", "{", "'RUNNING'", "}", ",", "user_ids", "=", "user_ids", ",", "job_ids", "=", "job_ids", ",", "task_ids", "=", "task_ids", ",", "labels", "=", "labels", ",", "create_time_min", "=", "create_time_min", ",", "create_time_max", "=", "create_time_max", ")", ")", "print", "(", "'Found %d tasks to delete.'", "%", "len", "(", "tasks", ")", ")", "return", "google_base", ".", "cancel", "(", "self", ".", "_service", ".", "new_batch_http_request", ",", "self", ".", "_service", ".", "operations", "(", ")", ".", "cancel", ",", "tasks", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation.get_field
Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'inputs'. Raises: ValueError: if the field label is not supported by the operation
dsub/providers/google.py
def get_field(self, field, default=None): """Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'inputs'. Raises: ValueError: if the field label is not supported by the operation """ metadata = self._op.get('metadata') value = None if field == 'internal-id': value = self._op['name'] elif field == 'job-id': value = metadata['labels'].get('job-id') elif field == 'job-name': value = metadata['labels'].get('job-name') elif field == 'task-id': value = metadata['labels'].get('task-id') elif field == 'task-attempt': value = metadata['labels'].get('task-attempt') elif field == 'user-id': value = metadata['labels'].get('user-id') elif field == 'dsub-version': value = metadata['labels'].get('dsub-version') elif field == 'task-status': value = self._operation_status() elif field == 'logging': value = metadata['request']['pipelineArgs']['logging']['gcsPath'] elif field == 'envs': value = self._get_operation_input_field_values(metadata, False) elif field == 'labels': # Reserved labels are filtered from dsub task output. value = { k: v for k, v in metadata['labels'].items() if k not in job_model.RESERVED_LABELS } elif field == 'inputs': value = self._get_operation_input_field_values(metadata, True) elif field == 'outputs': value = self._get_operation_output_field_values(metadata) elif field == 'mounts': value = None elif field == 'create-time': value = google_base.parse_rfc3339_utc_string(metadata['createTime']) elif field == 'start-time': # Look through the events list for all "start" events (only one expected). start_events = [ e for e in metadata.get('events', []) if e['description'] == 'start' ] # Get the startTime from the last "start" event. if start_events: value = google_base.parse_rfc3339_utc_string( start_events[-1]['startTime']) elif field == 'end-time': if 'endTime' in metadata: value = google_base.parse_rfc3339_utc_string(metadata['endTime']) elif field == 'status': value = self._operation_status() elif field in ['status-message', 'status-detail']: status, last_update = self._operation_status_message() value = status elif field == 'last-update': status, last_update = self._operation_status_message() value = last_update elif field == 'provider': return _PROVIDER_NAME elif field == 'provider-attributes': # Use soft getting of keys to address a race condition and to # pull the null values found in jobs that fail prior to scheduling. gce_data = metadata.get('runtimeMetadata', {}).get('computeEngine', {}) if 'machineType' in gce_data: machine_type = gce_data.get('machineType').rpartition('/')[2] else: machine_type = None instance_name = gce_data.get('instanceName') instance_zone = gce_data.get('zone') value = { 'machine-type': machine_type, 'instance-name': instance_name, 'zone': instance_zone, } elif field == 'events': events = metadata.get('events', []) value = [] for event in events: event_value = { 'name': event.get('description', ''), 'start-time': google_base.parse_rfc3339_utc_string(event['startTime']) } if 'endTime' in event: event_value['end-time'] = google_base.parse_rfc3339_utc_string( event['endTime']) value.append(event_value) elif field in [ 'user-project', 'script-name', 'script', 'input-recursives', 'output-recursives' ]: # Supported in local and google-v2 providers. value = None else: raise ValueError('Unsupported field: "%s"' % field) return value if value else default
def get_field(self, field, default=None): """Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'inputs'. Raises: ValueError: if the field label is not supported by the operation """ metadata = self._op.get('metadata') value = None if field == 'internal-id': value = self._op['name'] elif field == 'job-id': value = metadata['labels'].get('job-id') elif field == 'job-name': value = metadata['labels'].get('job-name') elif field == 'task-id': value = metadata['labels'].get('task-id') elif field == 'task-attempt': value = metadata['labels'].get('task-attempt') elif field == 'user-id': value = metadata['labels'].get('user-id') elif field == 'dsub-version': value = metadata['labels'].get('dsub-version') elif field == 'task-status': value = self._operation_status() elif field == 'logging': value = metadata['request']['pipelineArgs']['logging']['gcsPath'] elif field == 'envs': value = self._get_operation_input_field_values(metadata, False) elif field == 'labels': # Reserved labels are filtered from dsub task output. value = { k: v for k, v in metadata['labels'].items() if k not in job_model.RESERVED_LABELS } elif field == 'inputs': value = self._get_operation_input_field_values(metadata, True) elif field == 'outputs': value = self._get_operation_output_field_values(metadata) elif field == 'mounts': value = None elif field == 'create-time': value = google_base.parse_rfc3339_utc_string(metadata['createTime']) elif field == 'start-time': # Look through the events list for all "start" events (only one expected). start_events = [ e for e in metadata.get('events', []) if e['description'] == 'start' ] # Get the startTime from the last "start" event. if start_events: value = google_base.parse_rfc3339_utc_string( start_events[-1]['startTime']) elif field == 'end-time': if 'endTime' in metadata: value = google_base.parse_rfc3339_utc_string(metadata['endTime']) elif field == 'status': value = self._operation_status() elif field in ['status-message', 'status-detail']: status, last_update = self._operation_status_message() value = status elif field == 'last-update': status, last_update = self._operation_status_message() value = last_update elif field == 'provider': return _PROVIDER_NAME elif field == 'provider-attributes': # Use soft getting of keys to address a race condition and to # pull the null values found in jobs that fail prior to scheduling. gce_data = metadata.get('runtimeMetadata', {}).get('computeEngine', {}) if 'machineType' in gce_data: machine_type = gce_data.get('machineType').rpartition('/')[2] else: machine_type = None instance_name = gce_data.get('instanceName') instance_zone = gce_data.get('zone') value = { 'machine-type': machine_type, 'instance-name': instance_name, 'zone': instance_zone, } elif field == 'events': events = metadata.get('events', []) value = [] for event in events: event_value = { 'name': event.get('description', ''), 'start-time': google_base.parse_rfc3339_utc_string(event['startTime']) } if 'endTime' in event: event_value['end-time'] = google_base.parse_rfc3339_utc_string( event['endTime']) value.append(event_value) elif field in [ 'user-project', 'script-name', 'script', 'input-recursives', 'output-recursives' ]: # Supported in local and google-v2 providers. value = None else: raise ValueError('Unsupported field: "%s"' % field) return value if value else default
[ "Returns", "a", "value", "from", "the", "operation", "for", "a", "specific", "set", "of", "field", "names", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L918-L1032
[ "def", "get_field", "(", "self", ",", "field", ",", "default", "=", "None", ")", ":", "metadata", "=", "self", ".", "_op", ".", "get", "(", "'metadata'", ")", "value", "=", "None", "if", "field", "==", "'internal-id'", ":", "value", "=", "self", ".", "_op", "[", "'name'", "]", "elif", "field", "==", "'job-id'", ":", "value", "=", "metadata", "[", "'labels'", "]", ".", "get", "(", "'job-id'", ")", "elif", "field", "==", "'job-name'", ":", "value", "=", "metadata", "[", "'labels'", "]", ".", "get", "(", "'job-name'", ")", "elif", "field", "==", "'task-id'", ":", "value", "=", "metadata", "[", "'labels'", "]", ".", "get", "(", "'task-id'", ")", "elif", "field", "==", "'task-attempt'", ":", "value", "=", "metadata", "[", "'labels'", "]", ".", "get", "(", "'task-attempt'", ")", "elif", "field", "==", "'user-id'", ":", "value", "=", "metadata", "[", "'labels'", "]", ".", "get", "(", "'user-id'", ")", "elif", "field", "==", "'dsub-version'", ":", "value", "=", "metadata", "[", "'labels'", "]", ".", "get", "(", "'dsub-version'", ")", "elif", "field", "==", "'task-status'", ":", "value", "=", "self", ".", "_operation_status", "(", ")", "elif", "field", "==", "'logging'", ":", "value", "=", "metadata", "[", "'request'", "]", "[", "'pipelineArgs'", "]", "[", "'logging'", "]", "[", "'gcsPath'", "]", "elif", "field", "==", "'envs'", ":", "value", "=", "self", ".", "_get_operation_input_field_values", "(", "metadata", ",", "False", ")", "elif", "field", "==", "'labels'", ":", "# Reserved labels are filtered from dsub task output.", "value", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "metadata", "[", "'labels'", "]", ".", "items", "(", ")", "if", "k", "not", "in", "job_model", ".", "RESERVED_LABELS", "}", "elif", "field", "==", "'inputs'", ":", "value", "=", "self", ".", "_get_operation_input_field_values", "(", "metadata", ",", "True", ")", "elif", "field", "==", "'outputs'", ":", "value", "=", "self", ".", "_get_operation_output_field_values", "(", "metadata", ")", "elif", "field", "==", "'mounts'", ":", "value", "=", "None", "elif", "field", "==", "'create-time'", ":", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "metadata", "[", "'createTime'", "]", ")", "elif", "field", "==", "'start-time'", ":", "# Look through the events list for all \"start\" events (only one expected).", "start_events", "=", "[", "e", "for", "e", "in", "metadata", ".", "get", "(", "'events'", ",", "[", "]", ")", "if", "e", "[", "'description'", "]", "==", "'start'", "]", "# Get the startTime from the last \"start\" event.", "if", "start_events", ":", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "start_events", "[", "-", "1", "]", "[", "'startTime'", "]", ")", "elif", "field", "==", "'end-time'", ":", "if", "'endTime'", "in", "metadata", ":", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "metadata", "[", "'endTime'", "]", ")", "elif", "field", "==", "'status'", ":", "value", "=", "self", ".", "_operation_status", "(", ")", "elif", "field", "in", "[", "'status-message'", ",", "'status-detail'", "]", ":", "status", ",", "last_update", "=", "self", ".", "_operation_status_message", "(", ")", "value", "=", "status", "elif", "field", "==", "'last-update'", ":", "status", ",", "last_update", "=", "self", ".", "_operation_status_message", "(", ")", "value", "=", "last_update", "elif", "field", "==", "'provider'", ":", "return", "_PROVIDER_NAME", "elif", "field", "==", "'provider-attributes'", ":", "# Use soft getting of keys to address a race condition and to", "# pull the null values found in jobs that fail prior to scheduling.", "gce_data", "=", "metadata", ".", "get", "(", "'runtimeMetadata'", ",", "{", "}", ")", ".", "get", "(", "'computeEngine'", ",", "{", "}", ")", "if", "'machineType'", "in", "gce_data", ":", "machine_type", "=", "gce_data", ".", "get", "(", "'machineType'", ")", ".", "rpartition", "(", "'/'", ")", "[", "2", "]", "else", ":", "machine_type", "=", "None", "instance_name", "=", "gce_data", ".", "get", "(", "'instanceName'", ")", "instance_zone", "=", "gce_data", ".", "get", "(", "'zone'", ")", "value", "=", "{", "'machine-type'", ":", "machine_type", ",", "'instance-name'", ":", "instance_name", ",", "'zone'", ":", "instance_zone", ",", "}", "elif", "field", "==", "'events'", ":", "events", "=", "metadata", ".", "get", "(", "'events'", ",", "[", "]", ")", "value", "=", "[", "]", "for", "event", "in", "events", ":", "event_value", "=", "{", "'name'", ":", "event", ".", "get", "(", "'description'", ",", "''", ")", ",", "'start-time'", ":", "google_base", ".", "parse_rfc3339_utc_string", "(", "event", "[", "'startTime'", "]", ")", "}", "if", "'endTime'", "in", "event", ":", "event_value", "[", "'end-time'", "]", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "event", "[", "'endTime'", "]", ")", "value", ".", "append", "(", "event_value", ")", "elif", "field", "in", "[", "'user-project'", ",", "'script-name'", ",", "'script'", ",", "'input-recursives'", ",", "'output-recursives'", "]", ":", "# Supported in local and google-v2 providers.", "value", "=", "None", "else", ":", "raise", "ValueError", "(", "'Unsupported field: \"%s\"'", "%", "field", ")", "return", "value", "if", "value", "else", "default" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation._operation_status_message
Returns the most relevant status string and last updated date string. This string is meant for display only. Returns: A printable status string and date string.
dsub/providers/google.py
def _operation_status_message(self): """Returns the most relevant status string and last updated date string. This string is meant for display only. Returns: A printable status string and date string. """ metadata = self._op['metadata'] if not self._op['done']: if 'events' in metadata and metadata['events']: # Get the last event last_event = metadata['events'][-1] msg = last_event['description'] ds = last_event['startTime'] else: msg = 'Pending' ds = metadata['createTime'] else: ds = metadata['endTime'] if 'error' in self._op: msg = self._op['error']['message'] else: msg = 'Success' return (msg, google_base.parse_rfc3339_utc_string(ds))
def _operation_status_message(self): """Returns the most relevant status string and last updated date string. This string is meant for display only. Returns: A printable status string and date string. """ metadata = self._op['metadata'] if not self._op['done']: if 'events' in metadata and metadata['events']: # Get the last event last_event = metadata['events'][-1] msg = last_event['description'] ds = last_event['startTime'] else: msg = 'Pending' ds = metadata['createTime'] else: ds = metadata['endTime'] if 'error' in self._op: msg = self._op['error']['message'] else: msg = 'Success' return (msg, google_base.parse_rfc3339_utc_string(ds))
[ "Returns", "the", "most", "relevant", "status", "string", "and", "last", "updated", "date", "string", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L1050-L1077
[ "def", "_operation_status_message", "(", "self", ")", ":", "metadata", "=", "self", ".", "_op", "[", "'metadata'", "]", "if", "not", "self", ".", "_op", "[", "'done'", "]", ":", "if", "'events'", "in", "metadata", "and", "metadata", "[", "'events'", "]", ":", "# Get the last event", "last_event", "=", "metadata", "[", "'events'", "]", "[", "-", "1", "]", "msg", "=", "last_event", "[", "'description'", "]", "ds", "=", "last_event", "[", "'startTime'", "]", "else", ":", "msg", "=", "'Pending'", "ds", "=", "metadata", "[", "'createTime'", "]", "else", ":", "ds", "=", "metadata", "[", "'endTime'", "]", "if", "'error'", "in", "self", ".", "_op", ":", "msg", "=", "self", ".", "_op", "[", "'error'", "]", "[", "'message'", "]", "else", ":", "msg", "=", "'Success'", "return", "(", "msg", ",", "google_base", ".", "parse_rfc3339_utc_string", "(", "ds", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation._get_operation_input_field_values
Returns a dictionary of envs or file inputs for an operation. Args: metadata: operation metadata field file_input: True to return a dict of file inputs, False to return envs. Returns: A dictionary of input field name value pairs
dsub/providers/google.py
def _get_operation_input_field_values(self, metadata, file_input): """Returns a dictionary of envs or file inputs for an operation. Args: metadata: operation metadata field file_input: True to return a dict of file inputs, False to return envs. Returns: A dictionary of input field name value pairs """ # To determine input parameter type, we iterate through the # pipeline inputParameters. # The values come from the pipelineArgs inputs. input_args = metadata['request']['ephemeralPipeline']['inputParameters'] vals_dict = metadata['request']['pipelineArgs']['inputs'] # Get the names for files or envs names = [ arg['name'] for arg in input_args if ('localCopy' in arg) == file_input ] # Build the return dict return {name: vals_dict[name] for name in names if name in vals_dict}
def _get_operation_input_field_values(self, metadata, file_input): """Returns a dictionary of envs or file inputs for an operation. Args: metadata: operation metadata field file_input: True to return a dict of file inputs, False to return envs. Returns: A dictionary of input field name value pairs """ # To determine input parameter type, we iterate through the # pipeline inputParameters. # The values come from the pipelineArgs inputs. input_args = metadata['request']['ephemeralPipeline']['inputParameters'] vals_dict = metadata['request']['pipelineArgs']['inputs'] # Get the names for files or envs names = [ arg['name'] for arg in input_args if ('localCopy' in arg) == file_input ] # Build the return dict return {name: vals_dict[name] for name in names if name in vals_dict}
[ "Returns", "a", "dictionary", "of", "envs", "or", "file", "inputs", "for", "an", "operation", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L1079-L1102
[ "def", "_get_operation_input_field_values", "(", "self", ",", "metadata", ",", "file_input", ")", ":", "# To determine input parameter type, we iterate through the", "# pipeline inputParameters.", "# The values come from the pipelineArgs inputs.", "input_args", "=", "metadata", "[", "'request'", "]", "[", "'ephemeralPipeline'", "]", "[", "'inputParameters'", "]", "vals_dict", "=", "metadata", "[", "'request'", "]", "[", "'pipelineArgs'", "]", "[", "'inputs'", "]", "# Get the names for files or envs", "names", "=", "[", "arg", "[", "'name'", "]", "for", "arg", "in", "input_args", "if", "(", "'localCopy'", "in", "arg", ")", "==", "file_input", "]", "# Build the return dict", "return", "{", "name", ":", "vals_dict", "[", "name", "]", "for", "name", "in", "names", "if", "name", "in", "vals_dict", "}" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation.error_message
Returns an error message if the operation failed for any reason. Failure as defined here means; ended for any reason other than 'success'. This means that a successful cancelation will also create an error message here. Returns: string, string will be empty if job did not error.
dsub/providers/google.py
def error_message(self): """Returns an error message if the operation failed for any reason. Failure as defined here means; ended for any reason other than 'success'. This means that a successful cancelation will also create an error message here. Returns: string, string will be empty if job did not error. """ if 'error' in self._op: if 'task-id' in self._op['metadata']['labels']: job_id = self._op['metadata']['labels']['task-id'] else: job_id = self._op['metadata']['labels']['job-id'] return 'Error in job %s - code %s: %s' % (job_id, self._op['error']['code'], self._op['error']['message']) else: return ''
def error_message(self): """Returns an error message if the operation failed for any reason. Failure as defined here means; ended for any reason other than 'success'. This means that a successful cancelation will also create an error message here. Returns: string, string will be empty if job did not error. """ if 'error' in self._op: if 'task-id' in self._op['metadata']['labels']: job_id = self._op['metadata']['labels']['task-id'] else: job_id = self._op['metadata']['labels']['job-id'] return 'Error in job %s - code %s: %s' % (job_id, self._op['error']['code'], self._op['error']['message']) else: return ''
[ "Returns", "an", "error", "message", "if", "the", "operation", "failed", "for", "any", "reason", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L1121-L1140
[ "def", "error_message", "(", "self", ")", ":", "if", "'error'", "in", "self", ".", "_op", ":", "if", "'task-id'", "in", "self", ".", "_op", "[", "'metadata'", "]", "[", "'labels'", "]", ":", "job_id", "=", "self", ".", "_op", "[", "'metadata'", "]", "[", "'labels'", "]", "[", "'task-id'", "]", "else", ":", "job_id", "=", "self", ".", "_op", "[", "'metadata'", "]", "[", "'labels'", "]", "[", "'job-id'", "]", "return", "'Error in job %s - code %s: %s'", "%", "(", "job_id", ",", "self", ".", "_op", "[", "'error'", "]", "[", "'code'", "]", ",", "self", ".", "_op", "[", "'error'", "]", "[", "'message'", "]", ")", "else", ":", "return", "''" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_format_task_name
Create a task name from a job-id, task-id, and task-attempt. Task names are used internally by dsub as well as by the docker task runner. The name is formatted as "<job-id>.<task-id>[.task-attempt]". Task names follow formatting conventions allowing them to be safely used as a docker name. Args: job_id: (str) the job ID. task_id: (str) the task ID. task_attempt: (int) the task attempt. Returns: a task name string.
dsub/providers/local.py
def _format_task_name(job_id, task_id, task_attempt): """Create a task name from a job-id, task-id, and task-attempt. Task names are used internally by dsub as well as by the docker task runner. The name is formatted as "<job-id>.<task-id>[.task-attempt]". Task names follow formatting conventions allowing them to be safely used as a docker name. Args: job_id: (str) the job ID. task_id: (str) the task ID. task_attempt: (int) the task attempt. Returns: a task name string. """ docker_name = '%s.%s' % (job_id, 'task' if task_id is None else task_id) if task_attempt is not None: docker_name += '.' + str(task_attempt) # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-] # So 1) prefix it with "dsub-" and 2) change all invalid characters to "-". return 'dsub-{}'.format(_convert_suffix_to_docker_chars(docker_name))
def _format_task_name(job_id, task_id, task_attempt): """Create a task name from a job-id, task-id, and task-attempt. Task names are used internally by dsub as well as by the docker task runner. The name is formatted as "<job-id>.<task-id>[.task-attempt]". Task names follow formatting conventions allowing them to be safely used as a docker name. Args: job_id: (str) the job ID. task_id: (str) the task ID. task_attempt: (int) the task attempt. Returns: a task name string. """ docker_name = '%s.%s' % (job_id, 'task' if task_id is None else task_id) if task_attempt is not None: docker_name += '.' + str(task_attempt) # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-] # So 1) prefix it with "dsub-" and 2) change all invalid characters to "-". return 'dsub-{}'.format(_convert_suffix_to_docker_chars(docker_name))
[ "Create", "a", "task", "name", "from", "a", "job", "-", "id", "task", "-", "id", "and", "task", "-", "attempt", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L119-L142
[ "def", "_format_task_name", "(", "job_id", ",", "task_id", ",", "task_attempt", ")", ":", "docker_name", "=", "'%s.%s'", "%", "(", "job_id", ",", "'task'", "if", "task_id", "is", "None", "else", "task_id", ")", "if", "task_attempt", "is", "not", "None", ":", "docker_name", "+=", "'.'", "+", "str", "(", "task_attempt", ")", "# Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]", "# So 1) prefix it with \"dsub-\" and 2) change all invalid characters to \"-\".", "return", "'dsub-{}'", ".", "format", "(", "_convert_suffix_to_docker_chars", "(", "docker_name", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_convert_suffix_to_docker_chars
Rewrite string so that all characters are valid in a docker name suffix.
dsub/providers/local.py
def _convert_suffix_to_docker_chars(suffix): """Rewrite string so that all characters are valid in a docker name suffix.""" # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-] accepted_characters = string.ascii_letters + string.digits + '_.-' def label_char_transform(char): if char in accepted_characters: return char return '-' return ''.join(label_char_transform(c) for c in suffix)
def _convert_suffix_to_docker_chars(suffix): """Rewrite string so that all characters are valid in a docker name suffix.""" # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-] accepted_characters = string.ascii_letters + string.digits + '_.-' def label_char_transform(char): if char in accepted_characters: return char return '-' return ''.join(label_char_transform(c) for c in suffix)
[ "Rewrite", "string", "so", "that", "all", "characters", "are", "valid", "in", "a", "docker", "name", "suffix", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L145-L155
[ "def", "_convert_suffix_to_docker_chars", "(", "suffix", ")", ":", "# Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]", "accepted_characters", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'_.-'", "def", "label_char_transform", "(", "char", ")", ":", "if", "char", "in", "accepted_characters", ":", "return", "char", "return", "'-'", "return", "''", ".", "join", "(", "label_char_transform", "(", "c", ")", "for", "c", "in", "suffix", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
_task_sort_function
Return a tuple for sorting 'most recent first'.
dsub/providers/local.py
def _task_sort_function(task): """Return a tuple for sorting 'most recent first'.""" return (task.get_field('create-time'), int(task.get_field('task-id', 0)), int(task.get_field('task-attempt', 0)))
def _task_sort_function(task): """Return a tuple for sorting 'most recent first'.""" return (task.get_field('create-time'), int(task.get_field('task-id', 0)), int(task.get_field('task-attempt', 0)))
[ "Return", "a", "tuple", "for", "sorting", "most", "recent", "first", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L158-L161
[ "def", "_task_sort_function", "(", "task", ")", ":", "return", "(", "task", ".", "get_field", "(", "'create-time'", ")", ",", "int", "(", "task", ".", "get_field", "(", "'task-id'", ",", "0", ")", ")", ",", "int", "(", "task", ".", "get_field", "(", "'task-attempt'", ",", "0", ")", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._datetime_in_range
Determine if the provided time is within the range, inclusive.
dsub/providers/local.py
def _datetime_in_range(self, dt, dt_min=None, dt_max=None): """Determine if the provided time is within the range, inclusive.""" # The pipelines API stores operation create-time with second granularity. # We mimic this behavior in the local provider by truncating to seconds. dt = dt.replace(microsecond=0) if dt_min: dt_min = dt_min.replace(microsecond=0) else: dt_min = dsub_util.replace_timezone(datetime.datetime.min, pytz.utc) if dt_max: dt_max = dt_max.replace(microsecond=0) else: dt_max = dsub_util.replace_timezone(datetime.datetime.max, pytz.utc) return dt_min <= dt <= dt_max
def _datetime_in_range(self, dt, dt_min=None, dt_max=None): """Determine if the provided time is within the range, inclusive.""" # The pipelines API stores operation create-time with second granularity. # We mimic this behavior in the local provider by truncating to seconds. dt = dt.replace(microsecond=0) if dt_min: dt_min = dt_min.replace(microsecond=0) else: dt_min = dsub_util.replace_timezone(datetime.datetime.min, pytz.utc) if dt_max: dt_max = dt_max.replace(microsecond=0) else: dt_max = dsub_util.replace_timezone(datetime.datetime.max, pytz.utc) return dt_min <= dt <= dt_max
[ "Determine", "if", "the", "provided", "time", "is", "within", "the", "range", "inclusive", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L566-L580
[ "def", "_datetime_in_range", "(", "self", ",", "dt", ",", "dt_min", "=", "None", ",", "dt_max", "=", "None", ")", ":", "# The pipelines API stores operation create-time with second granularity.", "# We mimic this behavior in the local provider by truncating to seconds.", "dt", "=", "dt", ".", "replace", "(", "microsecond", "=", "0", ")", "if", "dt_min", ":", "dt_min", "=", "dt_min", ".", "replace", "(", "microsecond", "=", "0", ")", "else", ":", "dt_min", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "datetime", ".", "min", ",", "pytz", ".", "utc", ")", "if", "dt_max", ":", "dt_max", "=", "dt_max", ".", "replace", "(", "microsecond", "=", "0", ")", "else", ":", "dt_max", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "datetime", ".", "max", ",", "pytz", ".", "utc", ")", "return", "dt_min", "<=", "dt", "<=", "dt_max" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._get_task_from_task_dir
Return a Task object with this task's info.
dsub/providers/local.py
def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt): """Return a Task object with this task's info.""" # We need to be very careful about how we read and interpret the contents # of the task directory. The directory could be changing because a new # task is being created. The directory could be changing because a task # is ending. # # If the meta.yaml does not exist, the task does not yet exist. # If the meta.yaml exists, it means the task is scheduled. It does not mean # it is yet running. # If the task.pid file exists, it means that the runner.sh was started. task_dir = self._task_directory(job_id, task_id, task_attempt) job_descriptor = self._read_task_metadata(task_dir) if not job_descriptor: return None # If we read up an old task, the user-id will not be in the job_descriptor. if not job_descriptor.job_metadata.get('user-id'): job_descriptor.job_metadata['user-id'] = user_id # Get the pid of the runner pid = -1 try: with open(os.path.join(task_dir, 'task.pid'), 'r') as f: pid = int(f.readline().strip()) except (IOError, OSError): pass # Get the script contents script = None script_name = job_descriptor.job_metadata.get('script-name') if script_name: script = self._read_script(task_dir, script_name) # Read the files written by the runner.sh. # For new tasks, these may not have been written yet. end_time = self._get_end_time_from_task_dir(task_dir) last_update = self._get_last_update_time_from_task_dir(task_dir) events = self._get_events_from_task_dir(task_dir) status = self._get_status_from_task_dir(task_dir) log_detail = self._get_log_detail_from_task_dir(task_dir) # If the status file is not yet written, then mark the task as pending if not status: status = 'RUNNING' log_detail = ['Pending'] return LocalTask( task_status=status, events=events, log_detail=log_detail, job_descriptor=job_descriptor, end_time=end_time, last_update=last_update, pid=pid, script=script)
def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt): """Return a Task object with this task's info.""" # We need to be very careful about how we read and interpret the contents # of the task directory. The directory could be changing because a new # task is being created. The directory could be changing because a task # is ending. # # If the meta.yaml does not exist, the task does not yet exist. # If the meta.yaml exists, it means the task is scheduled. It does not mean # it is yet running. # If the task.pid file exists, it means that the runner.sh was started. task_dir = self._task_directory(job_id, task_id, task_attempt) job_descriptor = self._read_task_metadata(task_dir) if not job_descriptor: return None # If we read up an old task, the user-id will not be in the job_descriptor. if not job_descriptor.job_metadata.get('user-id'): job_descriptor.job_metadata['user-id'] = user_id # Get the pid of the runner pid = -1 try: with open(os.path.join(task_dir, 'task.pid'), 'r') as f: pid = int(f.readline().strip()) except (IOError, OSError): pass # Get the script contents script = None script_name = job_descriptor.job_metadata.get('script-name') if script_name: script = self._read_script(task_dir, script_name) # Read the files written by the runner.sh. # For new tasks, these may not have been written yet. end_time = self._get_end_time_from_task_dir(task_dir) last_update = self._get_last_update_time_from_task_dir(task_dir) events = self._get_events_from_task_dir(task_dir) status = self._get_status_from_task_dir(task_dir) log_detail = self._get_log_detail_from_task_dir(task_dir) # If the status file is not yet written, then mark the task as pending if not status: status = 'RUNNING' log_detail = ['Pending'] return LocalTask( task_status=status, events=events, log_detail=log_detail, job_descriptor=job_descriptor, end_time=end_time, last_update=last_update, pid=pid, script=script)
[ "Return", "a", "Task", "object", "with", "this", "task", "s", "info", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L641-L699
[ "def", "_get_task_from_task_dir", "(", "self", ",", "job_id", ",", "user_id", ",", "task_id", ",", "task_attempt", ")", ":", "# We need to be very careful about how we read and interpret the contents", "# of the task directory. The directory could be changing because a new", "# task is being created. The directory could be changing because a task", "# is ending.", "#", "# If the meta.yaml does not exist, the task does not yet exist.", "# If the meta.yaml exists, it means the task is scheduled. It does not mean", "# it is yet running.", "# If the task.pid file exists, it means that the runner.sh was started.", "task_dir", "=", "self", ".", "_task_directory", "(", "job_id", ",", "task_id", ",", "task_attempt", ")", "job_descriptor", "=", "self", ".", "_read_task_metadata", "(", "task_dir", ")", "if", "not", "job_descriptor", ":", "return", "None", "# If we read up an old task, the user-id will not be in the job_descriptor.", "if", "not", "job_descriptor", ".", "job_metadata", ".", "get", "(", "'user-id'", ")", ":", "job_descriptor", ".", "job_metadata", "[", "'user-id'", "]", "=", "user_id", "# Get the pid of the runner", "pid", "=", "-", "1", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "task_dir", ",", "'task.pid'", ")", ",", "'r'", ")", "as", "f", ":", "pid", "=", "int", "(", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "pass", "# Get the script contents", "script", "=", "None", "script_name", "=", "job_descriptor", ".", "job_metadata", ".", "get", "(", "'script-name'", ")", "if", "script_name", ":", "script", "=", "self", ".", "_read_script", "(", "task_dir", ",", "script_name", ")", "# Read the files written by the runner.sh.", "# For new tasks, these may not have been written yet.", "end_time", "=", "self", ".", "_get_end_time_from_task_dir", "(", "task_dir", ")", "last_update", "=", "self", ".", "_get_last_update_time_from_task_dir", "(", "task_dir", ")", "events", "=", "self", ".", "_get_events_from_task_dir", "(", "task_dir", ")", "status", "=", "self", ".", "_get_status_from_task_dir", "(", "task_dir", ")", "log_detail", "=", "self", ".", "_get_log_detail_from_task_dir", "(", "task_dir", ")", "# If the status file is not yet written, then mark the task as pending", "if", "not", "status", ":", "status", "=", "'RUNNING'", "log_detail", "=", "[", "'Pending'", "]", "return", "LocalTask", "(", "task_status", "=", "status", ",", "events", "=", "events", ",", "log_detail", "=", "log_detail", ",", "job_descriptor", "=", "job_descriptor", ",", "end_time", "=", "end_time", ",", "last_update", "=", "last_update", ",", "pid", "=", "pid", ",", "script", "=", "script", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._delocalize_logging_command
Returns a command to delocalize logs. Args: logging_path: location of log files. user_project: name of the project to be billed for the request. Returns: eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12'
dsub/providers/local.py
def _delocalize_logging_command(self, logging_path, user_project): """Returns a command to delocalize logs. Args: logging_path: location of log files. user_project: name of the project to be billed for the request. Returns: eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12' """ # Get the logging prefix (everything up to ".log") logging_prefix = os.path.splitext(logging_path.uri)[0] # Set the provider-specific mkdir and file copy commands if logging_path.file_provider == job_model.P_LOCAL: mkdir_cmd = 'mkdir -p "%s"\n' % os.path.dirname(logging_prefix) cp_cmd = 'cp' elif logging_path.file_provider == job_model.P_GCS: mkdir_cmd = '' if user_project: cp_cmd = 'gsutil -u {} -mq cp'.format(user_project) else: cp_cmd = 'gsutil -mq cp' else: assert False # Construct the copy command copy_logs_cmd = textwrap.dedent("""\ local cp_cmd="{cp_cmd}" local prefix="{prefix}" """).format( cp_cmd=cp_cmd, prefix=logging_prefix) # Build up the command body = textwrap.dedent("""\ {mkdir_cmd} {copy_logs_cmd} """).format( mkdir_cmd=mkdir_cmd, copy_logs_cmd=copy_logs_cmd) return body
def _delocalize_logging_command(self, logging_path, user_project): """Returns a command to delocalize logs. Args: logging_path: location of log files. user_project: name of the project to be billed for the request. Returns: eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12' """ # Get the logging prefix (everything up to ".log") logging_prefix = os.path.splitext(logging_path.uri)[0] # Set the provider-specific mkdir and file copy commands if logging_path.file_provider == job_model.P_LOCAL: mkdir_cmd = 'mkdir -p "%s"\n' % os.path.dirname(logging_prefix) cp_cmd = 'cp' elif logging_path.file_provider == job_model.P_GCS: mkdir_cmd = '' if user_project: cp_cmd = 'gsutil -u {} -mq cp'.format(user_project) else: cp_cmd = 'gsutil -mq cp' else: assert False # Construct the copy command copy_logs_cmd = textwrap.dedent("""\ local cp_cmd="{cp_cmd}" local prefix="{prefix}" """).format( cp_cmd=cp_cmd, prefix=logging_prefix) # Build up the command body = textwrap.dedent("""\ {mkdir_cmd} {copy_logs_cmd} """).format( mkdir_cmd=mkdir_cmd, copy_logs_cmd=copy_logs_cmd) return body
[ "Returns", "a", "command", "to", "delocalize", "logs", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L704-L745
[ "def", "_delocalize_logging_command", "(", "self", ",", "logging_path", ",", "user_project", ")", ":", "# Get the logging prefix (everything up to \".log\")", "logging_prefix", "=", "os", ".", "path", ".", "splitext", "(", "logging_path", ".", "uri", ")", "[", "0", "]", "# Set the provider-specific mkdir and file copy commands", "if", "logging_path", ".", "file_provider", "==", "job_model", ".", "P_LOCAL", ":", "mkdir_cmd", "=", "'mkdir -p \"%s\"\\n'", "%", "os", ".", "path", ".", "dirname", "(", "logging_prefix", ")", "cp_cmd", "=", "'cp'", "elif", "logging_path", ".", "file_provider", "==", "job_model", ".", "P_GCS", ":", "mkdir_cmd", "=", "''", "if", "user_project", ":", "cp_cmd", "=", "'gsutil -u {} -mq cp'", ".", "format", "(", "user_project", ")", "else", ":", "cp_cmd", "=", "'gsutil -mq cp'", "else", ":", "assert", "False", "# Construct the copy command", "copy_logs_cmd", "=", "textwrap", ".", "dedent", "(", "\"\"\"\\\n local cp_cmd=\"{cp_cmd}\"\n local prefix=\"{prefix}\"\n \"\"\"", ")", ".", "format", "(", "cp_cmd", "=", "cp_cmd", ",", "prefix", "=", "logging_prefix", ")", "# Build up the command", "body", "=", "textwrap", ".", "dedent", "(", "\"\"\"\\\n {mkdir_cmd}\n {copy_logs_cmd}\n \"\"\"", ")", ".", "format", "(", "mkdir_cmd", "=", "mkdir_cmd", ",", "copy_logs_cmd", "=", "copy_logs_cmd", ")", "return", "body" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._task_directory
The local dir for staging files for that particular task.
dsub/providers/local.py
def _task_directory(self, job_id, task_id, task_attempt): """The local dir for staging files for that particular task.""" dir_name = 'task' if task_id is None else str(task_id) if task_attempt: dir_name = '%s.%s' % (dir_name, task_attempt) return self._provider_root() + '/' + job_id + '/' + dir_name
def _task_directory(self, job_id, task_id, task_attempt): """The local dir for staging files for that particular task.""" dir_name = 'task' if task_id is None else str(task_id) if task_attempt: dir_name = '%s.%s' % (dir_name, task_attempt) return self._provider_root() + '/' + job_id + '/' + dir_name
[ "The", "local", "dir", "for", "staging", "files", "for", "that", "particular", "task", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L765-L770
[ "def", "_task_directory", "(", "self", ",", "job_id", ",", "task_id", ",", "task_attempt", ")", ":", "dir_name", "=", "'task'", "if", "task_id", "is", "None", "else", "str", "(", "task_id", ")", "if", "task_attempt", ":", "dir_name", "=", "'%s.%s'", "%", "(", "dir_name", ",", "task_attempt", ")", "return", "self", ".", "_provider_root", "(", ")", "+", "'/'", "+", "job_id", "+", "'/'", "+", "dir_name" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._make_environment
Return a dictionary of environment variables for the container.
dsub/providers/local.py
def _make_environment(self, inputs, outputs, mounts): """Return a dictionary of environment variables for the container.""" env = {} env.update(providers_util.get_file_environment_variables(inputs)) env.update(providers_util.get_file_environment_variables(outputs)) env.update(providers_util.get_file_environment_variables(mounts)) return env
def _make_environment(self, inputs, outputs, mounts): """Return a dictionary of environment variables for the container.""" env = {} env.update(providers_util.get_file_environment_variables(inputs)) env.update(providers_util.get_file_environment_variables(outputs)) env.update(providers_util.get_file_environment_variables(mounts)) return env
[ "Return", "a", "dictionary", "of", "environment", "variables", "for", "the", "container", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L779-L785
[ "def", "_make_environment", "(", "self", ",", "inputs", ",", "outputs", ",", "mounts", ")", ":", "env", "=", "{", "}", "env", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "inputs", ")", ")", "env", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "outputs", ")", ")", "env", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "mounts", ")", ")", "return", "env" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._localize_inputs_recursive_command
Returns a command that will stage recursive inputs.
dsub/providers/local.py
def _localize_inputs_recursive_command(self, task_dir, inputs): """Returns a command that will stage recursive inputs.""" data_dir = os.path.join(task_dir, _DATA_SUBDIR) provider_commands = [ providers_util.build_recursive_localize_command(data_dir, inputs, file_provider) for file_provider in _SUPPORTED_INPUT_PROVIDERS ] return '\n'.join(provider_commands)
def _localize_inputs_recursive_command(self, task_dir, inputs): """Returns a command that will stage recursive inputs.""" data_dir = os.path.join(task_dir, _DATA_SUBDIR) provider_commands = [ providers_util.build_recursive_localize_command(data_dir, inputs, file_provider) for file_provider in _SUPPORTED_INPUT_PROVIDERS ] return '\n'.join(provider_commands)
[ "Returns", "a", "command", "that", "will", "stage", "recursive", "inputs", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L787-L795
[ "def", "_localize_inputs_recursive_command", "(", "self", ",", "task_dir", ",", "inputs", ")", ":", "data_dir", "=", "os", ".", "path", ".", "join", "(", "task_dir", ",", "_DATA_SUBDIR", ")", "provider_commands", "=", "[", "providers_util", ".", "build_recursive_localize_command", "(", "data_dir", ",", "inputs", ",", "file_provider", ")", "for", "file_provider", "in", "_SUPPORTED_INPUT_PROVIDERS", "]", "return", "'\\n'", ".", "join", "(", "provider_commands", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._get_input_target_path
Returns a directory or file path to be the target for "gsutil cp". If the filename contains a wildcard, then the target path must be a directory in order to ensure consistency whether the source pattern contains one or multiple files. Args: local_file_path: A full path terminating in a file or a file wildcard. Returns: The path to use as the "gsutil cp" target.
dsub/providers/local.py
def _get_input_target_path(self, local_file_path): """Returns a directory or file path to be the target for "gsutil cp". If the filename contains a wildcard, then the target path must be a directory in order to ensure consistency whether the source pattern contains one or multiple files. Args: local_file_path: A full path terminating in a file or a file wildcard. Returns: The path to use as the "gsutil cp" target. """ path, filename = os.path.split(local_file_path) if '*' in filename: return path + '/' else: return local_file_path
def _get_input_target_path(self, local_file_path): """Returns a directory or file path to be the target for "gsutil cp". If the filename contains a wildcard, then the target path must be a directory in order to ensure consistency whether the source pattern contains one or multiple files. Args: local_file_path: A full path terminating in a file or a file wildcard. Returns: The path to use as the "gsutil cp" target. """ path, filename = os.path.split(local_file_path) if '*' in filename: return path + '/' else: return local_file_path
[ "Returns", "a", "directory", "or", "file", "path", "to", "be", "the", "target", "for", "gsutil", "cp", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L797-L816
[ "def", "_get_input_target_path", "(", "self", ",", "local_file_path", ")", ":", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "local_file_path", ")", "if", "'*'", "in", "filename", ":", "return", "path", "+", "'/'", "else", ":", "return", "local_file_path" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._localize_inputs_command
Returns a command that will stage inputs.
dsub/providers/local.py
def _localize_inputs_command(self, task_dir, inputs, user_project): """Returns a command that will stage inputs.""" commands = [] for i in inputs: if i.recursive or not i.value: continue source_file_path = i.uri local_file_path = task_dir + '/' + _DATA_SUBDIR + '/' + i.docker_path dest_file_path = self._get_input_target_path(local_file_path) commands.append('mkdir -p "%s"' % os.path.dirname(local_file_path)) if i.file_provider in [job_model.P_LOCAL, job_model.P_GCS]: # The semantics that we expect here are implemented consistently in # "gsutil cp", and are a bit different than "cp" when it comes to # wildcard handling, so use it for both local and GCS: # # - `cp path/* dest/` will error if "path" has subdirectories. # - `cp "path/*" "dest/"` will fail (it expects wildcard expansion # to come from shell). if user_project: command = 'gsutil -u %s -mq cp "%s" "%s"' % ( user_project, source_file_path, dest_file_path) else: command = 'gsutil -mq cp "%s" "%s"' % (source_file_path, dest_file_path) commands.append(command) return '\n'.join(commands)
def _localize_inputs_command(self, task_dir, inputs, user_project): """Returns a command that will stage inputs.""" commands = [] for i in inputs: if i.recursive or not i.value: continue source_file_path = i.uri local_file_path = task_dir + '/' + _DATA_SUBDIR + '/' + i.docker_path dest_file_path = self._get_input_target_path(local_file_path) commands.append('mkdir -p "%s"' % os.path.dirname(local_file_path)) if i.file_provider in [job_model.P_LOCAL, job_model.P_GCS]: # The semantics that we expect here are implemented consistently in # "gsutil cp", and are a bit different than "cp" when it comes to # wildcard handling, so use it for both local and GCS: # # - `cp path/* dest/` will error if "path" has subdirectories. # - `cp "path/*" "dest/"` will fail (it expects wildcard expansion # to come from shell). if user_project: command = 'gsutil -u %s -mq cp "%s" "%s"' % ( user_project, source_file_path, dest_file_path) else: command = 'gsutil -mq cp "%s" "%s"' % (source_file_path, dest_file_path) commands.append(command) return '\n'.join(commands)
[ "Returns", "a", "command", "that", "will", "stage", "inputs", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L818-L847
[ "def", "_localize_inputs_command", "(", "self", ",", "task_dir", ",", "inputs", ",", "user_project", ")", ":", "commands", "=", "[", "]", "for", "i", "in", "inputs", ":", "if", "i", ".", "recursive", "or", "not", "i", ".", "value", ":", "continue", "source_file_path", "=", "i", ".", "uri", "local_file_path", "=", "task_dir", "+", "'/'", "+", "_DATA_SUBDIR", "+", "'/'", "+", "i", ".", "docker_path", "dest_file_path", "=", "self", ".", "_get_input_target_path", "(", "local_file_path", ")", "commands", ".", "append", "(", "'mkdir -p \"%s\"'", "%", "os", ".", "path", ".", "dirname", "(", "local_file_path", ")", ")", "if", "i", ".", "file_provider", "in", "[", "job_model", ".", "P_LOCAL", ",", "job_model", ".", "P_GCS", "]", ":", "# The semantics that we expect here are implemented consistently in", "# \"gsutil cp\", and are a bit different than \"cp\" when it comes to", "# wildcard handling, so use it for both local and GCS:", "#", "# - `cp path/* dest/` will error if \"path\" has subdirectories.", "# - `cp \"path/*\" \"dest/\"` will fail (it expects wildcard expansion", "# to come from shell).", "if", "user_project", ":", "command", "=", "'gsutil -u %s -mq cp \"%s\" \"%s\"'", "%", "(", "user_project", ",", "source_file_path", ",", "dest_file_path", ")", "else", ":", "command", "=", "'gsutil -mq cp \"%s\" \"%s\"'", "%", "(", "source_file_path", ",", "dest_file_path", ")", "commands", ".", "append", "(", "command", ")", "return", "'\\n'", ".", "join", "(", "commands", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
LocalJobProvider._delocalize_outputs_commands
Copy outputs from local disk to GCS.
dsub/providers/local.py
def _delocalize_outputs_commands(self, task_dir, outputs, user_project): """Copy outputs from local disk to GCS.""" commands = [] for o in outputs: if o.recursive or not o.value: continue # The destination path is o.uri.path, which is the target directory # (rather than o.uri, which includes the filename or wildcard). dest_path = o.uri.path local_path = task_dir + '/' + _DATA_SUBDIR + '/' + o.docker_path if o.file_provider == job_model.P_LOCAL: commands.append('mkdir -p "%s"' % dest_path) # Use gsutil even for local files (explained in _localize_inputs_command). if o.file_provider in [job_model.P_LOCAL, job_model.P_GCS]: if user_project: command = 'gsutil -u %s -mq cp "%s" "%s"' % (user_project, local_path, dest_path) else: command = 'gsutil -mq cp "%s" "%s"' % (local_path, dest_path) commands.append(command) return '\n'.join(commands)
def _delocalize_outputs_commands(self, task_dir, outputs, user_project): """Copy outputs from local disk to GCS.""" commands = [] for o in outputs: if o.recursive or not o.value: continue # The destination path is o.uri.path, which is the target directory # (rather than o.uri, which includes the filename or wildcard). dest_path = o.uri.path local_path = task_dir + '/' + _DATA_SUBDIR + '/' + o.docker_path if o.file_provider == job_model.P_LOCAL: commands.append('mkdir -p "%s"' % dest_path) # Use gsutil even for local files (explained in _localize_inputs_command). if o.file_provider in [job_model.P_LOCAL, job_model.P_GCS]: if user_project: command = 'gsutil -u %s -mq cp "%s" "%s"' % (user_project, local_path, dest_path) else: command = 'gsutil -mq cp "%s" "%s"' % (local_path, dest_path) commands.append(command) return '\n'.join(commands)
[ "Copy", "outputs", "from", "local", "disk", "to", "GCS", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L875-L899
[ "def", "_delocalize_outputs_commands", "(", "self", ",", "task_dir", ",", "outputs", ",", "user_project", ")", ":", "commands", "=", "[", "]", "for", "o", "in", "outputs", ":", "if", "o", ".", "recursive", "or", "not", "o", ".", "value", ":", "continue", "# The destination path is o.uri.path, which is the target directory", "# (rather than o.uri, which includes the filename or wildcard).", "dest_path", "=", "o", ".", "uri", ".", "path", "local_path", "=", "task_dir", "+", "'/'", "+", "_DATA_SUBDIR", "+", "'/'", "+", "o", ".", "docker_path", "if", "o", ".", "file_provider", "==", "job_model", ".", "P_LOCAL", ":", "commands", ".", "append", "(", "'mkdir -p \"%s\"'", "%", "dest_path", ")", "# Use gsutil even for local files (explained in _localize_inputs_command).", "if", "o", ".", "file_provider", "in", "[", "job_model", ".", "P_LOCAL", ",", "job_model", ".", "P_GCS", "]", ":", "if", "user_project", ":", "command", "=", "'gsutil -u %s -mq cp \"%s\" \"%s\"'", "%", "(", "user_project", ",", "local_path", ",", "dest_path", ")", "else", ":", "command", "=", "'gsutil -mq cp \"%s\" \"%s\"'", "%", "(", "local_path", ",", "dest_path", ")", "commands", ".", "append", "(", "command", ")", "return", "'\\n'", ".", "join", "(", "commands", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
get_dsub_version
Get the dsub version out of the _dsub_version.py source file. Setup.py should not import dsub version from dsub directly since ambiguity in import order could lead to an old version of dsub setting the version number. Parsing the file directly is simpler than using import tools (whose interface varies between python 2.7, 3.4, and 3.5). Returns: string of dsub version. Raises: ValueError: if the version is not found.
setup.py
def get_dsub_version(): """Get the dsub version out of the _dsub_version.py source file. Setup.py should not import dsub version from dsub directly since ambiguity in import order could lead to an old version of dsub setting the version number. Parsing the file directly is simpler than using import tools (whose interface varies between python 2.7, 3.4, and 3.5). Returns: string of dsub version. Raises: ValueError: if the version is not found. """ filename = os.path.join(os.path.dirname(__file__), 'dsub/_dsub_version.py') with open(filename, 'r') as versionfile: for line in versionfile: if line.startswith('DSUB_VERSION ='): # Get the version then strip whitespace and quote characters. version = line.partition('=')[2] return version.strip().strip('\'"') raise ValueError('Could not find version.')
def get_dsub_version(): """Get the dsub version out of the _dsub_version.py source file. Setup.py should not import dsub version from dsub directly since ambiguity in import order could lead to an old version of dsub setting the version number. Parsing the file directly is simpler than using import tools (whose interface varies between python 2.7, 3.4, and 3.5). Returns: string of dsub version. Raises: ValueError: if the version is not found. """ filename = os.path.join(os.path.dirname(__file__), 'dsub/_dsub_version.py') with open(filename, 'r') as versionfile: for line in versionfile: if line.startswith('DSUB_VERSION ='): # Get the version then strip whitespace and quote characters. version = line.partition('=')[2] return version.strip().strip('\'"') raise ValueError('Could not find version.')
[ "Get", "the", "dsub", "version", "out", "of", "the", "_dsub_version", ".", "py", "source", "file", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/setup.py#L25-L46
[ "def", "get_dsub_version", "(", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'dsub/_dsub_version.py'", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "versionfile", ":", "for", "line", "in", "versionfile", ":", "if", "line", ".", "startswith", "(", "'DSUB_VERSION ='", ")", ":", "# Get the version then strip whitespace and quote characters.", "version", "=", "line", ".", "partition", "(", "'='", ")", "[", "2", "]", "return", "version", ".", "strip", "(", ")", ".", "strip", "(", "'\\'\"'", ")", "raise", "ValueError", "(", "'Could not find version.'", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2EventMap.get_filtered_normalized_events
Filter the granular v2 events down to events of interest. Filter through the large number of granular events returned by the pipelines API, and extract only those that are interesting to a user. This is implemented by filtering out events which are known to be uninteresting (i.e. the default actions run for every job) and by explicitly matching specific events which are interesting and mapping those to v1 style naming. Events which are not whitelisted or blacklisted will still be output, meaning any events which are added in the future won't be masked. We don't want to suppress display of events that we don't recognize. They may be important. Returns: A list of maps containing the normalized, filtered events.
dsub/providers/google_v2.py
def get_filtered_normalized_events(self): """Filter the granular v2 events down to events of interest. Filter through the large number of granular events returned by the pipelines API, and extract only those that are interesting to a user. This is implemented by filtering out events which are known to be uninteresting (i.e. the default actions run for every job) and by explicitly matching specific events which are interesting and mapping those to v1 style naming. Events which are not whitelisted or blacklisted will still be output, meaning any events which are added in the future won't be masked. We don't want to suppress display of events that we don't recognize. They may be important. Returns: A list of maps containing the normalized, filtered events. """ # Need the user-image to look for the right "pulling image" event user_image = google_v2_operations.get_action_image(self._op, _ACTION_USER_COMMAND) # Only create an "ok" event for operations with SUCCESS status. need_ok = google_v2_operations.is_success(self._op) # Events are keyed by name for easier deletion. events = {} # Events are assumed to be ordered by timestamp (newest to oldest). for event in google_v2_operations.get_events(self._op): if self._filter(event): continue mapped, match = self._map(event) name = mapped['name'] if name == 'ok': # If we want the "ok" event, we grab the first (most recent). if not need_ok or 'ok' in events: continue if name == 'pulling-image': if match.group(1) != user_image: continue events[name] = mapped return sorted(events.values(), key=operator.itemgetter('start-time'))
def get_filtered_normalized_events(self): """Filter the granular v2 events down to events of interest. Filter through the large number of granular events returned by the pipelines API, and extract only those that are interesting to a user. This is implemented by filtering out events which are known to be uninteresting (i.e. the default actions run for every job) and by explicitly matching specific events which are interesting and mapping those to v1 style naming. Events which are not whitelisted or blacklisted will still be output, meaning any events which are added in the future won't be masked. We don't want to suppress display of events that we don't recognize. They may be important. Returns: A list of maps containing the normalized, filtered events. """ # Need the user-image to look for the right "pulling image" event user_image = google_v2_operations.get_action_image(self._op, _ACTION_USER_COMMAND) # Only create an "ok" event for operations with SUCCESS status. need_ok = google_v2_operations.is_success(self._op) # Events are keyed by name for easier deletion. events = {} # Events are assumed to be ordered by timestamp (newest to oldest). for event in google_v2_operations.get_events(self._op): if self._filter(event): continue mapped, match = self._map(event) name = mapped['name'] if name == 'ok': # If we want the "ok" event, we grab the first (most recent). if not need_ok or 'ok' in events: continue if name == 'pulling-image': if match.group(1) != user_image: continue events[name] = mapped return sorted(events.values(), key=operator.itemgetter('start-time'))
[ "Filter", "the", "granular", "v2", "events", "down", "to", "events", "of", "interest", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L357-L403
[ "def", "get_filtered_normalized_events", "(", "self", ")", ":", "# Need the user-image to look for the right \"pulling image\" event", "user_image", "=", "google_v2_operations", ".", "get_action_image", "(", "self", ".", "_op", ",", "_ACTION_USER_COMMAND", ")", "# Only create an \"ok\" event for operations with SUCCESS status.", "need_ok", "=", "google_v2_operations", ".", "is_success", "(", "self", ".", "_op", ")", "# Events are keyed by name for easier deletion.", "events", "=", "{", "}", "# Events are assumed to be ordered by timestamp (newest to oldest).", "for", "event", "in", "google_v2_operations", ".", "get_events", "(", "self", ".", "_op", ")", ":", "if", "self", ".", "_filter", "(", "event", ")", ":", "continue", "mapped", ",", "match", "=", "self", ".", "_map", "(", "event", ")", "name", "=", "mapped", "[", "'name'", "]", "if", "name", "==", "'ok'", ":", "# If we want the \"ok\" event, we grab the first (most recent).", "if", "not", "need_ok", "or", "'ok'", "in", "events", ":", "continue", "if", "name", "==", "'pulling-image'", ":", "if", "match", ".", "group", "(", "1", ")", "!=", "user_image", ":", "continue", "events", "[", "name", "]", "=", "mapped", "return", "sorted", "(", "events", ".", "values", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "'start-time'", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2EventMap._map
Extract elements from an operation event and map to a named event.
dsub/providers/google_v2.py
def _map(self, event): """Extract elements from an operation event and map to a named event.""" description = event.get('description', '') start_time = google_base.parse_rfc3339_utc_string( event.get('timestamp', '')) for name, regex in _EVENT_REGEX_MAP.items(): match = regex.match(description) if match: return {'name': name, 'start-time': start_time}, match return {'name': description, 'start-time': start_time}, None
def _map(self, event): """Extract elements from an operation event and map to a named event.""" description = event.get('description', '') start_time = google_base.parse_rfc3339_utc_string( event.get('timestamp', '')) for name, regex in _EVENT_REGEX_MAP.items(): match = regex.match(description) if match: return {'name': name, 'start-time': start_time}, match return {'name': description, 'start-time': start_time}, None
[ "Extract", "elements", "from", "an", "operation", "event", "and", "map", "to", "a", "named", "event", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L405-L416
[ "def", "_map", "(", "self", ",", "event", ")", ":", "description", "=", "event", ".", "get", "(", "'description'", ",", "''", ")", "start_time", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "event", ".", "get", "(", "'timestamp'", ",", "''", ")", ")", "for", "name", ",", "regex", "in", "_EVENT_REGEX_MAP", ".", "items", "(", ")", ":", "match", "=", "regex", ".", "match", "(", "description", ")", "if", "match", ":", "return", "{", "'name'", ":", "name", ",", "'start-time'", ":", "start_time", "}", ",", "match", "return", "{", "'name'", ":", "description", ",", "'start-time'", ":", "start_time", "}", ",", "None" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._get_logging_env
Returns the environment for actions that copy logging files.
dsub/providers/google_v2.py
def _get_logging_env(self, logging_uri, user_project): """Returns the environment for actions that copy logging files.""" if not logging_uri.endswith('.log'): raise ValueError('Logging URI must end in ".log": {}'.format(logging_uri)) logging_prefix = logging_uri[:-len('.log')] return { 'LOGGING_PATH': '{}.log'.format(logging_prefix), 'STDOUT_PATH': '{}-stdout.log'.format(logging_prefix), 'STDERR_PATH': '{}-stderr.log'.format(logging_prefix), 'USER_PROJECT': user_project, }
def _get_logging_env(self, logging_uri, user_project): """Returns the environment for actions that copy logging files.""" if not logging_uri.endswith('.log'): raise ValueError('Logging URI must end in ".log": {}'.format(logging_uri)) logging_prefix = logging_uri[:-len('.log')] return { 'LOGGING_PATH': '{}.log'.format(logging_prefix), 'STDOUT_PATH': '{}-stdout.log'.format(logging_prefix), 'STDERR_PATH': '{}-stderr.log'.format(logging_prefix), 'USER_PROJECT': user_project, }
[ "Returns", "the", "environment", "for", "actions", "that", "copy", "logging", "files", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L468-L479
[ "def", "_get_logging_env", "(", "self", ",", "logging_uri", ",", "user_project", ")", ":", "if", "not", "logging_uri", ".", "endswith", "(", "'.log'", ")", ":", "raise", "ValueError", "(", "'Logging URI must end in \".log\": {}'", ".", "format", "(", "logging_uri", ")", ")", "logging_prefix", "=", "logging_uri", "[", ":", "-", "len", "(", "'.log'", ")", "]", "return", "{", "'LOGGING_PATH'", ":", "'{}.log'", ".", "format", "(", "logging_prefix", ")", ",", "'STDOUT_PATH'", ":", "'{}-stdout.log'", ".", "format", "(", "logging_prefix", ")", ",", "'STDERR_PATH'", ":", "'{}-stderr.log'", ".", "format", "(", "logging_prefix", ")", ",", "'USER_PROJECT'", ":", "user_project", ",", "}" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._get_prepare_env
Return a dict with variables for the 'prepare' action.
dsub/providers/google_v2.py
def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts): """Return a dict with variables for the 'prepare' action.""" # Add the _SCRIPT_REPR with the repr(script) contents # Add the _META_YAML_REPR with the repr(meta) contents # Add variables for directories that need to be created, for example: # DIR_COUNT: 2 # DIR_0: /mnt/data/input/gs/bucket/path1/ # DIR_1: /mnt/data/output/gs/bucket/path2 # List the directories in sorted order so that they are created in that # order. This is primarily to ensure that permissions are set as we create # each directory. # For example: # mkdir -m 777 -p /root/first/second # mkdir -m 777 -p /root/first # *may* not actually set 777 on /root/first docker_paths = sorted([ var.docker_path if var.recursive else os.path.dirname(var.docker_path) for var in inputs | outputs | mounts if var.value ]) env = { _SCRIPT_VARNAME: repr(script.value), _META_YAML_VARNAME: repr(job_descriptor.to_yaml()), 'DIR_COUNT': str(len(docker_paths)) } for idx, path in enumerate(docker_paths): env['DIR_{}'.format(idx)] = os.path.join(providers_util.DATA_MOUNT_POINT, path) return env
def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts): """Return a dict with variables for the 'prepare' action.""" # Add the _SCRIPT_REPR with the repr(script) contents # Add the _META_YAML_REPR with the repr(meta) contents # Add variables for directories that need to be created, for example: # DIR_COUNT: 2 # DIR_0: /mnt/data/input/gs/bucket/path1/ # DIR_1: /mnt/data/output/gs/bucket/path2 # List the directories in sorted order so that they are created in that # order. This is primarily to ensure that permissions are set as we create # each directory. # For example: # mkdir -m 777 -p /root/first/second # mkdir -m 777 -p /root/first # *may* not actually set 777 on /root/first docker_paths = sorted([ var.docker_path if var.recursive else os.path.dirname(var.docker_path) for var in inputs | outputs | mounts if var.value ]) env = { _SCRIPT_VARNAME: repr(script.value), _META_YAML_VARNAME: repr(job_descriptor.to_yaml()), 'DIR_COUNT': str(len(docker_paths)) } for idx, path in enumerate(docker_paths): env['DIR_{}'.format(idx)] = os.path.join(providers_util.DATA_MOUNT_POINT, path) return env
[ "Return", "a", "dict", "with", "variables", "for", "the", "prepare", "action", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L481-L516
[ "def", "_get_prepare_env", "(", "self", ",", "script", ",", "job_descriptor", ",", "inputs", ",", "outputs", ",", "mounts", ")", ":", "# Add the _SCRIPT_REPR with the repr(script) contents", "# Add the _META_YAML_REPR with the repr(meta) contents", "# Add variables for directories that need to be created, for example:", "# DIR_COUNT: 2", "# DIR_0: /mnt/data/input/gs/bucket/path1/", "# DIR_1: /mnt/data/output/gs/bucket/path2", "# List the directories in sorted order so that they are created in that", "# order. This is primarily to ensure that permissions are set as we create", "# each directory.", "# For example:", "# mkdir -m 777 -p /root/first/second", "# mkdir -m 777 -p /root/first", "# *may* not actually set 777 on /root/first", "docker_paths", "=", "sorted", "(", "[", "var", ".", "docker_path", "if", "var", ".", "recursive", "else", "os", ".", "path", ".", "dirname", "(", "var", ".", "docker_path", ")", "for", "var", "in", "inputs", "|", "outputs", "|", "mounts", "if", "var", ".", "value", "]", ")", "env", "=", "{", "_SCRIPT_VARNAME", ":", "repr", "(", "script", ".", "value", ")", ",", "_META_YAML_VARNAME", ":", "repr", "(", "job_descriptor", ".", "to_yaml", "(", ")", ")", ",", "'DIR_COUNT'", ":", "str", "(", "len", "(", "docker_paths", ")", ")", "}", "for", "idx", ",", "path", "in", "enumerate", "(", "docker_paths", ")", ":", "env", "[", "'DIR_{}'", ".", "format", "(", "idx", ")", "]", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "path", ")", "return", "env" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._get_localization_env
Return a dict with variables for the 'localization' action.
dsub/providers/google_v2.py
def _get_localization_env(self, inputs, user_project): """Return a dict with variables for the 'localization' action.""" # Add variables for paths that need to be localized, for example: # INPUT_COUNT: 1 # INPUT_0: MY_INPUT_FILE # INPUT_RECURSIVE_0: 0 # INPUT_SRC_0: gs://mybucket/mypath/myfile # INPUT_DST_0: /mnt/data/inputs/mybucket/mypath/myfile non_empty_inputs = [var for var in inputs if var.value] env = {'INPUT_COUNT': str(len(non_empty_inputs))} for idx, var in enumerate(non_empty_inputs): env['INPUT_{}'.format(idx)] = var.name env['INPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive)) env['INPUT_SRC_{}'.format(idx)] = var.value # For wildcard paths, the destination must be a directory dst = os.path.join(providers_util.DATA_MOUNT_POINT, var.docker_path) path, filename = os.path.split(dst) if '*' in filename: dst = '{}/'.format(path) env['INPUT_DST_{}'.format(idx)] = dst env['USER_PROJECT'] = user_project return env
def _get_localization_env(self, inputs, user_project): """Return a dict with variables for the 'localization' action.""" # Add variables for paths that need to be localized, for example: # INPUT_COUNT: 1 # INPUT_0: MY_INPUT_FILE # INPUT_RECURSIVE_0: 0 # INPUT_SRC_0: gs://mybucket/mypath/myfile # INPUT_DST_0: /mnt/data/inputs/mybucket/mypath/myfile non_empty_inputs = [var for var in inputs if var.value] env = {'INPUT_COUNT': str(len(non_empty_inputs))} for idx, var in enumerate(non_empty_inputs): env['INPUT_{}'.format(idx)] = var.name env['INPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive)) env['INPUT_SRC_{}'.format(idx)] = var.value # For wildcard paths, the destination must be a directory dst = os.path.join(providers_util.DATA_MOUNT_POINT, var.docker_path) path, filename = os.path.split(dst) if '*' in filename: dst = '{}/'.format(path) env['INPUT_DST_{}'.format(idx)] = dst env['USER_PROJECT'] = user_project return env
[ "Return", "a", "dict", "with", "variables", "for", "the", "localization", "action", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L518-L545
[ "def", "_get_localization_env", "(", "self", ",", "inputs", ",", "user_project", ")", ":", "# Add variables for paths that need to be localized, for example:", "# INPUT_COUNT: 1", "# INPUT_0: MY_INPUT_FILE", "# INPUT_RECURSIVE_0: 0", "# INPUT_SRC_0: gs://mybucket/mypath/myfile", "# INPUT_DST_0: /mnt/data/inputs/mybucket/mypath/myfile", "non_empty_inputs", "=", "[", "var", "for", "var", "in", "inputs", "if", "var", ".", "value", "]", "env", "=", "{", "'INPUT_COUNT'", ":", "str", "(", "len", "(", "non_empty_inputs", ")", ")", "}", "for", "idx", ",", "var", "in", "enumerate", "(", "non_empty_inputs", ")", ":", "env", "[", "'INPUT_{}'", ".", "format", "(", "idx", ")", "]", "=", "var", ".", "name", "env", "[", "'INPUT_RECURSIVE_{}'", ".", "format", "(", "idx", ")", "]", "=", "str", "(", "int", "(", "var", ".", "recursive", ")", ")", "env", "[", "'INPUT_SRC_{}'", ".", "format", "(", "idx", ")", "]", "=", "var", ".", "value", "# For wildcard paths, the destination must be a directory", "dst", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "var", ".", "docker_path", ")", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "dst", ")", "if", "'*'", "in", "filename", ":", "dst", "=", "'{}/'", ".", "format", "(", "path", ")", "env", "[", "'INPUT_DST_{}'", ".", "format", "(", "idx", ")", "]", "=", "dst", "env", "[", "'USER_PROJECT'", "]", "=", "user_project", "return", "env" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._get_delocalization_env
Return a dict with variables for the 'delocalization' action.
dsub/providers/google_v2.py
def _get_delocalization_env(self, outputs, user_project): """Return a dict with variables for the 'delocalization' action.""" # Add variables for paths that need to be delocalized, for example: # OUTPUT_COUNT: 1 # OUTPUT_0: MY_OUTPUT_FILE # OUTPUT_RECURSIVE_0: 0 # OUTPUT_SRC_0: gs://mybucket/mypath/myfile # OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile non_empty_outputs = [var for var in outputs if var.value] env = {'OUTPUT_COUNT': str(len(non_empty_outputs))} for idx, var in enumerate(non_empty_outputs): env['OUTPUT_{}'.format(idx)] = var.name env['OUTPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive)) env['OUTPUT_SRC_{}'.format(idx)] = os.path.join( providers_util.DATA_MOUNT_POINT, var.docker_path) # For wildcard paths, the destination must be a directory if '*' in var.uri.basename: dst = var.uri.path else: dst = var.uri env['OUTPUT_DST_{}'.format(idx)] = dst env['USER_PROJECT'] = user_project return env
def _get_delocalization_env(self, outputs, user_project): """Return a dict with variables for the 'delocalization' action.""" # Add variables for paths that need to be delocalized, for example: # OUTPUT_COUNT: 1 # OUTPUT_0: MY_OUTPUT_FILE # OUTPUT_RECURSIVE_0: 0 # OUTPUT_SRC_0: gs://mybucket/mypath/myfile # OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile non_empty_outputs = [var for var in outputs if var.value] env = {'OUTPUT_COUNT': str(len(non_empty_outputs))} for idx, var in enumerate(non_empty_outputs): env['OUTPUT_{}'.format(idx)] = var.name env['OUTPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive)) env['OUTPUT_SRC_{}'.format(idx)] = os.path.join( providers_util.DATA_MOUNT_POINT, var.docker_path) # For wildcard paths, the destination must be a directory if '*' in var.uri.basename: dst = var.uri.path else: dst = var.uri env['OUTPUT_DST_{}'.format(idx)] = dst env['USER_PROJECT'] = user_project return env
[ "Return", "a", "dict", "with", "variables", "for", "the", "delocalization", "action", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L547-L575
[ "def", "_get_delocalization_env", "(", "self", ",", "outputs", ",", "user_project", ")", ":", "# Add variables for paths that need to be delocalized, for example:", "# OUTPUT_COUNT: 1", "# OUTPUT_0: MY_OUTPUT_FILE", "# OUTPUT_RECURSIVE_0: 0", "# OUTPUT_SRC_0: gs://mybucket/mypath/myfile", "# OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile", "non_empty_outputs", "=", "[", "var", "for", "var", "in", "outputs", "if", "var", ".", "value", "]", "env", "=", "{", "'OUTPUT_COUNT'", ":", "str", "(", "len", "(", "non_empty_outputs", ")", ")", "}", "for", "idx", ",", "var", "in", "enumerate", "(", "non_empty_outputs", ")", ":", "env", "[", "'OUTPUT_{}'", ".", "format", "(", "idx", ")", "]", "=", "var", ".", "name", "env", "[", "'OUTPUT_RECURSIVE_{}'", ".", "format", "(", "idx", ")", "]", "=", "str", "(", "int", "(", "var", ".", "recursive", ")", ")", "env", "[", "'OUTPUT_SRC_{}'", ".", "format", "(", "idx", ")", "]", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "var", ".", "docker_path", ")", "# For wildcard paths, the destination must be a directory", "if", "'*'", "in", "var", ".", "uri", ".", "basename", ":", "dst", "=", "var", ".", "uri", ".", "path", "else", ":", "dst", "=", "var", ".", "uri", "env", "[", "'OUTPUT_DST_{}'", ".", "format", "(", "idx", ")", "]", "=", "dst", "env", "[", "'USER_PROJECT'", "]", "=", "user_project", "return", "env" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._build_user_environment
Returns a dictionary of for the user container environment.
dsub/providers/google_v2.py
def _build_user_environment(self, envs, inputs, outputs, mounts): """Returns a dictionary of for the user container environment.""" envs = {env.name: env.value for env in envs} envs.update(providers_util.get_file_environment_variables(inputs)) envs.update(providers_util.get_file_environment_variables(outputs)) envs.update(providers_util.get_file_environment_variables(mounts)) return envs
def _build_user_environment(self, envs, inputs, outputs, mounts): """Returns a dictionary of for the user container environment.""" envs = {env.name: env.value for env in envs} envs.update(providers_util.get_file_environment_variables(inputs)) envs.update(providers_util.get_file_environment_variables(outputs)) envs.update(providers_util.get_file_environment_variables(mounts)) return envs
[ "Returns", "a", "dictionary", "of", "for", "the", "user", "container", "environment", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L577-L583
[ "def", "_build_user_environment", "(", "self", ",", "envs", ",", "inputs", ",", "outputs", ",", "mounts", ")", ":", "envs", "=", "{", "env", ".", "name", ":", "env", ".", "value", "for", "env", "in", "envs", "}", "envs", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "inputs", ")", ")", "envs", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "outputs", ")", ")", "envs", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "mounts", ")", ")", "return", "envs" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._get_mount_actions
Returns a list of two actions per gcs bucket to mount.
dsub/providers/google_v2.py
def _get_mount_actions(self, mounts, mnt_datadisk): """Returns a list of two actions per gcs bucket to mount.""" actions_to_add = [] for mount in mounts: bucket = mount.value[len('gs://'):] mount_path = mount.docker_path actions_to_add.extend([ google_v2_pipelines.build_action( name='mount-{}'.format(bucket), flags=['ENABLE_FUSE', 'RUN_IN_BACKGROUND'], image_uri=_GCSFUSE_IMAGE, mounts=[mnt_datadisk], commands=[ '--implicit-dirs', '--foreground', '-o ro', bucket, os.path.join(providers_util.DATA_MOUNT_POINT, mount_path) ]), google_v2_pipelines.build_action( name='mount-wait-{}'.format(bucket), flags=['ENABLE_FUSE'], image_uri=_GCSFUSE_IMAGE, mounts=[mnt_datadisk], commands=[ 'wait', os.path.join(providers_util.DATA_MOUNT_POINT, mount_path) ]) ]) return actions_to_add
def _get_mount_actions(self, mounts, mnt_datadisk): """Returns a list of two actions per gcs bucket to mount.""" actions_to_add = [] for mount in mounts: bucket = mount.value[len('gs://'):] mount_path = mount.docker_path actions_to_add.extend([ google_v2_pipelines.build_action( name='mount-{}'.format(bucket), flags=['ENABLE_FUSE', 'RUN_IN_BACKGROUND'], image_uri=_GCSFUSE_IMAGE, mounts=[mnt_datadisk], commands=[ '--implicit-dirs', '--foreground', '-o ro', bucket, os.path.join(providers_util.DATA_MOUNT_POINT, mount_path) ]), google_v2_pipelines.build_action( name='mount-wait-{}'.format(bucket), flags=['ENABLE_FUSE'], image_uri=_GCSFUSE_IMAGE, mounts=[mnt_datadisk], commands=[ 'wait', os.path.join(providers_util.DATA_MOUNT_POINT, mount_path) ]) ]) return actions_to_add
[ "Returns", "a", "list", "of", "two", "actions", "per", "gcs", "bucket", "to", "mount", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L585-L611
[ "def", "_get_mount_actions", "(", "self", ",", "mounts", ",", "mnt_datadisk", ")", ":", "actions_to_add", "=", "[", "]", "for", "mount", "in", "mounts", ":", "bucket", "=", "mount", ".", "value", "[", "len", "(", "'gs://'", ")", ":", "]", "mount_path", "=", "mount", ".", "docker_path", "actions_to_add", ".", "extend", "(", "[", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'mount-{}'", ".", "format", "(", "bucket", ")", ",", "flags", "=", "[", "'ENABLE_FUSE'", ",", "'RUN_IN_BACKGROUND'", "]", ",", "image_uri", "=", "_GCSFUSE_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "commands", "=", "[", "'--implicit-dirs'", ",", "'--foreground'", ",", "'-o ro'", ",", "bucket", ",", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "mount_path", ")", "]", ")", ",", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'mount-wait-{}'", ".", "format", "(", "bucket", ")", ",", "flags", "=", "[", "'ENABLE_FUSE'", "]", ",", "image_uri", "=", "_GCSFUSE_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "commands", "=", "[", "'wait'", ",", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "mount_path", ")", "]", ")", "]", ")", "return", "actions_to_add" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._build_pipeline_request
Returns a Pipeline objects for the task.
dsub/providers/google_v2.py
def _build_pipeline_request(self, task_view): """Returns a Pipeline objects for the task.""" job_metadata = task_view.job_metadata job_params = task_view.job_params job_resources = task_view.job_resources task_metadata = task_view.task_descriptors[0].task_metadata task_params = task_view.task_descriptors[0].task_params task_resources = task_view.task_descriptors[0].task_resources # Set up VM-specific variables mnt_datadisk = google_v2_pipelines.build_mount( disk=_DATA_DISK_NAME, path=providers_util.DATA_MOUNT_POINT, read_only=False) scopes = job_resources.scopes or google_base.DEFAULT_SCOPES # Set up the task labels labels = { label.name: label.value if label.value else '' for label in google_base.build_pipeline_labels(job_metadata, task_metadata) | job_params['labels'] | task_params['labels'] } # Set local variables for the core pipeline values script = task_view.job_metadata['script'] user_project = task_view.job_metadata['user-project'] or '' envs = job_params['envs'] | task_params['envs'] inputs = job_params['inputs'] | task_params['inputs'] outputs = job_params['outputs'] | task_params['outputs'] mounts = job_params['mounts'] gcs_mounts = param_util.get_gcs_mounts(mounts) persistent_disk_mount_params = param_util.get_persistent_disk_mounts(mounts) persistent_disks = [ google_v2_pipelines.build_disk( name=disk.name.replace('_', '-'), # Underscores not allowed size_gb=disk.disk_size or job_model.DEFAULT_MOUNTED_DISK_SIZE, source_image=disk.value, disk_type=disk.disk_type or job_model.DEFAULT_DISK_TYPE) for disk in persistent_disk_mount_params ] persistent_disk_mounts = [ google_v2_pipelines.build_mount( disk=persistent_disk.get('name'), path=os.path.join(providers_util.DATA_MOUNT_POINT, persistent_disk_mount_param.docker_path), read_only=True) for persistent_disk, persistent_disk_mount_param in zip( persistent_disks, persistent_disk_mount_params) ] # The list of "actions" (1-based) will be: # 1- continuous copy of log files off to Cloud Storage # 2- prepare the shared mount point (write the user script) # 3- localize objects from Cloud Storage to block storage # 4- execute user command # 5- delocalize objects from block storage to Cloud Storage # 6- final copy of log files off to Cloud Storage # # If the user has requested an SSH server be started, it will be inserted # after logging is started, and all subsequent action numbers above will be # incremented by 1. # If the user has requested to mount one or more buckets, two actions per # bucket will be inserted after the prepare step, and all subsequent action # numbers will be incremented by the number of actions added. # # We need to track the action numbers specifically for the user action and # the final logging action. optional_actions = 0 if job_resources.ssh: optional_actions += 1 mount_actions = self._get_mount_actions(gcs_mounts, mnt_datadisk) optional_actions += len(mount_actions) user_action = 4 + optional_actions final_logging_action = 6 + optional_actions # Set up the commands and environment for the logging actions logging_cmd = _LOGGING_CMD.format( log_cp_fn=_GSUTIL_CP_FN, log_cp_cmd=_LOG_CP_CMD.format( user_action=user_action, logging_action='logging_action')) continuous_logging_cmd = _CONTINUOUS_LOGGING_CMD.format( log_msg_fn=_LOG_MSG_FN, log_cp_fn=_GSUTIL_CP_FN, log_cp_cmd=_LOG_CP_CMD.format( user_action=user_action, logging_action='continuous_logging_action'), final_logging_action=final_logging_action, log_interval=job_resources.log_interval or '60s') logging_env = self._get_logging_env(task_resources.logging_path.uri, user_project) # Set up command and environments for the prepare, localization, user, # and de-localization actions script_path = os.path.join(providers_util.SCRIPT_DIR, script.name) prepare_command = _PREPARE_CMD.format( log_msg_fn=_LOG_MSG_FN, mk_runtime_dirs=_MK_RUNTIME_DIRS_CMD, script_var=_SCRIPT_VARNAME, python_decode_script=_PYTHON_DECODE_SCRIPT, script_path=script_path, mk_io_dirs=_MK_IO_DIRS) prepare_env = self._get_prepare_env(script, task_view, inputs, outputs, mounts) localization_env = self._get_localization_env(inputs, user_project) user_environment = self._build_user_environment(envs, inputs, outputs, mounts) delocalization_env = self._get_delocalization_env(outputs, user_project) # Build the list of actions actions = [] actions.append( google_v2_pipelines.build_action( name='logging', flags='RUN_IN_BACKGROUND', image_uri=_CLOUD_SDK_IMAGE, environment=logging_env, entrypoint='/bin/bash', commands=['-c', continuous_logging_cmd])) if job_resources.ssh: actions.append( google_v2_pipelines.build_action( name='ssh', image_uri=_SSH_IMAGE, mounts=[mnt_datadisk], entrypoint='ssh-server', port_mappings={_DEFAULT_SSH_PORT: _DEFAULT_SSH_PORT}, flags='RUN_IN_BACKGROUND')) actions.append( google_v2_pipelines.build_action( name='prepare', image_uri=_PYTHON_IMAGE, mounts=[mnt_datadisk], environment=prepare_env, entrypoint='/bin/bash', commands=['-c', prepare_command]),) actions.extend(mount_actions) actions.extend([ google_v2_pipelines.build_action( name='localization', image_uri=_CLOUD_SDK_IMAGE, mounts=[mnt_datadisk], environment=localization_env, entrypoint='/bin/bash', commands=[ '-c', _LOCALIZATION_CMD.format( log_msg_fn=_LOG_MSG_FN, recursive_cp_fn=_GSUTIL_RSYNC_FN, cp_fn=_GSUTIL_CP_FN, cp_loop=_LOCALIZATION_LOOP) ]), google_v2_pipelines.build_action( name='user-command', image_uri=job_resources.image, mounts=[mnt_datadisk] + persistent_disk_mounts, environment=user_environment, entrypoint='/usr/bin/env', commands=[ 'bash', '-c', _USER_CMD.format( tmp_dir=providers_util.TMP_DIR, working_dir=providers_util.WORKING_DIR, user_script=script_path) ]), google_v2_pipelines.build_action( name='delocalization', image_uri=_CLOUD_SDK_IMAGE, mounts=[mnt_datadisk], environment=delocalization_env, entrypoint='/bin/bash', commands=[ '-c', _LOCALIZATION_CMD.format( log_msg_fn=_LOG_MSG_FN, recursive_cp_fn=_GSUTIL_RSYNC_FN, cp_fn=_GSUTIL_CP_FN, cp_loop=_DELOCALIZATION_LOOP) ]), google_v2_pipelines.build_action( name='final_logging', flags='ALWAYS_RUN', image_uri=_CLOUD_SDK_IMAGE, environment=logging_env, entrypoint='/bin/bash', commands=['-c', logging_cmd]), ]) assert len(actions) - 2 == user_action assert len(actions) == final_logging_action # Prepare the VM (resources) configuration disks = [ google_v2_pipelines.build_disk( _DATA_DISK_NAME, job_resources.disk_size, source_image=None, disk_type=job_resources.disk_type or job_model.DEFAULT_DISK_TYPE) ] disks.extend(persistent_disks) network = google_v2_pipelines.build_network( job_resources.network, job_resources.subnetwork, job_resources.use_private_address) if job_resources.machine_type: machine_type = job_resources.machine_type elif job_resources.min_cores or job_resources.min_ram: machine_type = GoogleV2CustomMachine.build_machine_type( job_resources.min_cores, job_resources.min_ram) else: machine_type = job_model.DEFAULT_MACHINE_TYPE accelerators = None if job_resources.accelerator_type: accelerators = [ google_v2_pipelines.build_accelerator(job_resources.accelerator_type, job_resources.accelerator_count) ] service_account = google_v2_pipelines.build_service_account( job_resources.service_account or 'default', scopes) resources = google_v2_pipelines.build_resources( self._project, job_resources.regions, google_base.get_zones(job_resources.zones), google_v2_pipelines.build_machine( network=network, machine_type=machine_type, preemptible=job_resources.preemptible, service_account=service_account, boot_disk_size_gb=job_resources.boot_disk_size, disks=disks, accelerators=accelerators, nvidia_driver_version=job_resources.nvidia_driver_version, labels=labels, cpu_platform=job_resources.cpu_platform), ) # Build the pipeline request pipeline = google_v2_pipelines.build_pipeline(actions, resources, None, job_resources.timeout) return {'pipeline': pipeline, 'labels': labels}
def _build_pipeline_request(self, task_view): """Returns a Pipeline objects for the task.""" job_metadata = task_view.job_metadata job_params = task_view.job_params job_resources = task_view.job_resources task_metadata = task_view.task_descriptors[0].task_metadata task_params = task_view.task_descriptors[0].task_params task_resources = task_view.task_descriptors[0].task_resources # Set up VM-specific variables mnt_datadisk = google_v2_pipelines.build_mount( disk=_DATA_DISK_NAME, path=providers_util.DATA_MOUNT_POINT, read_only=False) scopes = job_resources.scopes or google_base.DEFAULT_SCOPES # Set up the task labels labels = { label.name: label.value if label.value else '' for label in google_base.build_pipeline_labels(job_metadata, task_metadata) | job_params['labels'] | task_params['labels'] } # Set local variables for the core pipeline values script = task_view.job_metadata['script'] user_project = task_view.job_metadata['user-project'] or '' envs = job_params['envs'] | task_params['envs'] inputs = job_params['inputs'] | task_params['inputs'] outputs = job_params['outputs'] | task_params['outputs'] mounts = job_params['mounts'] gcs_mounts = param_util.get_gcs_mounts(mounts) persistent_disk_mount_params = param_util.get_persistent_disk_mounts(mounts) persistent_disks = [ google_v2_pipelines.build_disk( name=disk.name.replace('_', '-'), # Underscores not allowed size_gb=disk.disk_size or job_model.DEFAULT_MOUNTED_DISK_SIZE, source_image=disk.value, disk_type=disk.disk_type or job_model.DEFAULT_DISK_TYPE) for disk in persistent_disk_mount_params ] persistent_disk_mounts = [ google_v2_pipelines.build_mount( disk=persistent_disk.get('name'), path=os.path.join(providers_util.DATA_MOUNT_POINT, persistent_disk_mount_param.docker_path), read_only=True) for persistent_disk, persistent_disk_mount_param in zip( persistent_disks, persistent_disk_mount_params) ] # The list of "actions" (1-based) will be: # 1- continuous copy of log files off to Cloud Storage # 2- prepare the shared mount point (write the user script) # 3- localize objects from Cloud Storage to block storage # 4- execute user command # 5- delocalize objects from block storage to Cloud Storage # 6- final copy of log files off to Cloud Storage # # If the user has requested an SSH server be started, it will be inserted # after logging is started, and all subsequent action numbers above will be # incremented by 1. # If the user has requested to mount one or more buckets, two actions per # bucket will be inserted after the prepare step, and all subsequent action # numbers will be incremented by the number of actions added. # # We need to track the action numbers specifically for the user action and # the final logging action. optional_actions = 0 if job_resources.ssh: optional_actions += 1 mount_actions = self._get_mount_actions(gcs_mounts, mnt_datadisk) optional_actions += len(mount_actions) user_action = 4 + optional_actions final_logging_action = 6 + optional_actions # Set up the commands and environment for the logging actions logging_cmd = _LOGGING_CMD.format( log_cp_fn=_GSUTIL_CP_FN, log_cp_cmd=_LOG_CP_CMD.format( user_action=user_action, logging_action='logging_action')) continuous_logging_cmd = _CONTINUOUS_LOGGING_CMD.format( log_msg_fn=_LOG_MSG_FN, log_cp_fn=_GSUTIL_CP_FN, log_cp_cmd=_LOG_CP_CMD.format( user_action=user_action, logging_action='continuous_logging_action'), final_logging_action=final_logging_action, log_interval=job_resources.log_interval or '60s') logging_env = self._get_logging_env(task_resources.logging_path.uri, user_project) # Set up command and environments for the prepare, localization, user, # and de-localization actions script_path = os.path.join(providers_util.SCRIPT_DIR, script.name) prepare_command = _PREPARE_CMD.format( log_msg_fn=_LOG_MSG_FN, mk_runtime_dirs=_MK_RUNTIME_DIRS_CMD, script_var=_SCRIPT_VARNAME, python_decode_script=_PYTHON_DECODE_SCRIPT, script_path=script_path, mk_io_dirs=_MK_IO_DIRS) prepare_env = self._get_prepare_env(script, task_view, inputs, outputs, mounts) localization_env = self._get_localization_env(inputs, user_project) user_environment = self._build_user_environment(envs, inputs, outputs, mounts) delocalization_env = self._get_delocalization_env(outputs, user_project) # Build the list of actions actions = [] actions.append( google_v2_pipelines.build_action( name='logging', flags='RUN_IN_BACKGROUND', image_uri=_CLOUD_SDK_IMAGE, environment=logging_env, entrypoint='/bin/bash', commands=['-c', continuous_logging_cmd])) if job_resources.ssh: actions.append( google_v2_pipelines.build_action( name='ssh', image_uri=_SSH_IMAGE, mounts=[mnt_datadisk], entrypoint='ssh-server', port_mappings={_DEFAULT_SSH_PORT: _DEFAULT_SSH_PORT}, flags='RUN_IN_BACKGROUND')) actions.append( google_v2_pipelines.build_action( name='prepare', image_uri=_PYTHON_IMAGE, mounts=[mnt_datadisk], environment=prepare_env, entrypoint='/bin/bash', commands=['-c', prepare_command]),) actions.extend(mount_actions) actions.extend([ google_v2_pipelines.build_action( name='localization', image_uri=_CLOUD_SDK_IMAGE, mounts=[mnt_datadisk], environment=localization_env, entrypoint='/bin/bash', commands=[ '-c', _LOCALIZATION_CMD.format( log_msg_fn=_LOG_MSG_FN, recursive_cp_fn=_GSUTIL_RSYNC_FN, cp_fn=_GSUTIL_CP_FN, cp_loop=_LOCALIZATION_LOOP) ]), google_v2_pipelines.build_action( name='user-command', image_uri=job_resources.image, mounts=[mnt_datadisk] + persistent_disk_mounts, environment=user_environment, entrypoint='/usr/bin/env', commands=[ 'bash', '-c', _USER_CMD.format( tmp_dir=providers_util.TMP_DIR, working_dir=providers_util.WORKING_DIR, user_script=script_path) ]), google_v2_pipelines.build_action( name='delocalization', image_uri=_CLOUD_SDK_IMAGE, mounts=[mnt_datadisk], environment=delocalization_env, entrypoint='/bin/bash', commands=[ '-c', _LOCALIZATION_CMD.format( log_msg_fn=_LOG_MSG_FN, recursive_cp_fn=_GSUTIL_RSYNC_FN, cp_fn=_GSUTIL_CP_FN, cp_loop=_DELOCALIZATION_LOOP) ]), google_v2_pipelines.build_action( name='final_logging', flags='ALWAYS_RUN', image_uri=_CLOUD_SDK_IMAGE, environment=logging_env, entrypoint='/bin/bash', commands=['-c', logging_cmd]), ]) assert len(actions) - 2 == user_action assert len(actions) == final_logging_action # Prepare the VM (resources) configuration disks = [ google_v2_pipelines.build_disk( _DATA_DISK_NAME, job_resources.disk_size, source_image=None, disk_type=job_resources.disk_type or job_model.DEFAULT_DISK_TYPE) ] disks.extend(persistent_disks) network = google_v2_pipelines.build_network( job_resources.network, job_resources.subnetwork, job_resources.use_private_address) if job_resources.machine_type: machine_type = job_resources.machine_type elif job_resources.min_cores or job_resources.min_ram: machine_type = GoogleV2CustomMachine.build_machine_type( job_resources.min_cores, job_resources.min_ram) else: machine_type = job_model.DEFAULT_MACHINE_TYPE accelerators = None if job_resources.accelerator_type: accelerators = [ google_v2_pipelines.build_accelerator(job_resources.accelerator_type, job_resources.accelerator_count) ] service_account = google_v2_pipelines.build_service_account( job_resources.service_account or 'default', scopes) resources = google_v2_pipelines.build_resources( self._project, job_resources.regions, google_base.get_zones(job_resources.zones), google_v2_pipelines.build_machine( network=network, machine_type=machine_type, preemptible=job_resources.preemptible, service_account=service_account, boot_disk_size_gb=job_resources.boot_disk_size, disks=disks, accelerators=accelerators, nvidia_driver_version=job_resources.nvidia_driver_version, labels=labels, cpu_platform=job_resources.cpu_platform), ) # Build the pipeline request pipeline = google_v2_pipelines.build_pipeline(actions, resources, None, job_resources.timeout) return {'pipeline': pipeline, 'labels': labels}
[ "Returns", "a", "Pipeline", "objects", "for", "the", "task", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L613-L862
[ "def", "_build_pipeline_request", "(", "self", ",", "task_view", ")", ":", "job_metadata", "=", "task_view", ".", "job_metadata", "job_params", "=", "task_view", ".", "job_params", "job_resources", "=", "task_view", ".", "job_resources", "task_metadata", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_metadata", "task_params", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_params", "task_resources", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_resources", "# Set up VM-specific variables", "mnt_datadisk", "=", "google_v2_pipelines", ".", "build_mount", "(", "disk", "=", "_DATA_DISK_NAME", ",", "path", "=", "providers_util", ".", "DATA_MOUNT_POINT", ",", "read_only", "=", "False", ")", "scopes", "=", "job_resources", ".", "scopes", "or", "google_base", ".", "DEFAULT_SCOPES", "# Set up the task labels", "labels", "=", "{", "label", ".", "name", ":", "label", ".", "value", "if", "label", ".", "value", "else", "''", "for", "label", "in", "google_base", ".", "build_pipeline_labels", "(", "job_metadata", ",", "task_metadata", ")", "|", "job_params", "[", "'labels'", "]", "|", "task_params", "[", "'labels'", "]", "}", "# Set local variables for the core pipeline values", "script", "=", "task_view", ".", "job_metadata", "[", "'script'", "]", "user_project", "=", "task_view", ".", "job_metadata", "[", "'user-project'", "]", "or", "''", "envs", "=", "job_params", "[", "'envs'", "]", "|", "task_params", "[", "'envs'", "]", "inputs", "=", "job_params", "[", "'inputs'", "]", "|", "task_params", "[", "'inputs'", "]", "outputs", "=", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", "mounts", "=", "job_params", "[", "'mounts'", "]", "gcs_mounts", "=", "param_util", ".", "get_gcs_mounts", "(", "mounts", ")", "persistent_disk_mount_params", "=", "param_util", ".", "get_persistent_disk_mounts", "(", "mounts", ")", "persistent_disks", "=", "[", "google_v2_pipelines", ".", "build_disk", "(", "name", "=", "disk", ".", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", ",", "# Underscores not allowed", "size_gb", "=", "disk", ".", "disk_size", "or", "job_model", ".", "DEFAULT_MOUNTED_DISK_SIZE", ",", "source_image", "=", "disk", ".", "value", ",", "disk_type", "=", "disk", ".", "disk_type", "or", "job_model", ".", "DEFAULT_DISK_TYPE", ")", "for", "disk", "in", "persistent_disk_mount_params", "]", "persistent_disk_mounts", "=", "[", "google_v2_pipelines", ".", "build_mount", "(", "disk", "=", "persistent_disk", ".", "get", "(", "'name'", ")", ",", "path", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "persistent_disk_mount_param", ".", "docker_path", ")", ",", "read_only", "=", "True", ")", "for", "persistent_disk", ",", "persistent_disk_mount_param", "in", "zip", "(", "persistent_disks", ",", "persistent_disk_mount_params", ")", "]", "# The list of \"actions\" (1-based) will be:", "# 1- continuous copy of log files off to Cloud Storage", "# 2- prepare the shared mount point (write the user script)", "# 3- localize objects from Cloud Storage to block storage", "# 4- execute user command", "# 5- delocalize objects from block storage to Cloud Storage", "# 6- final copy of log files off to Cloud Storage", "#", "# If the user has requested an SSH server be started, it will be inserted", "# after logging is started, and all subsequent action numbers above will be", "# incremented by 1.", "# If the user has requested to mount one or more buckets, two actions per", "# bucket will be inserted after the prepare step, and all subsequent action", "# numbers will be incremented by the number of actions added.", "#", "# We need to track the action numbers specifically for the user action and", "# the final logging action.", "optional_actions", "=", "0", "if", "job_resources", ".", "ssh", ":", "optional_actions", "+=", "1", "mount_actions", "=", "self", ".", "_get_mount_actions", "(", "gcs_mounts", ",", "mnt_datadisk", ")", "optional_actions", "+=", "len", "(", "mount_actions", ")", "user_action", "=", "4", "+", "optional_actions", "final_logging_action", "=", "6", "+", "optional_actions", "# Set up the commands and environment for the logging actions", "logging_cmd", "=", "_LOGGING_CMD", ".", "format", "(", "log_cp_fn", "=", "_GSUTIL_CP_FN", ",", "log_cp_cmd", "=", "_LOG_CP_CMD", ".", "format", "(", "user_action", "=", "user_action", ",", "logging_action", "=", "'logging_action'", ")", ")", "continuous_logging_cmd", "=", "_CONTINUOUS_LOGGING_CMD", ".", "format", "(", "log_msg_fn", "=", "_LOG_MSG_FN", ",", "log_cp_fn", "=", "_GSUTIL_CP_FN", ",", "log_cp_cmd", "=", "_LOG_CP_CMD", ".", "format", "(", "user_action", "=", "user_action", ",", "logging_action", "=", "'continuous_logging_action'", ")", ",", "final_logging_action", "=", "final_logging_action", ",", "log_interval", "=", "job_resources", ".", "log_interval", "or", "'60s'", ")", "logging_env", "=", "self", ".", "_get_logging_env", "(", "task_resources", ".", "logging_path", ".", "uri", ",", "user_project", ")", "# Set up command and environments for the prepare, localization, user,", "# and de-localization actions", "script_path", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "SCRIPT_DIR", ",", "script", ".", "name", ")", "prepare_command", "=", "_PREPARE_CMD", ".", "format", "(", "log_msg_fn", "=", "_LOG_MSG_FN", ",", "mk_runtime_dirs", "=", "_MK_RUNTIME_DIRS_CMD", ",", "script_var", "=", "_SCRIPT_VARNAME", ",", "python_decode_script", "=", "_PYTHON_DECODE_SCRIPT", ",", "script_path", "=", "script_path", ",", "mk_io_dirs", "=", "_MK_IO_DIRS", ")", "prepare_env", "=", "self", ".", "_get_prepare_env", "(", "script", ",", "task_view", ",", "inputs", ",", "outputs", ",", "mounts", ")", "localization_env", "=", "self", ".", "_get_localization_env", "(", "inputs", ",", "user_project", ")", "user_environment", "=", "self", ".", "_build_user_environment", "(", "envs", ",", "inputs", ",", "outputs", ",", "mounts", ")", "delocalization_env", "=", "self", ".", "_get_delocalization_env", "(", "outputs", ",", "user_project", ")", "# Build the list of actions", "actions", "=", "[", "]", "actions", ".", "append", "(", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'logging'", ",", "flags", "=", "'RUN_IN_BACKGROUND'", ",", "image_uri", "=", "_CLOUD_SDK_IMAGE", ",", "environment", "=", "logging_env", ",", "entrypoint", "=", "'/bin/bash'", ",", "commands", "=", "[", "'-c'", ",", "continuous_logging_cmd", "]", ")", ")", "if", "job_resources", ".", "ssh", ":", "actions", ".", "append", "(", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'ssh'", ",", "image_uri", "=", "_SSH_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "entrypoint", "=", "'ssh-server'", ",", "port_mappings", "=", "{", "_DEFAULT_SSH_PORT", ":", "_DEFAULT_SSH_PORT", "}", ",", "flags", "=", "'RUN_IN_BACKGROUND'", ")", ")", "actions", ".", "append", "(", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'prepare'", ",", "image_uri", "=", "_PYTHON_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "environment", "=", "prepare_env", ",", "entrypoint", "=", "'/bin/bash'", ",", "commands", "=", "[", "'-c'", ",", "prepare_command", "]", ")", ",", ")", "actions", ".", "extend", "(", "mount_actions", ")", "actions", ".", "extend", "(", "[", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'localization'", ",", "image_uri", "=", "_CLOUD_SDK_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "environment", "=", "localization_env", ",", "entrypoint", "=", "'/bin/bash'", ",", "commands", "=", "[", "'-c'", ",", "_LOCALIZATION_CMD", ".", "format", "(", "log_msg_fn", "=", "_LOG_MSG_FN", ",", "recursive_cp_fn", "=", "_GSUTIL_RSYNC_FN", ",", "cp_fn", "=", "_GSUTIL_CP_FN", ",", "cp_loop", "=", "_LOCALIZATION_LOOP", ")", "]", ")", ",", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'user-command'", ",", "image_uri", "=", "job_resources", ".", "image", ",", "mounts", "=", "[", "mnt_datadisk", "]", "+", "persistent_disk_mounts", ",", "environment", "=", "user_environment", ",", "entrypoint", "=", "'/usr/bin/env'", ",", "commands", "=", "[", "'bash'", ",", "'-c'", ",", "_USER_CMD", ".", "format", "(", "tmp_dir", "=", "providers_util", ".", "TMP_DIR", ",", "working_dir", "=", "providers_util", ".", "WORKING_DIR", ",", "user_script", "=", "script_path", ")", "]", ")", ",", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'delocalization'", ",", "image_uri", "=", "_CLOUD_SDK_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "environment", "=", "delocalization_env", ",", "entrypoint", "=", "'/bin/bash'", ",", "commands", "=", "[", "'-c'", ",", "_LOCALIZATION_CMD", ".", "format", "(", "log_msg_fn", "=", "_LOG_MSG_FN", ",", "recursive_cp_fn", "=", "_GSUTIL_RSYNC_FN", ",", "cp_fn", "=", "_GSUTIL_CP_FN", ",", "cp_loop", "=", "_DELOCALIZATION_LOOP", ")", "]", ")", ",", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'final_logging'", ",", "flags", "=", "'ALWAYS_RUN'", ",", "image_uri", "=", "_CLOUD_SDK_IMAGE", ",", "environment", "=", "logging_env", ",", "entrypoint", "=", "'/bin/bash'", ",", "commands", "=", "[", "'-c'", ",", "logging_cmd", "]", ")", ",", "]", ")", "assert", "len", "(", "actions", ")", "-", "2", "==", "user_action", "assert", "len", "(", "actions", ")", "==", "final_logging_action", "# Prepare the VM (resources) configuration", "disks", "=", "[", "google_v2_pipelines", ".", "build_disk", "(", "_DATA_DISK_NAME", ",", "job_resources", ".", "disk_size", ",", "source_image", "=", "None", ",", "disk_type", "=", "job_resources", ".", "disk_type", "or", "job_model", ".", "DEFAULT_DISK_TYPE", ")", "]", "disks", ".", "extend", "(", "persistent_disks", ")", "network", "=", "google_v2_pipelines", ".", "build_network", "(", "job_resources", ".", "network", ",", "job_resources", ".", "subnetwork", ",", "job_resources", ".", "use_private_address", ")", "if", "job_resources", ".", "machine_type", ":", "machine_type", "=", "job_resources", ".", "machine_type", "elif", "job_resources", ".", "min_cores", "or", "job_resources", ".", "min_ram", ":", "machine_type", "=", "GoogleV2CustomMachine", ".", "build_machine_type", "(", "job_resources", ".", "min_cores", ",", "job_resources", ".", "min_ram", ")", "else", ":", "machine_type", "=", "job_model", ".", "DEFAULT_MACHINE_TYPE", "accelerators", "=", "None", "if", "job_resources", ".", "accelerator_type", ":", "accelerators", "=", "[", "google_v2_pipelines", ".", "build_accelerator", "(", "job_resources", ".", "accelerator_type", ",", "job_resources", ".", "accelerator_count", ")", "]", "service_account", "=", "google_v2_pipelines", ".", "build_service_account", "(", "job_resources", ".", "service_account", "or", "'default'", ",", "scopes", ")", "resources", "=", "google_v2_pipelines", ".", "build_resources", "(", "self", ".", "_project", ",", "job_resources", ".", "regions", ",", "google_base", ".", "get_zones", "(", "job_resources", ".", "zones", ")", ",", "google_v2_pipelines", ".", "build_machine", "(", "network", "=", "network", ",", "machine_type", "=", "machine_type", ",", "preemptible", "=", "job_resources", ".", "preemptible", ",", "service_account", "=", "service_account", ",", "boot_disk_size_gb", "=", "job_resources", ".", "boot_disk_size", ",", "disks", "=", "disks", ",", "accelerators", "=", "accelerators", ",", "nvidia_driver_version", "=", "job_resources", ".", "nvidia_driver_version", ",", "labels", "=", "labels", ",", "cpu_platform", "=", "job_resources", ".", "cpu_platform", ")", ",", ")", "# Build the pipeline request", "pipeline", "=", "google_v2_pipelines", ".", "build_pipeline", "(", "actions", ",", "resources", ",", "None", ",", "job_resources", ".", "timeout", ")", "return", "{", "'pipeline'", ":", "pipeline", ",", "'labels'", ":", "labels", "}" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider.submit_job
Submit the job (or tasks) to be executed. Args: job_descriptor: all parameters needed to launch all job tasks skip_if_output_present: (boolean) if true, skip tasks whose output is present (see --skip flag for more explanation). Returns: A dictionary containing the 'user-id', 'job-id', and 'task-id' list. For jobs that are not task array jobs, the task-id list should be empty. Raises: ValueError: if job resources or task data contain illegal values.
dsub/providers/google_v2.py
def submit_job(self, job_descriptor, skip_if_output_present): """Submit the job (or tasks) to be executed. Args: job_descriptor: all parameters needed to launch all job tasks skip_if_output_present: (boolean) if true, skip tasks whose output is present (see --skip flag for more explanation). Returns: A dictionary containing the 'user-id', 'job-id', and 'task-id' list. For jobs that are not task array jobs, the task-id list should be empty. Raises: ValueError: if job resources or task data contain illegal values. """ # Validate task data and resources. param_util.validate_submit_args_or_fail( job_descriptor, provider_name=_PROVIDER_NAME, input_providers=_SUPPORTED_INPUT_PROVIDERS, output_providers=_SUPPORTED_OUTPUT_PROVIDERS, logging_providers=_SUPPORTED_LOGGING_PROVIDERS) # Prepare and submit jobs. launched_tasks = [] requests = [] for task_view in job_model.task_view_generator(job_descriptor): job_params = task_view.job_params task_params = task_view.task_descriptors[0].task_params outputs = job_params['outputs'] | task_params['outputs'] if skip_if_output_present: # check whether the output's already there if dsub_util.outputs_are_present(outputs): print('Skipping task because its outputs are present') continue request = self._build_pipeline_request(task_view) if self._dry_run: requests.append(request) else: task_id = self._submit_pipeline(request) launched_tasks.append(task_id) # If this is a dry-run, emit all the pipeline request objects if self._dry_run: print( json.dumps( requests, indent=2, sort_keys=True, separators=(',', ': '))) if not requests and not launched_tasks: return {'job-id': dsub_util.NO_JOB} return { 'job-id': job_descriptor.job_metadata['job-id'], 'user-id': job_descriptor.job_metadata['user-id'], 'task-id': [task_id for task_id in launched_tasks if task_id], }
def submit_job(self, job_descriptor, skip_if_output_present): """Submit the job (or tasks) to be executed. Args: job_descriptor: all parameters needed to launch all job tasks skip_if_output_present: (boolean) if true, skip tasks whose output is present (see --skip flag for more explanation). Returns: A dictionary containing the 'user-id', 'job-id', and 'task-id' list. For jobs that are not task array jobs, the task-id list should be empty. Raises: ValueError: if job resources or task data contain illegal values. """ # Validate task data and resources. param_util.validate_submit_args_or_fail( job_descriptor, provider_name=_PROVIDER_NAME, input_providers=_SUPPORTED_INPUT_PROVIDERS, output_providers=_SUPPORTED_OUTPUT_PROVIDERS, logging_providers=_SUPPORTED_LOGGING_PROVIDERS) # Prepare and submit jobs. launched_tasks = [] requests = [] for task_view in job_model.task_view_generator(job_descriptor): job_params = task_view.job_params task_params = task_view.task_descriptors[0].task_params outputs = job_params['outputs'] | task_params['outputs'] if skip_if_output_present: # check whether the output's already there if dsub_util.outputs_are_present(outputs): print('Skipping task because its outputs are present') continue request = self._build_pipeline_request(task_view) if self._dry_run: requests.append(request) else: task_id = self._submit_pipeline(request) launched_tasks.append(task_id) # If this is a dry-run, emit all the pipeline request objects if self._dry_run: print( json.dumps( requests, indent=2, sort_keys=True, separators=(',', ': '))) if not requests and not launched_tasks: return {'job-id': dsub_util.NO_JOB} return { 'job-id': job_descriptor.job_metadata['job-id'], 'user-id': job_descriptor.job_metadata['user-id'], 'task-id': [task_id for task_id in launched_tasks if task_id], }
[ "Submit", "the", "job", "(", "or", "tasks", ")", "to", "be", "executed", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L872-L931
[ "def", "submit_job", "(", "self", ",", "job_descriptor", ",", "skip_if_output_present", ")", ":", "# Validate task data and resources.", "param_util", ".", "validate_submit_args_or_fail", "(", "job_descriptor", ",", "provider_name", "=", "_PROVIDER_NAME", ",", "input_providers", "=", "_SUPPORTED_INPUT_PROVIDERS", ",", "output_providers", "=", "_SUPPORTED_OUTPUT_PROVIDERS", ",", "logging_providers", "=", "_SUPPORTED_LOGGING_PROVIDERS", ")", "# Prepare and submit jobs.", "launched_tasks", "=", "[", "]", "requests", "=", "[", "]", "for", "task_view", "in", "job_model", ".", "task_view_generator", "(", "job_descriptor", ")", ":", "job_params", "=", "task_view", ".", "job_params", "task_params", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_params", "outputs", "=", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", "if", "skip_if_output_present", ":", "# check whether the output's already there", "if", "dsub_util", ".", "outputs_are_present", "(", "outputs", ")", ":", "print", "(", "'Skipping task because its outputs are present'", ")", "continue", "request", "=", "self", ".", "_build_pipeline_request", "(", "task_view", ")", "if", "self", ".", "_dry_run", ":", "requests", ".", "append", "(", "request", ")", "else", ":", "task_id", "=", "self", ".", "_submit_pipeline", "(", "request", ")", "launched_tasks", ".", "append", "(", "task_id", ")", "# If this is a dry-run, emit all the pipeline request objects", "if", "self", ".", "_dry_run", ":", "print", "(", "json", ".", "dumps", "(", "requests", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", ")", "if", "not", "requests", "and", "not", "launched_tasks", ":", "return", "{", "'job-id'", ":", "dsub_util", ".", "NO_JOB", "}", "return", "{", "'job-id'", ":", "job_descriptor", ".", "job_metadata", "[", "'job-id'", "]", ",", "'user-id'", ":", "job_descriptor", ".", "job_metadata", "[", "'user-id'", "]", ",", "'task-id'", ":", "[", "task_id", "for", "task_id", "in", "launched_tasks", "if", "task_id", "]", ",", "}" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider._operations_list
Gets the list of operations for the specified filter. Args: ops_filter: string filter of operations to return max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) page_token: page token returned by a previous _operations_list call. Returns: Operations matching the filter criteria.
dsub/providers/google_v2.py
def _operations_list(self, ops_filter, max_tasks, page_size, page_token): """Gets the list of operations for the specified filter. Args: ops_filter: string filter of operations to return max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) page_token: page token returned by a previous _operations_list call. Returns: Operations matching the filter criteria. """ # We are not using the documented default page size of 256, # nor allowing for the maximum page size of 2048 as larger page sizes # currently cause the operations.list() API to return an error: # HttpError 429 ... Resource has been exhausted (e.g. check quota). max_page_size = 128 # Set the page size to the smallest (non-zero) size we can page_size = min(sz for sz in [page_size, max_page_size, max_tasks] if sz) # Execute operations.list() and return all of the dsub operations api = self._service.projects().operations().list( name='projects/{}/operations'.format(self._project), filter=ops_filter, pageToken=page_token, pageSize=page_size) response = google_base.Api.execute(api) return [ GoogleOperation(op) for op in response.get('operations', []) if google_v2_operations.is_dsub_operation(op) ], response.get('nextPageToken')
def _operations_list(self, ops_filter, max_tasks, page_size, page_token): """Gets the list of operations for the specified filter. Args: ops_filter: string filter of operations to return max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the number of operations to requested on each list operation to the pipelines API (if 0 or None, the API default is used) page_token: page token returned by a previous _operations_list call. Returns: Operations matching the filter criteria. """ # We are not using the documented default page size of 256, # nor allowing for the maximum page size of 2048 as larger page sizes # currently cause the operations.list() API to return an error: # HttpError 429 ... Resource has been exhausted (e.g. check quota). max_page_size = 128 # Set the page size to the smallest (non-zero) size we can page_size = min(sz for sz in [page_size, max_page_size, max_tasks] if sz) # Execute operations.list() and return all of the dsub operations api = self._service.projects().operations().list( name='projects/{}/operations'.format(self._project), filter=ops_filter, pageToken=page_token, pageSize=page_size) response = google_base.Api.execute(api) return [ GoogleOperation(op) for op in response.get('operations', []) if google_v2_operations.is_dsub_operation(op) ], response.get('nextPageToken')
[ "Gets", "the", "list", "of", "operations", "for", "the", "specified", "filter", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1029-L1064
[ "def", "_operations_list", "(", "self", ",", "ops_filter", ",", "max_tasks", ",", "page_size", ",", "page_token", ")", ":", "# We are not using the documented default page size of 256,", "# nor allowing for the maximum page size of 2048 as larger page sizes", "# currently cause the operations.list() API to return an error:", "# HttpError 429 ... Resource has been exhausted (e.g. check quota).", "max_page_size", "=", "128", "# Set the page size to the smallest (non-zero) size we can", "page_size", "=", "min", "(", "sz", "for", "sz", "in", "[", "page_size", ",", "max_page_size", ",", "max_tasks", "]", "if", "sz", ")", "# Execute operations.list() and return all of the dsub operations", "api", "=", "self", ".", "_service", ".", "projects", "(", ")", ".", "operations", "(", ")", ".", "list", "(", "name", "=", "'projects/{}/operations'", ".", "format", "(", "self", ".", "_project", ")", ",", "filter", "=", "ops_filter", ",", "pageToken", "=", "page_token", ",", "pageSize", "=", "page_size", ")", "response", "=", "google_base", ".", "Api", ".", "execute", "(", "api", ")", "return", "[", "GoogleOperation", "(", "op", ")", "for", "op", "in", "response", ".", "get", "(", "'operations'", ",", "[", "]", ")", "if", "google_v2_operations", ".", "is_dsub_operation", "(", "op", ")", "]", ",", "response", ".", "get", "(", "'nextPageToken'", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2JobProvider.lookup_job_tasks
Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings are 'RUNNING', 'SUCCESS', 'FAILURE', or 'CANCELED'. user_ids: a list of ids for the user(s) who launched the job. job_ids: a list of job ids to return. job_names: a list of job names to return. task_ids: a list of specific tasks within the specified job(s) to return. task_attempts: a list of specific attempts within the specified tasks(s) to return. labels: a list of LabelParam with user-added labels. All labels must match the task being fetched. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the page size to use for each query to the pipelins API. Raises: ValueError: if both a job id list and a job name list are provided Yeilds: Genomics API Operations objects.
dsub/providers/google_v2.py
def lookup_job_tasks(self, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create_time_min=None, create_time_max=None, max_tasks=0, page_size=0): """Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings are 'RUNNING', 'SUCCESS', 'FAILURE', or 'CANCELED'. user_ids: a list of ids for the user(s) who launched the job. job_ids: a list of job ids to return. job_names: a list of job names to return. task_ids: a list of specific tasks within the specified job(s) to return. task_attempts: a list of specific attempts within the specified tasks(s) to return. labels: a list of LabelParam with user-added labels. All labels must match the task being fetched. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the page size to use for each query to the pipelins API. Raises: ValueError: if both a job id list and a job name list are provided Yeilds: Genomics API Operations objects. """ # Build a filter for operations to return ops_filter = self._build_query_filter( statuses, user_ids, job_ids, job_names, task_ids, task_attempts, labels, create_time_min, create_time_max) # Execute the operations.list() API to get batches of operations to yield page_token = None tasks_yielded = 0 while True: # If max_tasks is set, let operations.list() know not to send more than # we need. max_to_fetch = None if max_tasks: max_to_fetch = max_tasks - tasks_yielded ops, page_token = self._operations_list(ops_filter, max_to_fetch, page_size, page_token) for op in ops: yield op tasks_yielded += 1 assert (max_tasks >= tasks_yielded or not max_tasks) if not page_token or 0 < max_tasks <= tasks_yielded: break
def lookup_job_tasks(self, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create_time_min=None, create_time_max=None, max_tasks=0, page_size=0): """Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings are 'RUNNING', 'SUCCESS', 'FAILURE', or 'CANCELED'. user_ids: a list of ids for the user(s) who launched the job. job_ids: a list of job ids to return. job_names: a list of job names to return. task_ids: a list of specific tasks within the specified job(s) to return. task_attempts: a list of specific attempts within the specified tasks(s) to return. labels: a list of LabelParam with user-added labels. All labels must match the task being fetched. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. max_tasks: the maximum number of job tasks to return or 0 for no limit. page_size: the page size to use for each query to the pipelins API. Raises: ValueError: if both a job id list and a job name list are provided Yeilds: Genomics API Operations objects. """ # Build a filter for operations to return ops_filter = self._build_query_filter( statuses, user_ids, job_ids, job_names, task_ids, task_attempts, labels, create_time_min, create_time_max) # Execute the operations.list() API to get batches of operations to yield page_token = None tasks_yielded = 0 while True: # If max_tasks is set, let operations.list() know not to send more than # we need. max_to_fetch = None if max_tasks: max_to_fetch = max_tasks - tasks_yielded ops, page_token = self._operations_list(ops_filter, max_to_fetch, page_size, page_token) for op in ops: yield op tasks_yielded += 1 assert (max_tasks >= tasks_yielded or not max_tasks) if not page_token or 0 < max_tasks <= tasks_yielded: break
[ "Yields", "operations", "based", "on", "the", "input", "criteria", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1066-L1132
[ "def", "lookup_job_tasks", "(", "self", ",", "statuses", ",", "user_ids", "=", "None", ",", "job_ids", "=", "None", ",", "job_names", "=", "None", ",", "task_ids", "=", "None", ",", "task_attempts", "=", "None", ",", "labels", "=", "None", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ",", "max_tasks", "=", "0", ",", "page_size", "=", "0", ")", ":", "# Build a filter for operations to return", "ops_filter", "=", "self", ".", "_build_query_filter", "(", "statuses", ",", "user_ids", ",", "job_ids", ",", "job_names", ",", "task_ids", ",", "task_attempts", ",", "labels", ",", "create_time_min", ",", "create_time_max", ")", "# Execute the operations.list() API to get batches of operations to yield", "page_token", "=", "None", "tasks_yielded", "=", "0", "while", "True", ":", "# If max_tasks is set, let operations.list() know not to send more than", "# we need.", "max_to_fetch", "=", "None", "if", "max_tasks", ":", "max_to_fetch", "=", "max_tasks", "-", "tasks_yielded", "ops", ",", "page_token", "=", "self", ".", "_operations_list", "(", "ops_filter", ",", "max_to_fetch", ",", "page_size", ",", "page_token", ")", "for", "op", "in", "ops", ":", "yield", "op", "tasks_yielded", "+=", "1", "assert", "(", "max_tasks", ">=", "tasks_yielded", "or", "not", "max_tasks", ")", "if", "not", "page_token", "or", "0", "<", "max_tasks", "<=", "tasks_yielded", ":", "break" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation._operation_status
Returns the status of this operation. Raises: ValueError: if the operation status cannot be determined. Returns: A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE).
dsub/providers/google_v2.py
def _operation_status(self): """Returns the status of this operation. Raises: ValueError: if the operation status cannot be determined. Returns: A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE). """ if not google_v2_operations.is_done(self._op): return 'RUNNING' if google_v2_operations.is_success(self._op): return 'SUCCESS' if google_v2_operations.is_canceled(self._op): return 'CANCELED' if google_v2_operations.is_failed(self._op): return 'FAILURE' raise ValueError('Status for operation {} could not be determined'.format( self._op['name']))
def _operation_status(self): """Returns the status of this operation. Raises: ValueError: if the operation status cannot be determined. Returns: A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE). """ if not google_v2_operations.is_done(self._op): return 'RUNNING' if google_v2_operations.is_success(self._op): return 'SUCCESS' if google_v2_operations.is_canceled(self._op): return 'CANCELED' if google_v2_operations.is_failed(self._op): return 'FAILURE' raise ValueError('Status for operation {} could not be determined'.format( self._op['name']))
[ "Returns", "the", "status", "of", "this", "operation", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1204-L1223
[ "def", "_operation_status", "(", "self", ")", ":", "if", "not", "google_v2_operations", ".", "is_done", "(", "self", ".", "_op", ")", ":", "return", "'RUNNING'", "if", "google_v2_operations", ".", "is_success", "(", "self", ".", "_op", ")", ":", "return", "'SUCCESS'", "if", "google_v2_operations", ".", "is_canceled", "(", "self", ".", "_op", ")", ":", "return", "'CANCELED'", "if", "google_v2_operations", ".", "is_failed", "(", "self", ".", "_op", ")", ":", "return", "'FAILURE'", "raise", "ValueError", "(", "'Status for operation {} could not be determined'", ".", "format", "(", "self", ".", "_op", "[", "'name'", "]", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation._operation_status_message
Returns the most relevant status string and failed action. This string is meant for display only. Returns: A printable status string and name of failed action (if any).
dsub/providers/google_v2.py
def _operation_status_message(self): """Returns the most relevant status string and failed action. This string is meant for display only. Returns: A printable status string and name of failed action (if any). """ msg = None action = None if not google_v2_operations.is_done(self._op): last_event = google_v2_operations.get_last_event(self._op) if last_event: msg = last_event['description'] action_id = last_event.get('details', {}).get('actionId') if action_id: action = google_v2_operations.get_action_by_id(self._op, action_id) else: msg = 'Pending' else: failed_events = google_v2_operations.get_failed_events(self._op) if failed_events: failed_event = failed_events[-1] msg = failed_event.get('details', {}).get('stderr') action_id = failed_event.get('details', {}).get('actionId') if action_id: action = google_v2_operations.get_action_by_id(self._op, action_id) if not msg: error = google_v2_operations.get_error(self._op) if error: msg = error['message'] else: msg = 'Success' return msg, action
def _operation_status_message(self): """Returns the most relevant status string and failed action. This string is meant for display only. Returns: A printable status string and name of failed action (if any). """ msg = None action = None if not google_v2_operations.is_done(self._op): last_event = google_v2_operations.get_last_event(self._op) if last_event: msg = last_event['description'] action_id = last_event.get('details', {}).get('actionId') if action_id: action = google_v2_operations.get_action_by_id(self._op, action_id) else: msg = 'Pending' else: failed_events = google_v2_operations.get_failed_events(self._op) if failed_events: failed_event = failed_events[-1] msg = failed_event.get('details', {}).get('stderr') action_id = failed_event.get('details', {}).get('actionId') if action_id: action = google_v2_operations.get_action_by_id(self._op, action_id) if not msg: error = google_v2_operations.get_error(self._op) if error: msg = error['message'] else: msg = 'Success' return msg, action
[ "Returns", "the", "most", "relevant", "status", "string", "and", "failed", "action", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1225-L1259
[ "def", "_operation_status_message", "(", "self", ")", ":", "msg", "=", "None", "action", "=", "None", "if", "not", "google_v2_operations", ".", "is_done", "(", "self", ".", "_op", ")", ":", "last_event", "=", "google_v2_operations", ".", "get_last_event", "(", "self", ".", "_op", ")", "if", "last_event", ":", "msg", "=", "last_event", "[", "'description'", "]", "action_id", "=", "last_event", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'actionId'", ")", "if", "action_id", ":", "action", "=", "google_v2_operations", ".", "get_action_by_id", "(", "self", ".", "_op", ",", "action_id", ")", "else", ":", "msg", "=", "'Pending'", "else", ":", "failed_events", "=", "google_v2_operations", ".", "get_failed_events", "(", "self", ".", "_op", ")", "if", "failed_events", ":", "failed_event", "=", "failed_events", "[", "-", "1", "]", "msg", "=", "failed_event", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'stderr'", ")", "action_id", "=", "failed_event", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'actionId'", ")", "if", "action_id", ":", "action", "=", "google_v2_operations", ".", "get_action_by_id", "(", "self", ".", "_op", ",", "action_id", ")", "if", "not", "msg", ":", "error", "=", "google_v2_operations", ".", "get_error", "(", "self", ".", "_op", ")", "if", "error", ":", "msg", "=", "error", "[", "'message'", "]", "else", ":", "msg", "=", "'Success'", "return", "msg", ",", "action" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation.error_message
Returns an error message if the operation failed for any reason. Failure as defined here means ended for any reason other than 'success'. This means that a successful cancelation will also return an error message. Returns: string, string will be empty if job did not error.
dsub/providers/google_v2.py
def error_message(self): """Returns an error message if the operation failed for any reason. Failure as defined here means ended for any reason other than 'success'. This means that a successful cancelation will also return an error message. Returns: string, string will be empty if job did not error. """ error = google_v2_operations.get_error(self._op) if error: job_id = self.get_field('job-id') task_id = self.get_field('task-id') task_str = job_id if task_id is None else '{} (task: {})'.format( job_id, task_id) return 'Error in {} - code {}: {}'.format(task_str, error['code'], error['message']) return ''
def error_message(self): """Returns an error message if the operation failed for any reason. Failure as defined here means ended for any reason other than 'success'. This means that a successful cancelation will also return an error message. Returns: string, string will be empty if job did not error. """ error = google_v2_operations.get_error(self._op) if error: job_id = self.get_field('job-id') task_id = self.get_field('task-id') task_str = job_id if task_id is None else '{} (task: {})'.format( job_id, task_id) return 'Error in {} - code {}: {}'.format(task_str, error['code'], error['message']) return ''
[ "Returns", "an", "error", "message", "if", "the", "operation", "failed", "for", "any", "reason", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1261-L1280
[ "def", "error_message", "(", "self", ")", ":", "error", "=", "google_v2_operations", ".", "get_error", "(", "self", ".", "_op", ")", "if", "error", ":", "job_id", "=", "self", ".", "get_field", "(", "'job-id'", ")", "task_id", "=", "self", ".", "get_field", "(", "'task-id'", ")", "task_str", "=", "job_id", "if", "task_id", "is", "None", "else", "'{} (task: {})'", ".", "format", "(", "job_id", ",", "task_id", ")", "return", "'Error in {} - code {}: {}'", ".", "format", "(", "task_str", ",", "error", "[", "'code'", "]", ",", "error", "[", "'message'", "]", ")", "return", "''" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleOperation.get_field
Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'inputs'. Raises: ValueError: if the field label is not supported by the operation
dsub/providers/google_v2.py
def get_field(self, field, default=None): """Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'inputs'. Raises: ValueError: if the field label is not supported by the operation """ value = None if field == 'internal-id': value = self._op['name'] elif field == 'user-project': if self._job_descriptor: value = self._job_descriptor.job_metadata.get(field) elif field in [ 'job-id', 'job-name', 'task-id', 'task-attempt', 'user-id', 'dsub-version' ]: value = google_v2_operations.get_label(self._op, field) elif field == 'task-status': value = self._operation_status() elif field == 'logging': if self._job_descriptor: # The job_resources will contain the "--logging" value. # The task_resources will contain the resolved logging path. # Return the resolved logging path. task_resources = self._job_descriptor.task_descriptors[0].task_resources value = task_resources.logging_path elif field in ['envs', 'labels']: if self._job_descriptor: items = providers_util.get_job_and_task_param( self._job_descriptor.job_params, self._job_descriptor.task_descriptors[0].task_params, field) value = {item.name: item.value for item in items} elif field in [ 'inputs', 'outputs', 'input-recursives', 'output-recursives' ]: if self._job_descriptor: value = {} items = providers_util.get_job_and_task_param( self._job_descriptor.job_params, self._job_descriptor.task_descriptors[0].task_params, field) value.update({item.name: item.value for item in items}) elif field == 'mounts': if self._job_descriptor: items = providers_util.get_job_and_task_param( self._job_descriptor.job_params, self._job_descriptor.task_descriptors[0].task_params, field) value = {item.name: item.value for item in items} elif field == 'create-time': ds = google_v2_operations.get_create_time(self._op) value = google_base.parse_rfc3339_utc_string(ds) elif field == 'start-time': ds = google_v2_operations.get_start_time(self._op) if ds: value = google_base.parse_rfc3339_utc_string(ds) elif field == 'end-time': ds = google_v2_operations.get_end_time(self._op) if ds: value = google_base.parse_rfc3339_utc_string(ds) elif field == 'status': value = self._operation_status() elif field == 'status-message': msg, action = self._operation_status_message() if msg.startswith('Execution failed:'): # msg may look something like # "Execution failed: action 2: pulling image..." # Emit the actual message ("pulling image...") msg = msg.split(': ', 2)[-1] value = msg elif field == 'status-detail': msg, action = self._operation_status_message() if action: value = '{}:\n{}'.format(action.get('name'), msg) else: value = msg elif field == 'last-update': last_update = google_v2_operations.get_last_update(self._op) if last_update: value = google_base.parse_rfc3339_utc_string(last_update) elif field == 'provider': return _PROVIDER_NAME elif field == 'provider-attributes': value = {} # The VM instance name and zone can be found in the WorkerAssignedEvent. # For a given operation, this may have occurred multiple times, so be # sure to grab the most recent. assigned_events = google_v2_operations.get_worker_assigned_events( self._op) if assigned_events: details = assigned_events[0].get('details', {}) value['instance-name'] = details.get('instance') value['zone'] = details.get('zone') # The rest of the information comes from the request itself. resources = google_v2_operations.get_resources(self._op) if 'regions' in resources: value['regions'] = resources['regions'] if 'zones' in resources: value['zones'] = resources['zones'] if 'virtualMachine' in resources: vm = resources['virtualMachine'] value['machine-type'] = vm.get('machineType') value['preemptible'] = vm.get('preemptible') value['boot-disk-size'] = vm.get('bootDiskSizeGb') value['network'] = vm.get('network', {}).get('name') value['subnetwork'] = vm.get('network', {}).get('subnetwork') value['use_private_address'] = vm.get('network', {}).get('usePrivateAddress') value['cpu_platform'] = vm.get('cpuPlatform') value['accelerators'] = vm.get('accelerators') value['service-account'] = vm.get('serviceAccount', {}).get('email') if 'disks' in vm: datadisk = next( (d for d in vm['disks'] if d['name'] == _DATA_DISK_NAME)) if datadisk: value['disk-size'] = datadisk.get('sizeGb') value['disk-type'] = datadisk.get('type') elif field == 'events': value = GoogleV2EventMap(self._op).get_filtered_normalized_events() elif field == 'script-name': if self._job_descriptor: value = self._job_descriptor.job_metadata.get(field) elif field == 'script': value = self._try_op_to_script_body() else: raise ValueError('Unsupported field: "%s"' % field) return value if value else default
def get_field(self, field, default=None): """Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'inputs'. Raises: ValueError: if the field label is not supported by the operation """ value = None if field == 'internal-id': value = self._op['name'] elif field == 'user-project': if self._job_descriptor: value = self._job_descriptor.job_metadata.get(field) elif field in [ 'job-id', 'job-name', 'task-id', 'task-attempt', 'user-id', 'dsub-version' ]: value = google_v2_operations.get_label(self._op, field) elif field == 'task-status': value = self._operation_status() elif field == 'logging': if self._job_descriptor: # The job_resources will contain the "--logging" value. # The task_resources will contain the resolved logging path. # Return the resolved logging path. task_resources = self._job_descriptor.task_descriptors[0].task_resources value = task_resources.logging_path elif field in ['envs', 'labels']: if self._job_descriptor: items = providers_util.get_job_and_task_param( self._job_descriptor.job_params, self._job_descriptor.task_descriptors[0].task_params, field) value = {item.name: item.value for item in items} elif field in [ 'inputs', 'outputs', 'input-recursives', 'output-recursives' ]: if self._job_descriptor: value = {} items = providers_util.get_job_and_task_param( self._job_descriptor.job_params, self._job_descriptor.task_descriptors[0].task_params, field) value.update({item.name: item.value for item in items}) elif field == 'mounts': if self._job_descriptor: items = providers_util.get_job_and_task_param( self._job_descriptor.job_params, self._job_descriptor.task_descriptors[0].task_params, field) value = {item.name: item.value for item in items} elif field == 'create-time': ds = google_v2_operations.get_create_time(self._op) value = google_base.parse_rfc3339_utc_string(ds) elif field == 'start-time': ds = google_v2_operations.get_start_time(self._op) if ds: value = google_base.parse_rfc3339_utc_string(ds) elif field == 'end-time': ds = google_v2_operations.get_end_time(self._op) if ds: value = google_base.parse_rfc3339_utc_string(ds) elif field == 'status': value = self._operation_status() elif field == 'status-message': msg, action = self._operation_status_message() if msg.startswith('Execution failed:'): # msg may look something like # "Execution failed: action 2: pulling image..." # Emit the actual message ("pulling image...") msg = msg.split(': ', 2)[-1] value = msg elif field == 'status-detail': msg, action = self._operation_status_message() if action: value = '{}:\n{}'.format(action.get('name'), msg) else: value = msg elif field == 'last-update': last_update = google_v2_operations.get_last_update(self._op) if last_update: value = google_base.parse_rfc3339_utc_string(last_update) elif field == 'provider': return _PROVIDER_NAME elif field == 'provider-attributes': value = {} # The VM instance name and zone can be found in the WorkerAssignedEvent. # For a given operation, this may have occurred multiple times, so be # sure to grab the most recent. assigned_events = google_v2_operations.get_worker_assigned_events( self._op) if assigned_events: details = assigned_events[0].get('details', {}) value['instance-name'] = details.get('instance') value['zone'] = details.get('zone') # The rest of the information comes from the request itself. resources = google_v2_operations.get_resources(self._op) if 'regions' in resources: value['regions'] = resources['regions'] if 'zones' in resources: value['zones'] = resources['zones'] if 'virtualMachine' in resources: vm = resources['virtualMachine'] value['machine-type'] = vm.get('machineType') value['preemptible'] = vm.get('preemptible') value['boot-disk-size'] = vm.get('bootDiskSizeGb') value['network'] = vm.get('network', {}).get('name') value['subnetwork'] = vm.get('network', {}).get('subnetwork') value['use_private_address'] = vm.get('network', {}).get('usePrivateAddress') value['cpu_platform'] = vm.get('cpuPlatform') value['accelerators'] = vm.get('accelerators') value['service-account'] = vm.get('serviceAccount', {}).get('email') if 'disks' in vm: datadisk = next( (d for d in vm['disks'] if d['name'] == _DATA_DISK_NAME)) if datadisk: value['disk-size'] = datadisk.get('sizeGb') value['disk-type'] = datadisk.get('type') elif field == 'events': value = GoogleV2EventMap(self._op).get_filtered_normalized_events() elif field == 'script-name': if self._job_descriptor: value = self._job_descriptor.job_metadata.get(field) elif field == 'script': value = self._try_op_to_script_body() else: raise ValueError('Unsupported field: "%s"' % field) return value if value else default
[ "Returns", "a", "value", "from", "the", "operation", "for", "a", "specific", "set", "of", "field", "names", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1282-L1419
[ "def", "get_field", "(", "self", ",", "field", ",", "default", "=", "None", ")", ":", "value", "=", "None", "if", "field", "==", "'internal-id'", ":", "value", "=", "self", ".", "_op", "[", "'name'", "]", "elif", "field", "==", "'user-project'", ":", "if", "self", ".", "_job_descriptor", ":", "value", "=", "self", ".", "_job_descriptor", ".", "job_metadata", ".", "get", "(", "field", ")", "elif", "field", "in", "[", "'job-id'", ",", "'job-name'", ",", "'task-id'", ",", "'task-attempt'", ",", "'user-id'", ",", "'dsub-version'", "]", ":", "value", "=", "google_v2_operations", ".", "get_label", "(", "self", ".", "_op", ",", "field", ")", "elif", "field", "==", "'task-status'", ":", "value", "=", "self", ".", "_operation_status", "(", ")", "elif", "field", "==", "'logging'", ":", "if", "self", ".", "_job_descriptor", ":", "# The job_resources will contain the \"--logging\" value.", "# The task_resources will contain the resolved logging path.", "# Return the resolved logging path.", "task_resources", "=", "self", ".", "_job_descriptor", ".", "task_descriptors", "[", "0", "]", ".", "task_resources", "value", "=", "task_resources", ".", "logging_path", "elif", "field", "in", "[", "'envs'", ",", "'labels'", "]", ":", "if", "self", ".", "_job_descriptor", ":", "items", "=", "providers_util", ".", "get_job_and_task_param", "(", "self", ".", "_job_descriptor", ".", "job_params", ",", "self", ".", "_job_descriptor", ".", "task_descriptors", "[", "0", "]", ".", "task_params", ",", "field", ")", "value", "=", "{", "item", ".", "name", ":", "item", ".", "value", "for", "item", "in", "items", "}", "elif", "field", "in", "[", "'inputs'", ",", "'outputs'", ",", "'input-recursives'", ",", "'output-recursives'", "]", ":", "if", "self", ".", "_job_descriptor", ":", "value", "=", "{", "}", "items", "=", "providers_util", ".", "get_job_and_task_param", "(", "self", ".", "_job_descriptor", ".", "job_params", ",", "self", ".", "_job_descriptor", ".", "task_descriptors", "[", "0", "]", ".", "task_params", ",", "field", ")", "value", ".", "update", "(", "{", "item", ".", "name", ":", "item", ".", "value", "for", "item", "in", "items", "}", ")", "elif", "field", "==", "'mounts'", ":", "if", "self", ".", "_job_descriptor", ":", "items", "=", "providers_util", ".", "get_job_and_task_param", "(", "self", ".", "_job_descriptor", ".", "job_params", ",", "self", ".", "_job_descriptor", ".", "task_descriptors", "[", "0", "]", ".", "task_params", ",", "field", ")", "value", "=", "{", "item", ".", "name", ":", "item", ".", "value", "for", "item", "in", "items", "}", "elif", "field", "==", "'create-time'", ":", "ds", "=", "google_v2_operations", ".", "get_create_time", "(", "self", ".", "_op", ")", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "ds", ")", "elif", "field", "==", "'start-time'", ":", "ds", "=", "google_v2_operations", ".", "get_start_time", "(", "self", ".", "_op", ")", "if", "ds", ":", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "ds", ")", "elif", "field", "==", "'end-time'", ":", "ds", "=", "google_v2_operations", ".", "get_end_time", "(", "self", ".", "_op", ")", "if", "ds", ":", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "ds", ")", "elif", "field", "==", "'status'", ":", "value", "=", "self", ".", "_operation_status", "(", ")", "elif", "field", "==", "'status-message'", ":", "msg", ",", "action", "=", "self", ".", "_operation_status_message", "(", ")", "if", "msg", ".", "startswith", "(", "'Execution failed:'", ")", ":", "# msg may look something like", "# \"Execution failed: action 2: pulling image...\"", "# Emit the actual message (\"pulling image...\")", "msg", "=", "msg", ".", "split", "(", "': '", ",", "2", ")", "[", "-", "1", "]", "value", "=", "msg", "elif", "field", "==", "'status-detail'", ":", "msg", ",", "action", "=", "self", ".", "_operation_status_message", "(", ")", "if", "action", ":", "value", "=", "'{}:\\n{}'", ".", "format", "(", "action", ".", "get", "(", "'name'", ")", ",", "msg", ")", "else", ":", "value", "=", "msg", "elif", "field", "==", "'last-update'", ":", "last_update", "=", "google_v2_operations", ".", "get_last_update", "(", "self", ".", "_op", ")", "if", "last_update", ":", "value", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "last_update", ")", "elif", "field", "==", "'provider'", ":", "return", "_PROVIDER_NAME", "elif", "field", "==", "'provider-attributes'", ":", "value", "=", "{", "}", "# The VM instance name and zone can be found in the WorkerAssignedEvent.", "# For a given operation, this may have occurred multiple times, so be", "# sure to grab the most recent.", "assigned_events", "=", "google_v2_operations", ".", "get_worker_assigned_events", "(", "self", ".", "_op", ")", "if", "assigned_events", ":", "details", "=", "assigned_events", "[", "0", "]", ".", "get", "(", "'details'", ",", "{", "}", ")", "value", "[", "'instance-name'", "]", "=", "details", ".", "get", "(", "'instance'", ")", "value", "[", "'zone'", "]", "=", "details", ".", "get", "(", "'zone'", ")", "# The rest of the information comes from the request itself.", "resources", "=", "google_v2_operations", ".", "get_resources", "(", "self", ".", "_op", ")", "if", "'regions'", "in", "resources", ":", "value", "[", "'regions'", "]", "=", "resources", "[", "'regions'", "]", "if", "'zones'", "in", "resources", ":", "value", "[", "'zones'", "]", "=", "resources", "[", "'zones'", "]", "if", "'virtualMachine'", "in", "resources", ":", "vm", "=", "resources", "[", "'virtualMachine'", "]", "value", "[", "'machine-type'", "]", "=", "vm", ".", "get", "(", "'machineType'", ")", "value", "[", "'preemptible'", "]", "=", "vm", ".", "get", "(", "'preemptible'", ")", "value", "[", "'boot-disk-size'", "]", "=", "vm", ".", "get", "(", "'bootDiskSizeGb'", ")", "value", "[", "'network'", "]", "=", "vm", ".", "get", "(", "'network'", ",", "{", "}", ")", ".", "get", "(", "'name'", ")", "value", "[", "'subnetwork'", "]", "=", "vm", ".", "get", "(", "'network'", ",", "{", "}", ")", ".", "get", "(", "'subnetwork'", ")", "value", "[", "'use_private_address'", "]", "=", "vm", ".", "get", "(", "'network'", ",", "{", "}", ")", ".", "get", "(", "'usePrivateAddress'", ")", "value", "[", "'cpu_platform'", "]", "=", "vm", ".", "get", "(", "'cpuPlatform'", ")", "value", "[", "'accelerators'", "]", "=", "vm", ".", "get", "(", "'accelerators'", ")", "value", "[", "'service-account'", "]", "=", "vm", ".", "get", "(", "'serviceAccount'", ",", "{", "}", ")", ".", "get", "(", "'email'", ")", "if", "'disks'", "in", "vm", ":", "datadisk", "=", "next", "(", "(", "d", "for", "d", "in", "vm", "[", "'disks'", "]", "if", "d", "[", "'name'", "]", "==", "_DATA_DISK_NAME", ")", ")", "if", "datadisk", ":", "value", "[", "'disk-size'", "]", "=", "datadisk", ".", "get", "(", "'sizeGb'", ")", "value", "[", "'disk-type'", "]", "=", "datadisk", ".", "get", "(", "'type'", ")", "elif", "field", "==", "'events'", ":", "value", "=", "GoogleV2EventMap", "(", "self", ".", "_op", ")", ".", "get_filtered_normalized_events", "(", ")", "elif", "field", "==", "'script-name'", ":", "if", "self", ".", "_job_descriptor", ":", "value", "=", "self", ".", "_job_descriptor", ".", "job_metadata", ".", "get", "(", "field", ")", "elif", "field", "==", "'script'", ":", "value", "=", "self", ".", "_try_op_to_script_body", "(", ")", "else", ":", "raise", "ValueError", "(", "'Unsupported field: \"%s\"'", "%", "field", ")", "return", "value", "if", "value", "else", "default" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2CustomMachine._validate_ram
Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE.
dsub/providers/google_v2.py
def _validate_ram(ram_in_mb): """Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE.""" return int(GoogleV2CustomMachine._MEMORY_MULTIPLE * math.ceil( ram_in_mb / GoogleV2CustomMachine._MEMORY_MULTIPLE))
def _validate_ram(ram_in_mb): """Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE.""" return int(GoogleV2CustomMachine._MEMORY_MULTIPLE * math.ceil( ram_in_mb / GoogleV2CustomMachine._MEMORY_MULTIPLE))
[ "Rounds", "ram", "up", "to", "the", "nearest", "multiple", "of", "_MEMORY_MULTIPLE", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1445-L1448
[ "def", "_validate_ram", "(", "ram_in_mb", ")", ":", "return", "int", "(", "GoogleV2CustomMachine", ".", "_MEMORY_MULTIPLE", "*", "math", ".", "ceil", "(", "ram_in_mb", "/", "GoogleV2CustomMachine", ".", "_MEMORY_MULTIPLE", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
GoogleV2CustomMachine.build_machine_type
Returns a custom machine type string.
dsub/providers/google_v2.py
def build_machine_type(cls, min_cores, min_ram): """Returns a custom machine type string.""" min_cores = min_cores or job_model.DEFAULT_MIN_CORES min_ram = min_ram or job_model.DEFAULT_MIN_RAM # First, min_ram is given in GB. Convert to MB. min_ram *= GoogleV2CustomMachine._MB_PER_GB # Only machine types with 1 vCPU or an even number of vCPUs can be created. cores = cls._validate_cores(min_cores) # The total memory of the instance must be a multiple of 256 MB. ram = cls._validate_ram(min_ram) # Memory must be between 0.9 GB per vCPU, up to 6.5 GB per vCPU. memory_to_cpu_ratio = ram / cores if memory_to_cpu_ratio < GoogleV2CustomMachine._MIN_MEMORY_PER_CPU: # If we're under the ratio, top up the memory. adjusted_ram = GoogleV2CustomMachine._MIN_MEMORY_PER_CPU * cores ram = cls._validate_ram(adjusted_ram) elif memory_to_cpu_ratio > GoogleV2CustomMachine._MAX_MEMORY_PER_CPU: # If we're over the ratio, top up the CPU. adjusted_cores = math.ceil( ram / GoogleV2CustomMachine._MAX_MEMORY_PER_CPU) cores = cls._validate_cores(adjusted_cores) else: # Ratio is within the restrictions - no adjustments needed. pass return 'custom-{}-{}'.format(int(cores), int(ram))
def build_machine_type(cls, min_cores, min_ram): """Returns a custom machine type string.""" min_cores = min_cores or job_model.DEFAULT_MIN_CORES min_ram = min_ram or job_model.DEFAULT_MIN_RAM # First, min_ram is given in GB. Convert to MB. min_ram *= GoogleV2CustomMachine._MB_PER_GB # Only machine types with 1 vCPU or an even number of vCPUs can be created. cores = cls._validate_cores(min_cores) # The total memory of the instance must be a multiple of 256 MB. ram = cls._validate_ram(min_ram) # Memory must be between 0.9 GB per vCPU, up to 6.5 GB per vCPU. memory_to_cpu_ratio = ram / cores if memory_to_cpu_ratio < GoogleV2CustomMachine._MIN_MEMORY_PER_CPU: # If we're under the ratio, top up the memory. adjusted_ram = GoogleV2CustomMachine._MIN_MEMORY_PER_CPU * cores ram = cls._validate_ram(adjusted_ram) elif memory_to_cpu_ratio > GoogleV2CustomMachine._MAX_MEMORY_PER_CPU: # If we're over the ratio, top up the CPU. adjusted_cores = math.ceil( ram / GoogleV2CustomMachine._MAX_MEMORY_PER_CPU) cores = cls._validate_cores(adjusted_cores) else: # Ratio is within the restrictions - no adjustments needed. pass return 'custom-{}-{}'.format(int(cores), int(ram))
[ "Returns", "a", "custom", "machine", "type", "string", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1451-L1482
[ "def", "build_machine_type", "(", "cls", ",", "min_cores", ",", "min_ram", ")", ":", "min_cores", "=", "min_cores", "or", "job_model", ".", "DEFAULT_MIN_CORES", "min_ram", "=", "min_ram", "or", "job_model", ".", "DEFAULT_MIN_RAM", "# First, min_ram is given in GB. Convert to MB.", "min_ram", "*=", "GoogleV2CustomMachine", ".", "_MB_PER_GB", "# Only machine types with 1 vCPU or an even number of vCPUs can be created.", "cores", "=", "cls", ".", "_validate_cores", "(", "min_cores", ")", "# The total memory of the instance must be a multiple of 256 MB.", "ram", "=", "cls", ".", "_validate_ram", "(", "min_ram", ")", "# Memory must be between 0.9 GB per vCPU, up to 6.5 GB per vCPU.", "memory_to_cpu_ratio", "=", "ram", "/", "cores", "if", "memory_to_cpu_ratio", "<", "GoogleV2CustomMachine", ".", "_MIN_MEMORY_PER_CPU", ":", "# If we're under the ratio, top up the memory.", "adjusted_ram", "=", "GoogleV2CustomMachine", ".", "_MIN_MEMORY_PER_CPU", "*", "cores", "ram", "=", "cls", ".", "_validate_ram", "(", "adjusted_ram", ")", "elif", "memory_to_cpu_ratio", ">", "GoogleV2CustomMachine", ".", "_MAX_MEMORY_PER_CPU", ":", "# If we're over the ratio, top up the CPU.", "adjusted_cores", "=", "math", ".", "ceil", "(", "ram", "/", "GoogleV2CustomMachine", ".", "_MAX_MEMORY_PER_CPU", ")", "cores", "=", "cls", ".", "_validate_cores", "(", "adjusted_cores", ")", "else", ":", "# Ratio is within the restrictions - no adjustments needed.", "pass", "return", "'custom-{}-{}'", ".", "format", "(", "int", "(", "cores", ")", ",", "int", "(", "ram", ")", ")" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7
valid
build_machine
Build a VirtualMachine object for a Pipeline request. Args: network (dict): Network details for the pipeline to run in. machine_type (str): GCE Machine Type string for the pipeline. preemptible (bool): Use a preemptible VM for the job. service_account (dict): Service account configuration for the VM. boot_disk_size_gb (int): Boot disk size in GB. disks (list[dict]): List of disks to mount. accelerators (list[dict]): List of accelerators to attach to the VM. labels (dict[string, string]): Labels for the VM. cpu_platform (str): The CPU platform to request. nvidia_driver_version (str): The NVIDIA driver version to use when attaching an NVIDIA GPU accelerator. Returns: An object representing a VirtualMachine.
dsub/providers/google_v2_pipelines.py
def build_machine(network=None, machine_type=None, preemptible=None, service_account=None, boot_disk_size_gb=None, disks=None, accelerators=None, labels=None, cpu_platform=None, nvidia_driver_version=None): """Build a VirtualMachine object for a Pipeline request. Args: network (dict): Network details for the pipeline to run in. machine_type (str): GCE Machine Type string for the pipeline. preemptible (bool): Use a preemptible VM for the job. service_account (dict): Service account configuration for the VM. boot_disk_size_gb (int): Boot disk size in GB. disks (list[dict]): List of disks to mount. accelerators (list[dict]): List of accelerators to attach to the VM. labels (dict[string, string]): Labels for the VM. cpu_platform (str): The CPU platform to request. nvidia_driver_version (str): The NVIDIA driver version to use when attaching an NVIDIA GPU accelerator. Returns: An object representing a VirtualMachine. """ return { 'network': network, 'machineType': machine_type, 'preemptible': preemptible, 'serviceAccount': service_account, 'bootDiskSizeGb': boot_disk_size_gb, 'disks': disks, 'accelerators': accelerators, 'labels': labels, 'cpuPlatform': cpu_platform, 'nvidiaDriverVersion': nvidia_driver_version, }
def build_machine(network=None, machine_type=None, preemptible=None, service_account=None, boot_disk_size_gb=None, disks=None, accelerators=None, labels=None, cpu_platform=None, nvidia_driver_version=None): """Build a VirtualMachine object for a Pipeline request. Args: network (dict): Network details for the pipeline to run in. machine_type (str): GCE Machine Type string for the pipeline. preemptible (bool): Use a preemptible VM for the job. service_account (dict): Service account configuration for the VM. boot_disk_size_gb (int): Boot disk size in GB. disks (list[dict]): List of disks to mount. accelerators (list[dict]): List of accelerators to attach to the VM. labels (dict[string, string]): Labels for the VM. cpu_platform (str): The CPU platform to request. nvidia_driver_version (str): The NVIDIA driver version to use when attaching an NVIDIA GPU accelerator. Returns: An object representing a VirtualMachine. """ return { 'network': network, 'machineType': machine_type, 'preemptible': preemptible, 'serviceAccount': service_account, 'bootDiskSizeGb': boot_disk_size_gb, 'disks': disks, 'accelerators': accelerators, 'labels': labels, 'cpuPlatform': cpu_platform, 'nvidiaDriverVersion': nvidia_driver_version, }
[ "Build", "a", "VirtualMachine", "object", "for", "a", "Pipeline", "request", "." ]
DataBiosphere/dsub
python
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_pipelines.py#L50-L89
[ "def", "build_machine", "(", "network", "=", "None", ",", "machine_type", "=", "None", ",", "preemptible", "=", "None", ",", "service_account", "=", "None", ",", "boot_disk_size_gb", "=", "None", ",", "disks", "=", "None", ",", "accelerators", "=", "None", ",", "labels", "=", "None", ",", "cpu_platform", "=", "None", ",", "nvidia_driver_version", "=", "None", ")", ":", "return", "{", "'network'", ":", "network", ",", "'machineType'", ":", "machine_type", ",", "'preemptible'", ":", "preemptible", ",", "'serviceAccount'", ":", "service_account", ",", "'bootDiskSizeGb'", ":", "boot_disk_size_gb", ",", "'disks'", ":", "disks", ",", "'accelerators'", ":", "accelerators", ",", "'labels'", ":", "labels", ",", "'cpuPlatform'", ":", "cpu_platform", ",", "'nvidiaDriverVersion'", ":", "nvidia_driver_version", ",", "}" ]
443ce31daa6023dc2fd65ef2051796e19d18d5a7