def _setup_sample_triggers(self, names=['st2.test.trigger1', 'st2.test.trigger2', 'st2.test.trigger3']): trigger_dbs = [] for name in names: trigtype = None try: trigtype = TriggerTypeDB() trigtype.pack = 'dummy_pack_1' trigtype.name = name trigtype.description = '' trigtype.payload_schema = {} trigtype.parameters_schema = {} try: trigtype = TriggerType.get_by_name(name) except: trigtype = TriggerType.add_or_update(trigtype) except NotUniqueError: pass created = TriggerDB() created.name = name created.pack = 'dummy_pack_1' created.description = '' created.type = trigtype.get_reference().ref created.parameters = {} created = Trigger.add_or_update(created) trigger_dbs.append(created) return trigger_dbs
def _create_trigger_type(pack, name, description=None, payload_schema=None, parameters_schema=None): triggertypes = TriggerType.query(pack=pack, name=name) is_update = False if len(triggertypes) > 0: trigger_type = triggertypes[0] LOG.debug( 'Found existing trigger id:%s with name:%s. Will update ' 'trigger.', trigger_type.id, name) is_update = True else: trigger_type = TriggerTypeDB() trigger_type.pack = pack trigger_type.name = name trigger_type.description = description trigger_type.payload_schema = payload_schema trigger_type.parameters_schema = parameters_schema try: triggertype_db = TriggerType.add_or_update(trigger_type) except: LOG.exception('Validation failed for TriggerType=%s.', trigger_type) raise TriggerTypeRegistrationException('Invalid TriggerType name=%s.' % name) if is_update: LOG.audit('TriggerType updated. TriggerType=%s', triggertype_db) else: LOG.audit('TriggerType created. TriggerType=%s', triggertype_db) return triggertype_db
def _create_trigger_type(pack, name, description=None, payload_schema=None, parameters_schema=None): triggertypes = TriggerType.query(pack=pack, name=name) is_update = False if len(triggertypes) > 0: trigger_type = triggertypes[0] LOG.debug('Found existing trigger id:%s with name:%s. Will update ' 'trigger.', trigger_type.id, name) is_update = True else: trigger_type = TriggerTypeDB() trigger_type.pack = pack trigger_type.name = name trigger_type.description = description trigger_type.payload_schema = payload_schema trigger_type.parameters_schema = parameters_schema try: triggertype_db = TriggerType.add_or_update(trigger_type) except: LOG.exception('Validation failed for TriggerType=%s.', trigger_type) raise TriggerTypeRegistrationException('Invalid TriggerType name=%s.' % name) if is_update: LOG.audit('TriggerType updated. TriggerType=%s', triggertype_db) else: LOG.audit('TriggerType created. TriggerType=%s', triggertype_db) return triggertype_db
def test_existing_rules_are_loaded_on_start(self): # Assert that we dispatch message for every existing Trigger object St2Timer._handle_create_trigger = Mock() timer = St2Timer() timer._scheduler = Mock() timer._trigger_watcher.run = Mock() # Verify there are no Trigger and TriggerType in the db wh:w self.assertItemsEqual(Trigger.get_all(), []) self.assertItemsEqual(TriggerType.get_all(), []) # Add a dummy timer Trigger object type = TIMER_TRIGGER_TYPES.keys()[0] parameters = {'unit': 'seconds', 'delta': 1000} trigger_db = TriggerDB(name='test_trigger_1', pack='dummy', type=type, parameters=parameters) trigger_db = Trigger.add_or_update(trigger_db) # Verify object has been added self.assertEqual(len(Trigger.get_all()), 1) timer.start() timer._trigger_watcher._load_thread.wait() # Verify handlers are called timer._handle_create_trigger.assert_called_with(trigger_db)
def post(self, triggertype): """ Create a new triggertype. Handles requests: POST /triggertypes/ """ LOG.info('POST /triggertypes/ with triggertype data=%s', triggertype) try: triggertype_db = TriggerTypeAPI.to_model(triggertype) triggertype_db = TriggerType.add_or_update(triggertype_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for triggertype data=%s.', triggertype) abort(http_client.BAD_REQUEST, str(e)) return except NotUniqueError as e: LOG.warn('TriggerType creation of %s failed with uniqueness conflict. Exception : %s', triggertype, str(e)) abort(http_client.CONFLICT, str(e)) return else: LOG.audit('TriggerType created. TriggerType=%s', triggertype_db) if not triggertype_db.parameters_schema: TriggerTypeController._create_shadow_trigger(triggertype_db) triggertype_api = TriggerTypeAPI.from_model(triggertype_db) LOG.debug('POST /triggertypes/ client_result=%s', triggertype_api) return triggertype_api
def test_add_trigger_type_with_params(self): MOCK_TRIGGER.type = 'system.test' # Trigger type with params should not create a trigger. PARAMETERS_SCHEMA = { "type": "object", "properties": { "url": { "type": "string" } }, "required": ['url'], "additionalProperties": False } trig_type = { 'name': 'myawesometriggertype2', 'pack': 'dummy_pack_1', 'description': 'Words cannot describe how awesome I am.', 'parameters_schema': PARAMETERS_SCHEMA, 'payload_schema': {} } trigtype_dbs = container_utils.add_trigger_models( pack='my_pack_1', trigger_types=[trig_type]) trigger_type, trigger = trigtype_dbs[0] trigtype_db = TriggerType.get_by_id(trigger_type.id) self.assertEqual(trigtype_db.pack, 'my_pack_1') self.assertEqual(trigtype_db.name, trig_type.get('name')) self.assertEqual(trigger, None)
def create_or_update_trigger_type_db(trigger_type): """ Create or update a trigger type db object in the db given trigger_type definition as dict. :param trigger_type: Trigger type model. :type trigger_type: ``dict`` :rtype: ``object`` """ assert isinstance(trigger_type, dict) trigger_type_api = TriggerTypeAPI(**trigger_type) trigger_type_api = TriggerTypeAPI.to_model(trigger_type_api) ref = ResourceReference.to_string_reference(name=trigger_type_api.name, pack=trigger_type_api.pack) existing_trigger_type_db = get_trigger_type_db(ref) if existing_trigger_type_db: is_update = True else: is_update = False if is_update: trigger_type_api.id = existing_trigger_type_db.id trigger_type_db = TriggerType.add_or_update(trigger_type_api) if is_update: LOG.audit('TriggerType updated. TriggerType=%s', trigger_type_db) else: LOG.audit('TriggerType created. TriggerType=%s', trigger_type_db) return trigger_type_db
def post(self, triggertype): """ Create a new triggertype. Handles requests: POST /triggertypes/ """ try: triggertype_db = TriggerTypeAPI.to_model(triggertype) triggertype_db = TriggerType.add_or_update(triggertype_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for triggertype data=%s.', triggertype) abort(http_client.BAD_REQUEST, str(e)) return except StackStormDBObjectConflictError as e: LOG.warn('TriggerType creation of %s failed with uniqueness conflict. Exception : %s', triggertype, str(e)) abort(http_client.CONFLICT, str(e), body={'conflict-id': e.conflict_id}) return else: extra = {'triggertype_db': triggertype_db} LOG.audit('TriggerType created. TriggerType.id=%s' % (triggertype_db.id), extra=extra) if not triggertype_db.parameters_schema: TriggerTypeController._create_shadow_trigger(triggertype_db) triggertype_api = TriggerTypeAPI.from_model(triggertype_db) return triggertype_api
def _setup_sample_trigger(self, name): trigtype = TriggerTypeDB() trigtype.name = name trigtype.pack = 'dummy_pack_1' trigtype.description = '' trigtype.payload_schema = {} trigtype.parameters_schema = {} TriggerType.add_or_update(trigtype) created = TriggerDB() created.name = name created.pack = 'dummy_pack_1' created.description = '' created.type = trigtype.get_reference().ref created.parameters = {} Trigger.add_or_update(created)
def put(self, triggertype_ref_or_id, triggertype): try: triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id) except Exception as e: LOG.exception(e.message) abort(http_client.NOT_FOUND, e.message) return triggertype_id = triggertype_db.id try: validate_not_part_of_system_pack(triggertype_db) except ValueValidationException as e: abort(http_client.BAD_REQUEST, str(e)) try: triggertype_db = TriggerTypeAPI.to_model(triggertype) if triggertype.id is not None and len(triggertype.id) > 0 and \ triggertype.id != triggertype_id: LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.', triggertype.id, triggertype_id) triggertype_db.id = triggertype_id old_triggertype_db = triggertype_db triggertype_db = TriggerType.add_or_update(triggertype_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for triggertype data=%s', triggertype) abort(http_client.BAD_REQUEST, str(e)) return extra = {'old_triggertype_db': old_triggertype_db, 'new_triggertype_db': triggertype_db} LOG.audit('TriggerType updated. TriggerType.id=%s' % (triggertype_db.id), extra=extra) triggertype_api = TriggerTypeAPI.from_model(triggertype_db) return triggertype_api
def test_add_trigger_type_with_params(self): MOCK_TRIGGER.type = 'system.test' # Trigger type with params should not create a trigger. PARAMETERS_SCHEMA = { "type": "object", "properties": { "url": {"type": "string"} }, "required": ['url'], "additionalProperties": False } trig_type = { 'name': 'myawesometriggertype2', 'pack': 'dummy_pack_1', 'description': 'Words cannot describe how awesome I am.', 'parameters_schema': PARAMETERS_SCHEMA, 'payload_schema': {} } trigtype_dbs = container_utils.add_trigger_models(pack='my_pack_1', trigger_types=[trig_type]) trigger_type, trigger = trigtype_dbs[0] trigtype_db = TriggerType.get_by_id(trigger_type.id) self.assertEqual(trigtype_db.pack, 'my_pack_1') self.assertEqual(trigtype_db.name, trig_type.get('name')) self.assertEqual(trigger, None)
def post(self, triggertype): """ Create a new triggertype. Handles requests: POST /triggertypes/ """ try: triggertype_db = TriggerTypeAPI.to_model(triggertype) triggertype_db = TriggerType.add_or_update(triggertype_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for triggertype data=%s.', triggertype) abort(http_client.BAD_REQUEST, str(e)) return except StackStormDBObjectConflictError as e: LOG.warn( 'TriggerType creation of %s failed with uniqueness conflict. Exception : %s', triggertype, str(e)) abort(http_client.CONFLICT, str(e), body={'conflict-id': e.conflict_id}) return else: extra = {'triggertype_db': triggertype_db} LOG.audit('TriggerType created. TriggerType.id=%s' % (triggertype_db.id), extra=extra) if not triggertype_db.parameters_schema: TriggerTypeController._create_shadow_trigger(triggertype_db) triggertype_api = TriggerTypeAPI.from_model(triggertype_db) return triggertype_api
def test_triggertype_crud(self): saved = ReactorModelTest._create_save_triggertype() retrieved = TriggerType.get_by_id(saved.id) self.assertEqual(saved.name, retrieved.name, 'Same triggertype was not returned.') # test update self.assertEqual(retrieved.description, '') retrieved.description = DUMMY_DESCRIPTION saved = TriggerType.add_or_update(retrieved) retrieved = TriggerType.get_by_id(saved.id) self.assertEqual(retrieved.description, DUMMY_DESCRIPTION, 'Update to trigger failed.') # cleanup ReactorModelTest._delete([retrieved]) try: retrieved = TriggerType.get_by_id(saved.id) except ValueError: retrieved = None self.assertIsNone(retrieved, 'managed to retrieve after failure.')
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)
def test_trigger_types_are_registered_on_start(self): timer = St2Timer() timer._scheduler = Mock() # Verify there are no TriggerType in the db when we start self.assertItemsEqual(TriggerType.get_all(), []) timer.start() # Verify TriggerType objects have been created trigger_type_dbs = TriggerType.get_all() self.assertEqual(len(trigger_type_dbs), len(TIMER_TRIGGER_TYPES)) timer_trigger_type_refs = TIMER_TRIGGER_TYPES.keys() for trigger_type in trigger_type_dbs: ref = ResourceReference(pack=trigger_type.pack, name=trigger_type.name).ref self.assertTrue(ref in timer_trigger_type_refs)
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)))
def delete(self, triggertype_ref_or_id): """ Delete a triggertype. Handles requests: DELETE /triggertypes/1 DELETE /triggertypes/pack.name """ LOG.info('DELETE /triggertypes/ with ref_or_id=%s', triggertype_ref_or_id) try: triggertype_db = self._get_by_ref_or_id( ref_or_id=triggertype_ref_or_id) except Exception as e: LOG.exception(e.message) abort(http_client.NOT_FOUND, e.message) return triggertype_id = triggertype_db.id try: validate_not_part_of_system_pack(triggertype_db) except ValueValidationException as e: abort(http_client.BAD_REQUEST, str(e)) try: TriggerType.delete(triggertype_db) except Exception as e: LOG.exception( 'Database delete encountered exception during delete of id="%s". ', triggertype_id) abort(http_client.INTERNAL_SERVER_ERROR, str(e)) return else: extra = {'triggertype': triggertype_db} LOG.audit('TriggerType deleted. TriggerType.id=%s' % (triggertype_db.id), extra=extra) if not triggertype_db.parameters_schema: TriggerTypeController._delete_shadow_trigger(triggertype_db)
def delete(self, triggertype_ref_or_id): """ Delete a triggertype. Handles requests: DELETE /triggertypes/1 DELETE /triggertypes/pack.name """ LOG.info('DELETE /triggertypes/ with ref_or_id=%s', triggertype_ref_or_id) try: triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id) except Exception as e: LOG.exception(e.message) abort(http_client.NOT_FOUND, e.message) return triggertype_id = triggertype_db.id try: validate_not_part_of_system_pack(triggertype_db) except ValueValidationException as e: abort(http_client.BAD_REQUEST, str(e)) try: TriggerType.delete(triggertype_db) except Exception as e: LOG.exception('Database delete encountered exception during delete of id="%s". ', triggertype_id) abort(http_client.INTERNAL_SERVER_ERROR, str(e)) return else: extra = {'triggertype': triggertype_db} LOG.audit('TriggerType deleted. TriggerType.id=%s' % (triggertype_db.id), extra=extra) if not triggertype_db.parameters_schema: TriggerTypeController._delete_shadow_trigger(triggertype_db)
def get_trigger_type_db(ref): """ Returns the trigger type object from db given a string ref. :param ref: Reference to the trigger type db object. :type ref: ``str`` :rtype trigger_type: ``object`` """ try: return TriggerType.get_by_ref(ref) except ValueError as e: LOG.debug('Database lookup for ref="%s" resulted ' + 'in exception : %s.', ref, e, exc_info=True) return None
def test_add_trigger_type_no_params(self): # Trigger type with no params should create a trigger with same name as trigger type. trig_type = { 'name': 'myawesometriggertype', 'pack': 'dummy_pack_1', 'description': 'Words cannot describe how awesome I am.', 'parameters_schema': {}, 'payload_schema': {} } trigtype_dbs = container_utils.add_trigger_models( pack='my_pack_1', trigger_types=[trig_type]) trigger_type, trigger = trigtype_dbs[0] trigtype_db = TriggerType.get_by_id(trigger_type.id) self.assertEqual(trigtype_db.pack, 'my_pack_1') self.assertEqual(trigtype_db.name, trig_type.get('name')) self.assertTrue(trigger is not None) self.assertEqual(trigger.name, trigtype_db.name)
def test_add_trigger_type_no_params(self): # Trigger type with no params should create a trigger with same name as trigger type. trig_type = { 'name': 'myawesometriggertype', 'pack': 'dummy_pack_1', 'description': 'Words cannot describe how awesome I am.', 'parameters_schema': {}, 'payload_schema': {} } trigtype_dbs = container_utils.add_trigger_models(pack='my_pack_1', trigger_types=[trig_type]) trigger_type, trigger = trigtype_dbs[0] trigtype_db = TriggerType.get_by_id(trigger_type.id) self.assertEqual(trigtype_db.pack, 'my_pack_1') self.assertEqual(trigtype_db.name, trig_type.get('name')) self.assertTrue(trigger is not None) self.assertEqual(trigger.name, trigtype_db.name)
def put(self, triggertype_ref_or_id, triggertype): LOG.info( 'PUT /triggertypes/ with triggertype ref_or_id=%s and data=%s', triggertype_ref_or_id, triggertype) try: triggertype_db = self._get_by_ref_or_id( ref_or_id=triggertype_ref_or_id) except Exception as e: LOG.exception(e.message) abort(http_client.NOT_FOUND, e.message) return triggertype_id = triggertype_db.id try: validate_not_part_of_system_pack(triggertype_db) except ValueValidationException as e: abort(http_client.BAD_REQUEST, str(e)) try: triggertype_db = TriggerTypeAPI.to_model(triggertype) if triggertype.id is not None and len(triggertype.id) > 0 and \ triggertype.id != triggertype_id: LOG.warning( 'Discarding mismatched id=%s found in payload and using uri_id=%s.', triggertype.id, triggertype_id) triggertype_db.id = triggertype_id old_triggertype_db = triggertype_db triggertype_db = TriggerType.add_or_update(triggertype_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for triggertype data=%s', triggertype) abort(http_client.BAD_REQUEST, str(e)) return LOG.audit( 'TriggerType updated. TriggerType=%s and original TriggerType=%s', triggertype_db, old_triggertype_db) triggertype_api = TriggerTypeAPI.from_model(triggertype_db) LOG.debug('PUT /triggertypes/ client_result=%s', triggertype_api) return triggertype_api
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)
def create_trigger_type_db(trigger_type): """ Creates a trigger type db object in the db given trigger_type definition as dict. :param trigger_type: Trigger type model. :type trigger_type: ``dict`` :rtype: ``object`` """ trigger_type_api = TriggerTypeAPI(**trigger_type) ref = ResourceReference.to_string_reference(name=trigger_type_api.name, pack=trigger_type_api.pack) trigger_type_db = get_trigger_type_db(ref) if not trigger_type_db: trigger_type_db = TriggerTypeAPI.to_model(trigger_type_api) LOG.debug('verified trigger and formulated TriggerDB=%s', trigger_type_db) trigger_type_db = TriggerType.add_or_update(trigger_type_db) return trigger_type_db
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)))
def create_or_update_trigger_type_db(trigger_type): """ Create or update a trigger type db object in the db given trigger_type definition as dict. :param trigger_type: Trigger type model. :type trigger_type: ``dict`` :rtype: ``object`` """ assert isinstance(trigger_type, dict) trigger_type_api = TriggerTypeAPI(**trigger_type) trigger_type_api.validate() trigger_type_api = TriggerTypeAPI.to_model(trigger_type_api) ref = ResourceReference.to_string_reference(name=trigger_type_api.name, pack=trigger_type_api.pack) existing_trigger_type_db = get_trigger_type_db(ref) if existing_trigger_type_db: is_update = True else: is_update = False if is_update: trigger_type_api.id = existing_trigger_type_db.id trigger_type_db = TriggerType.add_or_update(trigger_type_api) extra = {'trigger_type_db': trigger_type_db} if is_update: LOG.audit('TriggerType updated. TriggerType.id=%s' % (trigger_type_db.id), extra=extra) else: LOG.audit('TriggerType created. TriggerType.id=%s' % (trigger_type_db.id), extra=extra) return trigger_type_db
def test_register_sensors(self): # Verify DB is empty at the beginning self.assertEqual(len(SensorType.get_all()), 0) self.assertEqual(len(TriggerType.get_all()), 0) self.assertEqual(len(Trigger.get_all()), 0) registrar = SensorsRegistrar() registrar.register_sensors_from_packs(base_dirs=[PACKS_DIR]) # Verify objects have been created sensor_dbs = SensorType.get_all() trigger_type_dbs = TriggerType.get_all() trigger_dbs = Trigger.get_all() self.assertEqual(len(sensor_dbs), 2) self.assertEqual(len(trigger_type_dbs), 2) self.assertEqual(len(trigger_dbs), 2) self.assertEqual(sensor_dbs[0].name, 'TestSensor') self.assertEqual(sensor_dbs[0].poll_interval, 10) self.assertTrue(sensor_dbs[0].enabled) self.assertEqual(sensor_dbs[1].name, 'TestSensorDisabled') self.assertEqual(sensor_dbs[1].poll_interval, 10) self.assertFalse(sensor_dbs[1].enabled) self.assertEqual(trigger_type_dbs[0].name, 'trigger_type_1') self.assertEqual(trigger_type_dbs[0].pack, 'pack_with_sensor') self.assertEqual(trigger_type_dbs[1].name, 'trigger_type_2') self.assertEqual(trigger_type_dbs[1].pack, 'pack_with_sensor') # Verify second call to registration doesn't create a duplicate objects registrar.register_sensors_from_packs(base_dirs=[PACKS_DIR]) sensor_dbs = SensorType.get_all() trigger_type_dbs = TriggerType.get_all() trigger_dbs = Trigger.get_all() self.assertEqual(len(sensor_dbs), 2) self.assertEqual(len(trigger_type_dbs), 2) self.assertEqual(len(trigger_dbs), 2) self.assertEqual(sensor_dbs[0].name, 'TestSensor') self.assertEqual(sensor_dbs[0].poll_interval, 10) self.assertEqual(trigger_type_dbs[0].name, 'trigger_type_1') self.assertEqual(trigger_type_dbs[0].pack, 'pack_with_sensor') self.assertEqual(trigger_type_dbs[1].name, 'trigger_type_2') self.assertEqual(trigger_type_dbs[1].pack, 'pack_with_sensor') # Verify sensor and trigger data is updated on registration original_load = registrar._meta_loader.load def mock_load(*args, **kwargs): # Update poll_interval and trigger_type_2 description data = original_load(*args, **kwargs) data['poll_interval'] = 50 data['trigger_types'][1]['description'] = 'test 2' return data registrar._meta_loader.load = mock_load registrar.register_sensors_from_packs(base_dirs=[PACKS_DIR]) sensor_dbs = SensorType.get_all() trigger_type_dbs = TriggerType.get_all() trigger_dbs = Trigger.get_all() self.assertEqual(len(sensor_dbs), 2) self.assertEqual(len(trigger_type_dbs), 2) self.assertEqual(len(trigger_dbs), 2) self.assertEqual(sensor_dbs[0].name, 'TestSensor') self.assertEqual(sensor_dbs[0].poll_interval, 50) self.assertEqual(trigger_type_dbs[0].name, 'trigger_type_1') self.assertEqual(trigger_type_dbs[0].pack, 'pack_with_sensor') self.assertEqual(trigger_type_dbs[1].name, 'trigger_type_2') self.assertEqual(trigger_type_dbs[1].pack, 'pack_with_sensor') self.assertEqual(trigger_type_dbs[1].description, 'test 2')