models.py 10.8 KB
Newer Older
Kálmán Viktor committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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/>.
17 18 19
import json
import logging

Kálmán Viktor committed
20 21 22
from django.db.models import (
    Model, CharField, IntegerField, TextField, ForeignKey, ManyToManyField,
)
23
from django.db.models.signals import post_save
24
from django.conf import settings
Kálmán Viktor committed
25 26
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
Kálmán Viktor committed
27 28
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
29 30 31
from django.utils.translation import (
    ugettext_lazy as _, ugettext_noop, ungettext
)
Kálmán Viktor committed
32 33
from django.core.urlresolvers import reverse

34
import requests
35
from sizefield.models import FileSizeField
Kálmán Viktor committed
36 37
from model_utils.models import TimeStampedModel
from model_utils import Choices
38
from sizefield.utils import filesizeformat
Kálmán Viktor committed
39 40

from vm.models import Instance, InstanceTemplate, Lease
41
from vm.operations import ResourcesOperation, ResizeDiskOperation
42
from storage.models import Disk
Kálmán Viktor committed
43

44 45
logger = logging.getLogger(__name__)

Kálmán Viktor committed
46 47 48 49 50 51

class RequestAction(Model):

    def accept(self):
        raise NotImplementedError

52 53 54 55
    @property
    def accept_msg(self):
        raise NotImplementedError

56 57 58
    def is_acceptable(self):
        return True

Kálmán Viktor committed
59 60 61
    class Meta:
        abstract = True

Kálmán Viktor committed
62 63

class RequestType(Model):
64
    name = CharField(max_length=100, verbose_name=_("Name"))
Kálmán Viktor committed
65 66 67 68

    def __unicode__(self):
        return self.name

Kálmán Viktor committed
69 70 71
    class Meta:
        abstract = True

Kálmán Viktor committed
72 73 74 75 76 77 78

class Request(TimeStampedModel):
    STATUSES = Choices(
        ('PENDING', _('pending')),
        ('ACCEPTED', _('accepted')),
        ('DECLINED', _('declined')),
    )
79
    status = CharField(choices=STATUSES, default=STATUSES.PENDING,
Kálmán Viktor committed
80
                       max_length=10)
81 82
    user = ForeignKey(User, related_name="user")
    closed_by = ForeignKey(User, related_name="closed_by", null=True)
Kálmán Viktor committed
83 84 85
    TYPES = Choices(
        ('resource', _('resource request')),
        ('lease', _("lease request")),
86
        ('template', _("template access request")),
87
        ('resize', _("disk resize request")),
Kálmán Viktor committed
88 89
    )
    type = CharField(choices=TYPES, max_length=10)
90
    message = TextField(verbose_name=_("Message"))
91
    reason = TextField(verbose_name=_("Reason"))
Kálmán Viktor committed
92 93 94 95 96

    content_type = ForeignKey(ContentType)
    object_id = IntegerField()
    action = GenericForeignKey("content_type", "object_id")

97 98 99
    def get_absolute_url(self):
        return reverse("request.views.request-detail", kwargs={'pk': self.pk})

Kálmán Viktor committed
100 101 102
    def get_readable_status(self):
        return self.STATUSES[self.status]

103 104 105
    def get_readable_type(self):
        return self.TYPES[self.type]

106
    def get_request_icon(self):
Kálmán Viktor committed
107 108 109
        return {
            'resource': "tasks",
            'lease': "clock-o",
110 111
            'template': "puzzle-piece",
            'resize': "arrows-alt",
Kálmán Viktor committed
112 113 114 115 116 117 118 119
        }.get(self.type)

    def get_effect(self):
        return {
            "PENDING": "warning",
            "ACCEPTED": "success",
            "DECLINED": "danger",
        }.get(self.status)
Kálmán Viktor committed
120

121 122 123 124 125 126 127
    def get_status_icon(self):
        return {
            "PENDING": "exclamation-triangle",
            "ACCEPTED": "check",
            "DECLINED": "times",
        }.get(self.status)

