kept data: the choice at reinstall, the list, the read-only view, the load (09 decision 36); R-690 fixed
gates / gates (push) Successful in 26s
gates / gates (push) Successful in 26s
An install over an app's kept drive folder (appdata/<app> non-empty) asks the household: "use my kept data" (a load from the newest copy of THIS drive's install, own unit or second-drive mirror, then the template's after_load) or "start fresh" (the folder is renamed into <drive>/kept/<app>/<date>/ with the removed app's unit; nothing deleted). The install API answers 409 kept_data_choice until one is chosen; DeployStack refuses too. New page Megorzott adatok / Kept data (/kept-data): Load / Look / Delete (typed confirmation, the only deletion of kept data). FileBrowser gets a read-only source. The drive-full warning names the kept folders. <drive>/kept is protected and outside every backup leg. R-690: the removed-app restore (R-487) never found a unit on a DATA drive — it asked GetStackComposePath (true for every catalog app) and restored nextcloud with no env. Now isStackDeployed; pinned with a production-shaped provider. Red-proofs: audits/night-2026-09-26/E/redproofs/. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
@@ -209,6 +209,9 @@ func ProtectedHDDPaths(hddPath string) map[string]bool {
|
||||
filepath.Join(hddPath, "backups"): true,
|
||||
filepath.Join(hddPath, "media"): true,
|
||||
filepath.Join(hddPath, "Dokumentumok"): true,
|
||||
// `09` §3 decision 36: the dated kept folders. Never removed by an app's removal — only the
|
||||
// household's Delete on the kept-data list removes one (kept.go rule 4).
|
||||
filepath.Join(hddPath, KeptDirName): true,
|
||||
// Legacy pre-Model-A double-nest location; kept protected so any leftover data there is
|
||||
// never wiped by a removal.
|
||||
filepath.Join(hddPath, felhomDataDir): true,
|
||||
|
||||
@@ -191,8 +191,18 @@ type InstalledImage struct {
|
||||
type DeployRequest struct {
|
||||
StackName string `json:"stack_name"`
|
||||
Values map[string]string `json:"values"` // env_var -> user-provided value
|
||||
// KeptData is the household's answer when the app's drive folder already holds old data
|
||||
// (`09` §3 decision 36): KeptChoiceFresh here; KeptChoiceUse is carried out by the API as a load
|
||||
// from a backup and never reaches DeployStack. "" = no choice was made — refused when old data exists.
|
||||
KeptData string `json:"kept_data,omitempty"`
|
||||
}
|
||||
|
||||
// Kept-data choices at install (`09` §3 decision 36).
|
||||
const (
|
||||
KeptChoiceUse = "use"
|
||||
KeptChoiceFresh = "fresh"
|
||||
)
|
||||
|
||||
// DeployStack handles first-time deployment of an app.
|
||||
// Returns a warning message (empty if none) and an error if deployment is blocked.
|
||||
// 1. Check available memory against app requirements
|
||||
@@ -358,6 +368,34 @@ func (m *Manager) DeployStack(req DeployRequest) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// `09` §3 decision 36 (R-657): an install NEVER runs into an app's old data silently. When the app's
|
||||
// private drive folder already holds something, the household chooses: „start fresh" moves it into a
|
||||
// dated kept folder (a rename on the same drive — nothing is deleted); „use my kept data" is a load
|
||||
// from a backup, which the API performs instead of an install. No choice → refused, nothing moved.
|
||||
// Pinned by TestKept_DeployRefusesOverOldDataWithoutAChoice.
|
||||
if old := OldAppDataPaths(stack.ComposePath, env["HDD_PATH"]); len(old) > 0 {
|
||||
switch req.KeptData {
|
||||
case KeptChoiceFresh:
|
||||
unit := ""
|
||||
if m.keptUnitFn != nil {
|
||||
unit = m.keptUnitFn(req.StackName, env["HDD_PATH"])
|
||||
}
|
||||
kept, err := m.KeepAside(req.StackName, env["HDD_PATH"], old, unit, time.Now())
|
||||
if err != nil {
|
||||
clearDeploying()
|
||||
return "", fmt.Errorf("start fresh: %w", err)
|
||||
}
|
||||
m.logger.Printf("[INFO] [stacks] Deploy %s: start fresh — the old data (%v) is kept in %s", req.StackName, old, kept)
|
||||
case "":
|
||||
clearDeploying()
|
||||
m.logger.Printf("[WARN] [stacks] Deploy %s REFUSED: the drive already holds its old data %v and no choice was made", req.StackName, old)
|
||||
return "", util.KindErrorf(ErrKeptDataChoice, "the drive already holds %s's old data (%s): choose use or fresh", req.StackName, strings.Join(old, ", "))
|
||||
default:
|
||||
clearDeploying()
|
||||
return "", util.KindErrorf(ErrKeptDataChoice, "kept_data %q is not an install choice here (use is a load from a backup)", req.KeptData)
|
||||
}
|
||||
}
|
||||
|
||||
// Save app.yaml.
|
||||
// CTRL-T2-1: persist the env now, but mark the ON-DISK state Deployed:false
|
||||
// until `docker compose up -d` actually succeeds (done in runComposeDeploy).
|
||||
|
||||
@@ -22,6 +22,9 @@ var (
|
||||
ErrPathMissing = errors.New("path field does not exist")
|
||||
// ErrNotEnoughMemory — the memory verdict refused the deploy (API: 400).
|
||||
ErrNotEnoughMemory = errors.New("not enough memory")
|
||||
// ErrKeptDataChoice — the app's drive folder already holds old data and the install named neither
|
||||
// „use my kept data" nor „start fresh" (`09` §3 decision 36; API: 409 with code kept_data_choice).
|
||||
ErrKeptDataChoice = errors.New("kept data: a choice is needed")
|
||||
// ErrStackDeploying — R-634 (v0.265.0): a stop or start was asked of a stack whose deploy is still
|
||||
// running. Refused, because a `compose down` or a second `compose up -d` in the middle of the
|
||||
// deploy's own `up` makes BOTH fail, and the deploy then records „not deployed" over whatever
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
package stacks
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
|
||||
)
|
||||
|
||||
// ── Kept data (`09` §3 decision 36, operator ruling 2026-09-25 evening) ────────────────────────────
|
||||
//
|
||||
// WHAT IT REPLACES. „Remove the app, keep my data" left the app's private drive folder
|
||||
// (`<drive>/appdata/<app>`) behind, and a later install of the same app ran straight into it (R-657):
|
||||
// measured 2026-09-23 as an install loop, and 2026-09-25 as a clean install whose database simply knows
|
||||
// nothing of the old files. Nothing listed the folder, nothing opened it, nothing deleted it.
|
||||
//
|
||||
// THE RULING. A reinstall over kept data asks: "use my kept data" (the database from a backup, with the
|
||||
// kept files) or "start fresh" (the kept files MOVE to a dated folder; nothing is deleted). And kept data
|
||||
// is never a dead end: the household can see it (read only), load it later, and delete it.
|
||||
//
|
||||
// FOUR RULES, each a guard with a test:
|
||||
//
|
||||
// 1. ONLY `<drive>/appdata/<…>` IS "OLD DATA". An app's bind under userdata/ or media/ is the household's
|
||||
// own shared files (a music library, a photo folder) — never moved, never listed here. Pinned by
|
||||
// TestKept_OnlyAppdataBindsAreOldData.
|
||||
// 2. "START FRESH" IS A RENAME ON THE SAME DRIVE — never a copy, never across drives. A rename that
|
||||
// fails with EXDEV (or anything else) puts back what it already moved and refuses. Pinned by
|
||||
// TestKept_KeepAsideIsARenameAndRollsBack.
|
||||
// 3. THE KEPT FOLDER IS `<drive>/kept/<app>/<date>/` — beside appdata/ and userdata/, inside neither:
|
||||
// no app bind reaches it, FileBrowser and Samba serve only userdata/, and no backup leg reads it (the
|
||||
// Tier-2 and off-site legs read userdata/ and the declared binds of DEPLOYED apps). It is in
|
||||
// ProtectedHDDPaths. The page says it is not backed up.
|
||||
// 4. THE BOX NEVER DELETES KEPT DATA BY ITSELF (D3 is open). DeleteKept is reachable only from the
|
||||
// household's typed confirmation, and refuses any path that is not a listed kept item. Pinned by
|
||||
// TestKept_DeleteRefusesAnythingNotListed.
|
||||
|
||||
// KeptDirName is the folder at a drive's namespace root that holds the dated kept folders.
|
||||
const KeptDirName = "kept"
|
||||
|
||||
// keptMarkerFile is written LAST into a dated kept folder: what was moved, from where, and when.
|
||||
const keptMarkerFile = ".felhom-kept.json"
|
||||
|
||||
// keptUnitDir is where a start-fresh moves the removed app's recovery unit, so the kept files keep the
|
||||
// database copy that belongs to them (the next backup of the fresh install would overwrite it in place).
|
||||
const keptUnitDir = "unit"
|
||||
|
||||
// Kept item kinds.
|
||||
const (
|
||||
KeptKindDated = "dated" // a start-fresh folder under <drive>/kept/<app>/<date>
|
||||
KeptKindLeftover = "leftover" // <drive>/appdata/<x> that no installed app binds (a plain keep-data remove)
|
||||
)
|
||||
|
||||
// KeptMarker is the record inside a dated kept folder.
|
||||
type KeptMarker struct {
|
||||
App string `json:"app"`
|
||||
MovedAt string `json:"moved_at"` // RFC3339 UTC
|
||||
Paths []string `json:"paths"` // relative to the drive root, as they were (e.g. appdata/nextcloud)
|
||||
Unit bool `json:"unit,omitempty"` // a recovery unit was moved in with them (<kept>/unit)
|
||||
Drive string `json:"drive,omitempty"` // the drive root they came from
|
||||
}
|
||||
|
||||
// KeptItem is one row of the „Megőrzött adatok" list.
|
||||
type KeptItem struct {
|
||||
App string `json:"app"` // the catalog app it belongs to ("" = unknown)
|
||||
DisplayName string `json:"display_name"` // the app's name, else the folder name
|
||||
Path string `json:"path"` // the kept folder (absolute)
|
||||
Drive string `json:"drive"` // the drive root it sits on
|
||||
Kind string `json:"kind"`
|
||||
Date time.Time `json:"date"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
// UnitDir is the recovery unit moved in with a dated folder ("" none) — its database copy.
|
||||
UnitDir string `json:"unit_dir,omitempty"`
|
||||
// Marker is the dated folder's record (nil for a leftover).
|
||||
Marker *KeptMarker `json:"marker,omitempty"`
|
||||
}
|
||||
|
||||
// Errors, born as bundle keys.
|
||||
var (
|
||||
ErrKeptNotListed = util.MsgError("err.kept.not_listed")
|
||||
ErrKeptOccupied = util.MsgError("err.kept.occupied")
|
||||
)
|
||||
|
||||
// OldAppDataPaths is rule 1 as a pure function: the app's binds under `<hdd>/appdata/` (never appdata
|
||||
// itself) that exist and hold at least one entry.
|
||||
func OldAppDataPaths(composePath, hddPath string) []string {
|
||||
if hddPath == "" {
|
||||
return nil
|
||||
}
|
||||
appdata := filepath.Join(filepath.Clean(hddPath), "appdata") + string(filepath.Separator)
|
||||
var out []string
|
||||
for _, p := range ParseComposeHDDMounts(composePath, hddPath) {
|
||||
p = filepath.Clean(p)
|
||||
if !strings.HasPrefix(p, appdata) {
|
||||
continue
|
||||
}
|
||||
if dirHasEntries(p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func dirHasEntries(p string) bool {
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer f.Close()
|
||||
names, _ := f.Readdirnames(1)
|
||||
return len(names) > 0
|
||||
}
|
||||
|
||||
// OldAppData is OldAppDataPaths for an app about to be installed on hddPath (its catalog definition).
|
||||
func (m *Manager) OldAppData(name, hddPath string) []string {
|
||||
st, ok := m.GetStack(name)
|
||||
if !ok || st.ComposePath == "" {
|
||||
return nil
|
||||
}
|
||||
return OldAppDataPaths(st.ComposePath, hddPath)
|
||||
}
|
||||
|
||||
// KeptDirFor names a new dated kept folder. The date is the box's local day and time, so the household
|
||||
// recognises „today" in the name.
|
||||
func KeptDirFor(hddPath, app string, now time.Time) string {
|
||||
return filepath.Join(filepath.Clean(hddPath), KeptDirName, app, now.In(getTimezone()).Format("2006-01-02_150405"))
|
||||
}
|
||||
|
||||
// renameFn is the rename seam (tests inject EXDEV); production is os.Rename.
|
||||
var renameFn = os.Rename
|
||||
|
||||
// KeepAside is "start fresh": it MOVES each old-data folder (and, when unitDir is on the same drive, the
|
||||
// removed app's recovery unit) into a new dated kept folder, keeping each one's path relative to the drive.
|
||||
// A failed move puts back everything already moved and returns the error — nothing is copied, nothing is
|
||||
// deleted. Returns the kept folder.
|
||||
func (m *Manager) KeepAside(name, hddPath string, paths []string, unitDir string, now time.Time) (string, error) {
|
||||
drive := filepath.Clean(hddPath)
|
||||
if len(paths) == 0 {
|
||||
return "", fmt.Errorf("nothing to keep aside for %s", name)
|
||||
}
|
||||
dest := KeptDirFor(drive, name, now)
|
||||
if _, err := os.Stat(dest); err == nil {
|
||||
return "", fmt.Errorf("the kept folder %s already exists", dest)
|
||||
}
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
return "", fmt.Errorf("creating the kept folder: %w", err)
|
||||
}
|
||||
type moved struct{ from, to string }
|
||||
var done []moved
|
||||
undo := func() {
|
||||
for i := len(done) - 1; i >= 0; i-- {
|
||||
if err := renameFn(done[i].to, done[i].from); err != nil {
|
||||
m.logger.Printf("[ERROR] [stacks] kept %s: putting %s back to %s FAILED: %v", name, done[i].to, done[i].from, err)
|
||||
}
|
||||
}
|
||||
removeEmptyDirs(dest) // os.Remove only: a folder a failed move-back left data in STAYS
|
||||
}
|
||||
marker := KeptMarker{App: name, MovedAt: now.UTC().Format(time.RFC3339), Drive: drive}
|
||||
for _, p := range paths {
|
||||
p = filepath.Clean(p)
|
||||
rel, err := filepath.Rel(drive, p)
|
||||
if err != nil || strings.HasPrefix(rel, "..") || !strings.HasPrefix(rel, "appdata"+string(filepath.Separator)) {
|
||||
undo()
|
||||
return "", fmt.Errorf("refusing to keep aside %s: not under %s/appdata", p, drive)
|
||||
}
|
||||
to := filepath.Join(dest, rel)
|
||||
if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil {
|
||||
undo()
|
||||
return "", err
|
||||
}
|
||||
if err := renameFn(p, to); err != nil {
|
||||
undo()
|
||||
if errors.Is(err, syscall.EXDEV) {
|
||||
return "", fmt.Errorf("moving %s would cross drives — refused, nothing moved: %w", p, err)
|
||||
}
|
||||
return "", fmt.Errorf("moving %s: %w — nothing moved", p, err)
|
||||
}
|
||||
done = append(done, moved{p, to})
|
||||
marker.Paths = append(marker.Paths, rel)
|
||||
m.logger.Printf("[INFO] [stacks] kept %s: moved %s → %s (start fresh)", name, p, to)
|
||||
}
|
||||
if unitDir != "" {
|
||||
to := filepath.Join(dest, keptUnitDir)
|
||||
if err := renameFn(unitDir, to); err != nil {
|
||||
// The files are kept either way; without the unit a later Load has no database copy, which
|
||||
// the list then says. Not a reason to undo the household's choice.
|
||||
m.logger.Printf("[WARN] [stacks] kept %s: the recovery unit %s could not move in with the files (%v) — the kept folder has no database copy", name, unitDir, err)
|
||||
} else {
|
||||
marker.Unit = true
|
||||
m.logger.Printf("[INFO] [stacks] kept %s: moved the recovery unit %s → %s", name, unitDir, to)
|
||||
}
|
||||
}
|
||||
b, _ := json.MarshalIndent(marker, "", " ")
|
||||
if err := os.WriteFile(filepath.Join(dest, keptMarkerFile), b, 0o644); err != nil {
|
||||
m.logger.Printf("[WARN] [stacks] kept %s: could not write the marker in %s: %v — listed without it", name, dest, err)
|
||||
}
|
||||
return dest, nil
|
||||
}
|
||||
|
||||
func readKeptMarker(dir string) *KeptMarker {
|
||||
b, err := os.ReadFile(filepath.Join(dir, keptMarkerFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var mk KeptMarker
|
||||
if json.Unmarshal(b, &mk) != nil {
|
||||
return nil
|
||||
}
|
||||
return &mk
|
||||
}
|
||||
|
||||
// liveDriveBinds is every drive folder an INSTALLED app binds — never kept data.
|
||||
func (m *Manager) liveDriveBinds() []string {
|
||||
var out []string
|
||||
for _, st := range m.GetStacks() {
|
||||
if !st.Deployed || st.AppConfig == nil {
|
||||
continue
|
||||
}
|
||||
hdd := strings.TrimSpace(st.AppConfig.Env["HDD_PATH"])
|
||||
if hdd == "" {
|
||||
continue
|
||||
}
|
||||
for _, p := range ParseComposeHDDMounts(st.ComposePath, hdd) {
|
||||
out = append(out, filepath.Clean(p))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func overlaps(a, b string) bool {
|
||||
sep := string(filepath.Separator)
|
||||
return a == b || strings.HasPrefix(a, b+sep) || strings.HasPrefix(b, a+sep)
|
||||
}
|
||||
|
||||
// ownerOf names the catalog app whose definition binds drive-relative folder rel (e.g. appdata/paperless
|
||||
// → paperless-ngx). A stack named like the folder wins; "" when none declares it.
|
||||
func (m *Manager) ownerOf(drive, abs string) (string, string) {
|
||||
var cands []Stack
|
||||
for _, st := range m.GetStacks() {
|
||||
if st.ComposePath == "" {
|
||||
continue
|
||||
}
|
||||
for _, p := range ParseComposeHDDMounts(st.ComposePath, drive) {
|
||||
if filepath.Clean(p) == abs {
|
||||
cands = append(cands, st)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(cands) == 0 {
|
||||
return "", ""
|
||||
}
|
||||
pick := cands[0]
|
||||
for _, c := range cands {
|
||||
if c.Name == filepath.Base(abs) {
|
||||
pick = c
|
||||
}
|
||||
}
|
||||
dn := pick.Meta.DisplayName
|
||||
if dn == "" {
|
||||
dn = pick.Name
|
||||
}
|
||||
return pick.Name, dn
|
||||
}
|
||||
|
||||
// sizeFn is the size seam (production walks the tree).
|
||||
var sizeFn = getDirSizeBytes
|
||||
|
||||
// ListKept lists every kept item on the given drive roots: the dated folders under <drive>/kept/<app>/,
|
||||
// and each <drive>/appdata/<x> that holds something and that no installed app binds. Sorted newest first.
|
||||
func (m *Manager) ListKept(drives []string) []KeptItem {
|
||||
live := m.liveDriveBinds()
|
||||
var out []KeptItem
|
||||
seen := map[string]bool{}
|
||||
for _, d := range drives {
|
||||
d = filepath.Clean(d)
|
||||
if d == "" || seen[d] {
|
||||
continue
|
||||
}
|
||||
seen[d] = true
|
||||
apps, _ := os.ReadDir(filepath.Join(d, KeptDirName))
|
||||
for _, a := range apps {
|
||||
if !a.IsDir() {
|
||||
continue
|
||||
}
|
||||
stamps, _ := os.ReadDir(filepath.Join(d, KeptDirName, a.Name()))
|
||||
for _, s := range stamps {
|
||||
if !s.IsDir() {
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(d, KeptDirName, a.Name(), s.Name())
|
||||
it := KeptItem{App: a.Name(), DisplayName: a.Name(), Path: dir, Drive: d, Kind: KeptKindDated,
|
||||
Marker: readKeptMarker(dir), SizeBytes: sizeFn(dir)}
|
||||
if st, ok := m.GetStack(a.Name()); ok && st.Meta.DisplayName != "" {
|
||||
it.DisplayName = st.Meta.DisplayName
|
||||
}
|
||||
if it.Marker != nil {
|
||||
if t, err := time.Parse(time.RFC3339, it.Marker.MovedAt); err == nil {
|
||||
it.Date = t
|
||||
}
|
||||
if it.Marker.Unit {
|
||||
if _, err := os.Stat(filepath.Join(dir, keptUnitDir)); err == nil {
|
||||
it.UnitDir = filepath.Join(dir, keptUnitDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
if it.Date.IsZero() {
|
||||
if fi, err := os.Stat(dir); err == nil {
|
||||
it.Date = fi.ModTime()
|
||||
}
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
}
|
||||
ents, _ := os.ReadDir(filepath.Join(d, "appdata"))
|
||||
for _, e := range ents {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
abs := filepath.Join(d, "appdata", e.Name())
|
||||
isLive := false
|
||||
for _, l := range live {
|
||||
if overlaps(abs, l) {
|
||||
isLive = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if isLive || !dirHasEntries(abs) {
|
||||
continue
|
||||
}
|
||||
app, dn := m.ownerOf(d, abs)
|
||||
if dn == "" {
|
||||
dn = e.Name()
|
||||
}
|
||||
it := KeptItem{App: app, DisplayName: dn, Path: abs, Drive: d, Kind: KeptKindLeftover, SizeBytes: sizeFn(abs)}
|
||||
if fi, err := os.Stat(abs); err == nil {
|
||||
it.Date = fi.ModTime()
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if !out[i].Date.Equal(out[j].Date) {
|
||||
return out[i].Date.After(out[j].Date)
|
||||
}
|
||||
return out[i].Path < out[j].Path
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// FindKept returns the listed item at exactly path — the only way an action names a kept item.
|
||||
func (m *Manager) FindKept(drives []string, path string) (KeptItem, bool) {
|
||||
clean := filepath.Clean(path)
|
||||
for _, it := range m.ListKept(drives) {
|
||||
if it.Path == clean {
|
||||
return it, true
|
||||
}
|
||||
}
|
||||
return KeptItem{}, false
|
||||
}
|
||||
|
||||
// DeleteKept is the household's Delete, and the ONLY deletion of kept data anywhere in the product
|
||||
// (rule 4). It refuses a path that is not a listed kept item — a live app's folder is never listed.
|
||||
func (m *Manager) DeleteKept(drives []string, path string) (KeptItem, error) {
|
||||
it, ok := m.FindKept(drives, path)
|
||||
if !ok {
|
||||
m.logger.Printf("[WARN] [stacks] kept: delete REFUSED for %s — not a listed kept item", path)
|
||||
return KeptItem{}, ErrKeptNotListed
|
||||
}
|
||||
if err := os.RemoveAll(it.Path); err != nil {
|
||||
return it, fmt.Errorf("deleting %s: %w", it.Path, err)
|
||||
}
|
||||
m.logger.Printf("[INFO] [stacks] kept: DELETED %s (%s, %d bytes) — the household's typed confirmation", it.Path, it.DisplayName, it.SizeBytes)
|
||||
if it.Kind == KeptKindDated {
|
||||
_ = os.Remove(filepath.Dir(it.Path)) // the per-app folder, only when now empty
|
||||
}
|
||||
return it, nil
|
||||
}
|
||||
|
||||
// RestoreKeptFiles puts a dated item's files back where they were (a rename, the reverse of KeepAside)
|
||||
// before a Load; a leftover item is already in place. It refuses when any destination holds something —
|
||||
// that would be two installs' data in one folder. Returns the unit to load from ("" none).
|
||||
func (m *Manager) RestoreKeptFiles(it KeptItem) (string, error) {
|
||||
if it.Kind != KeptKindDated {
|
||||
return "", nil
|
||||
}
|
||||
if it.Marker == nil || len(it.Marker.Paths) == 0 {
|
||||
return "", fmt.Errorf("the kept folder %s has no record of where its files came from", it.Path)
|
||||
}
|
||||
for _, rel := range it.Marker.Paths {
|
||||
if dirHasEntries(filepath.Join(it.Drive, rel)) {
|
||||
return "", ErrKeptOccupied
|
||||
}
|
||||
}
|
||||
var done []string
|
||||
for _, rel := range it.Marker.Paths {
|
||||
from, to := filepath.Join(it.Path, rel), filepath.Join(it.Drive, rel)
|
||||
_ = os.Remove(to) // an EMPTY leftover directory only (checked above)
|
||||
if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := renameFn(from, to); err != nil {
|
||||
for _, r := range done {
|
||||
_ = renameFn(filepath.Join(it.Drive, r), filepath.Join(it.Path, r))
|
||||
}
|
||||
return "", fmt.Errorf("moving %s back: %w — nothing moved", from, err)
|
||||
}
|
||||
done = append(done, rel)
|
||||
m.logger.Printf("[INFO] [stacks] kept %s: moved %s back → %s (load)", it.App, from, to)
|
||||
}
|
||||
return it.UnitDir, nil
|
||||
}
|
||||
|
||||
// FinishKeptLoad runs after a successful Load of a dated item: the unit it carried becomes the app's own
|
||||
// unit again when that place is free (unitHome = backups/primary/<app> on the drive), and the kept folder
|
||||
// is removed only when nothing but empty directories and its marker remain — no data is deleted here.
|
||||
func (m *Manager) FinishKeptLoad(it KeptItem, unitHome string) {
|
||||
if it.Kind != KeptKindDated {
|
||||
return
|
||||
}
|
||||
if it.UnitDir != "" && unitHome != "" {
|
||||
if _, err := os.Stat(unitHome); os.IsNotExist(err) {
|
||||
if err := os.MkdirAll(filepath.Dir(unitHome), 0o755); err == nil {
|
||||
if err := renameFn(it.UnitDir, unitHome); err == nil {
|
||||
m.logger.Printf("[INFO] [stacks] kept %s: the loaded unit is the app's own again → %s", it.App, unitHome)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
m.logger.Printf("[INFO] [stacks] kept %s: %s already holds a unit — the loaded one stays in %s (listed; the household decides)", it.App, unitHome, it.UnitDir)
|
||||
}
|
||||
}
|
||||
if keptHoldsOnlyEmptyDirs(it.Path) {
|
||||
_ = os.Remove(filepath.Join(it.Path, keptMarkerFile))
|
||||
removeEmptyDirs(it.Path)
|
||||
if _, err := os.Stat(it.Path); os.IsNotExist(err) {
|
||||
_ = os.Remove(filepath.Dir(it.Path))
|
||||
m.logger.Printf("[INFO] [stacks] kept %s: %s is empty after the load — removed from the list", it.App, it.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// keptHoldsOnlyEmptyDirs: true when the tree holds no file other than the marker.
|
||||
func keptHoldsOnlyEmptyDirs(root string) bool {
|
||||
only := true
|
||||
_ = filepath.Walk(root, func(p string, fi os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
only = false
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if !fi.IsDir() && !(filepath.Dir(p) == root && fi.Name() == keptMarkerFile) {
|
||||
only = false
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return only
|
||||
}
|
||||
|
||||
// RunAfterLoad runs the app's `after_load:` once, after a Load, when the app is running (waits up to
|
||||
// wait). Logged by name either way; a failure is reported, never retried.
|
||||
func (m *Manager) RunAfterLoad(name string, wait time.Duration) (bool, error) {
|
||||
st, ok := m.GetStack(name)
|
||||
if !ok {
|
||||
return false, fmt.Errorf("stack %q not found", name)
|
||||
}
|
||||
al := st.Meta.AfterLoad
|
||||
if al == nil || al.Service == "" || len(al.Command) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
deadline := time.Now().Add(wait)
|
||||
for {
|
||||
_ = m.RefreshStatus()
|
||||
if s, ok := m.GetStack(name); ok && (s.State == StateRunning || s.State == StateUnhealthy) {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return true, fmt.Errorf("the app did not start within %s — after_load not run", wait)
|
||||
}
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
return true, m.runAfterLoadNow(name)
|
||||
}
|
||||
|
||||
// runAfterLoadNow runs the declared command once, now (RunAfterLoad has waited for the app).
|
||||
func (m *Manager) runAfterLoadNow(name string) error {
|
||||
st, ok := m.GetStack(name)
|
||||
if !ok || st.Meta.AfterLoad == nil {
|
||||
return nil
|
||||
}
|
||||
al := st.Meta.AfterLoad
|
||||
dir := filepath.Dir(st.ComposePath)
|
||||
args := []string{"exec", "-T"}
|
||||
if al.User != "" {
|
||||
args = append(args, "-u", al.User)
|
||||
}
|
||||
args = append(args, al.Service)
|
||||
args = append(args, al.Command...)
|
||||
t0 := time.Now()
|
||||
out, err := m.afterLoadExec(dir, args...)
|
||||
m.logger.Printf("[INFO] [stacks] after_load %s: %s %v in %s (err=%v): %s", name, al.Service, al.Command, time.Since(t0).Round(time.Millisecond), err, truncateStr(out, 400))
|
||||
return err
|
||||
}
|
||||
|
||||
// afterLoadExec is the exec seam; production runs compose with the app's env.
|
||||
func (m *Manager) afterLoadExec(dir string, args ...string) (string, error) {
|
||||
if m.afterLoadFn != nil {
|
||||
return m.afterLoadFn(dir, args...)
|
||||
}
|
||||
return m.composeExecCustomEnv(dir, m.stackEnv(dir), args...)
|
||||
}
|
||||
|
||||
var keptTZ *time.Location
|
||||
|
||||
func getTimezone() *time.Location {
|
||||
if keptTZ == nil {
|
||||
if loc, err := time.LoadLocation("Europe/Budapest"); err == nil {
|
||||
keptTZ = loc
|
||||
} else {
|
||||
keptTZ = time.UTC
|
||||
}
|
||||
}
|
||||
return keptTZ
|
||||
}
|
||||
|
||||
// removeEmptyDirs removes root and every directory under it that is EMPTY — never a file, never a
|
||||
// directory holding one (os.Remove refuses a non-empty directory). Deepest first.
|
||||
func removeEmptyDirs(root string) {
|
||||
var dirs []string
|
||||
_ = filepath.Walk(root, func(p string, fi os.FileInfo, err error) error {
|
||||
if err == nil && fi.IsDir() {
|
||||
dirs = append(dirs, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
for i := len(dirs) - 1; i >= 0; i-- {
|
||||
_ = os.Remove(dirs[i])
|
||||
}
|
||||
}
|
||||
|
||||
// DirSizeBytes is the size seam's value for one folder (du -sb; 0 when unreadable).
|
||||
func DirSizeBytes(p string) int64 { return sizeFn(p) }
|
||||
|
||||
// DirModTime is a folder's modification time (zero when unreadable).
|
||||
func DirModTime(p string) time.Time {
|
||||
fi, err := os.Stat(p)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return fi.ModTime()
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package stacks
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||
)
|
||||
|
||||
// keptManager is a real Manager over a temp stacks dir with one app, "cloudapp", whose compose binds
|
||||
// its private data (appdata/cloudapp), a household folder (userdata/Photos) and the shared media root.
|
||||
// Nothing here reaches Docker (R-650): no test calls a path that runs compose.
|
||||
func keptManager(t *testing.T) (*Manager, string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
drive := filepath.Join(dir, "drive")
|
||||
cfg := &config.Config{}
|
||||
cfg.Paths.StacksDir = filepath.Join(dir, "stacks")
|
||||
cfg.Paths.SystemDataPath = filepath.Join(dir, "system")
|
||||
cfg.Stacks.ComposeCommand = "docker compose"
|
||||
app := filepath.Join(cfg.Paths.StacksDir, "cloudapp")
|
||||
must(t, os.MkdirAll(app, 0o755))
|
||||
compose := "services:\n cloudapp:\n image: busybox\n volumes:\n" +
|
||||
" - ${HDD_PATH}/appdata/cloudapp:/data\n" +
|
||||
" - ${HDD_PATH}/userdata/Photos:/photos\n" +
|
||||
" - ${HDD_PATH}/media:/media\n"
|
||||
must(t, os.WriteFile(filepath.Join(app, "docker-compose.yml"), []byte(compose), 0o644))
|
||||
must(t, os.WriteFile(filepath.Join(app, ".felhom.yml"), []byte("display_name: Cloud App\ndeploy_fields:\n - env_var: HDD_PATH\n label: Drive\n type: path\n required: true\n"), 0o644))
|
||||
m, err := NewManager(cfg, log.New(io.Discard, "", 0))
|
||||
must(t, err)
|
||||
must(t, m.ScanStacks())
|
||||
for _, d := range []string{"appdata/cloudapp/user1", "userdata/Photos", "media"} {
|
||||
must(t, os.MkdirAll(filepath.Join(drive, d), 0o755))
|
||||
}
|
||||
must(t, os.WriteFile(filepath.Join(drive, "appdata/cloudapp/user1/file.txt"), []byte("old"), 0o644))
|
||||
must(t, os.WriteFile(filepath.Join(drive, "userdata/Photos/p.jpg"), []byte("photo"), 0o644))
|
||||
must(t, os.WriteFile(filepath.Join(drive, "media/song.mp3"), []byte("song"), 0o644))
|
||||
return m, drive
|
||||
}
|
||||
|
||||
func must(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Rule 1 — only the app's private appdata bind is "old data"; the household's shared folders never are.
|
||||
// COMPANION RED-PROOF: drop the appdata prefix check in OldAppDataPaths → the Photos and media folders
|
||||
// are returned and this fails.
|
||||
func TestKept_OnlyAppdataBindsAreOldData(t *testing.T) {
|
||||
m, drive := keptManager(t)
|
||||
got := m.OldAppData("cloudapp", drive)
|
||||
want := []string{filepath.Join(drive, "appdata/cloudapp")}
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Fatalf("old data = %v, want only %v (a household folder must never be moved)", got, want)
|
||||
}
|
||||
// An EMPTY private folder is not old data.
|
||||
must(t, os.RemoveAll(filepath.Join(drive, "appdata/cloudapp/user1")))
|
||||
if got := m.OldAppData("cloudapp", drive); len(got) != 0 {
|
||||
t.Fatalf("an empty folder was called old data: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Rule 2 — start fresh is a RENAME (same inode, nothing copied) and a failed move puts back what moved.
|
||||
// COMPANION RED-PROOF: delete the undo() call on the rename failure → the first folder stays inside the
|
||||
// kept folder and this fails at "was not put back".
|
||||
func TestKept_KeepAsideIsARenameAndRollsBack(t *testing.T) {
|
||||
m, drive := keptManager(t)
|
||||
src := filepath.Join(drive, "appdata/cloudapp")
|
||||
second := filepath.Join(drive, "appdata/cloudapp-extra")
|
||||
must(t, os.MkdirAll(second, 0o755))
|
||||
must(t, os.WriteFile(filepath.Join(second, "x"), []byte("x"), 0o644))
|
||||
before, err := os.Stat(filepath.Join(src, "user1/file.txt"))
|
||||
must(t, err)
|
||||
now := time.Date(2026, 9, 25, 11, 0, 0, 0, time.UTC)
|
||||
|
||||
// A: the second rename fails with EXDEV → both stay where they were, no kept folder, the error says so.
|
||||
calls := 0
|
||||
renameFn = func(a, b string) error {
|
||||
calls++
|
||||
if calls == 2 {
|
||||
return &os.LinkError{Op: "rename", Old: a, New: b, Err: syscall.EXDEV}
|
||||
}
|
||||
return os.Rename(a, b)
|
||||
}
|
||||
defer func() { renameFn = os.Rename }()
|
||||
_, err = m.KeepAside("cloudapp", drive, []string{src, second}, "", now)
|
||||
if err == nil || !strings.Contains(err.Error(), "cross drives") {
|
||||
t.Fatalf("want a cross-drive refusal, got %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(src, "user1/file.txt")); err != nil {
|
||||
t.Fatalf("the first folder was not put back after the failed move: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(KeptDirFor(drive, "cloudapp", now)); !os.IsNotExist(err) {
|
||||
t.Fatalf("a failed start-fresh left a kept folder behind (%v)", err)
|
||||
}
|
||||
|
||||
// B: success — the data is in the kept folder under its drive-relative path, as the SAME file.
|
||||
renameFn = os.Rename
|
||||
kept, err := m.KeepAside("cloudapp", drive, []string{src}, "", now)
|
||||
must(t, err)
|
||||
after, err := os.Stat(filepath.Join(kept, "appdata/cloudapp/user1/file.txt"))
|
||||
must(t, err)
|
||||
if !os.SameFile(before, after) {
|
||||
t.Fatal("the kept file is not the same inode — it was copied, not moved")
|
||||
}
|
||||
if _, err := os.Stat(src); !os.IsNotExist(err) {
|
||||
t.Fatalf("the old folder is still in place after start fresh (%v)", err)
|
||||
}
|
||||
if mk := readKeptMarker(kept); mk == nil || mk.App != "cloudapp" || fmt.Sprint(mk.Paths) != "[appdata/cloudapp]" {
|
||||
t.Fatalf("marker = %+v", mk)
|
||||
}
|
||||
if !strings.HasPrefix(kept, filepath.Join(drive, KeptDirName)+string(filepath.Separator)) ||
|
||||
strings.Contains(kept, "userdata") {
|
||||
t.Fatalf("kept folder %s is not under <drive>/kept (and never under userdata)", kept)
|
||||
}
|
||||
}
|
||||
|
||||
// Rule 3 — the kept folder is protected from an app removal's drive clean-up.
|
||||
// COMPANION RED-PROOF: drop the KeptDirName line from ProtectedHDDPaths → fails.
|
||||
func TestKept_KeptDirIsProtected(t *testing.T) {
|
||||
if !ProtectedHDDPaths("/mnt/d")["/mnt/d/"+KeptDirName] {
|
||||
t.Fatal("<drive>/kept is not in ProtectedHDDPaths")
|
||||
}
|
||||
}
|
||||
|
||||
// The list: a dated folder (with its unit) and a leftover appdata folder are listed; a live app's
|
||||
// folder is not; the leftover is named after the catalog app that declares it.
|
||||
func TestKept_ListShowsKeptAndNeverALiveFolder(t *testing.T) {
|
||||
m, drive := keptManager(t)
|
||||
// A leftover of cloudapp (not installed): listed, owner resolved from the catalog definition.
|
||||
items := m.ListKept([]string{drive})
|
||||
if len(items) != 1 || items[0].Kind != KeptKindLeftover || items[0].App != "cloudapp" || items[0].DisplayName != "Cloud App" {
|
||||
t.Fatalf("leftover listing = %+v", items)
|
||||
}
|
||||
// Installed now: its folder is LIVE and disappears from the list.
|
||||
m.mu.Lock()
|
||||
s := m.stacks["cloudapp"]
|
||||
s.Deployed = true
|
||||
s.AppConfig = &AppConfig{Deployed: true, Env: map[string]string{"HDD_PATH": drive}}
|
||||
m.mu.Unlock()
|
||||
if items := m.ListKept([]string{drive}); len(items) != 0 {
|
||||
t.Fatalf("a live app's folder was listed as kept data: %+v", items)
|
||||
}
|
||||
// A dated kept folder with a unit moved in.
|
||||
unit := filepath.Join(drive, "backups/primary/cloudapp")
|
||||
must(t, os.MkdirAll(unit, 0o755))
|
||||
must(t, os.WriteFile(filepath.Join(unit, "manifest.json"), []byte("{}"), 0o644))
|
||||
old := filepath.Join(drive, "appdata/older")
|
||||
must(t, os.MkdirAll(old, 0o755))
|
||||
must(t, os.WriteFile(filepath.Join(old, "f"), []byte("f"), 0o644))
|
||||
kept, err := m.KeepAside("cloudapp", drive, []string{old}, unit, time.Now())
|
||||
must(t, err)
|
||||
items = m.ListKept([]string{drive})
|
||||
if len(items) != 1 || items[0].Kind != KeptKindDated || items[0].Path != kept || items[0].UnitDir != filepath.Join(kept, keptUnitDir) {
|
||||
t.Fatalf("dated listing = %+v", items)
|
||||
}
|
||||
}
|
||||
|
||||
// Rule 4 — Delete removes ONLY a listed kept item; anything else is refused and untouched.
|
||||
// COMPANION RED-PROOF: skip the FindKept check in DeleteKept → the live folder is deleted and this fails.
|
||||
func TestKept_DeleteRefusesAnythingNotListed(t *testing.T) {
|
||||
m, drive := keptManager(t)
|
||||
m.mu.Lock()
|
||||
s := m.stacks["cloudapp"]
|
||||
s.Deployed = true
|
||||
s.AppConfig = &AppConfig{Deployed: true, Env: map[string]string{"HDD_PATH": drive}}
|
||||
m.mu.Unlock()
|
||||
for _, p := range []string{
|
||||
filepath.Join(drive, "appdata/cloudapp"), // a LIVE app's folder
|
||||
filepath.Join(drive, "userdata/Photos"), // the household's files
|
||||
drive, // the drive itself
|
||||
filepath.Join(drive, "appdata/cloudapp/../../userdata"),
|
||||
} {
|
||||
if _, err := m.DeleteKept([]string{drive}, p); !errors.Is(err, ErrKeptNotListed) {
|
||||
t.Fatalf("delete of %s: want ErrKeptNotListed, got %v", p, err)
|
||||
}
|
||||
}
|
||||
for _, p := range []string{"appdata/cloudapp/user1/file.txt", "userdata/Photos/p.jpg", "media/song.mp3"} {
|
||||
if _, err := os.Stat(filepath.Join(drive, p)); err != nil {
|
||||
t.Fatalf("%s was touched by a refused delete: %v", p, err)
|
||||
}
|
||||
}
|
||||
// A listed item IS deleted.
|
||||
left := filepath.Join(drive, "appdata/gone")
|
||||
must(t, os.MkdirAll(left, 0o755))
|
||||
must(t, os.WriteFile(filepath.Join(left, "f"), []byte("f"), 0o644))
|
||||
if _, err := m.DeleteKept([]string{drive}, left); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(left); !os.IsNotExist(err) {
|
||||
t.Fatalf("the listed kept item is still there (%v)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The install never runs into old data silently: no choice (or a wrong one) is refused BEFORE anything
|
||||
// is written — no app.yaml, the old data in place.
|
||||
// COMPANION RED-PROOF: delete the OldAppDataPaths block in DeployStack → the deploy saves app.yaml and
|
||||
// goes on to compose (this test then fails at "no choice was accepted").
|
||||
func TestKept_DeployRefusesOverOldDataWithoutAChoice(t *testing.T) {
|
||||
m, drive := keptManager(t)
|
||||
for _, choice := range []string{"", "use", "whatever"} {
|
||||
_, err := m.DeployStack(DeployRequest{StackName: "cloudapp", Values: map[string]string{"HDD_PATH": drive}, KeptData: choice})
|
||||
if !errors.Is(err, ErrKeptDataChoice) {
|
||||
t.Fatalf("choice %q: no choice was accepted — want ErrKeptDataChoice, got %v", choice, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(m.cfg.Paths.StacksDir, "cloudapp", "app.yaml")); !os.IsNotExist(err) {
|
||||
t.Fatalf("choice %q: app.yaml was written by a refused install", choice)
|
||||
}
|
||||
if st, _ := m.GetStack("cloudapp"); st.Deploying || st.Deployed {
|
||||
t.Fatalf("choice %q: the stack is left Deploying=%v Deployed=%v", choice, st.Deploying, st.Deployed)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(drive, "appdata/cloudapp/user1/file.txt")); err != nil {
|
||||
t.Fatalf("the old data moved without a choice: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Load puts a dated item's files back, refusing when the destination already holds something.
|
||||
func TestKept_RestoreKeptFilesRefusesAnOccupiedFolder(t *testing.T) {
|
||||
m, drive := keptManager(t)
|
||||
src := filepath.Join(drive, "appdata/cloudapp")
|
||||
kept, err := m.KeepAside("cloudapp", drive, []string{src}, "", time.Now())
|
||||
must(t, err)
|
||||
it, ok := m.FindKept([]string{drive}, kept)
|
||||
if !ok {
|
||||
t.Fatal("kept folder not listed")
|
||||
}
|
||||
must(t, os.MkdirAll(filepath.Join(src, "new"), 0o755)) // a fresh install wrote here
|
||||
if _, err := m.RestoreKeptFiles(it); !errors.Is(err, ErrKeptOccupied) {
|
||||
t.Fatalf("want ErrKeptOccupied over an occupied folder, got %v", err)
|
||||
}
|
||||
must(t, os.RemoveAll(src))
|
||||
if _, err := m.RestoreKeptFiles(it); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(src, "user1/file.txt")); err != nil {
|
||||
t.Fatalf("the file did not come back: %v", err)
|
||||
}
|
||||
m.FinishKeptLoad(it, "")
|
||||
if _, err := os.Stat(kept); !os.IsNotExist(err) {
|
||||
t.Fatalf("the emptied kept folder is still listed (%v)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// after_load runs the template's ONE command, as its user, in its service.
|
||||
func TestKept_AfterLoadRunsTheDeclaredCommand(t *testing.T) {
|
||||
m, _ := keptManager(t)
|
||||
var got []string
|
||||
m.afterLoadFn = func(dir string, args ...string) (string, error) { got = args; return "ok", nil }
|
||||
m.mu.Lock()
|
||||
m.stacks["cloudapp"].Meta.AfterLoad = &AfterLoadCommand{Service: "cloudapp", User: "www-data", Command: []string{"php", "occ", "files:scan", "--all"}}
|
||||
m.stacks["cloudapp"].State = StateRunning
|
||||
m.mu.Unlock()
|
||||
if err := m.runAfterLoadNow("cloudapp"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := "exec -T -u www-data cloudapp php occ files:scan --all"; strings.Join(got, " ") != want {
|
||||
t.Fatalf("after_load ran %q, want %q", strings.Join(got, " "), want)
|
||||
}
|
||||
}
|
||||
@@ -284,13 +284,18 @@ type Manager struct {
|
||||
pgConv pgConverter
|
||||
convertFreeFn func(path string) (int64, bool)
|
||||
updateUndoHealthFn func(ctx context.Context, name string, timeout time.Duration, meta *Metadata) (bool, string)
|
||||
probeRunFn func(t probeTarget) *HealthProbeResult // the health wait's network probe; nil ⇒ runChecks
|
||||
updateEventSink func(UpdateEvent) // v0.264.0: the notifier; nil ⇒ no events
|
||||
updateMemoryFn func(newReqMB, newLimitMB, releasedReqMB, releasedLimitMB int) (refusal error, warning string)
|
||||
updateDiskFreeFn func() (freeGiB float64, ok bool)
|
||||
updateNowFn func() time.Time
|
||||
updateJournalMu sync.Mutex
|
||||
updateResume []string // apps whose update was interrupted after `up`; resumed once guards exist
|
||||
// afterLoadFn is RunAfterLoad's exec seam (kept.go); nil = compose exec with the app's env.
|
||||
afterLoadFn func(dir string, args ...string) (string, error)
|
||||
// keptUnitFn names the removed app's recovery unit on a drive (backup.RemovedAppUnitFor, wired in
|
||||
// main.go) so a start-fresh moves it in with the files it belongs to. nil = files only.
|
||||
keptUnitFn func(app, drive string) string
|
||||
probeRunFn func(t probeTarget) *HealthProbeResult // the health wait's network probe; nil ⇒ runChecks
|
||||
updateEventSink func(UpdateEvent) // v0.264.0: the notifier; nil ⇒ no events
|
||||
updateMemoryFn func(newReqMB, newLimitMB, releasedReqMB, releasedLimitMB int) (refusal error, warning string)
|
||||
updateDiskFreeFn func() (freeGiB float64, ok bool)
|
||||
updateNowFn func() time.Time
|
||||
updateJournalMu sync.Mutex
|
||||
updateResume []string // apps whose update was interrupted after `up`; resumed once guards exist
|
||||
// inspectRestartPolicyFn is the docker-inspect seam for the above; nil in production
|
||||
// (dockerRestartPolicy). Tests inject a scripted lookup and never touch docker.
|
||||
inspectRestartPolicyFn func(containerName string) (string, error)
|
||||
@@ -1711,3 +1716,6 @@ func (m *Manager) getCatalogTemplateSlugs() map[string]bool {
|
||||
func AggregateStateForTest(containers []ContainerInfo) ContainerState {
|
||||
return aggregateState(containers, func(string) string { return "unless-stopped" })
|
||||
}
|
||||
|
||||
// SetKeptUnitFinder wires the backup side's removed-app unit lookup (INIT-ONLY; main.go).
|
||||
func (m *Manager) SetKeptUnitFinder(fn func(app, drive string) string) { m.keptUnitFn = fn }
|
||||
|
||||
@@ -48,7 +48,12 @@ type Metadata struct {
|
||||
AppInfo AppInfo `yaml:"app_info" json:"app_info"`
|
||||
OptionalConfig []OptionalConfigGroup `yaml:"optional_config" json:"optional_config"`
|
||||
HealthCheck *HealthCheckConfig `yaml:"healthcheck,omitempty" json:"healthcheck,omitempty"`
|
||||
Integrations []IntegrationDef `yaml:"integrations,omitempty" json:"integrations,omitempty"`
|
||||
// AfterLoad (`09` §3 decision 36, E1 2026-09-25) is ONE command the box runs once after it loads an
|
||||
// app's kept data (a database from a backup under files kept on the drive) — for an app whose own
|
||||
// index of its files must be rebuilt. Measured on nextcloud: a file written after the backup is on
|
||||
// the drive and invisible until `occ files:scan --all`. Optional; absent = nothing runs.
|
||||
AfterLoad *AfterLoadCommand `yaml:"after_load,omitempty" json:"after_load,omitempty"`
|
||||
Integrations []IntegrationDef `yaml:"integrations,omitempty" json:"integrations,omitempty"`
|
||||
// InitialCreds: for apps that auto-generate a first-login credential into a file inside the
|
||||
// container (e.g. Crafty's default-creds.txt). The controller reads + parses that file live and
|
||||
// surfaces it on the app page, so the customer never has to dig through logs. Optional.
|
||||
@@ -533,3 +538,10 @@ func (m *Metadata) HasOptionalConfig() bool {
|
||||
func (m *Metadata) HasIntegrations() bool {
|
||||
return len(m.Integrations) > 0
|
||||
}
|
||||
|
||||
// AfterLoadCommand is `.felhom.yml`'s `after_load:` — run with `docker compose exec -T` in Service.
|
||||
type AfterLoadCommand struct {
|
||||
Service string `yaml:"service" json:"service"`
|
||||
User string `yaml:"user,omitempty" json:"user,omitempty"`
|
||||
Command []string `yaml:"command" json:"command"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user