From 049f7289bcb3bdbcc0e826fee350e50861704ef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sandstr=C3=B6m?= Date: Thu, 16 Nov 2023 12:57:38 +0100 Subject: [PATCH] Added delete develop-apps task that runs every day a 4 am. (#99) * Added cronjob that deletes all apps under category "Develop" after 7 days --- apps/tasks.py | 22 +++++++++++++++++++-- fixtures/periodic_tasks_fixtures.json | 28 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/apps/tasks.py b/apps/tasks.py index ab81db7c..b1fe690d 100644 --- a/apps/tasks.py +++ b/apps/tasks.py @@ -1,7 +1,7 @@ import json import subprocess import time -from datetime import datetime +from django.utils import timezone import requests from celery import shared_task @@ -385,7 +385,7 @@ def check_status(): status.status_type = "Deleted" status.save() instance.state = "Deleted" - instance.deleted_on = datetime.now() + instance.deleted_on = timezone.now() instance.save() # Fetch all app instances whose state is "Deleted" and check whether @@ -636,3 +636,21 @@ def purge_tasks(): Remove tasks from queue to avoid overflow """ app.control.purge() + + +@app.task +def delete_old_objects(): + """ + Deletes apps of category Develop (e.g., jupyter-lab, vscode etc) + + Setting the threshold to 7 days. If any app is older than this, it will be deleted. + The deleted resource will still exist in the database, but with status "Deleted" + + TODO: Make this a variable in settings.py and use the same number in templates + """ + threshold = 7 + threshold_time = timezone.now() - timezone.timedelta(days=threshold) + + old_apps = AppInstance.objects.filter(created_on__lt=threshold_time, app__category__name="Develop") + for app in old_apps: + delete_resource.delay(app.pk) diff --git a/fixtures/periodic_tasks_fixtures.json b/fixtures/periodic_tasks_fixtures.json index 5a688c09..7c77c72b 100644 --- a/fixtures/periodic_tasks_fixtures.json +++ b/fixtures/periodic_tasks_fixtures.json @@ -110,5 +110,33 @@ "date_changed": "2021-02-26T14:03:40.168Z", "description": "" } + }, + { + "model": "django_celery_beat.periodictask", + "pk": 6, + "fields": { + "name": "delete_old_objects", + "task": "apps.tasks.delete_old_objects", + "interval": null, + "crontab": 3, + "solar": null, + "clocked": null, + "args": "[]", + "kwargs": "{}", + "queue": null, + "exchange": null, + "routing_key": null, + "headers": "{}", + "priority": null, + "expires": null, + "expire_seconds": null, + "one_off": false, + "start_time": null, + "enabled": true, + "last_run_at": "2021-02-26T14:03:37.169Z", + "total_run_count": 174, + "date_changed": "2021-02-26T14:03:40.168Z", + "description": "Deletes apps under develop after specified amount of time" + } } ]