Split into a FastAPI backend and a React frontend, add case state and SSO
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

The single-file stdlib server became the limit: no way to track what had been
done about an alert, no accounts, and a UI that had to be hand-rolled in
template strings. This restructures it into something deployable.

Backend (FastAPI)
- app/ holds config, database, auth, delivery and the routers; triagelib keeps
  the triage engine unchanged, so the validated screening and runbook logic is
  untouched.
- Cases persist per alert fingerprint with a status workflow (investigating,
  customer contacted, escalated to Infra, waiting, remediated, resolved, won't
  fix, false positive), an assignee, notes and an append-only history. An alert
  that stops and re-fires lands back on the same case and counts as a reopen.
- Suppression rules move from a JSON file into the database.

Auth
- Signed session cookies over PBKDF2 local accounts, plus an OIDC flow ready for
  Authentik: users are created on first login and admin follows a group claim.
  Local login can be switched off entirely once SSO is live.

Zendesk and Jira
- Delivery is now implemented, behind three gates: the integration must be
  configured, its feature flag on, and CX_FEATURE_SEND_ENABLED on. A demo
  instance leaves the last off and cannot mail anyone. Both search before
  creating, so re-diagnosing an alert updates one ticket rather than opening
  several, and a rolling daily cap stops a loop mailing everybody.

Deployment
- Multi-stage Dockerfile builds the bundle and serves it from the API origin.
- docker-compose for local and single-host use; Gitea Actions runs the tests,
  builds the image and renders deploy/k8s with envsubst.

Two fixes found while testing: assigning a case returned a null assignee, and
add_event could leave an already-loaded history collection stale.

Known gap: the engine reaches OpenStack via `docker exec <region>-osc`, which
does not work in a pod without the CX-Tools containers alongside it.
docs/DEPLOYMENT.md sets out the three ways to close that.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-06 07:11:28 +01:00
parent a039e0b5fd
commit 1262690276
68 changed files with 3839 additions and 2223 deletions

View File

@@ -0,0 +1,4 @@
"""CX Triage: read-only alert diagnosis on top of the CX-Tools (vmc) collectors."""
from __future__ import annotations
VERSION = "cx-triage 0.1"

421
backend/triagelib/alerts.py Normal file
View File

