289 lines
10 KiB
Python
289 lines
10 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
from typing import Any
|
|
|
|
_PRESSURE_TYPES = {
|
|
"MemoryPressure",
|
|
"DiskPressure",
|
|
"PIDPressure",
|
|
"NetworkUnavailable",
|
|
}
|
|
|
|
|
|
def _node_ready(conditions: Any) -> bool:
|
|
if not isinstance(conditions, list):
|
|
return False
|
|
for condition in conditions:
|
|
if not isinstance(condition, dict):
|
|
continue
|
|
if condition.get("type") == "Ready":
|
|
return condition.get("status") == "True"
|
|
return False
|
|
|
|
|
|
def _node_labels(labels: dict[str, Any]) -> dict[str, Any]:
|
|
if not isinstance(labels, dict):
|
|
return {}
|
|
keep: dict[str, Any] = {}
|
|
for key, value in labels.items():
|
|
if key.startswith("node-role.kubernetes.io/"):
|
|
keep[key] = value
|
|
if key in {
|
|
"kubernetes.io/arch",
|
|
"kubernetes.io/hostname",
|
|
"beta.kubernetes.io/arch",
|
|
"hardware",
|
|
"jetson",
|
|
}:
|
|
keep[key] = value
|
|
return keep
|
|
|
|
|
|
def _node_addresses(status: dict[str, Any]) -> dict[str, str]:
|
|
addresses = status.get("addresses") if isinstance(status.get("addresses"), list) else []
|
|
output: dict[str, str] = {}
|
|
for addr in addresses:
|
|
if not isinstance(addr, dict):
|
|
continue
|
|
addr_type = addr.get("type")
|
|
addr_value = addr.get("address")
|
|
if isinstance(addr_type, str) and isinstance(addr_value, str):
|
|
output[addr_type] = addr_value
|
|
return output
|
|
|
|
|
|
def _age_hours(timestamp: str) -> float | None:
|
|
if not timestamp:
|
|
return None
|
|
try:
|
|
parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
return round((datetime.now(timezone.utc) - parsed).total_seconds() / 3600, 1)
|
|
|
|
|
|
def _node_taints(raw: Any) -> list[dict[str, str]]:
|
|
if not isinstance(raw, list):
|
|
return []
|
|
taints: list[dict[str, str]] = []
|
|
for entry in raw:
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
key = entry.get("key")
|
|
effect = entry.get("effect")
|
|
value = entry.get("value")
|
|
if isinstance(key, str) and isinstance(effect, str):
|
|
taints.append(
|
|
{
|
|
"key": key,
|
|
"value": value if isinstance(value, str) else "",
|
|
"effect": effect,
|
|
}
|
|
)
|
|
return taints
|
|
|
|
|
|
def _node_capacity(raw: Any) -> dict[str, str]:
|
|
if not isinstance(raw, dict):
|
|
return {}
|
|
output: dict[str, str] = {}
|
|
for key in ("cpu", "memory", "pods", "ephemeral-storage"):
|
|
value = raw.get(key)
|
|
if isinstance(value, (str, int, float)) and value != "":
|
|
output[key] = str(value)
|
|
return output
|
|
|
|
|
|
def _node_pressure_conditions(conditions: Any) -> dict[str, bool]:
|
|
if not isinstance(conditions, list):
|
|
return {}
|
|
pressure: dict[str, bool] = {}
|
|
for condition in conditions:
|
|
if not isinstance(condition, dict):
|
|
continue
|
|
cond_type = condition.get("type")
|
|
if cond_type in _PRESSURE_TYPES:
|
|
pressure[cond_type] = condition.get("status") == "True"
|
|
return pressure
|
|
|
|
|
|
def _node_roles(labels: dict[str, Any]) -> list[str]:
|
|
roles: list[str] = []
|
|
for key in labels.keys():
|
|
if key.startswith("node-role.kubernetes.io/"):
|
|
role = key.split("/", 1)[-1]
|
|
if role:
|
|
roles.append(role)
|
|
return sorted(set(roles))
|
|
|
|
|
|
def _node_is_worker(labels: dict[str, Any]) -> bool:
|
|
if "node-role.kubernetes.io/control-plane" in labels:
|
|
return False
|
|
if "node-role.kubernetes.io/master" in labels:
|
|
return False
|
|
if "node-role.kubernetes.io/worker" in labels:
|
|
return True
|
|
return True
|
|
|
|
|
|
def _hardware_hint(labels: dict[str, Any], node_info: dict[str, Any]) -> str:
|
|
result = "unknown"
|
|
if str(labels.get("jetson") or "").lower() == "true":
|
|
result = "jetson"
|
|
else:
|
|
hardware = (labels.get("hardware") or "").strip().lower()
|
|
if hardware:
|
|
result = hardware
|
|
else:
|
|
kernel = str(node_info.get("kernelVersion") or "").lower()
|
|
os_image = str(node_info.get("osImage") or "").lower()
|
|
if "tegra" in kernel or "jetson" in os_image:
|
|
result = "jetson"
|
|
elif "raspi" in kernel or "bcm2711" in kernel:
|
|
result = "rpi"
|
|
else:
|
|
arch = str(node_info.get("architecture") or "").lower()
|
|
if arch == "amd64":
|
|
result = "amd64"
|
|
elif arch == "arm64":
|
|
result = "arm64-unknown"
|
|
return result
|
|
|
|
|
|
def _node_details(payload: dict[str, Any]) -> list[dict[str, Any]]:
|
|
details: list[dict[str, Any]] = []
|
|
for node in payload.get("items") if isinstance(payload.get("items"), list) else []:
|
|
if not isinstance(node, dict):
|
|
continue
|
|
metadata = node.get("metadata") if isinstance(node.get("metadata"), dict) else {}
|
|
spec = node.get("spec") if isinstance(node.get("spec"), dict) else {}
|
|
status = node.get("status") if isinstance(node.get("status"), dict) else {}
|
|
node_info = status.get("nodeInfo") if isinstance(status.get("nodeInfo"), dict) else {}
|
|
labels = metadata.get("labels") if isinstance(metadata.get("labels"), dict) else {}
|
|
name = metadata.get("name") if isinstance(metadata.get("name"), str) else ""
|
|
if not name:
|
|
continue
|
|
created_at = metadata.get("creationTimestamp") if isinstance(metadata.get("creationTimestamp"), str) else ""
|
|
taints = _node_taints(spec.get("taints"))
|
|
details.append(
|
|
{
|
|
"name": name,
|
|
"ready": _node_ready(status.get("conditions")),
|
|
"roles": _node_roles(labels),
|
|
"is_worker": _node_is_worker(labels),
|
|
"labels": labels,
|
|
"hardware": _hardware_hint(labels, node_info),
|
|
"arch": node_info.get("architecture") or "",
|
|
"os": node_info.get("operatingSystem") or "",
|
|
"kernel": node_info.get("kernelVersion") or "",
|
|
"kubelet": node_info.get("kubeletVersion") or "",
|
|
"container_runtime": node_info.get("containerRuntimeVersion") or "",
|
|
"addresses": _node_addresses(status),
|
|
"created_at": created_at,
|
|
"age_hours": _age_hours(created_at),
|
|
"taints": taints,
|
|
"unschedulable": bool(spec.get("unschedulable")),
|
|
"capacity": _node_capacity(status.get("capacity")),
|
|
"allocatable": _node_capacity(status.get("allocatable")),
|
|
"pressure": _node_pressure_conditions(status.get("conditions")),
|
|
}
|
|
)
|
|
details.sort(key=lambda item: item.get("name") or "")
|
|
return details
|
|
|
|
|
|
def _node_age_stats(details: list[dict[str, Any]]) -> dict[str, Any]:
|
|
ages: list[tuple[str, float]] = []
|
|
for node in details:
|
|
name = node.get("name") if isinstance(node, dict) else ""
|
|
age = node.get("age_hours")
|
|
if isinstance(name, str) and name and isinstance(age, (int, float)):
|
|
ages.append((name, float(age)))
|
|
if not ages:
|
|
return {}
|
|
ages.sort(key=lambda item: item[1])
|
|
values = [age for _, age in ages]
|
|
return {
|
|
"min": round(min(values), 1),
|
|
"max": round(max(values), 1),
|
|
"avg": round(sum(values) / len(values), 1),
|
|
"youngest": [{"name": name, "age_hours": age} for name, age in ages[:5]],
|
|
"oldest": [{"name": name, "age_hours": age} for name, age in ages[-5:]],
|
|
}
|
|
|
|
|
|
def _node_flagged(details: list[dict[str, Any]], key: str) -> list[str]:
|
|
names: list[str] = []
|
|
for node in details:
|
|
name = node.get("name") if isinstance(node, dict) else ""
|
|
if not isinstance(name, str) or not name:
|
|
continue
|
|
if node.get(key):
|
|
names.append(name)
|
|
names.sort()
|
|
return names
|
|
|
|
|
|
def _apply_node_summary(summary: dict[str, Any], node: dict[str, Any]) -> str:
|
|
name = node.get("name") if isinstance(node.get("name"), str) else ""
|
|
if not name:
|
|
return ""
|
|
summary["total"] += 1
|
|
if node.get("ready"):
|
|
summary["ready"] += 1
|
|
if node.get("is_worker"):
|
|
summary["workers"]["total"] += 1
|
|
if node.get("ready"):
|
|
summary["workers"]["ready"] += 1
|
|
hardware = str(node.get("hardware") or "unknown")
|
|
summary["by_hardware"][hardware] = summary["by_hardware"].get(hardware, 0) + 1
|
|
arch = str(node.get("arch") or "unknown")
|
|
summary["by_arch"][arch] = summary["by_arch"].get(arch, 0) + 1
|
|
for role in node.get("roles") or []:
|
|
summary["by_role"][role] = summary["by_role"].get(role, 0) + 1
|
|
_apply_pressure(summary, node, name)
|
|
return name
|
|
|
|
|
|
def _apply_pressure(summary: dict[str, Any], node: dict[str, Any], name: str) -> None:
|
|
pressure = node.get("pressure") or {}
|
|
if not isinstance(pressure, dict):
|
|
return
|
|
for cond_type, active in pressure.items():
|
|
if active and cond_type in summary["pressure_nodes"]:
|
|
summary["pressure_nodes"][cond_type].append(name)
|
|
|
|
|
|
def _summarize_inventory(details: list[dict[str, Any]]) -> dict[str, Any]:
|
|
summary = {
|
|
"total": 0,
|
|
"ready": 0,
|
|
"workers": {"total": 0, "ready": 0},
|
|
"by_hardware": {},
|
|
"by_arch": {},
|
|
"by_role": {},
|
|
"not_ready_names": [],
|
|
"pressure_nodes": {key: [] for key in _PRESSURE_TYPES},
|
|
"age_stats": {},
|
|
"tainted_nodes": [],
|
|
"unschedulable_nodes": [],
|
|
}
|
|
not_ready: list[str] = []
|
|
for node in details:
|
|
name = _apply_node_summary(summary, node)
|
|
if name and not node.get("ready"):
|
|
not_ready.append(name)
|
|
not_ready.sort()
|
|
summary["not_ready_names"] = not_ready
|
|
for cond_type in summary["pressure_nodes"]:
|
|
summary["pressure_nodes"][cond_type].sort()
|
|
summary["age_stats"] = _node_age_stats(details)
|
|
summary["tainted_nodes"] = _node_flagged(details, "taints")
|
|
summary["unschedulable_nodes"] = _node_flagged(details, "unschedulable")
|
|
return summary
|
|
|
|
|
|
__all__ = [name for name in globals() if not name.startswith("__")]
|