models.py 20.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

Őry Máté committed
18
from collections import deque
19
from contextlib import contextmanager
20
from functools import update_wrapper
21
from hashlib import sha224
22
from itertools import chain, imap
23
from logging import getLogger
24
from time import time
25
from warnings import warn
26

27
from django.contrib import messages
28
from django.contrib.auth.models import User
29
from django.core.cache import cache
30
from django.core.exceptions import PermissionDenied
31
from django.core.serializers.json import DjangoJSONEncoder
Dudás Ádám committed
32 33 34
from django.db.models import (
    CharField, DateTimeField, ForeignKey, NullBooleanField
)
35
from django.template import defaultfilters
36
from django.utils import timezone
37 38
from django.utils.encoding import force_text
from django.utils.functional import Promise
39 40
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from jsonfield import JSONField
41

42
from manager.mancelery import celery
43 44
from model_utils.models import TimeStampedModel

45 46
logger = getLogger(__name__)

47

48 49 50 51
class WorkerNotFound(Exception):
    pass


52 53 54 55 56 57 58
def get_error_msg(exception):
    try:
        return unicode(exception)
    except UnicodeDecodeError:
        return unicode(str(exception), encoding='utf-8', errors='replace')


59
def activitycontextimpl(act, on_abort=None, on_commit=None):
60
    result = None
61
    try:
62 63 64 65 66 67 68 69 70 71 72
        try:
            yield act
        except HumanReadableException as e:
            result = e
            raise
        except BaseException as e:
            # BaseException is the common parent of Exception and
            # system-exiting exceptions, e.g. KeyboardInterrupt
            result = create_readable(
                ugettext_noop("Failure."),
                ugettext_noop("Unhandled exception: %(error)s"),
73
                error=get_error_msg(e))
74 75 76
            raise
    except:
        logger.exception("Failed activity %s" % unicode(act))
77
        handler = None if on_abort is None else lambda a: on_abort(a, e)
78
        act.finish(succeeded=False, result=result, event_handler=handler)
79
        raise
80
    else:
81
        act.finish(succeeded=True, event_handler=on_commit)
82 83


84 85 86
activity_context = contextmanager(activitycontextimpl)


87 88 89
activity_code_separator = '.'


90 91 92
def has_prefix(activity_code, *prefixes):
    """Determine whether the activity code has the specified prefix.

93 94 95 96 97
    >>> assert has_prefix('foo.bar.buz', 'foo.bar')
    >>> assert has_prefix('foo.bar.buz', 'foo', 'bar')
    >>> assert has_prefix('foo.bar.buz', 'foo.bar', 'buz')
    >>> assert has_prefix('foo.bar.buz', 'foo', 'bar', 'buz')
    >>> assert not has_prefix('foo.bar.buz', 'foo', 'buz')
98 99 100 101 102 103 104 105 106 107
    """
    equal = lambda a, b: a == b
    act_code_parts = split_activity_code(activity_code)
    prefixes = chain(*imap(split_activity_code, prefixes))
    return all(imap(equal, act_code_parts, prefixes))


def has_suffix(activity_code, *suffixes):
    """Determine whether the activity code has the specified suffix.

108 109 110 111 112
    >>> assert has_suffix('foo.bar.buz', 'bar.buz')
    >>> assert has_suffix('foo.bar.buz', 'bar', 'buz')
    >>> assert has_suffix('foo.bar.buz', 'foo.bar', 'buz')
    >>> assert has_suffix('foo.bar.buz', 'foo', 'bar', 'buz')
    >>> assert not has_suffix('foo.bar.buz', 'foo', 'buz')
113 114 115
    """
    equal = lambda a, b: a == b
    act_code_parts = split_activity_code(activity_code)
116
    suffixes = list(chain(*imap(split_activity_code, suffixes)))
117 118 119
    return all(imap(equal, reversed(act_code_parts), reversed(suffixes)))


120 121
def join_activity_code(*args):
    """Join the specified parts into an activity code.
122 123

    :returns: Activity code string.
124 125 126 127
    """
    return activity_code_separator.join(args)


128 129 130 131 132 133 134 135
def split_activity_code(activity_code):
    """Split the specified activity code into its parts.

    :returns: A list of activity code parts.
    """
    return activity_code.split(activity_code_separator)


136 137 138 139 140 141 142 143 144 145
class Encoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Promise):
            obj = force_text(obj)
        try:
            return super(Encoder, self).default(obj)
        except TypeError:
            return unicode(obj)


