models.py 21.6 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
# django senders need their arguments
# pylint: disable=unused-argument

import json
import logging
6
import pika
Lukas Burgey's avatar
Lukas Burgey committed
7
from pika.exceptions import ConnectionClosed
Lukas Burgey's avatar
Lukas Burgey committed
8
from requests.auth import HTTPBasicAuth
Lukas Burgey's avatar
Lukas Burgey committed
9
from django.contrib.auth.models import AbstractUser, Group
10
from django.core.cache import cache
Lukas Burgey's avatar
Lukas Burgey committed
11
from django.db import models
Lukas Burgey's avatar
Lukas Burgey committed
12
from django.db.models.signals import post_save
Lukas Burgey's avatar
Lukas Burgey committed
13
from django.dispatch import receiver
14
from django_mysql.models import JSONField
Lukas Burgey's avatar
Lukas Burgey committed
15
from .auth.v1.models import OIDCConfig
Lukas Burgey's avatar
Lukas Burgey committed
16

Lukas Burgey's avatar
Lukas Burgey committed
17
LOGGER = logging.getLogger(__name__)
18
19

RABBITMQ_CONNECTION = None
20

Lukas Burgey's avatar
Lukas Burgey committed
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# singleton for simple configs
# https://steelkiwi.com/blog/practical-application-singleton-design-pattern/
class SingletonModel(models.Model):
    class Meta:
        abstract = True

    def set_cache(self):
        cache.set(self.__class__.__name__, self)

    # pylint: disable=invalid-name, arguments-differ
    def save(self, *args, **kwargs):
        self.pk = 1
        super(SingletonModel, self).save(*args, **kwargs)
        self.set_cache()

    @classmethod
    def load(cls):
        if cache.get(cls.__name__) is None:
            obj, created = cls.objects.get_or_create(pk=1)
            if not created:
                obj.set_cache()
        return cache.get(cls.__name__)


Lukas Burgey's avatar
Lukas Burgey committed
46
47
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
48
class RabbitMQInstance(SingletonModel):
Lukas Burgey's avatar
Lukas Burgey committed
49
    host = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
50
51
52
        max_length=150,
        default='localhost',
    )
Lukas Burgey's avatar
Lukas Burgey committed
53
54
55
56
    vhost = models.CharField(
        max_length=150,
        default='%2f',
    )
Lukas Burgey's avatar
Lukas Burgey committed
57
    exchange = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
58
59
60
        max_length=150,
        default='deployments',
    )
Lukas Burgey's avatar
Lukas Burgey committed
61
    port = models.IntegerField(
Lukas Burgey's avatar
Lukas Burgey committed
62
        default=15672,
Lukas Burgey's avatar
Lukas Burgey committed
63
    )
Lukas Burgey's avatar
Lukas Burgey committed
64
    username = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
65
66
67
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
68
    password = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
69
70
71
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
72
73
74
75

    def __str__(self):
        return self.host

Lukas Burgey's avatar
Lukas Burgey committed
76
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
77
        return '[RabbitMQ:{}] {}'.format(self.host, msg)
Lukas Burgey's avatar
Lukas Burgey committed
78
79
80
81

    @property
    def auth(self):
        return HTTPBasicAuth(
Lukas Burgey's avatar
Lukas Burgey committed
82
            self.username,
Lukas Burgey's avatar
Lukas Burgey committed
83
            self.password,
Lukas Burgey's avatar
Lukas Burgey committed
84
        )
Lukas Burgey's avatar
Lukas Burgey committed
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
    def _init_exchanges(self, channel):
        channel.exchange_declare(
            exchange=self.exchange,
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        # TODO put in config
        channel.exchange_declare(
            exchange='update',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )

    def _init_connection(self):
        global RABBITMQ_CONNECTION
        LOGGER.info('Opening new BlockingConnection')
        RABBITMQ_CONNECTION = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=self.host,
                ssl=True,
                heartbeat_interval=60,
            )
        )
        return RABBITMQ_CONNECTION

    @property
    def _connection(self):
        global RABBITMQ_CONNECTION
        if RABBITMQ_CONNECTION is not None:
            if RABBITMQ_CONNECTION.is_open:
                return RABBITMQ_CONNECTION
            elif RABBITMQ_CONNECTION.is_closing:
                RABBITMQ_CONNECTION.close()

        connection = self._init_connection()
        channel = connection.channel()
        self._init_exchanges(connection.channel())
        channel.close()
        RABBITMQ_CONNECTION = connection
        return connection

