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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
            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):
299
        LOGGER.debug('Constructing User from:\n%s', userinfo)
Lukas Burgey's avatar
Lukas Burgey committed
300
301
302
303
304
305

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

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

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

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

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

344
345
346
347
    @property
    def is_active_at_clients(self):
        return self._is_active

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

Lukas Burgey's avatar
Lukas Burgey committed
361
362
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
363

Lukas Burgey's avatar
Lukas Burgey committed
364
    def msg(self, msg):
365
366
        return '[{}] {}'.format(self, msg)

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

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

    def activate(self):
379
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
380
            LOGGER.error(self.msg('already activated'))
381
382
            return

Lukas Burgey's avatar
Lukas Burgey committed
383
384
385
386
        self.is_active = True
        self._is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))
387

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

    def deactivate(self):
394
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
395
            LOGGER.error(self.msg('already deactivated'))
396
397
            return

Lukas Burgey's avatar
Lukas Burgey committed
398
399
400
401
402
        self.is_active = False
        self._is_active = False
        self.save()
        LOGGER.info(self.msg('deactivated'))

Lukas Burgey's avatar
Lukas Burgey committed
403
        # oidcuser: remove all credentials
404
405
406
407
408
        if self.user_type == 'oidcuser':

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

Lukas Burgey's avatar
Lukas Burgey committed
409

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

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

Lukas Burgey's avatar
Lukas Burgey committed
443
444
445
446
447
    def __str__(self):
        return self.name


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

466
467
468
469
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
470
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
471
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
472
473
474


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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
514
        LOGGER.info(self.msg('Deletion of key started'))
515
516
517
        self.deleted = True
        self.save()

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

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

Lukas Burgey's avatar
Lukas Burgey committed
527
                LOGGER.info(self.msg('All clients have removen this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
528
529
530
531
532
533
534
535
536
                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
537

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

543
544
545
    def msg(self, msg):
        return '[SSHKey:{}] {}'.format(self, msg)

Lukas Burgey's avatar
Lukas Burgey committed
546

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

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

599
600
601
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
602
            LOGGER.error(self.msg('already active'))
603
604
605
606
607
608
609
            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
610
        LOGGER.info(self.msg('activated'))
611

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

        self.is_active = False
619
        self.save()
620

621
        for key in self.ssh_keys.all():
622
            self._remove_key(key)
623

Lukas Burgey's avatar
Lukas Burgey committed
624
        LOGGER.info(self.msg('deactivated'))
625
626
627
628

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

        self.ssh_keys.add(key)

Lukas Burgey's avatar
Lukas Burgey committed
634
635
        if key in self.ssh_keys_to_remove.all():
            self.ssh_keys_to_remove.remove(key)
636
637
638
639
        self.save()

        self._deploy_key(key)

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

        self.ssh_keys.remove(key)

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

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

671
672
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
Lukas Burgey's avatar
Lukas Burgey committed
673

674
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
675
        return '[Depl.m:{}] {}'.format(self, msg)
676
677


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

694
695
696
697
698
699
    # 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
700

Lukas Burgey's avatar
Lukas Burgey committed
701
702
703
704
    @property
    def user(self):
        return self.deployment.user

705
706
707
    @property
    def states(self):
        return [item.state for item in self.state_items.all()]
708

709
710
711
    @property
    def state(self):
        return analyze_states(self.states)
712

713
714
715
    @property
    def service(self):
        return self.deployment.service
Lukas Burgey's avatar
Lukas Burgey committed
716

717
718
719
    @property
    def target_reached(self):
        return self.state_target == self.state
Lukas Burgey's avatar
Lukas Burgey committed
720

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

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

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

749
        return state
Lukas Burgey's avatar
Lukas Burgey committed
750

751
752
753
754
755
    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
756
        # each state item publishes its state to the user
757

758
759
760
761
762
    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
763
        # each state item publishes its state to the user
764

765
    def publish_to_client(self):
Lukas Burgey's avatar
Lukas Burgey committed
766
767
768
769
770
771
772
773
774
        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,
            )
775
    # update the state of the remote webpage
776
    def publish_to_user(self):
Lukas Burgey's avatar
Lukas Burgey committed
777
778
779
780
781
782
783
784
785
        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,
            )
786

787
788
    def msg(self, msg):
        return '[DState:{}] {}'.format(self, msg)
789

790
791
792
793
    def _set_target(self, target):
        self.state_target = target
        LOGGER.debug(self.msg('target: '+target))
        self.save()
794

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

802

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

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

Lukas Burgey's avatar
Lukas Burgey committed
832
833
834
835
    @property
    def user(self):
        return self.parent.user

Lukas Burgey's avatar
Lukas Burgey committed
836
837
    @property
    def service(self):
838
        return self.parent.service
Lukas Burgey's avatar
Lukas Burgey committed
839
840
841

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

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

854
        self._set_state('deployment_pending')
855

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

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

869
        self._set_state('removal_pending')
870

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

877
878
879
880
    # client: deployed
    def client_deployed(self, credentials=None):
        self.credentials = credentials
        self._set_state('deployed')
881

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

Lukas Burgey's avatar
Lukas Burgey committed
889
890
891
892
        # this removal maybe was the last of out ssh key
        self.key.try_final_deletion()


893
894
    # client: questionnaire
    def client_questionnaire(self, questionnaire=None):
895
        self.questionnaire = questionnaire
896
        self._set_state('questionnaire')
Lukas Burgey's avatar
Lukas Burgey committed
897

898
899
900
901
902
903
904
905
906
    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
907

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


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

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

926
    if not instance.is_active and instance.is_active_at_clients:
927
928
929
930
931
932
933
934
        instance.deactivate()


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

935
    if instance.is_active and not instance.is_active_at_clients:
936
        instance.activate()