carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1package provision
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "log"
8 "os"
9
10 "github.com/carlosframework/platform/internal/registry"
11 "github.com/carlosframework/platform/internal/release"
12 "github.com/carlosframework/platform/internal/seeds"
13)
14
15// rollbackImport is spec §5.6's rollback, driven by the journal and not the
16// record (codex R2-7). Each step is idempotent, and the journal's state is
17// where a later pass resumes:
18//
19// swapped 1. close the gate (journal rolling-back, with a fence generation)
20// rolling-back 2. fence and stop the host under the journal's generation
21// 3. retire the instance key the import created, then
22// remove the import's local data
23// 4. put the original route back (journal cleanup-pending)
24// 5. lift the fence
25// cleanup-pending 6. delete this seed's snapshot and the host's replica
26// 7. delete the journal row
27// 8. CAS the record to rolled-back, if it names this seed
28//
29// The route steps act only on the import's own row (importRowOf). Any other
30// row at the host belongs to someone else, a later instance when a stale
31// journal row came back from a snapshot, and the rollback holds there,
32// touching nothing, until an operator looks. A host with no row at all is
33// rolled back without a restore: whatever removed the import's row decided
34// the host should not be served. Its local database at the host's default
35// path is still removed when the database's <db>.seed marker names this
36// seed and the host still has no row.
37//
38// Step 3 retires the import's instance key first (merge review S1). The
39// key the import's first launch minted into the host's own env file would
40// otherwise outlive the rollback and outrank the key a second import of
41// the host configures. The journal's EnvBefore, recorded at the swap, says
42// what was there before the import: only what the import created goes
43// (SeedHooks.RetireKey). With the row gone the key is retired under the
44// same marker rule as the database, and before it, so the marker that
45// proves the installation is the import's is still there if the key's
46// removal has to be tried again.
47//
48// rec is the pass's view of the journal's record (nil when gone). It chose
49// the rollback; the destructive cleanup reads the record again (step 6).
50func rollbackImport(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig, j registry.ImportJournal, rec *Record) {
51 h := cfg.Seeds
52 if cfg.DryRun {
53 log.Printf("provision: dry-run: would roll back %s's import %s", j.Host, j.SeedID)
54 return
55 }
56 if !rollbackArmed(h) {
57 log.Printf("provision: %s: import %s cannot roll back on this box: the activator is not wired; it stays journaled and gated", j.Host, j.SeedID)
58 return
59 }
60 switch j.State {
61 case registry.JournalSwapped, registry.JournalRollingBack:
62 var ok bool
63 if j, ok = rollBackRoute(ctx, s, reg, cfg, j); !ok {
64 return
65 }
66 case registry.JournalCleanupPending:
67 default:
68 log.Printf("provision: %s: import %s is journaled in an unknown state %q; leaving it alone", j.Host, j.SeedID, j.State)
69 return
70 }
71 cleanUpImport(ctx, s, reg, cfg, j)
72}
73
74// importRowOf reports whether rt is j's import row as the swap made it:
75// the registry's test (gated, provisioned, naming the seed, whose ids are
76// never reused), at the nested database path the swap gave it. The path is
77// what step 3 removes at, so a row pointing anywhere else is not acted on.
78func importRowOf(cfg ReconcileConfig, rt registry.Route, j registry.ImportJournal) bool {
79 return registry.IsImportRow(rt, j) && rt.DBPath == NestedDBPath(cfg.DataDir, j.Host)
80}
81
82// rollBackRoute is steps 1 to 5. It returns the journal as it now stands
83// and whether the route steps are done (the journal is cleanup-pending).
84func rollBackRoute(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig, j registry.ImportJournal) (registry.ImportJournal, bool) {
85 h := cfg.Seeds
86 // Nothing is closed, fenced or removed for a row that is not the
87 // import's. The registry refuses the gate close and the restore for
88 // one as well; this check keeps the fence and the removal off it.
89 row, err := reg.Get(j.Host)
90 if err != nil {
91 log.Printf("provision: %s: import %s rollback deferred: the route could not be read: %v", j.Host, j.SeedID, err)
92 return j, false
93 }
94 if row != nil && !importRowOf(cfg, *row, j) {
95 // A fence an earlier pass kept for this rollback must not hold the
96 // host for whoever owns it now. LiftFence lifts only this
97 // generation.
98 if j.State == registry.JournalRollingBack {
99 h.LiftFence(j.Host, j.FenceGen)
100 }
101 log.Printf("provision: %s: import %s is not rolled back: the route at the host is not the import's, so nothing there is touched", j.Host, j.SeedID)
102 return j, false
103 }
104
105 // Step 1. The generation an earlier close stored is the one the fence
106 // is known by, so the journal is read back rather than trusted.
107 if j.State == registry.JournalSwapped {
108 gen, err := h.NextFenceGen()
109 if err == nil && gen == 0 {
110 err = errors.New("the generation source answered 0")
111 }
112 if err != nil {
113 log.Printf("provision: %s: import %s rollback deferred: no fence generation: %v", j.Host, j.SeedID, err)
114 return j, false
115 }
116 if err := reg.CloseImportGate(j.Host, j.SeedID, gen); err != nil {
117 log.Printf("provision: %s: import %s: close the import gate: %v", j.Host, j.SeedID, err)
118 return j, false
119 }
120 cur, err := reg.ImportJournal(j.Host)
121 if err != nil || cur == nil || cur.SeedID != j.SeedID || cur.State != registry.JournalRollingBack {
122 log.Printf("provision: %s: import %s: the journal after the gate closed is %+v (%v)", j.Host, j.SeedID, cur, err)
123 return j, false
124 }
125 j = *cur
126 }
127
128 // Step 2. The host is fenced and stopped before anything is removed,
129 // so no wake can write the database or the replica afterwards. The
130 // hook lifts any fence it installs when it does not proceed.
131 proceed, err := h.FenceForRollback(ctx, j.Host, j.FenceGen)
132 if err != nil || !proceed {
133 if err != nil {
134 h.LiftFence(j.Host, j.FenceGen) // a hook that failed may have fenced first
135 }
136 log.Printf("provision: %s: import %s rollback deferred: the host is not fenced and stopped yet (%v)", j.Host, j.SeedID, err)
137 return j, false
138 }
139
140 // Step 3, under the fence. A failure from here on keeps the fence: the
141 // next pass finds it its own by the journal's generation and resumes.
142 row, err = reg.Get(j.Host)
143 if err != nil {
144 log.Printf("provision: %s: import %s: read the route under the fence: %v", j.Host, j.SeedID, err)
145 return j, false
146 }
147 switch {
148 case row == nil:
149 if !removeOrphanedLocal(reg, cfg, j) {
150 return j, false
151 }
152 case !importRowOf(cfg, *row, j) || row.ImportGate != registry.ImportGateClosed:
153 h.LiftFence(j.Host, j.FenceGen)
154 log.Printf("provision: %s: import %s is not rolled back: the route changed under the fence, so nothing there is touched", j.Host, j.SeedID)
155 return j, false
156 default:
157 if err := h.RetireKey(row.DBPath, j.Host, j.EnvBefore); err != nil {
158 log.Printf("provision: %s: import %s: retire its instance key: %v", j.Host, j.SeedID, err)
159 return j, false
160 }
161 if err := h.RemoveLocal(*row); err != nil {
162 log.Printf("provision: %s: import %s: remove its local data: %v", j.Host, j.SeedID, err)
163 return j, false
164 }
165 }
166
167 // Step 4: the original route back, and the journal at cleanup-pending,
168 // in one transaction. Step 5: the fence goes.
169 if err := reg.RestoreImportRoute(j.Host, j.SeedID); err != nil {
170 log.Printf("provision: %s: import %s: restore the original route: %v", j.Host, j.SeedID, err)
171 return j, false
172 }
173 h.LiftFence(j.Host, j.FenceGen)
174 j.State = registry.JournalCleanupPending
175 if row != nil {
176 log.Printf("provision: %s: import %s rolled back to its original route", j.Host, j.SeedID)
177 }
178 return j, true
179}
180
181// cleanUpImport is steps 6 to 8, run from cleanup-pending. It never fences
182// or stops anything: the route is the original row by now (or none), and
183// its process is the app's own.
184func cleanUpImport(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig, j registry.ImportJournal) {
185 h := cfg.Seeds
186 valid := seeds.Check(j.Host, j.SeedID) == nil
187 if !valid {
188 log.Printf("provision: %s: import %q names no snapshot and no replica; only its journal row is cleaned up", j.Host, j.SeedID)
189 } else if err := h.Data.Delete(ctx, seeds.SnapshotKey(j.Host, j.SeedID)); err != nil && !errors.Is(err, os.ErrNotExist) {
190 log.Printf("provision: %s: import %s: delete its snapshot: %v", j.Host, j.SeedID, err)
191 return
192 }
193
194 // The replica is keyed by host, not by seed, so the record is read
195 // again right before it: the pass's copy may be stale.
196 rec, err := journalRecordByKey(ctx, s, j)
197 if err != nil {
198 log.Printf("provision: %s: import %s cleanup deferred: its record cannot be read: %v", j.Host, j.SeedID, err)
199 return
200 }
201 if valid {
202 ours, why, err := replicaIsTheImports(ctx, s, j, rec)
203 switch {
204 case err != nil:
205 log.Printf("provision: %s: import %s cleanup deferred: %v", j.Host, j.SeedID, err)
206 return
207 case !ours:
208 log.Printf("provision: %s: import %s: the host's replica is left alone: %s", j.Host, j.SeedID, why)
209 default:
210 if err := h.DeleteReplica(ctx, j.Host); err != nil {
211 log.Printf("provision: %s: import %s: delete the host's replica: %v", j.Host, j.SeedID, err)
212 return
213 }
214 }
215 }
216
217 if err := reg.DeleteImportJournal(j.Host, j.SeedID); err != nil {
218 log.Printf("provision: %s: import %s: retire its journal row: %v", j.Host, j.SeedID, err)
219 return
220 }
221 log.Printf("provision: %s: import %s is cleaned up and its journal row retired", j.Host, j.SeedID)
222
223 // Step 8. Only from aborted (SeedRolledBack): a record already
224 // refused or rolled back, or gone, is done. An aborted record whose
225 // CAS fails is finished by the no-journal path on a later pass.
226 if rec == nil || rec.Seed == nil || rec.Seed.ID != j.SeedID {
227 return
228 }
229 if _, err := SetRecordSeed(ctx, s, rec.Account, rec.App, rec.Host, SeedRolledBack(j.SeedID)); err != nil &&
230 !errors.Is(err, ErrSeedConflict) && !errors.Is(err, os.ErrNotExist) {
231 log.Printf("provision: %s: mark import %s rolled back: %v", j.Host, j.SeedID, err)
232 }
233}
234
235// removeOrphanedLocal is step 3 for an import whose row something removed,
236// run under the fence. Its local database is still at the host's default
237// nested path (routeFor's), where a later instance at the host would open
238// it as a warm cache and replicate it as its own. It is decided from the
239// file, whoever holds the host's record: while the journal row exists no
240// other row can be minted at the host, so under the fence nothing else
241// has that file open. The database is removed only when its <db>.seed
242// marker names this seed and the host still has no row. A marker that is
243// absent or names another seed does not prove the data is the import's,
244// so the file is left. The import's instance key is retired by the same
245// rule, just before the database, and left with it. ok false defers the
246// rollback, with the fence lifted.
247func removeOrphanedLocal(reg *registry.Registry, cfg ReconcileConfig, j registry.ImportJournal) (ok bool) {
248 h := cfg.Seeds
249 db := NestedDBPath(cfg.DataDir, j.Host)
250 id, err := h.LocalSeedID(db)
251 if err != nil {
252 h.LiftFence(j.Host, j.FenceGen)
253 log.Printf("provision: %s: import %s rollback deferred: the seed marker beside %s cannot be read: %v", j.Host, j.SeedID, db, err)
254 return false
255 }
256 if id != j.SeedID {
257 log.Printf("provision: %s: import %s has no route on this box; the database at %s is left: its seed marker names %q, not this seed", j.Host, j.SeedID, db, id)
258 return true
259 }
260 row, err := reg.Get(j.Host)
261 if err != nil {
262 h.LiftFence(j.Host, j.FenceGen)
263 log.Printf("provision: %s: import %s rollback deferred: the route could not be read: %v", j.Host, j.SeedID, err)
264 return false
265 }
266 if row != nil {
267 // Not expected while journaled. The next pass judges the row.
268 h.LiftFence(j.Host, j.FenceGen)
269 log.Printf("provision: %s: import %s: a route appeared at the host, so its local database is left and the rollback waits", j.Host, j.SeedID)
270 return false
271 }
272 // The key before the database: the marker just read is what says this
273 // installation is the import's, and RemoveLocal removes it.
274 if err := h.RetireKey(db, j.Host, j.EnvBefore); err != nil {
275 log.Printf("provision: %s: import %s: retire its instance key: %v", j.Host, j.SeedID, err)
276 return false
277 }
278 if err := h.RemoveLocal(registry.Route{Host: j.Host, Kind: "instance", DBPath: db}); err != nil {
279 log.Printf("provision: %s: import %s: remove its local data: %v", j.Host, j.SeedID, err)
280 return false
281 }
282 log.Printf("provision: %s: import %s has no route on this box: its local data is removed and no route is put back", j.Host, j.SeedID)
283 return true
284}
285
286// replicaIsTheImports decides step 6's replica delete. The host's replica
287// is the import's to delete only while the journal's record, if there is
288// one, still names this seed in an abandoned state, and no other record
289// holds the host. A record gone with no other record for the host counts.
290// A record naming another seed, or none, or another record for the host,
291// means the replica is someone else's: ours is false, and why says so.
292// Anything this pass cannot tell is an error, and the cleanup waits.
293func replicaIsTheImports(ctx context.Context, s release.Store, j registry.ImportJournal, rec *Record) (ours bool, why string, err error) {
294 if rec != nil {
295 switch {
296 case rec.Seed == nil || rec.Seed.ID != j.SeedID:
297 return false, "its record no longer names this seed", nil
298 case rec.Seed.State != seeds.StateAborted && rec.Seed.State != seeds.StateRefused && rec.Seed.State != seeds.StateRolledBack:
299 return false, "", fmt.Errorf("its record names this seed as %s, not abandoned", rec.Seed.State)
300 }
301 }
302 known, failed, err := knownAccounts(ctx, s)
303 if err != nil {
304 return false, "", err
305 }
306 if failed {
307 return false, "", errors.New("an account could not be read, so another record for the host cannot be ruled out")
308 }
309 keys, partial, err := listAppSubtree(ctx, s, known, "instances/")
310 if err != nil {
311 return false, "", err
312 }
313 if partial {
314 return false, "", errors.New("the records could not all be listed, so another record for the host cannot be ruled out")
315 }
316 for _, key := range keys {
317 if _, _, host, ok := ParseRecordKey(key, known); ok && host == j.Host && key != j.RecordKey {
318 return false, "the record " + key + " holds the host", nil
319 }
320 }
321 return true, "", nil
322}
323
324// journalRecordByKey reads the record under the journal's own key: nil when
325// it is gone, an error when it cannot be read, does not decode, or is not
326// the journal's (another host or key in its body).
327func journalRecordByKey(ctx context.Context, s release.Store, j registry.ImportJournal) (*Record, error) {
328 raw, _, err := s.Get(ctx, j.RecordKey)
329 if errors.Is(err, os.ErrNotExist) {
330 return nil, nil
331 }
332 if err != nil {
333 return nil, err
334 }
335 r, err := DecodeRecord(raw)
336 if err != nil {
337 return nil, err
338 }
339 if r.Host != j.Host || RecordKey(r.Account, r.App, r.Host) != j.RecordKey {
340 return nil, fmt.Errorf("the record under %s is %s's", j.RecordKey, RecordKey(r.Account, r.App, r.Host))
341 }
342 return &r, nil
343}
344