summaryrefslogtreecommitdiffstats
path: root/azure/aria/aria-extension-cloudify/src/aria/aria/modeling/orchestration.py
blob: 4d4f0fe19215eee704f2e693763eb8b54e0bd393 (plain)
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
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

"""
ARIA modeling orchestration module
"""

# pylint: disable=no-self-argument, no-member, abstract-method
from datetime import datetime

from sqlalchemy import (
    Column,
    Integer,
    Text,
    DateTime,
    Boolean,
    Enum,
    String,
    Float,
    orm,
    PickleType)
from sqlalchemy.ext.declarative import declared_attr

from ..orchestrator.exceptions import (TaskAbortException, TaskRetryException)
from . import mixins
from . import (
    relationship,
    types as modeling_types
)


class ExecutionBase(mixins.ModelMixin):
    """
    Workflow execution.
    """

    __tablename__ = 'execution'

    __private_fields__ = ('service_fk',
                          'service_template')

    SUCCEEDED = 'succeeded'
    FAILED = 'failed'
    CANCELLED = 'cancelled'
    PENDING = 'pending'
    STARTED = 'started'
    CANCELLING = 'cancelling'

    STATES = (SUCCEEDED, FAILED, CANCELLED, PENDING, STARTED, CANCELLING)
    END_STATES = (SUCCEEDED, FAILED, CANCELLED)

    VALID_TRANSITIONS = {
        PENDING: (STARTED, CANCELLED),
        STARTED: END_STATES + (CANCELLING,),
        CANCELLING: END_STATES,
        # Retrying
        CANCELLED: PENDING,
        FAILED: PENDING
    }

    # region one_to_many relationships

    @declared_attr
    def inputs(cls):
        """
        Execution parameters.

        :type: {:obj:`basestring`: :class:`Input`}
        """
        return relationship.one_to_many(cls, 'input', dict_key='name')

    @declared_attr
    def tasks(cls):
        """
        Tasks.

        :type: [:class:`Task`]
        """
        return relationship.one_to_many(cls, 'task')

    @declared_attr
    def logs(cls):
        """
        Log messages for the execution (including log messages for its tasks).

        :type: [:class:`Log`]
        """
        return relationship.one_to_many(cls, 'log')

    # endregion

    # region many_to_one relationships

    @declared_attr
    def service(cls):
        """
        Associated service.

        :type: :class:`Service`
        """
        return relationship.many_to_one(cls, 'service')

    # endregion

    # region association proxies

    @declared_attr
    def service_name(cls):
        return relationship.association_proxy('service', cls.name_column_name())

    @declared_attr
    def service_template(cls):
        return relationship.association_proxy('service', 'service_template')

    @declared_attr
    def service_template_name(cls):
        return relationship.association_proxy('service', 'service_template_name')

    # endregion

    # region foreign keys

    @declared_attr
    def service_fk(cls):
        return relationship.foreign_key('service')

    # endregion

    created_at = Column(DateTime, index=True, doc="""
    Creation timestamp.

    :type: :class:`~datetime.datetime`
    """)

    started_at = Column(DateTime, nullable=True, index=True, doc="""
    Started timestamp.

    :type: :class:`~datetime.datetime`
    """)

    ended_at = Column(DateTime, nullable=True, index=True, doc="""
    Ended timestamp.

    :type: :class:`~datetime.datetime`
    """)

    error = Column(Text, nullable=True, doc="""
    Error message.

    :type: :obj:`basestring`
    """)

    status = Column(Enum(*STATES, name='execution_status'), default=PENDING, doc="""
    Status.

    :type: :obj:`basestring`
    """)

    workflow_name = Column(Text, doc="""
    Workflow name.

    :type: :obj:`basestring`
    """)

    @orm.validates('status')
    def validate_status(self, key, value):
        """Validation function that verifies execution status transitions are OK"""
        try:
            current_status = getattr(self, key)
        except AttributeError:
            return
        valid_transitions = self.VALID_TRANSITIONS.get(current_status, [])
        if all([current_status is not None,
                current_status != value,
                value not in valid_transitions]):
            raise ValueError('Cannot change execution status from {current} to {new}'.format(
                current=current_status,
                new=value))
        return value

    def has_ended(self):
        return self.status in self.END_STATES

    def is_active(self):
        return not self.has_ended() and self.status != self.PENDING

    def __str__(self):
        return '<{0} id=`{1}` (status={2})>'.format(
            self.__class__.__name__,
            getattr(self, self.name_column_name()),
            self.status
        )


