Exemple #1
0
class AzRotatingFileHandler(logging.handlers.RotatingFileHandler):
    from azure.cli.core._environment import get_config_dir
    from azure.cli.core._config import az_config

    ENABLED = az_config.getboolean('logging',
                                   'enable_log_file',
                                   fallback=False)
    LOGFILE_DIR = os.path.expanduser(
        az_config.get('logging',
                      'log_dir',
                      fallback=os.path.join(get_config_dir(), 'logs')))

    def __init__(self):
        logging_file_path = self.get_log_file_path()
        super(AzRotatingFileHandler, self).__init__(logging_file_path,
                                                    maxBytes=10 * 1024 * 1024,
                                                    backupCount=5)
        self.setFormatter(
            logging.Formatter(
                '%(process)d : %(asctime)s : %(levelname)s : %(name)s : %(message)s'
            ))
        self.setLevel(logging.DEBUG)

    def get_log_file_path(self):
        if not os.path.isdir(self.LOGFILE_DIR):
            os.makedirs(self.LOGFILE_DIR)
        return os.path.join(self.LOGFILE_DIR, 'az.log')
Exemple #2
0
    def _execute_command(kwargs):
        if confirmation \
            and not kwargs.get(CONFIRM_PARAM_NAME) \
            and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
                and not _user_confirmed(confirmation, kwargs):
            raise CLIError('Operation cancelled.')

        client = client_factory(kwargs) if client_factory else None
        try:
            op = get_op_handler(operation)
            try:
                result = op(client, **kwargs) if client else op(**kwargs)
                if no_wait_param and kwargs.get(no_wait_param, None):
                    return None  # return None for 'no-wait'

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

                # otherwise handle based on return type of results
                if _is_poller(result):
                    return LongRunningOperation(
                        'Starting {}'.format(name))(result)
                elif _is_paged(result):
                    return list(result)
                return result
            except Exception as ex:  # pylint: disable=broad-except
                if exception_handler:
                    exception_handler(ex)
                else:
                    reraise(*sys.exc_info())
        except _load_validation_error_class() as validation_error:
            fault_type = name.replace(' ', '-') + '-validation-error'
            telemetry.set_exception(validation_error,
                                    fault_type=fault_type,
                                    summary='SDK validation error')
            raise CLIError(validation_error)
        except _load_client_exception_class() as client_exception:
            fault_type = name.replace(' ', '-') + '-client-error'
            telemetry.set_exception(
                client_exception,
                fault_type=fault_type,
                summary='Unexpected client exception during command creation')
            raise client_exception
        except _load_azure_exception_class() as azure_exception:
            fault_type = name.replace(' ', '-') + '-service-error'
            telemetry.set_exception(
                azure_exception,
                fault_type=fault_type,
                summary='Unexpected azure exception during command creation')
            message = re.search(r"([A-Za-z\t .])+", str(azure_exception))
            raise CLIError('\n{}'.format(
                message.group(0) if message else str(azure_exception)))
        except ValueError as value_error:
            fault_type = name.replace(' ', '-') + '-value-error'
            telemetry.set_exception(
                value_error,
                fault_type=fault_type,
                summary='Unexpected value exception during command creation')
            raise CLIError(value_error)
