events.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import logging
  2. from collections import UserDict, defaultdict
  3. from django.conf import settings
  4. from django.utils.module_loading import import_string
  5. from django.utils.translation import gettext as _
  6. from core.events import *
  7. from core.models import ObjectType
  8. from netbox.models.features import has_feature
  9. from utilities.api import get_serializer_for_model
  10. from utilities.serialization import serialize_object
  11. from .conditions import AbsentData
  12. from .models import EventRule
  13. logger = logging.getLogger('netbox.events_processor')
  14. class EventContext(UserDict):
  15. """
  16. Dictionary-compatible wrapper for queued events that lazily serializes
  17. ``event['data']`` on first access.
  18. Backward-compatible with the plain-dict interface expected by existing
  19. EVENTS_PIPELINE consumers. When the same object is enqueued more than once
  20. in a single request, the serialization source is updated so consumers see
  21. the latest state.
  22. """
  23. def __init__(self, *args, **kwargs):
  24. super().__init__(*args, **kwargs)
  25. # Track which model instance should be serialized if/when `data` is
  26. # requested. This may be refreshed on duplicate enqueue, while leaving
  27. # the public `object` entry untouched for compatibility.
  28. self._serialization_source = None
  29. if 'object' in self:
  30. self._serialization_source = super().__getitem__('object')
  31. def refresh_serialization_source(self, instance):
  32. """
  33. Point lazy serialization at a fresher instance, invalidating any
  34. already-materialized ``data``.
  35. """
  36. self._serialization_source = instance
  37. # UserDict.__contains__ checks the backing dict directly, so `in`
  38. # does not trigger __getitem__'s lazy serialization.
  39. if 'data' in self:
  40. del self['data']
  41. def freeze_data(self, instance):
  42. """
  43. Eagerly serialize and cache the payload for delete events, where the
  44. object may become inaccessible after deletion.
  45. """
  46. super().__setitem__('data', serialize_for_event(instance))
  47. self._serialization_source = None
  48. def __getitem__(self, item):
  49. if item == 'data' and 'data' not in self:
  50. # Materialize the payload only when an event consumer asks for it.
  51. #
  52. # On coalesced events, use the latest explicitly queued instance so
  53. # webhooks/scripts/notifications observe the final queued state for
  54. # that object within the request.
  55. source = self._serialization_source or super().__getitem__('object')
  56. super().__setitem__('data', serialize_for_event(source))
  57. return super().__getitem__(item)
  58. def serialize_for_event(instance):
  59. """
  60. Return a serialized representation of the given instance suitable for use in a queued event.
  61. """
  62. serializer_class = get_serializer_for_model(instance.__class__)
  63. serializer_context = {
  64. 'request': None,
  65. }
  66. serializer = serializer_class(instance, context=serializer_context)
  67. return serializer.data
  68. def get_snapshots(instance, event_type):
  69. """
  70. Return a dictionary of pre- and post-change snapshots for the given instance.
  71. """
  72. if event_type == OBJECT_DELETED:
  73. # Post-change snapshot must be empty for deleted objects
  74. postchange_snapshot = None
  75. elif hasattr(instance, '_postchange_snapshot'):
  76. # Use the cached post-change snapshot if one is available
  77. postchange_snapshot = instance._postchange_snapshot
  78. elif hasattr(instance, 'serialize_object'):
  79. # Use model's serialize_object() method if defined
  80. postchange_snapshot = instance.serialize_object()
  81. else:
  82. # Fall back to the serialize_object() utility function
  83. postchange_snapshot = serialize_object(instance)
  84. return {
  85. 'prechange': getattr(instance, '_prechange_snapshot', None),
  86. 'postchange': postchange_snapshot,
  87. }
  88. def enqueue_event(queue, instance, request, event_type, object_change_id=None):
  89. """
  90. Enqueue (or coalesce) an event for a created/updated/deleted object. If provided, object_change_id identifies the
  91. ObjectChange recorded for the change.
  92. Events are processed after the request completes.
  93. """
  94. # Bail if this type of object does not support event rules
  95. if not has_feature(instance, 'event_rules'):
  96. return
  97. app_label = instance._meta.app_label
  98. model_name = instance._meta.model_name
  99. if instance.pk is None:
  100. raise ValueError(
  101. _("Cannot enqueue an event for an unsaved {app_label}.{model} instance.").format(
  102. app_label=app_label,
  103. model=model_name,
  104. )
  105. )
  106. key = f'{app_label}.{model_name}:{instance.pk}'
  107. if key in queue:
  108. queue[key]['snapshots']['postchange'] = get_snapshots(instance, event_type)['postchange']
  109. # If the object is being deleted, convert any prior update event into a
  110. # delete event and freeze the payload before the object (or related
  111. # rows) become inaccessible.
  112. if event_type == OBJECT_DELETED:
  113. queue[key]['event_type'] = event_type
  114. else:
  115. # Keep the public `object` entry stable for compatibility.
  116. queue[key].refresh_serialization_source(instance)
  117. else:
  118. queue[key] = EventContext(
  119. object_type=ObjectType.objects.get_for_model(instance),
  120. object_id=instance.pk,
  121. object=instance,
  122. event_type=event_type,
  123. snapshots=get_snapshots(instance, event_type),
  124. object_change_ids=[],
  125. request=request,
  126. user=request.user,
  127. )
  128. # A coalesced event may span multiple ObjectChanges
  129. object_change_ids = queue[key].setdefault('object_change_ids', [])
  130. if object_change_id is not None and object_change_id not in object_change_ids:
  131. object_change_ids.append(object_change_id)
  132. # For delete events, eagerly serialize the payload before the row is gone.
  133. # This covers both first-time enqueues and coalesced update→delete promotions.
  134. if event_type == OBJECT_DELETED:
  135. queue[key].freeze_data(instance)
  136. def process_event_rules(event_rules, object_type, event):
  137. """
  138. Process a list of EventRules against an event.
  139. Notes on event sources:
  140. - Object change events (created/updated/deleted) are enqueued via enqueue_event()
  141. during an HTTP request. These events include a request object, and their payload is
  142. always the serialized object.
  143. - Job lifecycle events (JOB_STARTED/JOB_COMPLETED) are emitted by job_start/job_end
  144. signal handlers and may not include a request context. Consumers must not assume
  145. that a request is always present. Their payload is the job's `data` field, which is
  146. nullable and (for a job which sets it directly) not guaranteed to be a dict.
  147. """
  148. if not event_rules:
  149. return
  150. # Normalize object_type onto the event context so that an action's enqueue() can always read
  151. # event_context['object_type']: job-lifecycle events pass it only as this parameter.
  152. event['object_type'] = object_type
  153. # Normalize the event payload to a dict or AbsentData once for all rules.
  154. data = event['data']
  155. if not isinstance(data, dict):
  156. if data is not None:
  157. logger.warning(
  158. _('Ignoring invalid data payload on {event_type} event (got {data_type})').format(
  159. event_type=event['event_type'],
  160. data_type=type(data).__name__,
  161. )
  162. )
  163. data = AbsentData()
  164. for event_rule in event_rules:
  165. # Merge snapshots and evaluate event rule conditions (if any).
  166. condition_data = data.copy()
  167. condition_data['snapshots'] = event.get('snapshots')
  168. if not event_rule.eval_conditions(condition_data):
  169. continue
  170. # Guard against action_data that is valid JSON but not a dict
  171. # (e.g. a bare string or number). Existing rows with bad data are
  172. # tolerated at runtime; validation on EventRule.clean() prevents
  173. # new ones.
  174. if event_rule.action_data is None:
  175. action_data = {}
  176. elif isinstance(event_rule.action_data, dict):
  177. action_data = event_rule.action_data
  178. else:
  179. logger.warning(
  180. _('Ignoring invalid action_data on event rule "{rule}" (got {data_type})').format(
  181. rule=event_rule,
  182. data_type=type(event_rule.action_data).__name__,
  183. )
  184. )
  185. action_data = {}
  186. # Merge rule-specific action_data with the event payload.
  187. # Copy to avoid mutating the rule's stored action_data dict.
  188. event_data = {**action_data, **data}
  189. action = event_rule.action_provider
  190. if action is None:
  191. # The plugin providing this action type may not be installed. Log and move on to the
  192. # next rule rather than raising: one rule's unavailable action must not prevent any
  193. # other rule in this batch from being processed.
  194. logger.warning(
  195. _('Skipping event rule "{rule}": action type "{action_type}" is not registered '
  196. '(the providing plugin may not be installed).').format(
  197. rule=event_rule, action_type=event_rule.action_type,
  198. )
  199. )
  200. continue
  201. try:
  202. action.enqueue(
  203. event_rule=event_rule,
  204. event_context=event,
  205. action_object=event_rule.action_object,
  206. action_data=event_data,
  207. )
  208. except Exception:
  209. # Isolate third-party bugs; a core action's own bugs should propagate instead.
  210. if not action.is_plugin_provided:
  211. raise
  212. logger.exception(
  213. _('Error processing event rule "{rule}" (action: {action_type})').format(
  214. rule=event_rule, action_type=event_rule.action_type,
  215. )
  216. )
  217. def process_event_queue(events):
  218. """
  219. Flush a list of object representation to RQ for EventRule processing.
  220. This is the default processor listed in EVENTS_PIPELINE.
  221. """
  222. events_cache = defaultdict(dict)
  223. for event in events:
  224. event_type = event['event_type']
  225. object_type = event['object_type']
  226. # Cache applicable Event Rules
  227. if object_type not in events_cache[event_type]:
  228. events_cache[event_type][object_type] = EventRule.objects.filter(
  229. event_types__contains=[event['event_type']],
  230. object_types=object_type,
  231. enabled=True
  232. )
  233. event_rules = events_cache[event_type][object_type]
  234. process_event_rules(
  235. event_rules=event_rules,
  236. object_type=object_type,
  237. event=event,
  238. )
  239. def flush_events(events):
  240. """
  241. Flush a list of object representations to RQ for event processing.
  242. """
  243. if events:
  244. for name in settings.EVENTS_PIPELINE:
  245. try:
  246. func = import_string(name)
  247. func(events)
  248. except ImportError as e:
  249. logger.error(_("Cannot import events pipeline {name} error: {error}").format(name=name, error=e))