PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
safety.py
Go to the documentation of this file.
1"""!
2@file safety.py
3@brief Refusals: active jobs, runtime locks, and cold-payload requirements.
4"""
5
6import argparse
7import base64
8import concurrent.futures
9import contextlib
10import datetime
11import errno
12import hashlib
13import json
14import os
15import re
16import shutil
17import socket
18import subprocess
19import sys
20import tarfile
21import tempfile
22import uuid
23from pathlib import Path
24import yaml
25from .models import (
26 STORAGE_LOCK_FILENAME,
27 StorageError,
28 _human_bytes,
29 _read_json,
30 _utc_now,
31 is_artifact_cold,
32 read_storage_state,
33)
34
35
36def cold_study_members(study_path: str) -> list:
37 """!
38 @brief Return numbered study members whose local payload was pruned.
39 @param[in] study_path Value supplied through the `study_path` argument.
40 @return Result produced by this operation.
41 """
42 cases_dir = Path(os.path.abspath(study_path)) / "cases"
43 if not cases_dir.is_dir():
44 return []
45 return [
46 child.name for child in sorted(cases_dir.iterdir())
47 if child.is_dir() and is_artifact_cold(str(child))
48 ]
49
50
51def require_storage_payload_local(
52 root_path: str,
53 operation: str,
54 checkpoint: int = None,
55 checkpoints=None,
56) -> None:
57 """!
58 @brief Reject a workflow that requires payload currently held in cold storage.
59 @param[in] root_path Run or study-member directory checked by an existing workflow.
60 @param[in] operation Human-readable consuming operation.
61 @param[in] checkpoint Optional single required checkpoint step.
62 @param[in] checkpoints Optional iterable of every required checkpoint step.
63 """
64 state = read_storage_state(root_path)
65 if not state or not state.get("local_pruned"):
66 return
67 required_steps = set()
68 if checkpoint is not None:
69 required_steps.add(int(checkpoint))
70 if checkpoints is not None:
71 required_steps.update(int(step) for step in checkpoints)
72 restored = set(state.get("restored_components") or [])
73 restored.update(state.get("retained_components") or [])
74 # A step the archive does not hold was never committed, so restoring cannot supply it;
75 # the consuming workflow reports it. Markers older than this record name no steps.
76 archived = state.get("archived_checkpoints")
77 missing_steps = sorted(
78 step for step in required_steps
79 if f"checkpoint:{step}" not in restored and (archived is None or step in archived)
80 )
81 if required_steps and not missing_steps:
82 return
83 archive_id = state.get("archive_id", "<archive-id>")
84 if missing_steps and len(missing_steps) <= 8:
85 suffix = "".join(f" --checkpoint {step}" for step in missing_steps)
86 else:
87 # A full restore is clearer than printing hundreds of repeatable selectors.
88 suffix = ""
89 raise StorageError(
90 f"{operation} requires payload archived from {os.path.abspath(root_path)}. Restore it first with:\n"
91 f" picurv storage restore --archive-id {archive_id}{suffix}"
92 )
93
94
95def _require_free_space(directory: str, needed_bytes: int, purpose: str) -> None:
96 """!
97 @brief Refuse to begin staging work the destination filesystem cannot hold.
98
99 @details Packaging and restore both stage uncompressed bytes on disk before the
100 verified result replaces or uploads them. Discovering the filesystem was
101 too small only after chunks were partially written wastes the transfer
102 and can leave a staging directory to clean up by hand; checking first
103 turns that into an immediate, actionable refusal.
104 @param[in] directory Directory whose filesystem free space is checked; must exist.
105 @param[in] needed_bytes Estimated peak bytes the operation holds on disk at once.
106 @param[in] purpose Short present-tense phrase describing the operation, for the message.
107 @throws StorageError when free space is smaller than the estimate.
108 """
109 try:
110 free_bytes = shutil.disk_usage(directory).free
111 except OSError:
112 return
113 if free_bytes < needed_bytes:
114 raise StorageError(
115 f"Not enough free space at {directory} to {purpose}: need approximately "
116 f"{_human_bytes(needed_bytes)}, {_human_bytes(free_bytes)} free."
117 )
118
119
120def _lock_owner_active(metadata_path: str) -> bool:
121 """!
122 @brief Conservatively determine whether a solver/post/storage owner marker is active.
123 @param[in] metadata_path Value supplied through the `metadata_path` argument.
124 @return Result produced by this operation.
125 """
126 owner = _read_json(metadata_path)
127 if not owner:
128 return True
129 host = owner.get("host")
130 pid = owner.get("pid")
131 if host and host != socket.gethostname():
132 return True
133 try:
134 pid = int(pid)
135 except (TypeError, ValueError):
136 return True
137 try:
138 os.kill(pid, 0)
139 except ProcessLookupError:
140 return False
141 except (PermissionError, OSError):
142 return True
143 return True
144
145
146def _collect_job_ids(payload) -> set:
147 """!
148 @brief Recursively collect submitted Slurm job IDs from scheduler metadata.
149 @param[in] payload Value supplied through the `payload` argument.
150 @return Result produced by this operation.
151 """
152 result = set()
153 if isinstance(payload, dict):
154 if payload.get("submitted") and payload.get("job_id") is not None:
155 result.add(str(payload["job_id"]).strip())
156 for value in payload.values():
157 result.update(_collect_job_ids(value))
158 elif isinstance(payload, list):
159 for value in payload:
160 result.update(_collect_job_ids(value))
161 return {item for item in result if item}
162
163
164def _slurm_activity(root: str) -> dict:
165 """!
166 @brief Query live Slurm state for every job recorded below an artifact scheduler directory.
167 @param[in] root Value supplied through the `root` argument.
168 @return Result produced by this operation.
169 """
170 job_ids = set()
171 scheduler_dirs = [Path(root) / "scheduler"]
172 if (Path(root) / "cases").is_dir():
173 scheduler_dirs.extend((Path(root) / "cases").glob("*/scheduler"))
174 for scheduler in scheduler_dirs:
175 if not scheduler.is_dir():
176 continue
177 for path in scheduler.glob("submission*.json"):
178 job_ids.update(_collect_job_ids(_read_json(str(path))))
179 if not job_ids:
180 return {"job_ids": [], "active": [], "unknown": False}
181 squeue = shutil.which("squeue")
182 if not squeue:
183 return {"job_ids": sorted(job_ids), "active": [], "unknown": True}
184 active = []
185 unknown_ids = []
186 for recorded_id in sorted(job_ids):
187 result = subprocess.run(
188 [squeue, "-h", "-j", recorded_id, "-o", "%i|%T"],
189 text=True, capture_output=True, check=False,
190 )
191 if result.returncode != 0:
192 detail = (result.stderr or result.stdout or "").lower()
193 # Slurm returns nonzero for a valid historical/purged job id. Such an id
194 # cannot be queued, so it is inactive rather than an ambiguous failure.
195 if "invalid job id" in detail or "invalid job/step" in detail:
196 continue
197 unknown_ids.append(recorded_id)
198 continue
199 for line in result.stdout.splitlines():
200 if not line.strip():
201 continue
202 job_id, _, state = line.partition("|")
203 active.append({"job_id": job_id.strip(), "state": state.strip() or "UNKNOWN"})
204 return {
205 "job_ids": sorted(job_ids),
206 "active": active,
207 "unknown": bool(unknown_ids),
208 "unknown_job_ids": unknown_ids,
209 }
210
211
212def _assert_archive_safe(inventory: dict) -> None:
213 """!
214 @brief Refuse to package a changing or scheduler-ambiguous artifact.
215 @param[in] inventory Value supplied through the `inventory` argument.
216 """
217 problems = []
218 if inventory["incomplete_checkpoints"]:
219 problems.append("incomplete checkpoint(s): " + ", ".join(inventory["incomplete_checkpoints"][:3]))
220 if inventory["active_locks"]:
221 problems.append("active runtime lock(s): " + ", ".join(inventory["active_locks"]))
222 if inventory["slurm"]["active"]:
223 problems.append(
224 "active Slurm job(s): " + ", ".join(
225 f"{item['job_id']} ({item['state']})" for item in inventory["slurm"]["active"]
226 )
227 )
228 if inventory["slurm"]["unknown"]:
229 problems.append(
230 "recorded Slurm job IDs could not be checked because squeue is unavailable or failed"
231 )
232 if problems:
233 raise StorageError("Artifact is not safe to archive/offload: " + "; ".join(problems) + ".")
234
235
236@contextlib.contextmanager
237def storage_operation_lock(root_path: str, operation: str):
238 """!
239 @brief Hold an exclusive local storage-operation marker for one artifact.
240 @param[in] root_path Value supplied through the `root_path` argument.
241 @param[in] operation Value supplied through the `operation` argument.
242 """
243 root = os.path.abspath(root_path)
244 lock_path = os.path.join(root, STORAGE_LOCK_FILENAME)
245 if os.path.exists(lock_path):
246 if _lock_owner_active(lock_path):
247 raise StorageError(f"Another storage operation owns {lock_path}.")
248 try:
249 os.remove(lock_path)
250 except OSError as exc:
251 raise StorageError(f"Unable to remove stale storage lock {lock_path}: {exc}") from exc
252 payload = {"operation": operation, "pid": os.getpid(), "host": socket.gethostname(), "started_at": _utc_now()}
253 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
254 try:
255 descriptor = os.open(lock_path, flags, 0o600)
256 with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
257 json.dump(payload, stream, indent=2, sort_keys=True)
258 stream.write("\n")
259 yield
260 finally:
261 try:
262 os.remove(lock_path)
263 except FileNotFoundError:
264 pass
265
266
267@contextlib.contextmanager
268def runtime_stage_lock(root_path: str, stage: str):
269 """!
270 @brief Mark a locally executed solver/post stage as active for storage safety.
271 @param[in] root_path Run directory used as the runtime working directory.
272 @param[in] stage Runtime stage label; storage currently uses this for solver execution.
273 """
274 scheduler = os.path.join(os.path.abspath(root_path), "scheduler")
275 os.makedirs(scheduler, exist_ok=True)
276 lock_path = os.path.join(scheduler, f"{stage}.lock.json")
277 if os.path.exists(lock_path):
278 if _lock_owner_active(lock_path):
279 raise StorageError(f"A {stage} runtime stage already owns {lock_path}.")
280 os.remove(lock_path)
281 payload = {"stage": stage, "pid": os.getpid(), "host": socket.gethostname(), "started_at": _utc_now()}
282 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
283 descriptor = os.open(lock_path, flags, 0o600)
284 with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
285 json.dump(payload, stream, indent=2, sort_keys=True)
286 stream.write("\n")
287 try:
288 yield
289 finally:
290 try:
291 os.remove(lock_path)
292 except FileNotFoundError:
293 pass
User-facing storage workflow failure.
Definition models.py:139