예제 #1
0
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
예제 #2
0
def main(args, file=sys.stdout):  #pylint: disable=redefined-builtin
    _logging.configure_logging(args)

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

    azure_folder = os.path.expanduser('~/.azure')
    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)
    APPLICATION.initialize(config)

    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:
            formatter = OutputProducer.get_formatter(
                APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=file).out(cmd_result)
    except Exception as ex:  # pylint: disable=broad-except
        log_telemetry('Error', log_type='trace')
        error_code = handle_exception(ex)
        return error_code
예제 #3
0
def main():
    """ the main function """

    azure_folder = cli_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

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        APPLICATION.execute(["configure"])
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(
        completer=AZCOMPLETER,
        lexer=AzLexer,
        history=FileHistory(os.path.join(CONFIGURATION.get_config_dir(), config.get_history())),
        app=APPLICATION,
        # cli_config=os.path.join(azure_folder, 'config')
    )
    shell_app.run()
예제 #4
0
파일: main.py 프로젝트: Azure/azure-cli
def main(args, file=sys.stdout): #pylint: disable=redefined-builtin
    _logging.configure_logging(args)

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

    azure_folder = os.path.expanduser('~/.azure')
    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)
    APPLICATION.initialize(config)

    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:
            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
        from azure.cli.core.telemetry import log_telemetry
        log_telemetry('Error', log_type='trace')
        error_code = handle_exception(ex)
        return error_code
예제 #5
0
def initialize_client():
    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())
예제 #6
0
def mock_echo_args(command_name, parameters):
    try:
        argv = ' '.join((command_name, parameters)).split()
        APPLICATION.initialize(Configuration(argv))
        command_table = APPLICATION.configuration.get_command_table()
        prefunc = command_table[command_name].handler
        command_table[command_name].handler = lambda args: args
        parsed_namespace = APPLICATION.execute(argv)
        return parsed_namespace
    finally:
        command_table[command_name].handler = prefunc
예제 #7
0
def mock_echo_args(command_name, parameters):
    try:
        argv = ' '.join((command_name, parameters)).split()
        APPLICATION.initialize(Configuration(argv))
        command_table = APPLICATION.configuration.get_command_table()
        prefunc = command_table[command_name].handler
        command_table[command_name].handler = lambda args: args
        parsed_namespace = APPLICATION.execute(argv)
        return parsed_namespace
    finally:
        command_table[command_name].handler = prefunc
예제 #8
0
def _update_progress(current, total):
    hook = APPLICATION.get_progress_controller(det=True)

    if total:
        hook.add(message='Alive', value=current, total_val=total)
        if total == current:
            hook.end()
예제 #9
0
def wait_for_blob_copy_operation(blob_name, target_container_name, target_storage_account_name,
                                 azure_pool_frequency, location):
    progress_controller = APPLICATION.get_progress_controller()
    copy_status = "pending"
    prev_progress = -1
    while copy_status == "pending":
        cmd = prepare_cli_command(['storage', 'blob', 'show',
                                   '--name', blob_name,
                                   '--container-name', target_container_name,
                                   '--account-name', target_storage_account_name])

        json_output = run_cli_command(cmd, return_as_json=True)
        copy_status = json_output["properties"]["copy"]["status"]
        copy_progress_1, copy_progress_2 = json_output["properties"]["copy"]["progress"].split("/")
        current_progress = round(int(copy_progress_1) / int(copy_progress_2), 1)

        if current_progress != prev_progress:
            msg = "{0} - copy progress: {1}%"\
                .format(location, str(current_progress))\
                .ljust(PROGRESS_LINE_LENGTH)  # need to justify since messages overide each other
            progress_controller.add(message=msg)

        prev_progress = current_progress

        try:
            time.sleep(azure_pool_frequency)
        except KeyboardInterrupt:
            progress_controller.stop()
            return

    if copy_status == 'success':
        progress_controller.stop()
    else:
        logger.error("The copy operation didn't succeed. Last status: %s", copy_status)
        raise CLIError('Blob copy failed')
