-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathdeployments.py
More file actions
2046 lines (1839 loc) · 70.4 KB
/
deployments.py
File metadata and controls
2046 lines (1839 loc) · 70.4 KB
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed 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.
############
import os
import uuid
import json
from datetime import datetime
from io import StringIO
import click
from cloudify_rest_client.constants import VISIBILITY_EXCEPT_PRIVATE
from cloudify_rest_client.exceptions import (
DeploymentPluginNotFound,
UnknownDeploymentInputError,
UnknownDeploymentSecretError,
MissingRequiredDeploymentInputError,
UnsupportedDeploymentGetSecretError,
CloudifyClientError
)
from cloudify.utils import parse_utc_datetime
from cloudify_cli.local import load_env
from cloudify_cli.table import (
print_data,
print_single,
print_details,
print_list
)
from cloudify_cli.cli import cfy, helptexts
from cloudify_cli.logger import (
get_events_logger,
get_global_json_output,
output,
get_global_extended_view
)
from cloudify_cli import env, execution_events_fetcher, filters_utils, utils
from cloudify_cli.constants import DEFAULT_BLUEPRINT_PATH, DELETE_DEP
from cloudify_cli.exceptions import (
CloudifyCliError,
SuppressedCloudifyCliError,
ExecutionTimeoutError)
from cloudify_cli.labels_utils import (
add_labels,
delete_labels,
get_output_resource_labels,
get_printable_resource_labels,
list_labels,
serialize_resource_labels)
from cloudify_cli.utils import (
prettify_client_error,
get_visibility,
validate_visibility,
get_deployment_environment_execution)
from cloudify_cli.commands.summary import (
BASE_SUMMARY_FIELDS,
structure_summary_results)
DEPLOYMENT_COLUMNS = [
'id', 'display_name', 'blueprint_id', 'created_at', 'updated_at',
'visibility', 'tenant_name', 'created_by', 'site_name', 'labels',
'deployment_status', 'installation_status'
]
DEPLOYMENT_STATUS_LIST_COLUMNS = [
'id', 'display_name', 'deployment_status', 'installation_status',
'unavailable_instances', 'drifted_instances',
]
EXTENDED_DEPLOYMENT_COLUMNS = DEPLOYMENT_COLUMNS + [
'sub_services_count', 'sub_services_status', 'sub_environments_count',
'sub_environments_status', 'unavailable_instances', 'drifted_instances',
]
DEPLOYMENT_UPDATE_COLUMNS = [
'id', 'deployment_id', 'tenant_name', 'state', 'execution_id',
'created_at', 'visibility', 'old_blueprint_id', 'new_blueprint_id'
]
DEPLOYMENT_UPDATE_PREVIEW_COLUMNS = [
'deployment_id', 'tenant_name', 'state', 'created_at', 'visibility',
'old_blueprint_id', 'new_blueprint_id'
]
DEPLOYMENT_MODIFICATION_COLUMNS = [
'id', 'workflow_id', 'execution_id', 'status', 'tenant_name',
'created_at', 'visibility',
]
NON_PREVIEW_COLUMNS = ['id', 'execution_id']
STEPS_COLUMNS = ['entity_type', 'entity_id', 'action']
DEPENDENCIES_COLUMNS = ['deployment', 'dependency_type', 'dependent_node',
'tenant']
DEP_GROUP_COLUMNS = [
'id', 'deployments', 'description', 'default_blueprint_id'
]
TENANT_HELP_MESSAGE = 'The name of the tenant of the deployment'
DEPLOYMENTS_SUMMARY_FIELDS = (['blueprint_id', 'site_name'] +
BASE_SUMMARY_FIELDS)
SCHEDULES_SUMMARY_FIELDS = (['deployment_id', 'workflow_id'] +
BASE_SUMMARY_FIELDS)
# for human-redable outputs, those fields are formatted separately. In
# machine-readable (json) output, they are just part of the output
MACHINE_READABLE_UPDATE_PREVIEW_COLUMNS = [
'old_inputs', 'new_inputs', 'steps', 'modified_entity_ids',
'installed_nodes', 'uninstalled_nodes', 'reinstalled_nodes',
'explicit_reinstall', 'recursive_dependencies', 'schedules_to_delete',
'schedules_to_create', 'labels_to_create'
]
MACHINE_READABLE_MODIFICATION_COLUMNS = [
'ended_at', 'node_instances', 'deployment_id', 'blueprint_id',
'modified_nodes', 'resource_availability',
]
SCHEDULE_TABLE_COLUMNS = ['id', 'deployment_id', 'workflow_id', 'created_at',
'next_occurrence', 'since', 'until', 'stop_on_fail',
'enabled', 'visibility', 'tenant_name', 'created_by']
@cfy.group(name='deployments')
@cfy.options.common_options
def deployments():
"""Handle deployments on the Manager"""
def _print_single_update(
deployment_update_dict,
explicit_reinstall=None,
preview=False,
skip_install=False,
skip_uninstall=False,
skip_reinstall=False,
):
if explicit_reinstall is None:
explicit_reinstall = []
if preview:
columns = DEPLOYMENT_UPDATE_PREVIEW_COLUMNS
else:
columns = DEPLOYMENT_UPDATE_COLUMNS
deployment_update_dict['explicit_reinstall'] = explicit_reinstall
deployment_update_dict['installed_nodes'] = []
deployment_update_dict['uninstalled_nodes'] = []
deployment_update_dict['reinstalled_nodes'] = []
for step in deployment_update_dict['steps']:
entity = step['entity_id']
if entity[0] != 'nodes':
continue
if step['action'] == 'add':
deployment_update_dict['installed_nodes'].append(entity[1])
elif step['action'] == 'remove':
deployment_update_dict['uninstalled_nodes'].append(entity[1])
elif step['action'] == 'modify':
deployment_update_dict['reinstalled_nodes'].append(entity[1])
raw_new_labels = deployment_update_dict.get('labels_to_create') or []
new_labels = get_output_resource_labels(raw_new_labels)
deployment_update_dict['labels_to_create'] = new_labels
if get_global_json_output():
columns += MACHINE_READABLE_UPDATE_PREVIEW_COLUMNS
print_single(columns,
deployment_update_dict,
'Deployment Update:',
max_width=50)
if not get_global_json_output():
# beautify steps entity IDs for display
for step in deployment_update_dict['steps']:
step['entity_id'] = ': '.join(step['entity_id'])
skip_msg = ' (will be skipped)'
print_details(deployment_update_dict['old_inputs'] or {},
'Old inputs:')
print_details(deployment_update_dict['new_inputs'] or {},
'New inputs:')
print_data(STEPS_COLUMNS,
deployment_update_dict['steps'] or {},
'Steps:')
print_list(
deployment_update_dict['installed_nodes'] or [],
'Installed nodes{0}:'.format(skip_msg if skip_install else '')
)
print_list(
deployment_update_dict['uninstalled_nodes'] or [],
'Uninstalled nodes{0}:'.format(skip_msg if skip_uninstall else '')
)
print_list(deployment_update_dict['reinstalled_nodes'] or [],
'Automatically detected nodes to reinstall{0}:'
.format(skip_msg if skip_reinstall else ''))
print_list(explicit_reinstall, 'Expicitly given nodes to reinstall:')
print_data(DEPENDENCIES_COLUMNS,
deployment_update_dict['recursive_dependencies'] or {},
'Affected (recursively) dependent deployments:')
output('Will delete the following schedules: {}'.format(', '.join(
deployment_update_dict.get('schedules_to_delete') or [])))
print_data(
['id', 'workflow', 'since', 'until', 'recurrence',
'count', 'weekdays'],
deployment_update_dict.get('schedules_to_create') or [],
'Then, will create the following schedules: ')
print_data(['key', 'values'],
get_printable_resource_labels(new_labels),
'The following labels will be created: ')
def deployments_list_base(
ctx,
blueprint_id,
group_id,
filter_id,
filter_rules,
sort_by,
descending,
all_tenants,
search,
search_name,
dependencies_of,
pagination_offset,
pagination_size,
logger,
client,
tenant_name,
):
"""Base function for deployment listing.
list and status-list delegate to this, so that they can have a single
implementation only differing by columns shown.
"""
utils.explicit_tenant_name_message(tenant_name, logger)
if blueprint_id:
logger.info('Listing deployments for blueprint %s...', blueprint_id)
else:
logger.info('Listing all deployments...')
deployments = client.deployments.list(sort=sort_by,
is_descending=descending,
filter_rules=filter_rules,
filter_id=filter_id,
_all_tenants=all_tenants,
_search=search,
_offset=pagination_offset,
_size=pagination_size,
_group_id=group_id,
blueprint_id=blueprint_id,
_search_name=search_name,
_dependencies_of=dependencies_of)
serialize_resource_labels(deployments)
total = deployments.metadata.pagination.total
if ctx.command.name == 'status-list':
columns = DEPLOYMENT_STATUS_LIST_COLUMNS
elif get_global_extended_view() or get_global_json_output():
columns = EXTENDED_DEPLOYMENT_COLUMNS
else:
columns = DEPLOYMENT_COLUMNS
print_data(columns, deployments, 'Deployments:')
filtered = None
if filter_rules or filter_id:
filtered = deployments.metadata.get('filtered')
if filtered:
logger.info('Showing %d of %d deployments (%d hidden by filter)',
len(deployments), total, filtered)
else:
logger.info('Showing %d of %d deployments', len(deployments), total)
# to have identical behaviour for both list and status-list, apply the same
# decorators to both. We'll have two "stub" functions representing those
# commands, and both delegate to the same base.
deployments_list_decorators = [
cfy.options.blueprint_id(
help='Show deployments created from this blueprint'),
click.option(
'--group-id', '-g',
help='Show deployments belonging to this group'),
cfy.options.filter_id,
cfy.options.deployment_filter_rules,
cfy.options.sort_by(),
cfy.options.descending,
cfy.options.tenant_name_for_list(
required=False, resource_name_for_help='deployment'),
cfy.options.all_tenants,
cfy.options.search,
cfy.options.search_name,
cfy.options.dependencies_of,
cfy.options.pagination_offset,
cfy.options.pagination_size,
cfy.options.common_options,
cfy.assert_manager_active(),
cfy.pass_client(),
cfy.pass_logger,
cfy.pass_context,
cfy.options.extended_view,
]
def manager_list(*args, **kwargs):
"""List deployments
If `--blueprint-id` is provided, list deployments for that blueprint.
Otherwise, list deployments for all blueprints.
"""
return deployments_list_base(*args, **kwargs)
def manager_status_list(*args, **kwargs):
"""Show deployment statuses
Show a grid of various deployment statuses, allowing an at-a-glance
insight of the state of the system.
This command allows the same filtering that `cfy deployments list` does.
"""
return deployments_list_base(*args, **kwargs)
for deco in deployments_list_decorators + [
deployments.command(
name='list', short_help='List deployments [manager only]'
)
]:
manager_list = deco(manager_list)
for deco in deployments_list_decorators + [
deployments.command(
name='status-list', short_help='Show deployment status [manager only]'
)
]:
manager_status_list = deco(manager_status_list)
@deployments.command(name='history',
short_help='List deployment updates [manager only]')
@cfy.options.deployment_id()
@cfy.options.sort_by()
@cfy.options.descending
@cfy.options.tenant_name_for_list(
required=False, resource_name_for_help='deployment update')
@cfy.options.all_tenants
@cfy.options.search
@cfy.options.pagination_offset
@cfy.options.pagination_size
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
@cfy.options.extended_view
def manager_history(
deployment_id,
sort_by,
descending,
all_tenants,
search,
pagination_offset,
pagination_size,
logger,
client,
tenant_name,
):
"""Show deployment history by listing deployment updates
If `--deployment-id` is provided, list deployment updates for that
deployment. Otherwise, list deployment updates for all deployments.
"""
utils.explicit_tenant_name_message(tenant_name, logger)
if deployment_id:
logger.info('Listing deployment updates for deployment %s...',
deployment_id)
else:
logger.info('Listing all deployment updates...')
deployment_updates = client.deployment_updates.list(
sort=sort_by,
is_descending=descending,
_all_tenants=all_tenants,
_search=search,
_offset=pagination_offset,
_size=pagination_size,
deployment_id=deployment_id
)
total = deployment_updates.metadata.pagination.total
print_data(
DEPLOYMENT_UPDATE_COLUMNS, deployment_updates, 'Deployment updates:')
logger.info('Showing %d of %s deployment updates',
len(deployment_updates), total)
@deployments.command(
name='get-update',
short_help='Retrieve deployment update information [manager only]'
)
@cfy.argument('deployment-update-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False,
resource_name_for_help='deployment update')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_get_update(deployment_update_id, logger, client, tenant_name):
"""Retrieve information for a specific deployment update
`DEPLOYMENT_UPDATE_ID` is the id of the deployment update to get
information on.
"""
utils.explicit_tenant_name_message(tenant_name, logger)
logger.info('Retrieving deployment update %s...', deployment_update_id)
deployment_update_dict = client.deployment_updates.get(
deployment_update_id)
_print_single_update(deployment_update_dict)
@deployments.command(
name='update', short_help='Update a deployment [manager only]')
@cfy.argument('deployment-id')
@cfy.options.blueprint_path(extra_message=' [UNSUPPORTED]')
@cfy.options.blueprint_filename(' [UNSUPPORTED]')
@cfy.options.blueprint_id()
@cfy.options.inputs
@cfy.options.reinstall_list
@cfy.options.workflow_id()
@cfy.options.skip_install
@cfy.options.skip_uninstall
@cfy.options.skip_reinstall
@cfy.options.skip_drift_check
@cfy.options.skip_heal
@cfy.options.force_reinstall
@cfy.options.ignore_failure
@cfy.options.install_first
@cfy.options.preview
@cfy.options.dont_update_plugins
@cfy.options.force(help=helptexts.FORCE_UPDATE)
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.options.visibility(mutually_exclusive_required=False)
@cfy.options.validate
@cfy.options.include_logs
@cfy.options.drift_only
@cfy.options.json_output
@cfy.options.common_options
@cfy.options.runtime_only_evaluation
@cfy.options.auto_correct_types
@cfy.options.reevaluate_active_statuses()
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
@cfy.pass_context
def manager_update(
ctx,
deployment_id,
blueprint_path,
inputs,
reinstall_list,
blueprint_filename,
skip_install,
skip_uninstall,
skip_reinstall,
skip_drift_check,
skip_heal,
force_reinstall,
ignore_failure,
install_first,
preview,
dont_update_plugins,
workflow_id,
force,
include_logs,
json_output,
logger,
client,
tenant_name,
blueprint_id,
drift_only,
visibility,
validate,
runtime_only_evaluation,
auto_correct_types,
reevaluate_active_statuses,
):
"""Update a specified deployment according to the specified blueprint.
The blueprint can be supplied as an id of a blueprint that already exists
in the system (recommended).
The other way (not recommended) is to supply a blueprint to upload and
use it to update the deployment [DEPRECATED]
Note: using the deprecated way will upload the blueprint and then use it
to update the deployment. So doing it twice with the same blueprint may
fail because the blueprint id in the system will already exist. In this
case it is better to use the first and recommended way, and simply pass
the blueprint id.
`DEPLOYMENT_ID` is the deployment's id to update.
"""
if blueprint_path:
raise CloudifyCliError(
'Passing a path to blueprint for deployment update is no longer '
'supported. Use -b, --blueprint-id option instead to pass an ID '
'of a blueprint that is already in the system, e.g. '
'`cfy deployments update -b UPDATED_BLUEPRINT_ID DEPLOYMENT_ID`.')
if not any([blueprint_id, blueprint_path, inputs, drift_only]):
raise CloudifyCliError(
'Must supply either a blueprint (by id of an existing blueprint, '
'or a path to a new blueprint), or new inputs')
if (not blueprint_path or not utils.is_archive(blueprint_path)) \
and blueprint_filename not in (DEFAULT_BLUEPRINT_PATH,
blueprint_path):
raise CloudifyCliError(
'--blueprint-filename param should be passed only when updating '
'from an archive, so --blueprint-path must be passed as a path to '
'a blueprint archive'
)
if tenant_name:
logger.info('Explicitly using tenant `%s`', tenant_name)
msg = 'Updating deployment {0}'.format(deployment_id)
if inputs:
msg += ' with new inputs'
if blueprint_id:
msg += ', using blueprint {0}'.format(blueprint_id)
logger.info(msg)
reinstall_list = reinstall_list or []
deployment_update = \
client.deployment_updates.update_with_existing_blueprint(
deployment_id,
blueprint_id,
inputs,
skip_install,
skip_uninstall,
skip_reinstall,
skip_drift_check,
skip_heal,
force_reinstall,
workflow_id,
force,
ignore_failure,
install_first,
reinstall_list,
preview,
not dont_update_plugins,
runtime_only_evaluation=runtime_only_evaluation,
auto_correct_types=auto_correct_types,
reevaluate_active_statuses=reevaluate_active_statuses,
)
if preview:
_print_single_update(
deployment_update,
explicit_reinstall=reinstall_list,
preview=True,
skip_install=skip_install,
skip_uninstall=skip_uninstall,
skip_reinstall=skip_reinstall,
)
return
events_logger = get_events_logger(json_output)
execution = execution_events_fetcher.wait_for_execution(
client,
client.executions.get(deployment_update.execution_id),
events_handler=events_logger,
include_logs=include_logs,
timeout=None # don't timeout ever
)
if execution.error:
logger.info(
"Execution of workflow '%s' for deployment '%s' failed [error=%s]",
execution.workflow_id,
execution.deployment_id,
execution.error,
)
logger.info(
'Failed updating deployment %s. Deployment update id: %s. '
'Execution id: %s',
deployment_id,
deployment_update.id,
execution.id,
)
raise SuppressedCloudifyCliError()
else:
logger.info(
"Finished executing workflow '%s' on deployment '%s'",
execution.workflow_id,
execution.deployment_id,
)
logger.info(
'Successfully updated deployment %s. '
'Deployment update id: %s. Execution id: %s',
deployment_id,
deployment_update.id,
execution.id,
)
@deployments.command(name='create',
short_help='Create a deployment [manager only]')
@cfy.argument('deployment-id', required=False, callback=cfy.validate_name)
@cfy.options.blueprint_id(required=True)
@cfy.options.inputs
@cfy.options.private_resource
@cfy.options.visibility()
@cfy.options.site_name
@cfy.options.labels
@cfy.options.generate_id
@cfy.options.display_name
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.options.runtime_only_evaluation
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
@cfy.options.skip_plugins_validation
def manager_create(
blueprint_id,
deployment_id,
inputs,
private_resource,
visibility,
site_name,
labels,
generate_id,
display_name,
logger,
client,
tenant_name,
skip_plugins_validation,
runtime_only_evaluation,
):
"""Create a deployment on the manager.
`DEPLOYMENT_ID` is the id of the deployment you'd like to create.
"""
utils.explicit_tenant_name_message(tenant_name, logger)
logger.info('Creating new deployment from blueprint %s...', blueprint_id)
visibility = get_visibility(private_resource, visibility, logger)
if deployment_id:
if generate_id:
raise CloudifyCliError('`--generate-id` cannot be provided if a '
'deployment ID is specified')
else:
if generate_id:
deployment_id = str(uuid.uuid4())
else:
deployment_id = blueprint_id
display_name = display_name or deployment_id
try:
deployment = client.deployments.create(
blueprint_id,
deployment_id,
inputs=inputs,
visibility=visibility,
skip_plugins_validation=skip_plugins_validation,
site_name=site_name,
runtime_only_evaluation=runtime_only_evaluation,
labels=labels,
display_name=display_name
)
except (MissingRequiredDeploymentInputError,
UnknownDeploymentInputError) as e:
logger.error('Unable to create deployment: %s', e)
raise SuppressedCloudifyCliError(str(e))
except DeploymentPluginNotFound as e:
logger.info(
"Unable to create deployment. Not all "
"deployment plugins are installed on the Manager."
)
logger.info(
"* Use 'cfy plugins upload' to upload the missing plugins"
" to the Manager, or use 'cfy deployments create' with "
"the '--skip-plugins-validation' flag to skip this validation."
)
raise CloudifyCliError(str(e))
except (UnknownDeploymentSecretError,
UnsupportedDeploymentGetSecretError) as e:
logger.info('Unable to create deployment due to invalid secret')
raise CloudifyCliError(str(e))
logger.info("Deployment `%s` created. The deployment's id is %s",
deployment.display_name, deployment.id)
@deployments.command(name='delete',
short_help='Delete a deployment [manager only]')
@cfy.argument('deployment-id')
@cfy.options.force(help=helptexts.FORCE_DELETE_DEPLOYMENT)
@cfy.options.common_options
@cfy.options.with_logs
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_delete(deployment_id, force, with_logs, logger, client,
tenant_name):
"""Delete a deployment from the manager
`DEPLOYMENT_ID` is the id of the deployment to delete.
"""
utils.explicit_tenant_name_message(tenant_name, logger)
logger.info('Trying to delete deployment %s...', deployment_id)
client.deployments.delete(deployment_id, force, with_logs=with_logs)
try:
execution = get_deployment_environment_execution(
client, deployment_id, DELETE_DEP)
if execution:
execution_events_fetcher.wait_for_execution(
client, execution, logger=logger)
except ExecutionTimeoutError:
raise CloudifyCliError(
'Timed out waiting for deployment `{0}` to be deleted. Please '
'execute `cfy deployments list` to check whether the '
'deployment has been deleted.'.format(deployment_id))
except CloudifyClientError as e:
# ignore 404 errors for the execution or deployment - it was already
# deleted before we were able to follow it
if 'not found' not in str(e):
raise
except RuntimeError as e:
# ignore the failure to get the execution - it was already deleted
# before we were able to follow it
if 'Failed to get' not in str(e):
raise
logger.info("Deployment deleted")
@deployments.command(name='outputs',
short_help='Show deployment outputs [manager only]')
@cfy.argument('deployment-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_outputs(deployment_id, logger, client, tenant_name):
"""Retrieve outputs for a specific deployment
`DEPLOYMENT_ID` is the id of the deployment to print outputs for.
"""
_present_outputs_or_capabilities(
'outputs',
deployment_id,
tenant_name,
logger,
client
)
@deployments.command(name='capabilities',
short_help='Show deployment capabilities [manager only]')
@cfy.argument('deployment-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_capabilities(deployment_id, logger, client, tenant_name):
"""Retrieve capabilities for a specific deployment
`DEPLOYMENT_ID` is the id of the deployment to print capabilities for.
"""
_present_outputs_or_capabilities(
'capabilities',
deployment_id,
tenant_name,
logger,
client
)
def _present_outputs_or_capabilities(
resource, deployment_id, tenant_name, logger, client
):
# resource is either "outputs" or "capabilities"
utils.explicit_tenant_name_message(tenant_name, logger)
logger.info('Retrieving %s for deployment %s...', resource, deployment_id)
dep = client.deployments.get(deployment_id, _include=[resource])
definitions = getattr(dep, resource)
client_api = getattr(client.deployments, resource)
response = client_api.get(deployment_id)
values_dict = getattr(response, resource)
if get_global_json_output():
values = {out: {
'value': val,
'description': definitions[out].get('description')
} for out, val in values_dict.items()}
print_details(values, 'Deployment {0}:'.format(resource))
else:
values = StringIO()
for elem_name, elem in values_dict.items():
values.write(' - "{0}":{1}'.format(elem_name, os.linesep))
description = definitions[elem_name].get('description', '')
values.write(' Description: {0}{1}'.format(description,
os.linesep))
values.write(
' Value: {0}{1}'.format(elem, os.linesep))
logger.info(values.getvalue())
@deployments.command(name='inputs',
short_help='Show deployment inputs [manager only]')
@cfy.argument('deployment-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_inputs(deployment_id, logger, client, tenant_name):
"""Retrieve inputs for a specific deployment
`DEPLOYMENT_ID` is the id of the deployment to print inputs for.
"""
utils.explicit_tenant_name_message(tenant_name, logger)
logger.info('Retrieving inputs for deployment %s...', deployment_id)
dep = client.deployments.get(deployment_id, _include=['inputs'])
if get_global_json_output():
print_details(dep.inputs, 'Deployment inputs:')
else:
inputs_ = StringIO()
for input_name, input in dep.inputs.items():
inputs_.write(' - "{0}":{1}'.format(input_name, os.linesep))
inputs_.write(' Value: {0}{1}'.format(input, os.linesep))
logger.info(inputs_.getvalue())
@deployments.command(
name='set-visibility',
short_help="Set the deployment's visibility [manager only]"
)
@cfy.argument('deployment-id')
@cfy.options.visibility(required=True, valid_values=VISIBILITY_EXCEPT_PRIVATE)
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client(use_tenant_in_header=True)
@cfy.pass_logger
def manager_set_visibility(deployment_id, visibility, logger, client):
"""Set the deployment's visibility to tenant
`DEPLOYMENT_ID` is the id of the deployment to update
"""
validate_visibility(visibility, valid_values=VISIBILITY_EXCEPT_PRIVATE)
status_codes = [400, 403, 404]
with prettify_client_error(status_codes, logger):
client.deployments.set_visibility(deployment_id, visibility)
logger.info('Deployment `%s` was set to %s', deployment_id, visibility)
@deployments.command(name='summary',
short_help='Retrieve summary of deployment details '
'[manager only]',
help=helptexts.SUMMARY_HELP.format(
type='deployments',
example='deployment with the same blueprint ID',
fields='|'.join(DEPLOYMENTS_SUMMARY_FIELDS)))
@cfy.argument('target_field', type=cfy.SummaryArgs(DEPLOYMENTS_SUMMARY_FIELDS))
@cfy.argument('sub_field', type=cfy.SummaryArgs(DEPLOYMENTS_SUMMARY_FIELDS),
default=None, required=False)
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='summary')
@cfy.options.group_id_filter
@cfy.options.all_tenants
@cfy.pass_logger
@cfy.pass_client()
def summary(target_field, sub_field, group_id, logger, client, tenant_name,
all_tenants):
utils.explicit_tenant_name_message(tenant_name, logger)
logger.info('Retrieving summary of deployments on field %s', target_field)
summary = client.summary.deployments.get(
_target_field=target_field,
_sub_field=sub_field,
_all_tenants=all_tenants,
deployment_group_id=group_id,
)
columns, items = structure_summary_results(
summary.items,
target_field,
sub_field,
'deployments',
)
print_data(
columns,
items,
'Deployment summary by {field}'.format(field=target_field),
)
@deployments.command(name='set-site',
short_help="Set the deployment's site [manager only]")
@cfy.argument('deployment-id')
@cfy.options.site_name
@cfy.options.detach_site
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client(use_tenant_in_header=True)
@cfy.pass_logger
def manager_set_site(deployment_id, site_name, detach_site, client, logger):
"""Set the deployment's site
`DEPLOYMENT_ID` is the id of the deployment to update
"""
if not (site_name or detach_site):
raise CloudifyCliError(
'Must provide either a `--site-name` of a valid site or '
'`--detach-site` (for detaching the current site of '
'the given deployment)'
)
client.deployments.set_site(deployment_id,
site_name=site_name,
detach_site=detach_site)
if detach_site:
logger.info('The site of `%s` was detached', deployment_id)
else:
logger.info('The site of `%s` was set to %s', deployment_id, site_name)
@deployments.command(name='set-owner',
short_help="Change deployment's ownership")
@cfy.argument('deployment-id')
@cfy.options.new_username()
@cfy.options.tenant_name(required=False, resource_name_for_help='secret')
@cfy.assert_manager_active()
@cfy.pass_client(use_tenant_in_header=True)
@cfy.pass_logger
def set_owner(deployment_id, username, tenant_name, logger, client):
"""Set a new owner for the deployment."""
utils.explicit_tenant_name_message(tenant_name, logger)
dep = client.deployments.set_attributes(deployment_id, creator=username)
logger.info('Deployment `%s` is now owned by user `%s`.',
deployment_id, dep.get('created_by'))
@deployments.group(name='labels',
short_help="Handle a deployment's labels")
@cfy.options.common_options
def labels():
if not env.is_initialized():
env.raise_uninitialized()
@labels.command(name='list',
short_help="List the labels of a specific deployment")
@cfy.argument('deployment-id')
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def list_deployment_labels(deployment_id,
logger,
client,
tenant_name):
list_labels(deployment_id, 'deployment', client.deployments,
logger, tenant_name)
@labels.command(name='add',
short_help="Add labels to a specific deployment")
@cfy.argument('labels-list',
callback=cfy.parse_and_validate_labels)
@cfy.argument('deployment-id')
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def add_deployment_labels(labels_list,
deployment_id,
logger,
client,
tenant_name):
"""
LABELS_LIST: <key>:<value>,<key>:<value>.
Any comma and colon in <value> must be escaped with '\\'.
"""
add_labels(deployment_id, 'deployment', client.deployments, labels_list,
logger, tenant_name)
@labels.command(name='delete',
short_help="Delete labels from a specific deployment")