models.py 15.4 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/>.

18 19
from __future__ import absolute_import

20
from itertools import chain
21
from hashlib import md5
22 23
from logging import getLogger

24
from django.conf import settings
25
from django.contrib.auth.models import User, Group
26
from django.contrib.auth.signals import user_logged_in
27
from django.core.urlresolvers import reverse
28
from django.db.models import (
29
    Model, ForeignKey, OneToOneField, CharField, IntegerField, TextField,
30
    DateTimeField, BooleanField
31
)
32
from django.db.models.signals import post_save, pre_delete, post_delete
33
from django.templatetags.static import static
34
from django.utils.html import escape
35
from django.utils.translation import ugettext_lazy as _
36
from django_sshkey.models import UserKey
Guba Sándor committed
37
from django.core.exceptions import ObjectDoesNotExist
38

39 40
from sizefield.models import FileSizeField

41
from jsonfield import JSONField
42
from model_utils.models import TimeFramedModel, TimeStampedModel
43 44
from model_utils.fields import StatusField
from model_utils import Choices
45

46
from acl.models import AclBase
47
from common.models import HumanReadableObject, create_readable, Encoder
48

49
from vm.tasks.agent_tasks import add_keys, del_keys
50
from vm.models.instance import ACCESS_METHODS
51

52
from .store_api import Store, NoStoreException, NotOkException, Timeout
53
from .validators import connect_command_template_validator
54

55 56
logger = getLogger(__name__)

Bach Dániel committed
57 58 59

def pwgen():
    return User.objects.make_random_password()
60

61

62
class Message(TimeStampedModel, TimeFramedModel):
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    message = CharField(max_length=500, verbose_name=_('message'))
    effect = CharField(
        default='info', max_length=10, verbose_name=_('effect'),
        choices=(('success', _('success')), ('info', _('info')),
                 ('warning', _('warning')), ('danger', _('danger'))))
    enabled = BooleanField(default=False, verbose_name=_('enabled'))

    class Meta:
        ordering = ["id"]
        verbose_name = _('message')
        verbose_name_plural = _('messages')

    def __unicode__(self):
        return self.message

    def get_absolute_url(self):
79 80
        return reverse('dashboard.views.message-detail',
                       kwargs={'pk': self.pk})
81 82


83
class Favourite(Model):
84
    instance = ForeignKey("vm.Instance")
85
    user = ForeignKey(User)
86 87


88 89 90 91 92 93 94
class Notification(TimeStampedModel):
    STATUS = Choices(('new', _('new')),
                     ('delivered', _('delivered')),
                     ('read', _('read')))

    status = StatusField()
    to = ForeignKey(User)
95 96
    subject_data = JSONField(null=True, dump_kwargs={"cls": Encoder})
    message_data = JSONField(null=True, dump_kwargs={"cls": Encoder})
97
    valid_until = DateTimeField(null=True, default=None)
98 99 100 101 102

    class Meta:
        ordering = ['-created']

    @classmethod
103 104 105
    def send(cls, user, subject, template, context,
             valid_until=None, subject_context=None):
        hro = create_readable(template, user=user, **context)
106
        subject = create_readable(subject, **(subject_context or context))
107 108 109
        return cls.objects.create(to=user,
                                  subject_data=subject.to_dict(),
                                  message_data=hro.to_dict(),
110
                                  valid_until=valid_until)
111

112 113
    @property
    def subject(self):
114 115
        return HumanReadableObject.from_dict(
            self.escape_dict(self.subject_data))
116 117 118 119 120 121 122

    @subject.setter
    def subject(self, value):
        self.subject_data = None if value is None else value.to_dict()

    @property
    def message(self):
123 124 125 126 127 128 129 130
        return HumanReadableObject.from_dict(
            self.escape_dict(self.message_data))

    def escape_dict(self, data):
        for k, v in data['params'].items():
            if isinstance(v, basestring):
                data['params'][k] = escape(v)
        return data
