本文整理汇总了Python中st2common.models.api.action.ActionAPI类的典型用法代码示例。如果您正苦于以下问题:Python ActionAPI类的具体用法?Python ActionAPI怎么用?Python ActionAPI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ActionAPI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _register_action
def _register_action(self, pack, action):
content = self._meta_loader.load(action)
pack_field = content.get('pack', None)
if not pack_field:
content['pack'] = pack
pack_field = pack
if pack_field != pack:
raise Exception('Model is in pack "%s" but field "pack" is different: %s' %
(pack, pack_field))
action_api = ActionAPI(**content)
action_api.validate()
action_validator.validate_action(action_api)
model = ActionAPI.to_model(action_api)
action_ref = ResourceReference.to_string_reference(pack=pack, name=str(content['name']))
existing = action_utils.get_action_by_ref(action_ref)
if not existing:
LOG.debug('Action %s not found. Creating new one with: %s', action_ref, content)
else:
LOG.debug('Action %s found. Will be updated from: %s to: %s',
action_ref, existing, model)
model.id = existing.id
try:
model = Action.add_or_update(model)
extra = {'action_db': model}
LOG.audit('Action updated. Action %s from %s.', model, action, extra=extra)
except Exception:
LOG.exception('Failed to write action to db %s.', model.name)
raise
示例2: post
def post(self, action):
"""
Create a new action.
Handles requests:
POST /actions/
"""
if not hasattr(action, 'pack'):
setattr(action, 'pack', DEFAULT_PACK_NAME)
try:
action_validator.validate_action(action)
except ValueValidationException as e:
abort(http_client.BAD_REQUEST, str(e))
return
# ActionsController._validate_action_parameters(action, runnertype_db)
action_model = ActionAPI.to_model(action)
LOG.debug('/actions/ POST verified ActionAPI object=%s', action)
action_db = Action.add_or_update(action_model)
LOG.debug('/actions/ POST saved ActionDB object=%s', action_db)
extra = {'action_db': action_db}
LOG.audit('Action created. Action.id=%s' % (action_db.id), extra=extra)
action_api = ActionAPI.from_model(action_db)
return action_api
示例3: post
def post(self, action):
"""
Create a new action.
Handles requests:
POST /actions/
"""
# Perform validation
validate_not_part_of_system_pack(action)
action_validator.validate_action(action)
# Write pack data files to disk (if any are provided)
data_files = getattr(action, 'data_files', [])
written_data_files = []
if data_files:
written_data_files = self._handle_data_files(pack_name=action.pack,
data_files=data_files)
action_model = ActionAPI.to_model(action)
LOG.debug('/actions/ POST verified ActionAPI object=%s', action)
action_db = Action.add_or_update(action_model)
LOG.debug('/actions/ POST saved ActionDB object=%s', action_db)
# Dispatch an internal trigger for each written data file. This way user
# automate comitting this files to git using StackStorm rule
if written_data_files:
self._dispatch_trigger_for_written_data_files(action_db=action_db,
written_data_files=written_data_files)
extra = {'acion_db': action_db}
LOG.audit('Action created. Action.id=%s' % (action_db.id), extra=extra)
action_api = ActionAPI.from_model(action_db)
return action_api
示例4: put
def put(self, action_ref_or_id, action):
action_db = self._get_by_ref_or_id(ref_or_id=action_ref_or_id)
action_id = action_db.id
try:
validate_not_part_of_system_pack(action_db)
except ValueValidationException as e:
abort(http_client.BAD_REQUEST, str(e))
if not getattr(action, 'pack', None):
action.pack = action_db.pack
try:
action_validator.validate_action(action)
except ValueValidationException as e:
abort(http_client.BAD_REQUEST, str(e))
return
try:
action_db = ActionAPI.to_model(action)
action_db.id = action_id
action_db = Action.add_or_update(action_db)
except (ValidationError, ValueError) as e:
LOG.exception('Unable to update action data=%s', action)
abort(http_client.BAD_REQUEST, str(e))
return
action_api = ActionAPI.from_model(action_db)
LOG.debug('PUT /actions/ client_result=%s', action_api)
return action_api
示例5: setUpClass
def setUpClass(cls):
super(TestActionExecutionHistoryWorker, cls).setUpClass()
runners_registrar.register_runners()
action_local = ActionAPI(**copy.deepcopy(fixture.ARTIFACTS["actions"]["local"]))
Action.add_or_update(ActionAPI.to_model(action_local))
action_chain = ActionAPI(**copy.deepcopy(fixture.ARTIFACTS["actions"]["chain"]))
action_chain.entry_point = fixture.PATH + "/chain.yaml"
Action.add_or_update(ActionAPI.to_model(action_chain))
示例6: setUpClass
def setUpClass(cls):
super(TestMistralRunner, cls).setUpClass()
runners_registrar.register_runner_types()
metadata = fixture.ARTIFACTS['metadata']
action_local = ActionAPI(**copy.deepcopy(metadata['actions']['local']))
Action.add_or_update(ActionAPI.to_model(action_local))
action_wkflow = ActionAPI(**copy.deepcopy(metadata['actions']['workflow-v2']))
Action.add_or_update(ActionAPI.to_model(action_wkflow))
示例7: setUpClass
def setUpClass(cls):
super(TestActionExecutionHistoryWorker, cls).setUpClass()
runners_registrar.register_runner_types()
action_local = ActionAPI(**copy.deepcopy(fixture.ARTIFACTS['actions']['local']))
Action.add_or_update(ActionAPI.to_model(action_local))
action_chain = ActionAPI(**copy.deepcopy(fixture.ARTIFACTS['actions']['chain']))
action_chain.entry_point = fixture.PATH + '/chain.yaml'
Action.add_or_update(ActionAPI.to_model(action_chain))
示例8: _register_action
def _register_action(self, pack, action):
content = self._meta_loader.load(action)
pack_field = content.get('pack', None)
if not pack_field:
content['pack'] = pack
pack_field = pack
if pack_field != pack:
raise Exception('Model is in pack "%s" but field "pack" is different: %s' %
(pack, pack_field))
action_api = ActionAPI(**content)
try:
action_api.validate()
except jsonschema.ValidationError as e:
# We throw a more user-friendly exception on invalid parameter name
msg = str(e)
is_invalid_parameter_name = 'does not match any of the regexes: ' in msg
if is_invalid_parameter_name:
match = re.search('\'(.+?)\' does not match any of the regexes', msg)
if match:
parameter_name = match.groups()[0]
else:
parameter_name = 'unknown'
new_msg = ('Parameter name "%s" is invalid. Valid characters for parameter name '
'are [a-zA-Z0-0_].' % (parameter_name))
new_msg += '\n\n' + msg
raise jsonschema.ValidationError(new_msg)
raise e
action_validator.validate_action(action_api)
model = ActionAPI.to_model(action_api)
action_ref = ResourceReference.to_string_reference(pack=pack, name=str(content['name']))
existing = action_utils.get_action_by_ref(action_ref)
if not existing:
LOG.debug('Action %s not found. Creating new one with: %s', action_ref, content)
else:
LOG.debug('Action %s found. Will be updated from: %s to: %s',
action_ref, existing, model)
model.id = existing.id
try:
model = Action.add_or_update(model)
extra = {'action_db': model}
LOG.audit('Action updated. Action %s from %s.', model, action, extra=extra)
except Exception:
LOG.exception('Failed to write action to db %s.', model.name)
raise
示例9: setUpClass
def setUpClass(cls):
super(DSLTransformTestCase, cls).setUpClass()
runners_registrar.register_runner_types()
action_local = ActionAPI(**copy.deepcopy(FIXTURES['actions']['local.yaml']))
Action.add_or_update(ActionAPI.to_model(action_local))
for action_name in ['action1', 'action2', 'action3']:
metadata = copy.deepcopy(FIXTURES['actions']['local.yaml'])
metadata['name'] = action_name
metadata['pack'] = 'demo'
action = ActionAPI(**metadata)
Action.add_or_update(ActionAPI.to_model(action))
示例10: post
def post(self, action):
"""
Create a new action.
Handles requests:
POST /actions/
"""
LOG.info('POST /actions/ with action data=%s', action)
if not hasattr(action, 'enabled'):
LOG.debug('POST /actions/ incoming action data has enabled field unset. '
'Defaulting enabled to True.')
setattr(action, 'enabled', True)
else:
action.enabled = bool(action.enabled)
if not hasattr(action, 'pack'):
setattr(action, 'pack', 'default')
try:
action_validator.validate_action(action)
except ValueValidationException as e:
abort(http_client.BAD_REQUEST, str(e))
return
# ActionsController._validate_action_parameters(action, runnertype_db)
action_model = ActionAPI.to_model(action)
LOG.debug('/actions/ POST verified ActionAPI object=%s', action)
try:
action_db = Action.add_or_update(action_model)
except NotUniqueError as e:
# If an existing DB object conflicts with new object then raise error.
LOG.warn('/actions/ POST unable to save ActionDB object "%s" due to uniqueness '
'conflict. %s', action_model, str(e))
abort(http_client.CONFLICT, str(e))
return
except Exception as e:
LOG.exception('/actions/ POST unable to save ActionDB object "%s". %s',
action_model, e)
abort(http_client.INTERNAL_SERVER_ERROR, str(e))
return
LOG.debug('/actions/ POST saved ActionDB object=%s', action_db)
LOG.audit('Action created. Action=%s', action_db)
action_api = ActionAPI.from_model(action_db)
LOG.debug('POST /actions/ client_result=%s', action_api)
return action_api
示例11: get_all
def get_all(self, exclude_attributes=None, include_attributes=None, sort=None, offset=0,
limit=None, requester_user=None, **raw_filters):
"""
List all actions.
Handles requests:
GET /actions/views/overview
"""
resp = super(OverviewController, self)._get_all(exclude_fields=exclude_attributes,
include_fields=include_attributes,
sort=sort,
offset=offset,
limit=limit,
raw_filters=raw_filters,
requester_user=requester_user)
runner_type_names = set([])
action_ids = []
result = []
for item in resp.json:
action_api = ActionAPI(**item)
result.append(action_api)
runner_type_names.add(action_api.runner_type)
action_ids.append(str(action_api.id))
# Add combined runner and action parameters to the compound result object
# NOTE: This approach results in 2 additional queries while previous one resulted in
# N * 2 additional queries
# 1. Retrieve all the respective runner objects - we only need parameters
runner_type_dbs = RunnerType.query(name__in=runner_type_names,
only_fields=['name', 'runner_parameters'])
runner_type_dbs = dict([(runner_db.name, runner_db) for runner_db in runner_type_dbs])
# 2. Retrieve all the respective action objects - we only need parameters
action_dbs = dict([(action_db.id, action_db) for action_db in result])
for action_api in result:
action_db = action_dbs.get(action_api.id, None)
runner_db = runner_type_dbs.get(action_api.runner_type, None)
all_params = action_param_utils.get_params_view(action_db=action_db,
runner_db=runner_db,
merged_only=True)
action_api.parameters = all_params
resp.json = result
return resp
示例12: post
def post(self, action, requester_user):
"""
Create a new action.
Handles requests:
POST /actions/
"""
permission_type = PermissionType.ACTION_CREATE
rbac_utils = get_rbac_backend().get_utils_class()
rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
resource_api=action,
permission_type=permission_type)
try:
# Perform validation
validate_not_part_of_system_pack(action)
action_validator.validate_action(action)
except (ValidationError, ValueError,
ValueValidationException, InvalidActionParameterException) as e:
LOG.exception('Unable to create action data=%s', action)
abort(http_client.BAD_REQUEST, six.text_type(e))
return
# Write pack data files to disk (if any are provided)
data_files = getattr(action, 'data_files', [])
written_data_files = []
if data_files:
written_data_files = self._handle_data_files(pack_ref=action.pack,
data_files=data_files)
action_model = ActionAPI.to_model(action)
LOG.debug('/actions/ POST verified ActionAPI object=%s', action)
action_db = Action.add_or_update(action_model)
LOG.debug('/actions/ POST saved ActionDB object=%s', action_db)
# Dispatch an internal trigger for each written data file. This way user
# automate comitting this files to git using StackStorm rule
if written_data_files:
self._dispatch_trigger_for_written_data_files(action_db=action_db,
written_data_files=written_data_files)
extra = {'acion_db': action_db}
LOG.audit('Action created. Action.id=%s' % (action_db.id), extra=extra)
action_api = ActionAPI.from_model(action_db)
return Response(json=action_api, status=http_client.CREATED)
示例13: setUpClass
def setUpClass(cls):
super(TestMistralRunner, cls).setUpClass()
runners_registrar.register_runner_types()
for _, fixture in six.iteritems(FIXTURES['actions']):
instance = ActionAPI(**fixture)
Action.add_or_update(ActionAPI.to_model(instance))
示例14: test_execution_creation_action_triggered_by_rule
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.yaml']
trigger = self.MODELS['triggers']['trigger2.yaml']
trigger_instance = self.MODELS['triggerinstances']['trigger_instance_1.yaml']
test_liveaction = self.FIXTURES['liveactions']['liveaction3.yaml']
rule = self.MODELS['rules']['rule3.yaml']
# 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, action_constants.LIVEACTION_STATUS_REQUESTED)
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: test_chained_executions
def test_chained_executions(self):
with mock.patch("st2common.runners.register_runner", mock.MagicMock(return_value=action_chain_runner)):
liveaction = LiveActionDB(action="executions.chain")
liveaction, _ = action_service.request(liveaction)
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_FAILED)
execution = self._get_action_execution(liveaction__id=str(liveaction.id), raise_exception=True)
action = action_utils.get_action_by_ref("executions.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")