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

import json
import logging
Lukas Burgey's avatar
Lukas Burgey committed
6

Lukas Burgey's avatar
Lukas Burgey committed
7
from django.contrib.auth.models import AbstractUser, Group
8
from django.core.cache import cache
Lukas Burgey's avatar
Lukas Burgey committed
9
from django.db import models
Lukas Burgey's avatar
Lukas Burgey committed
10
from django.db.models.signals import post_save
Lukas Burgey's avatar
Lukas Burgey committed
11
from django.dispatch import receiver
12
from django_mysql.models import JSONField
Lukas Burgey's avatar
Lukas Burgey committed
13
14
15
16
from pika.exceptions import ConnectionClosed
import pika
from requests.auth import HTTPBasicAuth

Lukas Burgey's avatar
Lukas Burgey committed
17
from .auth.v1.models import OIDCConfig
Lukas Burgey's avatar
Lukas Burgey committed
18

Lukas Burgey's avatar
Lukas Burgey committed
19
LOGGER = logging.getLogger(__name__)
20
21

RABBITMQ_CONNECTION = None
22

23
24
25
26
27
28
29
30
STATE_CHOICES = (
    ('deployment_pending', 'Deployment Pending'),
    ('removal_pending', 'Removal Pending'),
    ('deployed', 'Deployed'),
    ('not_deployed', 'Not Deployed'),
    ('questionnaire', 'Questionnaire'),
)

Lukas Burgey's avatar
Lukas Burgey committed
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 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
55
56
57
def exchanges_default():
    return []

58
59
60
61
62
63
64
65
66
67
68
69
70
# takes a list of states
# return '<state>' if all states are equal to '<state>'
# else it returns 'mixed'
def analyze_states(states):
    _state = ''
    for state in states:
        if _state == '':
            _state = state
        elif _state != state:
            return 'mixed'

    return _state

71

Lukas Burgey's avatar
Lukas Burgey committed
72
73
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
74
class RabbitMQInstance(SingletonModel):
Lukas Burgey's avatar
Lukas Burgey committed
75
    host = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
76
77
78
        max_length=150,
        default='localhost',
    )
Lukas Burgey's avatar
Lukas Burgey committed
79
80
81
82
    vhost = models.CharField(
        max_length=150,
        default='%2f',
    )
Lukas Burgey's avatar
Lukas Burgey committed
83
84
85
86
    exchanges = JSONField(
        default=exchanges_default,
        null=True,
        blank=True,
Lukas Burgey's avatar
Lukas Burgey committed
87
    )
Lukas Burgey's avatar
Lukas Burgey committed
88
    port = models.IntegerField(
Lukas Burgey's avatar
Lukas Burgey committed
89
        default=15672,
Lukas Burgey's avatar
Lukas Burgey committed
90
    )
Lukas Burgey's avatar
Lukas Burgey committed
91
    username = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
92
93
94
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
95
    password = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
96
97
98
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
99
100
101
102

    def __str__(self):
        return self.host

Lukas Burgey's avatar
Lukas Burgey committed
103
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
104
        return '[RabbitMQ:{}] {}'.format(self.host, msg)
Lukas Burgey's avatar
Lukas Burgey committed
105
106
107
108

    @property
    def auth(self):
        return HTTPBasicAuth(
Lukas Burgey's avatar
Lukas Burgey committed
109
            self.username,
Lukas Burgey's avatar
Lukas Burgey committed
110
            self.password,
Lukas Burgey's avatar
Lukas Burgey committed
111
        )
Lukas Burgey's avatar
Lukas Burgey committed
112

