mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +00:00
feat(vmbackups): back up a running or shut-off VM into a target
A superuser backs a VM up from its new Backups tab, or with POST /api/v1/backups/ (202 with the job); GET lists and reads backups. The backup.create job holds the VM, its compute (shared) and the target, so migrations, snapshots and power changes of the VM wait meanwhile. - A shut-off VM's disks are copied one at a time into the target pool, flat, in their format (createXMLFrom); a cancel stops before the next. - A running or paused VM's disks go by libvirt's push backup into volumes made first, as the live clone: the file systems frozen for its start when the guest agent answers (frozen), crash-consistent otherwise, or refused when frozen file systems are required. A guest that shuts down meanwhile does not end the backup. - A running VM's NVRAM file is kept only when it reads the same after the copy as before it (three reads), so it is the capture point's. - Then the NVRAM file, the definition and the manifest (written last) are uploaded and read back, and the row becomes ready with its files. - Recovery thaws a frozen guest first, watches a push backup still running, finishes a copied backup, removes the files of a failed or cancelled one, and leaves a copy whose end libvirt cannot tell uncertain with its files named. The target pool is checked by UUID and its free space before anything is made.
This commit is contained in:
parent
89835f2b06
commit
f4559acbc7
17 changed files with 1703 additions and 353 deletions
|
|
@ -107,6 +107,11 @@
|
|||
<button class="nav-link text-nowrap" id="graphics-tab" aria-controls="graphics" data-bs-toggle="pill" data-bs-target="#graphics" type="button" role="tab" aria-selected="false">{% bs_icon 'bar-chart-line' %} {% trans "Stats" %}</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if backups %}
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link text-nowrap" id="backups-tab" aria-controls="backups" data-bs-toggle="pill" data-bs-target="#backups" type="button" role="tab" aria-selected="false">{% bs_icon 'archive' %} {% trans "Backups" %}</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link text-nowrap" id="undefine-tab" aria-controls="undefine" data-bs-toggle="pill" data-bs-target="#undefine" type="button" role="tab" aria-selected="false">{% bs_icon 'trash' %} {% trans "Destroy" %}</button>
|
||||
</li>
|
||||
|
|
@ -126,6 +131,7 @@
|
|||
{% if can_snapshot and not instance.is_template %}{% include 'instances/snapshots_tab.html' %}{% endif %}
|
||||
{% if show_settings %}{% include 'instances/settings_tab.html' %}{% endif %}
|
||||
{% if not instance.is_template %}{% include 'instances/stats_tab.html' %}{% endif %}
|
||||
{% if backups %}{% include 'vmbackups/vm_tab.html' %}{% endif %}
|
||||
{% include 'instances/destroy_tab.html' %}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ from vrtManager.util import randomPasswd
|
|||
|
||||
from instances.models import Instance
|
||||
from instances.templatetags.vm_states import disk_seen
|
||||
from vmbackups.utils import vm_tab
|
||||
|
||||
from . import addresses, report, utils
|
||||
from .api.serializers import DestroyOptionsSerializer, PowerOnSerializer
|
||||
|
|
@ -386,8 +387,12 @@ def _instance_page(request, pk, instance, compute):
|
|||
else:
|
||||
migrate_refusal = None
|
||||
|
||||
# superusers back VMs up; not a template, which is cloned
|
||||
backups = vm_tab(instance) if request.user.is_superuser and not instance.is_template else None
|
||||
|
||||
return render(request, "instance.html", {
|
||||
"instance": instance,
|
||||
"backups": backups,
|
||||
"compute": compute,
|
||||
"computes": computes,
|
||||
"users": users,
|
||||
|
|
|
|||
Binary file not shown.
File diff suppressed because it is too large
Load diff
Binary file not shown.
File diff suppressed because it is too large
Load diff
32
vmbackups/api.py
Normal file
32
vmbackups/api.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
from django.urls import reverse
|
||||
from drf_spectacular.utils import extend_schema
|
||||
from rest_framework import mixins, status, viewsets
|
||||
from rest_framework.response import Response
|
||||
|
||||
from admin.permissions import IsSuperUser
|
||||
from operations import jobs
|
||||
from operations.api.serializers import OperationSerializer
|
||||
from webvirtcloud.serializers import ErrorSerializer
|
||||
|
||||
from .models import Backup
|
||||
from .serializers import BackupSerializer, CreateBackupSerializer
|
||||
|
||||
|
||||
class BackupViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
"""VM backups: list, read, and back a VM up (a job, answered 202)."""
|
||||
|
||||
permission_classes = [IsSuperUser]
|
||||
serializer_class = BackupSerializer
|
||||
queryset = Backup.objects.select_related("target").prefetch_related("files")
|
||||
lookup_field = "uuid"
|
||||
|
||||
@extend_schema(request=CreateBackupSerializer, responses={202: OperationSerializer, 400: dict, 409: ErrorSerializer})
|
||||
def create(self, request):
|
||||
serializer = CreateBackupSerializer(data=request.data)
|
||||
if not serializer.is_valid():
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
data = serializer.validated_data
|
||||
raw = {"instance": data["instance"].pk, "target": data["target"].pk, "frozen": data["frozen"]}
|
||||
op = jobs.submit("backup.create", request.user, raw, data["submission_key"])
|
||||
return Response(OperationSerializer(op, context={"request": request}).data, status=status.HTTP_202_ACCEPTED,
|
||||
headers={"Location": reverse("operation-detail", args=[op.pk])})
|
||||
409
vmbackups/jobs.py
Normal file
409
vmbackups/jobs.py
Normal file
|
|
@ -0,0 +1,409 @@
|
|||
"""Jobs of the vmbackups app (operations framework)."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_noop as _
|
||||
from libvirt import VIR_DOMAIN_PAUSED, VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF, VIR_ERR_NO_DOMAIN, libvirtError
|
||||
|
||||
from appsettings.settings import app_settings
|
||||
from instances.jobs import PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapshot_free_space
|
||||
from instances.models import Instance
|
||||
from operations import claims
|
||||
from operations.jobs import Cancelled, Kind, Outcome, Plan, register
|
||||
from operations.models import Claim, Operation
|
||||
from operations.utils import safe_text, say
|
||||
from vrtManager import util
|
||||
from vrtManager.backup import backup_file_names, check_target_space, put_file, remove_files, target_pool, wvmBackup
|
||||
from vrtManager.instance import LIVE_CLONE_MIN_LIBVIRT
|
||||
|
||||
from .models import Backup, BackupFile, BackupTarget
|
||||
|
||||
MANIFEST_FORMAT = 1
|
||||
NVRAM_READS = 3 # a running VM's NVRAM read after its backup, until it is the one read before
|
||||
NVRAM_WAIT = 5 # seconds between those reads
|
||||
PROGRESS_EVERY = 2 # seconds between reads of a push backup's progress
|
||||
|
||||
|
||||
def _superuser(user):
|
||||
if user is None or not user.is_active or not user.is_superuser:
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
def _proxy(instance):
|
||||
c = instance.compute
|
||||
return wvmBackup(c.hostname, c.login, c.password, c.type, instance.name, uuid=instance.uuid)
|
||||
|
||||
|
||||
def _target_row(target, compute):
|
||||
row = target.pool_on(compute)
|
||||
if row is None:
|
||||
raise util.OperationError(_("Backup target %(target)s has no storage pool on %(compute)s"),
|
||||
target=target.name, compute=compute.name)
|
||||
return row
|
||||
|
||||
|
||||
def _check_state(proxy, frozen):
|
||||
"""A running, paused or shut-off VM is backed up; frozen file systems
|
||||
only when its guest agent answers."""
|
||||
status = proxy.get_status()
|
||||
if status not in (VIR_DOMAIN_RUNNING, VIR_DOMAIN_PAUSED, VIR_DOMAIN_SHUTOFF):
|
||||
raise util.OperationError(_("The VM must be running, paused or shut off to be backed up"))
|
||||
if status == VIR_DOMAIN_SHUTOFF:
|
||||
return
|
||||
if proxy.wvm.getLibVersion() < LIVE_CLONE_MIN_LIBVIRT:
|
||||
raise util.OperationError(_("A running VM's backup needs libvirt 11.10 or later; shut the VM down to back it up"))
|
||||
if frozen and status == VIR_DOMAIN_PAUSED:
|
||||
raise util.OperationError(_("A paused VM's file systems cannot be frozen"))
|
||||
if frozen and not proxy.is_agent_ready():
|
||||
raise util.OperationError(_("The guest agent does not answer: the file systems cannot be frozen"))
|
||||
|
||||
|
||||
def _checked(op):
|
||||
"""In the worker, before anything is made: the VM, its target pool (the
|
||||
one registered) and the space for its disks."""
|
||||
_superuser(op.user)
|
||||
instance = _instance(op.params["instance"])
|
||||
if instance.compute_id != op.intent["compute"]:
|
||||
raise util.OperationError(_("The VM moved to another compute after the job was queued"))
|
||||
target = BackupTarget.objects.get(pk=op.params["target"])
|
||||
row = _target_row(target, instance.compute)
|
||||
proxy = _proxy(instance)
|
||||
pool = target_pool(proxy, row.pool, row.pool_uuid)
|
||||
plan = proxy.backup_plan()
|
||||
_check_state(proxy, op.params["frozen"])
|
||||
check_target_space(pool, plan["disks"], **_free_space())
|
||||
return instance, target, row, proxy, pool, plan
|
||||
|
||||
|
||||
def _free_space():
|
||||
values = _snapshot_free_space()
|
||||
return {"free_percent": values.get("free_percent", 10), "free_min_gib": values.get("free_min_gib", 1)}
|
||||
|
||||
|
||||
def _owner():
|
||||
return int(app_settings.INSTANCE_VOLUME_DEFAULT_OWNER_UID), int(app_settings.INSTANCE_VOLUME_DEFAULT_OWNER_GID)
|
||||
|
||||
|
||||
def _all_names(names):
|
||||
return [*names["disks"].values(), *(n for n in (names["nvram"], names["domain"], names["manifest"]) if n)]
|
||||
|
||||
|
||||
def _nvram(op, proxy):
|
||||
"""The NVRAM file's bytes, or None when the VM has none or never
|
||||
started. A running VM's is kept only when it is the one read before its
|
||||
backup began: the guest did not write it across the capture point."""
|
||||
path = op.intent["plan"]["nvram"]
|
||||
if not path:
|
||||
return None
|
||||
before = op.intent.get("nvram_before")
|
||||
data = proxy.read_nvram(path)
|
||||
if not op.intent["live"]:
|
||||
return data
|
||||
for attempt in range(NVRAM_READS):
|
||||
if attempt:
|
||||
time.sleep(NVRAM_WAIT)
|
||||
data = proxy.read_nvram(path)
|
||||
if (hashlib.sha256(data).hexdigest() if data is not None else None) == before:
|
||||
return data
|
||||
raise util.OperationError(_("The VM's NVRAM file changed while it was backed up; back the VM up again"))
|
||||
|
||||
|
||||
def _publish(op, proxy, pool):
|
||||
"""The copied disks are complete: the NVRAM file, the definition and the
|
||||
manifest written and read back, then the row ready with its files.
|
||||
Runs again in recovery: each upload replaces its volume."""
|
||||
plan, names = op.intent["plan"], op.intent["names"]
|
||||
backup = Backup.objects.get(uuid=op.intent["backup"])
|
||||
pool.refresh(0)
|
||||
files = []
|
||||
for disk in plan["disks"]:
|
||||
size = pool.storageVolLookupByName(names["disks"][disk["dev"]]).info()[2]
|
||||
files.append({"role": BackupFile.DISK, "dev": disk["dev"], "volume": names["disks"][disk["dev"]],
|
||||
"format": disk["format"], "capacity": disk["capacity"], "size": size, "sha256": ""})
|
||||
nvram = _nvram(op, proxy)
|
||||
if nvram is not None:
|
||||
files.append({"role": BackupFile.NVRAM, "dev": "", "volume": names["nvram"], "format": "raw",
|
||||
"capacity": len(nvram), "size": len(nvram), "sha256": put_file(proxy, pool, names["nvram"], nvram, _owner())})
|
||||
definition = plan["definition"].encode()
|
||||
files.append({"role": BackupFile.DOMAIN, "dev": "", "volume": names["domain"], "format": "", "capacity": len(definition),
|
||||
"size": len(definition), "sha256": put_file(proxy, pool, names["domain"], definition, _owner())})
|
||||
manifest = {
|
||||
"format": MANIFEST_FORMAT,
|
||||
"backup": str(backup.uuid),
|
||||
"vm": {"name": backup.vm_name, "uuid": backup.vm_uuid},
|
||||
"compute": backup.compute_name,
|
||||
"created_at": backup.created_at.isoformat(),
|
||||
"consistency": op.intent["consistency"],
|
||||
"nvram": "copied" if nvram is not None else ("never written" if plan["nvram"] else "none"),
|
||||
"files": files,
|
||||
"left_out": plan["left_out"],
|
||||
"libvirt": proxy.wvm.getLibVersion(),
|
||||
"hypervisor": proxy.wvm.getVersion(),
|
||||
}
|
||||
data = json.dumps(manifest, indent=2, sort_keys=True).encode()
|
||||
put_file(proxy, pool, names["manifest"], data, _owner())
|
||||
with transaction.atomic():
|
||||
backup.files.all().delete()
|
||||
BackupFile.objects.bulk_create(BackupFile(backup=backup, **f) for f in files)
|
||||
backup.manifest = manifest
|
||||
backup.consistency = op.intent["consistency"]
|
||||
backup.size = sum(f["size"] for f in files) + len(data)
|
||||
backup.state = Backup.READY
|
||||
backup.finished_at = timezone.now()
|
||||
backup.save()
|
||||
return {"backup": str(backup.uuid)}
|
||||
|
||||
|
||||
def _discard(op, pool):
|
||||
"""The job's files removed, its row failed."""
|
||||
remove_files(pool, _all_names(op.intent["names"]))
|
||||
Backup.objects.filter(uuid=op.intent["backup"]).update(state=Backup.FAILED, finished_at=timezone.now())
|
||||
|
||||
|
||||
@register
|
||||
class CreateBackup(Kind):
|
||||
"""A shut-off VM's disks are copied one at a time; a running or paused
|
||||
VM's with libvirt's push backup, from one instant (the live clone's)."""
|
||||
|
||||
name = "backup.create"
|
||||
label = _("Back up VM")
|
||||
cancellable = True # libvirt aborts a push backup; an offline copy stops before its next disk
|
||||
progress_bytes = True
|
||||
|
||||
def normalize(self, raw):
|
||||
return {"instance": int(raw["instance"]), "target": int(raw["target"]),
|
||||
"frozen": str(raw.get("frozen", "")).lower() in ("1", "true", "on")}
|
||||
|
||||
def plan(self, user, params):
|
||||
_superuser(user)
|
||||
instance = _instance(params["instance"])
|
||||
target = BackupTarget.objects.get(pk=params["target"])
|
||||
_target_row(target, instance.compute)
|
||||
proxy = _proxy(instance)
|
||||
proxy.backup_plan()
|
||||
_check_state(proxy, params["frozen"])
|
||||
return Plan(
|
||||
claims={claims.compute_key(instance.compute_id): Claim.SHARED,
|
||||
claims.instance_key(instance.uuid): Claim.EXCLUSIVE,
|
||||
claims.backup_target_key(target.pk): Claim.EXCLUSIVE},
|
||||
resource=claims.instance_key(instance.uuid),
|
||||
label=f"{instance.compute.name}/{instance.name}",
|
||||
intent={"compute": instance.compute_id, "uuid": instance.uuid, "backup": str(uuid4()),
|
||||
"target": target.name},
|
||||
)
|
||||
|
||||
def run(self, op, ctx):
|
||||
instance, target, row, proxy, pool, plan = _checked(op)
|
||||
status = proxy.get_status()
|
||||
live = status != VIR_DOMAIN_SHUTOFF
|
||||
names = backup_file_names(op.intent["backup"], plan["disks"], bool(plan["nvram"]))
|
||||
ctx.record_intent(live=live, plan=plan, names=names, pool=row.pool, pool_uuid=row.pool_uuid,
|
||||
consistency=Backup.OFFLINE if not live else Backup.CRASH)
|
||||
Backup.objects.create(uuid=op.intent["backup"], target=target, instance=instance, vm_uuid=instance.uuid,
|
||||
vm_name=instance.name, compute_name=instance.compute.name, operation=op)
|
||||
ctx.set_phase(_("Copying disks"))
|
||||
if live:
|
||||
return self._run_live(op, ctx, proxy, pool, status)
|
||||
try:
|
||||
for disk in plan["disks"]:
|
||||
op.refresh_from_db(fields=["cancel_requested"])
|
||||
if op.cancel_requested:
|
||||
_discard(op, pool)
|
||||
raise Cancelled
|
||||
ctx.record_intent(copying=disk["dev"])
|
||||
proxy.copy_disk_offline(disk, row.pool, names["disks"][disk["dev"]], *_owner())
|
||||
ctx.record_intent(copied=[*op.intent.get("copied", []), disk["dev"]], copying=None)
|
||||
except libvirtError as err: # libvirt answered: the copy failed and ended
|
||||
ctx.record_intent(copy_result=[False, safe_text(err)], copying=None)
|
||||
raise
|
||||
ctx.record_intent(copy_result=[True, ""])
|
||||
ctx.set_phase(_("Writing the backup's files"))
|
||||
return _publish(op, proxy, pool)
|
||||
|
||||
def _run_live(self, op, ctx, proxy, pool, status):
|
||||
plan, names = op.intent["plan"], op.intent["names"]
|
||||
if plan["nvram"]:
|
||||
data = proxy.read_nvram(plan["nvram"])
|
||||
ctx.record_intent(nvram_before=hashlib.sha256(data).hexdigest() if data is not None else None)
|
||||
ctx.record_intent(made=True)
|
||||
targets = proxy.make_live_targets(plan["disks"], op.intent["pool"], names["disks"], *_owner())
|
||||
ctx.record_intent(paths=[t["path"] for t in targets])
|
||||
# a completed result libvirt still holds is of an earlier job
|
||||
proxy.discard_backup_result()
|
||||
ctx.record_intent(copy_started=True)
|
||||
op.refresh_from_db(fields=["cancel_requested"])
|
||||
if op.cancel_requested:
|
||||
_discard(op, pool)
|
||||
raise Cancelled
|
||||
|
||||
# a required freeze is tried even when the agent seems gone: its failure then fails the backup
|
||||
freeze = status == VIR_DOMAIN_RUNNING and (op.params["frozen"] or proxy.is_agent_ready())
|
||||
thaw_error = None
|
||||
try:
|
||||
try:
|
||||
if freeze:
|
||||
ctx.record_intent(frozen=True)
|
||||
try:
|
||||
proxy.fs_freeze()
|
||||
except libvirtError:
|
||||
if op.params["frozen"]:
|
||||
raise
|
||||
# crash-consistent, as without an agent; a freeze that failed part way may have
|
||||
# frozen some file systems: frozen stays recorded, so the guest is thawed as frozen
|
||||
else:
|
||||
ctx.record_intent(consistency=Backup.FROZEN)
|
||||
proxy.begin_clone_backup(targets)
|
||||
finally:
|
||||
if op.intent.get("frozen"):
|
||||
thaw_error = self._thaw(op, ctx, proxy)
|
||||
except libvirtError as err:
|
||||
# no backup of ours runs: the copy failed (if this read fails, recovery decides)
|
||||
if proxy.backup_targets() != set(op.intent["paths"]):
|
||||
ctx.record_intent(copy_result=[False, safe_text(err)])
|
||||
raise
|
||||
op.refresh_from_db(fields=["cancel_requested"])
|
||||
if op.cancel_requested: # the cancel hook may have run before the backup began
|
||||
try:
|
||||
self.cancel(op)
|
||||
except libvirtError:
|
||||
pass # the hook aborted it, or it ended: its result tells
|
||||
|
||||
while proxy.backup_progress() is not None:
|
||||
if thaw_error: # the guest must not stay frozen for the copy: tried at each look
|
||||
thaw_error = self._thaw(op, ctx, proxy)
|
||||
time.sleep(PROGRESS_EVERY)
|
||||
if thaw_error:
|
||||
thaw_error = self._thaw(op, ctx, proxy)
|
||||
result = proxy.backup_result()
|
||||
ctx.record_intent(copy_result=[result[0], safe_text(result[1] or "")] if result else None)
|
||||
if result is None:
|
||||
raise util.OperationError(_("libvirt has no result of the copy")) # recovery decides
|
||||
if not result[0]:
|
||||
_discard(op, pool)
|
||||
op.refresh_from_db(fields=["cancel_requested"])
|
||||
if op.cancel_requested:
|
||||
raise Cancelled
|
||||
raise util.OperationError(result[1] or _("The copy failed"))
|
||||
ctx.set_phase(_("Writing the backup's files"))
|
||||
done = _publish(op, proxy, pool)
|
||||
if thaw_error: # the backup is ready; recovery keeps trying to thaw the guest
|
||||
raise util.OperationError(THAW_FAILED, error=thaw_error, vm=op.resource_label.rpartition("/")[2])
|
||||
return done
|
||||
|
||||
@staticmethod
|
||||
def _thaw(op, ctx, proxy):
|
||||
"""Thaws the guest; its error, or None once thawed."""
|
||||
try:
|
||||
proxy.fs_thaw()
|
||||
except libvirtError as err: # frozen stays recorded
|
||||
ctx.set_phase(_("The guest's file systems could not be thawed; trying again"))
|
||||
return err
|
||||
ctx.record_intent(frozen=False)
|
||||
return None
|
||||
|
||||
def progress(self, op):
|
||||
if op.intent.get("live"):
|
||||
return _proxy(_instance(op.params["instance"])).backup_progress() if op.intent.get("copy_started") else None
|
||||
disks = op.intent.get("plan", {}).get("disks", [])
|
||||
copied = set(op.intent.get("copied", []))
|
||||
return sum(d["capacity"] for d in disks if d["dev"] in copied), sum(d["capacity"] for d in disks)
|
||||
|
||||
def cancel(self, op):
|
||||
# an offline copy stops before its next disk (run checks the request)
|
||||
if not op.intent.get("live"):
|
||||
return
|
||||
proxy = _proxy(_instance(op.params["instance"]))
|
||||
paths = set(op.intent.get("paths", []))
|
||||
if paths and proxy.backup_targets() == paths:
|
||||
proxy.abort_backup()
|
||||
|
||||
def reconcile(self, op):
|
||||
backup = Backup.objects.filter(uuid=op.intent["backup"]).first()
|
||||
if backup is None: # the row comes before any file
|
||||
return Outcome(Operation.FAILED, error=say(_("The job stopped before the copy started")))
|
||||
instance = Instance.objects.select_related("compute").filter(pk=op.params["instance"]).first()
|
||||
ended = Operation.CANCELLED if op.cancel_requested else Operation.FAILED
|
||||
names = ", ".join(_all_names(op.intent["names"]))
|
||||
proxy = None
|
||||
if instance is not None and instance.compute_id == op.intent["compute"]:
|
||||
try:
|
||||
proxy = _proxy(instance)
|
||||
except libvirtError as err:
|
||||
if err.get_error_code() != VIR_ERR_NO_DOMAIN:
|
||||
raise # unreachable: recovery waits and retries
|
||||
|
||||
thawed = []
|
||||
if op.intent.get("frozen") and proxy is not None: # thawed first, before anything else
|
||||
status = proxy.get_status()
|
||||
if status == VIR_DOMAIN_RUNNING:
|
||||
proxy.fs_thaw() # a failure raises: recovery waits and tries again
|
||||
elif status == VIR_DOMAIN_PAUSED: # libvirt thaws no paused guest
|
||||
thawed = say(PAUSED_FROZEN, vm=op.resource_label.rpartition("/")[2])
|
||||
if backup.state == Backup.READY:
|
||||
return Outcome(Operation.SUCCEEDED, result={"backup": str(backup.uuid), **({"warning": thawed} if thawed else {})})
|
||||
|
||||
if proxy is None:
|
||||
Backup.objects.filter(pk=backup.pk).update(state=Backup.FAILED, finished_at=timezone.now())
|
||||
return Outcome(Operation.UNCERTAIN, error=say(_(
|
||||
"The VM is no longer on the compute the job ran on; check these volumes of the backup target, "
|
||||
"then resolve this job: %(volumes)s"), volumes=names))
|
||||
# after the thaw: an unreachable target must not keep a guest frozen
|
||||
pool = target_pool(proxy, op.intent["pool"], op.intent["pool_uuid"])
|
||||
outcome = self._outcome(op, proxy, pool, ended, names)
|
||||
if outcome.state == Operation.SUCCEEDED and thawed:
|
||||
outcome.result["warning"] = thawed
|
||||
else:
|
||||
outcome.error += thawed
|
||||
return outcome
|
||||
|
||||
def _outcome(self, op, proxy, pool, ended, names):
|
||||
result = op.intent.get("copy_result")
|
||||
if not op.intent["live"]:
|
||||
if result is None and op.intent.get("copying"):
|
||||
Backup.objects.filter(uuid=op.intent["backup"]).update(state=Backup.FAILED, finished_at=timezone.now())
|
||||
return Outcome(Operation.UNCERTAIN, error=say(_(
|
||||
"A disk was being copied when the job stopped; check these volumes of the backup target, then "
|
||||
"resolve this job: %(volumes)s"), volumes=names))
|
||||
elif op.intent.get("copy_started") and result is None:
|
||||
targets = proxy.backup_targets()
|
||||
paths = set(op.intent["paths"])
|
||||
if targets == paths:
|
||||
return Outcome(Operation.RUNNING, phase=_("libvirt is still copying the disks"),
|
||||
progress=proxy.backup_progress())
|
||||
if targets is not None:
|
||||
return Outcome(Operation.UNCERTAIN, error=say(_(
|
||||
"Another backup runs on the VM; check these volumes of the backup target, then resolve this "
|
||||
"job: %(volumes)s"), volumes=names))
|
||||
result = proxy.backup_result()
|
||||
if result is None:
|
||||
Backup.objects.filter(uuid=op.intent["backup"]).update(state=Backup.FAILED, finished_at=timezone.now())
|
||||
return Outcome(Operation.UNCERTAIN, error=say(_(
|
||||
"libvirt has no result of the copy; check these volumes of the backup target, then resolve this "
|
||||
"job: %(volumes)s"), volumes=names))
|
||||
elif op.intent.get("made") and not op.intent.get("paths"):
|
||||
# the push backup's volumes were being made: they are named from the backup, so removed by name
|
||||
result = [False, ""]
|
||||
if result is None or not result[0]:
|
||||
_discard(op, pool)
|
||||
return Outcome(ended, error=say(result[1]) if result and result[1] else
|
||||
say(_("The job stopped before the copy ended")))
|
||||
try:
|
||||
return Outcome(Operation.SUCCEEDED, result=_publish(op, proxy, pool))
|
||||
except util.ConnectionFailed:
|
||||
raise # unreachable: recovery waits and retries
|
||||
except libvirtError as err: # it would fail the same way at every retry
|
||||
_discard(op, pool)
|
||||
return Outcome(Operation.FAILED, error=say(_("The backup's files could not be written: %(error)s"), error=err))
|
||||
|
||||
def log_entry(self, op, state):
|
||||
if state == Operation.SUCCEEDED:
|
||||
action = f"backed up to {op.intent['target']} ({op.intent.get('consistency', '')})"
|
||||
else:
|
||||
action = f"back up to {op.intent['target']}"
|
||||
return _log(op, state, action)
|
||||
29
vmbackups/serializers.py
Normal file
29
vmbackups/serializers.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
from rest_framework import serializers
|
||||
|
||||
from instances.models import Instance
|
||||
|
||||
from .models import Backup, BackupFile, BackupTarget
|
||||
|
||||
|
||||
class BackupFileSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = BackupFile
|
||||
fields = ["role", "dev", "volume", "format", "capacity", "size", "sha256"]
|
||||
|
||||
|
||||
class BackupSerializer(serializers.ModelSerializer):
|
||||
target = serializers.SlugRelatedField(slug_field="name", read_only=True)
|
||||
files = BackupFileSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Backup
|
||||
fields = ["uuid", "target", "instance", "vm_uuid", "vm_name", "compute_name", "created_at", "finished_at",
|
||||
"state", "consistency", "size", "files", "operation"]
|
||||
read_only_fields = fields
|
||||
|
||||
|
||||
class CreateBackupSerializer(serializers.Serializer):
|
||||
instance = serializers.PrimaryKeyRelatedField(queryset=Instance.objects.all())
|
||||
target = serializers.PrimaryKeyRelatedField(queryset=BackupTarget.objects.all())
|
||||
frozen = serializers.BooleanField(default=False)
|
||||
submission_key = serializers.CharField(write_only=True)
|
||||
62
vmbackups/templates/vmbackups/vm_tab.html
Normal file
62
vmbackups/templates/vmbackups/vm_tab.html
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
{% load i18n %}
|
||||
{% load operations %}
|
||||
{% load bootstrap_icons %}
|
||||
<div class="tab-pane" id="backups" role="tabpanel">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
{% if backups.problem %}
|
||||
<div class="alert alert-warning" role="status">{% bs_icon 'exclamation-triangle' %} {{ backups.problem }}</div>
|
||||
{% else %}
|
||||
<form action="{% url 'vmbackups:create' instance.id %}" method="post" aria-label="{% trans "Back up now" %}">{% csrf_token %}{% submission_key %}
|
||||
<div class="row g-2 align-items-center">
|
||||
<div class="col-12 col-md">
|
||||
<label class="visually-hidden" for="backup-target">{% trans "Backup target" %}</label>
|
||||
<select class="form-select" id="backup-target" name="target" required>
|
||||
{% for target in backups.targets %}<option value="{{ target.id }}">{{ target.name }}</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-12 col-md-auto">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" name="frozen" id="backup-frozen"{% if instance.status != 1 or not instance.guest_agent_ready %} disabled{% endif %}>
|
||||
<label class="form-check-label" for="backup-frozen">{% trans "Require frozen file systems" %}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 col-md-auto d-grid">
|
||||
<button type="submit" class="btn btn-primary">{% bs_icon 'archive' %} {% trans "Back up now" %}</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="small text-body-secondary mt-2 mb-0">{% blocktrans %}A running VM keeps running: its disks are copied from one instant, its file systems frozen for that instant when the guest agent answers, otherwise the backup is crash-consistent. Memory is not kept.{% endblocktrans %}</p>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if backups.rows %}
|
||||
<div class="table-responsive mt-3">
|
||||
<table class="table table-sm align-middle mb-0">
|
||||
<thead>
|
||||
<tr><th>{% trans "Time" %}</th><th>{% trans "Target" %}</th><th>{% trans "Consistency" %}</th><th class="text-end">{% trans "Size" %}</th><th>{% trans "State" %}</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for backup in backups.rows %}
|
||||
<tr>
|
||||
<td class="text-nowrap">{{ backup.created_at|date:"Y-m-d H:i" }}</td>
|
||||
<td>{{ backup.target.name }}</td>
|
||||
<td>{{ backup.get_consistency_display }}</td>
|
||||
<td class="text-end text-nowrap">{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}</td>
|
||||
<td>
|
||||
{% if backup.state == "ready" %}<span class="badge text-bg-success">{% trans "Ready" %}</span>
|
||||
{% elif backup.state == "creating" %}<span class="badge text-bg-info">{% trans "Creating" %}</span>
|
||||
{% elif backup.state == "deleting" %}<span class="badge text-bg-warning">{% trans "Deleting" %}</span>
|
||||
{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}
|
||||
{% if backup.operation_id %}<a class="small ms-1" href="{% url 'operations:job' backup.operation_id %}">{% trans "Job" %}</a>{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="text-body-secondary mt-3 mb-0">{% trans "No backup of this VM yet." %}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
440
vmbackups/tests/test_create.py
Normal file
440
vmbackups/tests/test_create.py
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
"""backup.create: a VM backed up into a target, offline or live, published
|
||||
last with its manifest, recovered from where the worker stopped."""
|
||||
|
||||
import itertools
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import libvirt
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TransactionTestCase
|
||||
from lxml import html as lxml_html
|
||||
|
||||
from appsettings.settings import get_settings
|
||||
from computes.models import Compute
|
||||
from instances.models import Instance
|
||||
from instances.tests.test_page_controls import PageControls
|
||||
from operations import jobs
|
||||
from operations.jobs import Cancelled, Context
|
||||
from operations.models import Operation, acquire
|
||||
from vmbackups.jobs import CreateBackup, _owner
|
||||
from vmbackups.models import Backup, BackupFile, BackupTarget, BackupTargetPool
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
GIB = 1024**3
|
||||
WORKER = "wvc-test:1:a"
|
||||
NVRAM = "/var/lib/libvirt/qemu/nvram/vm1_VARS.fd"
|
||||
|
||||
|
||||
def libvirt_error(text="x"):
|
||||
return libvirt.libvirtError(text)
|
||||
|
||||
|
||||
def plan(nvram=None):
|
||||
return {
|
||||
"definition": "<domain><name>vm1</name></domain>",
|
||||
"disks": [{"dev": "vda", "path": "/pool/a.qcow2", "pool": "default", "format": "qcow2", "capacity": GIB}],
|
||||
"nvram": nvram,
|
||||
"left_out": [{"dev": "sda", "why": "CD-ROM: not copied"}],
|
||||
}
|
||||
|
||||
|
||||
def proxy(status=libvirt.VIR_DOMAIN_SHUTOFF, nvram=None):
|
||||
p = MagicMock()
|
||||
p.get_status.return_value = status
|
||||
p.backup_plan.return_value = plan(nvram)
|
||||
p.wvm.getLibVersion.return_value = 11_010_000
|
||||
p.wvm.getVersion.return_value = 10_001_000
|
||||
p.is_agent_ready.return_value = True
|
||||
p.make_live_targets.side_effect = lambda disks, pool, names, uid, gid: [
|
||||
{"dev": d["dev"], "path": f"/b1/{names[d['dev']]}", "format": d["format"]} for d in disks]
|
||||
p.backup_targets.return_value = None
|
||||
p.backup_progress.return_value = None
|
||||
p.backup_result.return_value = (True, "")
|
||||
p.read_nvram.return_value = b"vars"
|
||||
return p
|
||||
|
||||
|
||||
def target_pool():
|
||||
pool = MagicMock()
|
||||
pool.name.return_value = "b1"
|
||||
pool.info.return_value = [2, 100 * GIB, 0, 100 * GIB]
|
||||
pool.storageVolLookupByName.return_value.info.return_value = [0, GIB, GIB // 2]
|
||||
return pool
|
||||
|
||||
|
||||
class CreateBackupTests(TransactionTestCase):
|
||||
def setUp(self):
|
||||
get_settings()
|
||||
self.admin = get_user_model().objects.create_superuser("bk_admin", "a@example.com", "pw")
|
||||
self.compute = Compute.objects.create(name="h1", hostname="192.0.2.21", login="u", password="p", type=1)
|
||||
self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="21212121-0000-4000-8000-000000000001")
|
||||
self.target = BackupTarget.objects.create(name="nfs1")
|
||||
BackupTargetPool.objects.create(target=self.target, compute=self.compute, pool="b1", pool_uuid="pool-uuid")
|
||||
self.proxy = proxy()
|
||||
self.pool = target_pool()
|
||||
self.written = []
|
||||
self.removed = []
|
||||
for name, value in (
|
||||
("vmbackups.jobs.wvmBackup", MagicMock(return_value=self.proxy)),
|
||||
("vmbackups.jobs.target_pool", MagicMock(return_value=self.pool)),
|
||||
("vmbackups.jobs.put_file", MagicMock(side_effect=lambda conn, pool, n, data, owner: self.written.append(n) or "sha")),
|
||||
("vmbackups.jobs.remove_files", MagicMock(side_effect=lambda pool, names: self.removed.extend(names))),
|
||||
("vmbackups.jobs.NVRAM_WAIT", 0),
|
||||
("vmbackups.jobs.PROGRESS_EVERY", 0),
|
||||
):
|
||||
patcher = patch(name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def submit(self, frozen=False):
|
||||
op = jobs.submit("backup.create", self.admin, {"instance": self.vm.pk, "target": self.target.pk, "frozen": frozen},
|
||||
f"key-{uuid4().hex[:12]}")
|
||||
acquire(WORKER, "wvc-test")
|
||||
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
|
||||
op.refresh_from_db()
|
||||
return op
|
||||
|
||||
def run_job(self, op):
|
||||
return CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
|
||||
|
||||
def interrupted(self, op, error=None):
|
||||
"""run stops where the test makes libvirt fail; the intent it recorded stays."""
|
||||
with self.assertRaises(Exception):
|
||||
self.run_job(op)
|
||||
op.refresh_from_db()
|
||||
return op
|
||||
|
||||
def backup(self, op):
|
||||
return Backup.objects.get(uuid=op.intent["backup"])
|
||||
|
||||
def test_a_shut_off_vm_is_copied_offline(self):
|
||||
op = self.submit()
|
||||
self.assertEqual(self.run_job(op), {"backup": op.intent["backup"]})
|
||||
prefix = f"wvc-{op.intent['backup']}"
|
||||
self.proxy.copy_disk_offline.assert_called_once_with(plan()["disks"][0], "b1", f"{prefix}-vda.qcow2", *_owner())
|
||||
self.proxy.begin_clone_backup.assert_not_called()
|
||||
self.assertEqual(self.written, [f"{prefix}-domain.xml", f"{prefix}-manifest.json"]) # the manifest last
|
||||
backup = self.backup(op)
|
||||
self.assertEqual((backup.state, backup.consistency, backup.instance), (Backup.READY, Backup.OFFLINE, self.vm))
|
||||
files = {f.role: f for f in backup.files.all()}
|
||||
self.assertEqual(set(files), {BackupFile.DISK, BackupFile.DOMAIN})
|
||||
self.assertEqual((files["disk"].dev, files["disk"].capacity, files["disk"].size), ("vda", GIB, GIB // 2))
|
||||
self.assertEqual(backup.manifest["left_out"], plan()["left_out"])
|
||||
self.assertEqual(backup.manifest["consistency"], "offline")
|
||||
|
||||
def test_a_running_vm_is_frozen_backed_up_and_thawed(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
calls = [c[0] for c in self.proxy.method_calls]
|
||||
self.assertLess(calls.index("fs_freeze"), calls.index("begin_clone_backup"))
|
||||
self.assertLess(calls.index("begin_clone_backup"), calls.index("fs_thaw"))
|
||||
self.assertEqual(self.backup(op).consistency, Backup.FROZEN)
|
||||
|
||||
def test_no_agent_gives_crash_consistency_unless_frozen_is_required(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.is_agent_ready.return_value = False
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
self.proxy.fs_freeze.assert_not_called()
|
||||
self.assertEqual(self.backup(op).consistency, Backup.CRASH)
|
||||
with self.assertRaisesMessage(OperationError, "guest agent does not answer"):
|
||||
self.submit(frozen=True)
|
||||
|
||||
def test_a_failed_freeze_goes_on_crash_consistent_unless_required(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.fs_freeze.side_effect = libvirt_error("agent timeout")
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
self.assertEqual(self.backup(op).consistency, Backup.CRASH)
|
||||
jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED))
|
||||
op = self.submit(frozen=True)
|
||||
self.interrupted(op)
|
||||
self.assertEqual(op.intent["copy_result"], [False, "agent timeout"])
|
||||
|
||||
def test_frozen_is_refused_for_a_paused_vm(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_PAUSED
|
||||
with self.assertRaisesMessage(OperationError, "paused"):
|
||||
self.submit(frozen=True)
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
self.proxy.fs_freeze.assert_not_called()
|
||||
self.assertEqual(self.backup(op).consistency, Backup.CRASH)
|
||||
|
||||
def test_a_failed_thaw_is_tried_again_while_the_copy_runs(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.fs_thaw.side_effect = [libvirt_error("thaw failed"), None]
|
||||
self.proxy.backup_progress.side_effect = [(1, 2), None]
|
||||
op = self.submit()
|
||||
result = self.run_job(op)
|
||||
self.assertNotIn("warning", result)
|
||||
self.assertEqual(self.proxy.fs_thaw.call_count, 2)
|
||||
op.refresh_from_db()
|
||||
self.assertFalse(op.intent["frozen"])
|
||||
|
||||
def test_a_thaw_that_keeps_failing_is_left_to_recovery(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.fs_thaw.side_effect = libvirt_error("thaw failed")
|
||||
op = self.interrupted(self.submit())
|
||||
self.assertEqual(self.backup(op).state, Backup.READY) # the copy is kept
|
||||
with self.assertRaises(libvirt.libvirtError): # recovery waits and tries again
|
||||
CreateBackup().reconcile(op)
|
||||
self.proxy.fs_thaw.side_effect = None
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.SUCCEEDED)
|
||||
|
||||
def test_an_optional_freeze_that_failed_is_thawed_until_it_works(self):
|
||||
# a freeze that failed part way may have frozen some file systems: the guest counts as frozen
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.fs_freeze.side_effect = libvirt_error("agent timeout")
|
||||
self.proxy.fs_thaw.side_effect = [libvirt_error("agent busy"), None]
|
||||
self.proxy.backup_progress.side_effect = [(1, 2), None]
|
||||
op = self.submit()
|
||||
result = self.run_job(op)
|
||||
self.assertNotIn("warning", result)
|
||||
self.assertEqual(self.proxy.fs_thaw.call_count, 2)
|
||||
op.refresh_from_db()
|
||||
self.assertFalse(op.intent["frozen"])
|
||||
self.assertEqual(self.backup(op).consistency, Backup.CRASH)
|
||||
|
||||
def test_a_running_vms_nvram_is_kept_when_it_did_not_change(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.backup_plan.return_value = plan(NVRAM)
|
||||
self.proxy.read_nvram.side_effect = [b"vars", b"new", b"vars"] # before; after, changed then back
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
self.assertIn(f"wvc-{op.intent['backup']}-nvram.fd", self.written)
|
||||
self.assertEqual(self.backup(op).manifest["nvram"], "copied")
|
||||
|
||||
def test_nvram_changed_across_the_copy_is_retried_then_refused(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.backup_plan.return_value = plan(NVRAM)
|
||||
counter = itertools.count()
|
||||
self.proxy.read_nvram.side_effect = lambda path: b"vars-%d" % next(counter)
|
||||
op = self.interrupted(self.submit())
|
||||
self.assertEqual(self.proxy.read_nvram.call_count, 4) # before, then three after
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
self.assertEqual(outcome.state, Operation.FAILED)
|
||||
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed)
|
||||
self.assertEqual(self.backup(op).state, Backup.FAILED)
|
||||
|
||||
def test_the_guest_shutting_down_does_not_fail_the_backup(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
|
||||
def progress():
|
||||
# the guest shuts down: its QEMU stays until the backup ends (PRESERVE_SHUTDOWN_DOMAIN)
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_SHUTOFF
|
||||
self.proxy.backup_progress.side_effect = None
|
||||
return (1, 2)
|
||||
|
||||
self.proxy.backup_progress.side_effect = progress
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
self.assertEqual((self.backup(op).state, self.backup(op).consistency), (Backup.READY, Backup.FROZEN))
|
||||
|
||||
def test_a_replaced_target_pool_is_refused_before_anything_is_made(self):
|
||||
op = self.submit()
|
||||
with patch("vmbackups.jobs.target_pool", side_effect=OperationError("Storage pool %(pool)s is replaced", pool="b1")):
|
||||
with self.assertRaisesMessage(OperationError, "Storage pool b1"):
|
||||
self.run_job(op)
|
||||
op.refresh_from_db()
|
||||
self.assertFalse(op.effects_started)
|
||||
self.assertFalse(Backup.objects.exists())
|
||||
self.proxy.copy_disk_offline.assert_not_called()
|
||||
self.proxy.make_live_targets.assert_not_called()
|
||||
|
||||
def test_a_target_without_room_is_refused_before_anything_is_made(self):
|
||||
self.pool.info.return_value = [2, 100 * GIB, 0, GIB]
|
||||
op = self.submit()
|
||||
with self.assertRaisesMessage(OperationError, "the backup needs"):
|
||||
self.run_job(op)
|
||||
self.assertFalse(Backup.objects.exists())
|
||||
|
||||
def test_a_full_target_fails_and_removes_the_volumes(self):
|
||||
self.proxy.copy_disk_offline.side_effect = libvirt_error("No space left on device")
|
||||
op = self.interrupted(self.submit())
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
self.assertEqual(outcome.state, Operation.FAILED)
|
||||
self.assertIn("No space left on device", outcome.error[0]["text"])
|
||||
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed)
|
||||
self.assertEqual(self.backup(op).state, Backup.FAILED)
|
||||
|
||||
def test_a_failed_push_backup_removes_the_volumes(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.backup_result.return_value = (False, "No space left on device")
|
||||
op = self.interrupted(self.submit())
|
||||
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed)
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.FAILED)
|
||||
|
||||
def live_interrupted(self):
|
||||
"""A push backup running when the worker stopped."""
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.backup_progress.side_effect = libvirt_error("connection lost")
|
||||
op = self.interrupted(self.submit())
|
||||
self.proxy.backup_progress.side_effect = None
|
||||
return op
|
||||
|
||||
def test_recovery_watches_its_running_backup(self):
|
||||
op = self.live_interrupted()
|
||||
self.proxy.backup_targets.return_value = set(op.intent["paths"])
|
||||
self.proxy.backup_progress.return_value = (1, 4)
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
self.assertEqual((outcome.state, outcome.progress), (Operation.RUNNING, (1, 4)))
|
||||
self.proxy.backup_targets.return_value = None
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.SUCCEEDED)
|
||||
self.assertEqual(self.backup(op).state, Backup.READY)
|
||||
|
||||
def test_recovery_without_a_result_is_uncertain(self):
|
||||
op = self.live_interrupted()
|
||||
self.proxy.backup_result.return_value = None
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
self.assertEqual(outcome.state, Operation.UNCERTAIN)
|
||||
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", outcome.error[0]["values"]["volumes"])
|
||||
self.assertEqual(self.removed, []) # the files stay for the administrator
|
||||
self.assertEqual(self.backup(op).state, Backup.FAILED)
|
||||
|
||||
def test_recovery_thaws_first(self):
|
||||
self.proxy.fs_thaw.side_effect = libvirt_error("thaw failed")
|
||||
op = self.live_interrupted()
|
||||
self.assertTrue(op.intent["frozen"])
|
||||
self.proxy.fs_thaw.side_effect = None
|
||||
self.proxy.method_calls.clear()
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.SUCCEEDED)
|
||||
calls = [c[0] for c in self.proxy.method_calls]
|
||||
self.assertLess(calls.index("fs_thaw"), calls.index("backup_targets"))
|
||||
|
||||
def test_recovery_thaws_even_when_the_target_pool_is_gone(self):
|
||||
self.proxy.fs_thaw.side_effect = libvirt_error("thaw failed")
|
||||
op = self.live_interrupted()
|
||||
self.proxy.fs_thaw.side_effect = None
|
||||
self.proxy.fs_thaw.reset_mock()
|
||||
with patch("vmbackups.jobs.target_pool", side_effect=OperationError("Storage pool %(pool)s is gone", pool="b1")):
|
||||
with self.assertRaises(OperationError):
|
||||
CreateBackup().reconcile(op)
|
||||
self.proxy.fs_thaw.assert_called_once_with()
|
||||
|
||||
def test_a_required_freeze_is_not_skipped_when_the_agent_goes(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
op = self.submit(frozen=True)
|
||||
# the run's check finds the agent; it is gone by the freeze
|
||||
self.proxy.is_agent_ready.side_effect = [True, False]
|
||||
self.proxy.fs_freeze.side_effect = libvirt_error("agent not connected")
|
||||
op = self.interrupted(op)
|
||||
self.proxy.begin_clone_backup.assert_not_called()
|
||||
self.assertEqual(op.intent["copy_result"], [False, "agent not connected"])
|
||||
|
||||
def test_a_required_freeze_without_an_agent_at_the_start_makes_nothing(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
op = self.submit(frozen=True)
|
||||
self.proxy.is_agent_ready.return_value = False
|
||||
with self.assertRaisesMessage(OperationError, "guest agent does not answer"):
|
||||
self.run_job(op)
|
||||
self.assertFalse(Backup.objects.exists())
|
||||
|
||||
def test_recovery_of_an_offline_copy_is_uncertain(self):
|
||||
self.proxy.copy_disk_offline.side_effect = RuntimeError("worker gone") # no answer from libvirt
|
||||
op = self.interrupted(self.submit())
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
self.assertEqual(outcome.state, Operation.UNCERTAIN)
|
||||
self.assertEqual(self.removed, [])
|
||||
|
||||
def test_recovery_of_a_ready_backup_succeeds(self):
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.SUCCEEDED)
|
||||
|
||||
def test_cancel_aborts_then_removes(self):
|
||||
op = self.live_interrupted()
|
||||
self.proxy.backup_targets.return_value = set(op.intent["paths"])
|
||||
CreateBackup().cancel(op)
|
||||
self.proxy.abort_backup.assert_called_once_with()
|
||||
Operation.objects.filter(pk=op.pk).update(cancel_requested=True)
|
||||
op.refresh_from_db()
|
||||
self.proxy.backup_targets.return_value = None
|
||||
self.proxy.backup_result.return_value = (False, "operation aborted")
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.CANCELLED)
|
||||
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed)
|
||||
|
||||
def test_an_offline_copy_cancelled_stops_before_its_next_disk(self):
|
||||
op = self.submit()
|
||||
Operation.objects.filter(pk=op.pk).update(cancel_requested=True)
|
||||
with self.assertRaises(Cancelled):
|
||||
self.run_job(op)
|
||||
self.proxy.copy_disk_offline.assert_not_called()
|
||||
self.assertEqual(self.backup(op).state, Backup.FAILED)
|
||||
|
||||
def test_progress_counts_the_copied_disks(self):
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
op.refresh_from_db()
|
||||
self.assertEqual(CreateBackup().progress(op), (GIB, GIB))
|
||||
|
||||
def test_the_log_names_the_target_and_consistency(self):
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
op.refresh_from_db()
|
||||
self.assertEqual(CreateBackup().log_entry(op, Operation.SUCCEEDED)[3], "VM vm1: backed up to nfs1 (offline)")
|
||||
|
||||
def test_a_vm_on_a_host_without_the_target_is_refused(self):
|
||||
other = Compute.objects.create(name="h2", hostname="192.0.2.22", login="u", password="p", type=1)
|
||||
Instance.objects.filter(pk=self.vm.pk).update(compute=other)
|
||||
with self.assertRaisesMessage(OperationError, "has no storage pool on h2"):
|
||||
self.submit()
|
||||
|
||||
|
||||
class BackupTabTests(PageControls, TransactionTestCase):
|
||||
def test_the_tab_lists_backups_and_says_why_not(self):
|
||||
admin = get_user_model().objects.create_superuser("tab-admin", "a@example.com", "x")
|
||||
target = BackupTarget.objects.create(name="nfs1")
|
||||
BackupTargetPool.objects.create(target=target, compute=self.compute, pool="b1", pool_uuid="u")
|
||||
Backup.objects.create(target=target, instance=self.instance, vm_uuid=self.instance.uuid, vm_name="ctl-vm",
|
||||
compute_name="ctl-compute", state=Backup.READY, consistency=Backup.FROZEN, size=3 * GIB)
|
||||
with patch("vmbackups.utils.wvmBackup") as backup_proxy:
|
||||
self.controls(admin)
|
||||
page = lxml_html.fromstring(self.last_page)
|
||||
self.assertTrue(page.xpath("//div[@id='backups']//form[contains(@action, '/backups/vm/')]"))
|
||||
self.assertIn("nfs1", page.xpath("string(//select[@id='backup-target'])"))
|
||||
self.assertIn("3.0", page.xpath("string(//div[@id='backups']//table)"))
|
||||
backup_proxy.return_value.backup_plan.side_effect = OperationError("%(vm)s has TPM state", vm="ctl-vm")
|
||||
self.controls(admin)
|
||||
page = lxml_html.fromstring(self.last_page)
|
||||
self.assertIn("ctl-vm has TPM state", page.xpath("string(//div[@id='backups'])"))
|
||||
self.assertFalse(page.xpath("//div[@id='backups']//form"))
|
||||
|
||||
def test_owners_have_no_backups_tab(self):
|
||||
self.controls(self.user("tab-owner", owner={"is_change": True}))
|
||||
self.assertFalse(lxml_html.fromstring(self.last_page).xpath("//*[@id='backups']"))
|
||||
|
||||
|
||||
class BackupApiTests(TransactionTestCase):
|
||||
def setUp(self):
|
||||
get_settings()
|
||||
self.admin = get_user_model().objects.create_superuser("api_admin", "a@example.com", "pw")
|
||||
self.compute = Compute.objects.create(name="h1", hostname="192.0.2.21", login="u", password="p", type=1)
|
||||
self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="21212121-0000-4000-8000-000000000001")
|
||||
self.target = BackupTarget.objects.create(name="nfs1")
|
||||
BackupTargetPool.objects.create(target=self.target, compute=self.compute, pool="b1", pool_uuid="u")
|
||||
|
||||
@patch("vmbackups.jobs.wvmBackup")
|
||||
def test_api_post_returns_the_job(self, backup_proxy):
|
||||
backup_proxy.return_value = proxy()
|
||||
self.client.force_login(self.admin)
|
||||
response = self.client.post("/api/v1/backups/", {"instance": self.vm.pk, "target": self.target.pk,
|
||||
"submission_key": "key-api-0001"}, content_type="application/json")
|
||||
self.assertEqual(response.status_code, 202, response.content)
|
||||
self.assertEqual(response.json()["kind"], "backup.create")
|
||||
backup = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
|
||||
compute_name="h1", state=Backup.READY)
|
||||
listed = self.client.get("/api/v1/backups/").json()
|
||||
rows = listed["results"] if isinstance(listed, dict) else listed
|
||||
self.assertEqual([r["uuid"] for r in rows], [str(backup.uuid)])
|
||||
self.assertEqual(self.client.get(f"/api/v1/backups/{backup.uuid}/").json()["target"], "nfs1")
|
||||
|
||||
def test_api_is_superuser_only(self):
|
||||
user = get_user_model().objects.create_user("api_user", password="pw")
|
||||
self.client.force_login(user)
|
||||
self.assertEqual(self.client.get("/api/v1/backups/").status_code, 403)
|
||||
response = self.client.post("/api/v1/backups/", {"instance": self.vm.pk, "target": self.target.pk,
|
||||
"submission_key": "key-api-0002"}, content_type="application/json")
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
|
@ -7,4 +7,5 @@ app_name = "vmbackups"
|
|||
urlpatterns = [
|
||||
path("targets/", views.targets, name="targets"),
|
||||
path("targets/<int:target_id>/", views.target, name="target"),
|
||||
path("vm/<int:instance_id>/create/", views.create, name="create"),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
from django.utils.translation import gettext_noop
|
||||
from django.utils.translation import gettext, gettext_noop
|
||||
from libvirt import libvirtError
|
||||
from lxml import etree
|
||||
|
||||
from storages.forms import inside
|
||||
from vrtManager.backup import wvmBackup
|
||||
from vrtManager.util import InUse
|
||||
|
||||
from .models import Backup, BackupTargetPool
|
||||
from .models import Backup, BackupTarget, BackupTargetPool
|
||||
|
||||
|
||||
def inside_vm_pool(conn, pool):
|
||||
|
|
@ -36,3 +38,19 @@ def refuse_target_pool(compute, pool):
|
|||
pool=pool,
|
||||
target=row.target.name,
|
||||
)
|
||||
|
||||
|
||||
def vm_tab(instance):
|
||||
"""The VM page's Backups tab: the VM's backups, the targets of its host,
|
||||
and why it cannot be backed up, if it cannot."""
|
||||
targets = list(BackupTarget.objects.filter(pools__compute=instance.compute).order_by("name"))
|
||||
problem = None
|
||||
if not targets:
|
||||
problem = gettext("No backup target has a storage pool on this VM's host.")
|
||||
else:
|
||||
c = instance.compute
|
||||
try:
|
||||
wvmBackup(c.hostname, c.login, c.password, c.type, instance.name, uuid=instance.uuid).backup_plan()
|
||||
except libvirtError as err:
|
||||
problem = str(err)
|
||||
return {"rows": instance.backups.select_related("target", "operation"), "targets": targets, "problem": problem}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,18 @@ from django.contrib import messages
|
|||
from django.db import transaction
|
||||
from django.db.models import Count
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse
|
||||
from django.views.decorators.http import require_POST
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.utils.translation import gettext_noop
|
||||
from libvirt import libvirtError
|
||||
|
||||
from admin.decorators import superuser_only
|
||||
from instances.models import Instance
|
||||
from logs.audit import audit
|
||||
from operations import claims, jobs
|
||||
from operations.utils import busy_message
|
||||
from webvirtcloud.middleware import error_text
|
||||
from vrtManager.backup import pool_space, target_pool
|
||||
from vrtManager.connection import wvmConnect
|
||||
from vrtManager.util import OperationError
|
||||
|
|
@ -99,3 +105,23 @@ def target(request, target_id):
|
|||
pools = [pool_state(row) for row in target.pools.select_related("compute").order_by("compute__name")]
|
||||
return render(request, "vmbackups/target.html", {"target": target, "pools": pools, "form": form,
|
||||
"backup_count": target.backups.count()})
|
||||
|
||||
|
||||
@require_POST
|
||||
@superuser_only
|
||||
def create(request, instance_id):
|
||||
"""Back up now, from the VM's Backups tab: a backup.create job."""
|
||||
instance = get_object_or_404(Instance, pk=instance_id)
|
||||
page = reverse("instances:instance", args=[instance.pk]) + "#backups"
|
||||
raw = {"instance": instance.pk, "target": request.POST.get("target", ""), "frozen": request.POST.get("frozen", "")}
|
||||
try:
|
||||
op = jobs.submit("backup.create", request.user, raw, request.POST.get("submission_key", ""))
|
||||
except claims.Busy as busy:
|
||||
messages.error(request, busy_message(busy, request.user))
|
||||
except (jobs.SubmissionConflict, libvirtError) as err:
|
||||
messages.error(request, error_text(request, err))
|
||||
except (ValueError, BackupTarget.DoesNotExist):
|
||||
messages.error(request, _("Choose a backup target"))
|
||||
else:
|
||||
jobs.remember_job(request, op)
|
||||
return redirect(page)
|
||||
|
|
|
|||
|
|
@ -2764,11 +2764,15 @@ class wvmInstance(wvmConnect):
|
|||
)
|
||||
|
||||
def backup_targets(self):
|
||||
"""The target paths of the running backup; None when none runs."""
|
||||
"""The target paths of the running backup; None when none runs, also
|
||||
when the domain stopped (a guest that shut down during its backup
|
||||
stops when the backup ends: PRESERVE_SHUTDOWN_DOMAIN)."""
|
||||
if not self.instance.isActive():
|
||||
return None
|
||||
try:
|
||||
xml = self.instance.backupGetXMLDesc(0)
|
||||
except libvirtError as err:
|
||||
if err.get_error_code() == VIR_ERR_NO_DOMAIN_BACKUP:
|
||||
if err.get_error_code() in (VIR_ERR_NO_DOMAIN_BACKUP, VIR_ERR_OPERATION_INVALID):
|
||||
return None
|
||||
raise
|
||||
return set(etree.fromstring(xml).xpath("disks/disk/target/@file"))
|
||||
|
|
@ -2776,7 +2780,14 @@ class wvmInstance(wvmConnect):
|
|||
def backup_progress(self):
|
||||
"""(bytes copied, bytes to copy) of the running backup; None when
|
||||
none runs."""
|
||||
stats = self.instance.jobStats(0)
|
||||
if not self.instance.isActive():
|
||||
return None
|
||||
try:
|
||||
stats = self.instance.jobStats(0)
|
||||
except libvirtError as err:
|
||||
if err.get_error_code() == VIR_ERR_OPERATION_INVALID: # stopped since: its backup ended
|
||||
return None
|
||||
raise
|
||||
if (
|
||||
stats.get("type", VIR_DOMAIN_JOB_NONE) == VIR_DOMAIN_JOB_NONE
|
||||
or stats.get("operation") != VIR_DOMAIN_JOB_OPERATION_BACKUP
|
||||
|
|
|
|||
|
|
@ -210,6 +210,19 @@ class BackupTestCase(unittest.TestCase):
|
|||
}
|
||||
self.assertIsNone(p.backup_progress())
|
||||
|
||||
def test_a_domain_stopped_after_its_backup_has_no_backup_running(self):
|
||||
# PRESERVE_SHUTDOWN_DOMAIN: libvirt stops a guest that shut down once its backup ends
|
||||
p = proxy()
|
||||
p.instance.isActive.return_value = False
|
||||
self.assertIsNone(p.backup_progress())
|
||||
self.assertIsNone(p.backup_targets())
|
||||
p.instance.jobStats.assert_not_called()
|
||||
p.instance.isActive.return_value = True # stopped between the check and the read
|
||||
p.instance.jobStats.side_effect = error(libvirt.VIR_ERR_OPERATION_INVALID)
|
||||
p.instance.backupGetXMLDesc.side_effect = error(libvirt.VIR_ERR_OPERATION_INVALID)
|
||||
self.assertIsNone(p.backup_progress())
|
||||
self.assertIsNone(p.backup_targets())
|
||||
|
||||
def test_result(self):
|
||||
p = proxy()
|
||||
backup = {"type": libvirt.VIR_DOMAIN_JOB_COMPLETED, "operation": libvirt.VIR_DOMAIN_JOB_OPERATION_BACKUP}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ from computes.api.viewsets import ComputeArchitecturesView, ComputeViewSet
|
|||
from networks.api.viewsets import NetworkViewSet
|
||||
from interfaces.api.viewsets import InterfaceViewSet
|
||||
from operations.api.viewsets import OperationViewSet
|
||||
from vmbackups.api import BackupViewSet
|
||||
from storages.api.viewsets import StorageViewSet, VolumeViewSet
|
||||
from instances.api.viewsets import FlavorViewSet, \
|
||||
InstancesViewSet, \
|
||||
|
|
@ -19,6 +20,7 @@ router.register(r'migrate', MigrateViewSet, basename='instance-migrate')
|
|||
router.register(r'flavor', FlavorViewSet, basename='instance-flavor')
|
||||
router.register(r'instances', InstancesViewSet, basename='instance')
|
||||
router.register(r'operations', OperationViewSet, basename='operation')
|
||||
router.register(r'backups', BackupViewSet, basename='backup')
|
||||
|
||||
compute_router = routers.NestedSimpleRouter(router, r'computes', lookup='compute', use_regex_path=False)
|
||||
compute_router.register(r'instances', InstanceViewSet, basename='compute-instance')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue