def test_with_dot(self): ar = options.cli_to_array('metadata.this<=34') self.assertEqual(ar, [{ 'field': 'metadata.this', 'op': 'le', 'value': '34' }])
def _do_test_typed_float_op(self, op, op_str): ar = options.cli_to_array('that%sfloat::283.347' % op) self.assertEqual([{'field': 'that', 'type': 'float', 'value': '283.347', 'op': op_str}], ar)
def do_resource_list(cc, args={}): """List the resources.""" resources = cc.resources.list(q=options.cli_to_array(args.query)) field_labels = ["Resource ID", "Source", "User ID", "Project ID"] fields = ["resource_id", "source", "user_id", "project_id"] utils.print_list(resources, fields, field_labels, sortby=1)
def do_sample_list(client, args): fields = { 'meter_name': args.meter, 'q': options.cli_to_array(args.query), 'limit': args.limit } return client.samples.list(**fields)
def do_resource_list(cc, args={}): '''List the resources.''' resources = cc.resources.list(q=options.cli_to_array(args.query)) field_labels = ['Resource ID', 'Source', 'User ID', 'Project ID'] fields = ['resource_id', 'source', 'user_id', 'project_id'] utils.print_list(resources, fields, field_labels, sortby=1)
def test_float(self): ar = options.cli_to_array('this<=283.347') self.assertEqual(ar, [{ 'field': 'this', 'op': 'le', 'value': '283.347' }])
def test_typed_string_whitespace(self): ar = options.cli_to_array('state=string::insufficient data') self.assertEqual([{'field': 'state', 'op': 'eq', 'type': 'string', 'value': 'insufficient data'}], ar)
def test_comma(self): ar = options.cli_to_array('this=2.4,fooo=doof') self.assertEqual([{'field': 'this', 'op': 'eq', 'value': '2.4,fooo=doof', 'type': ''}], ar)
def test_special_character(self): ar = options.cli_to_array('key~123=value!123') self.assertEqual([{'field': 'key~123', 'op': 'eq', 'value': 'value!123', 'type': ''}], ar)
def do_alarm_list(cc, args={}): '''List all active alarms.''' includeUUID = args.uuid include_suppress = False if args.include_suppress: include_suppress = True include_mgmt_affecting = False if args.mgmt_affecting: include_mgmt_affecting = True faults = cc.ialarm.list(q=options.cli_to_array(args.query), include_suppress=include_suppress) for f in faults: cgts_utils.normalize_field_data(f, ['entity_type_id', 'entity_instance_id', 'reason_text', 'proposed_repair_action']) # omit action initially to keep output width sane # (can switch over to vertical formatting when available from CLIFF) def hightlightAlarmId(alarm): suppressed = hasattr(alarm,"suppression_status") and alarm.suppression_status=="suppressed" if suppressed: value = "S({})".format(alarm.alarm_id) else: value = alarm.alarm_id return value field_labels = ['Alarm ID', 'Reason Text', 'Entity ID', 'Severity', 'Time Stamp'] fields = ['alarm_id', 'reason_text', 'entity_instance_id', 'severity', 'timestamp'] # for best results, ensure width ratios add up to 1 (=100%) formatterSpec = { "alarm_id" : {"formatter" : hightlightAlarmId, "wrapperFormatter": .08}, "reason_text" : .54, "entity_instance_id" : .15, "severity" : .10, "timestamp" : .10, } if includeUUID: field_labels.insert(0, 'UUID') fields.insert(0, 'uuid') # for best results, ensure width ratios add up to 1 (=100%) formatterSpec['uuid'] = wrapping_formatters.UUID_MIN_LENGTH formatterSpec['reason_text'] -= .05 formatterSpec['entity_instance_id'] -= .02 if include_mgmt_affecting: field_labels.insert(4, 'Management Affecting') fields.insert(4, 'mgmt_affecting') # for best results, ensure width ratios add up to 1 (=100%) formatterSpec['mgmt_affecting'] = .08 formatterSpec['reason_text'] -= .05 formatterSpec['severity'] -= .03 formatters = wrapping_formatters.build_wrapping_formatters(faults, fields, field_labels, formatterSpec) cgts_utils.print_list(faults, fields, field_labels, formatters=formatters, sortby=fields.index('timestamp'), reversesort=True)
def test_with_float_data_type(self): ar = options.cli_to_array('average=float::1234.5678') self.assertEqual(ar, [{ 'field': 'average', 'op': 'eq', 'type': 'float', 'value': '1234.5678' }])
def test_with_datetime_data_type(self): ar = options.cli_to_array('timestamp=datetime::sometimestamp') self.assertEqual(ar, [{ 'field': 'timestamp', 'op': 'eq', 'type': 'datetime', 'value': 'sometimestamp' }])
def test_with_incorrect_type(self): ar = options.cli_to_array('timestamp=invalid::sometimestamp') self.assertEqual(ar, [{ 'field': 'timestamp', 'op': 'eq', 'type': '', 'value': 'invalid::sometimestamp' }])
def test_comma(self): ar = options.cli_to_array('this=2.4,fooo=doof') self.assertEqual([{ 'field': 'this', 'op': 'eq', 'value': '2.4,fooo=doof', 'type': '' }], ar)
def test_typed_string_whitespace(self): ar = options.cli_to_array('state=string::insufficient data') self.assertEqual([{ 'field': 'state', 'op': 'eq', 'type': 'string', 'value': 'insufficient data' }], ar)
def test_with_bool_data_type(self): ar = options.cli_to_array('port=boolean::true') self.assertEqual(ar, [{ 'field': 'port', 'op': 'eq', 'type': 'boolean', 'value': 'true' }])
def test_with_int_data_type(self): ar = options.cli_to_array('port=integer::1234') self.assertEqual(ar, [{ 'field': 'port', 'op': 'eq', 'type': 'integer', 'value': '1234' }])
def test_negative(self): ar = options.cli_to_array('this>=-783') self.assertEqual(ar, [{ 'field': 'this', 'op': 'ge', 'value': '-783', 'type': '' }])
def do_meter_list(cc, args={}): '''List the user's meters.''' meters = cc.meters.list(q=options.cli_to_array(args.query)) field_labels = [ 'Name', 'Type', 'Unit', 'Resource ID', 'User ID', 'Project ID' ] fields = ['name', 'type', 'unit', 'resource_id', 'user_id', 'project_id'] utils.print_list(meters, fields, field_labels, sortby=0)
def test_one(self): ar = options.cli_to_array('this<=34') self.assertEqual(ar, [{ 'field': 'this', 'op': 'le', 'value': '34', 'type': '' }])
def test_with_string_data_type(self): ar = options.cli_to_array('hostname=string::localhost') self.assertEqual(ar, [{ 'field': 'hostname', 'op': 'eq', 'type': 'string', 'value': 'localhost' }])
def test_with_single_colon(self): ar = options.cli_to_array('timestamp=datetime:sometimestamp') self.assertEqual(ar, [{ 'field': 'timestamp', 'op': 'eq', 'type': '', 'value': 'datetime:sometimestamp' }])
def _do_test_typed_float_op(self, op, op_str): ar = options.cli_to_array('that%sfloat::283.347' % op) self.assertEqual([{ 'field': 'that', 'type': 'float', 'value': '283.347', 'op': op_str }], ar)
def test_special_character(self): ar = options.cli_to_array('key~123=value!123') self.assertEqual([{ 'field': 'key~123', 'op': 'eq', 'value': 'value!123', 'type': '' }], ar)
def test_typed_string_whitespace_complex(self): ar = options.cli_to_array("that>=float::99.9999;state=string::insufficient data") self.assertEqual( [ {"field": "that", "op": "ge", "type": "float", "value": "99.9999"}, {"field": "state", "op": "eq", "type": "string", "value": "insufficient data"}, ], ar, )
def test_timestamp_value(self): ar = options.cli_to_array("project=cow;timestamp>=datetime::2014-03-11T16:02:58") self.assertEqual( [ {"field": "project", "op": "eq", "type": "", "value": "cow"}, {"field": "timestamp", "op": "ge", "type": "datetime", "value": "2014-03-11T16:02:58"}, ], ar, )
def test_two(self): ar = options.cli_to_array("this<=34;that!=foo") self.assertEqual( ar, [ {"field": "this", "op": "le", "value": "34", "type": ""}, {"field": "that", "op": "ne", "value": "foo", "type": ""}, ], )
def do_meter_list(cc, args={}): '''List the user's meters.''' meters = cc.meters.list(q=options.cli_to_array(args.query)) field_labels = ['Name', 'Type', 'Unit', 'Resource ID', 'User ID', 'Project ID'] fields = ['name', 'type', 'unit', 'resource_id', 'user_id', 'project_id'] utils.print_list(meters, fields, field_labels, sortby=0)
def do_alarm_threshold_create(cc, args={}): '''Create a new alarm based on computed statistics.''' fields = dict(filter(lambda x: not (x[1] is None), vars(args).items())) fields = utils.key_with_slash_to_nested_dict(fields) fields['type'] = 'threshold' if 'query' in fields['threshold_rule']: fields['threshold_rule']['query'] = options.cli_to_array( fields['threshold_rule']['query']) alarm = cc.alarms.create(**fields) _display_alarm(alarm)
def _do_old_sample_list(cc, args): 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)
def do_event_list(cc, args={}): '''List events.''' events = cc.events.list(q=options.cli_to_array(args.query)) field_labels = ['Message ID', 'Event Type', 'Generated', 'Traits'] fields = ['message_id', 'event_type', 'generated', 'traits'] utils.print_list(events, fields, field_labels, formatters={ 'traits': utils.nested_list_of_dict_formatter( 'traits', ['name', 'type', 'value'] )})
def test_single_char_field_or_value(self): ar = options.cli_to_array("m<=34;large.thing>s;x!=y") self.assertEqual( [ {"field": "m", "op": "le", "value": "34", "type": ""}, {"field": "large.thing", "op": "gt", "value": "s", "type": ""}, {"field": "x", "op": "ne", "value": "y", "type": ""}, ], ar, )
def do_alarm_threshold_create(cc, args={}): """Create a new 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["type"] = "threshold" if "query" in fields["threshold_rule"]: fields["threshold_rule"]["query"] = options.cli_to_array(fields["threshold_rule"]["query"]) alarm = cc.alarms.create(**fields) _display_alarm(alarm)
def do_alarm_list(cc, args={}): '''List the user's alarms.''' alarms = cc.alarms.list(q=options.cli_to_array(args.query)) # omit action initially to keep output width sane # (can switch over to vertical formatting when available from CLIFF) 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=0)
def do_alarm_list(cc, args={}): '''List the user's alarms.''' alarms = cc.alarms.list(q=options.cli_to_array(args.query)) # omit action initially to keep output width sane # (can switch over to vertical formatting when available from CLIFF) field_labels = ['Name', 'Description', 'State', 'Enabled', 'Continuous', 'Alarm ID', 'User ID', 'Project ID'] fields = ['name', 'description', 'state', 'enabled', 'repeat_actions', 'alarm_id', 'user_id', 'project_id'] utils.print_list(alarms, fields, field_labels, sortby=0)
def test_two(self): ar = options.cli_to_array('this<=34;that!=foo') self.assertEqual(ar, [{ 'field': 'this', 'op': 'le', 'value': '34' }, { 'field': 'that', 'op': 'ne', 'value': 'foo' }])
def do_statistics(client, 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} return client.statistics.list(**api_args)
def filter_ceilometer_stats(instance_id, meters): ceilometer = get_client(api_version=2, **{ 'os_username': os.environ.get("OS_USERNAME"), 'os_password': os.environ.get("OS_PASSWORD"), 'os_tenant_name': os.environ.get("OS_TENANT_NAME"), 'os_auth_url': os.environ.get("OS_AUTH_URL"), }) for meter in meters: for stat in ceilometer.statistics.list(meter_name=meter.get('field'), q=cli_to_array("resource_id={0}".format(instance_id))): yield getattr(operator, meter.get('op'))(float(stat.avg), float(meter.get('value')))
def _event_suppression_list(cc, include_unsuppressed=False): query = 'suppression_status=string::suppressed' queryAsArray = [] if include_unsuppressed: query = None if query != None: queryAsArray = options.cli_to_array(query) event_suppression_list = cc.event_suppression.list(q=queryAsArray) return event_suppression_list
def test_timestamp_value(self): ar = options.cli_to_array( 'project=cow;timestamp>=datetime::2014-03-11T16:02:58' ) self.assertEqual([{'field': 'project', 'op': 'eq', 'type': '', 'value': 'cow'}, {'field': 'timestamp', 'op': 'ge', 'type': 'datetime', 'value': '2014-03-11T16:02:58'}], ar)
def test_typed_string_whitespace_complex(self): ar = options.cli_to_array( 'that>=float::99.9999;state=string::insufficient data' ) self.assertEqual([{'field': 'that', 'op': 'ge', 'type': 'float', 'value': '99.9999'}, {'field': 'state', 'op': 'eq', 'type': 'string', 'value': 'insufficient data'}], ar)
def test_with_whitespace(self): ar = options.cli_to_array('start_timestamp= 2015-01-01T00:00:00;' ' end_timestamp =2015-06-20T14:01:59 ') self.assertEqual([{'field': 'start_timestamp', 'op': 'eq', 'type': '', 'value': '2015-01-01T00:00:00'}, {'field': 'end_timestamp', 'op': 'eq', 'type': '', 'value': '2015-06-20T14:01:59'}], ar)
def do_statistics(client, 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 } return client.statistics.list(**api_args)
def do_alarm_list(cc, args={}): '''List the user's alarms.''' alarms = cc.alarms.list(q=options.cli_to_array(args.query)) # omit action initially to keep output width sane # (can switch over to vertical formatting when available from CLIFF) field_labels = ['Name', 'Description', 'Metric', 'Period', 'Count', 'Threshold', 'Comparison', 'State', 'Enabled', 'Alarm ID', 'User ID', 'Project ID'] fields = ['name', 'description', 'counter_name', 'period', 'evaluation_periods', 'threshold', 'comparison_operator', 'state', 'enabled', 'alarm_id', 'user_id', 'project_id'] utils.print_list(alarms, fields, field_labels, sortby=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)
def do_sample_list(cc, args): """List the samples for this meters""" fields = {"meter_name": args.meter, "q": options.cli_to_array(args.query)} if args.meter is None: raise exc.CommandError("Meter name not provided (-m <meter name>)") 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=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.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)
def test_typed_string_whitespace_complex(self): ar = options.cli_to_array( 'that>=float::99.9999;state=string::insufficient data') self.assertEqual([{ 'field': 'that', 'op': 'ge', 'type': 'float', 'value': '99.9999' }, { 'field': 'state', 'op': 'eq', 'type': 'string', 'value': 'insufficient data' }], ar)
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)
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"] # We're using sortby=None as the alarm history returned from the Ceilometer # is already sorted in the "the newer state is the earlier one in the # list". If we'll pass any field as a sortby param, it'll be sorted in the # ASC way by the PrettyTable utils.print_list(history, fields, field_labels, formatters={"detail": alarm_change_detail_formatter}, sortby=None)
def test_timestamp_value(self): ar = options.cli_to_array( 'project=cow;timestamp>=datetime::2014-03-11T16:02:58') self.assertEqual([{ 'field': 'project', 'op': 'eq', 'type': '', 'value': 'cow' }, { 'field': 'timestamp', 'op': 'ge', 'type': 'datetime', 'value': '2014-03-11T16:02:58' }], ar)
def do_event_list(cc, args={}): """List events.""" events = cc.events.list(q=options.cli_to_array(args.query)) field_labels = ["Message ID", "Event Type", "Generated", "Traits"] fields = ["message_id", "event_type", "generated", "traits"] if args.no_traits: field_labels.pop() fields.pop() utils.print_list( events, fields, field_labels, formatters={"traits": utils.nested_list_of_dict_formatter("traits", ["name", "type", "value"])}, sortby=None, )
def do_sample_list(cc, args): '''List the samples for this meters.''' fields = {'meter_name': args.meter, 'q': options.cli_to_array(args.query)} 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=0)
def test_single_char_field_or_value(self): ar = options.cli_to_array('m<=34;large.thing>s;x!=y') self.assertEqual([{'field': 'm', 'op': 'le', 'value': '34', 'type': ''}, {'field': 'large.thing', 'op': 'gt', 'value': 's', 'type': ''}, {'field': 'x', 'op': 'ne', 'value': 'y', 'type': ''}], ar)