dashboard/app/routers/disks.py

52 lines
1.6 KiB
Python

import time
from typing import Any
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from app.collect import disks as disk_col
from app.render import render
router = APIRouter(prefix="/api", tags=["disks"])
_prev: dict[str, Any] | None = None
_prev_t: float = 0.0
@router.get("/disks")
async def disks(_request: Request):
"""Render the Disks tab fragment: partition usage + per-disk rates.
Per-disk read/write rates are computed from the delta between this
request's counters and the previous request's (module-level state,
so rates depend on poll frequency and are 0 on the first hit).
Args:
_request: FastAPI request (unused beyond app state access).
Returns:
The rendered disks.html as an HTMLResponse.
"""
global _prev, _prev_t
now = time.monotonic()
cur = disk_col.counters()
per_disk: list[dict[str, Any]] = []
dt = (now - _prev_t) if _prev is not None and _prev_t else 0.0
for name, c in sorted(cur.items()):
p = (_prev or {}).get(name)
per_disk.append(
{
"device": name,
"read_rate": (c.read_bytes - p.read_bytes) / dt if p and dt > 0 else 0.0,
"write_rate": (c.write_bytes - p.write_bytes) / dt if p and dt > 0 else 0.0,
"reads": c.read_count,
"writes": c.write_count,
"read_bytes": c.read_bytes,
"write_bytes": c.write_bytes,
}
)
_prev = cur
_prev_t = now
return HTMLResponse(
render("disks.html", partitions=disk_col.partitions(), per_disk=per_disk)
)