예제 #1
0
def _create_key_vault_command(name, operation, transform_result, table_transformer):

    def _execute_command(kwargs):

        try:

            def get_token(server, resource, scope): # pylint: disable=unused-argument
                return Profile().get_login_credentials(resource)[0]._token_retriever() # pylint: disable=protected-access

            # since the convenience client can be inconvenient, we have to check and create the
            # correct client version
            if 'generated' in operation.__module__:
                client = BaseKeyVaultClient(KeyVaultAuthentication(get_token))
            else:
                client = KeyVaultClient(KeyVaultAuthentication(get_token)) # pylint: disable=redefined-variable-type
            result = operation(client, **kwargs)

            # apply results transform if specified
            if transform_result:
                return _encode_hex(transform_result(result))

            # otherwise handle based on return type of results
            if isinstance(result, AzureOperationPoller):
                return _encode_hex(LongRunningOperation('Starting {}'.format(name))(result))
            elif isinstance(result, Paged):
                try:
                    return _encode_hex(list(result))
                except TypeError:
                    # TODO: Workaround for an issue in either KeyVault server-side or msrest
                    # See https://github.com/Azure/autorest/issues/1309
                    return []
            else:
                return _encode_hex(result)
        except (ValidationError, KeyVaultErrorException) as ex:
            try:
                raise CLIError(ex.inner_exception.error.message)
            except AttributeError:
                raise CLIError(ex)

    name = ' '.join(name.split())
    cmd = CliCommand(name, _execute_command, table_transformer=table_transformer)
    cmd.description = extract_full_summary_from_signature(operation)
    cmd.arguments.update(extract_args_from_signature(operation))
    return cmd
예제 #2
0
    def __init__(
            self,
            module_name,
            name,  # pylint:disable=too-many-statements
            operation,
            factory,
            transform_result,
            flatten,
            ignore,
            validator,
            silent):

        if not isinstance(operation, string_types):
            raise ValueError(
                "Operation must be a string. Got '{}'".format(operation))

        self.flatten = flatten  # Number of object levels to flatten
        self.silent = silent if silent else []
        self.ignore = list(IGNORE_PARAMETERS)  # Parameters to ignore
        if ignore:
            self.ignore.extend(ignore)
        self.parser = None
        self.validator = validator
        self.confirmation = 'delete' in operation
        self.head_cmd = False

        # The name of the request options parameter
        self._options_param = format_options_name(operation)
        # Arguments used for request options
        self._options_attrs = []
        # The loaded options model to populate for the request
        self._options_model = None

        def _execute_command(kwargs):
            from msrest.paging import Paged
            from msrest.exceptions import ValidationError, ClientRequestError
            from azure.batch.models import BatchErrorException
            from azure.cli.core.util import CLIError
            from azure.cli.core._config import az_config
            from azure.cli.core.commands import _user_confirmed

            if self._cancel_operation(kwargs, az_config, _user_confirmed):
                raise CLIError('Operation cancelled.')

            try:
                client = factory(kwargs)
                self._build_options(kwargs)

                stream_output = kwargs.pop('destination', None)
                json_file = kwargs.pop('json_file', None)

                # Build the request parameters from command line arguments
                if json_file:
                    self.parser.deserialize_json(client, kwargs, json_file)
                    for arg, _ in self.parser:
                        del kwargs[arg]
                else:
                    for arg, details in self.parser:
                        try:
                            param_value = kwargs.pop(arg)
                            if param_value is None:
                                continue
                            else:
                                self._build_parameters(details['path'], kwargs,
                                                       details['root'],
                                                       param_value)
                        except KeyError:
                            continue

                # Make request
                op = get_op_handler(operation)
                if self.head_cmd:
                    kwargs['raw'] = True
                result = op(client, **kwargs)

                # Head output
                if self.head_cmd:
                    return transformers.transform_response_headers(result)

                # File download
                if stream_output:
                    with open(stream_output, "wb") as file_handle:
                        for data in result:
                            file_handle.write(data)
                    return

                # Apply results transform if specified
                elif transform_result:
                    return transform_result(result)

                # Otherwise handle based on return type of results
                elif isinstance(result, Paged):
                    return list(result)

                return result
            except BatchErrorException as ex:
                try:
                    message = ex.error.message.value
                    if ex.error.values:
                        for detail in ex.error.values:
                            message += "\n{}: {}".format(
                                detail.key, detail.value)
                    raise CLIError(message)
                except AttributeError:
                    raise CLIError(ex)
            except (ValidationError, ClientRequestError) as ex:
                raise CLIError(ex)

        table_transformer = None
        try:
            transform_func = '_'.join(name.split()[1:]).replace('-', '_')
            table_transformer = getattr(transformers,
                                        transform_func + "_table_format")
        except AttributeError:
            pass
        command_module_map[name] = module_name
        self.cmd = CliCommand(
            ' '.join(name.split()),
            _execute_command,
            table_transformer=table_transformer,
            arguments_loader=lambda: self._load_transformed_arguments(
                get_op_handler(operation)),
            description_loader=lambda: extract_full_summary_from_signature(
                get_op_handler(operation)))
 def description_loader():
     return extract_full_summary_from_signature(get_op_handler(operation))
