models.py 19.2 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
from django.conf import settings
Lukas Burgey's avatar
Lukas Burgey committed
2
3
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
4
from django.db.models.signals import post_save, pre_delete
Lukas Burgey's avatar
Lukas Burgey committed
5
from django.dispatch import receiver
Lukas Burgey's avatar
Lukas Burgey committed
6
from requests.auth import HTTPBasicAuth
Lukas Burgey's avatar
Lukas Burgey committed
7
from rest_framework.authtoken.models import Token
Lukas Burgey's avatar
Lukas Burgey committed
8
import json
Lukas Burgey's avatar
Lukas Burgey committed
9
10
import pika
import requests
Lukas Burgey's avatar
Lukas Burgey committed
11
12
13
from .logging import get_logger

logger = get_logger(__name__)
14

Lukas Burgey's avatar
Lukas Burgey committed
15

Lukas Burgey's avatar
Lukas Burgey committed
16
17
18
19
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
class RabbitMQInstance(models.Model):
    host = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
20
21
22
        max_length=150,
        default='localhost',
    )
Lukas Burgey's avatar
Lukas Burgey committed
23
    exchange = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
24
25
26
        max_length=150,
        default='deployments',
    )
Lukas Burgey's avatar
Lukas Burgey committed
27
    port = models.IntegerField(
Lukas Burgey's avatar
Lukas Burgey committed
28
29
        default=15672
    )
Lukas Burgey's avatar
Lukas Burgey committed
30
    path = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
31
32
33
        max_length=150,
        default='api',
    )
Lukas Burgey's avatar
Lukas Burgey committed
34
    username = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
35
36
37
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
38
    password = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
39
40
41
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
42
43
    is_active = models.BooleanField(
        default=True,
Lukas Burgey's avatar
Lukas Burgey committed
44
    )
Lukas Burgey's avatar
Lukas Burgey committed
45
46
47
48

    def __str__(self):
        return self.host

Lukas Burgey's avatar
Lukas Burgey committed
49
50
    def msg(self, msg):
        return '[RabbitMQ:{}] {}'.format(self.host, msg)
Lukas Burgey's avatar
Lukas Burgey committed
51
52
53
54

    @property
    def api(self):
        return 'http://{}:{}/{}'.format(
Lukas Burgey's avatar
Lukas Burgey committed
55
56
57
58
            self.host,
            self.port,
            self.path,
        )
Lukas Burgey's avatar
Lukas Burgey committed
59
60
61
62

    @property
    def auth(self):
        return HTTPBasicAuth(
Lukas Burgey's avatar
Lukas Burgey committed
63
64
65
            self.username,
            self.password
        )
Lukas Burgey's avatar
Lukas Burgey committed
66
67
68
69
70

    @property
    def vhost(self):
        return '%2f'

71
72
73
74
75
76
77
78
    # singletons
    rabbitmq_connection = None
    rabbitmq_channel = None

    @property
    def connection(self):
        if self.rabbitmq_connection is None:
            rabbitmqconnection_properties = pika.ConnectionParameters(
Lukas Burgey's avatar
Lukas Burgey committed
79
80
81
                host=self.host,
                ssl=True,
            )
82
            self.rabbitmq_connection = pika.BlockingConnection(
Lukas Burgey's avatar
Lukas Burgey committed
83
84
                rabbitmqconnection_properties
            )
Lukas Burgey's avatar
Lukas Burgey committed
85
            logger.debug(self.msg('opened connection'))
86
87
88
89
90
91
92
93

        return self.rabbitmq_connection

    @property
    def channel(self):
        if self.rabbitmq_channel is None:
            self.rabbitmq_channel = self.connection.channel()
            self.rabbitmq_channel.exchange_declare(
Lukas Burgey's avatar
Lukas Burgey committed
94
95
96
                exchange=self.exchange,
                durable=True,
                exchange_type='topic')
97
            self.rabbitmq_channel.confirm_delivery()
Lukas Burgey's avatar
Lukas Burgey committed
98
99
            logger.debug(self.msg('opened channel'))

100
101
        return self.rabbitmq_channel

