diff --git a/docs/CHANGELOG.rst b/docs/CHANGELOG.rst index e8c73cf51..06f8319b9 100644 --- a/docs/CHANGELOG.rst +++ b/docs/CHANGELOG.rst @@ -15,6 +15,10 @@ Changed - Relation slug can be updated - Anonymous user can access the annotation field endpoint +Added +----- +- Add ``clean_observers`` management command to clean old subsciptions + =================== 36.0.0 - 2023-07-17 diff --git a/resolwe/observers/management/__init__.py b/resolwe/observers/management/__init__.py new file mode 100644 index 000000000..0f0e714c0 --- /dev/null +++ b/resolwe/observers/management/__init__.py @@ -0,0 +1,10 @@ +""".. Ignore pydocstyle D400. + +==================== +Observers Management +==================== + +.. automodule:: resolwe.observers.management.commands.register + :members: + +""" diff --git a/resolwe/observers/management/commands/__init__.py b/resolwe/observers/management/commands/__init__.py new file mode 100644 index 000000000..4d3c8c8a9 --- /dev/null +++ b/resolwe/observers/management/commands/__init__.py @@ -0,0 +1 @@ +"""Management commands module.""" diff --git a/resolwe/observers/management/commands/clean_observers.py b/resolwe/observers/management/commands/clean_observers.py new file mode 100644 index 000000000..ba5c1a955 --- /dev/null +++ b/resolwe/observers/management/commands/clean_observers.py @@ -0,0 +1,54 @@ +""".. Ignore pydocstyle D400. + +======================= +Clean old observer data +======================= + +Command to run: + + ./manage.py clean_observers + +""" +import logging + +from django.core.management.base import BaseCommand +from django.utils import timezone + +from resolwe.observers.models import Observer, Subscription + +# Delete subscriptions older than DELETE_OLDER_THAN hours. +DELETE_OLDER_THAN = 5 * 24 + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + """Delete old observers subscriptions.""" + + help = "Delete old observer subscriptions." + + def add_arguments(self, parser): + """Command arguments.""" + parser.add_argument( + "--older-than", + type=int, + dest="older_than", + help="Delete subscriptions older than older-than hours", + ) + + def handle(self, *args, **options): + """Delete old observer subscriptions.""" + delete_older_than = options["older_than"] or DELETE_OLDER_THAN + logger.info( + "Deleting observer subscriptions older than %d hours.", delete_older_than + ) + # Delete subscriptions older than delete_older_than hours. + deleted_subscriptions = Subscription.objects.filter( + created__lt=timezone.now() - timezone.timedelta(hours=delete_older_than) + ).delete()[0] + logger.info("Deleted %d subscriptions.", deleted_subscriptions) + # Delete observers without subscriptions. + deleted_observers = Observer.objects.filter( + subscriptions__isnull=True + ).delete()[0] + logger.info("Deleted %d observers.", deleted_observers)