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/contrib/gcs.py | _wait_for_consistency | def _wait_for_consistency(checker):
"""Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
"""
for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS):
if checker():
return
time.sleep(EVENTUAL_CONSISTENCY_SLEEP_INTERVAL)
logger.warning('Exceeded wait for eventual GCS consistency - this may be a'
'bug in the library or something is terribly wrong.') | python | def _wait_for_consistency(checker):
"""Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
"""
for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS):
if checker():
return
time.sleep(EVENTUAL_CONSISTENCY_SLEEP_INTERVAL)
logger.warning('Exceeded wait for eventual GCS consistency - this may be a'
'bug in the library or something is terribly wrong.') | [
"def",
"_wait_for_consistency",
"(",
"checker",
")",
":",
"for",
"_",
"in",
"xrange",
"(",
"EVENTUAL_CONSISTENCY_MAX_SLEEPS",
")",
":",
"if",
"checker",
"(",
")",
":",
"return",
"time",
".",
"sleep",
"(",
"EVENTUAL_CONSISTENCY_SLEEP_INTERVAL",
")",
"logger",
".",
"warning",
"(",
"'Exceeded wait for eventual GCS consistency - this may be a'",
"'bug in the library or something is terribly wrong.'",
")"
] | Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit. | [
"Eventual",
"consistency",
":",
"wait",
"until",
"GCS",
"reports",
"something",
"is",
"true",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L68-L81 | train |
spotify/luigi | luigi/contrib/gcs.py | GCSClient.move | def move(self, source_path, destination_path):
"""
Rename/move an object from one GCS location to another.
"""
self.copy(source_path, destination_path)
self.remove(source_path) | python | def move(self, source_path, destination_path):
"""
Rename/move an object from one GCS location to another.
"""
self.copy(source_path, destination_path)
self.remove(source_path) | [
"def",
"move",
"(",
"self",
",",
"source_path",
",",
"destination_path",
")",
":",
"self",
".",
"copy",
"(",
"source_path",
",",
"destination_path",
")",
"self",
".",
"remove",
"(",
"source_path",
")"
] | Rename/move an object from one GCS location to another. | [
"Rename",
"/",
"move",
"an",
"object",
"from",
"one",
"GCS",
"location",
"to",
"another",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L344-L349 | train |
spotify/luigi | luigi/contrib/gcs.py | GCSClient.listdir | def listdir(self, path):
"""
Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path.
"""
bucket, obj = self._path_to_bucket_and_key(path)
obj_prefix = self._add_path_delimiter(obj)
if self._is_root(obj_prefix):
obj_prefix = ''
obj_prefix_len = len(obj_prefix)
for it in self._list_iter(bucket, obj_prefix):
yield self._add_path_delimiter(path) + it['name'][obj_prefix_len:] | python | def listdir(self, path):
"""
Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path.
"""
bucket, obj = self._path_to_bucket_and_key(path)
obj_prefix = self._add_path_delimiter(obj)
if self._is_root(obj_prefix):
obj_prefix = ''
obj_prefix_len = len(obj_prefix)
for it in self._list_iter(bucket, obj_prefix):
yield self._add_path_delimiter(path) + it['name'][obj_prefix_len:] | [
"def",
"listdir",
"(",
"self",
",",
"path",
")",
":",
"bucket",
",",
"obj",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"obj_prefix",
"=",
"self",
".",
"_add_path_delimiter",
"(",
"obj",
")",
"if",
"self",
".",
"_is_root",
"(",
"obj_prefix",
")",
":",
"obj_prefix",
"=",
"''",
"obj_prefix_len",
"=",
"len",
"(",
"obj_prefix",
")",
"for",
"it",
"in",
"self",
".",
"_list_iter",
"(",
"bucket",
",",
"obj_prefix",
")",
":",
"yield",
"self",
".",
"_add_path_delimiter",
"(",
"path",
")",
"+",
"it",
"[",
"'name'",
"]",
"[",
"obj_prefix_len",
":",
"]"
] | Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path. | [
"Get",
"an",
"iterable",
"with",
"GCS",
"folder",
"contents",
".",
"Iterable",
"contains",
"paths",
"relative",
"to",
"queried",
"path",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L351-L364 | train |
spotify/luigi | luigi/contrib/gcs.py | GCSClient.list_wildcard | def list_wildcard(self, wildcard_path):
"""Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iterator.py...)
"""
path, wildcard_obj = wildcard_path.rsplit('/', 1)
assert '*' not in path, "The '*' wildcard character is only supported after the last '/'"
wildcard_parts = wildcard_obj.split('*')
assert len(wildcard_parts) == 2, "Only one '*' wildcard is supported"
for it in self.listdir(path):
if it.startswith(path + '/' + wildcard_parts[0]) and it.endswith(wildcard_parts[1]) and \
len(it) >= len(path + '/' + wildcard_parts[0]) + len(wildcard_parts[1]):
yield it | python | def list_wildcard(self, wildcard_path):
"""Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iterator.py...)
"""
path, wildcard_obj = wildcard_path.rsplit('/', 1)
assert '*' not in path, "The '*' wildcard character is only supported after the last '/'"
wildcard_parts = wildcard_obj.split('*')
assert len(wildcard_parts) == 2, "Only one '*' wildcard is supported"
for it in self.listdir(path):
if it.startswith(path + '/' + wildcard_parts[0]) and it.endswith(wildcard_parts[1]) and \
len(it) >= len(path + '/' + wildcard_parts[0]) + len(wildcard_parts[1]):
yield it | [
"def",
"list_wildcard",
"(",
"self",
",",
"wildcard_path",
")",
":",
"path",
",",
"wildcard_obj",
"=",
"wildcard_path",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"assert",
"'*'",
"not",
"in",
"path",
",",
"\"The '*' wildcard character is only supported after the last '/'\"",
"wildcard_parts",
"=",
"wildcard_obj",
".",
"split",
"(",
"'*'",
")",
"assert",
"len",
"(",
"wildcard_parts",
")",
"==",
"2",
",",
"\"Only one '*' wildcard is supported\"",
"for",
"it",
"in",
"self",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"it",
".",
"startswith",
"(",
"path",
"+",
"'/'",
"+",
"wildcard_parts",
"[",
"0",
"]",
")",
"and",
"it",
".",
"endswith",
"(",
"wildcard_parts",
"[",
"1",
"]",
")",
"and",
"len",
"(",
"it",
")",
">=",
"len",
"(",
"path",
"+",
"'/'",
"+",
"wildcard_parts",
"[",
"0",
"]",
")",
"+",
"len",
"(",
"wildcard_parts",
"[",
"1",
"]",
")",
":",
"yield",
"it"
] | Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iterator.py...) | [
"Yields",
"full",
"object",
"URIs",
"matching",
"the",
"given",
"wildcard",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L366-L382 | train |
spotify/luigi | luigi/contrib/gcs.py | GCSClient.download | def download(self, path, chunksize=None, chunk_callback=lambda _: False):
"""Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True.
"""
chunksize = chunksize or self.chunksize
bucket, obj = self._path_to_bucket_and_key(path)
with tempfile.NamedTemporaryFile(delete=False) as fp:
# We can't return the tempfile reference because of a bug in python: http://bugs.python.org/issue18879
return_fp = _DeleteOnCloseFile(fp.name, 'r')
# Special case empty files because chunk-based downloading doesn't work.
result = self.client.objects().get(bucket=bucket, object=obj).execute()
if int(result['size']) == 0:
return return_fp
request = self.client.objects().get_media(bucket=bucket, object=obj)
downloader = http.MediaIoBaseDownload(fp, request, chunksize=chunksize)
attempts = 0
done = False
while not done:
error = None
try:
_, done = downloader.next_chunk()
if chunk_callback(fp):
done = True
except errors.HttpError as err:
error = err
if err.resp.status < 500:
raise
logger.warning('Error downloading file, retrying', exc_info=True)
except RETRYABLE_ERRORS as err:
logger.warning('Error downloading file, retrying', exc_info=True)
error = err
if error:
attempts += 1
if attempts >= NUM_RETRIES:
raise error
else:
attempts = 0
return return_fp | python | def download(self, path, chunksize=None, chunk_callback=lambda _: False):
"""Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True.
"""
chunksize = chunksize or self.chunksize
bucket, obj = self._path_to_bucket_and_key(path)
with tempfile.NamedTemporaryFile(delete=False) as fp:
# We can't return the tempfile reference because of a bug in python: http://bugs.python.org/issue18879
return_fp = _DeleteOnCloseFile(fp.name, 'r')
# Special case empty files because chunk-based downloading doesn't work.
result = self.client.objects().get(bucket=bucket, object=obj).execute()
if int(result['size']) == 0:
return return_fp
request = self.client.objects().get_media(bucket=bucket, object=obj)
downloader = http.MediaIoBaseDownload(fp, request, chunksize=chunksize)
attempts = 0
done = False
while not done:
error = None
try:
_, done = downloader.next_chunk()
if chunk_callback(fp):
done = True
except errors.HttpError as err:
error = err
if err.resp.status < 500:
raise
logger.warning('Error downloading file, retrying', exc_info=True)
except RETRYABLE_ERRORS as err:
logger.warning('Error downloading file, retrying', exc_info=True)
error = err
if error:
attempts += 1
if attempts >= NUM_RETRIES:
raise error
else:
attempts = 0
return return_fp | [
"def",
"download",
"(",
"self",
",",
"path",
",",
"chunksize",
"=",
"None",
",",
"chunk_callback",
"=",
"lambda",
"_",
":",
"False",
")",
":",
"chunksize",
"=",
"chunksize",
"or",
"self",
".",
"chunksize",
"bucket",
",",
"obj",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"as",
"fp",
":",
"# We can't return the tempfile reference because of a bug in python: http://bugs.python.org/issue18879",
"return_fp",
"=",
"_DeleteOnCloseFile",
"(",
"fp",
".",
"name",
",",
"'r'",
")",
"# Special case empty files because chunk-based downloading doesn't work.",
"result",
"=",
"self",
".",
"client",
".",
"objects",
"(",
")",
".",
"get",
"(",
"bucket",
"=",
"bucket",
",",
"object",
"=",
"obj",
")",
".",
"execute",
"(",
")",
"if",
"int",
"(",
"result",
"[",
"'size'",
"]",
")",
"==",
"0",
":",
"return",
"return_fp",
"request",
"=",
"self",
".",
"client",
".",
"objects",
"(",
")",
".",
"get_media",
"(",
"bucket",
"=",
"bucket",
",",
"object",
"=",
"obj",
")",
"downloader",
"=",
"http",
".",
"MediaIoBaseDownload",
"(",
"fp",
",",
"request",
",",
"chunksize",
"=",
"chunksize",
")",
"attempts",
"=",
"0",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"error",
"=",
"None",
"try",
":",
"_",
",",
"done",
"=",
"downloader",
".",
"next_chunk",
"(",
")",
"if",
"chunk_callback",
"(",
"fp",
")",
":",
"done",
"=",
"True",
"except",
"errors",
".",
"HttpError",
"as",
"err",
":",
"error",
"=",
"err",
"if",
"err",
".",
"resp",
".",
"status",
"<",
"500",
":",
"raise",
"logger",
".",
"warning",
"(",
"'Error downloading file, retrying'",
",",
"exc_info",
"=",
"True",
")",
"except",
"RETRYABLE_ERRORS",
"as",
"err",
":",
"logger",
".",
"warning",
"(",
"'Error downloading file, retrying'",
",",
"exc_info",
"=",
"True",
")",
"error",
"=",
"err",
"if",
"error",
":",
"attempts",
"+=",
"1",
"if",
"attempts",
">=",
"NUM_RETRIES",
":",
"raise",
"error",
"else",
":",
"attempts",
"=",
"0",
"return",
"return_fp"
] | Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True. | [
"Downloads",
"the",
"object",
"contents",
"to",
"local",
"file",
"system",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L384-L428 | train |
spotify/luigi | luigi/format.py | InputPipeProcessWrapper.create_subprocess | def create_subprocess(self, command):
"""
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html
"""
def subprocess_setup():
# Python installs a SIGPIPE handler by default. This is usually not what
# non-Python subprocesses expect.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
return subprocess.Popen(command,
stdin=self._input_pipe,
stdout=subprocess.PIPE,
preexec_fn=subprocess_setup,
close_fds=True) | python | def create_subprocess(self, command):
"""
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html
"""
def subprocess_setup():
# Python installs a SIGPIPE handler by default. This is usually not what
# non-Python subprocesses expect.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
return subprocess.Popen(command,
stdin=self._input_pipe,
stdout=subprocess.PIPE,
preexec_fn=subprocess_setup,
close_fds=True) | [
"def",
"create_subprocess",
"(",
"self",
",",
"command",
")",
":",
"def",
"subprocess_setup",
"(",
")",
":",
"# Python installs a SIGPIPE handler by default. This is usually not what",
"# non-Python subprocesses expect.",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
"signal",
".",
"SIG_DFL",
")",
"return",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdin",
"=",
"self",
".",
"_input_pipe",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"preexec_fn",
"=",
"subprocess_setup",
",",
"close_fds",
"=",
"True",
")"
] | http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html | [
"http",
":",
"//",
"www",
".",
"chiark",
".",
"greenend",
".",
"org",
".",
"uk",
"/",
"ucgi",
"/",
"~cjwatson",
"/",
"blosxom",
"/",
"2009",
"-",
"07",
"-",
"02",
"-",
"python",
"-",
"sigpipe",
".",
"html"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/format.py#L93-L107 | train |
spotify/luigi | luigi/format.py | OutputPipeProcessWrapper._finish | def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True | python | def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True | [
"def",
"_finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
":",
"self",
".",
"_process",
".",
"stdin",
".",
"flush",
"(",
")",
"self",
".",
"_process",
".",
"stdin",
".",
"close",
"(",
")",
"self",
".",
"_process",
".",
"wait",
"(",
")",
"self",
".",
"closed",
"=",
"True"
] | Closes and waits for subprocess to exit. | [
"Closes",
"and",
"waits",
"for",
"subprocess",
"to",
"exit",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/format.py#L197-L205 | train |
spotify/luigi | luigi/worker.py | check_complete | def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((task, is_complete)) | python | def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((task, is_complete)) | [
"def",
"check_complete",
"(",
"task",
",",
"out_queue",
")",
":",
"logger",
".",
"debug",
"(",
"\"Checking if %s is complete\"",
",",
"task",
")",
"try",
":",
"is_complete",
"=",
"task",
".",
"complete",
"(",
")",
"except",
"Exception",
":",
"is_complete",
"=",
"TracebackWrapper",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"out_queue",
".",
"put",
"(",
"(",
"task",
",",
"is_complete",
")",
")"
] | Checks if task is complete, puts the result to out_queue. | [
"Checks",
"if",
"task",
"is",
"complete",
"puts",
"the",
"result",
"to",
"out_queue",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L395-L404 | train |
spotify/luigi | luigi/worker.py | Worker._add_task | def _add_task(self, *args, **kwargs):
"""
Call ``self._scheduler.add_task``, but store the values too so we can
implement :py:func:`luigi.execution_summary.summary`.
"""
task_id = kwargs['task_id']
status = kwargs['status']
runnable = kwargs['runnable']
task = self._scheduled_tasks.get(task_id)
if task:
self._add_task_history.append((task, status, runnable))
kwargs['owners'] = task._owner_list()
if task_id in self._batch_running_tasks:
for batch_task in self._batch_running_tasks.pop(task_id):
self._add_task_history.append((batch_task, status, True))
if task and kwargs.get('params'):
kwargs['param_visibilities'] = task._get_param_visibilities()
self._scheduler.add_task(*args, **kwargs)
logger.info('Informed scheduler that task %s has status %s', task_id, status) | python | def _add_task(self, *args, **kwargs):
"""
Call ``self._scheduler.add_task``, but store the values too so we can
implement :py:func:`luigi.execution_summary.summary`.
"""
task_id = kwargs['task_id']
status = kwargs['status']
runnable = kwargs['runnable']
task = self._scheduled_tasks.get(task_id)
if task:
self._add_task_history.append((task, status, runnable))
kwargs['owners'] = task._owner_list()
if task_id in self._batch_running_tasks:
for batch_task in self._batch_running_tasks.pop(task_id):
self._add_task_history.append((batch_task, status, True))
if task and kwargs.get('params'):
kwargs['param_visibilities'] = task._get_param_visibilities()
self._scheduler.add_task(*args, **kwargs)
logger.info('Informed scheduler that task %s has status %s', task_id, status) | [
"def",
"_add_task",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task_id",
"=",
"kwargs",
"[",
"'task_id'",
"]",
"status",
"=",
"kwargs",
"[",
"'status'",
"]",
"runnable",
"=",
"kwargs",
"[",
"'runnable'",
"]",
"task",
"=",
"self",
".",
"_scheduled_tasks",
".",
"get",
"(",
"task_id",
")",
"if",
"task",
":",
"self",
".",
"_add_task_history",
".",
"append",
"(",
"(",
"task",
",",
"status",
",",
"runnable",
")",
")",
"kwargs",
"[",
"'owners'",
"]",
"=",
"task",
".",
"_owner_list",
"(",
")",
"if",
"task_id",
"in",
"self",
".",
"_batch_running_tasks",
":",
"for",
"batch_task",
"in",
"self",
".",
"_batch_running_tasks",
".",
"pop",
"(",
"task_id",
")",
":",
"self",
".",
"_add_task_history",
".",
"append",
"(",
"(",
"batch_task",
",",
"status",
",",
"True",
")",
")",
"if",
"task",
"and",
"kwargs",
".",
"get",
"(",
"'params'",
")",
":",
"kwargs",
"[",
"'param_visibilities'",
"]",
"=",
"task",
".",
"_get_param_visibilities",
"(",
")",
"self",
".",
"_scheduler",
".",
"add_task",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"info",
"(",
"'Informed scheduler that task %s has status %s'",
",",
"task_id",
",",
"status",
")"
] | Call ``self._scheduler.add_task``, but store the values too so we can
implement :py:func:`luigi.execution_summary.summary`. | [
"Call",
"self",
".",
"_scheduler",
".",
"add_task",
"but",
"store",
"the",
"values",
"too",
"so",
"we",
"can",
"implement",
":",
"py",
":",
"func",
":",
"luigi",
".",
"execution_summary",
".",
"summary",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L561-L583 | train |
spotify/luigi | luigi/worker.py | Worker.add | def add(self, task, multiprocess=False, processes=0):
"""
Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before.
"""
if self._first_task is None and hasattr(task, 'task_id'):
self._first_task = task.task_id
self.add_succeeded = True
if multiprocess:
queue = multiprocessing.Manager().Queue()
pool = multiprocessing.Pool(processes=processes if processes > 0 else None)
else:
queue = DequeQueue()
pool = SingleProcessPool()
self._validate_task(task)
pool.apply_async(check_complete, [task, queue])
# we track queue size ourselves because len(queue) won't work for multiprocessing
queue_size = 1
try:
seen = {task.task_id}
while queue_size:
current = queue.get()
queue_size -= 1
item, is_complete = current
for next in self._add(item, is_complete):
if next.task_id not in seen:
self._validate_task(next)
seen.add(next.task_id)
pool.apply_async(check_complete, [next, queue])
queue_size += 1
except (KeyboardInterrupt, TaskException):
raise
except Exception as ex:
self.add_succeeded = False
formatted_traceback = traceback.format_exc()
self._log_unexpected_error(task)
task.trigger_event(Event.BROKEN_TASK, task, ex)
self._email_unexpected_error(task, formatted_traceback)
raise
finally:
pool.close()
pool.join()
return self.add_succeeded | python | def add(self, task, multiprocess=False, processes=0):
"""
Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before.
"""
if self._first_task is None and hasattr(task, 'task_id'):
self._first_task = task.task_id
self.add_succeeded = True
if multiprocess:
queue = multiprocessing.Manager().Queue()
pool = multiprocessing.Pool(processes=processes if processes > 0 else None)
else:
queue = DequeQueue()
pool = SingleProcessPool()
self._validate_task(task)
pool.apply_async(check_complete, [task, queue])
# we track queue size ourselves because len(queue) won't work for multiprocessing
queue_size = 1
try:
seen = {task.task_id}
while queue_size:
current = queue.get()
queue_size -= 1
item, is_complete = current
for next in self._add(item, is_complete):
if next.task_id not in seen:
self._validate_task(next)
seen.add(next.task_id)
pool.apply_async(check_complete, [next, queue])
queue_size += 1
except (KeyboardInterrupt, TaskException):
raise
except Exception as ex:
self.add_succeeded = False
formatted_traceback = traceback.format_exc()
self._log_unexpected_error(task)
task.trigger_event(Event.BROKEN_TASK, task, ex)
self._email_unexpected_error(task, formatted_traceback)
raise
finally:
pool.close()
pool.join()
return self.add_succeeded | [
"def",
"add",
"(",
"self",
",",
"task",
",",
"multiprocess",
"=",
"False",
",",
"processes",
"=",
"0",
")",
":",
"if",
"self",
".",
"_first_task",
"is",
"None",
"and",
"hasattr",
"(",
"task",
",",
"'task_id'",
")",
":",
"self",
".",
"_first_task",
"=",
"task",
".",
"task_id",
"self",
".",
"add_succeeded",
"=",
"True",
"if",
"multiprocess",
":",
"queue",
"=",
"multiprocessing",
".",
"Manager",
"(",
")",
".",
"Queue",
"(",
")",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"processes",
"=",
"processes",
"if",
"processes",
">",
"0",
"else",
"None",
")",
"else",
":",
"queue",
"=",
"DequeQueue",
"(",
")",
"pool",
"=",
"SingleProcessPool",
"(",
")",
"self",
".",
"_validate_task",
"(",
"task",
")",
"pool",
".",
"apply_async",
"(",
"check_complete",
",",
"[",
"task",
",",
"queue",
"]",
")",
"# we track queue size ourselves because len(queue) won't work for multiprocessing",
"queue_size",
"=",
"1",
"try",
":",
"seen",
"=",
"{",
"task",
".",
"task_id",
"}",
"while",
"queue_size",
":",
"current",
"=",
"queue",
".",
"get",
"(",
")",
"queue_size",
"-=",
"1",
"item",
",",
"is_complete",
"=",
"current",
"for",
"next",
"in",
"self",
".",
"_add",
"(",
"item",
",",
"is_complete",
")",
":",
"if",
"next",
".",
"task_id",
"not",
"in",
"seen",
":",
"self",
".",
"_validate_task",
"(",
"next",
")",
"seen",
".",
"add",
"(",
"next",
".",
"task_id",
")",
"pool",
".",
"apply_async",
"(",
"check_complete",
",",
"[",
"next",
",",
"queue",
"]",
")",
"queue_size",
"+=",
"1",
"except",
"(",
"KeyboardInterrupt",
",",
"TaskException",
")",
":",
"raise",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"add_succeeded",
"=",
"False",
"formatted_traceback",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"self",
".",
"_log_unexpected_error",
"(",
"task",
")",
"task",
".",
"trigger_event",
"(",
"Event",
".",
"BROKEN_TASK",
",",
"task",
",",
"ex",
")",
"self",
".",
"_email_unexpected_error",
"(",
"task",
",",
"formatted_traceback",
")",
"raise",
"finally",
":",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")",
"return",
"self",
".",
"add_succeeded"
] | Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before. | [
"Add",
"a",
"Task",
"for",
"the",
"worker",
"to",
"check",
"and",
"possibly",
"schedule",
"and",
"run",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L725-L769 | train |
spotify/luigi | luigi/worker.py | Worker._purge_children | def _purge_children(self):
"""
Find dead children and put a response on the result queue.
:return:
"""
for task_id, p in six.iteritems(self._running_tasks):
if not p.is_alive() and p.exitcode:
error_msg = 'Task {} died unexpectedly with exit code {}'.format(task_id, p.exitcode)
p.task.trigger_event(Event.PROCESS_FAILURE, p.task, error_msg)
elif p.timeout_time is not None and time.time() > float(p.timeout_time) and p.is_alive():
p.terminate()
error_msg = 'Task {} timed out after {} seconds and was terminated.'.format(task_id, p.worker_timeout)
p.task.trigger_event(Event.TIMEOUT, p.task, error_msg)
else:
continue
logger.info(error_msg)
self._task_result_queue.put((task_id, FAILED, error_msg, [], [])) | python | def _purge_children(self):
"""
Find dead children and put a response on the result queue.
:return:
"""
for task_id, p in six.iteritems(self._running_tasks):
if not p.is_alive() and p.exitcode:
error_msg = 'Task {} died unexpectedly with exit code {}'.format(task_id, p.exitcode)
p.task.trigger_event(Event.PROCESS_FAILURE, p.task, error_msg)
elif p.timeout_time is not None and time.time() > float(p.timeout_time) and p.is_alive():
p.terminate()
error_msg = 'Task {} timed out after {} seconds and was terminated.'.format(task_id, p.worker_timeout)
p.task.trigger_event(Event.TIMEOUT, p.task, error_msg)
else:
continue
logger.info(error_msg)
self._task_result_queue.put((task_id, FAILED, error_msg, [], [])) | [
"def",
"_purge_children",
"(",
"self",
")",
":",
"for",
"task_id",
",",
"p",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_running_tasks",
")",
":",
"if",
"not",
"p",
".",
"is_alive",
"(",
")",
"and",
"p",
".",
"exitcode",
":",
"error_msg",
"=",
"'Task {} died unexpectedly with exit code {}'",
".",
"format",
"(",
"task_id",
",",
"p",
".",
"exitcode",
")",
"p",
".",
"task",
".",
"trigger_event",
"(",
"Event",
".",
"PROCESS_FAILURE",
",",
"p",
".",
"task",
",",
"error_msg",
")",
"elif",
"p",
".",
"timeout_time",
"is",
"not",
"None",
"and",
"time",
".",
"time",
"(",
")",
">",
"float",
"(",
"p",
".",
"timeout_time",
")",
"and",
"p",
".",
"is_alive",
"(",
")",
":",
"p",
".",
"terminate",
"(",
")",
"error_msg",
"=",
"'Task {} timed out after {} seconds and was terminated.'",
".",
"format",
"(",
"task_id",
",",
"p",
".",
"worker_timeout",
")",
"p",
".",
"task",
".",
"trigger_event",
"(",
"Event",
".",
"TIMEOUT",
",",
"p",
".",
"task",
",",
"error_msg",
")",
"else",
":",
"continue",
"logger",
".",
"info",
"(",
"error_msg",
")",
"self",
".",
"_task_result_queue",
".",
"put",
"(",
"(",
"task_id",
",",
"FAILED",
",",
"error_msg",
",",
"[",
"]",
",",
"[",
"]",
")",
")"
] | Find dead children and put a response on the result queue.
:return: | [
"Find",
"dead",
"children",
"and",
"put",
"a",
"response",
"on",
"the",
"result",
"queue",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1021-L1039 | train |
spotify/luigi | luigi/worker.py | Worker._handle_next_task | def _handle_next_task(self):
"""
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies added,
3. child process dies: we need to catch this separately.
"""
self._idle_since = None
while True:
self._purge_children() # Deal with subprocess failures
try:
task_id, status, expl, missing, new_requirements = (
self._task_result_queue.get(
timeout=self._config.wait_interval))
except Queue.Empty:
return
task = self._scheduled_tasks[task_id]
if not task or task_id not in self._running_tasks:
continue
# Not a running task. Probably already removed.
# Maybe it yielded something?
# external task if run not implemented, retry-able if config option is enabled.
external_task_retryable = _is_external(task) and self._config.retry_external_tasks
if status == FAILED and not external_task_retryable:
self._email_task_failure(task, expl)
new_deps = []
if new_requirements:
new_req = [load_task(module, name, params)
for module, name, params in new_requirements]
for t in new_req:
self.add(t)
new_deps = [t.task_id for t in new_req]
self._add_task(worker=self._id,
task_id=task_id,
status=status,
expl=json.dumps(expl),
resources=task.process_resources(),
runnable=None,
params=task.to_str_params(),
family=task.task_family,
module=task.task_module,
new_deps=new_deps,
assistant=self._assistant,
retry_policy_dict=_get_retry_policy_dict(task))
self._running_tasks.pop(task_id)
# re-add task to reschedule missing dependencies
if missing:
reschedule = True
# keep out of infinite loops by not rescheduling too many times
for task_id in missing:
self.unfulfilled_counts[task_id] += 1
if (self.unfulfilled_counts[task_id] >
self._config.max_reschedules):
reschedule = False
if reschedule:
self.add(task)
self.run_succeeded &= (status == DONE) or (len(new_deps) > 0)
return | python | def _handle_next_task(self):
"""
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies added,
3. child process dies: we need to catch this separately.
"""
self._idle_since = None
while True:
self._purge_children() # Deal with subprocess failures
try:
task_id, status, expl, missing, new_requirements = (
self._task_result_queue.get(
timeout=self._config.wait_interval))
except Queue.Empty:
return
task = self._scheduled_tasks[task_id]
if not task or task_id not in self._running_tasks:
continue
# Not a running task. Probably already removed.
# Maybe it yielded something?
# external task if run not implemented, retry-able if config option is enabled.
external_task_retryable = _is_external(task) and self._config.retry_external_tasks
if status == FAILED and not external_task_retryable:
self._email_task_failure(task, expl)
new_deps = []
if new_requirements:
new_req = [load_task(module, name, params)
for module, name, params in new_requirements]
for t in new_req:
self.add(t)
new_deps = [t.task_id for t in new_req]
self._add_task(worker=self._id,
task_id=task_id,
status=status,
expl=json.dumps(expl),
resources=task.process_resources(),
runnable=None,
params=task.to_str_params(),
family=task.task_family,
module=task.task_module,
new_deps=new_deps,
assistant=self._assistant,
retry_policy_dict=_get_retry_policy_dict(task))
self._running_tasks.pop(task_id)
# re-add task to reschedule missing dependencies
if missing:
reschedule = True
# keep out of infinite loops by not rescheduling too many times
for task_id in missing:
self.unfulfilled_counts[task_id] += 1
if (self.unfulfilled_counts[task_id] >
self._config.max_reschedules):
reschedule = False
if reschedule:
self.add(task)
self.run_succeeded &= (status == DONE) or (len(new_deps) > 0)
return | [
"def",
"_handle_next_task",
"(",
"self",
")",
":",
"self",
".",
"_idle_since",
"=",
"None",
"while",
"True",
":",
"self",
".",
"_purge_children",
"(",
")",
"# Deal with subprocess failures",
"try",
":",
"task_id",
",",
"status",
",",
"expl",
",",
"missing",
",",
"new_requirements",
"=",
"(",
"self",
".",
"_task_result_queue",
".",
"get",
"(",
"timeout",
"=",
"self",
".",
"_config",
".",
"wait_interval",
")",
")",
"except",
"Queue",
".",
"Empty",
":",
"return",
"task",
"=",
"self",
".",
"_scheduled_tasks",
"[",
"task_id",
"]",
"if",
"not",
"task",
"or",
"task_id",
"not",
"in",
"self",
".",
"_running_tasks",
":",
"continue",
"# Not a running task. Probably already removed.",
"# Maybe it yielded something?",
"# external task if run not implemented, retry-able if config option is enabled.",
"external_task_retryable",
"=",
"_is_external",
"(",
"task",
")",
"and",
"self",
".",
"_config",
".",
"retry_external_tasks",
"if",
"status",
"==",
"FAILED",
"and",
"not",
"external_task_retryable",
":",
"self",
".",
"_email_task_failure",
"(",
"task",
",",
"expl",
")",
"new_deps",
"=",
"[",
"]",
"if",
"new_requirements",
":",
"new_req",
"=",
"[",
"load_task",
"(",
"module",
",",
"name",
",",
"params",
")",
"for",
"module",
",",
"name",
",",
"params",
"in",
"new_requirements",
"]",
"for",
"t",
"in",
"new_req",
":",
"self",
".",
"add",
"(",
"t",
")",
"new_deps",
"=",
"[",
"t",
".",
"task_id",
"for",
"t",
"in",
"new_req",
"]",
"self",
".",
"_add_task",
"(",
"worker",
"=",
"self",
".",
"_id",
",",
"task_id",
"=",
"task_id",
",",
"status",
"=",
"status",
",",
"expl",
"=",
"json",
".",
"dumps",
"(",
"expl",
")",
",",
"resources",
"=",
"task",
".",
"process_resources",
"(",
")",
",",
"runnable",
"=",
"None",
",",
"params",
"=",
"task",
".",
"to_str_params",
"(",
")",
",",
"family",
"=",
"task",
".",
"task_family",
",",
"module",
"=",
"task",
".",
"task_module",
",",
"new_deps",
"=",
"new_deps",
",",
"assistant",
"=",
"self",
".",
"_assistant",
",",
"retry_policy_dict",
"=",
"_get_retry_policy_dict",
"(",
"task",
")",
")",
"self",
".",
"_running_tasks",
".",
"pop",
"(",
"task_id",
")",
"# re-add task to reschedule missing dependencies",
"if",
"missing",
":",
"reschedule",
"=",
"True",
"# keep out of infinite loops by not rescheduling too many times",
"for",
"task_id",
"in",
"missing",
":",
"self",
".",
"unfulfilled_counts",
"[",
"task_id",
"]",
"+=",
"1",
"if",
"(",
"self",
".",
"unfulfilled_counts",
"[",
"task_id",
"]",
">",
"self",
".",
"_config",
".",
"max_reschedules",
")",
":",
"reschedule",
"=",
"False",
"if",
"reschedule",
":",
"self",
".",
"add",
"(",
"task",
")",
"self",
".",
"run_succeeded",
"&=",
"(",
"status",
"==",
"DONE",
")",
"or",
"(",
"len",
"(",
"new_deps",
")",
">",
"0",
")",
"return"
] | We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies added,
3. child process dies: we need to catch this separately. | [
"We",
"have",
"to",
"catch",
"three",
"ways",
"a",
"task",
"can",
"be",
"done",
":"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1041-L1109 | train |
spotify/luigi | luigi/worker.py | Worker._keep_alive | def _keep_alive(self, get_work_response):
"""
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will also
require that one of the tasks is unique to this worker.
"""
if not self._config.keep_alive:
return False
elif self._assistant:
return True
elif self._config.count_last_scheduled:
return get_work_response.n_pending_last_scheduled > 0
elif self._config.count_uniques:
return get_work_response.n_unique_pending > 0
elif get_work_response.n_pending_tasks == 0:
return False
elif not self._config.max_keep_alive_idle_duration:
return True
elif not self._idle_since:
return True
else:
time_to_shutdown = self._idle_since + self._config.max_keep_alive_idle_duration - datetime.datetime.now()
logger.debug("[%s] %s until shutdown", self._id, time_to_shutdown)
return time_to_shutdown > datetime.timedelta(0) | python | def _keep_alive(self, get_work_response):
"""
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will also
require that one of the tasks is unique to this worker.
"""
if not self._config.keep_alive:
return False
elif self._assistant:
return True
elif self._config.count_last_scheduled:
return get_work_response.n_pending_last_scheduled > 0
elif self._config.count_uniques:
return get_work_response.n_unique_pending > 0
elif get_work_response.n_pending_tasks == 0:
return False
elif not self._config.max_keep_alive_idle_duration:
return True
elif not self._idle_since:
return True
else:
time_to_shutdown = self._idle_since + self._config.max_keep_alive_idle_duration - datetime.datetime.now()
logger.debug("[%s] %s until shutdown", self._id, time_to_shutdown)
return time_to_shutdown > datetime.timedelta(0) | [
"def",
"_keep_alive",
"(",
"self",
",",
"get_work_response",
")",
":",
"if",
"not",
"self",
".",
"_config",
".",
"keep_alive",
":",
"return",
"False",
"elif",
"self",
".",
"_assistant",
":",
"return",
"True",
"elif",
"self",
".",
"_config",
".",
"count_last_scheduled",
":",
"return",
"get_work_response",
".",
"n_pending_last_scheduled",
">",
"0",
"elif",
"self",
".",
"_config",
".",
"count_uniques",
":",
"return",
"get_work_response",
".",
"n_unique_pending",
">",
"0",
"elif",
"get_work_response",
".",
"n_pending_tasks",
"==",
"0",
":",
"return",
"False",
"elif",
"not",
"self",
".",
"_config",
".",
"max_keep_alive_idle_duration",
":",
"return",
"True",
"elif",
"not",
"self",
".",
"_idle_since",
":",
"return",
"True",
"else",
":",
"time_to_shutdown",
"=",
"self",
".",
"_idle_since",
"+",
"self",
".",
"_config",
".",
"max_keep_alive_idle_duration",
"-",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"logger",
".",
"debug",
"(",
"\"[%s] %s until shutdown\"",
",",
"self",
".",
"_id",
",",
"time_to_shutdown",
")",
"return",
"time_to_shutdown",
">",
"datetime",
".",
"timedelta",
"(",
"0",
")"
] | Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will also
require that one of the tasks is unique to this worker. | [
"Returns",
"true",
"if",
"a",
"worker",
"should",
"stay",
"alive",
"given",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1120-L1148 | train |
spotify/luigi | luigi/worker.py | Worker.run | def run(self):
"""
Returns True if all scheduled tasks were executed successfully.
"""
logger.info('Running Worker with %d processes', self.worker_processes)
sleeper = self._sleeper()
self.run_succeeded = True
self._add_worker()
while True:
while len(self._running_tasks) >= self.worker_processes > 0:
logger.debug('%d running tasks, waiting for next task to finish', len(self._running_tasks))
self._handle_next_task()
get_work_response = self._get_work()
if get_work_response.worker_state == WORKER_STATE_DISABLED:
self._start_phasing_out()
if get_work_response.task_id is None:
if not self._stop_requesting_work:
self._log_remote_tasks(get_work_response)
if len(self._running_tasks) == 0:
self._idle_since = self._idle_since or datetime.datetime.now()
if self._keep_alive(get_work_response):
six.next(sleeper)
continue
else:
break
else:
self._handle_next_task()
continue
# task_id is not None:
logger.debug("Pending tasks: %s", get_work_response.n_pending_tasks)
self._run_task(get_work_response.task_id)
while len(self._running_tasks):
logger.debug('Shut down Worker, %d more tasks to go', len(self._running_tasks))
self._handle_next_task()
return self.run_succeeded | python | def run(self):
"""
Returns True if all scheduled tasks were executed successfully.
"""
logger.info('Running Worker with %d processes', self.worker_processes)
sleeper = self._sleeper()
self.run_succeeded = True
self._add_worker()
while True:
while len(self._running_tasks) >= self.worker_processes > 0:
logger.debug('%d running tasks, waiting for next task to finish', len(self._running_tasks))
self._handle_next_task()
get_work_response = self._get_work()
if get_work_response.worker_state == WORKER_STATE_DISABLED:
self._start_phasing_out()
if get_work_response.task_id is None:
if not self._stop_requesting_work:
self._log_remote_tasks(get_work_response)
if len(self._running_tasks) == 0:
self._idle_since = self._idle_since or datetime.datetime.now()
if self._keep_alive(get_work_response):
six.next(sleeper)
continue
else:
break
else:
self._handle_next_task()
continue
# task_id is not None:
logger.debug("Pending tasks: %s", get_work_response.n_pending_tasks)
self._run_task(get_work_response.task_id)
while len(self._running_tasks):
logger.debug('Shut down Worker, %d more tasks to go', len(self._running_tasks))
self._handle_next_task()
return self.run_succeeded | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Running Worker with %d processes'",
",",
"self",
".",
"worker_processes",
")",
"sleeper",
"=",
"self",
".",
"_sleeper",
"(",
")",
"self",
".",
"run_succeeded",
"=",
"True",
"self",
".",
"_add_worker",
"(",
")",
"while",
"True",
":",
"while",
"len",
"(",
"self",
".",
"_running_tasks",
")",
">=",
"self",
".",
"worker_processes",
">",
"0",
":",
"logger",
".",
"debug",
"(",
"'%d running tasks, waiting for next task to finish'",
",",
"len",
"(",
"self",
".",
"_running_tasks",
")",
")",
"self",
".",
"_handle_next_task",
"(",
")",
"get_work_response",
"=",
"self",
".",
"_get_work",
"(",
")",
"if",
"get_work_response",
".",
"worker_state",
"==",
"WORKER_STATE_DISABLED",
":",
"self",
".",
"_start_phasing_out",
"(",
")",
"if",
"get_work_response",
".",
"task_id",
"is",
"None",
":",
"if",
"not",
"self",
".",
"_stop_requesting_work",
":",
"self",
".",
"_log_remote_tasks",
"(",
"get_work_response",
")",
"if",
"len",
"(",
"self",
".",
"_running_tasks",
")",
"==",
"0",
":",
"self",
".",
"_idle_since",
"=",
"self",
".",
"_idle_since",
"or",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"self",
".",
"_keep_alive",
"(",
"get_work_response",
")",
":",
"six",
".",
"next",
"(",
"sleeper",
")",
"continue",
"else",
":",
"break",
"else",
":",
"self",
".",
"_handle_next_task",
"(",
")",
"continue",
"# task_id is not None:",
"logger",
".",
"debug",
"(",
"\"Pending tasks: %s\"",
",",
"get_work_response",
".",
"n_pending_tasks",
")",
"self",
".",
"_run_task",
"(",
"get_work_response",
".",
"task_id",
")",
"while",
"len",
"(",
"self",
".",
"_running_tasks",
")",
":",
"logger",
".",
"debug",
"(",
"'Shut down Worker, %d more tasks to go'",
",",
"len",
"(",
"self",
".",
"_running_tasks",
")",
")",
"self",
".",
"_handle_next_task",
"(",
")",
"return",
"self",
".",
"run_succeeded"
] | Returns True if all scheduled tasks were executed successfully. | [
"Returns",
"True",
"if",
"all",
"scheduled",
"tasks",
"were",
"executed",
"successfully",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1165-L1208 | train |
spotify/luigi | luigi/db_task_history.py | _upgrade_schema | def _upgrade_schema(engine):
"""
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database.
"""
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
# Upgrade 1. Add task_id column and index to tasks
if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]:
logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id')
conn.execute('ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)')
conn.execute('CREATE INDEX ix_task_id ON tasks (task_id)')
# Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard
if 'mysql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY COLUMN value TEXT')
elif 'oracle' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY value TEXT')
elif 'mssql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TEXT')
elif 'postgresql' in engine.dialect.name:
if str([x for x in inspector.get_columns('task_parameters')
if x['name'] == 'value'][0]['type']) != 'TEXT':
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT')
elif 'sqlite' in engine.dialect.name:
# SQLite does not support changing column types. A database file will need
# to be used to pickup this migration change.
for i in conn.execute('PRAGMA table_info(task_parameters);').fetchall():
if i['name'] == 'value' and i['type'] != 'TEXT':
logger.warning(
'SQLite can not change column types. Please use a new database '
'to pickup column type changes.'
)
else:
logger.warning(
'SQLAlcheny dialect {} could not be migrated to the TEXT type'.format(
engine.dialect
)
) | python | def _upgrade_schema(engine):
"""
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database.
"""
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
# Upgrade 1. Add task_id column and index to tasks
if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]:
logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id')
conn.execute('ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)')
conn.execute('CREATE INDEX ix_task_id ON tasks (task_id)')
# Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard
if 'mysql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY COLUMN value TEXT')
elif 'oracle' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY value TEXT')
elif 'mssql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TEXT')
elif 'postgresql' in engine.dialect.name:
if str([x for x in inspector.get_columns('task_parameters')
if x['name'] == 'value'][0]['type']) != 'TEXT':
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT')
elif 'sqlite' in engine.dialect.name:
# SQLite does not support changing column types. A database file will need
# to be used to pickup this migration change.
for i in conn.execute('PRAGMA table_info(task_parameters);').fetchall():
if i['name'] == 'value' and i['type'] != 'TEXT':
logger.warning(
'SQLite can not change column types. Please use a new database '
'to pickup column type changes.'
)
else:
logger.warning(
'SQLAlcheny dialect {} could not be migrated to the TEXT type'.format(
engine.dialect
)
) | [
"def",
"_upgrade_schema",
"(",
"engine",
")",
":",
"inspector",
"=",
"reflection",
".",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"with",
"engine",
".",
"connect",
"(",
")",
"as",
"conn",
":",
"# Upgrade 1. Add task_id column and index to tasks",
"if",
"'task_id'",
"not",
"in",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"inspector",
".",
"get_columns",
"(",
"'tasks'",
")",
"]",
":",
"logger",
".",
"warning",
"(",
"'Upgrading DbTaskHistory schema: Adding tasks.task_id'",
")",
"conn",
".",
"execute",
"(",
"'ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)'",
")",
"conn",
".",
"execute",
"(",
"'CREATE INDEX ix_task_id ON tasks (task_id)'",
")",
"# Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard",
"if",
"'mysql'",
"in",
"engine",
".",
"dialect",
".",
"name",
":",
"conn",
".",
"execute",
"(",
"'ALTER TABLE task_parameters MODIFY COLUMN value TEXT'",
")",
"elif",
"'oracle'",
"in",
"engine",
".",
"dialect",
".",
"name",
":",
"conn",
".",
"execute",
"(",
"'ALTER TABLE task_parameters MODIFY value TEXT'",
")",
"elif",
"'mssql'",
"in",
"engine",
".",
"dialect",
".",
"name",
":",
"conn",
".",
"execute",
"(",
"'ALTER TABLE task_parameters ALTER COLUMN value TEXT'",
")",
"elif",
"'postgresql'",
"in",
"engine",
".",
"dialect",
".",
"name",
":",
"if",
"str",
"(",
"[",
"x",
"for",
"x",
"in",
"inspector",
".",
"get_columns",
"(",
"'task_parameters'",
")",
"if",
"x",
"[",
"'name'",
"]",
"==",
"'value'",
"]",
"[",
"0",
"]",
"[",
"'type'",
"]",
")",
"!=",
"'TEXT'",
":",
"conn",
".",
"execute",
"(",
"'ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT'",
")",
"elif",
"'sqlite'",
"in",
"engine",
".",
"dialect",
".",
"name",
":",
"# SQLite does not support changing column types. A database file will need",
"# to be used to pickup this migration change.",
"for",
"i",
"in",
"conn",
".",
"execute",
"(",
"'PRAGMA table_info(task_parameters);'",
")",
".",
"fetchall",
"(",
")",
":",
"if",
"i",
"[",
"'name'",
"]",
"==",
"'value'",
"and",
"i",
"[",
"'type'",
"]",
"!=",
"'TEXT'",
":",
"logger",
".",
"warning",
"(",
"'SQLite can not change column types. Please use a new database '",
"'to pickup column type changes.'",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"'SQLAlcheny dialect {} could not be migrated to the TEXT type'",
".",
"format",
"(",
"engine",
".",
"dialect",
")",
")"
] | Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database. | [
"Ensure",
"the",
"database",
"schema",
"is",
"up",
"to",
"date",
"with",
"the",
"codebase",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L243-L283 | train |
spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_all_by_parameters | def find_all_by_parameters(self, task_name, session=None, **task_params):
"""
Find tasks with the given task_name and the same parameters as the kwargs.
"""
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name)
for (k, v) in six.iteritems(task_params):
alias = sqlalchemy.orm.aliased(TaskParameter)
query = query.join(alias).filter(alias.name == k, alias.value == v)
tasks = query.order_by(TaskEvent.ts)
for task in tasks:
# Sanity check
assert all(k in task.parameters and v == str(task.parameters[k].value) for (k, v) in six.iteritems(task_params))
yield task | python | def find_all_by_parameters(self, task_name, session=None, **task_params):
"""
Find tasks with the given task_name and the same parameters as the kwargs.
"""
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name)
for (k, v) in six.iteritems(task_params):
alias = sqlalchemy.orm.aliased(TaskParameter)
query = query.join(alias).filter(alias.name == k, alias.value == v)
tasks = query.order_by(TaskEvent.ts)
for task in tasks:
# Sanity check
assert all(k in task.parameters and v == str(task.parameters[k].value) for (k, v) in six.iteritems(task_params))
yield task | [
"def",
"find_all_by_parameters",
"(",
"self",
",",
"task_name",
",",
"session",
"=",
"None",
",",
"*",
"*",
"task_params",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"query",
"=",
"session",
".",
"query",
"(",
"TaskRecord",
")",
".",
"join",
"(",
"TaskEvent",
")",
".",
"filter",
"(",
"TaskRecord",
".",
"name",
"==",
"task_name",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"task_params",
")",
":",
"alias",
"=",
"sqlalchemy",
".",
"orm",
".",
"aliased",
"(",
"TaskParameter",
")",
"query",
"=",
"query",
".",
"join",
"(",
"alias",
")",
".",
"filter",
"(",
"alias",
".",
"name",
"==",
"k",
",",
"alias",
".",
"value",
"==",
"v",
")",
"tasks",
"=",
"query",
".",
"order_by",
"(",
"TaskEvent",
".",
"ts",
")",
"for",
"task",
"in",
"tasks",
":",
"# Sanity check",
"assert",
"all",
"(",
"k",
"in",
"task",
".",
"parameters",
"and",
"v",
"==",
"str",
"(",
"task",
".",
"parameters",
"[",
"k",
"]",
".",
"value",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"task_params",
")",
")",
"yield",
"task"
] | Find tasks with the given task_name and the same parameters as the kwargs. | [
"Find",
"tasks",
"with",
"the",
"given",
"task_name",
"and",
"the",
"same",
"parameters",
"as",
"the",
"kwargs",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L134-L149 | train |
spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_all_runs | def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() | python | def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() | [
"def",
"find_all_runs",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"return",
"session",
".",
"query",
"(",
"TaskRecord",
")",
".",
"all",
"(",
")"
] | Return all tasks that have been updated. | [
"Return",
"all",
"tasks",
"that",
"have",
"been",
"updated",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L170-L175 | train |
spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_all_events | def find_all_events(self, session=None):
"""
Return all running/failed/done events.
"""
with self._session(session) as session:
return session.query(TaskEvent).all() | python | def find_all_events(self, session=None):
"""
Return all running/failed/done events.
"""
with self._session(session) as session:
return session.query(TaskEvent).all() | [
"def",
"find_all_events",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"return",
"session",
".",
"query",
"(",
"TaskEvent",
")",
".",
"all",
"(",
")"
] | Return all running/failed/done events. | [
"Return",
"all",
"running",
"/",
"failed",
"/",
"done",
"events",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L177-L182 | train |
spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_task_by_id | def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) | python | def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) | [
"def",
"find_task_by_id",
"(",
"self",
",",
"id",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"return",
"session",
".",
"query",
"(",
"TaskRecord",
")",
".",
"get",
"(",
"id",
")"
] | Find task with the given record ID. | [
"Find",
"task",
"with",
"the",
"given",
"record",
"ID",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L184-L189 | train |
spotify/luigi | luigi/contrib/gcp.py | get_authenticate_kwargs | def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient` and `bigquery.BigQueryClient` to initiate the API Client
"""
if oauth_credentials:
authenticate_kwargs = {
"credentials": oauth_credentials
}
elif http_:
authenticate_kwargs = {
"http": http_
}
else:
# neither http_ or credentials provided
try:
# try default credentials
credentials, _ = google.auth.default()
authenticate_kwargs = {
"credentials": credentials
}
except google.auth.exceptions.DefaultCredentialsError:
# try http using httplib2
authenticate_kwargs = {
"http": httplib2.Http()
}
return authenticate_kwargs | python | def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient` and `bigquery.BigQueryClient` to initiate the API Client
"""
if oauth_credentials:
authenticate_kwargs = {
"credentials": oauth_credentials
}
elif http_:
authenticate_kwargs = {
"http": http_
}
else:
# neither http_ or credentials provided
try:
# try default credentials
credentials, _ = google.auth.default()
authenticate_kwargs = {
"credentials": credentials
}
except google.auth.exceptions.DefaultCredentialsError:
# try http using httplib2
authenticate_kwargs = {
"http": httplib2.Http()
}
return authenticate_kwargs | [
"def",
"get_authenticate_kwargs",
"(",
"oauth_credentials",
"=",
"None",
",",
"http_",
"=",
"None",
")",
":",
"if",
"oauth_credentials",
":",
"authenticate_kwargs",
"=",
"{",
"\"credentials\"",
":",
"oauth_credentials",
"}",
"elif",
"http_",
":",
"authenticate_kwargs",
"=",
"{",
"\"http\"",
":",
"http_",
"}",
"else",
":",
"# neither http_ or credentials provided",
"try",
":",
"# try default credentials",
"credentials",
",",
"_",
"=",
"google",
".",
"auth",
".",
"default",
"(",
")",
"authenticate_kwargs",
"=",
"{",
"\"credentials\"",
":",
"credentials",
"}",
"except",
"google",
".",
"auth",
".",
"exceptions",
".",
"DefaultCredentialsError",
":",
"# try http using httplib2",
"authenticate_kwargs",
"=",
"{",
"\"http\"",
":",
"httplib2",
".",
"Http",
"(",
")",
"}",
"return",
"authenticate_kwargs"
] | Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient` and `bigquery.BigQueryClient` to initiate the API Client | [
"Returns",
"a",
"dictionary",
"with",
"keyword",
"arguments",
"for",
"use",
"with",
"discovery"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcp.py#L15-L46 | train |
spotify/luigi | luigi/contrib/redshift.py | _CredentialsMixin._credentials | def _credentials(self):
"""
Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError.
"""
if self.aws_account_id and self.aws_arn_role_name:
return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
id=self.aws_account_id,
role=self.aws_arn_role_name
)
elif self.aws_access_key_id and self.aws_secret_access_key:
return 'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'.format(
key=self.aws_access_key_id,
secret=self.aws_secret_access_key,
opt=';token={}'.format(self.aws_session_token) if self.aws_session_token else ''
)
else:
raise NotImplementedError("Missing Credentials. "
"Ensure one of the pairs of auth args below are set "
"in a configuration file, environment variables or by "
"being overridden in the task: "
"'aws_access_key_id' AND 'aws_secret_access_key' OR "
"'aws_account_id' AND 'aws_arn_role_name'") | python | def _credentials(self):
"""
Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError.
"""
if self.aws_account_id and self.aws_arn_role_name:
return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
id=self.aws_account_id,
role=self.aws_arn_role_name
)
elif self.aws_access_key_id and self.aws_secret_access_key:
return 'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'.format(
key=self.aws_access_key_id,
secret=self.aws_secret_access_key,
opt=';token={}'.format(self.aws_session_token) if self.aws_session_token else ''
)
else:
raise NotImplementedError("Missing Credentials. "
"Ensure one of the pairs of auth args below are set "
"in a configuration file, environment variables or by "
"being overridden in the task: "
"'aws_access_key_id' AND 'aws_secret_access_key' OR "
"'aws_account_id' AND 'aws_arn_role_name'") | [
"def",
"_credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"aws_account_id",
"and",
"self",
".",
"aws_arn_role_name",
":",
"return",
"'aws_iam_role=arn:aws:iam::{id}:role/{role}'",
".",
"format",
"(",
"id",
"=",
"self",
".",
"aws_account_id",
",",
"role",
"=",
"self",
".",
"aws_arn_role_name",
")",
"elif",
"self",
".",
"aws_access_key_id",
"and",
"self",
".",
"aws_secret_access_key",
":",
"return",
"'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'",
".",
"format",
"(",
"key",
"=",
"self",
".",
"aws_access_key_id",
",",
"secret",
"=",
"self",
".",
"aws_secret_access_key",
",",
"opt",
"=",
"';token={}'",
".",
"format",
"(",
"self",
".",
"aws_session_token",
")",
"if",
"self",
".",
"aws_session_token",
"else",
"''",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"Missing Credentials. \"",
"\"Ensure one of the pairs of auth args below are set \"",
"\"in a configuration file, environment variables or by \"",
"\"being overridden in the task: \"",
"\"'aws_access_key_id' AND 'aws_secret_access_key' OR \"",
"\"'aws_account_id' AND 'aws_arn_role_name'\"",
")"
] | Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError. | [
"Return",
"a",
"credential",
"string",
"for",
"the",
"provided",
"task",
".",
"If",
"no",
"valid",
"credentials",
"are",
"set",
"raise",
"a",
"NotImplementedError",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L100-L123 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.do_prune | def do_prune(self):
"""
Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in.
"""
if self.prune_table and self.prune_column and self.prune_date:
return True
elif self.prune_table or self.prune_column or self.prune_date:
raise Exception('override zero or all prune variables')
else:
return False | python | def do_prune(self):
"""
Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in.
"""
if self.prune_table and self.prune_column and self.prune_date:
return True
elif self.prune_table or self.prune_column or self.prune_date:
raise Exception('override zero or all prune variables')
else:
return False | [
"def",
"do_prune",
"(",
"self",
")",
":",
"if",
"self",
".",
"prune_table",
"and",
"self",
".",
"prune_column",
"and",
"self",
".",
"prune_date",
":",
"return",
"True",
"elif",
"self",
".",
"prune_table",
"or",
"self",
".",
"prune_column",
"or",
"self",
".",
"prune_date",
":",
"raise",
"Exception",
"(",
"'override zero or all prune variables'",
")",
"else",
":",
"return",
"False"
] | Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in. | [
"Return",
"True",
"if",
"prune_table",
"prune_column",
"and",
"prune_date",
"are",
"implemented",
".",
"If",
"only",
"a",
"subset",
"of",
"prune",
"variables",
"are",
"override",
"an",
"exception",
"is",
"raised",
"to",
"remind",
"the",
"user",
"to",
"implement",
"all",
"or",
"none",
".",
"Prune",
"(",
"data",
"newer",
"than",
"prune_date",
"deleted",
")",
"before",
"copying",
"new",
"data",
"in",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L240-L251 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.create_schema | def create_schema(self, connection):
"""
Will create the schema in the database
"""
if '.' not in self.table:
return
query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0])
connection.cursor().execute(query) | python | def create_schema(self, connection):
"""
Will create the schema in the database
"""
if '.' not in self.table:
return
query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0])
connection.cursor().execute(query) | [
"def",
"create_schema",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"not",
"in",
"self",
".",
"table",
":",
"return",
"query",
"=",
"'CREATE SCHEMA IF NOT EXISTS {schema_name};'",
".",
"format",
"(",
"schema_name",
"=",
"self",
".",
"table",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"connection",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"query",
")"
] | Will create the schema in the database | [
"Will",
"create",
"the",
"schema",
"in",
"the",
"database"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L283-L291 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.create_table | def create_table(self, connection):
"""
Override to provide code for creating the target table.
By default it will be created using types (optionally)
specified in columns.
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.
"""
if len(self.columns[0]) == 1:
# only names of columns specified, no types
raise NotImplementedError("create_table() not implemented "
"for %r and columns types not "
"specified" % self.table)
elif len(self.columns[0]) == 2:
# if columns is specified as (name, type) tuples
coldefs = ','.join(
'{name} {type}'.format(
name=name,
type=type) for name, type in self.columns
)
table_constraints = ''
if self.table_constraints != '':
table_constraints = ', ' + self.table_constraints
query = ("CREATE {type} TABLE "
"{table} ({coldefs} {table_constraints}) "
"{table_attributes}").format(
type=self.table_type,
table=self.table,
coldefs=coldefs,
table_constraints=table_constraints,
table_attributes=self.table_attributes)
connection.cursor().execute(query)
elif len(self.columns[0]) == 3:
# if columns is specified as (name, type, encoding) tuples
# possible column encodings: https://docs.aws.amazon.com/redshift/latest/dg/c_Compression_encodings.html
coldefs = ','.join(
'{name} {type} ENCODE {encoding}'.format(
name=name,
type=type,
encoding=encoding) for name, type, encoding in self.columns
)
table_constraints = ''
if self.table_constraints != '':
table_constraints = ',' + self.table_constraints
query = ("CREATE {type} TABLE "
"{table} ({coldefs} {table_constraints}) "
"{table_attributes}").format(
type=self.table_type,
table=self.table,
coldefs=coldefs,
table_constraints=table_constraints,
table_attributes=self.table_attributes)
connection.cursor().execute(query)
else:
raise ValueError("create_table() found no columns for %r"
% self.table) | python | def create_table(self, connection):
"""
Override to provide code for creating the target table.
By default it will be created using types (optionally)
specified in columns.
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.
"""
if len(self.columns[0]) == 1:
# only names of columns specified, no types
raise NotImplementedError("create_table() not implemented "
"for %r and columns types not "
"specified" % self.table)
elif len(self.columns[0]) == 2:
# if columns is specified as (name, type) tuples
coldefs = ','.join(
'{name} {type}'.format(
name=name,
type=type) for name, type in self.columns
)
table_constraints = ''
if self.table_constraints != '':
table_constraints = ', ' + self.table_constraints
query = ("CREATE {type} TABLE "
"{table} ({coldefs} {table_constraints}) "
"{table_attributes}").format(
type=self.table_type,
table=self.table,
coldefs=coldefs,
table_constraints=table_constraints,
table_attributes=self.table_attributes)
connection.cursor().execute(query)
elif len(self.columns[0]) == 3:
# if columns is specified as (name, type, encoding) tuples
# possible column encodings: https://docs.aws.amazon.com/redshift/latest/dg/c_Compression_encodings.html
coldefs = ','.join(
'{name} {type} ENCODE {encoding}'.format(
name=name,
type=type,
encoding=encoding) for name, type, encoding in self.columns
)
table_constraints = ''
if self.table_constraints != '':
table_constraints = ',' + self.table_constraints
query = ("CREATE {type} TABLE "
"{table} ({coldefs} {table_constraints}) "
"{table_attributes}").format(
type=self.table_type,
table=self.table,
coldefs=coldefs,
table_constraints=table_constraints,
table_attributes=self.table_attributes)
connection.cursor().execute(query)
else:
raise ValueError("create_table() found no columns for %r"
% self.table) | [
"def",
"create_table",
"(",
"self",
",",
"connection",
")",
":",
"if",
"len",
"(",
"self",
".",
"columns",
"[",
"0",
"]",
")",
"==",
"1",
":",
"# only names of columns specified, no types",
"raise",
"NotImplementedError",
"(",
"\"create_table() not implemented \"",
"\"for %r and columns types not \"",
"\"specified\"",
"%",
"self",
".",
"table",
")",
"elif",
"len",
"(",
"self",
".",
"columns",
"[",
"0",
"]",
")",
"==",
"2",
":",
"# if columns is specified as (name, type) tuples",
"coldefs",
"=",
"','",
".",
"join",
"(",
"'{name} {type}'",
".",
"format",
"(",
"name",
"=",
"name",
",",
"type",
"=",
"type",
")",
"for",
"name",
",",
"type",
"in",
"self",
".",
"columns",
")",
"table_constraints",
"=",
"''",
"if",
"self",
".",
"table_constraints",
"!=",
"''",
":",
"table_constraints",
"=",
"', '",
"+",
"self",
".",
"table_constraints",
"query",
"=",
"(",
"\"CREATE {type} TABLE \"",
"\"{table} ({coldefs} {table_constraints}) \"",
"\"{table_attributes}\"",
")",
".",
"format",
"(",
"type",
"=",
"self",
".",
"table_type",
",",
"table",
"=",
"self",
".",
"table",
",",
"coldefs",
"=",
"coldefs",
",",
"table_constraints",
"=",
"table_constraints",
",",
"table_attributes",
"=",
"self",
".",
"table_attributes",
")",
"connection",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"query",
")",
"elif",
"len",
"(",
"self",
".",
"columns",
"[",
"0",
"]",
")",
"==",
"3",
":",
"# if columns is specified as (name, type, encoding) tuples",
"# possible column encodings: https://docs.aws.amazon.com/redshift/latest/dg/c_Compression_encodings.html",
"coldefs",
"=",
"','",
".",
"join",
"(",
"'{name} {type} ENCODE {encoding}'",
".",
"format",
"(",
"name",
"=",
"name",
",",
"type",
"=",
"type",
",",
"encoding",
"=",
"encoding",
")",
"for",
"name",
",",
"type",
",",
"encoding",
"in",
"self",
".",
"columns",
")",
"table_constraints",
"=",
"''",
"if",
"self",
".",
"table_constraints",
"!=",
"''",
":",
"table_constraints",
"=",
"','",
"+",
"self",
".",
"table_constraints",
"query",
"=",
"(",
"\"CREATE {type} TABLE \"",
"\"{table} ({coldefs} {table_constraints}) \"",
"\"{table_attributes}\"",
")",
".",
"format",
"(",
"type",
"=",
"self",
".",
"table_type",
",",
"table",
"=",
"self",
".",
"table",
",",
"coldefs",
"=",
"coldefs",
",",
"table_constraints",
"=",
"table_constraints",
",",
"table_attributes",
"=",
"self",
".",
"table_attributes",
")",
"connection",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"query",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"create_table() found no columns for %r\"",
"%",
"self",
".",
"table",
")"
] | Override to provide code for creating the target table.
By default it will be created using types (optionally)
specified in columns.
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. | [
"Override",
"to",
"provide",
"code",
"for",
"creating",
"the",
"target",
"table",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L293-L357 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.run | def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
output = self.output()
connection = output.connect()
cursor = connection.cursor()
self.init_copy(connection)
self.copy(cursor, path)
self.post_copy(cursor)
if self.enable_metadata_columns:
self.post_copy_metacolumns(cursor)
# update marker table
output.touch(connection)
connection.commit()
# commit and clean up
connection.close() | python | def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
output = self.output()
connection = output.connect()
cursor = connection.cursor()
self.init_copy(connection)
self.copy(cursor, path)
self.post_copy(cursor)
if self.enable_metadata_columns:
self.post_copy_metacolumns(cursor)
# update marker table
output.touch(connection)
connection.commit()
# commit and clean up
connection.close() | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"table",
")",
":",
"raise",
"Exception",
"(",
"\"table need to be specified\"",
")",
"path",
"=",
"self",
".",
"s3_load_path",
"(",
")",
"output",
"=",
"self",
".",
"output",
"(",
")",
"connection",
"=",
"output",
".",
"connect",
"(",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"self",
".",
"init_copy",
"(",
"connection",
")",
"self",
".",
"copy",
"(",
"cursor",
",",
"path",
")",
"self",
".",
"post_copy",
"(",
"cursor",
")",
"if",
"self",
".",
"enable_metadata_columns",
":",
"self",
".",
"post_copy_metacolumns",
"(",
"cursor",
")",
"# update marker table",
"output",
".",
"touch",
"(",
"connection",
")",
"connection",
".",
"commit",
"(",
")",
"# commit and clean up",
"connection",
".",
"close",
"(",
")"
] | If the target table doesn't exist, self.create_table
will be called to attempt to create the table. | [
"If",
"the",
"target",
"table",
"doesn",
"t",
"exist",
"self",
".",
"create_table",
"will",
"be",
"called",
"to",
"attempt",
"to",
"create",
"the",
"table",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L359-L384 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.copy | def copy(self, cursor, f):
"""
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used.
"""
logger.info("Inserting file: %s", f)
colnames = ''
if self.columns and len(self.columns) > 0:
colnames = ",".join([x[0] for x in self.columns])
colnames = '({})'.format(colnames)
cursor.execute("""
COPY {table} {colnames} from '{source}'
CREDENTIALS '{creds}'
{options}
;""".format(
table=self.table,
colnames=colnames,
source=f,
creds=self._credentials(),
options=self.copy_options)
) | python | def copy(self, cursor, f):
"""
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used.
"""
logger.info("Inserting file: %s", f)
colnames = ''
if self.columns and len(self.columns) > 0:
colnames = ",".join([x[0] for x in self.columns])
colnames = '({})'.format(colnames)
cursor.execute("""
COPY {table} {colnames} from '{source}'
CREDENTIALS '{creds}'
{options}
;""".format(
table=self.table,
colnames=colnames,
source=f,
creds=self._credentials(),
options=self.copy_options)
) | [
"def",
"copy",
"(",
"self",
",",
"cursor",
",",
"f",
")",
":",
"logger",
".",
"info",
"(",
"\"Inserting file: %s\"",
",",
"f",
")",
"colnames",
"=",
"''",
"if",
"self",
".",
"columns",
"and",
"len",
"(",
"self",
".",
"columns",
")",
">",
"0",
":",
"colnames",
"=",
"\",\"",
".",
"join",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"self",
".",
"columns",
"]",
")",
"colnames",
"=",
"'({})'",
".",
"format",
"(",
"colnames",
")",
"cursor",
".",
"execute",
"(",
"\"\"\"\n COPY {table} {colnames} from '{source}'\n CREDENTIALS '{creds}'\n {options}\n ;\"\"\"",
".",
"format",
"(",
"table",
"=",
"self",
".",
"table",
",",
"colnames",
"=",
"colnames",
",",
"source",
"=",
"f",
",",
"creds",
"=",
"self",
".",
"_credentials",
"(",
")",
",",
"options",
"=",
"self",
".",
"copy_options",
")",
")"
] | Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used. | [
"Defines",
"copying",
"from",
"s3",
"into",
"redshift",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L386-L408 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.does_schema_exist | def does_schema_exist(self, connection):
"""
Determine whether the schema already exists.
"""
if '.' in self.table:
query = ("select 1 as schema_exists "
"from pg_namespace "
"where nspname = lower(%s) limit 1")
else:
return True
cursor = connection.cursor()
try:
schema = self.table.split('.')[0]
cursor.execute(query, [schema])
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | python | def does_schema_exist(self, connection):
"""
Determine whether the schema already exists.
"""
if '.' in self.table:
query = ("select 1 as schema_exists "
"from pg_namespace "
"where nspname = lower(%s) limit 1")
else:
return True
cursor = connection.cursor()
try:
schema = self.table.split('.')[0]
cursor.execute(query, [schema])
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | [
"def",
"does_schema_exist",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"in",
"self",
".",
"table",
":",
"query",
"=",
"(",
"\"select 1 as schema_exists \"",
"\"from pg_namespace \"",
"\"where nspname = lower(%s) limit 1\"",
")",
"else",
":",
"return",
"True",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"try",
":",
"schema",
"=",
"self",
".",
"table",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"cursor",
".",
"execute",
"(",
"query",
",",
"[",
"schema",
"]",
")",
"result",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"bool",
"(",
"result",
")",
"finally",
":",
"cursor",
".",
"close",
"(",
")"
] | Determine whether the schema already exists. | [
"Determine",
"whether",
"the",
"schema",
"already",
"exists",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L424-L443 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.does_table_exist | def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = lower(%s) and table_name = lower(%s) limit 1")
else:
query = ("select 1 as table_exists "
"from pg_table_def "
"where tablename = lower(%s) limit 1")
cursor = connection.cursor()
try:
cursor.execute(query, tuple(self.table.split('.')))
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | python | def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = lower(%s) and table_name = lower(%s) limit 1")
else:
query = ("select 1 as table_exists "
"from pg_table_def "
"where tablename = lower(%s) limit 1")
cursor = connection.cursor()
try:
cursor.execute(query, tuple(self.table.split('.')))
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | [
"def",
"does_table_exist",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"in",
"self",
".",
"table",
":",
"query",
"=",
"(",
"\"select 1 as table_exists \"",
"\"from information_schema.tables \"",
"\"where table_schema = lower(%s) and table_name = lower(%s) limit 1\"",
")",
"else",
":",
"query",
"=",
"(",
"\"select 1 as table_exists \"",
"\"from pg_table_def \"",
"\"where tablename = lower(%s) limit 1\"",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"query",
",",
"tuple",
"(",
"self",
".",
"table",
".",
"split",
"(",
"'.'",
")",
")",
")",
"result",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"bool",
"(",
"result",
")",
"finally",
":",
"cursor",
".",
"close",
"(",
")"
] | Determine whether the table already exists. | [
"Determine",
"whether",
"the",
"table",
"already",
"exists",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L445-L464 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.init_copy | def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info("Creating schema for %s", self.table)
self.create_schema(connection)
if not self.does_table_exist(connection):
logger.info("Creating table %s", self.table)
self.create_table(connection)
if self.enable_metadata_columns:
self._add_metadata_columns(connection)
if self.do_truncate_table:
logger.info("Truncating table %s", self.table)
self.truncate_table(connection)
if self.do_prune():
logger.info("Removing %s older than %s from %s", self.prune_column, self.prune_date, self.prune_table)
self.prune(connection) | python | def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info("Creating schema for %s", self.table)
self.create_schema(connection)
if not self.does_table_exist(connection):
logger.info("Creating table %s", self.table)
self.create_table(connection)
if self.enable_metadata_columns:
self._add_metadata_columns(connection)
if self.do_truncate_table:
logger.info("Truncating table %s", self.table)
self.truncate_table(connection)
if self.do_prune():
logger.info("Removing %s older than %s from %s", self.prune_column, self.prune_date, self.prune_table)
self.prune(connection) | [
"def",
"init_copy",
"(",
"self",
",",
"connection",
")",
":",
"if",
"not",
"self",
".",
"does_schema_exist",
"(",
"connection",
")",
":",
"logger",
".",
"info",
"(",
"\"Creating schema for %s\"",
",",
"self",
".",
"table",
")",
"self",
".",
"create_schema",
"(",
"connection",
")",
"if",
"not",
"self",
".",
"does_table_exist",
"(",
"connection",
")",
":",
"logger",
".",
"info",
"(",
"\"Creating table %s\"",
",",
"self",
".",
"table",
")",
"self",
".",
"create_table",
"(",
"connection",
")",
"if",
"self",
".",
"enable_metadata_columns",
":",
"self",
".",
"_add_metadata_columns",
"(",
"connection",
")",
"if",
"self",
".",
"do_truncate_table",
":",
"logger",
".",
"info",
"(",
"\"Truncating table %s\"",
",",
"self",
".",
"table",
")",
"self",
".",
"truncate_table",
"(",
"connection",
")",
"if",
"self",
".",
"do_prune",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing %s older than %s from %s\"",
",",
"self",
".",
"prune_column",
",",
"self",
".",
"prune_date",
",",
"self",
".",
"prune_table",
")",
"self",
".",
"prune",
"(",
"connection",
")"
] | Perform pre-copy sql - such as creating table, truncating, or removing data older than x. | [
"Perform",
"pre",
"-",
"copy",
"sql",
"-",
"such",
"as",
"creating",
"table",
"truncating",
"or",
"removing",
"data",
"older",
"than",
"x",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L466-L487 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.post_copy | def post_copy(self, cursor):
"""
Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc.
"""
logger.info('Executing post copy queries')
for query in self.queries:
cursor.execute(query) | python | def post_copy(self, cursor):
"""
Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc.
"""
logger.info('Executing post copy queries')
for query in self.queries:
cursor.execute(query) | [
"def",
"post_copy",
"(",
"self",
",",
"cursor",
")",
":",
"logger",
".",
"info",
"(",
"'Executing post copy queries'",
")",
"for",
"query",
"in",
"self",
".",
"queries",
":",
"cursor",
".",
"execute",
"(",
"query",
")"
] | Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc. | [
"Performs",
"post",
"-",
"copy",
"sql",
"-",
"such",
"as",
"cleansing",
"data",
"inserting",
"into",
"production",
"table",
"(",
"if",
"copied",
"to",
"temp",
"table",
")",
"etc",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L489-L495 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.post_copy_metacolums | def post_copy_metacolums(self, cursor):
"""
Performs post-copy to fill metadata columns.
"""
logger.info('Executing post copy metadata queries')
for query in self.metadata_queries:
cursor.execute(query) | python | def post_copy_metacolums(self, cursor):
"""
Performs post-copy to fill metadata columns.
"""
logger.info('Executing post copy metadata queries')
for query in self.metadata_queries:
cursor.execute(query) | [
"def",
"post_copy_metacolums",
"(",
"self",
",",
"cursor",
")",
":",
"logger",
".",
"info",
"(",
"'Executing post copy metadata queries'",
")",
"for",
"query",
"in",
"self",
".",
"metadata_queries",
":",
"cursor",
".",
"execute",
"(",
"query",
")"
] | Performs post-copy to fill metadata columns. | [
"Performs",
"post",
"-",
"copy",
"to",
"fill",
"metadata",
"columns",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L497-L503 | train |
spotify/luigi | luigi/contrib/redshift.py | S3CopyJSONToTable.copy | def copy(self, cursor, f):
"""
Defines copying JSON from s3 into redshift.
"""
logger.info("Inserting file: %s", f)
cursor.execute("""
COPY %s from '%s'
CREDENTIALS '%s'
JSON AS '%s' %s
%s
;""" % (self.table, f, self._credentials(),
self.jsonpath, self.copy_json_options, self.copy_options)) | python | def copy(self, cursor, f):
"""
Defines copying JSON from s3 into redshift.
"""
logger.info("Inserting file: %s", f)
cursor.execute("""
COPY %s from '%s'
CREDENTIALS '%s'
JSON AS '%s' %s
%s
;""" % (self.table, f, self._credentials(),
self.jsonpath, self.copy_json_options, self.copy_options)) | [
"def",
"copy",
"(",
"self",
",",
"cursor",
",",
"f",
")",
":",
"logger",
".",
"info",
"(",
"\"Inserting file: %s\"",
",",
"f",
")",
"cursor",
".",
"execute",
"(",
"\"\"\"\n COPY %s from '%s'\n CREDENTIALS '%s'\n JSON AS '%s' %s\n %s\n ;\"\"\"",
"%",
"(",
"self",
".",
"table",
",",
"f",
",",
"self",
".",
"_credentials",
"(",
")",
",",
"self",
".",
"jsonpath",
",",
"self",
".",
"copy_json_options",
",",
"self",
".",
"copy_options",
")",
")"
] | Defines copying JSON from s3 into redshift. | [
"Defines",
"copying",
"JSON",
"from",
"s3",
"into",
"redshift",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L546-L558 | train |
spotify/luigi | luigi/contrib/redshift.py | KillOpenRedshiftSessions.output | def output(self):
"""
Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this.
"""
# uses class name as a meta-table
return RedshiftTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.__class__.__name__,
update_id=self.update_id) | python | def output(self):
"""
Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this.
"""
# uses class name as a meta-table
return RedshiftTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.__class__.__name__,
update_id=self.update_id) | [
"def",
"output",
"(",
"self",
")",
":",
"# uses class name as a meta-table",
"return",
"RedshiftTarget",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"self",
".",
"database",
",",
"user",
"=",
"self",
".",
"user",
",",
"password",
"=",
"self",
".",
"password",
",",
"table",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"update_id",
"=",
"self",
".",
"update_id",
")"
] | Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this. | [
"Returns",
"a",
"RedshiftTarget",
"representing",
"the",
"inserted",
"dataset",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L649-L662 | train |
spotify/luigi | luigi/contrib/redshift.py | KillOpenRedshiftSessions.run | def run(self):
"""
Kill any open Redshift sessions for the given database.
"""
connection = self.output().connect()
# kill any sessions other than ours and
# internal Redshift sessions (rdsdb)
query = ("select pg_terminate_backend(process) "
"from STV_SESSIONS "
"where db_name=%s "
"and user_name != 'rdsdb' "
"and process != pg_backend_pid()")
cursor = connection.cursor()
logger.info('Killing all open Redshift sessions for database: %s', self.database)
try:
cursor.execute(query, (self.database,))
cursor.close()
connection.commit()
except psycopg2.DatabaseError as e:
if e.message and 'EOF' in e.message:
# sometimes this operation kills the current session.
# rebuild the connection. Need to pause for 30-60 seconds
# before Redshift will allow us back in.
connection.close()
logger.info('Pausing %s seconds for Redshift to reset connection', self.connection_reset_wait_seconds)
time.sleep(self.connection_reset_wait_seconds)
logger.info('Reconnecting to Redshift')
connection = self.output().connect()
else:
raise
try:
self.output().touch(connection)
connection.commit()
finally:
connection.close()
logger.info('Done killing all open Redshift sessions for database: %s', self.database) | python | def run(self):
"""
Kill any open Redshift sessions for the given database.
"""
connection = self.output().connect()
# kill any sessions other than ours and
# internal Redshift sessions (rdsdb)
query = ("select pg_terminate_backend(process) "
"from STV_SESSIONS "
"where db_name=%s "
"and user_name != 'rdsdb' "
"and process != pg_backend_pid()")
cursor = connection.cursor()
logger.info('Killing all open Redshift sessions for database: %s', self.database)
try:
cursor.execute(query, (self.database,))
cursor.close()
connection.commit()
except psycopg2.DatabaseError as e:
if e.message and 'EOF' in e.message:
# sometimes this operation kills the current session.
# rebuild the connection. Need to pause for 30-60 seconds
# before Redshift will allow us back in.
connection.close()
logger.info('Pausing %s seconds for Redshift to reset connection', self.connection_reset_wait_seconds)
time.sleep(self.connection_reset_wait_seconds)
logger.info('Reconnecting to Redshift')
connection = self.output().connect()
else:
raise
try:
self.output().touch(connection)
connection.commit()
finally:
connection.close()
logger.info('Done killing all open Redshift sessions for database: %s', self.database) | [
"def",
"run",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"output",
"(",
")",
".",
"connect",
"(",
")",
"# kill any sessions other than ours and",
"# internal Redshift sessions (rdsdb)",
"query",
"=",
"(",
"\"select pg_terminate_backend(process) \"",
"\"from STV_SESSIONS \"",
"\"where db_name=%s \"",
"\"and user_name != 'rdsdb' \"",
"\"and process != pg_backend_pid()\"",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"logger",
".",
"info",
"(",
"'Killing all open Redshift sessions for database: %s'",
",",
"self",
".",
"database",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"query",
",",
"(",
"self",
".",
"database",
",",
")",
")",
"cursor",
".",
"close",
"(",
")",
"connection",
".",
"commit",
"(",
")",
"except",
"psycopg2",
".",
"DatabaseError",
"as",
"e",
":",
"if",
"e",
".",
"message",
"and",
"'EOF'",
"in",
"e",
".",
"message",
":",
"# sometimes this operation kills the current session.",
"# rebuild the connection. Need to pause for 30-60 seconds",
"# before Redshift will allow us back in.",
"connection",
".",
"close",
"(",
")",
"logger",
".",
"info",
"(",
"'Pausing %s seconds for Redshift to reset connection'",
",",
"self",
".",
"connection_reset_wait_seconds",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"connection_reset_wait_seconds",
")",
"logger",
".",
"info",
"(",
"'Reconnecting to Redshift'",
")",
"connection",
"=",
"self",
".",
"output",
"(",
")",
".",
"connect",
"(",
")",
"else",
":",
"raise",
"try",
":",
"self",
".",
"output",
"(",
")",
".",
"touch",
"(",
"connection",
")",
"connection",
".",
"commit",
"(",
")",
"finally",
":",
"connection",
".",
"close",
"(",
")",
"logger",
".",
"info",
"(",
"'Done killing all open Redshift sessions for database: %s'",
",",
"self",
".",
"database",
")"
] | Kill any open Redshift sessions for the given database. | [
"Kill",
"any",
"open",
"Redshift",
"sessions",
"for",
"the",
"given",
"database",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L664-L701 | train |
spotify/luigi | luigi/date_interval.py | DateInterval.dates | def dates(self):
''' Returns a list of dates in this date interval.'''
dates = []
d = self.date_a
while d < self.date_b:
dates.append(d)
d += datetime.timedelta(1)
return dates | python | def dates(self):
''' Returns a list of dates in this date interval.'''
dates = []
d = self.date_a
while d < self.date_b:
dates.append(d)
d += datetime.timedelta(1)
return dates | [
"def",
"dates",
"(",
"self",
")",
":",
"dates",
"=",
"[",
"]",
"d",
"=",
"self",
".",
"date_a",
"while",
"d",
"<",
"self",
".",
"date_b",
":",
"dates",
".",
"append",
"(",
"d",
")",
"d",
"+=",
"datetime",
".",
"timedelta",
"(",
"1",
")",
"return",
"dates"
] | Returns a list of dates in this date interval. | [
"Returns",
"a",
"list",
"of",
"dates",
"in",
"this",
"date",
"interval",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/date_interval.py#L67-L75 | train |
spotify/luigi | luigi/date_interval.py | DateInterval.hours | def hours(self):
''' Same as dates() but returns 24 times more info: one for each hour.'''
for date in self.dates():
for hour in xrange(24):
yield datetime.datetime.combine(date, datetime.time(hour)) | python | def hours(self):
''' Same as dates() but returns 24 times more info: one for each hour.'''
for date in self.dates():
for hour in xrange(24):
yield datetime.datetime.combine(date, datetime.time(hour)) | [
"def",
"hours",
"(",
"self",
")",
":",
"for",
"date",
"in",
"self",
".",
"dates",
"(",
")",
":",
"for",
"hour",
"in",
"xrange",
"(",
"24",
")",
":",
"yield",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"date",
",",
"datetime",
".",
"time",
"(",
"hour",
")",
")"
] | Same as dates() but returns 24 times more info: one for each hour. | [
"Same",
"as",
"dates",
"()",
"but",
"returns",
"24",
"times",
"more",
"info",
":",
"one",
"for",
"each",
"hour",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/date_interval.py#L77-L81 | train |
spotify/luigi | examples/ftp_experiment_outputs.py | ExperimentTask.run | def run(self):
"""
The execution of this task will write 4 lines of data on this task's target output.
"""
with self.output().open('w') as outfile:
print("data 0 200 10 50 60", file=outfile)
print("data 1 190 9 52 60", file=outfile)
print("data 2 200 10 52 60", file=outfile)
print("data 3 195 1 52 60", file=outfile) | python | def run(self):
"""
The execution of this task will write 4 lines of data on this task's target output.
"""
with self.output().open('w') as outfile:
print("data 0 200 10 50 60", file=outfile)
print("data 1 190 9 52 60", file=outfile)
print("data 2 200 10 52 60", file=outfile)
print("data 3 195 1 52 60", file=outfile) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"self",
".",
"output",
"(",
")",
".",
"open",
"(",
"'w'",
")",
"as",
"outfile",
":",
"print",
"(",
"\"data 0 200 10 50 60\"",
",",
"file",
"=",
"outfile",
")",
"print",
"(",
"\"data 1 190 9 52 60\"",
",",
"file",
"=",
"outfile",
")",
"print",
"(",
"\"data 2 200 10 52 60\"",
",",
"file",
"=",
"outfile",
")",
"print",
"(",
"\"data 3 195 1 52 60\"",
",",
"file",
"=",
"outfile",
")"
] | The execution of this task will write 4 lines of data on this task's target output. | [
"The",
"execution",
"of",
"this",
"task",
"will",
"write",
"4",
"lines",
"of",
"data",
"on",
"this",
"task",
"s",
"target",
"output",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/ftp_experiment_outputs.py#L46-L54 | train |
spotify/luigi | luigi/mock.py | MockFileSystem.copy | def copy(self, path, dest, raise_if_exists=False):
"""
Copies the contents of a single file path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data()[path]
self.get_all_data()[dest] = contents | python | def copy(self, path, dest, raise_if_exists=False):
"""
Copies the contents of a single file path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data()[path]
self.get_all_data()[dest] = contents | [
"def",
"copy",
"(",
"self",
",",
"path",
",",
"dest",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"if",
"raise_if_exists",
"and",
"dest",
"in",
"self",
".",
"get_all_data",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Destination exists: %s'",
"%",
"path",
")",
"contents",
"=",
"self",
".",
"get_all_data",
"(",
")",
"[",
"path",
"]",
"self",
".",
"get_all_data",
"(",
")",
"[",
"dest",
"]",
"=",
"contents"
] | Copies the contents of a single file path to dest | [
"Copies",
"the",
"contents",
"of",
"a",
"single",
"file",
"path",
"to",
"dest"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L40-L47 | train |
spotify/luigi | luigi/mock.py | MockFileSystem.remove | def remove(self, path, recursive=True, skip_trash=True):
"""
Removes the given mockfile. skip_trash doesn't have any meaning.
"""
if recursive:
to_delete = []
for s in self.get_all_data().keys():
if s.startswith(path):
to_delete.append(s)
for s in to_delete:
self.get_all_data().pop(s)
else:
self.get_all_data().pop(path) | python | def remove(self, path, recursive=True, skip_trash=True):
"""
Removes the given mockfile. skip_trash doesn't have any meaning.
"""
if recursive:
to_delete = []
for s in self.get_all_data().keys():
if s.startswith(path):
to_delete.append(s)
for s in to_delete:
self.get_all_data().pop(s)
else:
self.get_all_data().pop(path) | [
"def",
"remove",
"(",
"self",
",",
"path",
",",
"recursive",
"=",
"True",
",",
"skip_trash",
"=",
"True",
")",
":",
"if",
"recursive",
":",
"to_delete",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"get_all_data",
"(",
")",
".",
"keys",
"(",
")",
":",
"if",
"s",
".",
"startswith",
"(",
"path",
")",
":",
"to_delete",
".",
"append",
"(",
"s",
")",
"for",
"s",
"in",
"to_delete",
":",
"self",
".",
"get_all_data",
"(",
")",
".",
"pop",
"(",
"s",
")",
"else",
":",
"self",
".",
"get_all_data",
"(",
")",
".",
"pop",
"(",
"path",
")"
] | Removes the given mockfile. skip_trash doesn't have any meaning. | [
"Removes",
"the",
"given",
"mockfile",
".",
"skip_trash",
"doesn",
"t",
"have",
"any",
"meaning",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L61-L73 | train |
spotify/luigi | luigi/mock.py | MockFileSystem.move | def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data().pop(path)
self.get_all_data()[dest] = contents | python | def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data().pop(path)
self.get_all_data()[dest] = contents | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"dest",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"if",
"raise_if_exists",
"and",
"dest",
"in",
"self",
".",
"get_all_data",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Destination exists: %s'",
"%",
"path",
")",
"contents",
"=",
"self",
".",
"get_all_data",
"(",
")",
".",
"pop",
"(",
"path",
")",
"self",
".",
"get_all_data",
"(",
")",
"[",
"dest",
"]",
"=",
"contents"
] | Moves a single file from path to dest | [
"Moves",
"a",
"single",
"file",
"from",
"path",
"to",
"dest"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L75-L82 | train |
spotify/luigi | luigi/mock.py | MockFileSystem.listdir | def listdir(self, path):
"""
listdir does a prefix match of self.get_all_data(), but doesn't yet support globs.
"""
return [s for s in self.get_all_data().keys()
if s.startswith(path)] | python | def listdir(self, path):
"""
listdir does a prefix match of self.get_all_data(), but doesn't yet support globs.
"""
return [s for s in self.get_all_data().keys()
if s.startswith(path)] | [
"def",
"listdir",
"(",
"self",
",",
"path",
")",
":",
"return",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"get_all_data",
"(",
")",
".",
"keys",
"(",
")",
"if",
"s",
".",
"startswith",
"(",
"path",
")",
"]"
] | listdir does a prefix match of self.get_all_data(), but doesn't yet support globs. | [
"listdir",
"does",
"a",
"prefix",
"match",
"of",
"self",
".",
"get_all_data",
"()",
"but",
"doesn",
"t",
"yet",
"support",
"globs",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L84-L89 | train |
spotify/luigi | luigi/mock.py | MockTarget.move | def move(self, path, raise_if_exists=False):
"""
Call MockFileSystem's move command
"""
self.fs.move(self.path, path, raise_if_exists) | python | def move(self, path, raise_if_exists=False):
"""
Call MockFileSystem's move command
"""
self.fs.move(self.path, path, raise_if_exists) | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"self",
".",
"fs",
".",
"move",
"(",
"self",
".",
"path",
",",
"path",
",",
"raise_if_exists",
")"
] | Call MockFileSystem's move command | [
"Call",
"MockFileSystem",
"s",
"move",
"command"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L122-L126 | train |
spotify/luigi | luigi/parameter.py | _recursively_freeze | def _recursively_freeze(value):
"""
Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively.
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return tuple(_recursively_freeze(v) for v in value)
return value | python | def _recursively_freeze(value):
"""
Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively.
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return tuple(_recursively_freeze(v) for v in value)
return value | [
"def",
"_recursively_freeze",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Mapping",
")",
":",
"return",
"_FrozenOrderedDict",
"(",
"(",
"(",
"k",
",",
"_recursively_freeze",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
"or",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"return",
"tuple",
"(",
"_recursively_freeze",
"(",
"v",
")",
"for",
"v",
"in",
"value",
")",
"return",
"value"
] | Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. | [
"Recursively",
"walks",
"Mapping",
"s",
"and",
"list",
"s",
"and",
"converts",
"them",
"to",
"_FrozenOrderedDict",
"and",
"tuples",
"respectively",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L929-L937 | train |
spotify/luigi | luigi/parameter.py | Parameter._get_value_from_config | def _get_value_from_config(self, section, name):
"""Loads the default from the config. Returns _no_value if it doesn't exist"""
conf = configuration.get_config()
try:
value = conf.get(section, name)
except (NoSectionError, NoOptionError, KeyError):
return _no_value
return self.parse(value) | python | def _get_value_from_config(self, section, name):
"""Loads the default from the config. Returns _no_value if it doesn't exist"""
conf = configuration.get_config()
try:
value = conf.get(section, name)
except (NoSectionError, NoOptionError, KeyError):
return _no_value
return self.parse(value) | [
"def",
"_get_value_from_config",
"(",
"self",
",",
"section",
",",
"name",
")",
":",
"conf",
"=",
"configuration",
".",
"get_config",
"(",
")",
"try",
":",
"value",
"=",
"conf",
".",
"get",
"(",
"section",
",",
"name",
")",
"except",
"(",
"NoSectionError",
",",
"NoOptionError",
",",
"KeyError",
")",
":",
"return",
"_no_value",
"return",
"self",
".",
"parse",
"(",
"value",
")"
] | Loads the default from the config. Returns _no_value if it doesn't exist | [
"Loads",
"the",
"default",
"from",
"the",
"config",
".",
"Returns",
"_no_value",
"if",
"it",
"doesn",
"t",
"exist"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L192-L202 | train |
spotify/luigi | luigi/parameter.py | Parameter._value_iterator | def _value_iterator(self, task_name, param_name):
"""
Yield the parameter values, with optional deprecation warning as second tuple value.
The parameter value will be whatever non-_no_value that is yielded first.
"""
cp_parser = CmdlineParser.get_instance()
if cp_parser:
dest = self._parser_global_dest(param_name, task_name)
found = getattr(cp_parser.known_args, dest, None)
yield (self._parse_or_no_value(found), None)
yield (self._get_value_from_config(task_name, param_name), None)
if self._config_path:
yield (self._get_value_from_config(self._config_path['section'], self._config_path['name']),
'The use of the configuration [{}] {} is deprecated. Please use [{}] {}'.format(
self._config_path['section'], self._config_path['name'], task_name, param_name))
yield (self._default, None) | python | def _value_iterator(self, task_name, param_name):
"""
Yield the parameter values, with optional deprecation warning as second tuple value.
The parameter value will be whatever non-_no_value that is yielded first.
"""
cp_parser = CmdlineParser.get_instance()
if cp_parser:
dest = self._parser_global_dest(param_name, task_name)
found = getattr(cp_parser.known_args, dest, None)
yield (self._parse_or_no_value(found), None)
yield (self._get_value_from_config(task_name, param_name), None)
if self._config_path:
yield (self._get_value_from_config(self._config_path['section'], self._config_path['name']),
'The use of the configuration [{}] {} is deprecated. Please use [{}] {}'.format(
self._config_path['section'], self._config_path['name'], task_name, param_name))
yield (self._default, None) | [
"def",
"_value_iterator",
"(",
"self",
",",
"task_name",
",",
"param_name",
")",
":",
"cp_parser",
"=",
"CmdlineParser",
".",
"get_instance",
"(",
")",
"if",
"cp_parser",
":",
"dest",
"=",
"self",
".",
"_parser_global_dest",
"(",
"param_name",
",",
"task_name",
")",
"found",
"=",
"getattr",
"(",
"cp_parser",
".",
"known_args",
",",
"dest",
",",
"None",
")",
"yield",
"(",
"self",
".",
"_parse_or_no_value",
"(",
"found",
")",
",",
"None",
")",
"yield",
"(",
"self",
".",
"_get_value_from_config",
"(",
"task_name",
",",
"param_name",
")",
",",
"None",
")",
"if",
"self",
".",
"_config_path",
":",
"yield",
"(",
"self",
".",
"_get_value_from_config",
"(",
"self",
".",
"_config_path",
"[",
"'section'",
"]",
",",
"self",
".",
"_config_path",
"[",
"'name'",
"]",
")",
",",
"'The use of the configuration [{}] {} is deprecated. Please use [{}] {}'",
".",
"format",
"(",
"self",
".",
"_config_path",
"[",
"'section'",
"]",
",",
"self",
".",
"_config_path",
"[",
"'name'",
"]",
",",
"task_name",
",",
"param_name",
")",
")",
"yield",
"(",
"self",
".",
"_default",
",",
"None",
")"
] | Yield the parameter values, with optional deprecation warning as second tuple value.
The parameter value will be whatever non-_no_value that is yielded first. | [
"Yield",
"the",
"parameter",
"values",
"with",
"optional",
"deprecation",
"warning",
"as",
"second",
"tuple",
"value",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L212-L228 | train |
spotify/luigi | luigi/parameter.py | Parameter._parse_list | def _parse_list(self, xs):
"""
Parse a list of values from the scheduler.
Only possible if this is_batchable() is True. This will combine the list into a single
parameter value using batch method. This should never need to be overridden.
:param xs: list of values to parse and combine
:return: the combined parsed values
"""
if not self._is_batchable():
raise NotImplementedError('No batch method found')
elif not xs:
raise ValueError('Empty parameter list passed to parse_list')
else:
return self._batch_method(map(self.parse, xs)) | python | def _parse_list(self, xs):
"""
Parse a list of values from the scheduler.
Only possible if this is_batchable() is True. This will combine the list into a single
parameter value using batch method. This should never need to be overridden.
:param xs: list of values to parse and combine
:return: the combined parsed values
"""
if not self._is_batchable():
raise NotImplementedError('No batch method found')
elif not xs:
raise ValueError('Empty parameter list passed to parse_list')
else:
return self._batch_method(map(self.parse, xs)) | [
"def",
"_parse_list",
"(",
"self",
",",
"xs",
")",
":",
"if",
"not",
"self",
".",
"_is_batchable",
"(",
")",
":",
"raise",
"NotImplementedError",
"(",
"'No batch method found'",
")",
"elif",
"not",
"xs",
":",
"raise",
"ValueError",
"(",
"'Empty parameter list passed to parse_list'",
")",
"else",
":",
"return",
"self",
".",
"_batch_method",
"(",
"map",
"(",
"self",
".",
"parse",
",",
"xs",
")",
")"
] | Parse a list of values from the scheduler.
Only possible if this is_batchable() is True. This will combine the list into a single
parameter value using batch method. This should never need to be overridden.
:param xs: list of values to parse and combine
:return: the combined parsed values | [
"Parse",
"a",
"list",
"of",
"values",
"from",
"the",
"scheduler",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L255-L270 | train |
spotify/luigi | luigi/parameter.py | _DateParameterBase.parse | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | python | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | [
"def",
"parse",
"(",
"self",
",",
"s",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"s",
",",
"self",
".",
"date_format",
")",
".",
"date",
"(",
")"
] | Parses a date string formatted like ``YYYY-MM-DD``. | [
"Parses",
"a",
"date",
"string",
"formatted",
"like",
"YYYY",
"-",
"MM",
"-",
"DD",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L373-L377 | train |
spotify/luigi | luigi/parameter.py | _DateParameterBase.serialize | def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format) | python | def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format) | [
"def",
"serialize",
"(",
"self",
",",
"dt",
")",
":",
"if",
"dt",
"is",
"None",
":",
"return",
"str",
"(",
"dt",
")",
"return",
"dt",
".",
"strftime",
"(",
"self",
".",
"date_format",
")"
] | Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`. | [
"Converts",
"the",
"date",
"to",
"a",
"string",
"using",
"the",
":",
"py",
":",
"attr",
":",
"~_DateParameterBase",
".",
"date_format",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L379-L385 | train |
spotify/luigi | luigi/parameter.py | MonthParameter._add_months | def _add_months(self, date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
year = date.year + (date.month + months - 1) // 12
month = (date.month + months - 1) % 12 + 1
return datetime.date(year=year, month=month, day=1) | python | def _add_months(self, date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
year = date.year + (date.month + months - 1) // 12
month = (date.month + months - 1) % 12 + 1
return datetime.date(year=year, month=month, day=1) | [
"def",
"_add_months",
"(",
"self",
",",
"date",
",",
"months",
")",
":",
"year",
"=",
"date",
".",
"year",
"+",
"(",
"date",
".",
"month",
"+",
"months",
"-",
"1",
")",
"//",
"12",
"month",
"=",
"(",
"date",
".",
"month",
"+",
"months",
"-",
"1",
")",
"%",
"12",
"+",
"1",
"return",
"datetime",
".",
"date",
"(",
"year",
"=",
"year",
",",
"month",
"=",
"month",
",",
"day",
"=",
"1",
")"
] | Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month. | [
"Add",
"months",
"months",
"to",
"date",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L447-L457 | train |
spotify/luigi | luigi/parameter.py | _DatetimeParameterBase.normalize | def normalize(self, dt):
"""
Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`.
"""
if dt is None:
return None
dt = self._convert_to_dt(dt)
dt = dt.replace(microsecond=0) # remove microseconds, to avoid float rounding issues.
delta = (dt - self.start).total_seconds()
granularity = (self._timedelta * self.interval).total_seconds()
return dt - datetime.timedelta(seconds=delta % granularity) | python | def normalize(self, dt):
"""
Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`.
"""
if dt is None:
return None
dt = self._convert_to_dt(dt)
dt = dt.replace(microsecond=0) # remove microseconds, to avoid float rounding issues.
delta = (dt - self.start).total_seconds()
granularity = (self._timedelta * self.interval).total_seconds()
return dt - datetime.timedelta(seconds=delta % granularity) | [
"def",
"normalize",
"(",
"self",
",",
"dt",
")",
":",
"if",
"dt",
"is",
"None",
":",
"return",
"None",
"dt",
"=",
"self",
".",
"_convert_to_dt",
"(",
"dt",
")",
"dt",
"=",
"dt",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"# remove microseconds, to avoid float rounding issues.",
"delta",
"=",
"(",
"dt",
"-",
"self",
".",
"start",
")",
".",
"total_seconds",
"(",
")",
"granularity",
"=",
"(",
"self",
".",
"_timedelta",
"*",
"self",
".",
"interval",
")",
".",
"total_seconds",
"(",
")",
"return",
"dt",
"-",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"delta",
"%",
"granularity",
")"
] | Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`. | [
"Clamp",
"dt",
"to",
"every",
"Nth",
":",
"py",
":",
"attr",
":",
"~_DatetimeParameterBase",
".",
"interval",
"starting",
"at",
":",
"py",
":",
"attr",
":",
"~_DatetimeParameterBase",
".",
"start",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L544-L557 | train |
spotify/luigi | luigi/parameter.py | BoolParameter.parse | def parse(self, val):
"""
Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case.
"""
s = str(val).lower()
if s == "true":
return True
elif s == "false":
return False
else:
raise ValueError("cannot interpret '{}' as boolean".format(val)) | python | def parse(self, val):
"""
Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case.
"""
s = str(val).lower()
if s == "true":
return True
elif s == "false":
return False
else:
raise ValueError("cannot interpret '{}' as boolean".format(val)) | [
"def",
"parse",
"(",
"self",
",",
"val",
")",
":",
"s",
"=",
"str",
"(",
"val",
")",
".",
"lower",
"(",
")",
"if",
"s",
"==",
"\"true\"",
":",
"return",
"True",
"elif",
"s",
"==",
"\"false\"",
":",
"return",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"\"cannot interpret '{}' as boolean\"",
".",
"format",
"(",
"val",
")",
")"
] | Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case. | [
"Parses",
"a",
"bool",
"from",
"the",
"string",
"matching",
"true",
"or",
"false",
"ignoring",
"case",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L686-L696 | train |
spotify/luigi | luigi/parameter.py | DateIntervalParameter.parse | def parse(self, s):
"""
Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals.
"""
# TODO: can we use xml.utils.iso8601 or something similar?
from luigi import date_interval as d
for cls in [d.Year, d.Month, d.Week, d.Date, d.Custom]:
i = cls.parse(s)
if i:
return i
raise ValueError('Invalid date interval - could not be parsed') | python | def parse(self, s):
"""
Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals.
"""
# TODO: can we use xml.utils.iso8601 or something similar?
from luigi import date_interval as d
for cls in [d.Year, d.Month, d.Week, d.Date, d.Custom]:
i = cls.parse(s)
if i:
return i
raise ValueError('Invalid date interval - could not be parsed') | [
"def",
"parse",
"(",
"self",
",",
"s",
")",
":",
"# TODO: can we use xml.utils.iso8601 or something similar?",
"from",
"luigi",
"import",
"date_interval",
"as",
"d",
"for",
"cls",
"in",
"[",
"d",
".",
"Year",
",",
"d",
".",
"Month",
",",
"d",
".",
"Week",
",",
"d",
".",
"Date",
",",
"d",
".",
"Custom",
"]",
":",
"i",
"=",
"cls",
".",
"parse",
"(",
"s",
")",
"if",
"i",
":",
"return",
"i",
"raise",
"ValueError",
"(",
"'Invalid date interval - could not be parsed'",
")"
] | Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals. | [
"Parses",
"a",
":",
"py",
":",
"class",
":",
"~luigi",
".",
"date_interval",
".",
"DateInterval",
"from",
"the",
"input",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L726-L742 | train |
spotify/luigi | luigi/parameter.py | TimeDeltaParameter.parse | def parse(self, input):
"""
Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats.
"""
result = self._parseIso8601(input)
if not result:
result = self._parseSimple(input)
if result is not None:
return result
else:
raise ParameterException("Invalid time delta - could not parse %s" % input) | python | def parse(self, input):
"""
Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats.
"""
result = self._parseIso8601(input)
if not result:
result = self._parseSimple(input)
if result is not None:
return result
else:
raise ParameterException("Invalid time delta - could not parse %s" % input) | [
"def",
"parse",
"(",
"self",
",",
"input",
")",
":",
"result",
"=",
"self",
".",
"_parseIso8601",
"(",
"input",
")",
"if",
"not",
"result",
":",
"result",
"=",
"self",
".",
"_parseSimple",
"(",
"input",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"else",
":",
"raise",
"ParameterException",
"(",
"\"Invalid time delta - could not parse %s\"",
"%",
"input",
")"
] | Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats. | [
"Parses",
"a",
"time",
"delta",
"from",
"the",
"input",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L790-L802 | train |
spotify/luigi | luigi/parameter.py | TimeDeltaParameter.serialize | def serialize(self, x):
"""
Converts datetime.timedelta to a string
:param x: the value to serialize.
"""
weeks = x.days // 7
days = x.days % 7
hours = x.seconds // 3600
minutes = (x.seconds % 3600) // 60
seconds = (x.seconds % 3600) % 60
result = "{} w {} d {} h {} m {} s".format(weeks, days, hours, minutes, seconds)
return result | python | def serialize(self, x):
"""
Converts datetime.timedelta to a string
:param x: the value to serialize.
"""
weeks = x.days // 7
days = x.days % 7
hours = x.seconds // 3600
minutes = (x.seconds % 3600) // 60
seconds = (x.seconds % 3600) % 60
result = "{} w {} d {} h {} m {} s".format(weeks, days, hours, minutes, seconds)
return result | [
"def",
"serialize",
"(",
"self",
",",
"x",
")",
":",
"weeks",
"=",
"x",
".",
"days",
"//",
"7",
"days",
"=",
"x",
".",
"days",
"%",
"7",
"hours",
"=",
"x",
".",
"seconds",
"//",
"3600",
"minutes",
"=",
"(",
"x",
".",
"seconds",
"%",
"3600",
")",
"//",
"60",
"seconds",
"=",
"(",
"x",
".",
"seconds",
"%",
"3600",
")",
"%",
"60",
"result",
"=",
"\"{} w {} d {} h {} m {} s\"",
".",
"format",
"(",
"weeks",
",",
"days",
",",
"hours",
",",
"minutes",
",",
"seconds",
")",
"return",
"result"
] | Converts datetime.timedelta to a string
:param x: the value to serialize. | [
"Converts",
"datetime",
".",
"timedelta",
"to",
"a",
"string"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L804-L816 | train |
spotify/luigi | luigi/parameter.py | TupleParameter.parse | def parse(self, x):
"""
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value.
"""
# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case.
# A tuple string may come from a config file or from cli execution.
# t = ((1, 2), (3, 4))
# t_str = '((1,2),(3,4))'
# t_json_str = json.dumps(t)
# t_json_str == '[[1, 2], [3, 4]]'
# json.loads(t_json_str) == t
# json.loads(t_str) == ValueError: No JSON object could be decoded
# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).
# ast.literal_eval(t_str) == t
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except (ValueError, TypeError):
return tuple(literal_eval(x)) | python | def parse(self, x):
"""
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value.
"""
# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case.
# A tuple string may come from a config file or from cli execution.
# t = ((1, 2), (3, 4))
# t_str = '((1,2),(3,4))'
# t_json_str = json.dumps(t)
# t_json_str == '[[1, 2], [3, 4]]'
# json.loads(t_json_str) == t
# json.loads(t_str) == ValueError: No JSON object could be decoded
# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).
# ast.literal_eval(t_str) == t
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except (ValueError, TypeError):
return tuple(literal_eval(x)) | [
"def",
"parse",
"(",
"self",
",",
"x",
")",
":",
"# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case.",
"# A tuple string may come from a config file or from cli execution.",
"# t = ((1, 2), (3, 4))",
"# t_str = '((1,2),(3,4))'",
"# t_json_str = json.dumps(t)",
"# t_json_str == '[[1, 2], [3, 4]]'",
"# json.loads(t_json_str) == t",
"# json.loads(t_str) == ValueError: No JSON object could be decoded",
"# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).",
"# ast.literal_eval(t_str) == t",
"try",
":",
"# loop required to parse tuple of tuples",
"return",
"tuple",
"(",
"tuple",
"(",
"x",
")",
"for",
"x",
"in",
"json",
".",
"loads",
"(",
"x",
",",
"object_pairs_hook",
"=",
"_FrozenOrderedDict",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"tuple",
"(",
"literal_eval",
"(",
"x",
")",
")"
] | Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value. | [
"Parse",
"an",
"individual",
"value",
"from",
"the",
"input",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L1096-L1119 | train |
spotify/luigi | examples/wordcount.py | WordCount.run | def run(self):
"""
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
"""
count = {}
# NOTE: self.input() actually returns an element for the InputText.output() target
for f in self.input(): # The input() method is a wrapper around requires() that returns Target objects
for line in f.open('r'): # Target objects are a file system/format abstraction and this will return a file stream object
for word in line.strip().split():
count[word] = count.get(word, 0) + 1
# output data
f = self.output().open('w')
for word, count in six.iteritems(count):
f.write("%s\t%d\n" % (word, count))
f.close() | python | def run(self):
"""
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
"""
count = {}
# NOTE: self.input() actually returns an element for the InputText.output() target
for f in self.input(): # The input() method is a wrapper around requires() that returns Target objects
for line in f.open('r'): # Target objects are a file system/format abstraction and this will return a file stream object
for word in line.strip().split():
count[word] = count.get(word, 0) + 1
# output data
f = self.output().open('w')
for word, count in six.iteritems(count):
f.write("%s\t%d\n" % (word, count))
f.close() | [
"def",
"run",
"(",
"self",
")",
":",
"count",
"=",
"{",
"}",
"# NOTE: self.input() actually returns an element for the InputText.output() target",
"for",
"f",
"in",
"self",
".",
"input",
"(",
")",
":",
"# The input() method is a wrapper around requires() that returns Target objects",
"for",
"line",
"in",
"f",
".",
"open",
"(",
"'r'",
")",
":",
"# Target objects are a file system/format abstraction and this will return a file stream object",
"for",
"word",
"in",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
":",
"count",
"[",
"word",
"]",
"=",
"count",
".",
"get",
"(",
"word",
",",
"0",
")",
"+",
"1",
"# output data",
"f",
"=",
"self",
".",
"output",
"(",
")",
".",
"open",
"(",
"'w'",
")",
"for",
"word",
",",
"count",
"in",
"six",
".",
"iteritems",
"(",
"count",
")",
":",
"f",
".",
"write",
"(",
"\"%s\\t%d\\n\"",
"%",
"(",
"word",
",",
"count",
")",
")",
"f",
".",
"close",
"(",
")"
] | 1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target | [
"1",
".",
"count",
"the",
"words",
"for",
"each",
"of",
"the",
":",
"py",
":",
"meth",
":",
"~",
".",
"InputText",
".",
"output",
"targets",
"created",
"by",
":",
"py",
":",
"class",
":",
"~",
".",
"InputText",
"2",
".",
"write",
"the",
"count",
"into",
"the",
":",
"py",
":",
"meth",
":",
"~",
".",
"WordCount",
".",
"output",
"target"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/wordcount.py#L63-L80 | train |
spotify/luigi | luigi/contrib/hadoop.py | create_packages_archive | def create_packages_archive(packages, filename):
"""
Create a tar archive which will contain the files for the packages listed in packages.
"""
import tarfile
tar = tarfile.open(filename, "w")
def add(src, dst):
logger.debug('adding to tar: %s -> %s', src, dst)
tar.add(src, dst)
def add_files_for_package(sub_package_path, root_package_path, root_package_name):
for root, dirs, files in os.walk(sub_package_path):
if '.svn' in dirs:
dirs.remove('.svn')
for f in files:
if not f.endswith(".pyc") and not f.startswith("."):
add(dereference(root + "/" + f), root.replace(root_package_path, root_package_name) + "/" + f)
for package in packages:
# Put a submodule's entire package in the archive. This is the
# magic that usually packages everything you need without
# having to attach packages/modules explicitly
if not getattr(package, "__path__", None) and '.' in package.__name__:
package = __import__(package.__name__.rpartition('.')[0], None, None, 'non_empty')
n = package.__name__.replace(".", "/")
if getattr(package, "__path__", None):
# TODO: (BUG) picking only the first path does not
# properly deal with namespaced packages in different
# directories
p = package.__path__[0]
if p.endswith('.egg') and os.path.isfile(p):
raise 'egg files not supported!!!'
# Add the entire egg file
# p = p[:p.find('.egg') + 4]
# add(dereference(p), os.path.basename(p))
else:
# include __init__ files from parent projects
root = []
for parent in package.__name__.split('.')[0:-1]:
root.append(parent)
module_name = '.'.join(root)
directory = '/'.join(root)
add(dereference(__import__(module_name, None, None, 'non_empty').__path__[0] + "/__init__.py"),
directory + "/__init__.py")
add_files_for_package(p, p, n)
# include egg-info directories that are parallel:
for egg_info_path in glob.glob(p + '*.egg-info'):
logger.debug(
'Adding package metadata to archive for "%s" found at "%s"',
package.__name__,
egg_info_path
)
add_files_for_package(egg_info_path, p, n)
else:
f = package.__file__
if f.endswith("pyc"):
f = f[:-3] + "py"
if n.find(".") == -1:
add(dereference(f), os.path.basename(f))
else:
add(dereference(f), n + ".py")
tar.close() | python | def create_packages_archive(packages, filename):
"""
Create a tar archive which will contain the files for the packages listed in packages.
"""
import tarfile
tar = tarfile.open(filename, "w")
def add(src, dst):
logger.debug('adding to tar: %s -> %s', src, dst)
tar.add(src, dst)
def add_files_for_package(sub_package_path, root_package_path, root_package_name):
for root, dirs, files in os.walk(sub_package_path):
if '.svn' in dirs:
dirs.remove('.svn')
for f in files:
if not f.endswith(".pyc") and not f.startswith("."):
add(dereference(root + "/" + f), root.replace(root_package_path, root_package_name) + "/" + f)
for package in packages:
# Put a submodule's entire package in the archive. This is the
# magic that usually packages everything you need without
# having to attach packages/modules explicitly
if not getattr(package, "__path__", None) and '.' in package.__name__:
package = __import__(package.__name__.rpartition('.')[0], None, None, 'non_empty')
n = package.__name__.replace(".", "/")
if getattr(package, "__path__", None):
# TODO: (BUG) picking only the first path does not
# properly deal with namespaced packages in different
# directories
p = package.__path__[0]
if p.endswith('.egg') and os.path.isfile(p):
raise 'egg files not supported!!!'
# Add the entire egg file
# p = p[:p.find('.egg') + 4]
# add(dereference(p), os.path.basename(p))
else:
# include __init__ files from parent projects
root = []
for parent in package.__name__.split('.')[0:-1]:
root.append(parent)
module_name = '.'.join(root)
directory = '/'.join(root)
add(dereference(__import__(module_name, None, None, 'non_empty').__path__[0] + "/__init__.py"),
directory + "/__init__.py")
add_files_for_package(p, p, n)
# include egg-info directories that are parallel:
for egg_info_path in glob.glob(p + '*.egg-info'):
logger.debug(
'Adding package metadata to archive for "%s" found at "%s"',
package.__name__,
egg_info_path
)
add_files_for_package(egg_info_path, p, n)
else:
f = package.__file__
if f.endswith("pyc"):
f = f[:-3] + "py"
if n.find(".") == -1:
add(dereference(f), os.path.basename(f))
else:
add(dereference(f), n + ".py")
tar.close() | [
"def",
"create_packages_archive",
"(",
"packages",
",",
"filename",
")",
":",
"import",
"tarfile",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"def",
"add",
"(",
"src",
",",
"dst",
")",
":",
"logger",
".",
"debug",
"(",
"'adding to tar: %s -> %s'",
",",
"src",
",",
"dst",
")",
"tar",
".",
"add",
"(",
"src",
",",
"dst",
")",
"def",
"add_files_for_package",
"(",
"sub_package_path",
",",
"root_package_path",
",",
"root_package_name",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"sub_package_path",
")",
":",
"if",
"'.svn'",
"in",
"dirs",
":",
"dirs",
".",
"remove",
"(",
"'.svn'",
")",
"for",
"f",
"in",
"files",
":",
"if",
"not",
"f",
".",
"endswith",
"(",
"\".pyc\"",
")",
"and",
"not",
"f",
".",
"startswith",
"(",
"\".\"",
")",
":",
"add",
"(",
"dereference",
"(",
"root",
"+",
"\"/\"",
"+",
"f",
")",
",",
"root",
".",
"replace",
"(",
"root_package_path",
",",
"root_package_name",
")",
"+",
"\"/\"",
"+",
"f",
")",
"for",
"package",
"in",
"packages",
":",
"# Put a submodule's entire package in the archive. This is the",
"# magic that usually packages everything you need without",
"# having to attach packages/modules explicitly",
"if",
"not",
"getattr",
"(",
"package",
",",
"\"__path__\"",
",",
"None",
")",
"and",
"'.'",
"in",
"package",
".",
"__name__",
":",
"package",
"=",
"__import__",
"(",
"package",
".",
"__name__",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"0",
"]",
",",
"None",
",",
"None",
",",
"'non_empty'",
")",
"n",
"=",
"package",
".",
"__name__",
".",
"replace",
"(",
"\".\"",
",",
"\"/\"",
")",
"if",
"getattr",
"(",
"package",
",",
"\"__path__\"",
",",
"None",
")",
":",
"# TODO: (BUG) picking only the first path does not",
"# properly deal with namespaced packages in different",
"# directories",
"p",
"=",
"package",
".",
"__path__",
"[",
"0",
"]",
"if",
"p",
".",
"endswith",
"(",
"'.egg'",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"p",
")",
":",
"raise",
"'egg files not supported!!!'",
"# Add the entire egg file",
"# p = p[:p.find('.egg') + 4]",
"# add(dereference(p), os.path.basename(p))",
"else",
":",
"# include __init__ files from parent projects",
"root",
"=",
"[",
"]",
"for",
"parent",
"in",
"package",
".",
"__name__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
":",
"-",
"1",
"]",
":",
"root",
".",
"append",
"(",
"parent",
")",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"root",
")",
"directory",
"=",
"'/'",
".",
"join",
"(",
"root",
")",
"add",
"(",
"dereference",
"(",
"__import__",
"(",
"module_name",
",",
"None",
",",
"None",
",",
"'non_empty'",
")",
".",
"__path__",
"[",
"0",
"]",
"+",
"\"/__init__.py\"",
")",
",",
"directory",
"+",
"\"/__init__.py\"",
")",
"add_files_for_package",
"(",
"p",
",",
"p",
",",
"n",
")",
"# include egg-info directories that are parallel:",
"for",
"egg_info_path",
"in",
"glob",
".",
"glob",
"(",
"p",
"+",
"'*.egg-info'",
")",
":",
"logger",
".",
"debug",
"(",
"'Adding package metadata to archive for \"%s\" found at \"%s\"'",
",",
"package",
".",
"__name__",
",",
"egg_info_path",
")",
"add_files_for_package",
"(",
"egg_info_path",
",",
"p",
",",
"n",
")",
"else",
":",
"f",
"=",
"package",
".",
"__file__",
"if",
"f",
".",
"endswith",
"(",
"\"pyc\"",
")",
":",
"f",
"=",
"f",
"[",
":",
"-",
"3",
"]",
"+",
"\"py\"",
"if",
"n",
".",
"find",
"(",
"\".\"",
")",
"==",
"-",
"1",
":",
"add",
"(",
"dereference",
"(",
"f",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"else",
":",
"add",
"(",
"dereference",
"(",
"f",
")",
",",
"n",
"+",
"\".py\"",
")",
"tar",
".",
"close",
"(",
")"
] | Create a tar archive which will contain the files for the packages listed in packages. | [
"Create",
"a",
"tar",
"archive",
"which",
"will",
"contain",
"the",
"files",
"for",
"the",
"packages",
"listed",
"in",
"packages",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L124-L194 | train |
spotify/luigi | luigi/contrib/hadoop.py | flatten | def flatten(sequence):
"""
A simple generator which flattens a sequence.
Only one level is flattened.
.. code-block:: python
(1, (2, 3), 4) -> (1, 2, 3, 4)
"""
for item in sequence:
if hasattr(item, "__iter__") and not isinstance(item, str) and not isinstance(item, bytes):
for i in item:
yield i
else:
yield item | python | def flatten(sequence):
"""
A simple generator which flattens a sequence.
Only one level is flattened.
.. code-block:: python
(1, (2, 3), 4) -> (1, 2, 3, 4)
"""
for item in sequence:
if hasattr(item, "__iter__") and not isinstance(item, str) and not isinstance(item, bytes):
for i in item:
yield i
else:
yield item | [
"def",
"flatten",
"(",
"sequence",
")",
":",
"for",
"item",
"in",
"sequence",
":",
"if",
"hasattr",
"(",
"item",
",",
"\"__iter__\"",
")",
"and",
"not",
"isinstance",
"(",
"item",
",",
"str",
")",
"and",
"not",
"isinstance",
"(",
"item",
",",
"bytes",
")",
":",
"for",
"i",
"in",
"item",
":",
"yield",
"i",
"else",
":",
"yield",
"item"
] | A simple generator which flattens a sequence.
Only one level is flattened.
.. code-block:: python
(1, (2, 3), 4) -> (1, 2, 3, 4) | [
"A",
"simple",
"generator",
"which",
"flattens",
"a",
"sequence",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L197-L213 | train |
spotify/luigi | luigi/contrib/hadoop.py | run_and_track_hadoop_job | def run_and_track_hadoop_job(arglist, tracking_url_callback=None, env=None):
"""
Runs the job by invoking the command from the given arglist.
Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails.
Throws HadoopJobError with information about the error
(including stdout and stderr from the process)
on failure and returns normally otherwise.
:param arglist:
:param tracking_url_callback:
:param env:
:return:
"""
logger.info('%s', subprocess.list2cmdline(arglist))
def write_luigi_history(arglist, history):
"""
Writes history to a file in the job's output directory in JSON format.
Currently just for tracking the job ID in a configuration where
no history is stored in the output directory by Hadoop.
"""
history_filename = configuration.get_config().get('core', 'history-filename', '')
if history_filename and '-output' in arglist:
output_dir = arglist[arglist.index('-output') + 1]
f = luigi.contrib.hdfs.HdfsTarget(os.path.join(output_dir, history_filename)).open('w')
f.write(json.dumps(history))
f.close()
def track_process(arglist, tracking_url_callback, env=None):
# Dump stdout to a temp file, poll stderr and log it
temp_stdout = tempfile.TemporaryFile('w+t')
proc = subprocess.Popen(arglist, stdout=temp_stdout, stderr=subprocess.PIPE, env=env, close_fds=True, universal_newlines=True)
# We parse the output to try to find the tracking URL.
# This URL is useful for fetching the logs of the job.
tracking_url = None
job_id = None
application_id = None
err_lines = []
with HadoopRunContext() as hadoop_context:
while proc.poll() is None:
err_line = proc.stderr.readline()
err_lines.append(err_line)
err_line = err_line.strip()
if err_line:
logger.info('%s', err_line)
err_line = err_line.lower()
tracking_url_match = TRACKING_RE.search(err_line)
if tracking_url_match:
tracking_url = tracking_url_match.group('url')
try:
tracking_url_callback(tracking_url)
except Exception as e:
logger.error("Error in tracking_url_callback, disabling! %s", e)
def tracking_url_callback(x):
return None
if err_line.find('running job') != -1:
# hadoop jar output
job_id = err_line.split('running job: ')[-1]
if err_line.find('submitted hadoop job:') != -1:
# scalding output
job_id = err_line.split('submitted hadoop job: ')[-1]
if err_line.find('submitted application ') != -1:
application_id = err_line.split('submitted application ')[-1]
hadoop_context.job_id = job_id
hadoop_context.application_id = application_id
# Read the rest + stdout
err = ''.join(err_lines + [an_err_line for an_err_line in proc.stderr])
temp_stdout.seek(0)
out = ''.join(temp_stdout.readlines())
if proc.returncode == 0:
write_luigi_history(arglist, {'job_id': job_id})
return (out, err)
# Try to fetch error logs if possible
message = 'Streaming job failed with exit code %d. ' % proc.returncode
if not tracking_url:
raise HadoopJobError(message + 'Also, no tracking url found.', out, err)
try:
task_failures = fetch_task_failures(tracking_url)
except Exception as e:
raise HadoopJobError(message + 'Additionally, an error occurred when fetching data from %s: %s' %
(tracking_url, e), out, err)
if not task_failures:
raise HadoopJobError(message + 'Also, could not fetch output from tasks.', out, err)
else:
raise HadoopJobError(message + 'Output from tasks below:\n%s' % task_failures, out, err)
if tracking_url_callback is None:
def tracking_url_callback(x): return None
return track_process(arglist, tracking_url_callback, env) | python | def run_and_track_hadoop_job(arglist, tracking_url_callback=None, env=None):
"""
Runs the job by invoking the command from the given arglist.
Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails.
Throws HadoopJobError with information about the error
(including stdout and stderr from the process)
on failure and returns normally otherwise.
:param arglist:
:param tracking_url_callback:
:param env:
:return:
"""
logger.info('%s', subprocess.list2cmdline(arglist))
def write_luigi_history(arglist, history):
"""
Writes history to a file in the job's output directory in JSON format.
Currently just for tracking the job ID in a configuration where
no history is stored in the output directory by Hadoop.
"""
history_filename = configuration.get_config().get('core', 'history-filename', '')
if history_filename and '-output' in arglist:
output_dir = arglist[arglist.index('-output') + 1]
f = luigi.contrib.hdfs.HdfsTarget(os.path.join(output_dir, history_filename)).open('w')
f.write(json.dumps(history))
f.close()
def track_process(arglist, tracking_url_callback, env=None):
# Dump stdout to a temp file, poll stderr and log it
temp_stdout = tempfile.TemporaryFile('w+t')
proc = subprocess.Popen(arglist, stdout=temp_stdout, stderr=subprocess.PIPE, env=env, close_fds=True, universal_newlines=True)
# We parse the output to try to find the tracking URL.
# This URL is useful for fetching the logs of the job.
tracking_url = None
job_id = None
application_id = None
err_lines = []
with HadoopRunContext() as hadoop_context:
while proc.poll() is None:
err_line = proc.stderr.readline()
err_lines.append(err_line)
err_line = err_line.strip()
if err_line:
logger.info('%s', err_line)
err_line = err_line.lower()
tracking_url_match = TRACKING_RE.search(err_line)
if tracking_url_match:
tracking_url = tracking_url_match.group('url')
try:
tracking_url_callback(tracking_url)
except Exception as e:
logger.error("Error in tracking_url_callback, disabling! %s", e)
def tracking_url_callback(x):
return None
if err_line.find('running job') != -1:
# hadoop jar output
job_id = err_line.split('running job: ')[-1]
if err_line.find('submitted hadoop job:') != -1:
# scalding output
job_id = err_line.split('submitted hadoop job: ')[-1]
if err_line.find('submitted application ') != -1:
application_id = err_line.split('submitted application ')[-1]
hadoop_context.job_id = job_id
hadoop_context.application_id = application_id
# Read the rest + stdout
err = ''.join(err_lines + [an_err_line for an_err_line in proc.stderr])
temp_stdout.seek(0)
out = ''.join(temp_stdout.readlines())
if proc.returncode == 0:
write_luigi_history(arglist, {'job_id': job_id})
return (out, err)
# Try to fetch error logs if possible
message = 'Streaming job failed with exit code %d. ' % proc.returncode
if not tracking_url:
raise HadoopJobError(message + 'Also, no tracking url found.', out, err)
try:
task_failures = fetch_task_failures(tracking_url)
except Exception as e:
raise HadoopJobError(message + 'Additionally, an error occurred when fetching data from %s: %s' %
(tracking_url, e), out, err)
if not task_failures:
raise HadoopJobError(message + 'Also, could not fetch output from tasks.', out, err)
else:
raise HadoopJobError(message + 'Output from tasks below:\n%s' % task_failures, out, err)
if tracking_url_callback is None:
def tracking_url_callback(x): return None
return track_process(arglist, tracking_url_callback, env) | [
"def",
"run_and_track_hadoop_job",
"(",
"arglist",
",",
"tracking_url_callback",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'%s'",
",",
"subprocess",
".",
"list2cmdline",
"(",
"arglist",
")",
")",
"def",
"write_luigi_history",
"(",
"arglist",
",",
"history",
")",
":",
"\"\"\"\n Writes history to a file in the job's output directory in JSON format.\n Currently just for tracking the job ID in a configuration where\n no history is stored in the output directory by Hadoop.\n \"\"\"",
"history_filename",
"=",
"configuration",
".",
"get_config",
"(",
")",
".",
"get",
"(",
"'core'",
",",
"'history-filename'",
",",
"''",
")",
"if",
"history_filename",
"and",
"'-output'",
"in",
"arglist",
":",
"output_dir",
"=",
"arglist",
"[",
"arglist",
".",
"index",
"(",
"'-output'",
")",
"+",
"1",
"]",
"f",
"=",
"luigi",
".",
"contrib",
".",
"hdfs",
".",
"HdfsTarget",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"history_filename",
")",
")",
".",
"open",
"(",
"'w'",
")",
"f",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"history",
")",
")",
"f",
".",
"close",
"(",
")",
"def",
"track_process",
"(",
"arglist",
",",
"tracking_url_callback",
",",
"env",
"=",
"None",
")",
":",
"# Dump stdout to a temp file, poll stderr and log it",
"temp_stdout",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"'w+t'",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"arglist",
",",
"stdout",
"=",
"temp_stdout",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"env",
"=",
"env",
",",
"close_fds",
"=",
"True",
",",
"universal_newlines",
"=",
"True",
")",
"# We parse the output to try to find the tracking URL.",
"# This URL is useful for fetching the logs of the job.",
"tracking_url",
"=",
"None",
"job_id",
"=",
"None",
"application_id",
"=",
"None",
"err_lines",
"=",
"[",
"]",
"with",
"HadoopRunContext",
"(",
")",
"as",
"hadoop_context",
":",
"while",
"proc",
".",
"poll",
"(",
")",
"is",
"None",
":",
"err_line",
"=",
"proc",
".",
"stderr",
".",
"readline",
"(",
")",
"err_lines",
".",
"append",
"(",
"err_line",
")",
"err_line",
"=",
"err_line",
".",
"strip",
"(",
")",
"if",
"err_line",
":",
"logger",
".",
"info",
"(",
"'%s'",
",",
"err_line",
")",
"err_line",
"=",
"err_line",
".",
"lower",
"(",
")",
"tracking_url_match",
"=",
"TRACKING_RE",
".",
"search",
"(",
"err_line",
")",
"if",
"tracking_url_match",
":",
"tracking_url",
"=",
"tracking_url_match",
".",
"group",
"(",
"'url'",
")",
"try",
":",
"tracking_url_callback",
"(",
"tracking_url",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Error in tracking_url_callback, disabling! %s\"",
",",
"e",
")",
"def",
"tracking_url_callback",
"(",
"x",
")",
":",
"return",
"None",
"if",
"err_line",
".",
"find",
"(",
"'running job'",
")",
"!=",
"-",
"1",
":",
"# hadoop jar output",
"job_id",
"=",
"err_line",
".",
"split",
"(",
"'running job: '",
")",
"[",
"-",
"1",
"]",
"if",
"err_line",
".",
"find",
"(",
"'submitted hadoop job:'",
")",
"!=",
"-",
"1",
":",
"# scalding output",
"job_id",
"=",
"err_line",
".",
"split",
"(",
"'submitted hadoop job: '",
")",
"[",
"-",
"1",
"]",
"if",
"err_line",
".",
"find",
"(",
"'submitted application '",
")",
"!=",
"-",
"1",
":",
"application_id",
"=",
"err_line",
".",
"split",
"(",
"'submitted application '",
")",
"[",
"-",
"1",
"]",
"hadoop_context",
".",
"job_id",
"=",
"job_id",
"hadoop_context",
".",
"application_id",
"=",
"application_id",
"# Read the rest + stdout",
"err",
"=",
"''",
".",
"join",
"(",
"err_lines",
"+",
"[",
"an_err_line",
"for",
"an_err_line",
"in",
"proc",
".",
"stderr",
"]",
")",
"temp_stdout",
".",
"seek",
"(",
"0",
")",
"out",
"=",
"''",
".",
"join",
"(",
"temp_stdout",
".",
"readlines",
"(",
")",
")",
"if",
"proc",
".",
"returncode",
"==",
"0",
":",
"write_luigi_history",
"(",
"arglist",
",",
"{",
"'job_id'",
":",
"job_id",
"}",
")",
"return",
"(",
"out",
",",
"err",
")",
"# Try to fetch error logs if possible",
"message",
"=",
"'Streaming job failed with exit code %d. '",
"%",
"proc",
".",
"returncode",
"if",
"not",
"tracking_url",
":",
"raise",
"HadoopJobError",
"(",
"message",
"+",
"'Also, no tracking url found.'",
",",
"out",
",",
"err",
")",
"try",
":",
"task_failures",
"=",
"fetch_task_failures",
"(",
"tracking_url",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"HadoopJobError",
"(",
"message",
"+",
"'Additionally, an error occurred when fetching data from %s: %s'",
"%",
"(",
"tracking_url",
",",
"e",
")",
",",
"out",
",",
"err",
")",
"if",
"not",
"task_failures",
":",
"raise",
"HadoopJobError",
"(",
"message",
"+",
"'Also, could not fetch output from tasks.'",
",",
"out",
",",
"err",
")",
"else",
":",
"raise",
"HadoopJobError",
"(",
"message",
"+",
"'Output from tasks below:\\n%s'",
"%",
"task_failures",
",",
"out",
",",
"err",
")",
"if",
"tracking_url_callback",
"is",
"None",
":",
"def",
"tracking_url_callback",
"(",
"x",
")",
":",
"return",
"None",
"return",
"track_process",
"(",
"arglist",
",",
"tracking_url_callback",
",",
"env",
")"
] | Runs the job by invoking the command from the given arglist.
Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails.
Throws HadoopJobError with information about the error
(including stdout and stderr from the process)
on failure and returns normally otherwise.
:param arglist:
:param tracking_url_callback:
:param env:
:return: | [
"Runs",
"the",
"job",
"by",
"invoking",
"the",
"command",
"from",
"the",
"given",
"arglist",
".",
"Finds",
"tracking",
"urls",
"from",
"the",
"output",
"and",
"attempts",
"to",
"fetch",
"errors",
"using",
"those",
"urls",
"if",
"the",
"job",
"fails",
".",
"Throws",
"HadoopJobError",
"with",
"information",
"about",
"the",
"error",
"(",
"including",
"stdout",
"and",
"stderr",
"from",
"the",
"process",
")",
"on",
"failure",
"and",
"returns",
"normally",
"otherwise",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L256-L353 | train |
spotify/luigi | luigi/contrib/hadoop.py | fetch_task_failures | def fetch_task_failures(tracking_url):
"""
Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we should probably use instead:
http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html
"""
import mechanize
timeout = 3.0
failures_url = tracking_url.replace('jobdetails.jsp', 'jobfailures.jsp') + '&cause=failed'
logger.debug('Fetching data from %s', failures_url)
b = mechanize.Browser()
b.open(failures_url, timeout=timeout)
links = list(b.links(text_regex='Last 4KB')) # For some reason text_regex='All' doesn't work... no idea why
links = random.sample(links, min(10, len(links))) # Fetch a random subset of all failed tasks, so not to be biased towards the early fails
error_text = []
for link in links:
task_url = link.url.replace('&start=-4097', '&start=-100000') # Increase the offset
logger.debug('Fetching data from %s', task_url)
b2 = mechanize.Browser()
try:
r = b2.open(task_url, timeout=timeout)
data = r.read()
except Exception as e:
logger.debug('Error fetching data from %s: %s', task_url, e)
continue
# Try to get the hex-encoded traceback back from the output
for exc in re.findall(r'luigi-exc-hex=[0-9a-f]+', data):
error_text.append('---------- %s:' % task_url)
error_text.append(exc.split('=')[-1].decode('hex'))
return '\n'.join(error_text) | python | def fetch_task_failures(tracking_url):
"""
Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we should probably use instead:
http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html
"""
import mechanize
timeout = 3.0
failures_url = tracking_url.replace('jobdetails.jsp', 'jobfailures.jsp') + '&cause=failed'
logger.debug('Fetching data from %s', failures_url)
b = mechanize.Browser()
b.open(failures_url, timeout=timeout)
links = list(b.links(text_regex='Last 4KB')) # For some reason text_regex='All' doesn't work... no idea why
links = random.sample(links, min(10, len(links))) # Fetch a random subset of all failed tasks, so not to be biased towards the early fails
error_text = []
for link in links:
task_url = link.url.replace('&start=-4097', '&start=-100000') # Increase the offset
logger.debug('Fetching data from %s', task_url)
b2 = mechanize.Browser()
try:
r = b2.open(task_url, timeout=timeout)
data = r.read()
except Exception as e:
logger.debug('Error fetching data from %s: %s', task_url, e)
continue
# Try to get the hex-encoded traceback back from the output
for exc in re.findall(r'luigi-exc-hex=[0-9a-f]+', data):
error_text.append('---------- %s:' % task_url)
error_text.append(exc.split('=')[-1].decode('hex'))
return '\n'.join(error_text) | [
"def",
"fetch_task_failures",
"(",
"tracking_url",
")",
":",
"import",
"mechanize",
"timeout",
"=",
"3.0",
"failures_url",
"=",
"tracking_url",
".",
"replace",
"(",
"'jobdetails.jsp'",
",",
"'jobfailures.jsp'",
")",
"+",
"'&cause=failed'",
"logger",
".",
"debug",
"(",
"'Fetching data from %s'",
",",
"failures_url",
")",
"b",
"=",
"mechanize",
".",
"Browser",
"(",
")",
"b",
".",
"open",
"(",
"failures_url",
",",
"timeout",
"=",
"timeout",
")",
"links",
"=",
"list",
"(",
"b",
".",
"links",
"(",
"text_regex",
"=",
"'Last 4KB'",
")",
")",
"# For some reason text_regex='All' doesn't work... no idea why",
"links",
"=",
"random",
".",
"sample",
"(",
"links",
",",
"min",
"(",
"10",
",",
"len",
"(",
"links",
")",
")",
")",
"# Fetch a random subset of all failed tasks, so not to be biased towards the early fails",
"error_text",
"=",
"[",
"]",
"for",
"link",
"in",
"links",
":",
"task_url",
"=",
"link",
".",
"url",
".",
"replace",
"(",
"'&start=-4097'",
",",
"'&start=-100000'",
")",
"# Increase the offset",
"logger",
".",
"debug",
"(",
"'Fetching data from %s'",
",",
"task_url",
")",
"b2",
"=",
"mechanize",
".",
"Browser",
"(",
")",
"try",
":",
"r",
"=",
"b2",
".",
"open",
"(",
"task_url",
",",
"timeout",
"=",
"timeout",
")",
"data",
"=",
"r",
".",
"read",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"'Error fetching data from %s: %s'",
",",
"task_url",
",",
"e",
")",
"continue",
"# Try to get the hex-encoded traceback back from the output",
"for",
"exc",
"in",
"re",
".",
"findall",
"(",
"r'luigi-exc-hex=[0-9a-f]+'",
",",
"data",
")",
":",
"error_text",
".",
"append",
"(",
"'---------- %s:'",
"%",
"task_url",
")",
"error_text",
".",
"append",
"(",
"exc",
".",
"split",
"(",
"'='",
")",
"[",
"-",
"1",
"]",
".",
"decode",
"(",
"'hex'",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"error_text",
")"
] | Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we should probably use instead:
http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html | [
"Uses",
"mechanize",
"to",
"fetch",
"the",
"actual",
"task",
"logs",
"from",
"the",
"task",
"tracker",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L356-L391 | train |
spotify/luigi | luigi/contrib/hadoop.py | BaseHadoopJobTask._get_pool | def _get_pool(self):
""" Protected method """
if self.pool:
return self.pool
if hadoop().pool:
return hadoop().pool | python | def _get_pool(self):
""" Protected method """
if self.pool:
return self.pool
if hadoop().pool:
return hadoop().pool | [
"def",
"_get_pool",
"(",
"self",
")",
":",
"if",
"self",
".",
"pool",
":",
"return",
"self",
".",
"pool",
"if",
"hadoop",
"(",
")",
".",
"pool",
":",
"return",
"hadoop",
"(",
")",
".",
"pool"
] | Protected method | [
"Protected",
"method"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L688-L693 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.job_runner | def job_runner(self):
# We recommend that you define a subclass, override this method and set up your own config
"""
Get the MapReduce runner for this job.
If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.
Otherwise, the LocalJobRunner which streams all data through the local machine
will be used (great for testing).
"""
outputs = luigi.task.flatten(self.output())
for output in outputs:
if not isinstance(output, luigi.contrib.hdfs.HdfsTarget):
warnings.warn("Job is using one or more non-HdfsTarget outputs" +
" so it will be run in local mode")
return LocalJobRunner()
else:
return DefaultHadoopJobRunner() | python | def job_runner(self):
# We recommend that you define a subclass, override this method and set up your own config
"""
Get the MapReduce runner for this job.
If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.
Otherwise, the LocalJobRunner which streams all data through the local machine
will be used (great for testing).
"""
outputs = luigi.task.flatten(self.output())
for output in outputs:
if not isinstance(output, luigi.contrib.hdfs.HdfsTarget):
warnings.warn("Job is using one or more non-HdfsTarget outputs" +
" so it will be run in local mode")
return LocalJobRunner()
else:
return DefaultHadoopJobRunner() | [
"def",
"job_runner",
"(",
"self",
")",
":",
"# We recommend that you define a subclass, override this method and set up your own config",
"outputs",
"=",
"luigi",
".",
"task",
".",
"flatten",
"(",
"self",
".",
"output",
"(",
")",
")",
"for",
"output",
"in",
"outputs",
":",
"if",
"not",
"isinstance",
"(",
"output",
",",
"luigi",
".",
"contrib",
".",
"hdfs",
".",
"HdfsTarget",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Job is using one or more non-HdfsTarget outputs\"",
"+",
"\" so it will be run in local mode\"",
")",
"return",
"LocalJobRunner",
"(",
")",
"else",
":",
"return",
"DefaultHadoopJobRunner",
"(",
")"
] | Get the MapReduce runner for this job.
If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.
Otherwise, the LocalJobRunner which streams all data through the local machine
will be used (great for testing). | [
"Get",
"the",
"MapReduce",
"runner",
"for",
"this",
"job",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L813-L829 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.writer | def writer(self, outputs, stdout, stderr=sys.stderr):
"""
Writer format is a method which iterates over the output records
from the reducer and formats them for output.
The default implementation outputs tab separated items.
"""
for output in outputs:
try:
output = flatten(output)
if self.data_interchange_format == "json":
# Only dump one json string, and skip another one, maybe key or value.
output = filter(lambda x: x, output)
else:
# JSON is already serialized, so we put `self.serialize` in a else statement.
output = map(self.serialize, output)
print("\t".join(output), file=stdout)
except BaseException:
print(output, file=stderr)
raise | python | def writer(self, outputs, stdout, stderr=sys.stderr):
"""
Writer format is a method which iterates over the output records
from the reducer and formats them for output.
The default implementation outputs tab separated items.
"""
for output in outputs:
try:
output = flatten(output)
if self.data_interchange_format == "json":
# Only dump one json string, and skip another one, maybe key or value.
output = filter(lambda x: x, output)
else:
# JSON is already serialized, so we put `self.serialize` in a else statement.
output = map(self.serialize, output)
print("\t".join(output), file=stdout)
except BaseException:
print(output, file=stderr)
raise | [
"def",
"writer",
"(",
"self",
",",
"outputs",
",",
"stdout",
",",
"stderr",
"=",
"sys",
".",
"stderr",
")",
":",
"for",
"output",
"in",
"outputs",
":",
"try",
":",
"output",
"=",
"flatten",
"(",
"output",
")",
"if",
"self",
".",
"data_interchange_format",
"==",
"\"json\"",
":",
"# Only dump one json string, and skip another one, maybe key or value.",
"output",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
",",
"output",
")",
"else",
":",
"# JSON is already serialized, so we put `self.serialize` in a else statement.",
"output",
"=",
"map",
"(",
"self",
".",
"serialize",
",",
"output",
")",
"print",
"(",
"\"\\t\"",
".",
"join",
"(",
"output",
")",
",",
"file",
"=",
"stdout",
")",
"except",
"BaseException",
":",
"print",
"(",
"output",
",",
"file",
"=",
"stderr",
")",
"raise"
] | Writer format is a method which iterates over the output records
from the reducer and formats them for output.
The default implementation outputs tab separated items. | [
"Writer",
"format",
"is",
"a",
"method",
"which",
"iterates",
"over",
"the",
"output",
"records",
"from",
"the",
"reducer",
"and",
"formats",
"them",
"for",
"output",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L839-L858 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.incr_counter | def incr_counter(self, *args, **kwargs):
"""
Increments a Hadoop counter.
Since counters can be a bit slow to update, this batches the updates.
"""
threshold = kwargs.get("threshold", self.batch_counter_default)
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
group_name, count = args
key = (group_name,)
else:
group, name, count = args
key = (group, name)
ct = self._counter_dict.get(key, 0)
ct += count
if ct >= threshold:
new_arg = list(key) + [ct]
self._incr_counter(*new_arg)
ct = 0
self._counter_dict[key] = ct | python | def incr_counter(self, *args, **kwargs):
"""
Increments a Hadoop counter.
Since counters can be a bit slow to update, this batches the updates.
"""
threshold = kwargs.get("threshold", self.batch_counter_default)
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
group_name, count = args
key = (group_name,)
else:
group, name, count = args
key = (group, name)
ct = self._counter_dict.get(key, 0)
ct += count
if ct >= threshold:
new_arg = list(key) + [ct]
self._incr_counter(*new_arg)
ct = 0
self._counter_dict[key] = ct | [
"def",
"incr_counter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"threshold",
"=",
"kwargs",
".",
"get",
"(",
"\"threshold\"",
",",
"self",
".",
"batch_counter_default",
")",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"# backwards compatibility with existing hadoop jobs",
"group_name",
",",
"count",
"=",
"args",
"key",
"=",
"(",
"group_name",
",",
")",
"else",
":",
"group",
",",
"name",
",",
"count",
"=",
"args",
"key",
"=",
"(",
"group",
",",
"name",
")",
"ct",
"=",
"self",
".",
"_counter_dict",
".",
"get",
"(",
"key",
",",
"0",
")",
"ct",
"+=",
"count",
"if",
"ct",
">=",
"threshold",
":",
"new_arg",
"=",
"list",
"(",
"key",
")",
"+",
"[",
"ct",
"]",
"self",
".",
"_incr_counter",
"(",
"*",
"new_arg",
")",
"ct",
"=",
"0",
"self",
".",
"_counter_dict",
"[",
"key",
"]",
"=",
"ct"
] | Increments a Hadoop counter.
Since counters can be a bit slow to update, this batches the updates. | [
"Increments",
"a",
"Hadoop",
"counter",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L870-L891 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask._flush_batch_incr_counter | def _flush_batch_incr_counter(self):
"""
Increments any unflushed counter values.
"""
for key, count in six.iteritems(self._counter_dict):
if count == 0:
continue
args = list(key) + [count]
self._incr_counter(*args)
self._counter_dict[key] = 0 | python | def _flush_batch_incr_counter(self):
"""
Increments any unflushed counter values.
"""
for key, count in six.iteritems(self._counter_dict):
if count == 0:
continue
args = list(key) + [count]
self._incr_counter(*args)
self._counter_dict[key] = 0 | [
"def",
"_flush_batch_incr_counter",
"(",
"self",
")",
":",
"for",
"key",
",",
"count",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_counter_dict",
")",
":",
"if",
"count",
"==",
"0",
":",
"continue",
"args",
"=",
"list",
"(",
"key",
")",
"+",
"[",
"count",
"]",
"self",
".",
"_incr_counter",
"(",
"*",
"args",
")",
"self",
".",
"_counter_dict",
"[",
"key",
"]",
"=",
"0"
] | Increments any unflushed counter values. | [
"Increments",
"any",
"unflushed",
"counter",
"values",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L893-L902 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask._incr_counter | def _incr_counter(self, *args):
"""
Increments a Hadoop counter.
Note that this seems to be a bit slow, ~1 ms
Don't overuse this function by updating very frequently.
"""
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
group_name, count = args
print('reporter:counter:%s,%s' % (group_name, count), file=sys.stderr)
else:
group, name, count = args
print('reporter:counter:%s,%s,%s' % (group, name, count), file=sys.stderr) | python | def _incr_counter(self, *args):
"""
Increments a Hadoop counter.
Note that this seems to be a bit slow, ~1 ms
Don't overuse this function by updating very frequently.
"""
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
group_name, count = args
print('reporter:counter:%s,%s' % (group_name, count), file=sys.stderr)
else:
group, name, count = args
print('reporter:counter:%s,%s,%s' % (group, name, count), file=sys.stderr) | [
"def",
"_incr_counter",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"# backwards compatibility with existing hadoop jobs",
"group_name",
",",
"count",
"=",
"args",
"print",
"(",
"'reporter:counter:%s,%s'",
"%",
"(",
"group_name",
",",
"count",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"group",
",",
"name",
",",
"count",
"=",
"args",
"print",
"(",
"'reporter:counter:%s,%s,%s'",
"%",
"(",
"group",
",",
"name",
",",
"count",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | Increments a Hadoop counter.
Note that this seems to be a bit slow, ~1 ms
Don't overuse this function by updating very frequently. | [
"Increments",
"a",
"Hadoop",
"counter",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L904-L918 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.dump | def dump(self, directory=''):
"""
Dump instance to file.
"""
with self.no_unpicklable_properties():
file_name = os.path.join(directory, 'job-instance.pickle')
if self.__module__ == '__main__':
d = pickle.dumps(self)
module_name = os.path.basename(sys.argv[0]).rsplit('.', 1)[0]
d = d.replace(b'(c__main__', "(c" + module_name)
open(file_name, "wb").write(d)
else:
pickle.dump(self, open(file_name, "wb")) | python | def dump(self, directory=''):
"""
Dump instance to file.
"""
with self.no_unpicklable_properties():
file_name = os.path.join(directory, 'job-instance.pickle')
if self.__module__ == '__main__':
d = pickle.dumps(self)
module_name = os.path.basename(sys.argv[0]).rsplit('.', 1)[0]
d = d.replace(b'(c__main__', "(c" + module_name)
open(file_name, "wb").write(d)
else:
pickle.dump(self, open(file_name, "wb")) | [
"def",
"dump",
"(",
"self",
",",
"directory",
"=",
"''",
")",
":",
"with",
"self",
".",
"no_unpicklable_properties",
"(",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'job-instance.pickle'",
")",
"if",
"self",
".",
"__module__",
"==",
"'__main__'",
":",
"d",
"=",
"pickle",
".",
"dumps",
"(",
"self",
")",
"module_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"d",
"=",
"d",
".",
"replace",
"(",
"b'(c__main__'",
",",
"\"(c\"",
"+",
"module_name",
")",
"open",
"(",
"file_name",
",",
"\"wb\"",
")",
".",
"write",
"(",
"d",
")",
"else",
":",
"pickle",
".",
"dump",
"(",
"self",
",",
"open",
"(",
"file_name",
",",
"\"wb\"",
")",
")"
] | Dump instance to file. | [
"Dump",
"instance",
"to",
"file",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L974-L987 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask._map_input | def _map_input(self, input_stream):
"""
Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments will be splitted in key and value.
"""
for record in self.reader(input_stream):
for output in self.mapper(*record):
yield output
if self.final_mapper != NotImplemented:
for output in self.final_mapper():
yield output
self._flush_batch_incr_counter() | python | def _map_input(self, input_stream):
"""
Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments will be splitted in key and value.
"""
for record in self.reader(input_stream):
for output in self.mapper(*record):
yield output
if self.final_mapper != NotImplemented:
for output in self.final_mapper():
yield output
self._flush_batch_incr_counter() | [
"def",
"_map_input",
"(",
"self",
",",
"input_stream",
")",
":",
"for",
"record",
"in",
"self",
".",
"reader",
"(",
"input_stream",
")",
":",
"for",
"output",
"in",
"self",
".",
"mapper",
"(",
"*",
"record",
")",
":",
"yield",
"output",
"if",
"self",
".",
"final_mapper",
"!=",
"NotImplemented",
":",
"for",
"output",
"in",
"self",
".",
"final_mapper",
"(",
")",
":",
"yield",
"output",
"self",
".",
"_flush_batch_incr_counter",
"(",
")"
] | Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments will be splitted in key and value. | [
"Iterate",
"over",
"input",
"and",
"call",
"the",
"mapper",
"for",
"each",
"item",
".",
"If",
"the",
"job",
"has",
"a",
"parser",
"defined",
"the",
"return",
"values",
"from",
"the",
"parser",
"will",
"be",
"passed",
"as",
"arguments",
"to",
"the",
"mapper",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L989-L1004 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask._reduce_input | def _reduce_input(self, inputs, reducer, final=NotImplemented):
"""
Iterate over input, collect values with the same key, and call the reducer for each unique key.
"""
for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
for output in reducer(self.deserialize(key), (v[1] for v in values)):
yield output
if final != NotImplemented:
for output in final():
yield output
self._flush_batch_incr_counter() | python | def _reduce_input(self, inputs, reducer, final=NotImplemented):
"""
Iterate over input, collect values with the same key, and call the reducer for each unique key.
"""
for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
for output in reducer(self.deserialize(key), (v[1] for v in values)):
yield output
if final != NotImplemented:
for output in final():
yield output
self._flush_batch_incr_counter() | [
"def",
"_reduce_input",
"(",
"self",
",",
"inputs",
",",
"reducer",
",",
"final",
"=",
"NotImplemented",
")",
":",
"for",
"key",
",",
"values",
"in",
"groupby",
"(",
"inputs",
",",
"key",
"=",
"lambda",
"x",
":",
"self",
".",
"internal_serialize",
"(",
"x",
"[",
"0",
"]",
")",
")",
":",
"for",
"output",
"in",
"reducer",
"(",
"self",
".",
"deserialize",
"(",
"key",
")",
",",
"(",
"v",
"[",
"1",
"]",
"for",
"v",
"in",
"values",
")",
")",
":",
"yield",
"output",
"if",
"final",
"!=",
"NotImplemented",
":",
"for",
"output",
"in",
"final",
"(",
")",
":",
"yield",
"output",
"self",
".",
"_flush_batch_incr_counter",
"(",
")"
] | Iterate over input, collect values with the same key, and call the reducer for each unique key. | [
"Iterate",
"over",
"input",
"collect",
"values",
"with",
"the",
"same",
"key",
"and",
"call",
"the",
"reducer",
"for",
"each",
"unique",
"key",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L1006-L1016 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.run_mapper | def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the mapper on the hadoop node.
"""
self.init_hadoop()
self.init_mapper()
outputs = self._map_input((line[:-1] for line in stdin))
if self.reducer == NotImplemented:
self.writer(outputs, stdout)
else:
self.internal_writer(outputs, stdout) | python | def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the mapper on the hadoop node.
"""
self.init_hadoop()
self.init_mapper()
outputs = self._map_input((line[:-1] for line in stdin))
if self.reducer == NotImplemented:
self.writer(outputs, stdout)
else:
self.internal_writer(outputs, stdout) | [
"def",
"run_mapper",
"(",
"self",
",",
"stdin",
"=",
"sys",
".",
"stdin",
",",
"stdout",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"init_hadoop",
"(",
")",
"self",
".",
"init_mapper",
"(",
")",
"outputs",
"=",
"self",
".",
"_map_input",
"(",
"(",
"line",
"[",
":",
"-",
"1",
"]",
"for",
"line",
"in",
"stdin",
")",
")",
"if",
"self",
".",
"reducer",
"==",
"NotImplemented",
":",
"self",
".",
"writer",
"(",
"outputs",
",",
"stdout",
")",
"else",
":",
"self",
".",
"internal_writer",
"(",
"outputs",
",",
"stdout",
")"
] | Run the mapper on the hadoop node. | [
"Run",
"the",
"mapper",
"on",
"the",
"hadoop",
"node",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L1018-L1028 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.run_reducer | def run_reducer(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the reducer on the hadoop node.
"""
self.init_hadoop()
self.init_reducer()
outputs = self._reduce_input(self.internal_reader((line[:-1] for line in stdin)), self.reducer, self.final_reducer)
self.writer(outputs, stdout) | python | def run_reducer(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the reducer on the hadoop node.
"""
self.init_hadoop()
self.init_reducer()
outputs = self._reduce_input(self.internal_reader((line[:-1] for line in stdin)), self.reducer, self.final_reducer)
self.writer(outputs, stdout) | [
"def",
"run_reducer",
"(",
"self",
",",
"stdin",
"=",
"sys",
".",
"stdin",
",",
"stdout",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"init_hadoop",
"(",
")",
"self",
".",
"init_reducer",
"(",
")",
"outputs",
"=",
"self",
".",
"_reduce_input",
"(",
"self",
".",
"internal_reader",
"(",
"(",
"line",
"[",
":",
"-",
"1",
"]",
"for",
"line",
"in",
"stdin",
")",
")",
",",
"self",
".",
"reducer",
",",
"self",
".",
"final_reducer",
")",
"self",
".",
"writer",
"(",
"outputs",
",",
"stdout",
")"
] | Run the reducer on the hadoop node. | [
"Run",
"the",
"reducer",
"on",
"the",
"hadoop",
"node",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L1030-L1037 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.internal_reader | def internal_reader(self, input_stream):
"""
Reader which uses python eval on each part of a tab separated string.
Yields a tuple of python objects.
"""
for input_line in input_stream:
yield list(map(self.deserialize, input_line.split("\t"))) | python | def internal_reader(self, input_stream):
"""
Reader which uses python eval on each part of a tab separated string.
Yields a tuple of python objects.
"""
for input_line in input_stream:
yield list(map(self.deserialize, input_line.split("\t"))) | [
"def",
"internal_reader",
"(",
"self",
",",
"input_stream",
")",
":",
"for",
"input_line",
"in",
"input_stream",
":",
"yield",
"list",
"(",
"map",
"(",
"self",
".",
"deserialize",
",",
"input_line",
".",
"split",
"(",
"\"\\t\"",
")",
")",
")"
] | Reader which uses python eval on each part of a tab separated string.
Yields a tuple of python objects. | [
"Reader",
"which",
"uses",
"python",
"eval",
"on",
"each",
"part",
"of",
"a",
"tab",
"separated",
"string",
".",
"Yields",
"a",
"tuple",
"of",
"python",
"objects",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L1045-L1051 | train |
spotify/luigi | luigi/contrib/hadoop.py | JobTask.internal_writer | def internal_writer(self, outputs, stdout):
"""
Writer which outputs the python repr for each item.
"""
for output in outputs:
print("\t".join(map(self.internal_serialize, output)), file=stdout) | python | def internal_writer(self, outputs, stdout):
"""
Writer which outputs the python repr for each item.
"""
for output in outputs:
print("\t".join(map(self.internal_serialize, output)), file=stdout) | [
"def",
"internal_writer",
"(",
"self",
",",
"outputs",
",",
"stdout",
")",
":",
"for",
"output",
"in",
"outputs",
":",
"print",
"(",
"\"\\t\"",
".",
"join",
"(",
"map",
"(",
"self",
".",
"internal_serialize",
",",
"output",
")",
")",
",",
"file",
"=",
"stdout",
")"
] | Writer which outputs the python repr for each item. | [
"Writer",
"which",
"outputs",
"the",
"python",
"repr",
"for",
"each",
"item",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hadoop.py#L1053-L1058 | train |
spotify/luigi | luigi/contrib/postgres.py | PostgresTarget.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:
# TODO: test this
connection = self.connect()
connection.autocommit = True # if connection created here, we commit it here
if self.use_db_timestamps:
connection.cursor().execute(
"""INSERT INTO {marker_table} (update_id, target_table)
VALUES (%s, %s)
""".format(marker_table=self.marker_table),
(self.update_id, self.table))
else:
connection.cursor().execute(
"""INSERT INTO {marker_table} (update_id, target_table, inserted)
VALUES (%s, %s, %s);
""".format(marker_table=self.marker_table),
(self.update_id, self.table,
datetime.datetime.now())) | 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:
# TODO: test this
connection = self.connect()
connection.autocommit = True # if connection created here, we commit it here
if self.use_db_timestamps:
connection.cursor().execute(
"""INSERT INTO {marker_table} (update_id, target_table)
VALUES (%s, %s)
""".format(marker_table=self.marker_table),
(self.update_id, self.table))
else:
connection.cursor().execute(
"""INSERT INTO {marker_table} (update_id, target_table, inserted)
VALUES (%s, %s, %s);
""".format(marker_table=self.marker_table),
(self.update_id, self.table,
datetime.datetime.now())) | [
"def",
"touch",
"(",
"self",
",",
"connection",
"=",
"None",
")",
":",
"self",
".",
"create_marker_table",
"(",
")",
"if",
"connection",
"is",
"None",
":",
"# TODO: test this",
"connection",
"=",
"self",
".",
"connect",
"(",
")",
"connection",
".",
"autocommit",
"=",
"True",
"# if connection created here, we commit it here",
"if",
"self",
".",
"use_db_timestamps",
":",
"connection",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"\"\"\"INSERT INTO {marker_table} (update_id, target_table)\n VALUES (%s, %s)\n \"\"\"",
".",
"format",
"(",
"marker_table",
"=",
"self",
".",
"marker_table",
")",
",",
"(",
"self",
".",
"update_id",
",",
"self",
".",
"table",
")",
")",
"else",
":",
"connection",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"\"\"\"INSERT INTO {marker_table} (update_id, target_table, inserted)\n VALUES (%s, %s, %s);\n \"\"\"",
".",
"format",
"(",
"marker_table",
"=",
"self",
".",
"marker_table",
")",
",",
"(",
"self",
".",
"update_id",
",",
"self",
".",
"table",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")"
] | 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/postgres.py#L139-L166 | train |
spotify/luigi | luigi/contrib/postgres.py | PostgresTarget.connect | def connect(self):
"""
Get a psycopg2 connection object to the database where the table is.
"""
connection = psycopg2.connect(
host=self.host,
port=self.port,
database=self.database,
user=self.user,
password=self.password)
connection.set_client_encoding('utf-8')
return connection | python | def connect(self):
"""
Get a psycopg2 connection object to the database where the table is.
"""
connection = psycopg2.connect(
host=self.host,
port=self.port,
database=self.database,
user=self.user,
password=self.password)
connection.set_client_encoding('utf-8')
return connection | [
"def",
"connect",
"(",
"self",
")",
":",
"connection",
"=",
"psycopg2",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"database",
"=",
"self",
".",
"database",
",",
"user",
"=",
"self",
".",
"user",
",",
"password",
"=",
"self",
".",
"password",
")",
"connection",
".",
"set_client_encoding",
"(",
"'utf-8'",
")",
"return",
"connection"
] | Get a psycopg2 connection object to the database where the table is. | [
"Get",
"a",
"psycopg2",
"connection",
"object",
"to",
"the",
"database",
"where",
"the",
"table",
"is",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/postgres.py#L187-L198 | train |
spotify/luigi | luigi/contrib/postgres.py | PostgresTarget.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()
connection.autocommit = True
cursor = connection.cursor()
if self.use_db_timestamps:
sql = """ CREATE TABLE {marker_table} (
update_id TEXT PRIMARY KEY,
target_table TEXT,
inserted TIMESTAMP DEFAULT NOW())
""".format(marker_table=self.marker_table)
else:
sql = """ CREATE TABLE {marker_table} (
update_id TEXT PRIMARY KEY,
target_table TEXT,
inserted TIMESTAMP);
""".format(marker_table=self.marker_table)
try:
cursor.execute(sql)
except psycopg2.ProgrammingError as e:
if e.pgcode == psycopg2.errorcodes.DUPLICATE_TABLE:
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()
connection.autocommit = True
cursor = connection.cursor()
if self.use_db_timestamps:
sql = """ CREATE TABLE {marker_table} (
update_id TEXT PRIMARY KEY,
target_table TEXT,
inserted TIMESTAMP DEFAULT NOW())
""".format(marker_table=self.marker_table)
else:
sql = """ CREATE TABLE {marker_table} (
update_id TEXT PRIMARY KEY,
target_table TEXT,
inserted TIMESTAMP);
""".format(marker_table=self.marker_table)
try:
cursor.execute(sql)
except psycopg2.ProgrammingError as e:
if e.pgcode == psycopg2.errorcodes.DUPLICATE_TABLE:
pass
else:
raise
connection.close() | [
"def",
"create_marker_table",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"connect",
"(",
")",
"connection",
".",
"autocommit",
"=",
"True",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"if",
"self",
".",
"use_db_timestamps",
":",
"sql",
"=",
"\"\"\" CREATE TABLE {marker_table} (\n update_id TEXT PRIMARY KEY,\n target_table TEXT,\n inserted TIMESTAMP DEFAULT NOW())\n \"\"\"",
".",
"format",
"(",
"marker_table",
"=",
"self",
".",
"marker_table",
")",
"else",
":",
"sql",
"=",
"\"\"\" CREATE TABLE {marker_table} (\n update_id TEXT PRIMARY KEY,\n target_table TEXT,\n inserted TIMESTAMP);\n \"\"\"",
".",
"format",
"(",
"marker_table",
"=",
"self",
".",
"marker_table",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"sql",
")",
"except",
"psycopg2",
".",
"ProgrammingError",
"as",
"e",
":",
"if",
"e",
".",
"pgcode",
"==",
"psycopg2",
".",
"errorcodes",
".",
"DUPLICATE_TABLE",
":",
"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/postgres.py#L200-L229 | train |
spotify/luigi | luigi/contrib/postgres.py | CopyToTable.rows | def rows(self):
"""
Return/yield tuples or lists corresponding to each row to be inserted.
"""
with self.input().open('r') as fobj:
for line in fobj:
yield line.strip('\n').split('\t') | python | def rows(self):
"""
Return/yield tuples or lists corresponding to each row to be inserted.
"""
with self.input().open('r') as fobj:
for line in fobj:
yield line.strip('\n').split('\t') | [
"def",
"rows",
"(",
"self",
")",
":",
"with",
"self",
".",
"input",
"(",
")",
".",
"open",
"(",
"'r'",
")",
"as",
"fobj",
":",
"for",
"line",
"in",
"fobj",
":",
"yield",
"line",
".",
"strip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"'\\t'",
")"
] | Return/yield tuples or lists corresponding to each row to be inserted. | [
"Return",
"/",
"yield",
"tuples",
"or",
"lists",
"corresponding",
"to",
"each",
"row",
"to",
"be",
"inserted",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/postgres.py#L247-L253 | train |
spotify/luigi | luigi/contrib/postgres.py | CopyToTable.map_column | def map_column(self, value):
"""
Applied to each column of every row returned by `rows`.
Default behaviour is to escape special characters and identify any self.null_values.
"""
if value in self.null_values:
return r'\\N'
else:
return default_escape(six.text_type(value)) | python | def map_column(self, value):
"""
Applied to each column of every row returned by `rows`.
Default behaviour is to escape special characters and identify any self.null_values.
"""
if value in self.null_values:
return r'\\N'
else:
return default_escape(six.text_type(value)) | [
"def",
"map_column",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"null_values",
":",
"return",
"r'\\\\N'",
"else",
":",
"return",
"default_escape",
"(",
"six",
".",
"text_type",
"(",
"value",
")",
")"
] | Applied to each column of every row returned by `rows`.
Default behaviour is to escape special characters and identify any self.null_values. | [
"Applied",
"to",
"each",
"column",
"of",
"every",
"row",
"returned",
"by",
"rows",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/postgres.py#L255-L264 | train |
spotify/luigi | luigi/contrib/postgres.py | CopyToTable.output | def output(self):
"""
Returns a PostgresTarget representing the inserted dataset.
Normally you don't override this.
"""
return PostgresTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.table,
update_id=self.update_id,
port=self.port
) | python | def output(self):
"""
Returns a PostgresTarget representing the inserted dataset.
Normally you don't override this.
"""
return PostgresTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.table,
update_id=self.update_id,
port=self.port
) | [
"def",
"output",
"(",
"self",
")",
":",
"return",
"PostgresTarget",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"self",
".",
"database",
",",
"user",
"=",
"self",
".",
"user",
",",
"password",
"=",
"self",
".",
"password",
",",
"table",
"=",
"self",
".",
"table",
",",
"update_id",
"=",
"self",
".",
"update_id",
",",
"port",
"=",
"self",
".",
"port",
")"
] | Returns a PostgresTarget representing the inserted dataset.
Normally you don't override this. | [
"Returns",
"a",
"PostgresTarget",
"representing",
"the",
"inserted",
"dataset",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/postgres.py#L268-L282 | train |
spotify/luigi | luigi/contrib/postgres.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()
# transform all data generated by rows() using map_column and write data
# to a temporary file for import using postgres COPY
tmp_dir = luigi.configuration.get_config().get('postgres', 'local-tmp-dir', None)
tmp_file = tempfile.TemporaryFile(dir=tmp_dir)
n = 0
for row in self.rows():
n += 1
if n % 100000 == 0:
logger.info("Wrote %d lines", n)
rowstr = self.column_separator.join(self.map_column(val) for val in row)
rowstr += "\n"
tmp_file.write(rowstr.encode('utf-8'))
logger.info("Done writing, importing at %s", datetime.datetime.now())
tmp_file.seek(0)
# attempt to copy the data into postgres
# 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()
self.init_copy(connection)
self.copy(cursor, tmp_file)
self.post_copy(connection)
if self.enable_metadata_columns:
self.post_copy_metacolumns(cursor)
except psycopg2.ProgrammingError as e:
if e.pgcode == psycopg2.errorcodes.UNDEFINED_TABLE and attempt == 0:
# if first attempt fails with "relation not found", try creating table
logger.info("Creating table %s", self.table)
connection.reset()
self.create_table(connection)
else:
raise
else:
break
# mark as complete in same transaction
self.output().touch(connection)
# commit and clean up
connection.commit()
connection.close()
tmp_file.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()
# transform all data generated by rows() using map_column and write data
# to a temporary file for import using postgres COPY
tmp_dir = luigi.configuration.get_config().get('postgres', 'local-tmp-dir', None)
tmp_file = tempfile.TemporaryFile(dir=tmp_dir)
n = 0
for row in self.rows():
n += 1
if n % 100000 == 0:
logger.info("Wrote %d lines", n)
rowstr = self.column_separator.join(self.map_column(val) for val in row)
rowstr += "\n"
tmp_file.write(rowstr.encode('utf-8'))
logger.info("Done writing, importing at %s", datetime.datetime.now())
tmp_file.seek(0)
# attempt to copy the data into postgres
# 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()
self.init_copy(connection)
self.copy(cursor, tmp_file)
self.post_copy(connection)
if self.enable_metadata_columns:
self.post_copy_metacolumns(cursor)
except psycopg2.ProgrammingError as e:
if e.pgcode == psycopg2.errorcodes.UNDEFINED_TABLE and attempt == 0:
# if first attempt fails with "relation not found", try creating table
logger.info("Creating table %s", self.table)
connection.reset()
self.create_table(connection)
else:
raise
else:
break
# mark as complete in same transaction
self.output().touch(connection)
# commit and clean up
connection.commit()
connection.close()
tmp_file.close() | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"table",
"and",
"self",
".",
"columns",
")",
":",
"raise",
"Exception",
"(",
"\"table and columns need to be specified\"",
")",
"connection",
"=",
"self",
".",
"output",
"(",
")",
".",
"connect",
"(",
")",
"# transform all data generated by rows() using map_column and write data",
"# to a temporary file for import using postgres COPY",
"tmp_dir",
"=",
"luigi",
".",
"configuration",
".",
"get_config",
"(",
")",
".",
"get",
"(",
"'postgres'",
",",
"'local-tmp-dir'",
",",
"None",
")",
"tmp_file",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"dir",
"=",
"tmp_dir",
")",
"n",
"=",
"0",
"for",
"row",
"in",
"self",
".",
"rows",
"(",
")",
":",
"n",
"+=",
"1",
"if",
"n",
"%",
"100000",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"Wrote %d lines\"",
",",
"n",
")",
"rowstr",
"=",
"self",
".",
"column_separator",
".",
"join",
"(",
"self",
".",
"map_column",
"(",
"val",
")",
"for",
"val",
"in",
"row",
")",
"rowstr",
"+=",
"\"\\n\"",
"tmp_file",
".",
"write",
"(",
"rowstr",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"logger",
".",
"info",
"(",
"\"Done writing, importing at %s\"",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"tmp_file",
".",
"seek",
"(",
"0",
")",
"# attempt to copy the data into postgres",
"# 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",
"(",
")",
"self",
".",
"init_copy",
"(",
"connection",
")",
"self",
".",
"copy",
"(",
"cursor",
",",
"tmp_file",
")",
"self",
".",
"post_copy",
"(",
"connection",
")",
"if",
"self",
".",
"enable_metadata_columns",
":",
"self",
".",
"post_copy_metacolumns",
"(",
"cursor",
")",
"except",
"psycopg2",
".",
"ProgrammingError",
"as",
"e",
":",
"if",
"e",
".",
"pgcode",
"==",
"psycopg2",
".",
"errorcodes",
".",
"UNDEFINED_TABLE",
"and",
"attempt",
"==",
"0",
":",
"# if first attempt fails with \"relation not found\", try creating table",
"logger",
".",
"info",
"(",
"\"Creating table %s\"",
",",
"self",
".",
"table",
")",
"connection",
".",
"reset",
"(",
")",
"self",
".",
"create_table",
"(",
"connection",
")",
"else",
":",
"raise",
"else",
":",
"break",
"# mark as complete in same transaction",
"self",
".",
"output",
"(",
")",
".",
"touch",
"(",
"connection",
")",
"# commit and clean up",
"connection",
".",
"commit",
"(",
")",
"connection",
".",
"close",
"(",
")",
"tmp_file",
".",
"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/postgres.py#L293-L349 | train |
spotify/luigi | luigi/configuration/core.py | get_config | def get_config(parser=PARSER):
"""Get configs singleton for parser
"""
parser_class = PARSERS[parser]
_check_parser(parser_class, parser)
return parser_class.instance() | python | def get_config(parser=PARSER):
"""Get configs singleton for parser
"""
parser_class = PARSERS[parser]
_check_parser(parser_class, parser)
return parser_class.instance() | [
"def",
"get_config",
"(",
"parser",
"=",
"PARSER",
")",
":",
"parser_class",
"=",
"PARSERS",
"[",
"parser",
"]",
"_check_parser",
"(",
"parser_class",
",",
"parser",
")",
"return",
"parser_class",
".",
"instance",
"(",
")"
] | Get configs singleton for parser | [
"Get",
"configs",
"singleton",
"for",
"parser"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/configuration/core.py#L53-L58 | train |
spotify/luigi | luigi/configuration/core.py | add_config_path | def add_config_path(path):
"""Select config parser by file extension and add path into parser.
"""
if not os.path.isfile(path):
warnings.warn("Config file does not exist: {path}".format(path=path))
return False
# select parser by file extension
_base, ext = os.path.splitext(path)
if ext and ext[1:] in PARSERS:
parser = ext[1:]
else:
parser = PARSER
parser_class = PARSERS[parser]
_check_parser(parser_class, parser)
if parser != PARSER:
msg = (
"Config for {added} parser added, but used {used} parser. "
"Set up right parser via env var: "
"export LUIGI_CONFIG_PARSER={added}"
)
warnings.warn(msg.format(added=parser, used=PARSER))
# add config path to parser
parser_class.add_config_path(path)
return True | python | def add_config_path(path):
"""Select config parser by file extension and add path into parser.
"""
if not os.path.isfile(path):
warnings.warn("Config file does not exist: {path}".format(path=path))
return False
# select parser by file extension
_base, ext = os.path.splitext(path)
if ext and ext[1:] in PARSERS:
parser = ext[1:]
else:
parser = PARSER
parser_class = PARSERS[parser]
_check_parser(parser_class, parser)
if parser != PARSER:
msg = (
"Config for {added} parser added, but used {used} parser. "
"Set up right parser via env var: "
"export LUIGI_CONFIG_PARSER={added}"
)
warnings.warn(msg.format(added=parser, used=PARSER))
# add config path to parser
parser_class.add_config_path(path)
return True | [
"def",
"add_config_path",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Config file does not exist: {path}\"",
".",
"format",
"(",
"path",
"=",
"path",
")",
")",
"return",
"False",
"# select parser by file extension",
"_base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"and",
"ext",
"[",
"1",
":",
"]",
"in",
"PARSERS",
":",
"parser",
"=",
"ext",
"[",
"1",
":",
"]",
"else",
":",
"parser",
"=",
"PARSER",
"parser_class",
"=",
"PARSERS",
"[",
"parser",
"]",
"_check_parser",
"(",
"parser_class",
",",
"parser",
")",
"if",
"parser",
"!=",
"PARSER",
":",
"msg",
"=",
"(",
"\"Config for {added} parser added, but used {used} parser. \"",
"\"Set up right parser via env var: \"",
"\"export LUIGI_CONFIG_PARSER={added}\"",
")",
"warnings",
".",
"warn",
"(",
"msg",
".",
"format",
"(",
"added",
"=",
"parser",
",",
"used",
"=",
"PARSER",
")",
")",
"# add config path to parser",
"parser_class",
".",
"add_config_path",
"(",
"path",
")",
"return",
"True"
] | Select config parser by file extension and add path into parser. | [
"Select",
"config",
"parser",
"by",
"file",
"extension",
"and",
"add",
"path",
"into",
"parser",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/configuration/core.py#L61-L87 | train |
spotify/luigi | luigi/contrib/spark.py | PySparkTask._setup_packages | def _setup_packages(self, sc):
"""
This method compresses and uploads packages to the cluster
"""
packages = self.py_packages
if not packages:
return
for package in packages:
mod = importlib.import_module(package)
try:
mod_path = mod.__path__[0]
except AttributeError:
mod_path = mod.__file__
tar_path = os.path.join(self.run_path, package + '.tar.gz')
tar = tarfile.open(tar_path, "w:gz")
tar.add(mod_path, os.path.basename(mod_path))
tar.close()
sc.addPyFile(tar_path) | python | def _setup_packages(self, sc):
"""
This method compresses and uploads packages to the cluster
"""
packages = self.py_packages
if not packages:
return
for package in packages:
mod = importlib.import_module(package)
try:
mod_path = mod.__path__[0]
except AttributeError:
mod_path = mod.__file__
tar_path = os.path.join(self.run_path, package + '.tar.gz')
tar = tarfile.open(tar_path, "w:gz")
tar.add(mod_path, os.path.basename(mod_path))
tar.close()
sc.addPyFile(tar_path) | [
"def",
"_setup_packages",
"(",
"self",
",",
"sc",
")",
":",
"packages",
"=",
"self",
".",
"py_packages",
"if",
"not",
"packages",
":",
"return",
"for",
"package",
"in",
"packages",
":",
"mod",
"=",
"importlib",
".",
"import_module",
"(",
"package",
")",
"try",
":",
"mod_path",
"=",
"mod",
".",
"__path__",
"[",
"0",
"]",
"except",
"AttributeError",
":",
"mod_path",
"=",
"mod",
".",
"__file__",
"tar_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"run_path",
",",
"package",
"+",
"'.tar.gz'",
")",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"tar_path",
",",
"\"w:gz\"",
")",
"tar",
".",
"add",
"(",
"mod_path",
",",
"os",
".",
"path",
".",
"basename",
"(",
"mod_path",
")",
")",
"tar",
".",
"close",
"(",
")",
"sc",
".",
"addPyFile",
"(",
"tar_path",
")"
] | This method compresses and uploads packages to the cluster | [
"This",
"method",
"compresses",
"and",
"uploads",
"packages",
"to",
"the",
"cluster"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/spark.py#L323-L341 | train |
spotify/luigi | luigi/contrib/mrrunner.py | main | def main(args=None, stdin=sys.stdin, stdout=sys.stdout, print_exception=print_exception):
"""
Run either the mapper, combiner, or reducer from the class instance in the file "job-instance.pickle".
Arguments:
kind -- is either map, combiner, or reduce
"""
try:
# Set up logging.
logging.basicConfig(level=logging.WARN)
kind = args is not None and args[1] or sys.argv[1]
Runner().run(kind, stdin=stdin, stdout=stdout)
except Exception as exc:
# Dump encoded data that we will try to fetch using mechanize
print_exception(exc)
raise | python | def main(args=None, stdin=sys.stdin, stdout=sys.stdout, print_exception=print_exception):
"""
Run either the mapper, combiner, or reducer from the class instance in the file "job-instance.pickle".
Arguments:
kind -- is either map, combiner, or reduce
"""
try:
# Set up logging.
logging.basicConfig(level=logging.WARN)
kind = args is not None and args[1] or sys.argv[1]
Runner().run(kind, stdin=stdin, stdout=stdout)
except Exception as exc:
# Dump encoded data that we will try to fetch using mechanize
print_exception(exc)
raise | [
"def",
"main",
"(",
"args",
"=",
"None",
",",
"stdin",
"=",
"sys",
".",
"stdin",
",",
"stdout",
"=",
"sys",
".",
"stdout",
",",
"print_exception",
"=",
"print_exception",
")",
":",
"try",
":",
"# Set up logging.",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"WARN",
")",
"kind",
"=",
"args",
"is",
"not",
"None",
"and",
"args",
"[",
"1",
"]",
"or",
"sys",
".",
"argv",
"[",
"1",
"]",
"Runner",
"(",
")",
".",
"run",
"(",
"kind",
",",
"stdin",
"=",
"stdin",
",",
"stdout",
"=",
"stdout",
")",
"except",
"Exception",
"as",
"exc",
":",
"# Dump encoded data that we will try to fetch using mechanize",
"print_exception",
"(",
"exc",
")",
"raise"
] | Run either the mapper, combiner, or reducer from the class instance in the file "job-instance.pickle".
Arguments:
kind -- is either map, combiner, or reduce | [
"Run",
"either",
"the",
"mapper",
"combiner",
"or",
"reducer",
"from",
"the",
"class",
"instance",
"in",
"the",
"file",
"job",
"-",
"instance",
".",
"pickle",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mrrunner.py#L80-L97 | train |
spotify/luigi | luigi/retcodes.py | run_with_retcodes | def run_with_retcodes(argv):
"""
Run luigi with command line parsing, but raise ``SystemExit`` with the configured exit code.
Note: Usually you use the luigi binary directly and don't call this function yourself.
:param argv: Should (conceptually) be ``sys.argv[1:]``
"""
logger = logging.getLogger('luigi-interface')
with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
retcodes = retcode()
worker = None
try:
worker = luigi.interface._run(argv).worker
except luigi.interface.PidLockAlreadyTakenExit:
sys.exit(retcodes.already_running)
except Exception:
# Some errors occur before logging is set up, we set it up now
env_params = luigi.interface.core()
InterfaceLogging.setup(env_params)
logger.exception("Uncaught exception in luigi")
sys.exit(retcodes.unhandled_exception)
with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
task_sets = luigi.execution_summary._summary_dict(worker)
root_task = luigi.execution_summary._root_task(worker)
non_empty_categories = {k: v for k, v in task_sets.items() if v}.keys()
def has(status):
assert status in luigi.execution_summary._ORDERED_STATUSES
return status in non_empty_categories
codes_and_conds = (
(retcodes.missing_data, has('still_pending_ext')),
(retcodes.task_failed, has('failed')),
(retcodes.already_running, has('run_by_other_worker')),
(retcodes.scheduling_error, has('scheduling_error')),
(retcodes.not_run, has('not_run')),
)
expected_ret_code = max(code * (1 if cond else 0) for code, cond in codes_and_conds)
if expected_ret_code == 0 and \
root_task not in task_sets["completed"] and \
root_task not in task_sets["already_done"]:
sys.exit(retcodes.not_run)
else:
sys.exit(expected_ret_code) | python | def run_with_retcodes(argv):
"""
Run luigi with command line parsing, but raise ``SystemExit`` with the configured exit code.
Note: Usually you use the luigi binary directly and don't call this function yourself.
:param argv: Should (conceptually) be ``sys.argv[1:]``
"""
logger = logging.getLogger('luigi-interface')
with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
retcodes = retcode()
worker = None
try:
worker = luigi.interface._run(argv).worker
except luigi.interface.PidLockAlreadyTakenExit:
sys.exit(retcodes.already_running)
except Exception:
# Some errors occur before logging is set up, we set it up now
env_params = luigi.interface.core()
InterfaceLogging.setup(env_params)
logger.exception("Uncaught exception in luigi")
sys.exit(retcodes.unhandled_exception)
with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
task_sets = luigi.execution_summary._summary_dict(worker)
root_task = luigi.execution_summary._root_task(worker)
non_empty_categories = {k: v for k, v in task_sets.items() if v}.keys()
def has(status):
assert status in luigi.execution_summary._ORDERED_STATUSES
return status in non_empty_categories
codes_and_conds = (
(retcodes.missing_data, has('still_pending_ext')),
(retcodes.task_failed, has('failed')),
(retcodes.already_running, has('run_by_other_worker')),
(retcodes.scheduling_error, has('scheduling_error')),
(retcodes.not_run, has('not_run')),
)
expected_ret_code = max(code * (1 if cond else 0) for code, cond in codes_and_conds)
if expected_ret_code == 0 and \
root_task not in task_sets["completed"] and \
root_task not in task_sets["already_done"]:
sys.exit(retcodes.not_run)
else:
sys.exit(expected_ret_code) | [
"def",
"run_with_retcodes",
"(",
"argv",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'luigi-interface'",
")",
"with",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"global_instance",
"(",
"argv",
")",
":",
"retcodes",
"=",
"retcode",
"(",
")",
"worker",
"=",
"None",
"try",
":",
"worker",
"=",
"luigi",
".",
"interface",
".",
"_run",
"(",
"argv",
")",
".",
"worker",
"except",
"luigi",
".",
"interface",
".",
"PidLockAlreadyTakenExit",
":",
"sys",
".",
"exit",
"(",
"retcodes",
".",
"already_running",
")",
"except",
"Exception",
":",
"# Some errors occur before logging is set up, we set it up now",
"env_params",
"=",
"luigi",
".",
"interface",
".",
"core",
"(",
")",
"InterfaceLogging",
".",
"setup",
"(",
"env_params",
")",
"logger",
".",
"exception",
"(",
"\"Uncaught exception in luigi\"",
")",
"sys",
".",
"exit",
"(",
"retcodes",
".",
"unhandled_exception",
")",
"with",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"global_instance",
"(",
"argv",
")",
":",
"task_sets",
"=",
"luigi",
".",
"execution_summary",
".",
"_summary_dict",
"(",
"worker",
")",
"root_task",
"=",
"luigi",
".",
"execution_summary",
".",
"_root_task",
"(",
"worker",
")",
"non_empty_categories",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"task_sets",
".",
"items",
"(",
")",
"if",
"v",
"}",
".",
"keys",
"(",
")",
"def",
"has",
"(",
"status",
")",
":",
"assert",
"status",
"in",
"luigi",
".",
"execution_summary",
".",
"_ORDERED_STATUSES",
"return",
"status",
"in",
"non_empty_categories",
"codes_and_conds",
"=",
"(",
"(",
"retcodes",
".",
"missing_data",
",",
"has",
"(",
"'still_pending_ext'",
")",
")",
",",
"(",
"retcodes",
".",
"task_failed",
",",
"has",
"(",
"'failed'",
")",
")",
",",
"(",
"retcodes",
".",
"already_running",
",",
"has",
"(",
"'run_by_other_worker'",
")",
")",
",",
"(",
"retcodes",
".",
"scheduling_error",
",",
"has",
"(",
"'scheduling_error'",
")",
")",
",",
"(",
"retcodes",
".",
"not_run",
",",
"has",
"(",
"'not_run'",
")",
")",
",",
")",
"expected_ret_code",
"=",
"max",
"(",
"code",
"*",
"(",
"1",
"if",
"cond",
"else",
"0",
")",
"for",
"code",
",",
"cond",
"in",
"codes_and_conds",
")",
"if",
"expected_ret_code",
"==",
"0",
"and",
"root_task",
"not",
"in",
"task_sets",
"[",
"\"completed\"",
"]",
"and",
"root_task",
"not",
"in",
"task_sets",
"[",
"\"already_done\"",
"]",
":",
"sys",
".",
"exit",
"(",
"retcodes",
".",
"not_run",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"expected_ret_code",
")"
] | Run luigi with command line parsing, but raise ``SystemExit`` with the configured exit code.
Note: Usually you use the luigi binary directly and don't call this function yourself.
:param argv: Should (conceptually) be ``sys.argv[1:]`` | [
"Run",
"luigi",
"with",
"command",
"line",
"parsing",
"but",
"raise",
"SystemExit",
"with",
"the",
"configured",
"exit",
"code",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/retcodes.py#L61-L108 | train |
spotify/luigi | luigi/tools/deps.py | find_deps_cli | def find_deps_cli():
'''
Finds all tasks on all paths from provided CLI task
'''
cmdline_args = sys.argv[1:]
with CmdlineParser.global_instance(cmdline_args) as cp:
return find_deps(cp.get_task_obj(), upstream().family) | python | def find_deps_cli():
'''
Finds all tasks on all paths from provided CLI task
'''
cmdline_args = sys.argv[1:]
with CmdlineParser.global_instance(cmdline_args) as cp:
return find_deps(cp.get_task_obj(), upstream().family) | [
"def",
"find_deps_cli",
"(",
")",
":",
"cmdline_args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"with",
"CmdlineParser",
".",
"global_instance",
"(",
"cmdline_args",
")",
"as",
"cp",
":",
"return",
"find_deps",
"(",
"cp",
".",
"get_task_obj",
"(",
")",
",",
"upstream",
"(",
")",
".",
"family",
")"
] | Finds all tasks on all paths from provided CLI task | [
"Finds",
"all",
"tasks",
"on",
"all",
"paths",
"from",
"provided",
"CLI",
"task"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/deps.py#L85-L91 | train |
spotify/luigi | luigi/tools/deps.py | get_task_output_description | def get_task_output_description(task_output):
'''
Returns a task's output as a string
'''
output_description = "n/a"
if isinstance(task_output, RemoteTarget):
output_description = "[SSH] {0}:{1}".format(task_output._fs.remote_context.host, task_output.path)
elif isinstance(task_output, S3Target):
output_description = "[S3] {0}".format(task_output.path)
elif isinstance(task_output, FileSystemTarget):
output_description = "[FileSystem] {0}".format(task_output.path)
elif isinstance(task_output, PostgresTarget):
output_description = "[DB] {0}:{1}".format(task_output.host, task_output.table)
else:
output_description = "to be determined"
return output_description | python | def get_task_output_description(task_output):
'''
Returns a task's output as a string
'''
output_description = "n/a"
if isinstance(task_output, RemoteTarget):
output_description = "[SSH] {0}:{1}".format(task_output._fs.remote_context.host, task_output.path)
elif isinstance(task_output, S3Target):
output_description = "[S3] {0}".format(task_output.path)
elif isinstance(task_output, FileSystemTarget):
output_description = "[FileSystem] {0}".format(task_output.path)
elif isinstance(task_output, PostgresTarget):
output_description = "[DB] {0}:{1}".format(task_output.host, task_output.table)
else:
output_description = "to be determined"
return output_description | [
"def",
"get_task_output_description",
"(",
"task_output",
")",
":",
"output_description",
"=",
"\"n/a\"",
"if",
"isinstance",
"(",
"task_output",
",",
"RemoteTarget",
")",
":",
"output_description",
"=",
"\"[SSH] {0}:{1}\"",
".",
"format",
"(",
"task_output",
".",
"_fs",
".",
"remote_context",
".",
"host",
",",
"task_output",
".",
"path",
")",
"elif",
"isinstance",
"(",
"task_output",
",",
"S3Target",
")",
":",
"output_description",
"=",
"\"[S3] {0}\"",
".",
"format",
"(",
"task_output",
".",
"path",
")",
"elif",
"isinstance",
"(",
"task_output",
",",
"FileSystemTarget",
")",
":",
"output_description",
"=",
"\"[FileSystem] {0}\"",
".",
"format",
"(",
"task_output",
".",
"path",
")",
"elif",
"isinstance",
"(",
"task_output",
",",
"PostgresTarget",
")",
":",
"output_description",
"=",
"\"[DB] {0}:{1}\"",
".",
"format",
"(",
"task_output",
".",
"host",
",",
"task_output",
".",
"table",
")",
"else",
":",
"output_description",
"=",
"\"to be determined\"",
"return",
"output_description"
] | Returns a task's output as a string | [
"Returns",
"a",
"task",
"s",
"output",
"as",
"a",
"string"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/deps.py#L94-L111 | train |
spotify/luigi | luigi/tools/range.py | _constrain_glob | def _constrain_glob(glob, paths, limit=5):
"""
Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.
Saves us minutes long listings for long dataset histories.
Specifically, in this implementation the leftmost occurrences of "[0-9]"
give rise to a few separate globs that each specialize the expression to
digits that actually occur in paths.
"""
def digit_set_wildcard(chars):
"""
Makes a wildcard expression for the set, a bit readable, e.g. [1-5].
"""
chars = sorted(chars)
if len(chars) > 1 and ord(chars[-1]) - ord(chars[0]) == len(chars) - 1:
return '[%s-%s]' % (chars[0], chars[-1])
else:
return '[%s]' % ''.join(chars)
current = {glob: paths}
while True:
pos = list(current.keys())[0].find('[0-9]')
if pos == -1:
# no wildcard expressions left to specialize in the glob
return list(current.keys())
char_sets = {}
for g, p in six.iteritems(current):
char_sets[g] = sorted({path[pos] for path in p})
if sum(len(s) for s in char_sets.values()) > limit:
return [g.replace('[0-9]', digit_set_wildcard(char_sets[g]), 1) for g in current]
for g, s in six.iteritems(char_sets):
for c in s:
new_glob = g.replace('[0-9]', c, 1)
new_paths = list(filter(lambda p: p[pos] == c, current[g]))
current[new_glob] = new_paths
del current[g] | python | def _constrain_glob(glob, paths, limit=5):
"""
Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.
Saves us minutes long listings for long dataset histories.
Specifically, in this implementation the leftmost occurrences of "[0-9]"
give rise to a few separate globs that each specialize the expression to
digits that actually occur in paths.
"""
def digit_set_wildcard(chars):
"""
Makes a wildcard expression for the set, a bit readable, e.g. [1-5].
"""
chars = sorted(chars)
if len(chars) > 1 and ord(chars[-1]) - ord(chars[0]) == len(chars) - 1:
return '[%s-%s]' % (chars[0], chars[-1])
else:
return '[%s]' % ''.join(chars)
current = {glob: paths}
while True:
pos = list(current.keys())[0].find('[0-9]')
if pos == -1:
# no wildcard expressions left to specialize in the glob
return list(current.keys())
char_sets = {}
for g, p in six.iteritems(current):
char_sets[g] = sorted({path[pos] for path in p})
if sum(len(s) for s in char_sets.values()) > limit:
return [g.replace('[0-9]', digit_set_wildcard(char_sets[g]), 1) for g in current]
for g, s in six.iteritems(char_sets):
for c in s:
new_glob = g.replace('[0-9]', c, 1)
new_paths = list(filter(lambda p: p[pos] == c, current[g]))
current[new_glob] = new_paths
del current[g] | [
"def",
"_constrain_glob",
"(",
"glob",
",",
"paths",
",",
"limit",
"=",
"5",
")",
":",
"def",
"digit_set_wildcard",
"(",
"chars",
")",
":",
"\"\"\"\n Makes a wildcard expression for the set, a bit readable, e.g. [1-5].\n \"\"\"",
"chars",
"=",
"sorted",
"(",
"chars",
")",
"if",
"len",
"(",
"chars",
")",
">",
"1",
"and",
"ord",
"(",
"chars",
"[",
"-",
"1",
"]",
")",
"-",
"ord",
"(",
"chars",
"[",
"0",
"]",
")",
"==",
"len",
"(",
"chars",
")",
"-",
"1",
":",
"return",
"'[%s-%s]'",
"%",
"(",
"chars",
"[",
"0",
"]",
",",
"chars",
"[",
"-",
"1",
"]",
")",
"else",
":",
"return",
"'[%s]'",
"%",
"''",
".",
"join",
"(",
"chars",
")",
"current",
"=",
"{",
"glob",
":",
"paths",
"}",
"while",
"True",
":",
"pos",
"=",
"list",
"(",
"current",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
".",
"find",
"(",
"'[0-9]'",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"# no wildcard expressions left to specialize in the glob",
"return",
"list",
"(",
"current",
".",
"keys",
"(",
")",
")",
"char_sets",
"=",
"{",
"}",
"for",
"g",
",",
"p",
"in",
"six",
".",
"iteritems",
"(",
"current",
")",
":",
"char_sets",
"[",
"g",
"]",
"=",
"sorted",
"(",
"{",
"path",
"[",
"pos",
"]",
"for",
"path",
"in",
"p",
"}",
")",
"if",
"sum",
"(",
"len",
"(",
"s",
")",
"for",
"s",
"in",
"char_sets",
".",
"values",
"(",
")",
")",
">",
"limit",
":",
"return",
"[",
"g",
".",
"replace",
"(",
"'[0-9]'",
",",
"digit_set_wildcard",
"(",
"char_sets",
"[",
"g",
"]",
")",
",",
"1",
")",
"for",
"g",
"in",
"current",
"]",
"for",
"g",
",",
"s",
"in",
"six",
".",
"iteritems",
"(",
"char_sets",
")",
":",
"for",
"c",
"in",
"s",
":",
"new_glob",
"=",
"g",
".",
"replace",
"(",
"'[0-9]'",
",",
"c",
",",
"1",
")",
"new_paths",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"p",
":",
"p",
"[",
"pos",
"]",
"==",
"c",
",",
"current",
"[",
"g",
"]",
")",
")",
"current",
"[",
"new_glob",
"]",
"=",
"new_paths",
"del",
"current",
"[",
"g",
"]"
] | Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.
Saves us minutes long listings for long dataset histories.
Specifically, in this implementation the leftmost occurrences of "[0-9]"
give rise to a few separate globs that each specialize the expression to
digits that actually occur in paths. | [
"Tweaks",
"glob",
"into",
"a",
"list",
"of",
"more",
"specific",
"globs",
"that",
"together",
"still",
"cover",
"paths",
"and",
"not",
"too",
"much",
"extra",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L491-L528 | train |
spotify/luigi | luigi/tools/range.py | most_common | def most_common(items):
"""
Wanted functionality from Counters (new in Python 2.7).
"""
counts = {}
for i in items:
counts.setdefault(i, 0)
counts[i] += 1
return max(six.iteritems(counts), key=operator.itemgetter(1)) | python | def most_common(items):
"""
Wanted functionality from Counters (new in Python 2.7).
"""
counts = {}
for i in items:
counts.setdefault(i, 0)
counts[i] += 1
return max(six.iteritems(counts), key=operator.itemgetter(1)) | [
"def",
"most_common",
"(",
"items",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"i",
"in",
"items",
":",
"counts",
".",
"setdefault",
"(",
"i",
",",
"0",
")",
"counts",
"[",
"i",
"]",
"+=",
"1",
"return",
"max",
"(",
"six",
".",
"iteritems",
"(",
"counts",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")"
] | Wanted functionality from Counters (new in Python 2.7). | [
"Wanted",
"functionality",
"from",
"Counters",
"(",
"new",
"in",
"Python",
"2",
".",
"7",
")",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L531-L539 | train |
spotify/luigi | luigi/tools/range.py | _get_per_location_glob | def _get_per_location_glob(tasks, outputs, regexes):
"""
Builds a glob listing existing output paths.
Esoteric reverse engineering, but worth it given that (compared to an
equivalent contiguousness guarantee by naive complete() checks)
requests to the filesystem are cut by orders of magnitude, and users
don't even have to retrofit existing tasks anyhow.
"""
paths = [o.path for o in outputs]
# naive, because some matches could be confused by numbers earlier
# in path, e.g. /foo/fifa2000k/bar/2000-12-31/00
matches = [r.search(p) for r, p in zip(regexes, paths)]
for m, p, t in zip(matches, paths, tasks):
if m is None:
raise NotImplementedError("Couldn't deduce datehour representation in output path %r of task %s" % (p, t))
n_groups = len(matches[0].groups())
# the most common position of every group is likely
# to be conclusive hit or miss
positions = [most_common((m.start(i), m.end(i)) for m in matches)[0] for i in range(1, n_groups + 1)]
glob = list(paths[0]) # FIXME sanity check that it's the same for all paths
for start, end in positions:
glob = glob[:start] + ['[0-9]'] * (end - start) + glob[end:]
# chop off the last path item
# (wouldn't need to if `hadoop fs -ls -d` equivalent were available)
return ''.join(glob).rsplit('/', 1)[0] | python | def _get_per_location_glob(tasks, outputs, regexes):
"""
Builds a glob listing existing output paths.
Esoteric reverse engineering, but worth it given that (compared to an
equivalent contiguousness guarantee by naive complete() checks)
requests to the filesystem are cut by orders of magnitude, and users
don't even have to retrofit existing tasks anyhow.
"""
paths = [o.path for o in outputs]
# naive, because some matches could be confused by numbers earlier
# in path, e.g. /foo/fifa2000k/bar/2000-12-31/00
matches = [r.search(p) for r, p in zip(regexes, paths)]
for m, p, t in zip(matches, paths, tasks):
if m is None:
raise NotImplementedError("Couldn't deduce datehour representation in output path %r of task %s" % (p, t))
n_groups = len(matches[0].groups())
# the most common position of every group is likely
# to be conclusive hit or miss
positions = [most_common((m.start(i), m.end(i)) for m in matches)[0] for i in range(1, n_groups + 1)]
glob = list(paths[0]) # FIXME sanity check that it's the same for all paths
for start, end in positions:
glob = glob[:start] + ['[0-9]'] * (end - start) + glob[end:]
# chop off the last path item
# (wouldn't need to if `hadoop fs -ls -d` equivalent were available)
return ''.join(glob).rsplit('/', 1)[0] | [
"def",
"_get_per_location_glob",
"(",
"tasks",
",",
"outputs",
",",
"regexes",
")",
":",
"paths",
"=",
"[",
"o",
".",
"path",
"for",
"o",
"in",
"outputs",
"]",
"# naive, because some matches could be confused by numbers earlier",
"# in path, e.g. /foo/fifa2000k/bar/2000-12-31/00",
"matches",
"=",
"[",
"r",
".",
"search",
"(",
"p",
")",
"for",
"r",
",",
"p",
"in",
"zip",
"(",
"regexes",
",",
"paths",
")",
"]",
"for",
"m",
",",
"p",
",",
"t",
"in",
"zip",
"(",
"matches",
",",
"paths",
",",
"tasks",
")",
":",
"if",
"m",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Couldn't deduce datehour representation in output path %r of task %s\"",
"%",
"(",
"p",
",",
"t",
")",
")",
"n_groups",
"=",
"len",
"(",
"matches",
"[",
"0",
"]",
".",
"groups",
"(",
")",
")",
"# the most common position of every group is likely",
"# to be conclusive hit or miss",
"positions",
"=",
"[",
"most_common",
"(",
"(",
"m",
".",
"start",
"(",
"i",
")",
",",
"m",
".",
"end",
"(",
"i",
")",
")",
"for",
"m",
"in",
"matches",
")",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n_groups",
"+",
"1",
")",
"]",
"glob",
"=",
"list",
"(",
"paths",
"[",
"0",
"]",
")",
"# FIXME sanity check that it's the same for all paths",
"for",
"start",
",",
"end",
"in",
"positions",
":",
"glob",
"=",
"glob",
"[",
":",
"start",
"]",
"+",
"[",
"'[0-9]'",
"]",
"*",
"(",
"end",
"-",
"start",
")",
"+",
"glob",
"[",
"end",
":",
"]",
"# chop off the last path item",
"# (wouldn't need to if `hadoop fs -ls -d` equivalent were available)",
"return",
"''",
".",
"join",
"(",
"glob",
")",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]"
] | Builds a glob listing existing output paths.
Esoteric reverse engineering, but worth it given that (compared to an
equivalent contiguousness guarantee by naive complete() checks)
requests to the filesystem are cut by orders of magnitude, and users
don't even have to retrofit existing tasks anyhow. | [
"Builds",
"a",
"glob",
"listing",
"existing",
"output",
"paths",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L542-L570 | train |
spotify/luigi | luigi/tools/range.py | _get_filesystems_and_globs | def _get_filesystems_and_globs(datetime_to_task, datetime_to_re):
"""
Yields a (filesystem, glob) tuple per every output location of task.
The task can have one or several FileSystemTarget outputs.
For convenience, the task can be a luigi.WrapperTask,
in which case outputs of all its dependencies are considered.
"""
# probe some scattered datetimes unlikely to all occur in paths, other than by being sincere datetime parameter's representations
# TODO limit to [self.start, self.stop) so messages are less confusing? Done trivially it can kill correctness
sample_datetimes = [datetime(y, m, d, h) for y in range(2000, 2050, 10) for m in range(1, 4) for d in range(5, 8) for h in range(21, 24)]
regexes = [re.compile(datetime_to_re(d)) for d in sample_datetimes]
sample_tasks = [datetime_to_task(d) for d in sample_datetimes]
sample_outputs = [flatten_output(t) for t in sample_tasks]
for o, t in zip(sample_outputs, sample_tasks):
if len(o) != len(sample_outputs[0]):
raise NotImplementedError("Outputs must be consistent over time, sorry; was %r for %r and %r for %r" % (o, t, sample_outputs[0], sample_tasks[0]))
# TODO fall back on requiring last couple of days? to avoid astonishing blocking when changes like that are deployed
# erm, actually it's not hard to test entire hours_back..hours_forward and split into consistent subranges FIXME?
for target in o:
if not isinstance(target, FileSystemTarget):
raise NotImplementedError("Output targets must be instances of FileSystemTarget; was %r for %r" % (target, t))
for o in zip(*sample_outputs): # transposed, so here we're iterating over logical outputs, not datetimes
glob = _get_per_location_glob(sample_tasks, o, regexes)
yield o[0].fs, glob | python | def _get_filesystems_and_globs(datetime_to_task, datetime_to_re):
"""
Yields a (filesystem, glob) tuple per every output location of task.
The task can have one or several FileSystemTarget outputs.
For convenience, the task can be a luigi.WrapperTask,
in which case outputs of all its dependencies are considered.
"""
# probe some scattered datetimes unlikely to all occur in paths, other than by being sincere datetime parameter's representations
# TODO limit to [self.start, self.stop) so messages are less confusing? Done trivially it can kill correctness
sample_datetimes = [datetime(y, m, d, h) for y in range(2000, 2050, 10) for m in range(1, 4) for d in range(5, 8) for h in range(21, 24)]
regexes = [re.compile(datetime_to_re(d)) for d in sample_datetimes]
sample_tasks = [datetime_to_task(d) for d in sample_datetimes]
sample_outputs = [flatten_output(t) for t in sample_tasks]
for o, t in zip(sample_outputs, sample_tasks):
if len(o) != len(sample_outputs[0]):
raise NotImplementedError("Outputs must be consistent over time, sorry; was %r for %r and %r for %r" % (o, t, sample_outputs[0], sample_tasks[0]))
# TODO fall back on requiring last couple of days? to avoid astonishing blocking when changes like that are deployed
# erm, actually it's not hard to test entire hours_back..hours_forward and split into consistent subranges FIXME?
for target in o:
if not isinstance(target, FileSystemTarget):
raise NotImplementedError("Output targets must be instances of FileSystemTarget; was %r for %r" % (target, t))
for o in zip(*sample_outputs): # transposed, so here we're iterating over logical outputs, not datetimes
glob = _get_per_location_glob(sample_tasks, o, regexes)
yield o[0].fs, glob | [
"def",
"_get_filesystems_and_globs",
"(",
"datetime_to_task",
",",
"datetime_to_re",
")",
":",
"# probe some scattered datetimes unlikely to all occur in paths, other than by being sincere datetime parameter's representations",
"# TODO limit to [self.start, self.stop) so messages are less confusing? Done trivially it can kill correctness",
"sample_datetimes",
"=",
"[",
"datetime",
"(",
"y",
",",
"m",
",",
"d",
",",
"h",
")",
"for",
"y",
"in",
"range",
"(",
"2000",
",",
"2050",
",",
"10",
")",
"for",
"m",
"in",
"range",
"(",
"1",
",",
"4",
")",
"for",
"d",
"in",
"range",
"(",
"5",
",",
"8",
")",
"for",
"h",
"in",
"range",
"(",
"21",
",",
"24",
")",
"]",
"regexes",
"=",
"[",
"re",
".",
"compile",
"(",
"datetime_to_re",
"(",
"d",
")",
")",
"for",
"d",
"in",
"sample_datetimes",
"]",
"sample_tasks",
"=",
"[",
"datetime_to_task",
"(",
"d",
")",
"for",
"d",
"in",
"sample_datetimes",
"]",
"sample_outputs",
"=",
"[",
"flatten_output",
"(",
"t",
")",
"for",
"t",
"in",
"sample_tasks",
"]",
"for",
"o",
",",
"t",
"in",
"zip",
"(",
"sample_outputs",
",",
"sample_tasks",
")",
":",
"if",
"len",
"(",
"o",
")",
"!=",
"len",
"(",
"sample_outputs",
"[",
"0",
"]",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Outputs must be consistent over time, sorry; was %r for %r and %r for %r\"",
"%",
"(",
"o",
",",
"t",
",",
"sample_outputs",
"[",
"0",
"]",
",",
"sample_tasks",
"[",
"0",
"]",
")",
")",
"# TODO fall back on requiring last couple of days? to avoid astonishing blocking when changes like that are deployed",
"# erm, actually it's not hard to test entire hours_back..hours_forward and split into consistent subranges FIXME?",
"for",
"target",
"in",
"o",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"FileSystemTarget",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Output targets must be instances of FileSystemTarget; was %r for %r\"",
"%",
"(",
"target",
",",
"t",
")",
")",
"for",
"o",
"in",
"zip",
"(",
"*",
"sample_outputs",
")",
":",
"# transposed, so here we're iterating over logical outputs, not datetimes",
"glob",
"=",
"_get_per_location_glob",
"(",
"sample_tasks",
",",
"o",
",",
"regexes",
")",
"yield",
"o",
"[",
"0",
"]",
".",
"fs",
",",
"glob"
] | Yields a (filesystem, glob) tuple per every output location of task.
The task can have one or several FileSystemTarget outputs.
For convenience, the task can be a luigi.WrapperTask,
in which case outputs of all its dependencies are considered. | [
"Yields",
"a",
"(",
"filesystem",
"glob",
")",
"tuple",
"per",
"every",
"output",
"location",
"of",
"task",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L573-L600 | train |
spotify/luigi | luigi/tools/range.py | _list_existing | def _list_existing(filesystem, glob, paths):
"""
Get all the paths that do in fact exist. Returns a set of all existing paths.
Takes a luigi.target.FileSystem object, a str which represents a glob and
a list of strings representing paths.
"""
globs = _constrain_glob(glob, paths)
time_start = time.time()
listing = []
for g in sorted(globs):
logger.debug('Listing %s', g)
if filesystem.exists(g):
listing.extend(filesystem.listdir(g))
logger.debug('%d %s listings took %f s to return %d items',
len(globs), filesystem.__class__.__name__, time.time() - time_start, len(listing))
return set(listing) | python | def _list_existing(filesystem, glob, paths):
"""
Get all the paths that do in fact exist. Returns a set of all existing paths.
Takes a luigi.target.FileSystem object, a str which represents a glob and
a list of strings representing paths.
"""
globs = _constrain_glob(glob, paths)
time_start = time.time()
listing = []
for g in sorted(globs):
logger.debug('Listing %s', g)
if filesystem.exists(g):
listing.extend(filesystem.listdir(g))
logger.debug('%d %s listings took %f s to return %d items',
len(globs), filesystem.__class__.__name__, time.time() - time_start, len(listing))
return set(listing) | [
"def",
"_list_existing",
"(",
"filesystem",
",",
"glob",
",",
"paths",
")",
":",
"globs",
"=",
"_constrain_glob",
"(",
"glob",
",",
"paths",
")",
"time_start",
"=",
"time",
".",
"time",
"(",
")",
"listing",
"=",
"[",
"]",
"for",
"g",
"in",
"sorted",
"(",
"globs",
")",
":",
"logger",
".",
"debug",
"(",
"'Listing %s'",
",",
"g",
")",
"if",
"filesystem",
".",
"exists",
"(",
"g",
")",
":",
"listing",
".",
"extend",
"(",
"filesystem",
".",
"listdir",
"(",
"g",
")",
")",
"logger",
".",
"debug",
"(",
"'%d %s listings took %f s to return %d items'",
",",
"len",
"(",
"globs",
")",
",",
"filesystem",
".",
"__class__",
".",
"__name__",
",",
"time",
".",
"time",
"(",
")",
"-",
"time_start",
",",
"len",
"(",
"listing",
")",
")",
"return",
"set",
"(",
"listing",
")"
] | Get all the paths that do in fact exist. Returns a set of all existing paths.
Takes a luigi.target.FileSystem object, a str which represents a glob and
a list of strings representing paths. | [
"Get",
"all",
"the",
"paths",
"that",
"do",
"in",
"fact",
"exist",
".",
"Returns",
"a",
"set",
"of",
"all",
"existing",
"paths",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L603-L619 | train |
spotify/luigi | luigi/tools/range.py | infer_bulk_complete_from_fs | def infer_bulk_complete_from_fs(datetimes, datetime_to_task, datetime_to_re):
"""
Efficiently determines missing datetimes by filesystem listing.
The current implementation works for the common case of a task writing
output to a ``FileSystemTarget`` whose path is built using strftime with
format like '...%Y...%m...%d...%H...', without custom ``complete()`` or
``exists()``.
(Eventually Luigi could have ranges of completion as first-class citizens.
Then this listing business could be factored away/be provided for
explicitly in target API or some kind of a history server.)
"""
filesystems_and_globs_by_location = _get_filesystems_and_globs(datetime_to_task, datetime_to_re)
paths_by_datetime = [[o.path for o in flatten_output(datetime_to_task(d))] for d in datetimes]
listing = set()
for (f, g), p in zip(filesystems_and_globs_by_location, zip(*paths_by_datetime)): # transposed, so here we're iterating over logical outputs, not datetimes
listing |= _list_existing(f, g, p)
# quickly learn everything that's missing
missing_datetimes = []
for d, p in zip(datetimes, paths_by_datetime):
if not set(p) <= listing:
missing_datetimes.append(d)
return missing_datetimes | python | def infer_bulk_complete_from_fs(datetimes, datetime_to_task, datetime_to_re):
"""
Efficiently determines missing datetimes by filesystem listing.
The current implementation works for the common case of a task writing
output to a ``FileSystemTarget`` whose path is built using strftime with
format like '...%Y...%m...%d...%H...', without custom ``complete()`` or
``exists()``.
(Eventually Luigi could have ranges of completion as first-class citizens.
Then this listing business could be factored away/be provided for
explicitly in target API or some kind of a history server.)
"""
filesystems_and_globs_by_location = _get_filesystems_and_globs(datetime_to_task, datetime_to_re)
paths_by_datetime = [[o.path for o in flatten_output(datetime_to_task(d))] for d in datetimes]
listing = set()
for (f, g), p in zip(filesystems_and_globs_by_location, zip(*paths_by_datetime)): # transposed, so here we're iterating over logical outputs, not datetimes
listing |= _list_existing(f, g, p)
# quickly learn everything that's missing
missing_datetimes = []
for d, p in zip(datetimes, paths_by_datetime):
if not set(p) <= listing:
missing_datetimes.append(d)
return missing_datetimes | [
"def",
"infer_bulk_complete_from_fs",
"(",
"datetimes",
",",
"datetime_to_task",
",",
"datetime_to_re",
")",
":",
"filesystems_and_globs_by_location",
"=",
"_get_filesystems_and_globs",
"(",
"datetime_to_task",
",",
"datetime_to_re",
")",
"paths_by_datetime",
"=",
"[",
"[",
"o",
".",
"path",
"for",
"o",
"in",
"flatten_output",
"(",
"datetime_to_task",
"(",
"d",
")",
")",
"]",
"for",
"d",
"in",
"datetimes",
"]",
"listing",
"=",
"set",
"(",
")",
"for",
"(",
"f",
",",
"g",
")",
",",
"p",
"in",
"zip",
"(",
"filesystems_and_globs_by_location",
",",
"zip",
"(",
"*",
"paths_by_datetime",
")",
")",
":",
"# transposed, so here we're iterating over logical outputs, not datetimes",
"listing",
"|=",
"_list_existing",
"(",
"f",
",",
"g",
",",
"p",
")",
"# quickly learn everything that's missing",
"missing_datetimes",
"=",
"[",
"]",
"for",
"d",
",",
"p",
"in",
"zip",
"(",
"datetimes",
",",
"paths_by_datetime",
")",
":",
"if",
"not",
"set",
"(",
"p",
")",
"<=",
"listing",
":",
"missing_datetimes",
".",
"append",
"(",
"d",
")",
"return",
"missing_datetimes"
] | Efficiently determines missing datetimes by filesystem listing.
The current implementation works for the common case of a task writing
output to a ``FileSystemTarget`` whose path is built using strftime with
format like '...%Y...%m...%d...%H...', without custom ``complete()`` or
``exists()``.
(Eventually Luigi could have ranges of completion as first-class citizens.
Then this listing business could be factored away/be provided for
explicitly in target API or some kind of a history server.) | [
"Efficiently",
"determines",
"missing",
"datetimes",
"by",
"filesystem",
"listing",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L622-L647 | train |
spotify/luigi | luigi/tools/range.py | RangeBase.of_cls | def of_cls(self):
"""
DONT USE. Will be deleted soon. Use ``self.of``!
"""
if isinstance(self.of, six.string_types):
warnings.warn('When using Range programatically, dont pass "of" param as string!')
return Register.get_task_cls(self.of)
return self.of | python | def of_cls(self):
"""
DONT USE. Will be deleted soon. Use ``self.of``!
"""
if isinstance(self.of, six.string_types):
warnings.warn('When using Range programatically, dont pass "of" param as string!')
return Register.get_task_cls(self.of)
return self.of | [
"def",
"of_cls",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"of",
",",
"six",
".",
"string_types",
")",
":",
"warnings",
".",
"warn",
"(",
"'When using Range programatically, dont pass \"of\" param as string!'",
")",
"return",
"Register",
".",
"get_task_cls",
"(",
"self",
".",
"of",
")",
"return",
"self",
".",
"of"
] | DONT USE. Will be deleted soon. Use ``self.of``! | [
"DONT",
"USE",
".",
"Will",
"be",
"deleted",
"soon",
".",
"Use",
"self",
".",
"of",
"!"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L117-L124 | train |
spotify/luigi | luigi/tools/range.py | RangeBase._emit_metrics | def _emit_metrics(self, missing_datetimes, finite_start, finite_stop):
"""
For consistent metrics one should consider the entire range, but
it is open (infinite) if stop or start is None.
Hence make do with metrics respective to the finite simplification.
"""
datetimes = self.finite_datetimes(
finite_start if self.start is None else min(finite_start, self.parameter_to_datetime(self.start)),
finite_stop if self.stop is None else max(finite_stop, self.parameter_to_datetime(self.stop)))
delay_in_jobs = len(datetimes) - datetimes.index(missing_datetimes[0]) if datetimes and missing_datetimes else 0
self.trigger_event(RangeEvent.DELAY, self.of_cls.task_family, delay_in_jobs)
expected_count = len(datetimes)
complete_count = expected_count - len(missing_datetimes)
self.trigger_event(RangeEvent.COMPLETE_COUNT, self.of_cls.task_family, complete_count)
self.trigger_event(RangeEvent.COMPLETE_FRACTION, self.of_cls.task_family, float(complete_count) / expected_count if expected_count else 1) | python | def _emit_metrics(self, missing_datetimes, finite_start, finite_stop):
"""
For consistent metrics one should consider the entire range, but
it is open (infinite) if stop or start is None.
Hence make do with metrics respective to the finite simplification.
"""
datetimes = self.finite_datetimes(
finite_start if self.start is None else min(finite_start, self.parameter_to_datetime(self.start)),
finite_stop if self.stop is None else max(finite_stop, self.parameter_to_datetime(self.stop)))
delay_in_jobs = len(datetimes) - datetimes.index(missing_datetimes[0]) if datetimes and missing_datetimes else 0
self.trigger_event(RangeEvent.DELAY, self.of_cls.task_family, delay_in_jobs)
expected_count = len(datetimes)
complete_count = expected_count - len(missing_datetimes)
self.trigger_event(RangeEvent.COMPLETE_COUNT, self.of_cls.task_family, complete_count)
self.trigger_event(RangeEvent.COMPLETE_FRACTION, self.of_cls.task_family, float(complete_count) / expected_count if expected_count else 1) | [
"def",
"_emit_metrics",
"(",
"self",
",",
"missing_datetimes",
",",
"finite_start",
",",
"finite_stop",
")",
":",
"datetimes",
"=",
"self",
".",
"finite_datetimes",
"(",
"finite_start",
"if",
"self",
".",
"start",
"is",
"None",
"else",
"min",
"(",
"finite_start",
",",
"self",
".",
"parameter_to_datetime",
"(",
"self",
".",
"start",
")",
")",
",",
"finite_stop",
"if",
"self",
".",
"stop",
"is",
"None",
"else",
"max",
"(",
"finite_stop",
",",
"self",
".",
"parameter_to_datetime",
"(",
"self",
".",
"stop",
")",
")",
")",
"delay_in_jobs",
"=",
"len",
"(",
"datetimes",
")",
"-",
"datetimes",
".",
"index",
"(",
"missing_datetimes",
"[",
"0",
"]",
")",
"if",
"datetimes",
"and",
"missing_datetimes",
"else",
"0",
"self",
".",
"trigger_event",
"(",
"RangeEvent",
".",
"DELAY",
",",
"self",
".",
"of_cls",
".",
"task_family",
",",
"delay_in_jobs",
")",
"expected_count",
"=",
"len",
"(",
"datetimes",
")",
"complete_count",
"=",
"expected_count",
"-",
"len",
"(",
"missing_datetimes",
")",
"self",
".",
"trigger_event",
"(",
"RangeEvent",
".",
"COMPLETE_COUNT",
",",
"self",
".",
"of_cls",
".",
"task_family",
",",
"complete_count",
")",
"self",
".",
"trigger_event",
"(",
"RangeEvent",
".",
"COMPLETE_FRACTION",
",",
"self",
".",
"of_cls",
".",
"task_family",
",",
"float",
"(",
"complete_count",
")",
"/",
"expected_count",
"if",
"expected_count",
"else",
"1",
")"
] | For consistent metrics one should consider the entire range, but
it is open (infinite) if stop or start is None.
Hence make do with metrics respective to the finite simplification. | [
"For",
"consistent",
"metrics",
"one",
"should",
"consider",
"the",
"entire",
"range",
"but",
"it",
"is",
"open",
"(",
"infinite",
")",
"if",
"stop",
"or",
"start",
"is",
"None",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L166-L183 | train |
spotify/luigi | luigi/tools/range.py | RangeBase.missing_datetimes | def missing_datetimes(self, finite_datetimes):
"""
Override in subclasses to do bulk checks.
Returns a sorted list.
This is a conservative base implementation that brutally checks completeness, instance by instance.
Inadvisable as it may be slow.
"""
return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()] | python | def missing_datetimes(self, finite_datetimes):
"""
Override in subclasses to do bulk checks.
Returns a sorted list.
This is a conservative base implementation that brutally checks completeness, instance by instance.
Inadvisable as it may be slow.
"""
return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()] | [
"def",
"missing_datetimes",
"(",
"self",
",",
"finite_datetimes",
")",
":",
"return",
"[",
"d",
"for",
"d",
"in",
"finite_datetimes",
"if",
"not",
"self",
".",
"_instantiate_task_cls",
"(",
"self",
".",
"datetime_to_parameter",
"(",
"d",
")",
")",
".",
"complete",
"(",
")",
"]"
] | Override in subclasses to do bulk checks.
Returns a sorted list.
This is a conservative base implementation that brutally checks completeness, instance by instance.
Inadvisable as it may be slow. | [
"Override",
"in",
"subclasses",
"to",
"do",
"bulk",
"checks",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L255-L265 | train |
spotify/luigi | luigi/tools/range.py | RangeBase._missing_datetimes | def _missing_datetimes(self, finite_datetimes):
"""
Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015)
"""
try:
return self.missing_datetimes(finite_datetimes)
except TypeError as ex:
if 'missing_datetimes()' in repr(ex):
warnings.warn('In your Range* subclass, missing_datetimes() should only take 1 argument (see latest docs)')
return self.missing_datetimes(self.of_cls, finite_datetimes)
else:
raise | python | def _missing_datetimes(self, finite_datetimes):
"""
Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015)
"""
try:
return self.missing_datetimes(finite_datetimes)
except TypeError as ex:
if 'missing_datetimes()' in repr(ex):
warnings.warn('In your Range* subclass, missing_datetimes() should only take 1 argument (see latest docs)')
return self.missing_datetimes(self.of_cls, finite_datetimes)
else:
raise | [
"def",
"_missing_datetimes",
"(",
"self",
",",
"finite_datetimes",
")",
":",
"try",
":",
"return",
"self",
".",
"missing_datetimes",
"(",
"finite_datetimes",
")",
"except",
"TypeError",
"as",
"ex",
":",
"if",
"'missing_datetimes()'",
"in",
"repr",
"(",
"ex",
")",
":",
"warnings",
".",
"warn",
"(",
"'In your Range* subclass, missing_datetimes() should only take 1 argument (see latest docs)'",
")",
"return",
"self",
".",
"missing_datetimes",
"(",
"self",
".",
"of_cls",
",",
"finite_datetimes",
")",
"else",
":",
"raise"
] | Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015) | [
"Backward",
"compatible",
"wrapper",
".",
"Will",
"be",
"deleted",
"eventually",
"(",
"stated",
"on",
"Dec",
"2015",
")"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L267-L278 | train |
spotify/luigi | luigi/tools/range.py | RangeDailyBase.parameters_to_datetime | def parameters_to_datetime(self, p):
"""
Given a dictionary of parameters, will extract the ranged task parameter value
"""
dt = p[self._param_name]
return datetime(dt.year, dt.month, dt.day) | python | def parameters_to_datetime(self, p):
"""
Given a dictionary of parameters, will extract the ranged task parameter value
"""
dt = p[self._param_name]
return datetime(dt.year, dt.month, dt.day) | [
"def",
"parameters_to_datetime",
"(",
"self",
",",
"p",
")",
":",
"dt",
"=",
"p",
"[",
"self",
".",
"_param_name",
"]",
"return",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")"
] | Given a dictionary of parameters, will extract the ranged task parameter value | [
"Given",
"a",
"dictionary",
"of",
"parameters",
"will",
"extract",
"the",
"ranged",
"task",
"parameter",
"value"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L316-L321 | train |
spotify/luigi | luigi/tools/range.py | RangeDailyBase.finite_datetimes | def finite_datetimes(self, finite_start, finite_stop):
"""
Simply returns the points in time that correspond to turn of day.
"""
date_start = datetime(finite_start.year, finite_start.month, finite_start.day)
dates = []
for i in itertools.count():
t = date_start + timedelta(days=i)
if t >= finite_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 day.
"""
date_start = datetime(finite_start.year, finite_start.month, finite_start.day)
dates = []
for i in itertools.count():
t = date_start + timedelta(days=i)
if t >= finite_stop:
return dates
if t >= finite_start:
dates.append(t) | [
"def",
"finite_datetimes",
"(",
"self",
",",
"finite_start",
",",
"finite_stop",
")",
":",
"date_start",
"=",
"datetime",
"(",
"finite_start",
".",
"year",
",",
"finite_start",
".",
"month",
",",
"finite_start",
".",
"day",
")",
"dates",
"=",
"[",
"]",
"for",
"i",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"t",
"=",
"date_start",
"+",
"timedelta",
"(",
"days",
"=",
"i",
")",
"if",
"t",
">=",
"finite_stop",
":",
"return",
"dates",
"if",
"t",
">=",
"finite_start",
":",
"dates",
".",
"append",
"(",
"t",
")"
] | Simply returns the points in time that correspond to turn of day. | [
"Simply",
"returns",
"the",
"points",
"in",
"time",
"that",
"correspond",
"to",
"turn",
"of",
"day",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L329-L340 | train |
spotify/luigi | luigi/tools/range.py | RangeHourlyBase.finite_datetimes | def finite_datetimes(self, finite_start, finite_stop):
"""
Simply returns the points in time that correspond to whole hours.
"""
datehour_start = datetime(finite_start.year, finite_start.month, finite_start.day, finite_start.hour)
datehours = []
for i in itertools.count():
t = datehour_start + timedelta(hours=i)
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 whole hours.
"""
datehour_start = datetime(finite_start.year, finite_start.month, finite_start.day, finite_start.hour)
datehours = []
for i in itertools.count():
t = datehour_start + timedelta(hours=i)
if t >= finite_stop:
return datehours
if t >= finite_start:
datehours.append(t) | [
"def",
"finite_datetimes",
"(",
"self",
",",
"finite_start",
",",
"finite_stop",
")",
":",
"datehour_start",
"=",
"datetime",
"(",
"finite_start",
".",
"year",
",",
"finite_start",
".",
"month",
",",
"finite_start",
".",
"day",
",",
"finite_start",
".",
"hour",
")",
"datehours",
"=",
"[",
"]",
"for",
"i",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"t",
"=",
"datehour_start",
"+",
"timedelta",
"(",
"hours",
"=",
"i",
")",
"if",
"t",
">=",
"finite_stop",
":",
"return",
"datehours",
"if",
"t",
">=",
"finite_start",
":",
"datehours",
".",
"append",
"(",
"t",
")"
] | Simply returns the points in time that correspond to whole hours. | [
"Simply",
"returns",
"the",
"points",
"in",
"time",
"that",
"correspond",
"to",
"whole",
"hours",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L391-L402 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.