Exemple #1
0
    def __init__(self, **kwargs):
        super(AzCli, self).__init__(**kwargs)

        from azure.cli.core.commands.arm import (
            register_ids_argument, register_global_subscription_argument)
        from azure.cli.core.cloud import get_active_cloud
        from azure.cli.core.commands.transform import register_global_transforms
        from azure.cli.core._session import ACCOUNT, CONFIG, SESSION

        from knack.util import ensure_dir

        self.data['headers'] = {}
        self.data['command'] = 'unknown'
        self.data['command_extension_name'] = None
        self.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
        self.data['query_active'] = False

        azure_folder = self.config.config_dir
        ensure_dir(azure_folder)
        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
        CONFIG.load(os.path.join(azure_folder, 'az.json'))
        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
        self.cloud = get_active_cloud(self)
        logger.debug('Current cloud config:\n%s', str(self.cloud.name))

        register_global_transforms(self)
        register_global_subscription_argument(self)
        register_ids_argument(self)  # global subscription must be registered first!

        self.progress_controller = None
Exemple #2
0
    def _init_command_logfile_handlers(self, command_metadata_logger, args):

        ensure_dir(self.command_log_dir)
        command = self.cli_ctx.invocation._rudimentary_get_command(args) or _UNKNOWN_COMMAND  # pylint: disable=protected-access, line-too-long
        command_str = command.replace(" ", "_")
        if command_str.lower() == "feedback":
            return

        date_str = str(datetime.datetime.now().date())
        time = datetime.datetime.now().time()
        time_str = "{:02}-{:02}-{:02}".format(time.hour, time.minute, time.second)

        log_name = "{}.{}.{}.{}.{}".format(date_str, time_str, command_str, os.getpid(), "log")

        log_file_path = os.path.join(self.command_log_dir, log_name)

        logfile_handler = logging.FileHandler(log_file_path)

        lfmt = logging.Formatter(_CMD_LOG_LINE_PREFIX + ' %(process)d | %(asctime)s | %(levelname)s | %(name)s | %(message)s')  # pylint: disable=line-too-long
        logfile_handler.setFormatter(lfmt)
        logfile_handler.setLevel(logging.DEBUG)
        command_metadata_logger.addHandler(logfile_handler)

        self.command_logger_handler = logfile_handler
        self.command_metadata_logger = command_metadata_logger

        args = AzCliLogging._get_clean_args(command if command != _UNKNOWN_COMMAND else None, args)
        command_metadata_logger.info("command args: %s", " ".join(args))
Exemple #3
0
    def __init__(self, **kwargs):
        super(AzCli, self).__init__(**kwargs)

        from azure.cli.core.commands import register_cache_arguments
        from azure.cli.core.commands.arm import (
            register_ids_argument, register_global_subscription_argument)
        from azure.cli.core.cloud import get_active_cloud
        from azure.cli.core.commands.transform import register_global_transforms
        from azure.cli.core._session import ACCOUNT, CONFIG, SESSION, INDEX, VERSIONS
        from azure.cli.core.util import handle_version_update
        from azure.cli.core.commands.query_examples import register_global_query_examples_argument

        from knack.util import ensure_dir

        self.data['headers'] = {}
        self.data['command'] = 'unknown'
        self.data['command_extension_name'] = None
        self.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
        self.data['query_active'] = False

        azure_folder = self.config.config_dir
        ensure_dir(azure_folder)
        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
        CONFIG.load(os.path.join(azure_folder, 'az.json'))
        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
        INDEX.load(os.path.join(azure_folder, 'commandIndex.json'))
        VERSIONS.load(os.path.join(azure_folder, 'versionCheck.json'))
        handle_version_update()

        self.cloud = get_active_cloud(self)
        logger.debug('Current cloud config:\n%s', str(self.cloud.name))
        self.local_context = AzCLILocalContext(self)
        register_global_transforms(self)
        register_global_subscription_argument(self)
        register_global_query_examples_argument(self)
        register_ids_argument(self)  # global subscription must be registered first!
        register_cache_arguments(self)

        self.progress_controller = None