예제 #4
0
    def __init__(self, module_name, name, operation, factory, transform_result,  # pylint:disable=too-many-arguments
                 table_transformer, flatten, ignore, validator, silent):

        if not isinstance(operation, string_types):
            raise ValueError("Operation must be a string. Got '{}'".format(operation))

        self.flatten = flatten  # Number of object levels to flatten
        self.silent = silent if silent else []
        self.ignore = list(IGNORE_PARAMETERS)  # Parameters to ignore
        if ignore:
            self.ignore.extend(ignore)
        self.parser = None
        self.validator = validator
        self.confirmation = 'delete' in operation

        # The name of the request options parameter
        self._options_param = format_options_name(operation)
        # Arguments used for request options
        self._options_attrs = []
        # The loaded options model to populate for the request
        self._options_model = None

        def _execute_command(kwargs):
            from msrest.paging import Paged
            from msrest.exceptions import ValidationError, ClientRequestError
            from azure.batch.models import BatchErrorException
            from azure.cli.core._util import CLIError
            from azure.cli.core._config import az_config
            from azure.cli.core.commands import _user_confirmed

            if self._cancel_operation(kwargs, az_config, _user_confirmed):
                raise CLIError('Operation cancelled.')

            try:
                client = factory(kwargs)
                self._build_options(kwargs)

                stream_output = kwargs.pop('destination', None)
                json_file = kwargs.pop('json_file', None)

                # Build the request parameters from command line arguments
                if json_file:
                    self.parser.deserialize_json(client, kwargs, json_file)
                    for arg, _ in self.parser:
                        del kwargs[arg]
                else:
                    for arg, details in self.parser:
                        try:
                            param_value = kwargs.pop(arg)
                            if param_value is None:
                                continue
                            else:
                                self._build_parameters(
                                    details['path'],
                                    kwargs,
                                    details['root'],
                                    param_value)
                        except KeyError:
                            continue

                # Make request
                op = get_op_handler(operation)
                result = op(client, **kwargs)

                # File download
                if stream_output:
                    with open(stream_output, "wb") as file_handle:
                        for data in result:
                            file_handle.write(data)
                    return

                # Apply results transform if specified
                elif transform_result:
                    return transform_result(result)

                # Otherwise handle based on return type of results
                elif isinstance(result, Paged):
                    return list(result)
                else:
                    return result
            except BatchErrorException as ex:
                try:
                    message = ex.error.message.value
                    if ex.error.values:
                        for detail in ex.error.values:
                            message += "\n{}: {}".format(detail.key, detail.value)
                    raise CLIError(message)
                except AttributeError:
                    raise CLIError(ex)
            except (ValidationError, ClientRequestError) as ex:
                raise CLIError(ex)

        command_module_map[name] = module_name
        self.cmd = CliCommand(
            ' '.join(name.split()),
            _execute_command,
            table_transformer=table_transformer,
            arguments_loader=lambda: self._load_transformed_arguments(
                get_op_handler(operation)),
            description_loader=lambda: extract_full_summary_from_signature(
                get_op_handler(operation))
        )
