def main(args, file=sys.stdout):  # pylint: disable=redefined-builtin
    azlogging.configure_logging(args)
    logger.debug('Command arguments %s', args)

    if len(args) > 0 and args[0] == '--version':
        show_version_info_exit(file)

    azure_folder = get_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(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)

    APPLICATION.initialize(Configuration())

    try:
        cmd_result = APPLICATION.execute(args)

        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result is not None:
            from azure.cli.core._output import OutputProducer
            formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=file).out(cmd_result)

    except Exception as ex:  # pylint: disable=broad-except

        # TODO: include additional details of the exception in telemetry
        telemetry.set_exception(ex, 'outer-exception',
                                'Unexpected exception caught during application execution.')
        telemetry.set_failure()

        error_code = handle_exception(ex)
        return error_code
 def __init__(self, auth_ctx_factory=None):
     # AZURE_ACCESS_TOKEN_FILE is used by Cloud Console and not meant to be user configured
     self._token_file = (os.environ.get('AZURE_ACCESS_TOKEN_FILE', None) or
                         os.path.join(get_config_dir(), 'accessTokens.json'))
     self._service_principal_creds = []
     self._auth_ctx_factory = auth_ctx_factory or _AUTH_CTX_FACTORY
     self.adal_token_cache = None
     self._load_creds()
Example #3
0
def flush():
    from azure.cli.core._environment import get_config_dir
    from azure.cli.telemetry import save

    # flush out current information
    _session.end_time = datetime.datetime.utcnow()
    save(get_config_dir(), _session.generate_payload())

    # reset session fields, retaining correlation id and application
    _session.__init__(correlation_id=_session.correlation_id, application=_session.application)