def _build_service_principal(client, name, url, client_secret):
    # use get_progress_controller
    hook = APPLICATION.get_progress_controller(True)
    hook.add(messsage='Creating service principal', value=0, total_val=1.0)
    logger.info('Creating service principal')
    result = create_application(client.applications,
                                name,
                                url, [url],
                                password=client_secret)
    service_principal = result.app_id  # pylint: disable=no-member
    for x in range(0, 10):
        hook.add(message='Creating service principal',
                 value=0.1 * x,
                 total_val=1.0)
        try:
            create_service_principal(service_principal, client=client)
            break
        # TODO figure out what exception AAD throws here sometimes.
        except Exception as ex:  # pylint: disable=broad-except
            logger.info(ex)
            time.sleep(2 + 2 * x)
    else:
        return False
    hook.add(message='Finished service principal creation',
             value=1.0,
             total_val=1.0)
    logger.info('Finished service principal creation')
    return service_principal
예제 #11
0
def _update_progress(current, total):
    HOOK = APPLICATION.get_progress_controller(True)

    if total:
        HOOK.add(message='Alive', value=current, total_val=total)
        if total == current:
            HOOK.end()
예제 #12
0
파일: custom.py 프로젝트: smoghe/azure-cli
def _update_progress(current, total):
    HOOK = APPLICATION.get_progress_controller(True)

    if total:
        HOOK.add(message='Alive', value=current, total_val=total)
        if total == current:
            HOOK.end()
예제 #13
0
def _add_role_assignment(role, service_principal, delay=2):
    # AAD can have delays in propagating data, so sleep and retry
    hook = APPLICATION.get_progress_controller(True)
    hook.add(message='Waiting for AAD role to propagate', value=0, total_val=1.0)
    logger.info('Waiting for AAD role to propagate')
    for x in range(0, 10):
        hook.add(message='Waiting for AAD role to propagate', value=0.1 * x, total_val=1.0)
        try:
            # TODO: break this out into a shared utility library
            create_role_assignment(role, service_principal)
            # Sleep for a while to get role assignment propagated
            time.sleep(delay + delay * x)
            break
        except CloudError as ex:
            if ex.message == 'The role assignment already exists.':
                break
            logger.info(ex.message)
        except:  # pylint: disable=bare-except
            pass
        time.sleep(delay + delay * x)
    else:
        return False
    hook.add(message='AAD role propagation done', value=1.0, total_val=1.0)
    logger.info('AAD role propagation done')
    return True
def _add_role_assignment(role, service_principal, delay=2):
    # AAD can have delays in propagating data, so sleep and retry
    hook = APPLICATION.get_progress_controller(True)
    hook.add(message='Waiting for AAD role to propagate',
             value=0,
             total_val=1.0)
    logger.info('Waiting for AAD role to propagate')
    for x in range(0, 10):
        hook.add(message='Waiting for AAD role to propagate',
                 value=0.1 * x,
                 total_val=1.0)
        try:
            # TODO: break this out into a shared utility library
            create_role_assignment(role, service_principal)
            # Sleep for a while to get role assignment propagated
            time.sleep(delay + delay * x)
            break
        except CloudError as ex:
            if ex.message == 'The role assignment already exists.':
                break
            logger.info(ex.message)
        except:  # pylint: disable=bare-except
            pass
        time.sleep(delay + delay * x)
    else:
        return False
    hook.add(message='AAD role propagation done', value=1.0, total_val=1.0)
    logger.info('AAD role propagation done')
    return True
예제 #15
0
    def __init__(self, start_msg='', finish_msg='',
                 poller_done_interval_ms=1000.0, progress_controller=None):

        self.start_msg = start_msg
        self.finish_msg = finish_msg
        self.poller_done_interval_ms = poller_done_interval_ms
        from azure.cli.core.application import APPLICATION
        self.progress_controller = progress_controller or APPLICATION.get_progress_controller()
