|
| 1 | +// Package corromigrate handles the one-time migration of the on-disk Corrosion store from |
| 2 | +// systemd-managed v0.x to v1.0.0 running in a uncloudd-managed container. |
| 3 | +// TODO: remove in 0.22 assuming all pre 0.20 clusters upgraded their pre-v1 Corrosion. |
| 4 | +package corromigrate |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "database/sql" |
| 9 | + "encoding/json" |
| 10 | + "errors" |
| 11 | + "fmt" |
| 12 | + "log/slog" |
| 13 | + "os" |
| 14 | + "os/exec" |
| 15 | + "path/filepath" |
| 16 | + "time" |
| 17 | + |
| 18 | + "github.com/psviderski/uncloud/internal/fs" |
| 19 | + "github.com/psviderski/uncloud/internal/machine/api/pb" |
| 20 | + "github.com/psviderski/uncloud/internal/machine/store" |
| 21 | + "google.golang.org/protobuf/encoding/protojson" |
| 22 | + _ "modernc.org/sqlite" |
| 23 | +) |
| 24 | + |
| 25 | +// legacyUnitName is the systemd unit that ran Corrosion before uncloudd took over its lifecycle. |
| 26 | +// The unit file at /etc/systemd/system/uncloud-corrosion.service and the binary at |
| 27 | +// /usr/local/bin/uncloud-corrosion are left in place after migration because uncloudd's sandbox |
| 28 | +// (ProtectSystem=full) blocks their removal. Operators should delete them manually as documented |
| 29 | +// in the release notes. |
| 30 | +const legacyUnitName = "uncloud-corrosion.service" |
| 31 | + |
| 32 | +// Seed is the on-disk representation of the durable rows dumped from a v0.x Corrosion store, |
| 33 | +// to be re-applied to the fresh v1.0.0 store. Existence of the seed file is the signal that |
| 34 | +// migration has not yet fully completed. |
| 35 | +type Seed struct { |
| 36 | + Cluster []ClusterEntry `json:"cluster"` |
| 37 | + Machines []MachineEntry `json:"machines"` |
| 38 | +} |
| 39 | + |
| 40 | +type ClusterEntry struct { |
| 41 | + Key string `json:"key"` |
| 42 | + Value string `json:"value"` |
| 43 | +} |
| 44 | + |
| 45 | +type MachineEntry struct { |
| 46 | + ID string `json:"id"` |
| 47 | + Info string `json:"info"` |
| 48 | +} |
| 49 | + |
| 50 | +func seedPath(dir string) string { return dir + ".seed-v1.json" } |
| 51 | + |
| 52 | +func backupPath(dir string) string { |
| 53 | + return dir + ".backup-" + time.Now().UTC().Format("20060102.150405") |
| 54 | +} |
| 55 | + |
| 56 | +// MigrateIfNeeded stops the legacy systemd Corrosion unit and, when a v0.x store.db is detected, dumps its durable |
| 57 | +// rows to a seed file next to the data dir, then backs up the dir so the new version can start fresh. |
| 58 | +// Idempotent: if the seed file already exists, the dump step is skipped (a prior run already produced it). |
| 59 | +func MigrateIfNeeded(ctx context.Context, dir, owner string) error { |
| 60 | + stopLegacyUnit() |
| 61 | + |
| 62 | + seedFile := seedPath(dir) |
| 63 | + if _, err := os.Stat(seedFile); err == nil { |
| 64 | + slog.Info("Corrosion migrations seed file found, dump already produced by a prior run.", |
| 65 | + "path", seedFile) |
| 66 | + return nil |
| 67 | + } else if !errors.Is(err, os.ErrNotExist) { |
| 68 | + return fmt.Errorf("stat seed file '%s': %w", seedFile, err) |
| 69 | + } |
| 70 | + |
| 71 | + dbFile := filepath.Join(dir, "store.db") |
| 72 | + if _, err := os.Stat(dbFile); errors.Is(err, os.ErrNotExist) { |
| 73 | + return nil |
| 74 | + } else if err != nil { |
| 75 | + return fmt.Errorf("stat '%s': %w", dbFile, err) |
| 76 | + } |
| 77 | + |
| 78 | + isV0, err := isV0Store(ctx, dbFile) |
| 79 | + if err != nil { |
| 80 | + return fmt.Errorf("detect old store version: %w", err) |
| 81 | + } |
| 82 | + if !isV0 { |
| 83 | + return nil |
| 84 | + } |
| 85 | + |
| 86 | + slog.Info("Migrating Corrosion store from v0.x to v1.0.0.", "db", dbFile) |
| 87 | + |
| 88 | + dump, err := dumpOldStore(ctx, dbFile) |
| 89 | + if err != nil { |
| 90 | + return fmt.Errorf("dump old store: %w", err) |
| 91 | + } |
| 92 | + slog.Info("Corrosion store dumped.", |
| 93 | + "cluster_rows", len(dump.Cluster), "machine_rows", len(dump.Machines)) |
| 94 | + |
| 95 | + if err = writeSeedAtomic(seedFile, dump, owner); err != nil { |
| 96 | + return fmt.Errorf("write seed file: %w", err) |
| 97 | + } |
| 98 | + slog.Info("Corrosion migration seed file written.", "path", seedFile) |
| 99 | + |
| 100 | + backup := backupPath(dir) |
| 101 | + if err = os.Rename(dir, backup); err != nil { |
| 102 | + return fmt.Errorf("backup corrosion dir: %w", err) |
| 103 | + } |
| 104 | + slog.Info("Old Corrosion dir backed up.", "from", dir, "to", backup) |
| 105 | + |
| 106 | + return nil |
| 107 | +} |
| 108 | + |
| 109 | +// stopLegacyUnit stops and disables the legacy uncloud-corrosion systemd unit if present. |
| 110 | +// Best-effort: errors are swallowed because the unit may not exist (fresh install) or systemctl |
| 111 | +// may be unavailable (containerised hosts). |
| 112 | +func stopLegacyUnit() { |
| 113 | + for _, cmd := range []string{"stop", "disable"} { |
| 114 | + if err := exec.Command("systemctl", cmd, legacyUnitName).Run(); err != nil { |
| 115 | + slog.Debug("systemctl on legacy corrosion unit failed (likely absent).", |
| 116 | + "cmd", cmd, "unit", legacyUnitName, "err", err) |
| 117 | + } |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +// isV0Store reports whether the SQLite database at dbPath is in the old v0.x Corrosion format. |
| 122 | +// v0.x has a __corro_bookkeeping table that was dropped in v1.0.0. |
| 123 | +func isV0Store(ctx context.Context, dbPath string) (bool, error) { |
| 124 | + db, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro") |
| 125 | + if err != nil { |
| 126 | + return false, fmt.Errorf("open db '%s': %w", dbPath, err) |
| 127 | + } |
| 128 | + defer db.Close() |
| 129 | + |
| 130 | + var one int |
| 131 | + err = db.QueryRowContext(ctx, |
| 132 | + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='__corro_bookkeeping' LIMIT 1", |
| 133 | + ).Scan(&one) |
| 134 | + if errors.Is(err, sql.ErrNoRows) { |
| 135 | + return false, nil |
| 136 | + } |
| 137 | + if err != nil { |
| 138 | + return false, err |
| 139 | + } |
| 140 | + return true, nil |
| 141 | +} |
| 142 | + |
| 143 | +func dumpOldStore(ctx context.Context, dbPath string) (*Seed, error) { |
| 144 | + db, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro") |
| 145 | + if err != nil { |
| 146 | + return nil, fmt.Errorf("open %q: %w", dbPath, err) |
| 147 | + } |
| 148 | + defer db.Close() |
| 149 | + |
| 150 | + seed := &Seed{} |
| 151 | + |
| 152 | + clusterRows, err := db.QueryContext(ctx, "SELECT key, value FROM cluster") |
| 153 | + if err != nil { |
| 154 | + return nil, fmt.Errorf("query cluster: %w", err) |
| 155 | + } |
| 156 | + for clusterRows.Next() { |
| 157 | + var key, value string |
| 158 | + if err = clusterRows.Scan(&key, &value); err != nil { |
| 159 | + clusterRows.Close() |
| 160 | + return nil, fmt.Errorf("scan cluster row: %w", err) |
| 161 | + } |
| 162 | + seed.Cluster = append(seed.Cluster, ClusterEntry{Key: key, Value: value}) |
| 163 | + } |
| 164 | + if err = clusterRows.Err(); err != nil { |
| 165 | + clusterRows.Close() |
| 166 | + return nil, fmt.Errorf("iterate cluster rows: %w", err) |
| 167 | + } |
| 168 | + clusterRows.Close() |
| 169 | + |
| 170 | + machineRows, err := db.QueryContext(ctx, "SELECT id, info FROM machines") |
| 171 | + if err != nil { |
| 172 | + return nil, fmt.Errorf("query machines: %w", err) |
| 173 | + } |
| 174 | + defer machineRows.Close() |
| 175 | + for machineRows.Next() { |
| 176 | + var id, info string |
| 177 | + if err = machineRows.Scan(&id, &info); err != nil { |
| 178 | + return nil, fmt.Errorf("scan machine row: %w", err) |
| 179 | + } |
| 180 | + seed.Machines = append(seed.Machines, MachineEntry{ID: id, Info: info}) |
| 181 | + } |
| 182 | + if err = machineRows.Err(); err != nil { |
| 183 | + return nil, fmt.Errorf("iterate machine rows: %w", err) |
| 184 | + } |
| 185 | + return seed, nil |
| 186 | +} |
| 187 | + |
| 188 | +func writeSeedAtomic(path string, seed *Seed, owner string) error { |
| 189 | + tmp := path + ".tmp" |
| 190 | + data, err := json.MarshalIndent(seed, "", " ") |
| 191 | + if err != nil { |
| 192 | + return err |
| 193 | + } |
| 194 | + |
| 195 | + f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) |
| 196 | + if err != nil { |
| 197 | + return err |
| 198 | + } |
| 199 | + if _, err = f.Write(data); err != nil { |
| 200 | + f.Close() |
| 201 | + os.Remove(tmp) |
| 202 | + return fmt.Errorf("write seed: %w", err) |
| 203 | + } |
| 204 | + if err = f.Sync(); err != nil { |
| 205 | + f.Close() |
| 206 | + os.Remove(tmp) |
| 207 | + return fmt.Errorf("fsync seed: %w", err) |
| 208 | + } |
| 209 | + if err = f.Close(); err != nil { |
| 210 | + os.Remove(tmp) |
| 211 | + return fmt.Errorf("close seed: %w", err) |
| 212 | + } |
| 213 | + |
| 214 | + if owner != "" { |
| 215 | + if chErr := fs.Chown(tmp, owner, owner); chErr != nil { |
| 216 | + os.Remove(tmp) |
| 217 | + return chErr |
| 218 | + } |
| 219 | + } |
| 220 | + if err = os.Rename(tmp, path); err != nil { |
| 221 | + return fmt.Errorf("rename seed: %w", err) |
| 222 | + } |
| 223 | + |
| 224 | + // Fsync the parent directory so the rename entry is durable. |
| 225 | + dir, err := os.Open(filepath.Dir(path)) |
| 226 | + if err != nil { |
| 227 | + return fmt.Errorf("open parent dir for fsync: %w", err) |
| 228 | + } |
| 229 | + defer dir.Close() |
| 230 | + if err = dir.Sync(); err != nil { |
| 231 | + return fmt.Errorf("fsync parent dir: %w", err) |
| 232 | + } |
| 233 | + return nil |
| 234 | +} |
| 235 | + |
| 236 | +// ApplySeedIfPresent re-applies the durable rows from the seed file into the running Corrosion store, |
| 237 | +// then deletes the seed file as the final completion marker. Idempotent: re-running on the same seed |
| 238 | +// is a no-op for cluster rows (INSERT OR REPLACE) and machines rows (skipped via GetMachine). |
| 239 | +func ApplySeedIfPresent(ctx context.Context, dir string, st *store.Store) error { |
| 240 | + seedFile := seedPath(dir) |
| 241 | + data, err := os.ReadFile(seedFile) |
| 242 | + if errors.Is(err, os.ErrNotExist) { |
| 243 | + return nil |
| 244 | + } |
| 245 | + if err != nil { |
| 246 | + return fmt.Errorf("read seed file: %w", err) |
| 247 | + } |
| 248 | + |
| 249 | + var seed Seed |
| 250 | + if err = json.Unmarshal(data, &seed); err != nil { |
| 251 | + return fmt.Errorf("parse seed file: %w", err) |
| 252 | + } |
| 253 | + slog.Info("Applying Corrosion migration seed.", |
| 254 | + "cluster_rows", len(seed.Cluster), "machine_rows", len(seed.Machines)) |
| 255 | + |
| 256 | + for _, e := range seed.Cluster { |
| 257 | + if err = st.Put(ctx, e.Key, e.Value); err != nil { |
| 258 | + return fmt.Errorf("seed cluster row '%s': %w", e.Key, err) |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + for _, e := range seed.Machines { |
| 263 | + var m pb.MachineInfo |
| 264 | + if err = protojson.Unmarshal([]byte(e.Info), &m); err != nil { |
| 265 | + return fmt.Errorf("parse machine '%s' info: %w", e.ID, err) |
| 266 | + } |
| 267 | + if _, err = st.GetMachine(ctx, m.Id); err == nil { |
| 268 | + continue |
| 269 | + } else if !errors.Is(err, store.ErrMachineNotFound) { |
| 270 | + return fmt.Errorf("check machine '%s': %w", m.Id, err) |
| 271 | + } |
| 272 | + if err = st.CreateMachine(ctx, &m); err != nil { |
| 273 | + return fmt.Errorf("seed machine '%s': %w", m.Id, err) |
| 274 | + } |
| 275 | + } |
| 276 | + |
| 277 | + if err = os.Remove(seedFile); err != nil { |
| 278 | + return fmt.Errorf("delete seed file: %w", err) |
| 279 | + } |
| 280 | + slog.Info("Corrosion migration completed.") |
| 281 | + return nil |
| 282 | +} |
0 commit comments