// Package datamigrate versions the data folder via StampFile and applies // idempotent in-place upgrades on startup. StampFile is separate from // reims-go.json so older releases rewriting Config from their struct do not // strip unknown version fields. package datamigrate import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "time" ) // StampFile sits at the root of the data folder. const StampFile = ".reims-go-data.json" // CurrentVersion is the data layout this build writes. Bump it together // with a new Step. const CurrentVersion = 3 // Stamp is the content of StampFile. type Stamp struct { DataVersion int `json:"data_version"` WrittenBy string `json:"written_by,omitempty"` // app version that last raised DataVersion UpdatedAt time.Time `json:"updated_at"` } // Step upgrades the data folder to layout To. Steps must be idempotent: a // step that fails part way is run again on the next start. type Step struct { To int Name string Run func(dataRoot string) error } // steps lists every upgrade in ascending To order. var steps = []Step{ {To: 1, Name: "vm-owner-markers", Run: backfillOwnerMarkers}, {To: 3, Name: "guest-vmref-metadata", Run: migrateGuestAndVMRef}, } // Result reports what Run did. type Result struct { From int // version found on disk (0 when unstamped) To int // version on disk afterwards Applied []string // names of the steps that ran // Newer is true when the folder was written by a newer release. Nothing // is changed then; the newer release owns the layout. Newer bool } // Run brings the data folder at dataRoot up to CurrentVersion. A missing or // empty dataRoot is not an error: there is nothing to migrate yet. func Run(dataRoot, appVersion string) (Result, error) { return run(dataRoot, appVersion, steps, CurrentVersion, time.Now, false) } // ErrDamagedStamp reports a StampFile that cannot be read. Run then changes // nothing: the folder may belong to a newer release whose stamp this build // cannot parse. Repair rebuilds it on the user's explicit request. var ErrDamagedStamp = errors.New("data version stamp is damaged") // Repair is Run for a folder whose stamp is damaged: it treats the folder as // unstamped and runs every step from version 0. Steps are idempotent, so this // is safe on a folder that was already partly or fully migrated. func Repair(dataRoot, appVersion string) (Result, error) { return run(dataRoot, appVersion, steps, CurrentVersion, time.Now, true) } func run(dataRoot, appVersion string, steps []Step, current int, now func() time.Time, repair bool) (Result, error) { if dataRoot == "" { return Result{}, nil } if st, err := os.Stat(dataRoot); err != nil || !st.IsDir() { return Result{}, nil } stamp, readErr := ReadStamp(dataRoot) if readErr != nil { if !repair { return Result{}, fmt.Errorf("%w: %v", ErrDamagedStamp, readErr) } stamp = Stamp{} } res := Result{From: stamp.DataVersion, To: stamp.DataVersion} if stamp.DataVersion > current { res.Newer = true return res, nil } for _, s := range steps { if s.To <= res.To || s.To > current { continue } if err := s.Run(dataRoot); err != nil { if res.To > res.From { _ = writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()}) } return res, fmt.Errorf("data migration %q (to v%d): %w", s.Name, s.To, err) } res.To = s.To res.Applied = append(res.Applied, s.Name) } // A folder already stamped at this layout is left untouched; anything // else (steps ran, no stamp yet, damaged stamp) gets a fresh stamp. if stamp.DataVersion == current && readErr == nil && stampExists(dataRoot) { return res, nil } res.To = current if err := writeStamp(dataRoot, Stamp{DataVersion: current, WrittenBy: appVersion, UpdatedAt: now()}); err != nil { return res, err } return res, nil } // ReadStamp reads StampFile. A folder without one is at version 0. func ReadStamp(dataRoot string) (Stamp, error) { raw, err := os.ReadFile(filepath.Join(dataRoot, StampFile)) if errors.Is(err, os.ErrNotExist) { return Stamp{}, nil } if err != nil { return Stamp{}, err } var s Stamp if err := json.Unmarshal(raw, &s); err != nil { return Stamp{}, fmt.Errorf("parse %s: %w", StampFile, err) } if s.DataVersion < 0 { return Stamp{}, fmt.Errorf("%s: negative data_version", StampFile) } return s, nil } func stampExists(dataRoot string) bool { _, err := os.Stat(filepath.Join(dataRoot, StampFile)) return err == nil } func writeStamp(dataRoot string, s Stamp) error { raw, err := json.MarshalIndent(s, "", " ") if err != nil { return err } path := filepath.Join(dataRoot, StampFile) tmp := path + ".tmp" if err := os.WriteFile(tmp, append(raw, '\n'), 0o644); err != nil { return err } return os.Rename(tmp, path) }