示例#1
0
    def setUpClass(cls):
        super(TestStreamController, cls).setUpClass()

        instance = RunnerTypeAPI(**RUNNER_TYPE_1)
        RunnerType.add_or_update(RunnerTypeAPI.to_model(instance))

        instance = ActionAPI(**ACTION_1)
        Action.add_or_update(ActionAPI.to_model(instance))
示例#2
0
    def setUpClass(cls):
        super(TestStreamController, cls).setUpClass()

        instance = RunnerTypeAPI(**RUNNER_TYPE_1)
        RunnerType.add_or_update(RunnerTypeAPI.to_model(instance))

        instance = ActionAPI(**ACTION_1)
        Action.add_or_update(ActionAPI.to_model(instance))
    def setUpClass(cls):
        super(TestActionAPIValidator, cls).setUpClass()

        runner_api_dict = fixture.ARTIFACTS['runners']['run-local']
        runner_api = RunnerTypeAPI(**runner_api_dict)
        runner_model = RunnerTypeAPI.to_model(runner_api)

        RunnerType.add_or_update(runner_model)
示例#4
0
 def setUp(self):
     RUNNER_TYPE.id = None
     RunnerType.add_or_update(RUNNER_TYPE)
     ACTION.id = None
     ACTION.runner_type = {'name': RUNNER_TYPE.name}
     Action.add_or_update(ACTION)
     TRIGGER.id = None
     Trigger.add_or_update(TRIGGER)
示例#5
0
 def setup_runner(cls):
     test_runner = {
         'name': 'test-runner',
         'description': 'A test runner.',
         'enabled': True,
         'runner_parameters': {
             'runnerstr': {
                 'description': 'Foo str param.',
                 'type': 'string',
                 'default': 'defaultfoo'
             },
             'runnerint': {
                 'description': 'Foo int param.',
                 'type': 'number'
             },
             'runnerdummy': {
                 'description': 'Dummy param.',
                 'type': 'string',
                 'default': 'runnerdummy'
             },
             'runnerimmutable': {
                 'description': 'Immutable param.',
                 'type': 'string',
                 'default': 'runnerimmutable',
                 'immutable': True
             }
         },
         'runner_module': 'tests.test_runner'
     }
     runnertype_api = RunnerTypeAPI(**test_runner)
     RunnerContainerTest.runnertype_db = RunnerType.add_or_update(
         RunnerTypeAPI.to_model(runnertype_api))
     test_failingrunner = {
         'name': 'test-failingrunner',
         'description': 'A failing test runner.',
         'enabled': True,
         'runner_parameters': {
             'raise': {
                 'description': 'Foo str param.',
                 'type': 'boolean',
                 'default': True,
                 'immutable': True
             }
         },
         'runner_module': 'tests.test_runner'
     }
     runnertype_api = RunnerTypeAPI(**test_failingrunner)
     RunnerContainerTest.runnertype_db = RunnerType.add_or_update(
         RunnerTypeAPI.to_model(runnertype_api))
示例#6
0
 def setUpClass(cls):
     super(TestActionExecutionService, cls).setUpClass()
     cls.runner = RunnerTypeAPI(**RUNNER)
     cls.runnerdb = RunnerType.add_or_update(
         RunnerTypeAPI.to_model(cls.runner))
     cls.action = ActionAPI(**ACTION)
     cls.actiondb = Action.add_or_update(ActionAPI.to_model(cls.action))
示例#7
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)))
示例#8
0
 def setup_runner(cls):
     test_runner = {
         'name': 'test-runner',
         'description': 'A test runner.',
         'enabled': True,
         'runner_parameters': {
             'runnerstr': {
                 'description': 'Foo str param.',
                 'type': 'string',
                 'default': 'defaultfoo'
             },
             'runnerint': {
                 'description': 'Foo int param.',
                 'type': 'number'
             },
             'runnerdummy': {
                 'description': 'Dummy param.',
                 'type': 'string',
                 'default': 'runnerdummy'
             }
         },
         'runner_module': 'tests.test_runner'
     }
     runnertype_api = RunnerTypeAPI(**test_runner)
     ActionDBUtilsTestCase.runnertype_db = RunnerType.add_or_update(
         RunnerTypeAPI.to_model(runnertype_api))
 def setup_runner(cls):
     test_runner = {
         'name': 'test-runner',
         'description': 'A test runner.',
         'enabled': True,
         'runner_parameters': {
             'runnerstr': {
                 'description': 'Foo str param.',
                 'type': 'string',
                 'default': 'defaultfoo'
             },
             'runnerint': {
                 'description': 'Foo int param.',
                 'type': 'number'
             },
             'runnerdummy': {
                 'description': 'Dummy param.',
                 'type': 'string',
                 'default': 'runnerdummy'
             }
         },
         'runner_module': 'tests.test_runner'
     }
     runnertype_api = RunnerTypeAPI(**test_runner)
     ActionDBUtilsTestCase.runnertype_db = RunnerType.add_or_update(
         RunnerTypeAPI.to_model(runnertype_api))
