From 5ab36448335859fb1d78a9f3ef50172e8cb63e9c Mon Sep 17 00:00:00 2001 From: catborise Date: Mon, 9 Nov 2026 23:04:46 +0300 Subject: [PATCH] fix(instances): a disk move or migration leaves one check on a stuck host Whether a moved disk's old file is used elsewhere is asked of every compute in a thread the job waits on for at most 60 s. A host that did not answer kept that thread, and each later disk move or migration left one more. As the VM delete's check does, a compute that does not answer is not asked again: the file counts as used, so it is kept. Both checks marked a compute as not answering from the moment they asked it. A check beside another one (two jobs at once) took a healthy compute that the other was asking for a stuck one, and refused at once; and two overlapping checks could both ask a stuck one, the first to end clearing the mark of the other. Each call to a compute now records when it started, and a compute counts as not answering only while a call to it has run for 60 s, checked again just before each compute is asked. And a VM delete's check whose thread had not yet reached the first compute when the 60 s ran out found no failure and no compute it was at, and answered that no file was used: the disks could have been deleted unchecked. It now counts as not answered. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kk4h2TcUiaWmU5MUszYSea --- instances/tests/test_destroy.py | 24 +++++++++- instances/tests/test_disk_move_job.py | 24 ++++++++++ instances/utils.py | 68 ++++++++++++++++++++------- 3 files changed, 97 insertions(+), 19 deletions(-) diff --git a/instances/tests/test_destroy.py b/instances/tests/test_destroy.py index 17eb4f93..9b91f5c0 100644 --- a/instances/tests/test_destroy.py +++ b/instances/tests/test_destroy.py @@ -301,6 +301,24 @@ class OtherComputesTestCase(TestCase): # users who do not see hosts get neither the host nor libvirt's text self.assertEqual(public_error_text(caught.exception), "The host of this virtual machine cannot be reached right now.") + def test_a_check_whose_thread_starts_late_is_an_error_not_an_empty_answer(self): + from types import SimpleNamespace + + late = [] + + class LateThread(threading.Thread): # scheduled only after the caller gave up + def run(self): + late.append(self) + time.sleep(0.3) + super().run() + hosts = self.hosts({"192.0.2.61": {"/nfs/a.qcow2"}}) + with patch("instances.utils.wvmConnect", side_effect=lambda host, *args: hosts[host]), \ + patch("instances.utils.USED_CHECK_WAIT", 0.1), \ + patch.object(utils, "threading", SimpleNamespace(Thread=LateThread)): + with self.assertRaises(ConnectionFailed): + paths_used_on_other_computes(self.source, ["/nfs/a.qcow2"]) + late[0].join(5) # its calls end within this test + def test_a_host_that_does_not_answer_is_an_error_in_bounded_time(self): # connected, but stuck (a hung NFS mount): the delete job must not wait for it for good hosts = self.hosts({"192.0.2.61": set(), "192.0.2.62": set()}) @@ -315,7 +333,9 @@ class OtherComputesTestCase(TestCase): self.assertLess(time.monotonic() - started, 2) self.assertEqual(caught.exception.args[0], "The disk files cannot be checked on host-c: it did not answer within 0.2 seconds") # a retry while the host still has not answered does not ask it again - with patch("instances.utils.wvmConnect", side_effect=lambda host, *args: hosts[host]): + time.sleep(0.25) # the call, started after the caller's wait began, is 0.2 s old + with patch("instances.utils.wvmConnect", side_effect=lambda host, *args: hosts[host]), \ + patch("instances.utils.USED_CHECK_WAIT", 0.2): with self.assertRaises(ConnectionFailed): paths_used_on_other_computes(self.source, ["/nfs/a.qcow2"]) self.assertEqual(hosts["192.0.2.62"].paths_in_use.call_count, 1) @@ -323,7 +343,7 @@ class OtherComputesTestCase(TestCase): hosts["192.0.2.62"].paths_in_use.side_effect = None hosts["192.0.2.62"].paths_in_use.return_value = set() deadline = time.monotonic() + 2 - while utils._UNANSWERED and time.monotonic() < deadline: + while utils._ASKING and time.monotonic() < deadline: time.sleep(0.01) with patch("instances.utils.wvmConnect", side_effect=lambda host, *args: hosts[host]): self.assertEqual(paths_used_on_other_computes(self.source, ["/nfs/a.qcow2"]), set()) diff --git a/instances/tests/test_disk_move_job.py b/instances/tests/test_disk_move_job.py index ced10689..61d739c9 100644 --- a/instances/tests/test_disk_move_job.py +++ b/instances/tests/test_disk_move_job.py @@ -144,4 +144,28 @@ class UsedAnywhereTestCase(TransactionTestCase): hosts.return_value.paths_in_use.side_effect = lambda: stuck.wait(10) and set() started = time.monotonic() self.assertTrue(utils.used_anywhere(OLD)) + # the next job does not leave one more check waiting on it + time.sleep(0.25) # the call, started after the caller's wait began, is 0.2 s old + self.assertTrue(utils.used_anywhere(OLD)) + self.assertEqual(hosts.return_value.paths_in_use.call_count, 1) self.assertLess(time.monotonic() - started, 2) + stuck.set() + deadline = time.monotonic() + 2 + while utils._ASKING and time.monotonic() < deadline: + time.sleep(0.01) + self.assertFalse(utils._ASKING) + + def test_a_check_beside_another_one_still_asks_a_host_that_answers(self): + from instances import utils + + Compute.objects.create(name="slow", hostname="192.0.2.63", login="root", password="", type=1) + answers = [] + with patch("instances.utils.wvmConnect") as hosts, patch.object(utils, "USED_CHECK_WAIT", 2): + hosts.return_value.paths_in_use.side_effect = lambda: time.sleep(0.2) or set() + checks = [threading.Thread(target=lambda: answers.append(utils.used_anywhere(OLD))) for _ in range(2)] + for check in checks: + check.start() + for check in checks: + check.join(5) + self.assertEqual(hosts.return_value.paths_in_use.call_count, 2) + self.assertEqual(answers, [False, False]) # not "in use" because the other check was asking diff --git a/instances/utils.py b/instances/utils.py index 0fb078ba..8c9588df 100644 --- a/instances/utils.py +++ b/instances/utils.py @@ -3,7 +3,9 @@ import random import re import string import threading +import time from collections import namedtuple +from contextlib import contextmanager from accounts.models import UserInstance, UserAttributes from appsettings.settings import app_settings @@ -50,9 +52,32 @@ def get_clone_free_names(size=10): return free_names -# the computes an earlier check still waits for: a new check does not ask them again, so -# retried deletes do not pile up calls to a host that does not answer -_UNANSWERED = set() +# when each call to a compute that has not returned started (time.monotonic()). A compute +# with one older than USED_CHECK_WAIT does not answer: a new check does not ask it, so +# retried deletes do not pile up calls to it; a check beside another one still asks. +_ASKING = {} +_ASKING_LOCK = threading.Lock() + + +@contextmanager +def _asking(compute): + started = time.monotonic() + with _ASKING_LOCK: + _ASKING.setdefault(compute.pk, []).append(started) + try: + yield + finally: + with _ASKING_LOCK: + _ASKING[compute.pk].remove(started) + if not _ASKING[compute.pk]: + del _ASKING[compute.pk] + + +def _unanswered(computes): + """The first of computes that a call has waited on for USED_CHECK_WAIT, or None.""" + now = time.monotonic() + with _ASKING_LOCK: + return next((c for c in computes if any(now - t >= USED_CHECK_WAIT for t in _ASKING.get(c.pk, ()))), None) @other_hosts() @@ -65,20 +90,24 @@ def paths_used_on_other_computes(compute, own): only that a host cannot be reached.""" host = wvmConnect(compute.hostname, compute.login, compute.password, compute.type).host_uuid() others = list(Compute.objects.exclude(pk=compute.pk)) - if waiting := [other.name for other in others if other.pk in _UNANSWERED]: + if waiting := _unanswered(others): raise ConnectionFailed(gettext_noop("The disk files cannot be checked on %(host)s: it did not answer within " - "%(seconds)s seconds"), host=waiting[0], seconds=USED_CHECK_WAIT) - used, failure, asking = set(), [], [] + "%(seconds)s seconds"), host=waiting.name, seconds=USED_CHECK_WAIT) + # the compute the check is at: the first one until the thread starts, so that a thread + # started late still counts as one that did not answer + used, failure, asking = set(), [], [other.name for other in others[:1]] def check(): for other in others: asking[:] = [other.name] - _UNANSWERED.add(other.pk) + if _unanswered([other]): # it stopped answering another check meanwhile + return try: - conn = wvmConnect(other.hostname, other.login, other.password, other.type) - if host and conn.host_uuid() == host: - continue # the VM's own host under another record: its VM is the one going - used.update(conn.paths_in_use(own=own)) + with _asking(other): + conn = wvmConnect(other.hostname, other.login, other.password, other.type) + if host and conn.host_uuid() == host: + continue # the VM's own host under another record: its VM is the one going + used.update(conn.paths_in_use(own=own)) except libvirtError as err: failure.append(ConnectionFailed(gettext_noop("The disk files cannot be checked on %(host)s: %(err)s"), host=other.name, err=err)) @@ -86,8 +115,6 @@ def paths_used_on_other_computes(compute, own): except Exception as err: # raised in the caller's thread, as before failure.append(err) return - finally: - _UNANSWERED.discard(other.pk) asking.clear() thread = threading.Thread(target=check, daemon=True) @@ -110,16 +137,23 @@ def used_anywhere(path, skip=None): shared storage holds it for every host that mounts it; a compute that cannot be read might, and so might one that does not answer within USED_CHECK_WAIT: libvirt has no call timeout, and a stuck host would - hold the job for as long as it is stuck. skip: a compute not asked.""" + hold the job for as long as it is stuck. A compute an earlier check still + has waited on for that long is not asked again (_ASKING). skip: a compute not asked.""" computes = list(Compute.objects.exclude(pk=skip)) + if _unanswered(computes): + return True answer = [] def check(): for c in computes: + if _unanswered([c]): # it stopped answering another check meanwhile + answer.append(True) + return try: - if path in wvmConnect(c.hostname, c.login, c.password, c.type).paths_in_use(): - answer.append(True) - return + with _asking(c): + if path in wvmConnect(c.hostname, c.login, c.password, c.type).paths_in_use(): + answer.append(True) + return except libvirtError: answer.append(True) return