ops(gen1): schedule safe nightly grid restart at 03:00 Berlin time
This commit is contained in:
1 parent
43037985b0
commit
6fa9a348c1
4 files changed
+230
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# Gen1 nightly grid restart
|
||||
|
||||
Production host uses existing root GNU screen sessions Simulator001 (42 regions), EventSim001 (1 region), and Robust. The script deliberately refuses missing or ambiguous sessions and never force-kills a process. It verifies region UUIDs before and after restart, uses existing startup scripts and checks SYS.API and network ports. No passwords or tokens are copied or printed.
|
||||
|
||||
Deploy the Python file to /usr/local/sbin/ogl-gen1-nightly-restart.py, service and timer to /etc/systemd/system/ (root-owned). Run python3 /usr/local/sbin/ogl-gen1-nightly-restart.py --check first, then systemctl daemon-reload and systemctl enable --now ogl-gen1-nightly-restart.timer.
|
||||
|
||||
Schedule: 03:00 Europe/Berlin daily, no daytime catch-up after downtime. Logs: journalctl -u ogl-gen1-nightly-restart.service. To disable: systemctl disable --now ogl-gen1-nightly-restart.timer. The timer does not update code or start a deliberately stopped grid; startup requires all three existing screen sessions and processes. Adjust expected region counts if grid topology changes. Production startup requires the existing host-specific start scripts, not stored credentials.
|
||||
Executable
+198
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Orderly nightly restart of an existing screen-managed Gen1 production grid."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Instance:
|
||||
name: str
|
||||
directory: str
|
||||
dll: str
|
||||
starter: str
|
||||
regions: int
|
||||
|
||||
MAIN = Instance("Simulator001", "/opt/robust/bin", "OpenSim.dll",
|
||||
"/opt/robust/bin/ogl-run-simulator-with-policy.sh", 42)
|
||||
EVENT = Instance("EventSim001", "/opt/eventsim/bin", "OpenSim.dll",
|
||||
"/opt/eventsim/bin/start-eventsim-ogl.sh", 1)
|
||||
ROBUST = Instance("Robust", "/opt/robust/bin", "Robust.dll",
|
||||
"/opt/robust/start-robust.sh", 0)
|
||||
SIMS = (MAIN, EVENT)
|
||||
ALL = (*SIMS, ROBUST)
|
||||
|
||||
def log(*args):
|
||||
print(*args, flush=True)
|
||||
|
||||
def screen_id(instance):
|
||||
listing = subprocess.run(["screen", "-ls"], capture_output=True, text=True).stdout
|
||||
matches = re.findall(r"(?m)^\s*(\d+\." + re.escape(instance.name) + r")\s", listing)
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError(f"{instance.name}: expected exactly one existing screen session")
|
||||
return matches[0]
|
||||
|
||||
def send(instance, command):
|
||||
subprocess.run(["screen", "-S", screen_id(instance), "-p", "0", "-X",
|
||||
"stuff", command + "\r"], check=True, timeout=10)
|
||||
|
||||
def pids(instance):
|
||||
result = []
|
||||
for proc in pathlib.Path("/proc").iterdir():
|
||||
if not proc.name.isdecimal():
|
||||
continue
|
||||
try:
|
||||
args = (proc / "cmdline").read_bytes().split(b"\0")
|
||||
if len(args) > 1 and args[0] == b"/usr/bin/dotnet" and args[1] == instance.dll.encode():
|
||||
if (proc / "cwd").resolve() == pathlib.Path(instance.directory):
|
||||
result.append(int(proc.name))
|
||||
except (OSError, RuntimeError):
|
||||
continue
|
||||
return result
|
||||
|
||||
def wait_until(predicate, seconds):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(2)
|
||||
return False
|
||||
|
||||
def healthy():
|
||||
try:
|
||||
if len(pids(ROBUST)) != 1:
|
||||
return False
|
||||
with urllib.request.urlopen("http://127.0.0.1:8851/v1/health", timeout=3) as response:
|
||||
if response.status != 200 or json.load(response).get("status") != "online":
|
||||
return False
|
||||
for port in (80, 8003):
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=2):
|
||||
pass
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def snapshot(instance):
|
||||
with tempfile.TemporaryDirectory(prefix="ogl-restart-") as directory:
|
||||
file = pathlib.Path(directory) / "screen.txt"
|
||||
subprocess.run(["screen", "-S", screen_id(instance), "-p", "0", "-X",
|
||||
"hardcopy", "-h", str(file)], check=True, timeout=10)
|
||||
return file.read_text(errors="replace").replace("\x00", "")
|
||||
|
||||
def region_rows(text):
|
||||
if "# show regions" not in text:
|
||||
return {}
|
||||
section = text.rsplit("# show regions", 1)[-1]
|
||||
return dict(re.findall(
|
||||
r"(?m)^\s*[^\n]*?\s+([0-9a-fA-F-]{36})\s+\d+,\d+\s+\d+x\d+\s+\d+\s+(Yes|No)\b",
|
||||
section))
|
||||
|
||||
def query_regions(instance):
|
||||
before = snapshot(instance)
|
||||
if not re.search(r"Region \([^\n]+\) #\s*$", before):
|
||||
return {}
|
||||
send(instance, "show regions")
|
||||
time.sleep(2)
|
||||
after = snapshot(instance)
|
||||
# A new console response is required; never accept a stale pre-restart list.
|
||||
if after == before or "# show regions" not in after:
|
||||
return {}
|
||||
return region_rows(after)
|
||||
|
||||
def region_set(instance, expected=None, seconds=120):
|
||||
result = None
|
||||
def check():
|
||||
nonlocal result
|
||||
if len(pids(instance)) != 1:
|
||||
return False
|
||||
rows = query_regions(instance)
|
||||
ready = {key for key, state in rows.items() if state == "Yes"}
|
||||
if len(rows) == instance.regions and len(ready) == instance.regions:
|
||||
if expected is None or ready == expected:
|
||||
result = ready
|
||||
return True
|
||||
return False
|
||||
if not wait_until(check, seconds):
|
||||
raise RuntimeError(f"{instance.name}: {instance.regions} ready regions not verified")
|
||||
return result
|
||||
|
||||
def start(instance):
|
||||
if not pids(instance):
|
||||
send(instance, instance.starter)
|
||||
log("Start requested:", instance.name)
|
||||
|
||||
def stop(instance):
|
||||
if pids(instance):
|
||||
send(instance, "shutdown")
|
||||
log("Graceful shutdown requested:", instance.name)
|
||||
|
||||
def preflight():
|
||||
for instance in ALL:
|
||||
screen_id(instance)
|
||||
if len(pids(instance)) != 1:
|
||||
raise RuntimeError(f"{instance.name}: expected exactly one running process")
|
||||
if not pathlib.Path(instance.starter).is_file():
|
||||
raise RuntimeError(f"{instance.name}: startup script missing")
|
||||
subprocess.run(["bash", "-n", instance.starter], check=True, timeout=10)
|
||||
if not healthy():
|
||||
raise RuntimeError("Robust preflight health failed")
|
||||
expected = {instance: region_set(instance) for instance in SIMS}
|
||||
log("Preflight OK:", MAIN.regions, "+", EVENT.regions, "regions ready; Robust online")
|
||||
return expected
|
||||
|
||||
def restart(expected):
|
||||
try:
|
||||
for instance in SIMS:
|
||||
stop(instance)
|
||||
if not wait_until(lambda: all(not pids(x) for x in SIMS), 600):
|
||||
raise RuntimeError("Simulator shutdown exceeded 600 seconds; no force kill")
|
||||
log("Both simulators stopped")
|
||||
stop(ROBUST)
|
||||
if not wait_until(lambda: not pids(ROBUST), 120):
|
||||
raise RuntimeError("Robust shutdown exceeded 120 seconds; no force kill")
|
||||
start(ROBUST)
|
||||
if not wait_until(healthy, 180):
|
||||
raise RuntimeError("Robust readiness not verified")
|
||||
log("Robust ready; SYS.API and grid ports healthy")
|
||||
for instance in SIMS:
|
||||
start(instance)
|
||||
for instance in SIMS:
|
||||
region_set(instance, expected[instance], 300)
|
||||
log(instance.name, f"{instance.regions}/{instance.regions} regions ready")
|
||||
if not healthy():
|
||||
raise RuntimeError("Robust final health failed")
|
||||
for port in (9000, 9002):
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=3):
|
||||
pass
|
||||
log("SUCCESS: all 43 regions and Robust online")
|
||||
except Exception:
|
||||
# Restore stopped services where safely possible; never kill a running process.
|
||||
if not pids(ROBUST):
|
||||
start(ROBUST)
|
||||
wait_until(healthy, 180)
|
||||
if healthy():
|
||||
for instance in SIMS:
|
||||
start(instance)
|
||||
raise
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--check", action="store_true", help="Read-only preflight; no restart")
|
||||
args = parser.parse_args()
|
||||
with open("/run/lock/ogl-gen1-nightly-restart.lock", "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
expected = preflight()
|
||||
if args.check:
|
||||
log("CHECK_OK: no services stopped")
|
||||
else:
|
||||
restart(expected)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=OpenGenesisLINK Gen1 nightly controlled grid restart
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Environment=HOME=/root
|
||||
ExecStart=/usr/bin/python3 /usr/local/sbin/ogl-gen1-nightly-restart.py
|
||||
TimeoutStartSec=35min
|
||||
UMask=0077
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=OpenGenesisLINK Gen1 daily grid restart at 03:00 Europe/Berlin
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 03:00:00 Europe/Berlin
|
||||
AccuracySec=1s
|
||||
Persistent=false
|
||||
Unit=ogl-gen1-nightly-restart.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Reference in new issue
Block a user