Lukas Burgey's avatar
Lukas Burgey committed
102
103
104
105
106
    def get_uri(self, path):
        return '{}/{}'.format(self.api, path)

    def rest_get(self, api_path):
        r = requests.get(
Lukas Burgey's avatar
Lukas Burgey committed
107
108
            self.get_uri(api_path),
            auth=self.auth)
Lukas Burgey's avatar
Lukas Burgey committed
109
110
111
112
113
114
115
        r.raise_for_status()
        return r.json()

    # send a rest call with path and data to the rest interface of
    # the rabbitmq instance
    def rest_put(self, api_path, data):
        r = requests.put(
Lukas Burgey's avatar
Lukas Burgey committed
116
117
118
            self.get_uri(api_path),
            json=data,
            auth=self.auth)
Lukas Burgey's avatar
Lukas Burgey committed
119
120
121
122
123
        r.raise_for_status()
        return r

    def rest_del(self, api_path):
        r = requests.delete(
Lukas Burgey's avatar
Lukas Burgey committed
124
125
            self.get_uri(api_path),
            auth=self.auth)
Lukas Burgey's avatar
Lukas Burgey committed
126
127
128
129
130
131
        r.raise_for_status()
        return r

    def set_topic_permissions(self, site):
        username = site.client.username
        path = 'topic-permissions/{}/{}/'.format(
Lukas Burgey's avatar
Lukas Burgey committed
132
133
134
            self.vhost,
            username,
        )
Lukas Burgey's avatar
Lukas Burgey committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148

        # set permissions for the correct topics
        # we construct a regex to match the services of the site
        services = ''
        omitBar = True
        for service in site.services.all():
            prefix = '|'
            if omitBar:
                prefix = ''
                omitBar = False

            services = services + prefix + service.name

        set_topic_permission_data = {
Lukas Burgey's avatar
Lukas Burgey committed
149
150
151
152
            'exchange': self.exchange,
            'write': '^$',
            'read': '^service\.({})$'.format(services),
        }
Lukas Burgey's avatar
Lukas Burgey committed
153
154
155
156
157
158
159

        return self.rest_put(path, set_topic_permission_data)

    # set permissions for the user
    def set_permissions(self, site):
        username = site.client.username
        path = 'permissions/{}/{}/'.format(
Lukas Burgey's avatar
Lukas Burgey committed
160
161
162
            self.vhost,
            username,
        )
Lukas Burgey's avatar
Lukas Burgey committed
163
164
        permission = '^(amq\.gen.*|{})'.format(self.exchange)
        set_permission_data = {
Lukas Burgey's avatar
Lukas Burgey committed
165
166
167
168
            'configure': permission,
            'write': permission,
            'read': permission,
        }
Lukas Burgey's avatar
Lukas Burgey committed
169
170
171
172
173
174
175
176
177

        return self.rest_put(path, set_permission_data)

    # create user at the rabbitmq instance
    def create_user(self, site):
        username = site.client.username
        path = 'users/{}/'.format(username)

        user_creation_data = {
Lukas Burgey's avatar
Lukas Burgey committed
178
179
180
            'password': str(site.client.auth_token.key),
            'tags': '',
        }
Lukas Burgey's avatar
Lukas Burgey committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

        return self.rest_put(path, user_creation_data)

    # delete user at the rabbitmq instance
    def delete_user(self, site):
        username = site.client.username
        path = 'users/{}/'.format(username)

        return self.rest_del(path)

    # PUBLIC API

    def register_site(self, site):
        self.create_user(site)
        self.set_permissions(site)
        self.set_topic_permissions(site)
197
        logger.info(self.msg('registered {}'.format(site.client)))
Lukas Burgey's avatar
Lukas Burgey committed
198
199
200

    def update_site(self, site):
        self.set_topic_permissions(site)
201
        logger.info(self.msg('updated permissions for {}'.format(site.client)))
Lukas Burgey's avatar
Lukas Burgey committed
202
203

    def deregister_site(self, site):
204
        logger.info(self.msg('deregistered {}'.format(site.client)))