示例#10
0
 def test_chained_executions(self):
     liveaction = LiveActionDB(action='core.chain')
     liveaction, _ = action_service.schedule(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)
     action = action_utils.get_action_by_ref('core.chain')
     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)
     self.assertGreater(len(execution.children), 0)
     for child in execution.children:
         record = ActionExecution.get(id=child, raise_exception=True)
         self.assertEqual(record.parent, str(execution.id))
         self.assertEqual(record.action['name'], 'local')
         self.assertEqual(record.runner['name'], 'run-local')
示例#11
0
 def test_basic_execution(self):
     liveaction = LiveActionDB(action='core.local',
                               parameters={'cmd': 'uname -a'})
     liveaction, _ = action_service.schedule(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, {})
     self.assertDictEqual(execution.trigger_type, {})
     self.assertDictEqual(execution.trigger_instance, {})
     self.assertDictEqual(execution.rule, {})
     action = action_utils.get_action_by_ref('core.local')
     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 get_runnertype_by_name(runnertype_name):
    """
            Get an runnertype by name.
            On error, raise ST2ObjectNotFoundError.
        """
    try:
        runnertypes = RunnerType.query(name=runnertype_name)
    except (ValueError, ValidationError) as e:
        LOG.error('Database lookup for name="%s" resulted in exception: %s',
                  runnertype_name, e)
        raise StackStormDBObjectNotFoundError(
            'Unable to find runnertype with name="%s"' % runnertype_name)

    if not runnertypes:
        LOG.error(
            'Database lookup for RunnerType with name="%s" produced no results',
            runnertype_name)
        raise StackStormDBObjectNotFoundError(
            'Unable to find RunnerType with name="%s"' % runnertype_name)

    if len(runnertypes) > 1:
        LOG.warning(
            'More than one RunnerType returned from DB lookup by name. '
            'Result list is: %s', runnertypes)

    return runnertypes[0]
示例#13
0
 def test_chained_executions(self):
     liveaction = LiveActionDB(action='core.chain')
     liveaction, _ = action_service.schedule(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)
     action = action_utils.get_action_by_ref('core.chain')
     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)
     self.assertGreater(len(execution.children), 0)
     for child in execution.children:
         record = ActionExecution.get(id=child, raise_exception=True)
         self.assertEqual(record.parent, str(execution.id))
         self.assertEqual(record.action['name'], 'local')
         self.assertEqual(record.runner['name'], 'run-local')
示例#14
0
 def test_execution_creation_action_triggered_by_rule(self):
     # Wait for the action execution to complete and then confirm outcome.
     trigger_type = self.MODELS['triggertypes']['triggertype2.json']
     trigger = self.MODELS['triggers']['trigger2.json']
     trigger_instance = self.MODELS['triggerinstances']['trigger_instance_1.json']
     test_liveaction = self.FIXTURES['liveactions']['liveaction3.json']
     rule = self.MODELS['rules']['rule3.json']
     # Setup LiveAction to point to right rule and trigger_instance.
     # XXX: We need support for dynamic fixtures.
     test_liveaction['context']['rule']['id'] = str(rule.id)
     test_liveaction['context']['trigger_instance']['id'] = str(trigger_instance.id)
     test_liveaction_api = LiveActionAPI(**test_liveaction)
     test_liveaction = LiveAction.add_or_update(LiveActionAPI.to_model(test_liveaction_api))
     liveaction = LiveAction.get(context__trigger_instance__id=str(trigger_instance.id))
     self.assertIsNotNone(liveaction)
     self.assertEqual(liveaction.status, LIVEACTION_STATUS_SCHEDULED)
     executions_util.create_execution_object(liveaction)
     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.assertEquals(execution.liveaction['id'], str(liveaction.id))
示例#15
0
def register_runner_types():
    LOG.debug('Start : register default RunnerTypes.')

    for runnertype in RUNNER_TYPES:
        try:
            runnertype_db = get_runnertype_by_name(runnertype['name'])
            update = True
        except StackStormDBObjectNotFoundError:
            runnertype_db = None
            update = False

        runnertype_api = RunnerTypeAPI(**runnertype)
        runnertype_api.validate()
        runner_type_model = RunnerTypeAPI.to_model(runnertype_api)

        if runnertype_db:
            runner_type_model.id = runnertype_db.id

        try:
            runnertype_db = RunnerType.add_or_update(runner_type_model)

            extra = {'runnertype_db': runnertype_db}
            if update:
                LOG.audit('RunnerType updated. RunnerType %s',
                          runnertype_db,
                          extra=extra)
            else:
                LOG.audit('RunnerType created. RunnerType %s',
                          runnertype_db,
                          extra=extra)
        except Exception:
            LOG.exception('Unable to register runner type %s.',
                          runnertype['name'])

    LOG.debug('End : register default RunnerTypes.')
示例#16
0
 def __get_by_id(id):
     try:
         return RunnerType.get_by_id(id)
     except (ValueError, ValidationError) as e:
         msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
         LOG.exception(msg)
         abort(http_client.NOT_FOUND, msg)