class TaskBase(mixins.ModelMixin):
    """
    Represents the smallest unit of stateful execution in ARIA. The task state includes inputs,
    outputs, as well as an atomic status, ensuring that the task can only be running once at any
    given time.

    The Python :attr:`function` is usually provided by an associated :class:`Plugin`. The
    :attr:`arguments` of the function should be set according to the specific signature of the
    function.

    Tasks may be "one shot" or may be configured to run repeatedly in the case of failure.

    Tasks are often based on :class:`Operation`, and thus act on either a :class:`Node` or a
    :class:`Relationship`, however this is not required.
    """

    __tablename__ = 'task'

    __private_fields__ = ('node_fk',
                          'relationship_fk',
                          'plugin_fk',
                          'execution_fk')

    START_WORKFLOW = 'start_workflow'
    END_WORKFLOW = 'end_workflow'
    START_SUBWROFKLOW = 'start_subworkflow'
    END_SUBWORKFLOW = 'end_subworkflow'
    STUB = 'stub'
    CONDITIONAL = 'conditional'

    STUB_TYPES = (
        START_WORKFLOW,
        START_SUBWROFKLOW,
        END_WORKFLOW,
        END_SUBWORKFLOW,
        STUB,
        CONDITIONAL,
    )

    PENDING = 'pending'
    RETRYING = 'retrying'
    SENT = 'sent'
    STARTED = 'started'
    SUCCESS = 'success'
    FAILED = 'failed'
    STATES = (
        PENDING,
        RETRYING,
        SENT,
        STARTED,
        SUCCESS,
        FAILED,
    )
    INFINITE_RETRIES = -1

    # region one_to_many relationships

    @declared_attr
    def logs(cls):
        """
        Log messages.

        :type: [:class:`Log`]
        """
        return relationship.one_to_many(cls, 'log')

    @declared_attr
    def arguments(cls):
        """
        Arguments sent to the Python :attr:`function``.

        :type: {:obj:`basestring`: :class:`Argument`}
        """
        return relationship.one_to_many(cls, 'argument', dict_key='name')

    # endregion

    # region many_one relationships

    @declared_attr
    def execution(cls):
        """
        Containing execution.

        :type: :class:`Execution`
        """
        return relationship.many_to_one(cls, 'execution')

    @declared_attr
    def node(cls):
        """
        Node actor (can be ``None``).

        :type: :class:`Node`
        """
        return relationship.many_to_one(cls, 'node')

    @declared_attr
    def relationship(cls):
        """
        Relationship actor (can be ``None``).

        :type: :class:`Relationship`
        """
        return relationship.many_to_one(cls, 'relationship')

    @declared_attr
    def plugin(cls):
        """
        Associated plugin.

        :type: :class:`Plugin`
        """
        return relationship.many_to_one(cls, 'plugin')

    # endregion

    # region association proxies

    @declared_attr
    def node_name(cls):
        return relationship.association_proxy('node', cls.name_column_name())

    @declared_attr
    def relationship_name(cls):
        return relationship.association_proxy('relationship', cls.name_column_name())

    @declared_attr
    def execution_name(cls):
        return relationship.association_proxy('execution', cls.name_column_name())

    # endregion

    # region foreign keys

    @declared_attr
    def execution_fk(cls):
        return relationship.foreign_key('execution', nullable=True)

    @declared_attr
    def node_fk(cls):
        return relationship.foreign_key('node', nullable=True)

    @declared_attr
    def relationship_fk(cls):
        return relationship.foreign_key('relationship', nullable=True)

    @declared_attr
    def plugin_fk(cls):
        return relationship.foreign_key('plugin', nullable=True)

    # endregion

    status = Column(Enum(*STATES, name='status'), default=PENDING, doc="""
    Current atomic status ('pending', 'retrying', 'sent', 'started', 'success', 'failed').

    :type: :obj:`basestring`
    """)

    due_at = Column(DateTime, nullable=False, index=True, default=datetime.utcnow(), doc="""
    Timestamp to start the task.

    :type: :class:`~datetime.datetime`
    """)

    started_at = Column(DateTime, default=None, doc="""
    Started timestamp.

    :type: :class:`~datetime.datetime`
    """)

    ended_at = Column(DateTime, default=None, doc="""
    Ended timestamp.

    :type: :class:`~datetime.datetime`
    """)

    attempts_count = Column(Integer, default=1, doc="""
    How many attempts occurred.

    :type: :class:`~datetime.datetime`
    """)

    function = Column(String, doc="""
    Full path to Python function.

    :type: :obj:`basestring`
    """)

    max_attempts = Column(Integer, default=1, doc="""
    Maximum number of attempts allowed in case of task failure.

    :type: :obj:`int`
    """)

    retry_interval = Column(Float, default=0, doc="""
    Interval between task retry attemps (in seconds).

    :type: :obj:`float`
    """)

    ignore_failure = Column(Boolean, default=False, doc="""
    Set to ``True`` to ignore failures.

    :type: :obj:`bool`
    """)

    interface_name = Column(String, doc="""
    Name of interface on node or relationship.

    :type: :obj:`basestring`
    """)

    operation_name = Column(String, doc="""
    Name of operation in interface on node or relationship.

    :type: :obj:`basestring`
    """)

    _api_id = Column(String)
    _executor = Column(PickleType)
    _context_cls = Column(PickleType)
    _stub_type = Column(Enum(*STUB_TYPES))

    @property
    def actor(self):
        """
        Actor of the task (node or relationship).
        """
        return self.node or self.relationship

    @orm.validates('max_attempts')
    def validate_max_attempts(self, _, value):                                  # pylint: disable=no-self-use
        """
        Validates that max attempts is either -1 or a positive number.
        """
        if value < 1 and value != TaskBase.INFINITE_RETRIES:
            raise ValueError('Max attempts can be either -1 (infinite) or any positive number. '
                             'Got {value}'.format(value=value))
        return value

    @staticmethod
    def abort(message=None):
        raise TaskAbortException(message)

    @staticmethod
    def retry(message=None, retry_interval=None):
        raise TaskRetryException(message, retry_interval=retry_interval)

    @declared_attr
    def dependencies(cls):
        return relationship.many_to_many(cls, self=True)

    def has_ended(self):
        return self.status in (self.SUCCESS, self.FAILED)

    def is_waiting(self):
        if self._stub_type:
            return not self.has_ended()
        else:
            return self.status in (self.PENDING, self.RETRYING)

    @classmethod
    def from_api_task(cls, api_task, executor, **kwargs):
        instantiation_kwargs = {}

        if hasattr(api_task.actor, 'outbound_relationships'):
            instantiation_kwargs['node'] = api_task.actor
        elif hasattr(api_task.actor, 'source_node'):
            instantiation_kwargs['relationship'] = api_task.actor
        else:
            raise RuntimeError('No operation context could be created for {actor.model_cls}'
                               .format(actor=api_task.actor))

        instantiation_kwargs.update(
            {
                'name': api_task.name,
                'status': cls.PENDING,
                'max_attempts': api_task.max_attempts,
                'retry_interval': api_task.retry_interval,
                'ignore_failure': api_task.ignore_failure,
                'execution': api_task._workflow_context.execution,
                'interface_name': api_task.interface_name,
                'operation_name': api_task.operation_name,

                # Only non-stub tasks have these fields
                'plugin': api_task.plugin,
                'function': api_task.function,
                'arguments': api_task.arguments,
                '_context_cls': api_task._context_cls,
                '_executor': executor,
            }
        )

        instantiation_kwargs.update(**kwargs)

        return cls(**instantiation_kwargs)


