fix: installer starts the service reliably (retry + verify + installer.log), fails loudly; 1.1.6

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
gti
2026-09-24 10:54:19 -03:00
co-authored by Claude Sonnet 5
parent 7e229f4b84
commit 40a4d835fe
22 changed files with 153 additions and 35 deletions
+70 -1
View File
@@ -172,8 +172,26 @@ def wait_for_heartbeat(agent_token: str, hub: str, timeout: float = 120.0) -> bo
return False
def log_path() -> Path:
return Path(os.environ.get("GTI_LOG_DIR") or os.path.join(os.environ.get("PROGRAMDATA", r"C:\ProgramData"), "GTI", "FiscalAgent")) / "installer.log"
def ilog(message: str) -> None:
"""Append one timestamped line to installer.log (best effort, never raises, never holds a secret)."""
try:
path = log_path()
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as fh:
fh.write(time.strftime("%Y-%m-%d %H:%M:%S ") + " ".join(message.split()) + chr(10))
except Exception: # noqa: BLE001
pass
def _sc(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(["sc.exe", *args], capture_output=True, text=True)
result = subprocess.run(["sc.exe", *args], capture_output=True, text=True)
text = " ".join((result.stdout + " " + result.stderr).split())
ilog(f"sc {' '.join(a for a in args if not a.lower().startswith('binpath'))} -> rc={result.returncode} {text[:300]}")
return result
def install_service(install_dir_path: Path) -> None:
@@ -209,6 +227,57 @@ def start_service() -> None:
_sc(["start", SERVICE_NAME])
def service_state() -> str:
out = subprocess.run(["sc.exe", "query", SERVICE_NAME], capture_output=True, text=True).stdout
for name in ("RUNNING", "START_PENDING", "STOP_PENDING", "STOPPED", "PAUSED"):
if name in out:
return name
return "UNKNOWN"
def service_process_alive() -> bool:
out = subprocess.run(["sc.exe", "queryex", SERVICE_NAME], capture_output=True, text=True).stdout
for line in out.splitlines():
if line.strip().upper().startswith("PID"):
pid = line.split(":", 1)[1].strip()
if pid.isdigit() and int(pid) > 0:
tl = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout
return pid in tl
return False
def start_and_verify(attempts: int = 4, per_attempt: float = 60.0) -> tuple[bool, str]:
"""Start the service and prove it: RUNNING for a few seconds AND a live host process.
The first start after fresh files often exceeds the SCM's 30 s limit (error 1053: antivirus scans the
new onedir), so a failed attempt is diagnosed into installer.log and retried; the second start is fast."""
detail = "not started"
for attempt in range(1, attempts + 1):
ilog(f"start attempt {attempt}/{attempts}; state={service_state()}")
if service_state() != "RUNNING":
_sc(["start", SERVICE_NAME])
deadline = time.time() + per_attempt
while time.time() < deadline and service_state() in ("START_PENDING", "STOP_PENDING", "UNKNOWN"):
time.sleep(1.5)
if service_state() == "RUNNING":
time.sleep(6) # must survive its own startup (preflight) rather than crash right after RUNNING
if service_state() == "RUNNING" and service_process_alive():
ilog("service RUNNING and host process alive")
return True, "RUNNING"
state = service_state()
query = subprocess.run(["sc.exe", "query", SERVICE_NAME], capture_output=True, text=True).stdout
exit_codes = " ".join(line.strip() for line in query.splitlines() if "EXIT_CODE" in line.upper())
detail = f"attempt {attempt}: state={state} {exit_codes}".strip()
ilog(detail)
try:
tail = (install_dir() / "logs" / "agent.log").read_text(encoding="utf-8", errors="replace").splitlines()[-3:]
ilog("agent.log tail: " + " | ".join(tail)[:400])
except Exception: # noqa: BLE001
pass
time.sleep(5)
ilog(f"service did NOT start: {detail}")
return False, detail
def stop_service() -> None:
_sc(["stop", SERVICE_NAME])