113
114
    def _init_exchanges(self, channel):
        channel.exchange_declare(
Lukas Burgey's avatar
Lukas Burgey committed
115
116
117
118
119
120
121
            exchange='deployments',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        channel.exchange_declare(
            exchange='sites',
122
123
124
125
126
127
128
129
130
131
132
133
134
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        channel.exchange_declare(
            exchange='update',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )

    def _init_connection(self):
        global RABBITMQ_CONNECTION
135
        #LOGGER.debug('Opening new BlockingConnection')
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
        RABBITMQ_CONNECTION = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=self.host,
                ssl=True,
                heartbeat_interval=60,
            )
        )
        return RABBITMQ_CONNECTION

    @property
    def _connection(self):
        global RABBITMQ_CONNECTION
        if RABBITMQ_CONNECTION is not None:
            if RABBITMQ_CONNECTION.is_open:
                return RABBITMQ_CONNECTION
            elif RABBITMQ_CONNECTION.is_closing:
                RABBITMQ_CONNECTION.close()

        connection = self._init_connection()
        channel = connection.channel()
        self._init_exchanges(connection.channel())
        channel.close()
        RABBITMQ_CONNECTION = connection
        return connection

Lukas Burgey's avatar
Lukas Burgey committed
161
    @property
162
    def _channel(self):
Lukas Burgey's avatar
Lukas Burgey committed
163
164
165
166
167
168
169
170
        try:
            channel = self._connection.channel()
            channel.confirm_delivery()
            return channel
        except ConnectionClosed as exception:
            LOGGER.error(self.msg('ConnectionClosed: ' + str(exception)))
            self._init_connection()
            return self._channel
171
172
173

    def _publish(self, exchange, routing_key, body):
        channel = self._channel
174
        channel.basic_publish(
175
176
177
178
179
180
            exchange=exchange,
            routing_key=routing_key,
            body=body,
            properties=pika.BasicProperties(
                delivery_mode=1,
            ),
Lukas Burgey's avatar
Lukas Burgey committed
181
        )
182
        channel.close()
183

184
    # PUBLIC API
185
    def publish_by_service(self, service, msg):
186
        self._publish(
Lukas Burgey's avatar
Lukas Burgey committed
187
            'deployments',
188
189
190
            service.routing_key,
            msg,
        )
Lukas Burgey's avatar
Lukas Burgey committed
191

Lukas Burgey's avatar
Lukas Burgey committed
192
193
194
195
196
197
198
    def publish_by_site(self, site, msg):
        self._publish(
            'sites',
            site.name,
            msg,
        )

Lukas Burgey's avatar
Lukas Burgey committed
199
    def publish_to_user(self, user, msg):
200
201
202
        self._publish(
            'update',
            str(user.id),
203
            json.dumps(msg),
204
        )
205

Lukas Burgey's avatar
Lukas Burgey committed
206

207
208
def user_info_default():
    return {}
209
210
211
212
def questionnaire_default():
    return {}
def credential_default():
    return {}
213
214


Lukas Burgey's avatar
Lukas Burgey committed
215
class User(AbstractUser):
216
    TYPE_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
217
218
219
220
        ('apiclient', 'API-Client'),
        ('oidcuser', 'OIDC User'),
        ('admin', 'Admin'),
    )
221
    user_type = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
222
223
        max_length=20,
        choices=TYPE_CHOICES,
Lukas Burgey's avatar
Lukas Burgey committed
224
        default='apiclient',
Lukas Burgey's avatar
Lukas Burgey committed
225
    )
226
227
228
229
    sub = models.CharField(
        max_length=150,
        blank=True,
        null=True,
230
        editable=False,
231
232
233
234
235
236
237
238
239
240
241
242
    )
    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
243
244
245
246
247
    # the idp which authenticated the user
    idp = models.ForeignKey(
        OIDCConfig,
        related_name='users',
        on_delete=models.CASCADE,
248
249
250
        blank=True,
        null=True,
        editable=False,
Lukas Burgey's avatar
Lukas Burgey committed
251
    )
252
253
254
255
    userinfo = JSONField(
        default=user_info_default,
        null=True,
        blank=True,
256
        editable=False,
257
    )
Lukas Burgey's avatar
Lukas Burgey committed
258

Lukas Burgey's avatar
Lukas Burgey committed
259
260
261
262
    # returns the user as identified by userinfo and idp
    # if the user does not exists
    @classmethod
    def get_user(cls, userinfo, idp):
