deployments.py 21.8 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6

from json import dumps
from logging import getLogger

from django.conf import settings
from django.db import models
7
from django.db.models import Q
Lukas Burgey's avatar
Lukas Burgey committed
8
9
10
11
12
from django_mysql.models import JSONField
from polymorphic.models import PolymorphicModel

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

13
from . import Site, Service, brokers
Lukas Burgey's avatar
Lukas Burgey committed
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 .users import User, SSHPublicKey


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
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:
56
        # get_deployment updates automatically
57
58
59
        return VODeployment.get_deployment(user, vo)

    if service is not None:
60
        # get_deployment updates automatically
61
62
        return ServiceDeployment.get_deployment(user, service)

63
64
65
66
67
    deps = Deployment.objects.filter(user=user)
    for dep in deps:
        dep.update()
    return deps

68

Lukas Burgey's avatar
Lukas Burgey committed
69
70
71
72
class Deployment(PolymorphicModel):
    user = models.ForeignKey(
        User,
        related_name='deployments',
Lukas Burgey's avatar
Lukas Burgey committed
73
74
75
        # TODO check what repercussions the change to set null has
        on_delete=models.SET_NULL,
        null=True,
Lukas Burgey's avatar
Lukas Burgey committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    )

    # 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):
96
        if self.states.exists():
Lukas Burgey's avatar
Lukas Burgey committed
97
            _state = ''
98
            for state in self.states.all():
Lukas Burgey's avatar
Lukas Burgey committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
                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):
114
115
        if str(self.state_target) == str(target):
            return
116

117
        LOGGER.debug(self.msg('Target: {} -> {} '.format(self.state_target, target)))
Lukas Burgey's avatar
Lukas Burgey committed
118

119
        self.state_target = target
Lukas Burgey's avatar
Lukas Burgey committed
120
121
        self.save()

122
        self.publish_to_user()
123

124
    # deprecated
125
    # Deployment.user_deploy
Lukas Burgey's avatar
Lukas Burgey committed
126
    def user_deploy(self):
127
128
129
130
131
        LOGGER.debug(self.msg('user_deploy'))
        self._set_target(DEPLOYED)

        # states which are not DEPLOYED
        for item in self.states.filter(~Q(state=DEPLOYED)):
Lukas Burgey's avatar
Lukas Burgey committed
132
133
            item.user_deploy()

134
        self.publish_to_client()
135

136
    # deprecated
137
    # Deployment.user_remove
Lukas Burgey's avatar
Lukas Burgey committed
138
    def user_remove(self):
139
        LOGGER.debug(self.msg('user_remove'))
140

Lukas Burgey's avatar
Lukas Burgey committed
141
        self._set_target(NOT_DEPLOYED)
142
143
144

        # states which are not NOT_DEPLOYED
        for item in self.states.filter(~Q(state=NOT_DEPLOYED)):
145
146
147
148
149
150
151
            item.user_remove()

        # we always publish to the client
        # ATTENTION! This may cause removals of Services which are wanted by other deployments!
        # These will be deployed again when their DepState realises the error
        self.publish_to_client()

152
153
154
155
156
157
158
159
160
161
162
163
164
165
    # call when you changed Deployment.state_target
    def target_changed(self):
        LOGGER.debug(self.msg('target_changed: {}'.format(self.state_target)))

        for item in self.states.filter(~Q(state=self.state_target)):
            item.dep_target_changed()

        self.publish_to_user()

        # publish if there are pending states
        for item in self.states.all():
            if item.is_pending or item.is_credential_pending:
                self.publish_to_client()
                return
Lukas Burgey's avatar
Lukas Burgey committed
166
167

    def user_credential_added(self, key):
168
        for item in self.states.all():
Lukas Burgey's avatar
Lukas Burgey committed
169
170
            item.user_credential_added(key)

171
172
        if self.state_target == DEPLOYED:
            self.publish()
