tasks.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from datetime import timedelta
  2. from celery import shared_task
  3. from django.conf import settings
  4. from django.utils.timezone import now
  5. from .models import Span, TransactionEvent, TransactionGroup
  6. @shared_task
  7. def cleanup_old_transaction_events():
  8. """Delete older events and associated data"""
  9. days = settings.GLITCHTIP_MAX_TRANSACTION_EVENT_LIFE_DAYS
  10. days_ago = now() - timedelta(days=days)
  11. qs = Span.objects.filter(created__lt=days_ago)
  12. # Fast bulk delete - see https://code.djangoproject.com/ticket/9519
  13. qs._raw_delete(qs.db)
  14. qs = TransactionEvent.objects.filter(created__lt=days_ago)
  15. qs._raw_delete(qs.db)
  16. # Delete ~1k empty transaction groups at a time until less than 1k remain then delete the rest. Avoids memory overload.
  17. queryset = TransactionGroup.objects.filter(transactionevent=None).order_by("id")
  18. while True:
  19. try:
  20. empty_group_delimiter = queryset.values_list("id", flat=True)[
  21. 1000:1001
  22. ].get()
  23. queryset.filter(id__lte=empty_group_delimiter).delete()
  24. except TransactionGroup.DoesNotExist:
  25. break
  26. queryset.delete()