diff --git a/README.md b/README.md index 3744cca0..083d8946 100644 --- a/README.md +++ b/README.md @@ -490,7 +490,7 @@ The QR code is mailed as a link to a page that shows it, good for one hour: the On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through the server's SMTP settings (`EMAIL_HOST` and the others, as for OTP), and **Alert webhook** a JSON POST (`subject`, `text`, `time`; Slack, Mattermost and ntfy take it) when a backup job fails, a scheduled backup is not taken (not for a host in maintenance), the daily target check finds backups missing, a verification finds a backup damaged, or a job ends uncertain. The job worker sends them within a minute and tries a failed channel again for ten minutes. -`/healthz`, without a login, answers 200 while the database answers and the job worker runs, 503 otherwise: point a monitor at it. +`/healthz`, without a login, answers 200 while the database answers and the job worker runs, 503 otherwise: point a monitor at it. The Docker image's health check reads it too. ### Serial console diff --git a/conf/docker/healthcheck b/conf/docker/healthcheck index b0f5df4b..10bad2e2 100644 --- a/conf/docker/healthcheck +++ b/conf/docker/healthcheck @@ -1,10 +1,11 @@ #!/bin/sh # Docker's health check: every process has run for 5 s at least (one that -# keeps failing never has) and the panel answers through nginx. +# keeps failing never has) and the panel answers /healthz through nginx: its +# database answers and the job worker beats (a hung worker runs still). # X-Forwarded-Proto: https keeps the HTTPS profile from redirecting it. # "webvirtcloud:worker RUNNING pid 27, uptime 0:00:10" (or "1 day, 0:00:10") supervisorctl status | awk ' $2 != "RUNNING" { print; bad = 1; next } $0 !~ / day/ { split($NF, t, ":"); if (t[1] * 3600 + t[2] * 60 + t[3] < 5) { print; bad = 1 } } END { exit bad }' || exit 1 -exec /srv/webvirtcloud/venv/bin/python3 -c "import urllib.request as u; u.urlopen(u.Request('http://127.0.0.1/accounts/login/', headers={'X-Forwarded-Proto': 'https'}), timeout=5)" +exec /srv/webvirtcloud/venv/bin/python3 -c "import urllib.request as u; u.urlopen(u.Request('http://127.0.0.1/healthz', headers={'X-Forwarded-Proto': 'https'}), timeout=5)" diff --git a/vmbackups/api.py b/vmbackups/api.py index 56a1a026..73c15d98 100644 --- a/vmbackups/api.py +++ b/vmbackups/api.py @@ -20,8 +20,8 @@ def _accepted(request, op): class BackupViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): - """VM backups: list, read, back a VM up and delete a backup (jobs, - answered 202).""" + """VM backups: list, read, back a VM up, verify, restore and delete a + backup (jobs, answered 202).""" permission_classes = [IsSuperUser] serializer_class = BackupSerializer @@ -45,6 +45,15 @@ class BackupViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.G key = serializer.validated_data["submission_key"] return _accepted(request, jobs.submit("backup.delete", request.user, {"backup": str(backup.uuid)}, key)) + @extend_schema(request=SubmissionSerializer, responses={202: OperationSerializer, 400: dict, 409: ErrorSerializer}) + @action(detail=True, methods=["post"]) + def verify(self, request, uuid=None): + backup = self.get_object() + serializer = SubmissionSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + key = serializer.validated_data["submission_key"] + return _accepted(request, jobs.submit("backup.verify", request.user, {"backup": str(backup.uuid)}, key)) + @extend_schema(request=RestoreBackupSerializer, responses={202: OperationSerializer, 400: dict, 409: ErrorSerializer}) @action(detail=True, methods=["post"]) def restore(self, request, uuid=None): diff --git a/vmbackups/serializers.py b/vmbackups/serializers.py index 4f05cf6e..6ef77fe8 100644 --- a/vmbackups/serializers.py +++ b/vmbackups/serializers.py @@ -2,6 +2,7 @@ from rest_framework import serializers from computes.models import Compute from instances.models import Instance +from operations.utils import words from .models import Backup, BackupFile, BackupTarget @@ -15,13 +16,20 @@ class BackupFileSerializer(serializers.ModelSerializer): class BackupSerializer(serializers.ModelSerializer): target = serializers.SlugRelatedField(slug_field="name", read_only=True) files = BackupFileSerializer(many=True, read_only=True) + # what a verification found wrong with it or, else, with the first backup it builds on (a restore reads + # those too); empty: nothing + damage = serializers.SerializerMethodField() class Meta: model = Backup fields = ["uuid", "target", "instance", "vm_uuid", "vm_name", "compute_name", "created_at", "finished_at", - "state", "consistency", "size", "files", "operation"] + "state", "consistency", "size", "files", "operation", "verified_at", "damage"] read_only_fields = fields + def get_damage(self, backup) -> str: + damaged = backup.damaged_in_chain() + return words(damaged.damage) if damaged else "" + class CreateBackupSerializer(serializers.Serializer): instance = serializers.PrimaryKeyRelatedField(queryset=Instance.objects.all()) diff --git a/vmbackups/tests/test_verify.py b/vmbackups/tests/test_verify.py index b4215562..c5991617 100644 --- a/vmbackups/tests/test_verify.py +++ b/vmbackups/tests/test_verify.py @@ -13,6 +13,7 @@ from django.contrib.auth import get_user_model from django.core.exceptions import PermissionDenied from django.test import TransactionTestCase from django.urls import reverse +from django.utils import timezone from appsettings.settings import get_settings from computes.models import Compute @@ -328,6 +329,23 @@ class VerifyBackupTests(TransactionTestCase): self.assertContains(page, "Damaged") self.assertContains(page, "The backup's file f is missing from the target") + def test_the_api_verifies_and_tells_what_was_found(self): + self.client.force_login(self.admin) + response = self.client.post(f"/api/v1/backups/{self.full.uuid}/verify/", {"submission_key": "key-api-ver1"}, + content_type="application/json") + self.assertEqual(response.status_code, 202, response.content) + self.assertEqual(response.json()["kind"], "backup.verify") + Backup.objects.filter(pk=self.full.pk).update(verified_at=timezone.now(), damage=[ + {"text": "The backup's file %(name)s is missing from the target", "values": {"name": "f"}}]) + backup = self.client.get(f"/api/v1/backups/{self.full.uuid}/").json() + self.assertTrue(backup["verified_at"]) + self.assertEqual(backup["damage"], "The backup's file f is missing from the target") + # an incremental restores its base's files too + self.assertEqual(self.client.get(f"/api/v1/backups/{self.incremental.uuid}/").json()["damage"], + "The backup's file f is missing from the target") + Backup.objects.filter(pk=self.full.pk).update(damage=[]) + self.assertEqual(self.client.get(f"/api/v1/backups/{self.incremental.uuid}/").json()["damage"], "") + def test_a_restore_page_tells_of_damage_in_the_chain(self): self.client.force_login(self.admin) damage = [{"text": "The backup's file %(name)s is missing from the target", "values": {"name": "base-vda.qcow2"}}]