models.py 16.9 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
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

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

Lukas Burgey's avatar
Lukas Burgey committed
93
94
    # PUBLIC API

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

129
130
            tries += 1

Lukas Burgey's avatar
Lukas Burgey committed
131

132
133
134
135
def user_info_default():
    return {}


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

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

186
187
188
189
    @property
    def is_active_at_clients(self):
        return self._is_active

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

Lukas Burgey's avatar
Lukas Burgey committed
203
204
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
205

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

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

        if self.user_type == 'oidcuser':
            self.is_active = True
227
            self._is_active = True
228
229
230
231
232
            self.save()

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

Lukas Burgey's avatar
Lukas Burgey committed
233
            LOGGER.info(self.msg('activated'))
234
235
236

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

        if self.user_type == 'oidcuser':
            self.is_active = False
243
            self._is_active = False
244
245
246
247
248
            self.save()

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

Lukas Burgey's avatar
Lukas Burgey committed
249
            LOGGER.info(self.msg('deactivated'))
250
251


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


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

    def __str__(self):
        return self.name

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # publish the task
        task.publish()
467

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
615

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

620
621
622
623
624
625
@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()

626
627
628
629
630
@receiver(post_save, sender=User)
def deactivate_user(sender, instance=None, created=False, **kwargs):
    if created:
        return

631
    if not instance.is_active and instance.is_active_at_clients:
632
633
634
635
636
637
638
639
        instance.deactivate()


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

640
    if instance.is_active and not instance.is_active_at_clients:
641
        instance.activate()