P1-24: live dashboard — fleet summary tiles + host table
Server-rendered HTML view backed by:
- new store.FleetSummary aggregating host counts + repo bytes +
snapshot total + open alerts + last-24h job rollup in two queries.
- GET /api/hosts (JSON list of hosts in the dashboard projection).
- GET /api/fleet/summary (JSON aggregate, same shape as above).
The HTML page (web/templates/pages/dashboard.html) renders the four
summary tiles + host table directly from store data — no separate
fetch. Per-row state colour comes from .host-row.{degraded,failed,
offline} which paint a 3px left edge so problem hosts are scannable
without reading. HTMX is loaded into the base layout so per-row
"Run now" buttons can hx-post to /hosts/{id}/run-backup, a thin
HTML wrapper that funnels into a new dispatchJob helper shared
with the JSON /api/hosts/{id}/jobs endpoint.
Empty state (zero hosts) collapses to the "no hosts yet" prompt
with the + Add host CTA — matches the v1 mockup.
Template helpers (internal/server/ui/funcs.go) added for byte
formatting (412 GB / 3.7 TB), relative time (3m ago / 2d ago), and
comma grouping (1,847). Pure Go, no template-magic dependency.
Browser-verified end-to-end with seeded fixture data: five hosts
across all four states render with correct dots, accents, last-
backup pills, sizes, snapshot counts, alerts, tags, and the right
action button (Run now / Retry / Run first / View → / offline).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
stdhttp "net/http"
|
||||
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
|
||||
)
|
||||
|
||||
// hostView is the JSON projection of a Host row. Same shape as the
|
||||
// store row, but with explicit time-strings so wire format is stable
|
||||
// across DB driver changes.
|
||||
type hostView struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
AgentVersion string `json:"agent_version,omitempty"`
|
||||
ResticVersion string `json:"restic_version,omitempty"`
|
||||
ProtocolVersion int `json:"protocol_version"`
|
||||
EnrolledAt string `json:"enrolled_at"`
|
||||
LastSeenAt *string `json:"last_seen_at,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Tags []string `json:"tags"`
|
||||
CurrentJobID *string `json:"current_job_id,omitempty"`
|
||||
LastBackupAt *string `json:"last_backup_at,omitempty"`
|
||||
LastBackupStatus *string `json:"last_backup_status,omitempty"`
|
||||
RepoSizeBytes int64 `json:"repo_size_bytes"`
|
||||
SnapshotCount int `json:"snapshot_count"`
|
||||
OpenAlertCount int `json:"open_alert_count"`
|
||||
}
|
||||
|
||||
// handleListHosts returns the full fleet as JSON. Authenticated; the
|
||||
// shape mirrors what the dashboard renders, so external API consumers
|
||||
// see the same projection.
|
||||
func (s *Server) handleListHosts(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
return
|
||||
}
|
||||
hosts, err := s.deps.Store.ListHosts(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
}
|
||||
out := make([]hostView, 0, len(hosts))
|
||||
for _, h := range hosts {
|
||||
out = append(out, hostToView(h))
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusOK, map[string]any{
|
||||
"count": len(out),
|
||||
"hosts": out,
|
||||
})
|
||||
}
|
||||
|
||||
// handleFleetSummary returns the dashboard tile aggregate.
|
||||
func (s *Server) handleFleetSummary(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
return
|
||||
}
|
||||
fs, err := s.deps.Store.FleetSummary(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusOK, fs)
|
||||
}
|
||||
|
||||
// hostToView converts a store.Host to its JSON shape. Times become
|
||||
// RFC 3339 strings; nullable times are passed through as nil.
|
||||
func hostToView(h store.Host) hostView {
|
||||
v := hostView{
|
||||
ID: h.ID,
|
||||
Name: h.Name,
|
||||
OS: h.OS,
|
||||
Arch: h.Arch,
|
||||
AgentVersion: h.AgentVersion,
|
||||
ResticVersion: h.ResticVersion,
|
||||
ProtocolVersion: h.ProtocolVersion,
|
||||
EnrolledAt: h.EnrolledAt.Format("2006-01-02T15:04:05.000000000Z"),
|
||||
Status: h.Status,
|
||||
Tags: h.Tags,
|
||||
CurrentJobID: h.CurrentJobID,
|
||||
LastBackupStatus: h.LastBackupStatus,
|
||||
RepoSizeBytes: h.RepoSizeBytes,
|
||||
SnapshotCount: h.SnapshotCount,
|
||||
OpenAlertCount: h.OpenAlertCount,
|
||||
}
|
||||
if v.Tags == nil {
|
||||
v.Tags = []string{}
|
||||
}
|
||||
if h.LastSeenAt != nil {
|
||||
s := h.LastSeenAt.Format("2006-01-02T15:04:05.000000000Z")
|
||||
v.LastSeenAt = &s
|
||||
}
|
||||
if h.LastBackupAt != nil {
|
||||
s := h.LastBackupAt.Format("2006-01-02T15:04:05.000000000Z")
|
||||
v.LastBackupAt = &s
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
stdhttp "net/http"
|
||||
"time"
|
||||
@@ -33,65 +34,76 @@ func (s *Server) handleRunNow(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
return
|
||||
}
|
||||
|
||||
hostID := chi.URLParam(r, "id")
|
||||
if hostID == "" {
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "missing_host_id", "")
|
||||
return
|
||||
}
|
||||
|
||||
var req runNowRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
|
||||
return
|
||||
}
|
||||
if !validJobKind(req.Kind) {
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_kind",
|
||||
"kind must be one of backup|forget|prune|check|unlock")
|
||||
|
||||
res, status, code, msg := s.dispatchJob(r.Context(), user, hostID, req.Kind, req.Args)
|
||||
if code != "" {
|
||||
writeJSONError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusAccepted, res)
|
||||
}
|
||||
|
||||
host, err := s.deps.Store.GetHost(r.Context(), hostID)
|
||||
// dispatchJob is the common path for HTTP-driven job dispatch. It
|
||||
// validates the kind, checks the host is online, persists the job
|
||||
// row, and ships command.run over the WS. Returns:
|
||||
// - res: the queued-job response (job_id + status)
|
||||
// - status: HTTP status to return on failure (or 0 on success)
|
||||
// - code, msg: error code/message for the wire (empty on success)
|
||||
//
|
||||
// JSON callers wrap with writeJSONError; HTML callers translate to
|
||||
// flash banner + redirect.
|
||||
func (s *Server) dispatchJob(ctx context.Context, user *store.User,
|
||||
hostID string, kind api.JobKind, args []string,
|
||||
) (res runNowResponse, status int, code, msg string) {
|
||||
if !validJobKind(kind) {
|
||||
return res, stdhttp.StatusBadRequest, "invalid_kind",
|
||||
"kind must be one of backup|forget|prune|check|unlock"
|
||||
}
|
||||
host, err := s.deps.Store.GetHost(ctx, hostID)
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusNotFound, "host_not_found", "")
|
||||
return
|
||||
return res, stdhttp.StatusNotFound, "host_not_found", ""
|
||||
}
|
||||
|
||||
if !s.deps.Hub.Connected(host.ID) {
|
||||
writeJSONError(w, stdhttp.StatusServiceUnavailable, "host_offline",
|
||||
"agent is not currently connected; try again when it reconnects")
|
||||
return
|
||||
return res, stdhttp.StatusServiceUnavailable, "host_offline",
|
||||
"agent is not currently connected; try again when it reconnects"
|
||||
}
|
||||
|
||||
jobID := ulid.Make().String()
|
||||
now := time.Now().UTC()
|
||||
if err := s.deps.Store.CreateJob(r.Context(), store.Job{
|
||||
if err := s.deps.Store.CreateJob(ctx, store.Job{
|
||||
ID: jobID,
|
||||
HostID: host.ID,
|
||||
Kind: string(req.Kind),
|
||||
Kind: string(kind),
|
||||
ActorKind: "user",
|
||||
ActorID: &user.ID,
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
return res, stdhttp.StatusInternalServerError, "internal", ""
|
||||
}
|
||||
|
||||
env, err := api.Marshal(api.MsgCommandRun, jobID, api.CommandRunPayload{
|
||||
JobID: jobID,
|
||||
Kind: req.Kind,
|
||||
Args: req.Args,
|
||||
Kind: kind,
|
||||
Args: args,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
return res, stdhttp.StatusInternalServerError, "internal", ""
|
||||
}
|
||||
if err := s.deps.Hub.Send(r.Context(), host.ID, env); err != nil {
|
||||
writeJSONError(w, stdhttp.StatusServiceUnavailable, "host_offline", err.Error())
|
||||
return
|
||||
if err := s.deps.Hub.Send(ctx, host.ID, env); err != nil {
|
||||
return res, stdhttp.StatusServiceUnavailable, "host_offline", err.Error()
|
||||
}
|
||||
|
||||
_ = s.deps.Store.AppendAudit(r.Context(), store.AuditEntry{
|
||||
_ = s.deps.Store.AppendAudit(ctx, store.AuditEntry{
|
||||
ID: ulid.Make().String(),
|
||||
UserID: &user.ID,
|
||||
Actor: "user",
|
||||
@@ -100,11 +112,7 @@ func (s *Server) handleRunNow(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
TargetID: &jobID,
|
||||
TS: now,
|
||||
})
|
||||
|
||||
writeJSON(w, stdhttp.StatusAccepted, runNowResponse{
|
||||
JobID: jobID,
|
||||
Status: "queued",
|
||||
})
|
||||
return runNowResponse{JobID: jobID, Status: "queued"}, 0, "", ""
|
||||
}
|
||||
|
||||
// requireUser resolves the session cookie to a user row. Stub of the
|
||||
|
||||
@@ -88,6 +88,10 @@ func (s *Server) routes(r chi.Router) {
|
||||
// host page can call it; for now just the create endpoint.
|
||||
r.Post("/enrollment-tokens", s.handleCreateEnrollmentToken)
|
||||
|
||||
// Fleet read endpoints — back the dashboard.
|
||||
r.Get("/hosts", s.handleListHosts)
|
||||
r.Get("/fleet/summary", s.handleFleetSummary)
|
||||
|
||||
// Run-now: dispatch a job to a host's agent.
|
||||
r.Post("/hosts/{id}/jobs", s.handleRunNow)
|
||||
|
||||
@@ -127,6 +131,8 @@ func (s *Server) routes(r chi.Router) {
|
||||
r.Get("/login", s.handleUILoginGet)
|
||||
r.Post("/login", s.handleUILoginPost)
|
||||
r.Post("/logout", s.handleUILogoutPost)
|
||||
// HTMX action endpoint for "Run now" buttons on the dashboard.
|
||||
r.Post("/hosts/{id}/run-backup", s.handleUIRunBackup)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ import (
|
||||
"log/slog"
|
||||
stdhttp "net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/api"
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/auth"
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/server/ui"
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
|
||||
@@ -91,6 +94,13 @@ func (s *Server) version() string {
|
||||
|
||||
// ----- handlers -------------------------------------------------------
|
||||
|
||||
// dashboardPage is the data the dashboard template renders against.
|
||||
type dashboardPage struct {
|
||||
Hosts []store.Host
|
||||
HostCount int
|
||||
Summary store.FleetSummary
|
||||
}
|
||||
|
||||
// handleUIDashboard is the root page. Auth-gated; falls through to
|
||||
// /login if there is no session.
|
||||
func (s *Server) handleUIDashboard(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
@@ -98,13 +108,76 @@ func (s *Server) handleUIDashboard(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
|
||||
hosts, err := s.deps.Store.ListHosts(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("ui dashboard: list hosts", "err", err)
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
summary, err := s.deps.Store.FleetSummary(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("ui dashboard: fleet summary", "err", err)
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view.OpenAlerts = summary.OpenAlerts
|
||||
view.Page = dashboardPage{
|
||||
Hosts: hosts,
|
||||
HostCount: len(hosts),
|
||||
Summary: summary,
|
||||
}
|
||||
if err := s.deps.UI.Render(w, "dashboard", view); err != nil {
|
||||
slog.Error("ui: render dashboard", "err", err)
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// handleUIRunBackup is the form-submit twin of POST /api/hosts/{id}/jobs
|
||||
// that the dashboard's "Run now" buttons call via hx-post. Returns
|
||||
// 204 on success — HTMX swap=none means "did the thing, no DOM
|
||||
// change needed." Failures return text in the body so HTMX's
|
||||
// response-header inspection surfaces it.
|
||||
func (s *Server) handleUIRunBackup(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
u := s.requireUIUser(w, r)
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
if hostID == "" {
|
||||
stdhttp.Error(w, "missing host id", stdhttp.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
storeUser, _, err := s.userByID(r, u.ID)
|
||||
if err != nil {
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_, status, code, msg := s.dispatchJob(r.Context(), storeUser, hostID, api.JobBackup, nil)
|
||||
if code != "" {
|
||||
stdhttp.Error(w, msg, status)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(stdhttp.StatusNoContent)
|
||||
}
|
||||
|
||||
// userByID fetches the full store.User the UI session represents.
|
||||
// Returns the user, ok-flag, error. Used by handlers that need the
|
||||
// store-side row (e.g. for audit_log.user_id) rather than just the
|
||||
// projected ui.User.
|
||||
func (s *Server) userByID(r *stdhttp.Request, id string) (*store.User, bool, error) {
|
||||
u, err := s.deps.Store.GetUserByID(r.Context(), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
return u, true, nil
|
||||
}
|
||||
|
||||
// handleUILoginGet renders the login form. If the user is already
|
||||
// signed in we redirect them home — login is for the unauthenticated.
|
||||
func (s *Server) handleUILoginGet(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
|
||||
Reference in New Issue
Block a user