class LogBase(mixins.ModelMixin):
    """
    Single log message.
    """

    __tablename__ = 'log'

    __private_fields__ = ('execution_fk',
                          'task_fk')

    # region many_to_one relationships

    @declared_attr
    def execution(cls):
        """
        Containing execution.

        :type: :class:`Execution`
        """
        return relationship.many_to_one(cls, 'execution')

    @declared_attr
    def task(cls):
        """
        Containing task (can be ``None``).

        :type: :class:`Task`
        """
        return relationship.many_to_one(cls, 'task')

    # endregion

    # region foreign keys

    @declared_attr
    def execution_fk(cls):
        return relationship.foreign_key('execution')

    @declared_attr
    def task_fk(cls):
        return relationship.foreign_key('task', nullable=True)

    # endregion

    level = Column(String, doc="""
    Log level.

    :type: :obj:`basestring`
    """)

    msg = Column(String, doc="""
    Log message.

    :type: :obj:`basestring`
    """)

    created_at = Column(DateTime, index=True, doc="""
    Creation timestamp.

    :type: :class:`~datetime.datetime`
    """)

    traceback = Column(Text, doc="""
    Error traceback in case of failure.

    :type: :class:`~datetime.datetime`
    """)

    def __str__(self):
        return self.msg

    def __repr__(self):
        name = (self.task.actor if self.task else self.execution).name
        return '{name}: {self.msg}'.format(name=name, self=self)


