models.py 24.4 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
263
264
265
266
267
268
269
270
271
272
273
274
275
    @property
    def deployment_states(self):
        states = []
        for deployment in self.deployments.all():
            for state in deployment.states.all():
                states.append(state)
        return states

    @property
    def deployment_state_items(self):
        items = []
        for state in self.deployment_states:
            for item in state.state_items.all():
                items.append(item)
        return items


Lukas Burgey's avatar
Lukas Burgey committed
276
277
278
279
    # 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
280
        if 'sub' not in userinfo:
Lukas Burgey's avatar
Lukas Burgey committed
281
282
            raise Exception('get_user needs a userinfo which contains the users subject')

Lukas Burgey's avatar
Lukas Burgey committed
283
        query = cls.objects.filter(
Lukas Burgey's avatar
Lukas Burgey committed
284
285
286
            sub=userinfo['sub'],
            idp=idp,
        )
Lukas Burgey's avatar
Lukas Burgey committed
287
        if not query.exists():
Lukas Burgey's avatar
Lukas Burgey committed
288
289
            return cls.construct_from_userinfo(userinfo, idp)

Lukas Burgey's avatar
Lukas Burgey committed
290
        if len(query) > 1:
Lukas Burgey's avatar
Lukas Burgey committed
291
292
            return Exception('Two user instances with same subject from the same idp')

Lukas Burgey's avatar
Lukas Burgey committed
293
294
295
296
297
298
        user = query.first()
        # update the users userinfo
        user.userinfo = userinfo
        user.save()

        return user
Lukas Burgey's avatar
Lukas Burgey committed
299
300
301

    @classmethod
    def construct_from_userinfo(cls, userinfo, idp):
302
        LOGGER.debug('Constructing User from:\n%s', userinfo)
Lukas Burgey's avatar
Lukas Burgey committed
303
304
305
306
307
308

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

        if 'email' not in userinfo:
309
            username = sub
Lukas Burgey's avatar
Lukas Burgey committed
310
311
        else:
            username = userinfo['email']
312
            email = userinfo['email']
Lukas Burgey's avatar
Lukas Burgey committed
313
314
315
316
317

        user = cls(
            user_type='oidcuser',
            username=username,
            sub=sub,
318
            email=email,
Lukas Burgey's avatar
Lukas Burgey committed
319
320
321
322
            idp=idp,
            userinfo=userinfo,
        )
        user.save()
Lukas Burgey's avatar
Lukas Burgey committed
323
324
325
326
327
328

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

Lukas Burgey's avatar
Lukas Burgey committed
329
330
331
332
333
334
335
336
337
338
339
340
        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
341
    # we hide deleted keys here
342
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
343
344
345
346
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

347
348
349
350
    @property
    def is_active_at_clients(self):
        return self._is_active

351
352
353
    def __str__(self):
        if self.user_type == 'admin':
            return 'ADMIN {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
354
        elif self.user_type == 'oidcuser':
355
356
357
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
358
        elif self.user_type == 'apiclient':
359
360
361
362
363
            try:
                return 'APICLIENT {}@{}'.format(self.username, self.site)
            except:
                return 'APICLIENT {}'.format(self.username)

Lukas Burgey's avatar
Lukas Burgey committed
364
365
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
366

Lukas Burgey's avatar
Lukas Burgey committed
367
    def msg(self, msg):
368
369
        return '[{}] {}'.format(self, msg)

Lukas Burgey's avatar
Lukas Burgey committed
370
    # oidcuser: remove and delete all credentials and delete the user
371
372
373
374
    def remove(self):
        if self.user_type == 'oidcuser':
            self.deactivate()

Lukas Burgey's avatar
Lukas Burgey committed
375
            # FIXME: deleting the user brings problems:
Lukas Burgey's avatar
Lukas Burgey committed
376
            # the deletion cascades down to DeploymentState and DeploymentStateItem
377
            # but these need to be conserved so all clients removals can be tracked