Lukas Burgey's avatar
Lukas Burgey committed
263
        if 'sub' not in userinfo:
Lukas Burgey's avatar
Lukas Burgey committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
            raise Exception('get_user needs a userinfo which contains the users subject')

        query_result = cls.objects.filter(
            sub=userinfo['sub'],
            idp=idp,
        )
        if not query_result.exists():
            return cls.construct_from_userinfo(userinfo, idp)

        if len(query_result) > 1:
            return Exception('Two user instances with same subject from the same idp')

        # TODO update the users userinfo when it changes
        # TODO update the users groupinfo when it changes
        return query_result.first()

    @classmethod
    def construct_from_userinfo(cls, userinfo, idp):
282
        LOGGER.debug('Constructing User from:\n%s', userinfo)
Lukas Burgey's avatar
Lukas Burgey committed
283
284
285
286
287
288

        if 'sub' not in userinfo:
            raise Exception('Missing attribute in userinfo: sub')
        sub = userinfo['sub']

        if 'email' not in userinfo:
289
            username = sub
Lukas Burgey's avatar
Lukas Burgey committed
290
291
        else:
            username = userinfo['email']
292
            email = userinfo['email']
Lukas Burgey's avatar
Lukas Burgey committed
293
294
295
296
297

        user = cls(
            user_type='oidcuser',
            username=username,
            sub=sub,
298
            email=email,
Lukas Burgey's avatar
Lukas Burgey committed
299
300
301
302
            idp=idp,
            userinfo=userinfo,
        )
        user.save()
Lukas Burgey's avatar
Lukas Burgey committed
303
304
305
306
307
308

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

Lukas Burgey's avatar
Lukas Burgey committed
309
310
311
312
313
314
315
316
317
318
319
320
        return user

    @classmethod
    def construct_client(cls, username, password):
        LOGGER.debug('APICLIENT: new client %s', username)
        client = cls(
            username=username,
            user_type='apiclient',
        )
        client.set_password(password)
        return client

Lukas Burgey's avatar
Lukas Burgey committed
321
    # we hide deleted keys here
322
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
323
324
325
326
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

327
328
329
330
    @property
    def is_active_at_clients(self):
        return self._is_active

331
332
333
    def __str__(self):
        if self.user_type == 'admin':
            return 'ADMIN {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
334
        elif self.user_type == 'oidcuser':
335
336
337
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
338
        elif self.user_type == 'apiclient':
339
340
341
342
343
            try:
                return 'APICLIENT {}@{}'.format(self.username, self.site)
            except:
                return 'APICLIENT {}'.format(self.username)

Lukas Burgey's avatar
Lukas Burgey committed
344
345
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
346

Lukas Burgey's avatar
Lukas Burgey committed
347
    def msg(self, msg):
348
349
350
351
352
353
354
        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
355
            # FIXME: deleting the user brings problems:
Lukas Burgey's avatar
Lukas Burgey committed
356
            # the deletion cascades down to DeploymentState and DeploymentStateItem
357
            # but these need to be conserved so all clients removals can be tracked
Lukas Burgey's avatar
Lukas Burgey committed
358
            LOGGER.info(self.msg('Deleting'))
359
360
361
            self.delete()

    def activate(self):
362
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
363
            LOGGER.error(self.msg('already activated'))
364
365
            return

Lukas Burgey's avatar
Lukas Burgey committed
366
367
368
369
        self.is_active = True
        self._is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))
370

Lukas Burgey's avatar
Lukas Burgey committed
371
372
        # oidcuser: deploy the according credentials
        if self.user_type == 'oidcuser':
373
374
375
376
            for dep in self.deployments.all():
                dep.activate()

    def deactivate(self):
377
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
378
            LOGGER.error(self.msg('already deactivated'))
379
380
            return

Lukas Burgey's avatar
Lukas Burgey committed
381
382
383
384
385
386
        self.is_active = False
        self._is_active = False
        self.save()
        LOGGER.info(self.msg('deactivated'))

        # oidcuser: withdraw all credentials
