2018-06-22 16:18:41 -04:00
|
|
|
import random
|
2018-07-10 13:33:54 -04:00
|
|
|
import threading
|
2018-06-19 15:45:15 -04:00
|
|
|
import uuid
|
2019-10-22 14:36:30 -04:00
|
|
|
from copy import deepcopy
|
2018-11-02 15:20:08 -04:00
|
|
|
from datetime import timedelta
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2018-06-22 16:18:41 -04:00
|
|
|
from django.conf import settings
|
2020-02-21 17:21:04 -05:00
|
|
|
from django.contrib import messages
|
2019-10-22 14:36:30 -04:00
|
|
|
from django.db.models.signals import pre_delete, post_save
|
2018-06-22 16:18:41 -04:00
|
|
|
from django.utils import timezone
|
2019-04-25 01:09:19 -04:00
|
|
|
from django_prometheus.models import model_deletes, model_inserts, model_updates
|
2020-02-21 17:21:04 -05:00
|
|
|
from redis.exceptions import RedisError
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2019-12-11 15:26:47 -05:00
|
|
|
from extras.utils import is_taggable
|
2020-02-21 17:21:04 -05:00
|
|
|
from utilities.api import is_api_request
|
2019-10-22 14:36:30 -04:00
|
|
|
from utilities.querysets import DummyQuerySet
|
2019-12-05 16:30:15 -05:00
|
|
|
from .choices import ObjectChangeActionChoices
|
2018-06-22 16:18:41 -04:00
|
|
|
from .models import ObjectChange
|
2019-08-26 11:59:38 -04:00
|
|
|
from .signals import purge_changelog
|
|
|
|
from .webhooks import enqueue_webhooks
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2018-07-10 13:33:54 -04:00
|
|
|
_thread_locals = threading.local()
|
|
|
|
|
|
|
|
|
2019-09-09 15:50:10 -04:00
|
|
|
def handle_changed_object(sender, instance, **kwargs):
|
2019-08-26 16:52:05 -04:00
|
|
|
"""
|
2019-10-22 14:36:30 -04:00
|
|
|
Fires when an object is created or updated.
|
2019-08-26 16:52:05 -04:00
|
|
|
"""
|
2019-10-22 16:12:25 -04:00
|
|
|
# Queue the object for processing once the request completes
|
2019-12-05 16:30:15 -05:00
|
|
|
action = ObjectChangeActionChoices.ACTION_CREATE if kwargs['created'] else ObjectChangeActionChoices.ACTION_UPDATE
|
2019-10-22 14:36:30 -04:00
|
|
|
_thread_locals.changed_objects.append(
|
|
|
|
(instance, action)
|
|
|
|
)
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2018-06-22 16:18:41 -04:00
|
|
|
|
2019-10-22 14:36:30 -04:00
|
|
|
def handle_deleted_object(sender, instance, **kwargs):
|
2019-08-26 16:52:05 -04:00
|
|
|
"""
|
2019-10-22 14:36:30 -04:00
|
|
|
Fires when an object is deleted.
|
2019-08-26 16:52:05 -04:00
|
|
|
"""
|
2019-10-22 14:36:30 -04:00
|
|
|
# Cache custom fields prior to copying the instance
|
|
|
|
if hasattr(instance, 'cache_custom_fields'):
|
|
|
|
instance.cache_custom_fields()
|
2019-09-09 15:50:10 -04:00
|
|
|
|
2019-10-22 14:36:30 -04:00
|
|
|
# Create a copy of the object being deleted
|
|
|
|
copy = deepcopy(instance)
|
2019-09-09 15:50:10 -04:00
|
|
|
|
2019-10-22 14:36:30 -04:00
|
|
|
# Preserve tags
|
2019-12-11 15:26:47 -05:00
|
|
|
if is_taggable(instance):
|
2019-10-22 14:36:30 -04:00
|
|
|
copy.tags = DummyQuerySet(instance.tags.all())
|
|
|
|
|
2019-10-22 16:12:25 -04:00
|
|
|
# Queue the copy of the object for processing once the request completes
|
2019-10-22 14:36:30 -04:00
|
|
|
_thread_locals.changed_objects.append(
|
2019-12-05 16:30:15 -05:00
|
|
|
(copy, ObjectChangeActionChoices.ACTION_DELETE)
|
2019-10-22 14:36:30 -04:00
|
|
|
)
|
2019-04-25 01:09:19 -04:00
|
|
|
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2019-08-26 11:59:38 -04:00
|
|
|
def purge_objectchange_cache(sender, **kwargs):
|
|
|
|
"""
|
|
|
|
Delete any queued object changes waiting to be written.
|
|
|
|
"""
|
2019-08-28 10:44:05 -04:00
|
|
|
_thread_locals.changed_objects = []
|
2019-08-26 11:59:38 -04:00
|
|
|
|
|
|
|
|
2018-07-30 14:23:49 -04:00
|
|
|
class ObjectChangeMiddleware(object):
|
|
|
|
"""
|
2019-04-25 01:09:19 -04:00
|
|
|
This middleware performs three functions in response to an object being created, updated, or deleted:
|
2018-07-30 16:33:37 -04:00
|
|
|
|
|
|
|
1. Create an ObjectChange to reflect the modification to the object in the changelog.
|
|
|
|
2. Enqueue any relevant webhooks.
|
2019-09-09 15:50:10 -04:00
|
|
|
3. Increment the metric counter for the event type.
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2019-05-30 10:32:09 -04:00
|
|
|
The post_save and post_delete signals are employed to catch object modifications, however changes are recorded a bit
|
2018-07-30 16:33:37 -04:00
|
|
|
differently for each. Objects being saved are cached into thread-local storage for action *after* the response has
|
|
|
|
completed. This ensures that serialization of the object is performed only after any related objects (e.g. tags)
|
|
|
|
have been created. Conversely, deletions are acted upon immediately, so that the serialized representation of the
|
|
|
|
object is recorded before it (and any related objects) are actually deleted from the database.
|
|
|
|
"""
|
2018-06-13 17:06:33 -04:00
|
|
|
def __init__(self, get_response):
|
|
|
|
self.get_response = get_response
|
|
|
|
|
|
|
|
def __call__(self, request):
|
|
|
|
|
2018-07-30 16:33:37 -04:00
|
|
|
# Initialize an empty list to cache objects being saved.
|
2018-07-10 13:33:54 -04:00
|
|
|
_thread_locals.changed_objects = []
|
|
|
|
|
|
|
|
# Assign a random unique ID to the request. This will be used to associate multiple object changes made during
|
|
|
|
# the same request.
|
|
|
|
request.id = uuid.uuid4()
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2019-05-30 10:32:09 -04:00
|
|
|
# Connect our receivers to the post_save and post_delete signals.
|
2019-10-22 14:36:30 -04:00
|
|
|
post_save.connect(handle_changed_object, dispatch_uid='handle_changed_object')
|
|
|
|
pre_delete.connect(handle_deleted_object, dispatch_uid='handle_deleted_object')
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2019-08-26 11:59:38 -04:00
|
|
|
# Provide a hook for purging the change cache
|
|
|
|
purge_changelog.connect(purge_objectchange_cache)
|
|
|
|
|
2018-07-10 13:33:54 -04:00
|
|
|
# Process the request
|
|
|
|
response = self.get_response(request)
|
2018-06-19 15:45:15 -04:00
|
|
|
|
2019-08-28 10:44:05 -04:00
|
|
|
# If the change cache is empty, there's nothing more we need to do.
|
|
|
|
if not _thread_locals.changed_objects:
|
2019-08-26 11:59:38 -04:00
|
|
|
return response
|
|
|
|
|
2020-02-24 12:42:51 -05:00
|
|
|
# Disconnect our receivers from the post_save and post_delete signals.
|
|
|
|
post_save.disconnect(handle_changed_object, dispatch_uid='handle_changed_object')
|
|
|
|
pre_delete.disconnect(handle_deleted_object, dispatch_uid='handle_deleted_object')
|
|
|
|
|
2019-10-22 14:36:30 -04:00
|
|
|
# Create records for any cached objects that were changed.
|
2020-02-21 17:21:04 -05:00
|
|
|
redis_failed = False
|
2019-10-22 14:36:30 -04:00
|
|
|
for instance, action in _thread_locals.changed_objects:
|
2018-07-30 16:33:37 -04:00
|
|
|
|
2019-10-22 16:12:25 -04:00
|
|
|
# Refresh cached custom field values
|
2019-12-05 16:30:15 -05:00
|
|
|
if action in [ObjectChangeActionChoices.ACTION_CREATE, ObjectChangeActionChoices.ACTION_UPDATE]:
|
2019-10-22 16:12:25 -04:00
|
|
|
if hasattr(instance, 'cache_custom_fields'):
|
|
|
|
instance.cache_custom_fields()
|
|
|
|
|
2019-10-22 14:36:30 -04:00
|
|
|
# Record an ObjectChange if applicable
|
|
|
|
if hasattr(instance, 'to_objectchange'):
|
|
|
|
objectchange = instance.to_objectchange(action)
|
|
|
|
objectchange.user = request.user
|
|
|
|
objectchange.request_id = request.id
|
|
|
|
objectchange.save()
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2018-07-30 16:33:37 -04:00
|
|
|
# Enqueue webhooks
|
2020-02-21 17:21:04 -05:00
|
|
|
try:
|
|
|
|
enqueue_webhooks(instance, request.user, request.id, action)
|
|
|
|
except RedisError as e:
|
|
|
|
if not redis_failed and not is_api_request(request):
|
|
|
|
messages.error(
|
|
|
|
request,
|
|
|
|
"There was an error processing webhooks for this request. Check that the Redis service is "
|
|
|
|
"running and reachable. The full error details were: {}".format(e)
|
|
|
|
)
|
|
|
|
redis_failed = True
|
2018-07-30 14:23:49 -04:00
|
|
|
|
2019-04-25 01:09:19 -04:00
|
|
|
# Increment metric counters
|
2019-12-05 16:30:15 -05:00
|
|
|
if action == ObjectChangeActionChoices.ACTION_CREATE:
|
2019-10-22 14:36:30 -04:00
|
|
|
model_inserts.labels(instance._meta.model_name).inc()
|
2019-12-05 16:30:15 -05:00
|
|
|
elif action == ObjectChangeActionChoices.ACTION_UPDATE:
|
2019-10-22 14:36:30 -04:00
|
|
|
model_updates.labels(instance._meta.model_name).inc()
|
2019-12-05 16:30:15 -05:00
|
|
|
elif action == ObjectChangeActionChoices.ACTION_DELETE:
|
2019-10-22 14:36:30 -04:00
|
|
|
model_deletes.labels(instance._meta.model_name).inc()
|
2019-04-25 01:09:19 -04:00
|
|
|
|
2019-08-28 10:44:05 -04:00
|
|
|
# Housekeeping: 1% chance of clearing out expired ObjectChanges. This applies only to requests which result in
|
|
|
|
# one or more changes being logged.
|
|
|
|
if settings.CHANGELOG_RETENTION and random.randint(1, 100) == 1:
|
2018-07-10 13:33:54 -04:00
|
|
|
cutoff = timezone.now() - timedelta(days=settings.CHANGELOG_RETENTION)
|
2020-07-07 13:54:49 -04:00
|
|
|
purged_count, _ = ObjectChange.objects.unrestricted().filter(
|
2018-07-10 13:33:54 -04:00
|
|
|
time__lt=cutoff
|
|
|
|
).delete()
|
2018-06-13 17:06:33 -04:00
|
|
|
|
2018-07-10 13:33:54 -04:00
|
|
|
return response
|