Example #4
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)

            if args and args[0] == 'feedback':
                self.config.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(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)

            invocation = self.cli_ctx.invocation_cls(cli_ctx=self.cli_ctx,
                                                     parser_cls=self.cli_ctx.parser_cls,
                                                     commands_loader_cls=self.cli_ctx.commands_loader_cls,
                                                     help_cls=self.cli_ctx.help_cls)

            if '--progress' in args:
                args.remove('--progress')
                execute_args = [args]
                thread = Thread(target=invocation.execute, args=execute_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                progress_args = [self]
                thread = Thread(target=progress_view, args=progress_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None
            else:
                result = invocation.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(self.cli_ctx.invocation.data['output'])
                    OutputProducer(formatter=formatter).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
Example #5
0
 def __init__(self, auth_ctx_factory=None, async_persist=True):
     # AZURE_ACCESS_TOKEN_FILE is used by Cloud Console and not meant to be user configured
     self._token_file = (os.environ.get('AZURE_ACCESS_TOKEN_FILE', None) or
                         os.path.join(get_config_dir(), 'accessTokens.json'))
     self._service_principal_creds = []
     self._auth_ctx_factory = auth_ctx_factory
     self._adal_token_cache_attr = None
     self._should_flush_to_disk = False
     self._async_persist = async_persist
     if async_persist:
         import atexit
         atexit.register(self.flush_to_disk)
Example #6
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            if len(args) > 0 and args[0] == 'feedback':
                SHELL_CONFIGURATION.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(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.app.initialize(Configuration())

            if '--progress' in args:
                args.remove('--progress')
                thread = ExecuteThread(self.app.execute, args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                thread = ProgressViewThread(progress_view, self)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None

            else:
                result = self.app.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter, file=self.output).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
Example #7
0
 def __init__(self, cli_ctx, auth_ctx_factory=None, async_persist=True):
     # AZURE_ACCESS_TOKEN_FILE is used by Cloud Console and not meant to be user configured
     self._token_file = (os.environ.get('AZURE_ACCESS_TOKEN_FILE', None)
                         or os.path.join(get_config_dir(),
                                         'accessTokens.json'))
     self._service_principal_creds = []
     self._auth_ctx_factory = auth_ctx_factory
     self._adal_token_cache_attr = None
     self._should_flush_to_disk = False
     self._async_persist = async_persist
     self._ctx = cli_ctx
     if async_persist:
         import atexit
         atexit.register(self.flush_to_disk)
Example #8
0
def _k8s_browse_internal(name, acs_info, disable_browser, ssh_key_file):
    if not which('kubectl'):
        raise CLIError('Can not find kubectl executable in PATH')
    browse_path = os.path.join(get_config_dir(), 'acsBrowseConfig.yaml')
    if os.path.exists(browse_path):
        os.remove(browse_path)

    _k8s_get_credentials_internal(name, acs_info, browse_path, ssh_key_file)

    logger.warning('Proxy running on 127.0.0.1:8001/ui')
    logger.warning('Press CTRL+C to close the tunnel...')
    if not disable_browser:
        wait_then_open_async('http://127.0.0.1:8001/ui')
    subprocess.call(["kubectl", "--kubeconfig", browse_path, "proxy"])
Example #9
0
def _k8s_browse_internal(name, acs_info, disable_browser, ssh_key_file):
    if not which('kubectl'):
        raise CLIError('Can not find kubectl executable in PATH')
    browse_path = os.path.join(get_config_dir(), 'acsBrowseConfig.yaml')
    if os.path.exists(browse_path):
        os.remove(browse_path)

    _k8s_get_credentials_internal(name, acs_info, browse_path, ssh_key_file)

    logger.warning('Proxy running on 127.0.0.1:8001/ui')
    logger.warning('Press CTRL+C to close the tunnel...')
    if not disable_browser:
        wait_then_open_async('http://127.0.0.1:8001/ui')
    subprocess.call(["kubectl", "--kubeconfig", browse_path, "proxy"])
Example #10
0
def store_acs_service_principal(subscription_id, client_secret, service_principal,
                                config_path=os.path.join(get_config_dir(),
                                                         'acsServicePrincipal.json')):
    obj = {}
    if client_secret:
        obj['client_secret'] = client_secret
    if service_principal:
        obj['service_principal'] = service_principal

    fullConfig = load_acs_service_principals(config_path=config_path)
    if not fullConfig:
        fullConfig = {}
    fullConfig[subscription_id] = obj

    with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600),
                   'w+') as spFile:
        json.dump(fullConfig, spFile)
Example #11
0
def show_updates_available(new_line_before=False, new_line_after=False):
    import os
    from azure.cli.core._session import VERSIONS
    import datetime
    from azure.cli.core._environment import get_config_dir

    VERSIONS.load(os.path.join(get_config_dir(), 'versionCheck.json'))
    if VERSIONS[_VERSION_CHECK_TIME]:
        version_check_time = datetime.datetime.strptime(VERSIONS[_VERSION_CHECK_TIME], '%Y-%m-%d %H:%M:%S.%f')
        if datetime.datetime.now() < version_check_time + datetime.timedelta(days=7):
            return

    _, updates_available = get_az_version_string(use_cache=True)
    if updates_available > 0:
        if new_line_before:
            logger.warning("")
        show_updates(updates_available)
        if new_line_after:
            logger.warning("")
    VERSIONS[_VERSION_CHECK_TIME] = str(datetime.datetime.now())
Example #12
0
def get_azure_cli_auth_token(resource):
    from adal import AuthenticationContext
    import os

    try:
        # this makes it cleaner, but in case azure cli is not present on virtual env,
        # but cli exists on computer, we can try and manually get the token from the cache
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir

        azure_folder = get_config_dir()
        ACCOUNT.load(os.path.join(azure_folder, "azureProfile.json"))
        profile = Profile(storage=ACCOUNT)
        token_data = profile.get_raw_token()[0][2]

        client_id = token_data["_clientId"]
        refresh_token = token_data["refreshToken"]

        logger.info(f"Found existing AZ CLI profile for {token_data[0]['userId']}")

    except ModuleNotFoundError:
        try:
            import os
            import json

            folder = os.getenv("AZURE_CONFIG_DIR", None) or os.path.expanduser(os.path.join("~", ".azure"))
            token_path = os.path.join(folder, "accessTokens.json")
            with open(token_path) as f:
                data = json.load(f)

            client_id = data[0]["_clientId"]
            refresh_token = data[0]["refreshToken"]

            logger.info(f"Found existing AZ CLI profile for {data[0]['userId']}")
        except Exception:
            return None

    return AuthenticationContext(f"https://login.microsoftonline.com/common").acquire_token_with_refresh_token(
        refresh_token, client_id, f"https://{resource}.kusto.windows.net"
    )["accessToken"]
Example #13
0
def get_cli_profile():
    """Return a CLI profile class.

    .. versionadded:: 1.1.6

    :return: A CLI Profile
    :rtype: azure.cli.core._profile.Profile
    :raises: ImportError if azure-cli-core package is not available
    """

    try:
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir
    except ImportError:
        raise ImportError(
            "You need to install 'azure-cli-core' to load CLI credentials")

    azure_folder = get_config_dir()
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    return Profile(storage=ACCOUNT)
Example #14
0
def get_cli_profile():
    """Return a CLI profile class.

    .. versionadded:: 1.1.6

    :return: A CLI Profile
    :rtype: azure.cli.core._profile.Profile
    :raises: ImportError if azure-cli-core package is not available
    """

    try:
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir
    except ImportError:
        raise ImportError("You need to install 'azure-cli-core' to load CLI credentials")


    azure_folder = get_config_dir()
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    return Profile(ACCOUNT)
Example #15
0
def main(args, output=sys.stdout, logging_stream=None):
    configure_logging(args, logging_stream)

    logger = get_az_logger(__name__)
    logger.debug('Command arguments %s', args)

    if args and (args[0] == '--version' or args[0] == '-v'):
        show_version_info_exit(output)

    azure_folder = get_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(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)

    APPLICATION.initialize(Configuration())

    try:
        cmd_result = APPLICATION.execute(args)

        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result is not None:
            from azure.cli.core._output import OutputProducer
            formatter = OutputProducer.get_formatter(
                APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=output).out(cmd_result)

    except Exception as ex:  # pylint: disable=broad-except

        # TODO: include additional details of the exception in telemetry
        telemetry.set_exception(
            ex, 'outer-exception',
            'Unexpected exception caught during application execution.')
        telemetry.set_failure()

        error_code = handle_exception(ex)
        return error_code
    def _get_azure_cli_auth_token() -> dict:
        """
        Try to get the az cli authenticated token
        :return: refresh token
        """
        import os

        try:
            # this makes it cleaner, but in case azure cli is not present on virtual env,
            # but cli exists on computer, we can try and manually get the token from the cache
            from azure.cli.core._profile import Profile
            from azure.cli.core._session import ACCOUNT
            from azure.cli.core._environment import get_config_dir

            azure_folder = get_config_dir()
            ACCOUNT.load(os.path.join(azure_folder, "azureProfile.json"))
            profile = Profile(storage=ACCOUNT)
            token_data = profile.get_raw_token()[0][2]

            return token_data

        except ModuleNotFoundError:
            try:
                import os
                import json

                folder = os.getenv("AZURE_CONFIG_DIR",
                                   None) or os.path.expanduser(
                                       os.path.join("~", ".azure"))
                token_path = os.path.join(folder, "accessTokens.json")
                with open(token_path) as f:
                    data = json.load(f)

                # TODO: not sure I should take the first
                return data[0]
            except Exception as e:
                raise KustoClientError(
                    "Azure cli token was not found. Please run 'az login' to setup account.",
                    e)
Example #17
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            if len(args) > 0 and args[0] == 'feedback':
                SHELL_CONFIGURATION.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(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)

            config = Configuration()
            self.app.initialize(config)

            result = self.app.execute(args)
            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.out(result)
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter,
                                   file=sys.stdout).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