示例#17
0
def register_runner_types():
    LOG.debug('Start : register default RunnerTypes.')

    for runnertype in RUNNER_TYPES:
        try:
            runnertype_db = get_runnertype_by_name(runnertype['name'])
            update = True
        except StackStormDBObjectNotFoundError:
            runnertype_db = None
            update = False

        runnertype_api = RunnerTypeAPI(**runnertype)
        runnertype_api.validate()
        runner_type_model = RunnerTypeAPI.to_model(runnertype_api)

        if runnertype_db:
            runner_type_model.id = runnertype_db.id

        try:
            runnertype_db = RunnerType.add_or_update(runner_type_model)

            extra = {'runnertype_db': runnertype_db}
            if update:
                LOG.audit('RunnerType updated. RunnerType %s', runnertype_db, extra=extra)
            else:
                LOG.audit('RunnerType created. RunnerType %s', runnertype_db, extra=extra)
        except Exception:
            LOG.exception('Unable to register runner type %s.', runnertype['name'])

    LOG.debug('End : register default RunnerTypes.')
示例#18
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')
示例#19
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
示例#20
0
 def __get_by_name(name):
     try:
         return [RunnerType.get_by_name(name)]
     except ValueError as e:
         LOG.debug(
             'Database lookup for name="%s" resulted in exception : %s.',
             name, e)
         return []
示例#21
0
 def __get_by_id(id):
     try:
         return RunnerType.get_by_id(id)
     except (ValueError, ValidationError) as e:
         msg = 'Database lookup for id="%s" resulted in exception. %s' % (
             id, e)
         LOG.exception(msg)
         abort(http_client.NOT_FOUND, msg)
示例#22
0
def register_runner_types(experimental=False):
    """
    :param experimental: True to also register experimental runners.
    :type experimental: ``bool``
    """
    LOG.debug('Start : register default RunnerTypes.')

    for runner_type in RUNNER_TYPES:
        runner_type = copy.deepcopy(runner_type)

        # For backward compatibility reasons, we also register runners under the old names
        runner_names = [runner_type['name']] + runner_type.get('aliases', [])
        for runner_name in runner_names:
            runner_type['name'] = runner_name
            runner_experimental = runner_type.get('experimental', False)

            if runner_experimental and not experimental:
                LOG.debug('Skipping experimental runner "%s"' % (runner_name))
                continue

            # Remove additional, non db-model attributes
            non_db_attributes = ['experimental', 'aliases']
            for attribute in non_db_attributes:
                if attribute in runner_type:
                    del runner_type[attribute]

            try:
                runner_type_db = get_runnertype_by_name(runner_name)
                update = True
            except StackStormDBObjectNotFoundError:
                runner_type_db = None
                update = False

            runner_type_api = RunnerTypeAPI(**runner_type)
            runner_type_api.validate()
            runner_type_model = RunnerTypeAPI.to_model(runner_type_api)

            if runner_type_db:
                runner_type_model.id = runner_type_db.id

            try:
                runner_type_db = RunnerType.add_or_update(runner_type_model)

                extra = {'runner_type_db': runner_type_db}
                if update:
                    LOG.audit('RunnerType updated. RunnerType %s',
                              runner_type_db,
                              extra=extra)
                else:
                    LOG.audit('RunnerType created. RunnerType %s',
                              runner_type_db,
                              extra=extra)
            except Exception:
                LOG.exception('Unable to register runner type %s.',
                              runner_type['name'])

    LOG.debug('End : register default RunnerTypes.')
示例#23
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)
示例#24
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)))
示例#25
0
    def get_all(self, **kw):
        """
            List all RunnerType objects.

            Handles requests:
                GET /runnertypes/
        """
        runnertype_dbs = RunnerType.get_all(**kw)
        runnertype_apis = [RunnerTypeAPI.from_model(runnertype_db)
                           for runnertype_db in runnertype_dbs]
        return runnertype_apis
示例#26
0
def register_runner_types(experimental=False):
    """
    :param experimental: True to also register experimental runners.
    :type experimental: ``bool``
    """
    LOG.debug('Start : register default RunnerTypes.')

    for runner_type in RUNNER_TYPES:
        runner_type = copy.deepcopy(runner_type)

        # For backward compatibility reasons, we also register runners under the old names
        runner_names = [runner_type['name']] + runner_type.get('aliases', [])
        for runner_name in runner_names:
            runner_type['name'] = runner_name
            runner_experimental = runner_type.get('experimental', False)

            if runner_experimental and not experimental:
                LOG.debug('Skipping experimental runner "%s"' % (runner_name))
                continue

            # Remove additional, non db-model attributes
            non_db_attributes = ['experimental', 'aliases']
            for attribute in non_db_attributes:
                if attribute in runner_type:
                    del runner_type[attribute]

            try:
                runner_type_db = get_runnertype_by_name(runner_name)
                update = True
            except StackStormDBObjectNotFoundError:
                runner_type_db = None
                update = False

            runner_type_api = RunnerTypeAPI(**runner_type)
            runner_type_api.validate()
            runner_type_model = RunnerTypeAPI.to_model(runner_type_api)

            if runner_type_db:
                runner_type_model.id = runner_type_db.id

            try:
                runner_type_db = RunnerType.add_or_update(runner_type_model)

                extra = {'runner_type_db': runner_type_db}
                if update:
                    LOG.audit('RunnerType updated. RunnerType %s', runner_type_db, extra=extra)
                else:
                    LOG.audit('RunnerType created. RunnerType %s', runner_type_db, extra=extra)
            except Exception:
                LOG.exception('Unable to register runner type %s.', runner_type['name'])

    LOG.debug('End : register default RunnerTypes.')