Lukas Burgey's avatar
Lukas Burgey committed
129
    @property
130
    def _channel(self):
Lukas Burgey's avatar
Lukas Burgey committed
131
132
133
134
135
136
137
138
        try:
            channel = self._connection.channel()
            channel.confirm_delivery()
            return channel
        except ConnectionClosed as exception:
            LOGGER.error(self.msg('ConnectionClosed: ' + str(exception)))
            self._init_connection()
            return self._channel
139
140
141
142
143
144
145
146
147
148

    def _publish(self, exchange, routing_key, body):
        channel = self._channel
        self._channel.basic_publish(
            exchange=exchange,
            routing_key=routing_key,
            body=body,
            properties=pika.BasicProperties(
                delivery_mode=1,
            ),
Lukas Burgey's avatar
Lukas Burgey committed
149
        )
150
        channel.close()
151

Lukas Burgey's avatar
Lukas Burgey committed
152

153
    # PUBLIC API
154
    def publish_by_service(self, service, msg):
155
156
157
158
159
        self._publish(
            self.exchange,
            service.routing_key,
            msg,
        )
Lukas Burgey's avatar
Lukas Burgey committed
160

161
    def publish_to_webpage(self, user, msg):
162
163
164
165
        LOGGER.debug('Signalling webpage of user %s', user)
        self._publish(
            'update',
            str(user.id),
166
            json.dumps(msg),
167
        )
168

Lukas Burgey's avatar
Lukas Burgey committed
169

170
171
172
173
def user_info_default():
    return {}


Lukas Burgey's avatar
Lukas Burgey committed
174
class User(AbstractUser):
175
    TYPE_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
176
177
178
179
        ('apiclient', 'API-Client'),
        ('oidcuser', 'OIDC User'),
        ('admin', 'Admin'),
    )
180
    user_type = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
181
182
        max_length=20,
        choices=TYPE_CHOICES,
Lukas Burgey's avatar
Lukas Burgey committed
183
        default='apiclient',
Lukas Burgey's avatar
Lukas Burgey committed
184
    )
185
186
187
188
    sub = models.CharField(
        max_length=150,
        blank=True,
        null=True,
189
        editable=False,
190
191
192
193
194
195
196
197
198
199
200
201
    )
    password = models.CharField(
        max_length=150,
        blank=True,
        null=True,
    )
    # the real state of the user
    # (self.is_active is the supposed state of the user)
    _is_active = models.BooleanField(
        default=True,
        editable=False,
    )
Lukas Burgey's avatar
Lukas Burgey committed
202
203
204
205
206
    # the idp which authenticated the user
    idp = models.ForeignKey(
        OIDCConfig,
        related_name='users',
        on_delete=models.CASCADE,
207
208
209
        blank=True,
        null=True,
        editable=False,
Lukas Burgey's avatar
Lukas Burgey committed
210
    )
211
212
213
214
    userinfo = JSONField(
        default=user_info_default,
        null=True,
        blank=True,
215
        editable=False,
216
    )
Lukas Burgey's avatar
Lukas Burgey committed
217

Lukas Burgey's avatar
Lukas Burgey committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    # returns the user as identified by userinfo and idp
    # if the user does not exists
    @classmethod
    def get_user(cls, userinfo, idp):
        if not 'sub' in userinfo:
            raise Exception('get_user needs a userinfo which contains the users subject')

        query_result = cls.objects.filter(
            sub=userinfo['sub'],
            idp=idp,
        )
        if not query_result.exists():
            return cls.construct_from_userinfo(userinfo, idp)

        if len(query_result) > 1:
            return Exception('Two user instances with same subject from the same idp')

        # TODO update the users userinfo when it changes
        # TODO update the users groupinfo when it changes
        return query_result.first()

    @classmethod
    def construct_from_userinfo(cls, userinfo, idp):
        LOGGER.debug('User: constructing from %s', userinfo)

        if 'sub' not in userinfo:
            raise Exception('Missing attribute in userinfo: sub')
        sub = userinfo['sub']

        if 'email' not in userinfo:
            if 'name' not in userinfo:
                raise Exception('Missing attributes in userinfo: email and name')

            username = userinfo['name']
        else:
            username = userinfo['email']

        user = cls(
            user_type='oidcuser',
            username=username,
            sub=sub,
            idp=idp,
            userinfo=userinfo,
        )
        user.save()