@@ -0,0 +1,421 @@
"""Normalizes Prometheus alerts into the alert kinds the CX runbooks cover."""
from __future__ import annotations
import datetime as dt
import hashlib
import re
from dataclasses import dataclass, field
from typing import Any, Optional
EMOJI_RE = re.compile(r":[a-z0-9_+\-]+:")
THRESHOLD_RE = re.compile(r"greater than\s*(\d+)\s*min", re.I)
ORG_RE = re.compile(r"^\s*(\d+)\s*-\s*(.*)$")
NONE_VALUES = {"", "none", "null", "unknown", "n/a"}
# Alerts excluded outright. "Exists in Infrahub but does not exist in OpenStack"
# is built as `Resources unless on(openstack_id) openstack_nova_server_status`,
# and that right-hand metric is currently empty - so every Infrahub VM matches
# and the alert fires thousands of times. It is a monitoring fault, not a queue
# of work, so it never reaches the UI.
EXCLUDED_ALERTNAMES = frozenset({
"Exists in Infrahub but does not exist in OpenStack",
})
# Rule files whose alerts belong to CX. Everything else is infrastructure.
CX_RULE_FILES = ("infrahub-rules",)
NODE_RULE_FILE = "node-exporter-rules.yml"
# The order CX wants to work the queue in.
FOCUS_ORDER = (
"rogue_vm", "duplicate_ip", "total_gpus", "hibernating",
"creating", "shutoff", "deleting", "error",
"restoring", "rebooting", "build", "orphan_vm", "status_mismatch",
)
# Priority and estimated time to resolve, from the "Infrahub Errors
# Remediation" alert-conditions and runbook tables.
KIND_META: dict[str, dict[str, str]] = {
"error": {"title": "Instance in ERROR state", "priority": "LOW-HIGH", "ettr": "5-30 min", "delay": "none"},
"deleting": {"title": "Instance in DELETING state", "priority": "LOW", "ettr": "5-15 min", "delay": "30 min"},
"shutoff": {"title": "Instance in SHUTOFF state", "priority": "LOW", "ettr": "5-10 min", "delay": "30 min"},
"hibernating": {"title": "Instance in HIBERNATING state", "priority": "HIGH", "ettr": "5-30 min", "delay": "30 min"},
"creating": {"title": "Instance in CREATING state", "priority": "MEDIUM", "ettr": "5-15 min", "delay": "30 min"},
"restoring": {"title": "Instance in RESTORING state", "priority": "HIGH", "ettr": "5-15 min", "delay": "30 min"},
"rebooting": {"title": "Instance in REBOOTING state", "priority": "HIGH", "ettr": "5-15 min", "delay": "30 min"},
"build": {"title": "Instance in BUILD state", "priority": "MEDIUM", "ettr": "5-15 min", "delay": "30 min"},
"rogue_vm": {"title": "Suspected Rogue VM", "priority": "HIGH", "ettr": "5-30 min", "delay": "4 hours"},
"duplicate_ip": {"title": "Duplicated IPs", "priority": "HIGH", "ettr": "5-15 min", "delay": "10 min"},
"total_gpus": {"title": "Problem with Total GPUs in a System", "priority": "HIGH", "ettr": "5-15 min", "delay": "5 min"},
"orphan_vm": {"title": "Suspected Orphan VM", "priority": "HIGH", "ettr": "5-30 min", "delay": "4 hours"},
"status_mismatch": {"title": "Infrahub/OpenStack status mismatch", "priority": "HIGH", "ettr": "5-30 min", "delay": "30 min"},
}
STATE_KINDS = ("error", "deleting", "shutoff", "hibernating", "creating", "restoring", "rebooting", "build")
def clean_alertname(name: str) -> str:
"""Strip the Slack emoji shortcodes Prometheus embeds in alert names."""
return EMOJI_RE.sub("", str(name or "")).strip()
def classify(alertname: str) -> str:
name = clean_alertname(alertname).lower()
if alertname in EXCLUDED_ALERTNAMES or clean_alertname(alertname) in EXCLUDED_ALERTNAMES:
return "excluded"
if "rogue vm" in name:
return "rogue_vm"
if "orphan vm" in name:
return "orphan_vm"
if "duplicated ip" in name or "duplicate ip" in name:
return "duplicate_ip"
if "total gpus" in name:
return "total_gpus"
match = re.search(r"instance in (\w+) state", name)
if match:
state = match.group(1).lower()
if state in STATE_KINDS:
return state
# The per-region cross-check rules, e.g.
# "Openstack status=SHUTOFF and Infrahub status!=SHUTOFF in CANADA-1".
if "failure of hibernation" in name:
return "hibernating"
if "openstack status=" in name and "infrahub status" in name:
return "status_mismatch"
return "other"
def category(alertname: str, rule_file: str = "") -> str:
"""Which tab an alert belongs in: 'cx', 'node', or 'infra'."""
if any(token in rule_file for token in CX_RULE_FILES):
return "cx"
if rule_file == NODE_RULE_FILE:
return "node"
if rule_file:
return "infra"
# No rule metadata (e.g. a pasted alert): fall back to the classifier.
return "cx" if classify(alertname) not in ("other", "excluded") else "infra"
def _clean(value: Any) -> str:
text = str(value or "").strip()
return "" if text.lower() in NONE_VALUES else text
def split_organization(value: str) -> tuple[str, str]:
"""Split the `organization` label ("8463 - Some Org") into id and name."""
match = ORG_RE.match(str(value or ""))
if match:
return match.group(1), match.group(2).strip()
return "", _clean(value)
def _parse_active_at(value: Any) -> Optional[dt.datetime]:
text = str(value or "").strip()
if not text:
return None
text = re.sub(r"(\.\d{1,6})\d*Z?$", r"\1", text.replace("Z", "+00:00"))
if text.endswith("+00:00") is False and "+" not in text[10:]:
text += "+00:00"
try:
return dt.datetime.fromisoformat(text)
except ValueError:
return None
@dataclass
class Alert:
"""One normalized Prometheus alert."""
kind: str
alertname: str
labels: dict[str, str] = field(default_factory=dict)
annotations: dict[str, str] = field(default_factory=dict)
state: str = "firing"
active_at: Optional[dt.datetime] = None
# Fields the runbooks key off.
openstack_id: str = ""
instance_name: str = ""
host: str = ""
region_label: str = ""
region: str = ""
status: str = ""
floating_ip: str = ""
flavor_name: str = ""
flavor_gpu: str = ""
org_id: str = ""
org_name: str = ""
contract_id: str = ""
gpu_name: str = ""
threshold_min: Optional[int] = None
# Where the rule came from (from RuleIndex), and the screening result.
rule_file: str = ""
rule_group: str = ""
for_seconds: int = 0
category: str = "cx"
screen: dict[str, Any] = field(default_factory=dict)
# How long the condition has actually held, recovered from ALERTS history.
# activeAt alone is unreliable: a metric-pipeline dip resets it on every
# live alert at once, which is why raw ages cluster on one timestamp.
true_age_minutes: Optional[int] = None
true_age_capped: bool = False
@property
def title(self) -> str:
return KIND_META.get(self.kind, {}).get("title", clean_alertname(self.alertname))
@property
def priority(self) -> str:
return KIND_META.get(self.kind, {}).get("priority", "UNKNOWN")
@property
def ettr(self) -> str:
return KIND_META.get(self.kind, {}).get("ettr", "unknown")
@property
def is_kubernetes(self) -> bool:
"""Per the general process: kube* instance names are likely K8s nodes."""
return self.instance_name.lower().startswith("kube") or "-minion-" in self.instance_name.lower()
@property
def age_minutes(self) -> Optional[int]:
if not self.active_at:
return None
now = dt.datetime.now(dt.timezone.utc)
return max(0, int((now - self.active_at).total_seconds() // 60))
@staticmethod
def _duration_text(minutes: Optional[int]) -> str:
if minutes is None:
return "unknown"
if minutes < 60:
return f"{minutes}m"
hours, mins = divmod(minutes, 60)
if hours < 24:
return f"{hours}h {mins}m" if mins else f"{hours}h"
days, hours = divmod(hours, 24)
return f"{days}d {hours}h" if hours else f"{days}d"
@property
def age_text(self) -> str:
"""Raw Prometheus activeAt duration."""
return self._duration_text(self.age_minutes)
@property
def effective_age_minutes(self) -> Optional[int]:
"""True condition duration where known, else the raw activeAt age."""
return self.true_age_minutes if self.true_age_minutes is not None else self.age_minutes
@property
def effective_age_text(self) -> str:
text = self._duration_text(self.effective_age_minutes)
if self.true_age_minutes is not None and self.true_age_capped:
return f"{text}+"
return text
@property
def age_is_reset(self) -> bool:
"""True when activeAt materially understates how long this has held."""
if self.true_age_minutes is None or self.age_minutes is None:
return False
return self.true_age_minutes - self.age_minutes > 60
@property
def is_internal_org(self) -> bool:
"""Internal/test organizations are not customer-impacting."""
return "nexgencloud.com" in self.org_name.lower()
@property
def is_infra_owned(self) -> bool:
"""Platform-owned nodes (storage etc.) name themselves after their host."""
return bool(self.instance_name) and self.instance_name.lower() == self.host.lower()
def fingerprint(self) -> str:
basis = "|".join([
self.kind,
self.openstack_id or self.instance_name or "",
self.host,
self.floating_ip,
self.region,
])
return hashlib.sha1(basis.encode()).hexdigest()[:16]
def to_json(self) -> dict[str, Any]:
return {
"id": self.fingerprint(),
"kind": self.kind,
"title": self.title,
"alertname": clean_alertname(self.alertname),
"raw_alertname": self.alertname,
"state": self.state,
"priority": self.priority,
"ettr": self.ettr,
"active_at": self.active_at.isoformat() if self.active_at else "",
"age_minutes": self.age_minutes,
"age_text": self.age_text,
"true_age_minutes": self.true_age_minutes,
"true_age_capped": self.true_age_capped,
"effective_age_minutes": self.effective_age_minutes,
"effective_age_text": self.effective_age_text,
"age_is_reset": self.age_is_reset,
"threshold_min": self.threshold_min,
"rule_file": self.rule_file,
"rule_group": self.rule_group,
"for_seconds": self.for_seconds,
"category": self.category,
"screen": self.screen,
"is_internal_org": self.is_internal_org,
"is_infra_owned": self.is_infra_owned,
"openstack_id": self.openstack_id,
"instance_name": self.instance_name,
"host": self.host,
"region": self.region,
"region_label": self.region_label,
"status": self.status,
"floating_ip": self.floating_ip,
"flavor_name": self.flavor_name,
"flavor_gpu": self.flavor_gpu,
"gpu_name": self.gpu_name,
"org_id": self.org_id,
"org_name": self.org_name,
"contract_id": self.contract_id,
"is_kubernetes": self.is_kubernetes,
"labels": self.labels,
"annotations": self.annotations,
}
def map_region(region_label: str) -> str:
"""CANADA-1 -> ca1.
Deliberately a local table rather than a call into CX-Tools: building the
alert queue must not touch cxlib, because constructing a CX-Tools Config
loads credentials and would pop a 1Password prompt just to list alerts.
Kept in sync with SUPPORTED_REGIONS in cxlib/constants.py.
"""
fallback = {
"canada-1": "ca1", "canada-2": "ca2", "us-1": "us1", "norway-1": "no1",
"ca-1": "ca1", "ca-2": "ca2", "no-1": "no1",
"ca1": "ca1", "ca2": "ca2", "us1": "us1", "no1": "no1",
}
return fallback.get(str(region_label or "").strip().lower(), "")
def from_labels(labels: dict[str, str], annotations: Optional[dict[str, str]] = None,
state: str = "firing", active_at: Any = None) -> Alert:
labels = {str(k): str(v) for k, v in (labels or {}).items()}
alertname = labels.get("alertname", "")
kind = classify(alertname)
region_label = _clean(labels.get("region"))
org_id, org_name = split_organization(labels.get("organization", ""))
threshold = THRESHOLD_RE.search(alertname)
# For host-scoped alerts the `instance` label is the hypervisor; for
# VM-scoped alerts it is the hypervisor too, or "Unknown" when the VM never
# landed on a host.
host = _clean(labels.get("instance"))
alert = Alert(
kind=kind,
alertname=alertname,
labels=labels,
annotations={str(k): str(v) for k, v in (annotations or {}).items()},
state=str(state or "firing"),
active_at=_parse_active_at(active_at),
openstack_id=_clean(labels.get("openstack_id")),
instance_name=_clean(labels.get("instance_name")),
host=host,
region_label=region_label,
region=map_region(region_label) or _infer_region_from_host(host),
status=_clean(labels.get("status")),
floating_ip=_clean(labels.get("floating_ip")),
flavor_name=_clean(labels.get("flavor_name")),
flavor_gpu=_clean(labels.get("flavor_gpu")),
gpu_name=_clean(labels.get("gpu_name")),
org_id=org_id,
org_name=org_name,
contract_id=_clean(labels.get("contract_id")),
threshold_min=int(threshold.group(1)) if threshold else None,
)
return alert
def _infer_region_from_host(host: str) -> str:
match = re.match(r"^(ca1|ca2|no1|us1)-", str(host or "").strip(), re.I)
return match.group(1).lower() if match else ""
def from_prometheus(raw: dict[str, Any], rule_index: Any = None, true_age: Any = None) -> Alert:
alert = from_labels(
raw.get("labels") or {},
raw.get("annotations") or {},
state=str(raw.get("state") or "firing"),
active_at=raw.get("activeAt"),
)
meta = rule_index.get(alert.alertname) if rule_index is not None else {}
if meta:
alert.rule_file = str(meta.get("file") or "")
alert.rule_group = str(meta.get("group") or "")
alert.for_seconds = int(meta.get("for_seconds") or 0)
alert.category = category(alert.alertname, alert.rule_file)
if true_age is not None:
alert.true_age_minutes, alert.true_age_capped = true_age.lookup(alert.labels)
return alert
def cx_relevant(alert: Alert) -> bool:
"""True for alert kinds the CX runbooks cover."""
return alert.kind in KIND_META and alert.kind != "excluded"
def is_excluded(alert: Alert) -> bool:
return alert.kind == "excluded" or alert.alertname in EXCLUDED_ALERTNAMES
def sort_key(alert: Alert) -> tuple:
"""Newest first: a fresh alert is the one that still needs a decision.
Long-running alerts sink to the bottom - they are either chronic and
already ticketed, or noise nobody has silenced. Alerts with no known start
time sort last rather than jumping to the top.
Sorted on the true condition duration, not activeAt: a pipeline dip resets
activeAt on every live alert at once, which would otherwise flatten the
ordering into a single tie.
"""
age = alert.effective_age_minutes
return (age if age is not None else 10**9, alert.title)
def focus_rank(kind: str) -> int:
try:
return FOCUS_ORDER.index(kind)
except ValueError:
return len(FOCUS_ORDER)
def group_alerts(items: list[Alert]) -> list[dict[str, Any]]:
"""Group alerts into collapsible sections, in CX's working order."""
buckets: dict[str, list[Alert]] = {}
for alert in items:
buckets.setdefault(alert.kind, []).append(alert)
groups: list[dict[str, Any]] = []
for kind, members in buckets.items():
members.sort(key=sort_key)
actionable = [a for a in members if a.screen.get("actionable", True)]
groups.append({
"kind": kind,
"title": KIND_META.get(kind, {}).get("title", kind),
"priority": KIND_META.get(kind, {}).get("priority", "UNKNOWN"),
"ettr": KIND_META.get(kind, {}).get("ettr", "unknown"),
"total": len(members),
"actionable": len(actionable),
"noise": len(members) - len(actionable),
"alerts": [a.to_json() for a in members],
})
groups.sort(key=lambda g: (focus_rank(g["kind"]), -g["actionable"]))
return groups

383
backend/triagelib/comms.py Normal file
View File

@@ -0,0 +1,383 @@
"""Customer comms templates, transcribed from the CX runbooks.
Wording is kept verbatim from Confluence so what CX sends stays consistent with
the approved snippets; only the named placeholders are substituted. Nothing here
sends anything - the app renders the draft for a human to review and send from
HubSpot.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Optional
INSTANCE_PLACEHOLDER = "INFRAHUB_INSTANCE_NAME"
FIP_PLACEHOLDER = "NEW_INFRAHUB_FLOATING_IP"
ID_PLACEHOLDER = "INFRAHUB_ID"
OSID_PLACEHOLDER = "OPENSTACK_ID"
NAME_PLACEHOLDER = "GREETING_NAME"
AGENT_PLACEHOLDER = "AGENT_NAME"
def first_name(owner: str) -> str:
"""'Bojan Jovanovic <bojan@polycam.ai>' -> 'Bojan'.
Falls back to an empty greeting rather than guessing: the examples show
'Hello,' is acceptable, but 'Hello shettyatulya@gmail.com,' is not.
"""
text = str(owner or "").split("<", 1)[0].strip()
if not text or "@" in text:
return ""
first = text.split()[0]
return first if first[:1].isalpha() else ""
@dataclass
class Draft:
template_id: str
label: str
subject: str
body: str
channel: str = "HubSpot ticket"
when: str = ""
unfilled: list[str] = field(default_factory=list)
source: str = ""
def to_json(self) -> dict[str, Any]:
return {
"template_id": self.template_id,
"label": self.label,
"subject": self.subject,
"body": self.body,
"channel": self.channel,
"when": self.when,
"unfilled": self.unfilled,
"source": self.source,
}
# Wording follows the house style CX actually sends: first-name greeting, the VM
# named with its Infrahub ID, an explicit "you will not be charged" line, the
# billing-states link, and a personal sign-off. Placeholders are substituted;
# everything else is left alone so what goes out stays consistent.
BILLING_DOC = ("Here is our documentation on VM states and their cost:\n"
"Which virtual machine states incur billing costs?")
STOCK_DOC = ("You can use our Stock API to check availability at the time of deploying a VM here - "
"Stock Availability")
_TEMPLATES: dict[str, dict[str, str]] = {
"error_never_active": {
"label": "ERROR - never deployed (transient stock issue)",
"subject": "VM in Error state",
"when": "The instance never reached a host, so nothing was built. Recommend delete and retry.",
"source": "Instance in ERROR state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
Due to a transient stock issue this VM never fully deployed and is currently showing in Error.
Our recommendation would be to delete the VM and try recreating a new one. Please be aware that whilst the VM is in an Error state you will not be charged for its usage.
{BILLING_DOC}
{STOCK_DOC}
Just so you are aware, if the VM is not deleted after 14 calendar days we will proceed with deleting the VM on your behalf.
Kind Regards,
AGENT_NAME""",
},
"error_was_active": {
"label": "ERROR - VM had been running, escalated",
"subject": "VM in Error state",
"when": "The instance had reached ACTIVE, so customer data may be involved. Escalate first, then send.",
"source": "Instance in ERROR state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
We can see this VM has gone into an Error state. We have escalated this to the appropriate team on your behalf and will come back to you as soon as we have more information.
Please be assured that whilst a VM is in an Error state you will not be charged for its usage.
{BILLING_DOC}
Kind Regards,
AGENT_NAME""",
},
"creating": {
"label": "CREATING - stuck on deploy, VM deleted for the customer",
"subject": "VM stuck in creating state",
"when": "Send after the stuck instance has been deleted.",
"source": "Instance in CREATING state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM INFRAHUB_INSTANCE_NAME (INFRAHUB_ID).
We can see you tried to deploy this VM but due to a transient error the VM got stuck in a creating state.
Unfortunately as the VM was not able to fully deploy, the safest option was to delete the VM which we have actioned for you.
Please be assured that whilst a VM is in a creating state you will not be charged for it's usage.
{BILLING_DOC}
If you have any queries please let us know.
Kind Regards,
AGENT_NAME""",
},
"deleting": {
"label": "DELETING - stuck delete finalised for the customer",
"subject": "VM stuck in deleting state",
"when": "Send once the delete has actually been finalised.",
"source": "Instance in DELETING state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
We can see one of your users requested the deletion and that due to a transient error the VM got stuck in a deleting state. I wanted to make sure you are aware that we have gone and finalised the deletion for you.
Please be assured that whilst a VM is in a deleting state you will not be charged for it's usage.
{BILLING_DOC}
Kind Regards,
AGENT_NAME""",
},
"deleting_resolved": {
"label": "DELETING - confirming resolution and closing the ticket",
"subject": "VM deleted - closing this ticket",
"when": "Use when replying on an existing ticket that can now be closed.",
"source": "Instance in DELETING state",
"body": """Hello GREETING_NAME,
Upon reviewing this ticket, we found that the VM below, which was previously stuck in a DELETING state, has now been deleted:
* OPENSTACK_ID (INFRAHUB_ID)
As the VM has been deleted, we are marking the issue as resolved and closing this ticket.
If you require further assistance, please feel free to contact us at support@hyperstack.cloud or open a new Live Chat via the Hyperstack Console.
Have a great rest of your day and thank you for using Hyperstack.
Kind regards,
AGENT_NAME""",
},
"build": {
"label": "BUILD - failed to build, escalated",
"subject": "VM stuck in build state",
"when": "Send once escalated to Infrastructure. The instance must be recreated.",
"source": "Instance in BUILD state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM INFRAHUB_INSTANCE_NAME (INFRAHUB_ID).
We can see you tried to deploy this VM but due to a transient error it did not finish building. We have escalated this on your behalf and ask that you retry creating the instance at your convenience.
Please be assured that whilst a VM is in this state you will not be charged for it's usage.
{BILLING_DOC}
If you have any queries please let us know.
Kind Regards,
AGENT_NAME""",
},
"rebooting": {
"label": "REBOOTING - reboot failed, now resolved",
"subject": "VM stuck rebooting",
"when": "Send only once the instance is confirmed ACTIVE in both Infrahub and OpenStack.",
"source": "Instance in REBOOTING state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM INFRAHUB_INSTANCE_NAME (INFRAHUB_ID).
We can see a reboot was requested but due to a transient error the VM got stuck. This has now been resolved and you may retry rebooting at your convenience.
{BILLING_DOC}
If you have any queries please let us know.
Kind Regards,
AGENT_NAME""",
},
"restoring": {
"label": "RESTORING - restore failed, now resolved",
"subject": "VM stuck restoring",
"when": "Send after the instance is back to SHELVED_OFFLOADED in OpenStack and HIBERNATED in Infrahub.",
"source": "Instance in RESTORING state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM INFRAHUB_INSTANCE_NAME (INFRAHUB_ID).
We can see you tried to restore this VM but due to a transient error it got stuck. This has now been resolved and you may retry restoring at your convenience.
{BILLING_DOC}
If you have any queries please let us know.
Kind Regards,
AGENT_NAME""",
},
"shutoff": {
"label": "SHUTOFF - billing awareness notice",
"subject": "VM in SHUT-OFF state is still accruing costs",
"when": "Send as-is. A HubSpot snippet also exists: type #shutoff.",
"source": "Instance in SHUTOFF state",
"body": f"""Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
We can see that this is in a SHUT-OFF state and wanted to make sure you are aware that in this state the VM is still accruing full costs.
{BILLING_DOC}
Kind Regards,
AGENT_NAME""",
},
"dupip_removed": {
"label": "Duplicated IP - incorrect IP removed, customer must attach a new one",
"subject": "Instance assigned an incorrect public IP",
"when": "The VM has no floating IP in OpenStack and the stale IP was removed in InfraInsight.",
"source": "Duplicated IPs",
"body": """Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
Due to a transient synchronisation issue this instance was showing an incorrect public IP. This has now been corrected. To restore external connectivity the instance will need a new public IP attached, which you can do at your convenience using either the Hyperstack UI or API.
We apologise for any inconvenience this may have caused.
Kind Regards,
AGENT_NAME""",
},
"dupip_corrected": {
"label": "Duplicated IP - Infrahub corrected to match OpenStack",
"subject": "Instance assigned an incorrect public IP",
"when": "The VM does have a floating IP in OpenStack and Infrahub was corrected to match.",
"source": "Duplicated IPs",
"body": """Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
Due to a transient synchronisation issue this instance was showing an incorrect public IP. This has now been resolved and your instance is reachable at NEW_INFRAHUB_FLOATING_IP.
We apologise for any inconvenience this may have caused.
Kind Regards,
AGENT_NAME""",
},
"sync_state": {
"label": "Rogue VM - instance was in the incorrect state",
"subject": "VM was showing an incorrect state",
"when": "Send after the state mismatch has been remediated.",
"source": "Suspected Rogue VM",
"body": """Hello GREETING_NAME,
We hope you are well.
We are emailing you in regards to VM: INFRAHUB_INSTANCE_NAME (INFRAHUB_ID)
Due to a transient sync error this instance was showing an incorrect state. This has since been resolved, and we ask that you retry any operations that failed as a result.
We apologise for any delay this may have caused.
Kind Regards,
AGENT_NAME""",
},
}
def draft(template_id: str, *, instance_name: str = "", floating_ip: str = "",
infrahub_id: str = "", openstack_id: str = "", greeting_name: str = "",
agent_name: str = "", note: Optional[str] = None) -> Optional[Draft]:
spec = _TEMPLATES.get(template_id)
if not spec:
return None
body = spec["body"]
unfilled: list[str] = []
# "Hello Bojan," when we know the name, "Hello," when we do not - never
# "Hello <placeholder>,".
body = body.replace(f"Hello {NAME_PLACEHOLDER},", f"Hello {greeting_name}," if greeting_name else "Hello,")
substitutions = {
INSTANCE_PLACEHOLDER: instance_name,
ID_PLACEHOLDER: infrahub_id,
OSID_PLACEHOLDER: openstack_id,
FIP_PLACEHOLDER: floating_ip,
AGENT_PLACEHOLDER: agent_name,
}
for placeholder, value in substitutions.items():
if placeholder not in body:
continue
if value and value not in ("N/A", "None"):
body = body.replace(placeholder, str(value))
else:
unfilled.append(placeholder)
# "(INFRAHUB_ID)" with nothing to put in it reads worse than no bracket.
if ID_PLACEHOLDER in unfilled:
body = body.replace(f" ({ID_PLACEHOLDER})", "").replace(f"({ID_PLACEHOLDER})", "")
unfilled.remove(ID_PLACEHOLDER)
when = spec["when"]
if note:
when = f"{when} {note}".strip()
return Draft(
template_id=template_id,
label=spec["label"],
subject=spec["subject"],
body=body,
when=when,
unfilled=unfilled,
source=spec["source"],
)
def contacts_from_result(result: dict[str, Any]) -> dict[str, Any]:
"""Pull the organization and owner contacts CX-Tools resolved for a VM."""
if not isinstance(result, dict):
return {"organization": "", "owners": [], "resolved": False}
org = str(result.get("org_value") or "").strip()
owners = [str(x) for x in (result.get("owners") or []) if str(x).strip()]
return {
"organization": org if org and org != "N/A" else "",
"owners": owners,
"resolved": bool(owners),
}