Lukas Burgey's avatar
Lukas Burgey committed
378
            LOGGER.info(self.msg('Deleting'))
379
380
381
            self.delete()

    def activate(self):
382
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
383
            LOGGER.error(self.msg('already activated'))
384
385
            return

Lukas Burgey's avatar
Lukas Burgey committed
386
387
388
389
        self.is_active = True
        self._is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))
390

Lukas Burgey's avatar
Lukas Burgey committed
391
392
        # oidcuser: deploy the according credentials
        if self.user_type == 'oidcuser':
393
394
395
396
            for dep in self.deployments.all():
                dep.activate()

    def deactivate(self):
397
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
398
            LOGGER.error(self.msg('already deactivated'))
399
400
            return

Lukas Burgey's avatar
Lukas Burgey committed
401
402
403
404
405
        self.is_active = False
        self._is_active = False
        self.save()
        LOGGER.info(self.msg('deactivated'))

Lukas Burgey's avatar
Lukas Burgey committed
406
        # oidcuser: remove all credentials
407
408
409
410
411
        if self.user_type == 'oidcuser':

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

Lukas Burgey's avatar
Lukas Burgey committed
412

Lukas Burgey's avatar
Lukas Burgey committed
413
414
415
416
417
418
419
420
421
422
423
424
# 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
425
class Site(models.Model):
426
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
427
428
        User,
        related_name='site',
429
430
431
432
433
434
435
436
437
438
439
        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
440
    )
Lukas Burgey's avatar
Lukas Burgey committed
441

Lukas Burgey's avatar
Lukas Burgey committed
442
443
444
445
    @property
    def pending_tasks(self):
        return [item.parent for item in self.state_items.all()]

Lukas Burgey's avatar
Lukas Burgey committed
446
447
448
449
450
    def __str__(self):
        return self.name


class Service(models.Model):
451
452
453
454
455
456
457
458
    name = models.CharField(
        max_length=150,
        unique=True,
    )
    description = models.TextField(
        max_length=300,
        blank=True,
    )
459
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
460
        Site,
461
462
        related_name='services',
    )
Lukas Burgey's avatar
Lukas Burgey committed
463
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
464
465
        Group,
        related_name='services',
466
467
        blank=True,
    )
Lukas Burgey's avatar
Lukas Burgey committed
468

469
470
471
472
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
473
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
474
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
475
476
477


class SSHPublicKey(models.Model):
Lukas Burgey's avatar
Lukas Burgey committed
478
479
480
481
482
483
    name = models.CharField(
        max_length=150,
    )
    key = models.TextField(
        max_length=1000
    )
Lukas Burgey's avatar
Lukas Burgey committed
484
    # hidden field at the user
485
    # TODO checks: if the user is null
Lukas Burgey's avatar
Lukas Burgey committed
486
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
487
488
        User,
        related_name='_ssh_keys',
489
490
        on_delete=models.SET_NULL,
        null=True,
Lukas Burgey's avatar
Lukas Burgey committed
491
    )
Lukas Burgey's avatar
Lukas Burgey committed
492

493
    # has the user triggered the deletion of this key?
Lukas Burgey's avatar
Lukas Burgey committed
494
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
495
496
497
        default=False,
        editable=False,
    )
498

Lukas Burgey's avatar
Lukas Burgey committed
499
500
    @property
    def deployed_anywhere(self):
501
        for state in self.states.all():
Lukas Burgey's avatar
Lukas Burgey committed
502
503
504
505
            for item in state.state_items.all():
                if item.state == 'deployed' or item.state == 'removal_pending':
                    return True
        return False
506

Lukas Burgey's avatar
Lukas Burgey committed
507
    # does not directly delete the key if the key is deployed or removen
508
    # somewhere
Lukas Burgey's avatar
Lukas Burgey committed
509
    # the receiver 'delete_removen_ssh_key' does the actual deletion
510
    def delete_key(self):
511
        # if this key is not deployed anywhere we delete it now
