Files
cx-ui/backend/app/main.py
Parham Monfared 8892144e0a
Some checks failed
build-and-deploy / test (push) Has been cancelled
build-and-deploy / image (push) Has been cancelled
build-and-deploy / deploy (push) Has been cancelled
Add shift handover and RunPod, and make CX-Tools work in a container
Handover
- The Confluence shift doc becomes the landing page: shift metadata, the
  top-of-page checks, key updates with their Zendesk/Jira refs and status, and
  the free-text comments. "Hand over shift" closes the shift, opens the next
  one and carries the live items across, dropping anything done or marked
  "remove at end of shift" - the retyping this replaces.
- The RunPod table on that page is read from live host state instead of being
  copied in by hand, with the six-colour key preserved.

RunPod
- GraphQL client keyed on CX_RUNPOD_API_KEY. The old console login is kept as a
  fallback but cannot run unattended: the account has 2FA, so Clerk verifies the
  password and then asks for an emailed code and never issues a session. That is
  the real cause of the "No active session found" failure, and the client now
  says so instead of failing opaquely. TOTP is supported if the account moves to
  an authenticator app.
- Hosts and their listing history are persisted, so "most problematic hosts" can
  be ranked and each machine has a timeline of who listed or unlisted it, with
  the Zendesk comment and the error hint.
- The unlisting emails are parsed for the error block (they arrive
  quoted-printable) and classified into a likely cause and a next step.

Zendesk and Jira
- Unlisting raises a Zendesk ticket that follows the format of RunPod's own
  email, keyed on the machine so one machine keeps one thread, posted as an
  internal note.
- Jira is split in two: the Infrahub/OIE instance and the RunPod/RMA one, which
  may be a different Atlassian site. Blank RunPod values fall back to the
  defaults rather than failing.

Running in a container
- CX-Tools reads its keys from 1Password, which needs a desktop app. Config is a
  dataclass whose lookups live in per-field default factories, so passing
  CX_INFRAHUB_TOKEN/CX_INFRAINSIGHT_TOKEN in means those factories never run and
  CX-Tools itself stays unmodified.
- CX-Tools reaches OpenStack with `docker exec <region>-osc`, so the image now
  carries the Docker client (the static binary, not the docker.io package) and
  compose mounts the host socket with group_add for it. Verified from inside the
  container: live OpenStack and Infrahub calls both succeed.

Also fixes Settings, which read the environment at class-definition time and so
ignored anything set afterwards; a fresh Settings() silently returned stale
values. Caught by the Jira scoping tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 08:21:59 +01:00

82 lines
2.8 KiB
Python

"""FastAPI application entry point."""
from __future__ import annotations
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import VERSION
from .auth import ensure_bootstrap_admin
from .config import get_settings
from .db import SessionLocal, init_db
from .routers import (actions_router, alerts_router, auth_router, cases_router,
handover_router, linkage_router, runpod_router, settings_router)
settings = get_settings()
def _bool_env(name: str) -> bool:
return str(os.environ.get(name, "")).strip().lower() in {"1", "true", "yes", "on"}
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
db = SessionLocal()
try:
message = ensure_bootstrap_admin(db)
if message:
print(f"[auth] {message}")
finally:
db.close()
if _bool_env("CX_SEED_DEMO"):
db = SessionLocal()
try:
from .seed.loader import run as seed_run
for line in seed_run(db):
print(f"[seed] {line}")
except Exception as exc:
print(f"[seed] skipped: {type(exc).__name__}: {exc}")
finally:
db.close()
print(f"[startup] {settings.app_name} {VERSION}")
print(f"[startup] prometheus: {settings.prometheus_base}")
print(f"[startup] sso: {'on' if settings.oidc_enabled else 'off'} | "
f"zendesk: {'ready' if settings.zendesk_ready else 'off'} | "
f"jira: {'ready' if settings.jira_ready else 'off'} | "
f"sending: {'ENABLED' if settings.feature_send_enabled else 'disabled'}")
alerts_router.engine.warm()
yield
app = FastAPI(title=settings.app_name, version=VERSION, lifespan=lifespan)
for module in (auth_router, alerts_router, cases_router, settings_router,
linkage_router, actions_router, handover_router, runpod_router):
app.include_router(module.router)
@app.get("/api/health")
def health():
return {"status": "ok", "version": VERSION, "config": settings.public_flags()}
# The built React bundle is copied into the image; in development Vite serves it
# instead and proxies /api here, so a missing directory is not an error.
if os.path.isdir(settings.static_dir):
app.mount("/assets", StaticFiles(directory=os.path.join(settings.static_dir, "assets")),
name="assets")
@app.get("/{full_path:path}")
def spa(full_path: str):
if full_path.startswith("api/"):
return JSONResponse({"detail": "Not found"}, status_code=404)
index = os.path.join(settings.static_dir, "index.html")
if os.path.isfile(index):
return FileResponse(index)
return JSONResponse({"detail": "Frontend not built"}, status_code=404)