示例#27
0
    def get_all(self, **kw):
        """
            List all RunnerType objects.

            Handles requests:
                GET /runnertypes/
        """
        LOG.info('GET all /runnertypes/ with filters=%s', kw)
        runnertype_dbs = RunnerType.get_all(**kw)
        runnertype_apis = [RunnerTypeAPI.from_model(runnertype_db)
                           for runnertype_db in runnertype_dbs]
        LOG.debug('GET all /runnertypes/ client_result=%s', runnertype_apis)
        return runnertype_apis
示例#28
0
    def get_all(self, **kw):
        """
            List all RunnerType objects.

            Handles requests:
                GET /runnertypes/
        """
        runnertype_dbs = RunnerType.get_all(**kw)
        runnertype_apis = [
            RunnerTypeAPI.from_model(runnertype_db)
            for runnertype_db in runnertype_dbs
        ]
        return runnertype_apis
示例#29
0
文件: test_db.py 项目: srenatus/st2
 def _create_save_runnertype(metadata=False):
     created = RunnerTypeDB()
     created.name = 'python'
     created.description = ''
     created.enabled = True
     if not metadata:
         created.runner_parameters = {'r1': None, 'r2': None}
     else:
         created.runner_parameters = {
             'r1': {'type': 'object', 'properties': {'r1a': {'type': 'string'}}},
             'r2': {'type': 'string', 'required': True}
         }
     created.runner_module = 'nomodule'
     return RunnerType.add_or_update(created)
示例#30
0
 def _create_save_runnertype(metadata=False):
     created = RunnerTypeDB()
     created.name = 'python'
     created.description = ''
     created.enabled = True
     if not metadata:
         created.runner_parameters = {'r1': None, 'r2': None}
     else:
         created.runner_parameters = {
             'r1': {'type': 'object', 'properties': {'r1a': {'type': 'string'}}},
             'r2': {'type': 'string', 'required': True}
         }
     created.runner_module = 'nomodule'
     return RunnerType.add_or_update(created)
示例#31
0
 def test_execution_creation_manual_action_run(self):
     liveaction = self.MODELS['liveactions']['liveaction1.json']
     executions_util.create_execution_object(liveaction)
     execution = self._get_action_execution(liveaction__id=str(liveaction.id),
                                            raise_exception=True)
     self.assertDictEqual(execution.trigger, {})
     self.assertDictEqual(execution.trigger_type, {})
     self.assertDictEqual(execution.trigger_instance, {})
     self.assertDictEqual(execution.rule, {})
     action = action_utils.get_action_by_ref('core.local')
     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.assertEquals(execution.liveaction['id'], str(liveaction.id))
示例#32
0
def get_runnertype_by_id(runnertype_id):
    """
        Get RunnerType by id.

        On error, raise StackStormDBObjectNotFoundError
    """
    try:
        runnertype = RunnerType.get_by_id(runnertype_id)
    except (ValueError, ValidationError) as e:
        LOG.warning('Database lookup for runnertype with id="%s" resulted in '
                    'exception: %s', runnertype_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find runnertype with '
                                              'id="%s"' % runnertype_id)

    return runnertype
示例#33
0
    def get_all(self, **kw):
        """
            List all RunnerType objects.

            Handles requests:
                GET /runnertypes/
        """
        LOG.info('GET all /runnertypes/ with filters=%s', kw)
        runnertype_dbs = RunnerType.get_all(**kw)
        runnertype_apis = [
            RunnerTypeAPI.from_model(runnertype_db)
            for runnertype_db in runnertype_dbs
        ]
        LOG.debug('GET all /runnertypes/ client_result=%s', runnertype_apis)
        return runnertype_apis
示例#34
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
示例#35
0
def get_runnertype_by_id(runnertype_id):
    """
        Get RunnerType by id.

        On error, raise StackStormDBObjectNotFoundError
    """
    try:
        runnertype = RunnerType.get_by_id(runnertype_id)
    except (ValueError, ValidationError) as e:
        LOG.warning(
            'Database lookup for runnertype with id="%s" resulted in '
            'exception: %s', runnertype_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find runnertype with '
                                              'id="%s"' % runnertype_id)

    return runnertype
示例#36
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)))
示例#37
0
 def test_execution_creation_manual_action_run(self):
     liveaction = self.MODELS['liveactions']['liveaction1.json']
     executions_util.create_execution_object(liveaction)
     execution = self._get_action_execution(liveaction__id=str(
         liveaction.id),
                                            raise_exception=True)
     self.assertDictEqual(execution.trigger, {})
     self.assertDictEqual(execution.trigger_type, {})
     self.assertDictEqual(execution.trigger_instance, {})
     self.assertDictEqual(execution.rule, {})
     action = action_utils.get_action_by_ref('core.local')
     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.assertEquals(execution.liveaction['id'], str(liveaction.id))
