package host import ( "context" "encoding/json" "errors" "fmt" "log" "os" "path/filepath" "strings" "github.com/carlosframework/platform/internal/moves" ) // The moves-owned local retirement (ruling H5(b), the pattern of Plan 2's // extraction staging): artifacts the claim's inventory does not list, so // park.Local cannot retire them, renamed into the park engine's local // layout under a journalled plan, and an op's own journal directory parked // after them. The source's finalization (movesfinal.go) uses it; Plan 4's // rollback reuses it. func journalComponent(s string) bool { return s != "" && s != "." && s != ".." && !strings.ContainsAny(s, "/\\\x00") } // localArtifactPark is one moves-owned local retirement (ruling H5(b), the // pattern of Plan 2's extraction staging): artifacts the claim's inventory // does not list, so park.Local cannot retire them, renamed into the park // engine's local layout, .parked////artifacts/, // keeping their paths. Plan 4's rollback reuses it. type localArtifactPark struct { DataDir, Incarnation, Host, Op string // Paths are the candidates, relative to DataDir. Absent ones are recorded // as absent and never touched. Paths []string // Step is the journal step that records the retirement id once every // rename is durable; Step+"-plan" records the plan before the first one. Step string NewID func() string // Fault is the test seam, after the plan and after each rename. Fault func(point string) error // Owns, when set, is asked about each candidate present when the plan // is made, with its identity: false records it in the plan as not this // park's (Unowned), so it is logged and left where it is, then and on // every replay. The rollback's cleaning passes its ownership evidence // here (the final review's finding 1); nil owns every candidate. Owns func(path, id string) (bool, error) } // localParkPlan is what is journalled before the first rename: the // retirement id and every candidate's identity ("dev:ino"; "" when absent). type localParkPlan struct { Retirement string `json:"retirement"` Incarnation string `json:"incarnation"` Items []localParkItem `json:"items"` } type localParkItem struct { Path string `json:"path"` ID string `json:"id,omitempty"` // Unowned is a candidate that was present when the plan was made but // that the park has no record of creating (localArtifactPark.Owns): ID // is empty, and it is never moved. Unowned bool `json:"unowned,omitempty"` } // localParkReceipt sits beside artifacts/ in the retirement, so a later // reader can find a moves-owned retirement by its op (D6, I57). type localParkReceipt struct { V int `json:"v"` Op string `json:"op"` Host string `json:"host"` Incarnation string `json:"incarnation"` Retirement string `json:"retirement"` Paths []string `json:"paths"` } const localParkReceiptName = "moves-retirement.json" // retireSync is the fsync every moves-owned retirement makes durable with // (syncPath); a variable so a test can see which directories were synced. var retireSync = syncPath // parkedEventDir and parkedArtifactsDir are the engine's local layout // (park.Local's parkLocal): one directory per retirement event. func parkedEventDir(dataDir, incarnation, host, retirement string) string { return filepath.Join(dataDir, ".parked", incarnation, host, retirement) } func parkedArtifactsDir(dataDir, incarnation, host, retirement string) string { return filepath.Join(parkedEventDir(dataDir, incarnation, host, retirement), "artifacts") } func journalledLocalPlan(j *moves.Journal, step string) (localParkPlan, error) { var plan localParkPlan raw, ok := j.Steps[step+"-plan"] if !ok { return plan, fmt.Errorf("the journal has no %s plan", step) } if err := json.Unmarshal([]byte(raw), &plan); err != nil { return plan, fmt.Errorf("the journal's %s plan: %w", step, err) } if !journalComponent(plan.Retirement) || !journalComponent(plan.Incarnation) { return plan, fmt.Errorf("the journal's %s plan names an unusable retirement", step) } return plan, nil } // artifactPathOK is a relative path under the data directory that is not // the guard's or the park's own. func artifactPathOK(p string) bool { if p == "" || filepath.IsAbs(p) || filepath.Clean(p) != p || strings.ContainsAny(p, "\\\x00") { return false } for _, c := range strings.Split(p, "/") { if !journalComponent(c) { return false } } first, _, _ := strings.Cut(p, "/") return first != ".parked" && first != "hostguard" } // parkLocalArtifacts runs one moves-owned local retirement and returns its // retirement id. In order: the plan (a fresh retirement id and each // candidate's identity) is journalled before anything moves; the retirement's // directories and its receipt are made; each recorded artifact is renamed to // the same path under artifacts/ and its source's parent and every // destination directory up to the data directory synced; then Step records // the retirement id. A replay resumes from the journal: // - an artifact already at its destination with its identity is synced as // a fresh rename is (a stop between the rename and its syncs leaves the // rename undurable, fix round 1), and is then done; // - one still at its live path with its identity is renamed; // - one recorded absent, or unowned (present, but with no record that // this park's op created it), or whose live path now holds something // with another identity, is not this park's: it is left where it is, // never moved or removed; // - a destination that holds anything else is an error, and nothing more // is moved. func parkLocalArtifacts(ctx context.Context, j *moves.Journal, mark func(step, value string) error, p localArtifactPark) (string, error) { if r, ok := j.Steps[p.Step]; ok { return r, nil } if p.DataDir == "" || !journalComponent(p.Incarnation) || !journalComponent(p.Host) || p.Op == "" || p.Step == "" || p.NewID == nil { return "", errors.New("a local park names its data directory, incarnation, host, op and step") } for _, path := range p.Paths { if !artifactPathOK(path) { return "", fmt.Errorf("a local park cannot retire %q", path) } } fault := func(point string) error { if p.Fault != nil { return p.Fault(point) } return nil } plan, err := journalledLocalPlan(j, p.Step) if err != nil { if _, planned := j.Steps[p.Step+"-plan"]; planned { return "", err } if plan, err = p.plan(); err != nil { return "", err } body, err := json.Marshal(plan) if err != nil { return "", err } if err := mark(p.Step+"-plan", string(body)); err != nil { return "", err } } if plan.Incarnation != p.Incarnation || len(plan.Items) != len(p.Paths) { return "", fmt.Errorf("the journal's %s plan is not this park's", p.Step) } for i, it := range plan.Items { if it.Path != p.Paths[i] { return "", fmt.Errorf("the journal's %s plan is not this park's", p.Step) } } dest := parkedArtifactsDir(p.DataDir, p.Incarnation, p.Host, plan.Retirement) if err := mkdirSynced(p.DataDir, dest); err != nil { return "", err } receipt, err := json.Marshal(localParkReceipt{V: 1, Op: p.Op, Host: p.Host, Incarnation: p.Incarnation, Retirement: plan.Retirement, Paths: p.Paths}) if err != nil { return "", err } event := parkedEventDir(p.DataDir, p.Incarnation, p.Host, plan.Retirement) if err := writeFileAtomic(filepath.Join(event, localParkReceiptName), receipt, 0o640); err != nil { return "", err } for _, it := range plan.Items { if err := ctx.Err(); err != nil { return "", err } src, dst := filepath.Join(p.DataDir, it.Path), filepath.Join(dest, it.Path) if it.Unowned { log.Printf("moves: %s: %s has no record that %s created it; it is left where it is", p.Host, it.Path, p.Op) continue } if it.ID == "" { if _, err := os.Lstat(src); err == nil { log.Printf("moves: %s: %s appeared after the park recorded it absent; it is not this park's and is left where it is", p.Host, it.Path) } continue } if done, err := sameIdentity(dst, it.ID); err != nil { return "", err } else if done { if err := syncRename(p.DataDir, src, dst); err != nil { return "", err } if err := fault("after-rename:" + it.Path); err != nil { return "", err } continue } if _, err := os.Lstat(dst); err == nil { return "", fmt.Errorf("%s holds what this park did not put there", dst) } else if !errors.Is(err, os.ErrNotExist) { return "", err } ours, err := sameIdentity(src, it.ID) if err != nil { return "", err } if !ours { log.Printf("moves: %s: %s is no longer the artifact the park recorded; what is there is left where it is", p.Host, it.Path) continue } if err := mkdirSynced(p.DataDir, filepath.Dir(dst)); err != nil { return "", err } if err := os.Rename(src, dst); err != nil { return "", fmt.Errorf("park %s: %w", it.Path, err) } if err := fault("after-rename-unsynced:" + it.Path); err != nil { return "", err } if err := syncRename(p.DataDir, src, dst); err != nil { return "", err } if err := fault("after-rename:" + it.Path); err != nil { return "", err } } if err := retireSync(dest); err != nil { return "", err } if err := mark(p.Step, plan.Retirement); err != nil { return "", err } log.Printf("moves: %s: the local artifacts of %s are parked in %s", p.Host, p.Op, event) return plan.Retirement, nil } // plan records a fresh retirement id and each candidate's identity, or, for // a present candidate Owns refuses, that it is not this park's. The // retirement's directory must not exist yet: the id is this park's alone. func (p localArtifactPark) plan() (localParkPlan, error) { plan := localParkPlan{Retirement: p.NewID(), Incarnation: p.Incarnation} if !journalComponent(plan.Retirement) { return plan, errors.New("no retirement id") } if _, err := os.Lstat(parkedEventDir(p.DataDir, p.Incarnation, p.Host, plan.Retirement)); err == nil { return plan, fmt.Errorf("retirement %s already exists", plan.Retirement) } else if !errors.Is(err, os.ErrNotExist) { return plan, err } for _, path := range p.Paths { id, err := pathIdentity(filepath.Join(p.DataDir, path)) if errors.Is(err, os.ErrNotExist) { id, err = "", nil } if err != nil { return plan, err } if id != "" && p.Owns != nil { owned, err := p.Owns(path, id) if err != nil { return plan, fmt.Errorf("the ownership of %s: %w", path, err) } if !owned { plan.Items = append(plan.Items, localParkItem{Path: path, Unowned: true}) continue } } plan.Items = append(plan.Items, localParkItem{Path: path, ID: id}) } return plan, nil } // mkdirSynced makes dir (under root) and syncs it and every directory above // it up to root. Every call syncs the whole chain, not only the directories // it made: a replay after a stop between MkdirAll and the syncs finds the // directories there and must still make their entries durable. func mkdirSynced(root, dir string) error { if err := os.MkdirAll(dir, 0o770); err != nil { return err } return syncChain(root, dir) } // syncChain syncs dir and every directory above it up to and including root. // dir must be root or under it. func syncChain(root, dir string) error { root, dir = filepath.Clean(root), filepath.Clean(dir) if rel, err := filepath.Rel(root, dir); err != nil || rel == ".." || strings.HasPrefix(rel, "../") { return fmt.Errorf("%s is not under %s", dir, root) } for d := dir; ; d = filepath.Dir(d) { if err := retireSync(d); err != nil { return err } if d == root || d == filepath.Dir(d) { return nil } } } // syncRename makes a rename from src to dst durable: the source's parent, // and every destination directory up to root. func syncRename(root, src, dst string) error { if err := retireSync(filepath.Dir(src)); err != nil { return err } return syncChain(root, filepath.Dir(dst)) } // parkOpJournal renames the op's journal directory into the retirement's // artifacts, at .moves//. The directory is the op's own (its name // is the op id). Absent with the destination there is a replay after the // rename, which is synced again and done; absent with no destination is // nothing to park; a destination already there beside the journal is // refused. func parkOpJournal(dataDir, incarnation, host, op, retirement string) error { src := moves.JournalDir(dataDir, host, op) dst := filepath.Join(parkedArtifactsDir(dataDir, incarnation, host, retirement), ".moves", host, op) if _, err := os.Lstat(src); errors.Is(err, os.ErrNotExist) { if _, err := os.Lstat(dst); err == nil { return syncRename(dataDir, src, dst) } return nil } else if err != nil { return err } if _, err := os.Lstat(dst); err == nil { return fmt.Errorf("%s already holds a journal", dst) } else if !errors.Is(err, os.ErrNotExist) { return err } if err := mkdirSynced(dataDir, filepath.Dir(dst)); err != nil { return err } if err := os.Rename(src, dst); err != nil { return err } return syncRename(dataDir, src, dst) }