__init__.py 18.3 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1

2
3
4
5
6
7
8
9
from json import dumps
from logging import getLogger

from django.contrib.auth.models import Group
from django.db import models
from django_mysql.models import JSONField

from .brokers import RabbitMQInstance
Lukas Burgey's avatar
Lukas Burgey committed
10
from .users import User, SSHPublicKey
11
12
13
14
15
16
17
18
19
20
21
22
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
131
132
133
134
135
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305

LOGGER = getLogger(__name__)


STATE_CHOICES = (
    ('deployment_pending', 'Deployment Pending'),
    ('removal_pending', 'Removal Pending'),
    ('deployed', 'Deployed'),
    ('not_deployed', 'Not Deployed'),
    ('questionnaire', 'Questionnaire'),
    ('failed', 'Failed'),
    ('rejected', 'Rejected'),
)
def questionnaire_default():
    return {}
def credential_default():
    return {}


class Site(models.Model):
    client = models.OneToOneField(
        User,
        related_name='site',
        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,
    )

    @property
    def pending_tasks(self):
        tasks = {}
        pending_items = self.state_items.filter(
            state='deployment_pending',
        ) | self.state_items.filter(
            state='removal_pending',
        ) | self.state_items.filter(
            state='failed',
        )
        for item in pending_items.all():
            tasks[item.parent.id] = item.parent

        return tasks.values()

    def __str__(self):
        return self.name


class Service(models.Model):
    name = models.CharField(
        max_length=150,
        unique=True,
    )
    description = models.TextField(
        max_length=300,
        blank=True,
    )
    site = models.ManyToManyField(
        Site,
        related_name='services',
    )
    groups = models.ManyToManyField(
        Group,
        related_name='services',
        blank=True,
    )

    def __str__(self):
        return self.name


    def handle_group_deployments(self):
        for group in self.groups.all():

            # users that have group deployments for this group
            for user in User.objects.filter(
                    deployments__group=group,
            ).distinct():
                LOGGER.debug(user.msg('New service for group. Adding to deployment'))

                try:
                    deployment = user.deployments.get(group=group)
                    deployment.service_added(self)
                except Deployment.DoesNotExist:
                    LOGGER.error('Inconsistency of group deployment')
                    raise


# Deployment describes the supposed state of the users ssh keys at either:
#   - a group (and and the services associated with the group)
#   - a single service
#
# DeploymentState track the state of a single ssh key at either:
#   - a group (and and the services associated with the group)
#   - a single service

# DeploymentStateItem track the acknowledgements from the clients for either :
#   - the sites that handle the associated group (i.e provide a service for members of the group)
#   - the sites that provide the associated service
#
# Note: two possible kinds of Deployment:
#   (group is None and service is not None) or
#   (group is not None and service is None)
class Deployment(models.Model):
    user = models.ForeignKey(
        User,
        related_name='deployments',
        on_delete=models.SET_NULL,
        null=True,
    )
    group = models.ForeignKey(
        Group,
        related_name='deployments',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    service = models.ForeignKey(
        Service,
        related_name='deployments',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    ssh_keys = models.ManyToManyField(
        SSHPublicKey,
        related_name='deployments',
        blank=True,
    )
    is_active = models.BooleanField(
        default=True,
    )

    # only used when group is not None and service is None
    @property
    def services(self):
        if self.group is not None:
            return self.group.services.all()
        return None

    # only used when group is not None and service is None
    @property
    def sites(self):
        return Site.objects.filter(services__groups=self.group).distinct()

    # get a deployment for a user/service.
    # if it does not exist it is created
    @classmethod
    def get_deployment(cls, user, service=None, group=None):
        try:
            if service is not None:
                return cls.objects.get(
                    user=user,
                    service=service,
                )

            elif group is not None:
                return cls.objects.get(
                    user=user,
                    group=group,
                )
            else:
                raise ValueError('Unable to create Deployment without service and group')

        except cls.DoesNotExist:
            deployment = None
            if service is not None:
                deployment = cls(
                    user=user,
                    service=service,
                )
            elif group is not None:
                deployment = cls(
                    user=user,
                    group=group,
                )
                if not group.services.exists():
                    LOGGER.info(deployment.msg('No services for group'))

            deployment.save()
            LOGGER.debug(deployment.msg('created'))
            return deployment

    # deploy credentials which were deployed prior to deactivation
    def activate(self):
        if self.is_active:
            LOGGER.error(self.msg('already active'))
            return

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

        self.is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))

    # remove all credentials
    def deactivate(self):
        if not self.is_active:
            LOGGER.error(self.msg('already deactivated'))
            return

        self.is_active = False
        self.save()

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

        LOGGER.info(self.msg('deactivated'))

    # deploy key and track changes in the key lists
    def deploy_key(self, key):
        if not self.is_active:
            LOGGER.error(self.msg('cannot deploy while deactivated'))
            raise Exception('deployment deactivated')

        self.ssh_keys.add(key)
        self.save()

        self._deploy_key(key)

    def service_added(self, service):
        # a new service for this group was added and we may have to deploy some keys
        LOGGER.debug(self.msg('Adding service {}'.format(service)))

        for state in self.states.all():
            state.service_added(service)

    # remove key and track changes in the key lists
    def remove_key(self, key):
        if not self.is_active:
            LOGGER.error(self.msg('cannot remove while deactivated'))
            raise Exception('deployment deactivated')

        self.ssh_keys.remove(key)
        self.save()

        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()

    def __str__(self):
        if self.service is not None:
            return '{}:{}'.format(self.service, self.user)
        return '{}:{}'.format(self.group, self.user)

    def msg(self, msg):
        return '[Depl.m:{}] {}'.format(self, msg)