Lukas Burgey's avatar
Lukas Burgey committed
205
206
207
208
209
210
211
212
213

    def is_client_connected(self, site):
        connections = self.rest_get("connections/")
        clients_for_site = [c
                            for c in connections
                            if c['user'] == site.client.username]
        return len(clients_for_site) > 0

    def disconnect(self):
Lukas Burgey's avatar
Lukas Burgey committed
214
        logger.debug(self.msg('closing connection'))
Lukas Burgey's avatar
Lukas Burgey committed
215
216
217
218
219
220
221
222
223
224
        self.connection.close()

    def service_routing_key(self, service):
        return 'service.' + service.name

    def online_clients(self, service):
        return [site
                for site in service.site.all()
                if self.is_client_connected(site)]

225
226
    def publish_by_service(self, service, msg):
        return self.channel.basic_publish(
Lukas Burgey's avatar
Lukas Burgey committed
227
228
229
230
231
232
233
            exchange=self.exchange,
            routing_key=self.service_routing_key(service),
            body=msg,
            properties=pika.BasicProperties(
                delivery_mode=1,
            ),
        )
Lukas Burgey's avatar
Lukas Burgey committed
234
235
236


def rabbitmq_instance():
Lukas Burgey's avatar
Lukas Burgey committed
237
    return RabbitMQInstance.objects.get(is_active=True)
Lukas Burgey's avatar
Lukas Burgey committed
238
239


Lukas Burgey's avatar
Lukas Burgey committed
240
class User(AbstractUser):
241
    TYPE_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
242
243
244
245
        ('apiclient', 'API-Client'),
        ('oidcuser', 'OIDC User'),
        ('admin', 'Admin'),
    )
246
    user_type = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
247
248
249
250
        max_length=20,
        choices=TYPE_CHOICES,
        default='oidcuser',
    )
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    sub = models.CharField(
        max_length=150,
        blank=True,
        null=True,
    )
    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
267

Lukas Burgey's avatar
Lukas Burgey committed
268
    # we hide deleted keys here
269
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
270
271
272
273
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

274
275
276
277
278
279
280
281
282
    def __str__(self):
        if self.user_type == 'admin':
            return 'ADMIN {}'.format(self.username)
        if self.user_type == 'oidcuser':
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
        if self.user_type == 'apiclient':
            return 'APICLIENT {}@{}'.format(self.username, self.site)
Lukas Burgey's avatar
Lukas Burgey committed
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    def msg(self, msg):
        return '[{}] {}'.format(self, msg)

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

            # TODO: deleting the user brings problems:
            # the deletion cascades down to DeploymentTask and DeploymentTaskItem
            # but these need to be conserved so all clients withdrawals can be tracked
            self.delete()

    def activate(self):
299
        if self._is_active:
300
301
302
303
304
            logger.error(self.msg('already activated'))
            return

        if self.user_type == 'oidcuser':
            self.is_active = True
305
            self._is_active = True
306
307
308
309
310
311
312
313
314
            self.save()

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

            logger.info(self.msg('activated'))

    # oidcuser: withdraw all credentials
    def deactivate(self):
315
        if not self._is_active:
316
317
318
319
320
            logger.error(self.msg('already deactivated'))
            return

        if self.user_type == 'oidcuser':
            self.is_active = False
321
            self._is_active = False
322
323
324
325
326
327
            self.save()

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

            logger.info(self.msg('deactivated'))
328
329


Lukas Burgey's avatar
Lukas Burgey committed
330
331
def construct_user(user_info):
    return User(
Lukas Burgey's avatar
Lukas Burgey committed
332
333
334
335
336
337
338
        sub=user_info['sub'],
        name=user_info['name'],
        first_name=user_info['given_name'],
        last_name=user_info['family_name'],
        email=user_info['email'],
        username=user_info['email'],
    )
Lukas Burgey's avatar
Lukas Burgey committed
339
340
341


class Site(models.Model):
342
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
343
344
345
        User,
        related_name='site',
    )
Lukas Burgey's avatar
Lukas Burgey committed
346
347
348
349
350
351
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)

    def __str__(self):
        return self.name

352
353
354
355
356
357
    # 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
358

Lukas Burgey's avatar
Lukas Burgey committed
359
360
361
362

class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
363
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
364
365
        Site,
        related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