示例#38
0
文件: executions.py 项目: timff/st2
def create_execution_object(liveaction, publish=True):
    action_db = action_utils.get_action_by_ref(liveaction.action)
    runner = RunnerType.get_by_name(action_db.runner_type['name'])

    attrs = {
        'action': vars(ActionAPI.from_model(action_db)),
        'runner': vars(RunnerTypeAPI.from_model(runner))
    }
    attrs.update(_decompose_liveaction(liveaction))

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

    if 'trigger_instance' in liveaction.context:
        trigger_instance_id = liveaction.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, liveaction.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 = ActionExecution.get(
        liveaction__id=liveaction.context.get('parent', ''))
    if parent:
        attrs['parent'] = str(parent.id)

    execution = ActionExecutionDB(**attrs)
    execution = ActionExecution.add_or_update(execution, publish=publish)

    if parent:
        if str(execution.id) not in parent.children:
            parent.children.append(str(execution.id))
            ActionExecution.add_or_update(parent)

    return execution
示例#39
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)
示例#40
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')
示例#41
0
def create_execution_object(liveaction, publish=True):
    action_db = action_utils.get_action_by_ref(liveaction.action)
    runner = RunnerType.get_by_name(action_db.runner_type['name'])

    attrs = {
        'action': vars(ActionAPI.from_model(action_db)),
        'runner': vars(RunnerTypeAPI.from_model(runner))
    }
    attrs.update(_decompose_liveaction(liveaction))

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

    if 'trigger_instance' in liveaction.context:
        trigger_instance_id = liveaction.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, liveaction.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 = ActionExecution.get(liveaction__id=liveaction.context.get('parent', ''))
    if parent:
        attrs['parent'] = str(parent.id)

    execution = ActionExecutionDB(**attrs)
    execution = ActionExecution.add_or_update(execution, publish=publish)

    if parent:
        if str(execution.id) not in parent.children:
            parent.children.append(str(execution.id))
            ActionExecution.add_or_update(parent)

    return execution
示例#42
0
文件: test_history.py 项目: miqui/st2
 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)))
示例#43
0
 def test_execution_creation_action_triggered_by_rule(self):
     # Wait for the action execution to complete and then confirm outcome.
     trigger_type = self.MODELS['triggertypes']['triggertype2.json']
     trigger = self.MODELS['triggers']['trigger2.json']
     trigger_instance = self.MODELS['triggerinstances'][
         'trigger_instance_1.json']
     test_liveaction = self.FIXTURES['liveactions']['liveaction3.json']
     rule = self.MODELS['rules']['rule3.json']
     # Setup LiveAction to point to right rule and trigger_instance.
     # XXX: We need support for dynamic fixtures.
     test_liveaction['context']['rule']['id'] = str(rule.id)
     test_liveaction['context']['trigger_instance']['id'] = str(
         trigger_instance.id)
     test_liveaction_api = LiveActionAPI(**test_liveaction)
     test_liveaction = LiveAction.add_or_update(
         LiveActionAPI.to_model(test_liveaction_api))
     liveaction = LiveAction.get(
         context__trigger_instance__id=str(trigger_instance.id))
     self.assertIsNotNone(liveaction)
     self.assertEqual(liveaction.status, LIVEACTION_STATUS_SCHEDULED)
     executions_util.create_execution_object(liveaction)
     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.assertEquals(execution.liveaction['id'], str(liveaction.id))
示例#44
0
def get_runnertype_by_name(runnertype_name):
    """
        Get an runnertype by name.
        On error, raise ST2ObjectNotFoundError.
    """
    try:
        runnertypes = RunnerType.query(name=runnertype_name)
    except (ValueError, ValidationError) as e:
        LOG.error('Database lookup for name="%s" resulted in exception: %s',
                  runnertype_name, e)
        raise StackStormDBObjectNotFoundError('Unable to find runnertype with name="%s"'
                                              % runnertype_name)

    if not runnertypes:
        raise StackStormDBObjectNotFoundError('Unable to find RunnerType with name="%s"'
                                              % runnertype_name)

    if len(runnertypes) > 1:
        LOG.warning('More than one RunnerType returned from DB lookup by name. '
                    'Result list is: %s', runnertypes)

    return runnertypes[0]
示例#45
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)))
示例#46
0
 def test_basic_execution(self):
     liveaction = LiveActionDB(action='core.local', parameters={'cmd': 'uname -a'})
     liveaction, _ = action_service.schedule(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, {})
     self.assertDictEqual(execution.trigger_type, {})
     self.assertDictEqual(execution.trigger_instance, {})
     self.assertDictEqual(execution.rule, {})
     action = action_utils.get_action_by_ref('core.local')
     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)
示例#47
0
 def __get_by_name(name):
     try:
         return [RunnerType.get_by_name(name)]
     except ValueError as e:
         LOG.debug('Database lookup for name="%s" resulted in exception : %s.', name, e)
         return []