Lukas Burgey's avatar
Lukas Burgey committed
173
174

    def user_credential_removed(self, key):
175
        for item in self.states.all():
Lukas Burgey's avatar
Lukas Burgey committed
176
177
            item.user_credential_removed(key)

178
179
        if self.state_target == DEPLOYED:
            self.publish()
Lukas Burgey's avatar
Lukas Burgey committed
180
181

    def publish_to_client(self):
Lukas Burgey's avatar
Lukas Burgey committed
182
        if settings.DEBUG_PUBLISHING:
183
            LOGGER.debug(self.msg('publish_to_client: {}'.format(self.state_target)))
184

185
186
187
        from .serializers import clients
        data = clients.DeploymentSerializer(self).data
        msg = dumps(data)
Lukas Burgey's avatar
Lukas Burgey committed
188

189
        brokers.RabbitMQInstance.load().publish(
190
191
192
            self,
            msg,
        )
Lukas Burgey's avatar
Lukas Burgey committed
193
194
195
196
197
198

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

Lukas Burgey's avatar
Lukas Burgey committed
199
        if settings.DEBUG_PUBLISHING:
200
            LOGGER.debug(self.msg('publish_to_user: {}'.format(self.state_target)))
201

202
        brokers.publish_to_user(
Lukas Burgey's avatar
Lukas Burgey committed
203
            self.user,
204
205
206
            {
                'deployment': self,
            },
Lukas Burgey's avatar
Lukas Burgey committed
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
        )

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

234
235
236
237
238
239
240
241
    @property
    def broker_exchange(self):
        return self.vo.broker_exchange

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

242
243
244
245
    def update(self):
        self._create_states()

    def _create_states(self):
Lukas Burgey's avatar
Lukas Burgey committed
246
247
        for service in self.services:
            DeploymentState.get_state_item(
248
249
250
                self.user,
                service.site,
                service,
251
                deployments=[self],
Lukas Burgey's avatar
Lukas Burgey committed
252
253
254
255
256
257
258
259
260
            )

    @classmethod
    def get_deployment(cls, user, vo):
        try:
            deployment = cls.objects.get(
                user=user,
                vo=vo,
            )
261
            deployment.update()
Lukas Burgey's avatar
Lukas Burgey committed
262
263
264
265
266
267
268
269
270
271

            return deployment

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

            deployment.save()
272
            deployment.update()
Lukas Burgey's avatar
Lukas Burgey committed
273

274
            LOGGER.debug(deployment.msg('Created'))
Lukas Burgey's avatar
Lukas Burgey committed
275
276
277
278
279
            return deployment

    def service_added(self, service):
        LOGGER.debug(self.msg('Adding service {}'.format(service)))
        item = DeploymentState.get_state_item(
280
281
282
            self.user,
            service.site,
            service,
283
            deployments=[self],
Lukas Burgey's avatar
Lukas Burgey committed
284
        )
285
        if str(self.state_target) == 'deployed':
Lukas Burgey's avatar
Lukas Burgey committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
            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,
    )

310
311
312
313
314
315
316
317
    @property
    def broker_exchange(self):
        return 'services'

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

318
    def _create_state(self):
Lukas Burgey's avatar
Lukas Burgey committed
319
        DeploymentState.get_state_item(
320
321
322
            self.user,
            self.service.site,
            self.service,
323
            deployments=[self],
Lukas Burgey's avatar
Lukas Burgey committed
324
325
        )

326
327
328
    def update(self):
        self._create_state()

Lukas Burgey's avatar
Lukas Burgey committed
329
330
331
332
333
334
335
    @classmethod
    def get_deployment(cls, user, service):
        try:
            deployment = cls.objects.get(
                user=user,
                service=service,
            )
336
            deployment.update()
Lukas Burgey's avatar
Lukas Burgey committed
337
338
339
340
341
342
343
344
345

            return deployment

        except cls.DoesNotExist:
            deployment = cls(
                user=user,
                service=service
            )
            deployment.save()
