~turku/turku/turku-api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
191
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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
# Turku backups - API server
# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the Affero GNU General Public License version 3,
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the Affero GNU General Public License for more details.
#
# You should have received a copy of the Affero GNU General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.

from datetime import timedelta
import json
import uuid

from django.db import models
from django.contrib.auth.hashers import is_password_usable
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils import timezone


def new_uuid():
    return str(uuid.uuid4())


def validate_uuid(value):
    try:
        str(uuid.UUID(value))
    except ValueError:
        raise ValidationError("Invalid UUID format")


def validate_hashed_password(value):
    if not is_password_usable(value):
        raise ValidationError("Invalid hashed password")


def validate_json_string_list(value):
    try:
        decoded_json = json.loads(value)
    except ValueError:
        raise ValidationError("Must be a valid JSON string list")
    if not isinstance(decoded_json, (list, tuple, set)):
        raise ValidationError("Must be a valid JSON string list")
    for i in decoded_json:
        if not isinstance(i, str):
            raise ValidationError("Must be a valid JSON string list")


def validate_storage_auth(value):
    try:
        a = Auth.objects.get(id=value)
    except Auth.DoesNotExist:
        raise ValidationError("Auth %s does not exist" % value)
    if a.secret_type != "storage_reg":
        raise ValidationError("Must be a Storage registration")


def validate_machine_auth(value):
    try:
        a = Auth.objects.get(id=value)
    except Auth.DoesNotExist:
        raise ValidationError("Auth %s does not exist" % value)
    if a.secret_type != "machine_reg":
        raise ValidationError("Must be a Machine registration")


class UuidPrimaryKeyField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs["blank"] = True
        kwargs["default"] = new_uuid
        kwargs["editable"] = False
        kwargs["max_length"] = 36
        kwargs["primary_key"] = True
        super(UuidPrimaryKeyField, self).__init__(*args, **kwargs)


class Auth(models.Model):
    SECRET_TYPES = (
        ("machine_reg", "Machine registration"),
        ("storage_reg", "Storage registration"),
    )
    id = UuidPrimaryKeyField()
    name = models.CharField(
        max_length=200, unique=True, help_text="Human-readable name of this auth."
    )
    secret_hash = models.CharField(
        max_length=200,
        validators=[validate_hashed_password],
        help_text="Hashed secret (password) of this auth.",
    )
    secret_type = models.CharField(
        max_length=200,
        choices=SECRET_TYPES,
        help_text="Auth secret type (machine/storage).",
    )
    comment = models.CharField(
        max_length=200, blank=True, null=True, help_text="Human-readable comment."
    )
    active = models.BooleanField(
        default=True,
        help_text="Whether this auth is enabled.  Disabling prevents new registrations using its key, and prevents "
        + "existing machines using its key from updating their configs.",
    )
    date_added = models.DateTimeField(
        default=timezone.now, help_text="Date/time this auth was added."
    )

    def __str__(self):
        return self.name


class Storage(models.Model):
    def healthy(self):
        now = timezone.now()
        if now <= (self.date_registered + timedelta(minutes=30)):
            # New registration, assume it's healthy
            return True
        if not self.date_checked_in:
            return False
        return now <= (self.date_checked_in + timedelta(minutes=30))

    healthy.boolean = True

    id = UuidPrimaryKeyField()
    name = models.CharField(
        max_length=200,
        unique=True,
        help_text="Name of this storage unit.  This is used as its login ID and must be unique.",
    )
    secret_hash = models.CharField(
        max_length=200,
        validators=[validate_hashed_password],
        help_text="Hashed secret (password) of this storage unit.",
    )
    comment = models.CharField(
        max_length=200, blank=True, null=True, help_text="Human-readable comment."
    )
    ssh_ping_host = models.CharField(
        max_length=200,
        verbose_name="SSH ping host",
        help_text="Hostname/IP address of this storage unit's SSH server.",
    )
    ssh_ping_host_keys = models.CharField(
        max_length=65536,
        default="[]",
        validators=[validate_json_string_list],
        verbose_name="SSH ping host keys",
        help_text="JSON list of this storage unit's SSH host keys.",
    )
    ssh_ping_port = models.PositiveIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        verbose_name="SSH ping port",
        help_text="Port number of this storage unit's SSH server.",
    )
    ssh_ping_user = models.CharField(
        max_length=200,
        verbose_name="SSH ping user",
        help_text="Username of this storage unit's SSH server.",
    )
    space_total = models.PositiveIntegerField(
        default=0,
        help_text="Total disk space of this storage unit's storage directories, in MiB.",
    )
    space_available = models.PositiveIntegerField(
        default=0,
        help_text="Available disk space of this storage unit's storage directories, in MiB.",
    )
    auth = models.ForeignKey(
        Auth,
        validators=[validate_storage_auth],
        on_delete=models.CASCADE,
        help_text="Storage auth used to register this storage unit.",
    )
    active = models.BooleanField(
        default=True,
        help_text="Whether this storage unit is enabled.  Disabling prevents this storage unit from checking in or "
        + "being assigned to new machines. Existing machines which ping this storage unit will get errors "
        + "because this storage unit can no longer query the API server.",
    )
    published = models.BooleanField(
        default=True, help_text="Whether this storage unit has been enabled by itself."
    )
    date_registered = models.DateTimeField(
        default=timezone.now, help_text="Date/time this storage unit was registered."
    )
    date_updated = models.DateTimeField(
        default=timezone.now,
        help_text="Date/time this storage unit presented a modified config.",
    )
    date_checked_in = models.DateTimeField(
        blank=True, null=True, help_text="Date/time this storage unit last checked in."
    )

    def __str__(self):
        return self.name


