models.py 25.2 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

Lukas Burgey's avatar
Lukas Burgey committed
23

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 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
48
49
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
50
class RabbitMQInstance(SingletonModel):
Lukas Burgey's avatar
Lukas Burgey committed
51
    host = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
52
53
54
        max_length=150,
        default='localhost',
    )
Lukas Burgey's avatar
Lukas Burgey committed
55
56
57
58
    vhost = models.CharField(
        max_length=150,
        default='%2f',
    )
Lukas Burgey's avatar
Lukas Burgey committed
59
    exchange = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
60
61
62
        max_length=150,
        default='deployments',
    )
Lukas Burgey's avatar
Lukas Burgey committed
63
    port = models.IntegerField(
Lukas Burgey's avatar
Lukas Burgey committed
64
        default=15672,
Lukas Burgey's avatar
Lukas Burgey committed
65
    )
Lukas Burgey's avatar
Lukas Burgey committed
66
    username = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
67
68
69
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
70
    password = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
71
72
73
        max_length=150,
        default='guest',
    )
Lukas Burgey's avatar
Lukas Burgey committed
74
75
76
77

    def __str__(self):
        return self.host

Lukas Burgey's avatar
Lukas Burgey committed
78
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
79
        return '[RabbitMQ:{}] {}'.format(self.host, msg)
Lukas Burgey's avatar
Lukas Burgey committed
80
81
82
83

    @property
    def auth(self):
        return HTTPBasicAuth(
Lukas Burgey's avatar
Lukas Burgey committed
84
            self.username,
Lukas Burgey's avatar
Lukas Burgey committed
85
            self.password,
Lukas Burgey's avatar
Lukas Burgey committed
86
        )
Lukas Burgey's avatar
Lukas Burgey committed
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    def _init_exchanges(self, channel):
        channel.exchange_declare(
            exchange=self.exchange,
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        # TODO put in config
        channel.exchange_declare(
            exchange='update',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )

    def _init_connection(self):
        global RABBITMQ_CONNECTION
105
        #LOGGER.debug('Opening new BlockingConnection')
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        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
131
    @property
132
    def _channel(self):
Lukas Burgey's avatar
Lukas Burgey committed
133
134
135
136
137
138
139
140
        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
141
142
143

    def _publish(self, exchange, routing_key, body):
        channel = self._channel
144
        channel.basic_publish(
145
146
147
148
149
150
            exchange=exchange,
            routing_key=routing_key,
            body=body,
            properties=pika.BasicProperties(
                delivery_mode=1,
            ),
Lukas Burgey's avatar
Lukas Burgey committed
151
        )
152
        channel.close()
153

154
    # PUBLIC API
155
    def publish_by_service(self, service, msg):
156
157
158
159
160
        self._publish(
            self.exchange,
            service.routing_key,
            msg,
        )
Lukas Burgey's avatar
Lukas Burgey committed
161

162
    def publish_to_webpage(self, user, msg):
163
164
        # noise
        # LOGGER.debug('Signalling webpage of user %s', user)
165
166
167
        self._publish(
            'update',
            str(user.id),
168
            json.dumps(msg),
169
        )
170

Lukas Burgey's avatar
Lukas Burgey committed
171

172
173
174
175
def user_info_default():
    return {}


Lukas Burgey's avatar
Lukas Burgey committed
176
class User(AbstractUser):
177
    TYPE_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
178
179
180
181
        ('apiclient', 'API-Client'),
        ('oidcuser', 'OIDC User'),
        ('admin', 'Admin'),
    )
182
    user_type = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
183
184
        max_length=20,
        choices=TYPE_CHOICES,
Lukas Burgey's avatar
Lukas Burgey committed
185
        default='apiclient',
Lukas Burgey's avatar
Lukas Burgey committed
186
    )
187
188
189
190
    sub = models.CharField(
        max_length=150,
        blank=True,
        null=True,
191
        editable=False,
192
193
194
195
196
197
198
199
200
201
202
203
    )
    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
204
205
206
207
208
    # the idp which authenticated the user
    idp = models.ForeignKey(
        OIDCConfig,
        related_name='users',
        on_delete=models.CASCADE,
209
210
211
        blank=True,
        null=True,
        editable=False,
Lukas Burgey's avatar
Lukas Burgey committed
212
    )
