activity.py 5.18 KB
Newer Older
1
from __future__ import absolute_import, unicode_literals
Őry Máté committed
2 3 4
from contextlib import contextmanager
from logging import getLogger

5
from django.db.models import CharField, ForeignKey
Őry Máté committed
6 7 8 9 10 11 12
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from common.models import ActivityModel, activitycontextimpl
logger = getLogger(__name__)


13 14 15 16 17 18 19 20 21 22 23 24
class ActivityInProgressError(Exception):

        def __init__(self, activity, message=None):
            if message is None:
                message = ("Another activity is currently in progress: '%s'."
                           % activity.activity_code)

            Exception.__init__(self, message)

            self.activity = activity


Őry Máté committed
25 26 27 28
class InstanceActivity(ActivityModel):
    instance = ForeignKey('Instance', related_name='activity_log',
                          help_text=_('Instance this activity works on.'),
                          verbose_name=_('instance'))
29
    resultant_state = CharField(blank=True, max_length=20, null=True)
Őry Máté committed
30 31 32 33

    class Meta:
        app_label = 'vm'
        db_table = 'vm_instanceactivity'
34
        ordering = ['-finished', '-started', 'instance', '-id']
Őry Máté committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

    def __unicode__(self):
        if self.parent:
            return '{}({})->{}'.format(self.parent.activity_code,
                                       self.instance,
                                       self.activity_code)
        else:
            return '{}({})'.format(self.activity_code,
                                   self.instance)

    def get_readable_name(self):
        return self.activity_code.split('.')[-1].replace('_', ' ').capitalize()

    @classmethod
    def create(cls, code_suffix, instance, task_uuid=None, user=None):
50 51 52 53 54
        # Check for concurrent activities
        active_activities = instance.activity_log.filter(finished__isnull=True)
        if active_activities.exists():
            raise ActivityInProgressError(active_activities[0])

Őry Máté committed
55
        act = cls(activity_code='vm.Instance.' + code_suffix,
56 57
                  instance=instance, parent=None, resultant_state=None,
                  started=timezone.now(), task_uuid=task_uuid, user=user)
Őry Máté committed
58 59 60 61
        act.save()
        return act

    def create_sub(self, code_suffix, task_uuid=None):
62 63 64 65 66
        # Check for concurrent activities
        active_children = self.children.filter(finished__isnull=True)
        if active_children.exists():
            raise ActivityInProgressError(active_children[0])

Őry Máté committed
67 68
        act = InstanceActivity(
            activity_code=self.activity_code + '.' + code_suffix,
69 70
            instance=self.instance, parent=self, resultant_state=None,
            started=timezone.now(), task_uuid=task_uuid, user=self.user)
Őry Máté committed
71 72 73 74
        act.save()
        return act

    @contextmanager
75 76
    def sub_activity(self, code_suffix, on_abort=None, on_commit=None,
                     task_uuid=None):
77 78
        """Create a transactional context for a nested instance activity.
        """
Őry Máté committed
79
        act = self.create_sub(code_suffix, task_uuid)
80
        return activitycontextimpl(act, on_abort=on_abort, on_commit=on_commit)
Őry Máté committed
81

82 83 84 85 86
    def save(self, *args, **kwargs):
        ret = super(InstanceActivity, self).save(*args, **kwargs)
        self.instance._update_status()
        return ret

Őry Máté committed
87 88

@contextmanager
89 90
def instance_activity(code_suffix, instance, on_abort=None, on_commit=None,
                      task_uuid=None, user=None):
91 92
    """Create a transactional context for an instance activity.
    """
Őry Máté committed
93
    act = InstanceActivity.create(code_suffix, instance, task_uuid, user)
94
    return activitycontextimpl(act, on_abort=on_abort, on_commit=on_commit)
95 96 97 98 99 100 101 102 103 104 105


class NodeActivity(ActivityModel):
    node = ForeignKey('Node', related_name='activity_log',
                      help_text=_('Node this activity works on.'),
                      verbose_name=_('node'))

    class Meta:
        app_label = 'vm'
        db_table = 'vm_nodeactivity'

106 107 108 109 110 111 112 113 114 115 116 117
    def __unicode__(self):
        if self.parent:
            return '{}({})->{}'.format(self.parent.activity_code,
                                       self.node,
                                       self.activity_code)
        else:
            return '{}({})'.format(self.activity_code,
                                   self.node)

    def get_readable_name(self):
        return self.activity_code.split('.')[-1].replace('_', ' ').capitalize()

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    @classmethod
    def create(cls, code_suffix, node, task_uuid=None, user=None):
        act = cls(activity_code='vm.Node.' + code_suffix,
                  node=node, parent=None, started=timezone.now(),
                  task_uuid=task_uuid, user=user)
        act.save()
        return act

    def create_sub(self, code_suffix, task_uuid=None):
        act = NodeActivity(
            activity_code=self.activity_code + '.' + code_suffix,
            node=self.node, parent=self, started=timezone.now(),
            task_uuid=task_uuid, user=self.user)
        act.save()
        return act

    @contextmanager
    def sub_activity(self, code_suffix, task_uuid=None):
        act = self.create_sub(code_suffix, task_uuid)
        return activitycontextimpl(act)


@contextmanager
def node_activity(code_suffix, node, task_uuid=None, user=None):
142
    act = NodeActivity.create(code_suffix, node, task_uuid, user)
143
    return activitycontextimpl(act)