models.py 16 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
3
from django.conf import settings
4
from django.dispatch import receiver, Signal
Lukas Burgey's avatar
Lukas Burgey committed
5
from django.utils.timezone import make_aware
6
from rest_framework.authtoken.models import Token
7
from django.db.models.signals import post_save, pre_delete
Lukas Burgey's avatar
Lukas Burgey committed
8
# from django.db.models.signals import m2m_changed
Lukas Burgey's avatar
Lukas Burgey committed
9
from datetime import datetime
Lukas Burgey's avatar
Lukas Burgey committed
10
11
12
import requests
from requests.auth import HTTPBasicAuth
import pika
Lukas Burgey's avatar
Lukas Burgey committed
13
import json
14

15
16
deployment_change = Signal(providing_args=['instance'])

Lukas Burgey's avatar
Lukas Burgey committed
17

Lukas Burgey's avatar
Lukas Burgey committed
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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
class RabbitMQInstance(models.Model):
    host = models.CharField(
            max_length=150,
            default='localhost',
            )
    exchange = models.CharField(
            max_length=150,
            default='deployments',
            )
    port = models.IntegerField(
            default=15672
            )
    path = models.CharField(
            max_length=150,
            default='api',
            )
    username = models.CharField(
            max_length=150,
            default='guest',
            )
    password = models.CharField(
            max_length=150,
            default='guest',
            )
    enabled = models.BooleanField(
            default=False,
            )

    def __str__(self):
        return self.host

    def print(self, msg):
        print('[RabbitMQ:{}] {}'.format(self.host, msg))

    @property
    def api(self):
        return 'http://{}:{}/{}'.format(
                self.host,
                self.port,
                self.path,
                )

    @property
    def auth(self):
        return HTTPBasicAuth(
                self.username,
                self.password
                )

    @property
    def vhost(self):
        return '%2f'

    def get_uri(self, path):
        return '{}/{}'.format(self.api, path)

    def rest_get(self, api_path):
        r = requests.get(
                self.get_uri(api_path),
                auth=self.auth)
        r.raise_for_status()
        return r.json()

    # send a rest call with path and data to the rest interface of
    # the rabbitmq instance
    def rest_put(self, api_path, data):
        r = requests.put(
                self.get_uri(api_path),
                json=data,
                auth=self.auth)
        r.raise_for_status()
        return r

    def rest_del(self, api_path):
        r = requests.delete(
                self.get_uri(api_path),
                auth=self.auth)
        r.raise_for_status()
        return r

    def set_topic_permissions(self, site):
        username = site.client.username
        path = 'topic-permissions/{}/{}/'.format(
                self.vhost,
                username,
                )

        # set permissions for the correct topics
        # we construct a regex to match the services of the site
        services = ''
        omitBar = True
        for service in site.services.all():
            prefix = '|'
            if omitBar:
                prefix = ''
                omitBar = False

            services = services + prefix + service.name

        set_topic_permission_data = {
                'exchange': self.exchange,
                'write': '^$',
                'read': '^service\.({})$'.format(services),
                }

        return self.rest_put(path, set_topic_permission_data)

    # set permissions for the user
    def set_permissions(self, site):
        username = site.client.username
        path = 'permissions/{}/{}/'.format(
                self.vhost,
                username,
                )
        permission = '^(amq\.gen.*|{})'.format(self.exchange)
        set_permission_data = {
                'configure': permission,
                'write': permission,
                'read': permission,
                }

        return self.rest_put(path, set_permission_data)

    # create user at the rabbitmq instance
    def create_user(self, site):
        username = site.client.username
        path = 'users/{}/'.format(username)

        user_creation_data = {
                'password': str(site.client.auth_token.key),
                'tags': '',
                }

        return self.rest_put(path, user_creation_data)

    # delete user at the rabbitmq instance
    def delete_user(self, site):
        username = site.client.username
        path = 'users/{}/'.format(username)

        return self.rest_del(path)

    # PUBLIC API

    def register_site(self, site):
        self.print('register: {} / {}'.format(
            site.name, site.client.username))
        self.create_user(site)
        self.set_permissions(site)
        self.set_topic_permissions(site)

    def update_site(self, site):
        self.print('update: {} / {}'.format(
            site.name, site.client.username))
        self.set_topic_permissions(site)

    def deregister_site(self, site):
        self.print('deregister: {} / {}'.format(
            site.name, site.client.username))
        self.delete_user(site)

    def is_client_connected(self, site):
        connections = self.rest_get("connections/")
        clients_for_site = [c
                            for c in connections
                            if c['user'] == site.client.username]
        return len(clients_for_site) > 0

    def connect(self):
        self.connection_properties = pika.ConnectionParameters(
                host=self.host,
Lukas Burgey's avatar
Lukas Burgey committed
191
                ssl=True,
Lukas Burgey's avatar
Lukas Burgey committed
192
193
194
195
196
197
198
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
                )
        self.connection = pika.BlockingConnection(self.connection_properties)

        self.channel = self.connection.channel()
        self.channel.exchange_declare(
                exchange=self.exchange,
                durable=True,
                exchange_type='topic')
        self.channel.confirm_delivery()

    def disconnect(self):
        self.connection.close()

    def service_routing_key(self, service):
        return 'service.' + service.name

    def online_clients(self, service):
        return [site
                for site in service.site.all()
                if self.is_client_connected(site)]

    def publish_by_service(self, service, message):
        online_clients = self.online_clients(service)
        if online_clients:
            self.print("Online clients for service {}: {}".format(
                service,
                online_clients,
                ))
            self.connect()

            self.print('Sent deployment update for service {}'.format(
                service
                ))

            # True if all the clients acked the message
            delivery_confirmed = self.channel.basic_publish(
                    exchange=self.exchange,
                    routing_key=self.service_routing_key(service),
                    body=message,
                    properties=pika.BasicProperties(
                        delivery_mode=1,
                        ),
                    )

            if delivery_confirmed:
                self.print('Delivery confirmed')
            else:
                self.print('Delivery unconfirmed')

            self.disconnect()

        else:
            self.print("No clients online for service {}".format(
                service
            ))
            delivery_confirmed = False
        return delivery_confirmed, online_clients