213
214
215
216
    userinfo = JSONField(
        default=user_info_default,
        null=True,
        blank=True,
217
        editable=False,
218
    )
Lukas Burgey's avatar
Lukas Burgey committed
219

Lukas Burgey's avatar
Lukas Burgey committed
220
221
222
223
    # 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
224
        if 'sub' not in userinfo:
Lukas Burgey's avatar
Lukas Burgey committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
            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):
243
        LOGGER.debug('Constructing User from:\n%s', userinfo)
Lukas Burgey's avatar
Lukas Burgey committed
244
245
246
247
248
249

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

        if 'email' not in userinfo:
250
            username = sub
Lukas Burgey's avatar
Lukas Burgey committed
251
252
        else:
            username = userinfo['email']
253
            email = userinfo['email']
Lukas Burgey's avatar
Lukas Burgey committed
254
255
256
257
258

        user = cls(
            user_type='oidcuser',
            username=username,
            sub=sub,
259
            email=email,
Lukas Burgey's avatar
Lukas Burgey committed
260
261
262
263
            idp=idp,
            userinfo=userinfo,
        )
        user.save()
Lukas Burgey's avatar
Lukas Burgey committed
264
265
266
267
268
269

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

Lukas Burgey's avatar
Lukas Burgey committed
270
271
272
273
274
275
276
277
278
279
280
281
        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
282
    # we hide deleted keys here
283
    # the full list of ssh keys is self._ssh_keys
Lukas Burgey's avatar
Lukas Burgey committed
284
285
286
287
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

288
289
290
291
    @property
    def is_active_at_clients(self):
        return self._is_active

292
293
294
    def __str__(self):
        if self.user_type == 'admin':
            return 'ADMIN {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
295
        elif self.user_type == 'oidcuser':
296
297
298
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
Lukas Burgey's avatar
Lukas Burgey committed
299
        elif self.user_type == 'apiclient':
300
301
302
303
304
            try:
                return 'APICLIENT {}@{}'.format(self.username, self.site)
            except:
                return 'APICLIENT {}'.format(self.username)

Lukas Burgey's avatar
Lukas Burgey committed
305
306
        else:
            raise Exception()
Lukas Burgey's avatar
Lukas Burgey committed
307

Lukas Burgey's avatar
Lukas Burgey committed
308
    def msg(self, msg):
309
310
311
312
313
314
315
        return '[{}] {}'.format(self, msg)

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

Lukas Burgey's avatar
Lukas Burgey committed
316
            # FIXME: deleting the user brings problems:
317
318
            # the deletion cascades down to DeploymentTask and DeploymentTaskItem
            # but these need to be conserved so all clients withdrawals can be tracked
Lukas Burgey's avatar
Lukas Burgey committed
319
            LOGGER.info(self.msg('Deleting'))
320
321
322
            self.delete()

    def activate(self):
323
        if self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
324
            LOGGER.error(self.msg('already activated'))
325
326
            return

Lukas Burgey's avatar
Lukas Burgey committed
327
328
329
330
        self.is_active = True
        self._is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))
331

Lukas Burgey's avatar
Lukas Burgey committed
332
333
        # oidcuser: deploy the according credentials
        if self.user_type == 'oidcuser':
334
335
336
337
            for dep in self.deployments.all():
                dep.activate()

    def deactivate(self):
338
        if not self._is_active:
Lukas Burgey's avatar
Lukas Burgey committed
339
            LOGGER.error(self.msg('already deactivated'))
340
341
            return

Lukas Burgey's avatar
Lukas Burgey committed
342
343
344
345
346
347
        self.is_active = False
        self._is_active = False
        self.save()
        LOGGER.info(self.msg('deactivated'))

        # oidcuser: withdraw all credentials
348
349
350
351
352
        if self.user_type == 'oidcuser':

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

Lukas Burgey's avatar
Lukas Burgey committed
353

Lukas Burgey's avatar
Lukas Burgey committed
354
355
356
357
358
359
360
361
362
363
364
365
# 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
366
class Site(models.Model):
367
    client = models.OneToOneField(
Lukas Burgey's avatar
Lukas Burgey committed
368
369
        User,
        related_name='site',
370
371
372
373
374
375
376
377
378
379
380
        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
381
    )