131 132 133 134 135

    @message.setter
    def message(self, value):
        self.message_data = None if value is None else value.to_dict()

136

137 138 139 140
class ConnectCommand(Model):
    user = ForeignKey(User, related_name='command_set')
    access_method = CharField(max_length=10, choices=ACCESS_METHODS,
                              verbose_name=_('access method'),
141
                              help_text=_('Type of the remote access method.'))
142 143
    name = CharField(max_length="128", verbose_name=_('name'), blank=False,
                     help_text=_("Name of your custom command."))
144
    template = CharField(blank=True, null=True, max_length=256,
145 146 147 148
                         verbose_name=_('command template'),
                         help_text=_('Template for connection command string. '
                                     'Available parameters are: '
                                     'username, password, '
149 150
                                     'host, port.'),
                         validators=[connect_command_template_validator])
151

152 153 154
    class Meta:
        ordering = ('id', )

155 156
    def __unicode__(self):
        return self.template
157 158


159 160 161 162 163 164 165 166 167
class Profile(Model):
    user = OneToOneField(User)
    preferred_language = CharField(verbose_name=_('preferred language'),
                                   choices=settings.LANGUAGES,
                                   max_length=32,
                                   default=settings.LANGUAGE_CODE, blank=False)
    org_id = CharField(  # may be populated from eduPersonOrgId field
        unique=True, blank=True, null=True, max_length=64,
        help_text=_('Unique identifier of the person, e.g. a student number.'))
168
    instance_limit = IntegerField(default=5)
169
    use_gravatar = BooleanField(
170
        verbose_name=_("Use Gravatar"), default=True,
171
        help_text=_("Whether to use email address as Gravatar profile image"))
172 173
    email_notifications = BooleanField(
        verbose_name=_("Email notifications"), default=True,
174
        help_text=_('Whether user wants to get digested email notifications.'))
175 176 177 178 179
    smb_password = CharField(
        max_length=20,
        verbose_name=_('Samba password'),
        help_text=_(
            'Generated password for accessing store from '
Kálmán Viktor committed
180
            'virtual machines.'),
181 182
        default=pwgen,
    )
183
    disk_quota = FileSizeField(
184
        verbose_name=_('disk quota'),
185
        default=2048 * 1024 * 1024,
186
        help_text=_('Disk quota in mebibytes.'))
187

188
    def get_connect_commands(self, instance, use_ipv6=False):
189
        """ Generate connection command based on template."""
190 191 192
        single_command = instance.get_connect_command(use_ipv6)
        if single_command:  # can we even connect to that VM
            commands = self.user.command_set.filter(
193
                access_method=instance.access_method)
194 195 196 197 198 199 200 201 202 203
            if commands.count() < 1:
                return [single_command]
            else:
                return [
                    command.template % {
                        'port': instance.get_connect_port(use_ipv6=use_ipv6),
                        'host':  instance.get_connect_host(use_ipv6=use_ipv6),
                        'password': instance.pw,
                        'username': 'cloud',
                    } for command in commands]
204
        else:
205
            return []
206

207 208 209 210 211
    def notify(self, subject, template, context=None, valid_until=None,
               **kwargs):
        if context is not None:
            kwargs.update(context)
        return Notification.send(self.user, subject, template, kwargs,
212
                                 valid_until)
213

214
    def get_absolute_url(self):
Kálmán Viktor committed
215 216
        return reverse("dashboard.views.profile",
                       kwargs={'username': self.user.username})
217

218 219 220 221 222 223 224 225
    def get_avatar_url(self):
        if self.use_gravatar:
            gravatar_hash = md5(self.user.email).hexdigest()
            return ("https://secure.gravatar.com/avatar/%s"
                    "?s=200" % gravatar_hash)
        else:
            return static("dashboard/img/avatar.png")

