def do_alarm_delete(cc, args={}): '''Delete an alarm.''' if args.alarm_id is None: raise exc.CommandError('Alarm ID not provided (-a <alarm id>)') try: cc.alarms.delete(args.alarm_id) except exc.HTTPNotFound: raise exc.CommandError('Alarm not found: %s' % args.alarm_id)
def do_alarm_show(cc, args={}): '''Show an alarm.''' if args.alarm_id is None: raise exc.CommandError('Alarm ID not provided (-a <alarm id>)') 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)
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 ((self.auth_plugin.opts.get('token') or self.auth_plugin.opts.get('auth_token')) and self.auth_plugin.opts['endpoint']): if not self.auth_plugin.opts['username']: raise exc.CommandError("You must provide a username via " "either --os-username or via " "env[OS_USERNAME]") if not self.auth_plugin.opts['password']: raise exc.CommandError("You must provide a password via " "either --os-password or via " "env[OS_PASSWORD]") if self.no_project_and_domain_set(args): # steer users towards Keystone V3 API raise exc.CommandError("You must provide a project_id via " "either --os-project-id or via " "env[OS_PROJECT_ID] and " "a domain_name via either " "--os-user-domain-name or via " "env[OS_USER_DOMAIN_NAME] or " "a domain_id via either " "--os-user-domain-id or via " "env[OS_USER_DOMAIN_ID]") if not self.auth_plugin.opts['auth_url']: raise exc.CommandError("You must provide an auth url via " "either --os-auth-url or via " "env[OS_AUTH_URL]") client_kwargs = vars(args) client_kwargs.update(self.auth_plugin.opts) client_kwargs['auth_plugin'] = self.auth_plugin client = ceiloclient.get_client(api_version, **client_kwargs) # call whatever callback was selected try: args.func(client, args) except exc.HTTPUnauthorized: raise exc.CommandError("Invalid OpenStack Identity credentials.")
def main(self, argv): # Parse args once to find version parser = self.get_base_parser() (options, args) = parser.parse_known_args(argv) self._setup_debugging(options.debug) # build available subcommands based on version api_version = options.ceilometer_api_version subcommand_parser = self.get_subcommand_parser(api_version) self.parser = subcommand_parser # Handle top-level --help/-h before attempting to parse # a command off the command line if options.help or not argv: self.do_help(options) return 0 # Parse args again and call whatever callback was selected args = subcommand_parser.parse_args(argv) # Short-circuit and deal with help command right away. if args.func == self.do_help: self.do_help(args) return 0 if not (args.os_auth_token and args.ceilometer_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 = ceiloclient.get_client(api_version, **(args.__dict__)) try: args.func(client, args) except exc.Unauthorized: raise exc.CommandError("Invalid OpenStack Identity credentials.")
def main(self, argv): warnings.warn( "ceilometerclient is now deprecated as the Ceilometer API has " "been deprecated. Please use either aodhclient, pankoclient or " "gnocchiclient.") 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 ((self.auth_plugin.opts.get('token') or self.auth_plugin.opts.get('auth_token')) and self.auth_plugin.opts['endpoint']): if not self.auth_plugin.opts['username']: raise exc.CommandError("You must provide a username via " "either --os-username or via " "env[OS_USERNAME]") if not self.auth_plugin.opts['password']: raise exc.CommandError("You must provide a password via " "either --os-password or via " "env[OS_PASSWORD]") if not (args.os_project_id or args.os_project_name or args.os_tenant_id or args.os_tenant_name): # steer users towards Keystone V3 API raise exc.CommandError("You must provide a project_id " "(or name) via either --os-project-id " "or via env[OS_PROJECT_ID]") if not self.auth_plugin.opts['auth_url']: raise exc.CommandError("You must provide an auth url via " "either --os-auth-url or via " "env[OS_AUTH_URL]") client_kwargs = vars(args) client_kwargs.update(self.auth_plugin.opts) client_kwargs['auth_plugin'] = self.auth_plugin client = ceiloclient.get_client(api_version, **client_kwargs) # call whatever callback was selected try: args.func(client, args) except exc.HTTPUnauthorized: raise exc.CommandError("Invalid OpenStack Identity credentials.")
def do_resource_show(cc, args={}): '''Show the resource.''' if args.resource_id is None: raise exc.CommandError('Resource id not provided (-r <resource id>)') 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)
def do_alarm_show(cc, args={}): """Show an alarm.""" alarm = cc.alarms.get(args.alarm_id) if alarm is None: raise exc.CommandError('Alarm not found: %s' % args.alarm_id) else: _display_alarm(alarm)
def _discover_auth_versions(session, auth_url): # discover the API versions the server is supporting based on the # given URL v2_auth_url = None v3_auth_url = None try: ks_discover = discover.Discover(session=session, url=auth_url) v2_auth_url = ks_discover.url_for('2.0') v3_auth_url = ks_discover.url_for('3.0') except ka_exc.DiscoveryFailure: raise except exceptions.ClientException: # Identity service may not support discovery. In that case, # try to determine version from auth_url url_parts = urlparse.urlparse(auth_url) (scheme, netloc, path, params, query, fragment) = url_parts path = path.lower() if path.startswith('/v3'): v3_auth_url = auth_url elif path.startswith('/v2'): v2_auth_url = auth_url else: raise exc.CommandError('Unable to determine the Keystone ' 'version to authenticate with ' 'using the given auth_url.') return v2_auth_url, v3_auth_url
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)
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)
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 _get_token_auth_ks_session(**kwargs): cacert = kwargs.pop('cacert', None) cert = kwargs.pop('cert', None) key = kwargs.pop('key', None) insecure = kwargs.pop('insecure', False) auth_url = kwargs.pop('auth_url', None) project_id = kwargs.pop('project_id', None) project_name = kwargs.pop('project_name', None) timeout = kwargs.get('timeout') token = kwargs['token'] if insecure: verify = False else: verify = cacert or True if cert and key: # passing cert and key together is deprecated in favour of the # requests lib form of having the cert and key as a tuple cert = (cert, key) # create the keystone client session ks_session = session.Session(verify=verify, cert=cert, timeout=timeout) v2_auth_url, v3_auth_url = _discover_auth_versions(ks_session, auth_url) user_domain_name = kwargs.pop('user_domain_name', None) user_domain_id = kwargs.pop('user_domain_id', None) project_domain_name = kwargs.pop('project_domain_name', None) project_domain_id = kwargs.pop('project_domain_id', None) auth = None use_domain = (user_domain_id or user_domain_name or project_domain_id or project_domain_name) use_v3 = v3_auth_url and (use_domain or (not v2_auth_url)) use_v2 = v2_auth_url and not use_domain if use_v3: auth = v3_auth.Token(v3_auth_url, token=token, project_name=project_name, project_id=project_id, project_domain_name=project_domain_name, project_domain_id=project_domain_id) elif use_v2: auth = v2_auth.Token(v2_auth_url, token=token, tenant_id=project_id, tenant_name=project_name) else: raise exc.CommandError('Unable to determine the Keystone version ' 'to authenticate with using the given ' 'auth_url.') ks_session.auth = auth return ks_session
def do_alarm_update(cc, args={}): '''Update an existing alarm.''' fields = dict(filter(lambda x: not (x[1] is None), vars(args).items())) 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)
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
def do_statistics(cc, args): '''List the statistics for this meter.''' fields = {'meter_name': args.meter, 'q': options.cli_to_array(args.query), 'period': args.period} if args.meter is None: raise exc.CommandError('Meter name not provided (-m <meter name>)') try: statistics = cc.statistics.list(**fields) except exc.HTTPNotFound: raise exc.CommandError('Samples not found: %s' % args.meter) else: field_labels = ['Period', 'Period Start', 'Period End', 'Count', 'Min', 'Max', 'Sum', 'Avg', 'Duration', 'Duration Start', 'Duration End'] fields = ['period', 'period_start', 'period_end', 'count', 'min', 'max', 'sum', 'avg', 'duration', 'duration_start', 'duration_end'] utils.print_list(statistics, fields, field_labels)
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()
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.ceilometer_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 = ceiloclient.get_client(api_version, **(args.__dict__)) # call whatever callback was selected try: args.func(client, args) except exc.Unauthorized: raise exc.CommandError("Invalid OpenStack Identity credentials.")
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.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)
def update(self, alarm_id, **kwargs): self._compat_legacy_alarm_kwargs(kwargs) alarm = self.get(alarm_id) if alarm is None: raise exc.CommandError('Alarm not found: %s' % alarm_id) updated = alarm.to_dict() updated['time_constraints'] = self._merge_time_constraints( updated.get('time_constraints', []), kwargs) kwargs = dict((k, v) for k, v in kwargs.items() if k in updated and k in UPDATABLE_ATTRIBUTES) utils.merge_nested_dict(updated, kwargs, depth=1) return self._update(self._path(alarm_id), updated)
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_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: _display_alarm_list(alarms, sortby=None)
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 '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 take_action(self, parsed_args): """Update output values for an existing csv pipeline.""" ceilometer_client = self.app.client_manager.telemetry fields = dict( filter(lambda x: not (x[1] is None), vars(parsed_args).items())) fields = ceilometer_utils.key_with_slash_to_nested_dict(fields) fields.pop('name') try: pipeline = ceilometer_client.pipelines.update( parsed_args.name, **fields) except exc.HTTPNotFound: raise exc.CommandError('Pipeline not found: %s' % parsed_args.name) _show_pipeline(pipeline)
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)
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)
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 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 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
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)
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)