346
            deployment.update()
Lukas Burgey's avatar
Lukas Burgey committed
347

348
            LOGGER.debug(deployment.msg('Created'))
Lukas Burgey's avatar
Lukas Burgey committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
            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):
363
    deployments = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
364
        Deployment,
365
        related_name='states',
Lukas Burgey's avatar
Lukas Burgey committed
366
367
368
369
    )

    user = models.ForeignKey(
        User,
370
        related_name='states',
Lukas Burgey's avatar
Lukas Burgey committed
371
372
373
374
375
376
377
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
    )

    site = models.ForeignKey(
        Site,
378
        related_name='states',
Lukas Burgey's avatar
Lukas Burgey committed
379
380
381
382
383
        on_delete=models.CASCADE,
    )

    service = models.ForeignKey(
        Service,
384
        related_name='states',
Lukas Burgey's avatar
Lukas Burgey committed
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
        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,
    )

415
416
417
418
419
420
421
422
    @property
    def state_target(self):
        for deployment in self.deployments.all():
            if deployment.state_target == DEPLOYED:
                return DEPLOYED

        return NOT_DEPLOYED

Lukas Burgey's avatar
Lukas Burgey committed
423
424
425
426
    @property
    def is_pending(self):
        # TODO
        # pending because we are orphaned -> pending until removed everywhere
427
        if not self.deployments.exists():
Lukas Burgey's avatar
Lukas Burgey committed
428
429
430
            return True

        # pending because the state target is not reached
431
        if self.state_target != self.state:
Lukas Burgey's avatar
Lukas Burgey committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
            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
448
    def get_state_item(cls, user, site, service, deployments=[]):
Lukas Burgey's avatar
Lukas Burgey committed
449
450
451
452
453
454
        try:
            item = cls.objects.get(
                user=user,
                site=site,
                service=service,
            )
455
456
457
458
459
460

            for deployment in deployments:
                if not item.deployments.filter(id=deployment.id).exists():
                    LOGGER.debug(item.msg('Binding to deployment {}'.format(deployment)))
                    item.deployments.add(deployment)

Lukas Burgey's avatar
Lukas Burgey committed
461
462
463
464
465
466
467
468
469
            return item

        except cls.DoesNotExist:
            item = cls(
                user=user,
                site=site,
                service=service,
            )
            item.save()
470
471
            for deployment in deployments:
                item.deployments.add(deployment)
Lukas Burgey's avatar
Lukas Burgey committed
472

473
            LOGGER.debug(item.msg('Created'))
Lukas Burgey's avatar
Lukas Burgey committed
474
475
476
477
478
            return item

    # starts tracking this the credential for this item
    def user_credential_added(self, credential):
        if settings.DEBUG_CREDENTIALS:
479
            LOGGER.debug(self.msg('Adding credential {}'.format(credential.name)))
Lukas Burgey's avatar
Lukas Burgey committed
480
481
482
483
484
485
486
487

        CredentialState.get_credential_state(
            credential,
            self,
        )

    def user_credential_removed(self, credential):
        if settings.DEBUG_CREDENTIALS:
488
            LOGGER.debug(self.msg('Removing credential {}'.format(credential.name)))
Lukas Burgey's avatar
Lukas Burgey committed
489
490
491
492
493
494
495
496
497
498

        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

499
    # DeploymentState.user_deploy
Lukas Burgey's avatar
Lukas Burgey committed
500
    def user_deploy(self):
501
502
503
504
505
506
507
        LOGGER.debug(self.msg('user_deploy'))

        self._assure_credential_states_exist()
        for cred_state in self.credential_states.all():
            cred_state.set_target(DEPLOYED)

        if str(self.state) == REMOVAL_PENDING:
Lukas Burgey's avatar
Lukas Burgey committed
508
509
510
            self._set_state(DEPLOYED)
            return