146 147
class ActivityModel(TimeStampedModel):
    activity_code = CharField(max_length=100, verbose_name=_('activity code'))
148
    readable_name_data = JSONField(blank=True, null=True,
149
                                   dump_kwargs={"cls": Encoder},
150 151 152
                                   verbose_name=_('human readable name'),
                                   help_text=_('Human readable name of '
                                               'activity.'))
153
    parent = ForeignKey('self', blank=True, null=True, related_name='children')
154 155 156 157 158 159 160 161 162 163 164
    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.'))
165 166 167
    succeeded = NullBooleanField(blank=True, null=True,
                                 help_text=_('True, if the activity has '
                                             'finished successfully.'))
168
    result_data = JSONField(verbose_name=_('result'), blank=True, null=True,
169
                            dump_kwargs={"cls": Encoder},
170
                            help_text=_('Human readable result of activity.'))
171

172 173 174 175 176 177
    def __unicode__(self):
        if self.parent:
            return self.parent.activity_code + "->" + self.activity_code
        else:
            return self.activity_code

178 179 180
    class Meta:
        abstract = True

181
    def finish(self, succeeded, result=None, event_handler=None):
182 183
        if not self.finished:
            self.finished = timezone.now()
184
            self.succeeded = succeeded
185 186
            if result is not None:
                self.result = result
187 188
            if event_handler is not None:
                event_handler(self)
189
            self.save()
190

191 192 193 194 195 196 197 198
    @property
    def has_succeeded(self):
        return self.finished and self.succeeded

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

199
    @property
200 201 202 203
    def readable_name(self):
        return HumanReadableObject.from_dict(self.readable_name_data)

    @readable_name.setter
Dudás Ádám committed
204
    def readable_name(self, value):
205 206 207
        self.readable_name_data = None if value is None else value.to_dict()

    @property
208 209 210 211
    def result(self):
        return HumanReadableObject.from_dict(self.result_data)

    @result.setter
Dudás Ádám committed
212
    def result(self, value):
213 214
        if isinstance(value, basestring):
            warn("Using string as result value is deprecated. Use "
215 216
                 "HumanReadableObject instead.",
                 DeprecationWarning, stacklevel=2)
217 218
            value = create_readable(user_text_template="",
                                    admin_text_template=value)
219 220 221 222
        elif not hasattr(value, "to_dict"):
            warn("Use HumanReadableObject.", DeprecationWarning, stacklevel=2)
            value = create_readable(user_text_template="",
                                    admin_text_template=unicode(value))
223

224 225
        self.result_data = None if value is None else value.to_dict()

226 227 228 229 230 231 232 233
    @classmethod
    def construct_activity_code(cls, code_suffix, sub_suffix=None):
        code = join_activity_code(cls.ACTIVITY_CODE_BASE, code_suffix)
        if sub_suffix:
            return join_activity_code(code, sub_suffix)
        else:
            return code

234

235 236 237 238 239 240 241
@celery.task()
def compute_cached(method, instance, memcached_seconds,
                   key, start, *args, **kwargs):
    """Compute and store actual value of cached method."""
    if isinstance(method, basestring):
        model, id = instance
        instance = model.objects.get(id=id)
242
        try:
243
            method = getattr(model, method)
244 245 246 247 248
            while hasattr(method, '_original') or hasattr(method, 'fget'):
                try:
                    method = method._original
                except AttributeError:
                    method = method.fget
249
        except AttributeError:
250 251
            logger.exception("Couldnt get original method of %s",
                             unicode(method))
252 253
            raise

254 255 256 257 258 259 260 261 262 263 264 265 266
    #  call the actual method
    result = method(instance, *args, **kwargs)
    # save to memcache
    cache.set(key, result, memcached_seconds)
    elapsed = time() - start
    cache.set("%s.cached" % key, 2, max(memcached_seconds * 0.5,
                                        memcached_seconds * 0.75 - elapsed))
    logger.debug('Value of <%s>.%s(%s)=<%s> saved to cache (%s elapsed).',
                 unicode(instance), method.__name__, unicode(args),
                 unicode(result), elapsed)
    return result


267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
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):

288 289
        method_name = method.__name__

