loop: support for locking via flock

Add support for locking the loopback block device via `flock(2)`.
The main use case for this is to prevent systemd-udevd from
proben the device while any modification is done to it. See the
systemd page, https://www.freedesktop.org/software/systemd, for
more details.
Add the corresponding tests to it.
This commit is contained in:
Christian Kellner 2021-08-11 19:22:28 +02:00 committed by Tom Gundersen
parent d8e48c0511
commit 2af964a1d5
2 changed files with 91 additions and 2 deletions

View file

@ -3,6 +3,7 @@
#
import contextlib
import fcntl
import os
import time
import threading
@ -158,3 +159,44 @@ def test_clear_fd_wait(tempdir):
f.close()
ctl.close()
@pytest.mark.skipif(not TestBase.can_bind_mount(), reason="root only")
def test_lock(tempdir):
path = os.path.join(tempdir, "test.img")
ctl = loop.LoopControl()
assert ctl
lo, lo2, f = None, None, None
try:
f = open(path, "wb+")
f.truncate(1024)
f.flush()
lo = ctl.loop_for_fd(f.fileno(), autoclear=True, lock=True)
assert lo
lo2 = loop.Loop(lo.minor)
assert lo2
with pytest.raises(BlockingIOError):
lo2.flock(fcntl.LOCK_EX | fcntl.LOCK_NB)
lo.close()
lo = None
# after lo is closed, the lock should be release and
# we should be able to obtain the lock
lo2.flock(fcntl.LOCK_EX | fcntl.LOCK_NB)
lo2.clear_fd()
finally:
if lo2:
lo2.close()
if lo:
lo.close()
if f:
f.close()
ctl.close()