scheduled_vm_cleanup.py 2.52 KB
Newer Older
Bach Dániel committed
1
# -*- coding: utf-8 -*-
Őry Máté committed
2
from django_extensions.management.jobs import HourlyJob
Bach Dániel committed
3 4 5 6 7 8
import datetime
from django.utils.timezone import utc
from one.models import Instance
from django.template.loader import render_to_string
from one.tasks import SendMailTask
from django.utils.translation import ugettext_lazy as _
Őry Máté committed
9 10 11 12

class Job(HourlyJob):
    help = "Suspend/delete expired Instances."

Bach Dániel committed
13 14 15
    def calc(self, orig, days=0, hours=0):
        return (orig + datetime.timedelta(days=days, hours=hours)).replace(minute=0, second=0, microsecond=0)

Őry Máté committed
16
    def execute(self):
Bach Dániel committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
        now = datetime.datetime.utcnow().replace(tzinfo=utc)
        d = {
            '1m': self.calc(orig=now, days=30),
            '2w': self.calc(orig=now, days=14),
            '1w': self.calc(orig=now, days=7),
            '1d': self.calc(orig=now, days=1),
            '1h': self.calc(orig=now, hours=2),
        }
        # for i in d:
        #    print i+':'+unicode(d[i])

        # delete
        for i in Instance.objects.filter(state__in=['ACTIVE', 'STOPPED'], time_of_delete__isnull=False):
            print "%s delete: %s" % (i.name, i.time_of_delete)
            delete = i.time_of_delete.replace(minute=0, second=0, microsecond=0)
            if delete < now:
                msg = render_to_string('mails/notification-delete-now.txt', { 'user': i.owner, 'instance': i } )
                SendMailTask.delay(to=i.owner.email, subject=_('Delete notification'), msg=msg)
            else:
                for t in d:
                    if delete == d[t]:
                        msg = render_to_string('mails/notification-delete.txt', { 'user': i.owner, 'instance': i } )
                        SendMailTask.delay(to=i.owner.email, subject=_('Delete notification'), msg=msg)

        # suspend
        for i in Instance.objects.filter(state='ACTIVE', time_of_suspend__isnull=False):
            print "%s suspend: %s" % (i.name, i.time_of_suspend)
            suspend = i.time_of_suspend.replace(minute=0, second=0, microsecond=0)

            if suspend < now:
                msg = render_to_string('mails/notification-suspend-now.txt', { 'user': i.owner, 'instance': i } )
                SendMailTask.delay(to=i.owner.email, subject=_('Stop notification'), msg=msg)
                i.stop()
            else:
                for t in d:
                    if suspend == d[t]:
                        msg = render_to_string('mails/notification-suspend.txt', { 'user': i.owner, 'instance': i } )
                        SendMailTask.delay(to=i.owner.email, subject=_('Stop notification'), msg=msg)