예제 #16
0
    def __init__(self, start_msg='', finish_msg='',
                 poller_done_interval_ms=1000.0, progress_controller=None):

        self.start_msg = start_msg
        self.finish_msg = finish_msg
        self.poller_done_interval_ms = poller_done_interval_ms
        from azure.cli.core.application import APPLICATION
        self.progress_controller = progress_controller or APPLICATION.get_progress_controller()
        self.deploy_dict = {}
    def test_command_consistency(self):
        argv = ['vm']
        APPLICATION.initialize(Configuration())
        command_table = APPLICATION.configuration.get_command_table(argv)
        vm_commands = ((vm_command, metadata) for vm_command, metadata
                       in command_table.items() if vm_command.startswith('vm'))

        for command_name, command_metadata in vm_commands:
            for argument_name, expected_options_list in self.consistent_arguments.items():
                try:
                    actual_options_list = command_metadata.arguments[argument_name].options_list
                    self.assertEqual(actual_options_list, expected_options_list,
                                     'Argument {} of command {} has inconsistent flags'.format(
                                         argument_name,
                                         command_name
                                     ))
                except KeyError:
                    pass
예제 #18
0
    def test_generic_update_ids(self):
        my_objs = [
            {
                'prop': 'val',
                'list': [
                    'a',
                    'b',
                    ['c', {'d': 'e'}]
                    ]
            },
            {
                'prop': 'val',
                'list': [
                    'a',
                    'b',
                    ['c', {'d': 'e'}]
                    ]
            }]

        def my_get(name, resource_group): #pylint:disable=unused-argument
            # name is None when tests are run in a batch on Python <=2.7.9
            if sys.version_info < (2, 7, 10):
                return my_objs[0]
            return my_objs[int(name)]

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_objs

        register_cli_argument('gencommand', 'name', CliArgumentType(options_list=('--name', '-n'),
                                                                    metavar='NAME', id_part='name'))
        cli_generic_update_command('gencommand', my_get, my_set)

        config = Configuration([])
        APPLICATION.initialize(config)

        id_str = ('/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/'
                  'providers/Microsoft.Compute/virtualMachines/')

        APPLICATION.execute('gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval'
                            .format(id_str).split())
        self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated')
        # name is None when tests are run in a batch on Python <=2.7.9
        if not sys.version_info < (2, 7, 10):
            self.assertEqual(my_objs[1]['prop'], 'newval', 'second object updated')
예제 #19
0
    def test_generic_update_ids(self):
        my_objs = [{
            'prop': 'val',
            'list': ['a', 'b', ['c', {
                'd': 'e'
            }]]
        }, {
            'prop': 'val',
            'list': ['a', 'b', ['c', {
                'd': 'e'
            }]]
        }]

        def my_get(name, resource_group):  #pylint:disable=unused-argument
            # name is None when tests are run in a batch on Python <=2.7.9
            if sys.version_info < (2, 7, 10):
                return my_objs[0]
            return my_objs[int(name)]

        def my_set(**kwargs):  #pylint:disable=unused-argument
            return my_objs

        register_cli_argument(
            'gencommand', 'name',
            CliArgumentType(options_list=('--name', '-n'),
                            metavar='NAME',
                            id_part='name'))
        cli_generic_update_command('gencommand', my_get, my_set)

        config = Configuration([])
        APPLICATION.initialize(config)

        id_str = (
            '/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/'
            'providers/Microsoft.Compute/virtualMachines/')

        APPLICATION.execute(
            'gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval'
            .format(id_str).split())
        self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated')
        # name is None when tests are run in a batch on Python <=2.7.9
        if not sys.version_info < (2, 7, 10):
            self.assertEqual(my_objs[1]['prop'], 'newval',
                             'second object updated')
