Completed
Push — master ( a65260...307dd7 )
by Paolo
07:35
created

biosample.tasks.cleanup   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 1
eloc 25
dl 0
loc 65
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A CleanUpTask.run() 0 30 1
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Thu Nov 14 16:06:10 2019
5
6
@author: Paolo Cozzi <[email protected]>
7
"""
8
9
from datetime import timedelta
10
from celery.utils.log import get_task_logger
11
from django.utils import timezone
12
13
from common.constants import COMPLETED
14
from common.tasks import BaseTask, NotifyAdminTaskMixin, exclusive_task
15
from image.celery import app as celery_app
16
17
from ..models import Submission
18
19
# Get an instance of a logger
20
logger = get_task_logger(__name__)
21
22
23
class CleanUpTask(NotifyAdminTaskMixin, BaseTask):
24
    """Perform biosample.models cleanup by selecting old completed submission
25
    and remove them from database"""
26
27
    name = "Clean biosample models"
28
    description = """Clean biosample models"""
29
30
    @exclusive_task(task_name="Clean biosample models", lock_id="CleanUpTask")
31
    def run(self):
32
        """
33
        This function is called when delay is called. It will acquire a lock
34
        in redis, so those tasks are mutually exclusive
35
36
        Returns:
37
            str: success if everything is ok. Different messages if task is
38
            already running or exception is caught"""
39
40
        logger.info("Clean biosample.database started")
41
42
        # get an interval starting from 7 days from now
43
        interval = timezone.now() - timedelta(days=7)
44
45
        # select all COMPLETED object older than interval
46
        qs = Submission.objects.filter(
47
            updated_at__lt=interval,
48
            status=COMPLETED)
49
50
        logger.info(
51
            "Deleting %s biosample.models.Submission objects" % qs.count())
52
53
        # delete all old objects
54
        qs.delete()
55
56
        # debug
57
        logger.info("Clean biosample.database completed")
58
59
        return "success"
60
61
62
# register explicitly tasks
63
# https://github.com/celery/celery/issues/3744#issuecomment-271366923
64
celery_app.tasks.register(CleanUpTask)
65