__init__.py 15.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
Lukas Burgey's avatar
Lukas Burgey committed
11
from .groups import GroupDescription
12
13
14
15

LOGGER = getLogger(__name__)


16
17
18
19
20
21
22
23
DEPLOYMENT_PENDING = 'deployment_pending'
REMOVAL_PENDING = 'removal_pending'
NOT_DEPLOYED = 'not_deployed'
DEPLOYED = 'deployed'
QUESTIONNAIRE = 'questionnaire'
FAILED = 'failed'
REJECTED = 'rejected'

24
STATE_CHOICES = (
25
26
27
28
29
30
31
    (DEPLOYMENT_PENDING, 'Deployment Pending'),
    (REMOVAL_PENDING, 'Removal Pending'),
    (DEPLOYED, 'Deployed'),
    (NOT_DEPLOYED, 'Not Deployed'),
    (QUESTIONNAIRE, 'Questionnaire'),
    (FAILED, 'Failed'),
    (REJECTED, 'Rejected'),
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
)
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,
    )

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    @classmethod
    def get_service(cls, name, description='', sites=None, groups=None):
        try:
            return cls.objects.get(name=name)
        except cls.DoesNotExist:
            service = cls(
                name=name,
                description=description,
            )
            service.save()

            if sites is not None:
                for site in sites:
                    service.site.add(site)
            if groups is not None:
                for group in groups:
                    service.groups.add(group)

            return service

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    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)
130
                except NewDeployment.DoesNotExist:
131
132
133
134
                    LOGGER.error('Inconsistency of group deployment')
                    raise


135
class NewDeployment(models.Model):
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    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,
    )
156
157
158
159
160

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

164
165
166
167
    is_active = models.BooleanField(
        default=True,
    )

168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    # credentials provided by the backend to the clients
    @property
    def user_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

192
193
194
195
    @property
    def services(self):
        if self.group is not None:
            return self.group.services.all()
196
        return [self.service]
197
198
199

    @property
    def sites(self):
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
        return [
            service.site
            for service in self.services
        ]

    def create_state_items(self, site=None):
        for service in self.services:
            LOGGER.debug('create_state_items: creating NewDeploymentStateItem for service %s at sites %s', service, service.site.all())

            if site is None:
                if not service.site.exists():
                    raise ValueError('Cannot create state item for service without site')

                for service_site in service.site.all():
                    # LOGGER.debug('create_state_items: creating NewDeploymentStateItems for service %s at site %s', service, service_site)
                    NewDeploymentStateItem.get_state_item(
                        parent=self,
                        site=service_site,
                        service=service,
                    ).save()
            else:
                NewDeploymentStateItem.get_state_item(
                    parent=self,
                    site=site,
                    service=service,
                ).save()

227
    @classmethod
228
229
230
231
    def get_deployment(cls, user, service=None, group=None, site=None):
        if service is None and group is None:
            raise ValueError('get_deployment needs a service or a group')

232
        try:
233
            dep = None
234
            if service is not None:
235
                dep = cls.objects.get(
236
237
238
239
240
                    user=user,
                    service=service,
                )

            elif group is not None:
241
                dep = cls.objects.get(
242
243
244
                    user=user,
                    group=group,
                )
245
246

            return dep
247
248
249

        except cls.DoesNotExist:
            deployment = None
250
            if service is not None and group is None:
251
252
253
254
                deployment = cls(
                    user=user,
                    service=service,
                )
255

256
257
258
259
260
261
262
            elif group is not None:
                deployment = cls(
                    user=user,
                    group=group,
                )

            deployment.save()
263
264
            deployment.create_state_items(site=site)

265
266
267
            LOGGER.debug(deployment.msg('created'))
            return deployment

268
269
270
271
272
273
    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
274

275
276
    def user_remove(self):
        for item in self.state_items.all():
277
278
            if item.state != NOT_DEPLOYED:
                item.user_remove()
279
        self._set_target(NOT_DEPLOYED)
280
281
        self.publish_to_client()
        # each state item publishes its state to the user
282

283
284
285
286
    # some parts of the user object / the credentials have changed
    # we have to update them at the clients
    def user_credentials_changed(self):
        LOGGER.debug('User object of %s changed', self.user)
Lukas Burgey's avatar
Lukas Burgey committed
287
288
        pass
        # TODO implement
289
290
291
292
293
294
295
296
297

    # Currently out of scope
    # def user_credential_added(self, key):
    #     raise Exception('user_credentialis currently out of scope and therefore not implemented')

    # Currently out of scope
    # def user_credential_removed(self, key):
    #     # TODO implement
    #     raise Exception('user_credential_removed is currently out of scope and therefore not implemented')
