Example #1
0
 def test_application_todict_dict_with_obj(self):
     MyObject = namedtuple('MyObject', 'a b')
     mo = MyObject('x', 'y')
     the_input = {'a': mo}
     actual = todict(the_input)
     expected = {'a': {'a': 'x', 'b': 'y'}}
     self.assertEqual(actual, expected)
Example #2
0
    def execute(self, unexpanded_argv):
        argv = Application._expand_file_prefixed_files(unexpanded_argv)
        command_table = self.configuration.get_command_table()
        self.raise_event(self.COMMAND_TABLE_LOADED,
                         command_table=command_table)
        self.parser.load_command_table(command_table)
        self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

        if len(argv) == 0:
            az_subparser = self.parser.subparsers[tuple()]
            _help.show_welcome(az_subparser)
            log_telemetry('welcome')
            return None

        if argv[0].lower() == 'help':
            argv[0] = '--help'

        args = self.parser.parse_args(argv)
        self.raise_event(self.COMMAND_PARSER_PARSED,
                         command=args.command,
                         args=args)
        results = []
        for expanded_arg in _explode_list_args(args):
            self.session['command'] = expanded_arg.command
            try:
                _validate_arguments(expanded_arg)
            except:  # pylint: disable=bare-except
                err = sys.exc_info()[1]
                getattr(expanded_arg, '_parser',
                        self.parser).validation_error(str(err))

            # Consider - we are using any args that start with an underscore (_) as 'private'
            # arguments and remove them from the arguments that we pass to the actual function.
            # This does not feel quite right.
            params = dict([(key, value)
                           for key, value in expanded_arg.__dict__.items()
                           if not key.startswith('_')])
            params.pop('subcommand', None)
            params.pop('func', None)
            params.pop('command', None)
            log_telemetry(
                expanded_arg.command,
                log_type='pageview',
                output_type=self.configuration.output_format,
                parameters=[p for p in unexpanded_argv if p.startswith('-')])

            result = expanded_arg.func(params)
            result = todict(result)
            results.append(result)

        if len(results) == 1:
            results = results[0]

        event_data = {'result': results}
        self.raise_event(self.TRANSFORM_RESULT, event_data=event_data)
        self.raise_event(self.FILTER_RESULT, event_data=event_data)
        return CommandResultItem(
            event_data['result'],
            table_transformer=command_table[args.command].table_transformer,
            is_query_active=self.session['query_active'])
Example #3
0
 def test_application_todict_dict_with_obj(self):
     MyObject = namedtuple('MyObject', 'a b')
     mo = MyObject('x', 'y')
     the_input = {'a': mo}
     actual = todict(the_input)
     expected = {'a': {'a': 'x', 'b': 'y'}}
     self.assertEqual(actual, expected)
Example #4
0
def verify_property(instance, condition):
    from jmespath import compile as compile_jmespath

    result = todict(instance)
    jmes_query = compile_jmespath(condition)
    value = jmes_query.search(result)
    return value
Example #5
0
def list_role_assignments(assignee=None, role=None, resource_group_name=None,#pylint: disable=too-many-arguments
                          scope=None, include_inherited=False,
                          show_all=False, include_groups=False):
    '''
    :param include_groups: include extra assignments to the groups of which the user is a
    member(transitively). Supported only for a user principal.
    '''
    graph_client = _graph_client_factory()
    factory = _auth_client_factory(scope)
    assignments_client = factory.role_assignments
    definitions_client = factory.role_definitions

    scope = None
    if show_all:
        if resource_group_name or scope:
            raise CLIError('group or scope are not required when --all is used')
        scope = None
    else:
        scope = _build_role_scope(resource_group_name, scope,
                                  definitions_client.config.subscription_id)

    assignments = _search_role_assignments(assignments_client, definitions_client,
                                           scope, assignee, role,
                                           include_inherited, include_groups)

    if not assignments:
        return []

    #fill in logic names to get things understandable.
    #it's possible that associated roles and principals were deleted, and we just do nothing.

    results = todict(assignments)

    #pylint: disable=line-too-long
    #fill in role names
    role_defs = list(definitions_client.list(
        scope=scope or ('/subscriptions/' + definitions_client.config.subscription_id)))
    role_dics = {i.id: i.properties.role_name for i in role_defs}
    for i in results:
        i['properties']['roleDefinitionName'] = role_dics.get(i['properties']['roleDefinitionId'], None)

    #fill in principal names
    principal_ids = set(i['properties']['principalId'] for i in results)
    if principal_ids:
        principals = _get_object_stubs(graph_client, principal_ids)
        principal_dics = {i.object_id:_get_displayable_name(i) for i in principals}
        for i in results:
            i['properties']['principalName'] = principal_dics.get(i['properties']['principalId'], None)

    return results