Lukas Burgey's avatar
Lukas Burgey committed
263
264
265
266
267
268

        for group in idp.get_user_groupinformation(
                userinfo,
        ).all():
            group.users.add(user)

Lukas Burgey's avatar
Lukas Burgey committed
269
270
271
272
273
274
275
276
277
278
279
280
        return user

    @classmethod
    def construct_client(cls, username, password):
        LOGGER.debug('APICLIENT: new client %s', username)
        client = cls(
            username=username,
            user_type='apiclient',
        )
        client.set_password(password)
        return client

Lukas Burgey's avatar
Lukas Burgey committed
281
    # we hide deleted keys here
282
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
283
284
285
286
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

287
288
289
290
    @property
    def is_active_at_clients(self):
        return self._is_active

291
292
293
    def __str__(self):
        if self.user_type == 'admin':
            return 'ADMIN {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
294
        elif self.user_type == 'oidcuser':
295
296
297
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
298
        elif self.user_type == 'apiclient':
299
300
301
302
303
            try:
                return 'APICLIENT {}@{}'.format(self.username, self.site)
            except:
                return 'APICLIENT {}'.format(self.username)

Lukas Burgey's avatar
Lukas Burgey committed
304
305
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
306

Lukas Burgey's avatar
Lukas Burgey committed
307
    def msg(self, msg):
308
309
310
311
312
313
314
        return '[{}] {}'.format(self, msg)

    # oidcuser: withdraw and delete all credentials and delete the user
    def remove(self):
        if self.user_type == 'oidcuser':
            self.deactivate()

Lukas Burgey's avatar
Lukas Burgey committed
315
            # FIXME: deleting the user brings problems:
316
317
            # the deletion cascades down to DeploymentTask and DeploymentTaskItem
            # but these need to be conserved so all clients withdrawals can be tracked
Lukas Burgey's avatar
Lukas Burgey committed
318
            LOGGER.info(self.msg('Deleting'))
319
320
321
            self.delete()

    def activate(self):
322
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
323
            LOGGER.error(self.msg('already activated'))
324
325
            return

Lukas Burgey's avatar
Lukas Burgey committed
326
327
328
329
        self.is_active = True
        self._is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))
330

Lukas Burgey's avatar
Lukas Burgey committed
331
332
        # oidcuser: deploy the according credentials
        if self.user_type == 'oidcuser':
333
334
335
336
            for dep in self.deployments.all():
                dep.activate()

    def deactivate(self):
337
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
338
            LOGGER.error(self.msg('already deactivated'))
339
340
            return

Lukas Burgey's avatar
Lukas Burgey committed
341
342
343
344
345
346
        self.is_active = False
        self._is_active = False
        self.save()
        LOGGER.info(self.msg('deactivated'))

        # oidcuser: withdraw all credentials
347
348
349
350
351
        if self.user_type == 'oidcuser':

            for dep in self.deployments.all():
                dep.deactivate()

Lukas Burgey's avatar
Lukas Burgey committed
352

Lukas Burgey's avatar
Lukas Burgey committed
353
354
355
356
357
358
359
360
361
362
363
364
# authorisation groups
class AuthGroup(models.Model):
    name = models.CharField(
        max_length=200,
    )
    users = models.ManyToManyField(
        User,
        related_name='auth_groups',
        blank=True,
    )


Lukas Burgey's avatar
Lukas Burgey committed
365
class Site(models.Model):
366
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
367
368
        User,
        related_name='site',
369
370
371
372
373
374
375
376
377
378
379
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    name = models.CharField(
        max_length=150,
        unique=True,
    )
    description = models.TextField(
        max_length=300,
        blank=True,
Lukas Burgey's avatar
Lukas Burgey committed
380
    )