Lukas Burgey's avatar
Lukas Burgey committed
298

299
300
301
    def service_added(self, service):
        LOGGER.debug(self.msg('Adding service {}'.format(service)))
        for site in service.site.all():
302
303
            # create new NewDeploymentStateItems
            item = NewDeploymentStateItem.get_state_item(
304
305
306
307
308
309
310
311
312
313
                parent=self,
                site=site,
                service=service,
            )
            item.save()
            if self.state_target == 'deployed':
                item.user_deploy()

    def publish_to_client(self):
        # mitigating circular dependencies here
314
315
316
        from .serializers.clients import NewDeploymentSerializer
        data = NewDeploymentSerializer(self).data
        data['credentials'] = self.user_credentials
Lukas Burgey's avatar
Lukas Burgey committed
317
        msg = dumps(data)
318
319
320
321
322
323
324
325
326
327
328
329

        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:
330
            LOGGER.error('Deployment has neither a group or a service')
331
            raise ValueError('Deployment has neither a group or a service')
332
333
334
335

    # update the state of the remote webpage
    def publish_to_user(self):
        if self.user is not None:
336
            # mitigating circular dependencies here
337
338
339
340
341
342
343
344
345
346
            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):
347
        return '[Deploy:{}] {}'.format(self, msg)
348
349
350

    def _set_target(self, target):
        self.state_target = target
351
        LOGGER.debug(self.msg('target is now: '+target))
352
353
354
355
356
357
        self.save()

    def __str__(self):
        if self.service is not None:
            return '{}:{}#{}'.format(
                self.service,
358
                self.user,
359
360
361
362
                self.id,
            )
        return '{}:{}#{}'.format(
            self.group,
363
            self.user,
364
365
366
367
            self.id,
        )


368
class NewDeploymentStateItem(models.Model):
369
    parent = models.ForeignKey(
370
        NewDeployment,
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
        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,
387
        default=NOT_DEPLOYED,
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
    )

    # 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
415
416
    def user_credentials(self):
        return self.parent.credentials
417
418
419
420
421
422
423
424

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

    @classmethod
    def get_state_item(cls, parent=None, site=None, service=None):
        try:
425
426
            item = cls.objects.get(
                parent=parent,
427
428
429
                site=site,
                service=service,
            )
430
            LOGGER.debug('get_state_item: item already exists')
431
432
            return item

433
434
435
436
437
438
439
440
441
442
        except cls.DoesNotExist:
            item = cls(
                parent=parent,
                site=site,
                service=service,
            )
            item.save()
            LOGGER.debug(item.msg('created'))
            return item

443
    # STATE TRANSITIONS
444
445
446

    # user: deployment requested
    def user_deploy(self):
447
448
        if self.state == REMOVAL_PENDING:
            self._set_state(DEPLOYED)
449
450
            return

451
        if self.state == DEPLOYED:
452
453
454
455
            LOGGER.info(self.msg('ignoring invalid state transition user_deploy'))
            return

        self._set_state(
456
457
            DEPLOYMENT_PENDING,
            publish=False,  # the post response already contains the update
458
459
460
461
        )

    # user: removal requested
    def user_remove(self):
462
463
464
465
        if (
                self.parent.state_target == DEPLOYED
                and (self.state == FAILED or self.state == REJECTED)
        ):
466
            self._reset()
Lukas Burgey's avatar
Lukas Burgey committed
467
            self._set_state(NOT_DEPLOYED, publish=False)
468
469
470
            return

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

474
        # FIXME this will break if the client 'finishes' the deployment, after user_remove
475
        if (
476
477
                self.state == DEPLOYMENT_PENDING
                or self.state == QUESTIONNAIRE
478
        ):
479
            self._set_state(NOT_DEPLOYED)
480
481
482
            return

        self._set_state(
483
484
            REMOVAL_PENDING,
            publish=False,  # the post response already contains the update
485
486
487
488
489
490
491
492
493
494
        )

    # 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):
495
        state = output.get('state', None)
496
497
498
        self.message = output.get('message', '')
        self.save()

499
500
        if state is None:
            return 'missing state in output'
501

502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
        # update values
        if state == DEPLOYED:
            if self.parent.state_target == NOT_DEPLOYED:
                self.user_remove()
            else:
                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:
            return 'unknown state \''+state+'\''
522

523
524
        self._set_state(state)
        return None
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543

    # 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):
        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:
544
            return '{}:{}@{}#{}'.format(
545
546
547
548
549
                self.group,
                self.service,
                self.site,
                self.id,
            )
550
        return '{}:@{}#{}'.format(
551
552
553
554
            self.service,
            self.site,
            self.id,
        )