128 129
    def accept(self, user):
        self.action.accept(user)
130
        self.status = "ACCEPTED"
131
        self.closed_by = user
132 133
        self.save()

134 135 136 137 138
        self.user.profile.notify(
            ugettext_noop("Request accepted"),
            self.action.accept_msg
        )

139
    def decline(self, user, reason):
140
        self.status = "DECLINED"
141
        self.closed_by = user
142
        self.reason = reason
143 144
        self.save()

145 146 147 148 149 150 151 152 153 154
        decline_msg = ugettext_noop(
            'Your <a href="%(url)s">request</a> was declined because of the '
            'following reason: %(reason)s'
        )

        self.user.profile.notify(
            ugettext_noop("Request declined"),
            decline_msg, url=self.get_absolute_url(), reason=self.reason,
        )

155 156 157 158
    @property
    def is_acceptable(self):
        return self.action.is_acceptable()

Kálmán Viktor committed
159 160

class LeaseType(RequestType):
161
    lease = ForeignKey(Lease, verbose_name=_("Lease"))
Kálmán Viktor committed
162

163 164 165 166 167 168
    def __unicode__(self):
        return _("%(name)s (suspend: %(s)s, remove: %(r)s)") % {
            'name': self.name,
            's': self.lease.get_readable_suspend_time(),
            'r': self.lease.get_readable_delete_time()}

Kálmán Viktor committed
169 170 171 172 173 174
    def get_absolute_url(self):
        return reverse("request.views.lease-type-detail",
                       kwargs={'pk': self.pk})


class TemplateAccessType(RequestType):
175
    templates = ManyToManyField(InstanceTemplate, verbose_name=_("Templates"))
Kálmán Viktor committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

    def get_absolute_url(self):
        return reverse("request.views.template-type-detail",
                       kwargs={'pk': self.pk})


class ResourceChangeAction(RequestAction):
    instance = ForeignKey(Instance)
    num_cores = IntegerField(verbose_name=_('number of cores'),
                             help_text=_('Number of virtual CPU cores '
                                         'available to the virtual machine.'),
                             validators=[MinValueValidator(0)])
    ram_size = IntegerField(verbose_name=_('RAM size'),
                            help_text=_('Mebibytes of memory.'),
                            validators=[MinValueValidator(0)])
    priority = IntegerField(verbose_name=_('priority'),
                            help_text=_('CPU priority.'),
                            validators=[MinValueValidator(0)])

195
    def accept(self, user):
196 197 198 199 200
        self.instance.resources_change.async(
            user=user, num_cores=self.num_cores, ram_size=self.ram_size,
            max_ram_size=self.ram_size, priority=self.priority,
            with_shutdown=True)

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    @property
    def accept_msg(self):
        return _(
            'The resources of <a href="%(url)s">%(name)s</a> were changed. '
            'Number of cores: %(num_cores)d, RAM size: '
            '<span class="nowrap">%(ram_size)d MiB</span>, '
            'CPU priority: %(priority)d/100.'
        ) % {
            'url': self.instance.get_absolute_url(),
            'name': self.instance.name,
            'num_cores': self.num_cores,
            'ram_size': self.ram_size,
            'priority': self.priority,
        }

216 217 218
    def is_acceptable(self):
        return self.instance.status in ResourcesOperation.accept_states

Kálmán Viktor committed
219 220 221 222 223

class ExtendLeaseAction(RequestAction):
    instance = ForeignKey(Instance)
    lease_type = ForeignKey(LeaseType)

224 225 226
    def accept(self, user):
        self.instance.renew(lease=self.lease_type.lease, save=True, force=True,
                            user=user)
Kálmán Viktor committed
227

