Esempio n. 1
0
    def post(self, execution):
        try:
            # Initialize execution context if it does not exist.
            if not hasattr(execution, 'context'):
                execution.context = dict()

            # Retrieve user context from the request header.
            user = pecan.request.headers.get('X-User-Name')
            if not user:
                user = cfg.CONF.system_user.user
            execution.context['user'] = user

            # Retrieve other st2 context from request header.
            if ('st2-context' in pecan.request.headers and pecan.request.headers['st2-context']):
                context = pecan.request.headers['st2-context'].replace("'", "\"")
                execution.context.update(json.loads(context))

            # Schedule the action execution.
            executiondb = ActionExecutionAPI.to_model(execution)
            executiondb = action_service.schedule(executiondb)
            return ActionExecutionAPI.from_model(executiondb)
        except ValueError as e:
            LOG.exception('Unable to execute action.')
            abort(http_client.BAD_REQUEST, str(e))
        except jsonschema.ValidationError as e:
            LOG.exception('Unable to execute action. Parameter validation failed.')
            abort(http_client.BAD_REQUEST, str(e))
        except Exception as e:
            LOG.exception('Unable to execute action. Unexpected error encountered.')
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
Esempio n. 2
0
    def post(self, execution):
        try:
            # Initialize execution context if it does not exist.
            if not hasattr(execution, 'context'):
                execution.context = dict()

            # Retrieve user context from the request header.
            user = pecan.request.headers.get('X-User-Name')
            if not user:
                user = cfg.CONF.system_user.user
            execution.context['user'] = user

            # Retrieve other st2 context from request header.
            if ('st2-context' in pecan.request.headers
                    and pecan.request.headers['st2-context']):
                context = pecan.request.headers['st2-context'].replace(
                    "'", "\"")
                execution.context.update(json.loads(context))

            # Schedule the action execution.
            executiondb = ActionExecutionAPI.to_model(execution)
            executiondb = action_service.schedule(executiondb)
            return ActionExecutionAPI.from_model(executiondb)
        except ValueError as e:
            LOG.exception('Unable to execute action.')
            abort(http_client.BAD_REQUEST, str(e))
        except jsonschema.ValidationError as e:
            LOG.exception(
                'Unable to execute action. Parameter validation failed.')
            abort(http_client.BAD_REQUEST, str(e))
        except Exception as e:
            LOG.exception(
                'Unable to execute action. Unexpected error encountered.')
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
Esempio n. 3
0
 def put(self, id, actionexecution):
     try:
         actionexec_db = ActionExecution.get_by_id(id)
     except:
         msg = 'ActionExecution by id: %s not found.' % id
         pecan.abort(http_client, msg)
     new_actionexec_db = ActionExecutionAPI.to_model(actionexecution)
     if actionexec_db.status != new_actionexec_db.status:
         actionexec_db.status = new_actionexec_db.status
     if actionexec_db.result != new_actionexec_db.result:
         actionexec_db.result = new_actionexec_db.result
     actionexec_db = ActionExecution.add_or_update(actionexec_db)
     actionexec_api = ActionExecutionAPI.from_model(actionexec_db)
     return actionexec_api
Esempio n. 4
0
 def put(self, id, actionexecution):
     try:
         actionexec_db = ActionExecution.get_by_id(id)
     except:
         msg = 'ActionExecution by id: %s not found.' % id
         pecan.abort(http_client, msg)
     new_actionexec_db = ActionExecutionAPI.to_model(actionexecution)
     if actionexec_db.status != new_actionexec_db.status:
         actionexec_db.status = new_actionexec_db.status
     if actionexec_db.result != new_actionexec_db.result:
         actionexec_db.result = new_actionexec_db.result
     actionexec_db = ActionExecution.add_or_update(actionexec_db)
     actionexec_api = ActionExecutionAPI.from_model(actionexec_db)
     return actionexec_api
Esempio n. 5
0
 def test_basic_execution(self):
     action_ref = ResourceReference(name='local', pack='core')
     execution = ActionExecutionDB(action=action_ref.ref,
                                   parameters={'cmd': 'uname -a'})
     execution = action_service.schedule(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, {})
     self.assertDictEqual(history.trigger_type, {})
     self.assertDictEqual(history.trigger_instance, {})
     self.assertDictEqual(history.rule, {})
     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)))
