forked from spotify/luigi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
444 lines (324 loc) · 14.2 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
============================================================
Using ``inherits`` and ``requires`` to ease parameter pain
============================================================
Most luigi plumbers will find themselves in an awkward task parameter situation
at some point or another. Consider the following "parameter explosion"
problem:
.. code-block:: python
class TaskA(luigi.ExternalTask):
param_a = luigi.Parameter()
def output(self):
return luigi.LocalTarget('/tmp/log-{t.param_a}'.format(t=self))
class TaskB(luigi.Task):
param_b = luigi.Parameter()
param_a = luigi.Parameter()
def requires(self):
return TaskA(param_a=self.param_a)
class TaskC(luigi.Task):
param_c = luigi.Parameter()
param_b = luigi.Parameter()
param_a = luigi.Parameter()
def requires(self):
return TaskB(param_b=self.param_b, param_a=self.param_a)
In work flows requiring many tasks to be chained together in this manner,
parameter handling can spiral out of control. Each downstream task becomes
more burdensome than the last. Refactoring becomes more difficult. There
are several ways one might try and avoid the problem.
**Approach 1**: Parameters via command line or config instead of ``requires``.
.. code-block:: python
class TaskA(luigi.ExternalTask):
param_a = luigi.Parameter()
def output(self):
return luigi.LocalTarget('/tmp/log-{t.param_a}'.format(t=self))
class TaskB(luigi.Task):
param_b = luigi.Parameter()
def requires(self):
return TaskA()
class TaskC(luigi.Task):
param_c = luigi.Parameter()
def requires(self):
return TaskB()
Then run in the shell like so:
.. code-block:: bash
luigi --module my_tasks TaskC --param-c foo --TaskB-param-b bar --TaskA-param-a baz
Repetitive parameters have been eliminated, but at the cost of making the job's
command line interface slightly clunkier. Often this is a reasonable
trade-off.
But parameters can't always be refactored out every class. Downstream
tasks might also need to use some of those parameters. For example,
if ``TaskC`` needs to use ``param_a`` too, then ``param_a`` would still need
to be repeated.
**Approach 2**: Use a common parameter class
.. code-block:: python
class Params(luigi.Config):
param_c = luigi.Parameter()
param_b = luigi.Parameter()
param_a = luigi.Parameter()
class TaskA(Params, luigi.ExternalTask):
def output(self):
return luigi.LocalTarget('/tmp/log-{t.param_a}'.format(t=self))
class TaskB(Params):
def requires(self):
return TaskA()
class TaskB(Params):
def requires(self):
return TaskB()
This looks great at first glance, but a couple of issues lurk. Now ``TaskA``
and ``TaskB`` have unnecessary significant parameters. Significant parameters
help define the identity of a task. Identical tasks are prevented from
running at the same time by the central planner. This helps preserve the
idempotent and atomic nature of luigi tasks. Unnecessary significant task
parameters confuse a task's identity. Under the right circumstances, task
identity confusion could lead to that task running when it shouldn't, or
failing to run when it should.
This approach should only be used when all of the parameters of the config
class, are significant (or all insignificant) for all of its subclasses.
And wait a second... there's a bug in the above code. See it?
``TaskA`` won't behave as an ``ExternalTask`` because the parent classes are
specified in the wrong order. This contrived example is easy to fix (by
swapping the ordering of the parents of ``TaskA``), but real world cases can be
more difficult to both spot and fix. Inheriting from multiple classes
derived from ``luigi.Task`` should be undertaken with caution and avoided
where possible.
**Approach 3**: Use ``inherits`` and ``requires``
The ``inherits`` class decorator in this module copies parameters (and
nothing else) from one task class to another, and avoids direct pythonic
inheritance.
.. code-block:: python
import luigi
from luigi.util import inherits
class TaskA(luigi.ExternalTask):
param_a = luigi.Parameter()
def output(self):
return luigi.LocalTarget('/tmp/log-{t.param_a}'.format(t=self))
@inherits(TaskA)
class TaskB(luigi.Task):
param_b = luigi.Parameter()
def requires(self):
t = self.clone(TaskA) # or t = self.clone_parent()
# Wait... whats this clone thingy do?
#
# Pass it a task class. It calls that task. And when it does, it
# supplies all parameters (and only those parameters) common to
# the caller and callee!
#
# The call to clone is equivalent to the following (note the
# fact that clone avoids passing param_b).
#
# return TaskA(param_a=self.param_a)
return t
@inherits(TaskB)
class TaskC(luigi.Task):
param_c = luigi.Parameter()
def requires(self):
return self.clone(TaskB)
This totally eliminates the need to repeat parameters, avoids inheritance
issues, and keeps the task command line interface as simple (as it can be,
anyway). Refactoring task parameters is also much easier.
The ``requires`` helper function can reduce this pattern even further. It
does everything ``inherits`` does, and also attaches a ``requires`` method
to your task (still all without pythonic inheritance).
But how does it know how to invoke the upstream task? It uses ``clone``
behind the scenes!
.. code-block:: python
import luigi
from luigi.util import inherits, requires
class TaskA(luigi.ExternalTask):
param_a = luigi.Parameter()
def output(self):
return luigi.LocalTarget('/tmp/log-{t.param_a}'.format(t=self))
@requires(TaskA)
class TaskB(luigi.Task):
param_b = luigi.Parameter()
# The class decorator does this for me!
# def requires(self):
# return self.clone(TaskA)
Use these helper functions effectively to avoid unnecessary
repetition and dodge a few potentially nasty workflow pitfalls at the same
time. Brilliant!
"""
import datetime
import functools
import logging
from luigi import six
from luigi import task
from luigi import parameter
from luigi.deprecate_kwarg import deprecate_kwarg # NOQA: removing this breaks code
if six.PY3:
xrange = range
logger = logging.getLogger('luigi-interface')
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
def task_wraps(P):
# In order to make the behavior of a wrapper class nicer, we set the name of the
# new class to the wrapped class, and copy over the docstring and module as well.
# This makes it possible to pickle the wrapped class etc.
# Btw, this is a slight abuse of functools.wraps. It's meant to be used only for
# functions, but it works for classes too, if you pass updated=[]
return functools.wraps(P, updated=[])
class inherits(object):
"""
Task inheritance.
Usage:
.. code-block:: python
class AnotherTask(luigi.Task):
n = luigi.IntParameter()
# ...
@inherits(AnotherTask):
class MyTask(luigi.Task):
def requires(self):
return self.clone_parent()
def run(self):
print self.n # this will be defined
# ...
"""
def __init__(self, task_to_inherit):
super(inherits, self).__init__()
self.task_to_inherit = task_to_inherit
def __call__(self, task_that_inherits):
for param_name, param_obj in self.task_to_inherit.get_params():
if not hasattr(task_that_inherits, param_name):
setattr(task_that_inherits, param_name, param_obj)
# Modify task_that_inherits by subclassing it and adding methods
@task_wraps(task_that_inherits)
class Wrapped(task_that_inherits):
def clone_parent(_self, **args):
return _self.clone(cls=self.task_to_inherit, **args)
return Wrapped
class requires(object):
"""
Same as @inherits, but also auto-defines the requires method.
"""
def __init__(self, task_to_require):
super(requires, self).__init__()
self.inherit_decorator = inherits(task_to_require)
def __call__(self, task_that_requires):
task_that_requires = self.inherit_decorator(task_that_requires)
# Modify task_that_requres by subclassing it and adding methods
@task_wraps(task_that_requires)
class Wrapped(task_that_requires):
def requires(_self):
return _self.clone_parent()
return Wrapped
class copies(object):
"""
Auto-copies a task.
Usage:
.. code-block:: python
@copies(MyTask):
class CopyOfMyTask(luigi.Task):
def output(self):
return LocalTarget(self.date.strftime('/var/xyz/report-%Y-%m-%d'))
"""
def __init__(self, task_to_copy):
super(copies, self).__init__()
self.requires_decorator = requires(task_to_copy)
def __call__(self, task_that_copies):
task_that_copies = self.requires_decorator(task_that_copies)
# Modify task_that_copies by subclassing it and adding methods
@task_wraps(task_that_copies)
class Wrapped(task_that_copies):
def run(_self):
i, o = _self.input(), _self.output()
f = o.open('w') # TODO: assert that i, o are Target objects and not complex datastructures
for line in i.open('r'):
f.write(line)
f.close()
return Wrapped
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_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
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.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)
def get_previous_completed(task, max_steps=10):
prev = task
for _ in xrange(max_steps):
prev = previous(prev)
logger.debug("Checking if %s is complete", prev)
if prev.complete():
return prev
return None