Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ Compute
Storage
~~~~~~~

- [Local] Serialize uploads to the same object across threads by sharing the
thread lock between lock instances and releasing it after the IPC lock.
(GITHUB-2250)
[Khushal Dangar - @khushalx]

- [Local Storage] Delete the partially written file when ``download_object_range``
fails and ``delete_on_failure`` is set.
(GITHUB-2223)
Expand Down
39 changes: 22 additions & 17 deletions libcloud/storage/drivers/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
"""

import os
import time
import errno
import shutil
import weakref
import tempfile
import threading
from hashlib import sha256
Expand Down Expand Up @@ -48,6 +48,18 @@


IGNORE_FOLDERS = [".lock", ".hash"]
_THREAD_LOCKS = weakref.WeakValueDictionary()
_THREAD_LOCKS_LOCK = threading.Lock()


def _reset_thread_locks() -> None:
global _THREAD_LOCKS_LOCK
_THREAD_LOCKS.clear()
_THREAD_LOCKS_LOCK = threading.Lock()


if hasattr(os, "register_at_fork"):
os.register_at_fork(after_in_child=_reset_thread_locks)


class NoOpLockLocalStorage:
Expand Down Expand Up @@ -80,21 +92,13 @@ def __init__(self, path, timeout=5):
# NOTE: fasteners.InterProcess lock has no guarantees regards usage by
# multiple threads in a single process which means we also need to
# use threading.lock for that purpose
self.thread_lock = threading.Lock()
with _THREAD_LOCKS_LOCK:
self.thread_lock = _THREAD_LOCKS.setdefault(path, threading.Lock())
self.ipc_lock = fasteners.InterProcessLock(self.ipc_lock_path)

def __enter__(self):
lock_acquire_timeout = self.lock_acquire_timeout
start_time = int(time.time())
end_time = start_time + lock_acquire_timeout

while int(time.time()) < end_time:
# pylint: disable=assignment-from-no-return
success = self.thread_lock.acquire(blocking=False)
# enable: disable=assignment-from-no-return

if success:
break
success = self.thread_lock.acquire(timeout=lock_acquire_timeout)

if not success:
raise LibcloudError(
Expand All @@ -115,11 +119,12 @@ def __enter__(self):
raise

def __exit__(self, type, value, traceback):
if self.thread_lock.locked():
self.thread_lock.release()

if self.ipc_lock.exists():
self.ipc_lock.release()
try:
if self.ipc_lock.exists():
self.ipc_lock.release()
finally:
if self.thread_lock.locked():
self.thread_lock.release()

if value is not None:
raise value
Expand Down
65 changes: 65 additions & 0 deletions libcloud/test/storage/test_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import platform
import tempfile
import unittest
import threading
import multiprocessing
from unittest import mock

Expand Down Expand Up @@ -66,6 +67,15 @@ def __call__(self, pid, success):
raise ValueError("Invalid pid")


class PickleableAcquireLockAfterFork:
def __call__(self, path, result):
try:
with LockLocalStorage(path, timeout=0.1):
result.value = 1
except LibcloudError as exc:
result.value = 2 if "Failed to acquire IPC lock" in str(exc) else 3


class LocalTests(unittest.TestCase):
driver_type = LocalStorageDriver

Expand Down Expand Up @@ -140,6 +150,61 @@ def test_lock_local_storage(self):
self.assertEqual(bool(success_1.value), True, "Check didn't pass")
self.assertEqual(bool(success_2.value), True, "Second check didn't pass")

@unittest.skipIf(platform.system().lower() == "windows", "Unsupported on Windows")
def test_lock_local_storage_serializes_separate_instances(self):
path = os.path.join(self.key, "shared-object")
first_lock = LockLocalStorage(path)
second_lock = LockLocalStorage(path, timeout=0.1)
result = []

def acquire_second_lock():
try:
with second_lock:
result.append("acquired")
except LibcloudError as exc:
result.append(str(exc))

with first_lock:
with LockLocalStorage(os.path.join(self.key, "other-object")):
pass
worker = threading.Thread(target=acquire_second_lock)
worker.start()
worker.join(timeout=3)
self.assertFalse(worker.is_alive())
self.assertEqual(len(result), 1)
self.assertIn("Failed to acquire thread lock", result[0])

with second_lock:
self.assertTrue(second_lock.thread_lock.locked())

@unittest.skipUnless("fork" in multiprocessing.get_all_start_methods(), "Requires fork")
def test_lock_local_storage_after_fork(self):
context = multiprocessing.get_context("fork")
result = context.Value("i", 0)
path = os.path.join(self.key, "forked-object")
with LockLocalStorage(path):
worker = context.Process(target=PickleableAcquireLockAfterFork(), args=(path, result))
worker.start()
worker.join(timeout=3)
if worker.is_alive():
worker.terminate()
worker.join()
self.fail("Forked child did not finish acquiring the lock")
self.assertEqual(worker.exitcode, 0)
self.assertEqual(result.value, 2)

def test_lock_local_storage_keeps_thread_lock_until_ipc_release(self):
lock = LockLocalStorage(os.path.join(self.key, "release-order"))

def release_ipc_lock():
self.assertTrue(lock.thread_lock.locked())

with mock.patch.object(lock.ipc_lock, "release", side_effect=release_ipc_lock):
with lock:
pass
lock.ipc_lock.release()
self.assertFalse(lock.thread_lock.locked())

def test_lock_local_storage_releases_thread_lock_on_ipc_failure(self):
for error in (None, OSError("lock unavailable"), KeyboardInterrupt()):
with self.subTest(error=error):
Expand Down