387
388
389
390
391
        if self.user_type == 'oidcuser':

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

Lukas Burgey's avatar
Lukas Burgey committed
392

Lukas Burgey's avatar
Lukas Burgey committed
393
394
395
396
397
398
399
400
401
402
403
404
# authorisation groups
class AuthGroup(models.Model):
    name = models.CharField(
        max_length=200,
    )
    users = models.ManyToManyField(
        User,
        related_name='auth_groups',
        blank=True,
    )


Lukas Burgey's avatar
Lukas Burgey committed
405
class Site(models.Model):
406
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
407
408
        User,
        related_name='site',
409
410
411
412
413
414
415
416
417
418
419
        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
420
    )
Lukas Burgey's avatar
Lukas Burgey committed
421

Lukas Burgey's avatar
Lukas Burgey committed
422
423
424
425
    @property
    def pending_tasks(self):
        return [item.parent for item in self.state_items.all()]

Lukas Burgey's avatar
Lukas Burgey committed
426
427
428
429
430
    def __str__(self):
        return self.name


class Service(models.Model):
431
432
433
434
435
436
437
438
    name = models.CharField(
        max_length=150,
        unique=True,
    )
    description = models.TextField(
        max_length=300,
        blank=True,
    )
439
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
440
        Site,
441
442
        related_name='services',
    )
Lukas Burgey's avatar
Lukas Burgey committed
443
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
444
445
        Group,
        related_name='services',
446
447
        blank=True,
    )
Lukas Burgey's avatar
Lukas Burgey committed
448

449
450
451
452
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
453
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
454
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
455
456
457


class SSHPublicKey(models.Model):
Lukas Burgey's avatar
Lukas Burgey committed
458
459
460
461
462
463
    name = models.CharField(
        max_length=150,
    )
    key = models.TextField(
        max_length=1000
    )
Lukas Burgey's avatar
Lukas Burgey committed
464
    # hidden field at the user
465
    # TODO checks: if the user is null
Lukas Burgey's avatar
Lukas Burgey committed
466
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
467
468
        User,
        related_name='_ssh_keys',
469
470
        on_delete=models.SET_NULL,
        null=True,
Lukas Burgey's avatar
Lukas Burgey committed
471
    )
Lukas Burgey's avatar
Lukas Burgey committed
472

473
    # has the user triggered the deletion of this key?
Lukas Burgey's avatar
Lukas Burgey committed
474
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
475
476
477
        default=False,
        editable=False,
    )
478

479
480
481
482
    def states(self):
        states = []
        for state in self.states.all():
            states.append(state.states)
483

484
485
486
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
487
    def delete_key(self):
488
        # if this key is not deployed anywhere we delete it now
Lukas Burgey's avatar
Lukas Burgey committed
489
        if analyze_states(self.states.all()) == 'not_deployed':
Lukas Burgey's avatar
Lukas Burgey committed
490
            LOGGER.info(self.msg('Direct deletion of key'))
491
492
493
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
494
        LOGGER.info(self.msg('Deletion of key started'))
495
496
497
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
498
        # delete implies withdrawing the key from all clients
499
        for deployment in self.deployments.all():
500
            deployment.remove_key(self)
501

Lukas Burgey's avatar
Lukas Burgey committed
502
503
    # 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
504
        if (self.deleted and not self.states.exists()):
505
            LOGGER.info(self.msg( 'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
506
507
508
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
509
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
510
511
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
512
513
        return self.name

514
515
516
    def msg(self, msg):
        return '[SSHKey:{}] {}'.format(self, msg)

Lukas Burgey's avatar
Lukas Burgey committed
517

518
# Deployment describes the credential state per user (and site) as it is supposed to be
519
520
521
522
#
# (exception: if is_active=False the ssh_keys contain the keys to be deployed
# if the deployment is reactivated)
#
Lukas Burgey's avatar
Lukas Burgey committed
523
524
# DeploymentState is what is sent to the clients via rabbitmq
# The DeploymentStateItem track the acknowledgements from the clients
Lukas Burgey's avatar
Lukas Burgey committed
525
526
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
527
528
529
530
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
531
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
532
533
534
535
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
536
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
537
538
539
540
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
541
    ssh_keys_to_withdraw = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
542
543
544
545
        SSHPublicKey,
        related_name='withdrawn_deployments',
        blank=True,
    )
546
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
547
548
        default=True,
    )
