1 # Licensed to the Apache Software Foundation (ASF) 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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
22 from datetime import datetime
24 from . import exceptions
25 from .context.workflow import WorkflowContext
26 from .workflows import builtin
27 from .workflows.core import engine, graph_compiler
28 from .workflows.executor.process import ProcessExecutor
29 from ..modeling import models
30 from ..modeling import utils as modeling_utils
31 from ..utils.imports import import_fullname
34 DEFAULT_TASK_MAX_ATTEMPTS = 30
35 DEFAULT_TASK_RETRY_INTERVAL = 30
38 class WorkflowRunner(object):
40 def __init__(self, model_storage, resource_storage, plugin_manager,
41 execution_id=None, retry_failed_tasks=False,
42 service_id=None, workflow_name=None, inputs=None, executor=None,
43 task_max_attempts=DEFAULT_TASK_MAX_ATTEMPTS,
44 task_retry_interval=DEFAULT_TASK_RETRY_INTERVAL):
46 Manages a single workflow execution on a given service.
48 :param workflow_name: workflow name
49 :param service_id: service ID
50 :param inputs: key-value dict of inputs for the execution
51 :param model_storage: model storage API ("MAPI")
52 :param resource_storage: resource storage API ("RAPI")
53 :param plugin_manager: plugin manager
54 :param executor: executor for tasks; defaults to a
55 :class:`~aria.orchestrator.workflows.executor.process.ProcessExecutor` instance
56 :param task_max_attempts: maximum attempts of repeating each failing task
57 :param task_retry_interval: retry interval between retry attempts of a failing task
60 if not (execution_id or (workflow_name and service_id)):
61 exceptions.InvalidWorkflowRunnerParams(
62 "Either provide execution id in order to resume a workflow or workflow name "
63 "and service id with inputs")
65 self._is_resume = execution_id is not None
66 self._retry_failed_tasks = retry_failed_tasks
68 self._model_storage = model_storage
69 self._resource_storage = resource_storage
71 # the IDs are stored rather than the models themselves, so this module could be used
72 # by several threads without raising errors on model objects shared between threads
75 self._execution_id = execution_id
76 self._service_id = self.execution.service.id
77 self._workflow_name = model_storage.execution.get(self._execution_id).workflow_name
79 self._service_id = service_id
80 self._workflow_name = workflow_name
81 self._validate_workflow_exists_for_service()
82 self._execution_id = self._create_execution_model(inputs).id
84 self._workflow_context = WorkflowContext(
85 name=self.__class__.__name__,
86 model_storage=self._model_storage,
87 resource_storage=resource_storage,
88 service_id=service_id,
89 execution_id=self._execution_id,
90 workflow_name=self._workflow_name,
91 task_max_attempts=task_max_attempts,
92 task_retry_interval=task_retry_interval)
94 # Set default executor and kwargs
95 executor = executor or ProcessExecutor(plugin_manager=plugin_manager)
97 # transforming the execution inputs to dict, to pass them to the workflow function
98 execution_inputs_dict = dict(inp.unwrapped for inp in self.execution.inputs.itervalues())
100 if not self._is_resume:
101 workflow_fn = self._get_workflow_fn()
102 self._tasks_graph = workflow_fn(ctx=self._workflow_context, **execution_inputs_dict)
103 compiler = graph_compiler.GraphCompiler(self._workflow_context, executor.__class__)
104 compiler.compile(self._tasks_graph)
106 self._engine = engine.Engine(executors={executor.__class__: executor})
109 def execution_id(self):
110 return self._execution_id
114 return self._model_storage.execution.get(self.execution_id)
118 return self._model_storage.service.get(self._service_id)
121 self._engine.execute(ctx=self._workflow_context,
122 resuming=self._is_resume,
123 retry_failed=self._retry_failed_tasks)
126 self._engine.cancel_execution(ctx=self._workflow_context)
128 def _create_execution_model(self, inputs):
129 execution = models.Execution(
130 created_at=datetime.utcnow(),
131 service=self.service,
132 workflow_name=self._workflow_name,
135 if self._workflow_name in builtin.BUILTIN_WORKFLOWS:
136 workflow_inputs = dict() # built-in workflows don't have any inputs
138 workflow_inputs = self.service.workflows[self._workflow_name].inputs
140 # modeling_utils.validate_no_undeclared_inputs(declared_inputs=workflow_inputs,
141 # supplied_inputs=inputs or {})
142 modeling_utils.validate_required_inputs_are_supplied(declared_inputs=workflow_inputs,
143 supplied_inputs=inputs or {})
144 execution.inputs = modeling_utils.merge_parameter_values(
145 inputs, workflow_inputs, model_cls=models.Input)
146 # TODO: these two following calls should execute atomically
147 self._validate_no_active_executions(execution)
148 self._model_storage.execution.put(execution)
151 def _validate_workflow_exists_for_service(self):
152 if self._workflow_name not in self.service.workflows and \
153 self._workflow_name not in builtin.BUILTIN_WORKFLOWS:
154 raise exceptions.UndeclaredWorkflowError(
155 'No workflow policy {0} declared in service {1}'
156 .format(self._workflow_name, self.service.name))
158 def _validate_no_active_executions(self, execution):
159 active_executions = [e for e in self.service.executions if e.is_active()]
160 if active_executions:
161 raise exceptions.ActiveExecutionsError(
162 "Can't start execution; Service {0} has an active execution with ID {1}"
163 .format(self.service.name, active_executions[0].id))
165 def _get_workflow_fn(self):
166 if self._workflow_name in builtin.BUILTIN_WORKFLOWS:
167 return import_fullname('{0}.{1}'.format(builtin.BUILTIN_WORKFLOWS_PATH_PREFIX,
168 self._workflow_name))
170 workflow = self.service.workflows[self._workflow_name]
172 # TODO: Custom workflow support needs improvement, currently this code uses internal
173 # knowledge of the resource storage; Instead, workflows should probably be loaded
174 # in a similar manner to operation plugins. Also consider passing to import_fullname
175 # as paths instead of appending to sys path.
176 service_template_resources_path = os.path.join(
177 self._resource_storage.service_template.base_path,
178 str(self.service.service_template.id))
179 sys.path.append(service_template_resources_path)
182 workflow_fn = import_fullname(workflow.function)
184 raise exceptions.WorkflowImplementationNotFoundError(
185 'Could not find workflow {0} function at {1}'.format(
186 self._workflow_name, workflow.function))