Example #6
0
def list_role_assignments(assignee=None, role=None, resource_group_name=None,#pylint: disable=too-many-arguments
                          scope=None, include_inherited=False,
                          show_all=False, include_groups=False):
    '''
    :param include_groups: include extra assignments to the groups of which the user is a
    member(transitively). Supported only for a user principal.
    '''
    graph_client = _graph_client_factory()
    factory = _auth_client_factory(scope)
    assignments_client = factory.role_assignments
    definitions_client = factory.role_definitions

    scope = None
    if show_all:
        if resource_group_name or scope:
            raise CLIError('group or scope are not required when --all is used')
        scope = None
    else:
        scope = _build_role_scope(resource_group_name, scope,
                                  definitions_client.config.subscription_id)

    assignments = _search_role_assignments(assignments_client, definitions_client,
                                           scope, assignee, role,
                                           include_inherited, include_groups)

    if not assignments:
        return []

    #fill in logic names to get things understandable.
    #it's possible that associated roles and principals were deleted, and we just do nothing.

    results = todict(assignments)

    #pylint: disable=line-too-long
    #fill in role names
    role_defs = list(definitions_client.list(
        scope=scope or ('/subscriptions/' + definitions_client.config.subscription_id)))
    role_dics = {i.id: i.properties.role_name for i in role_defs}
    for i in results:
        i['properties']['roleDefinitionName'] = role_dics.get(i['properties']['roleDefinitionId'], None)

    #fill in principal names
    principal_ids = set(i['properties']['principalId'] for i in results)
    if principal_ids:
        principals = _get_object_stubs(graph_client, principal_ids)
        principal_dics = {i.object_id:_get_displayable_name(i) for i in principals}
        for i in results:
            i['properties']['principalName'] = principal_dics.get(i['properties']['principalId'], None)

    return results
Example #7
0
    def execute(self, unexpanded_argv):  # pylint: disable=too-many-statements
        argv = Application._expand_file_prefixed_files(unexpanded_argv)
        command_table = self.configuration.get_command_table()
        self.raise_event(self.COMMAND_TABLE_LOADED, command_table=command_table)
        self.parser.load_command_table(command_table)
        self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

        if len(argv) == 0:
            enable_autocomplete(self.parser)
            az_subparser = self.parser.subparsers[tuple()]
            _help.show_welcome(az_subparser)

            # TODO: Question, is this needed?
            telemetry.set_command_details('az')
            telemetry.set_success(summary='welcome')

            return None

        if argv[0].lower() == 'help':
            argv[0] = '--help'

        # Rudimentary parsing to get the command
        nouns = []
        for noun in argv:
            try:
                if noun[0] == '-':
                    break
            except IndexError:
                pass
            nouns.append(noun)
        command = ' '.join(nouns)

        if argv[-1] in ('--help', '-h') or command in command_table:
            self.configuration.load_params(command)
            self.raise_event(self.COMMAND_TABLE_PARAMS_LOADED, command_table=command_table)
            self.parser.load_command_table(command_table)

        if self.session['completer_active']:
            enable_autocomplete(self.parser)

        args = self.parser.parse_args(argv)

        self.raise_event(self.COMMAND_PARSER_PARSED, command=args.command, args=args)
        results = []
        for expanded_arg in _explode_list_args(args):
            self.session['command'] = expanded_arg.command
            try:
                _validate_arguments(expanded_arg)
            except CLIError:
                raise
            except:  # pylint: disable=bare-except
                err = sys.exc_info()[1]
                getattr(expanded_arg, '_parser', self.parser).validation_error(str(err))

            # Consider - we are using any args that start with an underscore (_) as 'private'
            # arguments and remove them from the arguments that we pass to the actual function.
            # This does not feel quite right.
            params = dict([(key, value)
                           for key, value in expanded_arg.__dict__.items()
                           if not key.startswith('_')])
            params.pop('subcommand', None)
            params.pop('func', None)
            params.pop('command', None)

            telemetry.set_command_details(expanded_arg.command,
                                          self.configuration.output_format,
                                          [p for p in unexpanded_argv if p.startswith('-')])

            result = expanded_arg.func(params)
            result = todict(result)
            results.append(result)

        if len(results) == 1:
            results = results[0]

        event_data = {'result': results}
        self.raise_event(self.TRANSFORM_RESULT, event_data=event_data)
        self.raise_event(self.FILTER_RESULT, event_data=event_data)

        return CommandResultItem(event_data['result'],
                                 table_transformer=command_table[args.command].table_transformer,
                                 is_query_active=self.session['query_active'])