class PluginBase(mixins.ModelMixin):
    """
    Installed plugin.

    Plugins are usually packaged as `wagons <https://github.com/cloudify-cosmo/wagon>`__, which
    are archives of one or more `wheels <https://packaging.python.org/distributing/#wheels>`__.
    Most of these fields are indeed extracted from the installed wagon's metadata.
    """

    __tablename__ = 'plugin'

    # region one_to_many relationships

    @declared_attr
    def tasks(cls):
        """
        Associated Tasks.

        :type: [:class:`Task`]
        """
        return relationship.one_to_many(cls, 'task')

    # endregion

    archive_name = Column(Text, nullable=False, index=True, doc="""
    Filename (not the full path) of the wagon's archive, often with a ``.wgn`` extension.

    :type: :obj:`basestring`
    """)

    distribution = Column(Text, doc="""
    Name of the operating system on which the wagon was installed (e.g. ``ubuntu``).

    :type: :obj:`basestring`
    """)

    distribution_release = Column(Text, doc="""
    Release of the operating system on which the wagon was installed (e.g. ``trusty``).

    :type: :obj:`basestring`
    """)

    distribution_version = Column(Text, doc="""
    Version of the operating system on which the wagon was installed (e.g. ``14.04``).

    :type: :obj:`basestring`
    """)

    package_name = Column(Text, nullable=False, index=True, doc="""
    Primary Python package name used when the wagon was installed, which is one of the wheels in the
    wagon (e.g. ``cloudify-script-plugin``).

    :type: :obj:`basestring`
    """)

    package_source = Column(Text, doc="""
    Full install string for the primary Python package name used when the wagon was installed (e.g.
    ``cloudify-script-plugin==1.2``).

    :type: :obj:`basestring`
    """)

    package_version = Column(Text, doc="""
    Version for the primary Python package name used when the wagon was installed (e.g. ``1.2``).

    :type: :obj:`basestring`
    """)

    supported_platform = Column(Text, doc="""
    If the wheels are *all* pure Python then this would be "any", otherwise it would be the
    installed platform name (e.g. ``linux_x86_64``).

    :type: :obj:`basestring`
    """)

    supported_py_versions = Column(modeling_types.StrictList(basestring), doc="""
    Python versions supported by all the wheels (e.g. ``["py26", "py27"]``)

    :type: [:obj:`basestring`]
    """)

    wheels = Column(modeling_types.StrictList(basestring), nullable=False, doc="""
    Filenames of the wheels archived in the wagon, often with a ``.whl`` extension.

    :type: [:obj:`basestring`]
    """)

    uploaded_at = Column(DateTime, nullable=False, index=True, doc="""
    Timestamp for when the wagon was installed.

    :type: :class:`~datetime.datetime`
    """)


class ArgumentBase(mixins.ParameterMixin):
    """
    Python function argument parameter.
    """

    __tablename__ = 'argument'

    # region many_to_one relationships

    @declared_attr
    def task(cls):
        """
        Containing task (can be ``None``);

        :type: :class:`Task`
        """
        return relationship.many_to_one(cls, 'task')

    @declared_attr
    def operation(cls):
        """
        Containing operation (can be ``None``);

        :type: :class:`Operation`
        """
        return relationship.many_to_one(cls, 'operation')

    # endregion

    # region foreign keys

    @declared_attr
    def task_fk(cls):
        return relationship.foreign_key('task', nullable=True)

    @declared_attr
    def operation_fk(cls):
        return relationship.foreign_key('operation', nullable=True)

    # endregion