Debian Codegraph @

mistralclient/commands/v2/executions.py

raw symbols SCIP
1 # Copyright 2014 - Mirantis, Inc.
2 # Copyright 2015 - StackStorm, Inc.
3 # Copyright 2016 - Brocade Communications Systems, Inc.
4 #
5 # All Rights Reserved
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18 #
19
20 import logging
21 import os.path
22
23 from oslo_serialization import jsonutils
24
25 from osc_lib.command import command
26
27 from cliff.lister import Lister as cliff_lister
28 from mistralclient.commands.v2 import base
29 from mistralclient import utils
30
31 LOG = logging.getLogger(__name__)
32
33
34 class ExecutionFormatter(base.MistralFormatter):
35 COLUMNS = [
36 ('id', 'ID'),
37 ('workflow_id', 'Workflow ID'),
38 ('workflow_name', 'Workflow name'),
39 ('workflow_namespace', 'Workflow namespace'),
40 ('description', 'Description'),
41 ('task_execution_id', 'Task Execution ID'),
42 ('root_execution_id', 'Root Execution ID'),
43 ('state', 'State'),
44 ('state_info', 'State info'),
45 ('created_at', 'Created at'),
46 ('updated_at', 'Updated at'),
47 ('duration', 'Duration', True),
48 ]
49
50 @staticmethod
51 def format(wf_ex=None, lister=False):
52 if wf_ex:
53 state_info = (
54 wf_ex.state_info if not lister
55 else base.cut(wf_ex.state_info)
56 )
57
58 duration = base.get_duration_str(
59 wf_ex.created_at,
60 wf_ex.updated_at if wf_ex.state in ['ERROR', 'SUCCESS'] else ''
61 )
62
63 data = (
64 wf_ex.id,
65 wf_ex.workflow_id,
66 wf_ex.workflow_name,
67 wf_ex.workflow_namespace,
68 wf_ex.description,
69 wf_ex.task_execution_id or '<none>',
70 wf_ex.root_execution_id or '<none>',
71 wf_ex.state,
72 state_info,
73 wf_ex.created_at,
74 wf_ex.updated_at or '<none>',
75 duration
76 )
77 else:
78 data = (tuple('' for _ in
79 range(len(ExecutionFormatter.COLUMNS))),)
80
81 return ExecutionFormatter.headings(), data
82
83
84 class List(base.MistralExecutionLister):
85 """List all executions."""
86
87 def _get_format_function(self):
88 return ExecutionFormatter.format_list
89
90 def get_parser(self, parsed_args):
91 parser = super(List, self).get_parser(parsed_args)
92
93 parser.add_argument(
94 '--task',
95 nargs='?',
96 help="Parent task execution ID associated with workflow "
97 "execution list.",
98 )
99 parser.add_argument(
100 '--rootsonly',
101 help="return only root executions",
102 action='store_true',
103 )
104
105 return parser
106
107 def _get_resources(self, parsed_args):
108 mistral_client = self.app.client_manager.workflow_engine
109
110 none_fields = 'root_execution_id' if parsed_args.rootsonly else ''
111
112 return mistral_client.executions.list(
113 nulls=none_fields,
114 task=parsed_args.task,
115 marker=parsed_args.marker,
116 limit=parsed_args.limit,
117 sort_keys=parsed_args.sort_keys,
118 sort_dirs=parsed_args.sort_dirs,
119 fields=ExecutionFormatter.fields(),
120 **base.get_filters(parsed_args)
121 )
122
123
124 class Get(command.ShowOne):
125 """Show specific execution."""
126
127 def get_parser(self, prog_name):
128 parser = super(Get, self).get_parser(prog_name)
129
130 parser.add_argument('execution', help='Execution identifier')
131
132 return parser
133
134 def take_action(self, parsed_args):
135 mistral_client = self.app.client_manager.workflow_engine
136 execution = mistral_client.executions.get(parsed_args.execution)
137
138 return ExecutionFormatter.format(execution)
139
140
141 class Create(command.ShowOne):
142 """Create new execution."""
143
144 def get_parser(self, prog_name):
145 parser = super(Create, self).get_parser(prog_name)
146
147 parser.add_argument(
148 'workflow_identifier',
149 nargs='?',
150 help='Workflow ID or name'
151 )
152 parser.add_argument(
153 '--namespace',
154 nargs='?',
155 default='',
156 help="Workflow namespace."
157 )
158 parser.add_argument(
159 'workflow_input',
160 nargs='?',
161 help='Workflow input'
162 )
163 parser.add_argument(
164 'params',
165 nargs='?',
166 help='Workflow additional parameters'
167 )
168 parser.add_argument(
169 '-d',
170 '--description',
171 dest='description',
172 default='',
173 help='Execution description'
174 )
175 parser.add_argument(
176 '-s',
177 dest='source_execution_id',
178 nargs='?',
179 help="Workflow Execution id which will allow operators to create "
180 "a new workflow execution based on the previously successful "
181 "executed workflow. Example: mistral execution-create -s "
182 "123e4567-e89b-12d3-a456-426655440000")
183
184 return parser
185
186 def take_action(self, parsed_args):
187 if parsed_args.workflow_input:
188 wf_input = utils.load_json(parsed_args.workflow_input)
189 else:
190 wf_input = {}
191
192 if parsed_args.params:
193 params = utils.load_json(parsed_args.params)
194 else:
195 params = {}
196
197 mistral_client = self.app.client_manager.workflow_engine
198
199 execution = mistral_client.executions.create(
200 parsed_args.workflow_identifier,
201 parsed_args.namespace,
202 wf_input,
203 parsed_args.description,
204 parsed_args.source_execution_id,
205 **params
206 )
207
208 return ExecutionFormatter.format(execution)
209
210
211 class Delete(command.Command):
212 """Delete execution."""
213
214 def get_parser(self, prog_name):
215 parser = super(Delete, self).get_parser(prog_name)
216
217 parser.add_argument(
218 'execution',
219 nargs='+',
220 help='Id of execution identifier(s).'
221 )
222
223 parser.add_argument(
224 '--force',
225 default=False,
226 action='store_true',
227 help='Force the deletion of an execution. Might cause a cascade '
228 ' of errors if used for running executions.'
229 )
230
231 return parser
232
233 def take_action(self, parsed_args):
234 mistral_client = self.app.client_manager.workflow_engine
235
236 force = parsed_args.force
237
238 utils.do_action_on_many(
239 lambda s: mistral_client.executions.delete(s, force=force),
240 parsed_args.execution,
241 "Request to delete execution %s has been accepted.",
242 "Unable to delete the specified execution(s)."
243 )
244
245
246 class Update(command.ShowOne):
247 """Update execution."""
248
249 def get_parser(self, prog_name):
250 parser = super(Update, self).get_parser(prog_name)
251
252 parser.add_argument('id', help='Execution identifier')
253
254 parser.add_argument(
255 '-s',
256 '--state',
257 dest='state',
258 choices=['RUNNING', 'PAUSED', 'SUCCESS', 'ERROR', 'CANCELLED'],
259 help='Execution state'
260 )
261
262 parser.add_argument(
263 '-e',
264 '--env',
265 dest='env',
266 help='Environment variables'
267 )
268
269 parser.add_argument(
270 '-d',
271 '--description',
272 dest='description',
273 help='Execution description'
274 )
275
276 return parser
277
278 def take_action(self, parsed_args):
279 mistral_client = self.app.client_manager.workflow_engine
280
281 env = (
282 utils.load_file(parsed_args.env)
283 if parsed_args.env and os.path.isfile(parsed_args.env)
284 else utils.load_content(parsed_args.env)
285 )
286
287 execution = mistral_client.executions.update(
288 parsed_args.id,
289 parsed_args.state,
290 description=parsed_args.description,
291 env=env
292 )
293
294 return ExecutionFormatter.format(execution)
295
296
297 class GetInput(command.Command):
298 """Show execution input data."""
299
300 def get_parser(self, prog_name):
301 parser = super(GetInput, self).get_parser(prog_name)
302
303 parser.add_argument('id', help='Execution ID')
304
305 return parser
306
307 def take_action(self, parsed_args):
308 mistral_client = self.app.client_manager.workflow_engine
309
310 ex_input = mistral_client.executions.get(parsed_args.id).input
311
312 try:
313 ex_input = jsonutils.loads(ex_input)
314 ex_input = jsonutils.dumps(ex_input, indent=4) + "\n"
315 except Exception:
316 LOG.debug("Execution input is not JSON.")
317
318 self.app.stdout.write(ex_input or "\n")
319
320
321 class GetOutput(command.Command):
322 """Show execution output data."""
323
324 def get_parser(self, prog_name):
325 parser = super(GetOutput, self).get_parser(prog_name)
326
327 parser.add_argument('id', help='Execution ID')
328
329 return parser
330
331 def take_action(self, parsed_args):
332 mistral_client = self.app.client_manager.workflow_engine
333
334 output = mistral_client.executions.get(parsed_args.id).output
335
336 try:
337 output = jsonutils.loads(output)
338 output = jsonutils.dumps(output, indent=4) + "\n"
339 except Exception:
340 LOG.debug("Execution output is not JSON.")
341
342 self.app.stdout.write(output or "\n")
343
344
345 REPORT_ENTRY_INDENT = 4
346
347
348 class GetReport(command.Command):
349 """Print execution report."""
350
351 def get_parser(self, prog_name):
352 parser = super(GetReport, self).get_parser(prog_name)
353
354 parser.add_argument('id', help='Execution ID')
355 parser.add_argument(
356 '--errors-only',
357 dest='errors_only',
358 action='store_true',
359 help='Only error paths will be included.'
360 )
361 parser.add_argument(
362 '--statistics-only',
363 dest='statistics_only',
364 action='store_true',
365 help='Only the statistics will be included.'
366 )
367 parser.add_argument(
368 '--no-errors-only',
369 dest='errors_only',
370 action='store_false',
371 help='Not only error paths will be included.'
372 )
373 parser.set_defaults(errors_only=True)
374
375 parser.add_argument(
376 '--max-depth',
377 dest='max_depth',
378 nargs='?',
379 type=int,
380 default=-1,
381 help='Maximum depth of the workflow execution tree. '
382 'If 0, only the root workflow execution and its '
383 'tasks will be included'
384 )
385
386 return parser
387
388 def print_line(self, line, level=0):
389 self.app.stdout.write(
390 "%s%s\n" % (' ' * (level * REPORT_ENTRY_INDENT), line)
391 )
392
393 def print_workflow_execution_entry(self, wf_ex, level):
394 self.print_line(
395 "workflow '%s' [%s] %s" %
396 (wf_ex['name'], wf_ex['state'], wf_ex['id']),
397 level
398 )
399
400 if 'task_executions' in wf_ex:
401 for t_ex in wf_ex['task_executions']:
402 self.print_task_execution_entry(t_ex, level + 1)
403
404 def print_task_execution_entry(self, t_ex, level):
405 self.print_line(
406 "task '%s' [%s] %s" %
407 (t_ex['name'], t_ex['state'], t_ex['id']),
408 level
409 )
410
411 if 'retry_count' in t_ex:
412 self.print_line('(retry count: %s)' % t_ex['retry_count'], level)
413
414 if t_ex['state'] == 'ERROR':
415 state_info = t_ex['state_info']
416
417 if state_info:
418 state_info = state_info[0:100].replace('\n', ' ') + '...'
419
420 self.print_line('(error info: %s)' % state_info, level)
421
422 if 'action_executions' in t_ex:
423 for a_ex in t_ex['action_executions']:
424 self.print_action_execution_entry(a_ex, level + 1)
425
426 if 'workflow_executions' in t_ex:
427 for wf_ex in t_ex['workflow_executions']:
428 self.print_workflow_execution_entry(wf_ex, level + 1)
429
430 def print_action_execution_entry(self, a_ex, level):
431 self.print_line(
432 "action '%s' [%s] %s" %
433 (a_ex['name'], a_ex['state'], a_ex['id']),
434 level
435 )
436
437 if a_ex['state'] == 'ERROR':
438 state_info = a_ex['state_info']
439
440 if state_info:
441 state_info = state_info[0:100] + '...'
442
443 self.print_line('(error info: %s)' % state_info, level)
444
445 def print_statistics(self, stat):
446 self.print_line(
447 'Number of tasks in SUCCESS state: %s' %
448 stat['success_tasks_count']
449 )
450 self.print_line(
451 'Number of tasks in ERROR state: %s' % stat['error_tasks_count']
452 )
453 self.print_line(
454 'Number of tasks in RUNNING state: %s' %
455 stat['running_tasks_count']
456 )
457 self.print_line(
458 'Number of tasks in IDLE state: %s' % stat['idle_tasks_count']
459 )
460 self.print_line(
461 'Number of tasks in PAUSED state: %s\n' %
462 stat['paused_tasks_count']
463 )
464
465 if 'estimated_time' in stat:
466 self.print_line(
467 'Estimated time (seconds) for the execution to finish:'' %s\n'
468 % stat['estimated_time']
469 )
470
471 def print_report(self, report_json):
472 self.print_line(
473 "\nTo get more details on a task failure "
474 "run: mistral task-get <id> -c 'State info'\n"
475 )
476
477 frame_line = '=' * 30
478
479 self.print_line(
480 '%s General Statistics %s\n' %
481 (frame_line, frame_line)
482 )
483 self.print_statistics(report_json['statistics'])
484
485 if 'root_workflow_execution' in report_json:
486 self.print_line(
487 '%s Workflow Execution Tree %s\n' %
488 (frame_line, frame_line)
489 )
490 self.print_workflow_execution_entry(
491 report_json['root_workflow_execution'],
492 0
493 )
494
495 def take_action(self, parsed_args):
496 mistral_client = self.app.client_manager.workflow_engine
497
498 report_json = mistral_client.executions.get_report(
499 parsed_args.id,
500 errors_only=parsed_args.errors_only,
501 max_depth=parsed_args.max_depth,
502 statistics_only=parsed_args.statistics_only,
503 )
504
505 self.print_report(report_json)
506
507
508 class GetPublished(command.Command):
509 """Show workflow global published variables."""
510
511 def get_parser(self, prog_name):
512 parser = super(GetPublished, self).get_parser(prog_name)
513 parser.add_argument(
514 'id',
515 help='Workflow ID')
516
517 return parser
518
519 def take_action(self, parsed_args):
520 mistral_client = self.app.client_manager.workflow_engine
521 res = mistral_client.executions.get(parsed_args.id)
522 published = res.published_global \
523 if hasattr(res, 'published_global') else None
524
525 try:
526 published = jsonutils.loads(published)
527 published = jsonutils.dumps(published, indent=4) + "\n"
528 except Exception:
529 LOG.debug("Task result is not JSON.")
530
531 self.app.stdout.write(published or "\n")
532
533
534 class SubExecutionsBaseLister(cliff_lister):
535
536 def _get_format_function(self):
537 raise NotImplementedError
538
539 def _get_resources_function(self):
540 raise NotImplementedError
541
542 def get_parser(self, prog_name):
543 parser = super(SubExecutionsBaseLister, self).get_parser(prog_name)
544
545 parser.add_argument(
546 'id',
547 metavar='ID',
548 help='origin id'
549 )
550 parser.add_argument(
551 '--errors-only',
552 dest='errors_only',
553 action='store_true',
554 help='Only error paths will be included.'
555 )
556 parser.add_argument(
557 '--max-depth',
558 dest='max_depth',
559 nargs='?',
560 type=int,
561 default=-1,
562 help='Maximum depth of the workflow execution tree. '
563 'If 0, only the root workflow execution and its '
564 'tasks will be included'
565 )
566
567 return parser
568
569 def _get_resources(self, parsed_args):
570 resource_function = self._get_resources_function()
571 errors_only = parsed_args.errors_only or ''
572
573 return resource_function(
574 parsed_args.id,
575 errors_only=errors_only,
576 max_depth=parsed_args.max_depth,
577 )
578
579 def take_action(self, parsed_args):
580 format_func = self._get_format_function()
581 execs_list = self._get_resources(parsed_args)
582
583 if not isinstance(execs_list, list):
584 execs_list = [execs_list]
585
586 data = [format_func(r)[1] for r in execs_list]
587
588 return (format_func()[0], data) if data else format_func()
589
590
591 class SubExecutionsLister(SubExecutionsBaseLister):
592
593 def _get_format_function(self):
594 return ExecutionFormatter.format_list
595
596 def _get_resources_function(self):
597 mistral_client = self.app.client_manager.workflow_engine
598
599 return mistral_client.executions.get_ex_sub_executions