# DeploymentState: knows:
# user, service, key, state_target
class DeploymentState(models.Model):
    key = models.ForeignKey(
        SSHPublicKey,
        related_name='states',
        # deleting the key leaves us without references about its deployments
        # we _HAVE_ to remove all deployments prior to deleting key
        on_delete=models.CASCADE,
    )
    deployment = models.ForeignKey(
        Deployment,
        related_name='states',
        on_delete=models.CASCADE,
    )

    # 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    # credentials provided by the backend to the clients
    @property
    def credentials(self):
        # FIXME hacky

        ssh_keys = [{
            'name': key.name,
            'value': key.key
        }
                    for key in self.user.ssh_keys.all()]
        return {
            'ssh_key': ssh_keys
        }

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    @property
    def user(self):
        return self.deployment.user

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

    @property
    def state(self):
        if self.states:
            _state = ''
            for state in self.states:
                if _state == '':
                    _state = state
                elif _state != state:
                    return 'mixed'

            return _state

        # if we have no states we have nothing to do
        return self.state_target

    @property
    def target_reached(self):
        return self.state_target == self.state

    @property
    def service(self):
        return self.deployment.service

    @property
    def services(self):
        return self.deployment.services

    @property
    def group(self):
        return self.deployment.group

    # get a state for a user/service.
    # if it does not exist it is created
    @classmethod
    def get_state(cls, deployment, key):
        # check if a state does already exist
        state = None
        try:
            state = cls.objects.get(
                deployment=deployment,
                key=key,
            )
            return state

        except cls.DoesNotExist:
            state = cls(
                deployment=deployment,
                key=key,
            )
            state.save()
            LOGGER.debug(state.msg('created'))

        except cls.MultipleObjectsReturned:
            LOGGER.error(
                deployment.msg('to many DeploymentState objects for key {}'.format(key.name))
            )
            raise


        # generate state items
        if deployment.service is not None:
            for site in deployment.service.site.all():
                DeploymentStateItem.get_state_item(
                    parent=state,
                    site=site,
                    service=deployment.service,
                ).save()
        elif deployment.group is not None:
            # every site which provides a service for group
            for site in deployment.sites:
                for service in Service.objects.filter(
                        groups=deployment.group,
                        site=site,
                ):
                    DeploymentStateItem.get_state_item(
                        parent=state,
                        site=site,
                        service=service,
                    ).save()

        return state

    def service_added(self, service):
        LOGGER.debug(self.msg('Adding service {}'.format(service)))
        for site in service.site.all():
            # create new DeploymentStateItems
            item = DeploymentStateItem.get_state_item(
                parent=self,
                site=site,
                service=service,
            )
            item.save()
            if self.state_target == 'deployed':
                item.user_deploy()

    def deploy(self):
        self._set_target('deployed')
        for item in self.state_items.all():
            item.user_deploy()
        self.publish_to_client()
        # each state item publishes its state to the user

    def remove(self):
        self._set_target('not_deployed')
        for item in self.state_items.all():
            item.user_remove()
        self.publish_to_client()
        # each state item publishes its state to the user

    def publish_to_client(self):
        # mitigating circular dependencies here
        from .serializers.clients import DeploymentStateSerializer
