1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 09:26:03 +00:00

feat(vmbackups): VM owners back up and restore their VMs within a quota

A permission 'Can back up instances' lets a user back up the VMs they
may change into targets open to VM owners, restore those backups over
the VM or as a new VM, and delete the backups they took by hand. Each job
checks the rights at admission and again when it runs.

- A backup quota (GiB, in the user's quota) counts the owner's own
  backups: a backup being made holds its estimate, what its disks and the
  files below them hold. An owner's backups run one at a time, so each
  run's check sees the others.
- An owner restores as a new VM on the VM's compute, into its first
  disk's pool, within the VM quota; the job counts in it until its VM is
  recorded, as a clone does.
- An owner's restore over the VM removes the disks it ran from once the
  switch is done, unless another VM uses them: the owner cannot remove
  them.
- Recovery never begins a deletion the job had not begun.

Superusers keep everything they had.
This commit is contained in:
catborise 2026-11-17 19:29:07 +03:00
parent 1b0a54e3d1
commit db4cbf806a
22 changed files with 1155 additions and 520 deletions

View file

@ -8,6 +8,8 @@ import time
from uuid import UUID, uuid4
from django.core.exceptions import PermissionDenied
from django.db.models import Sum
from django.http import Http404
from django.urls import reverse
from django.db import transaction
from django.utils import timezone
@ -16,10 +18,11 @@ from django.utils.translation import gettext_noop as _
from lxml import etree
from libvirt import VIR_DOMAIN_PAUSED, VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF, VIR_ERR_NO_DOMAIN, VIR_ERR_NO_STORAGE_VOL, libvirtError
from accounts.models import UserAttributes
from appsettings.settings import app_settings
from computes.models import Compute
from instances.jobs import MOVED, PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapshot_free_space, record_vm, vm_claims
from instances.utils import get_random_mac_address
from instances.utils import QUOTA_UNVERIFIED, paths_used_on_other_computes, QUOTA_UNVERIFIED_TEXT, check_user_quota, get_random_mac_address, quota_message
from instances.models import Instance
from operations import claims
from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic
@ -47,6 +50,51 @@ def _superuser(user):
raise PermissionDenied
def _may_use(user, instance=None, target=None):
"""A superuser; or a VM owner with the backup permission, who may change
instance, on a target open to VM owners."""
if user is None or not user.is_active:
raise PermissionDenied
if user.is_superuser:
return
if not user.has_perm("instances.backup_instances"):
raise PermissionDenied
if instance is not None:
from instances.views import get_instance
if instance.is_template: # a template is cloned, not backed up by its owner
raise PermissionDenied
try:
get_instance(user, instance.pk, perm_type="change")
except Http404 as err:
raise PermissionDenied from err
if target is not None and not target.owners:
raise util.OperationError(_("Backup target %(target)s is not open to VM owners"), target=target.name)
def _backup_quota(user, needed):
"""A VM owner's backups by hand (being made: their estimate) and needed
bytes more stay within their backup quota."""
if user.is_superuser:
return
limit = UserAttributes.objects.get_or_create(user=user)[0].max_backup_size
if limit < 0:
return
used = (Backup.objects.filter(taken_by=user, policy__isnull=True, state__in=Backup.LIVING)
.aggregate(total=Sum("size"))["total"] or 0)
if used + needed > limit * 1024**3:
raise util.OperationError(_("The backup needs %(needed).1f GiB; %(used).1f GiB of your %(limit)d GiB backup "
"quota is used"), needed=needed / 1024**3, used=used / 1024**3, limit=limit)
def _vm_pool(instance):
"""The storage pool of the VM's first disk: where its owner's restore as
a new VM goes."""
proxy = _proxy(instance)
path = etree.fromstring(proxy._XMLDesc(PERSISTENT_XML)).xpath("string(devices/disk[@device='disk']/source/@file)")
return proxy.get_volume_by_path(path).storagePoolLookupByVolume().name()
def _proxy(instance):
c = instance.compute
return wvmBackup(c.hostname, c.login, c.password, c.type, instance.name, uuid=instance.uuid)
@ -79,20 +127,27 @@ def _check_state(proxy, 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"])
target = BackupTarget.objects.get(pk=op.params["target"])
_may_use(op.user, instance, target) # again: rights may have changed since the job was queued
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())
# the target claim admits one backup at a time: this check counts every other one of the user's
_backup_quota(op.user, _estimate(plan))
return instance, target, row, proxy, pool, plan
def _estimate(plan):
"""A backup's size before it is made: what its disks hold now."""
return sum(d.get("allocation", 0) for d in plan["disks"])
def _free_space():
values = _snapshot_free_space()
return {"free_percent": values.get("free_percent", 10), "free_min_gib": values.get("free_min_gib", 1)}
@ -245,17 +300,21 @@ class CreateBackup(Kind):
"deadline": parse_datetime(raw["deadline"]).isoformat() if raw.get("deadline") else None}
def plan(self, user, params):
_superuser(user)
instance = _instance(params["instance"])
target = BackupTarget.objects.get(pk=params["target"])
_may_use(user, instance, target)
if not user.is_superuser and (params["policy"] or params["deadline"]):
raise PermissionDenied # only a schedule asks for those
_target_row(target, instance.compute)
proxy = _proxy(instance)
proxy.backup_plan()
_backup_quota(user, _estimate(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},
claims.backup_target_key(target.pk): Claim.EXCLUSIVE,
# a VM owner's backups one at a time: each run's quota check sees the others' rows
**({} if user.is_superuser else {f"backup_quota:{user.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()),
@ -287,7 +346,8 @@ class CreateBackup(Kind):
parent=parent.checkpoint if parent else None, backing=backing)
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, policy=policy,
parent=parent, checkpoint=checkpoint)
parent=parent, checkpoint=checkpoint, taken_by=op.user,
size=_estimate(plan)) # until it is written: the quota counts it
ctx.set_phase(_("Copying disks"))
if live:
return self._run_live(op, ctx, proxy, pool, status)
@ -545,9 +605,18 @@ class DeleteBackup(Kind):
return {"backup": str(UUID(str(raw["backup"]))),
"retention": int(raw["retention"]) if raw.get("retention") else None}
@staticmethod
def _may_delete(user, backup):
"""A superuser; or a VM owner with the backup permission, a backup
they took by hand."""
_may_use(user)
if not user.is_superuser and (backup.taken_by_id != user.pk or backup.policy_id is not None):
raise PermissionDenied
_may_use(user, target=backup.target)
def plan(self, user, params):
_superuser(user)
backup = _backup(params)
self._may_delete(user, backup)
if backup.state == Backup.CREATING:
raise util.OperationError(_("This backup is being made; cancel its job to stop it"))
if backup.depended_on():
@ -561,8 +630,8 @@ class DeleteBackup(Kind):
)
def run(self, op, ctx):
_superuser(op.user)
backup = _backup(op.params)
self._may_delete(op.user, backup)
if op.params.get("retention") and not _beyond_keep(backup, op.params["retention"]):
raise util.OperationError(_("The backup is no longer beyond what its schedule keeps; it is kept"))
if backup.depended_on(): # made since the deletion was queued: the target claim now holds it off
@ -583,6 +652,8 @@ class DeleteBackup(Kind):
return {}
def reconcile(self, op):
if not op.intent.get("deleting"): # stopped before it began: the rights it checks are not checked here
return Outcome(Operation.FAILED, error=say(_("The job stopped before the deletion began")))
backup = Backup.objects.select_related("target").filter(uuid=op.params["backup"]).first()
if backup is None:
return Outcome(Operation.SUCCEEDED)
@ -669,11 +740,40 @@ class RestoreBackup(Kind):
"connect": str(raw.get("connect", "")).lower() in ("1", "true", "on"),
"start": str(raw.get("start", "")).lower() in ("1", "true", "on")}
@staticmethod
def _owner_quota(user, params, backup):
"""For a VM owner: the backup is of a VM they may change, restored on
its compute into its first disk's pool, within their quota. What the
new VM adds to the quota, None for a superuser."""
_may_use(user, backup.instance, backup.target)
if user.is_superuser:
return None
if backup.instance is None:
raise PermissionDenied
if params["compute"] != backup.instance.compute_id or params["pool"] != _vm_pool(backup.instance):
raise PermissionDenied
compute = backup.instance.compute
conn = _connect(compute)
row = _target_row(backup.target, compute)
tree = etree.fromstring(get_file(conn, target_pool(conn, row.pool, row.pool_uuid),
backup.files.get(role=BackupFile.DOMAIN).volume))
memory = int(tree.findtext("memory")) * {"KiB": 1, "MiB": 1024, "GiB": 1024**2}.get(
tree.find("memory").get("unit", "KiB"), 1) // 1024
disk = sum(f.capacity >> 30 for f in backup.files.filter(role=BackupFile.DISK))
quota = {"cpus": int(tree.findtext("vcpu")), "memory": memory, "disk": disk}
exceeded = check_user_quota(user, 1, quota["cpus"], quota["memory"], quota["disk"])
if exceeded == QUOTA_UNVERIFIED:
raise util.OperationError(QUOTA_UNVERIFIED_TEXT)
if exceeded:
raise util.OperationError(_("%(quota)s: cannot restore %(name)s"), quota=quota_message(exceeded),
name=params["name"])
return quota
def plan(self, user, params):
_superuser(user)
backup = _backup(params)
if backup.state != Backup.READY:
raise util.OperationError(_("Only a ready backup is restored"))
quota = self._owner_quota(user, params, backup)
compute = Compute.objects.get(pk=params["compute"])
_target_row(backup.target, compute)
compute.refuse_new_vms()
@ -685,19 +785,25 @@ class RestoreBackup(Kind):
keys[claims.volume_key(compute.pk, params["pool"], name)] = Claim.EXCLUSIVE
keys[claims.backup_key(backup.uuid)] = Claim.SHARED
keys[claims.backup_target_key(backup.target_id)] = Claim.EXCLUSIVE
if quota: # a VM owner's: no other increase of their quota is admitted until the VM is recorded
keys[claims.quota_key(user.pk)] = Claim.EXCLUSIVE
return Plan(
claims=keys,
resource=claims.backup_key(backup.uuid),
label=f"{compute.name}/{params['name']}",
intent={"compute": compute.pk, "uuid": str(uuid4()), "name": params["name"], "from": backup.vm_name,
"volumes": volumes, "pool": params["pool"],
"volumes": volumes, "pool": params["pool"], **({"quota": quota} if quota else {}),
"time": timezone.localtime(backup.created_at).strftime("%Y-%m-%d %H:%M")},
)
def run(self, op, ctx):
_superuser(op.user)
p = op.params
backup = _backup(p)
# the rights again; the quota was taken at admission: the job counts in it until its VM is recorded
_may_use(op.user, backup.instance if not op.user.is_superuser else None, backup.target)
if not op.user.is_superuser and (backup.instance is None or p["compute"] != backup.instance.compute_id
or p["pool"] != _vm_pool(backup.instance)):
raise PermissionDenied # the VM moved since the job was queued: the owner's restore follows it
compute = Compute.objects.get(pk=p["compute"])
compute.refuse_new_vms()
_check_name(p["name"])
@ -812,7 +918,7 @@ class RestoreBackup(Kind):
return _log(op, state, f"restored from the backup of {op.intent['from']} taken {op.intent['time']}")
def _over_plan(backup, proxy):
def _over_plan(backup, proxy, owner=False):
"""What a restore over the backup's VM makes: {"disks": {dev: [pool,
volume name]}, "old": {dev: the disk's path now}, "nvram": the VM's NVRAM
path or None, "tpm": bool}.
@ -829,6 +935,10 @@ def _over_plan(backup, proxy):
if set(now) != set(files):
raise util.OperationError(_("The VM's disks (%(now)s) are not the backup's (%(then)s); restore it as a new VM "
"or one disk"), now=", ".join(sorted(now)), then=", ".join(sorted(files)))
for dev, f in files.items(): # a VM owner's disk quota counts the VM's disks as they are now
if owner and f.capacity > now[dev]["capacity"]:
raise util.OperationError(_("The backup's disk %(dev)s is larger than the VM's now; restore it as a new VM"),
dev=dev)
if bool(plan["nvram"]) != (backup.manifest.get("nvram", "none") != "none"):
raise util.OperationError(_("The VM's UEFI firmware changed since the backup; restore it as a new VM"))
if plan["tpm"] != (backup.manifest.get("tpm", "none") != "none"):
@ -854,15 +964,16 @@ class RestoreOver(Kind):
return {"backup": str(UUID(str(raw["backup"])))}
def plan(self, user, params):
_superuser(user)
backup = _backup(params)
if backup.state != Backup.READY:
raise util.OperationError(_("Only a ready backup is restored"))
instance = backup.instance
if instance is None:
_may_use(user)
raise util.OperationError(_("The backup's VM is no longer in the panel; restore it as a new VM"))
_may_use(user, instance, backup.target)
_target_row(backup.target, instance.compute)
over = _over_plan(backup, _proxy(instance))
over = _over_plan(backup, _proxy(instance), owner=not user.is_superuser)
keys = {claims.compute_key(instance.compute_id): Claim.SHARED, claims.instance_key(instance.uuid): Claim.EXCLUSIVE,
claims.backup_key(backup.uuid): Claim.SHARED, claims.backup_target_key(backup.target_id): Claim.EXCLUSIVE}
for pool, name in over["disks"].values(): # no other job makes a volume of these names meanwhile
@ -876,13 +987,13 @@ class RestoreOver(Kind):
)
def run(self, op, ctx):
_superuser(op.user)
backup = _backup(op.params)
instance = _instance(backup.instance_id)
_may_use(op.user, instance, backup.target)
if instance.compute_id != op.intent["compute"]:
raise util.OperationError(MOVED)
proxy = _proxy(instance)
if _over_plan(backup, proxy) != op.intent["over"]:
if _over_plan(backup, proxy, owner=not op.user.is_superuser) != op.intent["over"]:
raise util.OperationError(_("The VM's disks changed after the job was queued"))
row = _target_row(backup.target, instance.compute)
tpool = target_pool(proxy, row.pool, row.pool_uuid)
@ -914,10 +1025,12 @@ class RestoreOver(Kind):
ctx.record_intent(copied=[*op.intent.get("copied", []), dev], paths=paths, copying=None)
# the VM may have been started or saved outside the panel meanwhile: then it keeps its disks
if _over_plan(backup, proxy) != op.intent["over"]:
if _over_plan(backup, proxy, owner=not op.user.is_superuser) != op.intent["over"]:
raise util.OperationError(_("The VM changed while its backup was copied; it keeps its disks"))
# an owner cannot remove the old disks: they go once the VM no longer names them
remove = [] if op.user.is_superuser else list(op.intent["over"]["old"].values())
ctx.set_phase(_("Replacing the VM's disks"))
ctx.record_intent(switching=True, autostart=bool(proxy.instance.autostart()))
ctx.record_intent(switching=True, autostart=bool(proxy.instance.autostart()), remove=remove)
return self._switch(op, backup, proxy, tpool)
@staticmethod
@ -947,8 +1060,24 @@ class RestoreOver(Kind):
proxy._defineXML(restore_over_definition(proxy._XMLDesc(PERSISTENT_XML), disks))
if op.intent["autostart"]:
proxy.instance.setAutostart(1)
RestoreOver._remove_old(op, proxy, backup.instance)
return {"open": reverse("instances:instance", args=[backup.instance_id])}
@staticmethod
def _remove_old(op, proxy, instance):
"""The disks the VM ran from, after the switch, when its owner restored
it; one another domain uses, checked right before, is kept."""
paths = op.intent.get("remove", [])
if not paths:
return
used = proxy.paths_used_by_other_domains(paths) | paths_used_on_other_computes(instance.compute, paths)
for path in (path for path in paths if path not in used):
try:
proxy.get_volume_by_path(path).delete(0)
except libvirtError as err:
if err.get_error_code() != VIR_ERR_NO_STORAGE_VOL:
raise
def progress(self, op):
disks = Backup.objects.filter(uuid=op.params["backup"]).values_list("files__dev", "files__capacity", "files__role")
copied = set(op.intent.get("copied", []))
@ -969,6 +1098,7 @@ class RestoreOver(Kind):
# defined: the switch is done; the VM may have run since, its NVRAM and TPM are not replaced again
if op.intent["autostart"]:
proxy.instance.setAutostart(1)
self._remove_old(op, proxy, instance)
return Outcome(Operation.SUCCEEDED, result={"open": reverse("instances:instance", args=[instance.pk])})
if proxy.get_status() != VIR_DOMAIN_SHUTOFF or proxy.instance.hasManagedSaveImage(0):
return Outcome(Operation.UNCERTAIN, error=say(_(

View file

@ -0,0 +1,26 @@
# Generated by Django 5.2.18 on 2026-11-17 16:04
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmbackups', '0004_incremental'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name='backup',
name='taken_by',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='backuptarget',
name='owners',
field=models.BooleanField(default=False),
),
]

View file

@ -14,6 +14,7 @@ class BackupTarget(models.Model):
name = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
checked_at = models.DateTimeField(null=True) # its last target check that ended
owners = models.BooleanField(default=False) # VM owners with the backup permission may use it
def __str__(self):
return self.name
@ -87,6 +88,7 @@ class BackupRun(models.Model):
class Backup(models.Model):
CREATING, READY, FAILED, DELETING, MISSING = "creating", "ready", "failed", "deleting", "missing"
STATES = [(CREATING, "creating"), (READY, "ready"), (FAILED, "failed"), (DELETING, "deleting"), (MISSING, "missing")]
LIVING = (CREATING, READY, MISSING, DELETING) # its files are or will be in the target
OFFLINE, FROZEN, CRASH = "offline", "frozen", "crash"
CONSISTENCIES = [(OFFLINE, "offline"), (FROZEN, "frozen"), (CRASH, "crash-consistent")]
@ -108,13 +110,15 @@ class Backup(models.Model):
# an incremental backup's base; its disk files have the parent's as backing files
parent = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, related_name="children")
checkpoint = models.CharField(max_length=64, blank=True) # the VM's checkpoint made with it
# whose job made it: a VM owner's own backups count in their backup quota
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="+")
class Meta:
ordering = ["-created_at"]
def depended_on(self):
"""Whether a backup builds on this one: a failed one holds nothing."""
return self.children.filter(state__in=(self.CREATING, self.READY, self.MISSING, self.DELETING)).exists()
return self.children.filter(state__in=self.LIVING).exists()
@property
def prefix(self):

View file

@ -80,6 +80,13 @@ class DeleteBackupTests(TransactionTestCase):
self.assertEqual(DeleteBackup().reconcile(op).state, Operation.SUCCEEDED)
self.assertFalse(Backup.objects.exists())
def test_recovery_does_not_begin_a_deletion(self):
# the worker stopped before run: the rights it would check are not checked again by recovery
op = self.submit()
self.assertEqual(DeleteBackup().reconcile(op).state, Operation.FAILED)
self.assertTrue(Backup.objects.filter(pk=self.backup.pk).exists())
self.assertEqual(self.removed, [])
def test_a_creating_backup_is_not_deleted(self):
Backup.objects.filter(pk=self.backup.pk).update(state=Backup.CREATING)
with self.assertRaisesMessage(OperationError, "being made"):

View file

@ -0,0 +1,294 @@
"""VM owners with the backup permission: their VMs, targets open to owners,
their own backups, and the backup quota (layer 6)."""
import hashlib
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import PermissionDenied
from django.test import TransactionTestCase
from accounts.models import UserAttributes, UserInstance
from appsettings.settings import get_settings
from computes.models import Compute
from instances.models import Instance
from operations import jobs
from operations.jobs import Context
from operations.models import Operation, acquire
from vmbackups.jobs import CreateBackup
from vmbackups.models import Backup, BackupFile, BackupTarget, BackupTargetPool
from vmbackups.tests.test_create import plan, proxy, target_pool
from vrtManager.util import OperationError
GIB = 1024**3
WORKER = "wvc-test:1:a"
DEFINITION = (
"<domain type='kvm'><name>vm1</name><uuid>71717171-0000-4000-8000-000000000001</uuid>"
"<memory unit='KiB'>2097152</memory><vcpu>2</vcpu>"
"<os><type arch='x86_64' machine='pc-q35-10.1'>hvm</type></os><devices><emulator>/usr/libexec/qemu-kvm</emulator>"
"<disk type='file' device='disk'><driver name='qemu' type='qcow2'/><source file='/pool/a.qcow2'/><target dev='vda'/></disk>"
"</devices></domain>"
).encode()
class OwnerTests(TransactionTestCase):
def setUp(self):
get_settings()
self.owner = get_user_model().objects.create_user("bk_owner", password="pw")
self.owner.user_permissions.add(Permission.objects.get(codename="backup_instances"))
self.compute = Compute.objects.create(name="h1", hostname="192.0.2.71", login="u", password="p", type=1)
self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="71717171-0000-4000-8000-000000000001")
UserInstance.objects.create(user=self.owner, instance=self.vm, is_change=True)
self.target = BackupTarget.objects.create(name="nfs1", owners=True)
BackupTargetPool.objects.create(target=self.target, compute=self.compute, pool="b1", pool_uuid="pool-uuid")
UserAttributes.objects.update_or_create(user=self.owner, defaults={"max_backup_size": 10})
self.proxy = proxy()
self.proxy.backup_plan.return_value = plan()
self.proxy.backup_plan.return_value["disks"][0]["allocation"] = 4 * GIB
self.pool = target_pool()
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(return_value="sha")),
("vmbackups.jobs.remove_files", MagicMock()),
):
patcher = patch(name, value)
patcher.start()
self.addCleanup(patcher.stop)
def submit(self, kind, raw, user=None):
op = jobs.submit(kind, user or self.owner, raw, 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 back_up(self, **raw):
return self.submit("backup.create", {"instance": self.vm.pk, "target": self.target.pk, **raw})
def taken(self, size_gib, user=None, policy=None, state=Backup.READY):
return Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
compute_name="h1", state=state, size=size_gib * GIB, taken_by=user or self.owner,
policy=policy)
# backing up
def test_an_owner_backs_up_their_vm_and_the_backup_is_theirs(self):
op = self.back_up()
CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
backup = Backup.objects.get(uuid=op.intent["backup"])
self.assertEqual((backup.state, backup.taken_by), (Backup.READY, self.owner))
def test_without_the_permission_or_change_rights_nothing_is_backed_up(self):
self.owner.user_permissions.clear()
with self.assertRaises(PermissionDenied):
self.back_up()
self.owner.user_permissions.add(Permission.objects.get(codename="backup_instances"))
UserInstance.objects.filter(user=self.owner).update(is_change=False)
self.owner = get_user_model().objects.get(pk=self.owner.pk) # a fresh permission cache
with self.assertRaises(PermissionDenied):
self.back_up()
def test_a_target_not_open_to_owners_is_refused(self):
BackupTarget.objects.filter(pk=self.target.pk).update(owners=False)
with self.assertRaisesMessage(OperationError, "not open to VM owners"):
self.back_up()
def test_an_owner_cannot_act_as_a_schedule(self):
with self.assertRaises(PermissionDenied):
self.back_up(policy=1)
def test_rights_lost_after_the_job_was_queued_stop_it(self):
op = self.back_up()
BackupTarget.objects.filter(pk=self.target.pk).update(owners=False)
with self.assertRaisesMessage(OperationError, "not open to VM owners"):
CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
def test_the_quota_counts_the_owners_own_backups(self):
self.taken(6)
self.taken(50, policy=None, user=get_user_model().objects.create_superuser("adm", "a@example.com", "pw"))
self.taken(50, state=Backup.FAILED)
op = self.back_up() # 6 + 4 of 10 GiB: the administrator's and the failed one do not count
CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED))
with self.assertRaisesMessage(OperationError, "backup quota"):
self.back_up() # 6 + the new one's real size + 4
UserAttributes.objects.filter(user=self.owner).update(max_backup_size=-1)
self.back_up()
def test_a_backup_being_made_holds_its_estimate(self):
op = self.back_up()
# the run check: another backup of the owner was admitted and made its row meanwhile
self.taken(7, state=Backup.CREATING)
with self.assertRaisesMessage(OperationError, "backup quota"):
CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
def test_an_owners_backups_run_one_at_a_time(self):
# different VMs, different targets: the run check reads the other's row only after it exists
op = self.back_up()
self.assertTrue(op.claims.filter(resource=f"backup_quota:{self.owner.pk}", mode="exclusive").exists())
def test_no_quota_means_none(self):
UserAttributes.objects.filter(user=self.owner).update(max_backup_size=0)
with self.assertRaisesMessage(OperationError, "backup quota"):
self.back_up()
# deleting
def test_an_owner_deletes_only_their_own_backups_by_hand(self):
mine, schedules, others = self.taken(1), self.taken(1), self.taken(1, user=get_user_model().objects.create_user("x"))
from vmbackups.models import BackupPolicy
import datetime
policy = BackupPolicy.objects.create(name="n", target=self.target, time=datetime.time(2), keep=2)
Backup.objects.filter(pk=schedules.pk).update(policy=policy)
self.submit("backup.delete", {"backup": str(mine.uuid)})
for backup in (schedules, others):
with self.assertRaises(PermissionDenied):
self.submit("backup.delete", {"backup": str(backup.uuid)})
# restoring
def ready_backup(self):
backup = self.taken(1, user=get_user_model().objects.create_superuser("adm2", "b@example.com", "pw"))
BackupFile.objects.create(backup=backup, role=BackupFile.DISK, dev="vda", volume=f"{backup.prefix}-vda.qcow2",
format="qcow2", capacity=8 * GIB)
BackupFile.objects.create(backup=backup, role=BackupFile.DOMAIN, volume=f"{backup.prefix}-domain.xml",
size=len(DEFINITION), sha256=hashlib.sha256(DEFINITION).hexdigest())
return backup
def restore(self, backup, **raw):
return self.submit("backup.restore", {"backup": str(backup.uuid), "compute": self.compute.pk, "pool": "default",
"name": "vm1-restored", **raw})
def test_an_owner_restores_as_a_new_vm_on_the_vms_host_and_pool_within_the_quota(self):
backup = self.ready_backup()
conn = MagicMock()
with (patch("vmbackups.jobs.wvmConnect", return_value=conn),
patch("vmbackups.jobs.get_file", return_value=DEFINITION),
patch("vmbackups.jobs._vm_pool", return_value="default")):
UserAttributes.objects.filter(user=self.owner).update(max_instances=-1, max_cpus=-1, max_memory=-1,
max_disk_size=-1)
op = self.restore(backup)
self.assertEqual(op.intent["quota"], {"cpus": 2, "memory": 2048, "disk": 8})
Operation.objects.all().delete()
from operations.models import Claim
Claim.objects.all().delete()
for raw in ({"compute": Compute.objects.create(name="h2", hostname="192.0.2.72", login="u", password="p",
type=1).pk}, {"pool": "fast"}):
with self.assertRaises(PermissionDenied):
self.restore(backup, **raw)
from instances.utils import QuotaExceeded
# the owner's VMs are read from their hosts: here the quota check answers
with (patch("vmbackups.jobs.check_user_quota", return_value=QuotaExceeded("cpu", 3, 1)) as check,
self.assertRaisesMessage(OperationError, "vCPU quota")):
self.restore(backup)
check.assert_called_once_with(self.owner, 1, 2, 2048, 8)
def test_a_restore_counts_in_the_quota_until_its_vm_is_recorded(self):
from instances.utils import check_user_quota
backup = self.ready_backup()
UserAttributes.objects.filter(user=self.owner).update(max_instances=2, max_cpus=-1, max_memory=-1, max_disk_size=-1)
with (patch("vmbackups.jobs.wvmConnect", return_value=MagicMock()),
patch("vmbackups.jobs.get_file", return_value=DEFINITION),
patch("vmbackups.jobs._vm_pool", return_value="default")):
self.restore(backup)
# the owner's VM and the restore make two: one more is over
self.assertTrue(check_user_quota(self.owner, 1, 0, 0, 0))
def test_an_owners_restore_over_removes_the_old_disks_not_used_elsewhere(self):
from vmbackups.jobs import RestoreOver
backup = self.ready_backup()
over = {"disks": {"vda": ["default", "vm1-vda-x.qcow2"]}, "old": {"vda": "/pool/a.qcow2"}, "nvram": None, "tpm": False}
old_vol = MagicMock()
self.proxy.get_volume_by_path.return_value = old_vol
self.proxy.paths_used_by_other_domains.return_value = set()
self.proxy._XMLDesc.return_value = DEFINITION.decode()
self.proxy.get_status.return_value = 5
self.proxy.instance.autostart.return_value = 0
with (patch("vmbackups.jobs._over_plan", return_value=over),
patch("vmbackups.jobs._check_files"),
patch("vmbackups.jobs.paths_used_on_other_computes", return_value=set()),
patch("vmbackups.jobs.wvmStorage") as storage,
patch("vmbackups.jobs.wvmInstance._refuse_taken"),
patch("vmbackups.jobs.check_target_space")):
storage.return_value.clone_volume.return_value = "/pool/vm1-vda-x.qcow2"
self.proxy.file_pools.return_value = {"default": (MagicMock(), "/pool")}
op = self.submit("backup.restore_over", {"backup": str(backup.uuid)})
RestoreOver().run(op, Context(op, SimpleNamespace(identity=WORKER)))
op.refresh_from_db()
self.assertEqual(op.intent["remove"], ["/pool/a.qcow2"])
old_vol.delete.assert_called_once_with(0)
def test_an_old_disk_used_meanwhile_by_another_vm_is_kept(self):
from vmbackups.jobs import RestoreOver
op = SimpleNamespace(intent={"remove": ["/pool/a.qcow2", "/pool/b.qcow2"]}, user=self.owner,
params={"backup": ""})
self.proxy.paths_used_by_other_domains.return_value = {"/pool/a.qcow2"} # attached since the switch began
volumes = {}
self.proxy.get_volume_by_path.side_effect = lambda path: volumes.setdefault(path, MagicMock())
with patch("vmbackups.jobs.paths_used_on_other_computes", return_value=set()):
RestoreOver._remove_old(op, self.proxy, self.vm)
self.assertEqual([p for p, v in volumes.items() if v.delete.called], ["/pool/b.qcow2"])
def test_an_owner_restores_over_only_disks_no_larger_than_the_vms(self):
from vmbackups.jobs import _over_plan
backup = self.ready_backup() # its vda is 8 GiB; the VM's now 1 GiB
self.proxy.get_status.return_value = 5
self.proxy.instance.snapshotNum.return_value = 0
self.proxy.instance.name.return_value = "vm1"
self.proxy.backup_plan.return_value = {"disks": [{"dev": "vda", "path": "/pool/a.qcow2", "pool": "default",
"format": "qcow2", "capacity": GIB}], "nvram": None, "tpm": False}
with self.assertRaisesMessage(OperationError, "larger"):
_over_plan(backup, self.proxy, owner=True)
self.assertTrue(_over_plan(backup, self.proxy, owner=False))
def test_an_owners_restore_holds_their_quota(self):
backup = self.ready_backup()
with (patch("vmbackups.jobs.wvmConnect", return_value=MagicMock()),
patch("vmbackups.jobs.get_file", return_value=DEFINITION),
patch("vmbackups.jobs._vm_pool", return_value="default"),
patch("vmbackups.jobs.check_user_quota", return_value="")):
op = self.restore(backup)
self.assertTrue(op.claims.filter(resource=f"quota:user:{self.owner.pk}", mode="exclusive").exists())
def test_a_template_is_not_backed_up_by_an_owner(self):
self.owner.is_staff = True # a staff owner may change a template
self.owner.save()
Instance.objects.filter(pk=self.vm.pk).update(is_template=True)
with self.assertRaises(PermissionDenied):
self.back_up()
def test_a_closed_target_stops_an_owners_deletion(self):
mine = self.taken(1)
BackupTarget.objects.filter(pk=self.target.pk).update(owners=False)
with self.assertRaisesMessage(OperationError, "not open to VM owners"):
self.submit("backup.delete", {"backup": str(mine.uuid)})
def test_another_owners_vm_is_not_restored_over(self):
backup = self.ready_backup()
UserInstance.objects.filter(user=self.owner).delete()
with self.assertRaises((PermissionDenied, Exception)):
self.submit("backup.restore_over", {"backup": str(backup.uuid)})
def test_a_restore_of_another_vms_backup_is_refused(self):
backup = self.ready_backup()
other = Instance.objects.create(compute=self.compute, name="vm2", uuid="71717171-0000-4000-8000-000000000002")
Backup.objects.filter(pk=backup.pk).update(instance=other)
with self.assertRaises(PermissionDenied):
self.restore(backup)
def test_superusers_keep_restore_one_disk(self):
backup = self.ready_backup()
with self.assertRaises(PermissionDenied):
self.submit("backup.restore_disk", {"backup": str(backup.uuid), "dev": "vda", "compute": self.compute.pk,
"pool": "default", "name": "x.qcow2"})