290 291
        def get_key(instance, *args, **kwargs):
            return sha224(unicode(method.__module__) +
292
                          method_name +
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                          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']
311
                    setattr(instance, key, {'time': now, 'value': result})
312 313 314 315 316

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

            if invalidate or (result is None):
317 318 319
                logger.debug("all caches failed, compute now")
                result = compute_cached(method, instance, memcached_seconds,
                                        key, time(), *args, **kwargs)
320
                setattr(instance, key, {'time': now, 'value': result})
321 322 323
            elif not cache.get("%s.cached" % key):
                logger.debug("caches expiring, compute async")
                cache.set("%s.cached" % key, 1, memcached_seconds * 0.5)
324 325 326 327 328 329 330
                try:
                    compute_cached.apply_async(
                        queue='localhost.man', kwargs=kwargs, args=[
                            method_name, (instance.__class__, instance.id),
                            memcached_seconds, key, time()] + list(args))
                except:
                    logger.exception("Couldnt compute async %s", method_name)
331 332

            return result
333 334 335

        update_wrapper(x, method)
        x._original = method
336 337 338
        return x

    return inner_cache
Őry Máté committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372


class HumanSortField(CharField):
    """
    A CharField that monitors another field on the same model and sets itself
    to a normalized value, which can be used for sensible lexicographycal
    sorting for fields containing numerals. (Avoiding technically correct
    orderings like [a1, a10, a2], which can be annoying for file or host
    names.)

    Apart from CharField's default arguments, an argument is requered:
        - monitor   sets the base field, whose value is normalized.
        - maximum_number_length    can also be provided, and defaults to 4. If
        you have to sort values containing numbers greater than 9999, you
        should increase it.

    Code is based on carljm's django-model-utils.
    """
    def __init__(self, *args, **kwargs):
        logger.debug('Initing HumanSortField(%s %s)',
                     unicode(args), unicode(kwargs))
        kwargs.setdefault('default', "")
        self.maximum_number_length = kwargs.pop('maximum_number_length', 4)
        monitor = kwargs.pop('monitor', None)
        if not monitor:
            raise TypeError(
                '%s requires a "monitor" argument' % self.__class__.__name__)
        self.monitor = monitor
        kwargs['blank'] = True
        super(HumanSortField, self).__init__(*args, **kwargs)

    def get_monitored_value(self, instance):
        return getattr(instance, self.monitor)

373 374 375 376 377 378
    def deconstruct(self):
        name, path, args, kwargs = super(HumanSortField, self).deconstruct()
        if self.monitor is not None:
            kwargs['monitor'] = self.monitor
        return name, path, args, kwargs

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    @staticmethod
    def _partition(s, pred):
        """Partition a deque of chars to a tuple of a
           - string of the longest prefix matching pred,
           - string of the longest prefix after the former one not matching,
           - deque of the remaining characters.

           >>> HumanSortField._partition(deque("1234abc567"),
           ...                           lambda s: s.isdigit())
           ('1234', 'abc', deque(['5', '6', '7']))
           >>> HumanSortField._partition(deque("12ab"), lambda s: s.isalpha())
           ('', '12', deque(['a', 'b']))
        """
        match, notmatch = deque(), deque()
        while s and pred(s[0]):
            match.append(s.popleft())
        while s and not pred(s[0]):
            notmatch.append(s.popleft())
        return (''.join(match), ''.join(notmatch), s)
Őry Máté committed
398

399
    def get_normalized_value(self, val):
Őry Máté committed
400 401 402 403
        logger.debug('Normalizing value: %s', val)
        norm = ""
        val = deque(val)
        while val:
404 405 406 407
            numbers, letters, val = self._partition(val,
                                                    lambda s: s[0].isdigit())
            if numbers:
                norm += numbers.rjust(self.maximum_number_length, '0')
Őry Máté committed
408 409 410 411 412 413 414 415 416 417 418 419
            norm += letters
        logger.debug('Normalized value: %s', norm)
        return norm

    def pre_save(self, model_instance, add):
        logger.debug('Pre-saving %s.%s. %s',
                     model_instance, self.attname, add)
        value = self.get_normalized_value(
            self.get_monitored_value(model_instance))
        setattr(model_instance, self.attname, value[:self.max_length])
        return super(HumanSortField, self).pre_save(model_instance, add)

420 421 422

class HumanReadableObject(object):
    def __init__(self, user_text_template, admin_text_template, params):
423 424 425
        self._set_values(user_text_template, admin_text_template, params)

    def _set_values(self, user_text_template, admin_text_template, params):
426 427 428 429
        if isinstance(user_text_template, Promise):
            user_text_template = user_text_template._proxy____args[0]
        if isinstance(admin_text_template, Promise):
            admin_text_template = admin_text_template._proxy____args[0]
430 431
        self.user_text_template = user_text_template
        self.admin_text_template = admin_text_template
432 433 434 435
        for k, v in params.iteritems():
            try:
                v = timezone.datetime.strptime(
                    v, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.UTC())
Őry Máté committed
436
            except (ValueError, TypeError):  # Mock raises TypeError
437 438 439
                pass
            if isinstance(v, timezone.datetime):
                params[k] = defaultfilters.date(v, "DATETIME_FORMAT")
440 441 442
        self.params = params

    @classmethod
443
    def create(cls, user_text_template, admin_text_template=None, **params):
444 445 446
        return cls(user_text_template=user_text_template,
                   admin_text_template=(admin_text_template
                                        or user_text_template), params=params)
447

448 449 450 451
    def set(self, user_text_template, admin_text_template=None, **params):
        self._set_values(user_text_template,
                         admin_text_template or user_text_template, params)

452 453 454 455
    @classmethod
    def from_dict(cls, d):
        return None if d is None else cls(**d)

456 457 458
    def _get_parsed_text(self, key):
        value = getattr(self, key)
        if value == "":
459
            return ""
460
        try:
461 462 463 464 465 466 467 468 469
            return _(value) % self.params
        except KeyError:
            logger.exception("Can't render %s '%s' %% %s",
                             key, value, unicode(self.params))
            raise

    def get_admin_text(self):
        try:
            return self._get_parsed_text("admin_text_template")
470 471
        except KeyError:
            return self.get_user_text()
472 473

    def get_user_text(self):
474
        try:
475
            return self._get_parsed_text("user_text_template")
476 477
        except KeyError:
            return self.user_text_template
478

479 480 481 482 483 484
    def get_text(self, user):
        if user and user.is_superuser:
            return self.get_admin_text()
        else:
            return self.get_user_text()

485 486 487 488 489
    def to_dict(self):
        return {"user_text_template": self.user_text_template,
                "admin_text_template": self.admin_text_template,
                "params": self.params}

490 491 492 493
    def __unicode__(self):
        return self.get_user_text()


494
create_readable = HumanReadableObject.create
495 496 497 498 499


class HumanReadableException(HumanReadableObject, Exception):
    """HumanReadableObject that is an Exception so can used in except clause.
    """
500

501 502 503 504 505 506 507 508 509 510
    def __init__(self, level=None, *args, **kwargs):
        super(HumanReadableException, self).__init__(*args, **kwargs)
        if level is not None:
            if hasattr(messages, level):
                self.level = level
            else:
                raise ValueError(
                    "Level should be the name of an attribute of django."
                    "contrib.messages (and it should be callable with "
                    "(request, message)). Like 'error', 'warning'.")
511
        elif not hasattr(self, "level"):
512 513 514
            self.level = "error"

    def send_message(self, request, level=None):
515
        msg = self.get_text(request.user)
516
        getattr(messages, level or self.level)(request, msg)
517 518


519
def fetch_human_exception(exception, user=None):
Őry Máté committed
520 521 522 523 524 525 526 527 528 529 530 531 532
    """Fetch user readable message from exception.

    >>> r = humanize_exception("foo", Exception())
    >>> fetch_human_exception(r, User())
    u'foo'
    >>> fetch_human_exception(r).get_text(User())
    u'foo'
    >>> fetch_human_exception(Exception(), User())
    u'Unknown error'
    >>> fetch_human_exception(PermissionDenied(), User())
    u'Permission Denied'
    """

533 534 535 536
    if not isinstance(exception, HumanReadableException):
        if isinstance(exception, PermissionDenied):
            exception = create_readable(ugettext_noop("Permission Denied"))
        else:
537 538 539
            exception = create_readable(ugettext_noop("Unknown error"),
                                        ugettext_noop("Unknown error: %(ex)s"),
                                        ex=unicode(exception))
540 541 542
    return exception.get_text(user) if user else exception


543
def humanize_exception(message, exception=None, level=None, **params):
544 545 546 547 548 549 550 551 552 553 554 555
    """Return new dynamic-class exception which is based on
    HumanReadableException and the original class with the dict of exception.

    >>> try: raise humanize_exception("Welcome!", TypeError("hello"))
    ... except HumanReadableException as e: print e.get_admin_text()
    ...
    Welcome!
    """

    Ex = type("HumanReadable" + type(exception).__name__,
              (HumanReadableException, type(exception)),
              exception.__dict__)
556 557 558 559
    ex = Ex.create(message, **params)
    if level:
        ex.level = level
    return ex