def detail(self, goal=None, strategy=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of audit templates with detail. :param goal: goal UUID or name to filter by :param strategy: strategy UUID or name to filter by :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. """ # NOTE(lucasagomes): /detail should only work agaist collections parent = pecan.request.path.split('/')[:-1][-1] if parent != "audit_templates": raise exception.HTTPNotFound filters = {} if goal: if common_utils.is_uuid_like(goal): filters['goal_uuid'] = goal else: filters['goal_name'] = goal if strategy: if common_utils.is_uuid_like(strategy): filters['strategy_uuid'] = strategy else: filters['strategy_name'] = strategy expand = True resource_url = '/'.join(['audit_templates', 'detail']) return self._get_audit_templates_collection(filters, marker, limit, sort_key, sort_dir, expand, resource_url)
def get_all(self, goal=None, strategy=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of audit templates. :param goal: goal UUID or name to filter by :param strategy: strategy UUID or name to filter by :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. """ context = pecan.request.context policy.enforce(context, 'audit_template:get_all', action='audit_template:get_all') filters = {} if goal: if common_utils.is_uuid_like(goal): filters['goal_uuid'] = goal else: filters['goal_name'] = goal if strategy: if common_utils.is_uuid_like(strategy): filters['strategy_uuid'] = strategy else: filters['strategy_name'] = strategy return self._get_audit_templates_collection( filters, marker, limit, sort_key, sort_dir)
def _get_audits_collection(self, marker, limit, sort_key, sort_dir, expand=False, resource_url=None, audit_template=None): limit = api_utils.validate_limit(limit) api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.Audit.get_by_uuid(pecan.request.context, marker) filters = {} if audit_template: if utils.is_uuid_like(audit_template): filters['audit_template_uuid'] = audit_template else: filters['audit_template_name'] = audit_template if sort_key == 'audit_template_uuid': sort_db_key = None else: sort_db_key = sort_key audits = objects.Audit.list(pecan.request.context, limit, marker_obj, sort_key=sort_db_key, sort_dir=sort_dir, filters=filters) return AuditCollection.convert_with_links(audits, limit, url=resource_url, expand=expand, sort_key=sort_key, sort_dir=sort_dir)
def launch_action_plan(self, context, action_plan_uuid=None): if not utils.is_uuid_like(action_plan_uuid): raise exception.InvalidUuidOrName(name=action_plan_uuid) return self.client.call( context.to_dict(), 'launch_action_plan', action_plan_uuid=action_plan_uuid)
def test_create_audit_template(self, mock_utcnow): audit_template_dict = post_get_test_audit_template( goal=self.fake_goal1.uuid, strategy=self.fake_strategy1.uuid) test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json('/audit_templates', audit_template_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) # Check location header self.assertIsNotNone(response.location) expected_location = \ '/v1/audit_templates/%s' % response.json['uuid'] self.assertEqual(urlparse.urlparse(response.location).path, expected_location) self.assertTrue(utils.is_uuid_like(response.json['uuid'])) self.assertNotIn('updated_at', response.json.keys) self.assertNotIn('deleted_at', response.json.keys) self.assertEqual(self.fake_goal1.uuid, response.json['goal_uuid']) self.assertEqual(self.fake_strategy1.uuid, response.json['strategy_uuid']) return_created_at = timeutils.parse_isotime( response.json['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at)
def test_create_audit_template_generate_uuid(self): audit_template_dict = post_get_test_audit_template( goal=self.fake_goal1.uuid, strategy=None) response = self.post_json('/audit_templates', audit_template_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def test_create_audit_template_generate_uuid(self): audit_template_dict = api_utils.audit_template_post_data() del audit_template_dict['uuid'] response = self.post_json('/audit_templates', audit_template_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(audit_template_dict['goal'], response.json['goal']) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def _get_audits_collection(self, marker, limit, sort_key, sort_dir, expand=False, resource_url=None, goal=None, strategy=None, host_aggregate=None): limit = api_utils.validate_limit(limit) api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.Audit.get_by_uuid(pecan.request.context, marker) filters = {} if goal: if utils.is_uuid_like(goal): filters['goal_uuid'] = goal else: # TODO(michaelgugino): add method to get goal by name. filters['goal_name'] = goal if strategy: if utils.is_uuid_like(strategy): filters['strategy_uuid'] = strategy else: # TODO(michaelgugino): add method to get goal by name. filters['strategy_name'] = strategy if sort_key == 'goal_uuid': sort_db_key = 'goal_id' elif sort_key == 'strategy_uuid': sort_db_key = 'strategy_id' else: sort_db_key = sort_key audits = objects.Audit.list(pecan.request.context, limit, marker_obj, sort_key=sort_db_key, sort_dir=sort_dir, filters=filters) return AuditCollection.convert_with_links(audits, limit, url=resource_url, expand=expand, sort_key=sort_key, sort_dir=sort_dir)
def test_create_audit_generate_uuid(self, mock_trigger_audit): mock_trigger_audit.return_value = mock.ANY audit_dict = post_get_test_audit() del audit_dict['uuid'] response = self.post_json('/audits', audit_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(objects.audit.State.PENDING, response.json['state']) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def get(cls, context, efficacy_indicator_id): """Find an efficacy indicator object given its ID or UUID :param efficacy_indicator_id: the ID or UUID of an efficacy indicator. :returns: a :class:`EfficacyIndicator` object. """ if utils.is_int_like(efficacy_indicator_id): return cls.get_by_id(context, efficacy_indicator_id) elif utils.is_uuid_like(efficacy_indicator_id): return cls.get_by_uuid(context, efficacy_indicator_id) else: raise exception.InvalidIdentity(identity=efficacy_indicator_id)
def get(cls, context, action_plan_id): """Find a action_plan based on its id or uuid and return a Action object. :param action_plan_id: the id *or* uuid of a action_plan. :returns: a :class:`Action` object. """ if utils.is_int_like(action_plan_id): return cls.get_by_id(context, action_plan_id) elif utils.is_uuid_like(action_plan_id): return cls.get_by_uuid(context, action_plan_id) else: raise exception.InvalidIdentity(identity=action_plan_id)
def get(cls, context, action_id, eager=False): """Find a action based on its id or uuid and return a Action object. :param action_id: the id *or* uuid of a action. :param eager: Load object fields if True (Default: False) :returns: a :class:`Action` object. """ if utils.is_int_like(action_id): return cls.get_by_id(context, action_id, eager=eager) elif utils.is_uuid_like(action_id): return cls.get_by_uuid(context, action_id, eager=eager) else: raise exception.InvalidIdentity(identity=action_id)
def test_create_audit_generate_uuid(self, mock_trigger_audit): mock_trigger_audit.return_value = mock.ANY audit_dict = post_get_test_audit( params_to_exclude=['uuid', 'state', 'interval', 'scope', 'next_run_time', 'hostname', 'goal']) response = self.post_json('/audits', audit_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(objects.audit.State.PENDING, response.json['state']) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def detail(self, goal=None, strategy=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of audit templates with detail. :param goal: goal UUID or name to filter by :param strategy: strategy UUID or name to filter by :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. """ context = pecan.request.context policy.enforce(context, 'audit_template:detail', action='audit_template:detail') # NOTE(lucasagomes): /detail should only work agaist collections parent = pecan.request.path.split('/')[:-1][-1] if parent != "audit_templates": raise exception.HTTPNotFound filters = {} if goal: if common_utils.is_uuid_like(goal): filters['goal_uuid'] = goal else: filters['goal_name'] = goal if strategy: if common_utils.is_uuid_like(strategy): filters['strategy_uuid'] = strategy else: filters['strategy_name'] = strategy expand = True resource_url = '/'.join(['audit_templates', 'detail']) return self._get_audit_templates_collection(filters, marker, limit, sort_key, sort_dir, expand, resource_url)
def delete(self, audit_template): """Delete a audit template. :param audit template_uuid: UUID or name of an audit template. """ if common_utils.is_uuid_like(audit_template): audit_template_to_delete = objects.AuditTemplate.get_by_uuid( pecan.request.context, audit_template) else: audit_template_to_delete = objects.AuditTemplate.get_by_name( pecan.request.context, audit_template) audit_template_to_delete.soft_delete()
def statistic_aggregation(self, resource_id=None, meter_name=None, period=300, granularity=300, dimensions=None, aggregation='avg', group_by='*'): """Representing a statistic aggregate by operators :param resource_id: id of resource to list statistics for. :param meter_name: meter name of which we want the statistics. :param period: Period in seconds over which to group samples. :param granularity: frequency of marking metric point, in seconds. :param dimensions: dimensions (dict). This param isn't used in Gnocchi datasource. :param aggregation: Should be chosen in accordance with policy aggregations. :param group_by: list of columns to group the metrics to be returned. This param isn't used in Gnocchi datasource. :return: value of aggregated metric """ stop_time = datetime.utcnow() start_time = stop_time - timedelta(seconds=(int(period))) if not common_utils.is_uuid_like(resource_id): kwargs = dict(query={"=": {"original_resource_id": resource_id}}, limit=1) resources = self.query_retry( f=self.gnocchi.resource.search, **kwargs) if not resources: raise exception.ResourceNotFound(name=resource_id) resource_id = resources[0]['id'] raw_kwargs = dict( metric=meter_name, start=start_time, stop=stop_time, resource_id=resource_id, granularity=granularity, aggregation=aggregation, ) kwargs = {k: v for k, v in raw_kwargs.items() if k and v} statistics = self.query_retry( f=self.gnocchi.metric.get_measures, **kwargs) if statistics: # return value of latest measure # measure has structure [time, granularity, value] return statistics[-1][2]
def _get_goal(self, value): if value == wtypes.Unset: return None goal = None try: if utils.is_uuid_like(value) or utils.is_int_like(value): goal = objects.Goal.get(pecan.request.context, value) else: goal = objects.Goal.get_by_name(pecan.request.context, value) except exception.GoalNotFound: pass if goal: self.goal_id = goal.id return goal
def _get_goal(self, value): if value == wtypes.Unset: return None goal = None try: if (common_utils.is_uuid_like(value) or common_utils.is_int_like(value)): goal = objects.Goal.get(pecan.request.context, value) else: goal = objects.Goal.get_by_name(pecan.request.context, value) except exception.GoalNotFound: pass if goal: self.goal_id = goal.id return goal
def _get_strategy(self, value): if value == wtypes.Unset: return None strategy = None try: if utils.is_uuid_like(value) or utils.is_int_like(value): strategy = objects.Strategy.get(pecan.request.context, value) else: strategy = objects.Strategy.get_by_name( pecan.request.context, value) except exception.StrategyNotFound: pass if strategy: self.strategy_id = strategy.id return strategy
def get_one(self, audit_template): """Retrieve information about the given audit template. :param audit audit_template: UUID or name of an audit template. """ if self.from_audit_templates: raise exception.OperationNotPermitted if common_utils.is_uuid_like(audit_template): rpc_audit_template = objects.AuditTemplate.get_by_uuid( pecan.request.context, audit_template) else: rpc_audit_template = objects.AuditTemplate.get_by_name( pecan.request.context, audit_template) return AuditTemplate.convert_with_links(rpc_audit_template)
def _get_strategy(self, value): if value == wtypes.Unset: return None strategy = None try: if utils.is_uuid_like(value) or utils.is_int_like(value): strategy = objects.Strategy.get( pecan.request.context, value) else: strategy = objects.Strategy.get_by_name( pecan.request.context, value) except exception.GoalNotFound: pass if strategy: self.strategy_id = strategy.id return strategy
def get_audit_scope(self, context, audit=None): scope = None try: if utils.is_uuid_like(audit) or utils.is_int_like(audit): audit = objects.Audit.get( context, audit) else: audit = objects.Audit.get_by_name( context, audit) except exception.AuditNotFound: raise exception.InvalidIdentity(identity=audit) if audit: scope = audit.scope else: scope = [] return scope
def _get_audit_template(self, value): if value == wtypes.Unset: return None audit_template = None try: if utils.is_uuid_like(value) or utils.is_int_like(value): audit_template = objects.AuditTemplate.get( pecan.request.context, value) else: audit_template = objects.AuditTemplate.get_by_name( pecan.request.context, value) except exception.AuditTemplateNotFound: pass if audit_template: self.audit_template_id = audit_template.id return audit_template
def test_create_continuous_audit_with_period(self, mock_trigger_audit): mock_trigger_audit.return_value = mock.ANY audit_dict = post_get_test_audit() del audit_dict['uuid'] del audit_dict['state'] del audit_dict['scope'] audit_dict['audit_type'] = objects.audit.AuditType.CONTINUOUS.value audit_dict['interval'] = 1200 response = self.post_json('/audits', audit_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(objects.audit.State.PENDING, response.json['state']) self.assertEqual(audit_dict['interval'], response.json['interval']) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def test_create_continuous_audit_with_cron_interval( self, mock_trigger_audit): mock_trigger_audit.return_value = mock.ANY audit_dict = post_get_test_audit(params_to_exclude=[ 'uuid', 'state', 'scope', 'next_run_time', 'hostname', 'goal' ]) audit_dict['audit_type'] = objects.audit.AuditType.CONTINUOUS.value audit_dict['interval'] = '* * * * *' response = self.post_json('/audits', audit_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(objects.audit.State.PENDING, response.json['state']) self.assertEqual(audit_dict['interval'], response.json['interval']) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def test_create_continuous_audit_with_period(self, mock_trigger_audit): mock_trigger_audit.return_value = mock.ANY audit_dict = post_get_test_audit() del audit_dict['uuid'] del audit_dict['state'] audit_dict['audit_type'] = objects.audit.AuditType.CONTINUOUS.value audit_dict['interval'] = 1200 response = self.post_json('/audits', audit_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(objects.audit.State.PENDING, response.json['state']) self.assertEqual(audit_dict['interval'], response.json['interval']) self.assertTrue(utils.is_uuid_like(response.json['uuid']))
def get_one(self, goal): """Retrieve information about the given goal. :param goal: UUID or name of the goal. """ if self.from_goals: raise exception.OperationNotPermitted if common_utils.is_uuid_like(goal): get_goal_func = objects.Goal.get_by_uuid else: get_goal_func = objects.Goal.get_by_name rpc_goal = get_goal_func(pecan.request.context, goal) return Goal.convert_with_links(rpc_goal)
def add_identity_filter(query, value): """Adds an identity filter to a query. Filters results by ID, if supplied value is a valid integer. Otherwise attempts to filter results by UUID. :param query: Initial query to add filter to. :param value: Value for filtering results by. :return: Modified query. """ if utils.is_int_like(value): return query.filter_by(id=value) elif utils.is_uuid_like(value): return query.filter_by(uuid=value) else: raise exception.InvalidIdentity(identity=value)
def get_one(self, strategy): """Retrieve information about the given strategy. :param strategy: UUID or name of the strategy. """ if self.from_strategies: raise exception.OperationNotPermitted if common_utils.is_uuid_like(strategy): get_strategy_func = objects.Strategy.get_by_uuid else: get_strategy_func = objects.Strategy.get_by_name rpc_strategy = get_strategy_func(pecan.request.context, strategy) return Strategy.convert_with_links(rpc_strategy)
def _get_action_plans_collection(self, marker, limit, sort_key, sort_dir, expand=False, resource_url=None, audit_uuid=None, strategy=None): limit = api_utils.validate_limit(limit) api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.ActionPlan.get_by_uuid( pecan.request.context, marker) filters = {} if audit_uuid: filters['audit_uuid'] = audit_uuid if strategy: if utils.is_uuid_like(strategy): filters['strategy_uuid'] = strategy else: filters['strategy_name'] = strategy if sort_key == 'audit_uuid': sort_db_key = None else: sort_db_key = sort_key action_plans = objects.ActionPlan.list(pecan.request.context, limit, marker_obj, sort_key=sort_db_key, sort_dir=sort_dir, filters=filters) return ActionPlanCollection.convert_with_links(action_plans, limit, url=resource_url, expand=expand, sort_key=sort_key, sort_dir=sort_dir)
def patch(self, audit_template, patch): """Update an existing audit template. :param audit template_uuid: UUID of a audit template. :param patch: a json PATCH document to apply to this audit template. """ if self.from_audit_templates: raise exception.OperationNotPermitted context = pecan.request.context audit_template_to_update = api_utils.get_resource('AuditTemplate', audit_template) policy.enforce(context, 'audit_template:update', audit_template_to_update, action='audit_template:update') if common_utils.is_uuid_like(audit_template): audit_template_to_update = objects.AuditTemplate.get_by_uuid( pecan.request.context, audit_template) else: audit_template_to_update = objects.AuditTemplate.get_by_name( pecan.request.context, audit_template) try: audit_template_dict = audit_template_to_update.as_dict() audit_template = AuditTemplate(**api_utils.apply_jsonpatch( audit_template_dict, patch)) except api_utils.JSONPATCH_EXCEPTIONS as e: raise exception.PatchError(patch=patch, reason=e) # Update only the fields that have changed for field in objects.AuditTemplate.fields: try: patch_val = getattr(audit_template, field) except AttributeError: # Ignore fields that aren't exposed in the API continue if patch_val == wtypes.Unset: patch_val = None if audit_template_to_update[field] != patch_val: audit_template_to_update[field] = patch_val audit_template_to_update.save() return AuditTemplate.convert_with_links(audit_template_to_update)
def _get_action_plans_collection(self, marker, limit, sort_key, sort_dir, expand=False, resource_url=None, audit_uuid=None, strategy=None): additional_fields = ['audit_uuid', 'strategy_uuid', 'strategy_name'] api_utils.validate_sort_key( sort_key, list(objects.ActionPlan.fields) + additional_fields) limit = api_utils.validate_limit(limit) api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.ActionPlan.get_by_uuid( pecan.request.context, marker) filters = {} if audit_uuid: filters['audit_uuid'] = audit_uuid if strategy: if utils.is_uuid_like(strategy): filters['strategy_uuid'] = strategy else: filters['strategy_name'] = strategy need_api_sort = api_utils.check_need_api_sort(sort_key, additional_fields) sort_db_key = (sort_key if not need_api_sort else None) action_plans = objects.ActionPlan.list( pecan.request.context, limit, marker_obj, sort_key=sort_db_key, sort_dir=sort_dir, filters=filters) action_plans_collection = ActionPlanCollection.convert_with_links( action_plans, limit, url=resource_url, expand=expand, sort_key=sort_key, sort_dir=sort_dir) if need_api_sort: api_utils.make_api_sort(action_plans_collection.action_plans, sort_key, sort_dir) return action_plans_collection
def get(cls, context, audit_id): """Find a audit based on its id or uuid and return a Audit object. :param context: Security context. NOTE: This should only be used internally by the indirection_api. Unfortunately, RPC requires context as the first argument, even though we don't use it. A context should be set when instantiating the object, e.g.: Audit(context) :param audit_id: the id *or* uuid of a audit. :returns: a :class:`Audit` object. """ if utils.is_int_like(audit_id): return cls.get_by_id(context, audit_id) elif utils.is_uuid_like(audit_id): return cls.get_by_uuid(context, audit_id) else: raise exception.InvalidIdentity(identity=audit_id)
def get(cls, context, scoring_engine_id): """Find a scoring engine based on its id or uuid :param context: Security context. NOTE: This should only be used internally by the indirection_api. Unfortunately, RPC requires context as the first argument, even though we don't use it. A context should be set when instantiating the object, e.g.: ScoringEngine(context) :param scoring_engine_name: the name of a scoring_engine. :returns: a :class:`ScoringEngine` object. """ if utils.is_int_like(scoring_engine_id): return cls.get_by_id(context, scoring_engine_id) elif utils.is_uuid_like(scoring_engine_id): return cls.get_by_uuid(context, scoring_engine_id) else: raise exception.InvalidIdentity(identity=scoring_engine_id)
def get(cls, context, goal_id): """Find a goal based on its id or uuid :param context: Security context. NOTE: This should only be used internally by the indirection_api. Unfortunately, RPC requires context as the first argument, even though we don't use it. A context should be set when instantiating the object, e.g.: Goal(context) :param goal_id: the id *or* uuid of a goal. :returns: a :class:`Goal` object. """ if utils.is_int_like(goal_id): return cls.get_by_id(context, goal_id) elif utils.is_uuid_like(goal_id): return cls.get_by_uuid(context, goal_id) else: raise exception.InvalidIdentity(identity=goal_id)
def get_all(self, goal=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of strategies. :param goal: goal UUID or name to filter by. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. """ filters = {} if goal: if common_utils.is_uuid_like(goal): filters['goal_uuid'] = goal else: filters['goal_name'] = goal return self._get_strategies_collection( filters, marker, limit, sort_key, sort_dir)
def get(cls, context, audit_id, eager=False): """Find a audit based on its id or uuid and return a Audit object. :param context: Security context. NOTE: This should only be used internally by the indirection_api. Unfortunately, RPC requires context as the first argument, even though we don't use it. A context should be set when instantiating the object, e.g.: Audit(context) :param audit_id: the id *or* uuid of a audit. :param eager: Load object fields if True (Default: False) :returns: a :class:`Audit` object. """ if utils.is_int_like(audit_id): return cls.get_by_id(context, audit_id, eager=eager) elif utils.is_uuid_like(audit_id): return cls.get_by_uuid(context, audit_id, eager=eager) else: raise exception.InvalidIdentity(identity=audit_id)
def get_goal_uuid(cls, uuid_or_name): if uuid_or_name is None: return query_func = None if not utils.is_uuid_like(uuid_or_name): query_func = objects.Goal.get_by_name else: query_func = objects.Goal.get_by_uuid try: goal = query_func(cls.ctx, uuid_or_name) except Exception as exc: LOG.exception(exc) raise exception.GoalNotFound(goal=uuid_or_name) if not goal.deleted_at: raise exception.NotSoftDeletedStateError(name=_('Goal'), id=uuid_or_name) return goal.uuid
def get_audit_template_uuid(cls, uuid_or_name): if uuid_or_name is None: return query_func = None if not utils.is_uuid_like(uuid_or_name): query_func = objects.audit_template.AuditTemplate.get_by_name else: query_func = objects.audit_template.AuditTemplate.get_by_uuid try: audit_template = query_func(cls.ctx, uuid_or_name) except Exception as exc: LOG.exception(exc) raise exception.AuditTemplateNotFound(audit_template=uuid_or_name) if not audit_template.deleted_at: raise exception.NotSoftDeletedStateError( name=_('Audit Template'), id=uuid_or_name) return audit_template.uuid
def get_goal_uuid(cls, uuid_or_name): if uuid_or_name is None: return query_func = None if not utils.is_uuid_like(uuid_or_name): query_func = objects.Goal.get_by_name else: query_func = objects.Goal.get_by_uuid try: goal = query_func(cls.ctx, uuid_or_name) except Exception as exc: LOG.exception(exc) raise exception.GoalNotFound(goal=uuid_or_name) if not goal.deleted_at: raise exception.NotSoftDeletedStateError( name=_('Goal'), id=uuid_or_name) return goal.uuid
def get_all(self, goal=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of strategies. :param goal: goal UUID or name to filter by. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. """ context = pecan.request.context policy.enforce(context, 'strategy:get_all', action='strategy:get_all') filters = {} if goal: if common_utils.is_uuid_like(goal): filters['goal_uuid'] = goal else: filters['goal_name'] = goal return self._get_strategies_collection( filters, marker, limit, sort_key, sort_dir)
def test_create_audit_template(self, mock_utcnow): audit_template_dict = post_get_test_audit_template( goal=self.fake_goal1.uuid, strategy=self.fake_strategy1.uuid) test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json('/audit_templates', audit_template_dict) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) # Check location header self.assertIsNotNone(response.location) expected_location = \ '/v1/audit_templates/%s' % response.json['uuid'] self.assertEqual( urlparse.urlparse(response.location).path, expected_location) self.assertTrue(utils.is_uuid_like(response.json['uuid'])) self.assertNotIn('updated_at', response.json.keys) self.assertNotIn('deleted_at', response.json.keys) self.assertEqual(self.fake_goal1.uuid, response.json['goal_uuid']) self.assertEqual(self.fake_strategy1.uuid, response.json['strategy_uuid']) return_created_at = timeutils.parse_isotime( response.json['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at)
def test_create_continuous_audit_with_start_end_time( self, mock_trigger_audit): mock_trigger_audit.return_value = mock.ANY start_time = datetime.datetime(2018, 3, 1, 0, 0) end_time = datetime.datetime(2018, 4, 1, 0, 0) audit_dict = post_get_test_audit( params_to_exclude=['uuid', 'state', 'scope', 'next_run_time', 'hostname', 'goal'] ) audit_dict['audit_type'] = objects.audit.AuditType.CONTINUOUS.value audit_dict['interval'] = '1200' audit_dict['start_time'] = str(start_time) audit_dict['end_time'] = str(end_time) response = self.post_json( '/audits', audit_dict, headers={'OpenStack-API-Version': 'infra-optim 1.1'}) self.assertEqual('application/json', response.content_type) self.assertEqual(201, response.status_int) self.assertEqual(objects.audit.State.PENDING, response.json['state']) self.assertEqual(audit_dict['interval'], response.json['interval']) self.assertTrue(utils.is_uuid_like(response.json['uuid'])) return_start_time = timeutils.parse_isotime( response.json['start_time']) return_end_time = timeutils.parse_isotime( response.json['end_time']) iso_start_time = start_time.replace( tzinfo=tz.tzlocal()).astimezone(tz.tzutc()) iso_end_time = end_time.replace( tzinfo=tz.tzlocal()).astimezone(tz.tzutc()) self.assertEqual(iso_start_time, return_start_time) self.assertEqual(iso_end_time, return_end_time)
def validate(value): if not utils.is_uuid_like(value): raise exception.InvalidUUID(uuid=value) return value
def check_resource_id(self, value): if (value is not None and len(value) > 0 and not utils.is_uuid_like(value)): raise voluptuous.Invalid(_("The parameter" " resource_id is invalid."))
def validate(value): if not (utils.is_uuid_like(value) or utils.is_hostname_safe(value)): raise exception.InvalidUuidOrName(name=value) return value
def trigger_audit(self, context, audit_uuid=None): if not utils.is_uuid_like(audit_uuid): raise exception.InvalidUuidOrName(name=audit_uuid) return self.conductor_client.call( context.to_dict(), 'trigger_audit', audit_uuid=audit_uuid)
def check_resource_id(self, value): if (value is not None and len(value) > 0 and not utils.is_uuid_like(value)): raise voluptuous.Invalid( _("The parameter " "resource_id is invalid."))