repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
spotify/luigi
luigi/tools/range.py
RangeByMinutesBase.finite_datetimes
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to a whole number of minutes intervals. """ # Validate that the minutes_interval can divide 60 and it is greater than 0 and lesser than 60 if not (0 < self.minutes_interval < 60): raise ParameterException('minutes-interval must be within 0..60') if (60 / self.minutes_interval) * self.minutes_interval != 60: raise ParameterException('minutes-interval does not evenly divide 60') # start of a complete interval, e.g. 20:13 and the interval is 5 -> 20:10 start_minute = int(finite_start.minute/self.minutes_interval)*self.minutes_interval datehour_start = datetime( year=finite_start.year, month=finite_start.month, day=finite_start.day, hour=finite_start.hour, minute=start_minute) datehours = [] for i in itertools.count(): t = datehour_start + timedelta(minutes=i*self.minutes_interval) if t >= finite_stop: return datehours if t >= finite_start: datehours.append(t)
python
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to a whole number of minutes intervals. """ # Validate that the minutes_interval can divide 60 and it is greater than 0 and lesser than 60 if not (0 < self.minutes_interval < 60): raise ParameterException('minutes-interval must be within 0..60') if (60 / self.minutes_interval) * self.minutes_interval != 60: raise ParameterException('minutes-interval does not evenly divide 60') # start of a complete interval, e.g. 20:13 and the interval is 5 -> 20:10 start_minute = int(finite_start.minute/self.minutes_interval)*self.minutes_interval datehour_start = datetime( year=finite_start.year, month=finite_start.month, day=finite_start.day, hour=finite_start.hour, minute=start_minute) datehours = [] for i in itertools.count(): t = datehour_start + timedelta(minutes=i*self.minutes_interval) if t >= finite_stop: return datehours if t >= finite_start: datehours.append(t)
[ "def", "finite_datetimes", "(", "self", ",", "finite_start", ",", "finite_stop", ")", ":", "# Validate that the minutes_interval can divide 60 and it is greater than 0 and lesser than 60", "if", "not", "(", "0", "<", "self", ".", "minutes_interval", "<", "60", ")", ":", "raise", "ParameterException", "(", "'minutes-interval must be within 0..60'", ")", "if", "(", "60", "/", "self", ".", "minutes_interval", ")", "*", "self", ".", "minutes_interval", "!=", "60", ":", "raise", "ParameterException", "(", "'minutes-interval does not evenly divide 60'", ")", "# start of a complete interval, e.g. 20:13 and the interval is 5 -> 20:10", "start_minute", "=", "int", "(", "finite_start", ".", "minute", "/", "self", ".", "minutes_interval", ")", "*", "self", ".", "minutes_interval", "datehour_start", "=", "datetime", "(", "year", "=", "finite_start", ".", "year", ",", "month", "=", "finite_start", ".", "month", ",", "day", "=", "finite_start", ".", "day", ",", "hour", "=", "finite_start", ".", "hour", ",", "minute", "=", "start_minute", ")", "datehours", "=", "[", "]", "for", "i", "in", "itertools", ".", "count", "(", ")", ":", "t", "=", "datehour_start", "+", "timedelta", "(", "minutes", "=", "i", "*", "self", ".", "minutes_interval", ")", "if", "t", ">=", "finite_stop", ":", "return", "datehours", "if", "t", ">=", "finite_start", ":", "datehours", ".", "append", "(", "t", ")" ]
Simply returns the points in time that correspond to a whole number of minutes intervals.
[ "Simply", "returns", "the", "points", "in", "time", "that", "correspond", "to", "a", "whole", "number", "of", "minutes", "intervals", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L462-L485
train
spotify/luigi
luigi/tools/range.py
RangeMonthly.finite_datetimes
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to turn of month. """ start_date = self._align(finite_start) aligned_stop = self._align(finite_stop) dates = [] for m in itertools.count(): t = start_date + relativedelta(months=m) if t >= aligned_stop: return dates if t >= finite_start: dates.append(t)
python
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to turn of month. """ start_date = self._align(finite_start) aligned_stop = self._align(finite_stop) dates = [] for m in itertools.count(): t = start_date + relativedelta(months=m) if t >= aligned_stop: return dates if t >= finite_start: dates.append(t)
[ "def", "finite_datetimes", "(", "self", ",", "finite_start", ",", "finite_stop", ")", ":", "start_date", "=", "self", ".", "_align", "(", "finite_start", ")", "aligned_stop", "=", "self", ".", "_align", "(", "finite_stop", ")", "dates", "=", "[", "]", "for", "m", "in", "itertools", ".", "count", "(", ")", ":", "t", "=", "start_date", "+", "relativedelta", "(", "months", "=", "m", ")", "if", "t", ">=", "aligned_stop", ":", "return", "dates", "if", "t", ">=", "finite_start", ":", "dates", ".", "append", "(", "t", ")" ]
Simply returns the points in time that correspond to turn of month.
[ "Simply", "returns", "the", "points", "in", "time", "that", "correspond", "to", "turn", "of", "month", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L709-L721
train
spotify/luigi
luigi/contrib/mssqldb.py
MSSqlTarget.touch
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() if connection is None: connection = self.connect() connection.execute_non_query( """IF NOT EXISTS(SELECT 1 FROM {marker_table} WHERE update_id = %(update_id)s) INSERT INTO {marker_table} (update_id, target_table) VALUES (%(update_id)s, %(table)s) ELSE UPDATE t SET target_table = %(table)s , inserted = GETDATE() FROM {marker_table} t WHERE update_id = %(update_id)s """.format(marker_table=self.marker_table), {"update_id": self.update_id, "table": self.table}) # make sure update is properly marked assert self.exists(connection)
python
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() if connection is None: connection = self.connect() connection.execute_non_query( """IF NOT EXISTS(SELECT 1 FROM {marker_table} WHERE update_id = %(update_id)s) INSERT INTO {marker_table} (update_id, target_table) VALUES (%(update_id)s, %(table)s) ELSE UPDATE t SET target_table = %(table)s , inserted = GETDATE() FROM {marker_table} t WHERE update_id = %(update_id)s """.format(marker_table=self.marker_table), {"update_id": self.update_id, "table": self.table}) # make sure update is properly marked assert self.exists(connection)
[ "def", "touch", "(", "self", ",", "connection", "=", "None", ")", ":", "self", ".", "create_marker_table", "(", ")", "if", "connection", "is", "None", ":", "connection", "=", "self", ".", "connect", "(", ")", "connection", ".", "execute_non_query", "(", "\"\"\"IF NOT EXISTS(SELECT 1\n FROM {marker_table}\n WHERE update_id = %(update_id)s)\n INSERT INTO {marker_table} (update_id, target_table)\n VALUES (%(update_id)s, %(table)s)\n ELSE\n UPDATE t\n SET target_table = %(table)s\n , inserted = GETDATE()\n FROM {marker_table} t\n WHERE update_id = %(update_id)s\n \"\"\"", ".", "format", "(", "marker_table", "=", "self", ".", "marker_table", ")", ",", "{", "\"update_id\"", ":", "self", ".", "update_id", ",", "\"table\"", ":", "self", ".", "table", "}", ")", "# make sure update is properly marked", "assert", "self", ".", "exists", "(", "connection", ")" ]
Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created.
[ "Mark", "this", "update", "as", "complete", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mssqldb.py#L71-L100
train
spotify/luigi
luigi/contrib/mssqldb.py
MSSqlTarget.connect
def connect(self): """ Create a SQL Server connection and return a connection object """ connection = _mssql.connect(user=self.user, password=self.password, server=self.host, port=self.port, database=self.database) return connection
python
def connect(self): """ Create a SQL Server connection and return a connection object """ connection = _mssql.connect(user=self.user, password=self.password, server=self.host, port=self.port, database=self.database) return connection
[ "def", "connect", "(", "self", ")", ":", "connection", "=", "_mssql", ".", "connect", "(", "user", "=", "self", ".", "user", ",", "password", "=", "self", ".", "password", ",", "server", "=", "self", ".", "host", ",", "port", "=", "self", ".", "port", ",", "database", "=", "self", ".", "database", ")", "return", "connection" ]
Create a SQL Server connection and return a connection object
[ "Create", "a", "SQL", "Server", "connection", "and", "return", "a", "connection", "object" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mssqldb.py#L119-L128
train
spotify/luigi
luigi/contrib/mssqldb.py
MSSqlTarget.create_marker_table
def create_marker_table(self): """ Create marker table if it doesn't exist. Use a separate connection since the transaction might have to be reset. """ connection = self.connect() try: connection.execute_non_query( """ CREATE TABLE {marker_table} ( id BIGINT NOT NULL IDENTITY(1,1), update_id VARCHAR(128) NOT NULL, target_table VARCHAR(128), inserted DATETIME DEFAULT(GETDATE()), PRIMARY KEY (update_id) ) """ .format(marker_table=self.marker_table) ) except _mssql.MSSQLDatabaseException as e: # Table already exists code if e.number == 2714: pass else: raise connection.close()
python
def create_marker_table(self): """ Create marker table if it doesn't exist. Use a separate connection since the transaction might have to be reset. """ connection = self.connect() try: connection.execute_non_query( """ CREATE TABLE {marker_table} ( id BIGINT NOT NULL IDENTITY(1,1), update_id VARCHAR(128) NOT NULL, target_table VARCHAR(128), inserted DATETIME DEFAULT(GETDATE()), PRIMARY KEY (update_id) ) """ .format(marker_table=self.marker_table) ) except _mssql.MSSQLDatabaseException as e: # Table already exists code if e.number == 2714: pass else: raise connection.close()
[ "def", "create_marker_table", "(", "self", ")", ":", "connection", "=", "self", ".", "connect", "(", ")", "try", ":", "connection", ".", "execute_non_query", "(", "\"\"\" CREATE TABLE {marker_table} (\n id BIGINT NOT NULL IDENTITY(1,1),\n update_id VARCHAR(128) NOT NULL,\n target_table VARCHAR(128),\n inserted DATETIME DEFAULT(GETDATE()),\n PRIMARY KEY (update_id)\n )\n \"\"\"", ".", "format", "(", "marker_table", "=", "self", ".", "marker_table", ")", ")", "except", "_mssql", ".", "MSSQLDatabaseException", "as", "e", ":", "# Table already exists code", "if", "e", ".", "number", "==", "2714", ":", "pass", "else", ":", "raise", "connection", ".", "close", "(", ")" ]
Create marker table if it doesn't exist. Use a separate connection since the transaction might have to be reset.
[ "Create", "marker", "table", "if", "it", "doesn", "t", "exist", ".", "Use", "a", "separate", "connection", "since", "the", "transaction", "might", "have", "to", "be", "reset", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mssqldb.py#L130-L154
train
spotify/luigi
luigi/contrib/opener.py
OpenerRegistry.get_opener
def get_opener(self, name): """Retrieve an opener for the given protocol :param name: name of the opener to open :type name: string :raises NoOpenerError: if no opener has been registered of that name """ if name not in self.registry: raise NoOpenerError("No opener for %s" % name) index = self.registry[name] return self.openers[index]
python
def get_opener(self, name): """Retrieve an opener for the given protocol :param name: name of the opener to open :type name: string :raises NoOpenerError: if no opener has been registered of that name """ if name not in self.registry: raise NoOpenerError("No opener for %s" % name) index = self.registry[name] return self.openers[index]
[ "def", "get_opener", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "registry", ":", "raise", "NoOpenerError", "(", "\"No opener for %s\"", "%", "name", ")", "index", "=", "self", ".", "registry", "[", "name", "]", "return", "self", ".", "openers", "[", "index", "]" ]
Retrieve an opener for the given protocol :param name: name of the opener to open :type name: string :raises NoOpenerError: if no opener has been registered of that name
[ "Retrieve", "an", "opener", "for", "the", "given", "protocol" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/opener.py#L89-L100
train
spotify/luigi
luigi/contrib/opener.py
OpenerRegistry.add
def add(self, opener): """Adds an opener to the registry :param opener: Opener object :type opener: Opener inherited object """ index = len(self.openers) self.openers[index] = opener for name in opener.names: self.registry[name] = index
python
def add(self, opener): """Adds an opener to the registry :param opener: Opener object :type opener: Opener inherited object """ index = len(self.openers) self.openers[index] = opener for name in opener.names: self.registry[name] = index
[ "def", "add", "(", "self", ",", "opener", ")", ":", "index", "=", "len", "(", "self", ".", "openers", ")", "self", ".", "openers", "[", "index", "]", "=", "opener", "for", "name", "in", "opener", ".", "names", ":", "self", ".", "registry", "[", "name", "]", "=", "index" ]
Adds an opener to the registry :param opener: Opener object :type opener: Opener inherited object
[ "Adds", "an", "opener", "to", "the", "registry" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/opener.py#L102-L113
train
spotify/luigi
luigi/contrib/opener.py
OpenerRegistry.open
def open(self, target_uri, **kwargs): """Open target uri. :param target_uri: Uri to open :type target_uri: string :returns: Target object """ target = urlsplit(target_uri, scheme=self.default_opener) opener = self.get_opener(target.scheme) query = opener.conform_query(target.query) target = opener.get_target( target.scheme, target.path, target.fragment, target.username, target.password, target.hostname, target.port, query, **kwargs ) target.opener_path = target_uri return target
python
def open(self, target_uri, **kwargs): """Open target uri. :param target_uri: Uri to open :type target_uri: string :returns: Target object """ target = urlsplit(target_uri, scheme=self.default_opener) opener = self.get_opener(target.scheme) query = opener.conform_query(target.query) target = opener.get_target( target.scheme, target.path, target.fragment, target.username, target.password, target.hostname, target.port, query, **kwargs ) target.opener_path = target_uri return target
[ "def", "open", "(", "self", ",", "target_uri", ",", "*", "*", "kwargs", ")", ":", "target", "=", "urlsplit", "(", "target_uri", ",", "scheme", "=", "self", ".", "default_opener", ")", "opener", "=", "self", ".", "get_opener", "(", "target", ".", "scheme", ")", "query", "=", "opener", ".", "conform_query", "(", "target", ".", "query", ")", "target", "=", "opener", ".", "get_target", "(", "target", ".", "scheme", ",", "target", ".", "path", ",", "target", ".", "fragment", ",", "target", ".", "username", ",", "target", ".", "password", ",", "target", ".", "hostname", ",", "target", ".", "port", ",", "query", ",", "*", "*", "kwargs", ")", "target", ".", "opener_path", "=", "target_uri", "return", "target" ]
Open target uri. :param target_uri: Uri to open :type target_uri: string :returns: Target object
[ "Open", "target", "uri", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/opener.py#L115-L142
train
spotify/luigi
luigi/contrib/opener.py
Opener.conform_query
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.allowed_kwargs, and cls.filter_kwargs to drive logic. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.allowed_kwargs with values set to True will be parsed as json strings. """ query = parse_qs(query, keep_blank_values=True) # Remove any unexpected keywords from the query string. if cls.filter_kwargs: query = {x: y for x, y in query.items() if x in cls.allowed_kwargs} for key, vals in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values if cls.allowed_kwargs.get(key, False): val = json.loads(vals[0] or 'true') else: val = vals[0] or 'true' query[key] = val return query
python
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.allowed_kwargs, and cls.filter_kwargs to drive logic. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.allowed_kwargs with values set to True will be parsed as json strings. """ query = parse_qs(query, keep_blank_values=True) # Remove any unexpected keywords from the query string. if cls.filter_kwargs: query = {x: y for x, y in query.items() if x in cls.allowed_kwargs} for key, vals in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values if cls.allowed_kwargs.get(key, False): val = json.loads(vals[0] or 'true') else: val = vals[0] or 'true' query[key] = val return query
[ "def", "conform_query", "(", "cls", ",", "query", ")", ":", "query", "=", "parse_qs", "(", "query", ",", "keep_blank_values", "=", "True", ")", "# Remove any unexpected keywords from the query string.", "if", "cls", ".", "filter_kwargs", ":", "query", "=", "{", "x", ":", "y", "for", "x", ",", "y", "in", "query", ".", "items", "(", ")", "if", "x", "in", "cls", ".", "allowed_kwargs", "}", "for", "key", ",", "vals", "in", "query", ".", "items", "(", ")", ":", "# Multiple values of the same name could be passed use first", "# Also params without strings will be treated as true values", "if", "cls", ".", "allowed_kwargs", ".", "get", "(", "key", ",", "False", ")", ":", "val", "=", "json", ".", "loads", "(", "vals", "[", "0", "]", "or", "'true'", ")", "else", ":", "val", "=", "vals", "[", "0", "]", "or", "'true'", "query", "[", "key", "]", "=", "val", "return", "query" ]
Converts the query string from a target uri, uses cls.allowed_kwargs, and cls.filter_kwargs to drive logic. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.allowed_kwargs with values set to True will be parsed as json strings.
[ "Converts", "the", "query", "string", "from", "a", "target", "uri", "uses", "cls", ".", "allowed_kwargs", "and", "cls", ".", "filter_kwargs", "to", "drive", "logic", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/opener.py#L157-L183
train
spotify/luigi
luigi/contrib/opener.py
Opener.get_target
def get_target(cls, scheme, path, fragment, username, password, hostname, port, query, **kwargs): """Override this method to use values from the parsed uri to initialize the expected target. """ raise NotImplementedError("get_target must be overridden")
python
def get_target(cls, scheme, path, fragment, username, password, hostname, port, query, **kwargs): """Override this method to use values from the parsed uri to initialize the expected target. """ raise NotImplementedError("get_target must be overridden")
[ "def", "get_target", "(", "cls", ",", "scheme", ",", "path", ",", "fragment", ",", "username", ",", "password", ",", "hostname", ",", "port", ",", "query", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "\"get_target must be overridden\"", ")" ]
Override this method to use values from the parsed uri to initialize the expected target.
[ "Override", "this", "method", "to", "use", "values", "from", "the", "parsed", "uri", "to", "initialize", "the", "expected", "target", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/opener.py#L186-L192
train
spotify/luigi
luigi/interface.py
_schedule_and_run
def _schedule_and_run(tasks, worker_scheduler_factory=None, override_defaults=None): """ :param tasks: :param worker_scheduler_factory: :param override_defaults: :return: True if all tasks and their dependencies were successfully run (or already completed); False if any error occurred. It will return a detailed response of type LuigiRunResult instead of a boolean if detailed_summary=True. """ if worker_scheduler_factory is None: worker_scheduler_factory = _WorkerSchedulerFactory() if override_defaults is None: override_defaults = {} env_params = core(**override_defaults) InterfaceLogging.setup(env_params) kill_signal = signal.SIGUSR1 if env_params.take_lock else None if (not env_params.no_lock and not(lock.acquire_for(env_params.lock_pid_dir, env_params.lock_size, kill_signal))): raise PidLockAlreadyTakenExit() if env_params.local_scheduler: sch = worker_scheduler_factory.create_local_scheduler() else: if env_params.scheduler_url != '': url = env_params.scheduler_url else: url = 'http://{host}:{port:d}/'.format( host=env_params.scheduler_host, port=env_params.scheduler_port, ) sch = worker_scheduler_factory.create_remote_scheduler(url=url) worker = worker_scheduler_factory.create_worker( scheduler=sch, worker_processes=env_params.workers, assistant=env_params.assistant) success = True logger = logging.getLogger('luigi-interface') with worker: for t in tasks: success &= worker.add(t, env_params.parallel_scheduling, env_params.parallel_scheduling_processes) logger.info('Done scheduling tasks') success &= worker.run() luigi_run_result = LuigiRunResult(worker, success) logger.info(luigi_run_result.summary_text) return luigi_run_result
python
def _schedule_and_run(tasks, worker_scheduler_factory=None, override_defaults=None): """ :param tasks: :param worker_scheduler_factory: :param override_defaults: :return: True if all tasks and their dependencies were successfully run (or already completed); False if any error occurred. It will return a detailed response of type LuigiRunResult instead of a boolean if detailed_summary=True. """ if worker_scheduler_factory is None: worker_scheduler_factory = _WorkerSchedulerFactory() if override_defaults is None: override_defaults = {} env_params = core(**override_defaults) InterfaceLogging.setup(env_params) kill_signal = signal.SIGUSR1 if env_params.take_lock else None if (not env_params.no_lock and not(lock.acquire_for(env_params.lock_pid_dir, env_params.lock_size, kill_signal))): raise PidLockAlreadyTakenExit() if env_params.local_scheduler: sch = worker_scheduler_factory.create_local_scheduler() else: if env_params.scheduler_url != '': url = env_params.scheduler_url else: url = 'http://{host}:{port:d}/'.format( host=env_params.scheduler_host, port=env_params.scheduler_port, ) sch = worker_scheduler_factory.create_remote_scheduler(url=url) worker = worker_scheduler_factory.create_worker( scheduler=sch, worker_processes=env_params.workers, assistant=env_params.assistant) success = True logger = logging.getLogger('luigi-interface') with worker: for t in tasks: success &= worker.add(t, env_params.parallel_scheduling, env_params.parallel_scheduling_processes) logger.info('Done scheduling tasks') success &= worker.run() luigi_run_result = LuigiRunResult(worker, success) logger.info(luigi_run_result.summary_text) return luigi_run_result
[ "def", "_schedule_and_run", "(", "tasks", ",", "worker_scheduler_factory", "=", "None", ",", "override_defaults", "=", "None", ")", ":", "if", "worker_scheduler_factory", "is", "None", ":", "worker_scheduler_factory", "=", "_WorkerSchedulerFactory", "(", ")", "if", "override_defaults", "is", "None", ":", "override_defaults", "=", "{", "}", "env_params", "=", "core", "(", "*", "*", "override_defaults", ")", "InterfaceLogging", ".", "setup", "(", "env_params", ")", "kill_signal", "=", "signal", ".", "SIGUSR1", "if", "env_params", ".", "take_lock", "else", "None", "if", "(", "not", "env_params", ".", "no_lock", "and", "not", "(", "lock", ".", "acquire_for", "(", "env_params", ".", "lock_pid_dir", ",", "env_params", ".", "lock_size", ",", "kill_signal", ")", ")", ")", ":", "raise", "PidLockAlreadyTakenExit", "(", ")", "if", "env_params", ".", "local_scheduler", ":", "sch", "=", "worker_scheduler_factory", ".", "create_local_scheduler", "(", ")", "else", ":", "if", "env_params", ".", "scheduler_url", "!=", "''", ":", "url", "=", "env_params", ".", "scheduler_url", "else", ":", "url", "=", "'http://{host}:{port:d}/'", ".", "format", "(", "host", "=", "env_params", ".", "scheduler_host", ",", "port", "=", "env_params", ".", "scheduler_port", ",", ")", "sch", "=", "worker_scheduler_factory", ".", "create_remote_scheduler", "(", "url", "=", "url", ")", "worker", "=", "worker_scheduler_factory", ".", "create_worker", "(", "scheduler", "=", "sch", ",", "worker_processes", "=", "env_params", ".", "workers", ",", "assistant", "=", "env_params", ".", "assistant", ")", "success", "=", "True", "logger", "=", "logging", ".", "getLogger", "(", "'luigi-interface'", ")", "with", "worker", ":", "for", "t", "in", "tasks", ":", "success", "&=", "worker", ".", "add", "(", "t", ",", "env_params", ".", "parallel_scheduling", ",", "env_params", ".", "parallel_scheduling_processes", ")", "logger", ".", "info", "(", "'Done scheduling tasks'", ")", "success", "&=", "worker", ".", "run", "(", ")", "luigi_run_result", "=", "LuigiRunResult", "(", "worker", ",", "success", ")", "logger", ".", "info", "(", "luigi_run_result", ".", "summary_text", ")", "return", "luigi_run_result" ]
:param tasks: :param worker_scheduler_factory: :param override_defaults: :return: True if all tasks and their dependencies were successfully run (or already completed); False if any error occurred. It will return a detailed response of type LuigiRunResult instead of a boolean if detailed_summary=True.
[ ":", "param", "tasks", ":", ":", "param", "worker_scheduler_factory", ":", ":", "param", "override_defaults", ":", ":", "return", ":", "True", "if", "all", "tasks", "and", "their", "dependencies", "were", "successfully", "run", "(", "or", "already", "completed", ")", ";", "False", "if", "any", "error", "occurred", ".", "It", "will", "return", "a", "detailed", "response", "of", "type", "LuigiRunResult", "instead", "of", "a", "boolean", "if", "detailed_summary", "=", "True", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/interface.py#L129-L176
train
spotify/luigi
luigi/interface.py
run
def run(*args, **kwargs): """ Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored """ luigi_run_result = _run(*args, **kwargs) return luigi_run_result if kwargs.get('detailed_summary') else luigi_run_result.scheduling_succeeded
python
def run(*args, **kwargs): """ Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored """ luigi_run_result = _run(*args, **kwargs) return luigi_run_result if kwargs.get('detailed_summary') else luigi_run_result.scheduling_succeeded
[ "def", "run", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "luigi_run_result", "=", "_run", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "luigi_run_result", "if", "kwargs", ".", "get", "(", "'detailed_summary'", ")", "else", "luigi_run_result", ".", "scheduling_succeeded" ]
Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored
[ "Please", "dont", "use", ".", "Instead", "use", "luigi", "binary", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/interface.py#L186-L195
train
spotify/luigi
luigi/interface.py
build
def build(tasks, worker_scheduler_factory=None, detailed_summary=False, **env_params): """ Run internally, bypassing the cmdline parsing. Useful if you have some luigi code that you want to run internally. Example: .. code-block:: python luigi.build([MyTask1(), MyTask2()], local_scheduler=True) One notable difference is that `build` defaults to not using the identical process lock. Otherwise, `build` would only be callable once from each process. :param tasks: :param worker_scheduler_factory: :param env_params: :return: True if there were no scheduling errors, even if tasks may fail. """ if "no_lock" not in env_params: env_params["no_lock"] = True luigi_run_result = _schedule_and_run(tasks, worker_scheduler_factory, override_defaults=env_params) return luigi_run_result if detailed_summary else luigi_run_result.scheduling_succeeded
python
def build(tasks, worker_scheduler_factory=None, detailed_summary=False, **env_params): """ Run internally, bypassing the cmdline parsing. Useful if you have some luigi code that you want to run internally. Example: .. code-block:: python luigi.build([MyTask1(), MyTask2()], local_scheduler=True) One notable difference is that `build` defaults to not using the identical process lock. Otherwise, `build` would only be callable once from each process. :param tasks: :param worker_scheduler_factory: :param env_params: :return: True if there were no scheduling errors, even if tasks may fail. """ if "no_lock" not in env_params: env_params["no_lock"] = True luigi_run_result = _schedule_and_run(tasks, worker_scheduler_factory, override_defaults=env_params) return luigi_run_result if detailed_summary else luigi_run_result.scheduling_succeeded
[ "def", "build", "(", "tasks", ",", "worker_scheduler_factory", "=", "None", ",", "detailed_summary", "=", "False", ",", "*", "*", "env_params", ")", ":", "if", "\"no_lock\"", "not", "in", "env_params", ":", "env_params", "[", "\"no_lock\"", "]", "=", "True", "luigi_run_result", "=", "_schedule_and_run", "(", "tasks", ",", "worker_scheduler_factory", ",", "override_defaults", "=", "env_params", ")", "return", "luigi_run_result", "if", "detailed_summary", "else", "luigi_run_result", ".", "scheduling_succeeded" ]
Run internally, bypassing the cmdline parsing. Useful if you have some luigi code that you want to run internally. Example: .. code-block:: python luigi.build([MyTask1(), MyTask2()], local_scheduler=True) One notable difference is that `build` defaults to not using the identical process lock. Otherwise, `build` would only be callable once from each process. :param tasks: :param worker_scheduler_factory: :param env_params: :return: True if there were no scheduling errors, even if tasks may fail.
[ "Run", "internally", "bypassing", "the", "cmdline", "parsing", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/interface.py#L214-L238
train
spotify/luigi
luigi/contrib/mysqldb.py
MySqlTarget.touch
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() if connection is None: connection = self.connect() connection.autocommit = True # if connection created here, we commit it here connection.cursor().execute( """INSERT INTO {marker_table} (update_id, target_table) VALUES (%s, %s) ON DUPLICATE KEY UPDATE update_id = VALUES(update_id) """.format(marker_table=self.marker_table), (self.update_id, self.table) ) # make sure update is properly marked assert self.exists(connection)
python
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() if connection is None: connection = self.connect() connection.autocommit = True # if connection created here, we commit it here connection.cursor().execute( """INSERT INTO {marker_table} (update_id, target_table) VALUES (%s, %s) ON DUPLICATE KEY UPDATE update_id = VALUES(update_id) """.format(marker_table=self.marker_table), (self.update_id, self.table) ) # make sure update is properly marked assert self.exists(connection)
[ "def", "touch", "(", "self", ",", "connection", "=", "None", ")", ":", "self", ".", "create_marker_table", "(", ")", "if", "connection", "is", "None", ":", "connection", "=", "self", ".", "connect", "(", ")", "connection", ".", "autocommit", "=", "True", "# if connection created here, we commit it here", "connection", ".", "cursor", "(", ")", ".", "execute", "(", "\"\"\"INSERT INTO {marker_table} (update_id, target_table)\n VALUES (%s, %s)\n ON DUPLICATE KEY UPDATE\n update_id = VALUES(update_id)\n \"\"\"", ".", "format", "(", "marker_table", "=", "self", ".", "marker_table", ")", ",", "(", "self", ".", "update_id", ",", "self", ".", "table", ")", ")", "# make sure update is properly marked", "assert", "self", ".", "exists", "(", "connection", ")" ]
Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created.
[ "Mark", "this", "update", "as", "complete", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mysqldb.py#L71-L94
train
spotify/luigi
luigi/contrib/mysqldb.py
MySqlTarget.create_marker_table
def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ connection = self.connect(autocommit=True) cursor = connection.cursor() try: cursor.execute( """ CREATE TABLE {marker_table} ( id BIGINT(20) NOT NULL AUTO_INCREMENT, update_id VARCHAR(128) NOT NULL, target_table VARCHAR(128), inserted TIMESTAMP DEFAULT NOW(), PRIMARY KEY (update_id), KEY id (id) ) """ .format(marker_table=self.marker_table) ) except mysql.connector.Error as e: if e.errno == errorcode.ER_TABLE_EXISTS_ERROR: pass else: raise connection.close()
python
def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ connection = self.connect(autocommit=True) cursor = connection.cursor() try: cursor.execute( """ CREATE TABLE {marker_table} ( id BIGINT(20) NOT NULL AUTO_INCREMENT, update_id VARCHAR(128) NOT NULL, target_table VARCHAR(128), inserted TIMESTAMP DEFAULT NOW(), PRIMARY KEY (update_id), KEY id (id) ) """ .format(marker_table=self.marker_table) ) except mysql.connector.Error as e: if e.errno == errorcode.ER_TABLE_EXISTS_ERROR: pass else: raise connection.close()
[ "def", "create_marker_table", "(", "self", ")", ":", "connection", "=", "self", ".", "connect", "(", "autocommit", "=", "True", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "\"\"\" CREATE TABLE {marker_table} (\n id BIGINT(20) NOT NULL AUTO_INCREMENT,\n update_id VARCHAR(128) NOT NULL,\n target_table VARCHAR(128),\n inserted TIMESTAMP DEFAULT NOW(),\n PRIMARY KEY (update_id),\n KEY id (id)\n )\n \"\"\"", ".", "format", "(", "marker_table", "=", "self", ".", "marker_table", ")", ")", "except", "mysql", ".", "connector", ".", "Error", "as", "e", ":", "if", "e", ".", "errno", "==", "errorcode", ".", "ER_TABLE_EXISTS_ERROR", ":", "pass", "else", ":", "raise", "connection", ".", "close", "(", ")" ]
Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset.
[ "Create", "marker", "table", "if", "it", "doesn", "t", "exist", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mysqldb.py#L125-L151
train
spotify/luigi
luigi/contrib/mysqldb.py
CopyToTable.run
def run(self): """ Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this. """ if not (self.table and self.columns): raise Exception("table and columns need to be specified") connection = self.output().connect() # attempt to copy the data into mysql # if it fails because the target table doesn't exist # try to create it by running self.create_table for attempt in range(2): try: cursor = connection.cursor() print("caling init copy...") self.init_copy(connection) self.copy(cursor) self.post_copy(connection) if self.enable_metadata_columns: self.post_copy_metacolumns(cursor) except Error as err: if err.errno == errorcode.ER_NO_SUCH_TABLE and attempt == 0: # if first attempt fails with "relation not found", try creating table # logger.info("Creating table %s", self.table) connection.reconnect() self.create_table(connection) else: raise else: break # mark as complete in same transaction self.output().touch(connection) connection.commit() connection.close()
python
def run(self): """ Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this. """ if not (self.table and self.columns): raise Exception("table and columns need to be specified") connection = self.output().connect() # attempt to copy the data into mysql # if it fails because the target table doesn't exist # try to create it by running self.create_table for attempt in range(2): try: cursor = connection.cursor() print("caling init copy...") self.init_copy(connection) self.copy(cursor) self.post_copy(connection) if self.enable_metadata_columns: self.post_copy_metacolumns(cursor) except Error as err: if err.errno == errorcode.ER_NO_SUCH_TABLE and attempt == 0: # if first attempt fails with "relation not found", try creating table # logger.info("Creating table %s", self.table) connection.reconnect() self.create_table(connection) else: raise else: break # mark as complete in same transaction self.output().touch(connection) connection.commit() connection.close()
[ "def", "run", "(", "self", ")", ":", "if", "not", "(", "self", ".", "table", "and", "self", ".", "columns", ")", ":", "raise", "Exception", "(", "\"table and columns need to be specified\"", ")", "connection", "=", "self", ".", "output", "(", ")", ".", "connect", "(", ")", "# attempt to copy the data into mysql", "# if it fails because the target table doesn't exist", "# try to create it by running self.create_table", "for", "attempt", "in", "range", "(", "2", ")", ":", "try", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "print", "(", "\"caling init copy...\"", ")", "self", ".", "init_copy", "(", "connection", ")", "self", ".", "copy", "(", "cursor", ")", "self", ".", "post_copy", "(", "connection", ")", "if", "self", ".", "enable_metadata_columns", ":", "self", ".", "post_copy_metacolumns", "(", "cursor", ")", "except", "Error", "as", "err", ":", "if", "err", ".", "errno", "==", "errorcode", ".", "ER_NO_SUCH_TABLE", "and", "attempt", "==", "0", ":", "# if first attempt fails with \"relation not found\", try creating table", "# logger.info(\"Creating table %s\", self.table)", "connection", ".", "reconnect", "(", ")", "self", ".", "create_table", "(", "connection", ")", "else", ":", "raise", "else", ":", "break", "# mark as complete in same transaction", "self", ".", "output", "(", ")", ".", "touch", "(", "connection", ")", "connection", ".", "commit", "(", ")", "connection", ".", "close", "(", ")" ]
Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this.
[ "Inserts", "data", "generated", "by", "rows", "()", "into", "target", "table", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mysqldb.py#L207-L246
train
spotify/luigi
luigi/contrib/hadoop_jar.py
fix_paths
def fix_paths(job): """ Coerce input arguments to use temporary files when used for output. Return a list of temporary file pairs (tmpfile, destination path) and a list of arguments. Converts each HdfsTarget to a string for the path. """ tmp_files = [] args = [] for x in job.args(): if isinstance(x, luigi.contrib.hdfs.HdfsTarget): # input/output if x.exists() or not job.atomic_output(): # input args.append(x.path) else: # output x_path_no_slash = x.path[:-1] if x.path[-1] == '/' else x.path y = luigi.contrib.hdfs.HdfsTarget(x_path_no_slash + '-luigi-tmp-%09d' % random.randrange(0, 1e10)) tmp_files.append((y, x_path_no_slash)) logger.info('Using temp path: %s for path %s', y.path, x.path) args.append(y.path) else: try: # hopefully the target has a path to use args.append(x.path) except AttributeError: # if there's no path then hope converting it to a string will work args.append(str(x)) return (tmp_files, args)
python
def fix_paths(job): """ Coerce input arguments to use temporary files when used for output. Return a list of temporary file pairs (tmpfile, destination path) and a list of arguments. Converts each HdfsTarget to a string for the path. """ tmp_files = [] args = [] for x in job.args(): if isinstance(x, luigi.contrib.hdfs.HdfsTarget): # input/output if x.exists() or not job.atomic_output(): # input args.append(x.path) else: # output x_path_no_slash = x.path[:-1] if x.path[-1] == '/' else x.path y = luigi.contrib.hdfs.HdfsTarget(x_path_no_slash + '-luigi-tmp-%09d' % random.randrange(0, 1e10)) tmp_files.append((y, x_path_no_slash)) logger.info('Using temp path: %s for path %s', y.path, x.path) args.append(y.path) else: try: # hopefully the target has a path to use args.append(x.path) except AttributeError: # if there's no path then hope converting it to a string will work args.append(str(x)) return (tmp_files, args)
[ "def", "fix_paths", "(", "job", ")", ":", "tmp_files", "=", "[", "]", "args", "=", "[", "]", "for", "x", "in", "job", ".", "args", "(", ")", ":", "if", "isinstance", "(", "x", ",", "luigi", ".", "contrib", ".", "hdfs", ".", "HdfsTarget", ")", ":", "# input/output", "if", "x", ".", "exists", "(", ")", "or", "not", "job", ".", "atomic_output", "(", ")", ":", "# input", "args", ".", "append", "(", "x", ".", "path", ")", "else", ":", "# output", "x_path_no_slash", "=", "x", ".", "path", "[", ":", "-", "1", "]", "if", "x", ".", "path", "[", "-", "1", "]", "==", "'/'", "else", "x", ".", "path", "y", "=", "luigi", ".", "contrib", ".", "hdfs", ".", "HdfsTarget", "(", "x_path_no_slash", "+", "'-luigi-tmp-%09d'", "%", "random", ".", "randrange", "(", "0", ",", "1e10", ")", ")", "tmp_files", ".", "append", "(", "(", "y", ",", "x_path_no_slash", ")", ")", "logger", ".", "info", "(", "'Using temp path: %s for path %s'", ",", "y", ".", "path", ",", "x", ".", "path", ")", "args", ".", "append", "(", "y", ".", "path", ")", "else", ":", "try", ":", "# hopefully the target has a path to use", "args", ".", "append", "(", "x", ".", "path", ")", "except", "AttributeError", ":", "# if there's no path then hope converting it to a string will work", "args", ".", "append", "(", "str", "(", "x", ")", ")", "return", "(", "tmp_files", ",", "args", ")" ]
Coerce input arguments to use temporary files when used for output. Return a list of temporary file pairs (tmpfile, destination path) and a list of arguments. Converts each HdfsTarget to a string for the path.
[ "Coerce", "input", "arguments", "to", "use", "temporary", "files", "when", "used", "for", "output", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop_jar.py#L33-L62
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.get_active_queue
def get_active_queue(self): """Get name of first active job queue""" # Get dict of active queues keyed by name queues = {q['jobQueueName']: q for q in self._client.describe_job_queues()['jobQueues'] if q['state'] == 'ENABLED' and q['status'] == 'VALID'} if not queues: raise Exception('No job queues with state=ENABLED and status=VALID') # Pick the first queue as default return list(queues.keys())[0]
python
def get_active_queue(self): """Get name of first active job queue""" # Get dict of active queues keyed by name queues = {q['jobQueueName']: q for q in self._client.describe_job_queues()['jobQueues'] if q['state'] == 'ENABLED' and q['status'] == 'VALID'} if not queues: raise Exception('No job queues with state=ENABLED and status=VALID') # Pick the first queue as default return list(queues.keys())[0]
[ "def", "get_active_queue", "(", "self", ")", ":", "# Get dict of active queues keyed by name", "queues", "=", "{", "q", "[", "'jobQueueName'", "]", ":", "q", "for", "q", "in", "self", ".", "_client", ".", "describe_job_queues", "(", ")", "[", "'jobQueues'", "]", "if", "q", "[", "'state'", "]", "==", "'ENABLED'", "and", "q", "[", "'status'", "]", "==", "'VALID'", "}", "if", "not", "queues", ":", "raise", "Exception", "(", "'No job queues with state=ENABLED and status=VALID'", ")", "# Pick the first queue as default", "return", "list", "(", "queues", ".", "keys", "(", ")", ")", "[", "0", "]" ]
Get name of first active job queue
[ "Get", "name", "of", "first", "active", "job", "queue" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L96-L106
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.get_job_id_from_name
def get_job_id_from_name(self, job_name): """Retrieve the first job ID matching the given name""" jobs = self._client.list_jobs(jobQueue=self._queue, jobStatus='RUNNING')['jobSummaryList'] matching_jobs = [job for job in jobs if job['jobName'] == job_name] if matching_jobs: return matching_jobs[0]['jobId']
python
def get_job_id_from_name(self, job_name): """Retrieve the first job ID matching the given name""" jobs = self._client.list_jobs(jobQueue=self._queue, jobStatus='RUNNING')['jobSummaryList'] matching_jobs = [job for job in jobs if job['jobName'] == job_name] if matching_jobs: return matching_jobs[0]['jobId']
[ "def", "get_job_id_from_name", "(", "self", ",", "job_name", ")", ":", "jobs", "=", "self", ".", "_client", ".", "list_jobs", "(", "jobQueue", "=", "self", ".", "_queue", ",", "jobStatus", "=", "'RUNNING'", ")", "[", "'jobSummaryList'", "]", "matching_jobs", "=", "[", "job", "for", "job", "in", "jobs", "if", "job", "[", "'jobName'", "]", "==", "job_name", "]", "if", "matching_jobs", ":", "return", "matching_jobs", "[", "0", "]", "[", "'jobId'", "]" ]
Retrieve the first job ID matching the given name
[ "Retrieve", "the", "first", "job", "ID", "matching", "the", "given", "name" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L108-L113
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.get_job_status
def get_job_status(self, job_id): """Retrieve task statuses from ECS API :param job_id (str): AWS Batch job uuid Returns one of {SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING|SUCCEEDED|FAILED} """ response = self._client.describe_jobs(jobs=[job_id]) # Error checking status_code = response['ResponseMetadata']['HTTPStatusCode'] if status_code != 200: msg = 'Job status request received status code {0}:\n{1}' raise Exception(msg.format(status_code, response)) return response['jobs'][0]['status']
python
def get_job_status(self, job_id): """Retrieve task statuses from ECS API :param job_id (str): AWS Batch job uuid Returns one of {SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING|SUCCEEDED|FAILED} """ response = self._client.describe_jobs(jobs=[job_id]) # Error checking status_code = response['ResponseMetadata']['HTTPStatusCode'] if status_code != 200: msg = 'Job status request received status code {0}:\n{1}' raise Exception(msg.format(status_code, response)) return response['jobs'][0]['status']
[ "def", "get_job_status", "(", "self", ",", "job_id", ")", ":", "response", "=", "self", ".", "_client", ".", "describe_jobs", "(", "jobs", "=", "[", "job_id", "]", ")", "# Error checking", "status_code", "=", "response", "[", "'ResponseMetadata'", "]", "[", "'HTTPStatusCode'", "]", "if", "status_code", "!=", "200", ":", "msg", "=", "'Job status request received status code {0}:\\n{1}'", "raise", "Exception", "(", "msg", ".", "format", "(", "status_code", ",", "response", ")", ")", "return", "response", "[", "'jobs'", "]", "[", "0", "]", "[", "'status'", "]" ]
Retrieve task statuses from ECS API :param job_id (str): AWS Batch job uuid Returns one of {SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING|SUCCEEDED|FAILED}
[ "Retrieve", "task", "statuses", "from", "ECS", "API" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L115-L130
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.get_logs
def get_logs(self, log_stream_name, get_last=50): """Retrieve log stream from CloudWatch""" response = self._log_client.get_log_events( logGroupName='/aws/batch/job', logStreamName=log_stream_name, startFromHead=False) events = response['events'] return '\n'.join(e['message'] for e in events[-get_last:])
python
def get_logs(self, log_stream_name, get_last=50): """Retrieve log stream from CloudWatch""" response = self._log_client.get_log_events( logGroupName='/aws/batch/job', logStreamName=log_stream_name, startFromHead=False) events = response['events'] return '\n'.join(e['message'] for e in events[-get_last:])
[ "def", "get_logs", "(", "self", ",", "log_stream_name", ",", "get_last", "=", "50", ")", ":", "response", "=", "self", ".", "_log_client", ".", "get_log_events", "(", "logGroupName", "=", "'/aws/batch/job'", ",", "logStreamName", "=", "log_stream_name", ",", "startFromHead", "=", "False", ")", "events", "=", "response", "[", "'events'", "]", "return", "'\\n'", ".", "join", "(", "e", "[", "'message'", "]", "for", "e", "in", "events", "[", "-", "get_last", ":", "]", ")" ]
Retrieve log stream from CloudWatch
[ "Retrieve", "log", "stream", "from", "CloudWatch" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L132-L139
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.submit_job
def submit_job(self, job_definition, parameters, job_name=None, queue=None): """Wrap submit_job with useful defaults""" if job_name is None: job_name = _random_id() response = self._client.submit_job( jobName=job_name, jobQueue=queue or self.get_active_queue(), jobDefinition=job_definition, parameters=parameters ) return response['jobId']
python
def submit_job(self, job_definition, parameters, job_name=None, queue=None): """Wrap submit_job with useful defaults""" if job_name is None: job_name = _random_id() response = self._client.submit_job( jobName=job_name, jobQueue=queue or self.get_active_queue(), jobDefinition=job_definition, parameters=parameters ) return response['jobId']
[ "def", "submit_job", "(", "self", ",", "job_definition", ",", "parameters", ",", "job_name", "=", "None", ",", "queue", "=", "None", ")", ":", "if", "job_name", "is", "None", ":", "job_name", "=", "_random_id", "(", ")", "response", "=", "self", ".", "_client", ".", "submit_job", "(", "jobName", "=", "job_name", ",", "jobQueue", "=", "queue", "or", "self", ".", "get_active_queue", "(", ")", ",", "jobDefinition", "=", "job_definition", ",", "parameters", "=", "parameters", ")", "return", "response", "[", "'jobId'", "]" ]
Wrap submit_job with useful defaults
[ "Wrap", "submit_job", "with", "useful", "defaults" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L141-L151
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.wait_on_job
def wait_on_job(self, job_id): """Poll task status until STOPPED""" while True: status = self.get_job_status(job_id) if status == 'SUCCEEDED': logger.info('Batch job {} SUCCEEDED'.format(job_id)) return True elif status == 'FAILED': # Raise and notify if job failed jobs = self._client.describe_jobs(jobs=[job_id])['jobs'] job_str = json.dumps(jobs, indent=4) logger.debug('Job details:\n' + job_str) log_stream_name = jobs[0]['attempts'][0]['container']['logStreamName'] logs = self.get_logs(log_stream_name) raise BatchJobException('Job {} failed: {}'.format( job_id, logs)) time.sleep(self.poll_time) logger.debug('Batch job status for job {0}: {1}'.format( job_id, status))
python
def wait_on_job(self, job_id): """Poll task status until STOPPED""" while True: status = self.get_job_status(job_id) if status == 'SUCCEEDED': logger.info('Batch job {} SUCCEEDED'.format(job_id)) return True elif status == 'FAILED': # Raise and notify if job failed jobs = self._client.describe_jobs(jobs=[job_id])['jobs'] job_str = json.dumps(jobs, indent=4) logger.debug('Job details:\n' + job_str) log_stream_name = jobs[0]['attempts'][0]['container']['logStreamName'] logs = self.get_logs(log_stream_name) raise BatchJobException('Job {} failed: {}'.format( job_id, logs)) time.sleep(self.poll_time) logger.debug('Batch job status for job {0}: {1}'.format( job_id, status))
[ "def", "wait_on_job", "(", "self", ",", "job_id", ")", ":", "while", "True", ":", "status", "=", "self", ".", "get_job_status", "(", "job_id", ")", "if", "status", "==", "'SUCCEEDED'", ":", "logger", ".", "info", "(", "'Batch job {} SUCCEEDED'", ".", "format", "(", "job_id", ")", ")", "return", "True", "elif", "status", "==", "'FAILED'", ":", "# Raise and notify if job failed", "jobs", "=", "self", ".", "_client", ".", "describe_jobs", "(", "jobs", "=", "[", "job_id", "]", ")", "[", "'jobs'", "]", "job_str", "=", "json", ".", "dumps", "(", "jobs", ",", "indent", "=", "4", ")", "logger", ".", "debug", "(", "'Job details:\\n'", "+", "job_str", ")", "log_stream_name", "=", "jobs", "[", "0", "]", "[", "'attempts'", "]", "[", "0", "]", "[", "'container'", "]", "[", "'logStreamName'", "]", "logs", "=", "self", ".", "get_logs", "(", "log_stream_name", ")", "raise", "BatchJobException", "(", "'Job {} failed: {}'", ".", "format", "(", "job_id", ",", "logs", ")", ")", "time", ".", "sleep", "(", "self", ".", "poll_time", ")", "logger", ".", "debug", "(", "'Batch job status for job {0}: {1}'", ".", "format", "(", "job_id", ",", "status", ")", ")" ]
Poll task status until STOPPED
[ "Poll", "task", "status", "until", "STOPPED" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L153-L174
train
spotify/luigi
luigi/contrib/batch.py
BatchClient.register_job_definition
def register_job_definition(self, json_fpath): """Register a job definition with AWS Batch, using a JSON""" with open(json_fpath) as f: job_def = json.load(f) response = self._client.register_job_definition(**job_def) status_code = response['ResponseMetadata']['HTTPStatusCode'] if status_code != 200: msg = 'Register job definition request received status code {0}:\n{1}' raise Exception(msg.format(status_code, response)) return response
python
def register_job_definition(self, json_fpath): """Register a job definition with AWS Batch, using a JSON""" with open(json_fpath) as f: job_def = json.load(f) response = self._client.register_job_definition(**job_def) status_code = response['ResponseMetadata']['HTTPStatusCode'] if status_code != 200: msg = 'Register job definition request received status code {0}:\n{1}' raise Exception(msg.format(status_code, response)) return response
[ "def", "register_job_definition", "(", "self", ",", "json_fpath", ")", ":", "with", "open", "(", "json_fpath", ")", "as", "f", ":", "job_def", "=", "json", ".", "load", "(", "f", ")", "response", "=", "self", ".", "_client", ".", "register_job_definition", "(", "*", "*", "job_def", ")", "status_code", "=", "response", "[", "'ResponseMetadata'", "]", "[", "'HTTPStatusCode'", "]", "if", "status_code", "!=", "200", ":", "msg", "=", "'Register job definition request received status code {0}:\\n{1}'", "raise", "Exception", "(", "msg", ".", "format", "(", "status_code", ",", "response", ")", ")", "return", "response" ]
Register a job definition with AWS Batch, using a JSON
[ "Register", "a", "job", "definition", "with", "AWS", "Batch", "using", "a", "JSON" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/batch.py#L176-L185
train
spotify/luigi
luigi/contrib/sge_runner.py
main
def main(args=sys.argv): """Run the work() method from the class instance in the file "job-instance.pickle". """ try: tarball = "--no-tarball" not in args # Set up logging. logging.basicConfig(level=logging.WARN) work_dir = args[1] assert os.path.exists(work_dir), "First argument to sge_runner.py must be a directory that exists" project_dir = args[2] sys.path.append(project_dir) _do_work_on_compute_node(work_dir, tarball) except Exception as e: # Dump encoded data that we will try to fetch using mechanize print(e) raise
python
def main(args=sys.argv): """Run the work() method from the class instance in the file "job-instance.pickle". """ try: tarball = "--no-tarball" not in args # Set up logging. logging.basicConfig(level=logging.WARN) work_dir = args[1] assert os.path.exists(work_dir), "First argument to sge_runner.py must be a directory that exists" project_dir = args[2] sys.path.append(project_dir) _do_work_on_compute_node(work_dir, tarball) except Exception as e: # Dump encoded data that we will try to fetch using mechanize print(e) raise
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "try", ":", "tarball", "=", "\"--no-tarball\"", "not", "in", "args", "# Set up logging.", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "WARN", ")", "work_dir", "=", "args", "[", "1", "]", "assert", "os", ".", "path", ".", "exists", "(", "work_dir", ")", ",", "\"First argument to sge_runner.py must be a directory that exists\"", "project_dir", "=", "args", "[", "2", "]", "sys", ".", "path", ".", "append", "(", "project_dir", ")", "_do_work_on_compute_node", "(", "work_dir", ",", "tarball", ")", "except", "Exception", "as", "e", ":", "# Dump encoded data that we will try to fetch using mechanize", "print", "(", "e", ")", "raise" ]
Run the work() method from the class instance in the file "job-instance.pickle".
[ "Run", "the", "work", "()", "method", "from", "the", "class", "instance", "in", "the", "file", "job", "-", "instance", ".", "pickle", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sge_runner.py#L80-L95
train
spotify/luigi
luigi/contrib/bigquery_avro.py
BigQueryLoadAvro._get_input_schema
def _get_input_schema(self): """Arbitrarily picks an object in input and reads the Avro schema from it.""" assert avro, 'avro module required' input_target = flatten(self.input())[0] input_fs = input_target.fs if hasattr(input_target, 'fs') else GCSClient() input_uri = self.source_uris()[0] if '*' in input_uri: file_uris = list(input_fs.list_wildcard(input_uri)) if file_uris: input_uri = file_uris[0] else: raise RuntimeError('No match for ' + input_uri) schema = [] exception_reading_schema = [] def read_schema(fp): # fp contains the file part downloaded thus far. We rely on that the DataFileReader # initializes itself fine as soon as the file header with schema is downloaded, without # requiring the remainder of the file... try: reader = avro.datafile.DataFileReader(fp, avro.io.DatumReader()) schema[:] = [reader.datum_reader.writers_schema] except Exception as e: # Save but assume benign unless schema reading ultimately fails. The benign # exception in case of insufficiently big downloaded file part seems to be: # TypeError('ord() expected a character, but string of length 0 found',). exception_reading_schema[:] = [e] return False return True input_fs.download(input_uri, 64 * 1024, read_schema).close() if not schema: raise exception_reading_schema[0] return schema[0]
python
def _get_input_schema(self): """Arbitrarily picks an object in input and reads the Avro schema from it.""" assert avro, 'avro module required' input_target = flatten(self.input())[0] input_fs = input_target.fs if hasattr(input_target, 'fs') else GCSClient() input_uri = self.source_uris()[0] if '*' in input_uri: file_uris = list(input_fs.list_wildcard(input_uri)) if file_uris: input_uri = file_uris[0] else: raise RuntimeError('No match for ' + input_uri) schema = [] exception_reading_schema = [] def read_schema(fp): # fp contains the file part downloaded thus far. We rely on that the DataFileReader # initializes itself fine as soon as the file header with schema is downloaded, without # requiring the remainder of the file... try: reader = avro.datafile.DataFileReader(fp, avro.io.DatumReader()) schema[:] = [reader.datum_reader.writers_schema] except Exception as e: # Save but assume benign unless schema reading ultimately fails. The benign # exception in case of insufficiently big downloaded file part seems to be: # TypeError('ord() expected a character, but string of length 0 found',). exception_reading_schema[:] = [e] return False return True input_fs.download(input_uri, 64 * 1024, read_schema).close() if not schema: raise exception_reading_schema[0] return schema[0]
[ "def", "_get_input_schema", "(", "self", ")", ":", "assert", "avro", ",", "'avro module required'", "input_target", "=", "flatten", "(", "self", ".", "input", "(", ")", ")", "[", "0", "]", "input_fs", "=", "input_target", ".", "fs", "if", "hasattr", "(", "input_target", ",", "'fs'", ")", "else", "GCSClient", "(", ")", "input_uri", "=", "self", ".", "source_uris", "(", ")", "[", "0", "]", "if", "'*'", "in", "input_uri", ":", "file_uris", "=", "list", "(", "input_fs", ".", "list_wildcard", "(", "input_uri", ")", ")", "if", "file_uris", ":", "input_uri", "=", "file_uris", "[", "0", "]", "else", ":", "raise", "RuntimeError", "(", "'No match for '", "+", "input_uri", ")", "schema", "=", "[", "]", "exception_reading_schema", "=", "[", "]", "def", "read_schema", "(", "fp", ")", ":", "# fp contains the file part downloaded thus far. We rely on that the DataFileReader", "# initializes itself fine as soon as the file header with schema is downloaded, without", "# requiring the remainder of the file...", "try", ":", "reader", "=", "avro", ".", "datafile", ".", "DataFileReader", "(", "fp", ",", "avro", ".", "io", ".", "DatumReader", "(", ")", ")", "schema", "[", ":", "]", "=", "[", "reader", ".", "datum_reader", ".", "writers_schema", "]", "except", "Exception", "as", "e", ":", "# Save but assume benign unless schema reading ultimately fails. The benign", "# exception in case of insufficiently big downloaded file part seems to be:", "# TypeError('ord() expected a character, but string of length 0 found',).", "exception_reading_schema", "[", ":", "]", "=", "[", "e", "]", "return", "False", "return", "True", "input_fs", ".", "download", "(", "input_uri", ",", "64", "*", "1024", ",", "read_schema", ")", ".", "close", "(", ")", "if", "not", "schema", ":", "raise", "exception_reading_schema", "[", "0", "]", "return", "schema", "[", "0", "]" ]
Arbitrarily picks an object in input and reads the Avro schema from it.
[ "Arbitrarily", "picks", "an", "object", "in", "input", "and", "reads", "the", "Avro", "schema", "from", "it", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery_avro.py#L40-L75
train
spotify/luigi
luigi/tools/deps_tree.py
print_tree
def print_tree(task, indent='', last=True): ''' Return a string representation of the tasks, their statuses/parameters in a dependency tree format ''' # dont bother printing out warnings about tasks with no output with warnings.catch_warnings(): warnings.filterwarnings(action='ignore', message='Task .* without outputs has no custom complete\\(\\) method') is_task_complete = task.complete() is_complete = (bcolors.OKGREEN + 'COMPLETE' if is_task_complete else bcolors.OKBLUE + 'PENDING') + bcolors.ENDC name = task.__class__.__name__ params = task.to_str_params(only_significant=True) result = '\n' + indent if(last): result += '└─--' indent += ' ' else: result += '|--' indent += '| ' result += '[{0}-{1} ({2})]'.format(name, params, is_complete) children = flatten(task.requires()) for index, child in enumerate(children): result += print_tree(child, indent, (index+1) == len(children)) return result
python
def print_tree(task, indent='', last=True): ''' Return a string representation of the tasks, their statuses/parameters in a dependency tree format ''' # dont bother printing out warnings about tasks with no output with warnings.catch_warnings(): warnings.filterwarnings(action='ignore', message='Task .* without outputs has no custom complete\\(\\) method') is_task_complete = task.complete() is_complete = (bcolors.OKGREEN + 'COMPLETE' if is_task_complete else bcolors.OKBLUE + 'PENDING') + bcolors.ENDC name = task.__class__.__name__ params = task.to_str_params(only_significant=True) result = '\n' + indent if(last): result += '└─--' indent += ' ' else: result += '|--' indent += '| ' result += '[{0}-{1} ({2})]'.format(name, params, is_complete) children = flatten(task.requires()) for index, child in enumerate(children): result += print_tree(child, indent, (index+1) == len(children)) return result
[ "def", "print_tree", "(", "task", ",", "indent", "=", "''", ",", "last", "=", "True", ")", ":", "# dont bother printing out warnings about tasks with no output", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "filterwarnings", "(", "action", "=", "'ignore'", ",", "message", "=", "'Task .* without outputs has no custom complete\\\\(\\\\) method'", ")", "is_task_complete", "=", "task", ".", "complete", "(", ")", "is_complete", "=", "(", "bcolors", ".", "OKGREEN", "+", "'COMPLETE'", "if", "is_task_complete", "else", "bcolors", ".", "OKBLUE", "+", "'PENDING'", ")", "+", "bcolors", ".", "ENDC", "name", "=", "task", ".", "__class__", ".", "__name__", "params", "=", "task", ".", "to_str_params", "(", "only_significant", "=", "True", ")", "result", "=", "'\\n'", "+", "indent", "if", "(", "last", ")", ":", "result", "+=", "'└─--'", "indent", "+=", "' '", "else", ":", "result", "+=", "'|--'", "indent", "+=", "'| '", "result", "+=", "'[{0}-{1} ({2})]'", ".", "format", "(", "name", ",", "params", ",", "is_complete", ")", "children", "=", "flatten", "(", "task", ".", "requires", "(", ")", ")", "for", "index", ",", "child", "in", "enumerate", "(", "children", ")", ":", "result", "+=", "print_tree", "(", "child", ",", "indent", ",", "(", "index", "+", "1", ")", "==", "len", "(", "children", ")", ")", "return", "result" ]
Return a string representation of the tasks, their statuses/parameters in a dependency tree format
[ "Return", "a", "string", "representation", "of", "the", "tasks", "their", "statuses", "/", "parameters", "in", "a", "dependency", "tree", "format" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/deps_tree.py#L41-L63
train
spotify/luigi
luigi/rpc.py
_urljoin
def _urljoin(base, url): """ Join relative URLs to base URLs like urllib.parse.urljoin but support arbitrary URIs (esp. 'http+unix://'). """ parsed = urlparse(base) scheme = parsed.scheme return urlparse( urljoin(parsed._replace(scheme='http').geturl(), url) )._replace(scheme=scheme).geturl()
python
def _urljoin(base, url): """ Join relative URLs to base URLs like urllib.parse.urljoin but support arbitrary URIs (esp. 'http+unix://'). """ parsed = urlparse(base) scheme = parsed.scheme return urlparse( urljoin(parsed._replace(scheme='http').geturl(), url) )._replace(scheme=scheme).geturl()
[ "def", "_urljoin", "(", "base", ",", "url", ")", ":", "parsed", "=", "urlparse", "(", "base", ")", "scheme", "=", "parsed", ".", "scheme", "return", "urlparse", "(", "urljoin", "(", "parsed", ".", "_replace", "(", "scheme", "=", "'http'", ")", ".", "geturl", "(", ")", ",", "url", ")", ")", ".", "_replace", "(", "scheme", "=", "scheme", ")", ".", "geturl", "(", ")" ]
Join relative URLs to base URLs like urllib.parse.urljoin but support arbitrary URIs (esp. 'http+unix://').
[ "Join", "relative", "URLs", "to", "base", "URLs", "like", "urllib", ".", "parse", ".", "urljoin", "but", "support", "arbitrary", "URIs", "(", "esp", ".", "http", "+", "unix", ":", "//", ")", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/rpc.py#L52-L61
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.dataset_exists
def dataset_exists(self, dataset): """Returns whether the given dataset exists. If regional location is specified for the dataset, that is also checked to be compatible with the remote dataset, otherwise an exception is thrown. :param dataset: :type dataset: BQDataset """ try: response = self.client.datasets().get(projectId=dataset.project_id, datasetId=dataset.dataset_id).execute() if dataset.location is not None: fetched_location = response.get('location') if dataset.location != fetched_location: raise Exception('''Dataset already exists with regional location {}. Can't use {}.'''.format( fetched_location if fetched_location is not None else 'unspecified', dataset.location)) except http.HttpError as ex: if ex.resp.status == 404: return False raise return True
python
def dataset_exists(self, dataset): """Returns whether the given dataset exists. If regional location is specified for the dataset, that is also checked to be compatible with the remote dataset, otherwise an exception is thrown. :param dataset: :type dataset: BQDataset """ try: response = self.client.datasets().get(projectId=dataset.project_id, datasetId=dataset.dataset_id).execute() if dataset.location is not None: fetched_location = response.get('location') if dataset.location != fetched_location: raise Exception('''Dataset already exists with regional location {}. Can't use {}.'''.format( fetched_location if fetched_location is not None else 'unspecified', dataset.location)) except http.HttpError as ex: if ex.resp.status == 404: return False raise return True
[ "def", "dataset_exists", "(", "self", ",", "dataset", ")", ":", "try", ":", "response", "=", "self", ".", "client", ".", "datasets", "(", ")", ".", "get", "(", "projectId", "=", "dataset", ".", "project_id", ",", "datasetId", "=", "dataset", ".", "dataset_id", ")", ".", "execute", "(", ")", "if", "dataset", ".", "location", "is", "not", "None", ":", "fetched_location", "=", "response", ".", "get", "(", "'location'", ")", "if", "dataset", ".", "location", "!=", "fetched_location", ":", "raise", "Exception", "(", "'''Dataset already exists with regional location {}. Can't use {}.'''", ".", "format", "(", "fetched_location", "if", "fetched_location", "is", "not", "None", "else", "'unspecified'", ",", "dataset", ".", "location", ")", ")", "except", "http", ".", "HttpError", "as", "ex", ":", "if", "ex", ".", "resp", ".", "status", "==", "404", ":", "return", "False", "raise", "return", "True" ]
Returns whether the given dataset exists. If regional location is specified for the dataset, that is also checked to be compatible with the remote dataset, otherwise an exception is thrown. :param dataset: :type dataset: BQDataset
[ "Returns", "whether", "the", "given", "dataset", "exists", ".", "If", "regional", "location", "is", "specified", "for", "the", "dataset", "that", "is", "also", "checked", "to", "be", "compatible", "with", "the", "remote", "dataset", "otherwise", "an", "exception", "is", "thrown", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L131-L155
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.table_exists
def table_exists(self, table): """Returns whether the given table exists. :param table: :type table: BQTable """ if not self.dataset_exists(table.dataset): return False try: self.client.tables().get(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id).execute() except http.HttpError as ex: if ex.resp.status == 404: return False raise return True
python
def table_exists(self, table): """Returns whether the given table exists. :param table: :type table: BQTable """ if not self.dataset_exists(table.dataset): return False try: self.client.tables().get(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id).execute() except http.HttpError as ex: if ex.resp.status == 404: return False raise return True
[ "def", "table_exists", "(", "self", ",", "table", ")", ":", "if", "not", "self", ".", "dataset_exists", "(", "table", ".", "dataset", ")", ":", "return", "False", "try", ":", "self", ".", "client", ".", "tables", "(", ")", ".", "get", "(", "projectId", "=", "table", ".", "project_id", ",", "datasetId", "=", "table", ".", "dataset_id", ",", "tableId", "=", "table", ".", "table_id", ")", ".", "execute", "(", ")", "except", "http", ".", "HttpError", "as", "ex", ":", "if", "ex", ".", "resp", ".", "status", "==", "404", ":", "return", "False", "raise", "return", "True" ]
Returns whether the given table exists. :param table: :type table: BQTable
[ "Returns", "whether", "the", "given", "table", "exists", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L157-L175
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.make_dataset
def make_dataset(self, dataset, raise_if_exists=False, body=None): """Creates a new dataset with the default permissions. :param dataset: :type dataset: BQDataset :param raise_if_exists: whether to raise an exception if the dataset already exists. :raises luigi.target.FileAlreadyExists: if raise_if_exists=True and the dataset exists """ if body is None: body = {} try: # Construct a message body in the format required by # https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/bigquery_v2.datasets.html#insert body['datasetReference'] = { 'projectId': dataset.project_id, 'datasetId': dataset.dataset_id } if dataset.location is not None: body['location'] = dataset.location self.client.datasets().insert(projectId=dataset.project_id, body=body).execute() except http.HttpError as ex: if ex.resp.status == 409: if raise_if_exists: raise luigi.target.FileAlreadyExists() else: raise
python
def make_dataset(self, dataset, raise_if_exists=False, body=None): """Creates a new dataset with the default permissions. :param dataset: :type dataset: BQDataset :param raise_if_exists: whether to raise an exception if the dataset already exists. :raises luigi.target.FileAlreadyExists: if raise_if_exists=True and the dataset exists """ if body is None: body = {} try: # Construct a message body in the format required by # https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/bigquery_v2.datasets.html#insert body['datasetReference'] = { 'projectId': dataset.project_id, 'datasetId': dataset.dataset_id } if dataset.location is not None: body['location'] = dataset.location self.client.datasets().insert(projectId=dataset.project_id, body=body).execute() except http.HttpError as ex: if ex.resp.status == 409: if raise_if_exists: raise luigi.target.FileAlreadyExists() else: raise
[ "def", "make_dataset", "(", "self", ",", "dataset", ",", "raise_if_exists", "=", "False", ",", "body", "=", "None", ")", ":", "if", "body", "is", "None", ":", "body", "=", "{", "}", "try", ":", "# Construct a message body in the format required by", "# https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/bigquery_v2.datasets.html#insert", "body", "[", "'datasetReference'", "]", "=", "{", "'projectId'", ":", "dataset", ".", "project_id", ",", "'datasetId'", ":", "dataset", ".", "dataset_id", "}", "if", "dataset", ".", "location", "is", "not", "None", ":", "body", "[", "'location'", "]", "=", "dataset", ".", "location", "self", ".", "client", ".", "datasets", "(", ")", ".", "insert", "(", "projectId", "=", "dataset", ".", "project_id", ",", "body", "=", "body", ")", ".", "execute", "(", ")", "except", "http", ".", "HttpError", "as", "ex", ":", "if", "ex", ".", "resp", ".", "status", "==", "409", ":", "if", "raise_if_exists", ":", "raise", "luigi", ".", "target", ".", "FileAlreadyExists", "(", ")", "else", ":", "raise" ]
Creates a new dataset with the default permissions. :param dataset: :type dataset: BQDataset :param raise_if_exists: whether to raise an exception if the dataset already exists. :raises luigi.target.FileAlreadyExists: if raise_if_exists=True and the dataset exists
[ "Creates", "a", "new", "dataset", "with", "the", "default", "permissions", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L177-L204
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.delete_dataset
def delete_dataset(self, dataset, delete_nonempty=True): """Deletes a dataset (and optionally any tables in it), if it exists. :param dataset: :type dataset: BQDataset :param delete_nonempty: if true, will delete any tables before deleting the dataset """ if not self.dataset_exists(dataset): return self.client.datasets().delete(projectId=dataset.project_id, datasetId=dataset.dataset_id, deleteContents=delete_nonempty).execute()
python
def delete_dataset(self, dataset, delete_nonempty=True): """Deletes a dataset (and optionally any tables in it), if it exists. :param dataset: :type dataset: BQDataset :param delete_nonempty: if true, will delete any tables before deleting the dataset """ if not self.dataset_exists(dataset): return self.client.datasets().delete(projectId=dataset.project_id, datasetId=dataset.dataset_id, deleteContents=delete_nonempty).execute()
[ "def", "delete_dataset", "(", "self", ",", "dataset", ",", "delete_nonempty", "=", "True", ")", ":", "if", "not", "self", ".", "dataset_exists", "(", "dataset", ")", ":", "return", "self", ".", "client", ".", "datasets", "(", ")", ".", "delete", "(", "projectId", "=", "dataset", ".", "project_id", ",", "datasetId", "=", "dataset", ".", "dataset_id", ",", "deleteContents", "=", "delete_nonempty", ")", ".", "execute", "(", ")" ]
Deletes a dataset (and optionally any tables in it), if it exists. :param dataset: :type dataset: BQDataset :param delete_nonempty: if true, will delete any tables before deleting the dataset
[ "Deletes", "a", "dataset", "(", "and", "optionally", "any", "tables", "in", "it", ")", "if", "it", "exists", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L206-L219
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.delete_table
def delete_table(self, table): """Deletes a table, if it exists. :param table: :type table: BQTable """ if not self.table_exists(table): return self.client.tables().delete(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id).execute()
python
def delete_table(self, table): """Deletes a table, if it exists. :param table: :type table: BQTable """ if not self.table_exists(table): return self.client.tables().delete(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id).execute()
[ "def", "delete_table", "(", "self", ",", "table", ")", ":", "if", "not", "self", ".", "table_exists", "(", "table", ")", ":", "return", "self", ".", "client", ".", "tables", "(", ")", ".", "delete", "(", "projectId", "=", "table", ".", "project_id", ",", "datasetId", "=", "table", ".", "dataset_id", ",", "tableId", "=", "table", ".", "table_id", ")", ".", "execute", "(", ")" ]
Deletes a table, if it exists. :param table: :type table: BQTable
[ "Deletes", "a", "table", "if", "it", "exists", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L221-L233
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.list_datasets
def list_datasets(self, project_id): """Returns the list of datasets in a given project. :param project_id: :type project_id: str """ request = self.client.datasets().list(projectId=project_id, maxResults=1000) response = request.execute() while response is not None: for ds in response.get('datasets', []): yield ds['datasetReference']['datasetId'] request = self.client.datasets().list_next(request, response) if request is None: break response = request.execute()
python
def list_datasets(self, project_id): """Returns the list of datasets in a given project. :param project_id: :type project_id: str """ request = self.client.datasets().list(projectId=project_id, maxResults=1000) response = request.execute() while response is not None: for ds in response.get('datasets', []): yield ds['datasetReference']['datasetId'] request = self.client.datasets().list_next(request, response) if request is None: break response = request.execute()
[ "def", "list_datasets", "(", "self", ",", "project_id", ")", ":", "request", "=", "self", ".", "client", ".", "datasets", "(", ")", ".", "list", "(", "projectId", "=", "project_id", ",", "maxResults", "=", "1000", ")", "response", "=", "request", ".", "execute", "(", ")", "while", "response", "is", "not", "None", ":", "for", "ds", "in", "response", ".", "get", "(", "'datasets'", ",", "[", "]", ")", ":", "yield", "ds", "[", "'datasetReference'", "]", "[", "'datasetId'", "]", "request", "=", "self", ".", "client", ".", "datasets", "(", ")", ".", "list_next", "(", "request", ",", "response", ")", "if", "request", "is", "None", ":", "break", "response", "=", "request", ".", "execute", "(", ")" ]
Returns the list of datasets in a given project. :param project_id: :type project_id: str
[ "Returns", "the", "list", "of", "datasets", "in", "a", "given", "project", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L235-L254
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.list_tables
def list_tables(self, dataset): """Returns the list of tables in a given dataset. :param dataset: :type dataset: BQDataset """ request = self.client.tables().list(projectId=dataset.project_id, datasetId=dataset.dataset_id, maxResults=1000) response = request.execute() while response is not None: for t in response.get('tables', []): yield t['tableReference']['tableId'] request = self.client.tables().list_next(request, response) if request is None: break response = request.execute()
python
def list_tables(self, dataset): """Returns the list of tables in a given dataset. :param dataset: :type dataset: BQDataset """ request = self.client.tables().list(projectId=dataset.project_id, datasetId=dataset.dataset_id, maxResults=1000) response = request.execute() while response is not None: for t in response.get('tables', []): yield t['tableReference']['tableId'] request = self.client.tables().list_next(request, response) if request is None: break response = request.execute()
[ "def", "list_tables", "(", "self", ",", "dataset", ")", ":", "request", "=", "self", ".", "client", ".", "tables", "(", ")", ".", "list", "(", "projectId", "=", "dataset", ".", "project_id", ",", "datasetId", "=", "dataset", ".", "dataset_id", ",", "maxResults", "=", "1000", ")", "response", "=", "request", ".", "execute", "(", ")", "while", "response", "is", "not", "None", ":", "for", "t", "in", "response", ".", "get", "(", "'tables'", ",", "[", "]", ")", ":", "yield", "t", "[", "'tableReference'", "]", "[", "'tableId'", "]", "request", "=", "self", ".", "client", ".", "tables", "(", ")", ".", "list_next", "(", "request", ",", "response", ")", "if", "request", "is", "None", ":", "break", "response", "=", "request", ".", "execute", "(", ")" ]
Returns the list of tables in a given dataset. :param dataset: :type dataset: BQDataset
[ "Returns", "the", "list", "of", "tables", "in", "a", "given", "dataset", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L256-L276
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.get_view
def get_view(self, table): """Returns the SQL query for a view, or None if it doesn't exist or is not a view. :param table: The table containing the view. :type table: BQTable """ request = self.client.tables().get(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id) try: response = request.execute() except http.HttpError as ex: if ex.resp.status == 404: return None raise return response['view']['query'] if 'view' in response else None
python
def get_view(self, table): """Returns the SQL query for a view, or None if it doesn't exist or is not a view. :param table: The table containing the view. :type table: BQTable """ request = self.client.tables().get(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id) try: response = request.execute() except http.HttpError as ex: if ex.resp.status == 404: return None raise return response['view']['query'] if 'view' in response else None
[ "def", "get_view", "(", "self", ",", "table", ")", ":", "request", "=", "self", ".", "client", ".", "tables", "(", ")", ".", "get", "(", "projectId", "=", "table", ".", "project_id", ",", "datasetId", "=", "table", ".", "dataset_id", ",", "tableId", "=", "table", ".", "table_id", ")", "try", ":", "response", "=", "request", ".", "execute", "(", ")", "except", "http", ".", "HttpError", "as", "ex", ":", "if", "ex", ".", "resp", ".", "status", "==", "404", ":", "return", "None", "raise", "return", "response", "[", "'view'", "]", "[", "'query'", "]", "if", "'view'", "in", "response", "else", "None" ]
Returns the SQL query for a view, or None if it doesn't exist or is not a view. :param table: The table containing the view. :type table: BQTable
[ "Returns", "the", "SQL", "query", "for", "a", "view", "or", "None", "if", "it", "doesn", "t", "exist", "or", "is", "not", "a", "view", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L278-L296
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.update_view
def update_view(self, table, view): """Updates the SQL query for a view. If the output table exists, it is replaced with the supplied view query. Otherwise a new table is created with this view. :param table: The table to contain the view. :type table: BQTable :param view: The SQL query for the view. :type view: str """ body = { 'tableReference': { 'projectId': table.project_id, 'datasetId': table.dataset_id, 'tableId': table.table_id }, 'view': { 'query': view } } if self.table_exists(table): self.client.tables().update(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id, body=body).execute() else: self.client.tables().insert(projectId=table.project_id, datasetId=table.dataset_id, body=body).execute()
python
def update_view(self, table, view): """Updates the SQL query for a view. If the output table exists, it is replaced with the supplied view query. Otherwise a new table is created with this view. :param table: The table to contain the view. :type table: BQTable :param view: The SQL query for the view. :type view: str """ body = { 'tableReference': { 'projectId': table.project_id, 'datasetId': table.dataset_id, 'tableId': table.table_id }, 'view': { 'query': view } } if self.table_exists(table): self.client.tables().update(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id, body=body).execute() else: self.client.tables().insert(projectId=table.project_id, datasetId=table.dataset_id, body=body).execute()
[ "def", "update_view", "(", "self", ",", "table", ",", "view", ")", ":", "body", "=", "{", "'tableReference'", ":", "{", "'projectId'", ":", "table", ".", "project_id", ",", "'datasetId'", ":", "table", ".", "dataset_id", ",", "'tableId'", ":", "table", ".", "table_id", "}", ",", "'view'", ":", "{", "'query'", ":", "view", "}", "}", "if", "self", ".", "table_exists", "(", "table", ")", ":", "self", ".", "client", ".", "tables", "(", ")", ".", "update", "(", "projectId", "=", "table", ".", "project_id", ",", "datasetId", "=", "table", ".", "dataset_id", ",", "tableId", "=", "table", ".", "table_id", ",", "body", "=", "body", ")", ".", "execute", "(", ")", "else", ":", "self", ".", "client", ".", "tables", "(", ")", ".", "insert", "(", "projectId", "=", "table", ".", "project_id", ",", "datasetId", "=", "table", ".", "dataset_id", ",", "body", "=", "body", ")", ".", "execute", "(", ")" ]
Updates the SQL query for a view. If the output table exists, it is replaced with the supplied view query. Otherwise a new table is created with this view. :param table: The table to contain the view. :type table: BQTable :param view: The SQL query for the view. :type view: str
[ "Updates", "the", "SQL", "query", "for", "a", "view", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L298-L329
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.run_job
def run_job(self, project_id, body, dataset=None): """Runs a BigQuery "job". See the documentation for the format of body. .. note:: You probably don't need to use this directly. Use the tasks defined below. :param dataset: :type dataset: BQDataset """ if dataset and not self.dataset_exists(dataset): self.make_dataset(dataset) new_job = self.client.jobs().insert(projectId=project_id, body=body).execute() job_id = new_job['jobReference']['jobId'] logger.info('Started import job %s:%s', project_id, job_id) while True: status = self.client.jobs().get(projectId=project_id, jobId=job_id).execute(num_retries=10) if status['status']['state'] == 'DONE': if status['status'].get('errorResult'): raise Exception('BigQuery job failed: {}'.format(status['status']['errorResult'])) return logger.info('Waiting for job %s:%s to complete...', project_id, job_id) time.sleep(5)
python
def run_job(self, project_id, body, dataset=None): """Runs a BigQuery "job". See the documentation for the format of body. .. note:: You probably don't need to use this directly. Use the tasks defined below. :param dataset: :type dataset: BQDataset """ if dataset and not self.dataset_exists(dataset): self.make_dataset(dataset) new_job = self.client.jobs().insert(projectId=project_id, body=body).execute() job_id = new_job['jobReference']['jobId'] logger.info('Started import job %s:%s', project_id, job_id) while True: status = self.client.jobs().get(projectId=project_id, jobId=job_id).execute(num_retries=10) if status['status']['state'] == 'DONE': if status['status'].get('errorResult'): raise Exception('BigQuery job failed: {}'.format(status['status']['errorResult'])) return logger.info('Waiting for job %s:%s to complete...', project_id, job_id) time.sleep(5)
[ "def", "run_job", "(", "self", ",", "project_id", ",", "body", ",", "dataset", "=", "None", ")", ":", "if", "dataset", "and", "not", "self", ".", "dataset_exists", "(", "dataset", ")", ":", "self", ".", "make_dataset", "(", "dataset", ")", "new_job", "=", "self", ".", "client", ".", "jobs", "(", ")", ".", "insert", "(", "projectId", "=", "project_id", ",", "body", "=", "body", ")", ".", "execute", "(", ")", "job_id", "=", "new_job", "[", "'jobReference'", "]", "[", "'jobId'", "]", "logger", ".", "info", "(", "'Started import job %s:%s'", ",", "project_id", ",", "job_id", ")", "while", "True", ":", "status", "=", "self", ".", "client", ".", "jobs", "(", ")", ".", "get", "(", "projectId", "=", "project_id", ",", "jobId", "=", "job_id", ")", ".", "execute", "(", "num_retries", "=", "10", ")", "if", "status", "[", "'status'", "]", "[", "'state'", "]", "==", "'DONE'", ":", "if", "status", "[", "'status'", "]", ".", "get", "(", "'errorResult'", ")", ":", "raise", "Exception", "(", "'BigQuery job failed: {}'", ".", "format", "(", "status", "[", "'status'", "]", "[", "'errorResult'", "]", ")", ")", "return", "logger", ".", "info", "(", "'Waiting for job %s:%s to complete...'", ",", "project_id", ",", "job_id", ")", "time", ".", "sleep", "(", "5", ")" ]
Runs a BigQuery "job". See the documentation for the format of body. .. note:: You probably don't need to use this directly. Use the tasks defined below. :param dataset: :type dataset: BQDataset
[ "Runs", "a", "BigQuery", "job", ".", "See", "the", "documentation", "for", "the", "format", "of", "body", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L331-L355
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryClient.copy
def copy(self, source_table, dest_table, create_disposition=CreateDisposition.CREATE_IF_NEEDED, write_disposition=WriteDisposition.WRITE_TRUNCATE): """Copies (or appends) a table to another table. :param source_table: :type source_table: BQTable :param dest_table: :type dest_table: BQTable :param create_disposition: whether to create the table if needed :type create_disposition: CreateDisposition :param write_disposition: whether to append/truncate/fail if the table exists :type write_disposition: WriteDisposition """ job = { "configuration": { "copy": { "sourceTable": { "projectId": source_table.project_id, "datasetId": source_table.dataset_id, "tableId": source_table.table_id, }, "destinationTable": { "projectId": dest_table.project_id, "datasetId": dest_table.dataset_id, "tableId": dest_table.table_id, }, "createDisposition": create_disposition, "writeDisposition": write_disposition, } } } self.run_job(dest_table.project_id, job, dataset=dest_table.dataset)
python
def copy(self, source_table, dest_table, create_disposition=CreateDisposition.CREATE_IF_NEEDED, write_disposition=WriteDisposition.WRITE_TRUNCATE): """Copies (or appends) a table to another table. :param source_table: :type source_table: BQTable :param dest_table: :type dest_table: BQTable :param create_disposition: whether to create the table if needed :type create_disposition: CreateDisposition :param write_disposition: whether to append/truncate/fail if the table exists :type write_disposition: WriteDisposition """ job = { "configuration": { "copy": { "sourceTable": { "projectId": source_table.project_id, "datasetId": source_table.dataset_id, "tableId": source_table.table_id, }, "destinationTable": { "projectId": dest_table.project_id, "datasetId": dest_table.dataset_id, "tableId": dest_table.table_id, }, "createDisposition": create_disposition, "writeDisposition": write_disposition, } } } self.run_job(dest_table.project_id, job, dataset=dest_table.dataset)
[ "def", "copy", "(", "self", ",", "source_table", ",", "dest_table", ",", "create_disposition", "=", "CreateDisposition", ".", "CREATE_IF_NEEDED", ",", "write_disposition", "=", "WriteDisposition", ".", "WRITE_TRUNCATE", ")", ":", "job", "=", "{", "\"configuration\"", ":", "{", "\"copy\"", ":", "{", "\"sourceTable\"", ":", "{", "\"projectId\"", ":", "source_table", ".", "project_id", ",", "\"datasetId\"", ":", "source_table", ".", "dataset_id", ",", "\"tableId\"", ":", "source_table", ".", "table_id", ",", "}", ",", "\"destinationTable\"", ":", "{", "\"projectId\"", ":", "dest_table", ".", "project_id", ",", "\"datasetId\"", ":", "dest_table", ".", "dataset_id", ",", "\"tableId\"", ":", "dest_table", ".", "table_id", ",", "}", ",", "\"createDisposition\"", ":", "create_disposition", ",", "\"writeDisposition\"", ":", "write_disposition", ",", "}", "}", "}", "self", ".", "run_job", "(", "dest_table", ".", "project_id", ",", "job", ",", "dataset", "=", "dest_table", ".", "dataset", ")" ]
Copies (or appends) a table to another table. :param source_table: :type source_table: BQTable :param dest_table: :type dest_table: BQTable :param create_disposition: whether to create the table if needed :type create_disposition: CreateDisposition :param write_disposition: whether to append/truncate/fail if the table exists :type write_disposition: WriteDisposition
[ "Copies", "(", "or", "appends", ")", "a", "table", "to", "another", "table", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L357-L393
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryTarget.from_bqtable
def from_bqtable(cls, table, client=None): """A constructor that takes a :py:class:`BQTable`. :param table: :type table: BQTable """ return cls(table.project_id, table.dataset_id, table.table_id, client=client)
python
def from_bqtable(cls, table, client=None): """A constructor that takes a :py:class:`BQTable`. :param table: :type table: BQTable """ return cls(table.project_id, table.dataset_id, table.table_id, client=client)
[ "def", "from_bqtable", "(", "cls", ",", "table", ",", "client", "=", "None", ")", ":", "return", "cls", "(", "table", ".", "project_id", ",", "table", ".", "dataset_id", ",", "table", ".", "table_id", ",", "client", "=", "client", ")" ]
A constructor that takes a :py:class:`BQTable`. :param table: :type table: BQTable
[ "A", "constructor", "that", "takes", "a", ":", "py", ":", "class", ":", "BQTable", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L402-L408
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryLoadTask.source_uris
def source_uris(self): """The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name.""" return [x.path for x in luigi.task.flatten(self.input())]
python
def source_uris(self): """The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name.""" return [x.path for x in luigi.task.flatten(self.input())]
[ "def", "source_uris", "(", "self", ")", ":", "return", "[", "x", ".", "path", "for", "x", "in", "luigi", ".", "task", ".", "flatten", "(", "self", ".", "input", "(", ")", ")", "]" ]
The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name.
[ "The", "fully", "-", "qualified", "URIs", "that", "point", "to", "your", "data", "in", "Google", "Cloud", "Storage", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L487-L491
train
spotify/luigi
luigi/contrib/bigquery.py
BigQueryExtractTask.destination_uris
def destination_uris(self): """ The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Wildcarded destinationUris in GCSQueryTarget might not be resolved correctly and result in incomplete data. If a GCSQueryTarget is used to pass wildcarded destinationUris be sure to overwrite this property to suppress the warning. """ return [x.path for x in luigi.task.flatten(self.output())]
python
def destination_uris(self): """ The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Wildcarded destinationUris in GCSQueryTarget might not be resolved correctly and result in incomplete data. If a GCSQueryTarget is used to pass wildcarded destinationUris be sure to overwrite this property to suppress the warning. """ return [x.path for x in luigi.task.flatten(self.output())]
[ "def", "destination_uris", "(", "self", ")", ":", "return", "[", "x", ".", "path", "for", "x", "in", "luigi", ".", "task", ".", "flatten", "(", "self", ".", "output", "(", ")", ")", "]" ]
The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Wildcarded destinationUris in GCSQueryTarget might not be resolved correctly and result in incomplete data. If a GCSQueryTarget is used to pass wildcarded destinationUris be sure to overwrite this property to suppress the warning.
[ "The", "fully", "-", "qualified", "URIs", "that", "point", "to", "your", "data", "in", "Google", "Cloud", "Storage", ".", "Each", "URI", "can", "contain", "one", "*", "wildcard", "character", "and", "it", "must", "come", "after", "the", "bucket", "name", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/bigquery.py#L701-L712
train
spotify/luigi
luigi/contrib/ssh.py
RemoteContext.Popen
def Popen(self, cmd, **kwargs): """ Remote Popen. """ prefixed_cmd = self._prepare_cmd(cmd) return subprocess.Popen(prefixed_cmd, **kwargs)
python
def Popen(self, cmd, **kwargs): """ Remote Popen. """ prefixed_cmd = self._prepare_cmd(cmd) return subprocess.Popen(prefixed_cmd, **kwargs)
[ "def", "Popen", "(", "self", ",", "cmd", ",", "*", "*", "kwargs", ")", ":", "prefixed_cmd", "=", "self", ".", "_prepare_cmd", "(", "cmd", ")", "return", "subprocess", ".", "Popen", "(", "prefixed_cmd", ",", "*", "*", "kwargs", ")" ]
Remote Popen.
[ "Remote", "Popen", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ssh.py#L116-L121
train
spotify/luigi
luigi/contrib/ssh.py
RemoteContext.check_output
def check_output(self, cmd): """ Execute a shell command remotely and return the output. Simplified version of Popen when you only want the output as a string and detect any errors. """ p = self.Popen(cmd, stdout=subprocess.PIPE) output, _ = p.communicate() if p.returncode != 0: raise RemoteCalledProcessError(p.returncode, cmd, self.host, output=output) return output
python
def check_output(self, cmd): """ Execute a shell command remotely and return the output. Simplified version of Popen when you only want the output as a string and detect any errors. """ p = self.Popen(cmd, stdout=subprocess.PIPE) output, _ = p.communicate() if p.returncode != 0: raise RemoteCalledProcessError(p.returncode, cmd, self.host, output=output) return output
[ "def", "check_output", "(", "self", ",", "cmd", ")", ":", "p", "=", "self", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "output", ",", "_", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", "!=", "0", ":", "raise", "RemoteCalledProcessError", "(", "p", ".", "returncode", ",", "cmd", ",", "self", ".", "host", ",", "output", "=", "output", ")", "return", "output" ]
Execute a shell command remotely and return the output. Simplified version of Popen when you only want the output as a string and detect any errors.
[ "Execute", "a", "shell", "command", "remotely", "and", "return", "the", "output", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ssh.py#L123-L133
train
spotify/luigi
luigi/contrib/ssh.py
RemoteContext.tunnel
def tunnel(self, local_port, remote_port=None, remote_host="localhost"): """ Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context. Remember to close() the returned "tunnel" object in order to clean up after yourself when you are done with the tunnel. """ tunnel_host = "{0}:{1}:{2}".format(local_port, remote_host, remote_port) proc = self.Popen( # cat so we can shut down gracefully by closing stdin ["-L", tunnel_host, "echo -n ready && cat"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) # make sure to get the data so we know the connection is established ready = proc.stdout.read(5) assert ready == b"ready", "Didn't get ready from remote echo" yield # user code executed here proc.communicate() assert proc.returncode == 0, "Tunnel process did an unclean exit (returncode %s)" % (proc.returncode,)
python
def tunnel(self, local_port, remote_port=None, remote_host="localhost"): """ Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context. Remember to close() the returned "tunnel" object in order to clean up after yourself when you are done with the tunnel. """ tunnel_host = "{0}:{1}:{2}".format(local_port, remote_host, remote_port) proc = self.Popen( # cat so we can shut down gracefully by closing stdin ["-L", tunnel_host, "echo -n ready && cat"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) # make sure to get the data so we know the connection is established ready = proc.stdout.read(5) assert ready == b"ready", "Didn't get ready from remote echo" yield # user code executed here proc.communicate() assert proc.returncode == 0, "Tunnel process did an unclean exit (returncode %s)" % (proc.returncode,)
[ "def", "tunnel", "(", "self", ",", "local_port", ",", "remote_port", "=", "None", ",", "remote_host", "=", "\"localhost\"", ")", ":", "tunnel_host", "=", "\"{0}:{1}:{2}\"", ".", "format", "(", "local_port", ",", "remote_host", ",", "remote_port", ")", "proc", "=", "self", ".", "Popen", "(", "# cat so we can shut down gracefully by closing stdin", "[", "\"-L\"", ",", "tunnel_host", ",", "\"echo -n ready && cat\"", "]", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", ")", "# make sure to get the data so we know the connection is established", "ready", "=", "proc", ".", "stdout", ".", "read", "(", "5", ")", "assert", "ready", "==", "b\"ready\"", ",", "\"Didn't get ready from remote echo\"", "yield", "# user code executed here", "proc", ".", "communicate", "(", ")", "assert", "proc", ".", "returncode", "==", "0", ",", "\"Tunnel process did an unclean exit (returncode %s)\"", "%", "(", "proc", ".", "returncode", ",", ")" ]
Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context. Remember to close() the returned "tunnel" object in order to clean up after yourself when you are done with the tunnel.
[ "Open", "a", "tunnel", "between", "localhost", ":", "local_port", "and", "remote_host", ":", "remote_port", "via", "the", "host", "specified", "by", "this", "context", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ssh.py#L136-L155
train
spotify/luigi
luigi/contrib/ssh.py
RemoteFileSystem.isdir
def isdir(self, path): """ Return `True` if directory at `path` exist, False otherwise. """ try: self.remote_context.check_output(["test", "-d", path]) except subprocess.CalledProcessError as e: if e.returncode == 1: return False else: raise return True
python
def isdir(self, path): """ Return `True` if directory at `path` exist, False otherwise. """ try: self.remote_context.check_output(["test", "-d", path]) except subprocess.CalledProcessError as e: if e.returncode == 1: return False else: raise return True
[ "def", "isdir", "(", "self", ",", "path", ")", ":", "try", ":", "self", ".", "remote_context", ".", "check_output", "(", "[", "\"test\"", ",", "\"-d\"", ",", "path", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "if", "e", ".", "returncode", "==", "1", ":", "return", "False", "else", ":", "raise", "return", "True" ]
Return `True` if directory at `path` exist, False otherwise.
[ "Return", "True", "if", "directory", "at", "path", "exist", "False", "otherwise", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ssh.py#L184-L195
train
spotify/luigi
luigi/contrib/ssh.py
RemoteFileSystem.remove
def remove(self, path, recursive=True): """ Remove file or directory at location `path`. """ if recursive: cmd = ["rm", "-r", path] else: cmd = ["rm", path] self.remote_context.check_output(cmd)
python
def remove(self, path, recursive=True): """ Remove file or directory at location `path`. """ if recursive: cmd = ["rm", "-r", path] else: cmd = ["rm", path] self.remote_context.check_output(cmd)
[ "def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "True", ")", ":", "if", "recursive", ":", "cmd", "=", "[", "\"rm\"", ",", "\"-r\"", ",", "path", "]", "else", ":", "cmd", "=", "[", "\"rm\"", ",", "path", "]", "self", ".", "remote_context", ".", "check_output", "(", "cmd", ")" ]
Remove file or directory at location `path`.
[ "Remove", "file", "or", "directory", "at", "location", "path", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ssh.py#L197-L206
train
spotify/luigi
luigi/lock.py
getpcmd
def getpcmd(pid): """ Returns command of process. :param pid: """ if os.name == "nt": # Use wmic command instead of ps on Windows. cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, ) with os.popen(cmd, 'r') as p: lines = [line for line in p.readlines() if line.strip("\r\n ") != ""] if lines: _, val = lines return val elif sys.platform == "darwin": # Use pgrep instead of /proc on macOS. pidfile = ".%d.pid" % (pid, ) with open(pidfile, 'w') as f: f.write(str(pid)) try: p = Popen(['pgrep', '-lf', '-F', pidfile], stdout=PIPE) stdout, _ = p.communicate() line = stdout.decode('utf8').strip() if line: _, scmd = line.split(' ', 1) return scmd finally: os.unlink(pidfile) else: # Use the /proc filesystem # At least on android there have been some issues with not all # process infos being readable. In these cases using the `ps` command # worked. See the pull request at # https://github.com/spotify/luigi/pull/1876 try: with open('/proc/{0}/cmdline'.format(pid), 'r') as fh: if six.PY3: return fh.read().replace('\0', ' ').rstrip() else: return fh.read().replace('\0', ' ').decode('utf8').rstrip() except IOError: # the system may not allow reading the command line # of a process owned by another user pass # Fallback instead of None, for e.g. Cygwin where -o is an "unknown option" for the ps command: return '[PROCESS_WITH_PID={}]'.format(pid)
python
def getpcmd(pid): """ Returns command of process. :param pid: """ if os.name == "nt": # Use wmic command instead of ps on Windows. cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, ) with os.popen(cmd, 'r') as p: lines = [line for line in p.readlines() if line.strip("\r\n ") != ""] if lines: _, val = lines return val elif sys.platform == "darwin": # Use pgrep instead of /proc on macOS. pidfile = ".%d.pid" % (pid, ) with open(pidfile, 'w') as f: f.write(str(pid)) try: p = Popen(['pgrep', '-lf', '-F', pidfile], stdout=PIPE) stdout, _ = p.communicate() line = stdout.decode('utf8').strip() if line: _, scmd = line.split(' ', 1) return scmd finally: os.unlink(pidfile) else: # Use the /proc filesystem # At least on android there have been some issues with not all # process infos being readable. In these cases using the `ps` command # worked. See the pull request at # https://github.com/spotify/luigi/pull/1876 try: with open('/proc/{0}/cmdline'.format(pid), 'r') as fh: if six.PY3: return fh.read().replace('\0', ' ').rstrip() else: return fh.read().replace('\0', ' ').decode('utf8').rstrip() except IOError: # the system may not allow reading the command line # of a process owned by another user pass # Fallback instead of None, for e.g. Cygwin where -o is an "unknown option" for the ps command: return '[PROCESS_WITH_PID={}]'.format(pid)
[ "def", "getpcmd", "(", "pid", ")", ":", "if", "os", ".", "name", "==", "\"nt\"", ":", "# Use wmic command instead of ps on Windows.", "cmd", "=", "'wmic path win32_process where ProcessID=%s get Commandline 2> nul'", "%", "(", "pid", ",", ")", "with", "os", ".", "popen", "(", "cmd", ",", "'r'", ")", "as", "p", ":", "lines", "=", "[", "line", "for", "line", "in", "p", ".", "readlines", "(", ")", "if", "line", ".", "strip", "(", "\"\\r\\n \"", ")", "!=", "\"\"", "]", "if", "lines", ":", "_", ",", "val", "=", "lines", "return", "val", "elif", "sys", ".", "platform", "==", "\"darwin\"", ":", "# Use pgrep instead of /proc on macOS.", "pidfile", "=", "\".%d.pid\"", "%", "(", "pid", ",", ")", "with", "open", "(", "pidfile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "str", "(", "pid", ")", ")", "try", ":", "p", "=", "Popen", "(", "[", "'pgrep'", ",", "'-lf'", ",", "'-F'", ",", "pidfile", "]", ",", "stdout", "=", "PIPE", ")", "stdout", ",", "_", "=", "p", ".", "communicate", "(", ")", "line", "=", "stdout", ".", "decode", "(", "'utf8'", ")", ".", "strip", "(", ")", "if", "line", ":", "_", ",", "scmd", "=", "line", ".", "split", "(", "' '", ",", "1", ")", "return", "scmd", "finally", ":", "os", ".", "unlink", "(", "pidfile", ")", "else", ":", "# Use the /proc filesystem", "# At least on android there have been some issues with not all", "# process infos being readable. In these cases using the `ps` command", "# worked. See the pull request at", "# https://github.com/spotify/luigi/pull/1876", "try", ":", "with", "open", "(", "'/proc/{0}/cmdline'", ".", "format", "(", "pid", ")", ",", "'r'", ")", "as", "fh", ":", "if", "six", ".", "PY3", ":", "return", "fh", ".", "read", "(", ")", ".", "replace", "(", "'\\0'", ",", "' '", ")", ".", "rstrip", "(", ")", "else", ":", "return", "fh", ".", "read", "(", ")", ".", "replace", "(", "'\\0'", ",", "' '", ")", ".", "decode", "(", "'utf8'", ")", ".", "rstrip", "(", ")", "except", "IOError", ":", "# the system may not allow reading the command line", "# of a process owned by another user", "pass", "# Fallback instead of None, for e.g. Cygwin where -o is an \"unknown option\" for the ps command:", "return", "'[PROCESS_WITH_PID={}]'", ".", "format", "(", "pid", ")" ]
Returns command of process. :param pid:
[ "Returns", "command", "of", "process", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/lock.py#L33-L79
train
spotify/luigi
luigi/lock.py
acquire_for
def acquire_for(pid_dir, num_available=1, kill_signal=None): """ Makes sure the process is only run once at the same time with the same name. Notice that we since we check the process name, different parameters to the same command can spawn multiple processes at the same time, i.e. running "/usr/bin/my_process" does not prevent anyone from launching "/usr/bin/my_process --foo bar". """ my_pid, my_cmd, pid_file = get_info(pid_dir) # Create a pid file if it does not exist try: os.mkdir(pid_dir) os.chmod(pid_dir, 0o777) except OSError as exc: if exc.errno != errno.EEXIST: raise pass # Let variable "pids" be all pids who exist in the .pid-file who are still # about running the same command. pids = {pid for pid in _read_pids_file(pid_file) if getpcmd(pid) == my_cmd} if kill_signal is not None: for pid in pids: os.kill(pid, kill_signal) print('Sent kill signal to Pids: {}'.format(pids)) # We allow for the killer to progress, yet we don't want these to stack # up! So we only allow it once. num_available += 1 if len(pids) >= num_available: # We are already running under a different pid print('Pid(s) {} already running'.format(pids)) if kill_signal is not None: print('Note: There have (probably) been 1 other "--take-lock"' ' process which continued to run! Probably no need to run' ' this one as well.') return False _write_pids_file(pid_file, pids | {my_pid}) return True
python
def acquire_for(pid_dir, num_available=1, kill_signal=None): """ Makes sure the process is only run once at the same time with the same name. Notice that we since we check the process name, different parameters to the same command can spawn multiple processes at the same time, i.e. running "/usr/bin/my_process" does not prevent anyone from launching "/usr/bin/my_process --foo bar". """ my_pid, my_cmd, pid_file = get_info(pid_dir) # Create a pid file if it does not exist try: os.mkdir(pid_dir) os.chmod(pid_dir, 0o777) except OSError as exc: if exc.errno != errno.EEXIST: raise pass # Let variable "pids" be all pids who exist in the .pid-file who are still # about running the same command. pids = {pid for pid in _read_pids_file(pid_file) if getpcmd(pid) == my_cmd} if kill_signal is not None: for pid in pids: os.kill(pid, kill_signal) print('Sent kill signal to Pids: {}'.format(pids)) # We allow for the killer to progress, yet we don't want these to stack # up! So we only allow it once. num_available += 1 if len(pids) >= num_available: # We are already running under a different pid print('Pid(s) {} already running'.format(pids)) if kill_signal is not None: print('Note: There have (probably) been 1 other "--take-lock"' ' process which continued to run! Probably no need to run' ' this one as well.') return False _write_pids_file(pid_file, pids | {my_pid}) return True
[ "def", "acquire_for", "(", "pid_dir", ",", "num_available", "=", "1", ",", "kill_signal", "=", "None", ")", ":", "my_pid", ",", "my_cmd", ",", "pid_file", "=", "get_info", "(", "pid_dir", ")", "# Create a pid file if it does not exist", "try", ":", "os", ".", "mkdir", "(", "pid_dir", ")", "os", ".", "chmod", "(", "pid_dir", ",", "0o777", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "pass", "# Let variable \"pids\" be all pids who exist in the .pid-file who are still", "# about running the same command.", "pids", "=", "{", "pid", "for", "pid", "in", "_read_pids_file", "(", "pid_file", ")", "if", "getpcmd", "(", "pid", ")", "==", "my_cmd", "}", "if", "kill_signal", "is", "not", "None", ":", "for", "pid", "in", "pids", ":", "os", ".", "kill", "(", "pid", ",", "kill_signal", ")", "print", "(", "'Sent kill signal to Pids: {}'", ".", "format", "(", "pids", ")", ")", "# We allow for the killer to progress, yet we don't want these to stack", "# up! So we only allow it once.", "num_available", "+=", "1", "if", "len", "(", "pids", ")", ">=", "num_available", ":", "# We are already running under a different pid", "print", "(", "'Pid(s) {} already running'", ".", "format", "(", "pids", ")", ")", "if", "kill_signal", "is", "not", "None", ":", "print", "(", "'Note: There have (probably) been 1 other \"--take-lock\"'", "' process which continued to run! Probably no need to run'", "' this one as well.'", ")", "return", "False", "_write_pids_file", "(", "pid_file", ",", "pids", "|", "{", "my_pid", "}", ")", "return", "True" ]
Makes sure the process is only run once at the same time with the same name. Notice that we since we check the process name, different parameters to the same command can spawn multiple processes at the same time, i.e. running "/usr/bin/my_process" does not prevent anyone from launching "/usr/bin/my_process --foo bar".
[ "Makes", "sure", "the", "process", "is", "only", "run", "once", "at", "the", "same", "time", "with", "the", "same", "name", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/lock.py#L94-L138
train
spotify/luigi
luigi/scheduler.py
Failures.add_failure
def add_failure(self): """ Add a failure event with the current timestamp. """ failure_time = time.time() if not self.first_failure_time: self.first_failure_time = failure_time self.failures.append(failure_time)
python
def add_failure(self): """ Add a failure event with the current timestamp. """ failure_time = time.time() if not self.first_failure_time: self.first_failure_time = failure_time self.failures.append(failure_time)
[ "def", "add_failure", "(", "self", ")", ":", "failure_time", "=", "time", ".", "time", "(", ")", "if", "not", "self", ".", "first_failure_time", ":", "self", ".", "first_failure_time", "=", "failure_time", "self", ".", "failures", ".", "append", "(", "failure_time", ")" ]
Add a failure event with the current timestamp.
[ "Add", "a", "failure", "event", "with", "the", "current", "timestamp", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L179-L188
train
spotify/luigi
luigi/scheduler.py
Failures.num_failures
def num_failures(self): """ Return the number of failures in the window. """ min_time = time.time() - self.window while self.failures and self.failures[0] < min_time: self.failures.popleft() return len(self.failures)
python
def num_failures(self): """ Return the number of failures in the window. """ min_time = time.time() - self.window while self.failures and self.failures[0] < min_time: self.failures.popleft() return len(self.failures)
[ "def", "num_failures", "(", "self", ")", ":", "min_time", "=", "time", ".", "time", "(", ")", "-", "self", ".", "window", "while", "self", ".", "failures", "and", "self", ".", "failures", "[", "0", "]", "<", "min_time", ":", "self", ".", "failures", ".", "popleft", "(", ")", "return", "len", "(", "self", ".", "failures", ")" ]
Return the number of failures in the window.
[ "Return", "the", "number", "of", "failures", "in", "the", "window", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L190-L199
train
spotify/luigi
luigi/scheduler.py
Worker.is_trivial_worker
def is_trivial_worker(self, state): """ If it's not an assistant having only tasks that are without requirements. We have to pass the state parameter for optimization reasons. """ if self.assistant: return False return all(not task.resources for task in self.get_tasks(state, PENDING))
python
def is_trivial_worker(self, state): """ If it's not an assistant having only tasks that are without requirements. We have to pass the state parameter for optimization reasons. """ if self.assistant: return False return all(not task.resources for task in self.get_tasks(state, PENDING))
[ "def", "is_trivial_worker", "(", "self", ",", "state", ")", ":", "if", "self", ".", "assistant", ":", "return", "False", "return", "all", "(", "not", "task", ".", "resources", "for", "task", "in", "self", ".", "get_tasks", "(", "state", ",", "PENDING", ")", ")" ]
If it's not an assistant having only tasks that are without requirements. We have to pass the state parameter for optimization reasons.
[ "If", "it", "s", "not", "an", "assistant", "having", "only", "tasks", "that", "are", "without", "requirements", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L401-L410
train
spotify/luigi
luigi/scheduler.py
SimpleTaskState.num_pending_tasks
def num_pending_tasks(self): """ Return how many tasks are PENDING + RUNNING. O(1). """ return len(self._status_tasks[PENDING]) + len(self._status_tasks[RUNNING])
python
def num_pending_tasks(self): """ Return how many tasks are PENDING + RUNNING. O(1). """ return len(self._status_tasks[PENDING]) + len(self._status_tasks[RUNNING])
[ "def", "num_pending_tasks", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_status_tasks", "[", "PENDING", "]", ")", "+", "len", "(", "self", ".", "_status_tasks", "[", "RUNNING", "]", ")" ]
Return how many tasks are PENDING + RUNNING. O(1).
[ "Return", "how", "many", "tasks", "are", "PENDING", "+", "RUNNING", ".", "O", "(", "1", ")", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L518-L522
train
spotify/luigi
luigi/scheduler.py
Scheduler._update_priority
def _update_priority(self, task, prio, worker): """ Update priority of the given task. Priority can only be increased. If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled. """ task.priority = prio = max(prio, task.priority) for dep in task.deps or []: t = self._state.get_task(dep) if t is not None and prio > t.priority: self._update_priority(t, prio, worker)
python
def _update_priority(self, task, prio, worker): """ Update priority of the given task. Priority can only be increased. If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled. """ task.priority = prio = max(prio, task.priority) for dep in task.deps or []: t = self._state.get_task(dep) if t is not None and prio > t.priority: self._update_priority(t, prio, worker)
[ "def", "_update_priority", "(", "self", ",", "task", ",", "prio", ",", "worker", ")", ":", "task", ".", "priority", "=", "prio", "=", "max", "(", "prio", ",", "task", ".", "priority", ")", "for", "dep", "in", "task", ".", "deps", "or", "[", "]", ":", "t", "=", "self", ".", "_state", ".", "get_task", "(", "dep", ")", "if", "t", "is", "not", "None", "and", "prio", ">", "t", ".", "priority", ":", "self", ".", "_update_priority", "(", "t", ",", "prio", ",", "worker", ")" ]
Update priority of the given task. Priority can only be increased. If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled.
[ "Update", "priority", "of", "the", "given", "task", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L771-L782
train
spotify/luigi
luigi/scheduler.py
Scheduler.add_task
def add_task(self, task_id=None, status=PENDING, runnable=True, deps=None, new_deps=None, expl=None, resources=None, priority=0, family='', module=None, params=None, param_visibilities=None, accepts_messages=False, assistant=False, tracking_url=None, worker=None, batchable=None, batch_id=None, retry_policy_dict=None, owners=None, **kwargs): """ * add task identified by task_id if it doesn't exist * if deps is not None, update dependency list * update status of task * add additional workers/stakeholders * update priority when needed """ assert worker is not None worker_id = worker worker = self._update_worker(worker_id) resources = {} if resources is None else resources.copy() if retry_policy_dict is None: retry_policy_dict = {} retry_policy = self._generate_retry_policy(retry_policy_dict) if worker.enabled: _default_task = self._make_task( task_id=task_id, status=PENDING, deps=deps, resources=resources, priority=priority, family=family, module=module, params=params, param_visibilities=param_visibilities, ) else: _default_task = None task = self._state.get_task(task_id, setdefault=_default_task) if task is None or (task.status != RUNNING and not worker.enabled): return # for setting priority, we'll sometimes create tasks with unset family and params if not task.family: task.family = family if not getattr(task, 'module', None): task.module = module if not getattr(task, 'param_visibilities', None): task.param_visibilities = _get_default(param_visibilities, {}) if not task.params: task.set_params(params) if batch_id is not None: task.batch_id = batch_id if status == RUNNING and not task.worker_running: task.worker_running = worker_id if batch_id: # copy resources_running of the first batch task batch_tasks = self._state.get_batch_running_tasks(batch_id) task.resources_running = batch_tasks[0].resources_running.copy() task.time_running = time.time() if accepts_messages is not None: task.accepts_messages = accepts_messages if tracking_url is not None or task.status != RUNNING: task.tracking_url = tracking_url if task.batch_id is not None: for batch_task in self._state.get_batch_running_tasks(task.batch_id): batch_task.tracking_url = tracking_url if batchable is not None: task.batchable = batchable if task.remove is not None: task.remove = None # unmark task for removal so it isn't removed after being added if expl is not None: task.expl = expl if task.batch_id is not None: for batch_task in self._state.get_batch_running_tasks(task.batch_id): batch_task.expl = expl task_is_not_running = task.status not in (RUNNING, BATCH_RUNNING) task_started_a_run = status in (DONE, FAILED, RUNNING) running_on_this_worker = task.worker_running == worker_id if task_is_not_running or (task_started_a_run and running_on_this_worker) or new_deps: # don't allow re-scheduling of task while it is running, it must either fail or succeed on the worker actually running it if status != task.status or status == PENDING: # Update the DB only if there was a acctual change, to prevent noise. # We also check for status == PENDING b/c that's the default value # (so checking for status != task.status woule lie) self._update_task_history(task, status) self._state.set_status(task, PENDING if status == SUSPENDED else status, self._config) if status == FAILED and self._config.batch_emails: batched_params, _ = self._state.get_batcher(worker_id, family) if batched_params: unbatched_params = { param: value for param, value in six.iteritems(task.params) if param not in batched_params } else: unbatched_params = task.params try: expl_raw = json.loads(expl) except ValueError: expl_raw = expl self._email_batcher.add_failure( task.pretty_id, task.family, unbatched_params, expl_raw, owners) if task.status == DISABLED: self._email_batcher.add_disable( task.pretty_id, task.family, unbatched_params, owners) if deps is not None: task.deps = set(deps) if new_deps is not None: task.deps.update(new_deps) if resources is not None: task.resources = resources if worker.enabled and not assistant: task.stakeholders.add(worker_id) # Task dependencies might not exist yet. Let's create dummy tasks for them for now. # Otherwise the task dependencies might end up being pruned if scheduling takes a long time for dep in task.deps or []: t = self._state.get_task(dep, setdefault=self._make_task(task_id=dep, status=UNKNOWN, deps=None, priority=priority)) t.stakeholders.add(worker_id) self._update_priority(task, priority, worker_id) # Because some tasks (non-dynamic dependencies) are `_make_task`ed # before we know their retry_policy, we always set it here task.retry_policy = retry_policy if runnable and status != FAILED and worker.enabled: task.workers.add(worker_id) self._state.get_worker(worker_id).tasks.add(task) task.runnable = runnable
python
def add_task(self, task_id=None, status=PENDING, runnable=True, deps=None, new_deps=None, expl=None, resources=None, priority=0, family='', module=None, params=None, param_visibilities=None, accepts_messages=False, assistant=False, tracking_url=None, worker=None, batchable=None, batch_id=None, retry_policy_dict=None, owners=None, **kwargs): """ * add task identified by task_id if it doesn't exist * if deps is not None, update dependency list * update status of task * add additional workers/stakeholders * update priority when needed """ assert worker is not None worker_id = worker worker = self._update_worker(worker_id) resources = {} if resources is None else resources.copy() if retry_policy_dict is None: retry_policy_dict = {} retry_policy = self._generate_retry_policy(retry_policy_dict) if worker.enabled: _default_task = self._make_task( task_id=task_id, status=PENDING, deps=deps, resources=resources, priority=priority, family=family, module=module, params=params, param_visibilities=param_visibilities, ) else: _default_task = None task = self._state.get_task(task_id, setdefault=_default_task) if task is None or (task.status != RUNNING and not worker.enabled): return # for setting priority, we'll sometimes create tasks with unset family and params if not task.family: task.family = family if not getattr(task, 'module', None): task.module = module if not getattr(task, 'param_visibilities', None): task.param_visibilities = _get_default(param_visibilities, {}) if not task.params: task.set_params(params) if batch_id is not None: task.batch_id = batch_id if status == RUNNING and not task.worker_running: task.worker_running = worker_id if batch_id: # copy resources_running of the first batch task batch_tasks = self._state.get_batch_running_tasks(batch_id) task.resources_running = batch_tasks[0].resources_running.copy() task.time_running = time.time() if accepts_messages is not None: task.accepts_messages = accepts_messages if tracking_url is not None or task.status != RUNNING: task.tracking_url = tracking_url if task.batch_id is not None: for batch_task in self._state.get_batch_running_tasks(task.batch_id): batch_task.tracking_url = tracking_url if batchable is not None: task.batchable = batchable if task.remove is not None: task.remove = None # unmark task for removal so it isn't removed after being added if expl is not None: task.expl = expl if task.batch_id is not None: for batch_task in self._state.get_batch_running_tasks(task.batch_id): batch_task.expl = expl task_is_not_running = task.status not in (RUNNING, BATCH_RUNNING) task_started_a_run = status in (DONE, FAILED, RUNNING) running_on_this_worker = task.worker_running == worker_id if task_is_not_running or (task_started_a_run and running_on_this_worker) or new_deps: # don't allow re-scheduling of task while it is running, it must either fail or succeed on the worker actually running it if status != task.status or status == PENDING: # Update the DB only if there was a acctual change, to prevent noise. # We also check for status == PENDING b/c that's the default value # (so checking for status != task.status woule lie) self._update_task_history(task, status) self._state.set_status(task, PENDING if status == SUSPENDED else status, self._config) if status == FAILED and self._config.batch_emails: batched_params, _ = self._state.get_batcher(worker_id, family) if batched_params: unbatched_params = { param: value for param, value in six.iteritems(task.params) if param not in batched_params } else: unbatched_params = task.params try: expl_raw = json.loads(expl) except ValueError: expl_raw = expl self._email_batcher.add_failure( task.pretty_id, task.family, unbatched_params, expl_raw, owners) if task.status == DISABLED: self._email_batcher.add_disable( task.pretty_id, task.family, unbatched_params, owners) if deps is not None: task.deps = set(deps) if new_deps is not None: task.deps.update(new_deps) if resources is not None: task.resources = resources if worker.enabled and not assistant: task.stakeholders.add(worker_id) # Task dependencies might not exist yet. Let's create dummy tasks for them for now. # Otherwise the task dependencies might end up being pruned if scheduling takes a long time for dep in task.deps or []: t = self._state.get_task(dep, setdefault=self._make_task(task_id=dep, status=UNKNOWN, deps=None, priority=priority)) t.stakeholders.add(worker_id) self._update_priority(task, priority, worker_id) # Because some tasks (non-dynamic dependencies) are `_make_task`ed # before we know their retry_policy, we always set it here task.retry_policy = retry_policy if runnable and status != FAILED and worker.enabled: task.workers.add(worker_id) self._state.get_worker(worker_id).tasks.add(task) task.runnable = runnable
[ "def", "add_task", "(", "self", ",", "task_id", "=", "None", ",", "status", "=", "PENDING", ",", "runnable", "=", "True", ",", "deps", "=", "None", ",", "new_deps", "=", "None", ",", "expl", "=", "None", ",", "resources", "=", "None", ",", "priority", "=", "0", ",", "family", "=", "''", ",", "module", "=", "None", ",", "params", "=", "None", ",", "param_visibilities", "=", "None", ",", "accepts_messages", "=", "False", ",", "assistant", "=", "False", ",", "tracking_url", "=", "None", ",", "worker", "=", "None", ",", "batchable", "=", "None", ",", "batch_id", "=", "None", ",", "retry_policy_dict", "=", "None", ",", "owners", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "worker", "is", "not", "None", "worker_id", "=", "worker", "worker", "=", "self", ".", "_update_worker", "(", "worker_id", ")", "resources", "=", "{", "}", "if", "resources", "is", "None", "else", "resources", ".", "copy", "(", ")", "if", "retry_policy_dict", "is", "None", ":", "retry_policy_dict", "=", "{", "}", "retry_policy", "=", "self", ".", "_generate_retry_policy", "(", "retry_policy_dict", ")", "if", "worker", ".", "enabled", ":", "_default_task", "=", "self", ".", "_make_task", "(", "task_id", "=", "task_id", ",", "status", "=", "PENDING", ",", "deps", "=", "deps", ",", "resources", "=", "resources", ",", "priority", "=", "priority", ",", "family", "=", "family", ",", "module", "=", "module", ",", "params", "=", "params", ",", "param_visibilities", "=", "param_visibilities", ",", ")", "else", ":", "_default_task", "=", "None", "task", "=", "self", ".", "_state", ".", "get_task", "(", "task_id", ",", "setdefault", "=", "_default_task", ")", "if", "task", "is", "None", "or", "(", "task", ".", "status", "!=", "RUNNING", "and", "not", "worker", ".", "enabled", ")", ":", "return", "# for setting priority, we'll sometimes create tasks with unset family and params", "if", "not", "task", ".", "family", ":", "task", ".", "family", "=", "family", "if", "not", "getattr", "(", "task", ",", "'module'", ",", "None", ")", ":", "task", ".", "module", "=", "module", "if", "not", "getattr", "(", "task", ",", "'param_visibilities'", ",", "None", ")", ":", "task", ".", "param_visibilities", "=", "_get_default", "(", "param_visibilities", ",", "{", "}", ")", "if", "not", "task", ".", "params", ":", "task", ".", "set_params", "(", "params", ")", "if", "batch_id", "is", "not", "None", ":", "task", ".", "batch_id", "=", "batch_id", "if", "status", "==", "RUNNING", "and", "not", "task", ".", "worker_running", ":", "task", ".", "worker_running", "=", "worker_id", "if", "batch_id", ":", "# copy resources_running of the first batch task", "batch_tasks", "=", "self", ".", "_state", ".", "get_batch_running_tasks", "(", "batch_id", ")", "task", ".", "resources_running", "=", "batch_tasks", "[", "0", "]", ".", "resources_running", ".", "copy", "(", ")", "task", ".", "time_running", "=", "time", ".", "time", "(", ")", "if", "accepts_messages", "is", "not", "None", ":", "task", ".", "accepts_messages", "=", "accepts_messages", "if", "tracking_url", "is", "not", "None", "or", "task", ".", "status", "!=", "RUNNING", ":", "task", ".", "tracking_url", "=", "tracking_url", "if", "task", ".", "batch_id", "is", "not", "None", ":", "for", "batch_task", "in", "self", ".", "_state", ".", "get_batch_running_tasks", "(", "task", ".", "batch_id", ")", ":", "batch_task", ".", "tracking_url", "=", "tracking_url", "if", "batchable", "is", "not", "None", ":", "task", ".", "batchable", "=", "batchable", "if", "task", ".", "remove", "is", "not", "None", ":", "task", ".", "remove", "=", "None", "# unmark task for removal so it isn't removed after being added", "if", "expl", "is", "not", "None", ":", "task", ".", "expl", "=", "expl", "if", "task", ".", "batch_id", "is", "not", "None", ":", "for", "batch_task", "in", "self", ".", "_state", ".", "get_batch_running_tasks", "(", "task", ".", "batch_id", ")", ":", "batch_task", ".", "expl", "=", "expl", "task_is_not_running", "=", "task", ".", "status", "not", "in", "(", "RUNNING", ",", "BATCH_RUNNING", ")", "task_started_a_run", "=", "status", "in", "(", "DONE", ",", "FAILED", ",", "RUNNING", ")", "running_on_this_worker", "=", "task", ".", "worker_running", "==", "worker_id", "if", "task_is_not_running", "or", "(", "task_started_a_run", "and", "running_on_this_worker", ")", "or", "new_deps", ":", "# don't allow re-scheduling of task while it is running, it must either fail or succeed on the worker actually running it", "if", "status", "!=", "task", ".", "status", "or", "status", "==", "PENDING", ":", "# Update the DB only if there was a acctual change, to prevent noise.", "# We also check for status == PENDING b/c that's the default value", "# (so checking for status != task.status woule lie)", "self", ".", "_update_task_history", "(", "task", ",", "status", ")", "self", ".", "_state", ".", "set_status", "(", "task", ",", "PENDING", "if", "status", "==", "SUSPENDED", "else", "status", ",", "self", ".", "_config", ")", "if", "status", "==", "FAILED", "and", "self", ".", "_config", ".", "batch_emails", ":", "batched_params", ",", "_", "=", "self", ".", "_state", ".", "get_batcher", "(", "worker_id", ",", "family", ")", "if", "batched_params", ":", "unbatched_params", "=", "{", "param", ":", "value", "for", "param", ",", "value", "in", "six", ".", "iteritems", "(", "task", ".", "params", ")", "if", "param", "not", "in", "batched_params", "}", "else", ":", "unbatched_params", "=", "task", ".", "params", "try", ":", "expl_raw", "=", "json", ".", "loads", "(", "expl", ")", "except", "ValueError", ":", "expl_raw", "=", "expl", "self", ".", "_email_batcher", ".", "add_failure", "(", "task", ".", "pretty_id", ",", "task", ".", "family", ",", "unbatched_params", ",", "expl_raw", ",", "owners", ")", "if", "task", ".", "status", "==", "DISABLED", ":", "self", ".", "_email_batcher", ".", "add_disable", "(", "task", ".", "pretty_id", ",", "task", ".", "family", ",", "unbatched_params", ",", "owners", ")", "if", "deps", "is", "not", "None", ":", "task", ".", "deps", "=", "set", "(", "deps", ")", "if", "new_deps", "is", "not", "None", ":", "task", ".", "deps", ".", "update", "(", "new_deps", ")", "if", "resources", "is", "not", "None", ":", "task", ".", "resources", "=", "resources", "if", "worker", ".", "enabled", "and", "not", "assistant", ":", "task", ".", "stakeholders", ".", "add", "(", "worker_id", ")", "# Task dependencies might not exist yet. Let's create dummy tasks for them for now.", "# Otherwise the task dependencies might end up being pruned if scheduling takes a long time", "for", "dep", "in", "task", ".", "deps", "or", "[", "]", ":", "t", "=", "self", ".", "_state", ".", "get_task", "(", "dep", ",", "setdefault", "=", "self", ".", "_make_task", "(", "task_id", "=", "dep", ",", "status", "=", "UNKNOWN", ",", "deps", "=", "None", ",", "priority", "=", "priority", ")", ")", "t", ".", "stakeholders", ".", "add", "(", "worker_id", ")", "self", ".", "_update_priority", "(", "task", ",", "priority", ",", "worker_id", ")", "# Because some tasks (non-dynamic dependencies) are `_make_task`ed", "# before we know their retry_policy, we always set it here", "task", ".", "retry_policy", "=", "retry_policy", "if", "runnable", "and", "status", "!=", "FAILED", "and", "worker", ".", "enabled", ":", "task", ".", "workers", ".", "add", "(", "worker_id", ")", "self", ".", "_state", ".", "get_worker", "(", "worker_id", ")", ".", "tasks", ".", "add", "(", "task", ")", "task", ".", "runnable", "=", "runnable" ]
* add task identified by task_id if it doesn't exist * if deps is not None, update dependency list * update status of task * add additional workers/stakeholders * update priority when needed
[ "*", "add", "task", "identified", "by", "task_id", "if", "it", "doesn", "t", "exist", "*", "if", "deps", "is", "not", "None", "update", "dependency", "list", "*", "update", "status", "of", "task", "*", "add", "additional", "workers", "/", "stakeholders", "*", "update", "priority", "when", "needed" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L803-L940
train
spotify/luigi
luigi/scheduler.py
Scheduler._traverse_graph
def _traverse_graph(self, root_task_id, seen=None, dep_func=None, include_done=True): """ Returns the dependency graph rooted at task_id This does a breadth-first traversal to find the nodes closest to the root before hitting the scheduler.max_graph_nodes limit. :param root_task_id: the id of the graph's root :return: A map of task id to serialized node """ if seen is None: seen = set() elif root_task_id in seen: return {} if dep_func is None: def dep_func(t): return t.deps seen.add(root_task_id) serialized = {} queue = collections.deque([root_task_id]) while queue: task_id = queue.popleft() task = self._state.get_task(task_id) if task is None or not task.family: logger.debug('Missing task for id [%s]', task_id) # NOTE : If a dependency is missing from self._state there is no way to deduce the # task family and parameters. family_match = TASK_FAMILY_RE.match(task_id) family = family_match.group(1) if family_match else UNKNOWN params = {'task_id': task_id} serialized[task_id] = { 'deps': [], 'status': UNKNOWN, 'workers': [], 'start_time': UNKNOWN, 'params': params, 'name': family, 'display_name': task_id, 'priority': 0, } else: deps = dep_func(task) if not include_done: deps = list(self._filter_done(deps)) serialized[task_id] = self._serialize_task(task_id, deps=deps) for dep in sorted(deps): if dep not in seen: seen.add(dep) queue.append(dep) if task_id != root_task_id: del serialized[task_id]['display_name'] if len(serialized) >= self._config.max_graph_nodes: break return serialized
python
def _traverse_graph(self, root_task_id, seen=None, dep_func=None, include_done=True): """ Returns the dependency graph rooted at task_id This does a breadth-first traversal to find the nodes closest to the root before hitting the scheduler.max_graph_nodes limit. :param root_task_id: the id of the graph's root :return: A map of task id to serialized node """ if seen is None: seen = set() elif root_task_id in seen: return {} if dep_func is None: def dep_func(t): return t.deps seen.add(root_task_id) serialized = {} queue = collections.deque([root_task_id]) while queue: task_id = queue.popleft() task = self._state.get_task(task_id) if task is None or not task.family: logger.debug('Missing task for id [%s]', task_id) # NOTE : If a dependency is missing from self._state there is no way to deduce the # task family and parameters. family_match = TASK_FAMILY_RE.match(task_id) family = family_match.group(1) if family_match else UNKNOWN params = {'task_id': task_id} serialized[task_id] = { 'deps': [], 'status': UNKNOWN, 'workers': [], 'start_time': UNKNOWN, 'params': params, 'name': family, 'display_name': task_id, 'priority': 0, } else: deps = dep_func(task) if not include_done: deps = list(self._filter_done(deps)) serialized[task_id] = self._serialize_task(task_id, deps=deps) for dep in sorted(deps): if dep not in seen: seen.add(dep) queue.append(dep) if task_id != root_task_id: del serialized[task_id]['display_name'] if len(serialized) >= self._config.max_graph_nodes: break return serialized
[ "def", "_traverse_graph", "(", "self", ",", "root_task_id", ",", "seen", "=", "None", ",", "dep_func", "=", "None", ",", "include_done", "=", "True", ")", ":", "if", "seen", "is", "None", ":", "seen", "=", "set", "(", ")", "elif", "root_task_id", "in", "seen", ":", "return", "{", "}", "if", "dep_func", "is", "None", ":", "def", "dep_func", "(", "t", ")", ":", "return", "t", ".", "deps", "seen", ".", "add", "(", "root_task_id", ")", "serialized", "=", "{", "}", "queue", "=", "collections", ".", "deque", "(", "[", "root_task_id", "]", ")", "while", "queue", ":", "task_id", "=", "queue", ".", "popleft", "(", ")", "task", "=", "self", ".", "_state", ".", "get_task", "(", "task_id", ")", "if", "task", "is", "None", "or", "not", "task", ".", "family", ":", "logger", ".", "debug", "(", "'Missing task for id [%s]'", ",", "task_id", ")", "# NOTE : If a dependency is missing from self._state there is no way to deduce the", "# task family and parameters.", "family_match", "=", "TASK_FAMILY_RE", ".", "match", "(", "task_id", ")", "family", "=", "family_match", ".", "group", "(", "1", ")", "if", "family_match", "else", "UNKNOWN", "params", "=", "{", "'task_id'", ":", "task_id", "}", "serialized", "[", "task_id", "]", "=", "{", "'deps'", ":", "[", "]", ",", "'status'", ":", "UNKNOWN", ",", "'workers'", ":", "[", "]", ",", "'start_time'", ":", "UNKNOWN", ",", "'params'", ":", "params", ",", "'name'", ":", "family", ",", "'display_name'", ":", "task_id", ",", "'priority'", ":", "0", ",", "}", "else", ":", "deps", "=", "dep_func", "(", "task", ")", "if", "not", "include_done", ":", "deps", "=", "list", "(", "self", ".", "_filter_done", "(", "deps", ")", ")", "serialized", "[", "task_id", "]", "=", "self", ".", "_serialize_task", "(", "task_id", ",", "deps", "=", "deps", ")", "for", "dep", "in", "sorted", "(", "deps", ")", ":", "if", "dep", "not", "in", "seen", ":", "seen", ".", "add", "(", "dep", ")", "queue", ".", "append", "(", "dep", ")", "if", "task_id", "!=", "root_task_id", ":", "del", "serialized", "[", "task_id", "]", "[", "'display_name'", "]", "if", "len", "(", "serialized", ")", ">=", "self", ".", "_config", ".", "max_graph_nodes", ":", "break", "return", "serialized" ]
Returns the dependency graph rooted at task_id This does a breadth-first traversal to find the nodes closest to the root before hitting the scheduler.max_graph_nodes limit. :param root_task_id: the id of the graph's root :return: A map of task id to serialized node
[ "Returns", "the", "dependency", "graph", "rooted", "at", "task_id" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L1343-L1402
train
spotify/luigi
luigi/scheduler.py
Scheduler.task_list
def task_list(self, status='', upstream_status='', limit=True, search=None, max_shown_tasks=None, **kwargs): """ Query for a subset of tasks by status. """ if not search: count_limit = max_shown_tasks or self._config.max_shown_tasks pre_count = self._state.get_active_task_count_for_status(status) if limit and pre_count > count_limit: return {'num_tasks': -1 if upstream_status else pre_count} self.prune() result = {} upstream_status_table = {} # used to memoize upstream status if search is None: def filter_func(_): return True else: terms = search.split() def filter_func(t): return all(term in t.pretty_id for term in terms) tasks = self._state.get_active_tasks_by_status(status) if status else self._state.get_active_tasks() for task in filter(filter_func, tasks): if task.status != PENDING or not upstream_status or upstream_status == self._upstream_status(task.id, upstream_status_table): serialized = self._serialize_task(task.id, include_deps=False) result[task.id] = serialized if limit and len(result) > (max_shown_tasks or self._config.max_shown_tasks): return {'num_tasks': len(result)} return result
python
def task_list(self, status='', upstream_status='', limit=True, search=None, max_shown_tasks=None, **kwargs): """ Query for a subset of tasks by status. """ if not search: count_limit = max_shown_tasks or self._config.max_shown_tasks pre_count = self._state.get_active_task_count_for_status(status) if limit and pre_count > count_limit: return {'num_tasks': -1 if upstream_status else pre_count} self.prune() result = {} upstream_status_table = {} # used to memoize upstream status if search is None: def filter_func(_): return True else: terms = search.split() def filter_func(t): return all(term in t.pretty_id for term in terms) tasks = self._state.get_active_tasks_by_status(status) if status else self._state.get_active_tasks() for task in filter(filter_func, tasks): if task.status != PENDING or not upstream_status or upstream_status == self._upstream_status(task.id, upstream_status_table): serialized = self._serialize_task(task.id, include_deps=False) result[task.id] = serialized if limit and len(result) > (max_shown_tasks or self._config.max_shown_tasks): return {'num_tasks': len(result)} return result
[ "def", "task_list", "(", "self", ",", "status", "=", "''", ",", "upstream_status", "=", "''", ",", "limit", "=", "True", ",", "search", "=", "None", ",", "max_shown_tasks", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "search", ":", "count_limit", "=", "max_shown_tasks", "or", "self", ".", "_config", ".", "max_shown_tasks", "pre_count", "=", "self", ".", "_state", ".", "get_active_task_count_for_status", "(", "status", ")", "if", "limit", "and", "pre_count", ">", "count_limit", ":", "return", "{", "'num_tasks'", ":", "-", "1", "if", "upstream_status", "else", "pre_count", "}", "self", ".", "prune", "(", ")", "result", "=", "{", "}", "upstream_status_table", "=", "{", "}", "# used to memoize upstream status", "if", "search", "is", "None", ":", "def", "filter_func", "(", "_", ")", ":", "return", "True", "else", ":", "terms", "=", "search", ".", "split", "(", ")", "def", "filter_func", "(", "t", ")", ":", "return", "all", "(", "term", "in", "t", ".", "pretty_id", "for", "term", "in", "terms", ")", "tasks", "=", "self", ".", "_state", ".", "get_active_tasks_by_status", "(", "status", ")", "if", "status", "else", "self", ".", "_state", ".", "get_active_tasks", "(", ")", "for", "task", "in", "filter", "(", "filter_func", ",", "tasks", ")", ":", "if", "task", ".", "status", "!=", "PENDING", "or", "not", "upstream_status", "or", "upstream_status", "==", "self", ".", "_upstream_status", "(", "task", ".", "id", ",", "upstream_status_table", ")", ":", "serialized", "=", "self", ".", "_serialize_task", "(", "task", ".", "id", ",", "include_deps", "=", "False", ")", "result", "[", "task", ".", "id", "]", "=", "serialized", "if", "limit", "and", "len", "(", "result", ")", ">", "(", "max_shown_tasks", "or", "self", ".", "_config", ".", "max_shown_tasks", ")", ":", "return", "{", "'num_tasks'", ":", "len", "(", "result", ")", "}", "return", "result" ]
Query for a subset of tasks by status.
[ "Query", "for", "a", "subset", "of", "tasks", "by", "status", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L1424-L1454
train
spotify/luigi
luigi/scheduler.py
Scheduler.resource_list
def resource_list(self): """ Resources usage info and their consumers (tasks). """ self.prune() resources = [ dict( name=resource, num_total=r_dict['total'], num_used=r_dict['used'] ) for resource, r_dict in six.iteritems(self.resources())] if self._resources is not None: consumers = collections.defaultdict(dict) for task in self._state.get_active_tasks_by_status(RUNNING): if task.status == RUNNING and task.resources: for resource, amount in six.iteritems(task.resources): consumers[resource][task.id] = self._serialize_task(task.id, include_deps=False) for resource in resources: tasks = consumers[resource['name']] resource['num_consumer'] = len(tasks) resource['running'] = tasks return resources
python
def resource_list(self): """ Resources usage info and their consumers (tasks). """ self.prune() resources = [ dict( name=resource, num_total=r_dict['total'], num_used=r_dict['used'] ) for resource, r_dict in six.iteritems(self.resources())] if self._resources is not None: consumers = collections.defaultdict(dict) for task in self._state.get_active_tasks_by_status(RUNNING): if task.status == RUNNING and task.resources: for resource, amount in six.iteritems(task.resources): consumers[resource][task.id] = self._serialize_task(task.id, include_deps=False) for resource in resources: tasks = consumers[resource['name']] resource['num_consumer'] = len(tasks) resource['running'] = tasks return resources
[ "def", "resource_list", "(", "self", ")", ":", "self", ".", "prune", "(", ")", "resources", "=", "[", "dict", "(", "name", "=", "resource", ",", "num_total", "=", "r_dict", "[", "'total'", "]", ",", "num_used", "=", "r_dict", "[", "'used'", "]", ")", "for", "resource", ",", "r_dict", "in", "six", ".", "iteritems", "(", "self", ".", "resources", "(", ")", ")", "]", "if", "self", ".", "_resources", "is", "not", "None", ":", "consumers", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "task", "in", "self", ".", "_state", ".", "get_active_tasks_by_status", "(", "RUNNING", ")", ":", "if", "task", ".", "status", "==", "RUNNING", "and", "task", ".", "resources", ":", "for", "resource", ",", "amount", "in", "six", ".", "iteritems", "(", "task", ".", "resources", ")", ":", "consumers", "[", "resource", "]", "[", "task", ".", "id", "]", "=", "self", ".", "_serialize_task", "(", "task", ".", "id", ",", "include_deps", "=", "False", ")", "for", "resource", "in", "resources", ":", "tasks", "=", "consumers", "[", "resource", "[", "'name'", "]", "]", "resource", "[", "'num_consumer'", "]", "=", "len", "(", "tasks", ")", "resource", "[", "'running'", "]", "=", "tasks", "return", "resources" ]
Resources usage info and their consumers (tasks).
[ "Resources", "usage", "info", "and", "their", "consumers", "(", "tasks", ")", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L1500-L1521
train
spotify/luigi
luigi/scheduler.py
Scheduler.resources
def resources(self): ''' get total resources and available ones ''' used_resources = self._used_resources() ret = collections.defaultdict(dict) for resource, total in six.iteritems(self._resources): ret[resource]['total'] = total if resource in used_resources: ret[resource]['used'] = used_resources[resource] else: ret[resource]['used'] = 0 return ret
python
def resources(self): ''' get total resources and available ones ''' used_resources = self._used_resources() ret = collections.defaultdict(dict) for resource, total in six.iteritems(self._resources): ret[resource]['total'] = total if resource in used_resources: ret[resource]['used'] = used_resources[resource] else: ret[resource]['used'] = 0 return ret
[ "def", "resources", "(", "self", ")", ":", "used_resources", "=", "self", ".", "_used_resources", "(", ")", "ret", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "resource", ",", "total", "in", "six", ".", "iteritems", "(", "self", ".", "_resources", ")", ":", "ret", "[", "resource", "]", "[", "'total'", "]", "=", "total", "if", "resource", "in", "used_resources", ":", "ret", "[", "resource", "]", "[", "'used'", "]", "=", "used_resources", "[", "resource", "]", "else", ":", "ret", "[", "resource", "]", "[", "'used'", "]", "=", "0", "return", "ret" ]
get total resources and available ones
[ "get", "total", "resources", "and", "available", "ones" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L1523-L1533
train
spotify/luigi
luigi/scheduler.py
Scheduler.task_search
def task_search(self, task_str, **kwargs): """ Query for a subset of tasks by task_id. :param task_str: :return: """ self.prune() result = collections.defaultdict(dict) for task in self._state.get_active_tasks(): if task.id.find(task_str) != -1: serialized = self._serialize_task(task.id, include_deps=False) result[task.status][task.id] = serialized return result
python
def task_search(self, task_str, **kwargs): """ Query for a subset of tasks by task_id. :param task_str: :return: """ self.prune() result = collections.defaultdict(dict) for task in self._state.get_active_tasks(): if task.id.find(task_str) != -1: serialized = self._serialize_task(task.id, include_deps=False) result[task.status][task.id] = serialized return result
[ "def", "task_search", "(", "self", ",", "task_str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "prune", "(", ")", "result", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "task", "in", "self", ".", "_state", ".", "get_active_tasks", "(", ")", ":", "if", "task", ".", "id", ".", "find", "(", "task_str", ")", "!=", "-", "1", ":", "serialized", "=", "self", ".", "_serialize_task", "(", "task", ".", "id", ",", "include_deps", "=", "False", ")", "result", "[", "task", ".", "status", "]", "[", "task", ".", "id", "]", "=", "serialized", "return", "result" ]
Query for a subset of tasks by task_id. :param task_str: :return:
[ "Query", "for", "a", "subset", "of", "tasks", "by", "task_id", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L1536-L1549
train
spotify/luigi
luigi/target.py
FileSystemTarget.exists
def exists(self): """ Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise. This method is implemented by using :py:attr:`fs`. """ path = self.path if '*' in path or '?' in path or '[' in path or '{' in path: logger.warning("Using wildcards in path %s might lead to processing of an incomplete dataset; " "override exists() to suppress the warning.", path) return self.fs.exists(path)
python
def exists(self): """ Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise. This method is implemented by using :py:attr:`fs`. """ path = self.path if '*' in path or '?' in path or '[' in path or '{' in path: logger.warning("Using wildcards in path %s might lead to processing of an incomplete dataset; " "override exists() to suppress the warning.", path) return self.fs.exists(path)
[ "def", "exists", "(", "self", ")", ":", "path", "=", "self", ".", "path", "if", "'*'", "in", "path", "or", "'?'", "in", "path", "or", "'['", "in", "path", "or", "'{'", "in", "path", ":", "logger", ".", "warning", "(", "\"Using wildcards in path %s might lead to processing of an incomplete dataset; \"", "\"override exists() to suppress the warning.\"", ",", "path", ")", "return", "self", ".", "fs", ".", "exists", "(", "path", ")" ]
Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise. This method is implemented by using :py:attr:`fs`.
[ "Returns", "True", "if", "the", "path", "for", "this", "FileSystemTarget", "exists", ";", "False", "otherwise", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/target.py#L242-L252
train
spotify/luigi
luigi/target.py
FileSystemTarget.temporary_path
def temporary_path(self): """ A context manager that enables a reasonably short, general and magic-less way to solve the :ref:`AtomicWrites`. * On *entering*, it will create the parent directories so the temporary_path is writeable right away. This step uses :py:meth:`FileSystem.mkdir`. * On *exiting*, it will move the temporary file if there was no exception thrown. This step uses :py:meth:`FileSystem.rename_dont_move` The file system operations will be carried out by calling them on :py:attr:`fs`. The typical use case looks like this: .. code:: python class MyTask(luigi.Task): def output(self): return MyFileSystemTarget(...) def run(self): with self.output().temporary_path() as self.temp_output_path: run_some_external_command(output_path=self.temp_output_path) """ num = random.randrange(0, 1e10) slashless_path = self.path.rstrip('/').rstrip("\\") _temp_path = '{}-luigi-tmp-{:010}{}'.format( slashless_path, num, self._trailing_slash()) # TODO: os.path doesn't make sense here as it's os-dependent tmp_dir = os.path.dirname(slashless_path) if tmp_dir: self.fs.mkdir(tmp_dir, parents=True, raise_if_exists=False) yield _temp_path # We won't reach here if there was an user exception. self.fs.rename_dont_move(_temp_path, self.path)
python
def temporary_path(self): """ A context manager that enables a reasonably short, general and magic-less way to solve the :ref:`AtomicWrites`. * On *entering*, it will create the parent directories so the temporary_path is writeable right away. This step uses :py:meth:`FileSystem.mkdir`. * On *exiting*, it will move the temporary file if there was no exception thrown. This step uses :py:meth:`FileSystem.rename_dont_move` The file system operations will be carried out by calling them on :py:attr:`fs`. The typical use case looks like this: .. code:: python class MyTask(luigi.Task): def output(self): return MyFileSystemTarget(...) def run(self): with self.output().temporary_path() as self.temp_output_path: run_some_external_command(output_path=self.temp_output_path) """ num = random.randrange(0, 1e10) slashless_path = self.path.rstrip('/').rstrip("\\") _temp_path = '{}-luigi-tmp-{:010}{}'.format( slashless_path, num, self._trailing_slash()) # TODO: os.path doesn't make sense here as it's os-dependent tmp_dir = os.path.dirname(slashless_path) if tmp_dir: self.fs.mkdir(tmp_dir, parents=True, raise_if_exists=False) yield _temp_path # We won't reach here if there was an user exception. self.fs.rename_dont_move(_temp_path, self.path)
[ "def", "temporary_path", "(", "self", ")", ":", "num", "=", "random", ".", "randrange", "(", "0", ",", "1e10", ")", "slashless_path", "=", "self", ".", "path", ".", "rstrip", "(", "'/'", ")", ".", "rstrip", "(", "\"\\\\\"", ")", "_temp_path", "=", "'{}-luigi-tmp-{:010}{}'", ".", "format", "(", "slashless_path", ",", "num", ",", "self", ".", "_trailing_slash", "(", ")", ")", "# TODO: os.path doesn't make sense here as it's os-dependent", "tmp_dir", "=", "os", ".", "path", ".", "dirname", "(", "slashless_path", ")", "if", "tmp_dir", ":", "self", ".", "fs", ".", "mkdir", "(", "tmp_dir", ",", "parents", "=", "True", ",", "raise_if_exists", "=", "False", ")", "yield", "_temp_path", "# We won't reach here if there was an user exception.", "self", ".", "fs", ".", "rename_dont_move", "(", "_temp_path", ",", "self", ".", "path", ")" ]
A context manager that enables a reasonably short, general and magic-less way to solve the :ref:`AtomicWrites`. * On *entering*, it will create the parent directories so the temporary_path is writeable right away. This step uses :py:meth:`FileSystem.mkdir`. * On *exiting*, it will move the temporary file if there was no exception thrown. This step uses :py:meth:`FileSystem.rename_dont_move` The file system operations will be carried out by calling them on :py:attr:`fs`. The typical use case looks like this: .. code:: python class MyTask(luigi.Task): def output(self): return MyFileSystemTarget(...) def run(self): with self.output().temporary_path() as self.temp_output_path: run_some_external_command(output_path=self.temp_output_path)
[ "A", "context", "manager", "that", "enables", "a", "reasonably", "short", "general", "and", "magic", "-", "less", "way", "to", "solve", "the", ":", "ref", ":", "AtomicWrites", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/target.py#L263-L301
train
spotify/luigi
luigi/contrib/esindex.py
ElasticsearchTarget.marker_index_document_id
def marker_index_document_id(self): """ Generate an id for the indicator document. """ params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id) return hashlib.sha1(params.encode('utf-8')).hexdigest()
python
def marker_index_document_id(self): """ Generate an id for the indicator document. """ params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id) return hashlib.sha1(params.encode('utf-8')).hexdigest()
[ "def", "marker_index_document_id", "(", "self", ")", ":", "params", "=", "'%s:%s:%s'", "%", "(", "self", ".", "index", ",", "self", ".", "doc_type", ",", "self", ".", "update_id", ")", "return", "hashlib", ".", "sha1", "(", "params", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")" ]
Generate an id for the indicator document.
[ "Generate", "an", "id", "for", "the", "indicator", "document", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L161-L166
train
spotify/luigi
luigi/contrib/esindex.py
ElasticsearchTarget.touch
def touch(self): """ Mark this update as complete. The document id would be sufficent but, for documentation, we index the parameters `update_id`, `target_index`, `target_doc_type` and `date` as well. """ self.create_marker_index() self.es.index(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id(), body={ 'update_id': self.update_id, 'target_index': self.index, 'target_doc_type': self.doc_type, 'date': datetime.datetime.now()}) self.es.indices.flush(index=self.marker_index) self.ensure_hist_size()
python
def touch(self): """ Mark this update as complete. The document id would be sufficent but, for documentation, we index the parameters `update_id`, `target_index`, `target_doc_type` and `date` as well. """ self.create_marker_index() self.es.index(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id(), body={ 'update_id': self.update_id, 'target_index': self.index, 'target_doc_type': self.doc_type, 'date': datetime.datetime.now()}) self.es.indices.flush(index=self.marker_index) self.ensure_hist_size()
[ "def", "touch", "(", "self", ")", ":", "self", ".", "create_marker_index", "(", ")", "self", ".", "es", ".", "index", "(", "index", "=", "self", ".", "marker_index", ",", "doc_type", "=", "self", ".", "marker_doc_type", ",", "id", "=", "self", ".", "marker_index_document_id", "(", ")", ",", "body", "=", "{", "'update_id'", ":", "self", ".", "update_id", ",", "'target_index'", ":", "self", ".", "index", ",", "'target_doc_type'", ":", "self", ".", "doc_type", ",", "'date'", ":", "datetime", ".", "datetime", ".", "now", "(", ")", "}", ")", "self", ".", "es", ".", "indices", ".", "flush", "(", "index", "=", "self", ".", "marker_index", ")", "self", ".", "ensure_hist_size", "(", ")" ]
Mark this update as complete. The document id would be sufficent but, for documentation, we index the parameters `update_id`, `target_index`, `target_doc_type` and `date` as well.
[ "Mark", "this", "update", "as", "complete", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L168-L184
train
spotify/luigi
luigi/contrib/esindex.py
ElasticsearchTarget.exists
def exists(self): """ Test, if this task has been run. """ try: self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id()) return True except elasticsearch.NotFoundError: logger.debug('Marker document not found.') except elasticsearch.ElasticsearchException as err: logger.warn(err) return False
python
def exists(self): """ Test, if this task has been run. """ try: self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id()) return True except elasticsearch.NotFoundError: logger.debug('Marker document not found.') except elasticsearch.ElasticsearchException as err: logger.warn(err) return False
[ "def", "exists", "(", "self", ")", ":", "try", ":", "self", ".", "es", ".", "get", "(", "index", "=", "self", ".", "marker_index", ",", "doc_type", "=", "self", ".", "marker_doc_type", ",", "id", "=", "self", ".", "marker_index_document_id", "(", ")", ")", "return", "True", "except", "elasticsearch", ".", "NotFoundError", ":", "logger", ".", "debug", "(", "'Marker document not found.'", ")", "except", "elasticsearch", ".", "ElasticsearchException", "as", "err", ":", "logger", ".", "warn", "(", "err", ")", "return", "False" ]
Test, if this task has been run.
[ "Test", "if", "this", "task", "has", "been", "run", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L186-L197
train
spotify/luigi
luigi/contrib/esindex.py
ElasticsearchTarget.create_marker_index
def create_marker_index(self): """ Create the index that will keep track of the tasks if necessary. """ if not self.es.indices.exists(index=self.marker_index): self.es.indices.create(index=self.marker_index)
python
def create_marker_index(self): """ Create the index that will keep track of the tasks if necessary. """ if not self.es.indices.exists(index=self.marker_index): self.es.indices.create(index=self.marker_index)
[ "def", "create_marker_index", "(", "self", ")", ":", "if", "not", "self", ".", "es", ".", "indices", ".", "exists", "(", "index", "=", "self", ".", "marker_index", ")", ":", "self", ".", "es", ".", "indices", ".", "create", "(", "index", "=", "self", ".", "marker_index", ")" ]
Create the index that will keep track of the tasks if necessary.
[ "Create", "the", "index", "that", "will", "keep", "track", "of", "the", "tasks", "if", "necessary", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L199-L204
train
spotify/luigi
luigi/contrib/esindex.py
ElasticsearchTarget.ensure_hist_size
def ensure_hist_size(self): """ Shrink the history of updates for a `index/doc_type` combination down to `self.marker_index_hist_size`. """ if self.marker_index_hist_size == 0: return result = self.es.search(index=self.marker_index, doc_type=self.marker_doc_type, body={'query': { 'term': {'target_index': self.index}}}, sort=('date:desc',)) for i, hit in enumerate(result.get('hits').get('hits'), start=1): if i > self.marker_index_hist_size: marker_document_id = hit.get('_id') self.es.delete(id=marker_document_id, index=self.marker_index, doc_type=self.marker_doc_type) self.es.indices.flush(index=self.marker_index)
python
def ensure_hist_size(self): """ Shrink the history of updates for a `index/doc_type` combination down to `self.marker_index_hist_size`. """ if self.marker_index_hist_size == 0: return result = self.es.search(index=self.marker_index, doc_type=self.marker_doc_type, body={'query': { 'term': {'target_index': self.index}}}, sort=('date:desc',)) for i, hit in enumerate(result.get('hits').get('hits'), start=1): if i > self.marker_index_hist_size: marker_document_id = hit.get('_id') self.es.delete(id=marker_document_id, index=self.marker_index, doc_type=self.marker_doc_type) self.es.indices.flush(index=self.marker_index)
[ "def", "ensure_hist_size", "(", "self", ")", ":", "if", "self", ".", "marker_index_hist_size", "==", "0", ":", "return", "result", "=", "self", ".", "es", ".", "search", "(", "index", "=", "self", ".", "marker_index", ",", "doc_type", "=", "self", ".", "marker_doc_type", ",", "body", "=", "{", "'query'", ":", "{", "'term'", ":", "{", "'target_index'", ":", "self", ".", "index", "}", "}", "}", ",", "sort", "=", "(", "'date:desc'", ",", ")", ")", "for", "i", ",", "hit", "in", "enumerate", "(", "result", ".", "get", "(", "'hits'", ")", ".", "get", "(", "'hits'", ")", ",", "start", "=", "1", ")", ":", "if", "i", ">", "self", ".", "marker_index_hist_size", ":", "marker_document_id", "=", "hit", ".", "get", "(", "'_id'", ")", "self", ".", "es", ".", "delete", "(", "id", "=", "marker_document_id", ",", "index", "=", "self", ".", "marker_index", ",", "doc_type", "=", "self", ".", "marker_doc_type", ")", "self", ".", "es", ".", "indices", ".", "flush", "(", "index", "=", "self", ".", "marker_index", ")" ]
Shrink the history of updates for a `index/doc_type` combination down to `self.marker_index_hist_size`.
[ "Shrink", "the", "history", "of", "updates", "for", "a", "index", "/", "doc_type", "combination", "down", "to", "self", ".", "marker_index_hist_size", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L206-L224
train
spotify/luigi
luigi/contrib/esindex.py
CopyToIndex._docs
def _docs(self): """ Since `self.docs` may yield documents that do not explicitly contain `_index` or `_type`, add those attributes here, if necessary. """ iterdocs = iter(self.docs()) first = next(iterdocs) needs_parsing = False if isinstance(first, six.string_types): needs_parsing = True elif isinstance(first, dict): pass else: raise RuntimeError('Document must be either JSON strings or dict.') for doc in itertools.chain([first], iterdocs): if needs_parsing: doc = json.loads(doc) if '_index' not in doc: doc['_index'] = self.index if '_type' not in doc: doc['_type'] = self.doc_type yield doc
python
def _docs(self): """ Since `self.docs` may yield documents that do not explicitly contain `_index` or `_type`, add those attributes here, if necessary. """ iterdocs = iter(self.docs()) first = next(iterdocs) needs_parsing = False if isinstance(first, six.string_types): needs_parsing = True elif isinstance(first, dict): pass else: raise RuntimeError('Document must be either JSON strings or dict.') for doc in itertools.chain([first], iterdocs): if needs_parsing: doc = json.loads(doc) if '_index' not in doc: doc['_index'] = self.index if '_type' not in doc: doc['_type'] = self.doc_type yield doc
[ "def", "_docs", "(", "self", ")", ":", "iterdocs", "=", "iter", "(", "self", ".", "docs", "(", ")", ")", "first", "=", "next", "(", "iterdocs", ")", "needs_parsing", "=", "False", "if", "isinstance", "(", "first", ",", "six", ".", "string_types", ")", ":", "needs_parsing", "=", "True", "elif", "isinstance", "(", "first", ",", "dict", ")", ":", "pass", "else", ":", "raise", "RuntimeError", "(", "'Document must be either JSON strings or dict.'", ")", "for", "doc", "in", "itertools", ".", "chain", "(", "[", "first", "]", ",", "iterdocs", ")", ":", "if", "needs_parsing", ":", "doc", "=", "json", ".", "loads", "(", "doc", ")", "if", "'_index'", "not", "in", "doc", ":", "doc", "[", "'_index'", "]", "=", "self", ".", "index", "if", "'_type'", "not", "in", "doc", ":", "doc", "[", "'_type'", "]", "=", "self", ".", "doc_type", "yield", "doc" ]
Since `self.docs` may yield documents that do not explicitly contain `_index` or `_type`, add those attributes here, if necessary.
[ "Since", "self", ".", "docs", "may", "yield", "documents", "that", "do", "not", "explicitly", "contain", "_index", "or", "_type", "add", "those", "attributes", "here", "if", "necessary", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L361-L382
train
spotify/luigi
luigi/contrib/esindex.py
CopyToIndex.create_index
def create_index(self): """ Override to provide code for creating the target index. By default it will be created without any special settings or mappings. """ es = self._init_connection() if not es.indices.exists(index=self.index): es.indices.create(index=self.index, body=self.settings)
python
def create_index(self): """ Override to provide code for creating the target index. By default it will be created without any special settings or mappings. """ es = self._init_connection() if not es.indices.exists(index=self.index): es.indices.create(index=self.index, body=self.settings)
[ "def", "create_index", "(", "self", ")", ":", "es", "=", "self", ".", "_init_connection", "(", ")", "if", "not", "es", ".", "indices", ".", "exists", "(", "index", "=", "self", ".", "index", ")", ":", "es", ".", "indices", ".", "create", "(", "index", "=", "self", ".", "index", ",", "body", "=", "self", ".", "settings", ")" ]
Override to provide code for creating the target index. By default it will be created without any special settings or mappings.
[ "Override", "to", "provide", "code", "for", "creating", "the", "target", "index", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L394-L402
train
spotify/luigi
luigi/contrib/esindex.py
CopyToIndex.delete_index
def delete_index(self): """ Delete the index, if it exists. """ es = self._init_connection() if es.indices.exists(index=self.index): es.indices.delete(index=self.index)
python
def delete_index(self): """ Delete the index, if it exists. """ es = self._init_connection() if es.indices.exists(index=self.index): es.indices.delete(index=self.index)
[ "def", "delete_index", "(", "self", ")", ":", "es", "=", "self", ".", "_init_connection", "(", ")", "if", "es", ".", "indices", ".", "exists", "(", "index", "=", "self", ".", "index", ")", ":", "es", ".", "indices", ".", "delete", "(", "index", "=", "self", ".", "index", ")" ]
Delete the index, if it exists.
[ "Delete", "the", "index", "if", "it", "exists", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L404-L410
train
spotify/luigi
luigi/contrib/esindex.py
CopyToIndex.output
def output(self): """ Returns a ElasticsearchTarget representing the inserted dataset. Normally you don't override this. """ return ElasticsearchTarget( host=self.host, port=self.port, http_auth=self.http_auth, index=self.index, doc_type=self.doc_type, update_id=self.update_id(), marker_index_hist_size=self.marker_index_hist_size, timeout=self.timeout, extra_elasticsearch_args=self.extra_elasticsearch_args )
python
def output(self): """ Returns a ElasticsearchTarget representing the inserted dataset. Normally you don't override this. """ return ElasticsearchTarget( host=self.host, port=self.port, http_auth=self.http_auth, index=self.index, doc_type=self.doc_type, update_id=self.update_id(), marker_index_hist_size=self.marker_index_hist_size, timeout=self.timeout, extra_elasticsearch_args=self.extra_elasticsearch_args )
[ "def", "output", "(", "self", ")", ":", "return", "ElasticsearchTarget", "(", "host", "=", "self", ".", "host", ",", "port", "=", "self", ".", "port", ",", "http_auth", "=", "self", ".", "http_auth", ",", "index", "=", "self", ".", "index", ",", "doc_type", "=", "self", ".", "doc_type", ",", "update_id", "=", "self", ".", "update_id", "(", ")", ",", "marker_index_hist_size", "=", "self", ".", "marker_index_hist_size", ",", "timeout", "=", "self", ".", "timeout", ",", "extra_elasticsearch_args", "=", "self", ".", "extra_elasticsearch_args", ")" ]
Returns a ElasticsearchTarget representing the inserted dataset. Normally you don't override this.
[ "Returns", "a", "ElasticsearchTarget", "representing", "the", "inserted", "dataset", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L418-L434
train
spotify/luigi
luigi/contrib/esindex.py
CopyToIndex.run
def run(self): """ Run task, namely: * purge existing index, if requested (`purge_existing_index`), * create the index, if missing, * apply mappings, if given, * set refresh interval to -1 (disable) for performance reasons, * bulk index in batches of size `chunk_size` (2000), * set refresh interval to 1s, * refresh Elasticsearch, * create entry in marker index. """ if self.purge_existing_index: self.delete_index() self.create_index() es = self._init_connection() if self.mapping: es.indices.put_mapping(index=self.index, doc_type=self.doc_type, body=self.mapping) es.indices.put_settings({"index": {"refresh_interval": "-1"}}, index=self.index) bulk(es, self._docs(), chunk_size=self.chunk_size, raise_on_error=self.raise_on_error) es.indices.put_settings({"index": {"refresh_interval": "1s"}}, index=self.index) es.indices.refresh() self.output().touch()
python
def run(self): """ Run task, namely: * purge existing index, if requested (`purge_existing_index`), * create the index, if missing, * apply mappings, if given, * set refresh interval to -1 (disable) for performance reasons, * bulk index in batches of size `chunk_size` (2000), * set refresh interval to 1s, * refresh Elasticsearch, * create entry in marker index. """ if self.purge_existing_index: self.delete_index() self.create_index() es = self._init_connection() if self.mapping: es.indices.put_mapping(index=self.index, doc_type=self.doc_type, body=self.mapping) es.indices.put_settings({"index": {"refresh_interval": "-1"}}, index=self.index) bulk(es, self._docs(), chunk_size=self.chunk_size, raise_on_error=self.raise_on_error) es.indices.put_settings({"index": {"refresh_interval": "1s"}}, index=self.index) es.indices.refresh() self.output().touch()
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "purge_existing_index", ":", "self", ".", "delete_index", "(", ")", "self", ".", "create_index", "(", ")", "es", "=", "self", ".", "_init_connection", "(", ")", "if", "self", ".", "mapping", ":", "es", ".", "indices", ".", "put_mapping", "(", "index", "=", "self", ".", "index", ",", "doc_type", "=", "self", ".", "doc_type", ",", "body", "=", "self", ".", "mapping", ")", "es", ".", "indices", ".", "put_settings", "(", "{", "\"index\"", ":", "{", "\"refresh_interval\"", ":", "\"-1\"", "}", "}", ",", "index", "=", "self", ".", "index", ")", "bulk", "(", "es", ",", "self", ".", "_docs", "(", ")", ",", "chunk_size", "=", "self", ".", "chunk_size", ",", "raise_on_error", "=", "self", ".", "raise_on_error", ")", "es", ".", "indices", ".", "put_settings", "(", "{", "\"index\"", ":", "{", "\"refresh_interval\"", ":", "\"1s\"", "}", "}", ",", "index", "=", "self", ".", "index", ")", "es", ".", "indices", ".", "refresh", "(", ")", "self", ".", "output", "(", ")", ".", "touch", "(", ")" ]
Run task, namely: * purge existing index, if requested (`purge_existing_index`), * create the index, if missing, * apply mappings, if given, * set refresh interval to -1 (disable) for performance reasons, * bulk index in batches of size `chunk_size` (2000), * set refresh interval to 1s, * refresh Elasticsearch, * create entry in marker index.
[ "Run", "task", "namely", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L436-L465
train
spotify/luigi
luigi/configuration/cfg_parser.py
LuigiConfigParser._get_with_default
def _get_with_default(self, method, section, option, default, expected_type=None, **kwargs): """ Gets the value of the section/option using method. Returns default if value is not found. Raises an exception if the default value is not None and doesn't match the expected_type. """ try: try: # Underscore-style is the recommended configuration style option = option.replace('-', '_') return method(self, section, option, **kwargs) except (NoOptionError, NoSectionError): # Support dash-style option names (with deprecation warning). option_alias = option.replace('_', '-') value = method(self, section, option_alias, **kwargs) warn = 'Configuration [{s}] {o} (with dashes) should be avoided. Please use underscores: {u}.'.format( s=section, o=option_alias, u=option) warnings.warn(warn, DeprecationWarning) return value except (NoOptionError, NoSectionError): if default is LuigiConfigParser.NO_DEFAULT: raise if expected_type is not None and default is not None and \ not isinstance(default, expected_type): raise return default
python
def _get_with_default(self, method, section, option, default, expected_type=None, **kwargs): """ Gets the value of the section/option using method. Returns default if value is not found. Raises an exception if the default value is not None and doesn't match the expected_type. """ try: try: # Underscore-style is the recommended configuration style option = option.replace('-', '_') return method(self, section, option, **kwargs) except (NoOptionError, NoSectionError): # Support dash-style option names (with deprecation warning). option_alias = option.replace('_', '-') value = method(self, section, option_alias, **kwargs) warn = 'Configuration [{s}] {o} (with dashes) should be avoided. Please use underscores: {u}.'.format( s=section, o=option_alias, u=option) warnings.warn(warn, DeprecationWarning) return value except (NoOptionError, NoSectionError): if default is LuigiConfigParser.NO_DEFAULT: raise if expected_type is not None and default is not None and \ not isinstance(default, expected_type): raise return default
[ "def", "_get_with_default", "(", "self", ",", "method", ",", "section", ",", "option", ",", "default", ",", "expected_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "try", ":", "# Underscore-style is the recommended configuration style", "option", "=", "option", ".", "replace", "(", "'-'", ",", "'_'", ")", "return", "method", "(", "self", ",", "section", ",", "option", ",", "*", "*", "kwargs", ")", "except", "(", "NoOptionError", ",", "NoSectionError", ")", ":", "# Support dash-style option names (with deprecation warning).", "option_alias", "=", "option", ".", "replace", "(", "'_'", ",", "'-'", ")", "value", "=", "method", "(", "self", ",", "section", ",", "option_alias", ",", "*", "*", "kwargs", ")", "warn", "=", "'Configuration [{s}] {o} (with dashes) should be avoided. Please use underscores: {u}.'", ".", "format", "(", "s", "=", "section", ",", "o", "=", "option_alias", ",", "u", "=", "option", ")", "warnings", ".", "warn", "(", "warn", ",", "DeprecationWarning", ")", "return", "value", "except", "(", "NoOptionError", ",", "NoSectionError", ")", ":", "if", "default", "is", "LuigiConfigParser", ".", "NO_DEFAULT", ":", "raise", "if", "expected_type", "is", "not", "None", "and", "default", "is", "not", "None", "and", "not", "isinstance", "(", "default", ",", "expected_type", ")", ":", "raise", "return", "default" ]
Gets the value of the section/option using method. Returns default if value is not found. Raises an exception if the default value is not None and doesn't match the expected_type.
[ "Gets", "the", "value", "of", "the", "section", "/", "option", "using", "method", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/configuration/cfg_parser.py#L156-L183
train
spotify/luigi
luigi/contrib/kubernetes.py
KubernetesJobTask.__track_job
def __track_job(self): """Poll job status while active""" while not self.__verify_job_has_started(): time.sleep(self.__POLL_TIME) self.__logger.debug("Waiting for Kubernetes job " + self.uu_name + " to start") self.__print_kubectl_hints() status = self.__get_job_status() while status == "RUNNING": self.__logger.debug("Kubernetes job " + self.uu_name + " is running") time.sleep(self.__POLL_TIME) status = self.__get_job_status() assert status != "FAILED", "Kubernetes job " + self.uu_name + " failed" # status == "SUCCEEDED" self.__logger.info("Kubernetes job " + self.uu_name + " succeeded") self.signal_complete()
python
def __track_job(self): """Poll job status while active""" while not self.__verify_job_has_started(): time.sleep(self.__POLL_TIME) self.__logger.debug("Waiting for Kubernetes job " + self.uu_name + " to start") self.__print_kubectl_hints() status = self.__get_job_status() while status == "RUNNING": self.__logger.debug("Kubernetes job " + self.uu_name + " is running") time.sleep(self.__POLL_TIME) status = self.__get_job_status() assert status != "FAILED", "Kubernetes job " + self.uu_name + " failed" # status == "SUCCEEDED" self.__logger.info("Kubernetes job " + self.uu_name + " succeeded") self.signal_complete()
[ "def", "__track_job", "(", "self", ")", ":", "while", "not", "self", ".", "__verify_job_has_started", "(", ")", ":", "time", ".", "sleep", "(", "self", ".", "__POLL_TIME", ")", "self", ".", "__logger", ".", "debug", "(", "\"Waiting for Kubernetes job \"", "+", "self", ".", "uu_name", "+", "\" to start\"", ")", "self", ".", "__print_kubectl_hints", "(", ")", "status", "=", "self", ".", "__get_job_status", "(", ")", "while", "status", "==", "\"RUNNING\"", ":", "self", ".", "__logger", ".", "debug", "(", "\"Kubernetes job \"", "+", "self", ".", "uu_name", "+", "\" is running\"", ")", "time", ".", "sleep", "(", "self", ".", "__POLL_TIME", ")", "status", "=", "self", ".", "__get_job_status", "(", ")", "assert", "status", "!=", "\"FAILED\"", ",", "\"Kubernetes job \"", "+", "self", ".", "uu_name", "+", "\" failed\"", "# status == \"SUCCEEDED\"", "self", ".", "__logger", ".", "info", "(", "\"Kubernetes job \"", "+", "self", ".", "uu_name", "+", "\" succeeded\"", ")", "self", ".", "signal_complete", "(", ")" ]
Poll job status while active
[ "Poll", "job", "status", "while", "active" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/kubernetes.py#L211-L228
train
spotify/luigi
luigi/contrib/kubernetes.py
KubernetesJobTask.__verify_job_has_started
def __verify_job_has_started(self): """Asserts that the job has successfully started""" # Verify that the job started self.__get_job() # Verify that the pod started pods = self.__get_pods() assert len(pods) > 0, "No pod scheduled by " + self.uu_name for pod in pods: status = pod.obj['status'] for cont_stats in status.get('containerStatuses', []): if 'terminated' in cont_stats['state']: t = cont_stats['state']['terminated'] err_msg = "Pod %s %s (exit code %d). Logs: `kubectl logs pod/%s`" % ( pod.name, t['reason'], t['exitCode'], pod.name) assert t['exitCode'] == 0, err_msg if 'waiting' in cont_stats['state']: wr = cont_stats['state']['waiting']['reason'] assert wr == 'ContainerCreating', "Pod %s %s. Logs: `kubectl logs pod/%s`" % ( pod.name, wr, pod.name) for cond in status.get('conditions', []): if 'message' in cond: if cond['reason'] == 'ContainersNotReady': return False assert cond['status'] != 'False', \ "[ERROR] %s - %s" % (cond['reason'], cond['message']) return True
python
def __verify_job_has_started(self): """Asserts that the job has successfully started""" # Verify that the job started self.__get_job() # Verify that the pod started pods = self.__get_pods() assert len(pods) > 0, "No pod scheduled by " + self.uu_name for pod in pods: status = pod.obj['status'] for cont_stats in status.get('containerStatuses', []): if 'terminated' in cont_stats['state']: t = cont_stats['state']['terminated'] err_msg = "Pod %s %s (exit code %d). Logs: `kubectl logs pod/%s`" % ( pod.name, t['reason'], t['exitCode'], pod.name) assert t['exitCode'] == 0, err_msg if 'waiting' in cont_stats['state']: wr = cont_stats['state']['waiting']['reason'] assert wr == 'ContainerCreating', "Pod %s %s. Logs: `kubectl logs pod/%s`" % ( pod.name, wr, pod.name) for cond in status.get('conditions', []): if 'message' in cond: if cond['reason'] == 'ContainersNotReady': return False assert cond['status'] != 'False', \ "[ERROR] %s - %s" % (cond['reason'], cond['message']) return True
[ "def", "__verify_job_has_started", "(", "self", ")", ":", "# Verify that the job started", "self", ".", "__get_job", "(", ")", "# Verify that the pod started", "pods", "=", "self", ".", "__get_pods", "(", ")", "assert", "len", "(", "pods", ")", ">", "0", ",", "\"No pod scheduled by \"", "+", "self", ".", "uu_name", "for", "pod", "in", "pods", ":", "status", "=", "pod", ".", "obj", "[", "'status'", "]", "for", "cont_stats", "in", "status", ".", "get", "(", "'containerStatuses'", ",", "[", "]", ")", ":", "if", "'terminated'", "in", "cont_stats", "[", "'state'", "]", ":", "t", "=", "cont_stats", "[", "'state'", "]", "[", "'terminated'", "]", "err_msg", "=", "\"Pod %s %s (exit code %d). Logs: `kubectl logs pod/%s`\"", "%", "(", "pod", ".", "name", ",", "t", "[", "'reason'", "]", ",", "t", "[", "'exitCode'", "]", ",", "pod", ".", "name", ")", "assert", "t", "[", "'exitCode'", "]", "==", "0", ",", "err_msg", "if", "'waiting'", "in", "cont_stats", "[", "'state'", "]", ":", "wr", "=", "cont_stats", "[", "'state'", "]", "[", "'waiting'", "]", "[", "'reason'", "]", "assert", "wr", "==", "'ContainerCreating'", ",", "\"Pod %s %s. Logs: `kubectl logs pod/%s`\"", "%", "(", "pod", ".", "name", ",", "wr", ",", "pod", ".", "name", ")", "for", "cond", "in", "status", ".", "get", "(", "'conditions'", ",", "[", "]", ")", ":", "if", "'message'", "in", "cond", ":", "if", "cond", "[", "'reason'", "]", "==", "'ContainersNotReady'", ":", "return", "False", "assert", "cond", "[", "'status'", "]", "!=", "'False'", ",", "\"[ERROR] %s - %s\"", "%", "(", "cond", "[", "'reason'", "]", ",", "cond", "[", "'message'", "]", ")", "return", "True" ]
Asserts that the job has successfully started
[ "Asserts", "that", "the", "job", "has", "successfully", "started" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/kubernetes.py#L267-L296
train
spotify/luigi
luigi/contrib/kubernetes.py
KubernetesJobTask.__get_job_status
def __get_job_status(self): """Return the Kubernetes job status""" # Figure out status and return it job = self.__get_job() if "succeeded" in job.obj["status"] and job.obj["status"]["succeeded"] > 0: job.scale(replicas=0) if self.print_pod_logs_on_exit: self.__print_pod_logs() if self.delete_on_success: self.__delete_job_cascade(job) return "SUCCEEDED" if "failed" in job.obj["status"]: failed_cnt = job.obj["status"]["failed"] self.__logger.debug("Kubernetes job " + self.uu_name + " status.failed: " + str(failed_cnt)) if self.print_pod_logs_on_exit: self.__print_pod_logs() if failed_cnt > self.max_retrials: job.scale(replicas=0) # avoid more retrials return "FAILED" return "RUNNING"
python
def __get_job_status(self): """Return the Kubernetes job status""" # Figure out status and return it job = self.__get_job() if "succeeded" in job.obj["status"] and job.obj["status"]["succeeded"] > 0: job.scale(replicas=0) if self.print_pod_logs_on_exit: self.__print_pod_logs() if self.delete_on_success: self.__delete_job_cascade(job) return "SUCCEEDED" if "failed" in job.obj["status"]: failed_cnt = job.obj["status"]["failed"] self.__logger.debug("Kubernetes job " + self.uu_name + " status.failed: " + str(failed_cnt)) if self.print_pod_logs_on_exit: self.__print_pod_logs() if failed_cnt > self.max_retrials: job.scale(replicas=0) # avoid more retrials return "FAILED" return "RUNNING"
[ "def", "__get_job_status", "(", "self", ")", ":", "# Figure out status and return it", "job", "=", "self", ".", "__get_job", "(", ")", "if", "\"succeeded\"", "in", "job", ".", "obj", "[", "\"status\"", "]", "and", "job", ".", "obj", "[", "\"status\"", "]", "[", "\"succeeded\"", "]", ">", "0", ":", "job", ".", "scale", "(", "replicas", "=", "0", ")", "if", "self", ".", "print_pod_logs_on_exit", ":", "self", ".", "__print_pod_logs", "(", ")", "if", "self", ".", "delete_on_success", ":", "self", ".", "__delete_job_cascade", "(", "job", ")", "return", "\"SUCCEEDED\"", "if", "\"failed\"", "in", "job", ".", "obj", "[", "\"status\"", "]", ":", "failed_cnt", "=", "job", ".", "obj", "[", "\"status\"", "]", "[", "\"failed\"", "]", "self", ".", "__logger", ".", "debug", "(", "\"Kubernetes job \"", "+", "self", ".", "uu_name", "+", "\" status.failed: \"", "+", "str", "(", "failed_cnt", ")", ")", "if", "self", ".", "print_pod_logs_on_exit", ":", "self", ".", "__print_pod_logs", "(", ")", "if", "failed_cnt", ">", "self", ".", "max_retrials", ":", "job", ".", "scale", "(", "replicas", "=", "0", ")", "# avoid more retrials", "return", "\"FAILED\"", "return", "\"RUNNING\"" ]
Return the Kubernetes job status
[ "Return", "the", "Kubernetes", "job", "status" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/kubernetes.py#L298-L320
train
spotify/luigi
luigi/contrib/sqla.py
SQLAlchemyTarget.engine
def engine(self): """ Return an engine instance, creating it if it doesn't exist. Recreate the engine connection if it wasn't originally created by the current process. """ pid = os.getpid() conn = SQLAlchemyTarget._engine_dict.get(self.connection_string) if not conn or conn.pid != pid: # create and reset connection engine = sqlalchemy.create_engine( self.connection_string, connect_args=self.connect_args, echo=self.echo ) SQLAlchemyTarget._engine_dict[self.connection_string] = self.Connection(engine, pid) return SQLAlchemyTarget._engine_dict[self.connection_string].engine
python
def engine(self): """ Return an engine instance, creating it if it doesn't exist. Recreate the engine connection if it wasn't originally created by the current process. """ pid = os.getpid() conn = SQLAlchemyTarget._engine_dict.get(self.connection_string) if not conn or conn.pid != pid: # create and reset connection engine = sqlalchemy.create_engine( self.connection_string, connect_args=self.connect_args, echo=self.echo ) SQLAlchemyTarget._engine_dict[self.connection_string] = self.Connection(engine, pid) return SQLAlchemyTarget._engine_dict[self.connection_string].engine
[ "def", "engine", "(", "self", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "conn", "=", "SQLAlchemyTarget", ".", "_engine_dict", ".", "get", "(", "self", ".", "connection_string", ")", "if", "not", "conn", "or", "conn", ".", "pid", "!=", "pid", ":", "# create and reset connection", "engine", "=", "sqlalchemy", ".", "create_engine", "(", "self", ".", "connection_string", ",", "connect_args", "=", "self", ".", "connect_args", ",", "echo", "=", "self", ".", "echo", ")", "SQLAlchemyTarget", ".", "_engine_dict", "[", "self", ".", "connection_string", "]", "=", "self", ".", "Connection", "(", "engine", ",", "pid", ")", "return", "SQLAlchemyTarget", ".", "_engine_dict", "[", "self", ".", "connection_string", "]", ".", "engine" ]
Return an engine instance, creating it if it doesn't exist. Recreate the engine connection if it wasn't originally created by the current process.
[ "Return", "an", "engine", "instance", "creating", "it", "if", "it", "doesn", "t", "exist", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sqla.py#L193-L210
train
spotify/luigi
luigi/contrib/sqla.py
SQLAlchemyTarget.touch
def touch(self): """ Mark this update as complete. """ if self.marker_table_bound is None: self.create_marker_table() table = self.marker_table_bound id_exists = self.exists() with self.engine.begin() as conn: if not id_exists: ins = table.insert().values(update_id=self.update_id, target_table=self.target_table, inserted=datetime.datetime.now()) else: ins = table.update().where(sqlalchemy.and_(table.c.update_id == self.update_id, table.c.target_table == self.target_table)).\ values(update_id=self.update_id, target_table=self.target_table, inserted=datetime.datetime.now()) conn.execute(ins) assert self.exists()
python
def touch(self): """ Mark this update as complete. """ if self.marker_table_bound is None: self.create_marker_table() table = self.marker_table_bound id_exists = self.exists() with self.engine.begin() as conn: if not id_exists: ins = table.insert().values(update_id=self.update_id, target_table=self.target_table, inserted=datetime.datetime.now()) else: ins = table.update().where(sqlalchemy.and_(table.c.update_id == self.update_id, table.c.target_table == self.target_table)).\ values(update_id=self.update_id, target_table=self.target_table, inserted=datetime.datetime.now()) conn.execute(ins) assert self.exists()
[ "def", "touch", "(", "self", ")", ":", "if", "self", ".", "marker_table_bound", "is", "None", ":", "self", ".", "create_marker_table", "(", ")", "table", "=", "self", ".", "marker_table_bound", "id_exists", "=", "self", ".", "exists", "(", ")", "with", "self", ".", "engine", ".", "begin", "(", ")", "as", "conn", ":", "if", "not", "id_exists", ":", "ins", "=", "table", ".", "insert", "(", ")", ".", "values", "(", "update_id", "=", "self", ".", "update_id", ",", "target_table", "=", "self", ".", "target_table", ",", "inserted", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "else", ":", "ins", "=", "table", ".", "update", "(", ")", ".", "where", "(", "sqlalchemy", ".", "and_", "(", "table", ".", "c", ".", "update_id", "==", "self", ".", "update_id", ",", "table", ".", "c", ".", "target_table", "==", "self", ".", "target_table", ")", ")", ".", "values", "(", "update_id", "=", "self", ".", "update_id", ",", "target_table", "=", "self", ".", "target_table", ",", "inserted", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "conn", ".", "execute", "(", "ins", ")", "assert", "self", ".", "exists", "(", ")" ]
Mark this update as complete.
[ "Mark", "this", "update", "as", "complete", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sqla.py#L212-L231
train
spotify/luigi
luigi/contrib/sqla.py
SQLAlchemyTarget.create_marker_table
def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ if self.marker_table is None: self.marker_table = luigi.configuration.get_config().get('sqlalchemy', 'marker-table', 'table_updates') engine = self.engine with engine.begin() as con: metadata = sqlalchemy.MetaData() if not con.dialect.has_table(con, self.marker_table): self.marker_table_bound = sqlalchemy.Table( self.marker_table, metadata, sqlalchemy.Column("update_id", sqlalchemy.String(128), primary_key=True), sqlalchemy.Column("target_table", sqlalchemy.String(128)), sqlalchemy.Column("inserted", sqlalchemy.DateTime, default=datetime.datetime.now())) metadata.create_all(engine) else: metadata.reflect(only=[self.marker_table], bind=engine) self.marker_table_bound = metadata.tables[self.marker_table]
python
def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ if self.marker_table is None: self.marker_table = luigi.configuration.get_config().get('sqlalchemy', 'marker-table', 'table_updates') engine = self.engine with engine.begin() as con: metadata = sqlalchemy.MetaData() if not con.dialect.has_table(con, self.marker_table): self.marker_table_bound = sqlalchemy.Table( self.marker_table, metadata, sqlalchemy.Column("update_id", sqlalchemy.String(128), primary_key=True), sqlalchemy.Column("target_table", sqlalchemy.String(128)), sqlalchemy.Column("inserted", sqlalchemy.DateTime, default=datetime.datetime.now())) metadata.create_all(engine) else: metadata.reflect(only=[self.marker_table], bind=engine) self.marker_table_bound = metadata.tables[self.marker_table]
[ "def", "create_marker_table", "(", "self", ")", ":", "if", "self", ".", "marker_table", "is", "None", ":", "self", ".", "marker_table", "=", "luigi", ".", "configuration", ".", "get_config", "(", ")", ".", "get", "(", "'sqlalchemy'", ",", "'marker-table'", ",", "'table_updates'", ")", "engine", "=", "self", ".", "engine", "with", "engine", ".", "begin", "(", ")", "as", "con", ":", "metadata", "=", "sqlalchemy", ".", "MetaData", "(", ")", "if", "not", "con", ".", "dialect", ".", "has_table", "(", "con", ",", "self", ".", "marker_table", ")", ":", "self", ".", "marker_table_bound", "=", "sqlalchemy", ".", "Table", "(", "self", ".", "marker_table", ",", "metadata", ",", "sqlalchemy", ".", "Column", "(", "\"update_id\"", ",", "sqlalchemy", ".", "String", "(", "128", ")", ",", "primary_key", "=", "True", ")", ",", "sqlalchemy", ".", "Column", "(", "\"target_table\"", ",", "sqlalchemy", ".", "String", "(", "128", ")", ")", ",", "sqlalchemy", ".", "Column", "(", "\"inserted\"", ",", "sqlalchemy", ".", "DateTime", ",", "default", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ")", "metadata", ".", "create_all", "(", "engine", ")", "else", ":", "metadata", ".", "reflect", "(", "only", "=", "[", "self", ".", "marker_table", "]", ",", "bind", "=", "engine", ")", "self", ".", "marker_table_bound", "=", "metadata", ".", "tables", "[", "self", ".", "marker_table", "]" ]
Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset.
[ "Create", "marker", "table", "if", "it", "doesn", "t", "exist", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sqla.py#L244-L266
train
spotify/luigi
luigi/contrib/sqla.py
CopyToTable.create_table
def create_table(self, engine): """ Override to provide code for creating the target table. By default it will be created using types specified in columns. If the table exists, then it binds to the existing table. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. :param engine: The sqlalchemy engine instance :type engine: object """ def construct_sqla_columns(columns): retval = [sqlalchemy.Column(*c[0], **c[1]) for c in columns] return retval needs_setup = (len(self.columns) == 0) or (False in [len(c) == 2 for c in self.columns]) if not self.reflect else False if needs_setup: # only names of columns specified, no types raise NotImplementedError("create_table() not implemented for %r and columns types not specified" % self.table) else: # if columns is specified as (name, type) tuples with engine.begin() as con: if self.schema: metadata = sqlalchemy.MetaData(schema=self.schema) else: metadata = sqlalchemy.MetaData() try: if not con.dialect.has_table(con, self.table, self.schema or None): sqla_columns = construct_sqla_columns(self.columns) self.table_bound = sqlalchemy.Table(self.table, metadata, *sqla_columns) metadata.create_all(engine) else: full_table = '.'.join([self.schema, self.table]) if self.schema else self.table metadata.reflect(only=[self.table], bind=engine) self.table_bound = metadata.tables[full_table] except Exception as e: self._logger.exception(self.table + str(e))
python
def create_table(self, engine): """ Override to provide code for creating the target table. By default it will be created using types specified in columns. If the table exists, then it binds to the existing table. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. :param engine: The sqlalchemy engine instance :type engine: object """ def construct_sqla_columns(columns): retval = [sqlalchemy.Column(*c[0], **c[1]) for c in columns] return retval needs_setup = (len(self.columns) == 0) or (False in [len(c) == 2 for c in self.columns]) if not self.reflect else False if needs_setup: # only names of columns specified, no types raise NotImplementedError("create_table() not implemented for %r and columns types not specified" % self.table) else: # if columns is specified as (name, type) tuples with engine.begin() as con: if self.schema: metadata = sqlalchemy.MetaData(schema=self.schema) else: metadata = sqlalchemy.MetaData() try: if not con.dialect.has_table(con, self.table, self.schema or None): sqla_columns = construct_sqla_columns(self.columns) self.table_bound = sqlalchemy.Table(self.table, metadata, *sqla_columns) metadata.create_all(engine) else: full_table = '.'.join([self.schema, self.table]) if self.schema else self.table metadata.reflect(only=[self.table], bind=engine) self.table_bound = metadata.tables[full_table] except Exception as e: self._logger.exception(self.table + str(e))
[ "def", "create_table", "(", "self", ",", "engine", ")", ":", "def", "construct_sqla_columns", "(", "columns", ")", ":", "retval", "=", "[", "sqlalchemy", ".", "Column", "(", "*", "c", "[", "0", "]", ",", "*", "*", "c", "[", "1", "]", ")", "for", "c", "in", "columns", "]", "return", "retval", "needs_setup", "=", "(", "len", "(", "self", ".", "columns", ")", "==", "0", ")", "or", "(", "False", "in", "[", "len", "(", "c", ")", "==", "2", "for", "c", "in", "self", ".", "columns", "]", ")", "if", "not", "self", ".", "reflect", "else", "False", "if", "needs_setup", ":", "# only names of columns specified, no types", "raise", "NotImplementedError", "(", "\"create_table() not implemented for %r and columns types not specified\"", "%", "self", ".", "table", ")", "else", ":", "# if columns is specified as (name, type) tuples", "with", "engine", ".", "begin", "(", ")", "as", "con", ":", "if", "self", ".", "schema", ":", "metadata", "=", "sqlalchemy", ".", "MetaData", "(", "schema", "=", "self", ".", "schema", ")", "else", ":", "metadata", "=", "sqlalchemy", ".", "MetaData", "(", ")", "try", ":", "if", "not", "con", ".", "dialect", ".", "has_table", "(", "con", ",", "self", ".", "table", ",", "self", ".", "schema", "or", "None", ")", ":", "sqla_columns", "=", "construct_sqla_columns", "(", "self", ".", "columns", ")", "self", ".", "table_bound", "=", "sqlalchemy", ".", "Table", "(", "self", ".", "table", ",", "metadata", ",", "*", "sqla_columns", ")", "metadata", ".", "create_all", "(", "engine", ")", "else", ":", "full_table", "=", "'.'", ".", "join", "(", "[", "self", ".", "schema", ",", "self", ".", "table", "]", ")", "if", "self", ".", "schema", "else", "self", ".", "table", "metadata", ".", "reflect", "(", "only", "=", "[", "self", ".", "table", "]", ",", "bind", "=", "engine", ")", "self", ".", "table_bound", "=", "metadata", ".", "tables", "[", "full_table", "]", "except", "Exception", "as", "e", ":", "self", ".", "_logger", ".", "exception", "(", "self", ".", "table", "+", "str", "(", "e", ")", ")" ]
Override to provide code for creating the target table. By default it will be created using types specified in columns. If the table exists, then it binds to the existing table. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. :param engine: The sqlalchemy engine instance :type engine: object
[ "Override", "to", "provide", "code", "for", "creating", "the", "target", "table", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sqla.py#L318-L357
train
spotify/luigi
luigi/contrib/sqla.py
CopyToTable.copy
def copy(self, conn, ins_rows, table_bound): """ This method does the actual insertion of the rows of data given by ins_rows into the database. A task that needs row updates instead of insertions should overload this method. :param conn: The sqlalchemy connection object :param ins_rows: The dictionary of rows with the keys in the format _<column_name>. For example if you have a table with a column name "property", then the key in the dictionary would be "_property". This format is consistent with the bindparam usage in sqlalchemy. :param table_bound: The object referring to the table :return: """ bound_cols = dict((c, sqlalchemy.bindparam("_" + c.key)) for c in table_bound.columns) ins = table_bound.insert().values(bound_cols) conn.execute(ins, ins_rows)
python
def copy(self, conn, ins_rows, table_bound): """ This method does the actual insertion of the rows of data given by ins_rows into the database. A task that needs row updates instead of insertions should overload this method. :param conn: The sqlalchemy connection object :param ins_rows: The dictionary of rows with the keys in the format _<column_name>. For example if you have a table with a column name "property", then the key in the dictionary would be "_property". This format is consistent with the bindparam usage in sqlalchemy. :param table_bound: The object referring to the table :return: """ bound_cols = dict((c, sqlalchemy.bindparam("_" + c.key)) for c in table_bound.columns) ins = table_bound.insert().values(bound_cols) conn.execute(ins, ins_rows)
[ "def", "copy", "(", "self", ",", "conn", ",", "ins_rows", ",", "table_bound", ")", ":", "bound_cols", "=", "dict", "(", "(", "c", ",", "sqlalchemy", ".", "bindparam", "(", "\"_\"", "+", "c", ".", "key", ")", ")", "for", "c", "in", "table_bound", ".", "columns", ")", "ins", "=", "table_bound", ".", "insert", "(", ")", ".", "values", "(", "bound_cols", ")", "conn", ".", "execute", "(", "ins", ",", "ins_rows", ")" ]
This method does the actual insertion of the rows of data given by ins_rows into the database. A task that needs row updates instead of insertions should overload this method. :param conn: The sqlalchemy connection object :param ins_rows: The dictionary of rows with the keys in the format _<column_name>. For example if you have a table with a column name "property", then the key in the dictionary would be "_property". This format is consistent with the bindparam usage in sqlalchemy. :param table_bound: The object referring to the table :return:
[ "This", "method", "does", "the", "actual", "insertion", "of", "the", "rows", "of", "data", "given", "by", "ins_rows", "into", "the", "database", ".", "A", "task", "that", "needs", "row", "updates", "instead", "of", "insertions", "should", "overload", "this", "method", ".", ":", "param", "conn", ":", "The", "sqlalchemy", "connection", "object", ":", "param", "ins_rows", ":", "The", "dictionary", "of", "rows", "with", "the", "keys", "in", "the", "format", "_<column_name", ">", ".", "For", "example", "if", "you", "have", "a", "table", "with", "a", "column", "name", "property", "then", "the", "key", "in", "the", "dictionary", "would", "be", "_property", ".", "This", "format", "is", "consistent", "with", "the", "bindparam", "usage", "in", "sqlalchemy", ".", ":", "param", "table_bound", ":", "The", "object", "referring", "to", "the", "table", ":", "return", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sqla.py#L400-L413
train
spotify/luigi
luigi/contrib/lsf_runner.py
main
def main(args=sys.argv): """Run the work() method from the class instance in the file "job-instance.pickle". """ try: # Set up logging. logging.basicConfig(level=logging.WARN) work_dir = args[1] assert os.path.exists(work_dir), "First argument to lsf_runner.py must be a directory that exists" do_work_on_compute_node(work_dir) except Exception as exc: # Dump encoded data that we will try to fetch using mechanize print(exc) raise
python
def main(args=sys.argv): """Run the work() method from the class instance in the file "job-instance.pickle". """ try: # Set up logging. logging.basicConfig(level=logging.WARN) work_dir = args[1] assert os.path.exists(work_dir), "First argument to lsf_runner.py must be a directory that exists" do_work_on_compute_node(work_dir) except Exception as exc: # Dump encoded data that we will try to fetch using mechanize print(exc) raise
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "try", ":", "# Set up logging.", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "WARN", ")", "work_dir", "=", "args", "[", "1", "]", "assert", "os", ".", "path", ".", "exists", "(", "work_dir", ")", ",", "\"First argument to lsf_runner.py must be a directory that exists\"", "do_work_on_compute_node", "(", "work_dir", ")", "except", "Exception", "as", "exc", ":", "# Dump encoded data that we will try to fetch using mechanize", "print", "(", "exc", ")", "raise" ]
Run the work() method from the class instance in the file "job-instance.pickle".
[ "Run", "the", "work", "()", "method", "from", "the", "class", "instance", "in", "the", "file", "job", "-", "instance", ".", "pickle", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf_runner.py#L67-L79
train
spotify/luigi
luigi/contrib/hdfs/target.py
HdfsTarget.rename
def rename(self, path, raise_if_exists=False): """ Does not change self.path. Unlike ``move_dir()``, ``rename()`` might cause nested directories. See spotify/luigi#522 """ if isinstance(path, HdfsTarget): path = path.path if raise_if_exists and self.fs.exists(path): raise RuntimeError('Destination exists: %s' % path) self.fs.rename(self.path, path)
python
def rename(self, path, raise_if_exists=False): """ Does not change self.path. Unlike ``move_dir()``, ``rename()`` might cause nested directories. See spotify/luigi#522 """ if isinstance(path, HdfsTarget): path = path.path if raise_if_exists and self.fs.exists(path): raise RuntimeError('Destination exists: %s' % path) self.fs.rename(self.path, path)
[ "def", "rename", "(", "self", ",", "path", ",", "raise_if_exists", "=", "False", ")", ":", "if", "isinstance", "(", "path", ",", "HdfsTarget", ")", ":", "path", "=", "path", ".", "path", "if", "raise_if_exists", "and", "self", ".", "fs", ".", "exists", "(", "path", ")", ":", "raise", "RuntimeError", "(", "'Destination exists: %s'", "%", "path", ")", "self", ".", "fs", ".", "rename", "(", "self", ".", "path", ",", "path", ")" ]
Does not change self.path. Unlike ``move_dir()``, ``rename()`` might cause nested directories. See spotify/luigi#522
[ "Does", "not", "change", "self", ".", "path", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/target.py#L121-L132
train
spotify/luigi
luigi/contrib/hdfs/target.py
HdfsTarget.move
def move(self, path, raise_if_exists=False): """ Alias for ``rename()`` """ self.rename(path, raise_if_exists=raise_if_exists)
python
def move(self, path, raise_if_exists=False): """ Alias for ``rename()`` """ self.rename(path, raise_if_exists=raise_if_exists)
[ "def", "move", "(", "self", ",", "path", ",", "raise_if_exists", "=", "False", ")", ":", "self", ".", "rename", "(", "path", ",", "raise_if_exists", "=", "raise_if_exists", ")" ]
Alias for ``rename()``
[ "Alias", "for", "rename", "()" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/target.py#L134-L138
train
spotify/luigi
luigi/contrib/hdfs/target.py
HdfsTarget.is_writable
def is_writable(self): """ Currently only works with hadoopcli """ if "/" in self.path: # example path: /log/ap/2013-01-17/00 parts = self.path.split("/") # start with the full path and then up the tree until we can check length = len(parts) for part in range(length): path = "/".join(parts[0:length - part]) + "/" if self.fs.exists(path): # if the path exists and we can write there, great! if self._is_writable(path): return True # if it exists and we can't =( sad panda else: return False # We went through all parts of the path and we still couldn't find # one that exists. return False
python
def is_writable(self): """ Currently only works with hadoopcli """ if "/" in self.path: # example path: /log/ap/2013-01-17/00 parts = self.path.split("/") # start with the full path and then up the tree until we can check length = len(parts) for part in range(length): path = "/".join(parts[0:length - part]) + "/" if self.fs.exists(path): # if the path exists and we can write there, great! if self._is_writable(path): return True # if it exists and we can't =( sad panda else: return False # We went through all parts of the path and we still couldn't find # one that exists. return False
[ "def", "is_writable", "(", "self", ")", ":", "if", "\"/\"", "in", "self", ".", "path", ":", "# example path: /log/ap/2013-01-17/00", "parts", "=", "self", ".", "path", ".", "split", "(", "\"/\"", ")", "# start with the full path and then up the tree until we can check", "length", "=", "len", "(", "parts", ")", "for", "part", "in", "range", "(", "length", ")", ":", "path", "=", "\"/\"", ".", "join", "(", "parts", "[", "0", ":", "length", "-", "part", "]", ")", "+", "\"/\"", "if", "self", ".", "fs", ".", "exists", "(", "path", ")", ":", "# if the path exists and we can write there, great!", "if", "self", ".", "_is_writable", "(", "path", ")", ":", "return", "True", "# if it exists and we can't =( sad panda", "else", ":", "return", "False", "# We went through all parts of the path and we still couldn't find", "# one that exists.", "return", "False" ]
Currently only works with hadoopcli
[ "Currently", "only", "works", "with", "hadoopcli" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/target.py#L158-L178
train
spotify/luigi
luigi/execution_summary.py
_partition_tasks
def _partition_tasks(worker): """ Takes a worker and sorts out tasks based on their status. Still_pending_not_ext is only used to get upstream_failure, upstream_missing_dependency and run_by_other_worker """ task_history = worker._add_task_history pending_tasks = {task for(task, status, ext) in task_history if status == 'PENDING'} set_tasks = {} set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks} set_tasks["already_done"] = {task for (task, status, ext) in task_history if status == 'DONE' and task not in pending_tasks and task not in set_tasks["completed"]} set_tasks["ever_failed"] = {task for (task, status, ext) in task_history if status == 'FAILED'} set_tasks["failed"] = set_tasks["ever_failed"] - set_tasks["completed"] set_tasks["scheduling_error"] = {task for(task, status, ext) in task_history if status == 'UNKNOWN'} set_tasks["still_pending_ext"] = {task for (task, status, ext) in task_history if status == 'PENDING' and task not in set_tasks["ever_failed"] and task not in set_tasks["completed"] and not ext} set_tasks["still_pending_not_ext"] = {task for (task, status, ext) in task_history if status == 'PENDING' and task not in set_tasks["ever_failed"] and task not in set_tasks["completed"] and ext} set_tasks["run_by_other_worker"] = set() set_tasks["upstream_failure"] = set() set_tasks["upstream_missing_dependency"] = set() set_tasks["upstream_run_by_other_worker"] = set() set_tasks["upstream_scheduling_error"] = set() set_tasks["not_run"] = set() return set_tasks
python
def _partition_tasks(worker): """ Takes a worker and sorts out tasks based on their status. Still_pending_not_ext is only used to get upstream_failure, upstream_missing_dependency and run_by_other_worker """ task_history = worker._add_task_history pending_tasks = {task for(task, status, ext) in task_history if status == 'PENDING'} set_tasks = {} set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks} set_tasks["already_done"] = {task for (task, status, ext) in task_history if status == 'DONE' and task not in pending_tasks and task not in set_tasks["completed"]} set_tasks["ever_failed"] = {task for (task, status, ext) in task_history if status == 'FAILED'} set_tasks["failed"] = set_tasks["ever_failed"] - set_tasks["completed"] set_tasks["scheduling_error"] = {task for(task, status, ext) in task_history if status == 'UNKNOWN'} set_tasks["still_pending_ext"] = {task for (task, status, ext) in task_history if status == 'PENDING' and task not in set_tasks["ever_failed"] and task not in set_tasks["completed"] and not ext} set_tasks["still_pending_not_ext"] = {task for (task, status, ext) in task_history if status == 'PENDING' and task not in set_tasks["ever_failed"] and task not in set_tasks["completed"] and ext} set_tasks["run_by_other_worker"] = set() set_tasks["upstream_failure"] = set() set_tasks["upstream_missing_dependency"] = set() set_tasks["upstream_run_by_other_worker"] = set() set_tasks["upstream_scheduling_error"] = set() set_tasks["not_run"] = set() return set_tasks
[ "def", "_partition_tasks", "(", "worker", ")", ":", "task_history", "=", "worker", ".", "_add_task_history", "pending_tasks", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'PENDING'", "}", "set_tasks", "=", "{", "}", "set_tasks", "[", "\"completed\"", "]", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'DONE'", "and", "task", "in", "pending_tasks", "}", "set_tasks", "[", "\"already_done\"", "]", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'DONE'", "and", "task", "not", "in", "pending_tasks", "and", "task", "not", "in", "set_tasks", "[", "\"completed\"", "]", "}", "set_tasks", "[", "\"ever_failed\"", "]", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'FAILED'", "}", "set_tasks", "[", "\"failed\"", "]", "=", "set_tasks", "[", "\"ever_failed\"", "]", "-", "set_tasks", "[", "\"completed\"", "]", "set_tasks", "[", "\"scheduling_error\"", "]", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'UNKNOWN'", "}", "set_tasks", "[", "\"still_pending_ext\"", "]", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'PENDING'", "and", "task", "not", "in", "set_tasks", "[", "\"ever_failed\"", "]", "and", "task", "not", "in", "set_tasks", "[", "\"completed\"", "]", "and", "not", "ext", "}", "set_tasks", "[", "\"still_pending_not_ext\"", "]", "=", "{", "task", "for", "(", "task", ",", "status", ",", "ext", ")", "in", "task_history", "if", "status", "==", "'PENDING'", "and", "task", "not", "in", "set_tasks", "[", "\"ever_failed\"", "]", "and", "task", "not", "in", "set_tasks", "[", "\"completed\"", "]", "and", "ext", "}", "set_tasks", "[", "\"run_by_other_worker\"", "]", "=", "set", "(", ")", "set_tasks", "[", "\"upstream_failure\"", "]", "=", "set", "(", ")", "set_tasks", "[", "\"upstream_missing_dependency\"", "]", "=", "set", "(", ")", "set_tasks", "[", "\"upstream_run_by_other_worker\"", "]", "=", "set", "(", ")", "set_tasks", "[", "\"upstream_scheduling_error\"", "]", "=", "set", "(", ")", "set_tasks", "[", "\"not_run\"", "]", "=", "set", "(", ")", "return", "set_tasks" ]
Takes a worker and sorts out tasks based on their status. Still_pending_not_ext is only used to get upstream_failure, upstream_missing_dependency and run_by_other_worker
[ "Takes", "a", "worker", "and", "sorts", "out", "tasks", "based", "on", "their", "status", ".", "Still_pending_not_ext", "is", "only", "used", "to", "get", "upstream_failure", "upstream_missing_dependency", "and", "run_by_other_worker" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L91-L115
train
spotify/luigi
luigi/execution_summary.py
_populate_unknown_statuses
def _populate_unknown_statuses(set_tasks): """ Add the "upstream_*" and "not_run" statuses my mutating set_tasks. """ visited = set() for task in set_tasks["still_pending_not_ext"]: _depth_first_search(set_tasks, task, visited)
python
def _populate_unknown_statuses(set_tasks): """ Add the "upstream_*" and "not_run" statuses my mutating set_tasks. """ visited = set() for task in set_tasks["still_pending_not_ext"]: _depth_first_search(set_tasks, task, visited)
[ "def", "_populate_unknown_statuses", "(", "set_tasks", ")", ":", "visited", "=", "set", "(", ")", "for", "task", "in", "set_tasks", "[", "\"still_pending_not_ext\"", "]", ":", "_depth_first_search", "(", "set_tasks", ",", "task", ",", "visited", ")" ]
Add the "upstream_*" and "not_run" statuses my mutating set_tasks.
[ "Add", "the", "upstream_", "*", "and", "not_run", "statuses", "my", "mutating", "set_tasks", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L125-L131
train
spotify/luigi
luigi/execution_summary.py
_depth_first_search
def _depth_first_search(set_tasks, current_task, visited): """ This dfs checks why tasks are still pending. """ visited.add(current_task) if current_task in set_tasks["still_pending_not_ext"]: upstream_failure = False upstream_missing_dependency = False upstream_run_by_other_worker = False upstream_scheduling_error = False for task in current_task._requires(): if task not in visited: _depth_first_search(set_tasks, task, visited) if task in set_tasks["ever_failed"] or task in set_tasks["upstream_failure"]: set_tasks["upstream_failure"].add(current_task) upstream_failure = True if task in set_tasks["still_pending_ext"] or task in set_tasks["upstream_missing_dependency"]: set_tasks["upstream_missing_dependency"].add(current_task) upstream_missing_dependency = True if task in set_tasks["run_by_other_worker"] or task in set_tasks["upstream_run_by_other_worker"]: set_tasks["upstream_run_by_other_worker"].add(current_task) upstream_run_by_other_worker = True if task in set_tasks["scheduling_error"]: set_tasks["upstream_scheduling_error"].add(current_task) upstream_scheduling_error = True if not upstream_failure and not upstream_missing_dependency and \ not upstream_run_by_other_worker and not upstream_scheduling_error and \ current_task not in set_tasks["run_by_other_worker"]: set_tasks["not_run"].add(current_task)
python
def _depth_first_search(set_tasks, current_task, visited): """ This dfs checks why tasks are still pending. """ visited.add(current_task) if current_task in set_tasks["still_pending_not_ext"]: upstream_failure = False upstream_missing_dependency = False upstream_run_by_other_worker = False upstream_scheduling_error = False for task in current_task._requires(): if task not in visited: _depth_first_search(set_tasks, task, visited) if task in set_tasks["ever_failed"] or task in set_tasks["upstream_failure"]: set_tasks["upstream_failure"].add(current_task) upstream_failure = True if task in set_tasks["still_pending_ext"] or task in set_tasks["upstream_missing_dependency"]: set_tasks["upstream_missing_dependency"].add(current_task) upstream_missing_dependency = True if task in set_tasks["run_by_other_worker"] or task in set_tasks["upstream_run_by_other_worker"]: set_tasks["upstream_run_by_other_worker"].add(current_task) upstream_run_by_other_worker = True if task in set_tasks["scheduling_error"]: set_tasks["upstream_scheduling_error"].add(current_task) upstream_scheduling_error = True if not upstream_failure and not upstream_missing_dependency and \ not upstream_run_by_other_worker and not upstream_scheduling_error and \ current_task not in set_tasks["run_by_other_worker"]: set_tasks["not_run"].add(current_task)
[ "def", "_depth_first_search", "(", "set_tasks", ",", "current_task", ",", "visited", ")", ":", "visited", ".", "add", "(", "current_task", ")", "if", "current_task", "in", "set_tasks", "[", "\"still_pending_not_ext\"", "]", ":", "upstream_failure", "=", "False", "upstream_missing_dependency", "=", "False", "upstream_run_by_other_worker", "=", "False", "upstream_scheduling_error", "=", "False", "for", "task", "in", "current_task", ".", "_requires", "(", ")", ":", "if", "task", "not", "in", "visited", ":", "_depth_first_search", "(", "set_tasks", ",", "task", ",", "visited", ")", "if", "task", "in", "set_tasks", "[", "\"ever_failed\"", "]", "or", "task", "in", "set_tasks", "[", "\"upstream_failure\"", "]", ":", "set_tasks", "[", "\"upstream_failure\"", "]", ".", "add", "(", "current_task", ")", "upstream_failure", "=", "True", "if", "task", "in", "set_tasks", "[", "\"still_pending_ext\"", "]", "or", "task", "in", "set_tasks", "[", "\"upstream_missing_dependency\"", "]", ":", "set_tasks", "[", "\"upstream_missing_dependency\"", "]", ".", "add", "(", "current_task", ")", "upstream_missing_dependency", "=", "True", "if", "task", "in", "set_tasks", "[", "\"run_by_other_worker\"", "]", "or", "task", "in", "set_tasks", "[", "\"upstream_run_by_other_worker\"", "]", ":", "set_tasks", "[", "\"upstream_run_by_other_worker\"", "]", ".", "add", "(", "current_task", ")", "upstream_run_by_other_worker", "=", "True", "if", "task", "in", "set_tasks", "[", "\"scheduling_error\"", "]", ":", "set_tasks", "[", "\"upstream_scheduling_error\"", "]", ".", "add", "(", "current_task", ")", "upstream_scheduling_error", "=", "True", "if", "not", "upstream_failure", "and", "not", "upstream_missing_dependency", "and", "not", "upstream_run_by_other_worker", "and", "not", "upstream_scheduling_error", "and", "current_task", "not", "in", "set_tasks", "[", "\"run_by_other_worker\"", "]", ":", "set_tasks", "[", "\"not_run\"", "]", ".", "add", "(", "current_task", ")" ]
This dfs checks why tasks are still pending.
[ "This", "dfs", "checks", "why", "tasks", "are", "still", "pending", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L134-L162
train
spotify/luigi
luigi/execution_summary.py
_get_str
def _get_str(task_dict, extra_indent): """ This returns a string for each status """ summary_length = execution_summary().summary_length lines = [] task_names = sorted(task_dict.keys()) for task_family in task_names: tasks = task_dict[task_family] tasks = sorted(tasks, key=lambda x: str(x)) prefix_size = 8 if extra_indent else 4 prefix = ' ' * prefix_size line = None if summary_length > 0 and len(lines) >= summary_length: line = prefix + "..." lines.append(line) break if len(tasks[0].get_params()) == 0: line = prefix + '- {0} {1}()'.format(len(tasks), str(task_family)) elif _get_len_of_params(tasks[0]) > 60 or len(str(tasks[0])) > 200 or \ (len(tasks) == 2 and len(tasks[0].get_params()) > 1 and (_get_len_of_params(tasks[0]) > 40 or len(str(tasks[0])) > 100)): """ This is to make sure that there is no really long task in the output """ line = prefix + '- {0} {1}(...)'.format(len(tasks), task_family) elif len((tasks[0].get_params())) == 1: attributes = {getattr(task, tasks[0].get_params()[0][0]) for task in tasks} param_class = tasks[0].get_params()[0][1] first, last = _ranging_attributes(attributes, param_class) if first is not None and last is not None and len(attributes) > 3: param_str = '{0}...{1}'.format(param_class.serialize(first), param_class.serialize(last)) else: param_str = '{0}'.format(_get_str_one_parameter(tasks)) line = prefix + '- {0} {1}({2}={3})'.format(len(tasks), task_family, tasks[0].get_params()[0][0], param_str) else: ranging = False params = _get_set_of_params(tasks) unique_param_keys = list(_get_unique_param_keys(params)) if len(unique_param_keys) == 1: unique_param, = unique_param_keys attributes = params[unique_param] param_class = unique_param[1] first, last = _ranging_attributes(attributes, param_class) if first is not None and last is not None and len(attributes) > 2: ranging = True line = prefix + '- {0} {1}({2}'.format(len(tasks), task_family, _get_str_ranging_multiple_parameters(first, last, tasks, unique_param)) if not ranging: if len(tasks) == 1: line = prefix + '- {0} {1}'.format(len(tasks), tasks[0]) if len(tasks) == 2: line = prefix + '- {0} {1} and {2}'.format(len(tasks), tasks[0], tasks[1]) if len(tasks) > 2: line = prefix + '- {0} {1} ...'.format(len(tasks), tasks[0]) lines.append(line) return '\n'.join(lines)
python
def _get_str(task_dict, extra_indent): """ This returns a string for each status """ summary_length = execution_summary().summary_length lines = [] task_names = sorted(task_dict.keys()) for task_family in task_names: tasks = task_dict[task_family] tasks = sorted(tasks, key=lambda x: str(x)) prefix_size = 8 if extra_indent else 4 prefix = ' ' * prefix_size line = None if summary_length > 0 and len(lines) >= summary_length: line = prefix + "..." lines.append(line) break if len(tasks[0].get_params()) == 0: line = prefix + '- {0} {1}()'.format(len(tasks), str(task_family)) elif _get_len_of_params(tasks[0]) > 60 or len(str(tasks[0])) > 200 or \ (len(tasks) == 2 and len(tasks[0].get_params()) > 1 and (_get_len_of_params(tasks[0]) > 40 or len(str(tasks[0])) > 100)): """ This is to make sure that there is no really long task in the output """ line = prefix + '- {0} {1}(...)'.format(len(tasks), task_family) elif len((tasks[0].get_params())) == 1: attributes = {getattr(task, tasks[0].get_params()[0][0]) for task in tasks} param_class = tasks[0].get_params()[0][1] first, last = _ranging_attributes(attributes, param_class) if first is not None and last is not None and len(attributes) > 3: param_str = '{0}...{1}'.format(param_class.serialize(first), param_class.serialize(last)) else: param_str = '{0}'.format(_get_str_one_parameter(tasks)) line = prefix + '- {0} {1}({2}={3})'.format(len(tasks), task_family, tasks[0].get_params()[0][0], param_str) else: ranging = False params = _get_set_of_params(tasks) unique_param_keys = list(_get_unique_param_keys(params)) if len(unique_param_keys) == 1: unique_param, = unique_param_keys attributes = params[unique_param] param_class = unique_param[1] first, last = _ranging_attributes(attributes, param_class) if first is not None and last is not None and len(attributes) > 2: ranging = True line = prefix + '- {0} {1}({2}'.format(len(tasks), task_family, _get_str_ranging_multiple_parameters(first, last, tasks, unique_param)) if not ranging: if len(tasks) == 1: line = prefix + '- {0} {1}'.format(len(tasks), tasks[0]) if len(tasks) == 2: line = prefix + '- {0} {1} and {2}'.format(len(tasks), tasks[0], tasks[1]) if len(tasks) > 2: line = prefix + '- {0} {1} ...'.format(len(tasks), tasks[0]) lines.append(line) return '\n'.join(lines)
[ "def", "_get_str", "(", "task_dict", ",", "extra_indent", ")", ":", "summary_length", "=", "execution_summary", "(", ")", ".", "summary_length", "lines", "=", "[", "]", "task_names", "=", "sorted", "(", "task_dict", ".", "keys", "(", ")", ")", "for", "task_family", "in", "task_names", ":", "tasks", "=", "task_dict", "[", "task_family", "]", "tasks", "=", "sorted", "(", "tasks", ",", "key", "=", "lambda", "x", ":", "str", "(", "x", ")", ")", "prefix_size", "=", "8", "if", "extra_indent", "else", "4", "prefix", "=", "' '", "*", "prefix_size", "line", "=", "None", "if", "summary_length", ">", "0", "and", "len", "(", "lines", ")", ">=", "summary_length", ":", "line", "=", "prefix", "+", "\"...\"", "lines", ".", "append", "(", "line", ")", "break", "if", "len", "(", "tasks", "[", "0", "]", ".", "get_params", "(", ")", ")", "==", "0", ":", "line", "=", "prefix", "+", "'- {0} {1}()'", ".", "format", "(", "len", "(", "tasks", ")", ",", "str", "(", "task_family", ")", ")", "elif", "_get_len_of_params", "(", "tasks", "[", "0", "]", ")", ">", "60", "or", "len", "(", "str", "(", "tasks", "[", "0", "]", ")", ")", ">", "200", "or", "(", "len", "(", "tasks", ")", "==", "2", "and", "len", "(", "tasks", "[", "0", "]", ".", "get_params", "(", ")", ")", ">", "1", "and", "(", "_get_len_of_params", "(", "tasks", "[", "0", "]", ")", ">", "40", "or", "len", "(", "str", "(", "tasks", "[", "0", "]", ")", ")", ">", "100", ")", ")", ":", "\"\"\"\n This is to make sure that there is no really long task in the output\n \"\"\"", "line", "=", "prefix", "+", "'- {0} {1}(...)'", ".", "format", "(", "len", "(", "tasks", ")", ",", "task_family", ")", "elif", "len", "(", "(", "tasks", "[", "0", "]", ".", "get_params", "(", ")", ")", ")", "==", "1", ":", "attributes", "=", "{", "getattr", "(", "task", ",", "tasks", "[", "0", "]", ".", "get_params", "(", ")", "[", "0", "]", "[", "0", "]", ")", "for", "task", "in", "tasks", "}", "param_class", "=", "tasks", "[", "0", "]", ".", "get_params", "(", ")", "[", "0", "]", "[", "1", "]", "first", ",", "last", "=", "_ranging_attributes", "(", "attributes", ",", "param_class", ")", "if", "first", "is", "not", "None", "and", "last", "is", "not", "None", "and", "len", "(", "attributes", ")", ">", "3", ":", "param_str", "=", "'{0}...{1}'", ".", "format", "(", "param_class", ".", "serialize", "(", "first", ")", ",", "param_class", ".", "serialize", "(", "last", ")", ")", "else", ":", "param_str", "=", "'{0}'", ".", "format", "(", "_get_str_one_parameter", "(", "tasks", ")", ")", "line", "=", "prefix", "+", "'- {0} {1}({2}={3})'", ".", "format", "(", "len", "(", "tasks", ")", ",", "task_family", ",", "tasks", "[", "0", "]", ".", "get_params", "(", ")", "[", "0", "]", "[", "0", "]", ",", "param_str", ")", "else", ":", "ranging", "=", "False", "params", "=", "_get_set_of_params", "(", "tasks", ")", "unique_param_keys", "=", "list", "(", "_get_unique_param_keys", "(", "params", ")", ")", "if", "len", "(", "unique_param_keys", ")", "==", "1", ":", "unique_param", ",", "=", "unique_param_keys", "attributes", "=", "params", "[", "unique_param", "]", "param_class", "=", "unique_param", "[", "1", "]", "first", ",", "last", "=", "_ranging_attributes", "(", "attributes", ",", "param_class", ")", "if", "first", "is", "not", "None", "and", "last", "is", "not", "None", "and", "len", "(", "attributes", ")", ">", "2", ":", "ranging", "=", "True", "line", "=", "prefix", "+", "'- {0} {1}({2}'", ".", "format", "(", "len", "(", "tasks", ")", ",", "task_family", ",", "_get_str_ranging_multiple_parameters", "(", "first", ",", "last", ",", "tasks", ",", "unique_param", ")", ")", "if", "not", "ranging", ":", "if", "len", "(", "tasks", ")", "==", "1", ":", "line", "=", "prefix", "+", "'- {0} {1}'", ".", "format", "(", "len", "(", "tasks", ")", ",", "tasks", "[", "0", "]", ")", "if", "len", "(", "tasks", ")", "==", "2", ":", "line", "=", "prefix", "+", "'- {0} {1} and {2}'", ".", "format", "(", "len", "(", "tasks", ")", ",", "tasks", "[", "0", "]", ",", "tasks", "[", "1", "]", ")", "if", "len", "(", "tasks", ")", ">", "2", ":", "line", "=", "prefix", "+", "'- {0} {1} ...'", ".", "format", "(", "len", "(", "tasks", ")", ",", "tasks", "[", "0", "]", ")", "lines", ".", "append", "(", "line", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
This returns a string for each status
[ "This", "returns", "a", "string", "for", "each", "status" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L165-L222
train
spotify/luigi
luigi/execution_summary.py
_ranging_attributes
def _ranging_attributes(attributes, param_class): """ Checks if there is a continuous range """ next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes} in_first = attributes.difference(next_attributes) in_second = next_attributes.difference(attributes) if len(in_first) == 1 and len(in_second) == 1: for x in attributes: if {param_class.next_in_enumeration(x)} == in_second: return next(iter(in_first)), x return None, None
python
def _ranging_attributes(attributes, param_class): """ Checks if there is a continuous range """ next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes} in_first = attributes.difference(next_attributes) in_second = next_attributes.difference(attributes) if len(in_first) == 1 and len(in_second) == 1: for x in attributes: if {param_class.next_in_enumeration(x)} == in_second: return next(iter(in_first)), x return None, None
[ "def", "_ranging_attributes", "(", "attributes", ",", "param_class", ")", ":", "next_attributes", "=", "{", "param_class", ".", "next_in_enumeration", "(", "attribute", ")", "for", "attribute", "in", "attributes", "}", "in_first", "=", "attributes", ".", "difference", "(", "next_attributes", ")", "in_second", "=", "next_attributes", ".", "difference", "(", "attributes", ")", "if", "len", "(", "in_first", ")", "==", "1", "and", "len", "(", "in_second", ")", "==", "1", ":", "for", "x", "in", "attributes", ":", "if", "{", "param_class", ".", "next_in_enumeration", "(", "x", ")", "}", "==", "in_second", ":", "return", "next", "(", "iter", "(", "in_first", ")", ")", ",", "x", "return", "None", ",", "None" ]
Checks if there is a continuous range
[ "Checks", "if", "there", "is", "a", "continuous", "range" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L257-L268
train
spotify/luigi
luigi/execution_summary.py
_get_comments
def _get_comments(group_tasks): """ Get the human readable comments and quantities for the task types. """ comments = {} for status, human in _COMMENTS: num_tasks = _get_number_of_tasks_for(status, group_tasks) if num_tasks: space = " " if status in _PENDING_SUB_STATUSES else "" comments[status] = '{space}* {num_tasks} {human}:\n'.format( space=space, num_tasks=num_tasks, human=human) return comments
python
def _get_comments(group_tasks): """ Get the human readable comments and quantities for the task types. """ comments = {} for status, human in _COMMENTS: num_tasks = _get_number_of_tasks_for(status, group_tasks) if num_tasks: space = " " if status in _PENDING_SUB_STATUSES else "" comments[status] = '{space}* {num_tasks} {human}:\n'.format( space=space, num_tasks=num_tasks, human=human) return comments
[ "def", "_get_comments", "(", "group_tasks", ")", ":", "comments", "=", "{", "}", "for", "status", ",", "human", "in", "_COMMENTS", ":", "num_tasks", "=", "_get_number_of_tasks_for", "(", "status", ",", "group_tasks", ")", "if", "num_tasks", ":", "space", "=", "\" \"", "if", "status", "in", "_PENDING_SUB_STATUSES", "else", "\"\"", "comments", "[", "status", "]", "=", "'{space}* {num_tasks} {human}:\\n'", ".", "format", "(", "space", "=", "space", ",", "num_tasks", "=", "num_tasks", ",", "human", "=", "human", ")", "return", "comments" ]
Get the human readable comments and quantities for the task types.
[ "Get", "the", "human", "readable", "comments", "and", "quantities", "for", "the", "task", "types", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L301-L314
train
spotify/luigi
luigi/execution_summary.py
_get_run_by_other_worker
def _get_run_by_other_worker(worker): """ This returns a set of the tasks that are being run by other worker """ task_sets = _get_external_workers(worker).values() return functools.reduce(lambda a, b: a | b, task_sets, set())
python
def _get_run_by_other_worker(worker): """ This returns a set of the tasks that are being run by other worker """ task_sets = _get_external_workers(worker).values() return functools.reduce(lambda a, b: a | b, task_sets, set())
[ "def", "_get_run_by_other_worker", "(", "worker", ")", ":", "task_sets", "=", "_get_external_workers", "(", "worker", ")", ".", "values", "(", ")", "return", "functools", ".", "reduce", "(", "lambda", "a", ",", "b", ":", "a", "|", "b", ",", "task_sets", ",", "set", "(", ")", ")" ]
This returns a set of the tasks that are being run by other worker
[ "This", "returns", "a", "set", "of", "the", "tasks", "that", "are", "being", "run", "by", "other", "worker" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L350-L355
train
spotify/luigi
luigi/execution_summary.py
_get_external_workers
def _get_external_workers(worker): """ This returns a dict with a set of tasks for all of the other workers """ worker_that_blocked_task = collections.defaultdict(set) get_work_response_history = worker._get_work_response_history for get_work_response in get_work_response_history: if get_work_response['task_id'] is None: for running_task in get_work_response['running_tasks']: other_worker_id = running_task['worker'] other_task_id = running_task['task_id'] other_task = worker._scheduled_tasks.get(other_task_id) if other_worker_id == worker._id or not other_task: continue worker_that_blocked_task[other_worker_id].add(other_task) return worker_that_blocked_task
python
def _get_external_workers(worker): """ This returns a dict with a set of tasks for all of the other workers """ worker_that_blocked_task = collections.defaultdict(set) get_work_response_history = worker._get_work_response_history for get_work_response in get_work_response_history: if get_work_response['task_id'] is None: for running_task in get_work_response['running_tasks']: other_worker_id = running_task['worker'] other_task_id = running_task['task_id'] other_task = worker._scheduled_tasks.get(other_task_id) if other_worker_id == worker._id or not other_task: continue worker_that_blocked_task[other_worker_id].add(other_task) return worker_that_blocked_task
[ "def", "_get_external_workers", "(", "worker", ")", ":", "worker_that_blocked_task", "=", "collections", ".", "defaultdict", "(", "set", ")", "get_work_response_history", "=", "worker", ".", "_get_work_response_history", "for", "get_work_response", "in", "get_work_response_history", ":", "if", "get_work_response", "[", "'task_id'", "]", "is", "None", ":", "for", "running_task", "in", "get_work_response", "[", "'running_tasks'", "]", ":", "other_worker_id", "=", "running_task", "[", "'worker'", "]", "other_task_id", "=", "running_task", "[", "'task_id'", "]", "other_task", "=", "worker", ".", "_scheduled_tasks", ".", "get", "(", "other_task_id", ")", "if", "other_worker_id", "==", "worker", ".", "_id", "or", "not", "other_task", ":", "continue", "worker_that_blocked_task", "[", "other_worker_id", "]", ".", "add", "(", "other_task", ")", "return", "worker_that_blocked_task" ]
This returns a dict with a set of tasks for all of the other workers
[ "This", "returns", "a", "dict", "with", "a", "set", "of", "tasks", "for", "all", "of", "the", "other", "workers" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L358-L373
train
spotify/luigi
luigi/execution_summary.py
_group_tasks_by_name_and_status
def _group_tasks_by_name_and_status(task_dict): """ Takes a dictionary with sets of tasks grouped by their status and returns a dictionary with dictionaries with an array of tasks grouped by their status and task name """ group_status = {} for task in task_dict: if task.task_family not in group_status: group_status[task.task_family] = [] group_status[task.task_family].append(task) return group_status
python
def _group_tasks_by_name_and_status(task_dict): """ Takes a dictionary with sets of tasks grouped by their status and returns a dictionary with dictionaries with an array of tasks grouped by their status and task name """ group_status = {} for task in task_dict: if task.task_family not in group_status: group_status[task.task_family] = [] group_status[task.task_family].append(task) return group_status
[ "def", "_group_tasks_by_name_and_status", "(", "task_dict", ")", ":", "group_status", "=", "{", "}", "for", "task", "in", "task_dict", ":", "if", "task", ".", "task_family", "not", "in", "group_status", ":", "group_status", "[", "task", ".", "task_family", "]", "=", "[", "]", "group_status", "[", "task", ".", "task_family", "]", ".", "append", "(", "task", ")", "return", "group_status" ]
Takes a dictionary with sets of tasks grouped by their status and returns a dictionary with dictionaries with an array of tasks grouped by their status and task name
[ "Takes", "a", "dictionary", "with", "sets", "of", "tasks", "grouped", "by", "their", "status", "and", "returns", "a", "dictionary", "with", "dictionaries", "with", "an", "array", "of", "tasks", "grouped", "by", "their", "status", "and", "task", "name" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L376-L387
train
spotify/luigi
luigi/execution_summary.py
_tasks_status
def _tasks_status(set_tasks): """ Given a grouped set of tasks, returns a LuigiStatusCode """ if set_tasks["ever_failed"]: if not set_tasks["failed"]: return LuigiStatusCode.SUCCESS_WITH_RETRY else: if set_tasks["scheduling_error"]: return LuigiStatusCode.FAILED_AND_SCHEDULING_FAILED return LuigiStatusCode.FAILED elif set_tasks["scheduling_error"]: return LuigiStatusCode.SCHEDULING_FAILED elif set_tasks["not_run"]: return LuigiStatusCode.NOT_RUN elif set_tasks["still_pending_ext"]: return LuigiStatusCode.MISSING_EXT else: return LuigiStatusCode.SUCCESS
python
def _tasks_status(set_tasks): """ Given a grouped set of tasks, returns a LuigiStatusCode """ if set_tasks["ever_failed"]: if not set_tasks["failed"]: return LuigiStatusCode.SUCCESS_WITH_RETRY else: if set_tasks["scheduling_error"]: return LuigiStatusCode.FAILED_AND_SCHEDULING_FAILED return LuigiStatusCode.FAILED elif set_tasks["scheduling_error"]: return LuigiStatusCode.SCHEDULING_FAILED elif set_tasks["not_run"]: return LuigiStatusCode.NOT_RUN elif set_tasks["still_pending_ext"]: return LuigiStatusCode.MISSING_EXT else: return LuigiStatusCode.SUCCESS
[ "def", "_tasks_status", "(", "set_tasks", ")", ":", "if", "set_tasks", "[", "\"ever_failed\"", "]", ":", "if", "not", "set_tasks", "[", "\"failed\"", "]", ":", "return", "LuigiStatusCode", ".", "SUCCESS_WITH_RETRY", "else", ":", "if", "set_tasks", "[", "\"scheduling_error\"", "]", ":", "return", "LuigiStatusCode", ".", "FAILED_AND_SCHEDULING_FAILED", "return", "LuigiStatusCode", ".", "FAILED", "elif", "set_tasks", "[", "\"scheduling_error\"", "]", ":", "return", "LuigiStatusCode", ".", "SCHEDULING_FAILED", "elif", "set_tasks", "[", "\"not_run\"", "]", ":", "return", "LuigiStatusCode", ".", "NOT_RUN", "elif", "set_tasks", "[", "\"still_pending_ext\"", "]", ":", "return", "LuigiStatusCode", ".", "MISSING_EXT", "else", ":", "return", "LuigiStatusCode", ".", "SUCCESS" ]
Given a grouped set of tasks, returns a LuigiStatusCode
[ "Given", "a", "grouped", "set", "of", "tasks", "returns", "a", "LuigiStatusCode" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L450-L468
train
spotify/luigi
luigi/task.py
task_id_str
def task_id_str(task_family, params): """ Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the family and params """ # task_id is a concatenation of task family, the first values of the first 3 parameters # sorted by parameter name and a md5hash of the family/parameters as a cananocalised json. param_str = json.dumps(params, separators=(',', ':'), sort_keys=True) param_hash = hashlib.md5(param_str.encode('utf-8')).hexdigest() param_summary = '_'.join(p[:TASK_ID_TRUNCATE_PARAMS] for p in (params[p] for p in sorted(params)[:TASK_ID_INCLUDE_PARAMS])) param_summary = TASK_ID_INVALID_CHAR_REGEX.sub('_', param_summary) return '{}_{}_{}'.format(task_family, param_summary, param_hash[:TASK_ID_TRUNCATE_HASH])
python
def task_id_str(task_family, params): """ Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the family and params """ # task_id is a concatenation of task family, the first values of the first 3 parameters # sorted by parameter name and a md5hash of the family/parameters as a cananocalised json. param_str = json.dumps(params, separators=(',', ':'), sort_keys=True) param_hash = hashlib.md5(param_str.encode('utf-8')).hexdigest() param_summary = '_'.join(p[:TASK_ID_TRUNCATE_PARAMS] for p in (params[p] for p in sorted(params)[:TASK_ID_INCLUDE_PARAMS])) param_summary = TASK_ID_INVALID_CHAR_REGEX.sub('_', param_summary) return '{}_{}_{}'.format(task_family, param_summary, param_hash[:TASK_ID_TRUNCATE_HASH])
[ "def", "task_id_str", "(", "task_family", ",", "params", ")", ":", "# task_id is a concatenation of task family, the first values of the first 3 parameters", "# sorted by parameter name and a md5hash of the family/parameters as a cananocalised json.", "param_str", "=", "json", ".", "dumps", "(", "params", ",", "separators", "=", "(", "','", ",", "':'", ")", ",", "sort_keys", "=", "True", ")", "param_hash", "=", "hashlib", ".", "md5", "(", "param_str", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "param_summary", "=", "'_'", ".", "join", "(", "p", "[", ":", "TASK_ID_TRUNCATE_PARAMS", "]", "for", "p", "in", "(", "params", "[", "p", "]", "for", "p", "in", "sorted", "(", "params", ")", "[", ":", "TASK_ID_INCLUDE_PARAMS", "]", ")", ")", "param_summary", "=", "TASK_ID_INVALID_CHAR_REGEX", ".", "sub", "(", "'_'", ",", "param_summary", ")", "return", "'{}_{}_{}'", ".", "format", "(", "task_family", ",", "param_summary", ",", "param_hash", "[", ":", "TASK_ID_TRUNCATE_HASH", "]", ")" ]
Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the family and params
[ "Returns", "a", "canonical", "string", "used", "to", "identify", "a", "particular", "task" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task.py#L120-L137
train
spotify/luigi
luigi/task.py
externalize
def externalize(taskclass_or_taskobject): """ Returns an externalized version of a Task. You may both pass an instantiated task object or a task class. Some examples: .. code-block:: python class RequiringTask(luigi.Task): def requires(self): task_object = self.clone(MyTask) return externalize(task_object) ... Here's mostly equivalent code, but ``externalize`` is applied to a task class instead. .. code-block:: python @luigi.util.requires(externalize(MyTask)) class RequiringTask(luigi.Task): pass ... Of course, it may also be used directly on classes and objects (for example for reexporting or other usage). .. code-block:: python MyTask = externalize(MyTask) my_task_2 = externalize(MyTask2(param='foo')) If you however want a task class to be external from the beginning, you're better off inheriting :py:class:`ExternalTask` rather than :py:class:`Task`. This function tries to be side-effect free by creating a copy of the class or the object passed in and then modify that object. In particular this code shouldn't do anything. .. code-block:: python externalize(MyTask) # BAD: This does nothing (as after luigi 2.4.0) """ # Seems like with python < 3.3 copy.copy can't copy classes # and objects with specified metaclass http://bugs.python.org/issue11480 compatible_copy = copy.copy if six.PY3 else copy.deepcopy copied_value = compatible_copy(taskclass_or_taskobject) if copied_value is taskclass_or_taskobject: # Assume it's a class clazz = taskclass_or_taskobject @_task_wraps(clazz) class _CopyOfClass(clazz): # How to copy a class: http://stackoverflow.com/a/9541120/621449 _visible_in_registry = False _CopyOfClass.run = None return _CopyOfClass else: # We assume it's an object copied_value.run = None return copied_value
python
def externalize(taskclass_or_taskobject): """ Returns an externalized version of a Task. You may both pass an instantiated task object or a task class. Some examples: .. code-block:: python class RequiringTask(luigi.Task): def requires(self): task_object = self.clone(MyTask) return externalize(task_object) ... Here's mostly equivalent code, but ``externalize`` is applied to a task class instead. .. code-block:: python @luigi.util.requires(externalize(MyTask)) class RequiringTask(luigi.Task): pass ... Of course, it may also be used directly on classes and objects (for example for reexporting or other usage). .. code-block:: python MyTask = externalize(MyTask) my_task_2 = externalize(MyTask2(param='foo')) If you however want a task class to be external from the beginning, you're better off inheriting :py:class:`ExternalTask` rather than :py:class:`Task`. This function tries to be side-effect free by creating a copy of the class or the object passed in and then modify that object. In particular this code shouldn't do anything. .. code-block:: python externalize(MyTask) # BAD: This does nothing (as after luigi 2.4.0) """ # Seems like with python < 3.3 copy.copy can't copy classes # and objects with specified metaclass http://bugs.python.org/issue11480 compatible_copy = copy.copy if six.PY3 else copy.deepcopy copied_value = compatible_copy(taskclass_or_taskobject) if copied_value is taskclass_or_taskobject: # Assume it's a class clazz = taskclass_or_taskobject @_task_wraps(clazz) class _CopyOfClass(clazz): # How to copy a class: http://stackoverflow.com/a/9541120/621449 _visible_in_registry = False _CopyOfClass.run = None return _CopyOfClass else: # We assume it's an object copied_value.run = None return copied_value
[ "def", "externalize", "(", "taskclass_or_taskobject", ")", ":", "# Seems like with python < 3.3 copy.copy can't copy classes", "# and objects with specified metaclass http://bugs.python.org/issue11480", "compatible_copy", "=", "copy", ".", "copy", "if", "six", ".", "PY3", "else", "copy", ".", "deepcopy", "copied_value", "=", "compatible_copy", "(", "taskclass_or_taskobject", ")", "if", "copied_value", "is", "taskclass_or_taskobject", ":", "# Assume it's a class", "clazz", "=", "taskclass_or_taskobject", "@", "_task_wraps", "(", "clazz", ")", "class", "_CopyOfClass", "(", "clazz", ")", ":", "# How to copy a class: http://stackoverflow.com/a/9541120/621449", "_visible_in_registry", "=", "False", "_CopyOfClass", ".", "run", "=", "None", "return", "_CopyOfClass", "else", ":", "# We assume it's an object", "copied_value", ".", "run", "=", "None", "return", "copied_value" ]
Returns an externalized version of a Task. You may both pass an instantiated task object or a task class. Some examples: .. code-block:: python class RequiringTask(luigi.Task): def requires(self): task_object = self.clone(MyTask) return externalize(task_object) ... Here's mostly equivalent code, but ``externalize`` is applied to a task class instead. .. code-block:: python @luigi.util.requires(externalize(MyTask)) class RequiringTask(luigi.Task): pass ... Of course, it may also be used directly on classes and objects (for example for reexporting or other usage). .. code-block:: python MyTask = externalize(MyTask) my_task_2 = externalize(MyTask2(param='foo')) If you however want a task class to be external from the beginning, you're better off inheriting :py:class:`ExternalTask` rather than :py:class:`Task`. This function tries to be side-effect free by creating a copy of the class or the object passed in and then modify that object. In particular this code shouldn't do anything. .. code-block:: python externalize(MyTask) # BAD: This does nothing (as after luigi 2.4.0)
[ "Returns", "an", "externalized", "version", "of", "a", "Task", ".", "You", "may", "both", "pass", "an", "instantiated", "task", "object", "or", "a", "task", "class", ".", "Some", "examples", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task.py#L757-L817
train
spotify/luigi
luigi/task.py
getpaths
def getpaths(struct): """ Maps all Tasks in a structured data object to their .output(). """ if isinstance(struct, Task): return struct.output() elif isinstance(struct, dict): return struct.__class__((k, getpaths(v)) for k, v in six.iteritems(struct)) elif isinstance(struct, (list, tuple)): return struct.__class__(getpaths(r) for r in struct) else: # Remaining case: assume struct is iterable... try: return [getpaths(r) for r in struct] except TypeError: raise Exception('Cannot map %s to Task/dict/list' % str(struct))
python
def getpaths(struct): """ Maps all Tasks in a structured data object to their .output(). """ if isinstance(struct, Task): return struct.output() elif isinstance(struct, dict): return struct.__class__((k, getpaths(v)) for k, v in six.iteritems(struct)) elif isinstance(struct, (list, tuple)): return struct.__class__(getpaths(r) for r in struct) else: # Remaining case: assume struct is iterable... try: return [getpaths(r) for r in struct] except TypeError: raise Exception('Cannot map %s to Task/dict/list' % str(struct))
[ "def", "getpaths", "(", "struct", ")", ":", "if", "isinstance", "(", "struct", ",", "Task", ")", ":", "return", "struct", ".", "output", "(", ")", "elif", "isinstance", "(", "struct", ",", "dict", ")", ":", "return", "struct", ".", "__class__", "(", "(", "k", ",", "getpaths", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "struct", ")", ")", "elif", "isinstance", "(", "struct", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "struct", ".", "__class__", "(", "getpaths", "(", "r", ")", "for", "r", "in", "struct", ")", "else", ":", "# Remaining case: assume struct is iterable...", "try", ":", "return", "[", "getpaths", "(", "r", ")", "for", "r", "in", "struct", "]", "except", "TypeError", ":", "raise", "Exception", "(", "'Cannot map %s to Task/dict/list'", "%", "str", "(", "struct", ")", ")" ]
Maps all Tasks in a structured data object to their .output().
[ "Maps", "all", "Tasks", "in", "a", "structured", "data", "object", "to", "their", ".", "output", "()", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task.py#L838-L853
train
spotify/luigi
luigi/task.py
flatten
def flatten(struct): """ Creates a flat list of all all items in structured output (dicts, lists, items): .. code-block:: python >>> sorted(flatten({'a': 'foo', 'b': 'bar'})) ['bar', 'foo'] >>> sorted(flatten(['foo', ['bar', 'troll']])) ['bar', 'foo', 'troll'] >>> flatten('foo') ['foo'] >>> flatten(42) [42] """ if struct is None: return [] flat = [] if isinstance(struct, dict): for _, result in six.iteritems(struct): flat += flatten(result) return flat if isinstance(struct, six.string_types): return [struct] try: # if iterable iterator = iter(struct) except TypeError: return [struct] for result in iterator: flat += flatten(result) return flat
python
def flatten(struct): """ Creates a flat list of all all items in structured output (dicts, lists, items): .. code-block:: python >>> sorted(flatten({'a': 'foo', 'b': 'bar'})) ['bar', 'foo'] >>> sorted(flatten(['foo', ['bar', 'troll']])) ['bar', 'foo', 'troll'] >>> flatten('foo') ['foo'] >>> flatten(42) [42] """ if struct is None: return [] flat = [] if isinstance(struct, dict): for _, result in six.iteritems(struct): flat += flatten(result) return flat if isinstance(struct, six.string_types): return [struct] try: # if iterable iterator = iter(struct) except TypeError: return [struct] for result in iterator: flat += flatten(result) return flat
[ "def", "flatten", "(", "struct", ")", ":", "if", "struct", "is", "None", ":", "return", "[", "]", "flat", "=", "[", "]", "if", "isinstance", "(", "struct", ",", "dict", ")", ":", "for", "_", ",", "result", "in", "six", ".", "iteritems", "(", "struct", ")", ":", "flat", "+=", "flatten", "(", "result", ")", "return", "flat", "if", "isinstance", "(", "struct", ",", "six", ".", "string_types", ")", ":", "return", "[", "struct", "]", "try", ":", "# if iterable", "iterator", "=", "iter", "(", "struct", ")", "except", "TypeError", ":", "return", "[", "struct", "]", "for", "result", "in", "iterator", ":", "flat", "+=", "flatten", "(", "result", ")", "return", "flat" ]
Creates a flat list of all all items in structured output (dicts, lists, items): .. code-block:: python >>> sorted(flatten({'a': 'foo', 'b': 'bar'})) ['bar', 'foo'] >>> sorted(flatten(['foo', ['bar', 'troll']])) ['bar', 'foo', 'troll'] >>> flatten('foo') ['foo'] >>> flatten(42) [42]
[ "Creates", "a", "flat", "list", "of", "all", "all", "items", "in", "structured", "output", "(", "dicts", "lists", "items", ")", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task.py#L856-L889
train
spotify/luigi
luigi/task.py
flatten_output
def flatten_output(task): """ Lists all output targets by recursively walking output-less (wrapper) tasks. FIXME order consistently. """ r = flatten(task.output()) if not r: for dep in flatten(task.requires()): r += flatten_output(dep) return r
python
def flatten_output(task): """ Lists all output targets by recursively walking output-less (wrapper) tasks. FIXME order consistently. """ r = flatten(task.output()) if not r: for dep in flatten(task.requires()): r += flatten_output(dep) return r
[ "def", "flatten_output", "(", "task", ")", ":", "r", "=", "flatten", "(", "task", ".", "output", "(", ")", ")", "if", "not", "r", ":", "for", "dep", "in", "flatten", "(", "task", ".", "requires", "(", ")", ")", ":", "r", "+=", "flatten_output", "(", "dep", ")", "return", "r" ]
Lists all output targets by recursively walking output-less (wrapper) tasks. FIXME order consistently.
[ "Lists", "all", "output", "targets", "by", "recursively", "walking", "output", "-", "less", "(", "wrapper", ")", "tasks", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task.py#L892-L902
train