Esempio n. 6
0
 def test_chained_executions(self):
     action_ref = ResourceReference(name='chain', pack='core')
     execution = ActionExecutionDB(action=action_ref.ref)
     execution = action_service.schedule(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)
     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)))
     self.assertGreater(len(history.children), 0)
     for child in history.children:
         record = ActionExecutionHistory.get(id=child, raise_exception=True)
         self.assertEqual(record.parent, str(history.id))
         self.assertEqual(record.action['name'], 'local')
         self.assertEqual(record.runner['name'], 'run-local')
Esempio n. 7
0
    def record_action_execution(self, body):
        try:
            history_id = bson.ObjectId()
            execution = ActionExecution.get_by_id(str(body.id))
            action_ref = ResourceReference.from_string_reference(
                ref=execution.action)
            action_db, _ = action_utils.get_action_by_dict({
                'name':
                action_ref.name,
                'pack':
                action_ref.pack
            })
            runner = RunnerType.get_by_name(action_db.runner_type['name'])

            attrs = {
                'id': history_id,
                'action': vars(ActionAPI.from_model(action_db)),
                'runner': vars(RunnerTypeAPI.from_model(runner)),
                'execution': vars(ActionExecutionAPI.from_model(execution))
            }

            if 'rule' in execution.context:
                rule = reference.get_model_from_ref(
                    Rule, execution.context.get('rule', {}))
                attrs['rule'] = vars(RuleAPI.from_model(rule))

            if 'trigger_instance' in execution.context:
                trigger_instance_id = execution.context.get(
                    'trigger_instance', {})
                trigger_instance_id = trigger_instance_id.get('id', None)
                trigger_instance = TriggerInstance.get_by_id(
                    trigger_instance_id)
                trigger = reference.get_model_by_resource_ref(
                    db_api=Trigger, ref=trigger_instance.trigger)
                trigger_type = reference.get_model_by_resource_ref(
                    db_api=TriggerType, ref=trigger.type)
                trigger_instance = reference.get_model_from_ref(
                    TriggerInstance,
                    execution.context.get('trigger_instance', {}))
                attrs['trigger_instance'] = vars(
                    TriggerInstanceAPI.from_model(trigger_instance))
                attrs['trigger'] = vars(TriggerAPI.from_model(trigger))
                attrs['trigger_type'] = vars(
                    TriggerTypeAPI.from_model(trigger_type))

            parent = ActionExecutionHistory.get(
                execution__id=execution.context.get('parent', ''))
            if parent:
                attrs['parent'] = str(parent.id)
                if str(history_id) not in parent.children:
                    parent.children.append(str(history_id))
                    ActionExecutionHistory.add_or_update(parent)

            history = ActionExecutionHistoryDB(**attrs)
            history = ActionExecutionHistory.add_or_update(history)
        except:
            LOG.exception('An unexpected error occurred while creating the '
                          'action execution history.')
            raise
Esempio n. 8
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)))
Esempio n. 9
0
    def record_action_execution(self, body):
        try:
            history_id = bson.ObjectId()
            execution = ActionExecution.get_by_id(str(body.id))
            action_ref = ResourceReference.from_string_reference(ref=execution.action)
            action_db, _ = action_utils.get_action_by_dict(
                {'name': action_ref.name,
                 'pack': action_ref.pack})
            runner = RunnerType.get_by_name(action_db.runner_type['name'])

            attrs = {
                'id': history_id,
                'action': vars(ActionAPI.from_model(action_db)),
                'runner': vars(RunnerTypeAPI.from_model(runner)),
                'execution': vars(ActionExecutionAPI.from_model(execution))
            }

            if 'rule' in execution.context:
                rule = reference.get_model_from_ref(Rule, execution.context.get('rule', {}))
                attrs['rule'] = vars(RuleAPI.from_model(rule))

            if 'trigger_instance' in execution.context:
                trigger_instance_id = execution.context.get('trigger_instance', {})
                trigger_instance_id = trigger_instance_id.get('id', None)
                trigger_instance = TriggerInstance.get_by_id(trigger_instance_id)
                trigger = reference.get_model_by_resource_ref(db_api=Trigger,
                                                              ref=trigger_instance.trigger)
                trigger_type = reference.get_model_by_resource_ref(db_api=TriggerType,
                                                                   ref=trigger.type)
                trigger_instance = reference.get_model_from_ref(
                    TriggerInstance, execution.context.get('trigger_instance', {}))
                attrs['trigger_instance'] = vars(TriggerInstanceAPI.from_model(trigger_instance))
                attrs['trigger'] = vars(TriggerAPI.from_model(trigger))
                attrs['trigger_type'] = vars(TriggerTypeAPI.from_model(trigger_type))

            parent = ActionExecutionHistory.get(execution__id=execution.context.get('parent', ''))
            if parent:
                attrs['parent'] = str(parent.id)
                if str(history_id) not in parent.children:
                    parent.children.append(str(history_id))
                    ActionExecutionHistory.add_or_update(parent)

            history = ActionExecutionHistoryDB(**attrs)
            history = ActionExecutionHistory.add_or_update(history)
        except:
            LOG.exception('An unexpected error occurred while creating the '
                          'action execution history.')
            raise
