__init__.py 14.4 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

LOGGER = getLogger(__name__)


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

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

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    @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

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


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

    # which state do we currently want to reach?
    state_target = models.CharField(
        max_length=50,
        choices=STATE_CHOICES,
Lukas Burgey's avatar
Lukas Burgey committed
160
        default=DEPLOYED,
161
    )
162

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

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    # 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

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

    @property
    def sites(self):
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
        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()

226
    @classmethod
227
228
229
230
    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')

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

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

            return dep
246
247
248

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

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

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

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

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

274
275
276
277
278
279
    def user_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
280

Lukas Burgey's avatar
Lukas Burgey committed
281
282
283
284
285
286
287
288
    def user_credential_removed(self, key):
        # TODO implement
        pass

    def user_credential_added(self, key):
        # TODO implement
        pass

289
290
291
    def service_added(self, service):
        LOGGER.debug(self.msg('Adding service {}'.format(service)))
        for site in service.site.all():
292
293
            # create new NewDeploymentStateItems
            item = NewDeploymentStateItem.get_state_item(
294
295
296
297
298
299
300
301
302
303
                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
304
305
306
        from .serializers.clients import NewDeploymentSerializer
        data = NewDeploymentSerializer(self).data
        data['credentials'] = self.user_credentials
Lukas Burgey's avatar
Lukas Burgey committed
307
        msg = dumps(data)
308
309
310
311
312
313
314
315
316
317
318
319

        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:
320
            LOGGER.error('Deployment has neither a group or a service')
321
322
323
324
325
326
327
328
329
330
331
332
333
334

    # 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):
335
        return '[Deploy:{}] {}'.format(self, msg)
336
337
338
339
340
341
342
343
344
345

    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,
346
                self.user,
347
348
349
350
                self.id,
            )
        return '{}:{}#{}'.format(
            self.group,
351
            self.user,
352
353
354
355
            self.id,
        )


356
class NewDeploymentStateItem(models.Model):
357
    parent = models.ForeignKey(
358
        NewDeployment,
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
        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,
375
        default=NOT_DEPLOYED,
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
    )

    # 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
403
404
    def user_credentials(self):
        return self.parent.credentials
405
406
407
408
409
410
411
412

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

    @classmethod
    def get_state_item(cls, parent=None, site=None, service=None):
        try:
413
414
            item = cls.objects.get(
                parent=parent,
415
416
417
                site=site,
                service=service,
            )
418
419
420
            LOGGER.debug('get_state_item hit')
            return item

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
        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:
526
            return '{}:{}@{}#{}'.format(
527
528
529
530
531
                self.group,
                self.service,
                self.site,
                self.id,
            )
532
        return '{}:@{}#{}'.format(
533
534
535
536
            self.service,
            self.site,
            self.id,
        )