226 227 228 229 230 231 232 233 234 235 236 237 238
    def get_display_name(self):
        if self.user.get_full_name():
            name = self.user.get_full_name()
        else:
            name = self.user.username

        if self.org_id:
            name = "%s (%s)" % (name, self.org_id)
        return name

    def __unicode__(self):
        return self.get_display_name()

239 240 241 242 243
    def save(self, *args, **kwargs):
        if self.org_id == "":
            self.org_id = None
        super(Profile, self).save(*args, **kwargs)

244
    class Meta:
245
        ordering = ('id', )
246 247 248 249
        permissions = (
            ('use_autocomplete', _('Can use autocomplete.')),
        )

Őry Máté committed
250

251 252 253 254 255 256
class FutureMember(Model):
    org_id = CharField(max_length=64, help_text=_(
        'Unique identifier of the person, e.g. a student number.'))
    group = ForeignKey(Group)

    class Meta:
257
        ordering = ('id', )
258 259 260 261 262
        unique_together = ('org_id', 'group')

    def __unicode__(self):
        return u"%s (%s)" % (self.org_id, self.group)

Őry Máté committed
263

264 265 266 267 268 269 270 271 272 273
class GroupProfile(AclBase):
    ACL_LEVELS = (
        ('operator', _('operator')),
        ('owner', _('owner')),
    )

    group = OneToOneField(Group)
    org_id = CharField(
        unique=True, blank=True, null=True, max_length=64,
        help_text=_('Unique identifier of the group at the organization.'))
274 275
    description = TextField(blank=True)

276 277 278
    class Meta:
        ordering = ('id', )

279 280 281
    def __unicode__(self):
        return self.group.name

282 283 284 285
    def save(self, *args, **kwargs):
        if not self.org_id:
            self.org_id = None
        super(GroupProfile, self).save(*args, **kwargs)
286 287 288 289 290 291 292 293

    @classmethod
    def search(cls, name):
        try:
            return cls.objects.get(org_id=name).group
        except cls.DoesNotExist:
            return Group.objects.get(name=name)

294
    def get_absolute_url(self):
295 296
        return reverse('dashboard.views.group-detail',
                       kwargs={'pk': self.group.pk})
297

298 299

def get_or_create_profile(self):
300
    obj, created = GroupProfile.objects.get_or_create(group_id=self.pk)
301 302 303 304 305
    return obj

Group.profile = property(get_or_create_profile)


306
def create_profile(user):
307 308
    if not user.pk:
        return False
309
    profile, created = Profile.objects.get_or_create(user=user)
310

Őry Máté committed
311 312 313 314
    try:
        Store(user).create_user(profile.smb_password, None, profile.disk_quota)
    except:
        logger.exception("Can't create user %s", unicode(user))
315 316
    return created

317 318 319 320 321

def create_profile_hook(sender, user, request, **kwargs):
    return create_profile(user)

user_logged_in.connect(create_profile_hook)
322

323
if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'):
324
    logger.debug("Register save_org_id to djangosaml2 pre_user_save")
325 326
    from djangosaml2.signals import pre_user_save

327
    def save_org_id(sender, **kwargs):
328
        logger.debug("save_org_id called by %s", sender.username)
329
        attributes = kwargs.pop('attributes')
330
        atr = settings.SAML_ORG_ID_ATTRIBUTE
331
        try:
332
            value = attributes[atr][0].upper()
333 334 335 336
        except Exception as e:
            value = None
            logger.info("save_org_id couldn't find attribute. %s", unicode(e))

337 338 339 340
        if sender.pk is None:
            sender.save()
            logger.debug("save_org_id saved user %s", unicode(sender))

341 342
        profile, created = Profile.objects.get_or_create(user=sender)
        if created or profile.org_id != value:
343 344
            logger.info("org_id of %s added to user %s's profile",
                        value, sender.username)
345 346
            profile.org_id = value
            profile.save()
347 348 349
        else:
            logger.debug("org_id of %s already added to user %s's profile",
                         value, sender.username)
