1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix: the API verifies a backup and shows what was found; Docker's health check reads /healthz

The backups API had every backup action but Verify, and did not show a
backup's verified_at and damage: a script restoring through it got no sign
of a damaged chain. Docker's health check asked for the login page, so a
hung job worker left the container healthy; it now reads /healthz.
This commit is contained in:
catborise 2026-11-19 20:45:09 +03:00
parent fc6ad4e8ca
commit 7b23c75bf5
5 changed files with 42 additions and 6 deletions

View file

@ -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

View file

@ -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)"

View file

@ -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):

View file

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

View file

@ -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&#x27;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"}}]