def get_arguments_loader(context, getter_op, cmd_args=None, operation_group=None): getter_args = dict(extract_args_from_signature(context.get_op_handler(getter_op, operation_group=operation_group), excluded_params=EXCLUDED_PARAMS)) cmd_args = cmd_args or {} cmd_args.update(getter_args) cmd_args['cmd'] = CLICommandArgument('cmd', arg_type=ignore_type) return cmd_args
def test_extract_args_custom_exclude(self): excluded_params = ['self', 'kwargs', 'arg2', 'arg3'] arguments = dict( extract_args_from_signature(op1, excluded_params=excluded_params)) self.assertEqual(len(arguments), 1) for param in excluded_params: self.assertNotIn(param, arguments)
def handler(args): from azure.cli.core.commands.client_factory import resolve_client_arg_name getter_args = dict(extract_args_from_signature(context.get_op_handler(getter_op), excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) cmd = args.get('cmd') if 'cmd' in getter_args else args.pop('cmd') operations_tmpl = _get_operations_tmpl(cmd, custom_command=custom_command) client_arg_name = resolve_client_arg_name(operations_tmpl, kwargs) try: client = factory(context.cli_ctx) if factory else None except TypeError: client = factory(context.cli_ctx, args) if factory else None if client and (client_arg_name in getter_args): args[client_arg_name] = client getter = context.get_op_handler(getter_op) try: return getter(**args) except Exception as ex: # pylint: disable=broad-except if getattr(getattr(ex, 'response', ex), 'status_code', None) == 404: logger.error(getattr(ex, 'message', ex)) import sys sys.exit(3) raise
def handler(args): from azure.cli.core.commands.client_factory import resolve_client_arg_name getter_args = dict( extract_args_from_signature( context.get_op_handler(getter_op), excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) cmd = args.get('cmd') if 'cmd' in getter_args else args.pop('cmd') operations_tmpl = _get_operations_tmpl(cmd, custom_command=custom_command) client_arg_name = resolve_client_arg_name(operations_tmpl, kwargs) try: client = factory(context.cli_ctx) if factory else None except TypeError: client = factory(context.cli_ctx, args) if factory else None if client and (client_arg_name in getter_args): args[client_arg_name] = client getter = context.get_op_handler(getter_op) try: return getter(**args) except Exception as ex: # pylint: disable=broad-except if getattr(getattr(ex, 'response', ex), 'status_code', None) == 404: logger.error(getattr(ex, 'message', ex)) import sys sys.exit(3) raise
def function_arguments_loader(): if not custom_function_op: return {} custom_op = context.get_op_handler(custom_function_op) context._apply_doc_string(custom_op, kwargs) # pylint: disable=protected-access return dict(extract_args_from_signature(custom_op, excluded_params=EXCLUDED_PARAMS))
def load_custom_function_op_arguments(self): if not self.custom_function_op_path: return {} op = self.get_op_handler(self.custom_function_op_path) self.apply_doc_string(op) # pylint: disable=protected-access return dict( extract_args_from_signature(op, excluded_params=EXCLUDED_PARAMS))
def handler(self, command_args): """ Callback function of CLICommand handler """ from azure.cli.core.commands.arm import show_exception_handler, EXCLUDED_NON_CLIENT_PARAMS op = self.get_op_handler(self.op_path) getter_args = dict( extract_args_from_signature( op, excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) self.cmd = command_args.get( 'cmd') if 'cmd' in getter_args else command_args.pop('cmd') client_arg_name = self.resolve_client_arg_name(self.op_path) try: client = self.client_factory( self.cli_ctx) if self.client_factory else None except TypeError: client = self.client_factory( self.cli_ctx, command_args) if self.client_factory else None if client and (client_arg_name in getter_args): command_args[client_arg_name] = client op = self.get_op_handler( self.op_path) # Fetch op handler again after cmd property is set try: return op(**command_args) except Exception as ex: # pylint: disable=broad-except show_exception_handler(ex)
def expand(self, dest, model_type, group_name=None, patches=None): # TODO: # two privates symbols are imported here. they should be made public or this utility class # should be moved into azure.cli.core from knack.introspection import extract_args_from_signature, option_descriptions self._check_stale() if not self._applicable(): return if not patches: patches = dict() # fetch the documentation for model parameters first. for models, which are the classes # derive from msrest.serialization.Model and used in the SDK API to carry parameters, the # document of their properties are attached to the classes instead of constructors. parameter_docs = option_descriptions(model_type) def get_complex_argument_processor(expanded_arguments, assigned_arg, model_type): """ Return a validator which will aggregate multiple arguments to one complex argument. """ def _expansion_validator_impl(namespace): """ The validator create a argument of a given type from a specific set of arguments from CLI command. :param namespace: The argparse namespace represents the CLI arguments. :return: The argument of specific type. """ ns = vars(namespace) kwargs = dict( (k, ns[k]) for k in ns if k in set(expanded_arguments)) setattr(namespace, assigned_arg, model_type(**kwargs)) return _expansion_validator_impl expanded_arguments = [] for name, arg in extract_args_from_signature( model_type.__init__, excluded_params=EXCLUDED_PARAMS): arg = arg.type if name in parameter_docs: arg.settings['help'] = parameter_docs[name] if group_name: arg.settings['arg_group'] = group_name if name in patches: patches[name](arg) self.extra(name, arg_type=arg) expanded_arguments.append(name) dest_option = ['--__{}'.format(dest.upper())] self.argument(dest, arg_type=ignore_type, options_list=dest_option, validator=get_complex_argument_processor( expanded_arguments, dest, model_type))
def function_arguments_loader(): if not custom_function_op: return {} custom_op = context.get_op_handler(custom_function_op) context._apply_doc_string(custom_op, kwargs) # pylint: disable=protected-access return dict(extract_args_from_signature(custom_op, excluded_params=EXCLUDED_PARAMS))
def default_arguments_loader(): op = handler or self.get_op_handler(operation) self._apply_doc_string(op, kwargs) cmd_args = list( extract_args_from_signature( op, excluded_params=self.excluded_command_handler_args)) return cmd_args
def arguments_loader(self): """ Callback function of CLICommand arguments_loader """ op = self.get_op_handler(self.op_path) self.apply_doc_string(op) cmd_args = list( extract_args_from_signature(op, excluded_params=self.command_loader. excluded_command_handler_args)) return cmd_args
def keyvault_arguments_loader(): op = get_op_handler() self.command_loader._apply_doc_string(op, merged_kwargs) # pylint: disable=protected-access cmd_args = list( extract_args_from_signature( op, excluded_params=self.command_loader. excluded_command_handler_args)) return cmd_args
def expand(self, dest, model_type, group_name=None, patches=None): # TODO: # two privates symbols are imported here. they should be made public or this utility class # should be moved into azure.cli.core from knack.introspection import extract_args_from_signature, option_descriptions self._check_stale() if not self._applicable(): return if not patches: patches = dict() # fetch the documentation for model parameters first. for models, which are the classes # derive from msrest.serialization.Model and used in the SDK API to carry parameters, the # document of their properties are attached to the classes instead of constructors. parameter_docs = option_descriptions(model_type) def get_complex_argument_processor(expanded_arguments, assigned_arg, model_type): """ Return a validator which will aggregate multiple arguments to one complex argument. """ def _expansion_validator_impl(namespace): """ The validator create a argument of a given type from a specific set of arguments from CLI command. :param namespace: The argparse namespace represents the CLI arguments. :return: The argument of specific type. """ ns = vars(namespace) kwargs = dict((k, ns[k]) for k in ns if k in set(expanded_arguments)) setattr(namespace, assigned_arg, model_type(**kwargs)) return _expansion_validator_impl expanded_arguments = [] for name, arg in extract_args_from_signature(model_type.__init__, excluded_params=EXCLUDED_PARAMS): arg = arg.type if name in parameter_docs: arg.settings['help'] = parameter_docs[name] if group_name: arg.settings['arg_group'] = group_name if name in patches: patches[name](arg) self.extra(name, arg_type=arg) expanded_arguments.append(name) dest_option = ['--__{}'.format(dest.upper())] self.argument(dest, arg_type=ignore_type, options_list=dest_option, validator=get_complex_argument_processor(expanded_arguments, dest, model_type))
def load_getter_op_arguments(self, getter_op_path, cmd_args=None): """ Load arguments from function signature of getter command op """ op = self.get_op_handler(getter_op_path) getter_args = dict( extract_args_from_signature(op, excluded_params=EXCLUDED_PARAMS)) cmd_args = cmd_args or {} cmd_args.update(getter_args) # The cmd argument is required when calling self.handler function. cmd_args['cmd'] = CLICommandArgument('cmd', arg_type=ignore_type) return cmd_args
def generic_wait_arguments_loader(): getter_args = dict( extract_args_from_signature(context.get_op_handler(getter_op), excluded_params=EXCLUDED_PARAMS)) cmd_args = getter_args.copy() group_name = 'Wait Condition' cmd_args['timeout'] = CLICommandArgument( 'timeout', options_list=['--timeout'], default=3600, arg_group=group_name, type=int, help='maximum wait in seconds') cmd_args['interval'] = CLICommandArgument( 'interval', options_list=['--interval'], default=30, arg_group=group_name, type=int, help='polling interval in seconds') cmd_args['deleted'] = CLICommandArgument('deleted', options_list=['--deleted'], action='store_true', arg_group=group_name, help='wait until deleted') cmd_args['created'] = CLICommandArgument( 'created', options_list=['--created'], action='store_true', arg_group=group_name, help="wait until created with 'provisioningState' at 'Succeeded'") cmd_args['updated'] = CLICommandArgument( 'updated', options_list=['--updated'], action='store_true', arg_group=group_name, help="wait until updated with provisioningState at 'Succeeded'") cmd_args['exists'] = CLICommandArgument( 'exists', options_list=['--exists'], action='store_true', arg_group=group_name, help="wait until the resource exists") cmd_args['custom'] = CLICommandArgument( 'custom', options_list=['--custom'], arg_group=group_name, help= "Wait until the condition satisfies a custom JMESPath query. E.g. " "provisioningState!='InProgress', " "instanceView.statuses[?code=='PowerState/running']") cmd_args['cmd'] = CLICommandArgument('cmd', arg_type=ignore_type) return [(k, v) for k, v in cmd_args.items()]
def default_arguments_loader(): '''Loads handler function's arguments from operation_template ''' # Get the handler function for the specified operation template op = handler or self.get_op_handler( operation, operation_group=kwargs.get('operation_group')) # Extract command args from the handler function signature cmd_args = list( extract_args_from_signature( op, excluded_params=self.excluded_command_handler_args)) return cmd_args
def _extract_handler_and_args(args, commmand_kwargs, op, context): from azure.cli.core.commands.client_factory import resolve_client_arg_name factory = _get_client_factory(name, **commmand_kwargs) client = None if factory: try: client = factory(context.cli_ctx) except TypeError: client = factory(context.cli_ctx, args) client_arg_name = resolve_client_arg_name(op, kwargs) op_handler = context.get_op_handler(op, operation_group=kwargs.get('operation_group')) raw_args = dict(extract_args_from_signature(op_handler, excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) op_args = {key: val for key, val in args.items() if key in raw_args} if client_arg_name in raw_args: op_args[client_arg_name] = client return op_handler, op_args
def _extract_handler_and_args(args, commmand_kwargs, op): factory = _get_client_factory(name, commmand_kwargs) client = None if factory: try: client = factory(context.cli_ctx) except TypeError: client = factory(context.cli_ctx, None) client_arg_name = 'client' if op.startswith(('azure.cli', 'azext')) else 'self' op_handler = context.get_op_handler(op) exclude = list(set(EXCLUDED_PARAMS) - set(['self', 'client'])) raw_args = dict(extract_args_from_signature(op_handler, excluded_params=exclude)) op_args = {key: val for key, val in args.items() if key in raw_args} if client_arg_name in raw_args: op_args[client_arg_name] = client return op_handler, op_args
def _extract_handler_and_args(args, commmand_kwargs, op): from azure.cli.core.commands.client_factory import resolve_client_arg_name factory = _get_client_factory(name, commmand_kwargs) client = None if factory: try: client = factory(context.cli_ctx) except TypeError: client = factory(context.cli_ctx, None) client_arg_name = resolve_client_arg_name(op, kwargs) op_handler = context.get_op_handler(op) exclude = list(set(EXCLUDED_PARAMS) - set(['self', 'client'])) raw_args = dict(extract_args_from_signature(op_handler, excluded_params=exclude)) op_args = {key: val for key, val in args.items() if key in raw_args} if client_arg_name in raw_args: op_args[client_arg_name] = client return op_handler, op_args
def _extract_handler_and_args(args, commmand_kwargs, op): from azure.cli.core.commands.client_factory import resolve_client_arg_name factory = _get_client_factory(name, commmand_kwargs) client = None if factory: try: client = factory(context.cli_ctx) except TypeError: client = factory(context.cli_ctx, args) client_arg_name = resolve_client_arg_name(op, kwargs) op_handler = context.get_op_handler(op) exclude = list(set(EXCLUDED_PARAMS) - set(['self', 'client'])) raw_args = dict( extract_args_from_signature(op_handler, excluded_params=exclude)) op_args = {key: val for key, val in args.items() if key in raw_args} if client_arg_name in raw_args: op_args[client_arg_name] = client return op_handler, op_args
def _extract_op_handler_and_args(self, args, op_path): from azure.cli.core.commands.arm import EXCLUDED_NON_CLIENT_PARAMS client = None if self.client_factory: try: client = self.client_factory(self.cli_ctx) except TypeError: client = self.client_factory(self.cli_ctx, args) client_arg_name = self.resolve_client_arg_name(op_path) op = self.get_op_handler(op_path) raw_args = dict( extract_args_from_signature( op, excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) op_args = {key: val for key, val in args.items() if key in raw_args} if client_arg_name in raw_args: op_args[client_arg_name] = client return op, op_args
def handler(args): from azure.cli.core.commands.client_factory import resolve_client_arg_name context_copy = copy.copy(context) getter_args = dict(extract_args_from_signature(context_copy.get_op_handler(getter_op), excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) cmd = args.get('cmd') if 'cmd' in getter_args else args.pop('cmd') context_copy.cli_ctx = cmd.cli_ctx operations_tmpl = _get_operations_tmpl(cmd, custom_command=custom_command) client_arg_name = resolve_client_arg_name(operations_tmpl, kwargs) try: client = factory(context_copy.cli_ctx) if factory else None except TypeError: client = factory(context_copy.cli_ctx, args) if factory else None if client and (client_arg_name in getter_args): args[client_arg_name] = client getter = context_copy.get_op_handler(getter_op) try: return getter(**args) except Exception as ex: # pylint: disable=broad-except show_exception_handler(ex)
def generic_wait_arguments_loader(): getter_args = dict(extract_args_from_signature(context.get_op_handler(getter_op), excluded_params=EXCLUDED_PARAMS)) cmd_args = getter_args.copy() group_name = 'Wait Condition' cmd_args['timeout'] = CLICommandArgument( 'timeout', options_list=['--timeout'], default=3600, arg_group=group_name, type=int, help='maximum wait in seconds' ) cmd_args['interval'] = CLICommandArgument( 'interval', options_list=['--interval'], default=30, arg_group=group_name, type=int, help='polling interval in seconds' ) cmd_args['deleted'] = CLICommandArgument( 'deleted', options_list=['--deleted'], action='store_true', arg_group=group_name, help='wait until deleted' ) cmd_args['created'] = CLICommandArgument( 'created', options_list=['--created'], action='store_true', arg_group=group_name, help="wait until created with 'provisioningState' at 'Succeeded'" ) cmd_args['updated'] = CLICommandArgument( 'updated', options_list=['--updated'], action='store_true', arg_group=group_name, help="wait until updated with provisioningState at 'Succeeded'" ) cmd_args['exists'] = CLICommandArgument( 'exists', options_list=['--exists'], action='store_true', arg_group=group_name, help="wait until the resource exists" ) cmd_args['custom'] = CLICommandArgument( 'custom', options_list=['--custom'], arg_group=group_name, help="Wait until the condition satisfies a custom JMESPath query. E.g. " "provisioningState!='InProgress', " "instanceView.statuses[?code=='PowerState/running']" ) cmd_args['cmd'] = CLICommandArgument('cmd', arg_type=ignore_type) return [(k, v) for k, v in cmd_args.items()]
def test_extract_args_simple(self): arguments = dict(extract_args_from_signature(op1)) self.assertEqual(len(arguments), 3) self.assertNotIn('self', arguments) self.assertNotIn('kwargs', arguments) self.assertIn('arg1', arguments) self.assertListEqual(arguments['arg1'].options_list, ['--arg1']) self.assertTrue(arguments['arg1'].options['required']) self.assertIn('arg2', arguments) self.assertListEqual(arguments['arg2'].options_list, ['--arg2']) self.assertFalse(arguments['arg2'].options['required']) self.assertEqual(arguments['arg2'].options['action'], 'store_true') self.assertIn('arg3', arguments) self.assertListEqual(arguments['arg3'].options_list, ['--arg3']) self.assertFalse(arguments['arg3'].options['required']) self.assertEqual(arguments['arg3'].options['default'], 'mydefaultvalue') self.assertEqual(arguments['arg3'].options['help'], 'This is an arg for a test.')
def handler(args): from azure.cli.core.commands.client_factory import resolve_client_arg_name context_copy = copy.copy(context) getter_args = dict(extract_args_from_signature( context_copy.get_op_handler(getter_op, operation_group=kwargs.get('operation_group')), excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) cmd = args.get('cmd') if 'cmd' in getter_args else args.pop('cmd') context_copy.cli_ctx = cmd.cli_ctx operations_tmpl = _get_operations_tmpl(cmd, custom_command=custom_command) client_arg_name = resolve_client_arg_name(operations_tmpl, kwargs) try: client = factory(context_copy.cli_ctx) if factory else None except TypeError: client = factory(context_copy.cli_ctx, args) if factory else None if client and (client_arg_name in getter_args): args[client_arg_name] = client getter = context_copy.get_op_handler(getter_op, operation_group=kwargs.get('operation_group')) try: return getter(**args) except Exception as ex: # pylint: disable=broad-except show_exception_handler(ex)
def _load_transformed_arguments(self, handler): """Load all the command line arguments from the request parameters. :param func handler: The operation function. """ from azure.cli.core.commands.parameters import file_type from argcomplete.completers import FilesCompleter, DirectoriesCompleter self.parser = BatchArgumentTree(self.validator) self._load_options_model(handler) args = [] for arg in extract_args_from_signature( handler, excluded_params=EXCLUDED_PARAMS): arg_type = find_param_type(handler, arg[0]) if arg[0] == self._options_param: for option_arg in self._process_options(): args.append(option_arg) elif arg_type.startswith("str or"): docstring = find_param_help(handler, arg[0]) choices = [] values_index = docstring.find(' Possible values include') if values_index >= 0: choices = docstring[values_index + 25:].split(', ') choices = [ enum_value(c) for c in choices if enum_value(c) != "'unmapped'" ] docstring = docstring[0:values_index] args.append( ((arg[0], CLICommandArgument(arg[0], options_list=[arg_name(arg[0])], required=False, default=None, choices=choices, help=docstring)))) elif arg_type.startswith( "~"): # TODO: could add handling for enums param_type = class_name(arg_type) self.parser.set_request_param(arg[0], param_type) param_model = _load_model(param_type) self._flatten_object(arg[0], param_model) for flattened_arg in self.parser.compile_args(): args.append(flattened_arg) param = 'json_file' docstring = "A file containing the {} specification in JSON " \ "(formatted to match the respective REST API body). " \ "If this parameter is specified, all '{} Arguments'" \ " are ignored.".format(arg[0].replace('_', ' '), group_title(arg[0])) args.append((param, CLICommandArgument(param, options_list=[arg_name(param)], required=False, default=None, type=file_type, completer=FilesCompleter(), help=docstring))) elif arg[0] not in pformat.IGNORE_PARAMETERS: args.append(arg) return_type = find_return_type(handler) if return_type and return_type.startswith('Generator'): param = 'destination' docstring = "The path to the destination file or directory." args.append((param, CLICommandArgument( param, options_list=[arg_name(param)], required=True, default=None, completer=DirectoriesCompleter(), type=file_type, validator=validators.validate_file_destination, help=docstring))) if return_type == 'None' and handler.__name__.startswith('get'): self._head_cmd = True if self.confirmation: param = CONFIRM_PARAM_NAME docstring = 'Do not prompt for confirmation.' args.append((param, CLICommandArgument(param, options_list=['--yes', '-y'], required=False, action='store_true', help=docstring))) auth_group_name = 'Batch Account' args.append(('cmd', CLICommandArgument('cmd', action=IgnoreAction))) args.append(( 'account_name', CLICommandArgument( 'account_name', options_list=['--account-name'], required=False, default=None, validator=validators.validate_client_parameters, arg_group=auth_group_name, help= 'Batch account name. Alternatively, set by environment variable: AZURE_BATCH_ACCOUNT' ))) args.append(( 'account_key', CLICommandArgument( 'account_key', options_list=['--account-key'], required=False, default=None, arg_group=auth_group_name, help= 'Batch account key. Alternatively, set by environment variable: AZURE_BATCH_ACCESS_KEY' ))) args.append(( 'account_endpoint', CLICommandArgument( 'account_endpoint', options_list=['--account-endpoint'], required=False, default=None, arg_group=auth_group_name, help= 'Batch service endpoint. Alternatively, set by environment variable: AZURE_BATCH_ENDPOINT' ))) return args
def load_setter_op_arguments(self): op = self.get_op_handler(self.setter_op_path) return dict( extract_args_from_signature(op, excluded_params=EXCLUDED_PARAMS))
def handler(args): from azure.cli.core.commands.client_factory import resolve_client_arg_name from msrest.exceptions import ClientException import time cmd = args.get('cmd') operations_tmpl = _get_operations_tmpl(cmd) getter_args = dict( extract_args_from_signature(context.get_op_handler(getter_op), excluded_params=EXCLUDED_PARAMS)) client_arg_name = resolve_client_arg_name(operations_tmpl, kwargs) try: client = factory(context.cli_ctx) if factory else None except TypeError: client = factory(context.cli_ctx, args) if factory else None if client and (client_arg_name in getter_args or client_arg_name == 'self'): args[client_arg_name] = client getter = context.get_op_handler(getter_op) timeout = args.pop('timeout') interval = args.pop('interval') wait_for_created = args.pop('created') wait_for_deleted = args.pop('deleted') wait_for_updated = args.pop('updated') wait_for_exists = args.pop('exists') custom_condition = args.pop('custom') if not any([ wait_for_created, wait_for_updated, wait_for_deleted, wait_for_exists, custom_condition ]): raise CLIError( "incorrect usage: --created | --updated | --deleted | --exists | --custom JMESPATH" ) progress_indicator = context.cli_ctx.get_progress_controller() progress_indicator.begin() for _ in range(0, timeout, interval): try: progress_indicator.add(message='Waiting') instance = getter(**args) if wait_for_exists: progress_indicator.end() return None provisioning_state = get_provisioning_state(instance) # until we have any needs to wait for 'Failed', let us bail out on this if provisioning_state == 'Failed': progress_indicator.stop() raise CLIError('The operation failed') if ((wait_for_created or wait_for_updated) and provisioning_state == 'Succeeded') or \ custom_condition and bool(verify_property(instance, custom_condition)): progress_indicator.end() return None except ClientException as ex: progress_indicator.stop() if getattr(ex, 'status_code', None) == 404: if wait_for_deleted: return None if not any( [wait_for_created, wait_for_exists, custom_condition]): raise else: raise except Exception as ex: # pylint: disable=broad-except progress_indicator.stop() raise time.sleep(interval) progress_indicator.end() return CLIError( 'Wait operation timed-out after {} seconds'.format(timeout))
def handler(self, command_args): # pylint: disable=too-many-statements, too-many-locals """ Callback function of CLICommand handler """ from msrest.exceptions import ClientException from azure.core.exceptions import HttpResponseError from knack.util import CLIError from azure.cli.core.commands.arm import EXCLUDED_NON_CLIENT_PARAMS, verify_property from azure.cli.core.commands.progress import IndeterminateProgressBar import time op = self.get_op_handler(self.op_path) getter_args = dict( extract_args_from_signature( op, excluded_params=EXCLUDED_NON_CLIENT_PARAMS)) self.cmd = command_args.get( 'cmd') if 'cmd' in getter_args else command_args.pop('cmd') client_arg_name = self.resolve_client_arg_name(self.op_path) try: client = self.client_factory( self.cli_ctx) if self.client_factory else None except TypeError: client = self.client_factory( self.cli_ctx, command_args) if self.client_factory else None if client and (client_arg_name in getter_args): command_args[client_arg_name] = client getter = self.get_op_handler( self.op_path) # Fetch op handler again after cmd property is set timeout = command_args.pop('timeout') interval = command_args.pop('interval') wait_for_created = command_args.pop('created') wait_for_deleted = command_args.pop('deleted') wait_for_updated = command_args.pop('updated') wait_for_exists = command_args.pop('exists') custom_condition = command_args.pop('custom') if not any([ wait_for_created, wait_for_updated, wait_for_deleted, wait_for_exists, custom_condition ]): raise CLIError( "incorrect usage: --created | --updated | --deleted | --exists | --custom JMESPATH" ) progress_indicator = IndeterminateProgressBar(self.cli_ctx, message='Waiting') progress_indicator.begin() for _ in range(0, timeout, interval): try: progress_indicator.update_progress() instance = getter(**command_args) if wait_for_exists: progress_indicator.end() return None provisioning_state = self._get_provisioning_state(instance) # until we have any needs to wait for 'Failed', let us bail out on this if provisioning_state: provisioning_state = provisioning_state.lower() if provisioning_state == 'failed': progress_indicator.stop() raise CLIError('The operation failed') if ((wait_for_created or wait_for_updated) and provisioning_state == 'succeeded') or \ custom_condition and bool(verify_property(instance, custom_condition)): progress_indicator.end() return None except (ClientException, HttpResponseError) as ex: progress_indicator.stop() if getattr(ex, 'status_code', None) == 404: if wait_for_deleted: return None if not any( [wait_for_created, wait_for_exists, custom_condition]): raise else: raise except Exception: # pylint: disable=broad-except progress_indicator.stop() raise time.sleep(interval) progress_indicator.end() return CLIError( 'Wait operation timed-out after {} seconds'.format(timeout))
def default_arguments_loader(): op = handler or self.get_op_handler(operation) self._apply_doc_string(op, kwargs) cmd_args = list(extract_args_from_signature(op, excluded_params=self.excluded_command_handler_args)) return cmd_args
def handler(args): from azure.cli.core.commands.client_factory import resolve_client_arg_name from msrest.exceptions import ClientException import time cmd = args.get('cmd') operations_tmpl = _get_operations_tmpl(cmd) getter_args = dict(extract_args_from_signature(context.get_op_handler(getter_op), excluded_params=EXCLUDED_PARAMS)) client_arg_name = resolve_client_arg_name(operations_tmpl, kwargs) try: client = factory(context.cli_ctx) if factory else None except TypeError: client = factory(context.cli_ctx, None) if factory else None if client and (client_arg_name in getter_args or client_arg_name == 'self'): args[client_arg_name] = client getter = context.get_op_handler(getter_op) timeout = args.pop('timeout') interval = args.pop('interval') wait_for_created = args.pop('created') wait_for_deleted = args.pop('deleted') wait_for_updated = args.pop('updated') wait_for_exists = args.pop('exists') custom_condition = args.pop('custom') if not any([wait_for_created, wait_for_updated, wait_for_deleted, wait_for_exists, custom_condition]): raise CLIError( "incorrect usage: --created | --updated | --deleted | --exists | --custom JMESPATH") progress_indicator = context.cli_ctx.get_progress_controller() progress_indicator.begin() for _ in range(0, timeout, interval): try: progress_indicator.add(message='Waiting') instance = getter(**args) if wait_for_exists: progress_indicator.end() return None provisioning_state = get_provisioning_state(instance) # until we have any needs to wait for 'Failed', let us bail out on this if provisioning_state == 'Failed': progress_indicator.stop() raise CLIError('The operation failed') if ((wait_for_created or wait_for_updated) and provisioning_state == 'Succeeded') or \ custom_condition and bool(verify_property(instance, custom_condition)): progress_indicator.end() return None except ClientException as ex: progress_indicator.stop() if getattr(ex, 'status_code', None) == 404: if wait_for_deleted: return None if not any([wait_for_created, wait_for_exists, custom_condition]): raise else: raise except Exception as ex: # pylint: disable=broad-except progress_indicator.stop() raise time.sleep(interval) progress_indicator.end() return CLIError('Wait operation timed-out after {} seconds'.format(timeout))
def set_arguments_loader(): return dict(extract_args_from_signature(context.get_op_handler(setter_op), excluded_params=EXCLUDED_PARAMS))
def keyvault_arguments_loader(): op = get_op_handler() self.command_loader._apply_doc_string(op, merged_kwargs) # pylint: disable=protected-access cmd_args = list( extract_args_from_signature(op, excluded_params=self.command_loader.excluded_command_handler_args)) return cmd_args
def _load_transformed_arguments(self, handler): """Load all the command line arguments from the request parameters. :param func handler: The operation function. """ from azure.cli.core.commands.parameters import file_type from argcomplete.completers import FilesCompleter, DirectoriesCompleter self.parser = BatchArgumentTree(self.validator) self._load_options_model(handler) args = [] for arg in extract_args_from_signature(handler, excluded_params=EXCLUDED_PARAMS): arg_type = find_param_type(handler, arg[0]) if arg[0] == self._options_param: for option_arg in self._process_options(): args.append(option_arg) elif arg_type.startswith("str or"): docstring = find_param_help(handler, arg[0]) choices = [] values_index = docstring.find(' Possible values include') if values_index >= 0: choices = docstring[values_index + 25:].split(', ') choices = [enum_value(c) for c in choices if enum_value(c) != "'unmapped'"] docstring = docstring[0:values_index] args.append(((arg[0], CLICommandArgument(arg[0], options_list=[arg_name(arg[0])], required=False, default=None, choices=choices, help=docstring)))) elif arg_type.startswith("~"): # TODO: could add handling for enums param_type = class_name(arg_type) self.parser.set_request_param(arg[0], param_type) param_model = _load_model(param_type) self._flatten_object(arg[0], param_model) for flattened_arg in self.parser.compile_args(): args.append(flattened_arg) param = 'json_file' docstring = "A file containing the {} specification in JSON " \ "(formatted to match the respective REST API body). " \ "If this parameter is specified, all '{} Arguments'" \ " are ignored.".format(arg[0].replace('_', ' '), group_title(arg[0])) args.append((param, CLICommandArgument(param, options_list=[arg_name(param)], required=False, default=None, type=file_type, completer=FilesCompleter(), help=docstring))) elif arg[0] not in pformat.IGNORE_PARAMETERS: args.append(arg) return_type = find_return_type(handler) if return_type and return_type.startswith('Generator'): param = 'destination' docstring = "The path to the destination file or directory." args.append((param, CLICommandArgument(param, options_list=[arg_name(param)], required=True, default=None, completer=DirectoriesCompleter(), type=file_type, validator=validators.validate_file_destination, help=docstring))) if return_type == 'None' and handler.__name__.startswith('get'): self._head_cmd = True if self.confirmation: param = CONFIRM_PARAM_NAME docstring = 'Do not prompt for confirmation.' args.append((param, CLICommandArgument(param, options_list=['--yes', '-y'], required=False, action='store_true', help=docstring))) auth_group_name = 'Batch Account' args.append(('cmd', CLICommandArgument('cmd', action=IgnoreAction))) args.append(('account_name', CLICommandArgument( 'account_name', options_list=['--account-name'], required=False, default=None, validator=validators.validate_client_parameters, arg_group=auth_group_name, help='Batch account name. Alternatively, set by environment variable: AZURE_BATCH_ACCOUNT'))) args.append(('account_key', CLICommandArgument( 'account_key', options_list=['--account-key'], required=False, default=None, arg_group=auth_group_name, help='Batch account key. Alternatively, set by environment variable: AZURE_BATCH_ACCESS_KEY'))) args.append(('account_endpoint', CLICommandArgument( 'account_endpoint', options_list=['--account-endpoint'], required=False, default=None, arg_group=auth_group_name, help='Batch service endpoint. Alternatively, set by environment variable: AZURE_BATCH_ENDPOINT'))) return args
def set_arguments_loader(): return dict( extract_args_from_signature(context.get_op_handler(setter_op), excluded_params=EXCLUDED_PARAMS))
def set_arguments_loader(): return dict(extract_args_from_signature(context.get_op_handler( setter_op, operation_group=kwargs.get('operation_group')), excluded_params=EXCLUDED_PARAMS))