示例#48
0
def register_runner_types():
    try:
        default_remote_dir = cfg.CONF.ssh_runner.remote_dir
    except:
        default_remote_dir = '/tmp'

    RUNNER_TYPES = [{
        'name': 'run-local',
        'description': 'A runner to execute local actions as a fixed user.',
        'enabled': True,
        'runner_parameters': {
            'hosts': {
                'description':
                'Fixed to localhost as this action is run locally.',
                'type': 'string',
                'default': 'localhost',
                'immutable': True
            },
            'cmd': {
                'description': 'Arbitrary Linux command to be executed on the '
                'host.',
                'type': 'string'
            },
            'parallel': {
                'description': 'Default to parallel execution.',
                'type': 'boolean',
                'default': True,
                'immutable': True
            },
            'sudo': {
                'description': 'The command will be executed with sudo.',
                'type': 'boolean',
                'default': False
            },
            'dir': {
                'description':
                'The working directory where the command will be '
                'executed on the host.',
                'type': 'string',
                'default': default_remote_dir
            },
            'kwarg_op': {
                'description':
                'Operator to use in front of keyword args i.e. "--" or "-".',
                'type': 'string',
                'default': '--'
            }
        },
        'runner_module': 'st2actions.runners.fabricrunner'
    }, {
        'name': 'run-local-script',
        'description': 'A runner to execute local actions as a fixed user.',
        'enabled': True,
        'runner_parameters': {
            'hosts': {
                'description':
                'Fixed to localhost as this action is run locally.',
                'type': 'string',
                'default': 'localhost',
                'immutable': True
            },
            'parallel': {
                'description': 'Default to parallel execution.',
                'type': 'boolean',
                'default': True,
                'immutable': True
            },
            'sudo': {
                'description': 'The command will be executed with sudo.',
                'type': 'boolean',
                'default': False
            },
            'dir': {
                'description':
                'The working directory where the command will be '
                'executed on the host.',
                'type': 'string',
                'default': default_remote_dir
            },
            'kwarg_op': {
                'description':
                'Operator to use in front of keyword args i.e. "--" or "-".',
                'type': 'string',
                'default': '--'
            }
        },
        'runner_module': 'st2actions.runners.fabricrunner'
    }, {
        'name':
        'run-remote',
        'description':
        'A remote execution runner that executes actions '
        'as a fixed system user.',
        'enabled':
        True,
        'runner_parameters': {
            'hosts': {
                'description': 'A comma delimited string of a list of hosts '
                'where the remote command will be executed.',
                'type': 'string',
                'required': True
            },
            'cmd': {
                'description': 'Arbitrary Linux command to be executed on the '
                'remote host(s).',
                'type': 'string'
            },
            'parallel': {
                'description': 'Default to parallel execution.',
                'type': 'boolean',
                'default': True,
                'immutable': True
            },
            'sudo': {
                'description':
                'The remote command will be executed with sudo.',
                'type': 'boolean'
            },
            'dir': {
                'description':
                'The working directory where the command will be '
                'executed on the remote host.',
                'type': 'string',
                'default': default_remote_dir
            },
            'kwarg_op': {
                'description':
                'Operator to use in front of keyword args i.e. "--" or "-".',
                'type': 'string',
                'default': '--'
            }
        },
        'runner_module':
        'st2actions.runners.fabricrunner'
    }, {
        'name':
        'run-remote-script',
        'description':
        'A remote execution runner that executes actions '
        'as a fixed system user.',
        'enabled':
        True,
        'runner_parameters': {
            'hosts': {
                'description': 'A comma delimited string of a list of hosts '
                'where the remote command will be executed.',
                'type': 'string',
                'required': True
            },
            'parallel': {
                'description': 'Default to parallel execution.',
                'type': 'boolean',
                'default': True,
                'immutable': True
            },
            'sudo': {
                'description':
                'The remote command will be executed with sudo.',
                'type': 'boolean'
            },
            'dir': {
                'description':
                'The working directory where the command will be '
                'executed on the remote host.',
                'type': 'string',
                'default': default_remote_dir
            },
            'kwarg_op': {
                'description':
                'Operator to use in front of keyword args i.e. "--" or "-".',
                'type': 'string',
                'default': '--'
            }
        },
        'runner_module':
        'st2actions.runners.fabricrunner'
    }, {
        'name': 'http-runner',
        'description': 'A HTTP client for running HTTP actions.',
        'enabled': True,
        'runner_parameters': {
            'url': {
                'description': 'URL to the HTTP endpoint.',
                'type': 'string',
                'required': True
            },
            'headers': {
                'description': 'HTTP headers for the request.',
                'type': 'string'
            },
            'cookies': {
                'description': 'TODO: Description for cookies.',
                'type': 'string'
            },
            'proxy': {
                'description': 'TODO: Description for proxy.',
                'type': 'string'
            },
            'redirects': {
                'description': 'TODO: Description for redirects.',
                'type': 'string'
            },
        },
        'runner_module': 'st2actions.runners.httprunner'
    }, {
        'name': 'mistral-v1',
        'description': 'A runner for executing mistral v1 workflow.',
        'enabled': True,
        'runner_parameters': {
            'workbook': {
                'description': 'The name of the workbook.',
                'type': 'string',
                'required': True
            },
            'task': {
                'description': 'The startup task in the workbook to execute.',
                'type': 'string',
                'required': True
            },
            'context': {
                'description': 'Context for the startup task.',
                'type': 'object',
                'default': {}
            }
        },
        'runner_module': 'st2actions.runners.mistral.v1'
    }, {
        'name': 'mistral-v2',
        'description': 'A runner for executing mistral v2 workflow.',
        'enabled': True,
        'runner_parameters': {
            'workflow': {
                'description': 'The name of the workflow.',
                'type': 'string',
                'required': True
            },
            'context': {
                'description': 'Context for the startup task.',
                'type': 'object',
                'default': {}
            }
        },
        'runner_module': 'st2actions.runners.mistral.v2'
    }, {
        'name': 'action-chain',
        'description': 'A runner for launching linear action chains.',
        'enabled': True,
        'runner_parameters': {},
        'runner_module': 'st2actions.runners.actionchainrunner'
    }, {
        'name': 'run-python',
        'description': 'A runner for launching python actions.',
        'enabled': True,
        'runner_parameters': {},
        'runner_module': 'st2actions.runners.pythonrunner'
    }]

    LOG.info('Start : register default RunnerTypes.')

    for runnertype in RUNNER_TYPES:
        try:
            runnertype_db = get_runnertype_by_name(runnertype['name'])
            if runnertype_db:
                LOG.info('RunnerType name=%s exists.', runnertype['name'])
                continue
        except StackStormDBObjectNotFoundError:
            pass

        runnertype_api = RunnerTypeAPI(**runnertype)
        try:
            runnertype_db = RunnerType.add_or_update(
                RunnerTypeAPI.to_model(runnertype_api))
            LOG.audit('RunnerType created. RunnerType %s', runnertype_db)
        except Exception:
            LOG.exception('Unable to register runner type %s.',
                          runnertype['name'])

    LOG.info('End : register default RunnerTypes.')
