Test Failed
Push — master ( de3728...9a434d )
by Tomaz
02:00 queued 11s
created

st2actions/st2actions/workflows/workflows.py (1 issue)

1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
from __future__ import absolute_import
17
18
import kombu
19
20
from orquesta import events
21
from orquesta import states
22
23
from st2common.constants import action as ac_const
24
from st2common import log as logging
25
from st2common.models.db import execution as ex_db_models
26
from st2common.models.db import workflow as wf_db_models
27
from st2common.persistence import liveaction as lv_db_access
28
from st2common.persistence import workflow as wf_db_access
29
from st2common.services import policies as pc_svc
30
from st2common.services import workflows as wf_svc
31
from st2common.transport import consumers
32
from st2common.transport import queues
33
from st2common.transport import utils as txpt_utils
34
from st2common.metrics.base import CounterWithTimer
35
36
37
LOG = logging.getLogger(__name__)
38
39
40
WORKFLOW_EXECUTION_QUEUES = [
41
    queues.WORKFLOW_EXECUTION_WORK_QUEUE,
42
    queues.WORKFLOW_EXECUTION_RESUME_QUEUE,
43
    queues.WORKFLOW_ACTION_EXECUTION_UPDATE_QUEUE
44
]
45
46
47
class WorkflowExecutionHandler(consumers.VariableMessageHandler):
48
49
    def __init__(self, connection, queues):
50
        super(WorkflowExecutionHandler, self).__init__(connection, queues)
51
52
        def handle_workflow_execution_with_instrumentation(wf_ex_db):
53
            with CounterWithTimer(key='orquesta.workflow.executions'):
54
                return self.handle_workflow_execution(wf_ex_db=wf_ex_db)
55
56
        def handle_action_execution_with_instrumentation(ac_ex_db):
57
            # Ignore non orquesta workflow executions
58
            if not self._is_orquesta_execution(ac_ex_db=ac_ex_db):
59
                return
60
61
            with CounterWithTimer(key='orquesta.action.executions'):
62
                return self.handle_action_execution(ac_ex_db=ac_ex_db)
63
64
        self.message_types = {
65
            wf_db_models.WorkflowExecutionDB: handle_workflow_execution_with_instrumentation,
66
            ex_db_models.ActionExecutionDB: handle_action_execution_with_instrumentation
67
        }
68
69
    def get_queue_consumer(self, connection, queues):
70
        # We want to use a special ActionsQueueConsumer which uses 2 dispatcher pools
71
        return consumers.VariableMessageQueueConsumer(
72
            connection=connection,
73
            queues=queues,
74
            handler=self
75
        )
76
77
    def process(self, message):
78
        handler_function = self.message_types.get(type(message), None)
79
        if not handler_function:
80
            raise ValueError('Handler function for message type "%s" is not defined' %
81
                             (type(message)))
82
83
        handler_function(message)
84
85
    def handle_workflow_execution(self, wf_ex_db):
86
        iteration = 0
87
        wf_ac_ex_id = wf_ex_db.action_execution
88
        LOG.info('[%s] Processing request for workflow execution.', wf_ac_ex_id)
89
90
        # Refresh record from the database in case the request is in the queue for too long.
91
        conductor, wf_ex_db = wf_svc.refresh_conductor(str(wf_ex_db.id))
92
93
        # Continue if workflow is still active and set workflow to running state.
94
        if conductor.get_workflow_state() not in states.COMPLETED_STATES:
95
            LOG.info('[%s] Requesting conductor to start running workflow execution.', wf_ac_ex_id)
96
            conductor.request_workflow_state(states.RUNNING)
97
98
        # Identify the next set of tasks to execute.
99
        msg = '[%s] Identifying next set (%s) of tasks for workflow execution in state "%s".'
100
        LOG.info(msg, wf_ac_ex_id, str(iteration), conductor.get_workflow_state())
101
        LOG.debug('[%s] %s', wf_ac_ex_id, conductor.serialize())
102
        next_tasks = conductor.get_next_tasks()
103
104
        # If there is no new tasks, update execution records to handle possible completion.
105
        if not next_tasks:
106
            # Update workflow execution and related liveaction and action execution.
107
            LOG.info('[%s] No tasks identified to execute next.', wf_ac_ex_id)
108
            wf_svc.update_execution_records(wf_ex_db, conductor)
109
110
        # If workflow execution is no longer active, then stop processing here.
111
        if wf_ex_db.status in states.COMPLETED_STATES:
112
            msg = '[%s] Workflow execution is in completed state "%s".'
113
            LOG.info(msg, wf_ac_ex_id, wf_ex_db.status)
114
            return
115
116
        # Iterate while there are next tasks identified for processing. In the case for
117
        # task with no action execution defined, the task execution will complete
118
        # immediately with a new set of tasks available.
119
        while next_tasks:
120
            msg = '[%s] Identified the following set of tasks to execute next: %s'
121
            LOG.info(msg, wf_ac_ex_id, ', '.join([task['id'] for task in next_tasks]))
122
123
            # Mark the tasks as running in the task flow before actual task execution.
124
            for task in next_tasks:
125
                msg = '[%s] Mark task "%s" in conductor as running.'
