示例#1
0
    def _register_rules_from_pack(self, pack, rules):
        registered_count = 0

        for rule in rules:
            LOG.debug('Loading rule from %s.', rule)
            try:
                content = self._meta_loader.load(rule)
                rule_api = RuleAPI(**content)
                rule_db = RuleAPI.to_model(rule_api)

                try:
                    rule_db.id = Rule.get_by_name(rule_api.name).id
                except ValueError:
                    LOG.debug('Rule %s not found. Creating new one.', rule)

                try:
                    rule_db = Rule.add_or_update(rule_db)
                    extra = {'rule_db': rule_db}
                    LOG.audit('Rule updated. Rule %s from %s.', rule_db, rule, extra=extra)
                except Exception:
                    LOG.exception('Failed to create rule %s.', rule_api.name)
            except:
                LOG.exception('Failed registering rule from %s.', rule)
            else:
                registered_count += 1

        return registered_count
    def test_register_rules(self):
        # Verify DB is empty at the beginning
        self.assertEqual(len(Rule.get_all()), 0)
        self.assertEqual(len(Trigger.get_all()), 0)

        registrar = RulesRegistrar()
        registrar.register_rules_from_packs(base_dirs=[PACKS_DIR])

        # Verify modeles are created
        rule_dbs = Rule.get_all()
        trigger_dbs = Trigger.get_all()
        self.assertEqual(len(rule_dbs), 2)
        self.assertEqual(len(trigger_dbs), 1)

        self.assertEqual(rule_dbs[0].name, 'sample.with_the_same_timer')
        self.assertEqual(rule_dbs[1].name, 'sample.with_timer')
        self.assertTrue(trigger_dbs[0].name is not None)

        # Verify second register call updates existing models
        registrar.register_rules_from_packs(base_dirs=[PACKS_DIR])

        rule_dbs = Rule.get_all()
        trigger_dbs = Trigger.get_all()
        self.assertEqual(len(rule_dbs), 2)
        self.assertEqual(len(trigger_dbs), 1)