Example #18
0
def get_cached_latest_versions(versions=None):
    """ Get the latest versions from a cached file"""
    import os
    import datetime
    from azure.cli.core._environment import get_config_dir
    from azure.cli.core._session import VERSIONS

    if not versions:
        versions = _get_local_versions()

    VERSIONS.load(os.path.join(get_config_dir(), 'versionCheck.json'))
    if VERSIONS[_VERSION_UPDATE_TIME]:
        version_update_time = datetime.datetime.strptime(VERSIONS[_VERSION_UPDATE_TIME], '%Y-%m-%d %H:%M:%S.%f')
        if datetime.datetime.now() < version_update_time + datetime.timedelta(days=1):
            cache_versions = VERSIONS['versions']
            if cache_versions and cache_versions['azure-cli']['local'] == versions['azure-cli']['local']:
                return cache_versions.copy(), True

    versions, success = _update_latest_from_pypi(versions)
    if success:
        VERSIONS['versions'] = versions
        VERSIONS[_VERSION_UPDATE_TIME] = str(datetime.datetime.now())
    return versions.copy(), success
Example #19
0
def conclude():
    from azure.cli.core._environment import get_config_dir
    from azure.cli.telemetry import save

    _session.end_time = datetime.datetime.utcnow()
    save(get_config_dir(), _session.generate_payload())
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

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,
    },
