91 lines
3.6 KiB
Python
91 lines
3.6 KiB
Python
"""File-backed state and launch support for detached jobs."""
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
TAIL_CHARS = 4000
|
|
|
|
|
|
def cluster_environment(body: dict, env: dict[str, str]) -> dict | None:
|
|
"""Apply a cluster choice to the child environment."""
|
|
if "cluster" not in body:
|
|
return None
|
|
cluster = body["cluster"]
|
|
if not isinstance(cluster, dict) or cluster.get("mode") not in ("auto", "local", "remote", "sync"):
|
|
raise ValueError("cluster.mode debe ser auto, local, remote o sync.")
|
|
mode = cluster["mode"]
|
|
scheduler = cluster.get("scheduler")
|
|
if "scheduler" in cluster and (not isinstance(scheduler, str) or not scheduler.strip() or "\0" in scheduler):
|
|
raise ValueError("cluster.scheduler debe ser texto no vacío.")
|
|
if mode == "auto":
|
|
return {"mode": mode}
|
|
env["EEG_ANALYSIS_CLUSTER"] = mode
|
|
if mode == "local":
|
|
env.pop("DASK_SCHEDULER_ADDRESS", None)
|
|
if mode == "remote":
|
|
scheduler = scheduler or env.get("DASK_SCHEDULER_ADDRESS")
|
|
if not scheduler:
|
|
raise ValueError("El modo remote requiere cluster.scheduler o DASK_SCHEDULER_ADDRESS.")
|
|
env["DASK_SCHEDULER_ADDRESS"] = scheduler
|
|
return {"mode": mode, "scheduler": scheduler}
|
|
return {"mode": mode}
|
|
|
|
|
|
def _alive(pid: int) -> bool:
|
|
try:
|
|
os.kill(pid, 0)
|
|
except ProcessLookupError:
|
|
return False
|
|
except PermissionError:
|
|
return True
|
|
return True
|
|
|
|
|
|
def _tail(path: Path) -> str:
|
|
return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else ""
|
|
|
|
|
|
def state(folder: Path) -> dict:
|
|
"""Read job metadata, logs, and process state."""
|
|
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
|
|
exit_file = folder / "exit"
|
|
code = int(exit_file.read_text().strip() or 1) if exit_file.exists() else None
|
|
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
|
|
if code == 0:
|
|
status = "completado"
|
|
elif code is not None:
|
|
status = "fallido"
|
|
else:
|
|
status = "en_curso" if _alive(job["pid"]) else "interrumpido"
|
|
return {**job, "estado": status, "codigo": code, "salida": out, "error": err}
|
|
|
|
|
|
def launch(base: Path, argv: list[str], env: dict[str, str], metadata: dict, *,
|
|
precise_id: bool = False, cwd: Path | None = None) -> Path:
|
|
"""Start a detached command and publish its job metadata."""
|
|
now = datetime.now(timezone.utc)
|
|
timestamp = now.strftime("%Y%m%dT%H%M%S%f" if precise_id else "%Y%m%dT%H%M%S")
|
|
job_id = f"{timestamp}-{uuid.uuid4().hex[:6]}"
|
|
folder = base / job_id
|
|
folder.mkdir(parents=True)
|
|
shell = '{ "$@" > "$0/stdout.log" 2> "$0/stderr.log"; echo $? > "$0/exit.tmp"; mv "$0/exit.tmp" "$0/exit"; }'
|
|
process = subprocess.Popen(["sh", "-c", shell, str(folder.resolve()), *argv],
|
|
cwd=cwd or folder, env={**env, "RUN_PROGRESS_DIR": str(folder.resolve())},
|
|
start_new_session=True,
|
|
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
job = {**metadata, "id": job_id, "pid": process.pid,
|
|
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
|
|
temporary = folder / "job.json.tmp"
|
|
temporary.write_text(json.dumps(job), encoding="utf-8")
|
|
temporary.replace(folder / "job.json")
|
|
return folder
|
|
|
|
|
|
def folders(base: Path) -> list[Path]:
|
|
"""List published jobs newest first by their timestamped IDs."""
|
|
return sorted((path for path in base.glob("*") if (path / "job.json").exists()), reverse=True)
|