Example #8
0
def verify_property(instance, condition):
    from jmespath import compile as compile_jmespath
    result = todict(instance)
    jmes_query = compile_jmespath(condition)
    value = jmes_query.search(result)
    return value
Example #9
0
 def test_application_todict_list(self):
     the_input = [{'a': 'b'}]
     actual = todict(the_input)
     expected = [{'a': 'b'}]
     self.assertEqual(actual, expected)
Example #10
0
 def test_application_todict_dict(self):
     the_input = {'a': 'b'}
     actual = todict(the_input)
     expected = {'a': 'b'}
     self.assertEqual(actual, expected)
Example #11
0
 def test_application_todict_none(self):
     the_input = None
     actual = todict(the_input)
     expected = None
     self.assertEqual(actual, expected)
Example #12
0
    def execute(self, unexpanded_argv):  # pylint: disable=too-many-statements
        argv = Application._expand_file_prefixed_files(unexpanded_argv)
        command_table = self.configuration.get_command_table()
        self.raise_event(self.COMMAND_TABLE_LOADED,
                         command_table=command_table)
        self.parser.load_command_table(command_table)
        self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

        if len(argv) == 0:
            enable_autocomplete(self.parser)
            az_subparser = self.parser.subparsers[tuple()]
            _help.show_welcome(az_subparser)

            # TODO: Question, is this needed?
            telemetry.set_command_details('az')
            telemetry.set_success(summary='welcome')

            return None

        if argv[0].lower() == 'help':
            argv[0] = '--help'

        # Rudimentary parsing to get the command
        nouns = []
        for noun in argv:
            try:
                if noun[0] == '-':
                    break
            except IndexError:
                pass
            nouns.append(noun)
        command = ' '.join(nouns)

        if argv[-1] in ('--help', '-h') or command in command_table:
            self.configuration.load_params(command)
            self.raise_event(self.COMMAND_TABLE_PARAMS_LOADED,
                             command_table=command_table)
            self.parser.load_command_table(command_table)

        if self.session['completer_active']:
            enable_autocomplete(self.parser)

        args = self.parser.parse_args(argv)

        self.raise_event(self.COMMAND_PARSER_PARSED,
                         command=args.command,
                         args=args)
        results = []
        for expanded_arg in _explode_list_args(args):
            self.session['command'] = expanded_arg.command
            try:
                _validate_arguments(expanded_arg)
            except CLIError:
                raise
            except:  # pylint: disable=bare-except
                err = sys.exc_info()[1]
                getattr(expanded_arg, '_parser',
                        self.parser).validation_error(str(err))

            # Consider - we are using any args that start with an underscore (_) as 'private'
            # arguments and remove them from the arguments that we pass to the actual function.
            # This does not feel quite right.
            params = dict([(key, value)
                           for key, value in expanded_arg.__dict__.items()
                           if not key.startswith('_')])
            params.pop('subcommand', None)
            params.pop('func', None)
            params.pop('command', None)

            telemetry.set_command_details(
                expanded_arg.command, self.configuration.output_format,
                [p for p in unexpanded_argv if p.startswith('-')])

            result = expanded_arg.func(params)
            result = todict(result)
            results.append(result)

        if len(results) == 1:
            results = results[0]

        event_data = {'result': results}
        self.raise_event(self.TRANSFORM_RESULT, event_data=event_data)
        self.raise_event(self.FILTER_RESULT, event_data=event_data)

        return CommandResultItem(
            event_data['result'],
            table_transformer=command_table[args.command].table_transformer,
            is_query_active=self.session['query_active'])
