deployments.py 18.8 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
7
8
9
10
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

from json import dumps
from logging import getLogger

from django.conf import settings
from django.db import models
from django_mysql.models import JSONField
from polymorphic.models import PolymorphicModel

from feudal.backend.auth.v1.models.vo import VO

from . import Site, Service
from .users import User, SSHPublicKey
from .brokers import RabbitMQInstance


LOGGER = getLogger(__name__)


DEPLOYMENT_PENDING = 'deployment_pending'
REMOVAL_PENDING = 'removal_pending'
NOT_DEPLOYED = 'not_deployed'
DEPLOYED = 'deployed'
QUESTIONNAIRE = 'questionnaire'
FAILED = 'failed'
REJECTED = 'rejected'

TARGET_CHOICES = (
    (DEPLOYED, 'Deployed'),
    (NOT_DEPLOYED, 'Not Deployed'),
)
STATE_CHOICES = (
    (DEPLOYMENT_PENDING, 'VODeployment 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 {}


51
52
53
54
55
56
57
58
59
60
61
62
63
def get_deployment(user, vo=None, service=None):
    if vo is not None and service is not None:
        raise ValueError('Cannot create deployment for both vo and service')

    if vo is not None:
        return VODeployment.get_deployment(user, vo)

    if service is not None:
        return ServiceDeployment.get_deployment(user, service)

    raise ValueError('Need vo or service to create deployment')


Lukas Burgey's avatar
Lukas Burgey committed
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
class Deployment(PolymorphicModel):
    user = models.ForeignKey(
        User,
        related_name='deployments',
        on_delete=models.CASCADE,
    )

    # which state do we currently want to reach?
    state_target = models.CharField(
        max_length=50,
        choices=TARGET_CHOICES,
        default=NOT_DEPLOYED,
    )

    is_active = models.BooleanField(
        default=True,
    )

    # credentials provided by the backend to the clients
    @property
    def credentials(self):
        return self.user.credentials

    @property
    def state(self):
        if self.state_items.exists():
            _state = ''
            for state in self.state_items.all():
                if _state == '':
                    _state = state.state
                elif _state != 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

    def _set_target(self, target):
107
108
        LOGGER.debug(self.msg('Target changed to '+target))

Lukas Burgey's avatar
Lukas Burgey committed
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
        self.state_target = target

        for credential_state in CredentialState.objects.filter(
                target__parent=self,
        ):
            credential_state.set_target(target)
        self.save()

    def user_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 user_remove(self):
        for item in self.state_items.all():
            if item.state != NOT_DEPLOYED:
                item.user_remove()
        self._set_target(NOT_DEPLOYED)
        self.publish_to_client()
        # each state item publishes its state to the user

    def user_credential_added(self, key):
        for item in self.state_items.all():
            item.user_credential_added(key)

        self.publish()

    def user_credential_removed(self, key):
        for item in self.state_items.all():
            item.user_credential_removed(key)

        self.publish()

    def publish_to_client(self):
145
146
147
        from .serializers import clients
        data = clients.DeploymentSerializer(self).data
        msg = dumps(data)
Lukas Burgey's avatar
Lukas Burgey committed
148

149
150
151
152
        RabbitMQInstance.load().publish(
            self,
            msg,
        )
Lukas Burgey's avatar
Lukas Burgey committed
153
154
155
156
157
158

    # sends a state update via RabbitMQ / STOMP to the users webpage instance
    def publish_to_user(self):
        if self.user is None:
            return

159
        from . import serializers
Lukas Burgey's avatar
Lukas Burgey committed
160
        msg = dumps({
161
            'deployment': serializers.DeploymentSerializer(self).data,
Lukas Burgey's avatar
Lukas Burgey committed
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
        })
        RabbitMQInstance.load().publish_to_user(
            self.user,
            msg,
        )

    def publish(self):
        self.publish_to_user()
        self.publish_to_client()

    def msg(self, msg):
        return '{} - {}'.format(self, msg)

    def __str__(self):
        return 'Abstr. Deployment:({})#{}'.format(
            self.user,
            self.id,
        )


class VODeployment(Deployment):
    vo = models.ForeignKey(
        VO,
        related_name='vo_deployments',
        on_delete=models.CASCADE,
    )

    @property
    def services(self):
        return self.vo.services.all()

193
194
195
196
197
198
199
200
    @property
    def broker_exchange(self):
        return self.vo.broker_exchange

    @property
    def routing_key(self):
        return self.vo.name

Lukas Burgey's avatar
Lukas Burgey committed
201
202
203
    def create_state_items(self):
        for service in self.services:
            DeploymentState.get_state_item(
204
205
206
207
                self,
                self.user,
                service.site,
                service,
Lukas Burgey's avatar
Lukas Burgey committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
            )

    @classmethod
    def get_deployment(cls, user, vo):
        try:
            deployment = cls.objects.get(
                user=user,
                vo=vo,
            )
            deployment.create_state_items()

            return deployment

        except cls.DoesNotExist:
            deployment = cls(
                user=user,
                vo=vo,
            )

            deployment.save()
            deployment.create_state_items()

230
            LOGGER.debug(deployment.msg('Created'))
Lukas Burgey's avatar
Lukas Burgey committed
231
232
233
234
235
            return deployment

    def service_added(self, service):
        LOGGER.debug(self.msg('Adding service {}'.format(service)))
        item = DeploymentState.get_state_item(
236
237
238
239
            self,
            self.user,
            service.site,
            service,
Lukas Burgey's avatar
Lukas Burgey committed
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
        )
        if self.state_target == 'deployed':
            item.user_deploy()

    def service_removed(self, service):
        LOGGER.debug(self.msg('Removing service {}'.format(service)))
        LOGGER.debug('TODO implement service removal')

    def msg(self, msg):
        return '{} - {}'.format(self, msg)

    def __str__(self):
        return 'VO-Dep: ({}:{})#{}'.format(
            self.vo,
            self.user,
            self.id,
        )


class ServiceDeployment(Deployment):
    service = models.ForeignKey(
        Service,
        related_name='service_deployments',
        on_delete=models.CASCADE,
    )

266
267
268
269
270
271
272
273
    @property
    def broker_exchange(self):
        return 'services'

    @property
    def routing_key(self):
        return self.service.name

Lukas Burgey's avatar
Lukas Burgey committed
274
275
276
    def create_state_item(self):
        LOGGER.debug('create_state_item: creating DeploymentState for service %s at site %s', self.service, self.service.site)
        DeploymentState.get_state_item(
277
278
279
280
            self,
            self.user,
            self.service.site,
            self.service,
Lukas Burgey's avatar
Lukas Burgey committed
281
282
283
284
285
286
287
288
289
        )

    @classmethod
    def get_deployment(cls, user, service):
        try:
            deployment = cls.objects.get(
                user=user,
                service=service,
            )
290
            deployment.create_state_item()
Lukas Burgey's avatar
Lukas Burgey committed
291
292
293
294
295
296
297
298
299
300
301
302

            return deployment

        except cls.DoesNotExist:
            deployment = cls(
                user=user,
                service=service
            )

            deployment.save()
            deployment.create_state_item()

303
            LOGGER.debug(deployment.msg('Created'))
Lukas Burgey's avatar
Lukas Burgey committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
            return deployment

    def msg(self, msg):
        return '{} - {}'.format(self, msg)

    def __str__(self):
        return 'Service-Dep: ({}:{})#{}'.format(
            self.service,
            self.user,
            self.id,
        )


class DeploymentState(models.Model):
    parentless = ValueError('Tried to access parent of parentless deployment state')

    parent = models.ForeignKey(
        Deployment,
        related_name='state_items',
        on_delete=models.SET_NULL,
        null=True
    )

    user = models.ForeignKey(
        User,
        related_name='state_items',
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
    )

    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=NOT_DEPLOYED,
    )

    # 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 is_pending(self):
        # TODO
        # pending because we are orphaned -> pending until removed everywhere
        if self.parent is None:
            return True

        # pending because the state target is not reached
        if self.parent.state_target != self.state:
            return True

        return False

    @property
    def is_credential_pending(self):
        for credential_state in self.credential_states.all():
            if credential_state.is_pending:
                return True
        return False

    @property
    def user_credentials(self):
        return self.user.credentials

    @classmethod
399
    def get_state_item(cls, parent, user, site, service):
Lukas Burgey's avatar
Lukas Burgey committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
        try:
            item = cls.objects.get(
                parent=parent,
                user=user,
                site=site,
                service=service,
            )
            return item

        except cls.DoesNotExist:
            item = cls(
                parent=parent,
                user=user,
                site=site,
                service=service,
            )
            item.save()

418
            LOGGER.debug(item.msg('Created'))
Lukas Burgey's avatar
Lukas Burgey committed
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
            return item

    # starts tracking this the credential for this item
    def user_credential_added(self, credential):
        if settings.DEBUG_CREDENTIALS:
            LOGGER.debug('user_credential_added: %s %s', self, credential)

        CredentialState.get_credential_state(
            credential,
            self,
        )

    def user_credential_removed(self, credential):
        if settings.DEBUG_CREDENTIALS:
            LOGGER.debug('user_credential_removed: %s %s', self, credential)

        try:
            credential_state = self.credential_states.get(credential=credential)
            credential_state.credential_deleted()

        except CredentialState.DoesNotExist:
            LOGGER.error(self.msg('Credential {} has no CredentialState'.format(credential)))

    # STATE TRANSITIONS

    # user: provisioning 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: deprovisioning requested
    def user_remove(self):
        if self.parent is None:
            LOGGER.error('user_remove: parentless')
            return

        if (
                self.parent.state_target == DEPLOYED
                and (self.state == FAILED or self.state == REJECTED)
        ):
            self._reset()
            self._set_state(NOT_DEPLOYED, publish=False)
            return

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

        # FIXME this will break if the client 'finishes' the deployment, after user_remove
        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):
        if self.parent is None:
            LOGGER.error('user_answers: parentless')
            return

        self.questionnaire = answers
        self._set_state(DEPLOYMENT_PENDING, publish=False)
        self.parent.publish_to_client()

    def client_credential_states(self, credential_states):
        # maps ssh key names to their state
        ssh_key_states = credential_states.get('ssh_key', None)

        # ASSUMPTION:
        # if we hear nothing about a credential we assume it got deprovisioned!
        for credential_state in self.credential_states.all():
            if (
                    ssh_key_states is not None
                    and credential_state.credential.name in ssh_key_states
            ):
                credential_state.set(ssh_key_states[credential_state.credential.name])
            else:
                credential_state.set(NOT_DEPLOYED)

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

        credential_states = output.get('user_credential_states', None)
        if credential_states is not None:
            self.client_credential_states(credential_states)

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

        if state is None:
            return 'missing state in output'

        # update values
        if state == DEPLOYED:
            self.credentials = output.get('credentials', {})
            self.save()

            # the client completed a deployment after the user wished to remove the deployment
            if self.parent is not None and self.parent.state_target == NOT_DEPLOYED:
                self.user_remove()

        elif state == NOT_DEPLOYED:
            # reset credentials and questionnaire
            self._reset()
            self.save()

            # the client completed a removal after the user wished to deploy the deployment
            if self.parent is not None and self.parent.state_target == DEPLOYED:
                self.user_deploy()

        elif state == QUESTIONNAIRE:
            self.questionnaire = output.get('questionnaire', {})
            self.save()
        elif state == REJECTED:
            pass
        elif state == FAILED:
            pass
        else:
            return 'unknown state \''+state+'\''

        self._set_state(state)
        return None

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

    def _set_state(self, state, publish=True):
        # assure all user credentials have a state
        if self.user is not None:
            for key in self.user.ssh_keys.all():
                try:
                    CredentialState.get_credential_state(
                        credential=key,
                        target=self,
                    )
                except CredentialState.DoesNotExist:
                    LOGGER.error('CredentialState.DoesNotExist in _set_state')

        if (
                state == DEPLOYMENT_PENDING or
                state == REMOVAL_PENDING or
                state == FAILED
        ):
            self.pending = True

        self.state = state
        self.save()
        LOGGER.debug(self.msg('State changed to '+self.state))
        if publish and self.parent is not None:
            self.parent.publish_to_user()

    def msg(self, msg):
        return '{} - {}'.format(self, msg)

    def __str__(self):
        if self.parent is not None:
            return 'DState: ({}:{}:{})#{}'.format(
                self.parent.id,
                self.service,
                self.site,
                self.id,
            )

        return 'DState: (ORPHANED:{}:{})#{}'.format(
            self.service,
            self.site,
            self.id,
        )


