local_periodic_tasks.py 1.96 KB
Newer Older
1 2 3 4
import logging
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

5
from manager.mancelery import celery
6 7 8
from vm.models import Node, Instance

logger = logging.getLogger(__name__)
9 10


11
@celery.task(ignore_result=True)
12 13 14 15
def update_domain_states():
    nodes = Node.objects.filter(enabled=True).all()
    for node in nodes:
        node.update_vm_states()
16 17 18 19 20 21 22 23 24 25 26 27


@celery.task(ignore_result=True)
def garbage_collector(timeout=15):
    """Garbage collector for instances.

    Suspends and destroys expired instances.

    :param timeout: Seconds before TimeOut exception
    :type timeout: int
    """
    now = timezone.now()
28
    for i in Instance.objects.filter(destroyed_at=None).all():
Bach Dániel committed
29
        if i.time_of_delete and now > i.time_of_delete:
30 31 32 33
            i.destroy_async()
            logger.info("Expired instance %d destroyed.", i.pk)
            try:
                i.owner.profile.notify(
34
                    _('%s destroyed') % unicode(i),
35 36
                    'dashboard/notifications/vm-destroyed.html',
                    {'instance': i})
37 38 39
            except Exception as e:
                logger.debug('Could not notify owner of instance %d .%s',
                             i.pk, unicode(e))
Bach Dániel committed
40
        elif (i.time_of_suspend and now > i.time_of_suspend and
41 42 43 44 45
              i.state == 'RUNNING'):
            i.sleep_async()
            logger.info("Expired instance %d suspended." % i.pk)
            try:
                i.owner.profile.notify(
46
                    _('%s suspended') % unicode(i),
47 48
                    'dashboard/notifications/vm-suspended.html',
                    {'instance': i})
49 50 51
            except Exception as e:
                logger.debug('Could not notify owner of instance %d .%s',
                             i.pk, unicode(e))
52 53 54
        elif i.is_expiring():
            logger.debug("Instance %d expires soon." % i.pk)
            i.notify_owners_about_expiration()
55 56
        else:
            logger.debug("Instance %d didn't expire." % i.pk)