Example #21
0
import sys
from datetime import datetime, timedelta

import requests
from azure.cli.core._environment import get_config_dir
from azure.cli.core.commands import CliCommandType
from azure.cli.core.util import get_file_json
from knack.log import get_logger
from knack.util import CLIError
from six.moves import configparser

from .cli_utils import az_cli

LOGGER = get_logger(__name__)

CONFIG_DIR = get_config_dir()
SELF_DESTRUCT_PATH = os.path.join(CONFIG_DIR, "self-destruct")

# you can specify self-destruct dates like 1d, 6h, 2h30m, 30m, etc
DURATION_RE = re.compile(
    r"^((?P<days>\d+?)d)?((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?$")

# self_destruct is used to track state between different phases of the CLI
SELF_DESTRUCT = {}
SELF_DESTRUCT["active"] = False


def init(self):
    from knack import events

    # In pre-parse args, we'll gather the --self-destruct arguments and validate them
Example #22
0
import textwrap
import shutil

import six
from whoosh.highlight import UppercaseFormatter, ContextFragmenter
from whoosh.qparser import MultifieldParser
from whoosh import index
from whoosh.fields import TEXT, Schema

from azure.cli.command_modules.find._gather_commands import build_command_table
import azure.cli.core.azlogging as azlogging
from azure.cli.core._environment import get_config_dir

logger = azlogging.get_az_logger(__name__)

INDEX_PATH = os.path.join(get_config_dir(), 'search_index')

schema = Schema(
    cmd_name=TEXT(stored=True),
    short_summary=TEXT(stored=True),
    long_summary=TEXT(stored=True),
    examples=TEXT(stored=True))


def _cli_index_corpus():
    return build_command_table()


def _index_help():
    ix = index.open_dir(INDEX_PATH)
    writer = ix.writer()