549

Lukas Burgey's avatar
Lukas Burgey committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    # get a deployment for a user/service.
    # if it does not exist it is created
    @classmethod
    def get_deployment(cls, user, service):
        query = cls.objects.filter(
            user=user,
            service=service,
        )
        if query.exists():
            return query.first()

        deployment = cls(
            user=user,
            service=service,
        )
        deployment.save()
566
        LOGGER.debug(deployment.msg('created'))
Lukas Burgey's avatar
Lukas Burgey committed
567
568
        return deployment

569
570
571
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
572
            LOGGER.error(self.msg('already active'))
573
574
            return

Lukas Burgey's avatar
Lukas Burgey committed
575
        LOGGER.debug(self.msg(str(self.ssh_keys.all())))
576
577
578
579
580
        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
Lukas Burgey's avatar
Lukas Burgey committed
581
        LOGGER.info(self.msg('activated'))
582
583
584
585

    # withdraw all credentials
    def deactivate(self):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
586
            LOGGER.error(self.msg('already deactivated'))
587
588
589
            return

        self.is_active = False
590
        self.save()
591

592
        for key in self.ssh_keys.all():
593
            self._remove_key(key)
594

Lukas Burgey's avatar
Lukas Burgey committed
595
        LOGGER.info(self.msg('deactivated'))
596
597
598
599

    # 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
600
            LOGGER.error(self.msg('cannot deploy while deactivated'))
601
602
603
604
605
606
607
608
609
610
611
            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
612
    def remove_key(self, key):
613
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
614
            LOGGER.error(self.msg('cannot withdraw while deactivated'))
615
616
617
618
619
620
621
622
            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()

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
        self._remove_key(key)

    # only deploy the key
    def _deploy_key(self, key):
        state = DeploymentState.get_state(
            deployment=self,
            key=key,
        )
        state.save()
        state.deploy()

    def _remove_key(self, key):
        state = DeploymentState.get_state(
            deployment=self,
            key=key,
        )
        state.save()
        state.remove()
641

642
643
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
Lukas Burgey's avatar
Lukas Burgey committed
644

645
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
646
        return '[Depl.m:{}] {}'.format(self, msg)
647
648


Lukas Burgey's avatar
Lukas Burgey committed
649
# DeploymentState: knows:
650
# user, service, key, state_target
Lukas Burgey's avatar
Lukas Burgey committed
651
class DeploymentState(models.Model):
652
    key = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
653
        SSHPublicKey,
Lukas Burgey's avatar
Lukas Burgey committed
654
        related_name='states',
655
656
        # deleting the key leaves us without references about its deployments
        # we _HAVE_ to remove all deployments prior to deleting key
Lukas Burgey's avatar
Lukas Burgey committed
657
658
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
659
    deployment = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
660
        Deployment,
Lukas Burgey's avatar
Lukas Burgey committed
661
        related_name='states',
Lukas Burgey's avatar
Lukas Burgey committed
662
663
        on_delete=models.CASCADE,
    )
664
665
    # TODO is this relation needed?
    # State does relate to Deployment which relates to User
666
667
    user = models.ForeignKey(
        User,
Lukas Burgey's avatar
Lukas Burgey committed
668
        related_name='deployment_states',
669
670
        # TODO deleting the user leaves us without references about its deployments
        # we _HAVE_ to remove all deployments prior to deleting site user
671
672
        on_delete=models.CASCADE,
    )
673
674
675
676
677
678
    # which state do we currently want to reach?
    state_target = models.CharField(
        max_length=50,
        choices=STATE_CHOICES,
        default='deployed',
    )
