-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1463 lines (1225 loc) · 65.4 KB
/
__init__.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
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) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=too-many-lines
import argparse
import datetime
import json
import logging as logs
import os
import re
import sys
import time
import copy
from importlib import import_module
# pylint: disable=unused-import
from azure.cli.core.commands.constants import (
BLOCKED_MODS, DEFAULT_QUERY_TIME_RANGE, CLI_COMMON_KWARGS, CLI_COMMAND_KWARGS, CLI_PARAM_KWARGS,
CLI_POSITIONAL_PARAM_KWARGS, CONFIRM_PARAM_NAME)
from azure.cli.core.commands.parameters import (
AzArgumentContext, patch_arg_make_required, patch_arg_make_optional)
from azure.cli.core.extension import get_extension
from azure.cli.core.util import (
get_command_type_kwarg, read_file_content, get_arg_list, poller_classes)
from azure.cli.core.local_context import LocalContextAction
from azure.cli.core import telemetry
from azure.cli.core.commands.progress import IndeterminateProgressBar
from knack.arguments import CLICommandArgument
from knack.commands import CLICommand, CommandGroup, PREVIEW_EXPERIMENTAL_CONFLICT_ERROR
from knack.deprecation import ImplicitDeprecated, resolve_deprecate_info
from knack.invocation import CommandInvoker
from knack.preview import ImplicitPreviewItem, PreviewItem, resolve_preview_info
from knack.experimental import ImplicitExperimentalItem, ExperimentalItem, resolve_experimental_info
from knack.log import get_logger, CLILogging
from knack.util import CLIError, CommandResultItem, todict
from knack.events import EVENT_INVOKER_TRANSFORM_RESULT
from knack.validators import DefaultStr
try:
t_JSONDecodeError = json.JSONDecodeError
except AttributeError: # in Python 2.7
t_JSONDecodeError = ValueError
logger = get_logger(__name__)
DEFAULT_CACHE_TTL = '10'
def _explode_list_args(args):
'''Iterate through each attribute member of args and create a copy with
the IterateValues 'flattened' to only contain a single value
Ex.
{ a1:'x', a2:IterateValue(['y', 'z']) } => [{ a1:'x', a2:'y'),{ a1:'x', a2:'z'}]
'''
from azure.cli.core.commands.validators import IterateValue
list_args = {argname: argvalue for argname, argvalue in vars(args).items()
if isinstance(argvalue, IterateValue)}
if not list_args:
yield args
else:
values = list(zip(*list_args.values()))
for key in list_args:
delattr(args, key)
for value in values:
new_ns = argparse.Namespace(**vars(args))
for key_index, key in enumerate(list_args.keys()):
setattr(new_ns, key, value[key_index])
yield new_ns
def _expand_file_prefixed_files(args):
def _load_file(path):
if path == '-':
content = sys.stdin.read()
else:
content = read_file_content(os.path.expanduser(path), allow_binary=True)
return content.rstrip(os.linesep)
def _maybe_load_file(arg):
ix = arg.find('@')
if ix == -1: # no @ found
return arg
poss_file = arg[ix + 1:]
if not poss_file: # if nothing after @ then it can't be a file
return arg
if ix == 0:
try:
return _load_file(poss_file)
except IOError:
logger.debug("Failed to load '%s', assume not a file", arg)
return arg
# if @ not at the start it can't be a file
return arg
def _expand_file_prefix(arg):
arg_split = arg.split('=', 1)
try:
return '='.join([arg_split[0], _maybe_load_file(arg_split[1])])
except IndexError:
return _maybe_load_file(arg_split[0])
return [_expand_file_prefix(arg) for arg in args]
def _pre_command_table_create(cli_ctx, args):
cli_ctx.refresh_request_id()
return _expand_file_prefixed_files(args)
# pylint: disable=too-many-instance-attributes
class CacheObject:
def path(self, args, kwargs):
from azure.cli.core._environment import get_config_dir
from azure.cli.core.commands.client_factory import get_subscription_id
cli_ctx = self._cmd.cli_ctx
subscription_id = get_subscription_id(cli_ctx)
if not subscription_id:
raise CLIError('subscription ID unexpectedly empty')
if not cli_ctx.cloud.name:
raise CLIError('cloud name unexpectedly empty')
copy_kwargs = kwargs.copy()
copy_kwargs.pop('self', None)
# handle "content_type" introduced by https://gist.github.com/iscai-msft/47fe6ecbdd06013bb19a2e16f85a0b43
# e.g., 2018-03-01-hybrid when execute "az network vnet update"
# https://github.com/Azure/azure-sdk-for-python/pull/24162
# sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_10_01/operations/_operations.py:22897
copy_kwargs.pop('content_type', None)
resource_group = copy_kwargs.pop('resource_group_name', None) or args[0]
if len(args) > 2:
raise CLIError('expected 2 args, got {}: {}'.format(len(args), args))
if len(copy_kwargs) > 1:
raise CLIError('expected 1 kwarg, got {}: {}'.format(len(copy_kwargs), copy_kwargs))
try:
resource_name = args[-1]
except IndexError:
resource_name = list(copy_kwargs.values())[0]
self._resource_group = resource_group
self._resource_name = resource_name
directory = os.path.join(
get_config_dir(),
'object_cache',
cli_ctx.cloud.name,
subscription_id,
self._resource_group,
self._model_name
)
filename = '{}.json'.format(resource_name)
return directory, filename
def _resolve_model(self):
if self._model_name and self._model_path:
return
import inspect
op_metadata = inspect.getmembers(self._operation)
doc_string = ''
for key, value in op_metadata:
if key == '__doc__':
doc_string = value or ''
break
doc_string = doc_string.replace('\r', '').replace('\n', ' ')
doc_string = re.sub(' +', ' ', doc_string)
# pylint: disable=line-too-long
# In track1, the doc_string for return type is like ':return: An instance of LROPoller that returns ConnectionSharedKey or ClientRawResponse<ConnectionSharedKey>'
# In track2, the doc_string for return type is like ':return: An instance of LROPoller that returns either ConnectionSharedKey or the result of cls(response)'
# Add '(?:either )?' to match 'either' zero or one times to support track2.
model_name_regex = re.compile(r':return: (?:.*?that returns (?:either )?)?(?P<model>[a-zA-Z]*)')
model_path_regex = re.compile(r':rtype:.*(?P<path>azure.mgmt[a-zA-Z0-9_\.]*)')
try:
self._model_name = model_name_regex.search(doc_string).group('model')
if not self._model_path:
self._model_path = model_path_regex.search(doc_string).group('path').rsplit('.', 1)[0]
except AttributeError:
return
def _dump_to_file(self, open_file):
cache_obj_dump = json.dumps({
'last_saved': self.last_saved,
'_payload': self._payload
})
open_file.write(cache_obj_dump)
def load(self, args, kwargs):
directory, filename = self.path(args, kwargs)
with open(os.path.join(directory, filename), 'r') as f:
logger.info(
"Loading %s '%s' from cache: %s", self._model_name, self._resource_name,
os.path.join(directory, filename)
)
obj_data = json.loads(f.read())
self._payload = obj_data['_payload']
self.last_saved = obj_data['last_saved']
self._payload = self.result()
def save(self, args, kwargs):
from knack.util import ensure_dir
directory, filename = self.path(args, kwargs)
ensure_dir(directory)
with open(os.path.join(directory, filename), 'w') as f:
logger.info(
"Caching %s '%s' as: %s", self._model_name, self._resource_name,
os.path.join(directory, filename)
)
self.last_saved = str(datetime.datetime.now())
self._dump_to_file(f)
def result(self):
module = import_module(self._model_path)
model_cls = getattr(module, self._model_name)
# model_cls = self._cmd.get_models(self._model_type)
# todo: Remove temp work around!!!
if model_cls is None:
from azure.mgmt.imagebuilder.models import ImageTemplate
model_cls = ImageTemplate
return model_cls.deserialize(self._payload)
def prop_dict(self):
return {
'model': self._model_name,
'name': self._resource_name,
'group': self._resource_group
}
def __init__(self, cmd, payload, operation, model_path=None):
self._cmd = cmd
self._operation = operation
self._resource_group = None
self._resource_name = None
self._model_name = None
self._model_path = model_path
self._payload = payload
self.last_saved = None
self._resolve_model()
def __getattribute__(self, key):
try:
payload = object.__getattribute__(self, '_payload')
return payload.__getattribute__(key)
except AttributeError:
return super(CacheObject, self).__getattribute__(key)
def __setattr__(self, key, value):
try:
return self._payload.__setattr__(key, value)
except AttributeError:
return super(CacheObject, self).__setattr__(key, value)
class AzCliCommand(CLICommand):
def __init__(self, loader, name, handler, description=None, table_transformer=None,
arguments_loader=None, description_loader=None,
formatter_class=None, deprecate_info=None, validator=None, **kwargs):
super(AzCliCommand, self).__init__(loader.cli_ctx, name, handler, description=description,
table_transformer=table_transformer, arguments_loader=arguments_loader,
description_loader=description_loader, formatter_class=formatter_class,
deprecate_info=deprecate_info, validator=validator, **kwargs)
self.loader = loader
self.command_source = None
self.no_wait_param = kwargs.get('no_wait_param', None)
self.supports_no_wait = kwargs.get('supports_no_wait', False)
self.exception_handler = kwargs.get('exception_handler', None)
self.confirmation = kwargs.get('confirmation', False)
self.command_kwargs = kwargs
# pylint: disable=no-self-use
def _add_vscode_extension_metadata(self, arg, overrides):
""" Adds metadata for use by the VSCode CLI extension. Do
not remove or modify without contacting the VSCode team. """
if not hasattr(arg.type, 'required_tooling'):
required = arg.type.settings.get('required', False)
setattr(arg.type, 'required_tooling', required)
if 'configured_default' in overrides.settings:
def_config = overrides.settings.get('configured_default', None)
setattr(arg.type, 'default_name_tooling', def_config)
def _resolve_default_value_from_config_file(self, arg, overrides):
self._add_vscode_extension_metadata(arg, overrides)
# same blunt mechanism like we handled id-parts, for create command, no name default
if not (self.name.split()[-1] == 'create' and overrides.settings.get('metavar', None) == 'NAME'):
super(AzCliCommand, self)._resolve_default_value_from_config_file(arg, overrides)
self._resolve_default_value_from_local_context(arg, overrides)
def _resolve_default_value_from_local_context(self, arg, overrides):
if self.cli_ctx.local_context.is_on:
lca = overrides.settings.get('local_context_attribute', None)
if not lca or not lca.actions or LocalContextAction.GET not in lca.actions:
return
if lca.name:
local_context = self.cli_ctx.local_context
value = local_context.get(self.name, lca.name)
if value:
logger.debug("parameter persistence '%s' for arg %s", value, arg.name)
overrides.settings['default'] = DefaultStr(value)
overrides.settings['required'] = False
overrides.settings['default_value_source'] = 'Local Context'
def load_arguments(self):
super(AzCliCommand, self).load_arguments()
if self.arguments_loader:
cmd_args = self.arguments_loader()
if self.supports_no_wait or self.no_wait_param:
if self.supports_no_wait:
no_wait_param_dest = 'no_wait'
elif self.no_wait_param:
no_wait_param_dest = self.no_wait_param
cmd_args.append(
(no_wait_param_dest,
CLICommandArgument(no_wait_param_dest, options_list=['--no-wait'], action='store_true',
help='Do not wait for the long-running operation to finish.')))
self.arguments.update(cmd_args)
def __call__(self, *args, **kwargs):
return self.handler(*args, **kwargs)
def _merge_kwargs(self, kwargs, base_kwargs=None):
base = base_kwargs if base_kwargs is not None else getattr(self, 'command_kwargs')
return _merge_kwargs(kwargs, base)
def get_api_version(self, resource_type=None, operation_group=None):
resource_type = resource_type or self.command_kwargs.get('resource_type', None)
return self.loader.get_api_version(resource_type=resource_type, operation_group=operation_group)
def supported_api_version(self, resource_type=None, min_api=None, max_api=None,
operation_group=None, parameter_name=None):
if min_api and parameter_name:
parameter_name = None
if parameter_name is not None and parameter_name in self.arguments:
min_api = self.arguments[parameter_name].type.settings.get('min_api', None)
resource_type = resource_type or self.command_kwargs.get('resource_type', None)
return self.loader.supported_api_version(resource_type=resource_type, min_api=min_api, max_api=max_api,
operation_group=operation_group)
def get_models(self, *attr_args, **kwargs):
resource_type = kwargs.get('resource_type', self.command_kwargs.get('resource_type', None))
operation_group = kwargs.get('operation_group', self.command_kwargs.get('operation_group', None))
return self.loader.get_sdk(*attr_args, resource_type=resource_type, mod='models',
operation_group=operation_group)
def update_context(self, obj_inst):
class UpdateContext:
def __init__(self, instance):
self.instance = instance
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def set_param(self, prop, value, allow_clear=True, curr_obj=None):
curr_obj = curr_obj or self.instance
if '.' in prop:
prop, path = prop.split('.', 1)
curr_obj = getattr(curr_obj, prop)
self.set_param(path, value, allow_clear=allow_clear, curr_obj=curr_obj)
elif value == '' and allow_clear:
setattr(curr_obj, prop, None)
elif value is not None:
setattr(curr_obj, prop, value)
return UpdateContext(obj_inst)
def _is_stale(cli_ctx, cache_obj):
cache_ttl = None
try:
cache_ttl = cli_ctx.config.get('core', 'cache_ttl')
except Exception as ex: # pylint: disable=broad-except
# TODO: No idea why Python2's except clause fails to catch NoOptionError, but this
# is a temp workaround
cls_str = str(ex.__class__)
if 'NoOptionError' in cls_str or 'NoSectionError' in cls_str:
# ensure a default value exists even if not previously set
cli_ctx.config.set_value('core', 'cache_ttl', DEFAULT_CACHE_TTL)
cache_ttl = DEFAULT_CACHE_TTL
else:
raise ex
time_now = datetime.datetime.now()
time_cache = datetime.datetime.strptime(cache_obj.last_saved, '%Y-%m-%d %H:%M:%S.%f')
return time_now - time_cache > datetime.timedelta(minutes=int(cache_ttl))
def cached_get(cmd_obj, operation, *args, **kwargs):
def _get_operation():
result = None
if args:
result = operation(*args)
elif kwargs is not None:
result = operation(**kwargs)
return result
# early out if the command does not use the cache
if not cmd_obj.command_kwargs.get('supports_local_cache', False):
return _get_operation()
# allow overriding model path, e.g. for extensions
model_path = cmd_obj.command_kwargs.get('model_path', None)
cache_obj = CacheObject(cmd_obj, None, operation, model_path=model_path)
try:
cache_obj.load(args, kwargs)
if _is_stale(cmd_obj.cli_ctx, cache_obj):
message = "{model} '{name}' stale in cache. Retrieving from Azure...".format(**cache_obj.prop_dict())
logger.warning(message)
return _get_operation()
return cache_obj
except Exception: # pylint: disable=broad-except
message = "{model} '{name}' not found in cache. Retrieving from Azure...".format(**cache_obj.prop_dict())
logger.debug(message)
return _get_operation()
def cached_put(cmd_obj, operation, parameters, *args, setter_arg_name='parameters', **kwargs):
"""
setter_arg_name: The name of the argument in the setter which corresponds to the object being updated.
In track2, unknown kwargs will raise, so we should not pass 'parameters" for operation when the name of the argument
in the setter which corresponds to the object being updated is not 'parameters'.
"""
def _put_operation():
result = None
if args:
extended_args = args + (parameters,)
result = operation(*extended_args)
elif kwargs is not None:
kwargs[setter_arg_name] = parameters
result = operation(**kwargs)
del kwargs[setter_arg_name]
return result
# early out if the command does not use the cache
if not cmd_obj.command_kwargs.get('supports_local_cache', False):
return _put_operation()
use_cache = cmd_obj.cli_ctx.data.get('_cache', False)
if not use_cache:
result = _put_operation()
# allow overriding model path, e.g. for extensions
model_path = cmd_obj.command_kwargs.get('model_path', None)
cache_obj = CacheObject(cmd_obj, parameters.serialize(), operation, model_path=model_path)
if use_cache:
cache_obj.save(args, kwargs)
return cache_obj
# for a successful PUT, attempt to delete the cache file
obj_dir, obj_file = cache_obj.path(args, kwargs)
obj_path = os.path.join(obj_dir, obj_file)
try:
os.remove(obj_path)
except (OSError, IOError): # FileNotFoundError introduced in Python 3
pass
return result
def upsert_to_collection(parent, collection_name, obj_to_add, key_name, warn=True):
if not getattr(parent, collection_name, None):
setattr(parent, collection_name, [])
collection = getattr(parent, collection_name, None)
value = getattr(obj_to_add, key_name)
if value is None:
raise CLIError(
"Unable to resolve a value for key '{}' with which to match.".format(key_name))
match = next((x for x in collection if getattr(x, key_name, None) == value), None)
if match:
if warn:
logger.warning("Item '%s' already exists. Replacing with new values.", value)
collection.remove(match)
collection.append(obj_to_add)
def get_property(items, name):
result = next((x for x in items if x.name.lower() == name.lower()), None)
if not result:
raise CLIError("Property '{}' does not exist".format(name))
return result
# pylint: disable=too-few-public-methods
class AzCliCommandInvoker(CommandInvoker):
# pylint: disable=too-many-statements,too-many-locals,too-many-branches
def execute(self, args):
from knack.events import (EVENT_INVOKER_PRE_CMD_TBL_CREATE, EVENT_INVOKER_POST_CMD_TBL_CREATE,
EVENT_INVOKER_CMD_TBL_LOADED, EVENT_INVOKER_PRE_PARSE_ARGS,
EVENT_INVOKER_POST_PARSE_ARGS,
EVENT_INVOKER_FILTER_RESULT)
from azure.cli.core.commands.events import (
EVENT_INVOKER_PRE_CMD_TBL_TRUNCATE, EVENT_INVOKER_PRE_LOAD_ARGUMENTS, EVENT_INVOKER_POST_LOAD_ARGUMENTS)
# TODO: Can't simply be invoked as an event because args are transformed
args = _pre_command_table_create(self.cli_ctx, args)
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_CMD_TBL_CREATE, args=args)
self.commands_loader.load_command_table(args)
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_CMD_TBL_TRUNCATE,
load_cmd_tbl_func=self.commands_loader.load_command_table, args=args)
command = self._rudimentary_get_command(args)
self.cli_ctx.invocation.data['command_string'] = command
telemetry.set_raw_command_name(command)
try:
self.commands_loader.command_table = {command: self.commands_loader.command_table[command]}
except KeyError:
# Trim down the command table to reduce the number of subparsers required to optimize the performance.
#
# When given a command table like this:
#
# network application-gateway create
# network application-gateway delete
# network list-usages
# storage account create
# storage account list
#
# input: az
# output: network application-gateway create
# storage account create
#
# input: az network
# output: network application-gateway create
# network list-usages
cmd_table = {}
group_names = set()
for cmd_name, cmd in self.commands_loader.command_table.items():
if command and not cmd_name.startswith(command):
continue
cmd_stub = cmd_name[len(command):].strip()
group_name = cmd_stub.split(' ', 1)[0]
if group_name not in group_names:
cmd_table[cmd_name] = cmd
group_names.add(group_name)
self.commands_loader.command_table = cmd_table
self.commands_loader.command_table = self.commands_loader.command_table # update with the truncated table
self.commands_loader.command_name = command
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_LOAD_ARGUMENTS, commands_loader=self.commands_loader)
self.commands_loader.load_arguments(command)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_LOAD_ARGUMENTS, commands_loader=self.commands_loader)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_CMD_TBL_CREATE, commands_loader=self.commands_loader)
self.parser.cli_ctx = self.cli_ctx
self.parser.load_command_table(self.commands_loader)
self.cli_ctx.raise_event(EVENT_INVOKER_CMD_TBL_LOADED, cmd_tbl=self.commands_loader.command_table,
parser=self.parser)
arg_check = [a for a in args if a not in
(CLILogging.DEBUG_FLAG, CLILogging.VERBOSE_FLAG, CLILogging.ONLY_SHOW_ERRORS_FLAG)]
if not arg_check:
self.parser.enable_autocomplete()
subparser = self.parser.subparsers[tuple()]
self.help.show_welcome(subparser)
# TODO: No event in base with which to target
telemetry.set_command_details('az')
telemetry.set_success(summary='welcome')
return CommandResultItem(None, exit_code=0)
if args[0].lower() == 'help':
args[0] = '--help'
self.parser.enable_autocomplete()
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_PARSE_ARGS, args=args)
print(args)
parsed_args = self.parser.parse_args(args)
print(parsed_args)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_PARSE_ARGS, command=parsed_args.command, args=parsed_args)
# print local context warning
if self.cli_ctx.local_context.is_on and command and command in self.commands_loader.command_table:
local_context_args = []
arguments = self.commands_loader.command_table[command].arguments
specified_arguments = self.parser.subparser_map[command].specified_arguments \
if command in self.parser.subparser_map else []
for name, argument in arguments.items():
default_value_source = argument.type.settings.get('default_value_source', None)
dest_name = argument.type.settings.get('dest', None)
options = argument.type.settings.get('options_list', None)
if default_value_source == 'Local Context' and dest_name not in specified_arguments and options:
value = getattr(parsed_args, name)
local_context_args.append((options[0], value))
if local_context_args:
logger.warning('Parameter persistence is turned on. Its information is saved in working directory %s. '
'You can run `az config param-persist off` to turn it off.',
self.cli_ctx.local_context.effective_working_directory())
args_str = []
for name, value in local_context_args:
args_str.append('{}: {}'.format(name, value))
logger.warning('Command argument values from persistent parameters: %s', ', '.join(args_str))
# TODO: This fundamentally alters the way Knack.invocation works here. Cannot be customized
# with an event. Would need to be customized via inheritance.
cmd = parsed_args.func
self.cli_ctx.data['command'] = parsed_args.command
self.cli_ctx.data['safe_params'] = AzCliCommandInvoker._extract_parameter_names(args)
command_source = self.commands_loader.command_table[command].command_source
extension_version = None
extension_name = None
try:
if isinstance(command_source, ExtensionCommandSource):
extension_name = command_source.extension_name
extension_version = get_extension(command_source.extension_name).version
except Exception: # pylint: disable=broad-except
pass
telemetry.set_command_details(self.cli_ctx.data['command'], self.data['output'],
self.cli_ctx.data['safe_params'],
extension_name=extension_name, extension_version=extension_version)
if extension_name:
self.data['command_extension_name'] = extension_name
self.cli_ctx.logging.log_cmd_metadata_extension_info(extension_name, extension_version)
self.resolve_warnings(cmd, parsed_args)
self.resolve_confirmation(cmd, parsed_args)
jobs = []
for expanded_arg in _explode_list_args(parsed_args):
cmd_copy = copy.copy(cmd)
cmd_copy.cli_ctx = copy.copy(cmd.cli_ctx)
cmd_copy.cli_ctx.data = copy.deepcopy(cmd.cli_ctx.data)
expanded_arg.cmd = expanded_arg._cmd = cmd_copy
if hasattr(expanded_arg, '_subscription'):
cmd_copy.cli_ctx.data['subscription_id'] = expanded_arg._subscription # pylint: disable=protected-access
self._validation(expanded_arg)
jobs.append((expanded_arg, cmd_copy))
ids = getattr(parsed_args, '_ids', None) or [None] * len(jobs)
if self.cli_ctx.config.getboolean('core', 'disable_concurrent_ids', False) or len(ids) < 2:
results, exceptions = self._run_jobs_serially(jobs, ids)
else:
results, exceptions = self._run_jobs_concurrently(jobs, ids)
# handle exceptions
if len(exceptions) == 1 and not results:
ex, id_arg = exceptions[0]
raise ex
if exceptions:
for exception, id_arg in exceptions:
logger.warning('%s: "%s"', id_arg, str(exception))
if not results:
return CommandResultItem(None, exit_code=1, error=CLIError('Encountered more than one exception.'))
logger.warning('Encountered more than one exception.')
if results and len(results) == 1:
results = results[0]
event_data = {'result': results}
self.cli_ctx.raise_event(EVENT_INVOKER_FILTER_RESULT, event_data=event_data)
# save to local context if it is turned on after command executed successfully
if self.cli_ctx.local_context.is_on and command and command in self.commands_loader.command_table and \
command in self.parser.subparser_map and self.parser.subparser_map[command].specified_arguments:
self.cli_ctx.save_local_context(parsed_args, self.commands_loader.command_table[command].arguments,
self.parser.subparser_map[command].specified_arguments)
return CommandResultItem(
event_data['result'],
table_transformer=self.commands_loader.command_table[parsed_args.command].table_transformer,
is_query_active=self.data['query_active'])
@staticmethod
def _extract_parameter_names(args):
# note: name start with more than 2 '-' will be treated as value e.g. certs in PEM format
return [(p.split('=', 1)[0] if p.startswith('--') else p[:2]) for p in args if
(p.startswith('-') and not p.startswith('---') and len(p) > 1)]
def _run_job(self, expanded_arg, cmd_copy):
params = self._filter_params(expanded_arg)
try:
result = cmd_copy(params)
if cmd_copy.supports_no_wait and getattr(expanded_arg, 'no_wait', False):
result = None
elif cmd_copy.no_wait_param and getattr(expanded_arg, cmd_copy.no_wait_param, False):
result = None
transform_op = cmd_copy.command_kwargs.get('transform', None)
if transform_op:
result = transform_op(result)
if _is_poller(result):
result = LongRunningOperation(cmd_copy.cli_ctx, 'Starting {}'.format(cmd_copy.name))(result)
elif _is_paged(result):
result = list(result)
result = todict(result, AzCliCommandInvoker.remove_additional_prop_layer)
event_data = {'result': result}
cmd_copy.cli_ctx.raise_event(EVENT_INVOKER_TRANSFORM_RESULT, event_data=event_data)
return event_data['result']
except Exception as ex: # pylint: disable=broad-except
if cmd_copy.exception_handler:
return cmd_copy.exception_handler(ex)
raise
def _run_jobs_serially(self, jobs, ids):
results, exceptions = [], []
for job, id_arg in zip(jobs, ids):
expanded_arg, cmd_copy = job
try:
results.append(self._run_job(expanded_arg, cmd_copy))
except(Exception, SystemExit) as ex: # pylint: disable=broad-except
exceptions.append((ex, id_arg))
return results, exceptions
def _run_jobs_concurrently(self, jobs, ids):
from concurrent.futures import ThreadPoolExecutor, as_completed
tasks, results, exceptions = [], [], []
with ThreadPoolExecutor(max_workers=10) as executor:
for expanded_arg, cmd_copy in jobs:
tasks.append(executor.submit(self._run_job, expanded_arg, cmd_copy))
for index, task in enumerate(as_completed(tasks)):
try:
results.append(task.result())
except (Exception, SystemExit) as ex: # pylint: disable=broad-except
exceptions.append((ex, ids[index]))
return results, exceptions
def resolve_warnings(self, cmd, parsed_args):
self._resolve_preview_and_deprecation_warnings(cmd, parsed_args)
self._resolve_extension_override_warning(cmd)
def _resolve_preview_and_deprecation_warnings(self, cmd, parsed_args):
deprecations = [] + getattr(parsed_args, '_argument_deprecations', [])
if cmd.deprecate_info:
deprecations.append(cmd.deprecate_info)
# search for implicit deprecation
path_comps = cmd.name.split()[:-1]
implicit_deprecate_info = None
while path_comps and not implicit_deprecate_info:
implicit_deprecate_info = resolve_deprecate_info(self.cli_ctx, ' '.join(path_comps))
del path_comps[-1]
if implicit_deprecate_info:
deprecate_kwargs = implicit_deprecate_info.__dict__.copy()
deprecate_kwargs['object_type'] = 'command'
del deprecate_kwargs['_get_tag']
del deprecate_kwargs['_get_message']
deprecations.append(ImplicitDeprecated(cli_ctx=self.cli_ctx, **deprecate_kwargs))
previews = [] + getattr(parsed_args, '_argument_previews', [])
if cmd.preview_info:
previews.append(cmd.preview_info)
else:
# search for implicit command preview status
path_comps = cmd.name.split()[:-1]
implicit_preview_info = None
while path_comps and not implicit_preview_info:
implicit_preview_info = resolve_preview_info(self.cli_ctx, ' '.join(path_comps))
del path_comps[-1]
if implicit_preview_info:
preview_kwargs = implicit_preview_info.__dict__.copy()
preview_kwargs['object_type'] = 'command'
del preview_kwargs['_get_tag']
del preview_kwargs['_get_message']
previews.append(ImplicitPreviewItem(cli_ctx=self.cli_ctx, **preview_kwargs))
experimentals = [] + getattr(parsed_args, '_argument_experimentals', [])
if cmd.experimental_info:
experimentals.append(cmd.experimental_info)
else:
# search for implicit command experimental status
path_comps = cmd.name.split()[:-1]
implicit_experimental_info = None
while path_comps and not implicit_experimental_info:
implicit_experimental_info = resolve_experimental_info(self.cli_ctx, ' '.join(path_comps))
del path_comps[-1]
if implicit_experimental_info:
experimental_kwargs = implicit_experimental_info.__dict__.copy()
experimental_kwargs['object_type'] = 'command'
del experimental_kwargs['_get_tag']
del experimental_kwargs['_get_message']
experimentals.append(ImplicitExperimentalItem(cli_ctx=self.cli_ctx, **experimental_kwargs))
if not self.cli_ctx.only_show_errors:
for d in deprecations:
print(d.message, file=sys.stderr)
for p in previews:
print(p.message, file=sys.stderr)
for e in experimentals:
print(e.message, file=sys.stderr)
def _resolve_extension_override_warning(self, cmd): # pylint: disable=no-self-use
if isinstance(cmd.command_source, ExtensionCommandSource) and cmd.command_source.overrides_command:
logger.warning(cmd.command_source.get_command_warn_msg())
def resolve_confirmation(self, cmd, parsed_args):
confirm = cmd.confirmation and not parsed_args.__dict__.pop('yes', None) \
and not cmd.cli_ctx.config.getboolean('core', 'disable_confirm_prompt', fallback=False)
parsed_args = self._filter_params(parsed_args)
if confirm and not cmd._user_confirmed(cmd.confirmation, parsed_args): # pylint: disable=protected-access
from knack.events import EVENT_COMMAND_CANCELLED
cmd.cli_ctx.raise_event(EVENT_COMMAND_CANCELLED, command=cmd.name, command_args=parsed_args)
raise CLIError('Operation cancelled.')
def _build_kwargs(self, func, ns): # pylint: disable=no-self-use
arg_list = get_arg_list(func)
kwargs = {}
if 'cmd' in arg_list:
kwargs['cmd'] = ns._cmd # pylint: disable=protected-access
if 'namespace' in arg_list:
kwargs['namespace'] = ns
if 'ns' in arg_list:
kwargs['ns'] = ns
return kwargs
@staticmethod
def remove_additional_prop_layer(obj, converted_dic):
# Follow EAFP to flatten `additional_properties` auto-generated by SDK
# See https://docs.python.org/3/glossary.html#term-eafp
try:
if 'additionalProperties' in converted_dic and isinstance(obj.additional_properties, dict):
converted_dic.update(converted_dic.pop('additionalProperties'))
except AttributeError:
pass
return converted_dic
def _validate_cmd_level(self, ns, cmd_validator): # pylint: disable=no-self-use
if cmd_validator:
cmd_validator(**self._build_kwargs(cmd_validator, ns))
try:
delattr(ns, '_command_validator')
except AttributeError:
pass
def _validate_arg_level(self, ns, **_): # pylint: disable=no-self-use
from azure.cli.core.azclierror import AzCLIError
for validator in getattr(ns, '_argument_validators', []):
try:
validator(**self._build_kwargs(validator, ns))
except AzCLIError:
raise
except Exception as ex:
# Delay the import and mimic an exception handler
from msrest.exceptions import ValidationError
if isinstance(ex, ValidationError):
logger.debug('Validation error in %s.', str(validator))
raise
try:
delattr(ns, '_argument_validators')
except AttributeError:
pass
class LongRunningOperation: # pylint: disable=too-few-public-methods
def __init__(self, cli_ctx, start_msg='', finish_msg='', poller_done_interval_ms=500.0,
progress_bar=None):
self.cli_ctx = cli_ctx
self.start_msg = start_msg
self.finish_msg = finish_msg
self.poller_done_interval_ms = poller_done_interval_ms
self.deploy_dict = {}
self.last_progress_report = datetime.datetime.now()
self.progress_bar = None
disable_progress_bar = self.cli_ctx.config.getboolean('core', 'disable_progress_bar', False)
if not disable_progress_bar and not cli_ctx.only_show_errors:
self.progress_bar = progress_bar if progress_bar is not None else IndeterminateProgressBar(cli_ctx)
def _delay(self):
time.sleep(self.poller_done_interval_ms / 1000.0)
def _generate_template_progress(self, correlation_id): # pylint: disable=no-self-use
""" gets the progress for template deployments """
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.mgmt.monitor import MonitorManagementClient
if correlation_id is not None: # pylint: disable=too-many-nested-blocks
formatter = "eventTimestamp ge {}"
end_time = datetime.datetime.utcnow()
start_time = end_time - datetime.timedelta(seconds=DEFAULT_QUERY_TIME_RANGE)
odata_filters = formatter.format(start_time.strftime('%Y-%m-%dT%H:%M:%SZ'))
odata_filters = "{} and {} eq '{}'".format(odata_filters, 'correlationId', correlation_id)
activity_log = get_mgmt_service_client(
self.cli_ctx, MonitorManagementClient).activity_logs.list(filter=odata_filters)
results = []
max_events = 50 # default max value for events in list_activity_log
for index, item in enumerate(activity_log):
if index < max_events:
results.append(item)
else:
break
if results:
for event in results:
update = False
long_name = event.resource_id.split('/')[-1]
if long_name not in self.deploy_dict:
self.deploy_dict[long_name] = {}
update = True
deploy_values = self.deploy_dict[long_name]
checked_values = {
str(event.resource_type.value): 'type',
str(event.status.value): 'status value',
str(event.event_name.value): 'request',
}
try:
checked_values[str(event.properties.get('statusCode', ''))] = 'status'
except AttributeError:
pass
if deploy_values.get('timestamp', None) is None or \
event.event_timestamp > deploy_values.get('timestamp'):
for value in checked_values:
if deploy_values.get(checked_values[value], None) != value:
update = True
deploy_values[checked_values[value]] = value
deploy_values['timestamp'] = event.event_timestamp
# don't want to show the timestamp
json_val = deploy_values.copy()
json_val.pop('timestamp', None)
status_val = deploy_values.get('status value', None)
if status_val and status_val != 'Started':
result = deploy_values['status value'] + ': ' + long_name
result += ' (' + deploy_values.get('type', '') + ')'
if update:
logger.info(result)
def __call__(self, poller): # pylint: disable=too-many-statements
from msrest.exceptions import ClientException
from azure.core.exceptions import HttpResponseError
correlation_message = ''
if self.progress_bar:
self.progress_bar.begin()
correlation_id = None
cli_logger = get_logger() # get CLI logger which has the level set through command lines
is_verbose = any(handler.level <= logs.INFO for handler in cli_logger.handlers)
telemetry.poll_start()
poll_flag = False
while not poller.done():
poll_flag = True
try:
# pylint: disable=protected-access
correlation_id = json.loads(
poller._response.__dict__['_content'].decode())['properties']['correlationId']
correlation_message = 'Correlation ID: {}'.format(correlation_id)
except: # pylint: disable=bare-except
pass
current_time = datetime.datetime.now()
if is_verbose and current_time - self.last_progress_report >= datetime.timedelta(seconds=10):
self.last_progress_report = current_time
try:
self._generate_template_progress(correlation_id)
except Exception as ex: # pylint: disable=broad-except
logger.warning('%s during progress reporting: %s', getattr(type(ex), '__name__', type(ex)), ex)
try:
if self.progress_bar:
self.progress_bar.update_progress()
self._delay()
except KeyboardInterrupt:
if self.progress_bar:
self.progress_bar.stop()
logger.error('Long-running operation wait cancelled. %s', correlation_message)
raise