mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +00:00
fix: a downloading volume is not put in a new VM or a CD-ROM; slow downloads read as bytes come
A download writes its volume under its final name, so the volume was offered while half written. #685 kept a copy and an attach away from it; a new VM and a CD-ROM still took it. The VM create job now claims the volumes it is made from (a writable one exclusive, a template or a CD-ROM image shared), and adding a CD-ROM or inserting media holds the ISO's volume shared and reads the ISO again in that pool under the claim (iso_location, iso_path_in). Each is refused with the download named. A claim's key holds a pool's and a volume's names: longer than 255 characters on PostgreSQL it failed the request; Claim.resource is text. A pool that belongs to more than one backup target is not stopped while a backup to any of them runs (it took the first target only). The download read 1 MiB at a time: on a slow server a cancel and the progress waited for a whole MiB. It reads what has come (read1).
This commit is contained in:
parent
1a39bd3480
commit
84d633af08
17 changed files with 484 additions and 378 deletions
|
|
@ -970,7 +970,17 @@ class CreateInstance(Kind):
|
|||
|
||||
def plan(self, user, params):
|
||||
compute = Compute.objects.get(pk=params["compute"])
|
||||
return Plan(claims=vm_claims(compute, params["name"]), resource=claims.compute_key(compute.pk),
|
||||
keys = vm_claims(compute, params["name"])
|
||||
# the volumes it is made from: not while a download writes them; a writable one
|
||||
# exclusive, as an attach holds it, a template or an image in a CD-ROM shared
|
||||
if params["template"]:
|
||||
keys[claims.volume_key(compute.pk, params["template_pool"], params["template"])] = Claim.SHARED
|
||||
for image, (device, _bus) in zip(filter(None, params["images"].split(",")), params["devices"]):
|
||||
pool, _sep, name = image.partition("/")
|
||||
key = claims.volume_key(compute.pk, pool, name)
|
||||
if keys.get(key) != Claim.EXCLUSIVE: # one given twice keeps its writable claim
|
||||
keys[key] = Claim.SHARED if device == "cdrom" else Claim.EXCLUSIVE
|
||||
return Plan(claims=keys, resource=claims.compute_key(compute.pk),
|
||||
label=f"{compute.name}/{params['name']}",
|
||||
intent={"compute": compute.pk, "uuid": str(uuid4()), "name": params["name"]})
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@ from instances.api.serializers import CreateInstanceSerializer
|
|||
from instances.models import Instance
|
||||
from instances.utils import nic_macs
|
||||
from operations.jobs import Context, Outcome, finish, get_kind
|
||||
from operations.models import Operation, acquire
|
||||
from operations.claims import admit
|
||||
from operations.models import Claim, Operation, acquire
|
||||
|
||||
|
||||
wvm_create = MagicMock() # the page and the job reach the same host
|
||||
|
|
@ -47,6 +48,25 @@ class CreateInstanceViewTests(TestCase):
|
|||
self.assertEqual(conn.create_instance.call_args.kwargs["volumes"][0]["bus"], "virtio")
|
||||
self.assertTrue(Instance.objects.filter(name="new-vm").exists())
|
||||
|
||||
@patch("instances.views.wvmCreate", new=wvm_create)
|
||||
@patch("instances.views.NewVMForm")
|
||||
def test_the_volumes_it_is_made_from_are_claimed(self, form_class):
|
||||
# not while a download writes them: an existing disk exclusive, a template shared
|
||||
self.create(form_class)
|
||||
compute = Compute.objects.get()
|
||||
self.assertIn((f"volume:{compute.pk}:pool-b/base.qcow2", Claim.EXCLUSIVE),
|
||||
set(Claim.objects.values_list("resource", "mode")))
|
||||
Operation.objects.all().delete()
|
||||
self.create(form_class, images="", template="base.qcow2", template_pool="pool-b", storage="default")
|
||||
self.assertIn((f"volume:{compute.pk}:pool-b/base.qcow2", Claim.SHARED),
|
||||
set(Claim.objects.values_list("resource", "mode")))
|
||||
Operation.objects.all().delete()
|
||||
admit({f"volume:{compute.pk}:pool-b/base.qcow2": Claim.EXCLUSIVE}, holder="other-node:1:1")
|
||||
response, _conn = self.create(form_class)
|
||||
self.assertIn("A short operation is in progress on this resource; try again in a moment.",
|
||||
[str(m) for m in get_messages(response.wsgi_request)])
|
||||
self.assertFalse(Operation.objects.exists())
|
||||
|
||||
@patch("instances.views.wvmCreate", new=wvm_create)
|
||||
@patch("instances.views.NewVMForm")
|
||||
def test_a_volume_is_taken_from_its_own_pool(self, form_class):
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ from computes.models import Compute
|
|||
from instances.models import Instance
|
||||
from operations.claims import admit
|
||||
from operations.models import Claim
|
||||
from vrtManager import util
|
||||
|
||||
PATH = "/var/lib/libvirt/images/data.qcow2"
|
||||
MAC = "52:54:00:aa:bb:cc"
|
||||
|
|
@ -95,9 +96,28 @@ class DuplicateDeviceTests(TestCase):
|
|||
[f"The VM already has a network device with MAC {MAC.upper()}"])
|
||||
self.proxy.add_network.assert_called_once()
|
||||
|
||||
def test_an_iso_a_download_writes_is_not_added_or_inserted(self):
|
||||
self.proxy.iso_location.return_value = ("isos", "/var/lib/libvirt/isos/alma.iso")
|
||||
admit({f"volume:{self.vm.compute_id}:isos/alma.iso": Claim.EXCLUSIVE}, holder="other-node:1:1")
|
||||
busy = ["A short operation is in progress on this resource; try again in a moment."]
|
||||
with patch("instances.views.cdrom_bus_choices", return_value=["sata"]):
|
||||
self.assertEqual(self.post("add_cdrom", {"bus": "sata", "media": "alma.iso"}), busy)
|
||||
self.assertEqual(self.post("mount_iso", {"mount_iso": "sda", "media": "alma.iso"})[-1:], busy)
|
||||
self.proxy.attach_disk.assert_not_called()
|
||||
self.proxy.mount_iso.assert_not_called()
|
||||
|
||||
def test_an_iso_is_read_again_in_the_pool_claimed(self):
|
||||
# another pool's image of that name (a download there) is not inserted under this pool's claim
|
||||
from vrtManager.instance import wvmInstance
|
||||
|
||||
vm = wvmInstance.__new__(wvmInstance)
|
||||
with patch.object(wvmInstance, "iso_location", return_value=("other", "/other/alma.iso")), \
|
||||
self.assertRaisesMessage(util.OperationError, "no longer in pool isos"):
|
||||
vm.iso_path_in("alma.iso", "isos")
|
||||
|
||||
def test_an_iso_in_a_cdrom_of_the_vm_is_not_added_again(self):
|
||||
iso = "/var/lib/libvirt/isos/alma.iso"
|
||||
self.proxy.get_iso_path.return_value = iso
|
||||
self.proxy.iso_location.return_value = ("isos", iso)
|
||||
with patch("instances.views.cdrom_bus_choices", return_value=["sata"]):
|
||||
form = {"bus": "sata", "media": "alma.iso"}
|
||||
self.post("add_cdrom", form)
|
||||
|
|
|
|||
|
|
@ -32,7 +32,8 @@ class NewDiskNameTestCase(TestCase):
|
|||
proxy.get_disk_devices.side_effect = lambda **kw: list((config if kw.get("config") else live)[0])
|
||||
proxy.get_media_devices.side_effect = lambda **kw: list((config if kw.get("config") else live)[1])
|
||||
proxy.get_disk_bus_types.return_value = ["virtio", "sata", "scsi", "usb"]
|
||||
proxy.get_iso_path.side_effect = lambda image: f"/iso/{image}"
|
||||
proxy.iso_location.side_effect = lambda image: ("isos", f"/iso/{image}")
|
||||
proxy.iso_path_in.side_effect = lambda image, pool: f"/iso/{image}"
|
||||
proxy.get_cache_modes.return_value = {"default": "", "none": ""}
|
||||
proxy.get_machine_type.return_value = "q35"
|
||||
proxy.get_status.return_value = status
|
||||
|
|
|
|||
|
|
@ -1848,7 +1848,7 @@ def add_cdrom(request, pk):
|
|||
if bus == "usb" and not image:
|
||||
messages.error(request, _("A USB CD-ROM needs an ISO image: libvirt has no empty USB drive"))
|
||||
return _back(request, pk, "disks")
|
||||
path = instance.proxy.get_iso_path(image) if image else ""
|
||||
pool, path = instance.proxy.iso_location(image) if image else ("", "")
|
||||
# a form sent twice (a double click) adds the drive once
|
||||
if path and path in {media["path"] for media in instance.media + instance.config_media}:
|
||||
messages.error(request, _("%(image)s is already in a CD-ROM of this VM") % {"image": image})
|
||||
|
|
@ -1858,7 +1858,10 @@ def add_cdrom(request, pk):
|
|||
instance.media + instance.config_media, instance.disks + instance.config_disks, bus
|
||||
)
|
||||
try:
|
||||
with audit_vm(request, instance, f"add CD-ROM {target}" + (f" with {image}" if image else "")):
|
||||
# the image shared: not inserted while a download writes it (Busy names the job)
|
||||
with claims.hold({claims.volume_key(instance.compute_id, pool, image): Claim.SHARED} if image else {}), \
|
||||
audit_vm(request, instance, f"add CD-ROM {target}" + (f" with {image}" if image else "")):
|
||||
path = instance.proxy.iso_path_in(image, pool) if image else "" # read again under the claim
|
||||
instance.proxy.attach_disk(
|
||||
target,
|
||||
path,
|
||||
|
|
@ -1920,8 +1923,11 @@ def mount_iso(request, pk):
|
|||
image = request.POST.get("media", "")
|
||||
dev = request.POST.get("mount_iso", "")
|
||||
try:
|
||||
with audit_vm(request, instance, f"insert media {image} into {dev}"):
|
||||
instance.proxy.mount_iso(dev, image)
|
||||
pool, _path = instance.proxy.iso_location(image)
|
||||
# the image shared: not inserted while a download writes it (Busy names the job)
|
||||
with claims.hold({claims.volume_key(instance.compute_id, pool, image): Claim.SHARED}), \
|
||||
audit_vm(request, instance, f"insert media {image} into {dev}"):
|
||||
instance.proxy.mount_iso(dev, image, pool)
|
||||
except libvirtError as err:
|
||||
messages.error(request, err)
|
||||
return redirect(same_origin_referer(request, reverse("instances:instance", args=[pk])) + "#disks")
|
||||
|
|
|
|||
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
18
operations/migrations/0006_claim_resource_text.py
Normal file
18
operations/migrations/0006_claim_resource_text.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 5.2.18 on 2026-11-20 13:45
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('operations', '0005_alert'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='claim',
|
||||
name='resource',
|
||||
field=models.TextField(db_index=True),
|
||||
),
|
||||
]
|
||||
|
|
@ -79,7 +79,7 @@ class Claim(models.Model):
|
|||
EXCLUSIVE = "exclusive"
|
||||
|
||||
operation = models.ForeignKey(Operation, null=True, on_delete=models.CASCADE, related_name="claims")
|
||||
resource = models.CharField(max_length=255, db_index=True)
|
||||
resource = models.TextField(db_index=True) # a volume's key holds its pool's and file's names
|
||||
mode = models.CharField(max_length=9, choices=[(SHARED, SHARED), (EXCLUSIVE, EXCLUSIVE)])
|
||||
holder = models.CharField(max_length=128, blank=True) # transient: host:pid:thread
|
||||
expires_at = models.DateTimeField(null=True) # transient only
|
||||
|
|
|
|||
|
|
@ -30,6 +30,13 @@ class AdmitTestCase(TestCase):
|
|||
claims.admit({"compute:1": X}, holder="c")
|
||||
self.assertEqual((busy.exception.resource, busy.exception.blocker), ("compute:1", None))
|
||||
|
||||
def test_a_long_volume_key_is_held(self):
|
||||
# a pool's and a long file name's: more than 255 characters, which PostgreSQL refused
|
||||
key = claims.volume_key(1, "default", "a" * 250 + ".iso")
|
||||
claims.admit({key: S}, holder="a")
|
||||
with self.assertRaises(claims.Busy):
|
||||
claims.admit({key: X}, holder="b")
|
||||
|
||||
def test_a_refusal_writes_nothing(self):
|
||||
claims.admit({"instance:u1": X}, holder="a")
|
||||
with self.assertRaises(claims.Busy):
|
||||
|
|
|
|||
|
|
@ -297,7 +297,8 @@ class FetchVolume(Kind):
|
|||
def chunks():
|
||||
done, checked = 0, time.monotonic()
|
||||
try:
|
||||
for data in answer.stream(2**20, decode_content=False):
|
||||
# what has come, up to 1 MiB: a slow server's bytes are not held until a whole MiB
|
||||
for data in iter(lambda: answer.read1(2**20, decode_content=False), b""):
|
||||
done += len(data)
|
||||
if done > size:
|
||||
raise util.OperationError(gettext_noop("The server sent more than the file's size"))
|
||||
|
|
|
|||
|
|
@ -83,8 +83,10 @@ class PoolInUseTests(TestCase):
|
|||
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")
|
||||
# the pool of two targets: a backup to the second one counts too
|
||||
for name in ("nfs-a", "nfs-b"):
|
||||
target = BackupTarget.objects.create(name=name)
|
||||
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())
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ def answer(chunks, size=None, status=200, headers=None):
|
|||
body.headers = {"Content-Length": str(size if size is not None else sum(map(len, chunks))), **(headers or {})}
|
||||
if size == -1:
|
||||
del body.headers["Content-Length"]
|
||||
body.stream.return_value = iter(chunks)
|
||||
body.read1.side_effect = [*chunks, b""]
|
||||
return body
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -53,11 +53,10 @@ def refuse_target_pool(compute, pool):
|
|||
|
||||
def pool_stop_claims(compute, pool):
|
||||
"""The claims that keep out a pool's jobs while it is stopped or deleted: the pool's, and its
|
||||
backup target's if it is one (backup jobs claim the target)."""
|
||||
backup targets' if it is one or more (backup jobs claim the target)."""
|
||||
keys = {claims.pool_key(compute.pk, pool): Claim.EXCLUSIVE}
|
||||
row = BackupTargetPool.objects.filter(compute=compute, pool=pool).first()
|
||||
if row:
|
||||
keys[claims.backup_target_key(row.target_id)] = Claim.EXCLUSIVE
|
||||
for target in BackupTargetPool.objects.filter(compute=compute, pool=pool).values_list("target_id", flat=True):
|
||||
keys[claims.backup_target_key(target)] = Claim.EXCLUSIVE
|
||||
return keys
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1401,21 +1401,33 @@ class wvmInstance(wvmConnect):
|
|||
raise util.OperationError(gettext_noop("Media of %(dev)s changed in the running VM only: %(err)s"), dev=dev, err=err) from err
|
||||
raise
|
||||
|
||||
def get_iso_path(self, image):
|
||||
"""The path of the ISO image of that name, in one of the active pools."""
|
||||
paths = []
|
||||
def iso_location(self, image):
|
||||
"""(pool, path) of the ISO image of that name, in one of the active pools."""
|
||||
found = []
|
||||
for storage in self.get_storages(only_actives=True):
|
||||
stg = self.get_storage(storage)
|
||||
if image in stg.listVolumes():
|
||||
paths.append(stg.storageVolLookupByName(image).path())
|
||||
if not paths:
|
||||
found.append((storage, stg.storageVolLookupByName(image).path()))
|
||||
if not found:
|
||||
raise util.OperationError(gettext_noop("ISO image %(image)s was not found"), image=image)
|
||||
if len(paths) > 1:
|
||||
if len(found) > 1:
|
||||
raise util.OperationError(gettext_noop("ISO image %(image)s is in more than one storage pool"), image=image)
|
||||
return paths[0]
|
||||
return found[0]
|
||||
|
||||
def mount_iso(self, dev, image):
|
||||
self._set_cdrom_media(dev, self.get_iso_path(image))
|
||||
def get_iso_path(self, image):
|
||||
return self.iso_location(image)[1]
|
||||
|
||||
def iso_path_in(self, image, pool):
|
||||
"""The path of the ISO image, which must still be the one of that pool (the one a caller claimed)."""
|
||||
found, path = self.iso_location(image)
|
||||
if found != pool:
|
||||
raise util.OperationError(gettext_noop("ISO image %(image)s is no longer in pool %(pool)s; choose it again"),
|
||||
image=image, pool=pool)
|
||||
return path
|
||||
|
||||
def mount_iso(self, dev, image, pool=None):
|
||||
"""Insert the ISO image; pool: the pool it must be in, when the caller claimed its volume there."""
|
||||
self._set_cdrom_media(dev, self.iso_path_in(image, pool) if pool else self.get_iso_path(image))
|
||||
|
||||
def umount_iso(self, dev, image=None):
|
||||
self._set_cdrom_media(dev, None)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue