models.py 24.8 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
STATE_CHOICES = (
    ('deployment_pending', 'Deployment Pending'),
    ('removal_pending', 'Removal Pending'),
    ('deployed', 'Deployed'),
    ('not_deployed', 'Not Deployed'),
    ('questionnaire', 'Questionnaire'),
29
30
    ('failed', 'Failed'),
    ('rejected', 'Rejected'),
31
32
)

Lukas Burgey's avatar
Lukas Burgey committed
33

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

60
61
62
63
64
65
66
67
68
69
70
71
72
# 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

73

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

    def __str__(self):
        return self.host

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

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

115
116
    def _init_exchanges(self, channel):
        channel.exchange_declare(
Lukas Burgey's avatar
Lukas Burgey committed
117
118
119
120
121
122
123
            exchange='deployments',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        channel.exchange_declare(
            exchange='sites',
124
125
126
127
128
129
130
131
132
133
134
135
136
            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
137
        #LOGGER.debug('Opening new BlockingConnection')
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        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
163
    @property
164
    def _channel(self):
Lukas Burgey's avatar
Lukas Burgey committed
165
166
167
168
169
170
171
172
        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
173
174
175

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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
208

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


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

Lukas Burgey's avatar
Lukas Burgey committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    @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
278
279
280
281
    # 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
282
        if 'sub' not in userinfo:
Lukas Burgey's avatar
Lukas Burgey committed
283
284
            raise Exception('get_user needs a userinfo which contains the users subject')

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

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

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

        return user
Lukas Burgey's avatar
Lukas Burgey committed
301
302
303

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

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

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

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

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

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

349
350
351
352
    @property
    def is_active_at_clients(self):
        return self._is_active

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

Lukas Burgey's avatar
Lukas Burgey committed
366
367
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
368

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

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

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

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

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

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

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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
414

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

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

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


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

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

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


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

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

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

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

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

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

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

Lukas Burgey's avatar
Lukas Burgey committed
532
                LOGGER.info(self.msg('All clients have removen this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
533
534
535
536
537
538
539
540
541
                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
542

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

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

Lukas Burgey's avatar
Lukas Burgey committed
551

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

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

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

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

        self.is_active = False
624
        self.save()
625

626
        for key in self.ssh_keys.all():
627
            self._remove_key(key)
628

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

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

        self.ssh_keys.add(key)

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

        self._deploy_key(key)

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

        self.ssh_keys.remove(key)

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

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

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

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


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

699
700
701
702
703
704
    # 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
705

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

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

714
715
716
    @property
    def state(self):
        return analyze_states(self.states)
717

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

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

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

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

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

754
        return state
Lukas Burgey's avatar
Lukas Burgey committed
755

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

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

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

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

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

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

807

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

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

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

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

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

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

859
        self._set_state('deployment_pending')
860

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

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

874
        self._set_state('removal_pending')
875

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

882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    # returns None on success, or a string describing an error
    def client_response(self, output):
        status = output.get('status', 'undefined')
        if status != 'undefined':
            # update values
            if status == 'deployed':
                self.credentials = output.get('credentials', {})
            elif status == 'removed':
                self.credentials = credential_default()
                self.questionnaire = questionnaire_default()
            elif status == 'questionnaire':
                self.questionnaire = output.get('questionnaire', {})
            elif status == 'rejected':
                pass
            elif status == 'failed':
                pass
            else:
                return 'unknown state '+status

            self._set_state(status)
            return None
        return 'missing status in output'
904

Lukas Burgey's avatar
Lukas Burgey committed
905

906
907
908
909
    def msg(self, msg):
        return '[DSItem:{}] {}'.format(self, msg)

    def _set_state(self, state):
910
911
912
913
914
        if self.state == 'rejected':
            LOGGER.info('refusing to change state of rejected state_item')
            self.save()
            return

915
916
917
918
919
        self.state = state
        self.save()
        LOGGER.debug(self.msg('state: '+self.state))
        self.parent.publish_to_user()

Lukas Burgey's avatar
Lukas Burgey committed
920

Lukas Burgey's avatar
Lukas Burgey committed
921
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
922
        return "{}:{}@{}#{}".format(
923
            self.parent.service,
Lukas Burgey's avatar
Lukas Burgey committed
924
            self.parent.key,
Lukas Burgey's avatar
Lukas Burgey committed
925
            self.site,
926
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
927
        )
928
929
930
931
932


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

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

939
    if not instance.is_active and instance.is_active_at_clients:
940
941
942
943
944
945
946
947
        instance.deactivate()


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

948
    if instance.is_active and not instance.is_active_at_clients:
949
        instance.activate()