Lukas Burgey's avatar
Lukas Burgey committed
382
383
384
385

    def __str__(self):
        return self.name

386
387
388
    # tasks which are still to be executed on this site
    @property
    def tasks(self):
389
390
391
        task_items = self.task_items.filter(state='pending')\
            | self.task_items.filter(state='failed')\
            | self.task_items.filter(state='answered')
392
393
        return [item.task
                for item
394
                in task_items]
Lukas Burgey's avatar
Lukas Burgey committed
395

Lukas Burgey's avatar
Lukas Burgey committed
396
397
398
399

class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
400
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
401
402
        Site,
        related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
403
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
404
405
406
        Group,
        related_name='services',
        blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
407

408
409
410
411
    @property
    def routing_key(self):
        return 'service.{}'.format(self.name)

Lukas Burgey's avatar
Lukas Burgey committed
412
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
413
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
414
415
416


class SSHPublicKey(models.Model):
Lukas Burgey's avatar
Lukas Burgey committed
417
418
419
420
421
422
    name = models.CharField(
        max_length=150,
    )
    key = models.TextField(
        max_length=1000
    )
Lukas Burgey's avatar
Lukas Burgey committed
423
    # hidden field at the user
424
    # TODO checks: if the user is null
Lukas Burgey's avatar
Lukas Burgey committed
425
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
426
427
        User,
        related_name='_ssh_keys',
428
429
        on_delete=models.SET_NULL,
        null=True,
Lukas Burgey's avatar
Lukas Burgey committed
430
    )
Lukas Burgey's avatar
Lukas Burgey committed
431

Lukas Burgey's avatar
Lukas Burgey committed
432
433
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
434
435
436
        default=False,
        editable=False,
    )
437

Lukas Burgey's avatar
Lukas Burgey committed
438
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
439
        return '[SSHPublicKey:{}] {}'.format(self, msg)
440

441
442
443
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
444
    def delete_key(self):
Lukas Burgey's avatar
Lukas Burgey committed
445
        if (not self.tasks.exists() and not self.deployments.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
446
            LOGGER.info(self.msg('Direct deletion of key'))
447
448
449
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
450
        LOGGER.info(self.msg('Deletion of key started'))
451
452
453
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
454
        # delete implies withdrawing the key from all clients
455
456
457
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
458
459
    # when a key is withdrawn by a client we try to finally delete it
    def try_final_deletion(self):
Lukas Burgey's avatar
Lukas Burgey committed
460
        if (self.deleted and not self.tasks.exists()):
Lukas Burgey's avatar
Lukas Burgey committed
461
            LOGGER.info(self.msg(
Lukas Burgey's avatar
Lukas Burgey committed
462
                'All clients have withdrawn this key. Final deletion'))
Lukas Burgey's avatar
Lukas Burgey committed
463
464
465
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
466
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
467
468
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
469
470
471
        return self.name


472
# Deployment describes the credential state per user (and site) as it is supposed to be
473
474
475
476
#
# (exception: if is_active=False the ssh_keys contain the keys to be deployed
# if the deployment is reactivated)
#
477
478
# DeploymentTask is what is sent to the clients via rabbitmq
# The DeploymentTaskItem track the acknowledgements from the clients
Lukas Burgey's avatar
Lukas Burgey committed
479
480
class Deployment(models.Model):
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
481
482
483
484
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
485
    service = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
486
487
488
489
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
490
    ssh_keys = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
491
492
493
494
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
495
    ssh_keys_to_withdraw = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
496
497
498
499
        SSHPublicKey,
        related_name='withdrawn_deployments',
        blank=True,
    )
500
    is_active = models.BooleanField(
Lukas Burgey's avatar
Lukas Burgey committed
501
502
        default=True,
    )
503

Lukas Burgey's avatar
Lukas Burgey committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

    # 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()
        return deployment


524
525
526
    @property
    def withdrawals(self):
        return self.tasks.filter(action='withdraw')
Lukas Burgey's avatar
Lukas Burgey committed
527

528
529
530
    @property
    def deploys(self):
        return self.tasks.filter(action='deploy')
Lukas Burgey's avatar
Lukas Burgey committed
531

