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
60 changes: 35 additions & 25 deletions src/borg/fslocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from . import platform
from .helpers import Error, ErrorWithTraceback
from .logger import create_logger
from .platform import SaveFile

ADD, REMOVE, REMOVE2 = "add", "remove", "remove2"
SHARED, EXCLUSIVE = "shared", "exclusive"
Expand Down Expand Up @@ -306,30 +307,37 @@ def load(self):
try:
with self.path.open() as f:
data = json.load(f)

# Just nuke the stale locks early on load
if self.kill_stale_locks:
for key in (SHARED, EXCLUSIVE):
try:
entries = data[key]
except KeyError:
continue
elements = set()
for host, pid, thread in entries:
if platform.process_alive(host, pid, thread):
elements.add((host, pid, thread))
else:
logger.warning(
"Removed stale %s roster lock for host %s pid %d thread %d.", key, host, pid, thread
)
data[key] = list(elements)
except (FileNotFoundError, ValueError):
# no or corrupt/empty roster file?
data = {}
except FileNotFoundError:
return {}
except ValueError as err:
# A corrupt or empty roster must not be treated as "no lockers", as that would
# allow an exclusive lock to be granted while readers are still active.
raise LockFailed(
str(self.path),
f"corrupt lock roster ({err}); if no borg process is using this borg 1.x repository, "
f"remove it or run 'borg break-lock' with borg 1.x",
) from None

# Just nuke the stale locks early on load
if self.kill_stale_locks:
for key in (SHARED, EXCLUSIVE):
try:
entries = data[key]
except KeyError:
continue
elements = set()
for host, pid, thread in entries:
if platform.process_alive(host, pid, thread):
elements.add((host, pid, thread))
else:
logger.warning(
"Removed stale %s roster lock for host %s pid %d thread %d.", key, host, pid, thread
)
data[key] = list(elements)
return data

def save(self, data):
with self.path.open("w") as f:
with SaveFile(self.path) as f:
json.dump(data, f)

def remove(self):
Expand Down Expand Up @@ -461,10 +469,12 @@ def _wait_for_readers_finishing(self, remove, sleep):

def release(self):
if self.is_exclusive:
self._roster.modify(EXCLUSIVE, REMOVE)
if self._roster.empty(EXCLUSIVE, SHARED):
self._roster.remove()
self._lock.release()
try:
self._roster.modify(EXCLUSIVE, REMOVE)
if self._roster.empty(EXCLUSIVE, SHARED):
self._roster.remove()
finally:
self._lock.release()
else:
with self._lock:
self._roster.modify(SHARED, REMOVE)
Expand Down
57 changes: 57 additions & 0 deletions src/borg/testsuite/fslocking_test.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import json
import os
import random
import stat
import time
from pathlib import Path
from threading import Thread, Lock as ThreadingLock
from traceback import format_exc
from types import SimpleNamespace

import pytest

Expand All @@ -16,6 +20,7 @@
REMOVE,
SHARED,
EXCLUSIVE,
LockFailed,
LockTimeout,
NotLocked,
NotMyLock,
Expand Down Expand Up @@ -306,6 +311,13 @@ def test_migrate_lock(self, lockpath):
assert lock.id == new_id
lock.release()

def test_release_exclusive_releases_underlying_lock_on_corrupt_roster(self, lockpath):
lock = Lock(lockpath, exclusive=True, id=ID1).acquire()
lock._roster.path.write_text("{corrupt")
with pytest.raises(LockFailed):
lock.release()
assert not lock._lock.is_locked()


@pytest.fixture()
def rosterpath(tmpdir):
Expand Down Expand Up @@ -373,3 +385,48 @@ def test_migrate_lock(self, rosterpath):
roster.migrate_lock(SHARED, old_id, new_id) # fix the lock
assert roster.id == new_id
assert roster.get(SHARED) == {new_id}

def test_corrupt_roster_raises(self, rosterpath):
rosterpath.write_text('{"shared": [["host", 1, 0]') # truncated JSON
roster = LockRoster(rosterpath)
with pytest.raises(LockFailed):
roster.load()

def test_empty_zero_byte_roster_raises(self, rosterpath):
rosterpath.write_text("") # 0-byte truncated file from crash
roster = LockRoster(rosterpath)
with pytest.raises(LockFailed):
roster.load()

def test_save_keeps_old_roster_on_write_error(self, rosterpath, monkeypatch):
roster = LockRoster(rosterpath, id=ID1)
roster.modify(SHARED, ADD)

def failing_dump(data, f):
f.write('{"shared": [') # partial write
raise OSError("simulated disk full")

monkeypatch.setattr("borg.fslocking.json", SimpleNamespace(load=json.load, dump=failing_dump))
with pytest.raises(OSError):
roster.save({"shared": []})
assert roster.get(SHARED) == {ID1} # old roster still intact
assert [p.name for p in rosterpath.parent.iterdir()] == [rosterpath.name] # no temp file left behind

@pytest.mark.skipif("BORG_TESTS_IGNORE_MODES" in os.environ, reason="modes ignored")
@pytest.mark.skipif(is_win32, reason="POSIX umask/permissions only")
def test_save_respects_umask(self, rosterpath):
old_umask = os.umask(0o002)
try:
roster = LockRoster(rosterpath, id=ID1)
roster.modify(SHARED, ADD)
finally:
os.umask(old_umask)
mode = stat.S_IMODE(rosterpath.stat().st_mode)
assert mode == 0o664

def test_release_exclusive_releases_underlying_lock_on_corrupt_roster(self, lockpath):
lock = Lock(lockpath, exclusive=True, id=ID1).acquire()
lock._roster.path.write_text("{corrupt")
with pytest.raises(LockFailed):
lock.release()
assert not lock._lock.is_locked()