350
        memberatrs = getattr(settings, 'SAML_GROUP_ATTRIBUTES', [])
351 352
        for group in chain(*[attributes[i]
                             for i in memberatrs if i in attributes]):
353 354 355 356 357 358 359 360 361
            try:
                g = GroupProfile.search(group)
            except Group.DoesNotExist:
                logger.debug('cant find membergroup %s', group)
            else:
                logger.debug('could find membergroup %s (%s)',
                             group, unicode(g))
                g.user_set.add(sender)

362
        for i in FutureMember.objects.filter(org_id__iexact=value):
363 364 365
            i.group.user_set.add(sender)
            i.delete()

366
        owneratrs = getattr(settings, 'SAML_GROUP_OWNER_ATTRIBUTES', [])
367 368
        for group in chain(*[attributes[i]
                             for i in owneratrs if i in attributes]):
369 370 371 372 373 374 375 376 377 378
            try:
                g = GroupProfile.search(group)
            except Group.DoesNotExist:
                logger.debug('cant find ownergroup %s', group)
            else:
                logger.debug('could find ownergroup %s (%s)',
                             group, unicode(g))
                g.profile.set_level(sender, 'owner')

        return False  # User did not change
379

380 381
    pre_user_save.connect(save_org_id)

382 383
else:
    logger.debug("Do not register save_org_id to djangosaml2 pre_user_save")
384 385


386 387 388
def update_store_profile(sender, **kwargs):
    profile = kwargs.get('instance')
    keys = [i.key for i in profile.user.userkey_set.all()]
Guba Sándor committed
389 390 391 392 393 394
    try:
        s = Store(profile.user)
        s.create_user(profile.smb_password, keys,
                      profile.disk_quota)
    except NoStoreException:
        logger.debug("Store is not available.")
395
    except (NotOkException, Timeout):
396
        logger.critical("Store is not accepting connections.")
Guba Sándor committed
397

398 399 400 401 402 403

post_save.connect(update_store_profile, sender=Profile)


def update_store_keys(sender, **kwargs):
    userkey = kwargs.get('instance')
Guba Sándor committed
404
    try:
Guba Sándor committed
405 406 407 408 409 410 411 412 413 414 415
        profile = userkey.user.profile
    except ObjectDoesNotExist:
        pass  # If there is no profile the user is deleted
    else:
        keys = [i.key for i in profile.user.userkey_set.all()]
        try:
            s = Store(userkey.user)
            s.create_user(profile.smb_password, keys,
                          profile.disk_quota)
        except NoStoreException:
            logger.debug("Store is not available.")
416 417
        except NotOkException:
            logger.critical("Store is not accepting connections.")
418 419 420 421 422 423


post_save.connect(update_store_keys, sender=UserKey)
post_delete.connect(update_store_keys, sender=UserKey)


424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
def add_ssh_keys(sender, **kwargs):
    from vm.models import Instance

    userkey = kwargs.get('instance')
    instances = Instance.get_objects_with_level(
        'user', userkey.user).filter(status='RUNNING')
    for i in instances:
        logger.info('called add_keys(%s, %s)', i, userkey)
        queue = i.get_remote_queue_name("agent")
        add_keys.apply_async(args=(i.vm_name, [userkey.key]),
                             queue=queue)


def del_ssh_keys(sender, **kwargs):
    from vm.models import Instance

    userkey = kwargs.get('instance')
    instances = Instance.get_objects_with_level(
        'user', userkey.user).filter(status='RUNNING')
    for i in instances:
        logger.info('called del_keys(%s, %s)', i, userkey)
        queue = i.get_remote_queue_name("agent")
        del_keys.apply_async(args=(i.vm_name, [userkey.key]),
                             queue=queue)


post_save.connect(add_ssh_keys, sender=UserKey)
pre_delete.connect(del_ssh_keys, sender=UserKey)