View File

@@ -0,0 +1,286 @@
"""Read-only adapter over the CX-Tools (vmc) collectors.
CX-Tools is imported as an unmodified library: this module never writes to the
CX-Tools tree and only calls collectors and query helpers that read. Every
OpenStack subcommand this module can reach is checked against READ_ONLY_VERBS
before it runs, so a bug here cannot mutate a live instance.
"""
from __future__ import annotations
import os
import sys
import threading
from typing import Any, Optional
DEFAULT_CX_TOOLS_PATHS = (
os.environ.get("CX_TOOLS_PATH", ""),
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "CX-Tools"),
os.path.expanduser("~/scripts/CX-Tools"),
os.path.expanduser("~/scripts/cx-tooling"),
)
# OpenStack verbs the diagnosis path is allowed to reach. Anything that could
# change state (create/delete/set/unset/shelve/reboot/...) is absent on purpose.
READ_ONLY_VERBS = frozenset({"show", "list"})
class BridgeError(RuntimeError):
"""Raised when CX-Tools cannot be located, imported, or authenticated."""
def locate_cx_tools() -> str:
for candidate in DEFAULT_CX_TOOLS_PATHS:
if not candidate:
continue
path = os.path.abspath(os.path.expanduser(candidate))
if os.path.isfile(os.path.join(path, "cxlib", "__init__.py")):
return path
raise BridgeError(
"Could not find the CX-Tools checkout. Set CX_TOOLS_PATH to the directory "
"that contains cxlib/ and the vmc entry point."
)
_lock = threading.Lock()
_state: dict[str, Any] = {"path": "", "cx": None, "config": None}
def _import_cxlib(path: str):
if path not in sys.path:
sys.path.insert(0, path)
try:
import cxlib # noqa: PLC0415 (import is intentionally deferred)
except Exception as exc: # pragma: no cover - depends on the local checkout
raise BridgeError(f"Failed to import cxlib from {path}: {exc}") from exc
return cxlib
def bootstrap() -> tuple[Any, Any]:
"""Import cxlib and build the shared Config, loading secrets exactly once.
Call this from the foreground at startup: constructing Config triggers the
CX-Tools 1Password loader, which may need an interactive sign-in.
"""
with _lock:
if _state["config"] is not None:
return _state["cx"], _state["config"]
path = locate_cx_tools()
cx = _import_cxlib(path)
config = cx.Config(no_color=True, debug=bool(os.environ.get("CX_DEBUG")))
if not config.api_key or config.api_key in {"REDACT", "REPLACE_WITH_API_KEY"}:
raise BridgeError(
"CX-Tools could not load the Infrahub API key from 1Password. "
"Run `op signin` in this shell, then restart cx-triage."
)
_state.update({"path": path, "cx": cx, "config": config})
return cx, config
def cx() -> Any:
return bootstrap()[0]
def config() -> Any:
return bootstrap()[1]
def cx_tools_path() -> str:
bootstrap()
return str(_state["path"])
def quiet_progress() -> Any:
"""A Progress object that renders nothing, for use off the terminal."""
c = cx()
return c.Progress(c.C(False), 1, enabled=False)
def _guard_openstack(args: list[str]) -> None:
verbs = [a for a in args if not str(a).startswith("-")]
if not any(v in READ_ONLY_VERBS for v in verbs):
raise BridgeError(f"Refusing to run a non-read-only OpenStack command: {' '.join(args)}")
def os_json(region: str, args: list[str], timeout: int = 90) -> tuple[bool, Any, str]:
"""Run a read-only `openstack ... -f json` command through CX-Tools."""
_guard_openstack(args)
return cx().os_json(config(), region, args, timeout=timeout)
# --- collectors -------------------------------------------------------------
def collect_vm(target: str, *, region: str = "", org_id: Optional[str] = None, ssh_timeout: int = 3) -> dict[str, Any]:
"""Full VM reconciliation: the same payload `vmc --json <target>` emits."""
return cx().collect_vm(
config(),
target,
region_arg=region or "",
org_id=org_id,
ssh_timeout=ssh_timeout,
include_ih_events=True,
include_volumes=True,
include_all_ih_events=True,
progress=quiet_progress(),
)
def collect_host(host: str, *, ssh_timeout: int = 3) -> dict[str, Any]:
"""Host reconciliation: the same payload `vmc --json --host <host>` emits."""
return cx().collect_host(
config(),
host,
ssh_timeout=ssh_timeout,
include_ih_events=True,
include_volumes=True,
progress=quiet_progress(),
)
def collect_vm_contacts(target: str, *, region: str = "", org_id: Optional[str] = None) -> dict[str, Any]:
return cx().collect_vm_contacts(
config(),
target,
region_arg=region or "",
org_id=org_id,
progress=quiet_progress(),
)
# --- targeted queries used by individual runbooks --------------------------
def openstack_events(region: str, openstack_id: str, limit: Optional[int] = 5) -> list[dict[str, Any]]:
ok, events, _raw = cx().server_event_list(config(), region, openstack_id)
if not ok:
return []
return events[:limit] if limit else events
def openstack_event_detail(region: str, openstack_id: str, request_id: str) -> dict[str, Any]:
ok, detail, _raw = cx().server_event_show(config(), region, openstack_id, request_id)
return detail if ok else {}
def failed_openstack_event(region: str, openstack_id: str, scan: int = 5) -> dict[str, Any]:
"""Return the most recent OpenStack event whose detail reports a failure.
The state runbooks all say "the most recent failed event is the thing to
escalate", so this walks recent events newest-first and returns the first
one whose result is not Success, together with its detail rows.
"""
c = cx()
for event in openstack_events(region, openstack_id, limit=scan):
request_id = c.event_request_id(event)
if not request_id:
continue
detail = openstack_event_detail(region, openstack_id, request_id)
if not detail:
continue
rows = dict((str(k), str(v)) for k, v in c.event_detail_rows(detail))
result = rows.get("Result", "")
if result and result.lower() != "success":
return {"request_id": request_id, "action": rows.get("Action", ""), "rows": rows}
return {}
def infrahub_events(infrahub_id: str, limit: Optional[int] = None) -> list[list[str]]:
c = cx()
ok, data, _raw = c.query_vm_events(config(), str(infrahub_id))
if not ok:
return []
return c.infrahub_event_rows(data, limit)
def host_health(region: str, host: str) -> dict[str, Any]:
"""Hypervisor, Nova service and OVS agent signals for one host.
This is the cheap subset of `vmc --host` - the runbooks' "Host Health
Checks" entry point - without collecting every instance on the host.
"""
c = cx()
cfg = config()
ok_hv, hv, raw_hv, hv_name = c.hypervisor_show_host(cfg, region, host)
if not ok_hv:
return {"ok": False, "error": raw_hv, "host": host, "region": region}
state = c.normalize_empty(c.first_present(hv, "state", "State", default=""))
status = c.normalize_empty(c.first_present(hv, "status", "Status", default=""))
disabled_reason = ""
if status.lower() == "disabled":
for candidate in dict.fromkeys([x for x in (c.normalize_empty(hv_name), host) if x]):
ok_svc, services, _raw = c.compute_service_list_host(cfg, region, candidate)
if ok_svc:
disabled_reason = c.disabled_reason_from_services(services)
if disabled_reason:
break
ovs: dict[str, Any] = {}
ok_agents, agents, _raw_agents = c.network_agent_list_host(cfg, region, host)
if ok_agents:
ovs = c.ovs_agent_summary(agents)
if ovs.get("agent_id"):
ok_show, detail, _raw_show = c.network_agent_show(cfg, region, str(ovs["agent_id"]))
if ok_show:
ovs["last_heartbeat_at"] = c.normalize_empty(
detail.get("last_heartbeat_at") or detail.get("Last Heartbeat At") or ovs.get("last_heartbeat_at")
)
return {
"ok": True,
"error": "",
"host": host,
"hypervisor_name": hv_name,
"region": region,
"nova_state": state or "N/A",
"nova_status": status or "N/A",
"disabled_reason": disabled_reason,
"uptime": c.host_uptime_summary(hv),
"aggregates": c.host_aggregates_summary(hv),
"ovs_alive": ovs.get("alive"),
"ovs_state": ovs.get("state"),
"ovs_last_heartbeat": ovs.get("last_heartbeat_at") or "",
"running_vms": c.normalize_empty(c.first_present(hv, "running_vms", "Running VMs", default="")) or "N/A",
"free_disk_gb": c.normalize_empty(c.first_present(hv, "free_disk_gb", "Free Disk GB", default="")) or "N/A",
"local_disk_free": c.normalize_empty(c.first_present(hv, "disk_available_least", "Disk Available Least", default="")) or "N/A",
}
def host_gpu_census(region: str, host: str) -> dict[str, Any]:
"""Sum GPU counts of every instance on a host.
Implements the ERROR-runbook check for the NUMA/PCI fault: "check if the
host is full prior to escalation - add the values after the x, if it = 8
then it is FULL".
"""
c = cx()
ok, rows, raw = c.server_list_on_host(config(), region, host)
if not ok:
return {"ok": False, "error": raw, "total_gpus": None, "instances": []}
total = 0
unknown = 0
instances: list[dict[str, str]] = []
for row in rows:
flavor = c.get_row_field(row, "Flavor", "flavor") or c.flavor_name_from_any(row)
count = c.gpu_count_from_flavor_name(flavor)
if count.isdigit():
total += int(count)
else:
unknown += 1
instances.append({
"name": c.get_row_field(row, "Name", "name") or "N/A",
"openstack_id": c.openstack_id_from_row(row) or "N/A",
"status": c.get_row_field(row, "Status", "status") or "N/A",
"flavor": flavor or "N/A",
"gpus": count,
})
return {
"ok": True,
"error": "",
"total_gpus": total,
"unknown_flavors": unknown,
"instances": instances,
}
def json_safe(obj: Any) -> Any:
return cx().json_safe(obj)