Lukas Burgey's avatar
Lukas Burgey committed
381
382
383
384

    def __str__(self):
        return self.name

385
386
387
388
389
390
    # tasks which are still to be executed on this site
    @property
    def tasks(self):
        return [item.task
                for item
                in self.task_items.all()]
Lukas Burgey's avatar
Lukas Burgey committed
391

Lukas Burgey's avatar
Lukas Burgey committed
392
393
394
395

class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
396
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
397
398
        Site,
        related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
399
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
400
401
402
        Group,
        related_name='services',
        blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
403

404
405
406
407
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
408
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
409
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
410
411
412


class SSHPublicKey(models.Model):
Lukas Burgey's avatar
Lukas Burgey committed
413
414
415
416
417
418
    name = models.CharField(
        max_length=150,
    )
    key = models.TextField(
        max_length=1000
    )
Lukas Burgey's avatar
Lukas Burgey committed
419
    # hidden field at the user
420
    # TODO checks: if the user is null
Lukas Burgey's avatar
Lukas Burgey committed
421
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
422
423
        User,
        related_name='_ssh_keys',
424
425
        on_delete=models.SET_NULL,
        null=True,
Lukas Burgey's avatar
Lukas Burgey committed
426
    )
Lukas Burgey's avatar
Lukas Burgey committed
427

Lukas Burgey's avatar
Lukas Burgey committed
428
429
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
430
431
432
        default=False,
        editable=False,
    )
433

Lukas Burgey's avatar
Lukas Burgey committed
434
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
435
        return '[SSHPublicKey:{}] {}'.format(self, msg)
436

437
438
439
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
440
    def delete_key(self):