Exemple #3
0
    def _execute_command(kwargs):
        from msrest.paging import Paged
        from msrest.exceptions import ClientException
        from msrestazure.azure_operation import AzureOperationPoller
        from azure.common import AzureException

        if confirmation \
            and not kwargs.get(CONFIRM_PARAM_NAME) \
            and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
                and not _user_confirmed(confirmation, kwargs):
            raise CLIError('Operation cancelled.')

        client = client_factory(kwargs) if client_factory else None
        try:
            op = get_op_handler(operation)
            result = op(client, **kwargs) if client else op(**kwargs)

            if no_wait_param and kwargs.get(no_wait_param, None):
                return None  # return None for 'no-wait'

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

            # otherwise handle based on return type of results
            if isinstance(result, AzureOperationPoller):
                return LongRunningOperation('Starting {}'.format(name))(result)
            elif isinstance(result, Paged):
                return list(result)
            else:
                return result
        except ClientException as client_exception:
            fault_type = name.replace(' ', '-') + '-client-error'
            telemetry.set_exception(
                client_exception,
                fault_type=fault_type,
                summary='Unexpected client exception during command creation')
            message = getattr(client_exception, 'message', client_exception)
            raise _polish_rp_not_registerd_error(CLIError(message))
        except AzureException as azure_exception:
            fault_type = name.replace(' ', '-') + '-service-error'
            telemetry.set_exception(
                azure_exception,
                fault_type=fault_type,
                summary='Unexpected azure exception during command creation')
            message = re.search(r"([A-Za-z\t .])+", str(azure_exception))
            raise CLIError('\n{}'.format(
                message.group(0) if message else str(azure_exception)))
        except ValueError as value_error:
            fault_type = name.replace(' ', '-') + '-value-error'
            telemetry.set_exception(
                value_error,
                fault_type=fault_type,
                summary='Unexpected value exception during command creation')
            raise CLIError(value_error)
        except CLIError as cli_error:
            raise _polish_rp_not_registerd_error(cli_error)
Exemple #4
0
    def firsttime(self):
        """ sets it as already done"""
        self.config.set('DEFAULT', 'firsttime', 'no')
        if az_config.getboolean('core', 'collect_telemetry', fallback=False):
            print(PRIVACY_STATEMENT)
        else:
            set_global_config_value('core', 'collect_telemetry', ask_user_for_telemetry())

        self.update()
    def firsttime(self):
        """ sets it as already done"""
        self.config.set('DEFAULT', 'firsttime', 'no')
        if az_config.getboolean('core', 'collect_telemetry', fallback=False):
            print(PRIVACY_STATEMENT)
        else:
            set_global_config_value('core', 'collect_telemetry', ask_user_for_telemetry())

        self.update()
Exemple #6
0
    def _execute_command(kwargs):
        if confirmation \
            and not kwargs.get(CONFIRM_PARAM_NAME) \
            and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
                and not _user_confirmed(confirmation, kwargs):
            raise CLIError('Operation cancelled.')

        client = client_factory(kwargs) if client_factory else None
        try:
            op = get_op_handler(operation)
            for _ in range(2):  # for possible retry, we do maximum 2 times.
                try:
                    result = op(client, **kwargs) if client else op(**kwargs)
                    if no_wait_param and kwargs.get(no_wait_param, None):
                        return None  # return None for 'no-wait'

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

                    # otherwise handle based on return type of results
                    if _is_poller(result):
                        return LongRunningOperation('Starting {}'.format(name))(result)
                    elif _is_paged(result):
                        return list(result)
                    return result
                except Exception as ex:  # pylint: disable=broad-except
                    rp = _check_rp_not_registered_err(ex)
                    if rp:
                        _register_rp(rp)
                        continue  # retry
                    if exception_handler:
                        exception_handler(ex)
                        return
                    else:
                        reraise(*sys.exc_info())
        except _load_validation_error_class() as validation_error:
            fault_type = name.replace(' ', '-') + '-validation-error'
            telemetry.set_exception(validation_error, fault_type=fault_type,
                                    summary='SDK validation error')
            raise CLIError(validation_error)
        except _load_client_exception_class() as client_exception:
            fault_type = name.replace(' ', '-') + '-client-error'
            telemetry.set_exception(client_exception, fault_type=fault_type,
                                    summary='Unexpected client exception during command creation')
            raise client_exception
        except _load_azure_exception_class() as azure_exception:
            fault_type = name.replace(' ', '-') + '-service-error'
            telemetry.set_exception(azure_exception, fault_type=fault_type,
                                    summary='Unexpected azure exception during command creation')
            message = re.search(r"([A-Za-z\t .])+", str(azure_exception))
            raise CLIError('\n{}'.format(message.group(0) if message else str(azure_exception)))
        except ValueError as value_error:
            fault_type = name.replace(' ', '-') + '-value-error'
            telemetry.set_exception(value_error, fault_type=fault_type,
                                    summary='Unexpected value exception during command creation')
            raise CLIError(value_error)