예제 #20
0
    def __init__(self, start_msg='', finish_msg='',
                 poller_done_interval_ms=1000.0, progress_controller=None):

        self.start_msg = start_msg
        self.finish_msg = finish_msg
        self.poller_done_interval_ms = poller_done_interval_ms
        from azure.cli.core.application import APPLICATION
        self.progress_controller = progress_controller or APPLICATION.get_progress_controller()
        self.deploy_dict = {}
        self.last_progress_report = datetime.datetime.now()
예제 #21
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
예제 #22
0
def _build_service_principal(client, name, url, client_secret):
    # use get_progress_controller
    hook = APPLICATION.get_progress_controller(True)
    hook.add(messsage='Creating service principal', value=0, total_val=1.0)
    logger.info('Creating service principal')
    result = create_application(client.applications, name, url, [url], password=client_secret)
    service_principal = result.app_id  # pylint: disable=no-member
    for x in range(0, 10):
        hook.add(message='Creating service principal', value=0.1 * x, total_val=1.0)
        try:
            create_service_principal(service_principal, client=client)
            break
        # TODO figure out what exception AAD throws here sometimes.
        except Exception as ex:  # pylint: disable=broad-except
            logger.info(ex)
            time.sleep(2 + 2 * x)
    else:
        return False
    hook.add(message='Finished service principal creation', value=1.0, total_val=1.0)
    logger.info('Finished service principal creation')
    return service_principal
예제 #23
0
from __future__ import print_function
from importlib import import_module

import json
import os
import pkgutil
import yaml

from azure.cli.core.application import APPLICATION, Configuration
from azure.cli.core.commands import _update_command_definitions, BLACKLISTED_MODS
from azure.cli.core.help_files import helps
from azure.cli.core.commands.arm import add_id_parameters

import azclishell.configuration as config

APPLICATION.initialize(Configuration())
CMD_TABLE = APPLICATION.configuration.get_command_table()


def install_modules():
    for cmd in CMD_TABLE:
        CMD_TABLE[cmd].load_arguments()

    try:
        mods_ns_pkg = import_module('azure.cli.command_modules')
        installed_command_modules = [
            modname
            for _, modname, _ in pkgutil.iter_modules(mods_ns_pkg.__path__)
            if modname not in BLACKLISTED_MODS
        ]
    except ImportError:
예제 #24
0
                             '--ids',
                             metavar='RESOURCE_ID',
                             dest=argparse.SUPPRESS,
                             help="One or more resource IDs (space delimited). If provided, "
                                  "no other 'Resource Id' arguments should be specified.",
                             action=split_action(command.arguments),
                             nargs='+',
                             type=ResourceId,
                             validator=required_values_validator,
                             arg_group=group_name)

    for command in command_table.values():
        command_loaded_handler(command)


APPLICATION.register(APPLICATION.COMMAND_TABLE_PARAMS_LOADED, add_id_parameters)

APPLICATION.register(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters)

add_usage = '--add property.listProperty <key=value, string or JSON string>'
set_usage = '--set property1.property2=<value>'
remove_usage = '--remove property.list <indexToRemove> OR --remove propertyToRemove'


def _get_child(parent, collection_name, item_name, collection_key):
    items = getattr(parent, collection_name)
    result = next((x for x in items if getattr(x, collection_key, '').lower() ==
                   item_name.lower()), None)
    if not result:
        raise CLIError("Property '{}' does not exist for key '{}'.".format(
            item_name, collection_key))
예제 #25
0
from __future__ import print_function
from importlib import import_module

import json
import os
import pkgutil
import yaml

from azure.cli.core.application import APPLICATION, Configuration
from azure.cli.core.commands import _update_command_definitions, BLACKLISTED_MODS
from azure.cli.core.help_files import helps
from azure.cli.core.commands.arm import add_id_parameters

import azclishell.configuration as config

APPLICATION.initialize(Configuration())
CMD_TABLE = APPLICATION.configuration.get_command_table()