Example #13
0
 def test_application_todict_list(self):
     the_input = [{'a': 'b'}]
     actual = todict(the_input)
     expected = [{'a': 'b'}]
     self.assertEqual(actual, expected)
Example #14
0
 def test_application_todict_dict(self):
     the_input = {'a': 'b'}
     actual = todict(the_input)
     expected = {'a': 'b'}
     self.assertEqual(actual, expected)
Example #15
0
 def test_application_todict_none(self):
     the_input = None
     actual = todict(the_input)
     expected = None
     self.assertEqual(actual, expected)
Example #16
0
    def execute(self, unexpanded_argv):
        argv = Application._expand_file_prefixed_files(unexpanded_argv)
        command_table = self.configuration.get_command_table()
        self.raise_event(self.COMMAND_TABLE_LOADED, command_table=command_table)
        self.parser.load_command_table(command_table)
        self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

        if len(argv) == 0:
            enable_autocomplete(self.parser)
            az_subparser = self.parser.subparsers[tuple()]
            _help.show_welcome(az_subparser)
            log_telemetry("welcome")
            return None

        if argv[0].lower() == "help":
            argv[0] = "--help"

        # Rudimentary parsing to get the command
        nouns = []
        for noun in argv:
            if noun[0] == "-":
                break
            nouns.append(noun)
        command = " ".join(nouns)

        if argv[-1] in ("--help", "-h") or command in command_table:
            self.configuration.load_params(command)
            self.raise_event(self.COMMAND_TABLE_PARAMS_LOADED, command_table=command_table)
            self.parser.load_command_table(command_table)

        if self.session["completer_active"]:
            enable_autocomplete(self.parser)

        args = self.parser.parse_args(argv)

        self.raise_event(self.COMMAND_PARSER_PARSED, command=args.command, args=args)
        results = []
        for expanded_arg in _explode_list_args(args):
            self.session["command"] = expanded_arg.command
            try:
                _validate_arguments(expanded_arg)
            except CLIError:
                raise
            except:  # pylint: disable=bare-except
                err = sys.exc_info()[1]
                getattr(expanded_arg, "_parser", self.parser).validation_error(str(err))

            # Consider - we are using any args that start with an underscore (_) as 'private'
            # arguments and remove them from the arguments that we pass to the actual function.
            # This does not feel quite right.
            params = dict([(key, value) for key, value in expanded_arg.__dict__.items() if not key.startswith("_")])
            params.pop("subcommand", None)
            params.pop("func", None)
            params.pop("command", None)
            log_telemetry(
                expanded_arg.command,
                log_type="pageview",
                output_type=self.configuration.output_format,
                parameters=[p for p in unexpanded_argv if p.startswith("-")],
            )

            result = expanded_arg.func(params)
            result = todict(result)
            results.append(result)

        if len(results) == 1:
            results = results[0]

        event_data = {"result": results}
        self.raise_event(self.TRANSFORM_RESULT, event_data=event_data)
        self.raise_event(self.FILTER_RESULT, event_data=event_data)
        return CommandResultItem(
            event_data["result"],
            table_transformer=command_table[args.command].table_transformer,
            is_query_active=self.session["query_active"],
        )