From 56806b2f8b4c2ca1d8b3b8dbc720d877b03b1f15 Mon Sep 17 00:00:00 2001 From: catborise Date: Sun, 8 Nov 2026 14:43:33 +0300 Subject: [PATCH] refactor(vrtManager): the connection manager locks its dict with threading.RLock The 223-line read-write lock guarded only the dict of connections, a lookup of a few entries: readers never waited on a long writer, as the connection is opened outside the lock. One reentrant lock does the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kk4h2TcUiaWmU5MUszYSea --- doc/architecture.md | 1 - vrtManager/connection.py | 46 +++---- vrtManager/rwlock.py | 223 ------------------------------- vrtManager/tests/test_rwlock.py | 225 -------------------------------- 4 files changed, 15 insertions(+), 480 deletions(-) delete mode 100644 vrtManager/rwlock.py delete mode 100644 vrtManager/tests/test_rwlock.py diff --git a/doc/architecture.md b/doc/architecture.md index 41c2eab3..2240f613 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -68,7 +68,6 @@ The libvirt layer: the connections and the host objects the apps work on (the ap | `hostdetails.py` | host CPU, memory and capabilities | | `storage.py`, `network.py`, `interface.py`, `nwfilters.py`, `virtsecrets.py`, `nodedevs.py` | the host objects of the apps with the same names | | `util.py` | `OperationError` (its text translated when shown, English in logs), XML helpers | -| `rwlock.py` | the connection manager's read-write lock | ## Jobs diff --git a/vrtManager/connection.py b/vrtManager/connection.py index c4d102ad..85af8465 100644 --- a/vrtManager/connection.py +++ b/vrtManager/connection.py @@ -15,7 +15,6 @@ from django.utils.functional import cached_property from libvirt import libvirtError from lxml import etree from vrtManager import util -from vrtManager.rwlock import ReadWriteLock CONN_SOCKET = 4 CONN_TLS = 3 @@ -379,7 +378,7 @@ class wvmConnectionManager(object): # connections are shared between all threads, see: # http://wiki.libvirt.org/page/FAQ#Is_libvirt_thread_safe.3F self._connections = dict() - self._connections_lock = ReadWriteLock() + self._connections_lock = threading.RLock() # the dict only: connecting runs outside it self._inherited = [] self._host_requests = {} # host: the web requests using it, whatever the login (HOST_REQUESTS) @@ -389,7 +388,7 @@ class wvmConnectionManager(object): would call libvirt in the child.""" self._inherited.append(self._connections) self._connections = dict() - self._connections_lock = ReadWriteLock() + self._connections_lock = threading.RLock() self._host_requests = {} def _search_connection(self, host, login, passwd, conn): @@ -397,17 +396,10 @@ class wvmConnectionManager(object): search the connection dict for a connection with the given credentials if it does not exist return None """ - self._connections_lock.acquireRead() - try: - if host in self._connections: - connections = self._connections[host] - - for connection in connections: - if connection.login == login and connection.passwd == passwd and connection.type == conn: - return connection - finally: - self._connections_lock.release() - + with self._connections_lock: + for connection in self._connections.get(host, []): + if connection.login == login and connection.passwd == passwd and connection.type == conn: + return connection return None def get_connection(self, host, login, passwd, conn): @@ -421,23 +413,15 @@ class wvmConnectionManager(object): login = str(login) passwd = str(passwd) if passwd is not None else None - connection = self._search_connection(host, login, passwd, conn) - - if connection is None: - self._connections_lock.acquireWrite() - try: - # we have to search for the connection again after acquiring the write lock - # as the thread previously holding the write lock may have already added our connection - connection = self._search_connection(host, login, passwd, conn) - if connection is None: - # Only register it here: connecting under the global lock - # would make every other host wait for a slow one. - connection = wvmConnection(host, login, passwd, conn) - connection.requests = self._host_requests.setdefault( - host, threading.BoundedSemaphore(HOST_REQUESTS)) - self._connections.setdefault(host, []).append(connection) - finally: - self._connections_lock.release() + with self._connections_lock: + connection = self._search_connection(host, login, passwd, conn) + if connection is None: + # Only register it here: connecting under the global lock + # would make every other host wait for a slow one. + connection = wvmConnection(host, login, passwd, conn) + connection.requests = self._host_requests.setdefault( + host, threading.BoundedSemaphore(HOST_REQUESTS)) + self._connections.setdefault(host, []).append(connection) _count_on(connection) live = connection.alive_connection() diff --git a/vrtManager/rwlock.py b/vrtManager/rwlock.py deleted file mode 100644 index 694a6d86..00000000 --- a/vrtManager/rwlock.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: iso-8859-15 -*- -"""locks.py - Read-Write lock thread lock implementation - -See the class documentation for more info. - -Copyright (C) 2007, Heiko Wundram. -Released under the BSD-license. - -found at: http://code.activestate.com/recipes/502283-read-write-lock-class-rlock-like/ -""" - -# Imports -# ------- -from threading import Condition, Lock, current_thread -from time import time - -# Read write lock -# --------------- - - -class ReadWriteLock(object): - """Read-Write lock class. A read-write lock differs from a standard - threading.RLock() by allowing multiple threads to simultaneously hold a - read lock, while allowing only a single thread to hold a write lock at the - same point of time. - - When a read lock is requested while a write lock is held, the reader - is blocked; when a write lock is requested while another write lock is - held or there are read locks, the writer is blocked. - - Writers are always preferred by this implementation: if there are blocked - threads waiting for a write lock, current readers may request more read - locks (which they eventually should free, as they starve the waiting - writers otherwise), but a new thread requesting a read lock will not - be granted one, and block. This might mean starvation for readers if - two writer threads interweave their calls to acquireWrite() without - leaving a window only for readers. - - In case a current reader requests a write lock, this can and will be - satisfied without giving up the read locks first, but, only one thread - may perform this kind of lock upgrade, as a deadlock would otherwise - occur. After the write lock has been granted, the thread will hold a - full write lock, and not be downgraded after the upgrading call to - acquireWrite() has been match by a corresponding release(). - """ - - def __init__(self): - """Initialize this read-write lock.""" - - # Condition variable, used to signal waiters of a change in object - # state. - self.__condition = Condition(Lock()) - - # Initialize with no writers. - self.__writer = None - self.__upgradewritercount = 0 - self.__pendingwriters = [] - - # Initialize with no readers. - self.__readers = {} - - def acquireRead(self, timeout=None): - """Acquire a read lock for the current thread, waiting at most - timeout seconds or doing a non-blocking check in case timeout is <= 0. - - In case timeout is None, the call to acquireRead blocks until the - lock request can be serviced. - - In case the timeout expires before the lock could be serviced, a - RuntimeError is thrown.""" - - if timeout is not None: - endtime = time() + timeout - me = current_thread() - self.__condition.acquire() - try: - if self.__writer is me: - # If we are the writer, grant a new read lock, always. - self.__writercount += 1 - return - while True: - if self.__writer is None: - # Only test anything if there is no current writer. - if self.__upgradewritercount or self.__pendingwriters: - if me in self.__readers: - # Only grant a read lock if we already have one - # in case writers are waiting for their turn. - # This means that writers can't easily get starved - # (but see below, readers can). - self.__readers[me] += 1 - return - # No, we aren't a reader (yet), wait for our turn. - else: - # Grant a new read lock, always, in case there are - # no pending writers (and no writer). - self.__readers[me] = self.__readers.get(me, 0) + 1 - return - if timeout is not None: - remaining = endtime - time() - if remaining <= 0: - # Timeout has expired, signal caller of this. - raise RuntimeError("Acquiring read lock timed out") - self.__condition.wait(remaining) - else: - self.__condition.wait() - finally: - self.__condition.release() - - def acquireWrite(self, timeout=None): - """Acquire a write lock for the current thread, waiting at most - timeout seconds or doing a non-blocking check in case timeout is <= 0. - - In case the write lock cannot be serviced due to the deadlock - condition mentioned above, a ValueError is raised. - - In case timeout is None, the call to acquireWrite blocks until the - lock request can be serviced. - - In case the timeout expires before the lock could be serviced, a - RuntimeError is thrown.""" - - if timeout is not None: - endtime = time() + timeout - me, upgradewriter = current_thread(), False - self.__condition.acquire() - try: - if self.__writer is me: - # If we are the writer, grant a new write lock, always. - self.__writercount += 1 - return - elif me in self.__readers: - # If we are a reader, no need to add us to pendingwriters, - # we get the upgradewriter slot. - if self.__upgradewritercount: - # If we are a reader and want to upgrade, and someone - # else also wants to upgrade, there is no way we can do - # this except if one of us releases all his read locks. - # Signal this to user. - raise ValueError("Inevitable dead lock, denying write lock") - upgradewriter = True - self.__upgradewritercount = self.__readers.pop(me) - else: - # We aren't a reader, so add us to the pending writers queue - # for synchronization with the readers. - self.__pendingwriters.append(me) - while True: - if not self.__readers and self.__writer is None: - # Only test anything if there are no readers and writers. - if self.__upgradewritercount: - if upgradewriter: - # There is a writer to upgrade, and it's us. Take - # the write lock. - self.__writer = me - self.__writercount = self.__upgradewritercount + 1 - self.__upgradewritercount = 0 - return - # There is a writer to upgrade, but it's not us. - # Always leave the upgrade writer the advance slot, - # because he presumes he'll get a write lock directly - # from a previously held read lock. - elif self.__pendingwriters[0] is me: - # If there are no readers and writers, it's always - # fine for us to take the writer slot, removing us - # from the pending writers queue. - # This might mean starvation for readers, though. - self.__writer = me - self.__writercount = 1 - self.__pendingwriters = self.__pendingwriters[1:] - return - if timeout is not None: - remaining = endtime - time() - if remaining <= 0: - # Timeout has expired, signal caller of this. - if upgradewriter: - # Put us back on the reader queue. No need to - # signal anyone of this change, because no other - # writer could've taken our spot before we got - # here (because of remaining readers), as the test - # for proper conditions is at the start of the - # loop, not at the end. - self.__readers[me] = self.__upgradewritercount - self.__upgradewritercount = 0 - else: - # We were a simple pending writer, just remove us - # from the FIFO list. - self.__pendingwriters.remove(me) - raise RuntimeError("Acquiring write lock timed out") - self.__condition.wait(remaining) - else: - self.__condition.wait() - finally: - self.__condition.release() - - def release(self): - """Release the currently held lock. - - In case the current thread holds no lock, a ValueError is thrown.""" - - me = current_thread() - self.__condition.acquire() - try: - if self.__writer is me: - # We are the writer, take one nesting depth away. - self.__writercount -= 1 - if not self.__writercount: - # No more write locks; take our writer position away and - # notify waiters of the new circumstances. - self.__writer = None - self.__condition.notify_all() - elif me in self.__readers: - # We are a reader currently, take one nesting depth away. - self.__readers[me] -= 1 - if not self.__readers[me]: - # No more read locks, take our reader position away. - del self.__readers[me] - if not self.__readers: - # No more readers, notify waiters of the new - # circumstances. - self.__condition.notify_all() - else: - raise ValueError("Trying to release unheld lock") - finally: - self.__condition.release() diff --git a/vrtManager/tests/test_rwlock.py b/vrtManager/tests/test_rwlock.py deleted file mode 100644 index 1e375e0e..00000000 --- a/vrtManager/tests/test_rwlock.py +++ /dev/null @@ -1,225 +0,0 @@ -import threading -import time -import unittest -import warnings - -from vrtManager.rwlock import ReadWriteLock - - -class TestReadWriteLock(unittest.TestCase): - def setUp(self): - self.lock = ReadWriteLock() - - def another_thread_gets(self, acquire_name): - """Whether another thread can take the read or write lock within 0.2 s now.""" - got = [] - - def run(): - try: - getattr(self.lock, acquire_name)(timeout=0.2) - except RuntimeError: - got.append(False) - else: - got.append(True) - self.lock.release() - thread = threading.Thread(target=run) - thread.start() - thread.join() - return got[0] - - def test_single_thread_read_lock(self): - """A read lock lets other readers in, keeps writers out, and is released.""" - self.lock.acquireRead() - self.assertTrue(self.another_thread_gets("acquireRead")) - self.assertFalse(self.another_thread_gets("acquireWrite")) - self.lock.release() - self.assertTrue(self.another_thread_gets("acquireWrite")) - - def test_single_thread_write_lock(self): - """A write lock keeps everyone else out until it is released.""" - self.lock.acquireWrite() - self.assertFalse(self.another_thread_gets("acquireRead")) - self.lock.release() - self.assertTrue(self.another_thread_gets("acquireRead")) - - def test_nested_read_locks(self): - """Reentrant read locks are held until the last release.""" - self.lock.acquireRead() - self.lock.acquireRead() - self.lock.release() - self.assertFalse(self.another_thread_gets("acquireWrite")) - self.lock.release() - self.assertTrue(self.another_thread_gets("acquireWrite")) - - def test_nested_write_locks(self): - """Reentrant write locks are held until the last release.""" - self.lock.acquireWrite() - self.lock.acquireWrite() - self.lock.release() - self.assertFalse(self.another_thread_gets("acquireRead")) - self.lock.release() - self.assertTrue(self.another_thread_gets("acquireRead")) - - def test_release_unheld_lock_raises_value_error(self): - """Releasing a lock when none is held should raise ValueError.""" - with self.assertRaises(ValueError): - self.lock.release() - - def test_read_to_write_upgrade(self): - """A thread holding a read lock can upgrade to a write lock.""" - self.lock.acquireRead() - self.lock.acquireWrite(timeout=1.0) - self.assertFalse(self.another_thread_gets("acquireRead")) - self.lock.release() - self.lock.release() - self.assertTrue(self.another_thread_gets("acquireWrite")) - - def test_multiple_concurrent_readers(self): - """Multiple threads should be able to acquire read locks simultaneously.""" - active_readers = 0 - max_concurrent_readers = 0 - state_lock = threading.Lock() - barrier = threading.Barrier(5) - - def reader_task(): - nonlocal active_readers, max_concurrent_readers - barrier.wait() - self.lock.acquireRead(timeout=2.0) - try: - with state_lock: - active_readers += 1 - if active_readers > max_concurrent_readers: - max_concurrent_readers = active_readers - time.sleep(0.05) - finally: - with state_lock: - active_readers -= 1 - self.lock.release() - - threads = [threading.Thread(target=reader_task) for _ in range(5)] - for t in threads: - t.start() - for t in threads: - t.join() - - self.assertEqual(max_concurrent_readers, 5) - - def test_writer_excludes_readers(self): - """While a writer holds the lock, no reader should be able to acquire it.""" - reader_acquired = False - reader_timed_out = False - - self.lock.acquireWrite() - - def reader_task(): - nonlocal reader_acquired, reader_timed_out - try: - self.lock.acquireRead(timeout=0.1) - reader_acquired = True - self.lock.release() - except RuntimeError: - reader_timed_out = True - - t = threading.Thread(target=reader_task) - t.start() - t.join() - - self.lock.release() - self.assertFalse(reader_acquired) - self.assertTrue(reader_timed_out) - - def test_readers_exclude_writer(self): - """While readers hold the lock, a writer should be blocked until released.""" - writer_acquired = False - writer_timed_out = False - - self.lock.acquireRead() - - def writer_task(): - nonlocal writer_acquired, writer_timed_out - try: - self.lock.acquireWrite(timeout=0.1) - writer_acquired = True - self.lock.release() - except RuntimeError: - writer_timed_out = True - - t = threading.Thread(target=writer_task) - t.start() - t.join() - - self.lock.release() - self.assertFalse(writer_acquired) - self.assertTrue(writer_timed_out) - - def test_writer_blocks_subsequent_readers(self): - """Pending writers take priority and should block subsequent new readers.""" - order = [] - writer_ready_event = threading.Event() - - # Step 1: Initial reader holds read lock - self.lock.acquireRead() - - # Step 2: Writer attempts to acquire write lock and waits - def writer_task(): - writer_ready_event.set() - self.lock.acquireWrite(timeout=2.0) - try: - order.append("writer") - finally: - self.lock.release() - - # Step 3: New reader attempts to acquire read lock after writer is pending - def new_reader_task(): - writer_ready_event.wait() - # small delay to ensure writer is queued in pendingwriters - time.sleep(0.05) - self.lock.acquireRead(timeout=2.0) - try: - order.append("new_reader") - finally: - self.lock.release() - - w_thread = threading.Thread(target=writer_task) - r_thread = threading.Thread(target=new_reader_task) - - w_thread.start() - r_thread.start() - - writer_ready_event.wait() - time.sleep(0.1) - - # Release initial reader: writer should acquire and complete before new reader - self.lock.release() - - w_thread.join() - r_thread.join() - - self.assertEqual(order, ["writer", "new_reader"]) - - def test_no_deprecation_warnings(self): - """Verify that lock operations do not emit DeprecationWarnings (e.g. currentThread, notifyAll).""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.simplefilter("always", DeprecationWarning) - lock = ReadWriteLock() - lock.acquireRead() - lock.release() - lock.acquireWrite() - lock.release() - - # Check for currentThread or notifyAll warnings - deprecations = [ - str(w.message) - for w in caught_warnings - if issubclass(w.category, DeprecationWarning) - and ("currentThread" in str(w.message) or "notifyAll" in str(w.message)) - ] - self.assertEqual( - deprecations, - [], - f"Found deprecation warnings: {deprecations}", - ) - - -if __name__ == "__main__": - unittest.main()