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

import json
5
import time
Lukas Burgey's avatar
Lukas Burgey committed
6
import logging
7
import pika
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

# TODO dirty
20
21
RECONNECT_TIMEOUT = 5
RECONNECT_RETRIES = 3
22
RABBITMQ_CONNECTION = None
23

Lukas Burgey's avatar
Lukas Burgey committed
24

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 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
49
50
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
51
class RabbitMQInstance(SingletonModel):
Lukas Burgey's avatar
Lukas Burgey committed
52
    host = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
53
54
55
        max_length=150,
        default='localhost',
    )
Lukas Burgey's avatar
Lukas Burgey committed
56
57
58
59
    vhost = models.CharField(
        max_length=150,
        default='%2f',
    )
Lukas Burgey's avatar
Lukas Burgey committed
60
    exchange = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
61
62
63
        max_length=150,
        default='deployments',
    )
Lukas Burgey's avatar
Lukas Burgey committed
64
    port = models.IntegerField(
Lukas Burgey's avatar
Lukas Burgey committed
65
        default=15672,
Lukas Burgey's avatar
Lukas Burgey committed
66
    )
Lukas Burgey's avatar
Lukas Burgey committed
67
    username = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
68
69
70
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
71
    password = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
72
73
74
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
75
76
77
78

    def __str__(self):
        return self.host

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

    @property
    def auth(self):
        return HTTPBasicAuth(
Lukas Burgey's avatar
Lukas Burgey committed
85
            self.username,
Lukas Burgey's avatar
Lukas Burgey committed
86
            self.password,
Lukas Burgey's avatar
Lukas Burgey committed
87
        )
Lukas Burgey's avatar
Lukas Burgey committed
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
    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
132
    @property
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    def _channel(self):
        channel = self._connection.channel()
        channel.confirm_delivery()
        return channel

    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
147
        )
148
        channel.close()
149

Lukas Burgey's avatar
Lukas Burgey committed
150

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

159
160
161
162
163
164
165
    def publish_to_webpage(self, user):
        LOGGER.debug('Signalling webpage of user %s', user)
        self._publish(
            'update',
            str(user.id),
            '<got update>',
        )
166

Lukas Burgey's avatar
Lukas Burgey committed
167

168
169
170
171
def user_info_default():
    return {}


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

Lukas Burgey's avatar
Lukas Burgey committed
216
217
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
    # 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
261
262
263
264
265
266

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

Lukas Burgey's avatar
Lukas Burgey committed
267
268
269
270
271
272
273
274
275
276
277
278
        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
279
    # we hide deleted keys here
280
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
281
282
283
284
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

285
286
287
288
    @property
    def is_active_at_clients(self):
        return self._is_active

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

Lukas Burgey's avatar
Lukas Burgey committed
302
303
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
304

Lukas Burgey's avatar
Lukas Burgey committed
305
    def msg(self, msg):
306
307
308
309
310
311
312
        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
313
            # FIXME: deleting the user brings problems:
314
315
            # 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
316
            LOGGER.info(self.msg('Deleting'))
317
318
319
            self.delete()

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

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

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

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

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

        # oidcuser: withdraw all credentials
345
346
347
348
349
        if self.user_type == 'oidcuser':

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

Lukas Burgey's avatar
Lukas Burgey committed
350

Lukas Burgey's avatar
Lukas Burgey committed
351
352
353
354
355
356
357
358
359
360
361
362
# 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
363
class Site(models.Model):
364
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
365
366
        User,
        related_name='site',
367
368
369
370
371
372
373
374
375
376
377
        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
378
    )
Lukas Burgey's avatar
Lukas Burgey committed
379
380
381
382

    def __str__(self):
        return self.name

383
384
385
386
387
388
    # 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
389

Lukas Burgey's avatar
Lukas Burgey committed
390
391
392
393

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

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

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


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

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

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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
452
453
    # 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
