models.py 16.7 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
RECONNECT_TIMEOUT = 5
RECONNECT_RETRIES = 3
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
    )
64
    # TODO obsolete
Lukas Burgey's avatar
Lukas Burgey committed
65
    path = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
66
67
68
        max_length=150,
        default='api',
    )
Lukas Burgey's avatar
Lukas Burgey committed
69
    username = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
70
71
72
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
73
    password = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
74
75
76
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
77
78
    is_active = models.BooleanField(
        default=True,
Lukas Burgey's avatar
Lukas Burgey committed
79
    )
Lukas Burgey's avatar
Lukas Burgey committed
80
81
82
83

    def __str__(self):
        return self.host

Lukas Burgey's avatar
Lukas Burgey committed
84
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
85
        return '[RabbitMQ:{}] {}'.format(self.host, msg)
Lukas Burgey's avatar
Lukas Burgey committed
86
87
88
89

    @property
    def auth(self):
        return HTTPBasicAuth(
Lukas Burgey's avatar
Lukas Burgey committed
90
            self.username,
Lukas Burgey's avatar
Lukas Burgey committed
91
            self.password,
Lukas Burgey's avatar
Lukas Burgey committed
92
        )
Lukas Burgey's avatar
Lukas Burgey committed
93
94

    @property
Lukas Burgey's avatar
Lukas Burgey committed
95
96
97
98
99
    def _connection_parameters(self):
        return pika.ConnectionParameters(
            host=self.host,
            ssl=True,
        )
100

Lukas Burgey's avatar
Lukas Burgey committed
101
102
    # PUBLIC API

103
    def publish_by_service(self, service, msg):
104
105
106
        # FIXME dirty
        tries = 0
        while tries < RECONNECT_RETRIES:
107
            try:
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
                # open connection
                connection = pika.BlockingConnection(
                    self._connection_parameters,
                )

                # open channel
                channel = connection.channel()
                channel.exchange_declare(
                    exchange=self.exchange,
                    durable=True,
                    auto_delete=False,
                    exchange_type='topic',
                )
                channel.confirm_delivery()

                channel.basic_publish(
124
125
126
127
128
129
130
                    exchange=self.exchange,
                    routing_key=service.routing_key,
                    body=msg,
                    properties=pika.BasicProperties(
                        delivery_mode=1,
                    ),
                )
131
132
133
134
                channel.close()
                connection.close()
                return
            except:
135
                time.sleep(RECONNECT_TIMEOUT)
Lukas Burgey's avatar
Lukas Burgey committed
136

137
138
            tries += 1

Lukas Burgey's avatar
Lukas Burgey committed
139

140
141
142
143
def user_info_default():
    return {}


Lukas Burgey's avatar
Lukas Burgey committed
144
class User(AbstractUser):
145
    TYPE_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
146
147
148
149
        ('apiclient', 'API-Client'),
        ('oidcuser', 'OIDC User'),
        ('admin', 'Admin'),
    )
150
    user_type = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
151
152
153
154
        max_length=20,
        choices=TYPE_CHOICES,
        default='oidcuser',
    )
155
156
157
158
    sub = models.CharField(
        max_length=150,
        blank=True,
        null=True,
159
        editable=False,
160
161
162
163
164
165
166
167
168
169
170
171
    )
    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
172
173
174
175
176
    # the idp which authenticated the user
    idp = models.ForeignKey(
        OIDCConfig,
        related_name='users',
        on_delete=models.CASCADE,
177
178
179
        blank=True,
        null=True,
        editable=False,
Lukas Burgey's avatar
Lukas Burgey committed
180
    )
181
182
183
184
    userinfo = JSONField(
        default=user_info_default,
        null=True,
        blank=True,
185
        editable=False,
186
    )
Lukas Burgey's avatar
Lukas Burgey committed
187

Lukas Burgey's avatar
Lukas Burgey committed
188
    # we hide deleted keys here
189
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
190
191
192
193
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

194
195
196
197
    @property
    def is_active_at_clients(self):
        return self._is_active

198
199
200
    def __str__(self):
        if self.user_type == 'admin':
            return 'ADMIN {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
201
        elif self.user_type == 'oidcuser':
202
203
204
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
205
        elif self.user_type == 'apiclient':
206
207
208
209
210
            try:
                return 'APICLIENT {}@{}'.format(self.username, self.site)
            except:
                return 'APICLIENT {}'.format(self.username)

Lukas Burgey's avatar
Lukas Burgey committed
211
212
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
213

Lukas Burgey's avatar
Lukas Burgey committed
214
    def msg(self, msg):
215
216
217
218
219
220
221
        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
222
            # FIXME: deleting the user brings problems:
223
224
            # 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
225
            LOGGER.info(self.msg('Deleting'))
226
227
228
            self.delete()

    def activate(self):
229
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
230
            LOGGER.error(self.msg('already activated'))
231
232
233
234
            return

        if self.user_type == 'oidcuser':
            self.is_active = True
235
            self._is_active = True
236
237
238
239
240
            self.save()

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

Lukas Burgey's avatar
Lukas Burgey committed
241
            LOGGER.info(self.msg('activated'))
242
243
244

    # oidcuser: withdraw all credentials
    def deactivate(self):
245
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
246
            LOGGER.error(self.msg('already deactivated'))
247
248
249
250
            return

        if self.user_type == 'oidcuser':
            self.is_active = False
251
            self._is_active = False
252
253
254
255
256
            self.save()

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

Lukas Burgey's avatar
Lukas Burgey committed
257
            LOGGER.info(self.msg('deactivated'))
258
259


260
261
262
263
264
265
266
267
268
269
    @classmethod
    def construct_from_user_info(cls, user_info, idp):
        LOGGER.debug('User: constructing from %s', user_info)
        return cls(
            sub=user_info.get('sub', ''),
            first_name=user_info.get('given_name', ''),
            last_name=user_info.get('family_name', ''),
            email=user_info.get('email', ''),
            username=user_info.get('email', ''),
            idp=idp,
270
            userinfo=user_info,
271
        )
Lukas Burgey's avatar
Lukas Burgey committed
272
273
274


class Site(models.Model):
275
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
276
277
278
        User,
        related_name='site',
    )
Lukas Burgey's avatar
Lukas Burgey committed
279
280
281
282
283
284
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)

    def __str__(self):
        return self.name

285
286
287
288
289
290
    # 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
291

Lukas Burgey's avatar
Lukas Burgey committed
292
293
294
295

class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
296
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
297
298
        Site,
        related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
299
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
300
301
302
        Group,
        related_name='services',
        blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
303

304
305
306
307
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
308
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
309
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
310
311
312


class SSHPublicKey(models.Model):
Lukas Burgey's avatar
Lukas Burgey committed
313
314
315
316
317
318
    name = models.CharField(
        max_length=150,
    )
    key = models.TextField(
        max_length=1000
    )
Lukas Burgey's avatar
Lukas Burgey committed
319
    # hidden field at the user
Lukas Burgey's avatar
Lukas Burgey committed
320
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
321
322
323
        User,
        related_name='_ssh_keys',
    )
Lukas Burgey's avatar
Lukas Burgey committed
324

Lukas Burgey's avatar
Lukas Burgey committed
325
326
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
327
328
329
        default=False,
        editable=False,
    )
330

Lukas Burgey's avatar
Lukas Burgey committed
331
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
332
        return '[SSHPublicKey:{}] {}'.format(self, msg)
333

334
335
336
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
337
    def delete_key(self):
Lukas Burgey's avatar
Lukas Burgey committed
338
        if (not self.tasks.exists() and not self.deployments.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
339
            LOGGER.info(self.msg('Direct deletion of key'))
340
341
342
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
343
        LOGGER.info(self.msg('Deletion of key started'))
344
345
346
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
347
        # delete implies withdrawing the key from all clients
348
349
350
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
351
352
    # 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
353
        if (self.deleted and not self.tasks.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
354
            LOGGER.info(self.msg(
Lukas Burgey's avatar
Lukas Burgey committed
355
                'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
356
357
358
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
359
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
360
361
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
362
363
364
        return self.name


365
# Deployment describes the credential state per user as it is supposed to be
366
367
368
369
#
# (exception: if is_active=False the ssh_keys contain the keys to be deployed
# if the deployment is reactivated)
#
370
371
# 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
372
373
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
374
375
376
377
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
378
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
379
380
381
382
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
383
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
384
385
386
387
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
388
    ssh_keys_to_withdraw = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
389
390
391
392
        SSHPublicKey,
        related_name='withdrawn_deployments',
        blank=True,
    )
393
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
394
395
        default=True,
    )
396

397
398
399
    @property
    def withdrawals(self):
        return self.tasks.filter(action='withdraw')
Lukas Burgey's avatar
Lukas Burgey committed
400

401
402
403
    @property
    def deploys(self):
        return self.tasks.filter(action='deploy')
Lukas Burgey's avatar
Lukas Burgey committed
404

405
406
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
407

Lukas Burgey's avatar
Lukas Burgey committed
408
    def msg(self, msg):
409
        return '[Deployment:{}] {}'.format(self, msg)
410

411
412
413
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
414
            LOGGER.error(self.msg('already active'))
415
416
            return

Lukas Burgey's avatar
Lukas Burgey committed
417
        LOGGER.debug(self.msg(str(self.ssh_keys.all())))
418
419
420
421
422
        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
Lukas Burgey's avatar
Lukas Burgey committed
423
        LOGGER.info(self.msg('activated'))
424
425
426
427

    # withdraw all credentials
    def deactivate(self):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
428
            LOGGER.error(self.msg('already deactivated'))
429
430
431
            return

        self.is_active = False
432
        self.save()
433

434
435
436
        for key in self.ssh_keys.all():
            self._withdraw_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
437
        LOGGER.info(self.msg('deactivated'))
438
439
440
441

    # only deploy the key
    def _deploy_key(self, key):
        # delete outstanding tasks which are made obsolete by this task
442
        for withdrawal in self.withdrawals.filter(key=key):
Lukas Burgey's avatar
Lukas Burgey committed
443
            LOGGER.debug(withdrawal.msg('now obsolete'))
Lukas Burgey's avatar
Lukas Burgey committed
444
            withdrawal.delete()
445
446
447

        # generate task
        task = DeploymentTask(
Lukas Burgey's avatar
Lukas Burgey committed
448
449
450
451
            action='deploy',
            deployment=self,
            key=key,
        )
452
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
453
        LOGGER.debug(task.msg('generated'))
454
455
456
457

        # generate task items
        for site in self.service.site.all():
            deploy = DeploymentTaskItem(
Lukas Burgey's avatar
Lukas Burgey committed
458
459
460
                task=task,
                site=site,
            )
461
            deploy.save()
Lukas Burgey's avatar
Lukas Burgey committed
462
            LOGGER.debug(deploy.msg('generated'))
463
464
465

        # publish the task
        task.publish()
466

467
468
    def _withdraw_key(self, key):
        # delete outstanding tasks which are made obsolete by this task
469
        for deploy in self.deploys.filter(key=key):
Lukas Burgey's avatar
Lukas Burgey committed
470
            LOGGER.debug(deploy.msg("now obsolete"))
Lukas Burgey's avatar
Lukas Burgey committed
471
            deploy.delete()
Lukas Burgey's avatar
Lukas Burgey committed
472

473
474
        # generate task
        task = DeploymentTask(
Lukas Burgey's avatar
Lukas Burgey committed
475
476
477
478
            action='withdraw',
            deployment=self,
            key=key,
        )
479
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
480
        LOGGER.debug(task.msg('generated'))
Lukas Burgey's avatar
Lukas Burgey committed
481

482
483
484
        # generate task items
        for site in self.service.site.all():
            withdrawal = DeploymentTaskItem(
Lukas Burgey's avatar
Lukas Burgey committed
485
486
487
                task=task,
                site=site,
            )
488
            withdrawal.save()
Lukas Burgey's avatar
Lukas Burgey committed
489
            LOGGER.debug(withdrawal.msg('generated'))
490

491
492
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
493

494
495
496
    # 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
497
            LOGGER.error(self.msg('cannot deploy while deactivated'))
498
499
500
501
502
503
504
505
506
507
508
509
510
            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
511
            LOGGER.error(self.msg('cannot withdraw while deactivated'))
512
513
514
515
516
517
518
519
520
521
            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
522

523
524
class DeploymentTask(models.Model):
    ACTION_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
525
526
527
        ('deploy', 'deploy'),
        ('withdraw', 'withdraw'),
    )
528
    action = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
529
530
531
        max_length=10,
        choices=ACTION_CHOICES,
    )
532
    key = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
533
534
535
536
        SSHPublicKey,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
537
    deployment = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
538
539
540
541
        Deployment,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
542
543
544
545
546
547
548
549
550

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

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

551
    def __str__(self):
552
        return "{}:{}:{} - {}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
553
554
555
556
            self.deployment.service,
            self.deployment.user,
            self.key,
            self.action,
557
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
558
        )
559

Lukas Burgey's avatar
Lukas Burgey committed
560
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
561
        return '[DeploymentTask:{}] {}'.format(self, msg)
562
563

    def publish(self):
564
        # FIXME mitigating circular dependencies here
565
566
567
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

568
        RabbitMQInstance.load().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
569
570
571
            self.service,
            msg,
        )
572
573
574

    # the client acked the receipt and execution of the task for his site
    def item_finished(self, site):
Lukas Burgey's avatar
Lukas Burgey committed
575
        item = self.task_items.get(site=site)
Lukas Burgey's avatar
Lukas Burgey committed
576
        LOGGER.debug(item.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
577
        item.delete()
578
579
580
581
582
583

        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
584
        LOGGER.info(self.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
585
        self.delete()
586
587
588
589
590
591
592
593

        # 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
594
595
596
597
        DeploymentTask,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
598
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
599
600
601
602
        Site,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
603

Lukas Burgey's avatar
Lukas Burgey committed
604
    def __str__(self):
605
        return "{}@{}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
606
607
            self.task,
            self.site,
608
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
609
        )
610

Lukas Burgey's avatar
Lukas Burgey committed
611
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
612
        return '[DeploymentTaskItem:{}] {}'.format(self, msg)
613

Lukas Burgey's avatar
Lukas Burgey committed
614

615
616
617
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
618

619
620
621
622
623
@receiver(post_save, sender=User)
def deactivate_user(sender, instance=None, created=False, **kwargs):
    if created:
        return

624
    if not instance.is_active and instance.is_active_at_clients:
625
626
627
628
629
630
631
632
        instance.deactivate()


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

633
    if instance.is_active and not instance.is_active_at_clients:
634
        instance.activate()