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

fix: a volume a job writes is not copied, attached or its pool stopped; download progress each second

A download into a pool listed its volume while it was written. The page
let a superuser copy it (the copy got a half-written file, live), attach
it to a VM, or stop the pool under it. Now:

- the copy job claims its source volume shared, and the worker refuses
  a copy whose name the source's format changed before the claim;
- attaching an existing volume holds it exclusive from its first read,
  so neither a download nor a copy is under way, and its format is read
  after the download ended;
- stopping or deleting a pool (page and API) holds the pool exclusive,
  and its backup target's claim if it is one; restores claim the pools
  they write into shared.

Each is refused with the job in the way named, as a volume delete
already was.

The download recorded its progress every 16 MiB, so a slow server's
bar stayed empty for a long time; it records it each second, with the
cancel check. The worker checks the name is still free before it
starts. A snapshot name or tag typed in the VM list's bulk form keeps
the list from reloading, as a chosen VM did.
This commit is contained in:
catborise 2026-11-20 15:12:20 +03:00
parent 7c8f5b3150
commit 7e70595fd2
19 changed files with 588 additions and 450 deletions

View file

@ -10,10 +10,11 @@ from django.utils.translation import gettext as _
from drf_spectacular.utils import extend_schema, inline_serializer
from libvirt import libvirtError
from logs.audit import audit, failed
from operations import claims
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from vmbackups.utils import refuse_backup_volume
from vmbackups.utils import pool_stop_claims, refuse_backup_volume
from vrtManager.storage import wvmStorage, wvmStorages
from webvirtcloud.serializers import ErrorSerializer, StatusSerializer
@ -93,7 +94,9 @@ class StorageViewSet(viewsets.ViewSet):
conn = wvmStorage(
compute.hostname, compute.login, compute.password, compute.type, pk
)
with audit(request, compute, f"Storage pool {pk}", "stop"):
# not while a job (a download, a copy) works in it
with claims.hold(pool_stop_claims(compute, pk)), \
audit(request, compute, f"Storage pool {pk}", "stop"):
ret = conn.stop()
return Response({"status": "Pool stop command send: " + str(ret)})

View file

@ -64,6 +64,10 @@ class CloneVolume(Kind):
stg = _storage(op.params)[1]
if op.intent["target"] in stg.get_volumes():
raise util.OperationError(gettext_noop("Name of volume already in use"))
# the source's format, which names the copy, may have changed before its claim was taken (a download ended)
if stg.clone_name(op.params["name"], op.params["format"] or stg.get_volume_format_type(op.params["image"])) \
!= op.intent["target"]:
raise util.OperationError(gettext_noop("The volume changed since the copy was asked; ask it again"))
stg.refuse_running_copy(op.params["image"]) # the VM may have started since
def plan(self, user, params):
@ -78,7 +82,9 @@ class CloneVolume(Kind):
if target in volumes:
raise util.OperationError(gettext_noop("Name of volume already in use"))
pool = claims.pool_key(compute.pk, params["pool"])
# the source shared: not copied while a download writes it
return Plan(claims={claims.compute_key(compute.pk): Claim.SHARED, pool: Claim.SHARED,
claims.volume_key(compute.pk, params["pool"], params["image"]): Claim.SHARED,
claims.volume_key(compute.pk, params["pool"], target): Claim.EXCLUSIVE},
resource=pool, label=f"{compute.name}/{params['pool']}", intent={"target": target})
@ -158,7 +164,6 @@ class UploadVolume(Kind):
# a volume's name as the pool page's forms take it
VOLUME_NAME = re.compile(r"[A-Za-z0-9._-]{1,120}")
FETCH_PROGRESS_EVERY = 16 * 2**20 # bytes between two progress records
FETCH_REDIRECTS = 5
FETCH_TIMEOUT = urllib3.Timeout(connect=10, read=60)
BAD_ADDRESS = gettext_noop("Give an http or https address")
@ -257,6 +262,12 @@ class FetchVolume(Kind):
if op.user is None or not op.user.is_active:
raise PermissionDenied
self.validate(op.user, op.params)
# a volume made outside the panel since the job was queued may have taken the name
stg = _storage(op.params)[1]
with contextlib.suppress(libvirtError):
stg.refresh()
if op.params["name"] in stg.get_volumes():
raise util.OperationError(gettext_noop("The pool has a volume named %(name)s"), name=op.params["name"])
@staticmethod
def _stop_if_cancelled(op):
@ -284,18 +295,16 @@ class FetchVolume(Kind):
raise
def chunks():
done, recorded, checked = 0, 0, time.monotonic()
done, checked = 0, time.monotonic()
try:
for data in answer.stream(2**20, decode_content=False):
done += len(data)
if done > size:
raise util.OperationError(gettext_noop("The server sent more than the file's size"))
if time.monotonic() - checked >= 1:
if time.monotonic() - checked >= 1: # each second: a cancel seen, the progress shown
self._stop_if_cancelled(op)
checked = time.monotonic()
if done - recorded >= FETCH_PROGRESS_EVERY:
ctx.record_intent(done=done)
recorded = done
checked = time.monotonic()
yield data
except urllib3.exceptions.HTTPError as err: # the connection lost, a read timeout
raise _download_error(err) from None