def install_modules():
    installed_command_modules = []
    for cmd in CMD_TABLE:
        try:
            CMD_TABLE[cmd].load_arguments()
        except (ImportError, ValueError):
            pass
        mods_ns_pkg = import_module('azure.cli.command_modules')
    for _, modname, _ in pkgutil.iter_modules(mods_ns_pkg.__path__):
        if modname not in BLACKLISTED_MODS:
            installed_command_modules.append(modname)
예제 #26
0
            if os.path.isfile(ssh_key_file):
                with open(ssh_key_file) as f:
                    args.ssh_key_value = f.read()
            else:
                raise CLIError(
                    'An RSA key file or key value must be supplied to SSH Key Value'
                )

    if hasattr(args, 'network_security_group_type'):
        args.network_security_group_rule = 'RDP' if is_windows else 'SSH'

    if hasattr(args, 'nat_backend_port') and not args.nat_backend_port:
        args.nat_backend_port = '3389' if is_windows else '22'


APPLICATION.register(APPLICATION.COMMAND_PARSER_PARSED, _handle_auth_types)


def load_images_from_aliases_doc(publisher=None, offer=None, sku=None):
    target_url = (
        'https://raw.githubusercontent.com/Azure/azure-rest-api-specs/'
        'master/arm-compute/quickstart-templates/aliases.json')
    txt = urlopen(target_url).read()
    dic = json.loads(txt.decode())
    try:
        all_images = []
        result = (dic['outputs']['aliases']['value'])
        for v in result.values():  #loop around os
            for alias, vv in v.items():  #loop around distros
                all_images.append({
                    'urnAlias': alias,
예제 #27
0
            '--ids',
            metavar='RESOURCE_ID',
            dest=argparse.SUPPRESS,
            help="One or more resource IDs (space delimited). If provided, "
            "no other 'Resource Id' arguments should be specified.",
            action=split_action(command.arguments),
            nargs='+',
            type=ResourceId,
            validator=required_values_validator,
            arg_group=group_name)

    for command in command_table.values():
        command_loaded_handler(command)


APPLICATION.register(APPLICATION.COMMAND_TABLE_PARAMS_LOADED,
                     add_id_parameters)

APPLICATION.register(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters)

add_usage = '--add property.listProperty <key=value, string or JSON string>'
set_usage = '--set property1.property2=<value>'
remove_usage = '--remove property.list <indexToRemove> OR --remove propertyToRemove'


def _get_child(parent, collection_name, item_name, collection_key):
    items = getattr(parent, collection_name)
    result = next(
        (x for x in items
         if getattr(x, collection_key, '').lower() == item_name.lower()), None)
    if not result:
        raise CLIError("Property '{}' does not exist for key '{}'.".format(
예제 #28
0
def load_command_table():
    APPLICATION.initialize(Configuration())
    command_table = APPLICATION.configuration.get_command_table()
    _install_modules(command_table)
    return command_table
예제 #29
0
파일: run.py 프로젝트: zooba/azure-cli
def dump_no_help(modules):
    APPLICATION.initialize(Configuration())
    cmd_table = APPLICATION.configuration.get_command_table()

    exit_val = 0
    for cmd in cmd_table:
        cmd_table[cmd].load_arguments()

    for mod in modules:
        try:
            import_module('azure.cli.command_modules.' + mod).load_params(mod)
        except Exception as ex:
            print("EXCEPTION: {} for module {}".format(ex, str(mod)))

    _update_command_definitions(cmd_table)
    add_id_parameters(cmd_table)

    with open(WHITE_DATA_FILE, 'r') as white:
        white_data = json.load(white)

    white_list_commands = set(white_data.get('commands', []))
    white_list_subgroups = set(white_data.get('subgroups', []))
    white_list_parameters = white_data.get('parameters', {})

    command_list = set()
    subgroups_list = set()
    parameters = {}
    for cmd in cmd_table:
        if not cmd_table[
                cmd].description and cmd not in helps and cmd not in white_list_commands:
            command_list.add(cmd)
            exit_val = 1
        group_name = " ".join(cmd.split()[:-1])
        if group_name not in helps:
            if group_name not in subgroups_list and group_name not in white_list_subgroups and group_name:
                exit_val = 1
                subgroups_list.add(group_name)

        param_list = set()
        for key in cmd_table[cmd].arguments:
            name = cmd_table[cmd].arguments[key].name
            if not cmd_table[cmd].arguments[key].type.settings.get(
                    'help') and name not in white_list_parameters.get(cmd, []):
                exit_val = 1
                param_list.add(name)
        if param_list:
            parameters[cmd] = param_list

    for cmd in helps:
        diction_help = yaml.load(helps[cmd])
        if "short-summary" in diction_help and "type" in diction_help:
            if diction_help["type"] == "command" and cmd in command_list:
                command_list.remove(cmd)
            elif diction_help["type"] == "group" and cmd in subgroups_list:
                subgroups_list.remove(cmd)
        if "parameters" in diction_help:
            for param in diction_help["parameters"]:
                if "short-summary" in param and param["name"].split(
                )[0] in parameters:
                    parameters.pop(cmd, None)

    data = {
        "subgroups": subgroups_list,
        "commands": command_list,
        "parameters": parameters
    }

    return exit_val, data
예제 #30
0
def add_id_parameters(command_table):

    def split_action(arguments):
        class SplitAction(argparse.Action): #pylint: disable=too-few-public-methods

            def __call__(self, parser, namespace, values, option_string=None):
                ''' The SplitAction will take the given ID parameter and spread the parsed
                parts of the id into the individual backing fields.

                Since the id value is expected to be of type `IterateValue`, all the backing
                (dest) fields will also be of type `IterateValue`
                '''
                try:
                    for value in [values] if isinstance(values, str) else values:
                        parts = parse_resource_id(value)
                        for arg in [arg for arg in arguments.values() if arg.id_part]:
                            existing_values = getattr(namespace, arg.name, None)
                            if existing_values is None:
                                existing_values = IterateValue()
                            existing_values.append(parts[arg.id_part])
                            setattr(namespace, arg.name, existing_values)
                except Exception as ex:
                    raise ValueError(ex)

        return SplitAction

    def command_loaded_handler(command):
        if not 'name' in [arg.id_part for arg in command.arguments.values() if arg.id_part]:
            # Only commands with a resource name are candidates for an id parameter
            return
        if command.name.split()[-1] == 'create':
            # Somewhat blunt hammer, but any create commands will not have an automatic id
            # parameter
            return

        required_arguments = []
        optional_arguments = []
        for arg in [argument for argument in command.arguments.values() if argument.id_part]:
            if arg.options.get('required', False):
                required_arguments.append(arg)
            else:
                optional_arguments.append(arg)
            arg.required = False

        def required_values_validator(namespace):
            errors = [arg for arg in required_arguments
                      if getattr(namespace, arg.name, None) is None]

            if errors:
                missing_required = ' '.join((arg.options_list[0] for arg in errors))
                raise CLIError('({} | {}) are required'.format(missing_required, '--ids'))

        group_name = 'Resource Id'
        for key, arg in command.arguments.items():
            if command.arguments[key].id_part:
                command.arguments[key].arg_group = group_name

        command.add_argument('ids',
                             '--ids',
                             metavar='RESOURCE_ID',
                             dest=argparse.SUPPRESS,
                             help="One or more resource IDs. If provided, no other 'Resource Id' "
                                  "arguments should be specified.",
                             action=split_action(command.arguments),
                             nargs='+',
                             type=ResourceId,
                             validator=required_values_validator,
                             arg_group=group_name)

    for command in command_table.values():
        command_loaded_handler(command)

    APPLICATION.remove(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters)
예제 #31
0
                break
        if not all_match:
            test_list.pop()
        else:
            return test_entry
    return '_ROOT_'

def _process_null_values(dict_):
    if hide_nulls:
        null_values = [x for x in dict_.keys() if dict_[x] is None]
        for key in null_values:
            dict_.pop(key)

def _dashed_to_camel(string):
    return string.replace('-', '_')

parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands', metavar='N', nargs='+', help='Filter by first level command (OR)')
parser.add_argument('--params', metavar='N', nargs='+', help='Filter by parameters (OR)')
parser.add_argument('--hide-nulls', action='store_true', default=False, help='Show null entries')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = [_dashed_to_camel(x) for x in args.params or []]
hide_nulls = args.hide_nulls

PRIMITIVES = (str, int, bool, float)
IGNORE_ARGS = ['help', 'help_file', 'base_type']

APPLICATION.register(Application.COMMAND_PARSER_LOADED, _dump_command_table)
APPLICATION.execute([])
def execute(command):
    try:
        ex_result = APPLICATION.execute(command)
        return {'result': ex_result.result, 'error': None}
    except CLIError as err:
        return {'result': None, 'error': err.args}
예제 #33
0
파일: run.py 프로젝트: LukaszStem/azure-cli
def dump_no_help(modules):
    APPLICATION.initialize(Configuration())
    cmd_table = APPLICATION.configuration.get_command_table()

    exit_val = 0
    for cmd in cmd_table:
        cmd_table[cmd].load_arguments()

    for mod in modules:
        try:
            import_module('azure.cli.command_modules.' + mod).load_params(mod)
        except Exception as ex:
            print("EXCEPTION: " + str(mod))

    _update_command_definitions(cmd_table)
    add_id_parameters(cmd_table)

    with open(WHITE_DATA_FILE, 'r') as white:
        white_data = json.load(white)

    white_list_commands = set(white_data.get('commands', []))
    white_list_subgroups = set(white_data.get('subgroups', []))
    white_list_parameters = white_data.get('parameters', {})

    command_list = set()
    subgroups_list = set()
    parameters = {}
    for cmd in cmd_table:
        if not cmd_table[cmd].description and cmd not in helps and cmd not in white_list_commands:
            command_list.add(cmd)
            exit_val = 1
        group_name = " ".join(cmd.split()[:-1])
        if group_name not in helps:
            if group_name not in subgroups_list and group_name not in white_list_subgroups and group_name:
                exit_val = 1
                subgroups_list.add(group_name)

        param_list = set()
        for key in cmd_table[cmd].arguments:
            name = cmd_table[cmd].arguments[key].name
            if not cmd_table[cmd].arguments[key].type.settings.get('help') and \
                    name not in white_list_parameters.get(cmd, []):
                exit_val = 1
                param_list.add(name)
        if param_list:
            parameters[cmd] = param_list

    for cmd in helps:
        diction_help = yaml.load(helps[cmd])
        if "short-summary" in diction_help and "type" in diction_help:
            if diction_help["type"] == "command" and cmd in command_list:
                command_list.remove(cmd)
            elif diction_help["type"] == "group" and cmd in subgroups_list:
                subgroups_list.remove(cmd)
        if "parameters" in diction_help:
            for param in diction_help["parameters"]:
                if "short-summary" in param and param["name"].split()[0] in parameters:
                    parameters.pop(cmd, None)

    data = {
        "subgroups": subgroups_list,
        "commands": command_list,
        "parameters": parameters
    }

    return exit_val, data
예제 #34
0
from azure.cli.core.application import APPLICATION
from azure.cli.core.commands import cli_command
from azure.cli.core.commands.arm import cli_generic_update_command
from azure.cli.core.util import empty_on_404
from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE

from ._client_factory import cf_web_client, cf_plans


def deprecate(argv):
    if len(argv) > 1 and argv[0] == 'appservice' and argv[1] == 'web':
        from azure.cli.core.util import CLIError
        raise CLIError("All 'appservice web' commands have been renamed to 'webapp'")


APPLICATION.register(APPLICATION.COMMAND_PARSER_PARSING, deprecate)


def output_slots_in_table(slots):
    return [{'name': s['name'], 'status': s['state'], 'plan': s['appServicePlan']} for s in slots]


def transform_list_location_output(result):
    return [{'name': x.name} for x in result]


def transform_web_output(web):
    props = ['name', 'state', 'location', 'resourceGroup', 'defaultHostName', 'appServicePlanId', 'ftpPublishingUrl']
    result = {k: web[k] for k in web if k in props}
    # to get width under control, also the plan usually is in the same RG
    result['appServicePlan'] = result.pop('appServicePlanId').split('/')[-1]
예제 #35
0
def execute_cli_command(command):
    cmd_result = APPLICATION.execute(command)
    return cmd_result.result
예제 #36
0
from azure.cli.core.commands import cli_command
from azure.cli.core.commands.arm import cli_generic_update_command
from azure.cli.core.util import empty_on_404
from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE

from ._client_factory import cf_web_client, cf_plans


def deprecate(argv):
    if len(argv) > 1 and argv[0] == 'appservice' and argv[1] == 'web':
        from azure.cli.core.util import CLIError
        raise CLIError(
            "All 'appservice web' commands have been renamed to 'webapp'")


APPLICATION.register(APPLICATION.COMMAND_PARSER_PARSING, deprecate)


def output_slots_in_table(slots):
    return [{
        'name': s['name'],
        'status': s['state'],
        'plan': s['appServicePlan']
    } for s in slots]


def transform_list_location_output(result):
    return [{'name': x.name} for x in result]


def transform_web_output(web):
예제 #37
0
            dict_.pop(key)


def _dashed_to_camel(string):
    return string.replace('-', '_')


parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands',
                    metavar='N',
                    nargs='+',
                    help='Filter by first level command (OR)')
parser.add_argument('--params',
                    metavar='N',
                    nargs='+',
                    help='Filter by parameters (OR)')
parser.add_argument('--hide-nulls',
                    action='store_true',
                    default=False,
                    help='Show null entries')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = [_dashed_to_camel(x) for x in args.params or []]
hide_nulls = args.hide_nulls

PRIMITIVES = (str, int, bool, float)
IGNORE_ARGS = ['help', 'help_file', 'base_type']

APPLICATION.register(Application.COMMAND_PARSER_LOADED, _dump_command_table)
APPLICATION.execute([])
예제 #38
0
        ssh_key_file = os.path.join(os.path.expanduser('~'), '.ssh/id_rsa.pub')
        if not args.ssh_key_value:
            if os.path.isfile(ssh_key_file):
                with open(ssh_key_file) as f:
                    args.ssh_key_value = f.read()
            else:
                raise CLIError('An RSA key file or key value must be supplied to SSH Key Value')

    if hasattr(args, 'network_security_group_type'):
        args.network_security_group_rule = 'RDP' if is_windows else 'SSH'

    if hasattr(args, 'nat_backend_port') and not args.nat_backend_port:
        args.nat_backend_port = '3389' if is_windows else '22'

APPLICATION.register(APPLICATION.COMMAND_PARSER_PARSED, _handle_auth_types)

def load_images_from_aliases_doc(publisher=None, offer=None, sku=None):
    target_url = ('https://raw.githubusercontent.com/Azure/azure-rest-api-specs/'
                  'master/arm-compute/quickstart-templates/aliases.json')
    txt = urlopen(target_url).read()
    dic = json.loads(txt.decode())
    try:
        all_images = []
        result = (dic['outputs']['aliases']['value'])
        for v in result.values(): #loop around os
            for alias, vv in v.items(): #loop around distros
                all_images.append({
                    'urnAlias': alias,
                    'publisher': vv['publisher'],
                    'offer': vv['offer'],
예제 #39
0
def _update_progress(current, total):
    hook = APPLICATION.get_progress_controller(det=True)
    if total:
        hook.add(message='Alive', value=current, total_val=total)
        if total == current:
            hook.end()