Example #23
0
    def run(self):
        """ runs the CLI """
        telemetry.start()
        self.cli.buffers['symbols'].reset(
            initial_document=Document(u'%s' %shell_help)
        )
        while True:
            try:
                document = self.cli.run(reset_current_buffer=True)
                text = document.text
                cmd = text
                outside = False
                if text.split() and text.split()[0] == 'az':
                    cmd = ' '.join(text.split()[1:])
                if self.default_command:
                    cmd = self.default_command + " " + cmd
                # if self.default_params:
                #     for param in self.default_params:
                #         cmd += ' ' + param

            except AttributeError:  # when the user pressed Control Q
                break
            else:
                if text.strip() == "quit" or text.strip() == "exit":
                    break
                elif text.strip() == "clear":  # clears the history, but only when you restart
                    outside = True
                    cmd = 'echo -n "" >' +\
                        os.path.join(
                            SHELL_CONFIGURATION.get_config_dir(),
                            SHELL_CONFIGURATION.get_history())
                elif text.strip() == "help":
                    print(help_doc.dump(shell_help))
                if text:
                    if text[0] == SELECT_SYMBOL['outside']:
                        cmd = text[1:]
                        outside = True
                    # elif text.split()[0] == "az":  # dumps the extra az
                    #     cmd = " ".join(text.split()[1:])
                    elif text[0] == SELECT_SYMBOL['exit_code']:
                        print(self.last_exit)
                        self.set_prompt()
                        continue
                    elif SELECT_SYMBOL['query'] in text:  # query previous output
                        if self.last and self.last.result:
                            if hasattr(self.last.result, '__dict__'):
                                input_dict = dict(self.last.result)
                            else:
                                input_dict = self.last.result
                            try:
                                result = jmespath.search(
                                    text.partition(SELECT_SYMBOL['query'])[2], input_dict)
                                if isinstance(result, str):
                                    print(result)
                                else:
                                    print(json.dumps(result, sort_keys=True, indent=2))
                            except jmespath.exceptions.ParseError:
                                print("Invalid Query")

                        self.set_prompt()
                        continue
                    elif "|" in text or ">" in text:  # anything I don't parse, send off
                        outside = True
                        cmd = "az " + cmd
                    elif SELECT_SYMBOL['example'] in text:
                        global NOTIFICATIONS
                        cmd = self.handle_example(text)
                if SELECT_SYMBOL['default'] in text:
                    default = text.partition(SELECT_SYMBOL['default'])[2].split()
                    if default[0].startswith('-'):
                        value = self.handle_default_param(default)
                    else:
                        value = self.handle_default_command(default)
                    print("defaulting: " + value)
                    self.set_prompt()
                    continue
                if SELECT_SYMBOL['undefault'] in text:
                    value = text.partition(SELECT_SYMBOL['undefault'])[2].split()
                    if len(value) == 0:
                        self.default_command = ""
                        set_default_command("", add=False)
                        # self.default_params = []
                        print('undefaulting all')
                    elif len(value) == 1 and value[0] == self.default_command:
                        self.default_command = ""
                        set_default_command("", add=False)
                        print('undefaulting: ' + value[0])
                    # elif len(value) == 2 and ' '.join(value[:2]) in self.default_params:
                    #     self.default_params.remove(' '.join(value[:2]))
                    #     print('undefaulting: ' + ' '.join(value[:2]))

                    self.set_prompt()
                    continue

                if not text: # not input
                    self.set_prompt()
                    continue

                self.history.append(cmd)
                self.set_prompt()
                if outside:
                    subprocess.Popen(cmd, shell=True).communicate()
                else:
                    try:
                        args = [str(command) for command in cmd.split()]
                        azlogging.configure_logging(args)

                        azure_folder = get_config_dir()
                        if not os.path.exists(azure_folder):
                            os.makedirs(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)

                        config = Configuration(args)
                        self.app.initialize(config)

                        result = self.app.execute(args)
                        if result and result.result is not None:
                            from azure.cli.core._output import OutputProducer, format_json
                            if self.output:
                                self.output.out(result)
                            else:
                                formatter = OutputProducer.get_formatter(
                                    self.app.configuration.output_format)
                                OutputProducer(formatter=formatter, file=self.input).out(result)
                                self.last = result
                                self.last_exit = 0
                    except Exception as ex:  # pylint: disable=broad-except
                        self.last_exit = handle_exception(ex)
                    except SystemExit as ex:
                        self.last_exit = ex.code
                    if self.last_exit != 0:
                        telemetry.set_failure()
                    else:
                        telemetry.set_success()

        print('Have a lovely day!!')
        telemetry.conclude()
Example #24
0
from __future__ import print_function

import os
import textwrap
import shutil

import re
import six

from azure.cli.command_modules.find._gather_commands import build_command_table
from azure.cli.core._environment import get_config_dir

INDEX_DIR_PREFIX = 'search_index'
INDEX_VERSION = 'v1'
INDEX_PATH = os.path.join(get_config_dir(),
                          '{}_{}'.format(INDEX_DIR_PREFIX, INDEX_VERSION))


def _get_schema():
    from whoosh.fields import TEXT, Schema
    from whoosh.analysis import StemmingAnalyzer
    stem_ana = StemmingAnalyzer()
    return Schema(cmd_name=TEXT(stored=True,
                                analyzer=stem_ana,
                                field_boost=1.3),
                  short_summary=TEXT(stored=True, analyzer=stem_ana),
                  long_summary=TEXT(stored=True, analyzer=stem_ana),
                  examples=TEXT(stored=True, analyzer=stem_ana))

 def get_exception_message(cls, exception):
     exception_message = str(exception).replace(get_config_dir(), '.azure')
     return _remove_cmd_chars(_remove_symbols(exception_message))
Example #26
0
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import os

from azure.cli.core._environment import get_config_dir

# Config directory
AZ_CLI_GLOBAL_CONFIG_DIR = get_config_dir()
_AZ_DEVOPS_CONFIG_DIR_NAME = 'azuredevops'
AZ_DEVOPS_DEFAULT_CONFIG_DIR = os.path.join(AZ_CLI_GLOBAL_CONFIG_DIR, _AZ_DEVOPS_CONFIG_DIR_NAME)


