-
-
Notifications
You must be signed in to change notification settings - Fork 740
/
pack.py
503 lines (413 loc) · 18.3 KB
/
pack.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
# Licensed to the StackStorm, Inc ('StackStorm') 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.
from __future__ import absolute_import
import sys
import six
import editor
import yaml
from st2client.models import Config
from st2client.models import Pack
from st2client.models import Execution
from st2client.commands import resource
from st2client.commands.resource import add_auth_token_to_kwargs_from_cli
from st2client.commands.action import ActionRunCommandMixin
from st2client.formatters import table
from st2client.exceptions.operations import OperationFailureException
import st2client.utils.terminal as term
from st2client.utils import interactive
LIVEACTION_STATUS_REQUESTED = 'requested'
LIVEACTION_STATUS_SCHEDULED = 'scheduled'
LIVEACTION_STATUS_DELAYED = 'delayed'
LIVEACTION_STATUS_RUNNING = 'running'
LIVEACTION_STATUS_SUCCEEDED = 'succeeded'
LIVEACTION_STATUS_FAILED = 'failed'
LIVEACTION_STATUS_TIMED_OUT = 'timeout'
LIVEACTION_STATUS_ABANDONED = 'abandoned'
LIVEACTION_STATUS_CANCELING = 'canceling'
LIVEACTION_STATUS_CANCELED = 'canceled'
LIVEACTION_COMPLETED_STATES = [
LIVEACTION_STATUS_SUCCEEDED,
LIVEACTION_STATUS_FAILED,
LIVEACTION_STATUS_TIMED_OUT,
LIVEACTION_STATUS_CANCELED,
LIVEACTION_STATUS_ABANDONED,
]
class PackBranch(resource.ResourceBranch):
def __init__(self, description, app, subparsers, parent_parser=None):
super(PackBranch, self).__init__(
Pack,
description,
app,
subparsers,
parent_parser=parent_parser,
read_only=True,
commands={'list': PackListCommand, 'get': PackGetCommand},
)
self.commands['show'] = PackShowCommand(self.resource, self.app, self.subparsers)
self.commands['search'] = PackSearchCommand(self.resource, self.app, self.subparsers)
self.commands['install'] = PackInstallCommand(self.resource, self.app, self.subparsers)
self.commands['remove'] = PackRemoveCommand(self.resource, self.app, self.subparsers)
self.commands['register'] = PackRegisterCommand(self.resource, self.app, self.subparsers)
self.commands['config'] = PackConfigCommand(self.resource, self.app, self.subparsers)
class PackResourceCommand(resource.ResourceCommand):
def run_and_print(self, args, **kwargs):
try:
instance = self.run(args, **kwargs)
if not instance:
raise resource.ResourceNotFoundError("No matching items found")
self.print_output(
instance,
table.PropertyValueTable,
attributes=['all'],
json=args.json,
yaml=args.yaml,
)
except resource.ResourceNotFoundError:
print("No matching items found")
except Exception as e:
message = six.text_type(e)
print('ERROR: %s' % (message))
raise OperationFailureException(message)
class PackAsyncCommand(ActionRunCommandMixin, resource.ResourceCommand):
def __init__(self, *args, **kwargs):
super(PackAsyncCommand, self).__init__(*args, **kwargs)
self.parser.add_argument(
'-w',
'--width',
nargs='+',
type=int,
default=None,
help='Set the width of columns in output.',
)
detail_arg_grp = self.parser.add_mutually_exclusive_group()
detail_arg_grp.add_argument(
'--attr',
nargs='+',
default=['name', 'description', 'version', 'author'],
help=(
'List of attributes to include in the '
'output. "all" or unspecified will '
'return all attributes.'
),
)
detail_arg_grp.add_argument(
'-d',
'--detail',
action='store_true',
help='Display full detail of the execution in table format.',
)
@add_auth_token_to_kwargs_from_cli
def run_and_print(self, args, **kwargs):
instance = self.run(args, **kwargs)
if not instance:
raise Exception('Server did not create instance.')
parent_id = instance.execution_id
stream_mgr = self.app.client.managers['Stream']
execution = None
with term.TaskIndicator() as indicator:
events = ['st2.execution__create', 'st2.execution__update']
for event in stream_mgr.listen(events, **kwargs):
execution = Execution(**event)
if execution.id == parent_id and execution.status in LIVEACTION_COMPLETED_STATES:
break
# Suppress intermediate output in case output formatter is requested
if args.json or args.yaml:
continue
if getattr(execution, 'parent', None) == parent_id:
status = execution.status
name = execution.context['chain']['name']
if status == LIVEACTION_STATUS_SCHEDULED:
indicator.add_stage(status, name)
if status == LIVEACTION_STATUS_RUNNING:
indicator.update_stage(status, name)
if status in LIVEACTION_COMPLETED_STATES:
indicator.finish_stage(status, name)
if execution and execution.status == LIVEACTION_STATUS_FAILED:
args.depth = 1
self._print_execution_details(execution=execution, args=args, **kwargs)
sys.exit(1)
return self.app.client.managers['Execution'].get_by_id(parent_id, **kwargs)
class PackListCommand(resource.ResourceListCommand):
display_attributes = ['ref', 'name', 'description', 'version', 'author']
attribute_display_order = ['ref', 'name', 'description', 'version', 'author']
class PackGetCommand(resource.ResourceGetCommand):
pk_argument_name = 'ref'
display_attributes = ['name', 'version', 'author', 'email', 'keywords', 'description']
attribute_display_order = ['name', 'version', 'author', 'email', 'keywords', 'description']
help_string = 'Get information about an installed pack.'
class PackShowCommand(PackResourceCommand):
def __init__(self, resource, *args, **kwargs):
help_string = (
'Get information about an available %s from the index.'
% resource.get_display_name().lower()
)
super(PackShowCommand, self).__init__(resource, 'show', help_string, *args, **kwargs)
self.parser.add_argument(
'pack', help='Name of the %s to show.' % resource.get_display_name().lower()
)
@add_auth_token_to_kwargs_from_cli
def run(self, args, **kwargs):
return self.manager.search(args, **kwargs)
class PackInstallCommand(PackAsyncCommand):
def __init__(self, resource, *args, **kwargs):
super(PackInstallCommand, self).__init__(
resource,
'install',
'Install new %s.' % resource.get_plural_display_name().lower(),
*args,
**kwargs
)
self.parser.add_argument(
'packs',
nargs='+',
metavar='pack',
help='Name of the %s in Exchange, or a git repo URL.'
% resource.get_plural_display_name().lower(),
)
self.parser.add_argument(
'--python3',
action='store_true',
default=False,
help='Use Python 3 binary for pack virtual environment.',
)
self.parser.add_argument(
'--force', action='store_true', default=False, help='Force pack installation.'
)
def run(self, args, **kwargs):
is_structured_output = args.json or args.yaml
# If structured output is requested, do not print information about contents of pack
# This information is already exposed via st2 pack show ${pack_name} -j
if not is_structured_output:
self._get_content_counts_for_pack(args, **kwargs)
return self.manager.install(args.packs, python3=args.python3, force=args.force, **kwargs)
def _get_content_counts_for_pack(self, args, **kwargs):
# Global content list, excluding "tests"
# Note: We skip this step for local packs
pack_content = {'actions': 0, 'rules': 0, 'sensors': 0, 'aliases': 0, 'triggers': 0}
if len(args.packs) == 1:
args.pack = args.packs[0]
if args.pack.startswith('file://'):
return
pack_info = self.manager.search(args, ignore_errors=True, **kwargs)
content = getattr(pack_info, 'content', {})
if content:
for entity in content.keys():
if entity in pack_content:
pack_content[entity] += content[entity]['count']
self._print_pack_content(args.packs, pack_content)
else:
pack_content = pack_content.fromkeys(pack_content, 0)
# TODO: Better solution is to update endpoint query param for one API call
# example: ?packs=pack1,pack2,pack3
for pack in args.packs:
# args.pack required for search
args.pack = pack
if args.pack.startswith('file://'):
return
pack_info = self.manager.search(args, ignore_errors=True, **kwargs)
content = getattr(pack_info, 'content', {})
if content:
for entity in content.keys():
if entity in pack_content:
pack_content[entity] += content[entity]['count']
if content:
self._print_pack_content(args.packs, pack_content)
@staticmethod
def _print_pack_content(pack_name, pack_content):
print(
'\nFor the "%s" %s, the following content will be registered:\n'
% (', '.join(pack_name), 'pack' if len(pack_name) == 1 else 'packs')
)
for item, count in pack_content.items():
print('%-10s| %s' % (item, count))
print('\nInstallation may take a while for packs with many items.')
@add_auth_token_to_kwargs_from_cli
def run_and_print(self, args, **kwargs):
instance = super(PackInstallCommand, self).run_and_print(args, **kwargs)
# Hack to get a list of resolved references of installed packs
packs = instance.result['tasks'][1]['result']['result']
if len(packs) == 1:
pack_instance = self.app.client.managers['Pack'].get_by_ref_or_id(packs[0], **kwargs)
self.print_output(
pack_instance,
table.PropertyValueTable,
attributes=args.attr,
json=args.json,
yaml=args.yaml,
attribute_display_order=self.attribute_display_order,
)
else:
all_pack_instances = self.app.client.managers['Pack'].get_all(**kwargs)
pack_instances = []
for pack in all_pack_instances:
if pack.name in packs:
pack_instances.append(pack)
self.print_output(
pack_instances,
table.MultiColumnTable,
attributes=args.attr,
widths=args.width,
json=args.json,
yaml=args.yaml,
)
class PackRemoveCommand(PackAsyncCommand):
def __init__(self, resource, *args, **kwargs):
super(PackRemoveCommand, self).__init__(
resource,
'remove',
'Remove %s.' % resource.get_plural_display_name().lower(),
*args,
**kwargs
)
self.parser.add_argument(
'packs',
nargs='+',
metavar='pack',
help='Name of the %s to remove.' % resource.get_plural_display_name().lower(),
)
def run(self, args, **kwargs):
return self.manager.remove(args.packs, **kwargs)
@add_auth_token_to_kwargs_from_cli
def run_and_print(self, args, **kwargs):
all_pack_instances = self.app.client.managers['Pack'].get_all(**kwargs)
super(PackRemoveCommand, self).run_and_print(args, **kwargs)
packs = args.packs
if len(packs) == 1:
pack_instance = self.app.client.managers['Pack'].get_by_ref_or_id(packs[0], **kwargs)
if pack_instance:
raise OperationFailureException('Pack %s has not been removed properly' % packs[0])
removed_pack_instance = next(
(pack for pack in all_pack_instances if pack.name == packs[0]), None
)
self.print_output(
removed_pack_instance,
table.PropertyValueTable,
attributes=args.attr,
json=args.json,
yaml=args.yaml,
attribute_display_order=self.attribute_display_order,
)
else:
remaining_pack_instances = self.app.client.managers['Pack'].get_all(**kwargs)
pack_instances = []
for pack in all_pack_instances:
if pack.name in packs:
pack_instances.append(pack)
if pack in remaining_pack_instances:
raise OperationFailureException(
'Pack %s has not been removed properly' % pack.name
)
self.print_output(
pack_instances,
table.MultiColumnTable,
attributes=args.attr,
widths=args.width,
json=args.json,
yaml=args.yaml,
)
class PackRegisterCommand(PackResourceCommand):
def __init__(self, resource, *args, **kwargs):
super(PackRegisterCommand, self).__init__(
resource,
'register',
'Register %s(s): sync all file changes with DB.' % resource.get_display_name().lower(),
*args,
**kwargs
)
self.parser.add_argument(
'packs',
nargs='*',
metavar='pack',
help='Name of the %s(s) to register.' % resource.get_display_name().lower(),
)
self.parser.add_argument('--types', nargs='+', help='Types of content to register.')
@add_auth_token_to_kwargs_from_cli
def run(self, args, **kwargs):
return self.manager.register(args.packs, args.types, **kwargs)
class PackSearchCommand(resource.ResourceTableCommand):
display_attributes = ['name', 'description', 'version', 'author']
attribute_display_order = ['name', 'description', 'version', 'author']
def __init__(self, resource, *args, **kwargs):
super(PackSearchCommand, self).__init__(
resource,
'search',
'Search the index for a %s with any attribute \
matching the query.'
% resource.get_display_name().lower(),
*args,
**kwargs
)
self.parser.add_argument('query', help='Search query.')
@add_auth_token_to_kwargs_from_cli
def run(self, args, **kwargs):
return self.manager.search(args, **kwargs)
class PackConfigCommand(resource.ResourceCommand):
def __init__(self, resource, *args, **kwargs):
super(PackConfigCommand, self).__init__(
resource,
'config',
'Configure a %s based on config schema.' % resource.get_display_name().lower(),
*args,
**kwargs
)
self.parser.add_argument(
'name', help='Name of the %s(s) to configure.' % resource.get_display_name().lower()
)
@add_auth_token_to_kwargs_from_cli
def run(self, args, **kwargs):
schema = self.app.client.managers['ConfigSchema'].get_by_ref_or_id(args.name, **kwargs)
if not schema:
msg = '%s "%s" doesn\'t exist or doesn\'t have a config schema defined.'
raise resource.ResourceNotFoundError(
msg % (self.resource.get_display_name(), args.name)
)
config = interactive.InteractiveForm(schema.attributes).initiate_dialog()
message = '---\nDo you want to preview the config in an editor before saving?'
description = 'Secrets will be shown in plain text.'
preview_dialog = interactive.Question(message, {'default': 'y', 'description': description})
if preview_dialog.read() == 'y':
try:
contents = yaml.safe_dump(config, indent=4, default_flow_style=False)
modified = editor.edit(contents=contents)
config = yaml.safe_load(modified)
except editor.EditorError as e:
print(six.text_type(e))
message = '---\nDo you want me to save it?'
save_dialog = interactive.Question(message, {'default': 'y'})
if save_dialog.read() == 'n':
raise OperationFailureException('Interrupted')
config_item = Config(pack=args.name, values=config)
result = self.app.client.managers['Config'].update(config_item, **kwargs)
return result
def run_and_print(self, args, **kwargs):
try:
instance = self.run(args, **kwargs)
if not instance:
raise Exception("Configuration failed")
self.print_output(
instance,
table.PropertyValueTable,
attributes=['all'],
json=args.json,
yaml=args.yaml,
)
except (KeyboardInterrupt, SystemExit):
raise OperationFailureException('Interrupted')
except Exception as e:
if self.app.client.debug:
raise
message = six.text_type(e)
print('ERROR: %s' % (message))
raise OperationFailureException(message)