Exemple #4
0
def _get_extension():
    # try to get from cache
    ensure_dir(GLOBAL_CONFIG_DIR)
    path_cache = os.path.join(GLOBAL_CONFIG_DIR, __CACHE_FILE_NAME)
    SESSION.data = {}
    SESSION.load(path_cache)
    query_extension = SESSION.data.get(__CACHE_KEY)

    # if cache is older than 1 day, we don't want to use it
    if datetime.utcnow() - datetime.utcfromtimestamp(os.path.getmtime(path_cache)) < timedelta(days=1) \
            and query_extension is not None:
        return query_extension

    queries_parts = []
    subscription_list = _get_cached_detailed_subscriptions()
    if subscription_list:
        sub_query = "extend subscriptionDisplayName=case("
        for sub in subscription_list:
            sub_query += "subscriptionId=='" + sub[0] + "', '" + sub[1] + "',"
        sub_query += "'')"
        queries_parts.append(sub_query)

    tenant_list = _get_cached_detailed_tenant()
    if tenant_list:
        tenant_query = "extend tenantDisplayName=case("
        for tenant in tenant_list:
            tenant_query += "tenantId=='" + tenant[0] + "', '" + tenant[
                1] + "',"
        tenant_query += "'')"
        queries_parts.append(tenant_query)

    query_extension = "| ".join(queries_parts)

    # save to cache
    SESSION.filename = path_cache
    SESSION.data.update({__CACHE_KEY: query_extension})
    SESSION.save()
    return query_extension
Exemple #5
0
    def _init_command_logfile_handlers(self, command_metadata_logger, args):

        ensure_dir(self.command_log_dir)
        command = self.cli_ctx.invocation._rudimentary_get_command(
            args) or _UNKNOWN_COMMAND  # pylint: disable=protected-access, line-too-long
        command_str = command.replace(" ", "_")
        if command_str.lower() == "feedback":
            return

        date_str = str(datetime.datetime.now().date())
        time = datetime.datetime.now().time()
        time_str = "{:02}-{:02}-{:02}".format(time.hour, time.minute,
                                              time.second)

        log_name = "{}.{}.{}.{}.{}".format(date_str, time_str, command_str,
                                           os.getpid(), "log")

        log_file_path = os.path.join(self.command_log_dir, log_name)
        get_logger(__name__).debug(
            "metadata file logging enabled - writing logs to '%s'.",
            log_file_path)

        logfile_handler = logging.FileHandler(log_file_path,
                                              encoding=LOG_FILE_ENCODING)

        lfmt = logging.Formatter(_CMD_LOG_LINE_PREFIX + ' %(process)d | %(asctime)s | %(levelname)s | %(name)s | %(message)s')  # pylint: disable=line-too-long
        logfile_handler.setFormatter(lfmt)
        logfile_handler.setLevel(logging.DEBUG)
        # command_metadata_logger should always accept all levels regardless of the root logger level.
        command_metadata_logger.setLevel(logging.DEBUG)
        command_metadata_logger.addHandler(logfile_handler)

        self.command_logger_handler = logfile_handler
        self.command_metadata_logger = command_metadata_logger

        args = AzCliLogging._get_clean_args(
            command if command != _UNKNOWN_COMMAND else None, args)
        command_metadata_logger.info("command args: %s", " ".join(args))
Exemple #6
0
    def get_password(self, key):
        try:
            import keyring
        except ImportError:
            return None

        try:
            return keyring.get_password(key, self._USERNAME)
        except RuntimeError as ex:
            # fetch credentials from file if keyring is missing
            if sys.platform.startswith(self._LINUX_PLATFORM):
                ensure_dir(AZ_DEVOPS_GLOBAL_CONFIG_DIR)
                logger.debug(
                    'Keyring package not found. Fetching credentials from the file: %s',
                    self._PAT_FILE)
                creds_list = self._get_credentials_list()
                try:
                    return creds_list.get(key, self._USERNAME)
                except (configparser.NoOptionError,
                        configparser.NoSectionError):
                    return None
            else:
                raise CLIError(ex)
Exemple #7
0
def _get_cache_dir():
    azdevops_config_dir = (os.getenv('AZURE_DEVOPS_CACHE_DIR', None) or
                           os.path.join(AZ_DEVOPS_GLOBAL_CONFIG_DIR, 'cache'))
    ensure_dir(azdevops_config_dir)
    return azdevops_config_dir
def _get_config_dir():
    azure_devops_config_dir = os.getenv(AZ_DEVOPS_CONFIG_DIR_ENVKEY,
                                        None) or AZ_DEVOPS_DEFAULT_CONFIG_DIR
    # Create a directory if it doesn't exist
    ensure_dir(azure_devops_config_dir)
    return azure_devops_config_dir