示例#49
0
文件: test_db.py 项目: srenatus/st2
 def tearDown(self):
     runnertype = RunnerType.get_by_name('python')
     self._delete([runnertype])
     super(ActionModelTest, self).tearDown()
示例#50
0
 def tearDownClass(cls):
     Action.delete(cls.actiondb)
     RunnerType.delete(cls.runnerdb)
     super(TestActionExecutionService, cls).tearDownClass()
示例#51
0
 def tearDown(self):
     Action.delete(ACTION)
     RunnerType.delete(RUNNER_TYPE)
     Trigger.delete(TRIGGER)
示例#52
0
 def setUpClass(cls):
     super(TestActionExecutionService, cls).setUpClass()
     cls.runner = RunnerTypeAPI(**RUNNER)
     cls.runnerdb = RunnerType.add_or_update(RunnerTypeAPI.to_model(cls.runner))
     cls.action = ActionAPI(**ACTION)
     cls.actiondb = Action.add_or_update(ActionAPI.to_model(cls.action))
示例#53
0
 def tearDownClass(cls):
     Action.delete(cls.actiondb)
     RunnerType.delete(cls.runnerdb)
     super(TestActionExecutionService, cls).tearDownClass()
示例#54
0
 def tearDown(self):
     runnertype = RunnerType.get_by_name('python')
     self._delete([runnertype])
     super(ActionModelTest, self).tearDown()
