-
Notifications
You must be signed in to change notification settings - Fork 28
/
activity.py
executable file
·527 lines (397 loc) · 16.5 KB
/
activity.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# -*- coding: utf-8 -*-
"""
Activity
========
Activities are self generated classes to which you can pass an identifier,
and a list of tasks to perform. The activities are in between the decider and
the tasks.
For ease, two types of task runners are available: Sync and Async. If
you need something more specific, you should either create your own runner, or
you should create a main task that will then split the work.
Create an activity::
from garcon import activity
# First step is to create the workflow on a specific domain.
create = activity.create('domain')
initial_activity = create(
# Name of your activity
name='activity_name',
# List of tasks to run (here we use the Sync runner)
run=runner.Sync(task1),
# No requires since it's the first one. Later in your flow, if you have
# a dependency, just use the variable that contains the activity.
requires=[],
# If the activity fails, number of times you want to retry.
retry=0,
# If you want to run the activity `n` times, you can use a generator.
generator=[generator_name])
"""
from threading import Thread
import boto.swf.layer2 as swf
import itertools
import json
from garcon import log
from garcon import utils
from garcon import runner
ACTIVITY_STANDBY = 0
ACTIVITY_SCHEDULED = 1
ACTIVITY_COMPLETED = 2
ACTIVITY_FAILED = 3
DEFAULT_ACTIVITY_SCHEDULE_TO_START = 600 # 10 minutes
class ActivityInstance:
def __init__(
self, activity_worker, local_context=None, execution_context=None):
"""Activity Instance.
In SWF, Activity is a worker: it will get information from the context,
and will launch activity instances (only one, unless you have a
generator.) The activity instance generates its key (visible in the SWF
console) from the local context. Activity instances are owned by an
execution.
Args:
activity_worker (ActivityWorker): The activity worker that owns
this specific Activity Instance.
local_context (dict): the local context of the activity (it does
not include the execution context.) Most times the context will
be empty since it is only filled with data that comes from the
generators.
execution_context (dict): the execution context of when an activity
will be scheduled with.
"""
self.activity_worker = activity_worker
self.execution_context = execution_context or dict()
self.local_context = local_context or dict()
self.global_context = dict(
list(self.execution_context.items()) +
list(self.local_context.items()))
@property
def activity_name(self):
"""Return the activity name of the worker.
"""
return self.activity_worker.name
@property
def retry(self):
"""Return the number of retries allowed (matches the worker.)
"""
return self.activity_worker.retry
@property
def id(self):
"""Generate the id of the activity.
The id is crutial (not just important): it allows to indentify the
state the activity instance in the event history (if it has failed,
been executed, or marked as completed.)
Return:
str: composed of the activity name (task list), and the activity
id.
"""
if not self.local_context:
activity_id = 1
else:
activity_id = utils.create_dictionary_key(self.local_context)
return '{name}-{id}'.format(
name=self.activity_name,
id=activity_id)
@property
def schedule_to_start(self):
"""Return the schedule to start timeout.
The schedule to start timeout assumes that only one activity worker is
available (since swf does not provide a count of available workers). So
if the default value is 5 minutes, and you have 10 instances: the
schedule to start will be 50 minutes for all instances.
Return:
int: Schedule to start timeout.
"""
return (
self.activity_worker.pool_size *
self.activity_worker.schedule_to_start_timeout)
@property
def schedule_to_close(self):
"""Return the schedule to close timeout.
The schedule to close timeout is a simple calculation that defines when
an activity (from the moment it has been scheduled) should end. It is
a calculation between the schedule to start timeout and the activity
timeout.
Return:
int: Schedule to close timeout.
"""
return self.schedule_to_start + self.timeout
@property
def timeout(self):
"""Return the timeout in seconds.
This timeout corresponds on when the activity has started and when we
assume the activity has ended (which corresponds in boto to
start_to_close_timeout.)
Return:
int: Task list timeout.
"""
return self.runner.timeout(self.global_context)
@property
def heartbeat_timeout(self):
"""Return the heartbeat in seconds.
This heartbeat corresponds on when an activity needs to send a signal
to swf that it is still running. This will set the value when the
activity is scheduled.
Return:
int: Task list timeout.
"""
return self.runner.heartbeat(self.global_context)
@property
def runner(self):
"""Shortcut to get access to the runner.
Raises:
runner.RunnerMissing: an activity should always have a runner,
if the runner is missing an exception is raised (we will not
be able to calculate values such as timeouts without a runner.)
Return:
Runner: the activity runner.
"""
activity_runner = getattr(self.activity_worker, 'runner', None)
if not activity_runner:
raise runner.RunnerMissing()
return activity_runner
def create_execution_input(self):
"""Create the input of the activity from the context.
AWS has a limit on the number of characters that can be used (32k). If
you use the `task.decorate`, the data sent to the activity is optimized
to match the values of the context.
Return:
dict: the input to send to the activity.
"""
activity_input = dict()
try:
for requirement in self.runner.requirements(self.global_context):
value = self.global_context.get(requirement)
if value:
activity_input.update({requirement: value})
except runner.NoRunnerRequirementsFound:
return self.global_context
return activity_input
class Activity(swf.ActivityWorker, log.GarconLogger):
version = '1.0'
task_list = None
def run(self):
"""Activity Runner.
Information is being pulled down from SWF and it checks if the Activity
can be ran. As part of the information provided, the input of the
previous activity is consumed (context).
"""
activity_task = self.poll()
packed_context = activity_task.get('input')
context = dict()
if packed_context:
context = json.loads(packed_context)
self.set_log_context(context)
if 'activityId' in activity_task:
try:
context = self.execute_activity(context)
self.complete(result=json.dumps(context))
except Exception as error:
# If the workflow has been stopped, it is not possible for the
# activity to be updated – it throws an exception which stops
# the worker immediately.
try:
self.fail(reason=str(error))
except:
pass
self.unset_log_context()
return True
def execute_activity(self, context):
"""Execute the runner.
Args:
context (dict): The flow context.
"""
return self.runner.execute(self, context)
def hydrate(self, data):
"""Hydrate the task with information provided.
Args:
data (dict): the data to use (if defined.)
"""
self.pool_size = 0
self.name = self.name or data.get('name')
self.domain = getattr(self, 'domain', '') or data.get('domain')
self.requires = getattr(self, 'requires', []) or data.get('requires')
self.retry = getattr(self, 'retry', None) or data.get('retry', 0)
self.task_list = self.task_list or data.get('task_list')
# The start timeout is how long it will take between the scheduling
# of the activity and the start of the activity.
self.schedule_to_start_timeout = (
getattr(self, 'schedule_to_start_timeout', None) or
data.get('schedule_to_start') or
DEFAULT_ACTIVITY_SCHEDULE_TO_START)
# The previous way to create an activity was to fill a `tasks` param,
# which is not `run`.
self.runner = (
getattr(self, 'runner', None) or
data.get('run') or data.get('tasks'))
self.generators = getattr(
self, 'generators', None) or data.get('generators')
def instances(self, context):
"""Get all instances for one activity based on the current context.
There are two scenarios: when the activity worker has a generator and
when it does not. When it doesn't (the most simple case), there will
always be one instance returned.
Generators will however consume the context to calculate how many
instances of the activity are needed – and it will generate them
(regardless of their state.)
Args:
context (dict): the current context.
Return:
list: all the instances of the activity (for a current workflow
execution.)
"""
if not self.generators:
self.pool_size = 1
yield ActivityInstance(self)
return
generator_values = []
for generator in self.generators:
generator_values.append(generator(context))
contexts = list(itertools.product(*generator_values))
self.pool_size = len(contexts)
for generator_contexts in contexts:
# Each generator returns a context, merge all the contexts
# to only be one - which can be used to 1/ create the id of the
# activity and 2/ be passed as a local context.
instance_context = dict()
for current_generator_context in generator_contexts:
instance_context.update(current_generator_context.items())
yield ActivityInstance(
self, execution_context=context, local_context=instance_context)
class ActivityWorker():
def __init__(self, flow, activities=None):
"""Initiate an activity worker.
The activity worker take in consideration all the activities from a
flow, or specific activities. Some activities (tasks) might require
more power than others, and be then launched on different machines.
If a list of activities is passed, the worker will be focused on
completing those and will ignore all the others.
Args:
flow (module): the flow module.
activities (list): the list of activities that this worker should
handle.
"""
self.flow = flow
self.activities = find_workflow_activities(self.flow)
self.worker_activities = activities
def run(self):
"""Run the activities.
"""
for activity in self.activities:
if (self.worker_activities and
not activity.name in self.worker_activities):
continue
Thread(target=worker_runner, args=(activity,)).start()
def worker_runner(worker):
"""Run indefinitely the worker.
Args:
worker (object): the Activity worker.
"""
while(worker.run()):
continue
def create(domain, name):
"""Helper method to create Activities.
The helper method simplifies the creation of an activity by setting the
domain, the task list, and the activity dependencies (what other
activities) need to be completed before this one can run.
Note:
The task list is generated based on the domain and the name of the
activity. Always make sure your activity name is unique.
"""
def wrapper(**options):
activity = Activity()
activity_name = '{name}_{activity}'.format(
name=name,
activity=options.get('name'))
activity.hydrate(dict(
domain=domain,
name=activity_name,
generators=options.get('generators', []),
requires=options.get('requires', []),
retry=options.get('retry'),
task_list=activity_name,
tasks=options.get('tasks'),
run=options.get('run'),
schedule_to_start=options.get('schedule_to_start')))
return activity
return wrapper
def find_available_activities(flow, history, context):
"""Find all available activity instances of a flow.
The history contains all the information of our activities (their state).
This method focuses on finding all the activities that need to run.
Args:
flow (module): the flow module.
history (dict): the history information.
context (dict): from the context find the available activities.
"""
for instance in find_activities(flow, context):
# If an event is already available for the activity, it means it is
# not in standby anymore, it's either processing or has been completed.
# The activity is thus not available anymore.
events = history.get(instance.activity_name, {}).get(instance.id)
if events:
if events[-1] != ACTIVITY_FAILED:
continue
elif (not instance.retry or
instance.retry < count_activity_failures(events)):
raise Exception(
'The activity failures has exceeded its retry limit.')
can_yield = True
for requirement in instance.activity_worker.requires:
require_history = history.get(requirement.name)
if not require_history:
can_yield = False
break
for requirement_evt in require_history.values():
if not ACTIVITY_COMPLETED in requirement_evt:
can_yield = False
break
if can_yield:
yield instance
def find_uncomplete_activities(flow, history, context):
"""Find uncomplete activity instances.
Uncomplete activities are all the activities that are not marked as
completed.
Args:
flow (module): the flow module.
history (dict): the history information.
context (dict): from the context find the available activities.
Yield:
activity: The available activity.
"""
for instance in find_activities(flow, context):
evts = history.get(instance.activity_name, {}).get(instance.id)
if not evts or ACTIVITY_COMPLETED not in evts:
yield instance
def find_workflow_activities(flow):
"""Retrieves all the activities from a flow
Args:
flow (module): the flow module.
Return:
list: all the activities.
"""
activities = []
for module_attribute in dir(flow):
current_activity = getattr(flow, module_attribute)
if isinstance(current_activity, Activity):
activities.append(current_activity)
return activities
def find_activities(flow, context):
"""Retrieves all the activities from a flow.
Args:
flow (module): the flow module.
Return:
list: All the activity instances for the flow.
"""
activities = []
for module_attribute in dir(flow):
current_activity = getattr(flow, module_attribute)
if isinstance(current_activity, Activity):
for activity_instance in current_activity.instances(context):
activities.append(activity_instance)
return activities
def count_activity_failures(events):
"""Count the number of times an activity has failed.
Args:
events (dict): list of activity events.
Return:
int: The number of times an activity has failed.
"""
return len([evt for evt in events if evt == ACTIVITY_FAILED])