def rabbitmq_instance():
    return RabbitMQInstance.objects.get(enabled=True)


Lukas Burgey's avatar
Lukas Burgey committed
255
class User(AbstractUser):
256
257
258
259
260
261
262
263
264
265
    TYPE_CHOICES = (
            ('apiclient', 'API-Client'),
            ('oidcuser', 'OIDC User'),
            ('admin', 'Admin'),
            )
    user_type = models.CharField(
            max_length=20,
            choices=TYPE_CHOICES,
            default='oidcuser',
            )
Lukas Burgey's avatar
Lukas Burgey committed
266
267
268
    sub = models.CharField(max_length=150, blank=True, null=True)
    password = models.CharField(max_length=150, blank=True, null=True)

Lukas Burgey's avatar
Lukas Burgey committed
269
270
271
272
273
274
    # we hide deleted keys here
    # the full list of ssh keys is at self._ssh_keys
    @property
    def ssh_keys(self):
        return self._ssh_keys.filter(deleted=False)

Lukas Burgey's avatar
Lukas Burgey committed
275
276
277
278
279
280
281
282
283
284
285
286
287

def construct_user(user_info):
    return User(
            sub=user_info['sub'],
            name=user_info['name'],
            first_name=user_info['given_name'],
            last_name=user_info['family_name'],
            email=user_info['email'],
            username=user_info['email'],
            )


class Site(models.Model):
288
289
290
    client = models.OneToOneField(
            User,
            related_name='site',
291
            )
Lukas Burgey's avatar
Lukas Burgey committed
292
293
294
295
296
297
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)

    def __str__(self):
        return self.name

Lukas Burgey's avatar
Lukas Burgey committed
298
299
300
    def ack_update(self, service=None):
        if service is None:
            for du in self.deployment_updates.all():
Lukas Burgey's avatar
Lukas Burgey committed
301
                du.done()