Exemple #7
0
    def _execute_command(kwargs):
        from msrest.paging import Paged
        from msrest.exceptions import ClientException
        from msrestazure.azure_operation import AzureOperationPoller
        from azure.common import AzureException

        if confirmation \
            and not kwargs.get(CONFIRM_PARAM_NAME) \
            and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
                and not _user_confirmed(confirmation, kwargs):
            raise CLIError('Operation cancelled.')

        client = client_factory(kwargs) if client_factory else None
        try:
            op = get_op_handler(operation)
            try:
                result = op(client, **kwargs) if client else op(**kwargs)
            except Exception as ex:  # pylint: disable=broad-except
                if exception_handler:
                    result = exception_handler(ex)
                else:
                    raise ex

            if no_wait_param and kwargs.get(no_wait_param, None):
                return None  # return None for 'no-wait'

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

            # otherwise handle based on return type of results
            if isinstance(result, AzureOperationPoller):
                return LongRunningOperation('Starting {}'.format(name))(result)
            elif isinstance(result, Paged):
                return list(result)
            else:
                return result
        except ClientException as client_exception:
            fault_type = name.replace(' ', '-') + '-client-error'
            telemetry.set_exception(client_exception, fault_type=fault_type,
                                    summary='Unexpected client exception during command creation')
            message = getattr(client_exception, 'message', client_exception)
            raise _polish_rp_not_registerd_error(CLIError(message))
        except AzureException as azure_exception:
            fault_type = name.replace(' ', '-') + '-service-error'
            telemetry.set_exception(azure_exception, fault_type=fault_type,
                                    summary='Unexpected azure exception during command creation')
            message = re.search(r"([A-Za-z\t .])+", str(azure_exception))
            raise CLIError('\n{}'.format(message.group(0) if message else str(azure_exception)))
        except ValueError as value_error:
            fault_type = name.replace(' ', '-') + '-value-error'
            telemetry.set_exception(value_error, fault_type=fault_type,
                                    summary='Unexpected value exception during command creation')
            raise CLIError(value_error)
        except CLIError as cli_error:
            raise _polish_rp_not_registerd_error(cli_error)
# --------------------------------------------------------------------------------------------

import os
import platform
import logging
from logging.handlers import RotatingFileHandler

import colorama

from azure.cli.core._environment import get_config_dir
from azure.cli.core._config import az_config

AZ_LOGFILE_NAME = 'az.log'
DEFAULT_LOG_DIR = os.path.join(get_config_dir(), 'logs')

ENABLE_LOG_FILE = az_config.getboolean('logging', 'enable_log_file', fallback=False)
LOG_DIR = os.path.expanduser(az_config.get('logging', 'log_dir', fallback=DEFAULT_LOG_DIR))