366
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
367
368
369
        Group,
        related_name='services',
        blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
370
371

    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
372
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
373
374
375


class SSHPublicKey(models.Model):
Lukas Burgey's avatar
Lukas Burgey committed
376
377
378
379
380
381
382
    name = models.CharField(
        max_length=150,
        unique=True,
    )
    key = models.TextField(
        max_length=1000
    )
Lukas Burgey's avatar
Lukas Burgey committed
383
    # hidden field at the user
Lukas Burgey's avatar
Lukas Burgey committed
384
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
385
386
387
        User,
        related_name='_ssh_keys',
    )
Lukas Burgey's avatar
Lukas Burgey committed
388

Lukas Burgey's avatar
Lukas Burgey committed
389
390
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
391
392
393
        default=False,
        editable=False,
    )
394

Lukas Burgey's avatar
Lukas Burgey committed
395
396
    def msg(self, msg):
        return '[SSHPublicKey:{}] {}'.format(self, msg)
397

398
399
400
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
401
    def delete_key(self):
Lukas Burgey's avatar
Lukas Burgey committed
402
403
        if (not self.tasks.exists() and not self.deployments.exists()):
            logger.info(self.msg('Direct deletion of key'))
404
405
406
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
407
        logger.info(self.msg('Deletion of key started'))
408
409
410
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
411
        # delete implies withdrawing the key from all clients
412
413
414
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
415
416
    # 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
417
418
419
        if (self.deleted and not self.tasks.exists()):
            logger.info(self.msg(
                'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
420
421
422
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
423
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
424
425
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
426
427
428
        return self.name


429
# Deployment describes the credential state per user as it is supposed to be
430
431
432
433
#
# (exception: if is_active=False the ssh_keys contain the keys to be deployed
# if the deployment is reactivated)
#
434
435
# 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
436
437
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
438
439
440
441
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
442
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
443
444
445
446
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
447
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
448
449
450
451
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
452
    ssh_keys_to_withdraw = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
453
454
455
456
        SSHPublicKey,
        related_name='withdrawn_deployments',
        blank=True,
    )
457
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
458
459
        default=True,
    )
460

461
462
463
    @property
    def withdrawals(self):
        return self.tasks.filter(action='withdraw')
Lukas Burgey's avatar
Lukas Burgey committed
464

465
466
467
    @property
    def deploys(self):
        return self.tasks.filter(action='deploy')
Lukas Burgey's avatar
Lukas Burgey committed
468

469
470
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
471

472
473
    def msg(self, msg):
        return '[Deployment:{}] {}'.format(self, msg)
474

475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
            logger.error(self.msg('already active'))
            return

        logger.debug(self.msg(str(self.ssh_keys.all())))
        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
        logger.info(self.msg('activated'))

    # withdraw all credentials
    def deactivate(self):
        if not self.is_active:
            logger.error(self.msg('already deactivated'))
            return

        self.is_active = False
496
        self.save()
497

498
499
500
501
502
503
504
505
        for key in self.ssh_keys.all():
            self._withdraw_key(key)

        logger.info(self.msg('deactivated'))

    # only deploy the key
    def _deploy_key(self, key):
        # delete outstanding tasks which are made obsolete by this task
506
        for withdrawal in self.withdrawals.filter(key=key):
Lukas Burgey's avatar
Lukas Burgey committed
507
508
            logger.debug(withdrawal.msg('now obsolete'))
            withdrawal.delete()
509
510
511

        # generate task
        task = DeploymentTask(
Lukas Burgey's avatar
Lukas Burgey committed
512
513
514
515
            action='deploy',
            deployment=self,
            key=key,
        )
516
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
517
        logger.debug(task.msg('generated'))
518
519
520
521

        # generate task items
        for site in self.service.site.all():
            deploy = DeploymentTaskItem(
Lukas Burgey's avatar
Lukas Burgey committed
522
523
524
                task=task,
                site=site,
            )
525
            deploy.save()
Lukas Burgey's avatar
Lukas Burgey committed
526
            logger.debug(deploy.msg('generated'))
527
528
529

        # publish the task
        task.publish()
530

