-
Notifications
You must be signed in to change notification settings - Fork 28
/
activity.py
executable file
·799 lines (603 loc) · 25 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
# -*- 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::
import boto3
from garcon import activity
# First step is to create the workflow on a specific domain.
client = boto3.client('swf')
create = activity.create(client, 'domain', 'workflow-name')
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 botocore import exceptions
import itertools
import json
import threading
import backoff
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 ActivityInstanceNotReadyException(Exception):
"""Exception when an activity instance is not ready.
Activity instances that are considered not ready are instances that have
not completed.
"""
pass
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 as well as the execution 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 is not None:
activity_input.update({requirement: value})
activity_input.update({
'execution.domain': self.global_context.get('execution.domain'),
'execution.run_id': self.global_context.get('execution.run_id'),
'execution.workflow_id': self.global_context.get(
'execution.workflow_id')
})
except runner.NoRunnerRequirementsFound:
return self.global_context
return activity_input
class Activity(log.GarconLogger):
version = '1.0'
task_list = None
def __init__(self, client):
"""Instantiates an activity.
Args:
client: the boto client used for this activity.
"""
self.client = client
self.name = None
self.domain = None
self.task_list = None
@backoff.on_exception(
backoff.expo,
exceptions.ClientError,
max_tries=5,
giveup=utils.non_throttle_error,
on_backoff=utils.throttle_backoff_handler,
jitter=backoff.full_jitter)
def poll_for_activity(self, identity=None):
"""Runs Activity Poll.
If a SWF throttling exception is raised during a poll, the poll will
be retried up to 5 times using exponential backoff algorithm.
Upgrading to boto3 would make this retry logic redundant.
Args:
identity (str): Identity of the worker making the request, which
is recorded in the ActivityTaskStarted event in the AWS
console. This enables diagnostic tracing when problems arise.
Return:
ActivityExecution: activity execution.
"""
additional_params = {}
if identity:
additional_params.update(identity=identity)
execution_definition = self.client.poll_for_activity_task(
domain=self.domain, taskList=dict(name=self.task_list),
**additional_params)
return ActivityExecution(
self.client, execution_definition.get('activityId'),
execution_definition.get('taskToken'),
execution_definition.get('input'))
def run(self, identity=None):
"""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).
Args:
identity (str): Identity of the worker making the request, which
is recorded in the ActivityTaskStarted event in the AWS
console. This enables diagnostic tracing when problems arise.
"""
try:
if identity:
self.logger.debug('Polling with {}'.format(identity))
execution = self.poll_for_activity(identity)
except Exception as error:
# Catch exceptions raised during poll() to avoid an Activity thread
# dying & worker daemon unable to process the affected Activity.
# AWS api limits on SWF calls are a common source of such
# exceptions (see https://github.com/xethorn/garcon/pull/75)
# on_exception() can be overriden by the flow to send an alert
# when an exception occurs.
if self.on_exception:
self.on_exception(self, error)
self.logger.error(error, exc_info=True)
return True
self.set_log_context(execution.context)
if execution.activity_id:
try:
context = self.execute_activity(execution)
execution.complete(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:
execution.fail(str(error)[:255])
if self.on_exception:
self.on_exception(self, error)
except Exception as error2: # noqa: E722
if self.on_exception:
self.on_exception(self, error2)
self.unset_log_context()
return True
def execute_activity(self, activity):
"""Execute the runner.
Args:
execution (ActivityExecution): the activity execution.
Return:
dict: The result of the operation.
"""
return self.runner.execute(activity, activity.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.version = data.get('version') or self.version
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')
self.on_exception = (
getattr(self, 'on_exception', None) or data.get('on_exception'))
# 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, execution_context=context)
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 ExternalActivity(Activity):
"""External activity
One of the main advantages of SWF is the ability to write a workflow that
has activities written in any languages. The external activity class allows
to write the workflow in Garcon and benefit from some features (timeout
calculation among other things, sending context data.)
"""
def __init__(self, timeout=None, heartbeat=None):
"""Create the External Activity.
Args:
timeout (int): activity timeout in seconds (mandatory)
heartbeat (int): heartbeat timeout in seconds, if not defined, it
will be equal to the timeout.
"""
Activity.__init__(self, client=None)
self.runner = runner.External(timeout=timeout, heartbeat=heartbeat)
def run(self):
"""Run the external activity.
This activity is handled outside, so the run method should remain
unimplemented and return False (so the run loop stops.)
"""
return False
class ActivityExecution(log.GarconLogger):
def __init__(self, client, activity_id, task_token, context):
"""Create an an activity execution.
Args:
client (boto3.client): the boto client (for easy access if needed).
activity_id (str): the activity id.
task_token (str): the task token.
context (str): data for the execution.
"""
self.client = client
self.activity_id = activity_id
self.task_token = task_token
self.context = context and json.loads(context) or dict()
def heartbeat(self, details=None):
"""Create a task heartbeat.
Args:
details (str): details to add to the heartbeat.
"""
self.client.record_activity_task_heartbeat(taskToken=self.task_token,
details=details or '')
def fail(self, reason=None):
"""Mark the activity execution as failed.
Args:
reason (str): optional reason for the failure.
"""
self.client.respond_activity_task_failed(
taskToken=self.task_token,
reason=reason or '')
def complete(self, context=None):
"""Mark the activity execution as completed.
Args:
context (str or dict): the context result of the operation.
"""
self.client.respond_activity_task_completed(
taskToken=self.task_token,
result=json.dumps(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
activity.name not in self.worker_activities):
continue
threading.Thread(target=worker_runner, args=(activity,)).start()
class ActivityState:
"""
Activity State
==============
Provides information about a specific activity instance state (if the
instance is already scheduled, has failed, or has been completed.) Along
with the default values, this class also provides additional metadata such
as the result of an activity instance.
"""
def __init__(self, activity_id):
"""Create a State.
Args:
activity_id (str): the activity id.
"""
self.activity_id = activity_id
self._result = None
self.states = []
@property
def result(self):
"""Get the result.
"""
if not self.ready:
raise ActivityInstanceNotReadyException()
return self._result
@property
def ready(self):
"""Check if an activity is ready.
"""
return self.get_last_state() == ACTIVITY_COMPLETED
def get_last_state(self):
"""Get the last state of the activity execution.
Return:
int: the state of the activity (see: activity.py)
"""
if len(self.states):
return self.states[-1]
return None
def add_state(self, state):
"""Add a state in the activity execution.
Args:
state (int): the state of the activity to add (see activity.py)
"""
self.states.append(state)
def set_result(self, result):
"""Set the result of the activity.
This method sometimes throws an exception: an activity id can only have
one result.
Args:
result (dict): Result of the activity.
"""
if self._result:
raise Exception('Result is ummutable – it should not be changed.')
self._result = result
def wait(self):
"""Wait until ready.
"""
if not self.ready:
raise ActivityInstanceNotReadyException()
def worker_runner(worker):
"""Run indefinitely the worker.
Args:
worker (object): the Activity worker.
"""
while (worker.run()):
continue
def create(client, domain, workflow_name, version='1.0', on_exception=None):
"""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.
Args:
client (boto3.client): the boto3 client.
domain (str): the domain name.
workflow_name (str): workflow name.
version (str): activity version.
on_exception (callable): the error handler.
Return:
callable: activity generator.
"""
def wrapper(**options):
activity = Activity(client)
if options.get('external'):
activity = ExternalActivity(
timeout=options.get('timeout'),
heartbeat=options.get('heartbeat'))
activity_name = '{name}_{activity}'.format(
name=workflow_name,
activity=options.get('name'))
activity.hydrate(dict(
domain=domain,
version=version,
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'),
on_exception=options.get('on_exception') or on_exception))
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.
states = history.get(instance.activity_name, {}).get(instance.id)
if states:
if states.get_last_state() != ACTIVITY_FAILED:
continue
elif (not instance.retry or
instance.retry < count_activity_failures(states)):
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_states in require_history.values():
if ACTIVITY_COMPLETED not in requirement_states.states:
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):
states = history.get(instance.activity_name, {}).get(instance.id)
if not states or ACTIVITY_COMPLETED not in states.states:
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(states):
"""Count the number of times an activity has failed.
Args:
states (dict): list of activity states.
Return:
int: The number of times an activity has failed.
"""
return len([evt for evt in states.states if evt == ACTIVITY_FAILED])