models.py 5.12 KB
Newer Older
1
from hashlib import sha224
2
from logging import getLogger
3 4
from time import time

5
from django.contrib.auth.models import User
6
from django.core.cache import cache
7 8
from django.db.models import (CharField, DateTimeField, ForeignKey,
                              NullBooleanField, TextField)
9 10
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
11

12 13
from model_utils.models import TimeStampedModel

14 15
logger = getLogger(__name__)

16

17 18 19 20
class WorkerNotFound(Exception):
    pass


21
def activitycontextimpl(act, on_abort=None, on_commit=None):
22 23
    try:
        yield act
24 25 26
    except BaseException as e:
        # BaseException is the common parent of Exception and
        # system-exiting exceptions, e.g. KeyboardInterrupt
27 28
        handler = None if on_abort is None else lambda a: on_abort(a, e)
        act.finish(succeeded=False, result=str(e), event_handler=handler)
29 30
        raise e
    else:
31
        act.finish(succeeded=True, event_handler=on_commit)
32 33 34 35


class ActivityModel(TimeStampedModel):
    activity_code = CharField(max_length=100, verbose_name=_('activity code'))
36
    parent = ForeignKey('self', blank=True, null=True, related_name='children')
37 38 39 40 41 42 43 44 45 46 47
    task_uuid = CharField(blank=True, max_length=50, null=True, unique=True,
                          help_text=_('Celery task unique identifier.'),
                          verbose_name=_('task_uuid'))
    user = ForeignKey(User, blank=True, null=True, verbose_name=_('user'),
                      help_text=_('The person who started this activity.'))
    started = DateTimeField(verbose_name=_('started at'),
                            blank=True, null=True,
                            help_text=_('Time of activity initiation.'))
    finished = DateTimeField(verbose_name=_('finished at'),
                             blank=True, null=True,
                             help_text=_('Time of activity finalization.'))
48 49 50
    succeeded = NullBooleanField(blank=True, null=True,
                                 help_text=_('True, if the activity has '
                                             'finished successfully.'))
51 52 53
    result = TextField(verbose_name=_('result'), blank=True, null=True,
                       help_text=_('Human readable result of activity.'))

54 55 56 57 58 59
    def __unicode__(self):
        if self.parent:
            return self.parent.activity_code + "->" + self.activity_code
        else:
            return self.activity_code

60 61 62
    class Meta:
        abstract = True

63
    def finish(self, succeeded, result=None, event_handler=None):
64 65
        if not self.finished:
            self.finished = timezone.now()
66
            self.succeeded = succeeded
67
            self.result = result
68 69
            if event_handler is not None:
                event_handler(self)
70
            self.save()
71

72 73 74 75 76 77 78 79
    @property
    def has_succeeded(self):
        return self.finished and self.succeeded

    @property
    def has_failed(self):
        return self.finished and not self.succeeded

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

def method_cache(memcached_seconds=60, instance_seconds=5):  # noqa
    """Cache return value of decorated method to memcached and memory.

    :param memcached_seconds: Invalidate memcached results after this time.
    :param instance_seconds: Invalidate results cached to static memory after
    this time.

    If a result is cached on instance, return that first.  If that fails, check
    memcached. If all else fails, run the method and cache on instance and in
    memcached.

    Do not use for methods with side effects.
    Instances are hashed by their id attribute, args by their unicode
    representation.

    ** NOTE: Methods that return None are always "recached".
    Based on https://djangosnippets.org/snippets/2477/
    """

    def inner_cache(method):

        def get_key(instance, *args, **kwargs):
            return sha224(unicode(method.__module__) +
                          unicode(method.__name__) +
                          unicode(instance.id) +
                          unicode(args) +
                          unicode(kwargs)).hexdigest()

        def x(instance, *args, **kwargs):
            invalidate = kwargs.pop('invalidate_cache', False)
            now = time()
            key = get_key(instance, *args, **kwargs)

            result = None
            try:
                vals = getattr(instance, key)
            except AttributeError:
                pass
            else:
                if vals['time'] + instance_seconds > now:
                    # has valid on class cache, return that
                    result = vals['value']

            if result is None:
                result = cache.get(key)

            if invalidate or (result is None):
                # all caches failed, call the actual method
                result = method(instance, *args, **kwargs)
                # save to memcache and class attr
                cache.set(key, result, memcached_seconds)
                setattr(instance, key, {'time': now, 'value': result})
133 134 135
                logger.debug('Value of <%s>.%s(%s)=<%s> saved to cache.',
                             unicode(instance), method.__name__,
                             unicode(args), unicode(result))
136 137 138 139 140

            return result
        return x

    return inner_cache