| 1 | // This file holds configure's one CARLOS write, the after snapshot that |
| 2 | // proves it preserved everything else, and the journalled rollback. Every |
| 3 | // write is conditional, journalled before it is sent, and recovered after |
| 4 | // a lost answer or a 412 by rereading (522 §4.7), never by guessing. |
| 5 | package adopt |
| 6 | |
| 7 | import ( |
| 8 | "context" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "net/http" |
| 12 | "regexp" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | |
| 16 | "amadan.net/oficina/alta/carlosop" |
| 17 | "amadan.net/oficina/alta/provision" |
| 18 | ) |
| 19 | |
| 20 | // Branch is what a reread after a lost answer or a 412 says of a write |
| 21 | // (522 §4.7). The first that matches wins, preserved keys first. The zero |
| 22 | // value is none of them. |
| 23 | type Branch int |
| 24 | |
| 25 | const ( |
| 26 | // Landed: every preserved key equals the baseline and both agent |
| 27 | // keys hold what was sent. |
| 28 | Landed Branch = iota + 1 |
| 29 | // Retry: every preserved key equals the baseline and both agent keys |
| 30 | // are absent. Retry with the version just read. |
| 31 | Retry |
| 32 | // StopPreservedChanged: a preserved key changed or went. |
| 33 | StopPreservedChanged |
| 34 | // StopConflict: the agent keys are partly present, or one holds |
| 35 | // another digest or kind. Another writer touched them. |
| 36 | StopConflict |
| 37 | ) |
| 38 | |
| 39 | // RollbackBranch is what a reread says of a rollback. As for the write, |
| 40 | // the first that matches wins, preserved keys first. The zero value is |
| 41 | // none of them. |
| 42 | type RollbackBranch int |
| 43 | |
| 44 | const ( |
| 45 | // RetryUnset: every preserved key equals the baseline and both agent |
| 46 | // keys hold exactly what the write sent. |
| 47 | RetryUnset RollbackBranch = iota + 1 |
| 48 | // RolledBack: every preserved key equals the baseline and both agent |
| 49 | // keys are absent. |
| 50 | RolledBack |
| 51 | // StopForeign: one key alone is present, or either holds another |
| 52 | // digest or kind. The runner never unsets a value it did not write. |
| 53 | StopForeign |
| 54 | // RollbackStopPreservedChanged: a preserved key changed or went. |
| 55 | // Nothing is unset; a person looks first. |
| 56 | RollbackStopPreservedChanged |
| 57 | ) |
| 58 | |
| 59 | // The stops. Each is the end of the road for its app until Paul has |
| 60 | // looked: the journal records it, and a resume refuses again. |
| 61 | var ( |
| 62 | ErrStopPreserved = errors.New("adopt: preserved-changed") |
| 63 | ErrStopConflict = errors.New("adopt: agent-keys-conflict") |
| 64 | ErrStopForeign = errors.New("adopt: agent-keys-foreign") |
| 65 | ) |
| 66 | |
| 67 | // maxAttempts bounds the PUTs of one write or one rollback. |
| 68 | const maxAttempts = 3 |
| 69 | |
| 70 | // sqidShape is a Home team sqid: the sqids alphabet, nothing else. |
| 71 | var sqidShape = regexp.MustCompile(`^[A-Za-z0-9]{1,64}$`) |
| 72 | |
| 73 | func varsOf(l carlosop.Layer) map[string]carlosop.Var { |
| 74 | m := make(map[string]carlosop.Var, len(l.Vars)) |
| 75 | for _, v := range l.Vars { |
| 76 | m[v.Key] = v |
| 77 | } |
| 78 | return m |
| 79 | } |
| 80 | |
| 81 | // preservedEqual reports whether read holds every key of baseline other |
| 82 | // than sent's, each with its kind and digest. A key read adds is not a |
| 83 | // change: a platform writer's new key is reported elsewhere, never fatal. |
| 84 | func preservedEqual(baseline, read carlosop.Layer, sent map[string]string) bool { |
| 85 | if baseline.Bundle != read.Bundle { |
| 86 | return false |
| 87 | } |
| 88 | now := varsOf(read) |
| 89 | for _, b := range baseline.Vars { |
| 90 | if _, ours := sent[b.Key]; ours { |
| 91 | continue |
| 92 | } |
| 93 | a, ok := now[b.Key] |
| 94 | if !ok || a.Kind != b.Kind || a.Digest != b.Digest { |
| 95 | return false |
| 96 | } |
| 97 | } |
| 98 | return true |
| 99 | } |
| 100 | |
| 101 | // agentState counts sent's keys in read: those holding exactly what was |
| 102 | // sent (a plain var with its digest), and those absent. |
| 103 | func agentState(read carlosop.Layer, sent map[string]string) (mine, absent int) { |
| 104 | now := varsOf(read) |
| 105 | for k, v := range sent { |
| 106 | got, ok := now[k] |
| 107 | switch { |
| 108 | case !ok: |
| 109 | absent++ |
| 110 | case got.Kind == "env" && got.Digest == carlosop.EnvDigest(v): |
| 111 | mine++ |
| 112 | } |
| 113 | } |
| 114 | return mine, absent |
| 115 | } |
| 116 | |
| 117 | // Classify takes 522 §4.7's first matching branch for a reread of the |
| 118 | // write layer, against the baseline's stored layer and what was sent. |
| 119 | func Classify(baseline, read carlosop.Layer, sent map[string]string) Branch { |
| 120 | if !preservedEqual(baseline, read, sent) { |
| 121 | return StopPreservedChanged |
| 122 | } |
| 123 | mine, absent := agentState(read, sent) |
| 124 | switch { |
| 125 | case len(sent) != 2: |
| 126 | return StopConflict |
| 127 | case mine == 2: |
| 128 | return Landed |
| 129 | case absent == 2: |
| 130 | return Retry |
| 131 | } |
| 132 | return StopConflict |
| 133 | } |
| 134 | |
| 135 | // ClassifyRollback takes the first matching rollback branch, preserved |
| 136 | // keys first (522 §4.7's rule, which binds the rollback too): a |
| 137 | // preserved key that changed stops the rollback, even with our keys |
| 138 | // still in place, for a person to investigate. |
| 139 | func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) RollbackBranch { |
| 140 | if !preservedEqual(baseline, read, sent) { |
| 141 | return RollbackStopPreservedChanged |
| 142 | } |
| 143 | mine, absent := agentState(read, sent) |
| 144 | switch { |
| 145 | case len(sent) != 2: |
| 146 | return StopForeign |
| 147 | case mine == 2: |
| 148 | return RetryUnset |
| 149 | case absent == 2: |
| 150 | return RolledBack |
| 151 | } |
| 152 | return StopForeign |
| 153 | } |
| 154 | |
| 155 | // The journal's states move one way only. A write is sent, then landed |
| 156 | // or stopped; nothing follows either. A rollback is sent, then unset, |
| 157 | // then restarted, or stopped instead (an unset one too, when a change is |
| 158 | // found before its restart); a rollback that finds the keys already gone |
| 159 | // goes straight to unset. A state may repeat (a retry, a failed |
| 160 | // restart), with its code updated. |
| 161 | var ( |
| 162 | writeNext = map[string][]string{ |
| 163 | "": {"sent"}, |
| 164 | "sent": {"sent", "landed", "stopped"}, |
| 165 | } |
| 166 | rollbackNext = map[string][]string{ |
| 167 | "": {"sent", "unset", "stopped"}, |
| 168 | "sent": {"sent", "unset", "stopped"}, |
| 169 | "unset": {"unset", "restarted", "stopped"}, |
| 170 | } |
| 171 | ) |
| 172 | |
| 173 | func sameSent(a, b map[string]string) bool { |
| 174 | if len(a) != len(b) { |
| 175 | return false |
| 176 | } |
| 177 | for k, v := range a { |
| 178 | if bv, ok := b[k]; !ok || bv != v { |
| 179 | return false |
| 180 | } |
| 181 | } |
| 182 | return true |
| 183 | } |
| 184 | |
| 185 | // advanceWrite journals next if the app's write may move to it, and if |
| 186 | // it sends what the journal already says was sent. |
| 187 | func advanceWrite(ctx context.Context, s *Store, next WriteRecord) error { |
| 188 | cur, ok, err := s.Write(ctx, next.App) |
| 189 | if err != nil { |
| 190 | return err |
| 191 | } |
| 192 | from := "" |
| 193 | if ok { |
| 194 | from = cur.State |
| 195 | if !sameSent(cur.Sent, next.Sent) { |
| 196 | return errors.New("adopt: sent-mismatch: the journal's write sent other values") |
| 197 | } |
| 198 | } |
| 199 | if !slices.Contains(writeNext[from], next.State) { |
| 200 | return fmt.Errorf("adopt: the write journal cannot go from %q to %q", from, next.State) |
| 201 | } |
| 202 | return s.SaveWrite(ctx, next) |
| 203 | } |
| 204 | |
| 205 | // advanceRollback journals next if the app's rollback may move to it. |
| 206 | func advanceRollback(ctx context.Context, s *Store, next RollbackRecord) error { |
| 207 | cur, ok, err := s.Rollback(ctx, next.App) |
| 208 | if err != nil { |
| 209 | return err |
| 210 | } |
| 211 | from := "" |
| 212 | if ok { |
| 213 | from = cur.State |
| 214 | } |
| 215 | if !slices.Contains(rollbackNext[from], next.State) { |
| 216 | return fmt.Errorf("adopt: the rollback journal cannot go from %q to %q", from, next.State) |
| 217 | } |
| 218 | return s.SaveRollback(ctx, next) |
| 219 | } |
| 220 | |
| 221 | // stoppedErr is the error a stopped record answers with on a resume. |
| 222 | func stoppedErr(code string) error { |
| 223 | stop := ErrStopConflict |
| 224 | switch code { |
| 225 | case "preserved-changed", "identity-changed": |
| 226 | stop = ErrStopPreserved |
| 227 | case "agent-keys-foreign": |
| 228 | stop = ErrStopForeign |
| 229 | } |
| 230 | return fmt.Errorf("%w: the journal says stopped (%s)", stop, code) |
| 231 | } |
| 232 | |
| 233 | // lost reports whether err leaves a write's outcome to a reread: a 412, |
| 234 | // or no answer at all (transport uncertainty). Nothing else is: a Put |
| 235 | // never sent, or a refusal the console answered, wrote nothing and is |
| 236 | // returned as it is; a malformed answer is a protocol failure, which |
| 237 | // malformedAnswer stops on. |
| 238 | func lost(err error) bool { |
| 239 | if errors.Is(err, carlosop.ErrNotSent) || errors.Is(err, carlosop.ErrMalformedAnswer) { |
| 240 | return false |
| 241 | } |
| 242 | return errors.Is(err, carlosop.ErrVersionMismatch) || errors.Is(err, carlosop.ErrNoAnswer) |
| 243 | } |
| 244 | |
| 245 | // malformedAnswer reports whether the console answered a PUT with no |
| 246 | // well-formed receipt for it. What it wrote is unknown, and a reread |
| 247 | // cannot vouch for an answer that broke the protocol: the run stops. A |
| 248 | // malformed answer to the read guarding a Put is not one: that PUT was |
| 249 | // never sent. |
| 250 | func malformedAnswer(err error) bool { |
| 251 | return errors.Is(err, carlosop.ErrMalformedAnswer) && !errors.Is(err, carlosop.ErrNotSent) |
| 252 | } |
| 253 | |
| 254 | // exactly reports whether got names each of keys once and nothing else. |
| 255 | func exactly(got []string, keys [2]string) bool { |
| 256 | return len(got) == 2 && got[0] != got[1] && slices.Contains(got, keys[0]) && slices.Contains(got, keys[1]) |
| 257 | } |
| 258 | |
| 259 | // writeReceiptOK checks a write's 200: it set exactly the two keys, unset |
| 260 | // nothing, carries the digest of what was sent for each and no other, was |
| 261 | // made against ifVersion, and moved no other layer. |
| 262 | func writeReceiptOK(rc carlosop.Receipt, keys [2]string, sent map[string]string, ifVersion string) bool { |
| 263 | if !exactly(rc.Set, keys) || len(rc.Unset) != 0 || len(rc.UnsetAbsent) != 0 || rc.VersionBefore != ifVersion { |
| 264 | return false |
| 265 | } |
| 266 | if len(rc.Digests) != 2 { |
| 267 | return false |
| 268 | } |
| 269 | for _, k := range keys { |
| 270 | if rc.Digests[k] != carlosop.EnvDigest(sent[k]) { |
| 271 | return false |
| 272 | } |
| 273 | } |
| 274 | for _, o := range rc.Others { |
| 275 | // A side the console could not read is empty: not proof. |
| 276 | if o.Before == "" || o.Before != o.After { |
| 277 | return false |
| 278 | } |
| 279 | } |
| 280 | return true |
| 281 | } |
| 282 | |
| 283 | // unsetReceiptOK checks a rollback's 200: the two keys, each removed or |
| 284 | // already absent, once, and nothing set. Already absent is accepted so a |
| 285 | // retry after a committed answer that was lost passes. |
| 286 | func unsetReceiptOK(rc carlosop.Receipt, keys [2]string) bool { |
| 287 | if len(rc.Set) != 0 { |
| 288 | return false |
| 289 | } |
| 290 | return exactly(append(append([]string{}, rc.Unset...), rc.UnsetAbsent...), keys) |
| 291 | } |
| 292 | |
| 293 | // WriteAgentKeys writes app's two agent keys, <P>_AGENT_ISSUER = Issuer |
| 294 | // and <P>_AGENT_TEAM = sqid, in one conditional PUT to the canonical |
| 295 | // host's write layer. It answers the dry-run description of the write. |
| 296 | // |
| 297 | // 1. A landed write is done: nothing is read or sent. A stopped one is |
| 298 | // refused again. Once a rollback is journalled, configure refuses. |
| 299 | // 2. Preflight runs on a fresh read, with mine set to the journal's sent |
| 300 | // values, and the served release must be the reviewed one, artifact |
| 301 | // (ReviewedRelease's codes); any code refuses it, with nothing |
| 302 | // written. |
| 303 | // 3. The baseline comes from the journal, or is this preflight's |
| 304 | // snapshot, sealed and stored. A journalled baseline that no longer |
| 305 | // describes the host's identity or write layer refuses the write. |
| 306 | // 4. The write is journalled as sent, then sent with if_version the |
| 307 | // baseline's version. |
| 308 | // 5. A 200 must carry a receipt for exactly this write |
| 309 | // (receipt-mismatch, ErrStopConflict, otherwise). One carlosop.Put |
| 310 | // refuses as malformed (none, another bundle, a malformed digest or |
| 311 | // version, unreadable) stops too (receipt-malformed): the console |
| 312 | // answered, so it is not a lost answer, and no reread stands in for |
| 313 | // the receipt. |
| 314 | // 6. A 412 or a lost answer (no answer at all) is reread and |
| 315 | // classified: landed is done; |
| 316 | // retry resends with the version just read, at most three PUTs in |
| 317 | // all (retry-exhausted); a stop is journalled and returned. The |
| 318 | // baseline is never retaken. |
| 319 | // |
| 320 | // A console that refuses if_version (carlosop.ErrNoConditional) stops the |
| 321 | // run with the record left at sent, code no-conditional. Without apply, |
| 322 | // it reads and refuses as it would, and stores and sends nothing. |
| 323 | func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, sqid, artifact string, apply bool) (string, error) { |
| 324 | switch { |
| 325 | case c == nil || h == nil || s == nil: |
| 326 | return "", errors.New("adopt: configure needs a console, a client and the journal") |
| 327 | case !sqidShape.MatchString(sqid): |
| 328 | return "", errors.New("adopt: the team is not a sqid") |
| 329 | } |
| 330 | keys := AgentKeys(app) |
| 331 | sent := map[string]string{keys[0]: Issuer, keys[1]: sqid} |
| 332 | if _, ok, err := s.Rollback(ctx, app.Slug); err != nil { |
| 333 | return "", err |
| 334 | } else if ok { |
| 335 | return "", errors.New("adopt: configure refused: rollback-recorded") |
| 336 | } |
| 337 | rec, have, err := s.Write(ctx, app.Slug) |
| 338 | if err != nil { |
| 339 | return "", err |
| 340 | } |
| 341 | if have { |
| 342 | if !sameSent(rec.Sent, sent) { |
| 343 | return "", errors.New("adopt: configure refused: sent-mismatch") |
| 344 | } |
| 345 | switch rec.State { |
| 346 | case "landed": |
| 347 | base, ok, err := s.Baseline(ctx, app.Slug) |
| 348 | if err != nil { |
| 349 | return "", err |
| 350 | } |
| 351 | if !ok { |
| 352 | return "", errors.New("adopt: the journal has a landed write and no baseline") |
| 353 | } |
| 354 | return WriteSummary(keys, base.Layer.Bundle), nil |
| 355 | case "stopped": |
| 356 | return "", stoppedErr(rec.Code) |
| 357 | } |
| 358 | } |
| 359 | var mine map[string]string |
| 360 | if have { |
| 361 | mine = rec.Sent |
| 362 | } |
| 363 | base, ok, err := s.Baseline(ctx, app.Slug) |
| 364 | if err != nil { |
| 365 | return "", err |
| 366 | } |
| 367 | var against *Snapshot |
| 368 | if ok { |
| 369 | against = &base |
| 370 | } |
| 371 | fresh, codes, err := admit(ctx, c, h, app, mine, against, artifact) |
| 372 | if err != nil { |
| 373 | return "", err |
| 374 | } |
| 375 | if len(codes) > 0 { |
| 376 | return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", ")) |
| 377 | } |
| 378 | if !ok { |
| 379 | base = fresh |
| 380 | } |
| 381 | summary := WriteSummary(keys, base.Layer.Bundle) |
| 382 | if !apply { |
| 383 | return summary, nil |
| 384 | } |
| 385 | if !ok { |
| 386 | if err := s.SaveBaseline(ctx, app.Slug, base); err != nil { |
| 387 | return "", err |
| 388 | } |
| 389 | } |
| 390 | w := WriteRecord{App: app.Slug, State: "sent", Sent: sent} |
| 391 | if err := advanceWrite(ctx, s, w); err != nil { |
| 392 | return "", err |
| 393 | } |
| 394 | stop := func(code string, e error) (string, error) { |
| 395 | w.State, w.Code = "stopped", code |
| 396 | if err := advanceWrite(ctx, s, w); err != nil { |
| 397 | return "", err |
| 398 | } |
| 399 | return "", fmt.Errorf("%w (%s)", e, code) |
| 400 | } |
| 401 | ifVersion := base.Layer.Version |
| 402 | for attempt := 1; ; attempt++ { |
| 403 | rc, err := c.Put(ctx, app.Slug, carlosop.PutRequest{Environment: base.WriteLayer, Set: sent, IfVersion: ifVersion}) |
| 404 | switch { |
| 405 | case err == nil: |
| 406 | if !writeReceiptOK(rc, keys, sent, ifVersion) { |
| 407 | // Kept, sealed, for Paul to look at. |
| 408 | w.Receipt = &rc |
| 409 | return stop("receipt-mismatch", ErrStopConflict) |
| 410 | } |
| 411 | w.State, w.Code, w.Receipt = "landed", "", &rc |
| 412 | if err := advanceWrite(ctx, s, w); err != nil { |
| 413 | return "", err |
| 414 | } |
| 415 | return summary, nil |
| 416 | case malformedAnswer(err): |
| 417 | return stop("receipt-malformed", ErrStopConflict) |
| 418 | case errors.Is(err, carlosop.ErrNoConditional): |
| 419 | w.Code = "no-conditional" |
| 420 | if serr := advanceWrite(ctx, s, w); serr != nil { |
| 421 | return "", serr |
| 422 | } |
| 423 | return "", err |
| 424 | case !lost(err): |
| 425 | return "", err |
| 426 | } |
| 427 | read, err := c.Config(ctx, app.Slug, base.WriteLayer) |
| 428 | if err != nil { |
| 429 | return "", err |
| 430 | } |
| 431 | switch Classify(base.Layer, read, sent) { |
| 432 | case Landed: |
| 433 | w.State, w.Code = "landed", "" |
| 434 | if err := advanceWrite(ctx, s, w); err != nil { |
| 435 | return "", err |
| 436 | } |
| 437 | return summary, nil |
| 438 | case StopPreservedChanged: |
| 439 | return stop("preserved-changed", ErrStopPreserved) |
| 440 | case Retry: |
| 441 | default: |
| 442 | return stop("agent-keys-conflict", ErrStopConflict) |
| 443 | } |
| 444 | if attempt >= maxAttempts { |
| 445 | w.Code = "retry-exhausted" |
| 446 | if err := advanceWrite(ctx, s, w); err != nil { |
| 447 | return "", err |
| 448 | } |
| 449 | return "", errors.New("adopt: retry-exhausted: the layer kept moving") |
| 450 | } |
| 451 | // Whatever moved the layer may be a refusal of its own (a |
| 452 | // team-mode key, a neighbour that would inherit): every preflight |
| 453 | // refusal is enforced again, on a fresh read, before the retry. |
| 454 | fresh, codes, err := admit(ctx, c, h, app, nil, &base, artifact) |
| 455 | if err != nil { |
| 456 | return "", err |
| 457 | } |
| 458 | if len(codes) > 0 { |
| 459 | w.Code = "preflight-refused" |
| 460 | if serr := advanceWrite(ctx, s, w); serr != nil { |
| 461 | return "", serr |
| 462 | } |
| 463 | return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", ")) |
| 464 | } |
| 465 | // The retry is conditional on the layer that read saw, so it is |
| 466 | // classified again: anything else in between is a 412. |
| 467 | switch Classify(base.Layer, fresh.Layer, sent) { |
| 468 | case Retry: |
| 469 | case StopPreservedChanged: |
| 470 | return stop("preserved-changed", ErrStopPreserved) |
| 471 | default: |
| 472 | return stop("agent-keys-conflict", ErrStopConflict) |
| 473 | } |
| 474 | ifVersion = fresh.Layer.Version |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | // admit runs Preflight on a fresh read and, given the journalled |
| 479 | // baseline, adds write-layer-moved when the write layer is no longer the |
| 480 | // baseline's and identity-<code> for each way the instance differs from |
| 481 | // it, and ReviewedRelease's code when the served release is not |
| 482 | // artifact. Any code refuses a write. Before a retry, mine is nil: the |
| 483 | // agent keys were just read absent, so a present one is another writer's. |
| 484 | func admit(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string, base *Snapshot, artifact string) (Snapshot, []string, error) { |
| 485 | fresh, codes, err := Preflight(ctx, c, h, app, mine) |
| 486 | if err != nil { |
| 487 | return fresh, codes, err |
| 488 | } |
| 489 | if code := ReviewedRelease(fresh.Delivery, artifact); code != "" { |
| 490 | codes = sortedSet(append(codes, code)) |
| 491 | } |
| 492 | if len(codes) > 0 || base == nil { |
| 493 | return fresh, codes, nil |
| 494 | } |
| 495 | if base.WriteLayer != fresh.WriteLayer || base.Layer.Bundle != fresh.Layer.Bundle { |
| 496 | codes = append(codes, "write-layer-moved") |
| 497 | } |
| 498 | for _, code := range SameIdentity(base.Identity, fresh.Identity) { |
| 499 | codes = append(codes, "identity-"+code) |
| 500 | } |
| 501 | return fresh, codes, nil |
| 502 | } |
| 503 | |
| 504 | // CaptureAfter takes and stores app's after snapshot, once the restart |
| 505 | // has passed Delivered against the baseline. It needs the baseline and a |
| 506 | // landed write, and refuses with ErrStopPreserved, storing nothing, |
| 507 | // unless a fresh observation: |
| 508 | // |
| 509 | // - preserves the baseline (Preserved is empty: every key but the two |
| 510 | // added, by digest, kind and source, every untouched layer and the |
| 511 | // identity); |
| 512 | // - holds both agent keys as plain vars from the write layer, with the |
| 513 | // digests of what was sent (agent-key:<KEY>); |
| 514 | // - holds no team-mode key (team-mode-<KEY>). |
| 515 | // |
| 516 | // A fresh probe that does not pass Delivered is after-not-delivered. A |
| 517 | // key a platform writer added is not a refusal; NewKeys reports it. |
| 518 | func CaptureAfter(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App) (Snapshot, error) { |
| 519 | if s == nil { |
| 520 | return Snapshot{}, errors.New("adopt: no adoption journal") |
| 521 | } |
| 522 | base, ok, err := s.Baseline(ctx, app.Slug) |
| 523 | if err != nil { |
| 524 | return Snapshot{}, err |
| 525 | } |
| 526 | if !ok { |
| 527 | return Snapshot{}, errors.New("adopt: after-baseline-missing") |
| 528 | } |
| 529 | w, ok, err := s.Write(ctx, app.Slug) |
| 530 | if err != nil { |
| 531 | return Snapshot{}, err |
| 532 | } |
| 533 | if !ok || w.State != "landed" { |
| 534 | return Snapshot{}, errors.New("adopt: after-write-not-landed") |
| 535 | } |
| 536 | after, err := Observe(ctx, c, h, app) |
| 537 | if err != nil { |
| 538 | return Snapshot{}, err |
| 539 | } |
| 540 | keys := AgentKeys(app) |
| 541 | codes := Preserved(base, after, keys) |
| 542 | for _, k := range keys { |
| 543 | v := findVar(after.Vars, k) |
| 544 | if v == nil || v.Kind != "env" || v.From != layerName(base.WriteLayer) || v.Digest != carlosop.EnvDigest(w.Sent[k]) { |
| 545 | codes = append(codes, "agent-key:"+k) |
| 546 | } |
| 547 | } |
| 548 | for _, k := range TeamModeKeys(app, after.Vars) { |
| 549 | codes = append(codes, "team-mode-"+k) |
| 550 | } |
| 551 | if len(codes) > 0 { |
| 552 | return Snapshot{}, fmt.Errorf("%w: %s", ErrStopPreserved, strings.Join(sortedSet(codes), ", ")) |
| 553 | } |
| 554 | if err := Delivered(app, base.Delivery, after.Delivery); err != nil { |
| 555 | return Snapshot{}, fmt.Errorf("adopt: after-not-delivered: %w", err) |
| 556 | } |
| 557 | if err := s.SaveAfter(ctx, app.Slug, after); err != nil { |
| 558 | return Snapshot{}, err |
| 559 | } |
| 560 | return after, nil |
| 561 | } |
| 562 | |
| 563 | // RollbackAgentKeys removes the two agent keys configure wrote, then |
| 564 | // restarts the canonical host until the app is back to its baseline |
| 565 | // shape. It is journalled, and a resume continues from the journal: |
| 566 | // |
| 567 | // - restarted is done; stopped is refused again; |
| 568 | // - before anything else, and again before every PUT, the host is |
| 569 | // re-observed against the baseline (rollbackDrift): a changed |
| 570 | // identity stops the rollback (identity-changed), as does any |
| 571 | // preserved key that changed anywhere in the effective config, or a |
| 572 | // layer the write did not touch that moved (preserved-changed); |
| 573 | // - unset goes to the restart, which re-observes again first; |
| 574 | // - otherwise the write layer that observation read is classified |
| 575 | // (ClassifyRollback). RetryUnset journals sent and sends one |
| 576 | // conditional PUT unsetting both keys at the version just read; a |
| 577 | // 412 or a lost answer is re-observed and classified again, at most |
| 578 | // three PUTs in all. RolledBack goes to the restart without a PUT. A |
| 579 | // malformed answer stops it (receipt-malformed). A stop is |
| 580 | // journalled and returned. |
| 581 | // |
| 582 | // The restart goes through RestartAndWait, so through RestartCanonical's |
| 583 | // dry run, and waits for Reverted against the baseline: removing the |
| 584 | // stored keys does not stop the running process. Only then is the |
| 585 | // rollback restarted. A restart that fails or never reverts leaves it at |
| 586 | // unset with code restart-failed. Without apply, it reads, classifies and |
| 587 | // makes the restart's dry run, and stores and sends nothing else. |
| 588 | func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, apply bool) error { |
| 589 | if c == nil || h == nil || s == nil { |
| 590 | return errors.New("adopt: rollback needs a console, a client and the journal") |
| 591 | } |
| 592 | keys := AgentKeys(app) |
| 593 | w, ok, err := s.Write(ctx, app.Slug) |
| 594 | if err != nil { |
| 595 | return err |
| 596 | } |
| 597 | if !ok { |
| 598 | return errors.New("adopt: rollback-nothing-written") |
| 599 | } |
| 600 | if len(w.Sent) != 2 || w.Sent[keys[0]] == "" || w.Sent[keys[1]] == "" { |
| 601 | return errors.New("adopt: the journal's write does not name the agent keys") |
| 602 | } |
| 603 | base, ok, err := s.Baseline(ctx, app.Slug) |
| 604 | if err != nil { |
| 605 | return err |
| 606 | } |
| 607 | if !ok { |
| 608 | return errors.New("adopt: rollback-baseline-missing") |
| 609 | } |
| 610 | rb, have, err := s.Rollback(ctx, app.Slug) |
| 611 | if err != nil { |
| 612 | return err |
| 613 | } |
| 614 | if !have { |
| 615 | rb = RollbackRecord{App: app.Slug} |
| 616 | } |
| 617 | stop := func(code string, e error, detail ...string) error { |
| 618 | if apply { |
| 619 | rb.State, rb.Code = "stopped", code |
| 620 | if err := advanceRollback(ctx, s, rb); err != nil { |
| 621 | return err |
| 622 | } |
| 623 | } |
| 624 | if len(detail) > 0 { |
| 625 | return fmt.Errorf("%w (%s): %s", e, code, strings.Join(detail, ", ")) |
| 626 | } |
| 627 | return fmt.Errorf("%w (%s)", e, code) |
| 628 | } |
| 629 | switch rb.State { |
| 630 | case "restarted": |
| 631 | return nil |
| 632 | case "stopped": |
| 633 | return stoppedErr(rb.Code) |
| 634 | case "unset": |
| 635 | return rollbackRestart(ctx, c, h, s, app, base, rb, apply) |
| 636 | } |
| 637 | for attempt := 1; ; attempt++ { |
| 638 | read, code, diff, err := rollbackDrift(ctx, c, app, base) |
| 639 | if err != nil { |
| 640 | return err |
| 641 | } |
| 642 | if code != "" { |
| 643 | return stop(code, ErrStopPreserved, diff...) |
| 644 | } |
| 645 | switch ClassifyRollback(base.Layer, read, w.Sent) { |
| 646 | case RolledBack: |
| 647 | if apply { |
| 648 | rb.State, rb.Code = "unset", "" |
| 649 | if err := advanceRollback(ctx, s, rb); err != nil { |
| 650 | return err |
| 651 | } |
| 652 | } |
| 653 | return rollbackRestart(ctx, c, h, s, app, base, rb, apply) |
| 654 | case StopForeign: |
| 655 | return stop("agent-keys-foreign", ErrStopForeign) |
| 656 | case RollbackStopPreservedChanged: |
| 657 | return stop("preserved-changed", ErrStopPreserved) |
| 658 | case RetryUnset: |
| 659 | default: |
| 660 | return stop("agent-keys-foreign", ErrStopForeign) |
| 661 | } |
| 662 | if !apply { |
| 663 | return rollbackRestart(ctx, c, h, s, app, base, rb, false) |
| 664 | } |
| 665 | if attempt > maxAttempts { |
| 666 | rb.State, rb.Code = "sent", "retry-exhausted" |
| 667 | if err := advanceRollback(ctx, s, rb); err != nil { |
| 668 | return err |
| 669 | } |
| 670 | return errors.New("adopt: retry-exhausted: the layer kept moving") |
| 671 | } |
| 672 | rb.State, rb.Code = "sent", "" |
| 673 | if err := advanceRollback(ctx, s, rb); err != nil { |
| 674 | return err |
| 675 | } |
| 676 | rc, err := c.Put(ctx, app.Slug, carlosop.PutRequest{Environment: base.WriteLayer, Unset: keys[:], IfVersion: read.Version}) |
| 677 | switch { |
| 678 | case err == nil: |
| 679 | if !unsetReceiptOK(rc, keys) { |
| 680 | rb.Receipt = &rc |
| 681 | return stop("receipt-mismatch", ErrStopConflict) |
| 682 | } |
| 683 | rb.State, rb.Receipt = "unset", &rc |
| 684 | if err := advanceRollback(ctx, s, rb); err != nil { |
| 685 | return err |
| 686 | } |
| 687 | return rollbackRestart(ctx, c, h, s, app, base, rb, true) |
| 688 | case malformedAnswer(err): |
| 689 | return stop("receipt-malformed", ErrStopConflict) |
| 690 | case errors.Is(err, carlosop.ErrNoConditional): |
| 691 | rb.Code = "no-conditional" |
| 692 | if serr := advanceRollback(ctx, s, rb); serr != nil { |
| 693 | return serr |
| 694 | } |
| 695 | return err |
| 696 | case !lost(err): |
| 697 | return err |
| 698 | } |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | // rollbackDrift re-observes app's canonical host, its identity and its |
| 703 | // config only (no delivery probe: a rollback must reach an app that is |
| 704 | // down), and compares it with the baseline, as every rollback mutation |
| 705 | // needs first. It answers the write layer that observation read and, |
| 706 | // when anything differs, the stop code and what differs, by field and |
| 707 | // key name only: |
| 708 | // |
| 709 | // - identity-changed: the canonical domain is no longer one claim |
| 710 | // routed to a record, or the record's instance, alias, environment |
| 711 | // binding, storage or record is not the baseline's (identity-<field>); |
| 712 | // a claim that is merely not live is not a change; |
| 713 | // - preserved-changed: any key of the baseline but the two agent keys |
| 714 | // changed, went, changed kind or moved layer, in the effective config |
| 715 | // or the write layer's stored vars, or a layer the write did not |
| 716 | // touch moved (Preserved's codes), or the host's Home issuer can no |
| 717 | // longer be located (observe's codes). |
| 718 | func rollbackDrift(ctx context.Context, c *carlosop.Client, app provision.App, base Snapshot) (carlosop.Layer, string, []string, error) { |
| 719 | fresh, _, codes, err := observe(ctx, c, nil, app) |
| 720 | // A claim that is not live still names the same record, which |
| 721 | // SameIdentity compares below: the rollback goes on, and its probe |
| 722 | // says whether the name is served. |
| 723 | codes = slices.DeleteFunc(codes, func(code string) bool { return code == "domain-not-live" }) |
| 724 | switch { |
| 725 | case err != nil: |
| 726 | return carlosop.Layer{}, "", nil, err |
| 727 | case slices.ContainsFunc(codes, unbound): |
| 728 | return carlosop.Layer{}, "identity-changed", codes, nil |
| 729 | case len(codes) > 0: |
| 730 | return carlosop.Layer{}, "preserved-changed", codes, nil |
| 731 | } |
| 732 | if id := SameIdentity(base.Identity, fresh.Identity); len(id) > 0 { |
| 733 | for i := range id { |
| 734 | id[i] = "identity-" + id[i] |
| 735 | } |
| 736 | return fresh.Layer, "identity-changed", id, nil |
| 737 | } |
| 738 | if diff := Preserved(base, fresh, AgentKeys(app)); len(diff) > 0 { |
| 739 | return fresh.Layer, "preserved-changed", diff, nil |
| 740 | } |
| 741 | return fresh.Layer, "", nil, nil |
| 742 | } |
| 743 | |
| 744 | // unbound reports whether an observe code says the canonical domain no |
| 745 | // longer resolves to a record. |
| 746 | func unbound(code string) bool { |
| 747 | switch code { |
| 748 | case "domain-missing", "domain-ambiguous", "instance-missing": |
| 749 | return true |
| 750 | } |
| 751 | return false |
| 752 | } |
| 753 | |
| 754 | // rollbackRestart restarts the canonical host and waits for Reverted |
| 755 | // against the baseline, then journals the rollback restarted. A failure |
| 756 | // journals it unset, code restart-failed, for a resume. |
| 757 | // |
| 758 | // Every rollback restart comes through here, after a fresh unset, a |
| 759 | // RolledBack reread or a resume at unset, so here the host is |
| 760 | // re-observed against the baseline first (rollbackDrift): the restart is |
| 761 | // a mutation too, and a change that landed during the unset, or since, |
| 762 | // stops the rollback with nothing restarted. |
| 763 | func rollbackRestart(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, base Snapshot, rb RollbackRecord, apply bool) error { |
| 764 | if _, code, diff, err := rollbackDrift(ctx, c, app, base); err != nil { |
| 765 | return err |
| 766 | } else if code != "" { |
| 767 | if apply { |
| 768 | rb.State, rb.Code = "stopped", code |
| 769 | if err := advanceRollback(ctx, s, rb); err != nil { |
| 770 | return err |
| 771 | } |
| 772 | } |
| 773 | return fmt.Errorf("%w (%s): %s", ErrStopPreserved, code, strings.Join(diff, ", ")) |
| 774 | } |
| 775 | _, err := RestartAndWait(ctx, c, h, app, base.Identity, func(d Delivery) error { return Reverted(base.Delivery, d) }, apply) |
| 776 | if !apply { |
| 777 | return err |
| 778 | } |
| 779 | if err != nil { |
| 780 | rb.State, rb.Code = "unset", "restart-failed" |
| 781 | if serr := advanceRollback(ctx, s, rb); serr != nil { |
| 782 | return errors.Join(err, serr) |
| 783 | } |
| 784 | return err |
| 785 | } |
| 786 | rb.State, rb.Code = "restarted", "" |
| 787 | return advanceRollback(ctx, s, rb) |
| 788 | } |
| 789 | |