From 7c7ab03e2d984d68b0d3330bb698242e16f18a30 Mon Sep 17 00:00:00 2001 From: Tim Burke Date: Tue, 23 Jul 2024 10:48:33 -0700 Subject: [PATCH] Implement context manager protocol for logging mutexes Newer versions of python expect to be able to say `with self.lock:` down in logging. See https://github.com/python/cpython/commit/74723e11 Change-Id: I30305566d12a1b8be4c8bde4b416b798322a1385 --- swift/common/utils/logs.py | 13 +++++++++++++ test/unit/common/test_utils.py | 27 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/swift/common/utils/logs.py b/swift/common/utils/logs.py index 54780f10df..fb5bb5e092 100644 --- a/swift/common/utils/logs.py +++ b/swift/common/utils/logs.py @@ -187,6 +187,13 @@ class PipeMutex(object): # do, so nobody does it and that's okay. self.close() + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *args): + self.release() + class NoopMutex(object): """ @@ -219,6 +226,12 @@ class NoopMutex(object): def release(self): pass + def __enter__(self): + return self + + def __exit__(self, *args): + pass + class ThreadSafeSysLogHandler(SysLogHandler): def createLock(self): diff --git a/test/unit/common/test_utils.py b/test/unit/common/test_utils.py index 492e15c7ea..29dd805bcd 100644 --- a/test/unit/common/test_utils.py +++ b/test/unit/common/test_utils.py @@ -5733,6 +5733,15 @@ class TestPipeMutex(unittest.TestCase): self.mutex.release() self.assertTrue(eventlet.spawn(try_acquire_lock).wait()) + def test_context_manager_api(self): + def try_acquire_lock(): + return self.mutex.acquire(blocking=False) + + with self.mutex as ref: + self.assertIs(ref, self.mutex) + self.assertFalse(eventlet.spawn(try_acquire_lock).wait()) + self.assertTrue(eventlet.spawn(try_acquire_lock).wait()) + def test_release_without_acquire(self): self.assertRaises(RuntimeError, self.mutex.release) @@ -5867,6 +5876,24 @@ class TestPipeMutex(unittest.TestCase): eventlet.debug.hub_prevent_multiple_readers(True) +class TestNoopMutex(unittest.TestCase): + def setUp(self): + self.mutex = utils.NoopMutex() + + def test_acquire_release_api(self): + # Prior to 3.13, logging called these explicitly + self.mutex.acquire() + self.mutex.release() + + def test_context_manager_api(self): + # python 3.13 started using it as a context manager + def try_acquire_lock(): + return self.mutex.acquire(blocking=False) + + with self.mutex as ref: + self.assertIs(ref, self.mutex) + + class TestDistributeEvenly(unittest.TestCase): def test_evenly_divided(self): out = utils.distribute_evenly(range(12), 3)