View file

@ -14,6 +14,8 @@ from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from operations.claims import admit
from operations.models import Claim
from rest_framework.test import APIClient
NODE = "<node><pool type='dir'><name>use-pool</name><target><path>/use-pool</path></target></pool></node>"
@ -65,6 +67,28 @@ class PoolInUseTests(TestCase):
self.assertIn("running VMs api-user", response.json()["detail"])
self.assertTrue(self.pool.isActive())
def test_a_pool_a_job_works_in_is_not_stopped_or_deleted(self):
# a download or a copy in it: its file would be left half-written, its cleanup could not see it
admit({f"pool:{self.compute.id}:use-pool": Claim.SHARED}, holder="other-node:1:1")
for action in ("stop", "delete"):
with self.subTest(action=action):
self.assertIn("A short operation is in progress on this resource; try again in a moment.", self.post(action))
self.assertTrue(self.pool.isActive())
api = APIClient()
api.force_login(self.admin)
response = api.post(reverse("compute-storage-stop", kwargs={"compute_pk": self.compute.id, "pk": "use-pool"}))
self.assertEqual(response.status_code, 409)
self.assertTrue(self.pool.isActive())
def test_a_backup_target_pool_is_not_stopped_during_a_backup(self):
from vmbackups.models import BackupTarget, BackupTargetPool
target = BackupTarget.objects.create(name="nfs-b")
BackupTargetPool.objects.create(target=target, compute=self.compute, pool="use-pool", pool_uuid="u1")
admit({f"backup_target:{target.pk}": Claim.EXCLUSIVE}, holder="other-node:1:1") # a backup writes to it
self.assertIn("A short operation is in progress on this resource; try again in a moment.", self.post("stop"))
self.assertTrue(self.pool.isActive())
def test_a_pool_a_vm_definition_names_is_not_deleted(self):
self.conn.defineXML(domain("by-name", "type='volume'><source pool='use-pool' volume='v1.img'/>"))
self.conn.defineXML(domain("by-path", f"type='file'><source file='{self.path}'/>"))

View file