Lukas Burgey's avatar
Lukas Burgey committed
441
        if (not self.tasks.exists() and not self.deployments.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
442
            LOGGER.info(self.msg('Direct deletion of key'))
443
444
445
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
446
        LOGGER.info(self.msg('Deletion of key started'))
447
448
449
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
450
        # delete implies withdrawing the key from all clients
451
452
453
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
454
455
    # when a key is withdrawn by a client we try to finally delete it
    def try_final_deletion(self):
Lukas Burgey's avatar
Lukas Burgey committed
456
        if (self.deleted and not self.tasks.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
457
            LOGGER.info(self.msg(
Lukas Burgey's avatar
Lukas Burgey committed
458
                'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
459
460
461
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
462
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
463
464
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
465
466
467
        return self.name


468
# Deployment describes the credential state per user as it is supposed to be
469
470
471
472
#
# (exception: if is_active=False the ssh_keys contain the keys to be deployed
# if the deployment is reactivated)
#
473
474
# DeploymentTask is what is sent to the clients via rabbitmq
# The DeploymentTaskItem track the acknowledgements from the clients
Lukas Burgey's avatar
Lukas Burgey committed
475
476
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
477
478
479
480
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
481
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
482
483
484
485
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
486
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
487
488
489
490
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
491
    ssh_keys_to_withdraw = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
492
493
494
495
        SSHPublicKey,
        related_name='withdrawn_deployments',
        blank=True,
    )
496
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
497
498
        default=True,
    )
499

Lukas Burgey's avatar
Lukas Burgey committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520

    # get a deployment for a user/service.
    # if it does not exist it is created
    @classmethod
    def get_deployment(cls, user, service):
        query = cls.objects.filter(
            user=user,
        ).filter(
            service=service,
        )
        if query.exists():
            return query.first()

        deployment = cls(
            user=user,
            service=service,
        )
        deployment.save()
        return deployment


521
522
523
    @property
    def withdrawals(self):
        return self.tasks.filter(action='withdraw')
Lukas Burgey's avatar
Lukas Burgey committed
524

525
526
527
    @property
    def deploys(self):
        return self.tasks.filter(action='deploy')
Lukas Burgey's avatar
Lukas Burgey committed
528

529
530
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
531

Lukas Burgey's avatar
Lukas Burgey committed
532
    def msg(self, msg):
533
        return '[Deployment:{}] {}'.format(self, msg)
534

535
536
537
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
538
            LOGGER.error(self.msg('already active'))
539
540
            return

Lukas Burgey's avatar
Lukas Burgey committed
541
        LOGGER.debug(self.msg(str(self.ssh_keys.all())))
542
543
544
545
546
        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
Lukas Burgey's avatar
Lukas Burgey committed
547
        LOGGER.info(self.msg('activated'))
548
549
550
551

    # withdraw all credentials
    def deactivate(self):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
552
            LOGGER.error(self.msg('already deactivated'))
553
554
555
            return

        self.is_active = False
556
        self.save()
557

558
559
560
        for key in self.ssh_keys.all():
            self._withdraw_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
561
        LOGGER.info(self.msg('deactivated'))
562
563
564

    # only deploy the key
    def _deploy_key(self, key):
Lukas Burgey's avatar
Lukas Burgey committed
565
        task = DeploymentTask.construct_deployment_task(
Lukas Burgey's avatar
Lukas Burgey committed
566
567
568
            deployment=self,
            key=key,
        )
569
570
        # publish the task
        task.publish()
571

572
    def _withdraw_key(self, key):
Lukas Burgey's avatar
Lukas Burgey committed
573
        task = DeploymentTask.construct_withdrawal_task(
Lukas Burgey's avatar
Lukas Burgey committed
574
575
576
            deployment=self,
            key=key,
        )
577

578
579
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
580

581
582
583
    # deploy key and track changes in the key lists
    def deploy_key(self, key):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
584
            LOGGER.error(self.msg('cannot deploy while deactivated'))
585
586
587
588
589
590
591
592
593
594
595
596
597
            raise Exception('deployment deactivated')

        self.ssh_keys.add(key)

        if key in self.ssh_keys_to_withdraw.all():
            self.ssh_keys_to_withdraw.remove(key)
        self.save()

        self._deploy_key(key)

    # withdraw key and track changes in the key lists
    def withdraw_key(self, key):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
598
            LOGGER.error(self.msg('cannot withdraw while deactivated'))
599
600
601
602
603
604
605
606
607
608
            raise Exception('deployment deactivated')

        self.ssh_keys.remove(key)

        # keys which are to be withdrawn by the clients
        self.ssh_keys_to_withdraw.add(key)
        self.save()

        self._withdraw_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
609

610
611
class DeploymentTask(models.Model):
    ACTION_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
612
613
614
        ('deploy', 'deploy'),
        ('withdraw', 'withdraw'),
    )
615
    action = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
616
617
618
        max_length=10,
        choices=ACTION_CHOICES,
    )
619
    key = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
620
621
622
623
        SSHPublicKey,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
624
    deployment = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
625
626
627
628
        Deployment,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
629
630
631
632
633
    user = models.ForeignKey(
        User,
        related_name='deployment_tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
634

Lukas Burgey's avatar
Lukas Burgey committed
635
636
637
638
639
640
641
642
643
644
645
    @classmethod
    def construct_deployment_task(cls, deployment, key):
        # delete outstanding tasks which are made obsolete by this task
        for withdrawal in deployment.withdrawals.filter(key=key):
            LOGGER.debug(withdrawal.msg('now obsolete'))
            withdrawal.delete()

        task = cls(
            action='deploy',
            deployment=deployment,
            key=key,
646
            user=deployment.user,
Lukas Burgey's avatar
Lukas Burgey committed
647
648
649
650
651
652
653
654
655
        )
        task.save()
        LOGGER.debug(task.msg('generated'))

        # generate task items
        for site in deployment.service.site.all():
            deploy = DeploymentTaskItem(
                task=task,
                site=site,
Lukas Burgey's avatar
Lukas Burgey committed
656
                user=deployment.user
Lukas Burgey's avatar
Lukas Burgey committed
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
            )
            deploy.save()
            LOGGER.debug(deploy.msg('generated'))

        return task

    @classmethod
    def construct_withdrawal_task(cls, deployment, key):
        # delete outstanding tasks which are made obsolete by this task
        for withdrawal in deployment.deploys.filter(key=key):
            LOGGER.debug(withdrawal.msg('now obsolete'))
            withdrawal.delete()

        task = cls(
            action='withdraw',
            deployment=deployment,
            key=key,
674
            user=deployment.user,
Lukas Burgey's avatar
Lukas Burgey committed
675
676
677
678
679
680
681
682
683
        )
        task.save()
        LOGGER.debug(task.msg('generated'))

        # generate task items
        for site in deployment.service.site.all():
            deploy = DeploymentTaskItem(
                task=task,
                site=site,
Lukas Burgey's avatar
Lukas Burgey committed
684
                user=deployment.user
Lukas Burgey's avatar
Lukas Burgey committed
685
686
687
688
689
690
            )
            deploy.save()
            LOGGER.debug(deploy.msg('generated'))

        return task

Lukas Burgey's avatar
Lukas Burgey committed
691
692
693
694
    @property
    def service(self):
        return self.deployment.service

695
    def __str__(self):
696
        return "{}:{}:{} - {}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
697
698
699
700
            self.deployment.service,
            self.deployment.user,
            self.key,
            self.action,
701
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
702
        )
