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:
@@ -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])
|
||||
|
||||
|
||||
+16
-9
@@ -108,14 +108,13 @@ def install_flow(code: str, *, hub: str | None = None, install_dir_path: str | N
|
||||
extract_payload(install)
|
||||
|
||||
started = heartbeat = False
|
||||
service_detail = ""
|
||||
if register_service:
|
||||
common.install_service(install)
|
||||
common.write_arp_uninstall(install)
|
||||
if chosen: # without a Firebird database the service would only fail preflight in a loop
|
||||
progress("Iniciando o serviço…")
|
||||
if not common.service_running():
|
||||
common.start_service()
|
||||
started = common.wait_service_state("RUNNING", timeout=45)
|
||||
started, service_detail = common.start_and_verify()
|
||||
if started and wait_heartbeat:
|
||||
progress("Aguardando o primeiro heartbeat…")
|
||||
heartbeat = common.wait_for_heartbeat(result["agent_token"], result.get("hub_url") or hub, timeout=120)
|
||||
@@ -125,7 +124,7 @@ def install_flow(code: str, *, hub: str | None = None, install_dir_path: str | N
|
||||
except Exception: # noqa: BLE001 — best effort
|
||||
pass
|
||||
|
||||
result.update(install_dir=str(install), agent_version=agent_version, firebird_path=chosen["path"] if chosen else None,
|
||||
result.update(service_detail=service_detail, install_dir=str(install), agent_version=agent_version, firebird_path=chosen["path"] if chosen else None,
|
||||
service_running=started, heartbeat=heartbeat, mode="INSTALL")
|
||||
return result
|
||||
|
||||
@@ -149,8 +148,8 @@ def upgrade_flow(*, install_dir_path: str | None = None, progress: Callable[[str
|
||||
common.write_arp_uninstall(install)
|
||||
os.environ["AGENT_VERSION"] = version
|
||||
progress("Iniciando o serviço…")
|
||||
common.start_service()
|
||||
started = common.wait_service_state("RUNNING", timeout=45)
|
||||
common.ilog(f"upgrade to {version} from {existing.get('agent_id')}")
|
||||
started, service_detail = common.start_and_verify()
|
||||
heartbeat = False
|
||||
try:
|
||||
from gti_fiscal_agent.credential_store import read_credential
|
||||
@@ -158,7 +157,7 @@ def upgrade_flow(*, install_dir_path: str | None = None, progress: Callable[[str
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return {"agent_id": existing["agent_id"], "installation_id": existing["installation_id"], "install_dir": str(install), "agent_version": version,
|
||||
"service_running": started, "heartbeat": heartbeat, "mode": "UPGRADE", "hub_url": existing["hub_url"]}
|
||||
"service_running": started, "service_detail": service_detail, "heartbeat": heartbeat, "mode": "UPGRADE", "hub_url": existing["hub_url"]}
|
||||
|
||||
|
||||
def extract_payload(install: Path) -> None:
|
||||
@@ -195,8 +194,9 @@ def final_message(result: dict) -> str:
|
||||
if result.get("service_running"):
|
||||
return ("Instalação concluída e serviço em execução, mas o primeiro heartbeat ainda não foi confirmado.\n\n"
|
||||
"O serviço continua tentando sozinho; acompanhe pelo painel. Nenhuma edição de arquivo é necessária.")
|
||||
return ("Instalação concluída, mas o serviço não iniciou.\n\nVerifique o log em "
|
||||
f"{result.get('install_dir')}\\logs\\agent.log ou contate o suporte.")
|
||||
return ("ATENÇÃO: o serviço GTI Fiscal Agent NÃO iniciou.\n\n"
|
||||
f"Motivo: {result.get('service_detail') or 'desconhecido'}\n"
|
||||
f"Detalhes em {common.log_path()} e {result.get('install_dir')}\\logs\\agent.log.")
|
||||
|
||||
|
||||
class SetupWizard:
|
||||
@@ -343,12 +343,19 @@ def cli() -> int:
|
||||
if not args.code:
|
||||
result = upgrade_flow(install_dir_path=args.install_dir, progress=print)
|
||||
print(f"UPGRADE_OK agent_id={result['agent_id']} service_running={result['service_running']} heartbeat={result['heartbeat']}")
|
||||
if not result["service_running"]:
|
||||
print(f"SERVICE_START_FAILED {result.get('service_detail')} (see {common.log_path()})", file=sys.stderr)
|
||||
return 3
|
||||
return 0
|
||||
explicit = {"path": args.fdb, "user": args.fb_user, "password": args.fb_password or ""} if args.fdb else None
|
||||
result = install_flow(args.code, hub=args.hub, install_dir_path=args.install_dir, register_service=not args.no_service,
|
||||
firebird=explicit, require_firebird=not args.no_firebird, progress=print)
|
||||
print(f"INSTALL_OK agent_id={result.get('agent_id')} install_dir={result.get('install_dir')} hub={result.get('hub_url')} "
|
||||
f"service_running={result.get('service_running')} heartbeat={result.get('heartbeat')}")
|
||||
if result.get("service_detail") and not result.get("service_running"): # a start was attempted and failed
|
||||
if True:
|
||||
print(f"SERVICE_START_FAILED {result.get('service_detail')} (see {common.log_path()})", file=sys.stderr)
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user