a781e95c94
Three small follow-ups from review:
1. Restore target is now operator-editable. Default value is the
literal '\$HOME/rm-restore/<job-id>/' (agent expands \$HOME at
run time using os.UserHomeDir(); also handles \${HOME} and ~/
prefixes). Operator can replace with any absolute path.
- ui_restore.go validates the input is either absolute or starts
with one of the recognised prefixes; other env-var refs (\$PATH
etc.) are deliberately rejected so operator paths can't pick up
arbitrary agent env values.
- host_restore.html replaces the read-only mono-text display with
a real <input>; help text spells out that \$HOME resolves
agent-side and <job-id> is substituted on dispatch.
- install.sh + the systemd unit prep /root/rm-restore so the
default works under the sandbox: ReadWritePaths gains a soft
'-/root/rm-restore' entry (the '-' makes the bind-mount soft-fail
if missing, but install.sh pre-creates it root-owned 0700).
2. --no-ownership flag now gated on restic version. The flag was
added in restic 0.17 and 0.16 rejects it. Previously dropped it
wholesale — that meant new-dir restores silently preserved
ownership against design intent on 0.17+. Now the agent threads
its detected restic version (sysinfo already collects it) through
runner.Config -> restic.Env, and RunRestore appends --no-ownership
only when AtLeastVersion(0, 17) returns true. 0.16 hosts still
restore with original uid/gid; help text in the wizard explicitly
notes this. The previous 'Original ownership is preserved' copy
was wrong for new-dir mode and is corrected.
3. golangci-lint misspell locale switched US -> UK and the codebase
swept (73 corrections, mostly behaviour/serialise/recognise/honour).
Wire-format ErrorCode 'unauthorized' -> 'unauthorised' is a tiny
contract change but the agent doesn't parse those codes today and
no external API consumers exist yet. Tests passed before + after.
Tests:
- internal/restic/version_test.go covers Env.AtLeastVersion across
edge cases (empty, exact match, patch above, minor below, non-
numeric) and expandHome on \$HOME / \${HOME} / ~/, plus
pass-through for absolute paths and refusal of other env vars.
- ui_restore_test updated: TargetDir now starts '\$HOME/rm-restore/'
with the job_id substituted into the placeholder.
Live verified on the smoke env: default target restored to
/root/rm-restore/<job-id>/ as the agent's expanded \$HOME (2 files,
14 bytes); custom override '/tmp/custom-restore/<job-id>/' restored
into the agent's PrivateTmp namespace (1 file, 6 bytes); both jobs
'succeeded', exit 0.
220 lines
7.0 KiB
Go
220 lines
7.0 KiB
Go
// schedules.go — REST API for /api/hosts/{id}/schedules.
|
|
//
|
|
// Slim-shape body: {cron, enabled, source_group_ids[]}. Paths,
|
|
// excludes, retention, retry, kind, manual — all gone. Those live on
|
|
// SourceGroup; a schedule is just "fire this cron, run backups for
|
|
// these groups." Mutations bump host_schedule_version and (best-effort)
|
|
// push the new set to a connected agent.
|
|
package http
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
stdhttp "net/http"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/oklog/ulid/v2"
|
|
"github.com/robfig/cron/v3"
|
|
|
|
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
|
|
)
|
|
|
|
// scheduleView is the JSON shape returned by GET. Stable wire format
|
|
// — UI form binds to it.
|
|
type scheduleView struct {
|
|
ID string `json:"id"`
|
|
HostID string `json:"host_id"`
|
|
CronExpr string `json:"cron"`
|
|
Enabled bool `json:"enabled"`
|
|
SourceGroupIDs []string `json:"source_group_ids"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
func toScheduleView(s store.Schedule) scheduleView {
|
|
ids := s.SourceGroupIDs
|
|
if ids == nil {
|
|
ids = []string{}
|
|
}
|
|
return scheduleView{
|
|
ID: s.ID, HostID: s.HostID,
|
|
CronExpr: s.CronExpr, Enabled: s.Enabled,
|
|
SourceGroupIDs: ids,
|
|
CreatedAt: s.CreatedAt, UpdatedAt: s.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
// scheduleWriteRequest is the body of POST and PUT.
|
|
type scheduleWriteRequest struct {
|
|
CronExpr string `json:"cron"`
|
|
Enabled bool `json:"enabled"`
|
|
SourceGroupIDs []string `json:"source_group_ids"`
|
|
}
|
|
|
|
// cronParser mirrors robfig/cron/v3's New() default; reuse it across
|
|
// every validate call so we're consistent with what the agent uses.
|
|
var cronParser = cron.NewParser(
|
|
cron.SecondOptional | cron.Minute | cron.Hour |
|
|
cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
|
|
)
|
|
|
|
func (s *Server) handleListSchedules(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
|
if !s.authedUser(r) {
|
|
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
|
return
|
|
}
|
|
hostID := chi.URLParam(r, "id")
|
|
if hostID == "" {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, "missing_id", "")
|
|
return
|
|
}
|
|
if _, err := s.deps.Store.GetHost(r.Context(), hostID); err != nil {
|
|
writeJSONError(w, stdhttp.StatusNotFound, "host_not_found", "")
|
|
return
|
|
}
|
|
rows, err := s.deps.Store.ListSchedulesByHost(r.Context(), hostID)
|
|
if err != nil {
|
|
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
|
return
|
|
}
|
|
out := make([]scheduleView, 0, len(rows))
|
|
for _, sc := range rows {
|
|
out = append(out, toScheduleView(sc))
|
|
}
|
|
writeJSON(w, stdhttp.StatusOK, struct {
|
|
Schedules []scheduleView `json:"schedules"`
|
|
}{Schedules: out})
|
|
}
|
|
|
|
func (s *Server) handleCreateSchedule(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
|
if !s.authedUser(r) {
|
|
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
|
return
|
|
}
|
|
hostID := chi.URLParam(r, "id")
|
|
if hostID == "" {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, "missing_id", "")
|
|
return
|
|
}
|
|
if _, err := s.deps.Store.GetHost(r.Context(), hostID); err != nil {
|
|
writeJSONError(w, stdhttp.StatusNotFound, "host_not_found", "")
|
|
return
|
|
}
|
|
var req scheduleWriteRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
if code, msg, ok := s.validateScheduleRequest(r, hostID, req); !ok {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, code, msg)
|
|
return
|
|
}
|
|
|
|
sc := store.Schedule{
|
|
ID: ulid.Make().String(), HostID: hostID,
|
|
CronExpr: req.CronExpr, Enabled: req.Enabled,
|
|
SourceGroupIDs: req.SourceGroupIDs,
|
|
}
|
|
if err := s.deps.Store.CreateSchedule(r.Context(), &sc); err != nil {
|
|
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.pushScheduleSetAsync(hostID)
|
|
writeJSON(w, stdhttp.StatusCreated, toScheduleView(sc))
|
|
}
|
|
|
|
func (s *Server) handleUpdateSchedule(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
|
if !s.authedUser(r) {
|
|
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
|
return
|
|
}
|
|
hostID := chi.URLParam(r, "id")
|
|
scheduleID := chi.URLParam(r, "sid")
|
|
if hostID == "" || scheduleID == "" {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, "missing_id", "")
|
|
return
|
|
}
|
|
if _, err := s.deps.Store.GetSchedule(r.Context(), hostID, scheduleID); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeJSONError(w, stdhttp.StatusNotFound, "schedule_not_found", "")
|
|
return
|
|
}
|
|
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
|
return
|
|
}
|
|
var req scheduleWriteRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
if code, msg, ok := s.validateScheduleRequest(r, hostID, req); !ok {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, code, msg)
|
|
return
|
|
}
|
|
|
|
sc := store.Schedule{
|
|
ID: scheduleID, HostID: hostID,
|
|
CronExpr: req.CronExpr, Enabled: req.Enabled,
|
|
SourceGroupIDs: req.SourceGroupIDs,
|
|
}
|
|
if err := s.deps.Store.UpdateSchedule(r.Context(), &sc); err != nil {
|
|
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.pushScheduleSetAsync(hostID)
|
|
out, _ := s.deps.Store.GetSchedule(r.Context(), hostID, scheduleID)
|
|
if out != nil {
|
|
writeJSON(w, stdhttp.StatusOK, toScheduleView(*out))
|
|
return
|
|
}
|
|
writeJSON(w, stdhttp.StatusOK, toScheduleView(sc))
|
|
}
|
|
|
|
func (s *Server) handleDeleteSchedule(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
|
if !s.authedUser(r) {
|
|
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
|
return
|
|
}
|
|
hostID := chi.URLParam(r, "id")
|
|
scheduleID := chi.URLParam(r, "sid")
|
|
if hostID == "" || scheduleID == "" {
|
|
writeJSONError(w, stdhttp.StatusBadRequest, "missing_id", "")
|
|
return
|
|
}
|
|
if err := s.deps.Store.DeleteSchedule(r.Context(), hostID, scheduleID); err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeJSONError(w, stdhttp.StatusNotFound, "schedule_not_found", "")
|
|
return
|
|
}
|
|
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.pushScheduleSetAsync(hostID)
|
|
w.WriteHeader(stdhttp.StatusNoContent)
|
|
}
|
|
|
|
// validateScheduleRequest enforces wire-shape rules: cron must parse,
|
|
// at least one source group must be attached, and every referenced
|
|
// group must belong to this host. Returns (code, msg, ok=false) on
|
|
// failure; ok=true means proceed.
|
|
func (s *Server) validateScheduleRequest(r *stdhttp.Request, hostID string, req scheduleWriteRequest) (string, string, bool) {
|
|
if req.CronExpr == "" {
|
|
return "missing_field", "cron is required", false
|
|
}
|
|
if _, err := cronParser.Parse(req.CronExpr); err != nil {
|
|
return "invalid_cron", err.Error(), false
|
|
}
|
|
if len(req.SourceGroupIDs) == 0 {
|
|
return "missing_field", "source_group_ids must contain at least one group", false
|
|
}
|
|
// Every referenced group must exist and belong to this host.
|
|
for _, gid := range req.SourceGroupIDs {
|
|
g, err := s.deps.Store.GetSourceGroup(r.Context(), hostID, gid)
|
|
if err != nil || g == nil {
|
|
return "invalid_group", "source group " + gid + " not found on this host", false
|
|
}
|
|
}
|
|
return "", "", true
|
|
}
|