本文整理汇总了Python中st2common.persistence.trigger.TriggerInstance类的典型用法代码示例。如果您正苦于以下问题:Python TriggerInstance类的具体用法?Python TriggerInstance怎么用?Python TriggerInstance使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TriggerInstance类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: purge_trigger_instances
def purge_trigger_instances(logger, timestamp):
"""
:param timestamp: Trigger instances older than this timestamp will be deleted.
:type timestamp: ``datetime.datetime
"""
if not timestamp:
raise ValueError('Specify a valid timestamp to purge.')
logger.info('Purging trigger instances older than timestamp: %s' %
timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
query_filters = {'occurrence_time__lt': isotime.parse(timestamp)}
# TODO: Update this code to return statistics on deleted objects once we
# upgrade to newer version of MongoDB where delete_by_query actually returns
# some data
try:
TriggerInstance.delete_by_query(**query_filters)
except InvalidQueryError as e:
msg = ('Bad query (%s) used to delete trigger instances: %s'
'Please contact support.' % (query_filters, str(e)))
raise InvalidQueryError(msg)
except:
logger.exception('Deleting instances using query_filters %s failed.', query_filters)
# Print stats
logger.info('All trigger instance models older than timestamp %s were deleted.', timestamp)
示例2: _purge_model
def _purge_model(instance):
try:
TriggerInstance.delete(instance)
except:
LOG.exception('Exception deleting instance %s.', instance)
else:
global DELETED_COUNT
DELETED_COUNT += 1
示例3: test_no_timestamp_doesnt_delete
def test_no_timestamp_doesnt_delete(self):
now = date_utils.get_datetime_utc_now()
instance_db = TriggerInstanceDB(trigger='purge_tool.dummy.trigger',
payload={'hola': 'hi', 'kuraci': 'chicken'},
occurrence_time=now - timedelta(days=20))
TriggerInstance.add_or_update(instance_db)
self.assertEqual(len(TriggerInstance.get_all()), 1)
purge_trigger_instances()
self.assertEqual(len(TriggerInstance.get_all()), 1)
示例4: test_triggerinstance_crud
def test_triggerinstance_crud(self):
triggertype = ReactorModelTest._create_save_triggertype()
trigger = ReactorModelTest._create_save_trigger(triggertype)
saved = ReactorModelTest._create_save_triggerinstance(trigger)
retrieved = TriggerInstance.get_by_id(saved.id)
self.assertIsNotNone(retrieved, 'No triggerinstance created.')
ReactorModelTest._delete([retrieved, trigger, triggertype])
try:
retrieved = TriggerInstance.get_by_id(saved.id)
except ValueError:
retrieved = None
self.assertIsNone(retrieved, 'managed to retrieve after failure.')
示例5: test_triggerinstance_crud
def test_triggerinstance_crud(self):
triggertype = ReactorModelTest._create_save_triggertype()
trigger = ReactorModelTest._create_save_trigger(triggertype)
saved = ReactorModelTest._create_save_triggerinstance(trigger)
retrieved = TriggerInstance.get_by_id(saved.id)
self.assertIsNotNone(retrieved, "No triggerinstance created.")
ReactorModelTest._delete([retrieved, trigger, triggertype])
try:
retrieved = TriggerInstance.get_by_id(saved.id)
except StackStormDBObjectNotFoundError:
retrieved = None
self.assertIsNone(retrieved, "managed to retrieve after failure.")
示例6: test_no_timestamp_doesnt_delete
def test_no_timestamp_doesnt_delete(self):
now = date_utils.get_datetime_utc_now()
instance_db = TriggerInstanceDB(trigger='purge_tool.dummy.trigger',
payload={'hola': 'hi', 'kuraci': 'chicken'},
occurrence_time=now - timedelta(days=20))
TriggerInstance.add_or_update(instance_db)
self.assertEqual(len(TriggerInstance.get_all()), 1)
expected_msg = 'Specify a valid timestamp'
self.assertRaisesRegexp(ValueError, expected_msg,
purge_trigger_instances,
logger=LOG, timestamp=None)
self.assertEqual(len(TriggerInstance.get_all()), 1)
示例7: create_trigger_instance
def create_trigger_instance(trigger, payload, occurrence_time, raise_on_no_trigger=False):
"""
This creates a trigger instance object given trigger and payload.
Trigger can be just a string reference (pack.name) or a ``dict``
containing 'type' and 'parameters'.
:param trigger: Dictionary with trigger query filters.
:type trigger: ``dict``
:param payload: Trigger payload.
:type payload: ``dict``
"""
# TODO: This is nasty, this should take a unique reference and not a dict
if isinstance(trigger, six.string_types):
trigger_db = TriggerService.get_trigger_db_by_ref(trigger)
else:
type_ = trigger.get('type', None)
parameters = trigger.get('parameters', {})
trigger_db = TriggerService.get_trigger_db_given_type_and_params(type=type_,
parameters=parameters)
if trigger_db is None:
LOG.debug('No trigger in db for %s', trigger)
if raise_on_no_trigger:
raise StackStormDBObjectNotFoundError('Trigger not found for %s', trigger)
return None
trigger_ref = trigger_db.get_reference().ref
trigger_instance = TriggerInstanceDB()
trigger_instance.trigger = trigger_ref
trigger_instance.payload = payload
trigger_instance.occurrence_time = occurrence_time
trigger_instance.status = TRIGGER_INSTANCE_PENDING
return TriggerInstance.add_or_update(trigger_instance)
示例8: create_trigger_instance
def create_trigger_instance(trigger, payload, occurrence_time, raise_on_no_trigger=False):
"""
This creates a trigger instance object given trigger and payload.
Trigger can be just a string reference (pack.name) or a ``dict`` containing 'id' or
'uid' or type' and 'parameters' keys.
:param trigger: Trigger reference or dictionary with trigger query filters.
:type trigger: ``str`` or ``dict``
:param payload: Trigger payload.
:type payload: ``dict``
"""
trigger_db = get_trigger_db_by_ref_or_dict(trigger=trigger)
if not trigger_db:
LOG.debug('No trigger in db for %s', trigger)
if raise_on_no_trigger:
raise StackStormDBObjectNotFoundError('Trigger not found for %s' % trigger)
return None
trigger_ref = trigger_db.get_reference().ref
trigger_instance = TriggerInstanceDB()
trigger_instance.trigger = trigger_ref
trigger_instance.payload = payload
trigger_instance.occurrence_time = occurrence_time
trigger_instance.status = TRIGGER_INSTANCE_PENDING
return TriggerInstance.add_or_update(trigger_instance)
示例9: purge_trigger_instances
def purge_trigger_instances(logger, timestamp):
"""
:param timestamp: Trigger instances older than this timestamp will be deleted.
:type timestamp: ``datetime.datetime
"""
if not timestamp:
raise ValueError('Specify a valid timestamp to purge.')
logger.info('Purging trigger instances older than timestamp: %s' %
timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
query_filters = {'occurrence_time__lt': isotime.parse(timestamp)}
try:
deleted_count = TriggerInstance.delete_by_query(**query_filters)
except InvalidQueryError as e:
msg = ('Bad query (%s) used to delete trigger instances: %s'
'Please contact support.' % (query_filters, str(e)))
raise InvalidQueryError(msg)
except:
logger.exception('Deleting instances using query_filters %s failed.', query_filters)
else:
logger.info('Deleted %s trigger instance objects' % (deleted_count))
# Print stats
logger.info('All trigger instance models older than timestamp %s were deleted.', timestamp)
示例10: _create_trigger_instance
def _create_trigger_instance(cls, trigger_ref, payload):
trigger_instance = TriggerInstanceDB()
trigger_instance.trigger = trigger_ref
trigger_instance.payload = payload
trigger_instance.occurrence_time = datetime.datetime.utcnow()
created = TriggerInstance.add_or_update(trigger_instance)
cls.triggerinstance_count += 1
return created
示例11: _create_save_triggerinstance
def _create_save_triggerinstance(trigger):
created = TriggerInstanceDB(
trigger=trigger.get_reference().ref,
payload={},
occurrence_time=date_utils.get_datetime_utc_now(),
status=TRIGGER_INSTANCE_PROCESSED,
)
return TriggerInstance.add_or_update(created)
示例12: get_all
def get_all(self, **kw):
"""
List all triggerinstances.
Handles requests:
GET /triggerinstances/
"""
trigger_instance_apis = [TriggerInstanceAPI.from_model(trigger_instance_db)
for trigger_instance_db in TriggerInstance.get_all(**kw)]
return trigger_instance_apis
示例13: create_execution_object
def create_execution_object(liveaction, action_db=None, runnertype_db=None, publish=True):
if not action_db:
action_db = action_utils.get_action_by_ref(liveaction.action)
if not runnertype_db:
runnertype_db = RunnerType.get_by_name(action_db.runner_type['name'])
attrs = {
'action': vars(ActionAPI.from_model(action_db)),
'parameters': liveaction['parameters'],
'runner': vars(RunnerTypeAPI.from_model(runnertype_db))
}
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 = _get_parent_execution(liveaction)
if parent:
attrs['parent'] = str(parent.id)
attrs['log'] = [_create_execution_log_entry(liveaction['status'])]
# TODO: This object initialization takes 20-30or so ms
execution = ActionExecutionDB(**attrs)
# TODO: Do 100% research this is fully safe and unique in distributed setups
execution.id = ObjectId()
execution.web_url = _get_web_url_for_execution(str(execution.id))
# NOTE: User input data is already validate as part of the API request,
# other data is set by us. Skipping validation here makes operation 10%-30% faster
execution = ActionExecution.add_or_update(execution, publish=publish, validate=False)
if parent and str(execution.id) not in parent.children:
values = {}
values['push__children'] = str(execution.id)
ActionExecution.update(parent, **values)
return execution
示例14: create_trigger_instance
def create_trigger_instance(trigger, payload, occurrence_time, raise_on_no_trigger=False):
"""
This creates a trigger instance object given trigger and payload.
Trigger can be just a string reference (pack.name) or a ``dict`` containing 'id' or
'uid' or type' and 'parameters' keys.
:param trigger: Trigger reference or dictionary with trigger query filters.
:type trigger: ``str`` or ``dict``
:param payload: Trigger payload.
:type payload: ``dict``
"""
# TODO: This is nasty, this should take a unique reference and not a dict
if isinstance(trigger, six.string_types):
trigger_db = TriggerService.get_trigger_db_by_ref(trigger)
else:
# If id / uid is available we try to look up Trigger by id. This way we can avoid bug in
# pymongo / mongoengine related to "parameters" dictionary lookups
trigger_id = trigger.get('id', None)
trigger_uid = trigger.get('uid', None)
# TODO: Remove parameters dictionary look up when we can confirm each trigger dictionary
# passed to this method always contains id or uid
if trigger_id:
LOG.debug('Looking up TriggerDB by id: %s', trigger_id)
trigger_db = TriggerService.get_trigger_db_by_id(id=trigger_id)
elif trigger_uid:
LOG.debug('Looking up TriggerDB by uid: %s', trigger_uid)
trigger_db = TriggerService.get_trigger_db_by_uid(uid=trigger_uid)
else:
# Last resort - look it up by parameters
trigger_type = trigger.get('type', None)
parameters = trigger.get('parameters', {})
LOG.debug('Looking up TriggerDB by type and parameters: type=%s, parameters=%s',
trigger_type, parameters)
trigger_db = TriggerService.get_trigger_db_given_type_and_params(type=trigger_type,
parameters=parameters)
if trigger_db is None:
LOG.debug('No trigger in db for %s', trigger)
if raise_on_no_trigger:
raise StackStormDBObjectNotFoundError('Trigger not found for %s', trigger)
return None
trigger_ref = trigger_db.get_reference().ref
trigger_instance = TriggerInstanceDB()
trigger_instance.trigger = trigger_ref
trigger_instance.payload = payload
trigger_instance.occurrence_time = occurrence_time
trigger_instance.status = TRIGGER_INSTANCE_PENDING
return TriggerInstance.add_or_update(trigger_instance)
示例15: _create_trigger_instance
def _create_trigger_instance(cls, trigger_ref, payload, seconds):
# Note: We use 1 second intervals between occurence time to prevent
# occasional test failures
occurrence_time = date_utils.get_datetime_utc_now()
occurrence_time = occurrence_time + datetime.timedelta(seconds=seconds)
trigger_instance = TriggerInstanceDB()
trigger_instance.trigger = trigger_ref
trigger_instance.payload = payload
trigger_instance.occurrence_time = occurrence_time
created = TriggerInstance.add_or_update(trigger_instance)
cls.triggerinstance_count += 1
return created