531
532
    def _withdraw_key(self, key):
        # delete outstanding tasks which are made obsolete by this task
533
        for deploy in self.deploys.filter(key=key):
Lukas Burgey's avatar
Lukas Burgey committed
534
535
            logger.debug(deploy.msg("now obsolete"))
            deploy.delete()
Lukas Burgey's avatar
Lukas Burgey committed
536

537
538
        # generate task
        task = DeploymentTask(
Lukas Burgey's avatar
Lukas Burgey committed
539
540
541
542
            action='withdraw',
            deployment=self,
            key=key,
        )
543
        task.save()
Lukas Burgey's avatar
Lukas Burgey committed
544
        logger.debug(task.msg('generated'))
Lukas Burgey's avatar
Lukas Burgey committed
545

546
547
548
        # generate task items
        for site in self.service.site.all():
            withdrawal = DeploymentTaskItem(
Lukas Burgey's avatar
Lukas Burgey committed
549
550
551
                task=task,
                site=site,
            )
552
            withdrawal.save()
Lukas Burgey's avatar
Lukas Burgey committed
553
            logger.debug(withdrawal.msg('generated'))
554

555
556
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
557

558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
    # deploy key and track changes in the key lists
    def deploy_key(self, key):
        if not self.is_active:
            logger.error(self.msg('cannot deploy while deactivated'))
            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:
            logger.error(self.msg('cannot withdraw while deactivated'))
            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
586

587
588
class DeploymentTask(models.Model):
    ACTION_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
589
590
591
        ('deploy', 'deploy'),
        ('withdraw', 'withdraw'),
    )
592
    action = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
593
594
595
        max_length=10,
        choices=ACTION_CHOICES,
    )
596
    key = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
597
598
599
600
        SSHPublicKey,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
601
    deployment = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
602
603
604
605
        Deployment,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
606
607
608
609
610
611
612
613
614

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

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

615
    def __str__(self):
616
        return "{}:{}:{} - {}".format(
Lukas Burgey's avatar
Lukas Burgey committed
617
618
619
620
621
            self.deployment.service,
            self.deployment.user,
            self.key,
            self.action,
        )
622

Lukas Burgey's avatar
Lukas Burgey committed
623
624
    def msg(self, msg):
        return '[DeploymentTask:{}] {}'.format(self, msg)
625
626
627
628
629
630

    def publish(self):
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

        rabbitmq_instance().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
631
632
633
            self.service,
            msg,
        )
634
635
636

    # 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
637
638
639
        item = self.task_items.get(site=site)
        logger.debug(item.msg('done'))
        item.delete()
640
641
642
643
644
645

        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
646
        logger.info(self.msg('done'))
Lukas Burgey's avatar
Lukas Burgey committed
647
        self.delete()
648
649
650
651
652
653
654
655

        # 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
656
657
658
659
        DeploymentTask,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
660
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
661
662
663
664
        Site,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
665

Lukas Burgey's avatar
Lukas Burgey committed
666
    def __str__(self):
667
        return "{}@{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
668
669
670
            self.task,
            self.site,
        )
671

Lukas Burgey's avatar
Lukas Burgey committed
672
673
    def msg(self, msg):
        return '[DeploymentTaskItem:{}] {}'.format(self, msg)
674

Lukas Burgey's avatar
Lukas Burgey committed
675

676
677
678
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
679
680
681
682
683
684
685
686

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if instance.user_type == 'apiclient' and created:
        Token.objects.create(user=instance)


@receiver(post_save, sender=Site)
Lukas Burgey's avatar
Lukas Burgey committed
687
def register_at_rabbitmq(sender, instance=None, created=False, **kwargs):
Lukas Burgey's avatar
Lukas Burgey committed
688
689
690
691
692
693
694
695
696
697
698
    if not created:
        return

    RabbitMQInstance().register_site(instance)


@receiver(pre_delete, sender=Site)
def deregister_at_rabbitmq(
        sender, instance=None, **kwargs):

    RabbitMQInstance().deregister_site(instance)
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716


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

    if not instance.is_active and instance._is_active:
        instance.deactivate()


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

    if instance.is_active and not instance._is_active:
        instance.activate()