Lukas Burgey's avatar
Lukas Burgey committed
440
441
442
        data = DeploymentStateSerializer(self).data
        data['credentials'] = self.credentials
        msg = dumps(data)
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
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
671

        if self.service is not None:
            RabbitMQInstance.load().publish_by_service(
                self.service,
                msg,
            )
        elif self.group is not None:
            RabbitMQInstance.load().publish_by_group(
                self.group,
                msg,
            )
        else:
            LOGGER.error('Deployment as neither a group or a service')

    # update the state of the remote webpage
    def publish_to_user(self):
        if self.user is not None:
            from ..views.webpage import user_state
            msg = dumps({
                'user_state': user_state(self.user),
            })
            RabbitMQInstance.load().publish_to_user(
                self.user,
                msg,
            )

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

    def _set_target(self, target):
        self.state_target = target
        LOGGER.debug(self.msg('target: '+target))
        self.save()

    def __str__(self):
        if self.service is not None:
            return '{}:{}#{}'.format(
                self.service,
                self.key.name,
                self.id,
            )
        return '{}:{}#{}'.format(
            self.group,
            self.key.name,
            self.id,
        )


# DeploymentStateItem: knows:
# user, service, key, state_target, _and_ site
class DeploymentStateItem(models.Model):
    parent = models.ForeignKey(
        DeploymentState,
        related_name='state_items',
        on_delete=models.CASCADE,
    )
    site = models.ForeignKey(
        Site,
        related_name='state_items',
        on_delete=models.CASCADE,
    )
    service = models.ForeignKey(
        Service,
        related_name='state_items',
        on_delete=models.CASCADE,
    )
    state = models.CharField(
        max_length=50,
        choices=STATE_CHOICES,
        default='deployment_pending',
    )

    # message for the user
    message = models.TextField(
        max_length=300,
        default='',
    )

    # questions for the user (needed for deployment
    questionnaire = JSONField(
        default=questionnaire_default,
        null=True,
        blank=True,
    )
    # credentials for the service
    # only valid when state == deployed
    credentials = JSONField(
        default=credential_default,
        null=True,
        blank=True,
    )

    @property
    def user(self):
        return self.parent.user

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

    @property
    def group(self):
        return self.parent.group

    @classmethod
    def get_state_item(cls, parent=None, site=None, service=None):
        try:
            return parent.state_items.get(
                site=site,
                service=service,
            )
        except cls.DoesNotExist:
            item = cls(
                parent=parent,
                site=site,
                service=service,
            )
            item.save()
            LOGGER.debug(item.msg('created'))
            return item


    # STATE transitions
    # user: deployment requested
    def user_deploy(self):
        if self.state == 'removal_pending':
            self._set_state('deployed')
            return

        if self.state == 'deployed':
            LOGGER.info(self.msg('ignoring invalid state transition user_deploy'))
            return

        self._set_state(
            'deployment_pending',
            publish=False, # the post response already contains the update
        )

    # user: removal requested
    def user_remove(self):
        if self.state == 'not_deployed':
            LOGGER.info(self.msg('ignoring invalid state transition user_remove'))
            return

        if (
                self.state == 'deployment_pending'
                or self.state == 'questionnaire'
        ):
            self._set_state('not_deployed')
            return

        self._set_state(
            'removal_pending',
            publish=False, # the post response already contains the update
        )

    # user: questionnaire answered
    def user_answers(self, answers=None):
        self.questionnaire = answers
        self._set_state('deployment_pending', publish=False)
        self.parent.publish_to_client()

    # returns None on success, or a string describing an error
    def client_response(self, output):
        status = output.get('state', 'undefined')

        self.message = output.get('message', '')
        self.save()

        if status != 'undefined':
            # update values
            if status == 'deployed':
                self.credentials = output.get('credentials', {})
                self.save()
            elif status == 'not_deployed':
                # reset credentials and questi
                self._reset()
                self.save()
            elif status == 'questionnaire':
                self.questionnaire = output.get('questionnaire', {})
                self.save()
            elif status == 'rejected':
                pass
            elif status == 'failed':
                pass
            else:
                return 'unknown state \''+status+'\''

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


    # resets all client sent values
    def _reset(self):
        self.credentials = credential_default()
        self.questionnaire = questionnaire_default()
        self.message = ''

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

    def _set_state(self, state, publish=True):
        if self.state == 'rejected':
            LOGGER.info('refusing to change state of rejected state_item')
            self.save()
            return

        self.state = state
        self.save()
        LOGGER.debug(self.msg('state: '+self.state))
        if publish:
            self.parent.publish_to_user()

    def __str__(self):
        if self.group is not None:
            return '{}:{}@{}:{}#{}'.format(
                self.group,
                self.service,
                self.site,
                self.key.name,
                self.id,
            )
        return '{}:@{}:{}#{}'.format(
            self.service,
            self.site,
            self.key.name,
            self.id,
        )