Example #1
0
def do_alarm_state_get(cc, args={}):
    '''Get the state of an alarm.'''
    try:
        state = cc.alarms.get_state(args.alarm_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
    utils.print_dict({'state': state}, wrap=72)
Example #2
0
def do_alarm_show(cc, args={}):
    '''Show an alarm.'''
    try:
        alarm = cc.alarms.get(args.alarm_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
    else:
        _display_alarm(alarm)
Example #3
0
 def do_help(self, args):
     """Display help about this program or one of its subcommands."""
     if getattr(args, 'command', None):
         if args.command in self.subcommands:
             self.subcommands[args.command].print_help()
         else:
             raise exc.CommandError("'%s' is not a valid subcommand" %
                                    args.command)
     else:
         self.parser.print_help()
Example #4
0
def args_array_to_dict(kwargs, key_to_convert):
    values_to_convert = kwargs.get(key_to_convert)
    if values_to_convert:
        try:
            kwargs[key_to_convert] = dict(
                v.split("=", 1) for v in values_to_convert)
        except ValueError:
            raise exc.CommandError('%s must be a list of key=value not "%s"' %
                                   (key_to_convert, values_to_convert))
    return kwargs
Example #5
0
def do_resource_show(cc, args={}):
    '''Show the resource.'''
    try:
        resource = cc.resources.get(args.resource_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Resource not found: %s' % args.resource_id)
    else:
        fields = ['resource_id', 'source', 'user_id', 'project_id', 'metadata']
        data = dict([(f, getattr(resource, f, '')) for f in fields])
        utils.print_dict(data, wrap=72)
Example #6
0
    def main(self, argv):
        parsed = self.parse_args(argv)
        if parsed == 0:
            return 0
        api_version, args = parsed

        # Short-circuit and deal with help command right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not (args.os_auth_token and args.gnocchi_url):
            if not args.os_username:
                raise exc.CommandError("You must provide a username via "
                                       "either --os-username or via "
                                       "env[OS_USERNAME]")

            if not args.os_password:
                raise exc.CommandError("You must provide a password via "
                                       "either --os-password or via "
                                       "env[OS_PASSWORD]")

            if not (args.os_tenant_id or args.os_tenant_name):
                raise exc.CommandError("You must provide a tenant_id via "
                                       "either --os-tenant-id or via "
                                       "env[OS_TENANT_ID]")

            if not args.os_auth_url:
                raise exc.CommandError("You must provide an auth url via "
                                       "either --os-auth-url or via "
                                       "env[OS_AUTH_URL]")

        client = gnoclient.get_client(api_version, **(args.__dict__))

        # call whatever callback was selected
        try:
            args.func(client, args)
        except exc.HTTPUnauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
Example #7
0
def do_alarm_update(cc, args={}):
    '''Update an existing alarm (Deprecated).'''
    fields = dict(filter(lambda x: not (x[1] is None), vars(args).items()))
    fields = utils.args_array_to_list_of_dicts(fields, "time_constraints")
    fields = utils.args_array_to_dict(fields, "matching_metadata")
    fields.pop('alarm_id')
    try:
        alarm = cc.alarms.update(args.alarm_id, **fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
    _display_alarm(alarm)
Example #8
0
def do_alarm_combination_update(cc, args={}):
    '''Update an existing alarm based on state of other alarms.'''
    fields = dict(filter(lambda x: not (x[1] is None), vars(args).items()))
    fields = utils.args_array_to_list_of_dicts(fields, 'time_constraints')
    fields = utils.key_with_slash_to_nested_dict(fields)
    fields.pop('alarm_id')
    fields['type'] = 'combination'
    try:
        alarm = cc.alarms.update(args.alarm_id, **fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
    _display_alarm(alarm)
Example #9
0
def do_alarm_history(cc, args={}):
    '''Display the change history of an alarm.'''
    kwargs = dict(alarm_id=args.alarm_id, q=options.cli_to_array(args.query))
    try:
        history = cc.alarms.get_history(**kwargs)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
    field_labels = ['Type', 'Timestamp', 'Detail']
    fields = ['type', 'timestamp', 'detail']
    utils.print_list(history,
                     fields,
                     field_labels,
                     formatters={'detail': alarm_change_detail_formatter},
                     sortby=1)
Example #10
0
def do_alarm_threshold_update(cc, args={}):
    '''Update an existing alarm based on computed statistics.'''
    fields = dict(filter(lambda x: not (x[1] is None), vars(args).items()))
    fields = utils.args_array_to_list_of_dicts(fields, 'time_constraints')
    fields = utils.key_with_slash_to_nested_dict(fields)
    fields.pop('alarm_id')
    fields['type'] = 'threshold'
    if 'threshold_rule' in fields and 'query' in fields['threshold_rule']:
        fields['threshold_rule']['query'] = options.cli_to_array(
            fields['threshold_rule']['query'])
    try:
        alarm = cc.alarms.update(args.alarm_id, **fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
    _display_alarm(alarm)
Example #11
0
def args_array_to_list_of_dicts(kwargs, key_to_convert):
    """Converts ['a=1;b=2','c=3;d=4'] to [{a:1,b:2},{c:3,d:4}]
    """
    values_to_convert = kwargs.get(key_to_convert)
    if values_to_convert:
        try:
            kwargs[key_to_convert] = []
            for lst in values_to_convert:
                pairs = lst.split(";")
                dct = dict()
                for pair in pairs:
                    kv = pair.split("=", 1)
                    dct[kv[0]] = kv[1].strip(" \"'")  # strip spaces and quotes
                kwargs[key_to_convert].append(dct)
        except Exception:
            raise exc.CommandError(
                '%s must be a list of key1=value1;key2=value2;... not "%s"' %
                (key_to_convert, values_to_convert))
    return kwargs
Example #12
0
def do_query_samples(cc, args):
    '''Query samples.'''
    fields = {
        'filter': args.filter,
        'orderby': args.orderby,
        'limit': args.limit
    }
    try:
        samples = cc.query_samples.query(**fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Samples not found')
    else:
        field_labels = [
            'Resource ID', 'Meter', 'Type', 'Volume', 'Unit', 'Timestamp'
        ]
        fields = [
            'resource_id', 'meter', 'type', 'volume', 'unit', 'timestamp'
        ]
        utils.print_list(samples, fields, field_labels, sortby=None)
Example #13
0
def do_statistics(cc, args):
    '''List the statistics for a meter.'''
    aggregates = []
    for a in args.aggregate:
        aggregates.append(dict(zip(('func', 'param'), a.split("<-"))))
    api_args = {
        'meter_name': args.meter,
        'q': options.cli_to_array(args.query),
        'period': args.period,
        'groupby': args.groupby,
        'aggregates': aggregates
    }
    try:
        statistics = cc.statistics.list(**api_args)
    except exc.HTTPNotFound:
        raise exc.CommandError('Samples not found: %s' % args.meter)
    else:
        fields_display = {
            'duration': 'Duration',
            'duration_end': 'Duration End',
            'duration_start': 'Duration Start',
            'period': 'Period',
            'period_end': 'Period End',
            'period_start': 'Period Start',
            'groupby': 'Group By'
        }
        fields_display.update(AGGREGATES)
        fields = ['period', 'period_start', 'period_end']
        if args.groupby:
            fields.append('groupby')
        if args.aggregate:
            for a in aggregates:
                if 'param' in a:
                    fields.append("%(func)s/%(param)s" % a)
                else:
                    fields.append(a['func'])
            for stat in statistics:
                stat.__dict__.update(stat.aggregate)
        else:
            fields.extend(['max', 'min', 'avg', 'sum', 'count'])
        fields.extend(['duration', 'duration_start', 'duration_end'])
        cols = [fields_display.get(f, f) for f in fields]
        utils.print_list(statistics, fields, cols)
Example #14
0
def do_query_alarm_history(cc, args):
    '''Query Alarm History.'''
    fields = {
        'filter': args.filter,
        'orderby': args.orderby,
        'limit': args.limit
    }
    try:
        alarm_history = cc.query_alarm_history.query(**fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm history not found')
    else:
        field_labels = ['Alarm ID', 'Event ID', 'Type', 'Detail', 'Timestamp']
        fields = ['alarm_id', 'event_id', 'type', 'detail', 'timestamp']
        utils.print_list(alarm_history,
                         fields,
                         field_labels,
                         formatters={'rule': alarm_change_detail_formatter},
                         sortby=None)
Example #15
0
def do_sample_list(cc, args):
    '''List the samples for a meter.'''
    fields = {
        'meter_name': args.meter,
        'q': options.cli_to_array(args.query),
        'limit': args.limit
    }
    try:
        samples = cc.samples.list(**fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Samples not found: %s' % args.meter)
    else:
        field_labels = [
            'Resource ID', 'Name', 'Type', 'Volume', 'Unit', 'Timestamp'
        ]
        fields = [
            'resource_id', 'counter_name', 'counter_type', 'counter_volume',
            'counter_unit', 'timestamp'
        ]
        utils.print_list(samples, fields, field_labels, sortby=None)
Example #16
0
def do_sample_list(cc, args):
    '''List the samples for this meters.'''
    fields = {
        'counter_name': args.counter_name,
        'resource_id': args.resource_id,
        'user_id': args.user_id,
        'project_id': args.project_id,
        'source': args.source,
        'start_timestamp': args.start,
        'end_timestamp': args.end,
        'metaquery': args.metaquery
    }
    try:
        samples = cc.samples.list(**fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Samples not found: %s' % args.counter_name)
    else:
        field_labels = ['Resource ID', 'Name', 'Type', 'Volume', 'Timestamp']
        fields = [
            'resource_id', 'counter_name', 'counter_type', 'counter_volume',
            'timestamp'
        ]
        utils.print_list(samples, fields, field_labels, sortby=0)
Example #17
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exc.HTTPNotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(str(name_or_id))
        return manager.get(name_or_id)
    except (ValueError, exc.HTTPNotFound):
        pass

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exc.HTTPNotFound:
        msg = "No %s with a name or ID of '%s' exists." % \
              (manager.resource_class.__name__.lower(), name_or_id)
        raise exc.CommandError(msg)
Example #18
0
def do_query_alarms(cc, args):
    '''Query Alarms.'''
    fields = {
        'filter': args.filter,
        'orderby': args.orderby,
        'limit': args.limit
    }
    try:
        alarms = cc.query_alarms.query(**fields)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarms not found')
    else:
        field_labels = [
            'Alarm ID', 'Name', 'State', 'Enabled', 'Continuous',
            'Alarm condition'
        ]
        fields = [
            'alarm_id', 'name', 'state', 'enabled', 'repeat_actions', 'rule'
        ]
        utils.print_list(alarms,
                         fields,
                         field_labels,
                         formatters={'rule': alarm_rule_formatter},
                         sortby=None)
 def test_dash_d_switch_raises_error(self, mock_ksclient):
     mock_ksclient.side_effect = exc.CommandError("FAIL")
     self.make_env()
     args = ['-d', 'event-list']
     self.assertRaises(exc.CommandError, ceilometer_shell.main, args)
Example #20
0
def do_alarm_delete(cc, args={}):
    '''Delete an alarm.'''
    try:
        cc.alarms.delete(args.alarm_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Alarm not found: %s' % args.alarm_id)