Files
unshackle/unshackle/core/temp.py
T

202 lines
6.4 KiB
Python

from __future__ import annotations
import contextlib
import functools
import logging
import os
import shutil
import sys
import time
import uuid
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import ParamSpec, TypeVar
from filelock import FileLock
from rich import filesize
from unshackle.core.config import config
TASK_PREFIX = "task_"
LOCK_NAME = ".lock"
STALE_GRACE = 60.0
RESUME_STASH = "resume"
STASH_MAX_AGE = 7 * 24 * 3600
log = logging.getLogger("temp")
P = ParamSpec("P")
R = TypeVar("R")
def is_stale(task_dir: Path) -> bool:
"""A task dir is stale when nothing holds its lock and it is past the setup grace."""
try:
if time.time() - task_dir.stat().st_mtime < STALE_GRACE:
return False
except OSError:
return False
return lock_free(task_dir)
def lock_free(task_dir: Path) -> bool:
"""Whether nothing holds the lock of a task dir."""
with claim(task_dir) as free:
return free
@contextmanager
def claim(task_dir: Path) -> Iterator[bool]:
"""Hold the lock of a task dir for the block when nothing else holds it; yield whether it did.
A plain lock call, not FileLock: FileLock deletes the lock file on release, and where the file system has no
lock call it falls back to a lock that it removes even when a live run holds it. A missing lock file counts as
free, any other OS error as held.
"""
try:
fd = os.open(task_dir / LOCK_NAME, os.O_RDWR)
except FileNotFoundError:
yield True
return
except OSError:
yield False
return
try:
try:
if sys.platform == "win32":
import msvcrt
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
yield False
return
yield True
finally:
os.close(fd)
def sweep_task_dirs(root: Path) -> None:
"""Remove task dirs left by processes that died without cleaning up, and resume stash entries past their age.
Each task dir that nothing holds the lock of first gives the stash the segment directories it keeps for resume,
also inside the setup grace: a task dir still in setup keeps none. The sweep holds that lock meanwhile, so a
concurrent sweep leaves the task dir alone.
"""
# the segment store imports this module
from unshackle.core.tracks.segment_store import stash_kept
if not root.is_dir():
return
stash = root / RESUME_STASH
for entry in root.iterdir():
if not entry.is_dir() or entry.is_symlink() or not entry.name.startswith(TASK_PREFIX):
continue
try:
young = time.time() - entry.stat().st_mtime < STALE_GRACE
except OSError:
continue
with claim(entry) as free:
if free:
stash_kept(entry, stash)
if not young:
shutil.rmtree(entry, ignore_errors=True)
if free and not young:
# Windows keeps the lock file that the claim held open
shutil.rmtree(entry, ignore_errors=True)
if stash.is_dir():
cutoff = time.time() - STASH_MAX_AGE
for entry in stash.iterdir():
try:
if entry.stat().st_mtime > cutoff:
continue
except OSError:
continue
if entry.is_dir() and not entry.is_symlink():
shutil.rmtree(entry, ignore_errors=True)
else:
entry.unlink(missing_ok=True)
def temp_root() -> Path:
"""The configured temp dir, also when config.directories.temp points at a task dir inside it."""
temp = config.directories.temp
return temp.parent if temp.name.startswith(TASK_PREFIX) else temp
LOW_FREE_SPACE = 1024**3
"""Free bytes on the temp volume below which a failure line names them."""
def low_free_space(e: BaseException) -> str:
"""``", 38.0 MB free on <temp>"`` when the temp volume is nearly full at ``e``'s first reading, else empty.
Code that deletes temp files on a failure reads it first. The reading is kept on ``e``, so a later report,
also one after the task temp dir is gone, gives the first reading.
"""
if (cached := getattr(e, "free_space", None)) is not None:
return str(cached)
temp = temp_root()
try:
free = shutil.disk_usage(temp).free
except OSError:
free = LOW_FREE_SPACE
note = f", {filesize.decimal(free)} free on {temp}" if free < LOW_FREE_SPACE else ""
e.free_space = note # type: ignore[attr-defined]
return note
def resume_stash() -> Path | None:
"""The dir beside the task dirs that keeps a failed track's segments for the next run.
None outside a task dir: there config.directories.temp itself outlives the run.
"""
root = temp_root()
return None if root == config.directories.temp else root / RESUME_STASH
@contextmanager
def task_temp_dir(task_id: str | None = None) -> Iterator[Path]:
"""Point config.directories.temp at a private dir for this task. Remove it on any exit."""
root = config.directories.temp
root.mkdir(parents=True, exist_ok=True)
sweep_task_dirs(root)
task_dir = root / f"{TASK_PREFIX}{task_id or uuid.uuid4().hex[:12]}"
task_dir.mkdir(parents=True, exist_ok=True)
lock = FileLock(task_dir / LOCK_NAME)
lock.acquire()
config.directories.temp = task_dir
try:
yield task_dir
finally:
config.directories.temp = root
# empty it under the lock, so the sweep of another run never takes from a half-deleted task dir
with contextlib.suppress(OSError):
for child in task_dir.iterdir():
if child.name == LOCK_NAME:
continue
if child.is_dir() and not child.is_symlink():
shutil.rmtree(child, ignore_errors=True)
else:
with contextlib.suppress(OSError):
child.unlink()
lock.release()
shutil.rmtree(task_dir, ignore_errors=True)
def with_task_temp(fn: Callable[P, R]) -> Callable[P, R]:
"""Call the wrapped callable inside its own task temp dir."""
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
with task_temp_dir():
return fn(*args, **kwargs)
return wrapper