本文整理汇总了Python中st2common.transport.reactor.TriggerDispatcher类的典型用法代码示例。如果您正苦于以下问题:Python TriggerDispatcher类的具体用法?Python TriggerDispatcher怎么用?Python TriggerDispatcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TriggerDispatcher类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: SensorService
class SensorService(object):
"""
Instance of this class is passed to the sensor instance and exposes "public"
methods which can be called by the sensor.
"""
def __init__(self, sensor_wrapper):
self._sensor_wrapper = sensor_wrapper
self._logger = self._sensor_wrapper._logger
self._dispatcher = TriggerDispatcher(self._logger)
def get_logger(self, name):
"""
Retrieve an instance of a logger to be used by the sensor class.
"""
logger_name = '%s.%s' % (self._sensor_wrapper._logger.name, name)
logger = logging.getLogger(logger_name)
logger.propagate = True
return logger
def dispatch(self, trigger, payload=None):
"""
Method which dispatches the trigger.
:param trigger: Full name / reference of the trigger.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
"""
self._dispatcher.dispatch(trigger, payload=payload)
开发者ID:nagyist,项目名称:StackStorm-st2,代码行数:31,代码来源:sensor_wrapper.py
示例2: _inject_instances
def _inject_instances(trigger, rate_per_trigger, duration, payload=None, max_throughput=False):
payload = payload or {}
start = date_utils.get_datetime_utc_now()
elapsed = 0.0
count = 0
dispatcher = TriggerDispatcher()
while elapsed < duration:
# print('Dispatching trigger %s at time %s', trigger, date_utils.get_datetime_utc_now())
dispatcher.dispatch(trigger, payload)
if rate_per_trigger:
# NOTE: We decrease sleep delay for 56% to take into account overhead / delay because
# of the call to dispatchet.dispatch method.
delta = random.expovariate(rate_per_trigger)
eventlet.sleep(delta * 0.56)
elapsed = (date_utils.get_datetime_utc_now() - start).seconds
count += 1
actual_rate = int(count / elapsed)
print('%s: Emitted %d triggers in %d seconds (actual rate=%s triggers / second)' %
(trigger, count, elapsed, actual_rate))
# NOTE: Due to the overhead of dispatcher.dispatch call, we allow for 10% of deviation from
# requested rate before warning
if rate_per_trigger and (actual_rate < (rate_per_trigger * 0.9)):
print('')
print('Warning, requested rate was %s triggers / second, but only achieved %s '
'triggers / second' % (rate_per_trigger, actual_rate))
print('Too increase the throuput you will likely need to run multiple instances of '
'this script in parallel.')
开发者ID:nzlosh,项目名称:st2,代码行数:34,代码来源:st2-inject-trigger-instances.py
示例3: Inquirer
class Inquirer(ActionRunner):
"""This runner implements the ability to ask for more input during a workflow
"""
def __init__(self, runner_id):
super(Inquirer, self).__init__(runner_id=runner_id)
self.trigger_dispatcher = TriggerDispatcher(LOG)
def pre_run(self):
super(Inquirer, self).pre_run()
# TODO :This is awful, but the way "runner_parameters" and other variables get
# assigned on the runner instance is even worse. Those arguments should
# be passed to the constructor.
self.schema = self.runner_parameters.get(RUNNER_SCHEMA, DEFAULT_SCHEMA)
self.roles_param = self.runner_parameters.get(RUNNER_ROLES, [])
self.users_param = self.runner_parameters.get(RUNNER_USERS, [])
self.route = self.runner_parameters.get(RUNNER_ROUTE, "")
self.ttl = self.runner_parameters.get(RUNNER_TTL, 1440)
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,代码行数:54,代码来源:inquirer_runner.py
示例4: _inject_instances
def _inject_instances(trigger, rate_per_trigger, duration, payload={}):
start = date_utils.get_datetime_utc_now()
elapsed = 0.0
count = 0
dispatcher = TriggerDispatcher()
while elapsed < duration:
# print('Dispatching trigger %s at time %s', trigger, date_utils.get_datetime_utc_now())
dispatcher.dispatch(trigger, payload)
delta = random.expovariate(rate_per_trigger)
eventlet.sleep(delta)
elapsed = (date_utils.get_datetime_utc_now() - start).seconds / 60.0
count += 1
print("%s: Emitted %d triggers in %d seconds" % (trigger, count, elapsed))
开发者ID:ipv1337,项目名称:st2,代码行数:15,代码来源:st2-inject-trigger-instances.py
示例5: TriggerInstanceResendController
class TriggerInstanceResendController(TriggerInstanceControllerMixin, resource.ResourceController):
supported_filters = {}
def __init__(self, *args, **kwargs):
super(TriggerInstanceResendController, self).__init__(*args, **kwargs)
self.trigger_dispatcher = TriggerDispatcher(LOG)
class TriggerInstancePayload(object):
def __init__(self, payload=None):
self.payload = payload or {}
def validate(self):
if self.payload:
assert isinstance(self.payload, dict)
return True
def post(self, trigger_instance_id):
"""
Re-send the provided trigger instance optionally specifying override parameters.
Handles requests:
POST /triggerinstance/<id>/re_emit
POST /triggerinstance/<id>/re_send
"""
# Note: We only really need parameters here
existing_trigger_instance = self._get_one_by_id(id=trigger_instance_id,
permission_type=None,
requester_user=None)
new_payload = copy.deepcopy(existing_trigger_instance.payload)
new_payload['__context'] = {
'original_id': trigger_instance_id
}
try:
self.trigger_dispatcher.dispatch(existing_trigger_instance.trigger,
new_payload)
return {
'message': 'Trigger instance %s succesfully re-sent.' % trigger_instance_id,
'payload': new_payload
}
except Exception as e:
abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
开发者ID:StackStorm,项目名称:st2,代码行数:45,代码来源:triggers.py
示例6: __init__
def __init__(self, sensor_wrapper):
self._sensor_wrapper = sensor_wrapper
self._logger = self._sensor_wrapper._logger
self._dispatcher = TriggerDispatcher(self._logger)
self._datastore_service = DatastoreService(logger=self._logger,
pack_name=self._sensor_wrapper._pack,
class_name=self._sensor_wrapper._class_name,
api_username='sensor_service')
self._client = None
开发者ID:cdminigun,项目名称:st2,代码行数:10,代码来源:sensor_wrapper.py
示例7: __init__
def __init__(self, local_timezone=None):
self._timezone = local_timezone
self._scheduler = BlockingScheduler(timezone=self._timezone)
self._jobs = {}
self._trigger_types = TIMER_TRIGGER_TYPES.keys()
self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types,
queue_suffix='timers')
self._trigger_dispatcher = TriggerDispatcher(LOG)
开发者ID:BlazeMediaGroup,项目名称:st2,代码行数:11,代码来源:base.py
示例8: __init__
def __init__(self, *args, **kwargs):
super(WebhooksController, self).__init__(*args, **kwargs)
self._hooks = {}
self._base_url = '/webhooks/'
self._trigger_types = [GENERIC_WEBHOOK_TRIGGER_REF]
self._trigger_dispatcher = TriggerDispatcher(LOG)
self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types)
self._trigger_watcher.start()
开发者ID:nagyist,项目名称:StackStorm-st2,代码行数:12,代码来源:webhooks.py
示例9: __init__
def __init__(self, local_timezone=None):
self._timezone = local_timezone
self._scheduler = BlockingScheduler(timezone=self._timezone)
self._jobs = {}
self._trigger_types = list(TIMER_TRIGGER_TYPES.keys())
self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types,
queue_suffix=self.__class__.__name__,
exclusive=True)
self._trigger_dispatcher = TriggerDispatcher(LOG)
开发者ID:lyandut,项目名称:st2,代码行数:12,代码来源:base.py
示例10: __init__
def __init__(self, *args, **kwargs):
super(WebhooksController, self).__init__(*args, **kwargs)
self._hooks = {}
self._base_url = '/webhooks/'
self._trigger_types = WEBHOOK_TRIGGER_TYPES.keys()
self._trigger_dispatcher = TriggerDispatcher(LOG)
self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types,
queue_suffix='webhooks')
self._trigger_watcher.start()
self._register_webhook_trigger_types()
开发者ID:BlazeMediaGroup,项目名称:st2,代码行数:14,代码来源:webhooks.py
示例11: __init__
def __init__(self, *args, **kwargs):
self._hooks = HooksHolder()
self._base_url = '/webhooks/'
self._trigger_types = list(WEBHOOK_TRIGGER_TYPES.keys())
self._trigger_dispatcher = TriggerDispatcher(LOG)
queue_suffix = self.__class__.__name__
self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types,
queue_suffix=queue_suffix,
exclusive=True)
self._trigger_watcher.start()
self._register_webhook_trigger_types()
开发者ID:lyandut,项目名称:st2,代码行数:15,代码来源:webhooks.py
示例12: __init__
def __init__(self, sensors, poll_interval=5):
"""
:param sensors: A list of sensor dicts.
:type sensors: ``list`` of ``dict``
"""
self._sensors = {} # maps sensor_id -> sensor object
self._processes = {} # maps sensor_id -> sensor process
self._dispatcher = TriggerDispatcher(LOG)
self.poll_interval = poll_interval
self.stopped = False
sensors = sensors or []
for sensor_obj in sensors:
sensor_id = self._get_sensor_id(sensor=sensor_obj)
self._sensors[sensor_id] = sensor_obj
开发者ID:ipv1337,项目名称:st2,代码行数:16,代码来源:process_container.py
示例13: SensorService
class SensorService(object):
"""
Instance of this class is passed to the sensor instance and exposes "public"
methods which can be called by the sensor.
"""
DATASTORE_NAME_SEPARATOR = ':'
def __init__(self, sensor_wrapper):
self._sensor_wrapper = sensor_wrapper
self._logger = self._sensor_wrapper._logger
self._dispatcher = TriggerDispatcher(self._logger)
self._client = None
def get_logger(self, name):
"""
Retrieve an instance of a logger to be used by the sensor class.
"""
logger_name = '%s.%s' % (self._sensor_wrapper._logger.name, name)
logger = logging.getLogger(logger_name)
logger.propagate = True
return logger
def dispatch(self, trigger, payload=None, trace_tag=None):
"""
Method which dispatches the trigger.
:param trigger: Full name / reference of the trigger.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
:param trace_tag: Tracer to track the triggerinstance.
:type trace_tags: ``str``
"""
# empty strings
trace_context = TraceContext(trace_tag=trace_tag) if trace_tag else None
self.dispatch_with_context(trigger, payload=payload, trace_context=trace_context)
def dispatch_with_context(self, trigger, payload=None, trace_context=None):
"""
Method which dispatches the trigger.
:param trigger: Full name / reference of the trigger.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
:param trace_context: Trace context to associate with Trigger.
:type trace_context: ``st2common.api.models.api.trace.TraceContext``
"""
self._dispatcher.dispatch(trigger, payload=payload, trace_context=trace_context)
##################################
# Methods for datastore management
##################################
def list_values(self, local=True, prefix=None):
"""
Retrieve all the datastores items.
:param local: List values from a namespace local to this sensor. Defaults to True.
:type: local: ``bool``
:param prefix: Optional key name prefix / startswith filter.
:type prefix: ``str``
:rtype: ``list`` of :class:`KeyValuePair`
"""
client = self._get_api_client()
self._logger.audit('Retrieving all the value from the datastore')
if local:
key_prefix = self._get_datastore_key_prefix() + self.DATASTORE_NAME_SEPARATOR
if prefix:
key_prefix += prefix
else:
key_prefix = prefix
kvps = client.keys.get_all(prefix=key_prefix)
return kvps
def get_value(self, name, local=True):
"""
Retrieve a value from the datastore for the provided key.
By default, value is retrieved from the namespace local to the sensor. If you want to
retrieve a global value from a datastore, pass local=False to this method.
:param name: Key name.
:type name: ``str``
:param local: Retrieve value from a namespace local to the sensor. Defaults to True.
:type: local: ``bool``
#.........这里部分代码省略.........
开发者ID:jonico,项目名称:st2,代码行数:101,代码来源:sensor_wrapper.py
示例14: SensorService
class SensorService(object):
"""
Instance of this class is passed to the sensor instance and exposes "public"
methods which can be called by the sensor.
"""
def __init__(self, sensor_wrapper):
self._sensor_wrapper = sensor_wrapper
self._logger = self._sensor_wrapper._logger
self._dispatcher = TriggerDispatcher(self._logger)
self._datastore_service = SensorDatastoreService(
logger=self._logger,
pack_name=self._sensor_wrapper._pack,
class_name=self._sensor_wrapper._class_name,
api_username='sensor_service')
self._client = None
@property
def datastore_service(self):
return self._datastore_service
def get_logger(self, name):
"""
Retrieve an instance of a logger to be used by the sensor class.
"""
logger_name = '%s.%s' % (self._sensor_wrapper._logger.name, name)
logger = logging.getLogger(logger_name)
logger.propagate = True
return logger
##################################
# General methods
##################################
def get_user_info(self):
return self._datastore_service.get_user_info()
##################################
# Sensor related methods
##################################
def dispatch(self, trigger, payload=None, trace_tag=None):
"""
Method which dispatches the trigger.
:param trigger: Full name / reference of the trigger.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
:param trace_tag: Tracer to track the triggerinstance.
:type trace_tags: ``str``
"""
# empty strings
trace_context = TraceContext(trace_tag=trace_tag) if trace_tag else None
self._logger.debug('Added trace_context %s to trigger %s.', trace_context, trigger)
self.dispatch_with_context(trigger, payload=payload, trace_context=trace_context)
def dispatch_with_context(self, trigger, payload=None, trace_context=None):
"""
Method which dispatches the trigger.
:param trigger: Full name / reference of the trigger.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
:param trace_context: Trace context to associate with Trigger.
:type trace_context: ``st2common.api.models.api.trace.TraceContext``
"""
# This means specified payload is complied with trigger_type schema, or not.
is_valid = True
try:
validate_trigger_payload(trigger_type_ref=trigger, payload=payload)
except (ValidationError, Exception) as e:
is_valid = False
self._logger.warn('Failed to validate payload (%s) for trigger "%s": %s' %
(str(payload), trigger, str(e)))
# If validation is disabled, still dispatch a trigger even if it failed validation
# This condition prevents unexpected restriction.
if not is_valid and cfg.CONF.system.validate_trigger_payload:
self._logger.warn('Trigger payload validation failed and validation is enabled, not '
'dispatching a trigger "%s" (%s)' % (trigger, str(payload)))
return None
self._logger.debug('Dispatching trigger %s with payload %s.', trigger, payload)
self._dispatcher.dispatch(trigger, payload=payload, trace_context=trace_context)
##################################
# Methods for datastore management
##################################
def list_values(self, local=True, prefix=None):
return self.datastore_service.list_values(local=local, prefix=prefix)
#.........这里部分代码省略.........
开发者ID:lyandut,项目名称:st2,代码行数:101,代码来源:sensor_wrapper.py
示例15: St2Timer
class St2Timer(object):
"""
A timer interface that uses APScheduler 3.0.
"""
def __init__(self, local_timezone=None):
self._timezone = local_timezone
self._scheduler = BlockingScheduler(timezone=self._timezone)
self._jobs = {}
self._trigger_types = TIMER_TRIGGER_TYPES.keys()
self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types,
queue_suffix=self.__class__.__name__,
exclusive=True)
self._trigger_dispatcher = TriggerDispatcher(LOG)
def start(self):
self._register_timer_trigger_types()
self._trigger_watcher.start()
self._scheduler.start()
def cleanup(self):
self._scheduler.shutdown(wait=True)
def add_trigger(self, trigger):
self._add_job_to_scheduler(trigger)
def update_trigger(self, trigger):
self.remove_trigger(trigger)
self.add_trigger(trigger)
def remove_trigger(self, trigger):
trigger_id = trigger['id']
try:
job_id = self._jobs[trigger_id]
except KeyError:
LOG.info('Job not found: %s', trigger_id)
return
self._scheduler.remove_job(job_id)
del self._jobs[trigger_id]
def _add_job_to_scheduler(self, trigger):
trigger_type_ref = trigger['type']
trigger_type = TIMER_TRIGGER_TYPES[trigger_type_ref]
try:
jsonschema.validate(trigger['parameters'],
trigger_type['parameters_schema'])
except jsonschema.ValidationError as e:
LOG.error('Exception scheduling timer: %s, %s',
trigger['parameters'], e, exc_info=True)
raise # Or should we just return?
time_spec = trigger['parameters']
time_zone = aps_utils.astimezone(trigger['parameters'].get('timezone'))
time_type = None
if trigger_type['name'] == 'st2.IntervalTimer':
unit = time_spec.get('unit', None)
value = time_spec.get('delta', None)
time_type = IntervalTrigger(**{unit: value, 'timezone': time_zone})
elif trigger_type['name'] == 'st2.DateTimer':
# Raises an exception if date string isn't a valid one.
dat = date_parser.parse(time_spec.get('date', None))
time_type = DateTrigger(dat, timezone=time_zone)
elif trigger_type['name'] == 'st2.CronTimer':
cron = time_spec.copy()
cron['timezone'] = time_zone
time_type = CronTrigger(**cron)
utc_now = date_utils.get_datetime_utc_now()
if hasattr(time_type, 'run_date') and utc_now > time_type.run_date:
LOG.warning('Not scheduling expired timer: %s : %s',
trigger['parameters'], time_type.run_date)
else:
self._add_job(trigger, time_type)
return time_type
def _add_job(self, trigger, time_type, replace=True):
try:
job = self._scheduler.add_job(self._emit_trigger_instance,
trigger=time_type,
args=[trigger],
replace_existing=replace)
LOG.info('Job %s scheduled.', job.id)
self._jobs[trigger['id']] = job.id
except Exception as e:
LOG.error('Exception scheduling timer: %s, %s',
trigger['parameters'], e, exc_info=True)
def _emit_trigger_instance(self, trigger):
utc_now = date_utils.get_datetime_utc_now()
# debug logging is reasonable for this one. A high resolution timer will end up
# trashing standard logs.
LOG.debug('Timer fired at: %s. Trigger: %s', str(utc_now), trigger)
#.........这里部分代码省略.........
开发者ID:hejin,项目名称:st2,代码行数:101,代码来源:base.py
示例16: ActionsController
class ActionsController(resource.ContentPackResourceController):
"""
Implements the RESTful web endpoint that handles
the lifecycle of Actions in the system.
"""
views = ActionViewsController()
model = ActionAPI
access = Action
supported_filters = {
'name': 'name',
'pack': 'pack',
'tags': 'name'
}
query_options = {
'sort': ['pack', 'name']
}
valid_exclude_attributes = [
'parameters',
'notify'
]
def __init__(self, *args, **kwargs):
super(ActionsController, self).__init__(*args, **kwargs)
self._trigger_dispatcher = TriggerDispatcher(LOG)
def get_all(self, exclude_attributes=None, include_attributes=None, sort=None, offset=0,
limit=None, requester_user=None, **raw_filters):
return super(ActionsController, 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)
def get_one(self, ref_or_id, requester_user):
return super(ActionsController, self)._get_one(ref_or_id, requester_user=requester_user,
permission_type=PermissionType.ACTION_VIEW)
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)
def put(self, action, ref_or_id, requester_user):
action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
# Assert permissions
permission_type = PermissionType.ACTION_MODIFY
rbac_utils = get_rbac_backend().get_utils_class()
rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
resource_db=action_db,
permission_type=permission_type)
#.........这里部分代码省略.........
开发者ID:StackStorm,项目名称:st2,代码行数:101,代码来源:actions.py
示例17: TriggerDispatcherService
class TriggerDispatcherService(object):
"""
Class for handling dispatching of trigger.
"""
def __init__(self, logger):
self._logger = logger
self._dispatcher = TriggerDispatcher(self._logger)
def dispatch(self, trigger, payload=None, trace_tag=None, throw_on_validation_error=False):
"""
Method which dispatches the trigger.
:param trigger: Reference to the TriggerTypeDB (<pack>.<name>) or TriggerDB object.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
:param trace_tag: Tracer to track the triggerinstance.
:type trace_tags: ``str``
:param throw_on_validation_error: True to throw on validation error (if validate_payload is
True) instead of logging the error.
:type throw_on_validation_error: ``boolean``
"""
# empty strings
trace_context = TraceContext(trace_tag=trace_tag) if trace_tag else None
self._logger.debug('Added trace_context %s to trigger %s.', trace_context, trigger)
return self.dispatch_with_context(trigger, payload=payload, trace_context=trace_context,
throw_on_validation_error=throw_on_validation_error)
def dispatch_with_context(self, trigger, payload=None, trace_context=None,
throw_on_validation_error=False):
"""
Method which dispatches the trigger.
:param trigger: Reference to the TriggerTypeDB (<pack>.<name>) or TriggerDB object.
:type trigger: ``str``
:param payload: Trigger payload.
:type payload: ``dict``
:param trace_context: Trace context to associate with Trigger.
:type trace_context: ``st2common.api.models.api.trace.TraceContext``
:param throw_on_validation_error: True to throw on validation error (if validate_payload is
True) instead of logging the error.
:type throw_on_validation_error: ``boolean``
"""
# Note: We perform validation even if it's disabled in the config so we can at least warn
# the user if validation fals (but not throw if it's disabled)
try:
validate_trigger_payload(trigger_type_ref=trigger, payload=payload,
throw_on_inexistent_trigger=True)
except (ValidationError, ValueError, Exception) as e:
self._logger.warn('Failed to validate payload (%s) for trigger "%s": %s' %
(str(payload), trigger, six.text_type(e)))
# If validation is disabled, still dispatch a trigger even if it failed validation
# This condition prevents unexpected restriction.
if cfg.CONF.system.validate_trigger_payload:
msg = ('Trigger payload validation failed and validation is enabled, not '
'dispatching a trigger "%s" (%s): %s' % (trigger, str(payload),
six.text_type(e)))
if throw_on_validation_error:
raise ValueError(msg)
self._logger.warn(msg)
return None
self._logger.debug('Dispatching trigger %s with payload %s.', trigger, payload)
return self._dispatcher.dispatch(trigger, payload=payload, trace_context=trace_context)
开发者ID:StackStorm,项目名称:st2,代码行数:74,代码来源:trigger_dispatcher.py
示例18: ActionsController
class ActionsController(resource.ContentPackResourceController):
"""
Implements the RESTful web endpoint that handles
the lifecycle of Actions in the system.
"""
views = ActionViewsController()
model = ActionAPI
access = Action
supported_filters = {
'name': 'name',
'pack': 'pack'
}
query_options = {
'sort': ['pack', 'name']
}
include_reference = True
def __init__(self, *args, **kwargs):
super(ActionsController, self).__init__(*args, **kwargs)
self._trigger_dispatcher = TriggerDispatcher(LOG)
@request_user_has_permission(permission_type=PermissionType.ACTION_VIEW)
@jsexpose()
def get_all(self, **kwargs):
return super(ActionsController, self)._get_all(**kwargs)
@request_user_has_resource_db_permission(permission_type=PermissionType.ACTION_VIEW)
@jsexpose(arg_types=[str])
def get_one(self, ref_or_id):
return super(ActionsController, self)._get_one(ref_or_id)
@jsexpose(body_cls=ActionCreateAPI, status_code=http_client.CREATED)
@request_user_has_resource_api_permission(permission_type=PermissionType.ACTION_CREATE)
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
@request_user_has_resource_db_permission(permission_type=PermissionType.ACTION_MODIFY)
@jsexpose(arg_types=[str], body_cls=ActionCreateAPI)
def put(self, action_ref_or_id, action):
action_db = self._get_by_ref_or_id(ref_or_id=action_ref_or_id)
# Assert permissions
action_id = action_db.id
if not getattr(action, 'pack', None):
action.pack = action_db.pack
# 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)
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)
#.........这里部分代码省略.........
开发者ID:jspittman,项目名称:st2,代码行数:101,代码来源:actions.py
示例19: WebhooksController
class WebhooksController(RestController):
def __init__(self, *args, **kwargs):
super(WebhooksController, self).__init__(*args, **kwargs)
self._hooks = HooksHolder()
self._base_url = "/webhooks/"
self._trigger_types = WEBHOOK_TRIGGER_TYPES.keys()
self._trigger_dispatcher = TriggerDispatcher(LOG)
queue_suffix = self.__class__.__name__
self._trigger_watcher = TriggerWatcher(
create_handler=self._handle_create_trigger,
update_handler=self._handle_update_trigger,
delete_handler=self._handle_delete_trigger,
trigger_types=self._trigger_types,
queue_suffix=queue_suffix,
exclusive=True,
)
self._trigger_watcher.start()
self._register_webhook_trigger_types()
@jsexpose()
def get_all(self):
# Return only the hooks known by this controller.
return self._hooks.get_all()
@jsexpose()
def get_one(self, name):
triggers = self._hooks.get_triggers_for_hook(name)
if not triggers:
abort(http_client.NOT_FOUND)
return
# For demonstration purpose return 1st
return triggers[0]
@request_user_has_webhook_permission(permission_type=PermissionType.WEBHOOK_SEND)
@jsexpose(arg_types=[str], status_code=http_client.ACCEPTED)
def post(self, *args, **kwargs):
hook = "/".join(args) # TODO: There must be a better way to do this.
# Note: For backward compatibility reasons we default to application/json if content
# type is not explicitly provided
content_type = pecan.request.headers.get("Content-Type", "application/json")
content_type = parse_content_type_header(content_type=content_type)[0]
body = pecan.request.body
try:
body = self._parse_request_body(content_type=content_type, body=body)
except Exception as e:
self._log_request("Failed to parse request body: %s." % (str(e)), pecan.request)
msg = 'Failed to parse request body "%s": %s' % (body, str(e))
return pecan.abort(http_client.BAD_REQUEST, msg)
headers = self._get_headers_as_dict(pecan.request.headers)
# If webhook contains a trace-tag use that el
|
请发表评论