示例#55
0
def register_runner_types():
    try:
        default_remote_dir = cfg.CONF.ssh_runner.remote_dir
    except:
        default_remote_dir = '/tmp'

    RUNNER_TYPES = [
        {
            'name': 'run-local',
            'description': 'A runner to execute local actions as a fixed user.',
            'enabled': True,
            'runner_parameters': {
                'hosts': {
                    'description': 'Fixed to localhost as this action is run locally.',
                    'type': 'string',
                    'default': 'localhost',
                    'immutable': True
                },
                'cmd': {
                    'description': 'Arbitrary Linux command to be executed on the '
                                   'host.',
                    'type': 'string'
                },
                'parallel': {
                    'description': 'Default to parallel execution.',
                    'type': 'boolean',
                    'default': True,
                    'immutable': True
                },
                'sudo': {
                    'description': 'The command will be executed with sudo.',
                    'type': 'boolean',
                    'default': False
                },
                'dir': {
                    'description': 'The working directory where the command will be '
                                   'executed on the host.',
                    'type': 'string',
                    'default': default_remote_dir
                },
                'kwarg_op': {
                    'description': 'Operator to use in front of keyword args i.e. "--" or "-".',
                    'type': 'string',
                    'default': '--'
                }
            },
            'runner_module': 'st2actions.runners.fabricrunner'
        },
        {
            'name': 'run-local-script',
            'description': 'A runner to execute local actions as a fixed user.',
            'enabled': True,
            'runner_parameters': {
                'hosts': {
                    'description': 'Fixed to localhost as this action is run locally.',
                    'type': 'string',
                    'default': 'localhost',
                    'immutable': True
                },
                'parallel': {
                    'description': 'Default to parallel execution.',
                    'type': 'boolean',
                    'default': True,
                    'immutable': True
                },
                'sudo': {
                    'description': 'The command will be executed with sudo.',
                    'type': 'boolean',
                    'default': False
                },
                'dir': {
                    'description': 'The working directory where the command will be '
                                   'executed on the host.',
                    'type': 'string',
                    'default': default_remote_dir
                },
                'kwarg_op': {
                    'description': 'Operator to use in front of keyword args i.e. "--" or "-".',
                    'type': 'string',
                    'default': '--'
                }
            },
            'runner_module': 'st2actions.runners.fabricrunner'
        },
        {
            'name': 'run-remote',
            'description': 'A remote execution runner that executes actions '
                           'as a fixed system user.',
            'enabled': True,
            'runner_parameters': {
                'hosts': {
                    'description': 'A comma delimited string of a list of hosts '
                                   'where the remote command will be executed.',
                    'type': 'string',
                    'required': True
                },
                'cmd': {
                    'description': 'Arbitrary Linux command to be executed on the '
                                   'remote host(s).',
                    'type': 'string'
                },
                'parallel': {
                    'description': 'Default to parallel execution.',
                    'type': 'boolean',
                    'default': True,
                    'immutable': True
                },
                'sudo': {
                    'description': 'The remote command will be executed with sudo.',
                    'type': 'boolean'
                },
                'dir': {
                    'description': 'The working directory where the command will be '
                                   'executed on the remote host.',
                    'type': 'string',
                    'default': default_remote_dir
                },
                'kwarg_op': {
                    'description': 'Operator to use in front of keyword args i.e. "--" or "-".',
                    'type': 'string',
                    'default': '--'
                }
            },
            'runner_module': 'st2actions.runners.fabricrunner'
        },
        {
            'name': 'run-remote-script',
            'description': 'A remote execution runner that executes actions '
                           'as a fixed system user.',
            'enabled': True,
            'runner_parameters': {
                'hosts': {
                    'description': 'A comma delimited string of a list of hosts '
                                   'where the remote command will be executed.',
                    'type': 'string',
                    'required': True
                },
                'parallel': {
                    'description': 'Default to parallel execution.',
                    'type': 'boolean',
                    'default': True,
                    'immutable': True
                },
                'sudo': {
                    'description': 'The remote command will be executed with sudo.',
                    'type': 'boolean'
                },
                'dir': {
                    'description': 'The working directory where the command will be '
                                   'executed on the remote host.',
                    'type': 'string',
                    'default': default_remote_dir
                },
                'kwarg_op': {
                    'description': 'Operator to use in front of keyword args i.e. "--" or "-".',
                    'type': 'string',
                    'default': '--'
                }
            },
            'runner_module': 'st2actions.runners.fabricrunner'
        },
        {
            'name': 'http-runner',
            'description': 'A HTTP client for running HTTP actions.',
            'enabled': True,
            'runner_parameters': {
                'url': {
                    'description': 'URL to the HTTP endpoint.',
                    'type': 'string',
                    'required': True
                },
                'headers': {
                    'description': 'HTTP headers for the request.',
                    'type': 'string'
                },
                'cookies': {
                    'description': 'TODO: Description for cookies.',
                    'type': 'string'
                },
                'proxy': {
                    'description': 'TODO: Description for proxy.',
                    'type': 'string'
                },
                'redirects': {
                    'description': 'TODO: Description for redirects.',
                    'type': 'string'
                },
            },
            'runner_module': 'st2actions.runners.httprunner'
        },
        {
            'name': 'mistral-v1',
            'description': 'A runner for executing mistral v1 workflow.',
            'enabled': True,
            'runner_parameters': {
                'workbook': {
                    'description': 'The name of the workbook.',
                    'type': 'string',
                    'required': True
                },
                'task': {
                    'description': 'The startup task in the workbook to execute.',
                    'type': 'string',
                    'required': True
                },
                'context': {
                    'description': 'Context for the startup task.',
                    'type': 'object',
                    'default': {}
                }
            },
            'runner_module': 'st2actions.runners.mistral.v1'
        },
        {
            'name': 'mistral-v2',
            'description': 'A runner for executing mistral v2 workflow.',
            'enabled': True,
            'runner_parameters': {
                'workflow': {
                    'description': 'The name of the workflow.',
                    'type': 'string',
                    'required': True
                },
                'context': {
                    'description': 'Context for the startup task.',
                    'type': 'object',
                    'default': {}
                }
            },
            'runner_module': 'st2actions.runners.mistral.v2'
        },
        {
            'name': 'action-chain',
            'description': 'A runner for launching linear action chains.',
            'enabled': True,
            'runner_parameters': {},
            'runner_module': 'st2actions.runners.actionchainrunner'
        },
        {
            'name': 'run-python',
            'description': 'A runner for launching python actions.',
            'enabled': True,
            'runner_parameters': {},
            'runner_module': 'st2actions.runners.pythonrunner'
        }
    ]

    LOG.info('Start : register default RunnerTypes.')

    for runnertype in RUNNER_TYPES:
        try:
            runnertype_db = get_runnertype_by_name(runnertype['name'])
            if runnertype_db:
                LOG.info('RunnerType name=%s exists.', runnertype['name'])
                continue
        except StackStormDBObjectNotFoundError:
            pass

        runnertype_api = RunnerTypeAPI(**runnertype)
        try:
            runnertype_db = RunnerType.add_or_update(RunnerTypeAPI.to_model(runnertype_api))
            LOG.audit('RunnerType created. RunnerType %s', runnertype_db)
        except Exception:
            LOG.exception('Unable to register runner type %s.', runnertype['name'])

    LOG.info('End : register default RunnerTypes.')