feat(dashboard): phase C richer panels — host time-series graph + cpu sparklines
Milestone 72 phase C — bring the host-view graphs onto the dashboard:
- host_resource_history widget reworked into a real host-view chart: epoch-ms
linear axis (no Chart.js date adapter), themed like the host-detail charts,
maintainAspectRatio:false so it fills the resized panel, unique canvas per
widget instance (wid), and empty states ("pick a host" / "no metrics yet").
Was previously unusable — it had a broken time axis and no way to choose a host.
- Add a "host" param type: the edit form renders a live dropdown of hosts
(dashboard routes now pass the host list to the editor); the chosen host_id is
stored in config and fed to the widget.
- Hosts-overview widget gains a per-row CPU sparkline (last hour) via the shared
sparkline_svg helper — the host-view at-a-glance trend, on the main widget.
Charts/sparklines render only in the browser, so CI can't exercise them — needs
an operator visual check.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -387,34 +387,44 @@ async def widget_table():
|
|||||||
@host_agent_bp.get("/widget/history")
|
@host_agent_bp.get("/widget/history")
|
||||||
async def widget_history():
|
async def widget_history():
|
||||||
host_id = request.args.get("host_id", "")
|
host_id = request.args.get("host_id", "")
|
||||||
hours = int(request.args.get("hours", "6"))
|
try:
|
||||||
|
hours = max(1, min(168, int(request.args.get("hours", "6"))))
|
||||||
|
except ValueError:
|
||||||
|
hours = 6
|
||||||
|
# wid (the dashboard widget row id) keeps the <canvas> id unique when several
|
||||||
|
# history widgets share a page; fall back to the host id.
|
||||||
|
wid = request.args.get("wid", "") or host_id
|
||||||
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
||||||
|
|
||||||
async with current_app.db_sessionmaker() as session:
|
series: dict[str, list[list]] = {"cpu_pct": [], "mem_used_pct": [], "disk_root": []}
|
||||||
host = (await session.execute(
|
host = None
|
||||||
select(Host).where(Host.id == host_id))).scalar_one_or_none()
|
if host_id:
|
||||||
if host is None:
|
async with current_app.db_sessionmaker() as session:
|
||||||
return _error(404, "not_found")
|
host = (await session.execute(
|
||||||
points = (await session.execute(
|
select(Host).where(Host.id == host_id))).scalar_one_or_none()
|
||||||
select(PluginMetric).where(
|
if host is not None:
|
||||||
PluginMetric.source_module == SOURCE_MODULE,
|
points = (await session.execute(
|
||||||
PluginMetric.recorded_at >= cutoff,
|
select(PluginMetric).where(
|
||||||
or_(
|
PluginMetric.source_module == SOURCE_MODULE,
|
||||||
and_(PluginMetric.resource_name == host.name,
|
PluginMetric.recorded_at >= cutoff,
|
||||||
PluginMetric.metric_name.in_(("cpu_pct", "mem_used_pct"))),
|
or_(
|
||||||
and_(PluginMetric.resource_name == host.name + ":/",
|
and_(PluginMetric.resource_name == host.name,
|
||||||
PluginMetric.metric_name == "disk_used_pct"),
|
PluginMetric.metric_name.in_(("cpu_pct", "mem_used_pct"))),
|
||||||
),
|
and_(PluginMetric.resource_name == host.name + ":/",
|
||||||
).order_by(PluginMetric.recorded_at)
|
PluginMetric.metric_name == "disk_used_pct"),
|
||||||
)).scalars().all()
|
),
|
||||||
|
).order_by(PluginMetric.recorded_at)
|
||||||
|
)).scalars().all()
|
||||||
|
# Disk = root (/), consistent with the host panel — not "worst".
|
||||||
|
# Epoch-ms x values let the chart use a plain linear axis (no
|
||||||
|
# Chart.js date adapter needed), matching the host-detail charts.
|
||||||
|
for p in points:
|
||||||
|
key = "disk_root" if p.resource_name != host.name else p.metric_name
|
||||||
|
series[key].append([int(p.recorded_at.timestamp() * 1000), round(p.value, 2)])
|
||||||
|
|
||||||
# Disk = root (/), consistent with the host panel — not the opaque "worst".
|
return await render_template(
|
||||||
series: dict[str, list[dict]] = {"cpu_pct": [], "mem_used_pct": [], "disk_root": []}
|
"widget_history.html", host=host, series=series, hours=hours, wid=wid,
|
||||||
for p in points:
|
)
|
||||||
key = "disk_root" if p.resource_name != host.name else p.metric_name
|
|
||||||
series[key].append({"t": p.recorded_at.isoformat(), "v": p.value})
|
|
||||||
|
|
||||||
return await render_template("widget_history.html", host=host, series=series, hours=hours)
|
|
||||||
|
|
||||||
|
|
||||||
# Host-level metrics charted on the detail page (sub-resources are shown as
|
# Host-level metrics charted on the detail page (sub-resources are shown as
|
||||||
|
|||||||
@@ -1,24 +1,53 @@
|
|||||||
<div class="widget-history">
|
{# host_agent history-graph widget — the host-view utilization chart, embedded
|
||||||
<h3>{{ host.name }} — last {{ hours }}h</h3>
|
on a dashboard. Fills the (resizable) panel; epoch-ms linear axis so no
|
||||||
<canvas id="host-agent-chart-{{ host.id }}" width="600" height="200"></canvas>
|
Chart.js date adapter is needed. #}
|
||||||
<script>
|
{% set has_data = host and (series.cpu_pct or series.mem_used_pct or series.disk_root) %}
|
||||||
(function() {
|
{% if not host %}
|
||||||
const ctx = document.getElementById("host-agent-chart-{{ host.id }}").getContext("2d");
|
<div style="color:var(--text-muted);font-size:0.85rem;padding:0.75rem 0;">
|
||||||
const series = {{ series|tojson }};
|
No host selected. <strong>Edit</strong> this dashboard and pick a host for this graph.
|
||||||
new Chart(ctx, {
|
|
||||||
type: "line",
|
|
||||||
data: {
|
|
||||||
datasets: [
|
|
||||||
{ label: "CPU %", data: series.cpu_pct.map(p => ({x: p.t, y: p.v})) },
|
|
||||||
{ label: "Mem %", data: series.mem_used_pct.map(p => ({x: p.t, y: p.v})) },
|
|
||||||
{ label: "Disk / %", data: series.disk_root.map(p => ({x: p.t, y: p.v})) },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
scales: { x: { type: "time" }, y: { min: 0, max: 100 } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
</div>
|
</div>
|
||||||
|
{% elif not has_data %}
|
||||||
|
<div style="color:var(--text-muted);font-size:0.85rem;padding:0.75rem 0;">
|
||||||
|
No agent metrics for <strong>{{ host.name }}</strong> in the last {{ hours }}h yet.
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div style="height:100%;min-height:180px;position:relative;">
|
||||||
|
<canvas id="host-hist-{{ wid }}"></canvas>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var el = document.getElementById("host-hist-{{ wid }}");
|
||||||
|
if (!el) return;
|
||||||
|
var series = {{ series|tojson }};
|
||||||
|
var fmtTime = function (v) {
|
||||||
|
var d = new Date(v);
|
||||||
|
return ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
|
||||||
|
};
|
||||||
|
var ds = [
|
||||||
|
{ key: "cpu_pct", label: "CPU %", color: "#c8a840" },
|
||||||
|
{ key: "mem_used_pct", label: "Mem %", color: "#4aa86a" },
|
||||||
|
{ key: "disk_root", label: "Disk / %", color: "#c87840" },
|
||||||
|
];
|
||||||
|
new Chart(el.getContext("2d"), {
|
||||||
|
type: "line",
|
||||||
|
data: { datasets: ds.map(function (d) {
|
||||||
|
return {
|
||||||
|
label: d.label,
|
||||||
|
data: (series[d.key] || []).map(function (p) { return { x: p[0], y: p[1] }; }),
|
||||||
|
borderColor: d.color, backgroundColor: d.color, borderWidth: 1.5, tension: 0.25,
|
||||||
|
};
|
||||||
|
}) },
|
||||||
|
options: {
|
||||||
|
responsive: true, maintainAspectRatio: false,
|
||||||
|
interaction: { mode: "index", intersect: false },
|
||||||
|
elements: { point: { radius: 0 } },
|
||||||
|
scales: {
|
||||||
|
x: { type: "linear", ticks: { callback: function (v) { return fmtTime(v); }, maxTicksLimit: 6, color: "#8a8a92", font: { size: 10 } }, grid: { color: "#30303a" } },
|
||||||
|
y: { beginAtZero: true, max: 100, ticks: { color: "#8a8a92", font: { size: 10 } }, grid: { color: "#30303a" } },
|
||||||
|
},
|
||||||
|
plugins: { legend: { labels: { color: "#b8b8b0", boxWidth: 10, font: { size: 11 } } } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% endif %}
|
||||||
|
|||||||
+10
-3
@@ -279,13 +279,20 @@ WIDGET_REGISTRY: dict[str, dict] = {
|
|||||||
},
|
},
|
||||||
"host_resource_history": {
|
"host_resource_history": {
|
||||||
"key": "host_resource_history",
|
"key": "host_resource_history",
|
||||||
"label": "Host Agent — History",
|
"label": "Host Agent — History Graph",
|
||||||
"description": "CPU/memory/disk history for one host",
|
"description": "CPU / memory / disk time-series graph for one host (the host-view chart, on your dashboard)",
|
||||||
"hx_url": "/plugins/host_agent/widget/history",
|
"hx_url": "/plugins/host_agent/widget/history",
|
||||||
"detail_url": "/plugins/host_agent/fleet/",
|
"detail_url": "/hosts/",
|
||||||
"plugin": "host_agent",
|
"plugin": "host_agent",
|
||||||
"poll": True,
|
"poll": True,
|
||||||
"params": [
|
"params": [
|
||||||
|
# type "host" → the edit form renders a live dropdown of hosts.
|
||||||
|
{
|
||||||
|
"key": "host_id",
|
||||||
|
"label": "Host",
|
||||||
|
"type": "host",
|
||||||
|
"default": "",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "hours",
|
"key": "hours",
|
||||||
"label": "Time range",
|
"label": "Time range",
|
||||||
|
|||||||
@@ -173,7 +173,7 @@ async def _get_panels_data(db, dashboard_id: int) -> tuple:
|
|||||||
result = await db.execute(select(Dashboard).where(Dashboard.id == dashboard_id))
|
result = await db.execute(select(Dashboard).where(Dashboard.id == dashboard_id))
|
||||||
dash = result.scalar_one_or_none()
|
dash = result.scalar_one_or_none()
|
||||||
if dash is None:
|
if dash is None:
|
||||||
return None, [], []
|
return None, [], [], []
|
||||||
widgets = await _get_widgets(db, dashboard_id)
|
widgets = await _get_widgets(db, dashboard_id)
|
||||||
plugins_cfg = current_app.config.get("PLUGINS", {})
|
plugins_cfg = current_app.config.get("PLUGINS", {})
|
||||||
available = get_available_widgets(plugins_cfg)
|
available = get_available_widgets(plugins_cfg)
|
||||||
@@ -182,15 +182,17 @@ async def _get_panels_data(db, dashboard_id: int) -> tuple:
|
|||||||
{"db": w, "defn": WIDGET_REGISTRY[w.widget_key], "title": w.title or WIDGET_REGISTRY[w.widget_key]["label"]}
|
{"db": w, "defn": WIDGET_REGISTRY[w.widget_key], "title": w.title or WIDGET_REGISTRY[w.widget_key]["label"]}
|
||||||
for w in widgets if w.widget_key in WIDGET_REGISTRY
|
for w in widgets if w.widget_key in WIDGET_REGISTRY
|
||||||
]
|
]
|
||||||
return dash, resolved, available
|
# Hosts feed the "host" param dropdown (e.g. the history-graph widget).
|
||||||
|
hosts = list((await db.execute(select(Host).order_by(Host.name))).scalars())
|
||||||
|
return dash, resolved, available, hosts
|
||||||
|
|
||||||
|
|
||||||
async def _panels_response(dashboard_id: int):
|
async def _panels_response(dashboard_id: int):
|
||||||
async with current_app.db_sessionmaker() as db:
|
async with current_app.db_sessionmaker() as db:
|
||||||
dash, resolved, addable = await _get_panels_data(db, dashboard_id)
|
dash, resolved, addable, hosts = await _get_panels_data(db, dashboard_id)
|
||||||
return await render_template(
|
return await render_template(
|
||||||
"dashboard/_edit_panels.html",
|
"dashboard/_edit_panels.html",
|
||||||
dashboard=dash, widgets=resolved, addable=addable,
|
dashboard=dash, widgets=resolved, addable=addable, hosts=hosts,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -369,12 +371,12 @@ async def edit(dash_id: int):
|
|||||||
user_id = current_user_id()
|
user_id = current_user_id()
|
||||||
user_role = session.get("user_role", "viewer")
|
user_role = session.get("user_role", "viewer")
|
||||||
async with current_app.db_sessionmaker() as db:
|
async with current_app.db_sessionmaker() as db:
|
||||||
dash, resolved, addable = await _get_panels_data(db, dash_id)
|
dash, resolved, addable, hosts = await _get_panels_data(db, dash_id)
|
||||||
if dash is None or not _can_edit(dash, user_id, user_role):
|
if dash is None or not _can_edit(dash, user_id, user_role):
|
||||||
abort(403)
|
abort(403)
|
||||||
return await render_template(
|
return await render_template(
|
||||||
"dashboard/edit.html",
|
"dashboard/edit.html",
|
||||||
dashboard=dash, widgets=resolved, addable=addable,
|
dashboard=dash, widgets=resolved, addable=addable, hosts=hosts,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+34
-2
@@ -153,6 +153,36 @@ async def _agent_overview_by_host(db, host_names: list[str]) -> dict[str, dict]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def _agent_cpu_sparks_by_host(db, host_names: list[str], hours: int = 1) -> dict[str, str]:
|
||||||
|
"""{host_name: inline-SVG cpu sparkline} over the last `hours` (core-safe).
|
||||||
|
|
||||||
|
A tiny at-a-glance trend in each row — the host-view sparkline, on the widget.
|
||||||
|
"""
|
||||||
|
from steward.models.metrics import PluginMetric
|
||||||
|
from steward.core.status import sparkline_svg
|
||||||
|
if not host_names:
|
||||||
|
return {}
|
||||||
|
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
||||||
|
rows = (await db.execute(
|
||||||
|
select(PluginMetric.resource_name, PluginMetric.value, PluginMetric.recorded_at)
|
||||||
|
.where(
|
||||||
|
PluginMetric.source_module == "host_agent",
|
||||||
|
PluginMetric.metric_name == "cpu_pct",
|
||||||
|
PluginMetric.resource_name.in_(host_names),
|
||||||
|
PluginMetric.recorded_at >= cutoff,
|
||||||
|
)
|
||||||
|
.order_by(PluginMetric.recorded_at)
|
||||||
|
)).all()
|
||||||
|
by_host: dict[str, list[float]] = {}
|
||||||
|
for r in rows:
|
||||||
|
by_host.setdefault(r.resource_name, []).append(r.value)
|
||||||
|
# Amber line to read as "CPU"; only draw when there are a couple of points.
|
||||||
|
return {
|
||||||
|
name: sparkline_svg(vals[-40:], width=64, height=18, stroke="#c8a840")
|
||||||
|
for name, vals in by_host.items() if len(vals) >= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@hosts_bp.get("/overview/widget")
|
@hosts_bp.get("/overview/widget")
|
||||||
@require_role(UserRole.viewer)
|
@require_role(UserRole.viewer)
|
||||||
async def overview_widget():
|
async def overview_widget():
|
||||||
@@ -180,12 +210,14 @@ async def overview_widget():
|
|||||||
& (DnsResult.resolved_at == latest_dns_subq.c.max_at),
|
& (DnsResult.resolved_at == latest_dns_subq.c.max_at),
|
||||||
))).scalars()}
|
))).scalars()}
|
||||||
uptime = await _compute_uptime(db)
|
uptime = await _compute_uptime(db)
|
||||||
agent = await _agent_overview_by_host(db, [h.name for h in hosts])
|
host_names = [h.name for h in hosts]
|
||||||
|
agent = await _agent_overview_by_host(db, host_names)
|
||||||
|
cpu_sparks = await _agent_cpu_sparks_by_host(db, host_names)
|
||||||
|
|
||||||
return await render_template(
|
return await render_template(
|
||||||
"hosts/overview_widget.html",
|
"hosts/overview_widget.html",
|
||||||
hosts=hosts, latest_pings=latest_pings, latest_dns=latest_dns,
|
hosts=hosts, latest_pings=latest_pings, latest_dns=latest_dns,
|
||||||
uptime=uptime, agent=agent,
|
uptime=uptime, agent=agent, cpu_sparks=cpu_sparks,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -92,6 +92,16 @@
|
|||||||
</option>
|
</option>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</select>
|
</select>
|
||||||
|
{% elif p.type == "host" %}
|
||||||
|
<select name="param_{{ p.key }}" required
|
||||||
|
style="width:100%;padding:0.32rem 0.6rem;background:var(--bg);
|
||||||
|
border:1px solid var(--border-mid);border-radius:4px;
|
||||||
|
color:var(--text);font-size:0.85rem;">
|
||||||
|
<option value="">— select a host —</option>
|
||||||
|
{% for h in hosts %}
|
||||||
|
<option value="{{ h.id }}">{{ h.name }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
{% else %}
|
{% else %}
|
||||||
<span title="{{ host.name }}" style="{{ name_style }}">{{ host.name }}</span>
|
<span title="{{ host.name }}" style="{{ name_style }}">{{ host.name }}</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
{% set spark = cpu_sparks.get(host.name) %}
|
||||||
|
{% if spark %}<span title="CPU — last hour" style="flex-shrink:0;line-height:0;opacity:0.85;">{{ spark | safe }}</span>{% endif %}
|
||||||
<span style="display:flex;gap:0.75rem;font-variant-numeric:tabular-nums;color:var(--text-muted);font-size:0.75rem;flex-shrink:0;">
|
<span style="display:flex;gap:0.75rem;font-variant-numeric:tabular-nums;color:var(--text-muted);font-size:0.75rem;flex-shrink:0;">
|
||||||
{# Monitors #}
|
{# Monitors #}
|
||||||
{% if host.ping_enabled and ping and ping.response_time_ms is not none %}
|
{% if host.ping_enabled and ping and ping.response_time_ms is not none %}
|
||||||
|
|||||||
Reference in New Issue
Block a user