126
                LOG.info(msg, wf_ac_ex_id, task['id'])
127
                ac_ex_event = events.ActionExecutionEvent(states.RUNNING)
128
                conductor.update_task_flow(task['id'], ac_ex_event)
129
130
            # Update workflow execution and related liveaction and action execution.
131
            wf_svc.update_execution_records(wf_ex_db, conductor)
132
133
            # If workflow execution is no longer active, then stop processing here.
134
            if wf_ex_db.status in states.COMPLETED_STATES:
135
                msg = '[%s] Workflow execution is in completed state "%s".'
136
                LOG.info(msg, wf_ac_ex_id, wf_ex_db.status)
137
                break
138
139
            # Request task execution for the tasks.
140
            for task in next_tasks:
141
                try:
142
                    LOG.info('[%s] Requesting execution for task "%s".', wf_ac_ex_id, task['id'])
143
                    task_id, task_spec, task_ctx = task['id'], task['spec'], task['ctx']
144
                    st2_ctx = {'execution_id': wf_ex_db.action_execution}
145
                    wf_svc.request_task_execution(wf_ex_db, task_id, task_spec, task_ctx, st2_ctx)
146
                except Exception as e:
147
                    LOG.exception('[%s] Failed task execution for "%s".', wf_ac_ex_id, task['id'])
148
                    wf_svc.fail_workflow_execution(str(wf_ex_db.id), e, task_id=task['id'])
149
                    return
150
151
            # Identify the next set of tasks to execute.
152
            iteration += 1
153
            conductor, wf_ex_db = wf_svc.refresh_conductor(str(wf_ex_db.id))
154
            msg = '[%s] Identifying next set (%s) of tasks for workflow execution in state "%s".'
155
            LOG.info(msg, wf_ac_ex_id, str(iteration), conductor.get_workflow_state())
156
            LOG.debug('[%s] %s', wf_ac_ex_id, conductor.serialize())
157
            next_tasks = conductor.get_next_tasks()
158
159
            if not next_tasks:
160
                LOG.info('[%s] No tasks identified to execute next.', wf_ac_ex_id)
161
162
    def handle_action_execution(self, ac_ex_db):
163
        # Exit if action execution is not  executed under an orquesta workflow.
164
        if not self._is_orquesta_execution(ac_ex_db=ac_ex_db):
165
            return
166
167
        # Get related record identifiers.
168
        wf_ex_id = ac_ex_db.context['orquesta']['workflow_execution_id']
169
        task_ex_id = ac_ex_db.context['orquesta']['task_execution_id']
170
171
        # Get execution records for logging purposes.
172
        wf_ex_db = wf_db_access.WorkflowExecution.get_by_id(wf_ex_id)
173
        task_ex_db = wf_db_access.TaskExecution.get_by_id(task_ex_id)
174
175
        wf_ac_ex_id = wf_ex_db.action_execution
176
        msg = '[%s] Action execution "%s" for task "%s" is updated and in "%s" state.'
177
        LOG.info(msg, wf_ac_ex_id, str(ac_ex_db.id), task_ex_db.task_id, ac_ex_db.status)
178
179
        # Skip if task execution is already in completed state.
180
        if task_ex_db.status in states.COMPLETED_STATES:
181
            LOG.info(
182
                '[%s] Action execution "%s" for task "%s" is not processed because '
183
                'task execution "%s" is already in completed state "%s".',
184
                wf_ac_ex_id,
185
                str(ac_ex_db.id),
186
                task_ex_db.task_id,
187
                str(task_ex_db.id),
188
                task_ex_db.status
189
            )
190
191
            return
192
193
        # Process pending request on the action execution.
194
        if ac_ex_db.status == ac_const.LIVEACTION_STATUS_PENDING:
195
            wf_svc.handle_action_execution_pending(ac_ex_db)
196
            return
197
198
        # Process pause request on the action execution.
199
        if ac_ex_db.status == ac_const.LIVEACTION_STATUS_PAUSED:
200
            wf_svc.handle_action_execution_pause(ac_ex_db)
201
            return
202
203
        # Exit if action execution has not completed yet.
204
        if ac_ex_db.status not in ac_const.LIVEACTION_COMPLETED_STATES:
205
            return
206
207
        # Apply post run policies.
208
        lv_ac_db = lv_db_access.LiveAction.get_by_id(ac_ex_db.liveaction['id'])
209
        pc_svc.apply_post_run_policies(lv_ac_db)
210
211
        # Process completion of the action execution.
212
        wf_svc.handle_action_execution_completion(ac_ex_db)
213
214
    def _is_orquesta_execution(self, ac_ex_db):
215
        """
216
        Return True if particular execution object represents a task in orquesta workflow, False
217
        otherwise.
218
        """
219
        return ('orquesta' in ac_ex_db.context)
0 ignored issues
show
Unused Code Coding Style introduced by
There is an unnecessary parenthesis after return.
Loading history...
220
221
222
def get_engine():
223
    with kombu.Connection(txpt_utils.get_messaging_urls()) as conn:
224
        return WorkflowExecutionHandler(conn, WORKFLOW_EXECUTION_QUEUES)
225