예제 #5
0
def _create_key_vault_command(module_name, name, operation, transform_result,
                              table_transformer):

    if not isinstance(operation, string_types):
        raise ValueError(
            "Operation must be a string. Got '{}'".format(operation))

    def _execute_command(kwargs):
        from msrest.paging import Paged
        from msrest.exceptions import ValidationError, ClientRequestError
        from msrestazure.azure_operation import AzureOperationPoller
        from azure.cli.core._profile import Profile
        from azure.cli.command_modules.keyvault.keyvaultclient import \
            (KeyVaultClient, KeyVaultAuthentication)
        from azure.cli.command_modules.keyvault.keyvaultclient.generated import \
            (KeyVaultClient as BaseKeyVaultClient)
        from azure.cli.command_modules.keyvault.keyvaultclient.generated.models import \
            (KeyVaultErrorException)

        try:

            def get_token(server, resource, scope):  # pylint: disable=unused-argument
                return Profile().get_login_credentials(
                    resource)[0]._token_retriever()  # pylint: disable=protected-access

            op = get_op_handler(operation)
            # since the convenience client can be inconvenient, we have to check and create the
            # correct client version
            if 'generated' in op.__module__:
                client = BaseKeyVaultClient(KeyVaultAuthentication(get_token))
            else:
                client = KeyVaultClient(KeyVaultAuthentication(get_token))  # pylint: disable=redefined-variable-type
            result = op(client, **kwargs)

            # apply results transform if specified
            if transform_result:
                return _encode_hex(transform_result(result))

            # otherwise handle based on return type of results
            if isinstance(result, AzureOperationPoller):
                return _encode_hex(
                    LongRunningOperation('Starting {}'.format(name))(result))
            elif isinstance(result, Paged):
                try:
                    return _encode_hex(list(result))
                except TypeError:
                    # TODO: Workaround for an issue in either KeyVault server-side or msrest
                    # See https://github.com/Azure/autorest/issues/1309
                    return []
            else:
                return _encode_hex(result)
        except (ValidationError, KeyVaultErrorException) as ex:
            try:
                raise CLIError(ex.inner_exception.error.message)
            except AttributeError:
                raise CLIError(ex)
        except ClientRequestError as ex:
            if 'Failed to establish a new connection' in str(
                    ex.inner_exception):
                raise CLIError(
                    'Max retries exceeded attempting to connect to vault. '
                    'The vault may not exist or you may need to flush your DNS cache '
                    'and try again later.')
            raise CLIError(ex)

    command_module_map[name] = module_name
    name = ' '.join(name.split())
    arguments_loader = lambda: extract_args_from_signature(
        get_op_handler(operation))
    description_loader = lambda: extract_full_summary_from_signature(
        get_op_handler(operation))
    cmd = CliCommand(name,
                     _execute_command,
                     table_transformer=table_transformer,
                     arguments_loader=arguments_loader,
                     description_loader=description_loader)
    return cmd
예제 #6
0
 def description_loader():
     return extract_full_summary_from_signature(get_op_handler(operation))
예제 #7
0
def _create_key_vault_command(module_name, name, operation, transform_result, table_transformer):

    if not isinstance(operation, string_types):
        raise ValueError("Operation must be a string. Got '{}'".format(operation))

    def _execute_command(kwargs):
        from msrest.paging import Paged
        from msrest.exceptions import ValidationError, ClientRequestError
        from msrestazure.azure_operation import AzureOperationPoller
        from azure.cli.core._profile import Profile
        from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
        from azure.keyvault.generated import KeyVaultClient as BaseKeyVaultClient
        from azure.keyvault.generated.models import KeyVaultErrorException

        try:

            def get_token(server, resource, scope):  # pylint: disable=unused-argument
                try:
                    return (
                        Profile().get_login_credentials(resource)[0]._token_retriever()
                    )  # pylint: disable=protected-access
                except adal.AdalError as err:
                    # pylint: disable=no-member
                    if (
                        hasattr(err, "error_response")
                        and ("error_description" in err.error_response)
                        and ("AADSTS70008:" in err.error_response["error_description"])
                    ):
                        raise CLIError("Credentials have expired due to inactivity. Please run 'az login'")
                    raise CLIError(err)

            op = get_op_handler(operation)
            # since the convenience client can be inconvenient, we have to check and create the
            # correct client version
            if "generated" in op.__module__:
                client = BaseKeyVaultClient(KeyVaultAuthentication(get_token))
            else:
                client = KeyVaultClient(KeyVaultAuthentication(get_token))  # pylint: disable=redefined-variable-type
            result = op(client, **kwargs)

            # apply results transform if specified
            if transform_result:
                return _encode_hex(transform_result(result))

            # otherwise handle based on return type of results
            if isinstance(result, AzureOperationPoller):
                return _encode_hex(LongRunningOperation("Starting {}".format(name))(result))
            elif isinstance(result, Paged):
                try:
                    return _encode_hex(list(result))
                except TypeError:
                    # TODO: Workaround for an issue in either KeyVault server-side or msrest
                    # See https://github.com/Azure/autorest/issues/1309
                    return []
            else:
                return _encode_hex(result)
        except (ValidationError, KeyVaultErrorException) as ex:
            try:
                raise CLIError(ex.inner_exception.error.message)
            except AttributeError:
                raise CLIError(ex)
        except ClientRequestError as ex:
            if "Failed to establish a new connection" in str(ex.inner_exception):
                raise CLIError(
                    "Max retries exceeded attempting to connect to vault. "
                    "The vault may not exist or you may need to flush your DNS cache "
                    "and try again later."
                )
            raise CLIError(ex)

    command_module_map[name] = module_name
    name = " ".join(name.split())
    arguments_loader = lambda: extract_args_from_signature(get_op_handler(operation))
    description_loader = lambda: extract_full_summary_from_signature(get_op_handler(operation))
    cmd = CliCommand(
        name,
        _execute_command,
        table_transformer=table_transformer,
        arguments_loader=arguments_loader,
        description_loader=description_loader,
    )
    return cmd