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

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

logger = logging.getLogger(__name__)
10 11


12
@celery.task(ignore_result=True)
13 14 15 16
def update_domain_states():
    nodes = Node.objects.filter(enabled=True).all()
    for node in nodes:
        node.update_vm_states()
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


@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()
    for i in Instance.objects.filter(destroyed=None).all():
        if i.time_of_delete and now < i.time_of_delete:
            i.destroy_async()
            logger.info("Expired instance %d destroyed.", i.pk)
            try:
                i.owner.profile.notify(
                    _('Machine destroyed'),
                    'dashboard/notifications/vm-destroyed.html',
                    {'instance': i})
            except:
                logger.debug('Could not notify owner of instance %d.', i.pk)
        elif (i.time_of_suspend and now < i.time_of_suspend and
              i.state == 'RUNNING'):
            i.sleep_async()
            logger.info("Expired instance %d suspended." % i.pk)
            try:
                i.owner.profile.notify(
                    _('Machine suspended'),
                    'dashboard/notifications/vm-suspended.html',
                    {'instance': i})
            except:
                logger.debug('Could not notify owner of instance %d.', i.pk)
        else:
            logger.debug("Instance %d didn't expire." % i.pk)