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>
This commit is contained in:
150
backend/app/seed/loader.py
Normal file
150
backend/app/seed/loader.py
Normal file
@@ -0,0 +1,150 @@
|
||||
"""Populate an empty database with representative data.
|
||||
|
||||
Runs on startup when CX_SEED_DEMO is on, and only when the relevant table is
|
||||
empty, so it never overwrites real work.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import (AppSetting, Handover, HandoverItem, HandoverStatus, ItemState,
|
||||
RunpodColour, RunpodEventType, RunpodHost, ShiftName)
|
||||
from ..runpod.service import record_event
|
||||
from .data import HANDOVER, RUNPOD_BOARD, RUNPOD_COLOURS
|
||||
|
||||
# Optional: the monitoring script's own exports, if they have been mounted in.
|
||||
RUNPOD_EXPORT_DIR = os.environ.get("CX_RUNPOD_EXPORT_DIR", "/seed/runpod")
|
||||
|
||||
|
||||
def seed_handover(db: Session) -> str:
|
||||
if db.scalar(select(Handover).limit(1)):
|
||||
return "handover: already present, left alone"
|
||||
|
||||
row = Handover(
|
||||
shift_date=dt.date.fromisoformat(HANDOVER["shift_date"]),
|
||||
shift=ShiftName(HANDOVER["shift"]),
|
||||
handing_to=HANDOVER["handing_to"],
|
||||
team_members=HANDOVER["team_members"],
|
||||
significant_issues_checked=HANDOVER["significant_issues_checked"],
|
||||
hubspot_checked=HANDOVER["hubspot_checked"],
|
||||
total_open_tickets=HANDOVER["total_open_tickets"],
|
||||
member_checks=HANDOVER["member_checks"],
|
||||
other_comments=HANDOVER["other_comments"],
|
||||
status=HandoverStatus.DRAFT,
|
||||
)
|
||||
for position, item in enumerate(HANDOVER["items"]):
|
||||
row.items.append(HandoverItem(
|
||||
position=position, title=item["title"],
|
||||
zendesk_tickets=item.get("zendesk_tickets", ""),
|
||||
jira_key=item.get("jira_key", ""), jira_status=item.get("jira_status", ""),
|
||||
body=item.get("body", ""), links=item.get("links", []),
|
||||
state=ItemState(item.get("state", "in_progress")),
|
||||
remove_at_end_of_shift=item.get("remove_at_end_of_shift", False),
|
||||
first_raised_on=row.shift_date,
|
||||
))
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return f"handover: seeded {row.shift.value} {row.shift_date} with {len(row.items)} items"
|
||||
|
||||
|
||||
def _load_export(name: str):
|
||||
path = Path(RUNPOD_EXPORT_DIR) / name
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
return json.loads(path.read_text())
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
|
||||
|
||||
def seed_runpod(db: Session) -> str:
|
||||
if db.scalar(select(RunpodHost).limit(1)):
|
||||
return "runpod: already present, left alone"
|
||||
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
rng = random.Random(20260806) # deterministic, so the demo looks the same each time
|
||||
hosts: dict[str, RunpodHost] = {}
|
||||
|
||||
# 1. The board rows from the handover, with their CX state.
|
||||
for entry in RUNPOD_BOARD:
|
||||
host = RunpodHost(
|
||||
machine_id=entry["machine_id"], name=entry["name"], listed=False,
|
||||
gpu_reserved=0, gpu_total=8, gpu_type="RTX 5090" if "5090" in entry["name"] else "RTX 4090",
|
||||
data_center="NO1" if entry["name"].startswith("no1") else "CA1",
|
||||
colour=RunpodColour(entry.get("colour", "white")),
|
||||
zendesk_ticket=entry.get("zendesk_ticket", ""),
|
||||
jira_key=entry.get("jira_key", ""), jira_status=entry.get("jira_status", ""),
|
||||
last_error=entry.get("last_error", ""), next_steps=entry.get("next_steps", ""),
|
||||
unlisted_at=now - dt.timedelta(hours=rng.randint(6, 96)),
|
||||
)
|
||||
db.add(host)
|
||||
db.flush()
|
||||
hosts[host.machine_id] = host
|
||||
|
||||
# 2. Anything else the monitoring script had recorded.
|
||||
hosts_db = _load_export("hosts_db.json") or {}
|
||||
jira_db = _load_export("jira_db.json") or {}
|
||||
for machine_id, record in list(hosts_db.items())[:200]:
|
||||
if machine_id in hosts:
|
||||
continue
|
||||
jira = jira_db.get(machine_id, {})
|
||||
host = RunpodHost(
|
||||
machine_id=machine_id, name=str(record.get("name") or ""),
|
||||
listed=bool(record.get("listed", True)),
|
||||
gpu_reserved=int(record.get("gpuReserved") or 0), gpu_total=8,
|
||||
historic_count=int(jira.get("historic_count") or 0),
|
||||
jira_key=jira.get("jira_issue_key") or "", jira_status=jira.get("jira_status") or "",
|
||||
)
|
||||
if not host.listed:
|
||||
host.unlisted_at = now - dt.timedelta(hours=rng.randint(2, 240))
|
||||
db.add(host)
|
||||
db.flush()
|
||||
hosts[machine_id] = host
|
||||
|
||||
# 3. A plausible history, so the timeline and ranking have something to show.
|
||||
for host in hosts.values():
|
||||
rounds = max(host.historic_count, 1 if not host.listed else 0)
|
||||
cursor = now - dt.timedelta(days=min(45, 3 + rounds * 4))
|
||||
for _ in range(min(rounds, 12)):
|
||||
cursor += dt.timedelta(hours=rng.randint(8, 72))
|
||||
if cursor >= now:
|
||||
break
|
||||
record_event(db, host, RunpodEventType.UNLISTED, actor="runpod",
|
||||
detail="Unlisted automatically after a critical error",
|
||||
error_hint=host.last_error or "gpu health check failed",
|
||||
gpu_reserved=rng.choice([0, 1, 2, 8]))
|
||||
host.events[-1].occurred_at = cursor
|
||||
host.unlist_count += 1
|
||||
|
||||
cursor += dt.timedelta(hours=rng.randint(4, 48))
|
||||
if cursor >= now or not host.listed:
|
||||
continue
|
||||
operator = rng.choice(["parham.monfared@nexgencloud.com", "luis.sarabando@nexgencloud.com",
|
||||
"kheano.martinez@nexgencloud.com"])
|
||||
record_event(db, host, RunpodEventType.LISTED, actor=operator,
|
||||
detail="Relisted after burn-in passed",
|
||||
zendesk_ticket=host.zendesk_ticket)
|
||||
host.events[-1].occurred_at = cursor
|
||||
|
||||
if not host.listed and host.last_error:
|
||||
record_event(db, host, RunpodEventType.UNLISTED, actor="runpod",
|
||||
detail="Current unlisting", error_hint=host.last_error,
|
||||
zendesk_ticket=host.zendesk_ticket, jira_key=host.jira_key)
|
||||
host.events[-1].occurred_at = host.unlisted_at or now
|
||||
host.unlist_count += 1
|
||||
|
||||
db.merge(AppSetting(key="runpod_colours", value=RUNPOD_COLOURS))
|
||||
db.commit()
|
||||
unlisted = sum(1 for h in hosts.values() if not h.listed)
|
||||
return f"runpod: seeded {len(hosts)} machines ({unlisted} unlisted) with history"
|
||||
|
||||
|
||||
def run(db: Session) -> list[str]:
|
||||
return [seed_handover(db), seed_runpod(db)]
|
||||
Reference in New Issue
Block a user