Skip to content
Closed
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
35 changes: 32 additions & 3 deletions devito/tools/os_helper.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import os
import stat
from contextlib import suppress
from functools import cache
from pathlib import Path
from tempfile import gettempdir, mkstemp
from tempfile import gettempdir, mkdtemp, mkstemp

from devito.logger import warning

__all__ = ['atomic_write', 'change_directory', 'make_tempdir']

Expand All @@ -27,13 +31,38 @@ def __exit__(self, etype, value, traceback):

def make_tempdir(prefix=None):
"""Create a temporary directory having a deterministic name. The directory
is created within the default OS temporary directory."""
is created within the default OS temporary directory.

Since anyone can predict the name, the directory is only used if private
to the current user. Otherwise, a fresh private directory is returned,
which is reused for the lifetime of the process but not across runs."""
if prefix is None:
name = f'devito-uid{os.getuid()}'
else:
name = f'devito-{str(prefix)}-uid{os.getuid()}'
tmpdir = Path(gettempdir()).joinpath(name)
tmpdir.mkdir(parents=True, exist_ok=True)
try:
tmpdir.mkdir(mode=0o700, parents=True, exist_ok=True)
st = tmpdir.lstat()
except FileExistsError:
# Not a directory
return _make_private_tempdir(name)

is_dir = stat.S_ISDIR(st.st_mode) # `lstat`, so not a symlink to one
is_ours = st.st_uid == os.getuid()
is_private = not st.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
if not (is_dir and is_ours and is_private):
return _make_private_tempdir(name)

return tmpdir


@cache
def _make_private_tempdir(name):
tmpdir = Path(mkdtemp(prefix=f'{name}-'))
warning(f"`{Path(gettempdir()).joinpath(name)}` is not a directory private "
f"to the current user; using `{tmpdir}` instead, which will not be "
"reused across runs. Remove the former to silence this warning")
return tmpdir


Expand Down
59 changes: 58 additions & 1 deletion tests/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import os
import shutil
import stat
import tempfile
import time
import uuid
from pathlib import Path

import numpy as np
import pytest
Expand All @@ -8,7 +13,8 @@
from devito import Eq, Operator, switchenv
from devito.tools import (
CacheInstances, DefaultFrozenDict, UnboundedMultiTuple, UnboundTuple, atomic_write,
ctypes_to_cstr, filter_ordered, memoized_meth, toposort, transitive_closure
ctypes_to_cstr, filter_ordered, make_tempdir, memoized_meth, toposort,
transitive_closure
)
from devito.types.basic import Symbol

Expand Down Expand Up @@ -373,3 +379,54 @@ def fail(*args):
with pytest.raises(OSError, match='Publication failed'):
atomic_write(tmp_path/'file', b'contents', mode='wb', overwrite=False)
assert not list(tmp_path.iterdir())


@pytest.fixture
def prefix():
"""
A unique prefix for `make_tempdir`, so that the tests can use the actual
OS temporary directory without clashing with anything else in there.
"""
prefix = f'test-{uuid.uuid4().hex}'
yield prefix
for path in Path(tempfile.gettempdir()).glob(f'devito-{prefix}-*'):
if path.is_dir() and not path.is_symlink():
shutil.rmtree(path)
else:
path.unlink()


def test_make_tempdir(prefix):
tmpdir = make_tempdir(prefix)

# Created private, with a deterministic name, and reused if already there
assert tmpdir.name == f'devito-{prefix}-uid{os.getuid()}'
assert stat.S_IMODE(tmpdir.lstat().st_mode) == 0o700
assert make_tempdir(prefix) == tmpdir


@pytest.mark.parametrize('plant', ['writable', 'symlink', 'file'])
def test_make_tempdir_untrusted(tmp_path, prefix, plant):
"""
The directory name is predictable, so whatever another user may have
planted under that name must not be used.
"""
target = Path(tempfile.gettempdir())/f'devito-{prefix}-uid{os.getuid()}'

if plant == 'writable':
target.mkdir()
target.chmod(0o777)
elif plant == 'symlink':
target.symlink_to(tmp_path, target_is_directory=True)
else:
target.touch()

# A fresh private directory is used instead
tmpdir = make_tempdir(prefix)
assert tmpdir not in (target, tmp_path)
assert tmpdir.is_dir() and not tmpdir.is_symlink()
assert stat.S_IMODE(tmpdir.lstat().st_mode) == 0o700
assert not list(tmp_path.iterdir())

# Reused for the lifetime of the process
assert make_tempdir(prefix) == tmpdir
Loading