228 229 230 231 232 233 234 235 236 237
    @property
    def accept_msg(self):
        return _(
            'The lease of <a href="%(url)s">%(name)s</a> got extended. '
            '(suspend: %(suspend)s, remove: %(remove)s)'
        ) % {'name': self.instance.name,
             'url': self.instance.get_absolute_url(),
             'suspend': self.lease_type.lease.get_readable_suspend_time(),
             'remove': self.lease_type.lease.get_readable_delete_time(), }

Kálmán Viktor committed
238 239 240 241 242 243 244 245 246 247 248

class TemplateAccessAction(RequestAction):
    template_type = ForeignKey(TemplateAccessType)
    LEVELS = Choices(
        ('user', _('user')),
        ('operator', _('operator')),
    )
    level = CharField(choices=LEVELS, default=LEVELS.user,
                      max_length=10)
    user = ForeignKey(User)

Kálmán Viktor committed
249 250 251
    def get_readable_level(self):
        return self.LEVELS[self.level]

252 253 254
    def accept(self, user):
        for t in self.template_type.templates.all():
            t.set_user_level(self.user, self.level)
255

256 257 258 259 260 261 262 263
    @property
    def accept_msg(self):
        return ungettext(
            "You got access to the following template: %s",
            "You got access to the following templates: %s",
            self.template_type.templates.count()
        ) % ", ".join([x.name for x in self.template_type.templates.all()])

264

265 266 267 268 269 270
class DiskResizeAction(RequestAction):
    instance = ForeignKey(Instance)
    disk = ForeignKey(Disk)
    size = FileSizeField(null=True, default=None)

    def accept(self, user):
271
        self.instance.resize_disk(disk=self.disk, size=self.size, user=user)
272 273 274

    @property
    def accept_msg(self):
275 276 277 278 279 280 281 282 283 284 285 286
        return _(
            'The disk <em class="text-muted">%(disk_name)s (#%(id)d)</em> of '
            '<a href="%(url)s">%(vm_name)s</a> got resized. '
            'The new size is: %(bytes)d bytes (%(size)s).'
        ) % {'disk_name': self.disk.name, 'id': self.disk.id,
             'url': self.instance.get_absolute_url(),
             'vm_name': self.instance.name,
             'bytes': self.size, 'size': filesizeformat(self.size),
             }

    def is_acceptable(self):
        return self.instance.status in ResizeDiskOperation.accept_states
287 288


289
def send_notifications(sender, instance, created, **kwargs):
290 291 292 293 294 295 296 297 298 299
    if not created:
        return

    notification_msg = ugettext_noop(
        'A new <a href="%(request_url)s">%(request_type)s</a> was submitted '
        'by <a href="%(user_url)s">%(display_name)s</a>.')
    context = {
        'display_name': instance.user.profile.get_display_name(),
        'user_url': instance.user.profile.get_absolute_url(),
        'request_url': instance.get_absolute_url(),
300
        'request_type': u"%s" % instance.get_readable_type()
301 302 303 304 305 306 307
    }

    for u in User.objects.filter(is_superuser=True):
        u.profile.notify(
            ugettext_noop("New %(request_type)s"), notification_msg, context
        )

308 309 310 311 312
    instance.user.profile.notify(
        ugettext_noop("Request submitted"),
        ugettext_noop('You can view the request\'s status at this '
                      '<a href="%(request_url)s">link</a>.'), context
    )
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    if settings.REQUEST_HOOK_URL:
        context.update({
            'object_kind': "request",
            'site_url': settings.DJANGO_URL,
        })
        try:
            r = requests.post(settings.REQUEST_HOOK_URL, timeout=3,
                              data=json.dumps(context, indent=2))
            r.raise_for_status()
        except requests.RequestException as e:
            logger.warning("Error in HTTP POST: %s. url: %s params: %s",
                           str(e), settings.REQUEST_HOOK_URL, context)
        else:
            logger.info("Successful HTTP POST. url: %s params: %s",
                        settings.REQUEST_HOOK_URL, context)


post_save.connect(send_notifications, sender=Request)