fix: installer tolerates localized 'service exists' (1073) and restarts the service if an upgrade step fails; 1.1.7
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "gti-fiscal-agent"
|
name = "gti-fiscal-agent"
|
||||||
version = "1.1.6"
|
version = "1.1.7"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
dependencies = ["httpx>=0.27,<1"]
|
dependencies = ["httpx>=0.27,<1"]
|
||||||
|
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ class Config:
|
|||||||
# (A legacy AGENT_JOBS_ENABLED line in an old agent.env is deliberately ignored.)
|
# (A legacy AGENT_JOBS_ENABLED line in an old agent.env is deliberately ignored.)
|
||||||
self.agent_jobs_enabled = True
|
self.agent_jobs_enabled = True
|
||||||
self.poll_interval_seconds = float(env.get("POLL_INTERVAL_SECONDS", "5"))
|
self.poll_interval_seconds = float(env.get("POLL_INTERVAL_SECONDS", "5"))
|
||||||
self.agent_version = env.get("AGENT_VERSION", "1.1.6")
|
self.agent_version = env.get("AGENT_VERSION", "1.1.7")
|
||||||
self.schema_fingerprint = env.get("SCHEMA_FINGERPRINT", REFERENCE_SCHEMA_V1)
|
self.schema_fingerprint = env.get("SCHEMA_FINGERPRINT", REFERENCE_SCHEMA_V1)
|
||||||
self.state_db = env.get("AGENT_STATE_DB", str(AGENT_ROOT / "agent_state.sqlite"))
|
self.state_db = env.get("AGENT_STATE_DB", str(AGENT_ROOT / "agent_state.sqlite"))
|
||||||
# Pilot write authorization: both must be explicitly set by the installer for
|
# Pilot write authorization: both must be explicitly set by the installer for
|
||||||
@@ -240,7 +240,7 @@ def execute_job(job, config, executor, state, env):
|
|||||||
"coverage": coverage,
|
"coverage": coverage,
|
||||||
"operational": operational,
|
"operational": operational,
|
||||||
"fiscal_mode": getattr(config, "fiscal_mode", None),
|
"fiscal_mode": getattr(config, "fiscal_mode", None),
|
||||||
"release_version": env.get("AGENT_VERSION") or "1.1.6",
|
"release_version": env.get("AGENT_VERSION") or "1.1.7",
|
||||||
"products_total": len(products),
|
"products_total": len(products),
|
||||||
"products_changed": len(to_process),
|
"products_changed": len(to_process),
|
||||||
"products_processed": summary["processed"],
|
"products_processed": summary["processed"],
|
||||||
@@ -398,7 +398,7 @@ def run(config, env, *, max_iterations=None, stopper=None):
|
|||||||
def enforce_startup_preflight(env):
|
def enforce_startup_preflight(env):
|
||||||
"""Full read-only preflight at startup (Hub, auth, Firebird, capabilities, company context, guards). Fail closed."""
|
"""Full read-only preflight at startup (Hub, auth, Firebird, capabilities, company context, guards). Fail closed."""
|
||||||
from gti_fiscal_agent.preflight import run_preflight
|
from gti_fiscal_agent.preflight import run_preflight
|
||||||
report = run_preflight(env, agent_version=env.get("AGENT_VERSION") or "1.1.6")
|
report = run_preflight(env, agent_version=env.get("AGENT_VERSION") or "1.1.7")
|
||||||
logger.info("startup preflight: %s", json.dumps({k: report[k] for k in ("PREFLIGHT", "blockers", "fiscal_mode", "effective_firebird_writes")}, ensure_ascii=False))
|
logger.info("startup preflight: %s", json.dumps({k: report[k] for k in ("PREFLIGHT", "blockers", "fiscal_mode", "effective_firebird_writes")}, ensure_ascii=False))
|
||||||
print(json.dumps({"PREFLIGHT": report["PREFLIGHT"], "blockers": report["blockers"]}, ensure_ascii=False))
|
print(json.dumps({"PREFLIGHT": report["PREFLIGHT"], "blockers": report["blockers"]}, ensure_ascii=False))
|
||||||
if report["PREFLIGHT"] != "PASS":
|
if report["PREFLIGHT"] != "PASS":
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import os
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
AGENT_VERSION_DEFAULT = "1.1.6"
|
AGENT_VERSION_DEFAULT = "1.1.7"
|
||||||
REQUIRED_ENV = ("GTI_HUB_URL", "AGENT_TOKEN", "FIREBIRD_DATABASE_PATH", "FB_USER", "FB_PASSWORD")
|
REQUIRED_ENV = ("GTI_HUB_URL", "AGENT_TOKEN", "FIREBIRD_DATABASE_PATH", "FB_USER", "FB_PASSWORD")
|
||||||
REQUIRED_CAPABILITIES = ("supports_ncm", "supports_ipi", "supports_cest")
|
REQUIRED_CAPABILITIES = ("supports_ncm", "supports_ipi", "supports_cest")
|
||||||
FISCAL_MODES = ("DRY_RUN", "AUTO_APPLY")
|
FISCAL_MODES = ("DRY_RUN", "AUTO_APPLY")
|
||||||
|
|||||||
@@ -4,5 +4,5 @@ kept identical to this) and what an AgentRelease row's `version` column holds
|
|||||||
once published — never a second, independent version number. Fiscal semantics
|
once published — never a second, independent version number. Fiscal semantics
|
||||||
are versioned separately (ENGINE_VERSION/DECISION_VERSION in classification.py,
|
are versioned separately (ENGINE_VERSION/DECISION_VERSION in classification.py,
|
||||||
DECISION_ENGINE_VERSION etc.) and are NOT changed by a release bump."""
|
DECISION_ENGINE_VERSION etc.) and are NOT changed by a release bump."""
|
||||||
GTI_FISCAL_VERSION = "1.1.6"
|
GTI_FISCAL_VERSION = "1.1.7"
|
||||||
API_COMPAT_MAJOR_MINOR = "1.0" # an Agent 1.0.x/1.1.x talks to any Hub 1.0.x
|
API_COMPAT_MAJOR_MINOR = "1.0" # an Agent 1.0.x/1.1.x talks to any Hub 1.0.x
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "gti-fiscal-hub"
|
name = "gti-fiscal-hub"
|
||||||
version = "1.1.6"
|
version = "1.1.7"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fastapi>=0.115,<1",
|
"fastapi>=0.115,<1",
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ def test_health_is_unavailable_when_database_is_down():
|
|||||||
|
|
||||||
def test_version_endpoint_reports_release_and_fiscal_versions():
|
def test_version_endpoint_reports_release_and_fiscal_versions():
|
||||||
body = TestClient(create_app(database_probe=lambda: True)).get("/version").json()
|
body = TestClient(create_app(database_probe=lambda: True)).get("/version").json()
|
||||||
assert body["version"] == "1.1.6" and body["api_compat"] == "1.0" and body["engine_version"] and body["decision_version"]
|
assert body["version"] == "1.1.7" and body["api_compat"] == "1.0" and body["engine_version"] and body["decision_version"]
|
||||||
|
|
||||||
|
|
||||||
def test_production_refuses_the_dev_token(monkeypatch):
|
def test_production_refuses_the_dev_token(monkeypatch):
|
||||||
|
|||||||
@@ -19,4 +19,4 @@ FB_PASSWORD=
|
|||||||
FISCAL_MODE=DRY_RUN
|
FISCAL_MODE=DRY_RUN
|
||||||
FIREBIRD_WRITES=0
|
FIREBIRD_WRITES=0
|
||||||
POLL_INTERVAL_SECONDS=5
|
POLL_INTERVAL_SECONDS=5
|
||||||
AGENT_VERSION=1.1.6
|
AGENT_VERSION=1.1.7
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ switch ($Command) {
|
|||||||
"GTI_HUB_URL=$hub", "AGENT_TOKEN=$token", "AGENT_ID=$agentId",
|
"GTI_HUB_URL=$hub", "AGENT_TOKEN=$token", "AGENT_ID=$agentId",
|
||||||
"COMPANY_CODE=$code", "COMPANY_CNPJ=$cnpj", "COMPANY_CRT_SOURCE=$crtSource",
|
"COMPANY_CODE=$code", "COMPANY_CNPJ=$cnpj", "COMPANY_CRT_SOURCE=$crtSource",
|
||||||
"FIREBIRD_DATABASE_PATH=$db", "FB_USER=$fbUser", "FB_PASSWORD=$fbPass",
|
"FIREBIRD_DATABASE_PATH=$db", "FB_USER=$fbUser", "FB_PASSWORD=$fbPass",
|
||||||
'FISCAL_MODE=DRY_RUN', 'FIREBIRD_WRITES=0', 'POLL_INTERVAL_SECONDS=5', 'AGENT_VERSION=1.1.6'
|
'FISCAL_MODE=DRY_RUN', 'FIREBIRD_WRITES=0', 'POLL_INTERVAL_SECONDS=5', 'AGENT_VERSION=1.1.7'
|
||||||
)
|
)
|
||||||
Set-Content -Path $EnvFile -Value $lines -Encoding UTF8
|
Set-Content -Path $EnvFile -Value $lines -Encoding UTF8
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,4 +19,4 @@ FB_PASSWORD=
|
|||||||
FISCAL_MODE=DRY_RUN
|
FISCAL_MODE=DRY_RUN
|
||||||
FIREBIRD_WRITES=0
|
FIREBIRD_WRITES=0
|
||||||
POLL_INTERVAL_SECONDS=5
|
POLL_INTERVAL_SECONDS=5
|
||||||
AGENT_VERSION=1.1.6
|
AGENT_VERSION=1.1.7
|
||||||
|
|||||||
@@ -19,4 +19,4 @@ FB_PASSWORD=
|
|||||||
FISCAL_MODE=DRY_RUN
|
FISCAL_MODE=DRY_RUN
|
||||||
FIREBIRD_WRITES=0
|
FIREBIRD_WRITES=0
|
||||||
POLL_INTERVAL_SECONDS=5
|
POLL_INTERVAL_SECONDS=5
|
||||||
AGENT_VERSION=1.1.6
|
AGENT_VERSION=1.1.7
|
||||||
|
|||||||
@@ -19,4 +19,4 @@ FB_PASSWORD=
|
|||||||
FISCAL_MODE=DRY_RUN
|
FISCAL_MODE=DRY_RUN
|
||||||
FIREBIRD_WRITES=0
|
FIREBIRD_WRITES=0
|
||||||
POLL_INTERVAL_SECONDS=5
|
POLL_INTERVAL_SECONDS=5
|
||||||
AGENT_VERSION=1.1.6
|
AGENT_VERSION=1.1.7
|
||||||
|
|||||||
@@ -19,4 +19,4 @@ FB_PASSWORD=
|
|||||||
FISCAL_MODE=DRY_RUN
|
FISCAL_MODE=DRY_RUN
|
||||||
FIREBIRD_WRITES=0
|
FIREBIRD_WRITES=0
|
||||||
POLL_INTERVAL_SECONDS=5
|
POLL_INTERVAL_SECONDS=5
|
||||||
AGENT_VERSION=1.1.6
|
AGENT_VERSION=1.1.7
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# GTI Fiscal Hub — production environment (copy to .env, never commit .env)
|
# GTI Fiscal Hub — production environment (copy to .env, never commit .env)
|
||||||
GTI_FISCAL_VERSION=1.1.6
|
GTI_FISCAL_VERSION=1.1.7
|
||||||
|
|
||||||
# REQUIRED. URL-safe secret (used inside a connection URL): openssl rand -hex 24
|
# REQUIRED. URL-safe secret (used inside a connection URL): openssl rand -hex 24
|
||||||
POSTGRES_PASSWORD=
|
POSTGRES_PASSWORD=
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: ../..
|
context: ../..
|
||||||
dockerfile: central/Dockerfile
|
dockerfile: central/Dockerfile
|
||||||
image: gti-fiscal-hub:${GTI_FISCAL_VERSION:-1.1.6}
|
image: gti-fiscal-hub:${GTI_FISCAL_VERSION:-1.1.7}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
|
|||||||
+1
-1
@@ -16,7 +16,7 @@ A variável de ambiente `GTI_SSH_PASSWORD`, se existir, tem prioridade. A senha
|
|||||||
## Deploy
|
## Deploy
|
||||||
```
|
```
|
||||||
powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1
|
powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1
|
||||||
powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1 -PublishAgent -Version 1.1.6
|
powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1 -PublishAgent -Version 1.1.7
|
||||||
```
|
```
|
||||||
Parâmetros: `-Version` (padrão `release/VERSION`), `-PublishAgent`, `-SkipTests`, `-DryRun`.
|
Parâmetros: `-Version` (padrão `release/VERSION`), `-PublishAgent`, `-SkipTests`, `-DryRun`.
|
||||||
|
|
||||||
|
|||||||
@@ -201,7 +201,8 @@ def install_service(install_dir_path: Path) -> None:
|
|||||||
exe = Path(install_dir_path) / "GTIFiscalAgentService" / "GTIFiscalAgentService.exe"
|
exe = Path(install_dir_path) / "GTIFiscalAgentService" / "GTIFiscalAgentService.exe"
|
||||||
bin_path = f"\"{exe}\""
|
bin_path = f"\"{exe}\""
|
||||||
result = _sc(["create", SERVICE_NAME, "binPath=", bin_path, "start=", "auto", "DisplayName=", SERVICE_DISPLAY])
|
result = _sc(["create", SERVICE_NAME, "binPath=", bin_path, "start=", "auto", "DisplayName=", SERVICE_DISPLAY])
|
||||||
if result.returncode != 0 and "already exists" not in (result.stdout + result.stderr):
|
# 1073 = ERROR_SERVICE_EXISTS. Match the code, never the message: the text is localized (pt-BR: "já existe").
|
||||||
|
if result.returncode not in (0, 1073) and "already exists" not in (result.stdout + result.stderr):
|
||||||
raise RuntimeError(f"sc create failed: {result.stdout} {result.stderr}".strip())
|
raise RuntimeError(f"sc create failed: {result.stdout} {result.stderr}".strip())
|
||||||
_sc(["config", SERVICE_NAME, "start=", "delayed-auto"])
|
_sc(["config", SERVICE_NAME, "start=", "delayed-auto"])
|
||||||
_sc(["config", SERVICE_NAME, "obj=", "LocalSystem"])
|
_sc(["config", SERVICE_NAME, "obj=", "LocalSystem"])
|
||||||
|
|||||||
@@ -142,10 +142,15 @@ def upgrade_flow(*, install_dir_path: str | None = None, progress: Callable[[str
|
|||||||
progress("Atualizando o Agent (identidade e credenciais preservadas)…")
|
progress("Atualizando o Agent (identidade e credenciais preservadas)…")
|
||||||
if common.service_installed():
|
if common.service_installed():
|
||||||
common.ensure_service_stopped()
|
common.ensure_service_stopped()
|
||||||
extract_payload(install)
|
try:
|
||||||
common.upgrade_agent_env(install, version)
|
extract_payload(install)
|
||||||
common.install_service(install)
|
common.upgrade_agent_env(install, version)
|
||||||
common.write_arp_uninstall(install)
|
common.install_service(install)
|
||||||
|
common.write_arp_uninstall(install)
|
||||||
|
except Exception as error: # noqa: BLE001 — never leave the host without a running Agent because an upgrade step failed
|
||||||
|
common.ilog(f"upgrade step failed: {error!r}; restarting the existing service")
|
||||||
|
common.start_and_verify(attempts=2)
|
||||||
|
raise
|
||||||
os.environ["AGENT_VERSION"] = version
|
os.environ["AGENT_VERSION"] = version
|
||||||
progress("Iniciando o serviço…")
|
progress("Iniciando o serviço…")
|
||||||
common.ilog(f"upgrade to {version} from {existing.get('agent_id')}")
|
common.ilog(f"upgrade to {version} from {existing.get('agent_id')}")
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
{
|
{
|
||||||
"artifact": "RELEASE_MANIFEST",
|
"artifact": "RELEASE_MANIFEST",
|
||||||
"GTI_FISCAL_VERSION": "1.1.6",
|
"GTI_FISCAL_VERSION": "1.1.7",
|
||||||
"generated_at": "2026-09-24T13:51:44+00:00",
|
"generated_at": "2026-09-24T14:13:15+00:00",
|
||||||
"hub": {
|
"hub": {
|
||||||
"version": "1.1.6",
|
"version": "1.1.7",
|
||||||
"api_compat": "1.0",
|
"api_compat": "1.0",
|
||||||
"engine_version": "0.3.0",
|
"engine_version": "0.3.0",
|
||||||
"decision_version": "mission-04c-ipi-ex-split"
|
"decision_version": "mission-04c-ipi-ex-split"
|
||||||
},
|
},
|
||||||
"agent_version": "1.1.6",
|
"agent_version": "1.1.7",
|
||||||
"fiscal_engine": {
|
"fiscal_engine": {
|
||||||
"ENGINE_VERSION": "0.3.0",
|
"ENGINE_VERSION": "0.3.0",
|
||||||
"DECISION_VERSION": "mission-04c-ipi-ex-split",
|
"DECISION_VERSION": "mission-04c-ipi-ex-split",
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
1.1.6
|
1.1.7
|
||||||
|
|||||||
@@ -14,11 +14,11 @@ sys.path.insert(0, str(ROOT))
|
|||||||
def test_versions_are_coherent_across_hub_agent_and_packages():
|
def test_versions_are_coherent_across_hub_agent_and_packages():
|
||||||
from central.app.version import GTI_FISCAL_VERSION
|
from central.app.version import GTI_FISCAL_VERSION
|
||||||
v = (ROOT / "release" / "VERSION").read_text(encoding="utf-8").strip()
|
v = (ROOT / "release" / "VERSION").read_text(encoding="utf-8").strip()
|
||||||
assert v == GTI_FISCAL_VERSION == "1.1.6"
|
assert v == GTI_FISCAL_VERSION == "1.1.7"
|
||||||
pep = v.replace("-rc", "rc")
|
pep = v.replace("-rc", "rc")
|
||||||
for pp in ("central/pyproject.toml", "agent/pyproject.toml"):
|
for pp in ("central/pyproject.toml", "agent/pyproject.toml"):
|
||||||
assert f'version = "{pep}"' in (ROOT / pp).read_text(encoding="utf-8")
|
assert f'version = "{pep}"' in (ROOT / pp).read_text(encoding="utf-8")
|
||||||
assert '"AGENT_VERSION", "1.1.6"' in (ROOT / "agent" / "scripts" / "run_agent_service.py").read_text(encoding="utf-8")
|
assert '"AGENT_VERSION", "1.1.7"' in (ROOT / "agent" / "scripts" / "run_agent_service.py").read_text(encoding="utf-8")
|
||||||
manifest = ROOT / "release" / "RELEASE_MANIFEST.json"
|
manifest = ROOT / "release" / "RELEASE_MANIFEST.json"
|
||||||
if manifest.exists():
|
if manifest.exists():
|
||||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||||
|
|||||||
@@ -157,3 +157,36 @@ def test_start_and_verify_reports_failure_after_all_attempts(monkeypatch, tmp_pa
|
|||||||
ok, detail = common.start_and_verify(attempts=2, per_attempt=0.01)
|
ok, detail = common.start_and_verify(attempts=2, per_attempt=0.01)
|
||||||
assert not ok and "1053" in detail
|
assert not ok and "1053" in detail
|
||||||
assert "NÃO iniciou" in setup_main.final_message({"service_running": False, "service_detail": detail, "install_dir": "x"})
|
assert "NÃO iniciou" in setup_main.final_message({"service_running": False, "service_detail": detail, "install_dir": "x"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_install_service_tolerates_localized_already_exists(monkeypatch):
|
||||||
|
"""pt-BR Windows says 'já existe', not 'already exists': the return code (1073) must decide."""
|
||||||
|
import subprocess
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def fake_sc(args):
|
||||||
|
seen.append(args[0])
|
||||||
|
if args[0] == "create":
|
||||||
|
return subprocess.CompletedProcess(args, 1073, "[SC] CreateService FALHA 1073: O serviço especificado já existe.", "")
|
||||||
|
if args[0] == "qc":
|
||||||
|
return subprocess.CompletedProcess(args, 0, "START_TYPE : 2 AUTO_START (DELAYED)", "")
|
||||||
|
return subprocess.CompletedProcess(args, 0, "", "")
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "_sc", fake_sc)
|
||||||
|
common.install_service(Path("C:/x"))
|
||||||
|
assert seen[:3] == ["create", "config", "config"] and "failure" in seen
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_upgrade_step_restarts_the_existing_service(world, monkeypatch):
|
||||||
|
calls, inst = world
|
||||||
|
inst.mkdir(parents=True)
|
||||||
|
(inst / "credentials.bin").write_bytes(b"b")
|
||||||
|
(inst / "agent.env").write_text("AGENT_ID=2\nINSTALLATION_ID=x\nGTI_HUB_URL=https://h\n")
|
||||||
|
|
||||||
|
def boom(d):
|
||||||
|
raise RuntimeError("boom")
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "install_service", boom)
|
||||||
|
with pytest.raises(RuntimeError, match="boom"):
|
||||||
|
setup_main.upgrade_flow()
|
||||||
|
assert ("start",) in calls # the Agent was brought back up despite the failure
|
||||||
|
|||||||
Reference in New Issue
Block a user