@ -10,6 +10,7 @@ from django.urls import reverse
from computes.models import Compute
from operations.jobs import Context
from operations.claims import admit
from operations.models import Claim, Operation, acquire
from libvirt import libvirtError
from storages.jobs import CloneVolume
@ -39,8 +40,9 @@ class VolumeCloneJobTestCase(TransactionTestCase):
self.assertRedirects(response, url, fetch_redirect_response=False)
op = Operation.objects.get()
self.assertEqual((op.kind, op.intent["target"]), ("volume.clone", "copy.qcow2"))
self.assertIn((f"volume:{self.compute.pk}:pool-a/copy.qcow2", "exclusive"),
set(Claim.objects.values_list("resource", "mode")))
self.assertLessEqual({(f"volume:{self.compute.pk}:pool-a/copy.qcow2", "exclusive"),
(f"volume:{self.compute.pk}:pool-a/base.qcow2", "shared")},
set(Claim.objects.values_list("resource", "mode")))
self.stg.clone_volume.assert_not_called()
acquire("wvc-test:1:a", "wvc-test")
@ -74,6 +76,18 @@ class VolumeCloneJobTestCase(TransactionTestCase):
self.assertContains(response, "The running VMs vm use volume base.qcow2")
self.assertFalse(Operation.objects.exists())
@patch("storages.views.wvmStorage")
def test_a_volume_a_job_writes_is_not_copied(self, page):
# a download holds the volume it writes: the copy waits for it, not a half-written file
page.return_value.is_active.return_value = False
page.return_value.get_size.return_value = (1, 1)
url = reverse("storage", args=[self.compute.pk, "pool-a"])
admit({f"volume:{self.compute.pk}:pool-a/base.qcow2": Claim.EXCLUSIVE}, holder="other-node:1:1")
response = self.client.post(url, {"cln_volume": "1", "image": "base.qcow2", "name": "copy",
"submission_key": "key-vol00005"}, follow=True)
self.assertContains(response, "try again in a moment")
self.assertFalse(Operation.objects.exists())
def test_recovery(self):
self.stg.get_volumes.return_value = ["base.qcow2", "copy.qcow2"]
op = Operation(params={"compute": self.compute.pk, "pool": "pool-a"}, intent={"target": "copy.qcow2"})
@ -89,6 +103,10 @@ class VolumeCloneJobTestCase(TransactionTestCase):
params={"compute": self.compute.pk, "pool": "pool-a", "image": "base.qcow2", "name": "copy",
"format": "", "prealloc": False})
CloneVolume().precheck(op, None)
self.stg.clone_name.return_value = "copy.img" # the source's format changed before the claim (a download ended)
with self.assertRaisesMessage(libvirtError, "The volume changed since the copy was asked"):
CloneVolume().precheck(op, None)
self.stg.clone_name.return_value = "copy.qcow2"
self.stg.get_volumes.return_value = ["base.qcow2", "copy.qcow2"] # made outside the panel meanwhile
with self.assertRaisesMessage(libvirtError, "Name of volume already in use"):
CloneVolume().precheck(op, None)

View file

@ -139,6 +139,12 @@ class FetchJobTestCase(TransactionTestCase):
self.run_job(op, [b"ab"])
self.assertEqual(recorded, [True])
def test_the_worker_checks_the_name_is_still_free(self):
op = self.queue()
self.stg.get_volumes.return_value = ["rocky-10.qcow2"] # made outside the panel meanwhile
with self.assertRaisesRegex(util.OperationError, "has a volume named"):
FetchVolume().precheck(op, None)
def test_a_deactivated_superuser_s_job_does_not_run(self):
op = self.queue()
op.user.is_active = False
@ -147,6 +153,22 @@ class FetchJobTestCase(TransactionTestCase):
with self.assertRaises(PermissionDenied):
FetchVolume().precheck(op, None)
def test_the_progress_is_recorded_each_second(self):
# a slow server: the bar moves before 16 MiB came
op = self.queue()
seen = []
def write(name, size, chunks):
for _chunk in chunks:
seen.append(Operation.objects.get(pk=op.pk).intent["done"])
return size
self.stg.write_volume.side_effect = write
clock = iter(range(0, 100, 2))
with patch("storages.jobs.time.monotonic", side_effect=lambda: next(clock)):
self.run_job(op, [b"ab", b"cd", b"ef"])
self.assertEqual(seen, [2, 4, 6])
def test_more_than_the_size_told_is_not_written(self):
op = self.queue()
self.stg.write_volume.side_effect = lambda name, size, chunks: sum(len(c) for c in chunks)

View file

@ -24,7 +24,7 @@ from vrtManager.storage import wvmStorage, wvmStorages
from storages.forms import AddStgPool, CloneImage, CreateVolumeForm
from storages.jobs import is_iso
from storages.upload import write_chunk
from vmbackups.utils import backups_of, refuse_backup_volume, refuse_target_pool
from vmbackups.utils import backups_of, pool_stop_claims, refuse_backup_volume, refuse_target_pool
from webvirtcloud.gunicorn_worker import request_progressed
@ -146,16 +146,18 @@ def storage(request, compute_id, pool):
with audit(request, compute, subject, "start"):
conn.start()
return HttpResponseRedirect(request.get_full_path())
# stopped or deleted only while no job (a download, a copy) works in it
in_pool = pool_stop_claims(compute, pool)
if "stop" in request.POST:
try:
with audit(request, compute, subject, "stop"):
with claims.hold(in_pool), audit(request, compute, subject, "stop"):
conn.stop()
except OperationError as err: # a running VM's disk is in it
messages.error(request, str(err))
return HttpResponseRedirect(request.get_full_path())
if "delete" in request.POST:
try:
with audit(request, compute, subject, "delete"):
with claims.hold(in_pool), audit(request, compute, subject, "delete"):
refuse_target_pool(compute, pool)
conn.delete()
except OperationError as err: # a VM names it for a disk