511
512
        if str(self.state) == DEPLOYED:
            LOGGER.debug(self.msg('State: already deployed'))
Lukas Burgey's avatar
Lukas Burgey committed
513
514
            return

515
        self._set_state(DEPLOYMENT_PENDING)
Lukas Burgey's avatar
Lukas Burgey committed
516

517
518
    # DeploymentState.user_remove
    # returns True if no other deployment needs this state_item to be deployed
Lukas Burgey's avatar
Lukas Burgey committed
519
    def user_remove(self):
520
521
522
523
524
        if str(self.state_target) == DEPLOYED:
            LOGGER.debug(self.msg('user_remove: Not removing: another deployment has target deployed'))

            # False: signal the callee that a publish_to_client is *not* permitted
            return False
Lukas Burgey's avatar
Lukas Burgey committed
525

526
527
528
529
530
531
532
533
534
535
536
537
        LOGGER.debug(self.msg('user_remove'))

        for cred_state in self.credential_states.all():
            cred_state.set_target(NOT_DEPLOYED)

        if str(self.state) == NOT_DEPLOYED:
            LOGGER.debug(self.msg('State: already not_deployed'))

        elif (
                self.state_target == DEPLOYED
                and (self.state == FAILED
                     or self.state == REJECTED)
Lukas Burgey's avatar
Lukas Burgey committed
538
539
        ):
            self._reset()
540
            self._set_state(NOT_DEPLOYED)
Lukas Burgey's avatar
Lukas Burgey committed
541

542
        elif (
Lukas Burgey's avatar
Lukas Burgey committed
543
544
545
                self.state == DEPLOYMENT_PENDING
                or self.state == QUESTIONNAIRE
        ):
546
            self._set_state(NOT_DEPLOYED, publish=True)
Lukas Burgey's avatar
Lukas Burgey committed
547

548
549
        else:
            # default: start the removal process
550
            self._set_state(REMOVAL_PENDING)
551
552
553

        # True: signal the callee that a publish_to_client is permitted
        return True
Lukas Burgey's avatar
Lukas Burgey committed
554
555
556

    # user: questionnaire answered
    def user_answers(self, answers=None):
557
558
        if not self.deployments.exists():
            LOGGER.error('user_remove: no deployments')
Lukas Burgey's avatar
Lukas Burgey committed
559
560
561
            return

        self.questionnaire = answers
562
        self._set_state(DEPLOYMENT_PENDING)
563
        self.publish_to_client()
Lukas Burgey's avatar
Lukas Burgey committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579

    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)

580
    # client_response returns None on success, or a string describing an error
Lukas Burgey's avatar
Lukas Burgey committed
581
    def client_response(self, output):
582
583
584
585
586
587
588

        if 'state' not in output:
            return 'field "state" is missing in output'

        state = output.get('state', '')
        LOGGER.debug(self.msg('Client response: {}'.format(state)))

Lukas Burgey's avatar
Lukas Burgey committed
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        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', '')

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

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

        elif state == QUESTIONNAIRE:
            self.questionnaire = output.get('questionnaire', {})
            self.save()
        elif state == REJECTED:
            pass
        elif state == FAILED:
            pass
        else:
613
614
            return 'unknown state "{}"'.format(state)

615
616
617
618
619
620
        # _set_state does not always save!
        self.save()

        # publish after we updated the values of the response
        self._set_state(state, publish=True)

621
622
623
        if state == FAILED or state == REJECTED:
            return

624
        # is the target reached now?
625
        if str(self.state_target) != str(self.state):
626
627
            LOGGER.debug(self.msg('State is {}, but should be {}. Publishing again'.format(
                self.state,
628
629
630
                self.state_target,
            )))
            self.publish_to_client()
Lukas Burgey's avatar
Lukas Burgey committed
631
632
633
634
635
636
637
638
639

        return None

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

640
    def _assure_credential_states_exist(self):