# Environment Variables
CLI_ENV_VARIABLE_PREFIX = 'AZURE_DEVOPS_EXT_'
AZ_DEVOPS_CONFIG_DIR_ENVKEY = CLI_ENV_VARIABLE_PREFIX + 'CONFIG_DIR'
AZ_DEVOPS_GITHUB_PAT_ENVKEY = CLI_ENV_VARIABLE_PREFIX + 'GITHUB_PAT'
AZ_DEVOPS_PIPELINES_VARIABLES_KEY_PREFIX = CLI_ENV_VARIABLE_PREFIX + 'PIPELINE_VAR_'

# Import request Environment Variable
GIT_SOURCE_PASSWORD_OR_PAT = CLI_ENV_VARIABLE_PREFIX + 'GIT_SOURCE_PASSWORD_OR_PAT'

# Config file constants
CONFIG_FILE_NAME = 'config'
DEFAULTS_SECTION = 'defaults'
DEVOPS_ORGANIZATION_DEFAULT = 'organization'
DEVOPS_TEAM_PROJECT_DEFAULT = 'project'
PAT_ENV_VARIABLE_NAME = CLI_ENV_VARIABLE_PREFIX + 'PAT'
AUTH_TOKEN_ENV_VARIABLE_NAME = CLI_ENV_VARIABLE_PREFIX + 'AUTH_TOKEN'
Example #27
0
def conclude():
    from azure.cli.core._environment import get_config_dir
    from azure.cli.telemetry import save

    _session.end_time = datetime.datetime.utcnow()
    save(get_config_dir(), _session.generate_payload())
Example #28
0
import os
import textwrap
import shutil

import re
import six

from azure.cli.command_modules.find._gather_commands import build_command_table
import azure.cli.core.azlogging as azlogging
from azure.cli.core._environment import get_config_dir

logger = azlogging.get_az_logger(__name__)

INDEX_DIR_PREFIX = 'search_index'
INDEX_VERSION = 'v1'
INDEX_PATH = os.path.join(get_config_dir(), '{}_{}'.format(INDEX_DIR_PREFIX, INDEX_VERSION))


def _get_schema():
    from whoosh.fields import TEXT, Schema
    from whoosh.analysis import StemmingAnalyzer
    stem_ana = StemmingAnalyzer()
    return Schema(
        cmd_name=TEXT(stored=True, analyzer=stem_ana, field_boost=1.3),
        short_summary=TEXT(stored=True, analyzer=stem_ana),
        long_summary=TEXT(stored=True, analyzer=stem_ana),
        examples=TEXT(stored=True, analyzer=stem_ana))

def _cli_index_corpus():
    return build_command_table()
Example #29
0
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

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

import colorama

from azure.cli.core._environment import get_config_dir

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

ENABLE_LOG_FILE = os.environ.get('AZURE_CLI_ENABLE_LOG_FILE')
LOG_DIR = os.environ.get('AZURE_CLI_LOG_DIR')

