package api import ( "context" "encoding/json" "errors" "net/http" "slices" "strconv" "strings" "time" "github.com/a-h/templ" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) // upcomingHorizon is how far ahead status pages and the console list // maintenance. const upcomingHorizon = 14 * 24 * time.Hour func loadLocation(name string) *time.Location { if loc, err := time.LoadLocation(name); err == nil { return loc } return time.UTC } func weekdaysOf(ws []int16) []time.Weekday { out := make([]time.Weekday, len(ws)) for i, w := range ws { out[i] = time.Weekday(w) } return out } func ruleOf(w store.MaintenanceWindow) maintenance.Rule { return maintenance.Rule{ Start: w.StartsAt, Duration: time.Duration(w.DurationSeconds) * time.Second, Location: loadLocation(w.TimeZone), Recurrence: maintenance.Recurrence(w.Recurrence), Every: int(w.Every), Weekdays: weekdaysOf(w.Weekdays), Until: w.Until, } } func windowOf(r store.MaintenanceForMonitorsRow) store.MaintenanceWindow { return store.MaintenanceWindow{ ID: r.ID, Title: r.Title, Description: r.Description, StartsAt: r.StartsAt, DurationSeconds: r.DurationSeconds, TimeZone: r.TimeZone, Recurrence: r.Recurrence, Every: r.Every, Weekdays: r.Weekdays, Until: r.Until, } } // maintenanceFor loads the windows covering monitors, by monitor. func maintenanceFor(ctx context.Context, q *store.Queries, ids []uuid.UUID) (map[uuid.UUID][]store.MaintenanceWindow, error) { rows, err := q.MaintenanceForMonitors(ctx, ids) out := map[uuid.UUID][]store.MaintenanceWindow{} for _, r := range rows { if r.MonitorID != nil { out[*r.MonitorID] = append(out[*r.MonitorID], windowOf(r)) } } return out, err } // inMaintenance returns the window of ws in progress at t. func inMaintenance(ws []store.MaintenanceWindow, t time.Time) (store.MaintenanceWindow, maintenance.Span, bool) { for _, w := range ws { if s, ok := ruleOf(w).ActiveAt(t); ok { return w, s, true } } return store.MaintenanceWindow{}, maintenance.Span{}, false } // flexInts accepts numbers or numeric strings, as HTML forms send them. type flexInts []int // UnmarshalJSON implements json.Unmarshaler. func (f *flexInts) UnmarshalJSON(b []byte) error { var raw []json.RawMessage if err := json.Unmarshal(b, &raw); err != nil { return err } *f = make(flexInts, 0, len(raw)) for _, r := range raw { s := strings.Trim(string(r), `"`) n, err := strconv.Atoi(s) if err != nil { return err } *f = append(*f, n) } return nil } type maintenanceRequest struct { Title string `json:"title" binding:"required,max=200"` Description string `json:"description" binding:"max=20000"` // Start is the local wall-clock time of the first occurrence, // "2006-01-02T15:04", in TimeZone. Start string `json:"start" binding:"required"` TimeZone string `json:"time_zone" binding:"required,max=64"` DurationMinutes int `json:"duration_minutes" binding:"required"` Recurrence string `json:"recurrence"` Every int `json:"every"` Weekdays flexInts `json:"weekdays"` // Until is the last day occurrences may start on, "2006-01-02". Until string `json:"until"` MonitorIDs []uuid.UUID `json:"monitor_ids"` GroupIDs []uuid.UUID `json:"group_ids"` } // params validates req into the stored form. func (req maintenanceRequest) params() (store.CreateMaintenanceParams, string) { loc, err := time.LoadLocation(req.TimeZone) if err != nil || req.TimeZone == "" || req.TimeZone == "Local" { return store.CreateMaintenanceParams{}, "invalid_time_zone" } start, err := time.ParseInLocation("2006-01-02T15:04", req.Start, loc) if err != nil { return store.CreateMaintenanceParams{}, "invalid_maintenance_time" } p := store.CreateMaintenanceParams{ Title: strings.TrimSpace(req.Title), Description: strings.TrimSpace(req.Description), StartsAt: start, DurationSeconds: int32(req.DurationMinutes * 60), TimeZone: req.TimeZone, Recurrence: req.Recurrence, Every: int32(max(req.Every, 1)), Weekdays: []int16{}, } if p.Recurrence == "" { p.Recurrence = string(maintenance.Once) } if p.Title == "" { return p, "invalid_input" } if p.Recurrence == string(maintenance.Weekly) { for _, w := range req.Weekdays { if w < 0 || w > 6 { return p, "invalid_maintenance_time" } p.Weekdays = append(p.Weekdays, int16(w)) } } if req.Until != "" && p.Recurrence != string(maintenance.Once) { day, err := time.ParseInLocation("2006-01-02", req.Until, loc) if err != nil { return p, "invalid_maintenance_time" } end := day.AddDate(0, 0, 1).Add(-time.Second) p.Until = &end } if err := ruleOf(store.MaintenanceWindow{ StartsAt: p.StartsAt, DurationSeconds: p.DurationSeconds, TimeZone: p.TimeZone, Recurrence: p.Recurrence, Every: p.Every, Weekdays: p.Weekdays, Until: p.Until, }).Validate(); err != nil { switch { case errors.Is(err, maintenance.ErrOverlap): return p, "maintenance_overlaps" case errors.Is(err, maintenance.ErrDuration): return p, "invalid_maintenance_duration" } return p, "invalid_maintenance_time" } if len(req.MonitorIDs)+len(req.GroupIDs) == 0 { return p, "maintenance_without_targets" } return p, "" } type maintenanceSpan struct { Start time.Time `json:"start"` End time.Time `json:"end"` } type maintenanceView struct { ID uuid.UUID `json:"id"` Title string `json:"title"` Description string `json:"description"` Start string `json:"start"` StartsAt time.Time `json:"starts_at"` TimeZone string `json:"time_zone"` DurationMinutes int `json:"duration_minutes"` Recurrence string `json:"recurrence"` Every int32 `json:"every"` Weekdays []int16 `json:"weekdays"` Until string `json:"until,omitempty"` MonitorIDs []uuid.UUID `json:"monitor_ids"` GroupIDs []uuid.UUID `json:"group_ids"` Active bool `json:"active"` Next *maintenanceSpan `json:"next"` } func viewMaintenance(w store.MaintenanceWindow, targets []store.MaintenanceTarget, now time.Time) maintenanceView { loc := loadLocation(w.TimeZone) v := maintenanceView{ ID: w.ID, Title: w.Title, Description: w.Description, Start: w.StartsAt.In(loc).Format("2006-01-02T15:04"), StartsAt: w.StartsAt, TimeZone: w.TimeZone, DurationMinutes: int(w.DurationSeconds / 60), Recurrence: w.Recurrence, Every: w.Every, Weekdays: w.Weekdays, MonitorIDs: []uuid.UUID{}, GroupIDs: []uuid.UUID{}, } if w.Until != nil { v.Until = w.Until.In(loc).Format("2006-01-02") } for _, t := range targets { if t.WindowID != w.ID { continue } if t.MonitorID != nil { v.MonitorIDs = append(v.MonitorIDs, *t.MonitorID) } else if t.GroupID != nil { v.GroupIDs = append(v.GroupIDs, *t.GroupID) } } if s, ok := ruleOf(w).Next(now, 400*24*time.Hour); ok { v.Next = &maintenanceSpan{Start: s.Start, End: s.End} v.Active = !now.Before(s.Start) } return v } // maintenanceScope holds what permission checks on windows need. type maintenanceScope struct { tree groupTree monitors map[uuid.UUID]store.Monitor } func (s *Server) loadMaintenanceScope(ctx context.Context, p *principal) (maintenanceScope, error) { ms := maintenanceScope{monitors: map[uuid.UUID]store.Monitor{}} var err error if ms.tree, err = s.loadGroupTree(ctx, p.scope()); err != nil { return ms, err } err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { rows, err := q.ListMonitors(ctx) for _, m := range rows { ms.monitors[m.ID] = m } return err }) return ms, err } // can reports whether p holds perm on every target, or with any=true on at // least one. Unknown targets fail. func (ms maintenanceScope) can(p *principal, perm authz.Permission, monitors, groups []uuid.UUID, any bool) bool { n := 0 check := func(ok bool) { if ok { n++ } } for _, id := range monitors { m, ok := ms.monitors[id] check(ok && canInGroup(p, perm, ms.tree, m.GroupID)) } for _, id := range groups { _, ok := ms.tree.byID[id] check(ok && canInGroup(p, perm, ms.tree, &id)) } if any { return n > 0 } return n == len(monitors)+len(groups) } func (s *Server) listMaintenanceViews(ctx context.Context, p *principal, ms maintenanceScope) ([]maintenanceView, error) { var ( windows []store.MaintenanceWindow targets []store.MaintenanceTarget ) err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error if windows, err = q.ListMaintenance(ctx); err != nil { return err } targets, err = q.ListMaintenanceTargets(ctx) return err }) out := []maintenanceView{} now := time.Now() for _, w := range windows { v := viewMaintenance(w, targets, now) if ms.can(p, authz.MonitorsRead, v.MonitorIDs, v.GroupIDs, true) { out = append(out, v) } } return out, err } func (s *Server) listMaintenance(c *gin.Context) { p := current(c) ctx := c.Request.Context() ms, err := s.loadMaintenanceScope(ctx, p) if err != nil { internalError(c, err) return } out, err := s.listMaintenanceViews(ctx, p, ms) if err != nil { internalError(c, err) return } c.JSON(http.StatusOK, gin.H{"maintenance": out}) } func (s *Server) saveMaintenance(c *gin.Context, id *uuid.UUID) { var req maintenanceRequest if !bind(c, &req) { return } params, code := req.params() if code != "" { fail(c, http.StatusUnprocessableEntity, code) return } p := current(c) ctx := c.Request.Context() ms, err := s.loadMaintenanceScope(ctx, p) if err != nil { internalError(c, err) return } if !ms.can(p, authz.MonitorsWrite, req.MonitorIDs, req.GroupIDs, false) { fail(c, http.StatusForbidden, "forbidden") return } params.OrgID = p.Org.ID var ( w store.MaintenanceWindow targets []store.MaintenanceTarget ) err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error if id == nil { w, err = q.CreateMaintenance(ctx, params) } else { old, err := q.GetMaintenance(ctx, *id) if err != nil { return err } prev, err := q.ListMaintenanceTargets(ctx) if err != nil { return err } // Changing a window needs write access to what it covered too. v := viewMaintenance(old, prev, time.Now()) if !ms.can(p, authz.MonitorsWrite, v.MonitorIDs, v.GroupIDs, false) { return errForbidden } w, err = q.UpdateMaintenance(ctx, store.UpdateMaintenanceParams{ ID: *id, Title: params.Title, Description: params.Description, StartsAt: params.StartsAt, DurationSeconds: params.DurationSeconds, TimeZone: params.TimeZone, Recurrence: params.Recurrence, Every: params.Every, Weekdays: params.Weekdays, Until: params.Until, }) if err != nil { return err } if err := q.ClearMaintenanceTargets(ctx, w.ID); err != nil { return err } } if err != nil { return err } for _, m := range dedupe(req.MonitorIDs) { if err := q.AddMaintenanceTarget(ctx, store.AddMaintenanceTargetParams{WindowID: w.ID, OrgID: p.Org.ID, MonitorID: &m}); err != nil { return err } targets = append(targets, store.MaintenanceTarget{WindowID: w.ID, MonitorID: &m}) } for _, g := range dedupe(req.GroupIDs) { if err := q.AddMaintenanceTarget(ctx, store.AddMaintenanceTargetParams{WindowID: w.ID, OrgID: p.Org.ID, GroupID: &g}); err != nil { return err } targets = append(targets, store.MaintenanceTarget{WindowID: w.ID, GroupID: &g}) } return nil }) switch { case errors.Is(err, pgx.ErrNoRows): fail(c, http.StatusNotFound, "not_found") return case errors.Is(err, errForbidden): fail(c, http.StatusForbidden, "forbidden") return case err != nil: internalError(c, err) return } status := http.StatusOK if id == nil { status = http.StatusCreated } c.JSON(status, viewMaintenance(w, targets, time.Now())) } var errForbidden = errors.New("api: forbidden") func dedupe(ids []uuid.UUID) []uuid.UUID { seen := map[uuid.UUID]bool{} var out []uuid.UUID for _, id := range ids { if !seen[id] { seen[id] = true out = append(out, id) } } return out } func (s *Server) createMaintenance(c *gin.Context) { s.saveMaintenance(c, nil) } func (s *Server) updateMaintenance(c *gin.Context) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } s.saveMaintenance(c, &id) } func (s *Server) deleteMaintenance(c *gin.Context) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } p := current(c) ctx := c.Request.Context() ms, err := s.loadMaintenanceScope(ctx, p) if err != nil { internalError(c, err) return } err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { w, err := q.GetMaintenance(ctx, id) if err != nil { return err } targets, err := q.ListMaintenanceTargets(ctx) if err != nil { return err } v := viewMaintenance(w, targets, time.Now()) if !ms.can(p, authz.MonitorsWrite, v.MonitorIDs, v.GroupIDs, false) { return errForbidden } auditDetail(c, "name", w.Title) _, err = q.DeleteMaintenance(ctx, id) return err }) switch { case errors.Is(err, pgx.ErrNoRows): fail(c, http.StatusNotFound, "not_found") case errors.Is(err, errForbidden): fail(c, http.StatusForbidden, "forbidden") case err != nil: internalError(c, err) default: c.Status(http.StatusNoContent) } } // monitorsInMaintenance loads, in system scope, which of ids are covered by // which windows; used while evaluating results. func (s *Server) monitorsInMaintenance(ctx context.Context, ids []uuid.UUID) map[uuid.UUID][]store.MaintenanceWindow { var out map[uuid.UUID][]store.MaintenanceWindow err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error out, err = maintenanceFor(ctx, q, ids) return err }) if err != nil { // Without the windows, failures alert as usual: better a page // during maintenance than silence during an outage. s.log.ErrorContext(ctx, "loading maintenance windows failed", "error", err) } return out } // scheduleText describes when a window repeats, e.g. "Every 2 weeks on // Tue, Thu until 2026-12-31". func scheduleText(ctx context.Context, v maintenanceView) string { var s string switch v.Recurrence { case string(maintenance.Daily): s = i18n.T(ctx, "maintenance.schedule_daily", "Count", int(v.Every)) case string(maintenance.Weekly): days := v.Weekdays if len(days) == 0 { days = []int16{int16(v.StartsAt.In(loadLocation(v.TimeZone)).Weekday())} } names := make([]string, 0, len(days)) for _, d := range []int16{1, 2, 3, 4, 5, 6, 0} { if slices.Contains(days, d) { names = append(names, i18n.T(ctx, "weekday."+strconv.Itoa(int(d)))) } } s = i18n.T(ctx, "maintenance.schedule_weekly", "Count", int(v.Every), "Days", strings.Join(names, ", ")) case string(maintenance.Monthly): s = i18n.T(ctx, "maintenance.schedule_monthly", "Count", int(v.Every), "Day", v.StartsAt.In(loadLocation(v.TimeZone)).Day()) default: s = i18n.T(ctx, "maintenance.schedule_once") } start := strings.Replace(v.Start, "T", " ", 1) s += " · " + i18n.T(ctx, "maintenance.schedule_from", "Time", start, "Minutes", v.DurationMinutes, "Zone", v.TimeZone) if v.Until != "" { s += " · " + i18n.T(ctx, "maintenance.schedule_until", "Date", v.Until) } return s } func (s *Server) maintenancePage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { ctx := c.Request.Context() ms, err := s.loadMaintenanceScope(ctx, p) if err != nil { return nil, err } windows, err := s.listMaintenanceViews(ctx, p, ms) if err != nil { return nil, err } v := web.MaintenanceView{Form: web.MaintenanceForm{Duration: 60, Recurrence: "none", Every: 1}} ms.tree.walk(func(g store.MonitorGroup, depth int) { if canInGroup(p, authz.MonitorsWrite, ms.tree, &g.ID) { v.Groups = append(v.Groups, web.TargetOption{ID: g.ID.String(), Name: g.Name, Depth: depth}) } }) names := map[uuid.UUID]string{} for _, m := range ms.monitors { names[m.ID] = m.Name if canInGroup(p, authz.MonitorsWrite, ms.tree, m.GroupID) { v.Monitors = append(v.Monitors, web.TargetOption{ID: m.ID.String(), Name: m.Name}) } } slices.SortFunc(v.Monitors, func(a, b web.TargetOption) int { return strings.Compare(a.Name, b.Name) }) v.CanWrite = len(v.Monitors)+len(v.Groups) > 0 for id, g := range ms.tree.byID { names[id] = g.Name } for _, w := range windows { row := web.MaintenanceRow{ ID: w.ID.String(), Title: w.Title, Schedule: scheduleText(ctx, w), Active: w.Active, CanWrite: ms.can(p, authz.MonitorsWrite, w.MonitorIDs, w.GroupIDs, false), } row.Description, _ = web.RenderMarkdown(w.Description) var targets []string for _, id := range w.GroupIDs { targets = append(targets, i18n.T(ctx, "maintenance.group_target", "Name", names[id])) } for _, id := range w.MonitorIDs { targets = append(targets, names[id]) } row.Targets = strings.Join(targets, ", ") if w.Next != nil && !w.Active { row.Next = w.Next.Start.In(loadLocation(w.TimeZone)).Format("2006-01-02 15:04") } v.Windows = append(v.Windows, row) if w.ID.String() == c.Query("edit") && row.CanWrite { f := web.MaintenanceForm{ ID: row.ID, Title: w.Title, Description: w.Description, Start: w.Start, TimeZone: w.TimeZone, Duration: w.DurationMinutes, Recurrence: w.Recurrence, Every: int(w.Every), Until: w.Until, Weekdays: map[int]bool{}, Monitors: map[string]bool{}, Groups: map[string]bool{}, } for _, d := range w.Weekdays { f.Weekdays[int(d)] = true } for _, id := range w.MonitorIDs { f.Monitors[id.String()] = true } for _, id := range w.GroupIDs { f.Groups[id.String()] = true } v.Form = f } } return web.MaintenancePage(page, me, v), nil }