models.py 8.32 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

Lukas Burgey's avatar
Lukas Burgey committed
11
from .rabbitmq import RabbitMQInstance
12

13
14
deployment_change = Signal(providing_args=['instance'])

Lukas Burgey's avatar
Lukas Burgey committed
15
16

class User(AbstractUser):
17
18
19
20
21
22
23
24
25
26
    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
27
28
29
    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
30
31
32
33
34
35
    # 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
36

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


Lukas Burgey's avatar
Lukas Burgey committed
43
44
45
46
47
48
49
50
51
52
53
54
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):
55
56
57
    client = models.OneToOneField(
            User,
            related_name='site',
58
            )
Lukas Burgey's avatar
Lukas Burgey committed
59
60
61
62
63
64
    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
65
66
67
68
69
70
71
72
    def ack_update(self, service=None):
        if service is None:
            for du in self.deployment_updates.all():
                du.delete()
        else:
            for deployment_update in self.deployment_updates.all():
                if deployment_update.service.name == service.name:
                    deployment_update.delete()
Lukas Burgey's avatar
Lukas Burgey committed
73

74
    def clientapi_get_deployments(self, all=False, filter=None):
75
76
        def service_deployments(service):
            if all:
Lukas Burgey's avatar
Lukas Burgey committed
77
                return service.deployments.all()
78
            else:
Lukas Burgey's avatar
Lukas Burgey committed
79
80
81
82
                ds = [deployment_update.deployment
                      for deployment_update
                      in self.deployment_updates.all()
                      if deployment_update.service.name == service.name]
83

Lukas Burgey's avatar
Lukas Burgey committed
84
85
86
                # TODO is this apropriate?
                self.ack_update(service=service)
                return ds
Lukas Burgey's avatar
Lukas Burgey committed
87

88
89
90
91
92
93
94
95
        if filter is not None:
            services = [s
                        for s
                        in self.services.all()
                        if s.name in filter]
        else:
            services = self.services.all()

96
97
        deployments = {service.name: service_deployments(service)
                       for service
98
                       in services}
99

Lukas Burgey's avatar
Lukas Burgey committed
100
101
        # changed deployments for this site
        # filtered by service name using filter parameter
102
        return deployments
Lukas Burgey's avatar
Lukas Burgey committed
103

Lukas Burgey's avatar
Lukas Burgey committed
104

105
@receiver(post_save, sender=Site)
Lukas Burgey's avatar
Lukas Burgey committed
106
107
def register_at_rabbitmq(
        sender, instance=None, created=False, **kwargs):
108
109
110
    if not created:
        return

Lukas Burgey's avatar
Lukas Burgey committed
111
    RabbitMQInstance().register_site(instance)
112
113


114
115
116
117
118
119
120
@receiver(pre_delete, sender=Site)
def deregister_at_rabbitmq(
        sender, instance=None, **kwargs):

    RabbitMQInstance().deregister_site(instance)


Lukas Burgey's avatar
Lukas Burgey committed
121
122
123
class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
124
    site = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
125
126
            Site,
            related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
127
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
128
129
130
            Group,
            related_name='services',
            blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
131
132

    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
133
        return self.name
Lukas Burgey's avatar
Lukas Burgey committed
134
135
136
137
138


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
139
    # hidden field at the user
Lukas Burgey's avatar
Lukas Burgey committed
140
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
141
            User,
Lukas Burgey's avatar
Lukas Burgey committed
142
            related_name='_ssh_keys')
Lukas Burgey's avatar
Lukas Burgey committed
143

Lukas Burgey's avatar
Lukas Burgey committed
144
145
146
147
148
    # has the user triggered the deletion of this key
    deleted = models.BooleanField(
            default=False,
            editable=False,
            )
149

150
151
152
    # does not directly delete the key if the key is deployed or withdrawn
    # somewhere
    # the receiver 'delete_withdrawn_ssh_key' does the actual deletion
153
    def delete_key(self):
154
155
156
157
158
        if (not self.deployments.exists()
                and not self.withdrawn_deployments.exists()):
            self.delete()
            return

159
160
161
        self.deleted = True
        self.save()

Lukas Burgey's avatar
Lukas Burgey committed
162
        # delete implies withdrawing the key from all clients
163
164
165
        for deployment in self.deployments.all():
            deployment.withdraw_key(self)

Lukas Burgey's avatar
Lukas Burgey committed
166
167
168
169
170
171
172
173
    # 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
174
    def __str__(self):
Lukas Burgey's avatar
Lukas Burgey committed
175
176
        if self.deleted:
            return "DELETED: {}".format(self.name)
Lukas Burgey's avatar
Lukas Burgey committed
177
178
179
        return self.name


Lukas Burgey's avatar
Lukas Burgey committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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,
            )
197
198
199
200
201
202
203
204

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

205
    last_change = models.DateTimeField(
206
207
            editable=False,
            default=make_aware(datetime.utcfromtimestamp(0)),
208
            )
Lukas Burgey's avatar
Lukas Burgey committed
209

Lukas Burgey's avatar
Lukas Burgey committed
210
211
212
    def __str__(self):
        return '{}@{}'.format(self.user, self.service)

213
214
    def changed(self):
        print("Deployment {} changed".format(self))
Lukas Burgey's avatar
Lukas Burgey committed
215
216
217
218
219
220
221
222
223
224
225
226

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

227
228
229
        self.last_change = make_aware(datetime.now())
        self.save()

230
231
232
233
234
235
236
    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()
237
        self.changed()
238
        self.send_change()
239
240
241
242
243
244
245
246

    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()
247
        self.changed()
248
        self.send_change()
249

Lukas Burgey's avatar
Lukas Burgey committed
250
251
252
253
254
    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
255
256
        withdrawn_keys = list(self.ssh_keys_to_withdraw.all())

257
258
        # 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
259
260
261
262

        for key in withdrawn_keys:
            key.try_final_deletion()

263
264
        self.save()

265
266
    def send_change(self):
        deployment_change.send(sender=self.__class__, instance=self)
Lukas Burgey's avatar
Lukas Burgey committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288


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

    def __str__(self):
        return str(self.user) + ':' + str(self.service) + '@' + str(self.site)