Lukas Burgey's avatar
Lukas Burgey committed
302
        else:
Lukas Burgey's avatar
Lukas Burgey committed
303
304
305
            for du in self.deployment_updates.all():
                if du.service.name == service.name:
                    du.done()
Lukas Burgey's avatar
Lukas Burgey committed
306

307
    def clientapi_get_deployments(self, all=False, filter=None):
308
309
        def service_deployments(service):
            if all:
Lukas Burgey's avatar
Lukas Burgey committed
310
                return service.deployments.all()
311
            else:
Lukas Burgey's avatar
Lukas Burgey committed
312
313
314
315
                ds = [deployment_update.deployment
                      for deployment_update
                      in self.deployment_updates.all()
                      if deployment_update.service.name == service.name]
316

Lukas Burgey's avatar
Lukas Burgey committed
317
                # TODO inappropriate
Lukas Burgey's avatar
Lukas Burgey committed
318
319
                self.ack_update(service=service)
                return ds
Lukas Burgey's avatar
Lukas Burgey committed
320

321
322
323
324
325
326
327
328
        if filter is not None:
            services = [s
                        for s
                        in self.services.all()
                        if s.name in filter]
        else:
            services = self.services.all()

329
330
        deployments = {service.name: service_deployments(service)
                       for service
331
                       in services}
332

Lukas Burgey's avatar
Lukas Burgey committed
333
334
        # changed deployments for this site
        # filtered by service name using filter parameter
335
        return deployments
Lukas Burgey's avatar
Lukas Burgey committed
336

Lukas Burgey's avatar
Lukas Burgey committed
337
338
339
340

class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
341
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
342
343
            Site,
            related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
344
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
345
346
347
            Group,
            related_name='services',
            blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
348
349

    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
350
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
351
352
353
354
355


class SSHPublicKey(models.Model):
    name = models.CharField(max_length=150, unique=True)
    key = models.TextField(max_length=1000)
Lukas Burgey's avatar
Lukas Burgey committed
356
    # hidden field at the user
Lukas Burgey's avatar
Lukas Burgey committed
357
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
358
            User,
Lukas Burgey's avatar
Lukas Burgey committed
359
            related_name='_ssh_keys')
Lukas Burgey's avatar
Lukas Burgey committed
360

Lukas Burgey's avatar
Lukas Burgey committed
361
362
363
364
365
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
            default=False,
            editable=False,
            )
366

367
368
369
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
370
    def delete_key(self):
371
372
373
374
375
        if (not self.deployments.exists()
                and not self.withdrawn_deployments.exists()):
            self.delete()
            return

376
377
378
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
379
        # delete implies withdrawing the key from all clients
380
381
382
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
383
384
385
386
387
388
389
390
    # when a key is withdrawn by a client we try to finally delete it
    def try_final_deletion(self):
        if (self.deleted
                and not self.deployments.exists()
                and not self.withdrawn_deployments.exists()):
            self.delete()
            return

Lukas Burgey's avatar
Lukas Burgey committed
391
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
392
393
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
394
395
396
        return self.name


Lukas Burgey's avatar
Lukas Burgey committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
class Deployment(models.Model):
    user = models.ForeignKey(
            User,
            related_name='deployments',
            on_delete=models.CASCADE,
            )
    service = models.ForeignKey(
            Service,
            related_name='deployments',
            on_delete=models.CASCADE,
            )
    # SET_NULL: we allow credentials to be deleted after deployment
    ssh_keys = models.ManyToManyField(
            SSHPublicKey,
            related_name='deployments',
            blank=True,
            )
414
415
416
417
418
419
420
421

    # these ssh keys are to be withdrawn by the clients
    ssh_keys_to_withdraw = models.ManyToManyField(
            SSHPublicKey,
            related_name='withdrawn_deployments',
            blank=True,
            )

422
    last_change = models.DateTimeField(
423
424
            editable=False,
            default=make_aware(datetime.utcfromtimestamp(0)),
425
            )
Lukas Burgey's avatar
Lukas Burgey committed
426