示例#3
0
    def post(self, rule):
        """
            Create a new rule.

            Handles requests:
                POST /rules/
        """
        LOG.info('POST /rules/ with rule data=%s', rule)

        try:
            rule_db = RuleAPI.to_model(rule)
            LOG.debug('/rules/ POST verified RuleAPI and formulated RuleDB=%s', rule_db)
            rule_db = Rule.add_or_update(rule_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except ValueValidationException as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except NotUniqueError as e:
            LOG.warn('Rule creation of %s failed with uniqueness conflict. Exception %s',
                     rule, str(e))
            abort(http_client.CONFLICT, str(e))
            return

        LOG.audit('Rule created. Rule=%s', rule_db)
        rule_api = RuleAPI.from_model(rule_db)
        LOG.debug('POST /rules/ client_result=%s', rule_api)

        return rule_api
示例#4
0
    def post(self, rule):
        """
            Create a new rule.

            Handles requests:
                POST /rules/
        """
        LOG.info('POST /rules/ with rule data=%s', rule)

        try:
            rule_db = RuleAPI.to_model(rule)
            LOG.debug('/rules/ POST verified RuleAPI and formulated RuleDB=%s',
                      rule_db)
            rule_db = Rule.add_or_update(rule_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except ValueValidationException as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except NotUniqueError as e:
            LOG.warn(
                'Rule creation of %s failed with uniqueness conflict. Exception %s',
                rule, str(e))
            abort(http_client.CONFLICT, str(e))
            return

        LOG.audit('Rule created. Rule=%s', rule_db)
        rule_api = RuleAPI.from_model(rule_db)
        LOG.debug('POST /rules/ client_result=%s', rule_api)

        return rule_api
示例#5
0
文件: rules.py 项目: gtmanfred/st2
    def put(self, rule_id, rule):
        LOG.info('PUT /rules/ with rule id=%s and data=%s', rule_id, rule)
        rule_db = RuleController.__get_by_id(rule_id)
        LOG.debug('PUT /rules/ lookup with id=%s found object: %s', rule_id,
                  rule_db)

        try:
            if rule.id is not None and rule.id is not '' and rule.id != rule_id:
                LOG.warning(
                    'Discarding mismatched id=%s found in payload and using uri_id=%s.',
                    rule.id, rule_id)
            old_rule_db = rule_db
            rule_db = RuleAPI.to_model(rule)
            rule_db.id = rule_id
            rule_db = Rule.add_or_update(rule_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        LOG.audit('Rule updated. Rule=%s and original Rule=%s.', rule_db,
                  old_rule_db)
        rule_api = RuleAPI.from_model(rule_db)
        LOG.debug('PUT /rules/ client_result=%s', rule_api)

        return rule_api
示例#6
0
文件: rules.py 项目: gtmanfred/st2
 def __get_by_id(rule_id):
     try:
         return Rule.get_by_id(rule_id)
     except (ValueError, ValidationError) as e:
         LOG.exception('Database lookup for id="%s" resulted in exception.',
                       rule_id)
         abort(http_client.NOT_FOUND, str(e))
 def _get_rule_db(self):
     if self._rule_file_path:
         return self._get_rule_db_from_file(
             file_path=os.path.realpath(self._rule_file_path))
     elif self._rule_ref:
         return Rule.get_by_ref(self._rule_ref)
     raise ValueError('One of _rule_file_path or _rule_ref should be specified.')
示例#8
0
文件: tester.py 项目: automotola/st2
 def _get_rule_db(self):
     if self._rule_file_path:
         return self._get_rule_db_from_file(
             file_path=os.path.realpath(self._rule_file_path))
     elif self._rule_ref:
         return Rule.get_by_ref(self._rule_ref)
     raise ValueError('One of _rule_file_path or _rule_ref should be specified.')
示例#9
0
    def post(self, rule):
        """
            Create a new rule.

            Handles requests:
                POST /rules/
        """
        try:
            rule_db = RuleAPI.to_model(rule)
            LOG.debug('/rules/ POST verified RuleAPI and formulated RuleDB=%s', rule_db)
            rule_db = Rule.add_or_update(rule_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except ValueValidationException as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except TriggerDoesNotExistException as e:
            msg = 'Trigger %s in rule does not exist in system' % rule.trigger['type']
            LOG.exception(msg)
            abort(http_client.BAD_REQUEST, msg)
            return
        except StackStormDBObjectConflictError as e:
            LOG.warn('Rule creation of %s failed with uniqueness conflict. Exception %s',
                     rule, str(e))
            abort(http_client.CONFLICT, str(e), body={'conflict-id': e.conflict_id})
            return

        extra = {'rule_db': rule_db}
        LOG.audit('Rule created. Rule.id=%s' % (rule_db.id), extra=extra)
        rule_api = RuleAPI.from_model(rule_db)

        return rule_api
示例#10
0
文件: rules.py 项目: gtmanfred/st2
 def __get_by_name(rule_name):
     try:
         return [Rule.get_by_name(rule_name)]
     except ValueError as e:
         LOG.debug(
             'Database lookup for name="%s" resulted in exception : %s.',
             rule_name, e)
         return []
示例#11
0
    def test_triggered_execution(self):
        docs = {
            'trigger_type':
            copy.deepcopy(fixture.ARTIFACTS['trigger_type']),
            'trigger':
            copy.deepcopy(fixture.ARTIFACTS['trigger']),
            'rule':
            copy.deepcopy(fixture.ARTIFACTS['rule']),
            'trigger_instance':
            copy.deepcopy(fixture.ARTIFACTS['trigger_instance'])
        }

        # Trigger an action execution.
        trigger_type = TriggerType.add_or_update(
            TriggerTypeAPI.to_model(TriggerTypeAPI(**docs['trigger_type'])))
        trigger = Trigger.add_or_update(
            TriggerAPI.to_model(TriggerAPI(**docs['trigger'])))
        rule = RuleAPI.to_model(RuleAPI(**docs['rule']))
        rule.trigger = reference.get_str_resource_ref_from_model(trigger)
        rule = Rule.add_or_update(rule)
        trigger_instance = TriggerInstance.add_or_update(
            TriggerInstanceAPI.to_model(
                TriggerInstanceAPI(**docs['trigger_instance'])))
        enforcer = RuleEnforcer(trigger_instance, rule)
        enforcer.enforce()

        # Wait for the action execution to complete and then confirm outcome.
        liveaction = LiveAction.get(
            context__trigger_instance__id=str(trigger_instance.id))
        self.assertIsNotNone(liveaction)
        liveaction = LiveAction.get_by_id(str(liveaction.id))
        self.assertEqual(liveaction.status, LIVEACTION_STATUS_FAILED)
        execution = self._get_action_execution(liveaction__id=str(
            liveaction.id),
                                               raise_exception=True)
        self.assertDictEqual(execution.trigger,
                             vars(TriggerAPI.from_model(trigger)))
        self.assertDictEqual(execution.trigger_type,
                             vars(TriggerTypeAPI.from_model(trigger_type)))
        self.assertDictEqual(
            execution.trigger_instance,
            vars(TriggerInstanceAPI.from_model(trigger_instance)))
        self.assertDictEqual(execution.rule, vars(RuleAPI.from_model(rule)))
        action = action_utils.get_action_by_ref(liveaction.action)
        self.assertDictEqual(execution.action,
                             vars(ActionAPI.from_model(action)))
        runner = RunnerType.get_by_name(action.runner_type['name'])
        self.assertDictEqual(execution.runner,
                             vars(RunnerTypeAPI.from_model(runner)))
        liveaction = LiveAction.get_by_id(str(liveaction.id))
        self.assertEqual(execution.start_timestamp, liveaction.start_timestamp)
        self.assertEqual(execution.end_timestamp, liveaction.end_timestamp)
        self.assertEqual(execution.result, liveaction.result)
        self.assertEqual(execution.status, liveaction.status)
        self.assertEqual(execution.context, liveaction.context)
        self.assertEqual(execution.liveaction['callback'], liveaction.callback)
        self.assertEqual(execution.liveaction['action'], liveaction.action)
示例#12
0
    def test_triggered_execution(self):
        docs = {
            'trigger_type':
            copy.deepcopy(fixture.ARTIFACTS['trigger_type']),
            'trigger':
            copy.deepcopy(fixture.ARTIFACTS['trigger']),
            'rule':
            copy.deepcopy(fixture.ARTIFACTS['rule']),
            'trigger_instance':
            copy.deepcopy(fixture.ARTIFACTS['trigger_instance'])
        }

        # Trigger an action execution.
        trigger_type = TriggerType.add_or_update(
            TriggerTypeAPI.to_model(TriggerTypeAPI(**docs['trigger_type'])))
        trigger = Trigger.add_or_update(
            TriggerAPI.to_model(TriggerAPI(**docs['trigger'])))
        rule = RuleAPI.to_model(RuleAPI(**docs['rule']))
        rule.trigger = reference.get_str_resource_ref_from_model(trigger)
        rule = Rule.add_or_update(rule)
        trigger_instance = TriggerInstance.add_or_update(
            TriggerInstanceAPI.to_model(
                TriggerInstanceAPI(**docs['trigger_instance'])))
        enforcer = RuleEnforcer(trigger_instance, rule)
        enforcer.enforce()

        # Wait for the action execution to complete and then confirm outcome.
        execution = ActionExecution.get(
            context__trigger_instance__id=str(trigger_instance.id))
        self.assertIsNotNone(execution)
        execution = ActionExecution.get_by_id(str(execution.id))
        self.assertEqual(execution.status, ACTIONEXEC_STATUS_SUCCEEDED)
        history = ActionExecutionHistory.get(execution__id=str(execution.id),
                                             raise_exception=True)
        self.assertDictEqual(history.trigger,
                             vars(TriggerAPI.from_model(trigger)))
        self.assertDictEqual(history.trigger_type,
                             vars(TriggerTypeAPI.from_model(trigger_type)))
        self.assertDictEqual(
            history.trigger_instance,
            vars(TriggerInstanceAPI.from_model(trigger_instance)))
        self.assertDictEqual(history.rule, vars(RuleAPI.from_model(rule)))
        action_ref = ResourceReference.from_string_reference(
            ref=execution.action)
        action, _ = action_utils.get_action_by_dict({
            'name': action_ref.name,
            'pack': action_ref.pack
        })
        self.assertDictEqual(history.action,
                             vars(ActionAPI.from_model(action)))
        runner = RunnerType.get_by_name(action.runner_type['name'])
        self.assertDictEqual(history.runner,
                             vars(RunnerTypeAPI.from_model(runner)))
        execution = ActionExecution.get_by_id(str(execution.id))
        self.assertDictEqual(history.execution,
                             vars(ActionExecutionAPI.from_model(execution)))
示例#13
0
文件: rules.py 项目: miqui/st2
    def delete(self, rule_id):
        """
            Delete a rule.

            Handles requests:
                DELETE /rules/1
        """
        LOG.info('DELETE /rules/ with id=%s', rule_id)
        rule_db = RuleController.__get_by_id(rule_id)
        LOG.debug('DELETE /rules/ lookup with id=%s found object: %s', rule_id, rule_db)
        try:
            Rule.delete(rule_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".',
                          rule_id)
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return

        LOG.audit('Rule deleted. Rule=%s.', rule_db)
示例#14
0
    def delete(self, rule_id):
        """
            Delete a rule.

            Handles requests:
                DELETE /rules/1
        """
        rule_db = RuleController.__get_by_id(rule_id)
        LOG.debug('DELETE /rules/ lookup with id=%s found object: %s', rule_id, rule_db)
        try:
            Rule.delete(rule_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".',
                          rule_id)
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return

        extra = {'rule_db': rule_db}
        LOG.audit('Rule deleted. Rule.id=%s.' % (rule_db.id), extra=extra)
示例#15
0
文件: test_db.py 项目: srenatus/st2
 def test_rule_lookup(self):
     triggertype = ReactorModelTest._create_save_triggertype()
     trigger = ReactorModelTest._create_save_trigger(triggertype)
     runnertype = ActionModelTest._create_save_runnertype()
     action = ActionModelTest._create_save_action(runnertype)
     saved = ReactorModelTest._create_save_rule(trigger, action)
     retrievedrules = Rule.query(trigger=reference.get_str_resource_ref_from_model(trigger))
     self.assertEqual(1, len(retrievedrules), 'No rules found.')
     for retrievedrule in retrievedrules:
         self.assertEqual(saved.id, retrievedrule.id, 'Incorrect rule returned.')
     ReactorModelTest._delete([saved, trigger, action, runnertype, triggertype])
示例#16
0
    def get_matching_rules_for_trigger(self, trigger_instance):
        trigger = get_trigger_db(trigger=trigger_instance.trigger)
        rules = Rule.query(trigger=trigger_instance.trigger, enabled=True)
        LOG.info('Found %d rules defined for trigger %s', len(rules), trigger['name'])
        matcher = RulesMatcher(trigger_instance=trigger_instance,
                               trigger=trigger, rules=rules)

        matching_rules = matcher.get_matching_rules()
        LOG.info('Matched %s rule(s) for trigger_instance %s.', len(matching_rules),
                 trigger['name'])
        return matching_rules
示例#17
0
 def test_rule_lookup(self):
     triggertype = ReactorModelTest._create_save_triggertype()
     trigger = ReactorModelTest._create_save_trigger(triggertype)
     runnertype = ActionModelTest._create_save_runnertype()
     action = ActionModelTest._create_save_action(runnertype)
     saved = ReactorModelTest._create_save_rule(trigger, action)
     retrievedrules = Rule.query(trigger=reference.get_str_resource_ref_from_model(trigger))
     self.assertEqual(1, len(retrievedrules), 'No rules found.')
     for retrievedrule in retrievedrules:
         self.assertEqual(saved.id, retrievedrule.id, 'Incorrect rule returned.')
     ReactorModelTest._delete([saved, trigger, action, runnertype, triggertype])
示例#18
0
 def test_rule_crud(self):
     triggertype = ReactorModelTest._create_save_triggertype()
     trigger = ReactorModelTest._create_save_trigger(triggertype)
     runnertype = ActionModelTest._create_save_runnertype()
     action = ActionModelTest._create_save_action(runnertype)
     saved = ReactorModelTest._create_save_rule(trigger, action)
     retrieved = Rule.get_by_id(saved.id)
     self.assertEqual(saved.name, retrieved.name, 'Same rule was not returned.')
     # test update
     self.assertEqual(retrieved.enabled, True)
     retrieved.enabled = False
     saved = Rule.add_or_update(retrieved)
     retrieved = Rule.get_by_id(saved.id)
     self.assertEqual(retrieved.enabled, False, 'Update to rule failed.')
     # cleanup
     ReactorModelTest._delete([retrieved, trigger, action, runnertype, triggertype])
     try:
         retrieved = Rule.get_by_id(saved.id)
     except ValueError:
         retrieved = None
     self.assertIsNone(retrieved, 'managed to retrieve after failure.')
示例#19
0
文件: unload.py 项目: zwunix/st2
    def _unregister_trigger_types(self, pack):
        deleted_trigger_types_dbs = self._delete_pack_db_objects(pack=pack, access_cls=TriggerType)

        # 2. Check if deleted trigger is used by any other rules outside this pack
        for trigger_type_db in deleted_trigger_types_dbs:
            rule_dbs = Rule.query(trigger=trigger_type_db.ref, pack__ne=trigger_type_db.pack)

            for rule_db in rule_dbs:
                self.logger.warning('Rule "%s" references deleted trigger "%s"' %
                                    (rule_db.name, trigger_type_db.ref))

        return deleted_trigger_types_dbs
示例#20
0
文件: test_db.py 项目: srenatus/st2
 def test_rule_crud(self):
     triggertype = ReactorModelTest._create_save_triggertype()
     trigger = ReactorModelTest._create_save_trigger(triggertype)
     runnertype = ActionModelTest._create_save_runnertype()
     action = ActionModelTest._create_save_action(runnertype)
     saved = ReactorModelTest._create_save_rule(trigger, action)
     retrieved = Rule.get_by_id(saved.id)
     self.assertEqual(saved.name, retrieved.name, 'Same rule was not returned.')
     # test update
     self.assertEqual(retrieved.enabled, True)
     retrieved.enabled = False
     saved = Rule.add_or_update(retrieved)
     retrieved = Rule.get_by_id(saved.id)
     self.assertEqual(retrieved.enabled, False, 'Update to rule failed.')
     # cleanup
     ReactorModelTest._delete([retrieved, trigger, action, runnertype, triggertype])
     try:
         retrieved = Rule.get_by_id(saved.id)
     except ValueError:
         retrieved = None
     self.assertIsNone(retrieved, 'managed to retrieve after failure.')
示例#21
0
文件: unload.py 项目: LindsayHill/st2
    def _unregister_trigger_types(self, pack):
        deleted_trigger_types_dbs = self._delete_pack_db_objects(pack=pack, access_cls=TriggerType)

        # 2. Check if deleted trigger is used by any other rules outside this pack
        for trigger_type_db in deleted_trigger_types_dbs:
            rule_dbs = Rule.query(trigger=trigger_type_db.ref, pack__ne=trigger_type_db.pack)

            for rule_db in rule_dbs:
                self.logger.warning('Rule "%s" references deleted trigger "%s"' %
                                    (rule_db.name, trigger_type_db.ref))

        return deleted_trigger_types_dbs
示例#22
0
文件: engine.py 项目: timff/st2
    def get_matching_rules_for_trigger(self, trigger_instance):
        trigger = trigger_instance.trigger
        trigger = get_trigger_db_by_ref(trigger_instance.trigger)
        rules = Rule.query(trigger=trigger_instance.trigger, enabled=True)
        LOG.info('Found %d rules defined for trigger %s', len(rules), trigger['name'])
        matcher = RulesMatcher(trigger_instance=trigger_instance,
                               trigger=trigger, rules=rules)

        matching_rules = matcher.get_matching_rules()
        LOG.info('Matched %s rule(s) for trigger_instance %s.', len(matching_rules),
                 trigger['name'])
        return matching_rules
示例#23
0
    def get_all(self, **kw):
        """
            List all rules.

            Handles requests:
                GET /rules/
        """
        LOG.info('GET all /rules/ with filters=%s', kw)
        rule_dbs = Rule.get_all(**kw)
        rule_apis = [RuleAPI.from_model(rule_db) for rule_db in rule_dbs]
        LOG.debug('GET all /rules/ client_result=%s', rule_apis)
        return rule_apis
示例#24
0
    def get_all(self, **kw):
        """
            List all rules.

            Handles requests:
                GET /rules/
        """
        LOG.info('GET all /rules/ with filters=%s', kw)
        rule_dbs = Rule.get_all(**kw)
        rule_apis = [RuleAPI.from_model(rule_db) for rule_db in rule_dbs]
        LOG.debug('GET all /rules/ client_result=%s', rule_apis)
        return rule_apis
示例#25
0
 def _create_save_rule(trigger, action=None, enabled=True):
     created = RuleDB()
     created.name = 'rule-1'
     created.description = ''
     created.enabled = enabled
     created.trigger = reference.get_str_resource_ref_from_model(trigger)
     created.criteria = {}
     created.action = ActionExecutionSpecDB()
     action_ref = ResourceReference(pack=action.pack, name=action.name).ref
     created.action.ref = action_ref
     created.action.pack = action.pack
     created.action.parameters = {}
     return Rule.add_or_update(created)
示例#26
0
文件: test_db.py 项目: srenatus/st2
 def _create_save_rule(trigger, action=None, enabled=True):
     created = RuleDB()
     created.name = 'rule-1'
     created.description = ''
     created.enabled = enabled
     created.trigger = reference.get_str_resource_ref_from_model(trigger)
     created.criteria = {}
     created.action = ActionExecutionSpecDB()
     action_ref = ResourceReference(pack=action.pack, name=action.name).ref
     created.action.ref = action_ref
     created.action.pack = action.pack
     created.action.parameters = {}
     return Rule.add_or_update(created)
示例#27
0
def _register_rules_from_pack(pack, rules):
    for rule in rules:
        LOG.debug('Loading rule from %s.', rule)
        try:
            with open(rule, 'r') as fd:
                try:
                    content = json.load(fd)
                except ValueError:
                    LOG.exception('Unable to load rule from %s.', rule)
                    continue
                rule_api = RuleAPI(**content)
                rule_db = RuleAPI.to_model(rule_api)
                try:
                    rule_db.id = Rule.get_by_name(rule_api.name).id
                except ValueError:
                    LOG.info('Rule %s not found. Creating new one.', rule)
                try:
                    rule_db = Rule.add_or_update(rule_db)
                    LOG.audit('Rule updated. Rule %s from %s.', rule_db, rule)
                except Exception:
                    LOG.exception('Failed to create rule %s.', rule_api.name)
        except:
            LOG.exception('Failed registering rule from %s.', rule)
示例#28
0
    def test_triggered_execution(self):
        docs = {
            'trigger_type': copy.deepcopy(fixture.ARTIFACTS['trigger_type']),
            'trigger': copy.deepcopy(fixture.ARTIFACTS['trigger']),
            'rule': copy.deepcopy(fixture.ARTIFACTS['rule']),
            'trigger_instance': copy.deepcopy(fixture.ARTIFACTS['trigger_instance'])}

        # Trigger an action execution.
        trigger_type = TriggerType.add_or_update(
            TriggerTypeAPI.to_model(TriggerTypeAPI(**docs['trigger_type'])))
        trigger = Trigger.add_or_update(TriggerAPI.to_model(TriggerAPI(**docs['trigger'])))
        rule = RuleAPI.to_model(RuleAPI(**docs['rule']))
        rule.trigger = reference.get_str_resource_ref_from_model(trigger)
        rule = Rule.add_or_update(rule)
        trigger_instance = TriggerInstance.add_or_update(
            TriggerInstanceAPI.to_model(TriggerInstanceAPI(**docs['trigger_instance'])))
        enforcer = RuleEnforcer(trigger_instance, rule)
        enforcer.enforce()

        # Wait for the action execution to complete and then confirm outcome.
        liveaction = LiveAction.get(context__trigger_instance__id=str(trigger_instance.id))
        self.assertIsNotNone(liveaction)
        liveaction = LiveAction.get_by_id(str(liveaction.id))
        self.assertEqual(liveaction.status, LIVEACTION_STATUS_FAILED)
        execution = self._get_action_execution(liveaction__id=str(liveaction.id),
                                               raise_exception=True)
        self.assertDictEqual(execution.trigger, vars(TriggerAPI.from_model(trigger)))
        self.assertDictEqual(execution.trigger_type, vars(TriggerTypeAPI.from_model(trigger_type)))
        self.assertDictEqual(execution.trigger_instance,
                             vars(TriggerInstanceAPI.from_model(trigger_instance)))
        self.assertDictEqual(execution.rule, vars(RuleAPI.from_model(rule)))
        action = action_utils.get_action_by_ref(liveaction.action)
        self.assertDictEqual(execution.action, vars(ActionAPI.from_model(action)))
        runner = RunnerType.get_by_name(action.runner_type['name'])
        self.assertDictEqual(execution.runner, vars(RunnerTypeAPI.from_model(runner)))
        liveaction = LiveAction.get_by_id(str(liveaction.id))
        self.assertEqual(execution.start_timestamp, liveaction.start_timestamp)
        self.assertEqual(execution.end_timestamp, liveaction.end_timestamp)
        self.assertEqual(execution.result, liveaction.result)
        self.assertEqual(execution.status, liveaction.status)
        self.assertEqual(execution.context, liveaction.context)
        self.assertEqual(execution.liveaction['callback'], liveaction.callback)
        self.assertEqual(execution.liveaction['action'], liveaction.action)
示例#29
0
文件: rules.py 项目: gtmanfred/st2
    def post(self, rule):
        """
            Create a new rule.

            Handles requests:
                POST /rules/
        """
        LOG.info('POST /rules/ with rule data=%s', rule)

        try:
            rule_db = RuleAPI.to_model(rule)
            LOG.debug('/rules/ POST verified RuleAPI and formulated RuleDB=%s',
                      rule_db)
            rule_db = Rule.add_or_update(rule_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except ValueValidationException as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except TriggerDoesNotExistException as e:
            msg = 'Trigger %s in rule does not exist in system' % rule.trigger[
                'type']
            LOG.exception(msg)
            abort(http_client.BAD_REQUEST, msg)
            return
        except StackStormDBObjectConflictError as e:
            LOG.warn(
                'Rule creation of %s failed with uniqueness conflict. Exception %s',
                rule, str(e))
            abort(http_client.CONFLICT,
                  str(e),
                  body={'conflict-id': e.conflict_id})
            return

        LOG.audit('Rule created. Rule=%s', rule_db)
        rule_api = RuleAPI.from_model(rule_db)
        LOG.debug('POST /rules/ client_result=%s', rule_api)

        return rule_api
示例#30
0
    def put(self, rule_id, rule):
        rule_db = RuleController.__get_by_id(rule_id)
        LOG.debug('PUT /rules/ lookup with id=%s found object: %s', rule_id, rule_db)

        try:
            if rule.id is not None and rule.id is not '' and rule.id != rule_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            rule.id, rule_id)
            old_rule_db = rule_db
            rule_db = RuleAPI.to_model(rule)
            rule_db.id = rule_id
            rule_db = Rule.add_or_update(rule_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'old_rule_db': old_rule_db, 'new_rule_db': rule_db}
        LOG.audit('Rule updated. Rule.id=%s.' % (rule_db.id), extra=extra)
        rule_api = RuleAPI.from_model(rule_db)

        return rule_api
示例#31
0
    def test_triggered_execution(self):
        docs = {
            'trigger_type': copy.deepcopy(fixture.ARTIFACTS['trigger_type']),
            'trigger': copy.deepcopy(fixture.ARTIFACTS['trigger']),
            'rule': copy.deepcopy(fixture.ARTIFACTS['rule']),
            'trigger_instance': copy.deepcopy(fixture.ARTIFACTS['trigger_instance'])}

        # Trigger an action execution.
        trigger_type = TriggerType.add_or_update(
            TriggerTypeAPI.to_model(TriggerTypeAPI(**docs['trigger_type'])))
        trigger = Trigger.add_or_update(TriggerAPI.to_model(TriggerAPI(**docs['trigger'])))
        rule = RuleAPI.to_model(RuleAPI(**docs['rule']))
        rule.trigger = reference.get_str_resource_ref_from_model(trigger)
        rule = Rule.add_or_update(rule)
        trigger_instance = TriggerInstance.add_or_update(
            TriggerInstanceAPI.to_model(TriggerInstanceAPI(**docs['trigger_instance'])))
        enforcer = RuleEnforcer(trigger_instance, rule)
        enforcer.enforce()

        # Wait for the action execution to complete and then confirm outcome.
        execution = ActionExecution.get(context__trigger_instance__id=str(trigger_instance.id))
        self.assertIsNotNone(execution)
        execution = ActionExecution.get_by_id(str(execution.id))
        self.assertEqual(execution.status, ACTIONEXEC_STATUS_SUCCEEDED)
        history = ActionExecutionHistory.get(execution__id=str(execution.id), raise_exception=True)
        self.assertDictEqual(history.trigger, vars(TriggerAPI.from_model(trigger)))
        self.assertDictEqual(history.trigger_type, vars(TriggerTypeAPI.from_model(trigger_type)))
        self.assertDictEqual(history.trigger_instance,
                             vars(TriggerInstanceAPI.from_model(trigger_instance)))
        self.assertDictEqual(history.rule, vars(RuleAPI.from_model(rule)))
        action_ref = ResourceReference.from_string_reference(ref=execution.action)
        action, _ = action_utils.get_action_by_dict(
            {'name': action_ref.name, 'pack': action_ref.pack})
        self.assertDictEqual(history.action, vars(ActionAPI.from_model(action)))
        runner = RunnerType.get_by_name(action.runner_type['name'])
        self.assertDictEqual(history.runner, vars(RunnerTypeAPI.from_model(runner)))
        execution = ActionExecution.get_by_id(str(execution.id))
        self.assertDictEqual(history.execution, vars(ActionExecutionAPI.from_model(execution)))
示例#32
0
    def _get_sample_rules(self):
        rules = []

        RULE_1 = {
            'enabled': True,
            'name': 'st2.test.rule1',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'k1': {  # Missing prefix 'trigger'. This rule won't match.
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_1)
        rule_db = RuleAPI.to_model(rule_api)
        trigger_api = TriggerAPI(**rule_api.trigger)
        trigger_db = TriggerService.create_trigger_db(trigger_api)
        trigger_ref = reference.get_str_resource_ref_from_model(trigger_db)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_2 = {  # Rule should match.
            'enabled': True,
            'name': 'st2.test.rule2',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_2)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_3 = {
            'enabled': False,  # Disabled rule shouldn't match.
            'name': 'st2.test.rule3',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_3)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        return rules
示例#33
0
 def __get_by_name(rule_name):
     try:
         return [Rule.get_by_name(rule_name)]
     except ValueError as e:
         LOG.debug('Database lookup for name="%s" resulted in exception : %s.', rule_name, e)
         return []
示例#34
0
 def __get_by_id(rule_id):
     try:
         return Rule.get_by_id(rule_id)
     except (ValueError, ValidationError) as e:
         LOG.exception('Database lookup for id="%s" resulted in exception.', rule_id)
         abort(http_client.NOT_FOUND, str(e))
示例#35
0
    def _setup_sample_rules(self):
        rules = []

        # Rules for st2.test.trigger1
        RULE_1 = {
            'enabled': True,
            'name': 'st2.test.rule1',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'k1': {                     # Missing prefix 'trigger'. This rule won't match.
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_1)
        rule_db = RuleAPI.to_model(rule_api)
        trigger_api = TriggerAPI(**rule_api.trigger)
        trigger_db = TriggerService.create_trigger_db(trigger_api)
        trigger_ref = reference.get_str_resource_ref_from_model(trigger_db)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_2 = {                      # Rule should match.
            'enabled': True,
            'name': 'st2.test.rule2',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_2)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_3 = {
            'enabled': False,         # Disabled rule shouldn't match.
            'name': 'st2.test.rule3',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_3)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        # Rules for st2.test.trigger2
        RULE_4 = {
            'enabled': True,
            'name': 'st2.test.rule4',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger2'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_4)
        rule_db = RuleAPI.to_model(rule_api)
        trigger_api = TriggerAPI(**rule_api.trigger)
        trigger_db = TriggerService.create_trigger_db(trigger_api)
        trigger_ref = reference.get_str_resource_ref_from_model(trigger_db)
        rule_db.trigger = trigger_ref
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        return rules
示例#36
0
    def _get_sample_rules(self):
        rules = []

        RULE_1 = {
            'enabled': True,
            'name': 'st2.test.rule1',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'k1': {                     # Missing prefix 'trigger'. This rule won't match.
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_1)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_2 = {                      # Rule should match.
            'enabled': True,
            'name': 'st2.test.rule2',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_2)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_3 = {
            'enabled': False,         # Disabled rule shouldn't match.
            'name': 'st2.test.rule3',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_3)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        return rules
示例#37
0
    def _setup_sample_rules(self):
        rules = []

        # Rules for st2.test.trigger1
        RULE_1 = {
            'enabled': True,
            'name': 'st2.test.rule1',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'k1': {  # Missing prefix 'trigger'. This rule won't match.
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_1)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_2 = {  # Rule should match.
            'enabled': True,
            'name': 'st2.test.rule2',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_2)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        RULE_3 = {
            'enabled': False,  # Disabled rule shouldn't match.
            'name': 'st2.test.rule3',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger1'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_3)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        # Rules for st2.test.trigger2
        RULE_4 = {
            'enabled': True,
            'name': 'st2.test.rule4',
            'trigger': {
                'type': 'dummy_pack_1.st2.test.trigger2'
            },
            'criteria': {
                'trigger.k1': {
                    'pattern': 't1_p_v',
                    'type': 'equals'
                }
            },
            'action': {
                'ref': 'sixpack.st2.test.action',
                'parameters': {
                    'ip2': '{{rule.k1}}',
                    'ip1': '{{trigger.t1_p}}'
                }
            },
            'id': '23',
            'description': ''
        }
        rule_api = RuleAPI(**RULE_4)
        rule_db = RuleAPI.to_model(rule_api)
        rule_db = Rule.add_or_update(rule_db)
        rules.append(rule_db)

        return rules