703

Lukas Burgey's avatar
Lukas Burgey committed
704
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
705
        return '[DeploymentTask:{}] {}'.format(self, msg)
706
707

    def publish(self):
708
        # FIXME mitigating circular dependencies here
709
710
711
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

712
        RabbitMQInstance.load().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
713
714
715
            self.service,
            msg,
        )
716
717
718

    # the client acked the receipt and execution of the task for his site
    def item_finished(self, site):
719

Lukas Burgey's avatar
Lukas Burgey committed
720
        item = self.task_items.get(site=site)
721
        # LOGGER.debug(item.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
722
        item.delete()
723
724

        if not self.task_items.exists():
725
            # finished sends its own message
726
            self.finished()
727
728
729
730
731
732
733
734
735
        else:
            from .frontend.views import user_state_dict
            content = {
                'user_state': user_state_dict(self.user),
            }
            RabbitMQInstance.load().publish_to_webpage(
                self.user,
                content,
            )
736
737
738

    # maintenance after all task items are done
    def finished(self):
Lukas Burgey's avatar
Lukas Burgey committed
739
        LOGGER.info(self.msg('done'))
740

Lukas Burgey's avatar
Lukas Burgey committed
741
        self.delete()
742
743
744
745
746

        # check if this was the final withdraw in a key deletion
        if self.action == 'withdraw':
            self.key.try_final_deletion()

Lukas Burgey's avatar
Lukas Burgey committed
747
748
749
750
751
        message = 'Completed: {} {} @ {}'.format(
            self.action,
            self.key,
            self.service,
        )
752
753
754
755
756
757
758
759
760
761
762

        from .frontend.views import user_state_dict
        content = {
            'user_state': user_state_dict(self.user),
            'message': message,
        }
        RabbitMQInstance.load().publish_to_webpage(
            self.user,
            content,
        )

763
764
765

class DeploymentTaskItem(models.Model):
    task = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
766
767
768
769
        DeploymentTask,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
770
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
771
772
773
774
        Site,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    user = models.ForeignKey(
        User,
        related_name='deployment_task_items',
        on_delete=models.CASCADE,
    )

    @property
    def service(self):
        return self.task.service

    @property
    def key(self):
        return self.task.key

    @property
    def action(self):
        return self.deployment.key
792

Lukas Burgey's avatar
Lukas Burgey committed
793
    def __str__(self):
794
        return "{}@{}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
795
796
            self.task,
            self.site,
797
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
798
        )
799

Lukas Burgey's avatar
Lukas Burgey committed
800
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
801
        return '[DeploymentTaskItem:{}] {}'.format(self, msg)
802

Lukas Burgey's avatar
Lukas Burgey committed
803

804
805
806
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
807

808
809
810
811
812
@receiver(post_save, sender=User)
def deactivate_user(sender, instance=None, created=False, **kwargs):
    if created:
        return

813
    if not instance.is_active and instance.is_active_at_clients:
814
815
816
817
818
819
820
821
        instance.deactivate()


@receiver(post_save, sender=User)
def activate_user(sender, instance=None, created=False, **kwargs):
    if created:
        return

822
    if instance.is_active and not instance.is_active_at_clients:
823
        instance.activate()