Lukas Burgey's avatar
Lukas Burgey committed
512
        if not self.deployed_anywhere:
Lukas Burgey's avatar
Lukas Burgey committed
513
            LOGGER.info(self.msg('Direct deletion of key'))
514
515
516
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
517
        LOGGER.info(self.msg('Deletion of key started'))
518
519
520
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
521
        # delete implies removeing the key from all clients
522
        for deployment in self.deployments.all():
523
            deployment.remove_key(self)
524

Lukas Burgey's avatar
Lukas Burgey committed
525
    # when a key is removen by a client we try to finally delete it
Lukas Burgey's avatar
Lukas Burgey committed
526
    def try_final_deletion(self):
Lukas Burgey's avatar
Lukas Burgey committed
527
528
529
        if self.deleted:
            if not self.deployed_anywhere:

Lukas Burgey's avatar
Lukas Burgey committed
530
                LOGGER.info(self.msg('All clients have removen this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
531
532
533
534
535
536
537
538
539
                self._final_deletion()

    def _final_deletion(self):
        _self = self
        for state in self.states.all():
            #for item in state.state_items.all():
            #    item.delete()
            state.delete()
        _self.delete()
Lukas Burgey's avatar
Lukas Burgey committed
540

Lukas Burgey's avatar
Lukas Burgey committed
541
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
542
543
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
544
545
        return self.name

546
547
548
    def msg(self, msg):
        return '[SSHKey:{}] {}'.format(self, msg)

Lukas Burgey's avatar
Lukas Burgey committed
549

550
# Deployment describes the credential state per user (and site) as it is supposed to be
551
552
553
554
#
# (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
555
556
# 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
557
558
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
559
560
        User,
        related_name='deployments',
Lukas Burgey's avatar
Lukas Burgey committed
561
562
        on_delete=models.SET_NULL,
        null=True,
Lukas Burgey's avatar
Lukas Burgey committed
563
    )
Lukas Burgey's avatar
Lukas Burgey committed
564
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
565
566
567
568
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
569
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
570
571
572
573
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
Lukas Burgey's avatar
Lukas Burgey committed
574
    ssh_keys_to_remove = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
575
        SSHPublicKey,
Lukas Burgey's avatar
Lukas Burgey committed
576
        related_name='removen_deployments',
Lukas Burgey's avatar
Lukas Burgey committed
577
578
        blank=True,
    )
579
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
580
581
        default=True,
    )
582

Lukas Burgey's avatar
Lukas Burgey committed
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    # 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()
599
        LOGGER.debug(deployment.msg('created'))
Lukas Burgey's avatar
Lukas Burgey committed
600
601
        return deployment

602
603
604
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
605
            LOGGER.error(self.msg('already active'))
606
607
608
609
610
611
612
            return

        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
Lukas Burgey's avatar
Lukas Burgey committed
613
        LOGGER.info(self.msg('activated'))
614

Lukas Burgey's avatar
Lukas Burgey committed
615
    # remove all credentials
616
617
    def deactivate(self):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
618
            LOGGER.error(self.msg('already deactivated'))
619
620
621
            return

        self.is_active = False
622
        self.save()
623

624
        for key in self.ssh_keys.all():
625
            self._remove_key(key)
626

Lukas Burgey's avatar
Lukas Burgey committed
627
        LOGGER.info(self.msg('deactivated'))
628
629
630
631

    # 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
632
            LOGGER.error(self.msg('cannot deploy while deactivated'))
633
634
635
636
            raise Exception('deployment deactivated')

        self.ssh_keys.add(key)

Lukas Burgey's avatar
Lukas Burgey committed
637
638
        if key in self.ssh_keys_to_remove.all():
            self.ssh_keys_to_remove.remove(key)
639
640
641
642
        self.save()

        self._deploy_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
643
    # remove key and track changes in the key lists
644
    def remove_key(self, key):
645
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
646
            LOGGER.error(self.msg('cannot remove while deactivated'))