532
533
    def __str__(self):
        return '{}:{}'.format(self.service, self.user)
534

Lukas Burgey's avatar
Lukas Burgey committed
535
    def msg(self, msg):
536
        return '[Deployment:{}] {}'.format(self, msg)
537

538
539
540
    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
541
            LOGGER.error(self.msg('already active'))
542
543
            return

Lukas Burgey's avatar
Lukas Burgey committed
544
        LOGGER.debug(self.msg(str(self.ssh_keys.all())))
545
546
547
548
549
        for key in self.ssh_keys.all():
            self._deploy_key(key)

        self.is_active = True
        self.save()
Lukas Burgey's avatar
Lukas Burgey committed
550
        LOGGER.info(self.msg('activated'))
551
552
553
554

    # withdraw all credentials
    def deactivate(self):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
555
            LOGGER.error(self.msg('already deactivated'))
556
557
558
            return

        self.is_active = False
559
        self.save()
560

561
562
563
        for key in self.ssh_keys.all():
            self._withdraw_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
564
        LOGGER.info(self.msg('deactivated'))
565
566
567

    # only deploy the key
    def _deploy_key(self, key):
Lukas Burgey's avatar
Lukas Burgey committed
568
        task = DeploymentTask.construct_deployment_task(
Lukas Burgey's avatar
Lukas Burgey committed
569
570
571
            deployment=self,
            key=key,
        )
572
573
        # publish the task
        task.publish()
574

575
    def _withdraw_key(self, key):
Lukas Burgey's avatar
Lukas Burgey committed
576
        task = DeploymentTask.construct_withdrawal_task(
Lukas Burgey's avatar
Lukas Burgey committed
577
578
579
            deployment=self,
            key=key,
        )
580

581
582
        # publish the task
        task.publish()
Lukas Burgey's avatar
Lukas Burgey committed
583

584
585
586
    # 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
587
            LOGGER.error(self.msg('cannot deploy while deactivated'))
588
589
590
591
592
593
594
595
596
597
598
599
600
            raise Exception('deployment deactivated')

        self.ssh_keys.add(key)

        if key in self.ssh_keys_to_withdraw.all():
            self.ssh_keys_to_withdraw.remove(key)
        self.save()

        self._deploy_key(key)

    # withdraw key and track changes in the key lists
    def withdraw_key(self, key):
        if not self.is_active:
Lukas Burgey's avatar
Lukas Burgey committed
601
            LOGGER.error(self.msg('cannot withdraw while deactivated'))
602
603
604
605
606
607
608
609
610
611
            raise Exception('deployment deactivated')

        self.ssh_keys.remove(key)

        # keys which are to be withdrawn by the clients
        self.ssh_keys_to_withdraw.add(key)
        self.save()

        self._withdraw_key(key)

Lukas Burgey's avatar
Lukas Burgey committed
612

613
614
615
616
617
618
619
620
621
def invert_action(action):
    if action == 'deploy':
        return 'withdraw'
    elif action == 'withdraw':
        return 'deploy'


# DeploymentTask: knows:
# user, service, key, action
622
623
class DeploymentTask(models.Model):
    ACTION_CHOICES = (
Lukas Burgey's avatar
Lukas Burgey committed
624
625
626
        ('deploy', 'deploy'),
        ('withdraw', 'withdraw'),
    )
627
    action = models.CharField(
Lukas Burgey's avatar
Lukas Burgey committed
628
629
630
        max_length=10,
        choices=ACTION_CHOICES,
    )
631
    key = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
632
633
634
635
        SSHPublicKey,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
636
    deployment = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
637
638
639
640
        Deployment,
        related_name='tasks',
        on_delete=models.CASCADE,
    )