Lukas Burgey's avatar
Lukas Burgey committed
641
642
643
644
645
646
647
648
649
650
651
        # 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')

652
    def _set_state(self, state, publish=False):
653
654
        self._assure_credential_states_exist()

655
        # not trans
656
        if str(self.state) == str(state):
657
658
659
            # publish to user (even if the state did not change!)
            if publish:
                self.publish_to_user()
660
661
662
            return

        LOGGER.debug(self.msg('State: {} -> {} - Target: {}'.format(self.state, state, self.state_target)))
Lukas Burgey's avatar
Lukas Burgey committed
663
664
665

        self.state = state
        self.save()
666

667
        if publish:
668
669
670
            self.publish_to_user()

    def publish_to_user(self):
671
672
673
674
675
676
677
678
679
680
        if self.user is not None:
            if settings.DEBUG_PUBLISHING:
                LOGGER.debug(self.msg('publish_to_user'))

            brokers.publish_to_user(
                self.user,
                {
                    'deployment_state': self,
                },
            )
681
682

    def publish_to_client(self):
683
684
        # only publish to the client using deployments with our target
        for deployment in self.deployments.filter(state_target=self.state_target):
685
            deployment.publish_to_client()
Lukas Burgey's avatar
Lukas Burgey committed
686
687

    def msg(self, msg):
688
        return ' {} - {}'.format(self, msg)
Lukas Burgey's avatar
Lukas Burgey committed
689
690

    def __str__(self):
691
692
693
        if self.deployments.exists():
            deployment_names = [str(deployment.id) for deployment in self.deployments.all()]

694
            return 'Dep-St: ({}:{}:{})#{}'.format(
695
                ','.join(deployment_names),
Lukas Burgey's avatar
Lukas Burgey committed
696
697
698
699
700
                self.service,
                self.site,
                self.id,
            )

701
        return 'Dep-St: (ORPHANED:{}:{})#{}'.format(
Lukas Burgey's avatar
Lukas Burgey committed
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
            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,
    )

731
    # TODO target is a stupid field name. Change it
Lukas Burgey's avatar
Lukas Burgey committed
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    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,
755
                state_target=target.state_target,
Lukas Burgey's avatar
Lukas Burgey committed
756
757
758
759
760
761
762
763
764
            )
            new_state.save()

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

            return new_state

    def set_target(self, target):
765
766
767
        if str(self.state_target) == str(target):
            return

Lukas Burgey's avatar
Lukas Burgey committed
768
769
770
771
        # state_target is locked, since we are marked for deletion
        if self._credential_deleted:
            return

772
773
        LOGGER.debug(self.msg('Target: {} -> {}'.format(self.state_target, target)))

Lukas Burgey's avatar
Lukas Burgey committed
774
775
776
777
        self.state_target = target
        self.save()

    def set(self, state):
778
779
780
        if str(self.state) == str(state):
            return

Lukas Burgey's avatar
Lukas Burgey committed
781
782
783
784
785
786
787
        if state == NOT_DEPLOYED and self._credential_deleted:
            self._delete_state()
            return

        if state == self.state:
            return

788
789
790
        if settings.DEBUG_CREDENTIALS:
            LOGGER.debug(self.msg('State: {} -> {}'.format(self.state, state)))

Lukas Burgey's avatar
Lukas Burgey committed
791
792
        self.state = state
        self.save()
793

Lukas Burgey's avatar
Lukas Burgey committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
    def credential_deleted(self):
        if self.state == NOT_DEPLOYED:
            self._delete_state()

        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):
813
        return '  {} - {}'.format(self, message)
Lukas Burgey's avatar
Lukas Burgey committed
814
815

    def __str__(self):
816
        return 'Cred-St: ({}:{})#{}'.format(
Lukas Burgey's avatar
Lukas Burgey committed
817
818
819
820
            self.target.id,
            self.credential,
            self.id,
        )