647
648
649
650
            raise Exception('deployment deactivated')

        self.ssh_keys.remove(key)

Lukas Burgey's avatar
Lukas Burgey committed
651
652
        # keys which are to be removen by the clients
        self.ssh_keys_to_remove.add(key)
653
654
        self.save()

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
        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()
673

674
675
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
Lukas Burgey's avatar
Lukas Burgey committed
676

677
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
678
        return '[Depl.m:{}] {}'.format(self, msg)
679
680


Lukas Burgey's avatar
Lukas Burgey committed
681
# DeploymentState: knows:
682
# user, service, key, state_target
Lukas Burgey's avatar
Lukas Burgey committed
683
class DeploymentState(models.Model):
684
    key = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
685
        SSHPublicKey,
Lukas Burgey's avatar
Lukas Burgey committed
686
        related_name='states',
687
688
        # 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
689
690
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
691
    deployment = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
692
        Deployment,
Lukas Burgey's avatar
Lukas Burgey committed
693
        related_name='states',
Lukas Burgey's avatar
Lukas Burgey committed
694
695
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
696

697
698
699
700
701
702
    # 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
703

Lukas Burgey's avatar
Lukas Burgey committed
704
705
706
707
    @property
    def user(self):
        return self.deployment.user

708
709
710
    @property
    def states(self):
        return [item.state for item in self.state_items.all()]
711

712
713
714
    @property
    def state(self):
        return analyze_states(self.states)
715

716
717
718
    @property
    def service(self):
        return self.deployment.service
Lukas Burgey's avatar
Lukas Burgey committed
719

720
721
722
    @property
    def target_reached(self):
        return self.state_target == self.state
Lukas Burgey's avatar
Lukas Burgey committed
723

724
725
    # get a deployment for a user/service.
    # if it does not exist it is created
Lukas Burgey's avatar
Lukas Burgey committed
726
    @classmethod
727
728
729
730
731
732
    def get_state(cls, deployment, key):
        # check if a state does already exist
        query = cls.objects.filter(
            deployment=deployment,
            key=key,
        )
733
        if query.exists():
734
            return query.first()
735

736
737
738
739
740
741
742
        # create new state if not
        state = cls(
            deployment=deployment,
            key=key,
        )
        state.save()
        LOGGER.debug(state.msg('created'))
743

744
745
746
747
748
        # generate state items
        for site in deployment.service.site.all():
            deploy = DeploymentStateItem(
                parent=state,
                site=site,
749
            )
750
            deploy.save()
751

752
        return state
Lukas Burgey's avatar
Lukas Burgey committed
753

754
755
756
757
758
    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
759
        # each state item publishes its state to the user
760

761
762
763
764
765
    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
766
        # each state item publishes its state to the user
767

768
    def publish_to_client(self):
Lukas Burgey's avatar
Lukas Burgey committed
769
770
771
772
773
774
775
776
777
        if self.service is not None:
            # mitigating circular dependencies here
            from .clientapi.serializers import DeploymentStateSerializer
            msg = json.dumps(DeploymentStateSerializer(self).data)

            RabbitMQInstance.load().publish_by_service(
                self.service,
                msg,
            )
778
    # update the state of the remote webpage
779
    def publish_to_user(self):
Lukas Burgey's avatar
Lukas Burgey committed
780
781
782
783
784
785
786
787
788
        if self.user is not None:
            from .frontend.views import user_state
            content = {
                'user_state': user_state(self.user),
            }
            RabbitMQInstance.load().publish_to_user(
                self.user,
                content,
            )
789

790
791
    def msg(self, msg):
        return '[DState:{}] {}'.format(self, msg)
792

793
794
795
796
    def _set_target(self, target):
        self.state_target = target
        LOGGER.debug(self.msg('target: '+target))
        self.save()
797

798
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
799
        return "{}:{}#{}".format(
800
            self.deployment.service,
Lukas Burgey's avatar
Lukas Burgey committed
801
            self.key,
802
            self.id,
803
804
        )

805