class Machine(models.Model):
    def healthy(self):
        now = timezone.now()
        if now <= (self.date_registered + timedelta(hours=1)):
            # New registration, assume it's healthy
            return True
        if not self.date_checked_in:
            return False
        return now <= (self.date_checked_in + timedelta(hours=10))

    healthy.boolean = True

    id = UuidPrimaryKeyField()
    uuid = models.CharField(
        max_length=36,
        unique=True,
        validators=[validate_uuid],
        verbose_name="UUID",
        help_text="UUID of this machine.  This UUID is set by the machine and must be globally unique.",
    )
    secret_hash = models.CharField(
        max_length=200,
        validators=[validate_hashed_password],
        help_text="Hashed secret (password) of this machine.",
    )
    environment_name = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        help_text="Environment this machine is part of.",
    )
    service_name = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        help_text="Service this machine is part of.  For Juju units, this is the first part of the unit name "
        + "(before the slash).",
    )
    unit_name = models.CharField(
        max_length=200,
        help_text='Unit name of this machine.  For Juju units, this is the full unit name (e.g. "service-name/0").  '
        + "Otherwise, this should be the machine's hostname.",
    )
    comment = models.CharField(
        max_length=200, blank=True, null=True, help_text="Human-readable comment."
    )
    ssh_public_key = models.CharField(
        max_length=2048,
        verbose_name="SSH public key",
        help_text="SSH public key of this machine's agent.",
    )
    auth = models.ForeignKey(
        Auth,
        validators=[validate_machine_auth],
        on_delete=models.CASCADE,
        help_text="Machine auth used to register this machine.",
    )
    storage = models.ForeignKey(
        Storage,
        on_delete=models.CASCADE,
        help_text="Storage unit this machine is assigned to.",
    )
    active = models.BooleanField(
        default=True,
        help_text="Whether this machine is enabled.  Disabling removes its key from its storage unit, stops this "
        + "machine from updating its registration, etc.",
    )
    published = models.BooleanField(
        default=True,
        help_text="Whether this machine has been enabled by the machine agent.",
    )
    date_registered = models.DateTimeField(
        default=timezone.now, help_text="Date/time this machine was registered."
    )
    date_updated = models.DateTimeField(
        default=timezone.now,
        help_text="Date/time this machine presented a modified config.",
    )
    date_checked_in = models.DateTimeField(
        blank=True, null=True, help_text="Date/time this machine last checked in."
    )

    def __str__(self):
        return "%s (%s)" % (self.unit_name, self.uuid[0:8])