Lukas Burgey's avatar
Lukas Burgey committed
679

680
681
682
    @property
    def states(self):
        return [item.state for item in self.state_items.all()]
683

684
685
686
    @property
    def state(self):
        return analyze_states(self.states)
687

688
689
690
    @property
    def service(self):
        return self.deployment.service
Lukas Burgey's avatar
Lukas Burgey committed
691

692
693
694
    @property
    def target_reached(self):
        return self.state_target == self.state
Lukas Burgey's avatar
Lukas Burgey committed
695

696
697
    # get a deployment for a user/service.
    # if it does not exist it is created
Lukas Burgey's avatar
Lukas Burgey committed
698
    @classmethod
699
700
701
702
703
704
    def get_state(cls, deployment, key):
        # check if a state does already exist
        query = cls.objects.filter(
            deployment=deployment,
            key=key,
        )
705
        if query.exists():
706
            return query.first()
707

708
709
710
711
712
713
714
715
        # create new state if not
        state = cls(
            deployment=deployment,
            user=deployment.user,
            key=key,
        )
        state.save()
        LOGGER.debug(state.msg('created'))
716

717
718
719
720
        # generate state items
        for site in deployment.service.site.all():
            deploy = DeploymentStateItem(
                parent=state,
721
                user=deployment.user,
722
                site=site,
723
            )
724
            deploy.save()
725

726
        return state
Lukas Burgey's avatar
Lukas Burgey committed
727

728
729
730
731
732
    def deploy(self):
        self._set_target('deployed')
        for item in self.state_items.all():
            item.user_deploy()
        self.publish_to_client()
Lukas Burgey's avatar
Lukas Burgey committed
733
        # each state item publishes its state to the user
734

735
736
737
738
739
    def remove(self):
        self._set_target('not_deployed')
        for item in self.state_items.all():
            item.user_remove()
        self.publish_to_client()
Lukas Burgey's avatar
Lukas Burgey committed
740
        # each state item publishes its state to the user
741

742
    def publish_to_client(self):
Lukas Burgey's avatar
Lukas Burgey committed
743
        # mitigating circular dependencies here
Lukas Burgey's avatar
Lukas Burgey committed
744
745
        from .clientapi.serializers import DeploymentStateSerializer
        msg = json.dumps(DeploymentStateSerializer(self).data)
746

747
        RabbitMQInstance.load().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
748
749
750
            self.service,
            msg,
        )
751
    # update the state of the remote webpage
752
    def publish_to_user(self):
Lukas Burgey's avatar
Lukas Burgey committed
753
        from .frontend.views import user_state
754
        content = {
Lukas Burgey's avatar
Lukas Burgey committed
755
            'user_state': user_state(self.user),
756
        }
Lukas Burgey's avatar
Lukas Burgey committed
757
        RabbitMQInstance.load().publish_to_user(
758
759
760
761
            self.user,
            content,
        )

762
763
    def msg(self, msg):
        return '[DState:{}] {}'.format(self, msg)
764

765
766
767
768
    def _set_target(self, target):
        self.state_target = target
        LOGGER.debug(self.msg('target: '+target))
        self.save()
769

770
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
771
        return "{}:{}#{}".format(
772
            self.deployment.service,
Lukas Burgey's avatar
Lukas Burgey committed
773
            self.key,
774
            self.id,
775
776
        )

777

Lukas Burgey's avatar
Lukas Burgey committed
778
# DeploymentStateItem: knows:
779
# user, service, key, state_target, _and_ site
Lukas Burgey's avatar
Lukas Burgey committed
780
class DeploymentStateItem(models.Model):
781
    parent = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
782
783
        DeploymentState,
        related_name='state_items',
Lukas Burgey's avatar
Lukas Burgey committed
784
785
        on_delete=models.CASCADE,
    )
786
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
787
        Site,
Lukas Burgey's avatar
Lukas Burgey committed
788
        related_name='state_items',
789
790
        # TODO deleting the site leaves us without references about its deployments
        # we _HAVE_ to remove all deployments prior to deleting a site