641
642
643
644
645
    user = models.ForeignKey(
        User,
        related_name='deployment_tasks',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
646

647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
    # the inverse action of this task is requirred
    # so we invert the task and manage its task_items accordingly
    def invert_task(self):
        LOGGER.debug(self.msg('inverting'))

        previous_action = self.action
        self.action = invert_action(previous_action)
        self.save()

        pending_sites = [task.site for task in self.task_items.all()]
        self.chancel_items()

        # sites which already executed the task
        # we have to send them an order to rollback the changes
        for site in self.deployment.service.site.all():
            if site not in pending_sites:
                deploy = DeploymentTaskItem(
                    task=self,
                    site=site,
                    user=self.deployment.user
                )
                deploy.save()
                LOGGER.debug(deploy.msg('pending'))

Lukas Burgey's avatar
Lukas Burgey committed
671
672
    @classmethod
    def construct_deployment_task(cls, deployment, key):
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        # does a task exist for this key?
        query = deployment.tasks.filter(key=key)
        if query.exists():
            if len(query) > 1:
                raise Exception('Unexpected query result')

            task = query.first()
            if task.action == 'deploy':
                raise Exception('Constructing deployment task when one already exists')

            task.invert_task()
            return task

        else:
            #create new task
            task = cls(
                action='deploy',
                deployment=deployment,
                key=key,
                user=deployment.user,
Lukas Burgey's avatar
Lukas Burgey committed
693
            )
694
695
696
697
698
699
700
701
702
703
704
705
            task.save()
            LOGGER.debug(task.msg('pending'))

            # generate task items
            for site in deployment.service.site.all():
                deploy = DeploymentTaskItem(
                    task=task,
                    site=site,
                    user=deployment.user
                )
                deploy.save()
                LOGGER.debug(deploy.msg('pending'))
Lukas Burgey's avatar
Lukas Burgey committed
706

707
            return task
Lukas Burgey's avatar
Lukas Burgey committed
708
709
710

    @classmethod
    def construct_withdrawal_task(cls, deployment, key):
711
712
713
714
715
        # does a task exist for this key?
        query = deployment.tasks.filter(key=key)
        if query.exists():
            if len(query) > 1:
                raise Exception('Unexpected query result')
Lukas Burgey's avatar
Lukas Burgey committed
716

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
            task = query.first()
            if task.action == 'withdraw':
                raise Exception('Constructing deployment task when one already exists')

            task.invert_task()
            return task

        else:
            # create a new task
            task = cls(
                action='withdraw',
                deployment=deployment,
                key=key,
                user=deployment.user,
            )
            task.save()
            LOGGER.debug(task.msg('pending'))

            # generate task items
            for site in deployment.service.site.all():
                deploy = DeploymentTaskItem(
                    task=task,
                    site=site,
                    user=deployment.user
                )
                deploy.save()
                LOGGER.debug(deploy.msg('pending'))

            return task

    def chancel_items(self):
        for item in self.task_items.all():
            item.chancel()

    def chancel(self):
        self.chancel_items()
        LOGGER.debug(self.msg("chanceled"))
        self.delete()
Lukas Burgey's avatar
Lukas Burgey committed
755

Lukas Burgey's avatar
Lukas Burgey committed
756
757
758
759
    @property
    def service(self):
        return self.deployment.service

760
    def __str__(self):
761
        return "{}:{}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
762
763
            self.deployment.service,
            self.action,
764
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
765
        )
766

Lukas Burgey's avatar
Lukas Burgey committed
767
    def msg(self, msg):
Lukas Burgey's avatar
Lukas Burgey committed
768
        return '[DeploymentTask:{}] {}'.format(self, msg)
769
770

    def publish(self):
Lukas Burgey's avatar
Lukas Burgey committed
771
        # mitigating circular dependencies here
772
773
774
        from .clientapi.serializers import DeploymentTaskSerializer
        msg = json.dumps(DeploymentTaskSerializer(self).data)

775
        RabbitMQInstance.load().publish_by_service(
Lukas Burgey's avatar
Lukas Burgey committed
776
777
778
            self.service,
            msg,
        )
779

780
781
782
783
784
785
786
787
788
789
790
    # update the state of the remote webpage
    def send_state_update(self):
        from .frontend.views import user_state_dict
        content = {
            'user_state': user_state_dict(self.user),
        }
        RabbitMQInstance.load().publish_to_webpage(
            self.user,
            content,
        )

791
    def try_finished(self):
792
        if not self.task_items.exists():
793
            # finished sends its own message
Lukas Burgey's avatar
Lukas Burgey committed
794
            self._finished()
795
796

    # maintenance after all task items are done
Lukas Burgey's avatar
Lukas Burgey committed
797
    def _finished(self):
Lukas Burgey's avatar
Lukas Burgey committed
798
        LOGGER.info(self.msg('done'))