Esempio n. 10
0
 def test_basic_execution(self):
     action_ref = ResourceReference(name='local', pack='core')
     execution = ActionExecutionDB(action=action_ref.ref, parameters={'cmd': 'uname -a'})
     execution = action_service.schedule(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, {})
     self.assertDictEqual(history.trigger_type, {})
     self.assertDictEqual(history.trigger_instance, {})
     self.assertDictEqual(history.rule, {})
     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)))
Esempio n. 11
0
 def update_action_execution_history(self, body):
     try:
         count = self.timeout / self.wait
         # Allow up to 1 minute for the post event to create the history record.
         for i in range(count):
             history = ActionExecutionHistory.get(execution__id=str(body.id))
             if history:
                 execution = ActionExecution.get_by_id(str(body.id))
                 history.execution = vars(ActionExecutionAPI.from_model(execution))
                 history = ActionExecutionHistory.add_or_update(history)
                 return
             if i >= count:
                 # If wait failed, create the history record regardless.
                 self.record_action_execution(body)
                 return
             eventlet.sleep(self.wait)
     except:
         LOG.exception('An unexpected error occurred while updating the '
                       'action execution history.')
         raise
Esempio n. 12
0
 def test_chained_executions(self):
     action_ref = ResourceReference(name='chain', pack='core')
     execution = ActionExecutionDB(action=action_ref.ref)
     execution = action_service.schedule(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)
     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)))
     self.assertGreater(len(history.children), 0)
     for child in history.children:
         record = ActionExecutionHistory.get(id=child, raise_exception=True)
         self.assertEqual(record.parent, str(history.id))
         self.assertEqual(record.action['name'], 'local')
         self.assertEqual(record.runner['name'], 'run-local')
Esempio n. 13
0
 def update_action_execution_history(self, body):
     try:
         count = self.timeout / self.wait
         # Allow up to 1 minute for the post event to create the history record.
         for i in range(count):
             history = ActionExecutionHistory.get(execution__id=str(body.id))
             if history:
                 execution = ActionExecution.get_by_id(str(body.id))
                 history.execution = vars(ActionExecutionAPI.from_model(execution))
                 history = ActionExecutionHistory.add_or_update(history)
                 return
             if i >= count:
                 # If wait failed, create the history record regardless.
                 self.record_action_execution(body)
                 return
             eventlet.sleep(self.wait)
     except:
         LOG.exception('An unexpected error occurred while updating the '
                       'action execution history.')
         raise
Esempio n. 14
0
 def test_basic_execution(self):
     execution = ActionExecutionDB(action='core.local',
                                   parameters={'cmd': 'uname -a'})
     execution = action_service.schedule(execution)
     execution = ActionExecution.get_by_id(str(execution.id))
     self.assertEqual(execution.status, ACTIONEXEC_STATUS_FAILED)
     history = ActionExecutionHistory.get(execution__id=str(execution.id),
                                          raise_exception=True)
     self.assertDictEqual(history.trigger, {})
     self.assertDictEqual(history.trigger_type, {})
     self.assertDictEqual(history.trigger_instance, {})
     self.assertDictEqual(history.rule, {})
     action = action_utils.get_action_by_ref('core.local')
     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)))
Esempio n. 15
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)))