Lukas Burgey's avatar
Lukas Burgey committed
791
792
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
793
794
    user = models.ForeignKey(
        User,
Lukas Burgey's avatar
Lukas Burgey committed
795
        related_name='deployment_state_items',
796
797
        # TODO deleting the user leaves us without references about its deployments
        # we _HAVE_ to remove all deployments prior to deleting site user
Lukas Burgey's avatar
Lukas Burgey committed
798
799
        on_delete=models.CASCADE,
    )
800
    state = models.CharField(
801
        max_length=50,
802
        choices=STATE_CHOICES,
803
        default='deployment_pending',
804
    )
Lukas Burgey's avatar
Lukas Burgey committed
805

806
    # questions for the user (needed for deployment
807
808
809
810
811
    questionnaire = JSONField(
        default=questionnaire_default,
        null=True,
        blank=True,
    )
812
813
    # credentials for the service
    # only valid when state == deployed
814
815
816
817
818
819
    credentials = JSONField(
        default=credential_default,
        null=True,
        blank=True,
    )

Lukas Burgey's avatar
Lukas Burgey committed
820
821
    @property
    def service(self):
822
        return self.parent.service
Lukas Burgey's avatar
Lukas Burgey committed
823
824
825

    @property
    def key(self):
826
        return self.parent.key
Lukas Burgey's avatar
Lukas Burgey committed
827

828
829
830
831
832
833
    # STATE transitions
    # user: deployment requested
    def user_deploy(self):
        if self.state == 'removal_pending':
            self._set_state('deployed')
            return
Lukas Burgey's avatar
Lukas Burgey committed
834
835
836
        if self.state == 'deployed':
            LOGGER.info(self.msg('ignoring invalid state transition user_deploy'))
            return
837

838
        self._set_state('deployment_pending')
839

840
841
842
843
844
845
846
847
    # user: removal requested
    def user_remove(self):
        if (
                self.state == 'deployment_pending'
                or self.state == 'questionnaire'
        ):
            self._set_state('not_deployed')
            return
848

Lukas Burgey's avatar
Lukas Burgey committed
849
850
851
852
        if self.state == 'not_deployed':
            LOGGER.info(self.msg('ignoring invalid state transition user_remove'))
            return

853
        self._set_state('removal_pending')
854

855
856
857
858
    # user: questionnaire answered
    def user_answers(self, answers=None):
        self.questionnaire = answers
        self._set_state('deployment_pending')
Lukas Burgey's avatar
Lukas Burgey committed
859
        self.parent.publish_to_client()
860

861
862
863
864
    # client: deployed
    def client_deployed(self, credentials=None):
        self.credentials = credentials
        self._set_state('deployed')
865

866
867
868
    # client: removed
    def client_removed(self):
        self._set_state('not_deployed')
869

870
871
    # client: questionnaire
    def client_questionnaire(self, questionnaire=None):
872
        self.questionnaire = questionnaire
873
        self._set_state('questionnaire')
Lukas Burgey's avatar
Lukas Burgey committed
874

875
876
877
878
879
880
881
882
883
    def msg(self, msg):
        return '[DSItem:{}] {}'.format(self, msg)

    def _set_state(self, state):
        self.state = state
        self.save()
        LOGGER.debug(self.msg('state: '+self.state))
        self.parent.publish_to_user()

Lukas Burgey's avatar
Lukas Burgey committed
884

Lukas Burgey's avatar
Lukas Burgey committed
885
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
886
        return "{}:{}@{}#{}".format(
887
            self.parent.service,
Lukas Burgey's avatar
Lukas Burgey committed
888
            self.parent.key,
Lukas Burgey's avatar
Lukas Burgey committed
889
            self.site,
890
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
891
        )
892
893
894
895
896


#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
897

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

903
    if not instance.is_active and instance.is_active_at_clients:
904
905
906
907
908
909
910
911
        instance.deactivate()


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

912
    if instance.is_active and not instance.is_active_at_clients:
913
        instance.activate()