本文整理汇总了Python中st2common.models.system.common.ResourceReference类的典型用法代码示例。如果您正苦于以下问题:Python ResourceReference类的具体用法?Python ResourceReference怎么用?Python ResourceReference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ResourceReference类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, tester):
self.tester = tester
self.notify_trigger = ResourceReference.to_string_reference(
pack=NOTIFY_TRIGGER_TYPE['pack'],
name=NOTIFY_TRIGGER_TYPE['name'])
self.action_trigger = ResourceReference.to_string_reference(
pack=ACTION_TRIGGER_TYPE['pack'],
name=ACTION_TRIGGER_TYPE['name'])
开发者ID:nzlosh,项目名称:st2,代码行数:8,代码来源:test_notifier.py
示例2: _register_rules_from_pack
def _register_rules_from_pack(self, pack, rules):
registered_count = 0
for rule in rules:
LOG.debug('Loading rule from %s.', rule)
try:
content = self._meta_loader.load(rule)
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))
rule_api = RuleAPI(**content)
rule_api.validate()
rule_db = RuleAPI.to_model(rule_api)
# Migration from rule without pack to rule with pack.
# There might be a rule with same name but in pack `default`
# generated in migration script. In this case, we want to
# delete so we don't have duplicates.
if pack_field != DEFAULT_PACK_NAME:
try:
rule_ref = ResourceReference.to_string_reference(name=content['name'],
pack=DEFAULT_PACK_NAME)
LOG.debug('Looking for rule %s in pack %s', content['name'],
DEFAULT_PACK_NAME)
existing = Rule.get_by_ref(rule_ref)
LOG.debug('Existing = %s', existing)
if existing:
LOG.debug('Found rule in pack default: %s; Deleting.', rule_ref)
Rule.delete(existing)
except:
LOG.exception('Exception deleting rule from %s pack.', DEFAULT_PACK_NAME)
try:
rule_ref = ResourceReference.to_string_reference(name=content['name'],
pack=content['pack'])
existing = Rule.get_by_ref(rule_ref)
if existing:
rule_db.id = existing.id
LOG.debug('Found existing rule: %s with id: %s', rule_ref, existing.id)
except ValueError:
LOG.debug('Rule %s not found. Creating new one.', rule)
try:
rule_db = Rule.add_or_update(rule_db)
extra = {'rule_db': rule_db}
LOG.audit('Rule updated. Rule %s from %s.', rule_db, rule, extra=extra)
except Exception:
LOG.exception('Failed to create rule %s.', rule_api.name)
except:
LOG.exception('Failed registering rule from %s.', rule)
else:
registered_count += 1
return registered_count
开发者ID:emptywee,项目名称:st2,代码行数:58,代码来源:rulesregistrar.py
示例3: __init__
def __init__(self, connection, queues, trigger_dispatcher=None):
super(Notifier, self).__init__(connection, queues)
self._trigger_dispatcher = trigger_dispatcher
self._notify_trigger = ResourceReference.to_string_reference(
pack=NOTIFY_TRIGGER_TYPE["pack"], name=NOTIFY_TRIGGER_TYPE["name"]
)
self._action_trigger = ResourceReference.to_string_reference(
pack=ACTION_TRIGGER_TYPE["pack"], name=ACTION_TRIGGER_TYPE["name"]
)
开发者ID:bernard357,项目名称:st2,代码行数:9,代码来源:notifier.py
示例4: __init__
def __init__(self, q_connection=None, trigger_dispatcher=None):
self._queue_consumer = LiveActionUpdateQueueConsumer(q_connection, self)
self._consumer_thread = None
self._trigger_dispatcher = trigger_dispatcher
self._notify_trigger = ResourceReference.to_string_reference(
pack=NOTIFY_TRIGGER_TYPE['pack'],
name=NOTIFY_TRIGGER_TYPE['name'])
self._action_trigger = ResourceReference.to_string_reference(
pack=ACTION_TRIGGER_TYPE['pack'],
name=ACTION_TRIGGER_TYPE['name'])
开发者ID:BlazeMediaGroup,项目名称:st2,代码行数:10,代码来源:notifier.py
示例5: _get_executions
def _get_executions(self, **kw):
action_ref = kw.get('action', None)
if action_ref:
action_name = ResourceReference.get_name(action_ref)
action_pack = ResourceReference.get_pack(action_ref)
del kw['action']
kw['action.name'] = action_name
kw['action.pack'] = action_pack
return super(ActionExecutionHistoryController, self)._get_all(**kw)
开发者ID:bjoernbessert,项目名称:st2,代码行数:11,代码来源:history.py
示例6: test_get_all
def test_get_all(self):
holder = TimersHolder()
for _, model in TestTimersHolder.MODELS.items():
holder.add_trigger(
ref=ResourceReference.to_string_reference(pack=model["pack"], name=model["name"]), trigger=model
)
self.assertEqual(len(holder.get_all()), 5)
开发者ID:Pulsant,项目名称:st2,代码行数:7,代码来源:test_timers.py
示例7: test_chain_runner_task_is_canceled_while_running
def test_chain_runner_task_is_canceled_while_running(self, request):
# Second task in the action is CANCELED, make sure runner doesn't get stuck in an infinite
# loop
chain_runner = acr.get_runner()
chain_runner.entry_point = CHAIN_2_PATH
chain_runner.action = ACTION_1
original_run_action = chain_runner._run_action
def mock_run_action(*args, **kwargs):
original_live_action = args[0]
if original_live_action.action == 'wolfpack.a2':
status = LIVEACTION_STATUS_CANCELED
else:
status = LIVEACTION_STATUS_SUCCEEDED
request.return_value = (DummyActionExecution(status=status), None)
liveaction = original_run_action(*args, **kwargs)
return liveaction
chain_runner._run_action = mock_run_action
action_ref = ResourceReference.to_string_reference(name=ACTION_1.name, pack=ACTION_1.pack)
chain_runner.liveaction = LiveActionDB(action=action_ref)
chain_runner.pre_run()
status, _, _ = chain_runner.run({})
self.assertEqual(status, LIVEACTION_STATUS_CANCELED)
self.assertNotEqual(chain_runner.chain_holder.actionchain, None)
# Chain count should be 2 since the last task doesn't get called since the second one was
# canceled
self.assertEqual(request.call_count, 2)
开发者ID:lyandut,项目名称:st2,代码行数:30,代码来源:test_actionchain.py
示例8: test_chain_runner_dependent_results_param
def test_chain_runner_dependent_results_param(self, request):
chain_runner = acr.get_runner()
chain_runner.entry_point = CHAIN_DEP_RESULTS_INPUT
chain_runner.action = ACTION_1
action_ref = ResourceReference.to_string_reference(name=ACTION_1.name, pack=ACTION_1.pack)
chain_runner.liveaction = LiveActionDB(action=action_ref)
chain_runner.pre_run()
chain_runner.run({'s1': 1})
self.assertNotEqual(chain_runner.chain_holder.actionchain, None)
if six.PY2:
expected_values = [{u'p1': u'1'},
{u'p1': u'1'},
{u'out': u"{'c2': {'o1': '1'}, 'c1': {'o1': '1'}}"}]
else:
expected_values = [{'p1': '1'},
{'p1': '1'},
{'out': "{'c1': {'o1': '1'}, 'c2': {'o1': '1'}}"}]
# Each of the call_args must be one of
self.assertEqual(request.call_count, 3)
for call_args in request.call_args_list:
self.assertTrue(call_args[0][0].parameters in expected_values)
expected_values.remove(call_args[0][0].parameters)
self.assertEqual(len(expected_values), 0, 'Not all expected values received.')
开发者ID:lyandut,项目名称:st2,代码行数:26,代码来源:test_actionchain.py
示例9: _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
开发者ID:Kailashkatheth1,项目名称:st2,代码行数:31,代码来源:actionsregistrar.py
示例10: to_model
def to_model(cls, rule):
kwargs = {}
kwargs['name'] = getattr(rule, 'name', None)
kwargs['description'] = getattr(rule, 'description', None)
# Create a trigger for the provided rule
trigger_db = TriggerService.create_trigger_db_from_rule(rule)
kwargs['trigger'] = reference.get_str_resource_ref_from_model(trigger_db)
# Validate trigger parameters
validator.validate_trigger_parameters(trigger_db=trigger_db)
kwargs['pack'] = getattr(rule, 'pack', DEFAULT_PACK_NAME)
kwargs['ref'] = ResourceReference.to_string_reference(pack=kwargs['pack'],
name=kwargs['name'])
# Validate criteria
kwargs['criteria'] = dict(getattr(rule, 'criteria', {}))
validator.validate_criteria(kwargs['criteria'])
kwargs['action'] = ActionExecutionSpecDB(ref=rule.action['ref'],
parameters=rule.action.get('parameters', {}))
rule_type = dict(getattr(rule, 'type', {}))
if rule_type:
kwargs['type'] = RuleTypeSpecDB(ref=rule_type['ref'],
parameters=rule_type.get('parameters', {}))
kwargs['enabled'] = getattr(rule, 'enabled', False)
kwargs['tags'] = TagsHelper.to_model(getattr(rule, 'tags', []))
model = cls.model(**kwargs)
return model
开发者ID:hejin,项目名称:st2,代码行数:33,代码来源:rule.py
示例11: to_model
def to_model(cls, action):
name = getattr(action, "name", None)
description = getattr(action, "description", None)
enabled = bool(getattr(action, "enabled", True))
entry_point = str(action.entry_point)
pack = str(action.pack)
runner_type = {"name": str(action.runner_type)}
parameters = getattr(action, "parameters", dict())
tags = TagsHelper.to_model(getattr(action, "tags", []))
ref = ResourceReference.to_string_reference(pack=pack, name=name)
if getattr(action, "notify", None):
notify = NotificationsHelper.to_model(action.notify)
else:
notify = None
model = cls.model(
name=name,
description=description,
enable=enabled,
enabled=enabled,
entry_point=entry_point,
pack=pack,
runner_type=runner_type,
tags=tags,
parameters=parameters,
notify=notify,
ref=ref,
)
return model
开发者ID:jspittman,项目名称:st2,代码行数:31,代码来源:action.py
示例12: run
def run(self, action_parameters):
liveaction_db = action_utils.get_liveaction_by_id(self.liveaction_id)
exc = ActionExecution.get(liveaction__id=str(liveaction_db.id))
# Assemble and dispatch trigger
trigger_ref = ResourceReference.to_string_reference(
pack=INQUIRY_TRIGGER['pack'],
name=INQUIRY_TRIGGER['name']
)
trigger_payload = {
"id": str(exc.id),
"route": self.route
}
self.trigger_dispatcher.dispatch(trigger_ref, trigger_payload)
# We only want to request a pause if this has a parent
if liveaction_db.context.get("parent"):
# Get the root liveaction and request that it pauses
root_liveaction = action_service.get_root_liveaction(liveaction_db)
action_service.request_pause(
root_liveaction,
self.context.get('user', None)
)
result = {
"schema": self.schema,
"roles": self.roles_param,
"users": self.users_param,
"route": self.route,
"ttl": self.ttl
}
return (LIVEACTION_STATUS_PENDING, result, None)
开发者ID:lyandut,项目名称:st2,代码行数:34,代码来源:inquirer_runner.py
示例13: _get_api_models_from_disk
def _get_api_models_from_disk(artifact_type, pack_dir=None):
loader = ContentPackLoader()
artifacts = None
if pack_dir:
artifacts_dir = loader.get_content_from_pack(pack_dir, artifact_type)
pack_name = os.path.basename(os.path.normpath(pack_dir))
artifacts = {pack_name: artifacts_dir}
else:
packs_dirs = content_utils.get_packs_base_paths()
artifacts = loader.get_content(packs_dirs, artifact_type)
artifacts_dict = {}
for pack_name, pack_path in artifacts.items():
artifacts_paths = registrar.get_resources_from_pack(pack_path)
for artifact_path in artifacts_paths:
artifact = meta_loader.load(artifact_path)
if artifact_type == "sensors":
sensors_dir = os.path.dirname(artifact_path)
sensor_file_path = os.path.join(sensors_dir, artifact["entry_point"])
artifact["artifact_uri"] = "file://" + sensor_file_path
name = artifact.get("name", None) or artifact.get("class_name", None)
if not artifact.get("pack", None):
artifact["pack"] = pack_name
ref = ResourceReference.to_string_reference(name=name, pack=pack_name)
API_MODEL = API_MODELS_ARTIFACT_TYPES[artifact_type]
# Following conversions are required because we add some fields with
# default values in db model. If we don't do these conversions,
# we'll see a unnecessary diff for those fields.
artifact_api = API_MODEL(**artifact)
artifact_db = API_MODEL.to_model(artifact_api)
artifact_api = API_MODEL.from_model(artifact_db)
artifacts_dict[ref] = artifact_api
return artifacts_dict
开发者ID:azamsheriff,项目名称:st2,代码行数:35,代码来源:diff-db-disk.py
示例14: post_trigger
def post_trigger(action_execution):
if not ACTION_SENSOR_ENABLED:
return
try:
payload = json.dumps({
'trigger': ResourceReference.to_string_reference(
pack=ACTION_TRIGGER_TYPE['pack'], name=ACTION_TRIGGER_TYPE['name']),
'payload': {
'execution_id': str(action_execution.id),
'status': action_execution.status,
'start_timestamp': str(action_execution.start_timestamp),
'action_name': action_execution.action,
'parameters': action_execution.parameters,
'result': action_execution.result
}
})
LOG.debug('POSTing %s for %s. Payload - %s.', ACTION_TRIGGER_TYPE['name'],
action_execution.id, payload)
r = requests.post(TRIGGER_INSTANCE_ENDPOINT,
data=payload,
headers=HTTP_POST_HEADER,
timeout=TIMEOUT)
except:
LOG.exception('Failed to fire trigger for action_execution %s.', str(action_execution.id))
else:
if r.status_code in [200, 201, 202]:
LOG.debug('POSTed actionexecution %s as a trigger.', action_execution.id)
else:
LOG.warn('Seeing status code %s on an attempt to post triggerinstance for %s.',
r.status_code, action_execution.id)
开发者ID:bjoernbessert,项目名称:st2,代码行数:30,代码来源:actionsensor.py
示例15: register_trigger_type
def register_trigger_type(trigger_definition, attempt_no=0):
LOG.debug('Attempt no %s to register trigger %s.', attempt_no, trigger_definition['name'])
ref = ResourceReference.to_string_reference(pack=trigger_definition['pack'],
name=trigger_definition['name'])
if _is_triggertype_exists(ref):
return
payload = json.dumps(trigger_definition)
try:
r = requests.post(url=TRIGGER_TYPE_ENDPOINT, data=payload,
headers=HTTP_POST_HEADER, timeout=TIMEOUT)
if r.status_code == httplib.CREATED:
LOG.info('Registered trigger %s.', trigger_definition['name'])
elif r.status_code == httplib.CONFLICT:
LOG.info('Trigger %s is already registered.', trigger_definition['name'])
else:
LOG.error('Seeing status code %s on an attempt to register trigger %s.',
r.status_code, trigger_definition['name'])
except requests.exceptions.ConnectionError:
if attempt_no < MAX_ATTEMPTS:
retry_wait = RETRY_WAIT * (attempt_no + 1)
LOG.debug(' ConnectionError. Will retry in %ss.', retry_wait)
eventlet.spawn_after(retry_wait, register_trigger_type,
trigger_definition=trigger_definition,
attempt_no=(attempt_no + 1))
else:
LOG.warn('Failed to register trigger %s. Exceeded max attempts to register trigger.',
trigger_definition['name'])
except:
LOG.exception('Failed to register trigger %s.', trigger_definition['name'])
开发者ID:BlazeMediaGroup,项目名称:st2,代码行数:32,代码来源:triggers.py
示例16: user_has_rule_action_permission
def user_has_rule_action_permission(user_db, action_ref):
"""
Check that the currently logged-in has necessary permissions on the action used / referenced
inside the rule.
Note: Rules can reference actions which don't yet exist in the system.
"""
if not cfg.CONF.rbac.enable:
return True
action_db = action_utils.get_action_by_ref(ref=action_ref)
if not action_db:
# We allow rules to be created for actions which don't yet exist in the
# system
ref = ResourceReference.from_string_reference(ref=action_ref)
action_db = ActionDB(pack=ref.pack, name=ref.name, ref=action_ref)
action_resolver = resolvers.get_resolver_for_resource_type(ResourceType.ACTION)
has_action_permission = action_resolver.user_has_resource_db_permission(
user_db=user_db, resource_db=action_db, permission_type=PermissionType.ACTION_EXECUTE)
if has_action_permission:
return True
return False
开发者ID:lyandut,项目名称:st2,代码行数:26,代码来源:utils.py
示例17: _get_by_ref_or_id
def _get_by_ref_or_id(self, ref_or_id, exclude_fields=None, include_fields=None):
"""
Retrieve resource object by an id of a reference.
Note: This method throws StackStormDBObjectNotFoundError exception if the object is not
found in the database.
"""
if exclude_fields and include_fields:
msg = ('exclude_fields and include_fields arguments are mutually exclusive. '
'You need to provide either one or another, but not both.')
raise ValueError(msg)
if ResourceReference.is_resource_reference(ref_or_id):
# references always contain a dot and id's can't contain it
is_reference = True
else:
is_reference = False
if is_reference:
resource_db = self._get_by_ref(resource_ref=ref_or_id, exclude_fields=exclude_fields,
include_fields=include_fields)
else:
resource_db = self._get_by_id(resource_id=ref_or_id, exclude_fields=exclude_fields,
include_fields=include_fields)
if not resource_db:
msg = 'Resource with a reference or id "%s" not found' % (ref_or_id)
raise StackStormDBObjectNotFoundError(msg)
return resource_db
开发者ID:lyandut,项目名称:st2,代码行数:31,代码来源:resource.py
示例18: dispatch
def dispatch(self, actionexec_db):
action_ref = ResourceReference.from_string_reference(ref=actionexec_db.action)
(action_db, _) = get_action_by_dict(
{'name': action_ref.name, 'pack': action_ref.pack})
runnertype_db = get_runnertype_by_name(action_db.runner_type['name'])
runner_type = runnertype_db.name
LOG.info('Dispatching runner for Action "%s"', actionexec_db)
LOG.debug(' liverunner_type: %s', runner_type)
LOG.debug(' RunnerType: %s', runnertype_db)
LOG.debug(' ActionExecution: %s', actionexec_db)
# Get runner instance.
runner = self._get_runner(runnertype_db)
LOG.debug('Runner instance for RunnerType "%s" is: %s', runnertype_db.name, runner)
# Invoke pre_run, run, post_run cycle.
result, actionexec_db = self._do_run(runner, runnertype_db, action_db, actionexec_db)
LOG.debug('runner do_run result: %s', result)
actionsensor.post_trigger(actionexec_db)
LOG.audit('ActionExecution complete.',
extra={'actionexecution': actionexec_db.to_serializable_dict()})
return result
开发者ID:nagyist,项目名称:StackStorm-st2,代码行数:25,代码来源:base.py
示例19: test_get_one_by_ref
def test_get_one_by_ref(self):
rule_name = RuleViewControllerTestCase.RULE_1.name
rule_pack = RuleViewControllerTestCase.RULE_1.pack
ref = ResourceReference.to_string_reference(name=rule_name, pack=rule_pack)
get_resp = self.__do_get_one(ref)
self.assertEqual(get_resp.json['name'], rule_name)
self.assertEqual(get_resp.status_int, http_client.OK)
开发者ID:StackStorm,项目名称:st2,代码行数:7,代码来源:test_rule_views.py
示例20: to_model
def to_model(cls, rule):
name = getattr(rule, 'name', None)
description = getattr(rule, 'description', None)
# Create a trigger for the provided rule
trigger_db = TriggerService.create_trigger_db_from_rule(rule)
trigger = reference.get_str_resource_ref_from_model(trigger_db)
criteria = dict(getattr(rule, 'criteria', {}))
pack = getattr(rule, 'pack', DEFAULT_PACK_NAME)
ref = ResourceReference.to_string_reference(pack=pack, name=name)
# Validate criteria
validator.validate_criteria(criteria)
# Validate trigger parameters
validator.validate_trigger_parameters(trigger_db=trigger_db)
action = ActionExecutionSpecDB(ref=rule.action['ref'],
parameters=rule.action['parameters'])
enabled = rule.enabled
tags = TagsHelper.to_model(getattr(rule, 'tags', []))
model = cls.model(name=name, description=description, pack=pack, ref=ref, trigger=trigger,
criteria=criteria, action=action, enabled=enabled, tags=tags)
return model
开发者ID:joshgre,项目名称:st2,代码行数:27,代码来源:rule.py
注:本文中的st2common.models.system.common.ResourceReference类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论