454
        if (self.deleted and not self.tasks.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
455
            LOGGER.info(self.msg(
Lukas Burgey's avatar
Lukas Burgey committed
456
                'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
457
458
459
            self.delete()
            return

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


466
# Deployment describes the credential state per user as it is supposed to be
467
468
469
470
#
# (exception: if is_active=False the ssh_keys contain the keys to be deployed
# if the deployment is reactivated)
#
471
472
# 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
473
474
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
475
476
477
478
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
479
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
480
481
482
483
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
484
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
485
486
487
488
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
489
    ssh_keys_to_withdraw = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
490
491
492
493
        SSHPublicKey,
        related_name='withdrawn_deployments',
        blank=True,
    )
494
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
495
496
        default=True,
    )
497

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

    # 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


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

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

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

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

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

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

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

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

        self.is_active = False
554
        self.save()
555

556
557
558
        for key in self.ssh_keys.all():
            self._withdraw_key(key)

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

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

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

576
577
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
578

579
580
581
    # 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
582
            LOGGER.error(self.msg('cannot deploy while deactivated'))
583
584
585
586
587
588
589
590
591
592
593
594
595
            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
596
            LOGGER.error(self.msg('cannot withdraw while deactivated'))
597
598
599
600
601
602
603
604
605
606
            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
607

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

Lukas Burgey's avatar
Lukas Burgey committed
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
    @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,
        )
        task.save()
        LOGGER.debug(task.msg('generated'))

        # generate task items
        for site in deployment.service.site.all():
            deploy = DeploymentTaskItem(
                task=task,
                site=site,
            )
            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,
        )
        task.save()
        LOGGER.debug(task.msg('generated'))

        # generate task items
        for site in deployment.service.site.all():
            deploy = DeploymentTaskItem(
                task=task,
                site=site,
            )
            deploy.save()
            LOGGER.debug(deploy.msg('generated'))

        return task

Lukas Burgey's avatar
Lukas Burgey committed
680
681
682
683
684
685
686
687
    @property
    def user(self):
        return self.deployment.user

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

688
    def __str__(self):
689
        return "{}:{}:{} - {}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
690
691
692
693
            self.deployment.service,
            self.deployment.user,
            self.key,
            self.action,
694
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
695
        )
696

Lukas Burgey's avatar
Lukas Burgey committed
697
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
698
        return '[DeploymentTask:{}] {}'.format(self, msg)
699
700

    def publish(self):
701
        # FIXME mitigating circular dependencies here
702
703
704
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

705
        RabbitMQInstance.load().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
706
707
708
            self.service,
            msg,
        )
709
710
711

    # the client acked the receipt and execution of the task for his site
    def item_finished(self, site):
712
713
714
        RabbitMQInstance.load().publish_to_webpage(
            self.user,
        )
Lukas Burgey's avatar
Lukas Burgey committed
715
        item = self.task_items.get(site=site)
Lukas Burgey's avatar
Lukas Burgey committed
716
        LOGGER.debug(item.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
717
        item.delete()
718
719
720
721
722
723

        if not self.task_items.exists():
            self.finished()

    # maintenance after all task items are done
    def finished(self):
Lukas Burgey's avatar
Lukas Burgey committed
724
        LOGGER.info(self.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
725
        self.delete()
726
727
728
729
730
731
732
733

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


class DeploymentTaskItem(models.Model):
    task = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
734
735
736
737
        DeploymentTask,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
738
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
739
740
741
742
        Site,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
743

Lukas Burgey's avatar
Lukas Burgey committed
744
    def __str__(self):
745
        return "{}@{}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
746
747
            self.task,
            self.site,
748
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
749
        )
750

Lukas Burgey's avatar
Lukas Burgey committed
751
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
752
        return '[DeploymentTaskItem:{}] {}'.format(self, msg)
753

Lukas Burgey's avatar
Lukas Burgey committed
754

755
756
757
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
758

759
760
761
762
763
@receiver(post_save, sender=User)
def deactivate_user(sender, instance=None, created=False, **kwargs):
    if created:
        return

764
    if not instance.is_active and instance.is_active_at_clients:
765
766
767
768
769
770
771
772
        instance.deactivate()


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

773
    if instance.is_active and not instance.is_active_at_clients:
774
        instance.activate()