test_lock.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from twisted.internet import defer, reactor
  15. from twisted.internet.base import ReactorBase
  16. from twisted.internet.defer import Deferred
  17. from twisted.test.proto_helpers import MemoryReactor
  18. from synapse.server import HomeServer
  19. from synapse.storage.databases.main.lock import _LOCK_TIMEOUT_MS
  20. from synapse.util import Clock
  21. from tests import unittest
  22. class LockTestCase(unittest.HomeserverTestCase):
  23. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  24. self.store = hs.get_datastores().main
  25. def test_acquire_contention(self) -> None:
  26. # Track the number of tasks holding the lock.
  27. # Should be at most 1.
  28. in_lock = 0
  29. max_in_lock = 0
  30. release_lock: "Deferred[None]" = Deferred()
  31. async def task() -> None:
  32. nonlocal in_lock
  33. nonlocal max_in_lock
  34. lock = await self.store.try_acquire_lock("name", "key")
  35. if not lock:
  36. return
  37. async with lock:
  38. in_lock += 1
  39. max_in_lock = max(max_in_lock, in_lock)
  40. # Block to allow other tasks to attempt to take the lock.
  41. await release_lock
  42. in_lock -= 1
  43. # Start 3 tasks.
  44. task1 = defer.ensureDeferred(task())
  45. task2 = defer.ensureDeferred(task())
  46. task3 = defer.ensureDeferred(task())
  47. # Give the reactor a kick so that the database transaction returns.
  48. self.pump()
  49. release_lock.callback(None)
  50. # Run the tasks to completion.
  51. # To work around `Linearizer`s using a different reactor to sleep when
  52. # contended (#12841), we call `runUntilCurrent` on
  53. # `twisted.internet.reactor`, which is a different reactor to that used
  54. # by the homeserver.
  55. assert isinstance(reactor, ReactorBase)
  56. self.get_success(task1)
  57. reactor.runUntilCurrent()
  58. self.get_success(task2)
  59. reactor.runUntilCurrent()
  60. self.get_success(task3)
  61. # At most one task should have held the lock at a time.
  62. self.assertEqual(max_in_lock, 1)
  63. def test_simple_lock(self) -> None:
  64. """Test that we can take out a lock and that while we hold it nobody
  65. else can take it out.
  66. """
  67. # First to acquire this lock, so it should complete
  68. lock = self.get_success(self.store.try_acquire_lock("name", "key"))
  69. assert lock is not None
  70. # Enter the context manager
  71. self.get_success(lock.__aenter__())
  72. # Attempting to acquire the lock again fails.
  73. lock2 = self.get_success(self.store.try_acquire_lock("name", "key"))
  74. self.assertIsNone(lock2)
  75. # Calling `is_still_valid` reports true.
  76. self.assertTrue(self.get_success(lock.is_still_valid()))
  77. # Drop the lock
  78. self.get_success(lock.__aexit__(None, None, None))
  79. # We can now acquire the lock again.
  80. lock3 = self.get_success(self.store.try_acquire_lock("name", "key"))
  81. assert lock3 is not None
  82. self.get_success(lock3.__aenter__())
  83. self.get_success(lock3.__aexit__(None, None, None))
  84. def test_maintain_lock(self) -> None:
  85. """Test that we don't time out locks while they're still active"""
  86. lock = self.get_success(self.store.try_acquire_lock("name", "key"))
  87. assert lock is not None
  88. self.get_success(lock.__aenter__())
  89. # Wait for ages with the lock, we should not be able to get the lock.
  90. self.reactor.advance(5 * _LOCK_TIMEOUT_MS / 1000)
  91. lock2 = self.get_success(self.store.try_acquire_lock("name", "key"))
  92. self.assertIsNone(lock2)
  93. self.get_success(lock.__aexit__(None, None, None))
  94. def test_timeout_lock(self) -> None:
  95. """Test that we time out locks if they're not updated for ages"""
  96. lock = self.get_success(self.store.try_acquire_lock("name", "key"))
  97. assert lock is not None
  98. self.get_success(lock.__aenter__())
  99. # We simulate the process getting stuck by cancelling the looping call
  100. # that keeps the lock active.
  101. lock._looping_call.stop()
  102. # Wait for the lock to timeout.
  103. self.reactor.advance(2 * _LOCK_TIMEOUT_MS / 1000)
  104. lock2 = self.get_success(self.store.try_acquire_lock("name", "key"))
  105. self.assertIsNotNone(lock2)
  106. self.assertFalse(self.get_success(lock.is_still_valid()))
  107. def test_drop(self) -> None:
  108. """Test that dropping the context manager means we stop renewing the lock"""
  109. lock = self.get_success(self.store.try_acquire_lock("name", "key"))
  110. self.assertIsNotNone(lock)
  111. del lock
  112. # Wait for the lock to timeout.
  113. self.reactor.advance(2 * _LOCK_TIMEOUT_MS / 1000)
  114. lock2 = self.get_success(self.store.try_acquire_lock("name", "key"))
  115. self.assertIsNotNone(lock2)
  116. def test_shutdown(self) -> None:
  117. """Test that shutting down Synapse releases the locks"""
  118. # Acquire two locks
  119. lock = self.get_success(self.store.try_acquire_lock("name", "key1"))
  120. self.assertIsNotNone(lock)
  121. lock2 = self.get_success(self.store.try_acquire_lock("name", "key2"))
  122. self.assertIsNotNone(lock2)
  123. # Now call the shutdown code
  124. self.get_success(self.store._on_shutdown())
  125. self.assertEqual(self.store._live_tokens, {})