code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def recursively_unfreeze(value):
"""
Recursively walks ``FrozenOrderedDict``s and ``tuple``s and converts them to ``dict`` and ``list``, respectively.
"""
if isinstance(value, Mapping):
return dict(((k, recursively_unfreeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return list(recursively_unfreeze(v) for v in value)
return value | Recursively walks ``FrozenOrderedDict``s and ``tuple``s and converts them to ``dict`` and ``list``, respectively. | recursively_unfreeze | python | spotify/luigi | luigi/freezing.py | https://github.com/spotify/luigi/blob/master/luigi/freezing.py | Apache-2.0 |
def __init__(self, default=_no_value, is_global=False, significant=True, description=None,
config_path=None, positional=True, always_in_help=False, batch_method=None,
visibility=ParameterVisibility.PUBLIC):
"""
:param default: the default value for this parameter. This should match the type of the
Parameter, i.e. ``datetime.date`` for ``DateParameter`` or ``int`` for
``IntParameter``. By default, no default is stored and
the value must be specified at runtime.
:param bool significant: specify ``False`` if the parameter should not be treated as part of
the unique identifier for a Task. An insignificant Parameter might
also be used to specify a password or other sensitive information
that should not be made public via the scheduler. Default:
``True``.
:param str description: A human-readable string describing the purpose of this Parameter.
For command-line invocations, this will be used as the `help` string
shown to users. Default: ``None``.
:param dict config_path: a dictionary with entries ``section`` and ``name``
specifying a config file entry from which to read the
default value for this parameter. DEPRECATED.
Default: ``None``.
:param bool positional: If true, you can set the argument as a
positional argument. It's true by default but we recommend
``positional=False`` for abstract base classes and similar cases.
:param bool always_in_help: For the --help option in the command line
parsing. Set true to always show in --help.
:param function(iterable[A])->A batch_method: Method to combine an iterable of parsed
parameter values into a single value. Used
when receiving batched parameter lists from
the scheduler. See :ref:`batch_method`
:param visibility: A Parameter whose value is a :py:class:`~luigi.parameter.ParameterVisibility`.
Default value is ParameterVisibility.PUBLIC
"""
self._default = default
self._batch_method = batch_method
if is_global:
warnings.warn("is_global support is removed. Assuming positional=False",
DeprecationWarning,
stacklevel=2)
positional = False
self.significant = significant # Whether different values for this parameter will differentiate otherwise equal tasks
self.positional = positional
self.visibility = visibility if ParameterVisibility.has_value(visibility) else ParameterVisibility.PUBLIC
self.description = description
self.always_in_help = always_in_help
if config_path is not None and ('section' not in config_path or 'name' not in config_path):
raise ParameterException('config_path must be a hash containing entries for section and name')
self._config_path = config_path
self._counter = Parameter._counter # We need to keep track of this to get the order right (see Task class)
Parameter._counter += 1 | :param default: the default value for this parameter. This should match the type of the
Parameter, i.e. ``datetime.date`` for ``DateParameter`` or ``int`` for
``IntParameter``. By default, no default is stored and
the value must be specified at runtime.
:param bool significant: specify ``False`` if the parameter should not be treated as part of
the unique identifier for a Task. An insignificant Parameter might
also be used to specify a password or other sensitive information
that should not be made public via the scheduler. Default:
``True``.
:param str description: A human-readable string describing the purpose of this Parameter.
For command-line invocations, this will be used as the `help` string
shown to users. Default: ``None``.
:param dict config_path: a dictionary with entries ``section`` and ``name``
specifying a config file entry from which to read the
default value for this parameter. DEPRECATED.
Default: ``None``.
:param bool positional: If true, you can set the argument as a
positional argument. It's true by default but we recommend
``positional=False`` for abstract base classes and similar cases.
:param bool always_in_help: For the --help option in the command line
parsing. Set true to always show in --help.
:param function(iterable[A])->A batch_method: Method to combine an iterable of parsed
parameter values into a single value. Used
when receiving batched parameter lists from
the scheduler. See :ref:`batch_method`
:param visibility: A Parameter whose value is a :py:class:`~luigi.parameter.ParameterVisibility`.
Default value is ParameterVisibility.PUBLIC | __init__ | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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) | Loads the default from the config. Returns _no_value if it doesn't exist | _get_value_from_config | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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) | 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. | _value_iterator | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, x):
"""
Parse an individual value from the input.
The default implementation is the identity function, but subclasses should override
this method for specialized parsing.
:param str x: the value to parse.
:return: the parsed value.
"""
return x # default impl | Parse an individual value from the input.
The default implementation is the identity function, but subclasses should override
this method for specialized parsing.
:param str x: the value to parse.
:return: the parsed value. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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)) | 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_list | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def serialize(self, x):
"""
Opposite of :py:meth:`parse`.
Converts the value ``x`` to a string.
:param x: the value to serialize.
"""
return str(x) | Opposite of :py:meth:`parse`.
Converts the value ``x`` to a string.
:param x: the value to serialize. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def normalize(self, x):
"""
Given a parsed parameter value, normalizes it.
The value can either be the result of parse(), the default value or
arguments passed into the task's constructor by instantiation.
This is very implementation defined, but can be used to validate/clamp
valid values. For example, if you wanted to only accept even integers,
and "correct" odd values to the nearest integer, you can implement
normalize as ``x // 2 * 2``.
"""
return x # default impl | Given a parsed parameter value, normalizes it.
The value can either be the result of parse(), the default value or
arguments passed into the task's constructor by instantiation.
This is very implementation defined, but can be used to validate/clamp
valid values. For example, if you wanted to only accept even integers,
and "correct" odd values to the nearest integer, you can implement
normalize as ``x // 2 * 2``. | normalize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def next_in_enumeration(self, value):
"""
If your Parameter type has an enumerable ordering of values. You can
choose to override this method. This method is used by the
:py:mod:`luigi.execution_summary` module for pretty printing
purposes. Enabling it to pretty print tasks like ``MyTask(num=1),
MyTask(num=2), MyTask(num=3)`` to ``MyTask(num=1..3)``.
:param value: The value
:return: The next value, like "value + 1". Or ``None`` if there's no enumerable ordering.
"""
return None | If your Parameter type has an enumerable ordering of values. You can
choose to override this method. This method is used by the
:py:mod:`luigi.execution_summary` module for pretty printing
purposes. Enabling it to pretty print tasks like ``MyTask(num=1),
MyTask(num=2), MyTask(num=3)`` to ``MyTask(num=1..3)``.
:param value: The value
:return: The next value, like "value + 1". Or ``None`` if there's no enumerable ordering. | next_in_enumeration | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def serialize(self, x):
"""
Parse the given value if the value is not None else return an empty string.
"""
if x is None:
return ''
else:
return super().serialize(x) | Parse the given value if the value is not None else return an empty string. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, x):
"""
Parse the given value if it is a string (empty strings are parsed to None).
"""
if not isinstance(x, str):
return x
elif x:
return super().parse(x)
else:
return None | Parse the given value if it is a string (empty strings are parsed to None). | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def normalize(self, x):
"""
Normalize the given value if it is not None.
"""
if x is None:
return None
return super().normalize(x) | Normalize the given value if it is not None. | normalize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def date_format(self):
"""
Override me with a :py:meth:`~datetime.date.strftime` string.
"""
pass | Override me with a :py:meth:`~datetime.date.strftime` string. | date_format | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | Parses a date string formatted like ``YYYY-MM-DD``. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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) | Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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) | 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 | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def date_format(self):
"""
Override me with a :py:meth:`~datetime.date.strftime` string.
"""
pass | Override me with a :py:meth:`~datetime.date.strftime` string. | date_format | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def _timedelta(self):
"""
How to move one interval of this type forward (i.e. not counting self.interval).
"""
pass | How to move one interval of this type forward (i.e. not counting self.interval). | _timedelta | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, s):
"""
Parses a string to a :py:class:`~datetime.datetime`.
"""
return datetime.datetime.strptime(s, self.date_format) | Parses a string to a :py:class:`~datetime.datetime`. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DatetimeParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format) | Converts the date to a string using the :py:attr:`~_DatetimeParameterBase.date_format`. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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) | Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`. | normalize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, s):
"""
Parses an ``int`` from the string using ``int()``.
"""
return int(s) | Parses an ``int`` from the string using ``int()``. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, s):
"""
Parses a ``float`` from the string using ``float()``.
"""
return float(s) | Parses a ``float`` from the string using ``float()``. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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)) | Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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') | Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, input):
"""
Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats.
"""
try:
return datetime.timedelta(seconds=float(input))
except ValueError:
pass
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. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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 | Converts datetime.timedelta to a string
:param x: the value to serialize. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, input):
"""
Parse a task_famly using the :class:`~luigi.task_register.Register`
"""
return task_register.Register.get_task_cls(input) | Parse a task_famly using the :class:`~luigi.task_register.Register` | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def serialize(self, cls):
"""
Converts the :py:class:`luigi.task.Task` (sub) class to its family name.
"""
return cls.get_task_family() | Converts the :py:class:`luigi.task.Task` (sub) class to its family name. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def normalize(self, value):
"""
Ensure that dictionary parameter is converted to a FrozenOrderedDict so it can be hashed.
"""
if self.schema is not None:
unfrozen_value = recursively_unfreeze(value)
try:
self.schema.validate(unfrozen_value)
value = unfrozen_value # Validators may update the instance inplace
except AttributeError:
jsonschema.validate(instance=unfrozen_value, schema=self.schema)
return recursively_freeze(value) | Ensure that dictionary parameter is converted to a FrozenOrderedDict so it can be hashed. | normalize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, source):
"""
Parses an immutable and ordered ``dict`` from a JSON string using standard JSON library.
We need to use an immutable dictionary, to create a hashable parameter and also preserve the internal structure
of parsing. The traversal order of standard ``dict`` is undefined, which can result various string
representations of this parameter, and therefore a different task id for the task containing this parameter.
This is because task id contains the hash of parameters' JSON representation.
:param s: String to be parse
"""
# TOML based config convert params to python types itself.
if not isinstance(source, str):
return source
return json.loads(source, object_pairs_hook=FrozenOrderedDict) | Parses an immutable and ordered ``dict`` from a JSON string using standard JSON library.
We need to use an immutable dictionary, to create a hashable parameter and also preserve the internal structure
of parsing. The traversal order of standard ``dict`` is undefined, which can result various string
representations of this parameter, and therefore a different task id for the task containing this parameter.
This is because task id contains the hash of parameters' JSON representation.
:param s: String to be parse | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def normalize(self, x):
"""
Ensure that struct is recursively converted to a tuple so it can be hashed.
:param str x: the value to parse.
:return: the normalized (hashable/immutable) value.
"""
if self.schema is not None:
unfrozen_value = recursively_unfreeze(x)
try:
self.schema.validate(unfrozen_value)
x = unfrozen_value # Validators may update the instance inplace
except AttributeError:
jsonschema.validate(instance=unfrozen_value, schema=self.schema)
return recursively_freeze(x) | Ensure that struct is recursively converted to a tuple so it can be hashed.
:param str x: the value to parse.
:return: the normalized (hashable/immutable) value. | normalize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def parse(self, x):
"""
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value.
"""
i = json.loads(x, object_pairs_hook=FrozenOrderedDict)
if i is None:
return None
return list(i) | Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def serialize(self, x):
"""
Opposite of :py:meth:`parse`.
Converts the value ``x`` to a string.
:param x: the value to serialize.
"""
return json.dumps(x, cls=_DictParamEncoder) | Opposite of :py:meth:`parse`.
Converts the value ``x`` to a string.
:param x: the value to serialize. | serialize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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(self._convert_iterable_to_tuple(x) for x in json.loads(x, object_pairs_hook=FrozenOrderedDict))
except (ValueError, TypeError):
result = literal_eval(x)
# t_str = '("abcd")'
# Ensure that the result is not a string to avoid cases like ('a','b','c','d')
if isinstance(result, str):
raise ValueError("Parsed result cannot be a string")
return tuple(result) # if this causes an error, let that error be raised. | Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value. | parse | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def __init__(self, left_op=operator.le, right_op=operator.lt, *args, **kwargs):
"""
:param function var_type: The type of the input variable, e.g. int or float.
:param min_value: The minimum value permissible in the accepted values
range. May be inclusive or exclusive based on left_op parameter.
This should be the same type as var_type.
:param max_value: The maximum value permissible in the accepted values
range. May be inclusive or exclusive based on right_op parameter.
This should be the same type as var_type.
:param function left_op: The comparison operator for the left-most comparison in
the expression ``min_value left_op value right_op value``.
This operator should generally be either
``operator.lt`` or ``operator.le``.
Default: ``operator.le``.
:param function right_op: The comparison operator for the right-most comparison in
the expression ``min_value left_op value right_op value``.
This operator should generally be either
``operator.lt`` or ``operator.le``.
Default: ``operator.lt``.
"""
if "var_type" not in kwargs:
raise ParameterException("var_type must be specified")
self._var_type = kwargs.pop("var_type")
if "min_value" not in kwargs:
raise ParameterException("min_value must be specified")
self._min_value = kwargs.pop("min_value")
if "max_value" not in kwargs:
raise ParameterException("max_value must be specified")
self._max_value = kwargs.pop("max_value")
self._left_op = left_op
self._right_op = right_op
self._permitted_range = (
"{var_type} in {left_endpoint}{min_value}, {max_value}{right_endpoint}".format(
var_type=self._var_type.__name__,
min_value=self._min_value, max_value=self._max_value,
left_endpoint="[" if left_op == operator.le else "(",
right_endpoint=")" if right_op == operator.lt else "]"))
super(NumericalParameter, self).__init__(*args, **kwargs)
if self.description:
self.description += " "
else:
self.description = ""
self.description += "permitted values: " + self._permitted_range | :param function var_type: The type of the input variable, e.g. int or float.
:param min_value: The minimum value permissible in the accepted values
range. May be inclusive or exclusive based on left_op parameter.
This should be the same type as var_type.
:param max_value: The maximum value permissible in the accepted values
range. May be inclusive or exclusive based on right_op parameter.
This should be the same type as var_type.
:param function left_op: The comparison operator for the left-most comparison in
the expression ``min_value left_op value right_op value``.
This operator should generally be either
``operator.lt`` or ``operator.le``.
Default: ``operator.le``.
:param function right_op: The comparison operator for the right-most comparison in
the expression ``min_value left_op value right_op value``.
This operator should generally be either
``operator.lt`` or ``operator.le``.
Default: ``operator.lt``. | __init__ | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def __init__(self, var_type=str, *args, **kwargs):
"""
:param function var_type: The type of the input variable, e.g. str, int,
float, etc.
Default: str
:param choices: An iterable, all of whose elements are of `var_type` to
restrict parameter choices to.
"""
if "choices" not in kwargs:
raise ParameterException("A choices iterable must be specified")
self._choices = set(kwargs.pop("choices"))
self._var_type = var_type
assert all(type(choice) is self._var_type for choice in self._choices), "Invalid type in choices"
super(ChoiceParameter, self).__init__(*args, **kwargs)
if self.description:
self.description += " "
else:
self.description = ""
self.description += (
"Choices: {" + ", ".join(str(choice) for choice in self._choices) + "}") | :param function var_type: The type of the input variable, e.g. str, int,
float, etc.
Default: str
:param choices: An iterable, all of whose elements are of `var_type` to
restrict parameter choices to. | __init__ | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def __init__(self, *args, absolute=False, exists=False, **kwargs):
"""
:param bool absolute: If set to ``True``, the given path is converted to an absolute path.
:param bool exists: If set to ``True``, a :class:`ValueError` is raised if the path does not exist.
"""
super().__init__(*args, **kwargs)
self.absolute = absolute
self.exists = exists | :param bool absolute: If set to ``True``, the given path is converted to an absolute path.
:param bool exists: If set to ``True``, a :class:`ValueError` is raised if the path does not exist. | __init__ | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
def normalize(self, x):
"""
Normalize the given value to a :class:`pathlib.Path` object.
"""
path = Path(x)
if self.absolute:
path = path.absolute()
if self.exists and not path.exists():
raise ValueError(f"The path {path} does not exist.")
return path | Normalize the given value to a :class:`pathlib.Path` object. | normalize | python | spotify/luigi | luigi/parameter.py | https://github.com/spotify/luigi/blob/master/luigi/parameter.py | Apache-2.0 |
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 | Returns a list of dates in this date interval. | dates | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def hours(self):
''' Same as dates() but returns 24 times more info: one for each hour.'''
for date in self.dates():
for hour in range(24):
yield datetime.datetime.combine(date, datetime.time(hour)) | Same as dates() but returns 24 times more info: one for each hour. | hours | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def prev(self):
''' Returns the preceding corresponding date interval (eg. May -> April).'''
return self.from_date(self.date_a - datetime.timedelta(1)) | Returns the preceding corresponding date interval (eg. May -> April). | prev | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def next(self):
''' Returns the subsequent corresponding date interval (eg. 2014 -> 2015).'''
return self.from_date(self.date_b) | Returns the subsequent corresponding date interval (eg. 2014 -> 2015). | next | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def from_date(cls, d):
''' Abstract class method.
For instance, ``Month.from_date(datetime.date(2012, 6, 6))`` returns a ``Month(2012, 6)``.'''
raise NotImplementedError | Abstract class method.
For instance, ``Month.from_date(datetime.date(2012, 6, 6))`` returns a ``Month(2012, 6)``. | from_date | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def parse(cls, s):
''' Abstract class method.
For instance, ``Year.parse("2014")`` returns a ``Year(2014)``.'''
raise NotImplementedError | Abstract class method.
For instance, ``Year.parse("2014")`` returns a ``Year(2014)``. | parse | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def __init__(self, y, w):
''' Python datetime does not have a method to convert from ISO weeks, so the constructor uses some stupid brute force'''
for d in range(-10, 370):
date = datetime.date(y, 1, 1) + datetime.timedelta(d)
if date.isocalendar() == (y, w, 1):
date_a = date
break
else:
raise ValueError('Invalid week')
date_b = date_a + datetime.timedelta(7)
super(Week, self).__init__(date_a, date_b) | Python datetime does not have a method to convert from ISO weeks, so the constructor uses some stupid brute force | __init__ | python | spotify/luigi | luigi/date_interval.py | https://github.com/spotify/luigi/blob/master/luigi/date_interval.py | Apache-2.0 |
def wrap_traceback(traceback):
"""
For internal use only (until further notice)
"""
if email().format == 'html':
try:
from pygments import highlight
from pygments.lexers import PythonTracebackLexer
from pygments.formatters import HtmlFormatter
with_pygments = True
except ImportError:
with_pygments = False
if with_pygments:
formatter = HtmlFormatter(noclasses=True)
wrapped = highlight(traceback, PythonTracebackLexer(), formatter)
else:
wrapped = '<pre>%s</pre>' % traceback
else:
wrapped = traceback
return wrapped | For internal use only (until further notice) | wrap_traceback | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def send_email_ses(sender, subject, message, recipients, image_png):
"""
Sends notification through AWS SES.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import client as boto3_client
client = boto3_client('ses')
msg_root = generate_email(sender, subject, message, recipients, image_png)
response = client.send_raw_email(Source=sender,
Destinations=recipients,
RawMessage={'Data': msg_root.as_string()})
logger.debug(("Message sent to SES.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) | Sends notification through AWS SES.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. | send_email_ses | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def send_email_sns(sender, subject, message, topic_ARN, image_png):
"""
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import resource as boto3_resource
sns = boto3_resource('sns')
topic = sns.Topic(topic_ARN[0])
# Subject is max 100 chars
if len(subject) > 100:
subject = subject[0:48] + '...' + subject[-49:]
response = topic.publish(Subject=subject, Message=message)
logger.debug(("Message sent to SNS.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) | Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. | send_email_sns | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def send_email(subject, message, sender, recipients, image_png=None):
"""
Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'.
"""
notifiers = {
'ses': send_email_ses,
'sendgrid': send_email_sendgrid,
'smtp': send_email_smtp,
'sns': send_email_sns,
}
subject = _prefix(subject)
if not recipients or recipients == (None,):
return
if _email_disabled_reason():
logger.info("Not sending email to %r because %s",
recipients, _email_disabled_reason())
return
# Clean the recipients lists to allow multiple email addresses, comma
# separated in luigi.cfg
recipients_tmp = []
for r in recipients:
recipients_tmp.extend([a.strip() for a in r.split(',') if a.strip()])
# Replace original recipients with the clean list
recipients = recipients_tmp
logger.info("Sending email to %r", recipients)
# Get appropriate sender and call it to send the notification
email_sender = notifiers[email().method]
email_sender(sender, subject, message, recipients, image_png) | Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'. | send_email | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def send_error_email(subject, message, additional_recipients=None):
"""
Sends an email to the configured error email, if it's configured.
"""
recipients = _email_recipients(additional_recipients)
sender = email().sender
send_email(
subject=subject,
message=message,
sender=sender,
recipients=recipients
) | Sends an email to the configured error email, if it's configured. | send_error_email | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def _prefix(subject):
"""
If the config has a special prefix for emails then this function adds
this prefix.
"""
if email().prefix:
return "{} {}".format(email().prefix, subject)
else:
return subject | If the config has a special prefix for emails then this function adds
this prefix. | _prefix | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def format_task_error(headline, task, command, formatted_exception=None):
"""
Format a message body for an error email related to a luigi.task.Task
:param headline: Summary line for the message
:param task: `luigi.task.Task` instance where this error occurred
:param formatted_exception: optional string showing traceback
:return: message body
"""
if formatted_exception:
if len(formatted_exception) > email().traceback_max_length:
truncated_exception = formatted_exception[:email().traceback_max_length]
formatted_exception = f"{truncated_exception}...Traceback exceeds max length and has been truncated."
if formatted_exception:
formatted_exception = wrap_traceback(formatted_exception)
else:
formatted_exception = ""
if email().format == 'html':
msg_template = textwrap.dedent('''
<html>
<body>
<h2>{headline}</h2>
<table style="border-top: 1px solid black; border-bottom: 1px solid black">
<thead>
<tr><th>name</th><td>{name}</td></tr>
</thead>
<tbody>
{param_rows}
</tbody>
</table>
</pre>
<h2>Command line</h2>
<pre>
{command}
</pre>
<h2>Traceback</h2>
{traceback}
</body>
</html>
''')
str_params = task.to_str_params()
params = '\n'.join('<tr><th>{}</th><td>{}</td></tr>'.format(*items) for items in str_params.items())
body = msg_template.format(headline=headline, name=task.task_family, param_rows=params,
command=command, traceback=formatted_exception)
else:
msg_template = textwrap.dedent('''\
{headline}
Name: {name}
Parameters:
{params}
Command line:
{command}
{traceback}
''')
str_params = task.to_str_params()
max_width = max([0] + [len(x) for x in str_params.keys()])
params = '\n'.join(' {:{width}}: {}'.format(*items, width=max_width) for items in str_params.items())
body = msg_template.format(headline=headline, name=task.task_family, params=params,
command=command, traceback=formatted_exception)
return body | Format a message body for an error email related to a luigi.task.Task
:param headline: Summary line for the message
:param task: `luigi.task.Task` instance where this error occurred
:param formatted_exception: optional string showing traceback
:return: message body | format_task_error | python | spotify/luigi | luigi/notifications.py | https://github.com/spotify/luigi/blob/master/luigi/notifications.py | Apache-2.0 |
def add_failure(self):
"""
Add a failure event with the current timestamp.
"""
failure_time = time.time()
if not self.first_failure_time:
self.first_failure_time = failure_time
self.failures.append(failure_time) | Add a failure event with the current timestamp. | add_failure | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def num_failures(self):
"""
Return the number of failures in the window.
"""
min_time = time.time() - self.retry_policy.disable_window
while self.failures and self.failures[0] < min_time:
self.failures.popleft()
return len(self.failures) | Return the number of failures in the window. | num_failures | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def clear_failures(self):
"""
Clear the failures history
"""
self.failures.clear()
self.first_failure_time = None | Clear the failures history | clear_failures | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def is_trivial_worker(self, state):
"""
If it's not an assistant having only tasks that are without
requirements.
We have to pass the state parameter for optimization reasons.
"""
if self.assistant:
return False
return all(not task.resources for task in self.get_tasks(state, PENDING)) | If it's not an assistant having only tasks that are without
requirements.
We have to pass the state parameter for optimization reasons. | is_trivial_worker | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def num_pending_tasks(self):
"""
Return how many tasks are PENDING + RUNNING. O(1).
"""
return len(self._status_tasks[PENDING]) + len(self._status_tasks[RUNNING]) | Return how many tasks are PENDING + RUNNING. O(1). | num_pending_tasks | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def __init__(self, config=None, resources=None, task_history_impl=None, **kwargs):
"""
Keyword Arguments:
:param config: an object of class "scheduler" or None (in which the global instance will be used)
:param resources: a dict of str->int constraints
:param task_history_impl: ignore config and use this object as the task history
"""
self._config = config or scheduler(**kwargs)
self._state = SimpleTaskState(self._config.state_path)
if task_history_impl:
self._task_history = task_history_impl
elif self._config.record_task_history:
from luigi import db_task_history # Needs sqlalchemy, thus imported here
self._task_history = db_task_history.DbTaskHistory()
else:
self._task_history = history.NopHistory()
self._resources = resources or configuration.get_config().getintdict('resources') # TODO: Can we make this a Parameter?
self._make_task = functools.partial(Task, retry_policy=self._config._get_retry_policy())
self._worker_requests = {}
self._paused = False
if self._config.batch_emails:
self._email_batcher = BatchNotifier()
self._state._metrics_collector = MetricsCollectors.get(self._config.metrics_collector, self._config.metrics_custom_import) | Keyword Arguments:
:param config: an object of class "scheduler" or None (in which the global instance will be used)
:param resources: a dict of str->int constraints
:param task_history_impl: ignore config and use this object as the task history | __init__ | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def _update_priority(self, task, prio, worker):
"""
Update priority of the given task.
Priority can only be increased.
If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled.
"""
task.priority = prio = max(prio, task.priority)
for dep in task.deps or []:
t = self._state.get_task(dep)
if t is not None and prio > t.priority:
self._update_priority(t, prio, worker) | Update priority of the given task.
Priority can only be increased.
If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled. | _update_priority | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def add_task(self, task_id=None, status=PENDING, runnable=True,
deps=None, new_deps=None, expl=None, resources=None,
priority=0, family='', module=None, params=None, param_visibilities=None, accepts_messages=False,
assistant=False, tracking_url=None, worker=None, batchable=None,
batch_id=None, retry_policy_dict=None, owners=None, **kwargs):
"""
* add task identified by task_id if it doesn't exist
* if deps is not None, update dependency list
* update status of task
* add additional workers/stakeholders
* update priority when needed
"""
assert worker is not None
worker_id = worker
worker = self._update_worker(worker_id)
resources = {} if resources is None else resources.copy()
if retry_policy_dict is None:
retry_policy_dict = {}
retry_policy = self._generate_retry_policy(retry_policy_dict)
if worker.enabled:
_default_task = self._make_task(
task_id=task_id, status=PENDING, deps=deps, resources=resources,
priority=priority, family=family, module=module, params=params, param_visibilities=param_visibilities,
)
else:
_default_task = None
task = self._state.get_task(task_id, setdefault=_default_task)
if task is None or (task.status != RUNNING and not worker.enabled):
return
# Ignore claims that the task is PENDING if it very recently was marked as DONE.
if status == PENDING and task.status == DONE and (time.time() - task.updated) < self._config.stable_done_cooldown_secs:
return
# for setting priority, we'll sometimes create tasks with unset family and params
if not task.family:
task.family = family
if not getattr(task, 'module', None):
task.module = module
if not getattr(task, 'param_visibilities', None):
task.param_visibilities = _get_default(param_visibilities, {})
if not task.params:
task.set_params(params)
if batch_id is not None:
task.batch_id = batch_id
if status == RUNNING and not task.worker_running:
task.worker_running = worker_id
if batch_id:
# copy resources_running of the first batch task
batch_tasks = self._state.get_batch_running_tasks(batch_id)
task.resources_running = batch_tasks[0].resources_running.copy()
task.time_running = time.time()
if accepts_messages is not None:
task.accepts_messages = accepts_messages
if tracking_url is not None or task.status != RUNNING:
task.tracking_url = tracking_url
if task.batch_id is not None:
for batch_task in self._state.get_batch_running_tasks(task.batch_id):
batch_task.tracking_url = tracking_url
if batchable is not None:
task.batchable = batchable
if task.remove is not None:
task.remove = None # unmark task for removal so it isn't removed after being added
if expl is not None:
task.expl = expl
if task.batch_id is not None:
for batch_task in self._state.get_batch_running_tasks(task.batch_id):
batch_task.expl = expl
task_is_not_running = task.status not in (RUNNING, BATCH_RUNNING)
task_started_a_run = status in (DONE, FAILED, RUNNING)
running_on_this_worker = task.worker_running == worker_id
if task_is_not_running or (task_started_a_run and running_on_this_worker) or new_deps:
# don't allow re-scheduling of task while it is running, it must either fail or succeed on the worker actually running it
if status != task.status or status == PENDING:
# Update the DB only if there was a acctual change, to prevent noise.
# We also check for status == PENDING b/c that's the default value
# (so checking for status != task.status woule lie)
self._update_task_history(task, status)
self._state.set_status(task, PENDING if status == SUSPENDED else status, self._config)
if status == FAILED and self._config.batch_emails:
batched_params, _ = self._state.get_batcher(worker_id, family)
if batched_params:
unbatched_params = {
param: value
for param, value in task.params.items()
if param not in batched_params
}
else:
unbatched_params = task.params
try:
expl_raw = json.loads(expl)
except ValueError:
expl_raw = expl
self._email_batcher.add_failure(
task.pretty_id, task.family, unbatched_params, expl_raw, owners)
if task.status == DISABLED:
self._email_batcher.add_disable(
task.pretty_id, task.family, unbatched_params, owners)
if deps is not None:
task.deps = set(deps)
if new_deps is not None:
task.deps.update(new_deps)
if resources is not None:
task.resources = resources
if worker.enabled and not assistant:
task.stakeholders.add(worker_id)
# Task dependencies might not exist yet. Let's create dummy tasks for them for now.
# Otherwise the task dependencies might end up being pruned if scheduling takes a long time
for dep in task.deps or []:
t = self._state.get_task(dep, setdefault=self._make_task(task_id=dep, status=UNKNOWN, deps=None, priority=priority))
t.stakeholders.add(worker_id)
self._update_priority(task, priority, worker_id)
# Because some tasks (non-dynamic dependencies) are `_make_task`ed
# before we know their retry_policy, we always set it here
task.retry_policy = retry_policy
if runnable and status != FAILED and worker.enabled:
task.workers.add(worker_id)
self._state.get_worker(worker_id).tasks.add(task)
task.runnable = runnable | * add task identified by task_id if it doesn't exist
* if deps is not None, update dependency list
* update status of task
* add additional workers/stakeholders
* update priority when needed | add_task | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def _rank(self, task):
"""
Return worker's rank function for task scheduling.
:return:
"""
return task.priority, -task.time | Return worker's rank function for task scheduling.
:return: | _rank | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def _traverse_graph(self, root_task_id, seen=None, dep_func=None, include_done=True):
""" Returns the dependency graph rooted at task_id
This does a breadth-first traversal to find the nodes closest to the
root before hitting the scheduler.max_graph_nodes limit.
:param root_task_id: the id of the graph's root
:return: A map of task id to serialized node
"""
if seen is None:
seen = set()
elif root_task_id in seen:
return {}
if dep_func is None:
def dep_func(t):
return t.deps
seen.add(root_task_id)
serialized = {}
queue = collections.deque([root_task_id])
while queue:
task_id = queue.popleft()
task = self._state.get_task(task_id)
if task is None or not task.family:
logger.debug('Missing task for id [%s]', task_id)
# NOTE : If a dependency is missing from self._state there is no way to deduce the
# task family and parameters.
family_match = TASK_FAMILY_RE.match(task_id)
family = family_match.group(1) if family_match else UNKNOWN
params = {'task_id': task_id}
serialized[task_id] = {
'deps': [],
'status': UNKNOWN,
'workers': [],
'start_time': UNKNOWN,
'params': params,
'name': family,
'display_name': task_id,
'priority': 0,
}
else:
deps = dep_func(task)
if not include_done:
deps = list(self._filter_done(deps))
serialized[task_id] = self._serialize_task(task_id, deps=deps)
for dep in sorted(deps):
if dep not in seen:
seen.add(dep)
queue.append(dep)
if task_id != root_task_id:
del serialized[task_id]['display_name']
if len(serialized) >= self._config.max_graph_nodes:
break
return serialized | Returns the dependency graph rooted at task_id
This does a breadth-first traversal to find the nodes closest to the
root before hitting the scheduler.max_graph_nodes limit.
:param root_task_id: the id of the graph's root
:return: A map of task id to serialized node | _traverse_graph | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def task_list(self, status='', upstream_status='', limit=True, search=None, max_shown_tasks=None,
**kwargs):
"""
Query for a subset of tasks by status.
"""
if not search:
count_limit = max_shown_tasks or self._config.max_shown_tasks
pre_count = self._state.get_active_task_count_for_status(status)
if limit and pre_count > count_limit:
return {'num_tasks': -1 if upstream_status else pre_count}
self.prune()
result = {}
upstream_status_table = {} # used to memoize upstream status
if search is None:
def filter_func(_):
return True
else:
terms = search.split()
def filter_func(t):
return all(term.casefold() in t.pretty_id.casefold() for term in terms)
tasks = self._state.get_active_tasks_by_status(status) if status else self._state.get_active_tasks()
for task in filter(filter_func, tasks):
if task.status != PENDING or not upstream_status or upstream_status == self._upstream_status(task.id, upstream_status_table):
serialized = self._serialize_task(task.id, include_deps=False)
result[task.id] = serialized
if limit and len(result) > (max_shown_tasks or self._config.max_shown_tasks):
return {'num_tasks': len(result)}
return result | Query for a subset of tasks by status. | task_list | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def resource_list(self):
"""
Resources usage info and their consumers (tasks).
"""
self.prune()
resources = [
dict(
name=resource,
num_total=r_dict['total'],
num_used=r_dict['used']
) for resource, r_dict in self.resources().items()]
if self._resources is not None:
consumers = collections.defaultdict(dict)
for task in self._state.get_active_tasks_by_status(RUNNING):
if task.status == RUNNING and task.resources:
for resource, amount in task.resources.items():
consumers[resource][task.id] = self._serialize_task(task.id, include_deps=False)
for resource in resources:
tasks = consumers[resource['name']]
resource['num_consumer'] = len(tasks)
resource['running'] = tasks
return resources | Resources usage info and their consumers (tasks). | resource_list | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def resources(self):
''' get total resources and available ones '''
used_resources = self._used_resources()
ret = collections.defaultdict(dict)
for resource, total in self._resources.items():
ret[resource]['total'] = total
if resource in used_resources:
ret[resource]['used'] = used_resources[resource]
else:
ret[resource]['used'] = 0
return ret | get total resources and available ones | resources | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def task_search(self, task_str, **kwargs):
"""
Query for a subset of tasks by task_id.
:param task_str:
:return:
"""
self.prune()
result = collections.defaultdict(dict)
for task in self._state.get_active_tasks():
if task.id.find(task_str) != -1:
serialized = self._serialize_task(task.id, include_deps=False)
result[task.status][task.id] = serialized
return result | Query for a subset of tasks by task_id.
:param task_str:
:return: | task_search | python | spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/master/luigi/scheduler.py | Apache-2.0 |
def __new__(metacls, classname, bases, classdict, **kwargs):
"""
Custom class creation for namespacing.
Also register all subclasses.
When the set or inherited namespace evaluates to ``None``, set the task namespace to
whatever the currently declared namespace is.
"""
cls = super(Register, metacls).__new__(metacls, classname, bases, classdict, **kwargs)
cls._namespace_at_class_time = metacls._get_namespace(cls.__module__)
metacls._reg.append(cls)
return cls | Custom class creation for namespacing.
Also register all subclasses.
When the set or inherited namespace evaluates to ``None``, set the task namespace to
whatever the currently declared namespace is. | __new__ | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def __call__(cls, *args, **kwargs):
"""
Custom class instantiation utilizing instance cache.
If a Task has already been instantiated with the same parameters,
the previous instance is returned to reduce number of object instances.
"""
def instantiate():
return super(Register, cls).__call__(*args, **kwargs)
h = cls.__instance_cache
if h is None: # disabled
return instantiate()
params = cls.get_params()
param_values = cls.get_param_values(params, args, kwargs)
k = (cls, tuple(param_values))
try:
hash(k)
except TypeError:
logger.debug("Not all parameter values are hashable so instance isn't coming from the cache")
return instantiate() # unhashable types in parameters
if k not in h:
h[k] = instantiate()
return h[k] | Custom class instantiation utilizing instance cache.
If a Task has already been instantiated with the same parameters,
the previous instance is returned to reduce number of object instances. | __call__ | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def clear_instance_cache(cls):
"""
Clear/Reset the instance cache.
"""
cls.__instance_cache = {} | Clear/Reset the instance cache. | clear_instance_cache | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def disable_instance_cache(cls):
"""
Disables the instance cache.
"""
cls.__instance_cache = None | Disables the instance cache. | disable_instance_cache | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def task_family(cls):
"""
Internal note: This function will be deleted soon.
"""
task_namespace = cls.get_task_namespace()
if not task_namespace:
return cls.__name__
else:
return f"{task_namespace}.{cls.__name__}" | Internal note: This function will be deleted soon. | task_family | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def _get_reg(cls):
"""Return all of the registered classes.
:return: an ``dict`` of task_family -> class
"""
# We have to do this on-demand in case task names have changed later
reg = dict()
for task_cls in cls._reg:
if not task_cls._visible_in_registry:
continue
name = task_cls.get_task_family()
if name in reg and \
(reg[name] == Register.AMBIGUOUS_CLASS or # Check so issubclass doesn't crash
not issubclass(task_cls, reg[name])):
# Registering two different classes - this means we can't instantiate them by name
# The only exception is if one class is a subclass of the other. In that case, we
# instantiate the most-derived class (this fixes some issues with decorator wrappers).
reg[name] = Register.AMBIGUOUS_CLASS
else:
reg[name] = task_cls
return reg | Return all of the registered classes.
:return: an ``dict`` of task_family -> class | _get_reg | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def _set_reg(cls, reg):
"""The writing complement of _get_reg
"""
cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS] | The writing complement of _get_reg | _set_reg | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def task_names(cls):
"""
List of task names as strings
"""
return sorted(cls._get_reg().keys()) | List of task names as strings | task_names | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def tasks_str(cls):
"""
Human-readable register contents dump.
"""
return ','.join(cls.task_names()) | Human-readable register contents dump. | tasks_str | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def get_task_cls(cls, name):
"""
Returns an unambiguous class or raises an exception.
"""
task_cls = cls._get_reg().get(name)
if not task_cls:
raise TaskClassNotFoundException(cls._missing_task_msg(name))
if task_cls == cls.AMBIGUOUS_CLASS:
raise TaskClassAmbigiousException('Task %r is ambiguous' % name)
return task_cls | Returns an unambiguous class or raises an exception. | get_task_cls | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def get_all_params(cls):
"""
Compiles and returns all parameters for all :py:class:`Task`.
:return: a generator of tuples (TODO: we should make this more elegant)
"""
for task_name, task_cls in cls._get_reg().items():
if task_cls == cls.AMBIGUOUS_CLASS:
continue
for param_name, param_obj in task_cls.get_params():
yield task_name, (not task_cls.use_cmdline_section), param_name, param_obj | Compiles and returns all parameters for all :py:class:`Task`.
:return: a generator of tuples (TODO: we should make this more elegant) | get_all_params | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def _editdistance(a, b):
""" Simple unweighted Levenshtein distance """
r0 = range(0, len(b) + 1)
r1 = [0] * (len(b) + 1)
for i in range(0, len(a)):
r1[0] = i + 1
for j in range(0, len(b)):
c = 0 if a[i] is b[j] else 1
r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[j] + c)
r0 = r1[:]
return r1[len(b)] | Simple unweighted Levenshtein distance | _editdistance | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def _module_parents(module_name):
'''
>>> list(Register._module_parents('a.b'))
['a.b', 'a', '']
'''
spl = module_name.split('.')
for i in range(len(spl), 0, -1):
yield '.'.join(spl[0:i])
if module_name:
yield '' | >>> list(Register._module_parents('a.b'))
['a.b', 'a', ''] | _module_parents | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def load_task(module, task_name, params_str):
"""
Imports task dynamically given a module and a task name.
"""
if module is not None:
__import__(module)
task_cls = Register.get_task_cls(task_name)
return task_cls.from_str_params(params_str) | Imports task dynamically given a module and a task name. | load_task | python | spotify/luigi | luigi/task_register.py | https://github.com/spotify/luigi/blob/master/luigi/task_register.py | Apache-2.0 |
def _section(cls, opts):
"""Get logging settings from config file section "logging"."""
if isinstance(cls.config, LuigiConfigParser):
return False
try:
logging_config = cls.config['logging']
except (TypeError, KeyError, NoSectionError):
return False
logging.config.dictConfig(recursively_unfreeze(logging_config))
return True | Get logging settings from config file section "logging". | _section | python | spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/master/luigi/setup_logging.py | Apache-2.0 |
def _cli(cls, opts):
"""Setup logging via CLI options
If `--background` -- set INFO level for root logger.
If `--logdir` -- set logging with next params:
default Luigi's formatter,
INFO level,
output in logdir in `luigi-server.log` file
"""
if opts.background:
logging.getLogger().setLevel(logging.INFO)
return True
if opts.logdir:
logging.basicConfig(
level=logging.INFO,
format=cls._log_format,
filename=os.path.join(opts.logdir, "luigi-server.log"))
return True
return False | Setup logging via CLI options
If `--background` -- set INFO level for root logger.
If `--logdir` -- set logging with next params:
default Luigi's formatter,
INFO level,
output in logdir in `luigi-server.log` file | _cli | python | spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/master/luigi/setup_logging.py | Apache-2.0 |
def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
logging_conf = cls.config.get('core', 'logging_conf_file', None)
if logging_conf is None:
return False
if not os.path.exists(logging_conf):
# FileNotFoundError added only in Python 3.3
# https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy
raise OSError("Error: Unable to locate specified logging configuration file!")
logging.config.fileConfig(logging_conf)
return True | Setup logging via ini-file from logging_conf_file option. | _conf | python | spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/master/luigi/setup_logging.py | Apache-2.0 |
def _default(cls, opts):
"""Setup default logger"""
logging.basicConfig(level=logging.INFO, format=cls._log_format)
return True | Setup default logger | _default | python | spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/master/luigi/setup_logging.py | Apache-2.0 |
def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
if not opts.logging_conf_file:
return False
if not os.path.exists(opts.logging_conf_file):
# FileNotFoundError added only in Python 3.3
# https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy
raise OSError("Error: Unable to locate specified logging configuration file!")
logging.config.fileConfig(opts.logging_conf_file, disable_existing_loggers=False)
return True | Setup logging via ini-file from logging_conf_file option. | _conf | python | spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/master/luigi/setup_logging.py | Apache-2.0 |
def _default(cls, opts):
"""Setup default logger"""
level = getattr(logging, opts.log_level, logging.DEBUG)
logger = logging.getLogger('luigi-interface')
logger.setLevel(level)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(level)
formatter = logging.Formatter('%(levelname)s: %(message)s')
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return True | Setup default logger | _default | python | spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/master/luigi/setup_logging.py | Apache-2.0 |
def __init__(self, command, input_pipe=None):
"""
Initializes a InputPipeProcessWrapper instance.
:param command: a subprocess.Popen instance with stdin=input_pipe and
stdout=subprocess.PIPE.
Alternatively, just its args argument as a convenience.
"""
self._command = command
self._input_pipe = input_pipe
self._original_input = True
if input_pipe is not None:
try:
input_pipe.fileno()
except (AttributeError, io.UnsupportedOperation):
# subprocess require a fileno to work, if not present we copy to disk first
self._original_input = False
f = tempfile.NamedTemporaryFile('wb', prefix='luigi-process_tmp', delete=False)
self._tmp_file = f.name
while True:
chunk = input_pipe.read(io.DEFAULT_BUFFER_SIZE)
if not chunk:
break
f.write(chunk)
input_pipe.close()
f.close()
self._input_pipe = FileWrapper(io.BufferedReader(io.FileIO(self._tmp_file, 'r')))
self._process = command if isinstance(command, subprocess.Popen) else self.create_subprocess(command)
# we want to keep a circular reference to avoid garbage collection
# when the object is used in, e.g., pipe.read()
self._process._selfref = self | Initializes a InputPipeProcessWrapper instance.
:param command: a subprocess.Popen instance with stdin=input_pipe and
stdout=subprocess.PIPE.
Alternatively, just its args argument as a convenience. | __init__ | python | spotify/luigi | luigi/format.py | https://github.com/spotify/luigi/blob/master/luigi/format.py | Apache-2.0 |
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) | http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html | create_subprocess | python | spotify/luigi | luigi/format.py | https://github.com/spotify/luigi/blob/master/luigi/format.py | Apache-2.0 |
def _abort(self):
"""
Call _finish, but eat the exception (if any).
"""
try:
self._finish()
except KeyboardInterrupt:
raise
except BaseException:
pass | Call _finish, but eat the exception (if any). | _abort | python | spotify/luigi | luigi/format.py | https://github.com/spotify/luigi/blob/master/luigi/format.py | Apache-2.0 |
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 | Closes and waits for subprocess to exit. | _finish | python | spotify/luigi | luigi/format.py | https://github.com/spotify/luigi/blob/master/luigi/format.py | Apache-2.0 |
def common_params(task_instance, task_cls):
"""
Grab all the values in task_instance that are found in task_cls.
"""
if not isinstance(task_cls, task.Register):
raise TypeError("task_cls must be an uninstantiated Task")
task_instance_param_names = dict(task_instance.get_params()).keys()
task_cls_params_dict = dict(task_cls.get_params())
task_cls_param_names = task_cls_params_dict.keys()
common_param_names = set(task_instance_param_names).intersection(set(task_cls_param_names))
common_param_vals = [(key, task_cls_params_dict[key]) for key in common_param_names]
common_kwargs = dict((key, task_instance.param_kwargs[key]) for key in common_param_names)
vals = dict(task_instance.get_param_values(common_param_vals, [], common_kwargs))
return vals | Grab all the values in task_instance that are found in task_cls. | common_params | python | spotify/luigi | luigi/util.py | https://github.com/spotify/luigi/blob/master/luigi/util.py | Apache-2.0 |
def delegates(task_that_delegates):
""" Lets a task call methods on subtask(s).
The way this works is that the subtask is run as a part of the task, but
the task itself doesn't have to care about the requirements of the subtasks.
The subtask doesn't exist from the scheduler's point of view, and
its dependencies are instead required by the main task.
Example:
.. code-block:: python
class PowersOfN(luigi.Task):
n = luigi.IntParameter()
def f(self, x): return x ** self.n
@delegates
class T(luigi.Task):
def subtasks(self): return PowersOfN(5)
def run(self): print self.subtasks().f(42)
"""
if not hasattr(task_that_delegates, 'subtasks'):
# This method can (optionally) define a couple of delegate tasks that
# will be accessible as interfaces, meaning that the task can access
# those tasks and run methods defined on them, etc
raise AttributeError('%s needs to implement the method "subtasks"' % task_that_delegates)
@task._task_wraps(task_that_delegates)
class Wrapped(task_that_delegates):
def deps(self):
# Overrides method in base class
return task.flatten(self.requires()) + task.flatten([t.deps() for t in task.flatten(self.subtasks())])
def run(self):
for t in task.flatten(self.subtasks()):
t.run()
task_that_delegates.run(self)
return Wrapped | Lets a task call methods on subtask(s).
The way this works is that the subtask is run as a part of the task, but
the task itself doesn't have to care about the requirements of the subtasks.
The subtask doesn't exist from the scheduler's point of view, and
its dependencies are instead required by the main task.
Example:
.. code-block:: python
class PowersOfN(luigi.Task):
n = luigi.IntParameter()
def f(self, x): return x ** self.n
@delegates
class T(luigi.Task):
def subtasks(self): return PowersOfN(5)
def run(self): print self.subtasks().f(42) | delegates | python | spotify/luigi | luigi/util.py | https://github.com/spotify/luigi/blob/master/luigi/util.py | Apache-2.0 |
def previous(task):
"""
Return a previous Task of the same family.
By default checks if this task family only has one non-global parameter and if
it is a DateParameter, DateHourParameter or DateIntervalParameter in which case
it returns with the time decremented by 1 (hour, day or interval)
"""
params = task.get_params()
previous_params = {}
previous_date_params = {}
for param_name, param_obj in params:
param_value = getattr(task, param_name)
if isinstance(param_obj, parameter.DateParameter):
previous_date_params[param_name] = param_value - datetime.timedelta(days=1)
elif isinstance(param_obj, parameter.DateSecondParameter):
previous_date_params[param_name] = param_value - datetime.timedelta(seconds=1)
elif isinstance(param_obj, parameter.DateMinuteParameter):
previous_date_params[param_name] = param_value - datetime.timedelta(minutes=1)
elif isinstance(param_obj, parameter.DateHourParameter):
previous_date_params[param_name] = param_value - datetime.timedelta(hours=1)
elif isinstance(param_obj, parameter.DateIntervalParameter):
previous_date_params[param_name] = param_value.prev()
else:
previous_params[param_name] = param_value
previous_params.update(previous_date_params)
if len(previous_date_params) == 0:
raise NotImplementedError("No task parameter - can't determine previous task")
elif len(previous_date_params) > 1:
raise NotImplementedError("Too many date-related task parameters - can't determine previous task")
else:
return task.clone(**previous_params) | Return a previous Task of the same family.
By default checks if this task family only has one non-global parameter and if
it is a DateParameter, DateHourParameter or DateIntervalParameter in which case
it returns with the time decremented by 1 (hour, day or interval) | previous | python | spotify/luigi | luigi/util.py | https://github.com/spotify/luigi/blob/master/luigi/util.py | Apache-2.0 |
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) | 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_with_retcodes | python | spotify/luigi | luigi/retcodes.py | https://github.com/spotify/luigi/blob/master/luigi/retcodes.py | Apache-2.0 |
def _schedule_and_run(tasks, worker_scheduler_factory=None, override_defaults=None):
"""
:param tasks:
:param worker_scheduler_factory:
:param override_defaults:
:return: True if all tasks and their dependencies were successfully run (or already completed);
False if any error occurred. It will return a detailed response of type LuigiRunResult
instead of a boolean if detailed_summary=True.
"""
if worker_scheduler_factory is None:
worker_scheduler_factory = _WorkerSchedulerFactory()
if override_defaults is None:
override_defaults = {}
env_params = core(**override_defaults)
InterfaceLogging.setup(env_params)
kill_signal = signal.SIGUSR1 if env_params.take_lock else None
if (not env_params.no_lock and
not (lock.acquire_for(env_params.lock_pid_dir, env_params.lock_size, kill_signal))):
raise PidLockAlreadyTakenExit()
if env_params.local_scheduler:
sch = worker_scheduler_factory.create_local_scheduler()
else:
if env_params.scheduler_url != '':
url = env_params.scheduler_url
else:
url = 'http://{host}:{port:d}/'.format(
host=env_params.scheduler_host,
port=env_params.scheduler_port,
)
sch = worker_scheduler_factory.create_remote_scheduler(url=url)
worker = worker_scheduler_factory.create_worker(
scheduler=sch, worker_processes=env_params.workers, assistant=env_params.assistant)
success = True
logger = logging.getLogger('luigi-interface')
with worker:
for t in tasks:
success &= worker.add(t, env_params.parallel_scheduling, env_params.parallel_scheduling_processes)
logger.info('Done scheduling tasks')
success &= worker.run()
luigi_run_result = LuigiRunResult(worker, success)
logger.info(luigi_run_result.summary_text)
if hasattr(sch, 'close'):
sch.close()
return luigi_run_result | :param tasks:
:param worker_scheduler_factory:
:param override_defaults:
:return: True if all tasks and their dependencies were successfully run (or already completed);
False if any error occurred. It will return a detailed response of type LuigiRunResult
instead of a boolean if detailed_summary=True. | _schedule_and_run | python | spotify/luigi | luigi/interface.py | https://github.com/spotify/luigi/blob/master/luigi/interface.py | Apache-2.0 |
def run(*args, **kwargs):
"""
Please dont use. Instead use `luigi` binary.
Run from cmdline using argparse.
:param use_dynamic_argparse: Deprecated and ignored
"""
luigi_run_result = _run(*args, **kwargs)
return luigi_run_result if kwargs.get('detailed_summary') else luigi_run_result.scheduling_succeeded | Please dont use. Instead use `luigi` binary.
Run from cmdline using argparse.
:param use_dynamic_argparse: Deprecated and ignored | run | python | spotify/luigi | luigi/interface.py | https://github.com/spotify/luigi/blob/master/luigi/interface.py | Apache-2.0 |
def build(tasks, worker_scheduler_factory=None, detailed_summary=False, **env_params):
"""
Run internally, bypassing the cmdline parsing.
Useful if you have some luigi code that you want to run internally.
Example:
.. code-block:: python
luigi.build([MyTask1(), MyTask2()], local_scheduler=True)
One notable difference is that `build` defaults to not using
the identical process lock. Otherwise, `build` would only be
callable once from each process.
:param tasks:
:param worker_scheduler_factory:
:param env_params:
:return: True if there were no scheduling errors, even if tasks may fail.
"""
if "no_lock" not in env_params:
env_params["no_lock"] = True
luigi_run_result = _schedule_and_run(tasks, worker_scheduler_factory, override_defaults=env_params)
return luigi_run_result if detailed_summary else luigi_run_result.scheduling_succeeded | Run internally, bypassing the cmdline parsing.
Useful if you have some luigi code that you want to run internally.
Example:
.. code-block:: python
luigi.build([MyTask1(), MyTask2()], local_scheduler=True)
One notable difference is that `build` defaults to not using
the identical process lock. Otherwise, `build` would only be
callable once from each process.
:param tasks:
:param worker_scheduler_factory:
:param env_params:
:return: True if there were no scheduling errors, even if tasks may fail. | build | python | spotify/luigi | luigi/interface.py | https://github.com/spotify/luigi/blob/master/luigi/interface.py | Apache-2.0 |
def instance(cls, *args, **kwargs):
""" Singleton getter """
if cls._instance is None:
cls._instance = cls(*args, **kwargs)
loaded = cls._instance.reload()
logging.getLogger('luigi-interface').info('Loaded %r', loaded)
return cls._instance | Singleton getter | instance | python | spotify/luigi | luigi/configuration/base_parser.py | https://github.com/spotify/luigi/blob/master/luigi/configuration/base_parser.py | Apache-2.0 |
def get_config(parser=None):
"""Get configs singleton for parser
"""
if parser is None:
parser = _get_default_parser()
parser_class = PARSERS[parser]
_check_parser(parser_class, parser)
return parser_class.instance() | Get configs singleton for parser | get_config | python | spotify/luigi | luigi/configuration/core.py | https://github.com/spotify/luigi/blob/master/luigi/configuration/core.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.