Skip to content
Merged
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
53 changes: 38 additions & 15 deletions app/nullius/ondisk.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@
from __future__ import annotations

import contextlib
import errno
import hashlib
import os
import stat
import uuid

# a handle that searches a folder without reading it: a folder its writer cannot list (0300) is written all the same
_SEARCH = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) or os.O_RDONLY


def write_whole(path, data, mode=None) -> None:
"""``data`` as the whole of ``path``, or ``path`` left as it was: text, bytes, or a
Expand All @@ -16,22 +20,41 @@ def write_whole(path, data, mode=None) -> None:
of two writers at once, each writes a complete file and the last rename wins.
``mode`` holds from the first byte. The folder is the caller's to make."""
path = os.fspath(path)
part = os.path.join(os.path.dirname(path), f".{uuid.uuid4().hex}.part") # the folder as the system resolves it
fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode)
here, name = os.path.dirname(path), f".{uuid.uuid4().hex}.part"
flags, perm = os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode
try: # the folder as the system resolves it, held: a failure removes the file there, moved or not
folder = os.open(here or ".", _SEARCH | os.O_DIRECTORY)
except OSError:
folder = None # no handle on it (no descriptor left, say): by its name
try:
text = isinstance(data, str) or callable(data)
with (os.fdopen(fd, "w", encoding="utf-8") if text else os.fdopen(fd, "wb")) as f:
if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode:
os.fchmod(fd, mode) # the umask took bits off
if callable(data):
data(f)
else:
f.write(data)
os.replace(part, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(part)
raise
if folder is not None:
try:
fd = os.open(name, flags, perm, dir_fd=folder)
except OSError as e:
if e.errno not in (errno.EMFILE, errno.ENFILE):
raise
held, folder = folder, None # the folder took the last descriptor: by its name
os.close(held)
if folder is None:
fd = os.open(os.path.join(here, name), flags, perm)
part = name if folder is not None else os.path.join(here, name)
try:
text = isinstance(data, str) or callable(data)
with (os.fdopen(fd, "w", encoding="utf-8") if text else os.fdopen(fd, "wb")) as f:
if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode:
os.fchmod(fd, mode) # the umask took bits off
if callable(data):
data(f)
else:
f.write(data)
os.replace(os.path.join(here, name), path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(part, dir_fd=folder)
raise
finally:
if folder is not None:
os.close(folder)


@contextlib.contextmanager
Expand Down
63 changes: 63 additions & 0 deletions app/tests/test_ondisk.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import textwrap
import threading
import unittest
from unittest import mock
Expand Down Expand Up @@ -108,6 +111,66 @@ def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self
self.assertEqual(f.read(), "kept")
self.assertEqual(self.left(), ["file.json"])

def test_a_write_whose_folder_is_renamed_leaves_nothing_in_it(self):
folder, moved, rename = os.path.join(self.tmp, "c"), os.path.join(self.tmp, "moved"), os.replace
os.mkdir(folder)
def renamed_first(src, dst):
rename(folder, moved) # another process, just before this write's rename
return rename(src, dst)
with mock.patch.object(os, "replace", renamed_first), self.assertRaises(FileNotFoundError):
ondisk.write_whole(os.path.join(folder, "file.json"), "x")
self.assertEqual((self.left(), os.listdir(moved)), (["moved"], []))

@unittest.skipIf(os.geteuid() == 0, "root lists any folder")
def test_a_folder_its_writer_cannot_list_is_written_all_the_same(self):
os.chmod(self.tmp, 0o300) # write and search, no read
self.addCleanup(os.chmod, self.tmp, 0o700)
ondisk.write_whole(self.path, "x", mode=0o600)
os.chmod(self.tmp, 0o700)
with open(self.path) as f:
self.assertEqual((f.read(), self.mode(), self.left()), ("x", 0o600, ["file.json"]))

def test_a_folder_that_cannot_be_held_is_written_by_its_name(self):
real = os.open
def no_folder(name, flags, *rest, **kw):
if flags & os.O_DIRECTORY:
raise OSError(24, "Too many open files")
return real(name, flags, *rest, **kw)
with mock.patch.object(os, "open", no_folder):
ondisk.write_whole(self.path, "x")
with mock.patch.object(os, "replace", side_effect=OSError("no rename")), self.assertRaises(OSError):
ondisk.write_whole(self.path, "lost")
with open(self.path) as f:
self.assertEqual((f.read(), self.left()), ("x", ["file.json"]))

def test_one_free_descriptor_is_enough(self):
ondisk.write_whole(self.path, "old")
script = textwrap.dedent("""
import os, resource, sys
from nullius import ondisk
resource.setrlimit(resource.RLIMIT_NOFILE, (64, resource.getrlimit(resource.RLIMIT_NOFILE)[1]))
held = []
try:
while True:
held.append(os.open(os.devnull, os.O_RDONLY))
except OSError:
os.close(held.pop()) # exactly one left
ondisk.write_whole(sys.argv[1], "new")
""")
app = os.path.dirname(os.path.dirname(os.path.abspath(ondisk.__file__)))
subprocess.run([sys.executable, "-c", script, self.path], check=True, env={**os.environ, "PYTHONPATH": app})
with open(self.path) as f:
self.assertEqual((f.read(), self.left()), ("new", ["file.json"]))

@unittest.skipUnless(os.path.isdir("/proc/self/fd"), "descriptors counted from /proc")
def test_a_name_that_fails_holds_no_descriptor(self):
before = len(os.listdir("/proc/self/fd"))
with mock.patch.object(ondisk.uuid, "uuid4", side_effect=OSError("no name")):
for _ in range(4):
with self.assertRaises(OSError):
ondisk.write_whole(self.path, "x")
self.assertEqual((len(os.listdir("/proc/self/fd")), self.left()), (before, []))

def test_writers_of_one_file_at_once_each_finish_and_one_of_them_wins(self):
texts = [str(i) * 4096 for i in range(16)]
gate, rename, failed = threading.Barrier(len(texts), timeout=5), os.replace, []
Expand Down
Loading