View File

@@ -0,0 +1,196 @@
"""Outbound action payloads: Zendesk tickets and Jira issues.
This module *builds* payloads and never sends them. Delivery is a separate,
explicitly configured step - see `outbox.py` - so that a diagnosis can never
contact a customer as a side effect of being viewed.
Every payload carries the evidence that justified it, so the ticket a customer
or the Infrastructure team receives is self-contained.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Any, Optional
# Set these to enable the Send buttons. Absent = preview only.
ZENDESK_SUBDOMAIN = os.environ.get("CX_ZENDESK_SUBDOMAIN", "")
ZENDESK_EMAIL = os.environ.get("CX_ZENDESK_EMAIL", "")
ZENDESK_TOKEN = os.environ.get("CX_ZENDESK_TOKEN", "")
JIRA_BASE = os.environ.get("CX_JIRA_BASE", "https://nexgencloud.atlassian.net")
JIRA_EMAIL = os.environ.get("CX_JIRA_EMAIL", "")
JIRA_TOKEN = os.environ.get("CX_JIRA_TOKEN", "")
JIRA_PROJECT = os.environ.get("CX_JIRA_PROJECT", "INFRA")
PRIORITY_BY_VERDICT = {"overdue": "high", "real": "normal", "unverified": "low"}
def zendesk_configured() -> bool:
return bool(ZENDESK_SUBDOMAIN and ZENDESK_EMAIL and ZENDESK_TOKEN)
def jira_configured() -> bool:
return bool(JIRA_BASE and JIRA_EMAIL and JIRA_TOKEN)
@dataclass
class Action:
"""One proposed outbound action, ready to send once a human confirms."""
id: str
kind: str # zendesk | jira | manual
label: str
summary: str # one line: what this does
payload: dict[str, Any] = field(default_factory=dict)
recipients: list[str] = field(default_factory=list)
enabled: bool = False # is the integration configured?
blocked_reason: str = ""
requires_confirmation: bool = True
def to_json(self) -> dict[str, Any]:
return {
"id": self.id, "kind": self.kind, "label": self.label, "summary": self.summary,
"payload": self.payload, "recipients": self.recipients, "enabled": self.enabled,
"blocked_reason": self.blocked_reason, "requires_confirmation": self.requires_confirmation,
}
def _parse_owner(owner: str) -> tuple[str, str]:
"""'Name <email@x>' -> ('Name', 'email@x')."""
text = str(owner or "").strip()
if "<" in text and ">" in text:
name = text.split("<", 1)[0].strip()
email = text.split("<", 1)[1].split(">", 1)[0].strip()
return name, email
return ("", text) if "@" in text else (text, "")
def _evidence_block(diagnosis: Any) -> str:
lines = [f"Alert: {diagnosis.alert.title}", f"Verdict: {diagnosis.verdict}", ""]
for finding in diagnosis.findings[:16]:
lines.append(f"- {finding.label}: {finding.value}")
return "\n".join(lines)
def build_zendesk(diagnosis: Any) -> Optional[Action]:
"""A customer ticket, only when the runbook actually calls for contact."""
if not diagnosis.drafts:
return None
draft = diagnosis.drafts[0]
alert = diagnosis.alert
contacts = diagnosis.contacts or {}
owners = contacts.get("owners") or []
if not owners:
return Action(
id="zendesk", kind="zendesk", label="Contact customer (Zendesk)",
summary="No owner contact resolved from Infrahub - look the organization up first.",
enabled=False, blocked_reason="No customer contact could be resolved.",
)
name, email = _parse_owner(owners[0])
verdict = (alert.screen or {}).get("verdict", "real")
payload = {
"ticket": {
"subject": draft.subject,
"comment": {"body": draft.body, "public": True},
"requester": {"name": name or email, "email": email},
"priority": PRIORITY_BY_VERDICT.get(verdict, "normal"),
"type": "incident",
"tags": ["cx-triage", f"alert-{alert.kind}", f"region-{alert.region or 'unknown'}"],
"external_id": f"cx-triage-{alert.fingerprint()}",
"custom_fields_note": {
"instance_name": alert.instance_name,
"openstack_id": alert.openstack_id,
"organization": alert.org_name,
"infrahub_org_id": alert.org_id,
},
},
"_template": draft.template_id,
"_when": draft.when,
"_unfilled": draft.unfilled,
}
blocked = ""
if draft.unfilled:
blocked = f"Template still has placeholders: {', '.join(draft.unfilled)}"
return Action(
id="zendesk", kind="zendesk",
label="Contact customer (Zendesk)",
summary=f"Public reply to {name or email} - {draft.label}",
payload=payload,
recipients=[o for o in owners],
enabled=zendesk_configured() and not blocked,
blocked_reason=blocked or ("" if zendesk_configured() else "Zendesk is not configured."),
)
def build_jira(diagnosis: Any) -> Optional[Action]:
"""An Infrastructure escalation, only when a step is owned by Infra."""
infra_steps = [a for a in diagnosis.actions if a.owner != "CX" and a.kind == "escalate"]
if not infra_steps:
return None
alert = diagnosis.alert
subject = alert.host or alert.instance_name or alert.floating_ip or "unknown"
description = "\n".join([
_evidence_block(diagnosis),
"",
"Requested of Infrastructure:",
*[f"- {s.text}" for s in infra_steps],
"",
f"Raised from CX Triage. Alert has held for {alert.effective_age_text}.",
])
payload = {
"fields": {
"project": {"key": JIRA_PROJECT},
"summary": f"{subject}: {diagnosis.verdict}"[:250],
"description": description,
"issuetype": {"name": "Task"},
"labels": ["cx-triage", f"alert-{alert.kind}", f"region-{alert.region or 'unknown'}"],
}
}
return Action(
id="jira", kind="jira",
label="Escalate to Infrastructure (Jira)",
summary=f"Create a {JIRA_PROJECT} issue for {subject}",
payload=payload,
enabled=jira_configured(),
blocked_reason="" if jira_configured() else "Jira is not configured.",
)
def build_manual(diagnosis: Any) -> list[Action]:
"""Steps a human must perform; surfaced as copyable commands, not buttons."""
out: list[Action] = []
alert = diagnosis.alert
osid = alert.openstack_id
region = alert.region
for step in diagnosis.actions:
if step.kind != "remediate" or step.status == "done":
continue
command = ""
low = step.text.lower()
if "delete the server in openstack" in low and osid and region:
command = f"{region} server delete {osid}"
elif "shelve" in low and osid and region:
command = f"{region} server shelve {osid}"
out.append(Action(
id=f"manual-{len(out)}", kind="manual", label=step.text,
summary=step.guide or "", payload={"command": command} if command else {},
enabled=False, blocked_reason="Perform manually - this tool is read-only.",
requires_confirmation=False,
))
return out
def build_all(diagnosis: Any) -> dict[str, Any]:
actions: list[Action] = []
for builder in (build_zendesk, build_jira):
action = builder(diagnosis)
if action:
actions.append(action)
actions.extend(build_manual(diagnosis))
return {
"actions": [a.to_json() for a in actions],
"zendesk_configured": zendesk_configured(),
"jira_configured": jira_configured(),
}

View File

@@ -0,0 +1,233 @@
"""Linkage analysis: Infrahub records that lost their OpenStack server, and
OpenStack servers that no Infrahub record claims.
A VM in ERROR is not always a failed build. Sometimes the build succeeded and
only the *link* between Infrahub and OpenStack was never written - so Infrahub
reports ERROR (or CREATING) with no usable openstack_id while a perfectly good
server of the same name is running. Those look identical on an alert dashboard
and are opposite problems: one needs a rebuild, the other needs a record fixed
and is quietly billing nobody.
This scans both sides in bulk and pairs them up by name.
It also finds the reverse - OpenStack servers with no Infrahub record at all -
which is what `Suspected Orphan VM` was meant to catch before its input metric
went empty.
"""
from __future__ import annotations
import difflib
import threading
import time
from typing import Any, Optional
from . import cxbridge
REGIONS = ("ca1", "ca2", "us1", "no1")
# Infrahub states where a missing OpenStack link is suspicious rather than normal.
# HIBERNATED is excluded: shelved instances legitimately have no running server.
UNLINKED_SUSPECT_STATES = {"ERROR", "CREATING", "BUILD", "ACTIVE", "REBOOTING", "RESTORING"}
# Projects to ignore, matching the CX-Tools tempest suppression.
def _is_ignorable(name: str) -> bool:
low = str(name or "").lower()
return "tempest" in low
_REGION_ALIAS = {"canada-1": "ca1", "canada-2": "ca2", "us-1": "us1", "norway-1": "no1",
"ca1": "ca1", "ca2": "ca2", "us1": "us1", "no1": "no1"}
def _region_alias(region: str) -> str:
return _REGION_ALIAS.get(str(region or "").strip().lower(), "")
def _norm(name: str) -> str:
return str(name or "").strip().lower()
class Scan:
"""One full cross-region scan. Slow (a server list per region), so cached."""
def __init__(self):
self.started = 0.0
self.finished = 0.0
self.state = "idle" # idle | running | done | error
self.error = ""
self.progress = ""
self.result: dict[str, Any] = {}
self._lock = threading.Lock()
def to_json(self) -> dict[str, Any]:
return {
"state": self.state, "error": self.error, "progress": self.progress,
"started": self.started, "finished": self.finished,
"age_seconds": int(time.time() - self.finished) if self.finished else None,
"result": self.result,
}
def run(self, snapshot: Any, regions: tuple[str, ...] = REGIONS) -> None:
with self._lock:
if self.state == "running":
return
self.state = "running"
self.started = time.time()
self.error = ""
self.progress = "starting"
try:
self.result = self._scan(snapshot, regions)
self.state = "done"
except Exception as exc: # surfaced in the UI rather than crashing the server
self.state = "error"
self.error = f"{type(exc).__name__}: {exc}"
finally:
self.finished = time.time()
self.progress = ""
# --- the analysis ------------------------------------------------------
def _scan(self, snapshot: Any, regions: tuple[str, ...]) -> dict[str, Any]:
# 1. Everything OpenStack has, per region.
os_by_id: dict[str, dict[str, str]] = {}
os_by_name: dict[str, list[dict[str, str]]] = {}
region_counts: dict[str, int] = {}
failures: dict[str, str] = {}
for region in regions:
self.progress = f"listing OpenStack servers in {region}"
ok, rows, raw = _server_list(region)
if not ok:
failures[region] = raw[:200]
continue
region_counts[region] = len(rows)
for row in rows:
sid = str(row.get("ID") or "")
if not sid:
continue
rec = {
"id": sid,
"name": str(row.get("Name") or ""),
"status": str(row.get("Status") or ""),
"task": str(row.get("Task State") or ""),
"host": str(row.get("Host") or ""),
"project_id": str(row.get("Project ID") or ""),
"flavor": str(row.get("Flavor") or ""),
"region": region,
}
os_by_id[sid] = rec
os_by_name.setdefault(_norm(rec["name"]), []).append(rec)
# 2. Everything Infrahub has, from the bulk metric snapshot.
self.progress = "comparing against Infrahub"
infrahub = list(snapshot.by_openstack_id.values()) + list(snapshot.by_instance_name.values())
seen: set[str] = set()
ih_records: list[dict[str, str]] = []
for row in infrahub:
key = f"{row.get('openstack_id','')}|{row.get('instance_name','')}"
if key in seen:
continue
seen.add(key)
ih_records.append(row)
ih_osids = {str(r.get("openstack_id") or "") for r in ih_records if r.get("openstack_id")}
ih_osids.discard("")
ih_osids.discard("None")
# 3a. Infrahub records whose OpenStack server is missing or never linked.
#
# Only records in a region that was actually listed can be judged: if a
# region failed, every VM in it would look "missing from OpenStack".
scanned = set(region_counts)
skipped_unscanned = 0
broken_links: list[dict[str, Any]] = []
for row in ih_records:
status = str(row.get("status") or "").upper()
if status not in UNLINKED_SUSPECT_STATES:
continue
if _region_alias(str(row.get("region") or "")) not in scanned:
skipped_unscanned += 1
continue
osid = str(row.get("openstack_id") or "")
has_link = bool(osid) and osid != "None"
if has_link and osid in os_by_id:
continue # properly linked, nothing to see
name = str(row.get("instance_name") or "")
if _is_ignorable(name):
continue
candidates = os_by_name.get(_norm(name), [])
# An exact-name server that nothing else claims is a very strong
# candidate for the link that was never written.
unclaimed = [c for c in candidates if c["id"] not in ih_osids]
match = unclaimed[0] if unclaimed else (candidates[0] if candidates else None)
broken_links.append({
"instance_name": name,
"infrahub_status": status,
"infrahub_openstack_id": osid or "(none)",
"organization": str(row.get("organization") or ""),
"region": str(row.get("region") or ""),
"flavor": str(row.get("flavor_name") or ""),
"gpus": str(row.get("_gpus") or ""),
"reason": (
"Infrahub holds an OpenStack ID that OpenStack does not have"
if has_link else "Infrahub never recorded an OpenStack ID"
),
"candidate": match,
"candidate_claimed_by_other": bool(match and match["id"] in ih_osids),
"confidence": (
"high" if match and not match["id"] in ih_osids and match["status"] not in ("", "ERROR")
else "medium" if match else "none"
),
})
# 3b. OpenStack servers no Infrahub record claims.
orphans: list[dict[str, Any]] = []
ih_names = {_norm(str(r.get("instance_name") or "")) for r in ih_records}
for sid, rec in os_by_id.items():
if sid in ih_osids or _is_ignorable(rec["name"]):
continue
orphans.append({**rec, "name_known_to_infrahub": _norm(rec["name"]) in ih_names})
linkable = [b for b in broken_links if b["candidate"] and not b["candidate_claimed_by_other"]]
return {
"scanned_regions": region_counts,
"region_failures": failures,
"openstack_servers": len(os_by_id),
"infrahub_records": len(ih_records),
"broken_links": sorted(broken_links, key=lambda b: (b["confidence"] != "high", b["instance_name"])),
"likely_linkage_failures": len(linkable),
"skipped_unscanned_regions": skipped_unscanned,
"orphans": sorted(orphans, key=lambda o: (not o["name_known_to_infrahub"], o["name"]))[:400],
"orphan_total": len(orphans),
}
def _server_list(region: str) -> tuple[bool, list[dict[str, Any]], str]:
ok, data, raw = cxbridge.os_json(
region, ["server", "list", "--all-projects", "--long", "-f", "json"], timeout=180
)
if ok and isinstance(data, list):
return True, [x for x in data if isinstance(x, dict)], ""
return False, [], str(raw)
def enrich(region: str, openstack_id: str) -> dict[str, Any]:
"""Fetch created time and fault for one candidate, on demand."""
c = cxbridge.cx()
ok, srv, raw = c.server_show(cxbridge.config(), region, openstack_id)
if not ok:
return {"ok": False, "error": str(raw)[:200]}
fault = srv.get("fault")
return {
"ok": True,
"created": str(srv.get("created") or srv.get("Created") or ""),
"launched": str(srv.get("OS-SRV-USG:launched_at") or ""),
"status": str(srv.get("status") or ""),
"host": str(srv.get("OS-EXT-SRV-ATTR:host") or ""),
"project_id": str(srv.get("project_id") or ""),
"fault": (fault.get("message") if isinstance(fault, dict) else str(fault or "")) or "None",
}

View File

@@ -0,0 +1,545 @@
"""Prometheus access.
The alert Prometheus lives on the internal 10.11/8 network, which is reachable
only from inside the CX-Tools VPN containers - the laptop itself routes 10.11.*
out of its default gateway. So queries go the same way CX-Tools reaches
OpenStack: `docker exec <region>-osc curl ...`. A direct HTTP transport is tried
first so this still works from a host that does have a route.
"""
from __future__ import annotations
import json
import os
import re
import shlex
import subprocess
import threading
import time
import urllib.parse
import urllib.request
from typing import Any, Optional
DEFAULT_BASE = os.environ.get("CX_PROMETHEUS_BASE", "http://10.11.254.250:9090")
# Containers to try as an HTTP relay, in order. These are the CX-Tools
# OpenStack client containers, which share the regional VPN network namespace.
RELAY_CONTAINERS = ("ca1-osc", "us1-osc", "no1-osc", "ca2-osc")
class PrometheusError(RuntimeError):
pass
class PrometheusClient:
def __init__(self, base: str = DEFAULT_BASE, timeout: int = 20):
self.base = base.rstrip("/")
self.timeout = timeout
self._transport: Optional[tuple[str, str]] = None
self._lock = threading.Lock()
# --- transport selection ------------------------------------------------
def _try_direct(self) -> bool:
try:
req = urllib.request.Request(f"{self.base}/api/v1/status/buildinfo", headers={"User-Agent": "cx-triage"})
with urllib.request.urlopen(req, timeout=5) as resp:
return 200 <= getattr(resp, "status", 200) < 300
except Exception:
return False
def _try_relay(self, container: str) -> bool:
rc, out, _err = _run(
["docker", "exec", "-i", container, "curl", "-sS", "-m", "6", f"{self.base}/api/v1/status/buildinfo"],
timeout=15,
)
return rc == 0 and '"status":"success"' in out
def transport(self) -> tuple[str, str]:
"""Return (kind, detail) where kind is 'direct' or 'relay'."""
with self._lock:
if self._transport is not None:
return self._transport
forced = os.environ.get("CX_PROMETHEUS_RELAY", "").strip()
if forced:
self._transport = ("relay", forced)
return self._transport
if self._try_direct():
self._transport = ("direct", "host")
return self._transport
for container in RELAY_CONTAINERS:
if self._try_relay(container):
self._transport = ("relay", container)
return self._transport
raise PrometheusError(
f"Cannot reach Prometheus at {self.base}. The host has no route to the internal "
f"network and none of {', '.join(RELAY_CONTAINERS)} answered. Start the CX-Tools "
"VPN/OSC containers, or set CX_PROMETHEUS_RELAY to a container that has a route."
)
def describe_transport(self) -> str:
try:
kind, detail = self.transport()
except PrometheusError as exc:
return f"unavailable ({exc})"
return "direct from host" if kind == "direct" else f"relayed through {detail}"
# --- requests -----------------------------------------------------------
def _get(self, path: str, params: Optional[dict[str, str]] = None) -> Any:
url = f"{self.base}{path}"
if params:
url = f"{url}?{urllib.parse.urlencode(params)}"
kind, detail = self.transport()
if kind == "direct":
req = urllib.request.Request(url, headers={"User-Agent": "cx-triage"})
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
body = resp.read().decode("utf-8", errors="replace")
else:
rc, out, err = _run(
["docker", "exec", "-i", detail, "curl", "-sS", "-m", str(self.timeout), url],
timeout=self.timeout + 10,
)
if rc != 0:
raise PrometheusError(f"Prometheus relay via {detail} failed: {(err or out).strip()}")
body = out
try:
data = json.loads(body)
except json.JSONDecodeError as exc:
raise PrometheusError(f"Prometheus returned non-JSON for {path}: {body[:200]}") from exc
if data.get("status") != "success":
raise PrometheusError(f"Prometheus error for {path}: {data.get('error') or data}")
return data.get("data")
def alerts(self) -> list[dict[str, Any]]:
data = self._get("/api/v1/alerts") or {}
alerts = data.get("alerts")
return [a for a in alerts if isinstance(a, dict)] if isinstance(alerts, list) else []
def query(self, expr: str) -> list[dict[str, Any]]:
data = self._get("/api/v1/query", {"query": expr}) or {}
result = data.get("result")
return [r for r in result if isinstance(r, dict)] if isinstance(result, list) else []
def resources_by_floating_ip(self, floating_ip: str) -> list[dict[str, Any]]:
"""The `Resources{floating_ip="..."}` query the Duplicated IPs runbook uses.
Unlike CX-Tools (production Infrahub only), this series covers every
environment, so it is how a PreProd/Staging claimant gets found.
"""
expr = 'Resources{floating_ip="%s"}' % floating_ip.replace('"', "")
return [dict(r.get("metric") or {}) for r in self.query(expr)]
def query_range(self, expr: str, start: int, end: int, step: int) -> list[dict[str, Any]]:
data = self._get("/api/v1/query_range", {
"query": expr, "start": str(start), "end": str(end), "step": str(step),
}) or {}
result = data.get("result")
return [r for r in result if isinstance(r, dict)] if isinstance(result, list) else []
def rules(self) -> list[dict[str, Any]]:
data = self._get("/api/v1/rules") or {}
return [g for g in (data.get("groups") or []) if isinstance(g, dict)]
def series_count(self, metric: str) -> int:
rows = self.query(f"count({metric})")
if not rows:
return 0
try:
return int(float(rows[0]["value"][1]))
except (KeyError, IndexError, ValueError, TypeError):
return 0
class RuleIndex:
"""Maps alertname -> which rule file it came from and its `for` duration.
Keying off the rule file (not the alert name) is what lets node-exporter
alerts be separated reliably: two different files both use the group name
"Imported Rules".
"""
def __init__(self, client: PrometheusClient, ttl: float = 600.0):
self.client = client
self.ttl = ttl
self._at = 0.0
self._by_name: dict[str, dict[str, Any]] = {}
self._error = ""
self._lock = threading.Lock()
def refresh(self) -> None:
groups = self.client.rules()
index: dict[str, dict[str, Any]] = {}
for group in groups:
source = str(group.get("file") or "").rsplit("/", 1)[-1]
for rule in group.get("rules") or []:
if rule.get("type") != "alerting":
continue
index[str(rule.get("name") or "")] = {
"group": str(group.get("name") or ""),
"file": source,
"for_seconds": int(rule.get("duration") or 0),
"query": str(rule.get("query") or ""),
}
self._by_name = index
def ensure(self) -> None:
"""Refresh if the cache is empty or stale."""
with self._lock:
if not self._by_name or time.monotonic() - self._at > self.ttl:
try:
self.refresh()
self._error = ""
except PrometheusError as exc:
self._error = str(exc)
self._at = time.monotonic()
def get(self, alertname: str) -> dict[str, Any]:
self.ensure()
return self._by_name.get(alertname, {})
@property
def count(self) -> int:
return len(self._by_name)
@property
def error(self) -> str:
return self._error
# Metrics the alert rules are built on. If one of these is empty, rules that
# depend on it are broken rather than quiet - see StateSnapshot.broken_inputs.
RULE_INPUT_METRICS = ("Resources", "In_Use_Gpus", "Total_Gpus", "openstack_nova_server_status")
ROGUE_DELTA_EXPR = (
'sum by (instance) (In_Use_Gpus) - sum by (instance) '
'(Resources{organization!="3491 - luis.sarabando+runpod@nexgencloud.coms-Organization",'
'status=~"ACTIVE|SHUTOFF|PRE_ACTIVE"})'
)
def _episode(points: list[tuple[int, float]], median: float) -> dict[str, Any]:
return {
"start": points[0][0],
"end": points[-1][0],
"minutes": max(1, (points[-1][0] - points[0][0]) // 60 + 1),
"low": int(min(v for _, v in points)),
"normal": int(median),
}
# Labels that identify one alert across time, for true-age lookup.
TRUE_AGE_KEY_LABELS = ("alertname", "instance_name", "floating_ip", "instance", "openstack_id")
def true_age_key(labels: dict[str, Any]) -> tuple:
"""Identity of an alert, built from raw label values on both sides."""
return tuple(str((labels or {}).get(k, "")) for k in TRUE_AGE_KEY_LABELS)
class TrueAgeIndex:
"""How long each alert's condition has *actually* held.
Prometheus resets an alert's activeAt whenever the alert resolves, and the
Infrahub metric pipeline drops most of the `Resources` series for a few
minutes several times a day. Every alert alive during such a dip resolves and
re-fires, so activeAt collapses to "time since the last dip" and every alert
reports the same age.
This walks the `ALERTS` series backwards instead, bridging gaps shorter than
GAP_TOLERANCE, which recovers the real duration. Both pending and firing are
counted, so rules with a long `for:` are not reported as young.
"""
WINDOW_DAYS = 7
STEP_SECONDS = 900
GAP_TOLERANCE = 2700 # 45 min: bridges pipeline dips, not genuine recoveries
def __init__(self, client: PrometheusClient, severity: str = "infrahub-critical", ttl: float = 300.0):
self.client = client
self.severity = severity
self.ttl = ttl
self._at = 0.0
self._lock = threading.Lock()
self._starts: dict[tuple, tuple[int, bool]] = {}
self.error = ""
self.window_start = 0
def refresh(self) -> None:
end = int(time.time())
start = end - self.WINDOW_DAYS * 86400
self.window_start = start
expr = (
"count by (%s) (ALERTS{severity=\"%s\"})"
% (", ".join(TRUE_AGE_KEY_LABELS), self.severity)
)
starts: dict[tuple, tuple[int, bool]] = {}
for series in self.client.query_range(expr, start, end, self.STEP_SECONDS):
stamps = []
for point in series.get("values") or []:
try:
stamps.append(int(float(point[0])))
except (ValueError, TypeError, IndexError):
continue
if not stamps:
continue
run_start = stamps[-1]
for earlier, later in list(zip(stamps, stamps[1:]))[::-1]:
if later - earlier > self.GAP_TOLERANCE:
break
run_start = earlier
# A run that reaches the window edge is only a lower bound.
capped = run_start <= start + self.STEP_SECONDS
key = true_age_key(series.get("metric") or {})
existing = starts.get(key)
if existing is None or run_start < existing[0]:
starts[key] = (run_start, capped)
self._starts = starts
def get(self) -> "TrueAgeIndex":
with self._lock:
if not self._at or time.monotonic() - self._at > self.ttl:
try:
self.refresh()
self.error = ""
except PrometheusError as exc:
self.error = str(exc)
self._at = time.monotonic()
return self
def lookup(self, labels: dict[str, Any]) -> tuple[Optional[int], bool]:
"""Return (minutes the condition has held, whether that is a floor)."""
entry = self._starts.get(true_age_key(labels))
if not entry:
return None, False
start, capped = entry
return max(0, int((time.time() - start) // 60)), capped
@property
def loaded(self) -> bool:
return bool(self._starts)
@property
def count(self) -> int:
return len(self._starts)
class StateSnapshot:
"""A bulk read of current platform state, used to screen alerts cheaply.
Re-checking whether an alert's condition still holds is what separates a
real alert from one that already self-resolved. Doing it from these few
aggregate queries costs one Prometheus round trip for the whole queue,
instead of an Infrahub and OpenStack call per alert.
"""
def __init__(self, client: PrometheusClient, ttl: float = 60.0):
self.client = client
self.ttl = ttl
self._at = 0.0
self._lock = threading.Lock()
self.error = ""
self.by_openstack_id: dict[str, dict[str, str]] = {}
self.by_instance_name: dict[str, dict[str, str]] = {}
self.fip_counts: dict[str, int] = {}
self.rogue_delta: dict[str, float] = {}
self.total_gpus: dict[str, float] = {}
self.in_use_gpus: dict[str, float] = {}
self.resources_by_host: dict[str, list[dict[str, str]]] = {}
self.broken_inputs: list[str] = []
# Infrahub VMs in a GPU-counted state with no host recorded. These are
# invisible to the per-host GPU sum the Rogue VM rule uses, so they can
# manufacture a gap on whichever host is actually running them.
self.unattributed_active: int = 0
self.unattributed_active_gpus: int = 0
# Episodes where the Resources series partially collapsed. Each one
# resets activeAt on every alert that was live at the time.
self.pipeline_dips: list[dict[str, Any]] = []
def refresh(self) -> None:
by_osid: dict[str, dict[str, str]] = {}
by_name: dict[str, dict[str, str]] = {}
fips: dict[str, int] = {}
by_host: dict[str, list[dict[str, str]]] = {}
counted_states = {"ACTIVE", "SHUTOFF", "PRE_ACTIVE"}
unattributed = 0
unattributed_gpus = 0
for row in self.client.query("Resources"):
metric = {str(k): str(v) for k, v in (row.get("metric") or {}).items()}
try:
metric["_gpus"] = str(int(float(row.get("value", [0, "0"])[1])))
except (ValueError, TypeError, IndexError):
metric["_gpus"] = "0"
osid = metric.get("openstack_id", "")
if osid and osid not in ("None", ""):
by_osid[osid] = metric
name = metric.get("instance_name", "")
if name:
by_name[name] = metric
fip = metric.get("floating_ip", "")
if fip and fip not in ("None", "NULL", ""):
fips[fip] = fips.get(fip, 0) + 1
host = metric.get("instance", "")
if host and host not in ("Unknown", "None"):
by_host.setdefault(host, []).append(metric)
elif metric.get("status", "").upper() in counted_states:
unattributed += 1
unattributed_gpus += int(metric["_gpus"] or 0)
self.by_openstack_id = by_osid
self.by_instance_name = by_name
self.fip_counts = fips
self.resources_by_host = by_host
self.unattributed_active = unattributed
self.unattributed_active_gpus = unattributed_gpus
# Summed by instance: these metrics are per (instance, gpu_name), so a
# host with two GPU models carries two series. Reading them unsummed
# would silently keep only one.
self.rogue_delta = self._scalar_by_instance(ROGUE_DELTA_EXPR)
self.total_gpus = self._scalar_by_instance("sum by (instance) (Total_Gpus)")
self.in_use_gpus = self._scalar_by_instance("sum by (instance) (In_Use_Gpus)")
self.broken_inputs = [m for m in RULE_INPUT_METRICS if self.client.series_count(m) == 0]
self.pipeline_dips = self._find_pipeline_dips()
def _find_pipeline_dips(self, hours: int = 24, drop_ratio: float = 0.8) -> list[dict[str, Any]]:
"""Find episodes where most of the `Resources` series went missing."""
end = int(time.time())
start = end - hours * 3600
series = self.client.query_range("count(Resources)", start, end, 60)
if not series:
return []
points: list[tuple[int, float]] = []
for point in series[0].get("values") or []:
try:
points.append((int(float(point[0])), float(point[1])))
except (ValueError, TypeError, IndexError):
continue
if len(points) < 10:
return []
ordered = sorted(v for _, v in points)
median = ordered[len(ordered) // 2]
if median <= 0:
return []
episodes: list[dict[str, Any]] = []
current: list[tuple[int, float]] = []
for stamp, value in points:
if value < median * drop_ratio:
if current and stamp - current[-1][0] > 180:
episodes.append(_episode(current, median))
current = []
current.append((stamp, value))
elif current:
episodes.append(_episode(current, median))
current = []
if current:
episodes.append(_episode(current, median))
return episodes
def _scalar_by_instance(self, expr: str) -> dict[str, float]:
out: dict[str, float] = {}
for row in self.client.query(expr):
host = str((row.get("metric") or {}).get("instance") or "")
if not host:
continue
try:
out[host] = float(row.get("value", [0, "0"])[1])
except (ValueError, TypeError, IndexError):
continue
return out
def get(self) -> "StateSnapshot":
with self._lock:
if not self._at or time.monotonic() - self._at > self.ttl:
try:
self.refresh()
self.error = ""
except PrometheusError as exc:
self.error = str(exc)
self._at = time.monotonic()
return self
@property
def loaded(self) -> bool:
return bool(self.by_openstack_id) or bool(self.total_gpus)
def _run(cmd: list[str], timeout: int) -> tuple[int, str, str]:
try:
p = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout)
return p.returncode, p.stdout, p.stderr
except subprocess.TimeoutExpired as exc:
return 124, exc.stdout or "", exc.stderr or f"timed out after {timeout}s"
except FileNotFoundError as exc:
return 127, "", str(exc)
except Exception as exc: # pragma: no cover
return 1, "", str(exc)
# --- parsing pasted alert text / URLs --------------------------------------
_LABEL_RE = re.compile(r'(\w+)\s*=\s*"((?:[^"\\]|\\.)*)"')
def parse_alert_text(text: str) -> list[dict[str, str]]:
"""Parse pasted `ALERTS{...}` lines, or a Prometheus graph URL, into labels.
Accepts what a CX engineer actually copies: a raw series line from the
Prometheus console, or the `g0.expr=` URL from the Slack alert.
"""
text = (text or "").strip()
if not text:
return []
found: list[dict[str, str]] = []
# A pasted graph URL: pull the expression out and parse its label matchers.
if text.startswith("http://") or text.startswith("https://"):
parsed = urllib.parse.urlparse(text)
params = urllib.parse.parse_qs(parsed.query)
exprs = [v for k, vs in params.items() if k.endswith("expr") for v in vs]
for expr in exprs:
labels = {k: _unescape(v) for k, v in _LABEL_RE.findall(expr)}
if labels:
found.append(labels)
return found
for block in re.findall(r"\{[^{}]*\}", text):
labels = {k: _unescape(v) for k, v in _LABEL_RE.findall(block)}
if labels:
found.append(labels)
if not found:
labels = {k: _unescape(v) for k, v in _LABEL_RE.findall(text)}
if labels:
found.append(labels)
return found
def _unescape(value: str) -> str:
return value.replace('\\"', '"').replace("\\\\", "\\").replace("\\n", "\n")
class AlertCache:
"""Short-lived cache so the UI can poll without hammering Prometheus."""
def __init__(self, client: PrometheusClient, ttl: float = 30.0):
self.client = client
self.ttl = ttl
self._at = 0.0
self._alerts: list[dict[str, Any]] = []
self._error = ""
self._lock = threading.Lock()
def get(self, force: bool = False) -> tuple[list[dict[str, Any]], str, float]:
with self._lock:
age = time.monotonic() - self._at
if not force and self._at and age < self.ttl:
return self._alerts, self._error, age
try:
self._alerts = self.client.alerts()
self._error = ""
except PrometheusError as exc:
self._error = str(exc)
self._at = time.monotonic()
return self._alerts, self._error, 0.0

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,313 @@
"""Noise-vs-real screening.
An alert firing is not the same as work existing. Prometheus keeps an alert up
until its expression stops matching on the next evaluation, and the CX rules sit
on top of a metric pipeline that can go stale or empty. So before anything gets
diagnosed, each alert's condition is re-checked against current state.
The re-check is deliberately cheap: it reads the same Prometheus series the rules
are built from (one bulk snapshot for the whole queue) rather than making an
Infrahub or OpenStack call per alert. Anything it cannot settle is treated as
real - screening only ever demotes an alert on positive evidence.
"""
from __future__ import annotations
import time
from typing import Any, Optional
from .alerts import Alert
# Beyond this, an alert is chronic: it is either already ticketed or nobody has
# silenced it. Either way it is not today's queue.
CHRONIC_DAYS = 3
# Verdicts, most to least urgent.
REAL = "real"
OVERDUE = "overdue"
UNVERIFIED = "unverified"
CHRONIC = "chronic"
LOW_IMPACT = "low_impact"
PENDING = "pending"
RESOLVED = "resolved"
RULE_DEFECT = "rule_defect"
SUPPRESSED = "suppressed"
VERDICT_LABELS = {
REAL: "needs action",
OVERDUE: "overdue",
UNVERIFIED: "needs action (unverified)",
CHRONIC: "chronic",
LOW_IMPACT: "low impact",
PENDING: "not yet firing",
RESOLVED: "already resolved",
RULE_DEFECT: "invalid - alert rule defect",
SUPPRESSED: "hidden by a rule",
}
# Runbook commitments: past this age the customer contact is late, not chronic.
# From "Instance in ERROR state": if a stock-failure instance is not deleted
# within a day, contact the customer. SHUTOFF is here for a different reason -
# the VM accrues full cost the entire time it is stopped, so an old one is a
# customer who has been paying for nothing for longer, not a stale alert.
SLA_HOURS = {"error": 24, "creating": 24, "restoring": 24, "rebooting": 24,
"build": 24, "shutoff": 48}
SLA_REASON = {
"shutoff": "a SHUTOFF VM accrues full cost the whole time, so this customer has been paying "
"for a stopped instance that long and may never have been told",
}
# Verdicts that stay in the working queue by default.
ACTIONABLE = {REAL, OVERDUE, UNVERIFIED}
# Kept for the SLA check: an internal owner should not make an alert *overdue*.
def _is_internal(alert) -> bool:
return bool(getattr(alert, 'is_internal_org', False))
def _result(verdict: str, reason: str, *, current: str = "", detail: str = "") -> dict[str, Any]:
return {
"verdict": verdict,
"label": VERDICT_LABELS[verdict],
"reason": reason,
"actionable": verdict in ACTIONABLE,
"current_state": current,
"detail": detail,
}
def _resources_row(alert: Alert, snap: Any) -> Optional[dict[str, str]]:
"""Find the VM's current Infrahub row in the snapshot."""
if alert.openstack_id and alert.openstack_id in snap.by_openstack_id:
return snap.by_openstack_id[alert.openstack_id]
if alert.instance_name and alert.instance_name in snap.by_instance_name:
return snap.by_instance_name[alert.instance_name]
return None
def _screen_state_alert(alert: Alert, snap: Any) -> dict[str, Any]:
"""State alerts: does Infrahub still report the state that fired?"""
expected = alert.status.upper()
row = _resources_row(alert, snap)
if row is None:
if alert.kind == "creating" and not alert.openstack_id:
# A CREATING VM that never reached OpenStack has no Resources row to
# find; the alert stands on its own.
return _result(REAL, "Instance never got an OpenStack ID, so it cannot have recovered.")
return _result(
RESOLVED,
"No longer present in Infrahub's Resources series - the record has been deleted or cleaned up.",
)
current = row.get("status", "").upper()
if not expected:
return _result(UNVERIFIED, "Alert carried no status label, so its condition could not be re-checked.",
current=current)
if current == expected:
return _result(REAL, f"Infrahub still reports {current}.", current=current)
return _result(
RESOLVED,
f"Fired on {expected} but Infrahub now reports {current} - it resolved on its own.",
current=current,
)
def _screen_duplicate_ip(alert: Alert, snap: Any) -> dict[str, Any]:
count = snap.fip_counts.get(alert.floating_ip)
if count is None:
return _result(RESOLVED, f"No Infrahub VM currently holds {alert.floating_ip}.")
if count > 1:
return _result(REAL, f"{count} VMs still hold {alert.floating_ip}.", current=f"{count} claimants")
return _result(
RESOLVED,
f"Only 1 VM holds {alert.floating_ip} now - the duplicate is gone.",
current="1 claimant",
)
def _screen_rogue_vm(alert: Alert, snap: Any) -> dict[str, Any]:
"""Rogue VM fires on a per-host GPU accounting gap; re-evaluate the gap.
The rule subtracts Infrahub's allocated GPUs from `In_Use_Gpus`. On almost
every host `In_Use_Gpus` equals `Total_Gpus` - the physical GPU count - so
the expression reduces to "this host has at least one unallocated GPU" and
fires on ordinary spare capacity. Validated against OpenStack on 10 firing
hosts: Infrahub and OpenStack agreed exactly on all of them.
"""
host = alert.host or alert.instance_name
delta = snap.rogue_delta.get(host)
if delta is None:
return _result(UNVERIFIED, f"No current GPU accounting data for {host}.")
if delta >= 1:
known = len(snap.resources_by_host.get(host, []))
in_use = snap.in_use_gpus.get(host)
total = snap.total_gpus.get(host)
if in_use is not None and total is not None and in_use == total:
return _result(
RULE_DEFECT,
f"Not a rogue VM: on {host} the rule's 'GPUs in use' reading ({int(in_use)}) is just the "
f"physical GPU count, so it is reporting {int(delta)} free GPU(s) as a discrepancy.",
current=f"{int(delta)} GPU(s) spare capacity",
detail=(
"In_Use_Gpus == Total_Gpus on this host, so the rule expression reduces to "
"'physical GPUs minus allocated GPUs', which is spare capacity rather than an "
"Infrahub/OpenStack mismatch. The rule needs fixing at source."
),
)
if total is None:
detail = (f"Infrahub records {known} VM(s) on this host. No Total_Gpus reading is available, so the "
"spare-capacity explanation cannot be confirmed or ruled out from metrics alone.")
else:
detail = (f"Infrahub records {known} VM(s) on this host. In_Use_Gpus ({int(in_use)}) differs from "
f"Total_Gpus ({int(total)}), so this is not simply spare capacity.")
return _result(
REAL,
f"{int(delta)} GPU(s) allocated on {host} are still unaccounted for in Infrahub.",
current=f"gap {int(delta)}",
detail=detail,
)
return _result(
RESOLVED,
f"GPU accounting for {host} now balances (delta {int(delta)}).",
current=f"delta {int(delta)}",
)
def _screen_total_gpus(alert: Alert, snap: Any) -> dict[str, Any]:
host = alert.host or alert.instance_name
total = snap.total_gpus.get(host)
if total is None:
return _result(UNVERIFIED, f"No current Total_Gpus reading for {host}.")
# The rule fires on any count in 1,2,3,5,6,7,9 - i.e. not a full complement.
if int(total) in (0, 4, 8):
return _result(
RESOLVED,
f"{host} now reports {int(total)} GPUs, a valid complement.",
current=f"{int(total)} GPUs",
)
in_use = snap.in_use_gpus.get(host)
detail = f"{int(in_use)} GPU(s) currently allocated to instances." if in_use is not None else ""
return _result(
REAL,
f"{host} still reports {int(total)} GPUs - hardware is missing.",
current=f"{int(total)} GPUs",
detail=detail,
)
_KIND_SCREENS = {
"duplicate_ip": _screen_duplicate_ip,
"rogue_vm": _screen_rogue_vm,
"orphan_vm": _screen_rogue_vm,
"total_gpus": _screen_total_gpus,
}
def screen(alert: Alert, snap: Any, user_settings: Any = None) -> dict[str, Any]:
"""Decide whether an alert is worth a human's attention right now."""
# A rule the team wrote wins over anything inferred here.
if user_settings is not None:
from . import settings as settings_mod
rule = settings_mod.first_match(user_settings, alert)
if rule:
reason = rule.get("reason") or "Matched a suppression rule."
return _result(
SUPPRESSED,
f"Hidden by \u201c{rule.get('name')}\u201d - {reason}",
detail="Edit or disable this in Settings.",
)
# Prometheus has not committed to this alert yet.
if alert.state == "pending":
remaining = ""
if alert.for_seconds and alert.age_minutes is not None:
remaining = f" It needs {alert.for_seconds // 60} min of continuous firing; it has {alert.age_minutes} min."
return _result(PENDING, f"Prometheus still has this pending, not firing.{remaining}")
if snap is None or not getattr(snap, "loaded", False):
return _result(UNVERIFIED, "Current-state snapshot unavailable, so the condition could not be re-checked.")
screener = _KIND_SCREENS.get(alert.kind)
result = screener(alert, snap) if screener else _screen_state_alert(alert, snap)
# A still-valid alert can still be the wrong thing to spend time on.
if result["actionable"]:
# Uses the recovered duration: activeAt is reset by pipeline dips, which
# would make every chronic alert look hours old.
age = alert.effective_age_minutes
sla = SLA_HOURS.get(alert.kind)
if sla and age is not None and age > sla * 60 and not alert.is_internal_org:
# The runbook commits to contacting the customer inside this window,
# so age makes it more urgent, not less. Never demote these to chronic.
why = SLA_REASON.get(
alert.kind,
f"past the {sla}h point where the runbook says to contact the customer",
)
return _result(
OVERDUE,
f"Condition has held for {alert.effective_age_text} - {why}. Overdue, not chronic.",
current=result["current_state"],
detail=result["reason"],
)
if age is not None and age > CHRONIC_DAYS * 24 * 60:
note = result["reason"]
if alert.age_is_reset:
note += (f" Prometheus reports only {alert.age_text} because a metric-pipeline dip reset "
"activeAt; the condition itself has held far longer.")
return _result(
CHRONIC,
f"Condition still holds, but it has held for {alert.effective_age_text} - "
"chronic, so it is likely already ticketed rather than new work.",
current=result["current_state"],
detail=note,
)
return result
def screen_all(items: list[Alert], snap: Any, user_settings: Any = None) -> None:
for alert in items:
alert.screen = screen(alert, snap, user_settings)
def summarize(items: list[Alert]) -> dict[str, Any]:
counts: dict[str, int] = {}
for alert in items:
verdict = alert.screen.get("verdict", UNVERIFIED)
counts[verdict] = counts.get(verdict, 0) + 1
return {
"counts": counts,
"actionable": sum(1 for a in items if a.screen.get("actionable")),
"screened_out": sum(1 for a in items if not a.screen.get("actionable")),
"labels": VERDICT_LABELS,
}
def health_warnings(snap: Any) -> list[str]:
"""Rules whose input metrics are empty are broken, not quiet."""
warnings: list[str] = []
for metric in getattr(snap, "broken_inputs", []) or []:
if metric == "openstack_nova_server_status":
warnings.append(
"The OpenStack server metric (openstack_nova_server_status) is currently empty. Any rule built on "
"it is unreliable: 'Exists in Infrahub but does not exist in OpenStack' matches every VM (which is "
"why it is excluded here), and 'Suspected Orphan VM' cannot fire at all. Worth raising with whoever "
"owns the exporter."
)
else:
warnings.append(
f"The metric '{metric}' is currently empty, so alert rules that depend on it are unreliable."
)
dips = getattr(snap, "pipeline_dips", []) or []
if dips:
latest = max(dips, key=lambda d: d["end"])
mins_ago = max(0, int((time.time() - latest["end"]) // 60))
warnings.append(
f"The Infrahub 'Resources' metric dropped most of its series {len(dips)} time(s) in the last 24h "
f"(most recently {mins_ago} min ago: {latest['low']} of ~{latest['normal']} series for "
f"{latest['minutes']} min). Every alert live during a dip resolves and re-fires, so Prometheus' own "
"alert ages all reset together. Ages shown here are recovered from ALERTS history instead."
)
return warnings

View File

@@ -0,0 +1,245 @@
"""User settings: suppression rules and comms identity.
Suppression rules replace hardcoded judgement calls. The internal-organisation
check used to be baked into the screening code, which meant the one person who
knew about it was whoever read the source. Now it ships as an editable default
rule that says what it does and why, and anyone can add their own.
A rule matches when *every* condition it sets matches (AND); within one
condition, any listed value matches (OR). So "type is error AND organisation
contains modal" is one rule with two conditions.
"""
from __future__ import annotations
import json
import os
import re
import threading
import time
import uuid
from typing import Any, Optional
SETTINGS_DIR = os.path.expanduser(os.environ.get("CX_TRIAGE_HOME", "~/.cx-triage"))
SETTINGS_PATH = os.path.join(SETTINGS_DIR, "settings.json")
# Conditions a rule can set. Every one is a substring match, case-insensitive,
# except `kind` and `region` which are exact.
CONDITIONS = {
"kind": "Alert type",
"organization": "Organisation contains",
"instance_name": "VM name contains",
"host": "Host contains",
"region": "Region",
"status": "Status is",
}
DEFAULT_RULES: list[dict[str, Any]] = [
{
"id": "builtin-internal-orgs",
"name": "Internal NexGen organisations",
"enabled": True,
"reason": "Owned by an internal test or platform organisation, not a customer.",
"conditions": {"organization": ["nexgencloud.com"]},
},
{
"id": "builtin-runpod-storage",
"name": "Runpod storage nodes (Luis)",
"enabled": True,
"reason": "Platform-owned storage nodes; SHUTOFF on these is expected and not customer-impacting.",
"conditions": {"kind": ["shutoff"], "instance_name": ["stor-runpod"]},
},
]
DEFAULTS: dict[str, Any] = {
"rules": DEFAULT_RULES,
"agent_name": "",
"chronic_days": 3,
}
def _blank(value: Any) -> bool:
return value is None or str(value).strip() == ""
class Settings:
"""Loaded once, written through on every change."""
def __init__(self, path: str = SETTINGS_PATH):
self.path = path
self._lock = threading.Lock()
self._data: dict[str, Any] = {}
self.load()
# --- persistence -------------------------------------------------------
def load(self) -> None:
data = dict(DEFAULTS)
try:
with open(self.path, encoding="utf-8") as handle:
stored = json.load(handle)
if isinstance(stored, dict):
data.update(stored)
except (OSError, json.JSONDecodeError):
pass
data["rules"] = [r for r in (data.get("rules") or []) if isinstance(r, dict)]
with self._lock:
self._data = data
def save(self) -> None:
with self._lock:
payload = json.dumps(self._data, indent=2, sort_keys=True)
try:
os.makedirs(os.path.dirname(self.path), exist_ok=True)
tmp = f"{self.path}.tmp"
with open(tmp, "w", encoding="utf-8") as handle:
handle.write(payload)
os.replace(tmp, self.path)
except OSError:
pass
# --- accessors ---------------------------------------------------------
@property
def rules(self) -> list[dict[str, Any]]:
with self._lock:
return [dict(r) for r in self._data.get("rules", [])]
@property
def agent_name(self) -> str:
with self._lock:
return str(self._data.get("agent_name") or "")
@property
def chronic_days(self) -> int:
with self._lock:
try:
return max(1, int(self._data.get("chronic_days") or 3))
except (TypeError, ValueError):
return 3
def to_json(self) -> dict[str, Any]:
with self._lock:
return {
"rules": [dict(r) for r in self._data.get("rules", [])],
"agent_name": self._data.get("agent_name") or "",
"chronic_days": self._data.get("chronic_days", 3),
"conditions": CONDITIONS,
"path": self.path,
}
# --- mutations ---------------------------------------------------------
def set_general(self, agent_name: Optional[str] = None, chronic_days: Optional[Any] = None) -> None:
with self._lock:
if agent_name is not None:
self._data["agent_name"] = str(agent_name).strip()
if chronic_days is not None:
try:
self._data["chronic_days"] = max(1, int(chronic_days))
except (TypeError, ValueError):
pass
self.save()
def upsert_rule(self, rule: dict[str, Any]) -> dict[str, Any]:
clean = _normalize_rule(rule)
with self._lock:
rules = self._data.setdefault("rules", [])
for idx, existing in enumerate(rules):
if existing.get("id") == clean["id"]:
rules[idx] = clean
break
else:
rules.append(clean)
self.save()
return clean
def delete_rule(self, rule_id: str) -> None:
with self._lock:
self._data["rules"] = [r for r in self._data.get("rules", []) if r.get("id") != rule_id]
self.save()
def toggle_rule(self, rule_id: str, enabled: bool) -> None:
with self._lock:
for rule in self._data.get("rules", []):
if rule.get("id") == rule_id:
rule["enabled"] = bool(enabled)
self.save()
def _normalize_rule(rule: dict[str, Any]) -> dict[str, Any]:
conditions: dict[str, list[str]] = {}
for field, values in (rule.get("conditions") or {}).items():
if field not in CONDITIONS:
continue
if isinstance(values, str):
values = [v.strip() for v in values.split(",")]
cleaned = [str(v).strip() for v in (values or []) if str(v).strip()]
if cleaned:
conditions[field] = cleaned
return {
"id": str(rule.get("id") or f"rule-{uuid.uuid4().hex[:8]}"),
"name": str(rule.get("name") or "Untitled rule").strip(),
"enabled": bool(rule.get("enabled", True)),
"reason": str(rule.get("reason") or "").strip(),
"conditions": conditions,
"created": rule.get("created") or time.strftime("%Y-%m-%d"),
}
# --- matching ---------------------------------------------------------------
def _alert_field(alert: Any, field: str) -> str:
if field == "kind":
return str(getattr(alert, "kind", ""))
if field == "organization":
return f"{getattr(alert, 'org_id', '')} {getattr(alert, 'org_name', '')}"
if field == "instance_name":
return str(getattr(alert, "instance_name", ""))
if field == "host":
return str(getattr(alert, "host", ""))
if field == "region":
return f"{getattr(alert, 'region', '')} {getattr(alert, 'region_label', '')}"
if field == "status":
return str(getattr(alert, "status", ""))
return ""
def _condition_matches(field: str, values: list[str], alert: Any) -> bool:
actual = _alert_field(alert, field).lower()
if field in ("kind", "status"):
return any(actual == str(v).strip().lower() for v in values)
if field == "region":
return any(str(v).strip().lower() in actual for v in values)
return any(str(v).strip().lower() in actual for v in values)
def rule_matches(rule: dict[str, Any], alert: Any) -> bool:
"""Every condition in the rule must match (AND)."""
conditions = rule.get("conditions") or {}
if not conditions:
return False # an empty rule would swallow the whole queue
return all(_condition_matches(f, v, alert) for f, v in conditions.items())
def first_match(settings: Settings, alert: Any) -> Optional[dict[str, Any]]:
for rule in settings.rules:
if rule.get("enabled") and rule_matches(rule, alert):
return rule
return None
def preview(settings: Settings, rule: dict[str, Any], alerts: list[Any]) -> list[dict[str, Any]]:
"""Which currently-firing alerts a rule would hide - shown before saving."""
clean = _normalize_rule(rule)
hits = []
for alert in alerts:
if rule_matches(clean, alert):
hits.append({
"kind": alert.kind,
"title": alert.title,
"instance_name": alert.instance_name,
"host": alert.host,
"org_name": alert.org_name,
"region": alert.region,
})
return hits