799

Lukas Burgey's avatar
Lukas Burgey committed
800
        self.delete()
801
802
803
804
805

        # check if this was the final withdraw in a key deletion
        if self.action == 'withdraw':
            self.key.try_final_deletion()

Lukas Burgey's avatar
Lukas Burgey committed
806
807
808
809
810
        message = 'Completed: {} {} @ {}'.format(
            self.action,
            self.key,
            self.service,
        )
811
812
813
814
815
816
817
818
819
820
821

        from .frontend.views import user_state_dict
        content = {
            'user_state': user_state_dict(self.user),
            'message': message,
        }
        RabbitMQInstance.load().publish_to_webpage(
            self.user,
            content,
        )

822

823
824
825
826
827
def questionnaire_default():
    return {}

# DeploymentTaskItem: knows:
# user, service, key, action, _and_ site
828
829
class DeploymentTaskItem(models.Model):
    task = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
830
831
832
833
        DeploymentTask,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
834
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
835
836
837
838
        Site,
        related_name='task_items',
        on_delete=models.CASCADE,
    )
Lukas Burgey's avatar
Lukas Burgey committed
839
840
841
842
843
    user = models.ForeignKey(
        User,
        related_name='deployment_task_items',
        on_delete=models.CASCADE,
    )
844
845
846
847
848
849
    STATE_CHOICES = (
        ('pending', 'Pending'),
        ('done', 'Done'),
        ('chanceled', 'Chanceled'),
        ('failed', 'Failed'),
        ('rejected', 'Rejected'),
850
        ('answered', 'Answered'),
851
852
853
854
855
856
    )
    state = models.CharField(
        max_length=20,
        choices=STATE_CHOICES,
        default='pending',
    )
Lukas Burgey's avatar
Lukas Burgey committed
857

858
859
860
861
862
863
    questionnaire = JSONField(
        default=questionnaire_default,
        null=True,
        blank=True,
    )

Lukas Burgey's avatar
Lukas Burgey committed
864
865
866
867
868
869
870
871
872
873
874
    @property
    def service(self):
        return self.task.service

    @property
    def key(self):
        return self.task.key

    @property
    def action(self):
        return self.deployment.key
875

876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
    # the client acked the receipt and execution of the task for his site
    def success(self):
        task = self.task

        LOGGER.debug(self.msg('success'))
        self.delete()

        task.send_state_update()
        task.try_finished()

    # the user changed the deployment
    # chancel (delete) this task item
    def chancel(self):
        LOGGER.debug(self.msg('chanceled'))
        self.delete()

        # no update on chancel
        # the next task will send an update
        #task.send_state_update()

    # the client failed to execute the item
    # the client can try again later
    # we signal the user about the failure
    def failed(self, site):
        LOGGER.debug(self.msg('failed'))
        self.state = 'failed'
        self.save()

        self.task.send_state_update()

    # the client failed to execute the item
    # the client needs additional information from the user to try again
    # we have to ask the user for data
    def rejected(self, questionnaire=None):
        LOGGER.debug(self.msg('rejected'))
        self.state = 'rejected'
        self.questionnaire = questionnaire
        self.save()

        self.task.send_state_update()

    def questionnaire_answered(self, answers=None):
        LOGGER.debug('%s %s', self.msg('answers'), answers)
        self.state = 'answered'
        self.questionnaire = answers
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
923
    def __str__(self):
924
        return "{}@{}#{}".format(
Lukas Burgey's avatar
Lukas Burgey committed
925
926
            self.task,
            self.site,
927
            self.id,
Lukas Burgey's avatar
Lukas Burgey committed
928
        )
929

Lukas Burgey's avatar
Lukas Burgey committed
930
    def msg(self, msg):
931
932
        return '[Depl. TaskItem:{}] {}'.format(self, msg)

933

Lukas Burgey's avatar
Lukas Burgey committed
934

935
936
937
#
# RECEIVERS
#
Lukas Burgey's avatar
Lukas Burgey committed
938

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

944
    if not instance.is_active and instance.is_active_at_clients:
945
946
947
948
949
950
951
952
        instance.deactivate()


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

953
    if instance.is_active and not instance.is_active_at_clients:
954
        instance.activate()