diff --git a/tests/test_write.py b/tests/test_write.py new file mode 100644 index 0000000..51845a2 --- /dev/null +++ b/tests/test_write.py @@ -0,0 +1,80 @@ +"""Tests for writing the active workspace.""" + +import threading +from pathlib import Path + +import pytest +import yaml + +from workflow.utils import write + +WORKSPACE = {"workspace": "test", "sites": ["local"], "http": {"baseurls": {}}} + + +def test_writes_a_dictionary(tmp_path: Path): + destination = tmp_path / "workspace.yml" + write.workspace(WORKSPACE, destination) + assert yaml.safe_load(destination.read_text()) == WORKSPACE + + +def test_copies_a_file_and_keeps_it(tmp_path: Path): + source = tmp_path / "mine.yml" + source.write_text(yaml.dump(WORKSPACE)) + destination = tmp_path / "active" / "workspace.yml" + write.workspace(source, destination) + assert yaml.safe_load(destination.read_text()) == WORKSPACE + assert source.exists() + + +def test_same_workspace_leaves_no_backup(tmp_path: Path): + destination = tmp_path / "workspace.yml" + write.workspace(WORKSPACE, destination) + write.workspace(WORKSPACE, destination) + assert sorted(p.name for p in tmp_path.iterdir()) == ["workspace.yml"] + + +def test_changed_workspace_backs_up_the_previous_one(tmp_path: Path): + destination = tmp_path / "workspace.yml" + write.workspace(WORKSPACE, destination) + write.workspace({**WORKSPACE, "workspace": "other"}, destination) + backups = list(tmp_path.glob("workspace.*.bak")) + assert len(backups) == 1 + assert yaml.safe_load(backups[0].read_text()) == WORKSPACE + assert yaml.safe_load(destination.read_text())["workspace"] == "other" + + +def test_rejects_other_sources(tmp_path: Path): + with pytest.raises(ValueError): + write.workspace("not a path", tmp_path / "workspace.yml") # type: ignore + + +def test_readers_never_see_it_missing_or_empty(tmp_path: Path): + """Runners sharing a home write the workspace while others read it.""" + destination = tmp_path / "workspace.yml" + write.workspace(WORKSPACE, destination) + stop = threading.Event() + seen = [] + + def writer(n: int): + for i in range(200): + write.workspace({**WORKSPACE, "workspace": f"w{n}-{i % 2}"}, destination) + + def reader(): + while not stop.is_set(): + try: + seen.append(yaml.safe_load(destination.read_text())) + except FileNotFoundError: + seen.append("missing") + + readers = [threading.Thread(target=reader) for _ in range(4)] + writers = [threading.Thread(target=writer, args=(n,)) for n in range(4)] + for thread in readers + writers: + thread.start() + for thread in writers: + thread.join() + stop.set() + for thread in readers: + thread.join() + assert seen + assert all(isinstance(s, dict) and s.get("workspace") for s in seen) + assert not list(tmp_path.glob(".workspace.yml.*.tmp")) diff --git a/workflow/utils/write.py b/workflow/utils/write.py index 7cc45ea..d4144e0 100644 --- a/workflow/utils/write.py +++ b/workflow/utils/write.py @@ -1,5 +1,8 @@ """Writing utilities for workflow.""" +import os +import shutil +import tempfile from datetime import datetime from pathlib import Path from typing import Any, Dict, Union @@ -14,6 +17,10 @@ def workspace( ) -> None: """Write a workspace to a destination. + The destination is replaced atomically, so a reader never finds it missing or + partly written; when it changes, the previous one is kept as a dated `.bak`. + A source file is copied, not moved. + Args: source (Union[Path, Dict[str, Any]]): Workspace to write. destination (Path): Destination to write the workspace. @@ -24,21 +31,30 @@ def workspace( Returns: None: None """ - if not destination.parent.exists(): - destination.parent.mkdir(parents=True, exist_ok=True) - # If destination file exists, move it to a backup location file. - date: str = datetime.now().strftime("%Y%m%d%H%M%S") - if destination.exists(): - destination.replace(destination.with_suffix(f".{date}.bak")) - # Make sure the source path exists. if isinstance(source, Path): assert source.exists(), f"workspace {source} does not exist." - source.replace(destination) - return - # Write dictionary to destination. + content: str = source.read_text() elif isinstance(source, dict): # type: ignore - with open(destination, "w") as filename: - yaml.dump(source, filename) - return + content = yaml.dump(source) else: raise ValueError(f"source {source} is not a dictionary or a file path.") + destination.parent.mkdir(parents=True, exist_ok=True) + # Runners can share one home (e.g. CANFAR sessions on /arc), so another one may be + # reading the workspace right now: it is never moved away or left half-written. + if destination.exists(): + if destination.read_text() == content: + return + # Back up the one being replaced, as a copy so it stays in place meanwhile. + date: str = datetime.now().strftime("%Y%m%d%H%M%S") + shutil.copy2(destination, destination.with_suffix(f".{date}.bak")) + # Write beside it, then rename into place: readers see the old or the new file. + descriptor, temporary = tempfile.mkstemp( + dir=destination.parent, prefix=f".{destination.name}.", suffix=".tmp" + ) + try: + with os.fdopen(descriptor, "w") as filename: + filename.write(content) + os.replace(temporary, destination) + except BaseException: + Path(temporary).unlink(missing_ok=True) + raise