Lukas Burgey's avatar
Lukas Burgey committed
806
# DeploymentStateItem: knows:
807
# user, service, key, state_target, _and_ site
Lukas Burgey's avatar
Lukas Burgey committed
808
class DeploymentStateItem(models.Model):
809
    parent = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
810
811
        DeploymentState,
        related_name='state_items',
Lukas Burgey's avatar
Lukas Burgey committed
812
813
        on_delete=models.CASCADE,
    )
814
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
815
        Site,
Lukas Burgey's avatar
Lukas Burgey committed
816
        related_name='state_items',
Lukas Burgey's avatar
Lukas Burgey committed
817
818
        on_delete=models.CASCADE,
    )
819
    state = models.CharField(
820
        max_length=50,
821
        choices=STATE_CHOICES,
822
        default='deployment_pending',
823
    )
Lukas Burgey's avatar
Lukas Burgey committed
824

825
    # questions for the user (needed for deployment
826
827
828
    questionnaire = JSONField(
        default=questionnaire_default,
    )
829
830
    # credentials for the service
    # only valid when state == deployed
831
832
833
834
    credentials = JSONField(
        default=credential_default,
    )

Lukas Burgey's avatar
Lukas Burgey committed
835
836
837
838
    @property
    def user(self):
        return self.parent.user

Lukas Burgey's avatar
Lukas Burgey committed
839
840
    @property
    def service(self):
841
        return self.parent.service
Lukas Burgey's avatar
Lukas Burgey committed
842
843
844

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

847
848
849
850
851
852
    # 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
853
854
855
        if self.state == 'deployed':
            LOGGER.info(self.msg('ignoring invalid state transition user_deploy'))
            return
856

857
        self._set_state('deployment_pending')
858

859
860
861
862
863
864
865
866
    # user: removal requested
    def user_remove(self):
        if (
                self.state == 'deployment_pending'
                or self.state == 'questionnaire'
        ):
            self._set_state('not_deployed')
            return
867

Lukas Burgey's avatar
Lukas Burgey committed
868
869
870
871
        if self.state == 'not_deployed':
            LOGGER.info(self.msg('ignoring invalid state transition user_remove'))
            return

872
        self._set_state('removal_pending')
873

874
875
876
877
    # user: questionnaire answered
    def user_answers(self, answers=None):
        self.questionnaire = answers
        self._set_state('deployment_pending')
Lukas Burgey's avatar
Lukas Burgey committed
878
        self.parent.publish_to_client()
879

880
881
882
883
    # client: deployed
    def client_deployed(self, credentials=None):
        self.credentials = credentials
        self._set_state('deployed')
884

885
886
    # client: removed
    def client_removed(self):
Lukas Burgey's avatar
Lukas Burgey committed
887
888
889
        # TODO check if all values are reset correctly 
        self.credentials = credential_default()
        self.questionnaire = questionnaire_default()
890
        self._set_state('not_deployed')
891

Lukas Burgey's avatar
Lukas Burgey committed
892
893
894
895
        # this removal maybe was the last of out ssh key
        self.key.try_final_deletion()


896
897
    # client: questionnaire
    def client_questionnaire(self, questionnaire=None):
898
        self.questionnaire = questionnaire
899
        self._set_state('questionnaire')
Lukas Burgey's avatar
Lukas Burgey committed
900

901
902
903
904
905
906
907
908
909
    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
910

Lukas Burgey's avatar
Lukas Burgey committed
911
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
912
        return "{}:{}@{}#{}".format(
913
            self.parent.service,
Lukas Burgey's avatar
Lukas Burgey committed
914
            self.parent.key,
Lukas Burgey's avatar
Lukas Burgey committed
915
            self.site,
916
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
917
        )
918
919
920
921
922


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

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

929
    if not instance.is_active and instance.is_active_at_clients:
930
931
932
933
934
935
936
937
        instance.deactivate()


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

938
    if instance.is_active and not instance.is_active_at_clients:
939
        instance.activate()