Lukas Burgey's avatar
Lukas Burgey committed
427
428
429
    def __str__(self):
        return '{}@{}'.format(self.user, self.service)

430
431
    def changed(self):
        print("Deployment {} changed".format(self))
Lukas Burgey's avatar
Lukas Burgey committed
432
433
434
435
436
437
438
439
440
441
442
443

        # delete old deployment_updates and generate new ones
        for du in self.deployment_updates.all():
            du.delete()

        for site in self.service.site.all():
            du = DeploymentUpdate(
                    site=site,
                    deployment=self,
                    )
            du.save()

444
445
446
        self.last_change = make_aware(datetime.now())
        self.save()

447
448
449
450
451
452
453
    def deploy_key(self, key):
        # key state: -> (2.5)
        self.ssh_keys.add(key)

        if key in self.ssh_keys_to_withdraw.all():
            self.ssh_keys_to_withdraw.remove(key)
        self.save()
454
        self.changed()
455
        self.send_change()
456
457
458
459
460
461
462
463

    def withdraw_key(self, key):
        # key state: -> (4)
        self.ssh_keys.remove(key)

        # keys which are to be withdrawn by the clients
        self.ssh_keys_to_withdraw.add(key)
        self.save()
464
        self.changed()
465
        self.send_change()
466

Lukas Burgey's avatar
Lukas Burgey committed
467
468
469
470
471
    def update(self):
        # if there are still remaining updates we do not change anything
        if self.deployment_updates.exists():
            return

Lukas Burgey's avatar
Lukas Burgey committed
472
473
        withdrawn_keys = list(self.ssh_keys_to_withdraw.all())

474
475
        # the client has withdrawn the keys so we can empty the list
        self.ssh_keys_to_withdraw.clear()
Lukas Burgey's avatar
Lukas Burgey committed
476
477
478
479

        for key in withdrawn_keys:
            key.try_final_deletion()

480
481
        self.save()

482
483
    def send_change(self):
        deployment_change.send(sender=self.__class__, instance=self)
Lukas Burgey's avatar
Lukas Burgey committed
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503


class DeploymentUpdate(models.Model):
    deployment = models.ForeignKey(
            Deployment,
            related_name='deployment_updates',
            )
    site = models.ForeignKey(
            Site,
            related_name='deployment_updates',
            )

    @property
    def user(self):
        return self.deployment.user

    @property
    def service(self):
        return self.deployment.service

Lukas Burgey's avatar
Lukas Burgey committed
504
505
506
507
508
509
510
511
512
    # to be called if all clients have received the update
    def done(self):
        print("[DeploymentUpdate:{}:{}:{}] done".format(
            self.service,
            self.site,
            self.user,
            ))
        self.delete()

Lukas Burgey's avatar
Lukas Burgey committed
513
514
    def __str__(self):
        return str(self.user) + ':' + str(self.service) + '@' + str(self.site)
Lukas Burgey's avatar
Lukas Burgey committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if instance.user_type == 'apiclient' and created:
        Token.objects.create(user=instance)


@receiver(post_save, sender=Site)
def register_at_rabbitmq(
        sender, instance=None, created=False, **kwargs):
    if not created:
        return

    RabbitMQInstance().register_site(instance)


@receiver(pre_delete, sender=Site)
def deregister_at_rabbitmq(
        sender, instance=None, **kwargs):

    RabbitMQInstance().deregister_site(instance)
Lukas Burgey's avatar
Lukas Burgey committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556


@receiver(deployment_change, sender=Deployment)
def publish_deployment(sender, instance=None, created=False, **kwargs):
    if instance is None:
        return

    from .clientapi.serializers import DeploymentSerializer
    message = json.dumps(DeploymentSerializer(instance).data)

    confirmed, online_sites = rabbitmq_instance().publish_by_service(
            instance.service, message)
    if confirmed:
        # delivery successful
        for site in online_sites:
            print('Client for site {} got update for service {}'.format(
                site,
                instance.service,
                ))
            site.ack_update(service=instance.service)