Implement Booking Cleanup Task
[pharos-tools.git] / dashboard / src / dashboard / tasks.py
1 ##############################################################################
2 # Copyright (c) 2016 Max Breitenfeldt and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 from datetime import timedelta
11
12 from celery import shared_task
13 from django.utils import timezone
14 from django.conf import settings
15 from booking.models import Booking
16
17 from jenkins.models import JenkinsStatistic
18
19 @shared_task
20 def database_cleanup():
21     now = timezone.now()
22     JenkinsStatistic.objects.filter(timestamp__lt=now - timedelta(weeks=4)).delete()
23
24 def booking_cleanup():
25     expire_time = timedelta(days=int(settings.BOOKING_EXP_TIME))
26     expire_number = int(settings.BOOKING_MAX_NUM)
27     expired_set = Booking.objects.filter(end__lte=timezone.now())
28     expired_count = len(expired_set)
29
30     for booking in expired_set:
31         if timezone.now() - booking.end > expire_time:
32             booking.delete()
33             expired_count = expired_count - 1
34
35     if expired_count > expire_number:
36         oldest = expired_set.order_by("end")[:expired_count-expire_number]
37         for booking in oldest:
38             booking.delete()