CONSOLE_LOG_CONFIGS = [
    # (default)
    {
        'az': logging.WARNING,
        'root': logging.CRITICAL,
    },
    # --verbose
    {
        'az': logging.INFO,
        'root': logging.CRITICAL,
    },
    # --debug
    {
Exemple #9
0
    def handler(args):  # pylint: disable=too-many-branches,too-many-statements
        from msrestazure.azure_operation import AzureOperationPoller

        if confirmation \
            and not args.items().get(CONFIRM_PARAM_NAME) \
            and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
                and not _user_confirmed(confirmation, args.items()):
            raise CLIError('Operation cancelled.')

        ordered_arguments = args.pop('ordered_arguments', [])
        for item in [
                'properties_to_add', 'properties_to_set',
                'properties_to_remove'
        ]:
            if args[item]:
                raise CLIError("Unexpected '{}' was not empty.".format(item))
            del args[item]

        try:
            client = factory() if factory else None
        except TypeError:
            client = factory(None) if factory else None

        getterargs = {
            key: val
            for key, val in args.items() if key in get_arguments_loader()
        }
        getter = get_op_handler(getter_op)
        try:
            if child_collection_prop_name:
                parent = getter(client, **getterargs) if client else getter(
                    **getterargs)
                instance = _get_child(parent, child_collection_prop_name,
                                      args.get(child_arg_name),
                                      child_collection_key)
            else:
                parent = None
                instance = getter(client, **getterargs) if client else getter(
                    **getterargs)

            # pass instance to the custom_function, if provided
            if custom_function_op:
                custom_function = get_op_handler(custom_function_op)
                custom_func_args = \
                    {k: v for k, v in args.items() if k in function_arguments_loader()}
                if child_collection_prop_name:
                    parent = custom_function(instance, parent,
                                             **custom_func_args)
                else:
                    instance = custom_function(instance, **custom_func_args)

            # apply generic updates after custom updates
            setterargs = {
                key: val
                for key, val in args.items() if key in set_arguments_loader()
            }

            for arg in ordered_arguments:
                arg_type, arg_values = arg
                if arg_type == '--set':
                    try:
                        for expression in arg_values:
                            set_properties(instance, expression)
                    except ValueError:
                        raise CLIError('invalid syntax: {}'.format(set_usage))
                elif arg_type == '--add':
                    try:
                        add_properties(instance, arg_values)
                    except ValueError:
                        raise CLIError('invalid syntax: {}'.format(add_usage))
                elif arg_type == '--remove':
                    try:
                        remove_properties(instance, arg_values)
                    except ValueError:
                        raise CLIError(
                            'invalid syntax: {}'.format(remove_usage))

            # Done... update the instance!
            setterargs[
                setter_arg_name] = parent if child_collection_prop_name else instance
            setter = get_op_handler(setter_op)

            opres = setter(client, **setterargs) if client else setter(
                **setterargs)

            if setterargs.get(no_wait_param, None):
                return None

            result = opres.result() if isinstance(
                opres, AzureOperationPoller) else opres
            if child_collection_prop_name:
                result = _get_child(result, child_collection_prop_name,
                                    args.get(child_arg_name),
                                    child_collection_key)
        except Exception as ex:  # pylint: disable=broad-except
            if exception_handler:
                result = exception_handler(ex)
            else:
                raise ex

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

        return result
Exemple #10
0
 def has_feedback(self):
     """ returns whether user has given feedback """
     return az_config.getboolean('core', 'given feedback', fallback='false')
Exemple #11
0
import os
import platform
import logging
from logging.handlers import RotatingFileHandler

import colorama

from azure.cli.core._environment import get_config_dir
from azure.cli.core._config import az_config

AZ_LOGFILE_NAME = 'az.log'
DEFAULT_LOG_DIR = os.path.join(get_config_dir(), 'logs')

ENABLE_LOG_FILE = az_config.getboolean('logging',
                                       'enable_log_file',
                                       fallback=False)
LOG_DIR = os.path.expanduser(
    az_config.get('logging', 'log_dir', fallback=DEFAULT_LOG_DIR))

CONSOLE_LOG_CONFIGS = [
    # (default)
    {
        'az': logging.WARNING,
        'root': logging.CRITICAL,
    },
    # --verbose
    {
        'az': logging.INFO,
        'root': logging.CRITICAL,
    },
Exemple #12
0
 def has_feedback(self):
     """ returns whether user has given feedback """
     return az_config.getboolean('core', 'given feedback', fallback='false')
Exemple #13
0
    def handler(args):  # pylint: disable=too-many-branches,too-many-statements
        from msrestazure.azure_operation import AzureOperationPoller

        if confirmation \
            and not args.items().get(CONFIRM_PARAM_NAME) \
            and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
                and not _user_confirmed(confirmation, args.items()):
            raise CLIError('Operation cancelled.')

        ordered_arguments = args.pop('ordered_arguments', [])
        for item in ['properties_to_add', 'properties_to_set', 'properties_to_remove']:
            if args[item]:
                raise CLIError("Unexpected '{}' was not empty.".format(item))
            del args[item]

        try:
            client = factory() if factory else None
        except TypeError:
            client = factory(None) if factory else None

        getterargs = {key: val for key, val in args.items() if key in get_arguments_loader()}
        getter = get_op_handler(getter_op)
        try:
            if child_collection_prop_name:
                parent = getter(client, **getterargs) if client else getter(**getterargs)
                instance = _get_child(
                    parent,
                    child_collection_prop_name,
                    args.get(child_arg_name),
                    child_collection_key
                )
            else:
                parent = None
                instance = getter(client, **getterargs) if client else getter(**getterargs)

            # pass instance to the custom_function, if provided
            if custom_function_op:
                custom_function = get_op_handler(custom_function_op)
                custom_func_args = \
                    {k: v for k, v in args.items() if k in function_arguments_loader()}
                if child_collection_prop_name:
                    parent = custom_function(instance, parent, **custom_func_args)
                else:
                    instance = custom_function(instance, **custom_func_args)

            # apply generic updates after custom updates
            setterargs = {key: val for key, val in args.items() if key in set_arguments_loader()}

            for arg in ordered_arguments:
                arg_type, arg_values = arg
                if arg_type == '--set':
                    try:
                        for expression in arg_values:
                            set_properties(instance, expression)
                    except ValueError:
                        raise CLIError('invalid syntax: {}'.format(set_usage))
                elif arg_type == '--add':
                    try:
                        add_properties(instance, arg_values)
                    except ValueError:
                        raise CLIError('invalid syntax: {}'.format(add_usage))
                elif arg_type == '--remove':
                    try:
                        remove_properties(instance, arg_values)
                    except ValueError:
                        raise CLIError('invalid syntax: {}'.format(remove_usage))

            # Done... update the instance!
            setterargs[setter_arg_name] = parent if child_collection_prop_name else instance
            setter = get_op_handler(setter_op)

            opres = setter(client, **setterargs) if client else setter(**setterargs)

            if setterargs.get(no_wait_param, None):
                return None

            result = opres.result() if isinstance(opres, AzureOperationPoller) else opres
            if child_collection_prop_name:
                result = _get_child(
                    result,
                    child_collection_prop_name,
                    args.get(child_arg_name),
                    child_collection_key
                )
        except Exception as ex:  # pylint: disable=broad-except
            if exception_handler:
                result = exception_handler(ex)
            else:
                raise ex

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

        return result
Exemple #14
0
def user_agrees_to_telemetry():
    return az_config.getboolean('core', 'collect_telemetry', fallback=True)
Exemple #15
0
def user_agrees_to_telemetry():
    return az_config.getboolean('core', 'collect_telemetry', fallback=True)
def show_privacy_statement():
    from azure.cli.core._config import az_config, set_global_config_value
    first_ran = az_config.getboolean('core', 'first_run', fallback=False)
    if not first_ran:
        print(PRIVACY_STATEMENT, file=sys.stdout)
        set_global_config_value('core', 'first_run', 'yes')
Exemple #17
0
def show_privacy_statement():
    from azure.cli.core._config import az_config, set_global_config_value
    first_ran = az_config.getboolean('core', 'first_run', fallback=False)
    if not first_ran:
        print(PRIVACY_STATEMENT, file=sys.stdout)
        set_global_config_value('core', 'first_run', 'yes')