class CredentialState(models.Model):
    state_target = models.CharField(
        max_length=50,
        choices=TARGET_CHOICES,
        default=NOT_DEPLOYED
    )

    state = models.CharField(
        max_length=50,
        choices=STATE_CHOICES,
        default=NOT_DEPLOYED
    )

    credential = models.ForeignKey(
        SSHPublicKey,
        related_name='credential_states',
        on_delete=models.CASCADE,
    )

    _credential_deleted = models.BooleanField(
        default=False,
    )

    target = models.ForeignKey(
        DeploymentState,
        related_name='credential_states',
        on_delete=models.CASCADE,
    )

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

    @classmethod
    def get_credential_state(cls, credential, target):
        try:
            return cls.objects.get(
                credential=credential,
                target=target,
            )
        except cls.DoesNotExist:

            new_state = cls(
                credential=credential,
                target=target,
                state=NOT_DEPLOYED,
                state_target=target.parent.state_target,
            )
            new_state.save()

            if settings.DEBUG_CREDENTIALS:
                LOGGER.debug(new_state.msg('Created'))

            return new_state

    def set_target(self, target):
        # state_target is locked, since we are marked for deletion
        if self._credential_deleted:
            return

        self.state_target = target
        self.save()

        if settings.DEBUG_CREDENTIALS:
            LOGGER.debug(self.msg('Target changed to {}'.format(target)))

    def set(self, state):
        if state == NOT_DEPLOYED and self._credential_deleted:
            self._delete_state()
            return

        if state == self.state:
            return

        self.state = state
        self.save()
        if settings.DEBUG_CREDENTIALS:
            LOGGER.debug(self.msg('State changed to {}'.format(state)))

    def credential_deleted(self):
        if self.state == NOT_DEPLOYED:
            self._delete_state()

        LOGGER.debug('related credential: %s', self.credential)
        self.state_target = NOT_DEPLOYED
        self._credential_deleted = True
        self.save()

        if settings.DEBUG_CREDENTIALS:
            LOGGER.debug(self.msg('Marked as deleted'))

    def _delete_state(self):
        LOGGER.debug(self.msg('Deleted'))
        credential = self.credential
        self.delete()

        credential.try_delete_key()

    def msg(self, message):
        return '{} - {}'.format(self, message)

    def __str__(self):
        return 'CState: ({}:{})#{}'.format(
            self.target.id,
            self.credential,
            self.id,
        )