// This file holds configure's one CARLOS write, the after snapshot that // proves it preserved everything else, and the journalled rollback. Every // write is conditional, journalled before it is sent, and recovered after // a lost answer or a 412 by rereading (522 §4.7), never by guessing. package adopt import ( "context" "errors" "fmt" "net/http" "regexp" "slices" "strings" "amadan.net/oficina/alta/carlosop" "amadan.net/oficina/alta/provision" ) // Branch is what a reread after a lost answer or a 412 says of a write // (522 §4.7). The first that matches wins, preserved keys first. The zero // value is none of them. type Branch int const ( // Landed: every preserved key equals the baseline and both agent // keys hold what was sent. Landed Branch = iota + 1 // Retry: every preserved key equals the baseline and both agent keys // are absent. Retry with the version just read. Retry // StopPreservedChanged: a preserved key changed or went. StopPreservedChanged // StopConflict: the agent keys are partly present, or one holds // another digest or kind. Another writer touched them. StopConflict ) // RollbackBranch is what a reread says of a rollback. As for the write, // the first that matches wins, preserved keys first. The zero value is // none of them. type RollbackBranch int const ( // RetryUnset: every preserved key equals the baseline and both agent // keys hold exactly what the write sent. RetryUnset RollbackBranch = iota + 1 // RolledBack: every preserved key equals the baseline and both agent // keys are absent. RolledBack // StopForeign: one key alone is present, or either holds another // digest or kind. The runner never unsets a value it did not write. StopForeign // RollbackStopPreservedChanged: a preserved key changed or went. // Nothing is unset; a person looks first. RollbackStopPreservedChanged ) // The stops. Each is the end of the road for its app until Paul has // looked: the journal records it, and a resume refuses again. var ( ErrStopPreserved = errors.New("adopt: preserved-changed") ErrStopConflict = errors.New("adopt: agent-keys-conflict") ErrStopForeign = errors.New("adopt: agent-keys-foreign") ) // maxAttempts bounds the PUTs of one write or one rollback. const maxAttempts = 3 // sqidShape is a Home team sqid: the sqids alphabet, nothing else. var sqidShape = regexp.MustCompile(`^[A-Za-z0-9]{1,64}$`) func varsOf(l carlosop.Layer) map[string]carlosop.Var { m := make(map[string]carlosop.Var, len(l.Vars)) for _, v := range l.Vars { m[v.Key] = v } return m } // preservedEqual reports whether read holds every key of baseline other // than sent's, each with its kind and digest. A key read adds is not a // change: a platform writer's new key is reported elsewhere, never fatal. func preservedEqual(baseline, read carlosop.Layer, sent map[string]string) bool { if baseline.Bundle != read.Bundle { return false } now := varsOf(read) for _, b := range baseline.Vars { if _, ours := sent[b.Key]; ours { continue } a, ok := now[b.Key] if !ok || a.Kind != b.Kind || a.Digest != b.Digest { return false } } return true } // agentState counts sent's keys in read: those holding exactly what was // sent (a plain var with its digest), and those absent. func agentState(read carlosop.Layer, sent map[string]string) (mine, absent int) { now := varsOf(read) for k, v := range sent { got, ok := now[k] switch { case !ok: absent++ case got.Kind == "env" && got.Digest == carlosop.EnvDigest(v): mine++ } } return mine, absent } // Classify takes 522 §4.7's first matching branch for a reread of the // write layer, against the baseline's stored layer and what was sent. func Classify(baseline, read carlosop.Layer, sent map[string]string) Branch { if !preservedEqual(baseline, read, sent) { return StopPreservedChanged } mine, absent := agentState(read, sent) switch { case len(sent) != 2: return StopConflict case mine == 2: return Landed case absent == 2: return Retry } return StopConflict } // ClassifyRollback takes the first matching rollback branch, preserved // keys first (522 §4.7's rule, which binds the rollback too): a // preserved key that changed stops the rollback, even with our keys // still in place, for a person to investigate. func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) RollbackBranch { if !preservedEqual(baseline, read, sent) { return RollbackStopPreservedChanged } mine, absent := agentState(read, sent) switch { case len(sent) != 2: return StopForeign case mine == 2: return RetryUnset case absent == 2: return RolledBack } return StopForeign } // The journal's states move one way only. A write is sent, then landed // or stopped; nothing follows either. A rollback is sent, then unset, // then restarted, or stopped instead (an unset one too, when a change is // found before its restart); a rollback that finds the keys already gone // goes straight to unset. A state may repeat (a retry, a failed // restart), with its code updated. var ( writeNext = map[string][]string{ "": {"sent"}, "sent": {"sent", "landed", "stopped"}, } rollbackNext = map[string][]string{ "": {"sent", "unset", "stopped"}, "sent": {"sent", "unset", "stopped"}, "unset": {"unset", "restarted", "stopped"}, } ) func sameSent(a, b map[string]string) bool { if len(a) != len(b) { return false } for k, v := range a { if bv, ok := b[k]; !ok || bv != v { return false } } return true } // advanceWrite journals next if the app's write may move to it, and if // it sends what the journal already says was sent. func advanceWrite(ctx context.Context, s *Store, next WriteRecord) error { cur, ok, err := s.Write(ctx, next.App) if err != nil { return err } from := "" if ok { from = cur.State if !sameSent(cur.Sent, next.Sent) { return errors.New("adopt: sent-mismatch: the journal's write sent other values") } } if !slices.Contains(writeNext[from], next.State) { return fmt.Errorf("adopt: the write journal cannot go from %q to %q", from, next.State) } return s.SaveWrite(ctx, next) } // advanceRollback journals next if the app's rollback may move to it. func advanceRollback(ctx context.Context, s *Store, next RollbackRecord) error { cur, ok, err := s.Rollback(ctx, next.App) if err != nil { return err } from := "" if ok { from = cur.State } if !slices.Contains(rollbackNext[from], next.State) { return fmt.Errorf("adopt: the rollback journal cannot go from %q to %q", from, next.State) } return s.SaveRollback(ctx, next) } // stoppedErr is the error a stopped record answers with on a resume. func stoppedErr(code string) error { stop := ErrStopConflict switch code { case "preserved-changed", "identity-changed": stop = ErrStopPreserved case "agent-keys-foreign": stop = ErrStopForeign } return fmt.Errorf("%w: the journal says stopped (%s)", stop, code) } // lost reports whether err leaves a write's outcome to a reread: a 412, // or no answer at all (transport uncertainty). Nothing else is: a Put // never sent, or a refusal the console answered, wrote nothing and is // returned as it is; a malformed answer is a protocol failure, which // malformedAnswer stops on. func lost(err error) bool { if errors.Is(err, carlosop.ErrNotSent) || errors.Is(err, carlosop.ErrMalformedAnswer) { return false } return errors.Is(err, carlosop.ErrVersionMismatch) || errors.Is(err, carlosop.ErrNoAnswer) } // malformedAnswer reports whether the console answered a PUT with no // well-formed receipt for it. What it wrote is unknown, and a reread // cannot vouch for an answer that broke the protocol: the run stops. A // malformed answer to the read guarding a Put is not one: that PUT was // never sent. func malformedAnswer(err error) bool { return errors.Is(err, carlosop.ErrMalformedAnswer) && !errors.Is(err, carlosop.ErrNotSent) } // exactly reports whether got names each of keys once and nothing else. func exactly(got []string, keys [2]string) bool { return len(got) == 2 && got[0] != got[1] && slices.Contains(got, keys[0]) && slices.Contains(got, keys[1]) } // writeReceiptOK checks a write's 200: it set exactly the two keys, unset // nothing, carries the digest of what was sent for each and no other, was // made against ifVersion, and moved no other layer. func writeReceiptOK(rc carlosop.Receipt, keys [2]string, sent map[string]string, ifVersion string) bool { if !exactly(rc.Set, keys) || len(rc.Unset) != 0 || len(rc.UnsetAbsent) != 0 || rc.VersionBefore != ifVersion { return false } if len(rc.Digests) != 2 { return false } for _, k := range keys { if rc.Digests[k] != carlosop.EnvDigest(sent[k]) { return false } } for _, o := range rc.Others { // A side the console could not read is empty: not proof. if o.Before == "" || o.Before != o.After { return false } } return true } // unsetReceiptOK checks a rollback's 200: the two keys, each removed or // already absent, once, and nothing set. Already absent is accepted so a // retry after a committed answer that was lost passes. func unsetReceiptOK(rc carlosop.Receipt, keys [2]string) bool { if len(rc.Set) != 0 { return false } return exactly(append(append([]string{}, rc.Unset...), rc.UnsetAbsent...), keys) } // WriteAgentKeys writes app's two agent keys,
_AGENT_ISSUER = Issuer // and
_AGENT_TEAM = sqid, in one conditional PUT to the canonical
// host's write layer. It answers the dry-run description of the write.
//
// 1. A landed write is done: nothing is read or sent. A stopped one is
// refused again. Once a rollback is journalled, configure refuses.
// 2. Preflight runs on a fresh read, with mine set to the journal's sent
// values, and the served release must be the reviewed one, artifact
// (ReviewedRelease's codes); any code refuses it, with nothing
// written.
// 3. The baseline comes from the journal, or is this preflight's
// snapshot, sealed and stored. A journalled baseline that no longer
// describes the host's identity or write layer refuses the write.
// 4. The write is journalled as sent, then sent with if_version the
// baseline's version.
// 5. A 200 must carry a receipt for exactly this write
// (receipt-mismatch, ErrStopConflict, otherwise). One carlosop.Put
// refuses as malformed (none, another bundle, a malformed digest or
// version, unreadable) stops too (receipt-malformed): the console
// answered, so it is not a lost answer, and no reread stands in for
// the receipt.
// 6. A 412 or a lost answer (no answer at all) is reread and
// classified: landed is done;
// retry resends with the version just read, at most three PUTs in
// all (retry-exhausted); a stop is journalled and returned. The
// baseline is never retaken.
//
// A console that refuses if_version (carlosop.ErrNoConditional) stops the
// run with the record left at sent, code no-conditional. Without apply,
// it reads and refuses as it would, and stores and sends nothing.
func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, sqid, artifact string, apply bool) (string, error) {
switch {
case c == nil || h == nil || s == nil:
return "", errors.New("adopt: configure needs a console, a client and the journal")
case !sqidShape.MatchString(sqid):
return "", errors.New("adopt: the team is not a sqid")
}
keys := AgentKeys(app)
sent := map[string]string{keys[0]: Issuer, keys[1]: sqid}
if _, ok, err := s.Rollback(ctx, app.Slug); err != nil {
return "", err
} else if ok {
return "", errors.New("adopt: configure refused: rollback-recorded")
}
rec, have, err := s.Write(ctx, app.Slug)
if err != nil {
return "", err
}
if have {
if !sameSent(rec.Sent, sent) {
return "", errors.New("adopt: configure refused: sent-mismatch")
}
switch rec.State {
case "landed":
base, ok, err := s.Baseline(ctx, app.Slug)
if err != nil {
return "", err
}
if !ok {
return "", errors.New("adopt: the journal has a landed write and no baseline")
}
return WriteSummary(keys, base.Layer.Bundle), nil
case "stopped":
return "", stoppedErr(rec.Code)
}
}
var mine map[string]string
if have {
mine = rec.Sent
}
base, ok, err := s.Baseline(ctx, app.Slug)
if err != nil {
return "", err
}
var against *Snapshot
if ok {
against = &base
}
fresh, codes, err := admit(ctx, c, h, app, mine, against, artifact)
if err != nil {
return "", err
}
if len(codes) > 0 {
return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", "))
}
if !ok {
base = fresh
}
summary := WriteSummary(keys, base.Layer.Bundle)
if !apply {
return summary, nil
}
if !ok {
if err := s.SaveBaseline(ctx, app.Slug, base); err != nil {
return "", err
}
}
w := WriteRecord{App: app.Slug, State: "sent", Sent: sent}
if err := advanceWrite(ctx, s, w); err != nil {
return "", err
}
stop := func(code string, e error) (string, error) {
w.State, w.Code = "stopped", code
if err := advanceWrite(ctx, s, w); err != nil {
return "", err
}
return "", fmt.Errorf("%w (%s)", e, code)
}
ifVersion := base.Layer.Version
for attempt := 1; ; attempt++ {
rc, err := c.Put(ctx, app.Slug, carlosop.PutRequest{Environment: base.WriteLayer, Set: sent, IfVersion: ifVersion})
switch {
case err == nil:
if !writeReceiptOK(rc, keys, sent, ifVersion) {
// Kept, sealed, for Paul to look at.
w.Receipt = &rc
return stop("receipt-mismatch", ErrStopConflict)
}
w.State, w.Code, w.Receipt = "landed", "", &rc
if err := advanceWrite(ctx, s, w); err != nil {
return "", err
}
return summary, nil
case malformedAnswer(err):
return stop("receipt-malformed", ErrStopConflict)
case errors.Is(err, carlosop.ErrNoConditional):
w.Code = "no-conditional"
if serr := advanceWrite(ctx, s, w); serr != nil {
return "", serr
}
return "", err
case !lost(err):
return "", err
}
read, err := c.Config(ctx, app.Slug, base.WriteLayer)
if err != nil {
return "", err
}
switch Classify(base.Layer, read, sent) {
case Landed:
w.State, w.Code = "landed", ""
if err := advanceWrite(ctx, s, w); err != nil {
return "", err
}
return summary, nil
case StopPreservedChanged:
return stop("preserved-changed", ErrStopPreserved)
case Retry:
default:
return stop("agent-keys-conflict", ErrStopConflict)
}
if attempt >= maxAttempts {
w.Code = "retry-exhausted"
if err := advanceWrite(ctx, s, w); err != nil {
return "", err
}
return "", errors.New("adopt: retry-exhausted: the layer kept moving")
}
// Whatever moved the layer may be a refusal of its own (a
// team-mode key, a neighbour that would inherit): every preflight
// refusal is enforced again, on a fresh read, before the retry.
fresh, codes, err := admit(ctx, c, h, app, nil, &base, artifact)
if err != nil {
return "", err
}
if len(codes) > 0 {
w.Code = "preflight-refused"
if serr := advanceWrite(ctx, s, w); serr != nil {
return "", serr
}
return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", "))
}
// The retry is conditional on the layer that read saw, so it is
// classified again: anything else in between is a 412.
switch Classify(base.Layer, fresh.Layer, sent) {
case Retry:
case StopPreservedChanged:
return stop("preserved-changed", ErrStopPreserved)
default:
return stop("agent-keys-conflict", ErrStopConflict)
}
ifVersion = fresh.Layer.Version
}
}
// admit runs Preflight on a fresh read and, given the journalled
// baseline, adds write-layer-moved when the write layer is no longer the
// baseline's and identity- for each way the instance differs from
// it, and ReviewedRelease's code when the served release is not
// artifact. Any code refuses a write. Before a retry, mine is nil: the
// agent keys were just read absent, so a present one is another writer's.
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) {
fresh, codes, err := Preflight(ctx, c, h, app, mine)
if err != nil {
return fresh, codes, err
}
if code := ReviewedRelease(fresh.Delivery, artifact); code != "" {
codes = sortedSet(append(codes, code))
}
if len(codes) > 0 || base == nil {
return fresh, codes, nil
}
if base.WriteLayer != fresh.WriteLayer || base.Layer.Bundle != fresh.Layer.Bundle {
codes = append(codes, "write-layer-moved")
}
for _, code := range SameIdentity(base.Identity, fresh.Identity) {
codes = append(codes, "identity-"+code)
}
return fresh, codes, nil
}
// CaptureAfter takes and stores app's after snapshot, once the restart
// has passed Delivered against the baseline. It needs the baseline and a
// landed write, and refuses with ErrStopPreserved, storing nothing,
// unless a fresh observation:
//
// - preserves the baseline (Preserved is empty: every key but the two
// added, by digest, kind and source, every untouched layer and the
// identity);
// - holds both agent keys as plain vars from the write layer, with the
// digests of what was sent (agent-key: