models.py 17 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
    )
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
    is_active = models.BooleanField(
        default=True,
Lukas Burgey's avatar
Lukas Burgey committed
74
    )
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

    @property
Lukas Burgey's avatar
Lukas Burgey committed
90
91
92
93
94
    def _connection_parameters(self):
        return pika.ConnectionParameters(
            host=self.host,
            ssl=True,
        )
95

Lukas Burgey's avatar
Lukas Burgey committed
96
97
    # PUBLIC API

98
    def publish_by_service(self, service, msg):
99
100
101
        # FIXME dirty
        tries = 0
        while tries < RECONNECT_RETRIES:
102
            try:
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
                # 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(
119
120
121
122
123
124
125
                    exchange=self.exchange,
                    routing_key=service.routing_key,
                    body=msg,
                    properties=pika.BasicProperties(
                        delivery_mode=1,
                    ),
                )
126
127
128
129
                channel.close()
                connection.close()
                return
            except:
130
                time.sleep(RECONNECT_TIMEOUT)
Lukas Burgey's avatar
Lukas Burgey committed
131

132
133
            tries += 1

Lukas Burgey's avatar
Lukas Burgey committed
134

135
136
137
138
def user_info_default():
    return {}


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

Lukas Burgey's avatar
Lukas Burgey committed
183
    # we hide deleted keys here
184
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
185
186
187
188
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

189
190
191
192
    @property
    def is_active_at_clients(self):
        return self._is_active

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

Lukas Burgey's avatar
Lukas Burgey committed
206
207
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
208

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

    def activate(self):
224
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
225
            LOGGER.error(self.msg('already activated'))
226
227
228
229
            return

        if self.user_type == 'oidcuser':
            self.is_active = True
230
            self._is_active = True
231
232
233
234
235
            self.save()

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

Lukas Burgey's avatar
Lukas Burgey committed
236
            LOGGER.info(self.msg('activated'))
237
238
239

    # oidcuser: withdraw all credentials
    def deactivate(self):
240
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
241
            LOGGER.error(self.msg('already deactivated'))
242
243
244
245
            return

        if self.user_type == 'oidcuser':
            self.is_active = False
246
            self._is_active = False
247
248
249
250
251
            self.save()

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

Lukas Burgey's avatar
Lukas Burgey committed
252
            LOGGER.info(self.msg('deactivated'))
253
254


255
256
257
258
259
260
261
262
263
264
    @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,
265
            userinfo=user_info,
266
        )
Lukas Burgey's avatar
Lukas Burgey committed
267
268
269


class Site(models.Model):
270
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
271
272
        User,
        related_name='site',
273
274
275
276
277
278
279
280
281
282
283
        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
284
    )
Lukas Burgey's avatar
Lukas Burgey committed
285
286
287
288

    def __str__(self):
        return self.name

289
290
291
292
293
294
    # 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
295

Lukas Burgey's avatar
Lukas Burgey committed
296
297
298
299

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

308
309
310
311
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
312
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
313
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
314
315
316


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

Lukas Burgey's avatar
Lukas Burgey committed
329
330
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
331
332
333
        default=False,
        editable=False,
    )
334

Lukas Burgey's avatar
Lukas Burgey committed
335
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
336
        return '[SSHPublicKey:{}] {}'.format(self, msg)
337

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

Lukas Burgey's avatar
Lukas Burgey committed
347
        LOGGER.info(self.msg('Deletion of key started'))
348
349
350
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
351
        # delete implies withdrawing the key from all clients
352
353
354
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

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

Lukas Burgey's avatar
Lukas Burgey committed
363
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
364
365
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
366
367
368
        return self.name


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

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

405
406
407
    @property
    def deploys(self):
        return self.tasks.filter(action='deploy')
Lukas Burgey's avatar
Lukas Burgey committed
408

409
410
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
411

Lukas Burgey's avatar
Lukas Burgey committed
412
    def msg(self, msg):
413
        return '[Deployment:{}] {}'.format(self, msg)
414

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

Lukas Burgey's avatar
Lukas Burgey committed
421
        LOGGER.debug(self.msg(str(self.ssh_keys.all())))
422
423
424
425
426
        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
Lukas Burgey's avatar
Lukas Burgey committed
427
        LOGGER.info(self.msg('activated'))
428
429
430
431

    # withdraw all credentials
    def deactivate(self):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
432
            LOGGER.error(self.msg('already deactivated'))
433
434
435
            return

        self.is_active = False
436
        self.save()
437

438
439
440
        for key in self.ssh_keys.all():
            self._withdraw_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
441
        LOGGER.info(self.msg('deactivated'))
442
443
444
445

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

        # generate task
        task = DeploymentTask(
Lukas Burgey's avatar
Lukas Burgey committed
452
453
454
455
            action='deploy',
            deployment=self,
            key=key,
        )
456
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
457
        LOGGER.debug(task.msg('generated'))
458
459
460
461

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

        # publish the task
        task.publish()
470

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

477
478
        # generate task
        task = DeploymentTask(
Lukas Burgey's avatar
Lukas Burgey committed
479
480
481
482
            action='withdraw',
            deployment=self,
            key=key,
        )
483
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
484
        LOGGER.debug(task.msg('generated'))
Lukas Burgey's avatar
Lukas Burgey committed
485

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

495
496
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
497

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

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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
564
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
565
        return '[DeploymentTask:{}] {}'.format(self, msg)
566
567

    def publish(self):
568
        # FIXME mitigating circular dependencies here
569
570
571
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

572
        RabbitMQInstance.load().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
573
574
575
            self.service,
            msg,
        )
576
577
578

    # 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
579
        item = self.task_items.get(site=site)
Lukas Burgey's avatar
Lukas Burgey committed
580
        LOGGER.debug(item.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
581
        item.delete()
582
583
584
585
586
587

        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
588
        LOGGER.info(self.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
589
        self.delete()
590
591
592
593
594
595
596
597

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

Lukas Burgey's avatar
Lukas Burgey committed
608
    def __str__(self):
609
        return "{}@{}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
610
611
            self.task,
            self.site,
612
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
613
        )
614

Lukas Burgey's avatar
Lukas Burgey committed
615
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
616
        return '[DeploymentTaskItem:{}] {}'.format(self, msg)
617

Lukas Burgey's avatar
Lukas Burgey committed
618

619
620
621
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
622

623
624
625
626
627
628
@receiver(post_save, sender=User)
def upgrade_password(sender, instance=None, created=False, **kwargs):
    if created and instance is not None and instance.user_type == 'apiclient':
        instance.set_password(instance.password)
        instance.save()

629
630
631
632
633
@receiver(post_save, sender=User)
def deactivate_user(sender, instance=None, created=False, **kwargs):
    if created:
        return

634
    if not instance.is_active and instance.is_active_at_clients:
635
636
637
638
639
640
641
642
        instance.deactivate()


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

643
    if instance.is_active and not instance.is_active_at_clients:
644
        instance.activate()