class Source(models.Model):
    def healthy(self):
        now = timezone.now()
        if now <= (self.date_added + timedelta(hours=4)):
            # New addition, assume it's healthy
            return True
        if not self.success:
            return False
        return now <= (self.date_next_backup + timedelta(hours=10))

    healthy.boolean = True

    SNAPSHOT_MODES = (
        ("none", "No snapshotting"),
        ("attic", "Attic"),
        ("link-dest", "Hardlink trees (rsync --link-dest)"),
    )
    id = UuidPrimaryKeyField()
    name = models.CharField(
        max_length=200, help_text="Computer-readable source name identifier."
    )
    machine = models.ForeignKey(
        Machine, on_delete=models.CASCADE, help_text="Machine this source belongs to."
    )
    comment = models.CharField(
        max_length=200, blank=True, null=True, help_text="Human-readable comment."
    )
    path = models.CharField(
        max_length=200, help_text="Full filesystem path of this source."
    )
    filter = models.CharField(
        max_length=2048,
        default="[]",
        validators=[validate_json_string_list],
        help_text="JSON list of rsync-compatible --filter options.",
    )
    exclude = models.CharField(
        max_length=2048,
        default="[]",
        validators=[validate_json_string_list],
        help_text="JSON list of rsync-compatible --exclude options.",
    )
    frequency = models.CharField(
        max_length=200, default="daily", help_text="How often to back up this source."
    )
    retention = models.CharField(
        max_length=200,
        default="last 5 days, earliest of month",
        help_text="Retention schedule, describing when to preserve snapshots.",
    )
    bwlimit = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        verbose_name="bandwidth limit",
        help_text="Bandwith limit for remote transfer, using the rsync --bwlimit format.",
    )
    snapshot_mode = models.CharField(
        blank=True,
        null=True,
        max_length=200,
        choices=SNAPSHOT_MODES,
        help_text="Override the storage unit's snapshot logic and use an explicit snapshot mode for this source.",
    )
    preserve_hard_links = models.BooleanField(
        default=False,
        help_text="Whether to preserve hard links when backing up this source.",
    )
    shared_service = models.BooleanField(
        default=False,
        help_text="Whether this source is part of a shared service of multiple machines to be backed up.",
    )
    large_rotating_files = models.BooleanField(
        default=False,
        help_text="Whether this source contains a number of large files which rotate through filenames, e.g. "
        + '"postgresql.1.dump.gz" becomes "postgresql.2.dump.gz".',
    )
    large_modifying_files = models.BooleanField(
        default=False,
        help_text="Whether this source contains a number of large files which grow or are otherwise modified, "
        + "e.g. log files or filesystem images.",
    )
    active = models.BooleanField(
        default=True,
        help_text="Whether this source is enabled.  Disabling means the API server no longer gives it to the "
        + "storage unit, even if it's time for a backup.",
    )
    success = models.BooleanField(
        default=True, help_text="Whether this source's last backup was successful."
    )
    published = models.BooleanField(
        default=True,
        help_text="Whether this source is actively being published by the machine agent.",
    )
    date_added = models.DateTimeField(
        default=timezone.now,
        help_text="Date/time this source was first added by the machine agent.",
    )
    date_updated = models.DateTimeField(
        default=timezone.now,
        help_text="Date/time the machine presented a modified config of this source.",
    )
    date_last_backed_up = models.DateTimeField(
        blank=True,
        null=True,
        help_text="Date/time this source was last successfully backed up.",
    )
    date_next_backup = models.DateTimeField(
        default=timezone.now,
        help_text="Date/time this source is next scheduled to be backed up.  Set to now (or in the past) to "
        + "trigger a backup as soon as possible.",
    )

    class Meta:
        unique_together = (("machine", "name"),)

    def __str__(self):
        return "%s %s" % (self.machine.unit_name, self.name)


class BackupLog(models.Model):
    id = UuidPrimaryKeyField()
    source = models.ForeignKey(
        Source, on_delete=models.CASCADE, help_text="Source this log entry belongs to."
    )
    date = models.DateTimeField(
        default=timezone.now,
        help_text="Date/time this log entry was received/processed.",
    )
    storage = models.ForeignKey(
        Storage,
        blank=True,
        null=True,
        on_delete=models.CASCADE,
        help_text="Storage unit this backup occurred on.",
    )
    success = models.BooleanField(
        default=False, help_text="Whether this backup succeeded."
    )
    date_begin = models.DateTimeField(
        blank=True, null=True, help_text="Date/time this backup began."
    )
    date_end = models.DateTimeField(
        blank=True, null=True, help_text="Date/time this backup ended."
    )
    snapshot = models.CharField(
        max_length=200, blank=True, null=True, help_text="Name of the created snapshot."
    )
    summary = models.TextField(
        blank=True, null=True, help_text="Summary of the backup's events."
    )

    def __str__(self):
        return "%s %s" % (str(self.source), self.date.strftime("%Y-%m-%d %H:%M:%S"))


class FilterSet(models.Model):
    id = UuidPrimaryKeyField()
    name = models.CharField(
        max_length=200, unique=True, help_text="Name of this filter set."
    )
    filters = models.TextField(
        default="[]",
        validators=[validate_json_string_list],
        help_text="JSON list of this filter set's filter rules.",
    )
    comment = models.CharField(
        max_length=200, blank=True, null=True, help_text="Human-readable comment."
    )
    active = models.BooleanField(
        default=True, help_text="Whether this filter set is enabled."
    )
    date_added = models.DateTimeField(
        default=timezone.now, help_text="Date/time this filter set was added."
    )

    def __str__(self):
        return self.name