103 lines
4.7 KiB
Python
103 lines
4.7 KiB
Python
"""The pumping, for its callers (aimsight-app): the tracked stations, launching pump.sh, its state.
|
|
|
|
- `tracked()`, `save(rows)`: extraction/stations.txt, one station per line, "SERIAL [position]" (position: "lat,lon" or a
|
|
Swiss place, for the weather, weather/meteoswiss.py; empty: an indoor site, no weather); pump.py reads it too;
|
|
- `start(stations, start, end, images, diff)`: pump.sh in the background (its lock: one pumping at a time); with diff,
|
|
pump_diff.sh (the differential images into data_diff/, its own lock: it runs beside pump.sh);
|
|
- `running(diff)`, `log(diff)`: a pumping running (any: the scheduler's, by hand, a caller's), the end of out/pump.log
|
|
(diff: out/pump_diff.log).
|
|
|
|
A refused request raises ValueError, with its reason. Standard library only.
|
|
"""
|
|
import fcntl
|
|
import os
|
|
import re
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SERIAL = re.compile(r"[A-Za-z0-9_-]+$") # it becomes an argument of pump.sh and a folder of data/
|
|
DAY = re.compile(r"\d{4}-\d{2}-\d{2}$")
|
|
|
|
|
|
def tracked():
|
|
"""{serial: position ("" without)}, in the order of the file, without duplicates."""
|
|
f = ROOT / "extraction" / "stations.txt"
|
|
out = {}
|
|
for line in f.read_text().splitlines() if f.is_file() else []:
|
|
serial, _, position = line.strip().partition(" ")
|
|
if serial:
|
|
out.setdefault(serial, position.strip())
|
|
return out
|
|
|
|
|
|
def save(rows):
|
|
"""rows: [{serial, position}] -> the new stations.txt, and its content as tracked()."""
|
|
out = {}
|
|
for r in rows:
|
|
serial, position = str(r.get("serial", "")).strip(), " ".join(str(r.get("position", "")).split())
|
|
if not SERIAL.match(serial):
|
|
raise ValueError(f"not a serial number: {serial!r}")
|
|
out.setdefault(serial, position)
|
|
(ROOT / "extraction" / "stations.txt").write_text("".join(f"{s} {p}".rstrip() + "\n" for s, p in out.items()))
|
|
return out
|
|
|
|
|
|
def name(diff):
|
|
return "pump_diff" if diff else "pump"
|
|
|
|
|
|
def running(diff=False):
|
|
"""A pumping running: the lock of pump.sh (diff: pump_diff.sh) is held."""
|
|
try:
|
|
with open(ROOT / "out" / f"{name(diff)}.lock") as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except FileNotFoundError:
|
|
return False
|
|
except BlockingIOError:
|
|
return True
|
|
return False
|
|
|
|
|
|
def log(lines=40, diff=False):
|
|
"""The last lines of out/pump.log (diff: out/pump_diff.log)."""
|
|
try:
|
|
with open(ROOT / "out" / f"{name(diff)}.log", "rb") as f:
|
|
f.seek(max(0, f.seek(0, os.SEEK_END) - 200 * lines))
|
|
return f.read().decode(errors="replace").splitlines()[-lines:]
|
|
except FileNotFoundError:
|
|
return []
|
|
|
|
|
|
def start(stations, start="", end="", images=False, diff=False):
|
|
"""pump.sh in the background, with --from start --to end (YYYY-MM-DD, end excluded), or without (the missing days of
|
|
each station up to now); --delay 300. With diff, pump_diff.sh (without range: from the last indexed day, a station
|
|
never pumped is skipped; images ignored, its IRON images one per hour). -> the process."""
|
|
if not stations or not all(isinstance(s, str) and SERIAL.match(s) for s in stations):
|
|
raise ValueError("no station, or not a serial number")
|
|
if bool(start) != bool(end) or (start and not (DAY.match(start) and DAY.match(end) and start < end)):
|
|
raise ValueError("a range: From and To, YYYY-MM-DD, From before To")
|
|
if running(diff):
|
|
raise ValueError("a pumping is already running")
|
|
args = ["--from", start, "--to", end] * bool(start) + ["--images"] * bool(images and not diff) + ["--delay", "300", *stations]
|
|
return subprocess.Popen([str(ROOT / "extraction" / f"{name(diff)}.sh"), *args], cwd=ROOT,
|
|
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
|
|
if __name__ == "__main__": # a check, in a temporary folder: python3 extraction/pumping.py
|
|
import tempfile
|
|
ROOT = Path(tempfile.mkdtemp())
|
|
(ROOT / "extraction").mkdir()
|
|
(ROOT / "extraction" / "stations.txt").write_text("NORDEND\nNIEDERHORN 46.69,7.78\n\nNORDEND Zermatt\n")
|
|
assert tracked() == {"NORDEND": "", "NIEDERHORN": "46.69,7.78"}, tracked()
|
|
assert save([{"serial": "A", "position": " Interlaken BE "}, {"serial": "B"}, {"serial": "A"}]) == {"A": "Interlaken BE", "B": ""}
|
|
assert (ROOT / "extraction" / "stations.txt").read_text() == "A Interlaken BE\nB\n"
|
|
assert not running() and log() == [] and not running(diff=True) and log(diff=True) == []
|
|
for bad in ((save, [{"serial": "../x"}]), (start, ["A;rm"]), (start, ["A"], "2026-11-10"), (start, ["A"], "2026-11-10", "2026-11-09")):
|
|
try:
|
|
bad[0](*bad[1:])
|
|
raise AssertionError(f"not refused: {bad}")
|
|
except ValueError:
|
|
pass
|
|
print("ok")
|