CONSOLE_LOG_CONFIGS = [
    # (default)
    {
        'az': logging.WARNING,
        'root': logging.CRITICAL,
    },
    # --verbose
    {
        'az': logging.INFO,
        'root': logging.CRITICAL,
    },
Example #30
0
def _purge():
    for f in os.listdir(get_config_dir()):
        if re.search("^{}_*".format(INDEX_DIR_PREFIX), f):
            shutil.rmtree(os.path.join(get_config_dir(), f))
Example #31
0
 def __init__(self, config_path=None):
     if not config_path:
         config_path = os.path.join(get_config_dir(), "config")
     self.az_config = AzConfig()
     self.az_config.config_parser.read(config_path)
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import os
import stat
from six.moves import configparser

from azure.cli.core._environment import get_config_dir

GLOBAL_CONFIG_DIR = get_config_dir()
CONFIG_FILE_NAME = 'config'
GLOBAL_CONFIG_PATH = os.path.join(GLOBAL_CONFIG_DIR, CONFIG_FILE_NAME)
ENV_VAR_PREFIX = 'AZURE_'
DEFAULTS_SECTION = 'defaults'

_UNSET = object()
_ENV_VAR_FORMAT = ENV_VAR_PREFIX + '{section}_{option}'


def get_config_parser():
    import sys

    python_version = sys.version_info.major
    if python_version == 3:
        return configparser.ConfigParser()
    else:
        return configparser.SafeConfigParser()


class AzConfig(object):
Example #33
0
def _get_cache_directory(cli_ctx):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from azure.cli.core._environment import get_config_dir
    return os.path.join(get_config_dir(), 'object_cache', cli_ctx.cloud.name,
                        get_subscription_id(cli_ctx))
 def get_exception_message(cls, exception):
     exception_message = str(exception).replace(get_config_dir(), '.azure')
     return _remove_cmd_chars(_remove_symbols(exception_message))
Example #35
0
import os
import textwrap
import shutil

import re
import six

from azure.cli.command_modules.find._gather_commands import build_command_table
import azure.cli.core.azlogging as azlogging
from azure.cli.core._environment import get_config_dir

logger = azlogging.get_az_logger(__name__)

INDEX_DIR_PREFIX = 'search_index'
INDEX_VERSION = 'v1'
INDEX_PATH = os.path.join(get_config_dir(), '{}_{}'.format(INDEX_DIR_PREFIX, INDEX_VERSION))


def _get_schema():
    from whoosh.fields import TEXT, Schema
    from whoosh.analysis import StemmingAnalyzer
    stem_ana = StemmingAnalyzer()
    return Schema(
        cmd_name=TEXT(stored=True, analyzer=stem_ana, field_boost=1.3),
        short_summary=TEXT(stored=True, analyzer=stem_ana),
        long_summary=TEXT(stored=True, analyzer=stem_ana),
        examples=TEXT(stored=True, analyzer=stem_ana))


def _cli_index_corpus():
    return build_command_table()
Example #36
0
def load_acs_service_principal(subscription_id, config_path=os.path.join(get_config_dir(),
                                                                         'acsServicePrincipal.json')):
    config = load_acs_service_principals(config_path)
    if not config:
        return None
    return config.get(subscription_id)
Example #37
0
def _purge():
    for f in os.listdir(get_config_dir()):
        if re.search("^{}_*".format(INDEX_DIR_PREFIX), f):
            shutil.rmtree(os.path.join(get_config_dir(), f))
Example #38
0
 def __init__(self, auth_ctx_factory=None):
     self._token_file = os.path.join(get_config_dir(), 'accessTokens.json')
     self._service_principal_creds = []
     self._auth_ctx_factory = auth_ctx_factory or _AUTH_CTX_FACTORY
     self.adal_token_cache = None
     self._load_creds()
Example #39
0
 def __init__(self, config_path=None):
     if not config_path:
         config_path = os.path.join(get_config_dir(), "config")
     self.az_config = AzConfig()
     self.az_config.config_parser.read(config_path)
Example #40
0
 def __init__(self, auth_ctx_factory=None):
     self._token_file = os.path.join(get_config_dir(), 'accessTokens.json')
     self._service_principal_creds = []
     self._auth_ctx_factory = auth_ctx_factory or _AUTH_CTX_FACTORY
     self.adal_token_cache = None
     self._load_creds()
Example #41
0
from azure.cli.command_modules.iot.mgmt_iot_hub_device.lib.iot_hub_device_client import IotHubDeviceClient
from azure.cli.command_modules.iot.mgmt_iot_hub_device.lib.models.authentication import Authentication
from azure.cli.command_modules.iot.mgmt_iot_hub_device.lib.models.device_description import DeviceDescription
from azure.cli.command_modules.iot.mgmt_iot_hub_device.lib.models.x509_thumbprint import X509Thumbprint
from azure.cli.command_modules.iot.sas_token_auth import SasTokenAuthentication
from azure.cli.core.extension import extension_exists
from azure.cli.core._environment import get_config_dir

from ._client_factory import resource_service_factory
from ._utils import create_self_signed_certificate, open_certificate

logger = get_logger(__name__)

# IoT Extension run once awareness
if not extension_exists('azure_cli_iot_ext'):
    config = CLIConfig(get_config_dir())
    ran_before = config.getboolean('iot', 'first_run', fallback=False)
    if not ran_before:
        extension_text = """
                         Comprehensive IoT data-plane functionality is available
                         in the Azure IoT CLI Extension. For more info and install guide
                         go to https://github.com/Azure/azure-iot-cli-extension
                         """
        logger.warning(extension_text)
        config.set_value('iot', 'first_run', 'yes')


# CUSTOM TYPE
class KeyType(Enum):
    primary = 'primary'
    secondary = 'secondary'