__init__.py 14.7 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,
160
        default=NOT_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
    def user_remove(self):
        for item in self.state_items.all():
276
277
            if item.state != NOT_DEPLOYED:
                item.user_remove()
Lukas Burgey's avatar
Lukas Burgey committed
278
        self._set_target('not_deployed')
279
280
        self.publish_to_client()
        # each state item publishes its state to the user
281

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

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

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

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

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

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


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

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

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

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

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
        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):
451
452
        if self.parent.state_target == DEPLOYED and (self.state == FAILED or self.state == REJECTED):
            self._reset()
Lukas Burgey's avatar
Lukas Burgey committed
453
            self._set_state(NOT_DEPLOYED, publish=False)
454
455
456
            return

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

460
        # FIXME this will break if the client 'finishes' the deployment, after user_remove
461
        if (
462
463
                self.state == DEPLOYMENT_PENDING
                or self.state == QUESTIONNAIRE
464
        ):
465
            self._set_state(NOT_DEPLOYED)
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
            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):
481
        state = output.get('state', 'undefined')
482
483
484
        self.message = output.get('message', '')
        self.save()

485
        if state != 'undefined':
486
            # update values
487
488
489
490
491
492
493
            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':
494
495
496
                # reset credentials and questi
                self._reset()
                self.save()
497
            elif state == 'questionnaire':
498
499
                self.questionnaire = output.get('questionnaire', {})
                self.save()
500
            elif state == 'rejected':
501
                pass
502
            elif state == 'failed':
503
504
                pass
            else:
505
                return 'unknown state \''+state+'\''
506

507
            self._set_state(state)
508
            return None
509
        return 'missing state in output'
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529


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