moves: carlos move offline run carries one move through (Task 5)
offlinerun.Runner (Step and Run) drives Decide over a Doors interface: read status, decide, at most one action, 2 s. A POST that is not a clean 2xx is followed by a status read, never resent. Ctrl-C: first aborts before open, second stops watching; after open nothing is undone. SIGHUP ignored on linux and darwin. The CLI verb prints one line per step (OR rows, approved by Luna), with --log appending the same bytes. Decide now counts a round that answers our own stage before the next read as watched, so a fast stager cannot exhaust the round cap. Census overlay omr-run for the --log OpenFile; golden, parity and CLI page fence updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+1,797
−20
approved_moves_copy_test.go+24 −2docs/parity.md+2 −2docs/site/cli.md+1 −0docs/superpowers/notes/census-proposal-omr-run.md+15 −0docs/superpowers/plans/2026-10-06-moves-phase1-copy.md+36 −0internal/moves/offlinerun/decide.go+12 −1internal/moves/offlinerun/decide_test.go+24 −0internal/moves/offlinerun/run.go+180 −0internal/moves/offlinerun/run_test.go+232 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-omr-run.tsv+7 −0move.go+32 −5move_offline_run.go+532 −0move_offline_run_other.go+7 −0move_offline_run_test.go+619 −0move_offline_run_unix.go+13 −0move_test.go+56 −9parity/cli.tsv+1 −0parity/parity.tsv+1 −1testdata/clireg-golden.jsonl+2 −0
diff --git a/approved_moves_copy_test.go b/approved_moves_copy_test.go| index f4ec99c03..9c57abb39 100644 |
| --- a/approved_moves_copy_test.go |
| +++ b/approved_moves_copy_test.go |
| @@ -114,6 +114,12 @@ var movesCopyIDs = []string{ |
| // #339: refused while the instance still serves, and status after an |
| // abort from staging. |
| "MV-O200", "MV-O202", "MV-O203", "MV-O204", |
| + // carlos move offline run (plans/2026-11-15-offline-move-run.md, Task 5; |
| + // deck docs/drafts/offline-move-run/copy-review/strings.json). |
| + "OR01", "OR02", "OR03", "OR04", "OR05", "OR06", "OR07", |
| + "OR10", "OR11", "OR12", "OR13", "OR14", "OR15", "OR16", "OR17", "OR18", "OR19", |
| + "OR20", "OR21", "OR22", "OR23", "OR24", "OR25", "OR26", "OR27", "OR28", "OR29", |
| + "OR40", "OR45", |
| } |
| // copyRow is one row of the record. The File cell is the file the sentence is |
| @@ -131,7 +137,7 @@ func (r copyRow) Path() string { |
| return r.File |
| } |
| -var movesCopyIDPattern = regexp.MustCompile(`^(M-C|MV-N|MV-O|HC5-N|RUN-C)[0-9]+$`) |
| +var movesCopyIDPattern = regexp.MustCompile(`^(M-C|MV-N|MV-O|HC5-N|RUN-C|OR)[0-9]+$`) |
| // parseMovesCopyRecord reads the record's tables. A data row is a line that |
| // follows a `| id | file | text | status |` header; the separator line is |
| @@ -146,7 +152,7 @@ func parseMovesCopyRecord(path string) ([]copyRow, error) { |
| } |
| func parseMovesCopyTable(src, name string) ([]copyRow, error) { |
| - return parseCopyTable(src, name, movesCopyIDPattern, "an M-C<n>, MV-N<n>, MV-O<n>, HC5-N<n> or RUN-C<n>") |
| + return parseCopyTable(src, name, movesCopyIDPattern, "an M-C<n>, MV-N<n>, MV-O<n>, HC5-N<n>, RUN-C<n> or OR<n>") |
| } |
| // parseCopyTable reads a copy record's tables: the moves record, the run |
| @@ -1374,6 +1380,10 @@ var movesScanFiles = []string{ |
| "internal/stopevidence/reconstruct_other.go", |
| "main.go", |
| "move.go", |
| + // carlos move offline run (plans/2026-11-15-offline-move-run.md). |
| + "move_offline_run.go", |
| + "internal/moves/offlinerun/decide.go", |
| + "internal/moves/offlinerun/run.go", |
| // Region HA stage B: relocation files that import internal/moves (the |
| // shared build, the probe attempts, the landing and wake owners). |
| "internal/host/relocationattempts.go", |
| @@ -1448,6 +1458,12 @@ var movesLocalSinks = map[string]map[string]int{ |
| // Text the console wrote goes through saySpoken instead, which is no |
| // sink here: it takes only serverText (movesServerText). |
| "move.go": {"moveSay": 1}, |
| + // carlos move offline run: moveSay for a whole line, runPiece for part |
| + // of one (a step line is written before its POST and completed with |
| + // the answer). The time and step columns (runWatcher.column), the |
| + // separators (runSep) and the commands under a sentence |
| + // (sayRunCommand) are no sentence. |
| + "move_offline_run.go": {"moveSay": 1, "runPiece": 1}, |
| } |
| var movesCopyTables = map[string][]string{ |
| @@ -1576,6 +1592,12 @@ type movesDiagnosticWrite struct { |
| } |
| var movesDiagnosticWrites = map[string]map[string]movesDiagnosticWrite{ |
| + "move_offline_run.go": { |
| + "offlineRun|runLogTrouble.logReason": { |
| + Why: "the OS error of opening the --log file (err.Error() of os.OpenFile), which OR45 shows as its <system error> by its approved wording; a diagnostic, not copy", |
| + Count: 1, |
| + }, |
| + }, |
| "internal/host/movesoffline.go": { |
| "retire|RetiredPath.Reason": { |
| Why: "the parked report's reason for a path left in place ends in the OS error of the rename (leftCannot or leftNotYet plus err.Error()), a box diagnostic that `carlos move offline status` shows as MV-O58's <reason>; it is not copy", |
diff --git a/docs/parity.md b/docs/parity.md| index d59c23b65..a2c903b9e 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -161,7 +161,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | steering | gap | `steering` | | [wp-instances](#wp-instances) | | |
| | routes | partial | `routes` | `GET /a/{sqid}/apps/{app}/instances`<br>`GET /a/{sqid}/apps/{app}/settings/{section}` | | The console shows host and channel but no environment or replication column. | |
| | restart | partial | `restart` | `POST /a/{sqid}/apps/{app}/restart`<br>`POST /a/{sqid}/apps/{app}/instances/{host}/restart` | | The console has no environment scope and no dry-run list. | |
| -| move | gap | `move`<br>`move status`<br>`move cut`<br>`move abort`<br>`move resolve [--retry]`<br>`move offline stage`<br>`move offline start`<br>`move offline seal`<br>`move offline flip`<br>`move offline open`<br>`move offline finish`<br>`move offline abort`<br>`move offline status` | | [wp-instances](#wp-instances) | Region moves; the instance page shows only that a move is running. | |
| +| move | gap | `move`<br>`move status`<br>`move cut`<br>`move abort`<br>`move resolve [--retry]`<br>`move offline stage`<br>`move offline start`<br>`move offline seal`<br>`move offline flip`<br>`move offline open`<br>`move offline finish`<br>`move offline abort`<br>`move offline status`<br>`move offline run` | | [wp-instances](#wp-instances) | Region moves; the instance page shows only that a move is running. | |
| ## observe |
| @@ -269,7 +269,7 @@ Discussion #734. |
| - `instances-set-assets` (instances), CLI has `instances set-assets` |
| - `instances-set-pages` (instances), CLI has `instances set-pages` |
| - `steering` (instances), CLI has `steering` |
| -- `move` (instances), CLI has `move`, `move status`, `move cut`, `move abort`, `move resolve [--retry]`, `move offline stage`, `move offline start`, `move offline seal`, `move offline flip`, `move offline open`, `move offline finish`, `move offline abort`, `move offline status` |
| +- `move` (instances), CLI has `move`, `move status`, `move cut`, `move abort`, `move resolve [--retry]`, `move offline stage`, `move offline start`, `move offline seal`, `move offline flip`, `move offline open`, `move offline finish`, `move offline abort`, `move offline status`, `move offline run` |
| <a id="wp-settings"></a> |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index e8093f3b2..340896c38 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -3462,6 +3462,7 @@ carlos move offline open --host <host> |
| carlos move offline finish --host <host> |
| carlos move offline abort --host <host> |
| carlos move offline status --host <host> |
| +carlos move offline run --host <host> --to <region> |
| ``` |
| The instance is offline from `start` until `open`. Until `open`, `abort` puts it back where it was with nothing lost. After `open`, moving it back is a new move. |
diff --git a/docs/superpowers/notes/census-proposal-omr-run.md b/docs/superpowers/notes/census-proposal-omr-run.md| new file mode 100644 |
| index 000000000..f962b70a3 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-omr-run.md |
| @@ -0,0 +1,15 @@ |
| +# Census approval: omr-run |
| + |
| +Ruling `census-ruling-omr-run`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `.`, `internal/moves/offlinerun`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `move_offline_run.go:mover.offlineRun`: reads +file:OpenFile; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `da718fcd010b3c1db861196e0bbb9121723a9857ad16c2a15a329983688b8981` → `968faa929b178c571f928f7b3c472360d4e6c60ba0239d771eee520e87ab44e3`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-omr-run.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-10-06-moves-phase1-copy.md b/docs/superpowers/plans/2026-10-06-moves-phase1-copy.md| index 04f149ae5..162a9e184 100644 |
| --- a/docs/superpowers/plans/2026-10-06-moves-phase1-copy.md |
| +++ b/docs/superpowers/plans/2026-10-06-moves-phase1-copy.md |
| @@ -737,3 +737,39 @@ A live link the target box still kept for the host from an earlier time it ran t |
| | MV-O202 | move.go | Nothing moved. The stage of <host> was abandoned, and <host> kept serving in <from>. | approved | |
| | MV-O203 | docs/site/cli.md | `stage` and `start` refuse an offline move when a box in the target region still holds a live link for the instance from an earlier time it ran there, or has more live links than its report can carry. The refusal names the box and says what it found. | approved | |
| | MV-O204 | internal/console/apiinstancemove_offline_facts.go | <box> holds more live links than it can report, so stage and start cannot tell whether one is for <host>. see the offline move runbook | approved | |
| + |
| +## Offline move run (`carlos move offline run`) |
| + |
| +Approved by Luna on 2026-11-15 under Paul's 2026-10-25 delegation (deck `docs/drafts/offline-move-run/copy-review/strings.json`, UX pass in that directory's README; OR02, OR05, OR06, OR21, OR25 and OR29 as Luna changed them). The deck's `%s` and `%d` are written here as `<placeholders>`; the words are the deck's. A step line is `<time> <step> <fact>`: OR11 is written before the POST, then `, ` and OR12, OR13 or OR14 once it answers, and OR15 after `. ` for `start`. The step column (a verb, `waiting`, `check` or `limit`), the separators and the commands printed under OR24, OR27 and OR29 are not sentences and have no rows. OR13's `<console sentence>` is the console's own refusal (server text), or MV-N368 when it gave none. OR45's `<system error>` is the OS's error (movesDiagnosticWrites). |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| OR01 | move_offline_run.go | carlos move offline run --host <host> --to <region> [--resume <move-id>] [--no-finish] [--max-offline <duration>] [--probe-path <path>] [--log <file>] | approved | |
| +| OR02 | move_offline_run.go | run carries the move through each step: it stages the data, takes the instance offline, copies it, starts it in the new region and checks that it answers. If a step fails or takes too long before it opens, it moves the instance back. | approved | |
| +| OR03 | move.go | carry on the move with this id from wherever it stands | approved | |
| +| OR04 | move.go | stop once the instance is served from the new region, before the old region is cleaned up | approved | |
| +| OR05 | move.go | when to move the instance back if it is still offline (default 15m) | approved | |
| +| OR06 | move.go | the path run checks after the instance opens (default /) | approved | |
| +| OR07 | move.go | also write each step to this file | approved | |
| +| OR10 | move_offline_run.go | Move <id>. | approved | |
| +| OR11 | move_offline_run.go | sent | approved | |
| +| OR12 | move_offline_run.go | accepted | approved | |
| +| OR13 | move_offline_run.go | refused: <console sentence> | approved | |
| +| OR14 | move_offline_run.go | no answer, checking where the move stands | approved | |
| +| OR15 | move_offline_run.go | Offline from now. | approved | |
| +| OR16 | move_offline_run.go | <staged> of <total> objects (<staged MB> of <total MB> MB) | approved | |
| +| OR17 | move_offline_run.go | no change for <duration>, woke the boxes | approved | |
| +| OR18 | move_offline_run.go | <url> answered <status> | approved | |
| +| OR19 | move_offline_run.go | <url> did not answer within <duration> | approved | |
| +| OR20 | move_offline_run.go | offline for <duration>, over the limit. Moving it back to <from>. | approved | |
| +| OR21 | move_offline_run.go | The <step> step took over <duration>. Moving it back to <from>. | approved | |
| +| OR22 | move_offline_run.go | Moving it back to <from>. | approved | |
| +| OR23 | move_offline_run.go | Stopped staging after <rounds> rounds: each still copied over 1 MB. <host> keeps serving and nothing went offline. | approved | |
| +| OR24 | move_offline_run.go | <host> is open in <to> but not finished. Check the site, then run: | approved | |
| +| OR25 | move_offline_run.go | <host> now has a different move (<id>). This run sent nothing for that move and stopped. | approved | |
| +| OR26 | move_offline_run.go | <host>'s move is <id>, not <resume id>. Nothing was sent. | approved | |
| +| OR27 | move_offline_run.go | <host> already has a move in flight (<id>). See where it is, then carry it on: | approved | |
| +| OR28 | move_offline_run.go | Moving <host> back to <from>. Press Ctrl-C again to stop watching. | approved | |
| +| OR29 | move_offline_run.go | Stopped watching. The move is still running. To see where it is, run: | approved | |
| +| OR40 | move_offline_run.go | <host> is already served from <to>, so the move is not undone. Stopped watching. | approved | |
| +| OR45 | move_offline_run.go | cannot write the log <path>: <system error> | approved | |
diff --git a/internal/moves/offlinerun/decide.go b/internal/moves/offlinerun/decide.go| index 27897ffa4..e4bcc94b1 100644 |
| --- a/internal/moves/offlinerun/decide.go |
| +++ b/internal/moves/offlinerun/decide.go |
| @@ -215,9 +215,11 @@ type Memory struct { |
| offlineSeen bool // a state from stopping to landed was read |
| offlineSince time.Duration // when the first was |
| - watched int64 // a staged_at this process read unanswered |
| + watched int64 // a staged_at this process watched (read unanswered, or new since its own stage POST) |
| finishedReq int64 // the watched staged_at, once read answered |
| finishedAt time.Duration // when it was first read answered |
| + stageSent bool // a stage POST was decided and no new staged_at read since |
| + lastStaged int64 // the staged_at last read |
| aborting bool // abort was decided; sticky until reverting or open |
| abortReason string // why |
| @@ -330,6 +332,13 @@ func (m Memory) observe(v View, now time.Duration) Memory { |
| m.offlineSeen, m.offlineSince = true, now |
| } |
| if v.State == StateStaging && v.StagedAt != 0 { |
| + // A request new since our own stage POST is ours, and a round that |
| + // already answers it finished after the POST: watched, however fast |
| + // the stager was. |
| + if m.stageSent && v.StagedAt != m.lastStaged { |
| + m.watched, m.stageSent = v.StagedAt, false |
| + } |
| + m.lastStaged = v.StagedAt |
| if !answered(v) { |
| m.watched = v.StagedAt |
| } else if v.StagedAt == m.watched && m.finishedReq != v.StagedAt { |
| @@ -364,6 +373,7 @@ func Decide(v View, p Policy, m Memory, now time.Duration) (Action, Memory) { |
| return Done{Exit: ExitStopped, Reason: ReasonStageNotWritten}, m |
| case m.id == "": |
| m.stagePosts++ |
| + m.stageSent = true |
| return Post{Verb: VerbStage}, m |
| case v.Last != nil && v.Last.ID == m.id: |
| switch v.Last.Outcome { |
| @@ -453,6 +463,7 @@ func (m Memory) staging(v View, p Policy, now time.Duration) (Action, Memory) { |
| return Post{Verb: VerbAbort, Reason: ReasonStageRounds}, m |
| } |
| m.stagePosts++ |
| + m.stageSent = true |
| return Post{Verb: VerbStage}, m |
| } |
diff --git a/internal/moves/offlinerun/decide_test.go b/internal/moves/offlinerun/decide_test.go| index 3dbc275f9..3bfb34a12 100644 |
| --- a/internal/moves/offlinerun/decide_test.go |
| +++ b/internal/moves/offlinerun/decide_test.go |
| @@ -194,6 +194,30 @@ func TestDecideSmallRoundWatched(t *testing.T) { |
| }) |
| } |
| +// TestDecideFastRoundIsWatched: a round that answers our stage POST before |
| +// the next read (a small instance, a stager that woke at once) was still |
| +// watched finish: its staged_at is new since the POST, so it finished after |
| +// it. Without this a fast stager never lets the run start, and the round |
| +// cap aborts a healthy move. |
| +func TestDecideFastRoundIsWatched(t *testing.T) { |
| + p := DefaultPolicy() |
| + play(t, p, NewMemory(""), []step{ |
| + {0, none(nil), Post{Verb: VerbStage}}, |
| + {at(2), withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStart}}, |
| + }) |
| + // A restage answered at once is watched the same way. |
| + play(t, p, NewMemory(tID), []step{ |
| + {0, withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStage}}, |
| + {at(2), withNext(staging(6, true, 10), VerbStart), Post{Verb: VerbStart}}, |
| + }) |
| + // A stage POST that wrote nothing leaves the old request: not watched, |
| + // so it stages again. |
| + play(t, p, NewMemory(tID), []step{ |
| + {0, withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStage}}, |
| + {at(2), withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStage}}, |
| + }) |
| +} |
| + |
| func TestDecideStageRoundsCapped(t *testing.T) { |
| p := DefaultPolicy() |
| steps := []step{{0, none(nil), Post{Verb: VerbStage}}} |
diff --git a/internal/moves/offlinerun/run.go b/internal/moves/offlinerun/run.go| new file mode 100644 |
| index 000000000..c7ed5bd3f |
| --- /dev/null |
| +++ b/internal/moves/offlinerun/run.go |
| @@ -0,0 +1,180 @@ |
| +package offlinerun |
| + |
| +import ( |
| + "context" |
| + "time" |
| +) |
| + |
| +// The loop behind `carlos move offline run` (plan §3): read status, Decide, |
| +// perform at most one action, sleep, again. Step is one tick and Run the |
| +// loop. Neither prints anything: what the operator reads is the Watcher's. |
| + |
| +// DefaultPoll is the gap between ticks. |
| +const DefaultPoll = 2 * time.Second |
| + |
| +// ReasonStoppedWatching ends a run the operator stopped with Ctrl-C (the |
| +// second before open, the first after it). The move itself goes on. |
| +const ReasonStoppedWatching = "stopped-watching" |
| + |
| +// Answer is how a door answered one POST. |
| +type Answer struct { |
| + // Accepted is a 2xx. |
| + Accepted bool |
| + // Refused: the console answered, with something other than a 2xx. It |
| + // is taken at its word (Memory.Refused). With neither flag no answer |
| + // arrived, or none that could be read: the write may or may not have |
| + // happened, and the next status read says which. Neither case is |
| + // ever sent again blindly. |
| + Refused bool |
| + // Sentence is the console's own sentence for a refusal, when the |
| + // Doors can carry it; "" otherwise. |
| + Sentence string |
| +} |
| + |
| +// Doors are the console's offline move doors, as this run reaches them. |
| +// Post and Nudge carry the id of the move the run is bound to ("" before |
| +// it is bound, for the first stage); the door refuses a different move. |
| +type Doors interface { |
| + Status(ctx context.Context) (View, error) |
| + Post(ctx context.Context, verb, id string) Answer |
| + Nudge(ctx context.Context, id string) Answer |
| +} |
| + |
| +// Result is what an action got: the door's Answer for a Post or a Nudge, |
| +// the HTTP status for a Probe (0 when nothing answered). |
| +type Result struct { |
| + Answer |
| + Status int |
| +} |
| + |
| +// Interrupt is what a Ctrl-C did. |
| +type Interrupt int |
| + |
| +const ( |
| + // InterruptAbort is the first Ctrl-C before open: the run aborts the |
| + // move and follows it through to finish. |
| + InterruptAbort Interrupt = iota + 1 |
| + // InterruptStop is the second Ctrl-C before open: the run stops |
| + // watching and the move goes on as it stands. |
| + InterruptStop |
| + // InterruptAfterOpen is a Ctrl-C once the move may be open: nothing |
| + // is undone, the run stops watching. |
| + InterruptAfterOpen |
| +) |
| + |
| +// Watcher sees the run: each view read, each action before it is performed |
| +// and its result after, and each Ctrl-C. |
| +type Watcher interface { |
| + Saw(v View) |
| + Acting(a Action, m Memory) |
| + Acted(a Action, r Result, m Memory) |
| + Interrupted(i Interrupt, m Memory) |
| +} |
| + |
| +// Runner runs one move. Clock is the terminal's monotonic clock; After is |
| +// the poll timer (time.After); both are seams for tests. |
| +type Runner struct { |
| + Doors Doors |
| + Probe func(ctx context.Context) int |
| + Policy Policy |
| + Clock func() time.Duration |
| + After func(d time.Duration) <-chan time.Time |
| + Poll time.Duration |
| + Watch Watcher |
| + |
| + // openSent: an open POST was accepted, or got no answer (it may have |
| + // committed). From then on a Ctrl-C never aborts. |
| + openSent bool |
| + stops int |
| +} |
| + |
| +// Step reads status once, decides, and performs at most one action. done |
| +// is set when the run ends; err when the status could not be read (nothing |
| +// was decided or sent). |
| +func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) { |
| + v, err := r.Doors.Status(ctx) |
| + if err != nil { |
| + return m, nil, err |
| + } |
| + r.Watch.Saw(v) |
| + var a Action |
| + a, m = Decide(v, r.Policy, m, r.Clock()) |
| + switch a := a.(type) { |
| + case Done: |
| + return m, &a, nil |
| + case Post: |
| + r.Watch.Acting(a, m) |
| + ans := r.Doors.Post(ctx, a.Verb, m.Bound()) |
| + if !ans.Accepted && ans.Refused { |
| + m = m.Refused(ans.Sentence) |
| + } |
| + if a.Verb == VerbOpen && (ans.Accepted || !ans.Refused) { |
| + r.openSent = true |
| + } |
| + r.Watch.Acted(a, Result{Answer: ans}, m) |
| + case Nudge: |
| + r.Watch.Acting(a, m) |
| + ans := r.Doors.Nudge(ctx, m.Bound()) |
| + r.Watch.Acted(a, Result{Answer: ans}, m) |
| + case Probe: |
| + r.Watch.Acting(a, m) |
| + code := r.Probe(ctx) |
| + m = m.Probed(code >= 200 && code <= 299) |
| + r.Watch.Acted(a, Result{Status: code}, m) |
| + } |
| + return m, nil, nil |
| +} |
| + |
| +// Run steps until the run ends, sleeping Poll between ticks. A status read |
| +// that fails before any view was read ends it with that error; later ones |
| +// are ridden out (the move is under way, and only a view decides). A |
| +// receive on interrupts is a Ctrl-C. |
| +func (r *Runner) Run(ctx context.Context, m Memory, interrupts <-chan struct{}) (Done, Memory, error) { |
| + read := false |
| + for { |
| + next, done, err := r.Step(ctx, m) |
| + m = next |
| + switch { |
| + case err != nil && !read: |
| + return Done{}, m, err |
| + case err == nil: |
| + read = true |
| + } |
| + if done != nil { |
| + return *done, m, nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return Done{}, m, ctx.Err() |
| + case <-interrupts: |
| + var stop *Done |
| + if m, stop = r.interrupt(m); stop != nil { |
| + return *stop, m, nil |
| + } |
| + case <-r.After(r.Poll): |
| + } |
| + } |
| +} |
| + |
| +// interrupt is one Ctrl-C (plan §7, decision 3). |
| +func (r *Runner) interrupt(m Memory) (Memory, *Done) { |
| + r.stops++ |
| + stop := &Done{Exit: ExitStopped, Reason: ReasonStoppedWatching} |
| + switch { |
| + case m.Opened() || r.openSent: |
| + r.Watch.Interrupted(InterruptAfterOpen, m) |
| + return m, stop |
| + case r.stops == 1: |
| + m = m.Abort(ReasonInterrupted) |
| + r.Watch.Interrupted(InterruptAbort, m) |
| + return m, nil |
| + } |
| + r.Watch.Interrupted(InterruptStop, m) |
| + return m, stop |
| +} |
| + |
| +// Opened says the run read the move open (or finishing): nothing aborts it. |
| +func (m Memory) Opened() bool { return m.opened } |
| + |
| +// QuietFor is how long the view has gone without a change, at now. |
| +func (m Memory) QuietFor(now time.Duration) time.Duration { return now - m.lastChange } |
diff --git a/internal/moves/offlinerun/run_test.go b/internal/moves/offlinerun/run_test.go| new file mode 100644 |
| index 000000000..ad98ff512 |
| --- /dev/null |
| +++ b/internal/moves/offlinerun/run_test.go |
| @@ -0,0 +1,232 @@ |
| +package offlinerun |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// fakeDoors answers each status read with the next view (the last repeats, |
| +// errors where errs says) and each POST with answer(verb). log records |
| +// every call in order. |
| +type fakeDoors struct { |
| + views []View |
| + errs map[int]bool // status read n (0-based) fails |
| + reads int |
| + answer func(verb string) Answer |
| + log []string |
| +} |
| + |
| +func (f *fakeDoors) Status(context.Context) (View, error) { |
| + n := f.reads |
| + f.reads++ |
| + f.log = append(f.log, "status") |
| + if f.errs[n] { |
| + return View{}, errors.New("no answer") |
| + } |
| + if n >= len(f.views) { |
| + n = len(f.views) - 1 |
| + } |
| + return f.views[n], nil |
| +} |
| + |
| +func (f *fakeDoors) Post(_ context.Context, verb, id string) Answer { |
| + f.log = append(f.log, verb+" "+id) |
| + if f.answer == nil { |
| + return Answer{Accepted: true} |
| + } |
| + return f.answer(verb) |
| +} |
| + |
| +func (f *fakeDoors) Nudge(_ context.Context, id string) Answer { |
| + f.log = append(f.log, "nudge "+id) |
| + return Answer{Accepted: true} |
| +} |
| + |
| +// nopWatch records the interrupts it saw. |
| +type nopWatch struct{ interrupts []Interrupt } |
| + |
| +func (*nopWatch) Saw(View) {} |
| +func (*nopWatch) Acting(Action, Memory) {} |
| +func (*nopWatch) Acted(Action, Result, Memory) {} |
| +func (w *nopWatch) Interrupted(i Interrupt, _ Memory) { |
| + w.interrupts = append(w.interrupts, i) |
| +} |
| + |
| +// testRunner is a Runner on fake time: each poll advances the clock by Poll |
| +// and fires at once. |
| +func testRunner(d Doors, probe func() int) (*Runner, *nopWatch) { |
| + var now time.Duration |
| + w := &nopWatch{} |
| + r := &Runner{ |
| + Doors: d, |
| + Probe: func(context.Context) int { return probe() }, |
| + Policy: DefaultPolicy(), |
| + Clock: func() time.Duration { return now }, |
| + After: func(d time.Duration) <-chan time.Time { |
| + now += d |
| + c := make(chan time.Time, 1) |
| + c <- time.Time{} |
| + return c |
| + }, |
| + Poll: DefaultPoll, |
| + Watch: w, |
| + } |
| + return r, w |
| +} |
| + |
| +func TestRunNoAnswerIsFollowedByAStatusRead(t *testing.T) { |
| + sealing := tv(StateSealing) |
| + d := &fakeDoors{ |
| + views: []View{withNext(tv(StateStopping), VerbSeal), sealing, none(&Outcome{ID: tID, Outcome: OutcomeAborted})}, |
| + answer: func(verb string) Answer { |
| + return Answer{} // the seal committed; its reply was lost |
| + }, |
| + } |
| + r, _ := testRunner(d, func() int { return 200 }) |
| + done, _, err := r.Run(context.Background(), NewMemory(tID), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{"status", "seal " + tID, "status", "status"} |
| + if !reflect.DeepEqual(d.log, want) { |
| + t.Fatalf("calls %q, want %q", d.log, want) |
| + } |
| + if done.Exit != ExitAborted { |
| + t.Fatalf("done = %#v", done) |
| + } |
| +} |
| + |
| +func TestRunRefusedFirstStageExits5(t *testing.T) { |
| + d := &fakeDoors{ |
| + views: []View{none(nil)}, |
| + answer: func(string) Answer { return Answer{Refused: true, Sentence: "another move is in flight"} }, |
| + } |
| + r, _ := testRunner(d, func() int { return 200 }) |
| + done, _, err := r.Run(context.Background(), NewMemory(""), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := (Done{Exit: ExitRefused, Reason: "another move is in flight"}); done != want { |
| + t.Fatalf("done = %#v, want %#v", done, want) |
| + } |
| + if want := []string{"status", "stage ", "status"}; !reflect.DeepEqual(d.log, want) { |
| + t.Fatalf("calls %q, want %q", d.log, want) |
| + } |
| +} |
| + |
| +func TestRunStatusErrors(t *testing.T) { |
| + // Before any view: the error ends the run, nothing sent. |
| + d := &fakeDoors{views: []View{none(nil)}, errs: map[int]bool{0: true}} |
| + r, _ := testRunner(d, func() int { return 200 }) |
| + if _, _, err := r.Run(context.Background(), NewMemory(""), nil); err == nil { |
| + t.Fatal("a first status read that failed did not end the run") |
| + } |
| + if len(d.log) != 1 { |
| + t.Fatalf("calls %q", d.log) |
| + } |
| + // After one: ridden out. |
| + d = &fakeDoors{ |
| + views: []View{tv(StateSealing), tv(StateSealing), tv(StateSealing), none(&Outcome{ID: tID, Outcome: OutcomeDone})}, |
| + errs: map[int]bool{1: true, 2: true}, |
| + } |
| + r, _ = testRunner(d, func() int { return 200 }) |
| + done, _, err := r.Run(context.Background(), offline(StateSealing, 0), nil) |
| + if err != nil || done.Exit != ExitDone { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| +} |
| + |
| +func TestRunCtrlC(t *testing.T) { |
| + // The first Ctrl-C before open aborts and follows to finish. |
| + d := &fakeDoors{views: []View{ |
| + tv(StateSealing), |
| + withNext(tv(StateSealed), VerbFlip), |
| + withNext(tv(StateReverting), VerbFinish), |
| + none(&Outcome{ID: tID, Outcome: OutcomeAborted}), |
| + }} |
| + r, w := testRunner(d, func() int { return 200 }) |
| + ints := make(chan struct{}, 1) |
| + ints <- struct{}{} |
| + // After lets the interrupt win the first select: it never fires. |
| + after := r.After |
| + first := true |
| + r.After = func(dd time.Duration) <-chan time.Time { |
| + if first { |
| + first = false |
| + return nil |
| + } |
| + return after(dd) |
| + } |
| + done, _, err := r.Run(context.Background(), offline(StateSealing, 0), ints) |
| + if err != nil || done.Exit != ExitAborted { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,status,abort "+tID+",status,finish "+tID+",status" { |
| + t.Fatalf("calls %s", got) |
| + } |
| + if !reflect.DeepEqual(w.interrupts, []Interrupt{InterruptAbort}) { |
| + t.Fatalf("interrupts %v", w.interrupts) |
| + } |
| + |
| + // The second stops watching: exit 4, nothing more sent. |
| + d = &fakeDoors{views: []View{tv(StateSealing)}, answer: func(string) Answer { return Answer{} }} |
| + r, w = testRunner(d, func() int { return 200 }) |
| + ints = make(chan struct{}, 2) |
| + ints <- struct{}{} |
| + ints <- struct{}{} |
| + r.After = func(time.Duration) <-chan time.Time { return nil } |
| + done, _, _ = r.Run(context.Background(), offline(StateSealing, 0), ints) |
| + if done != (Done{Exit: ExitStopped, Reason: ReasonStoppedWatching}) { |
| + t.Fatalf("done %#v", done) |
| + } |
| + if !reflect.DeepEqual(w.interrupts, []Interrupt{InterruptAbort, InterruptStop}) { |
| + t.Fatalf("interrupts %v", w.interrupts) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,status,abort "+tID { |
| + t.Fatalf("calls %s", got) |
| + } |
| + |
| + // Once open was sent, a Ctrl-C undoes nothing. |
| + d = &fakeDoors{views: []View{withNext(tv(StateLanded), VerbOpen), tv(StateLanded)}, answer: func(string) Answer { return Answer{} }} |
| + r, w = testRunner(d, func() int { return 200 }) |
| + ints = make(chan struct{}, 1) |
| + calls := 0 |
| + r.After = func(time.Duration) <-chan time.Time { |
| + calls++ |
| + if calls == 1 { |
| + ints <- struct{}{} |
| + return nil |
| + } |
| + return nil |
| + } |
| + done, _, _ = r.Run(context.Background(), offline(StateLanded, 0), ints) |
| + if done != (Done{Exit: ExitStopped, Reason: ReasonStoppedWatching}) { |
| + t.Fatalf("done %#v", done) |
| + } |
| + if !reflect.DeepEqual(w.interrupts, []Interrupt{InterruptAfterOpen}) { |
| + t.Fatalf("interrupts %v", w.interrupts) |
| + } |
| + for _, c := range d.log { |
| + if strings.HasPrefix(c, "abort") { |
| + t.Fatalf("aborted after open: %q", d.log) |
| + } |
| + } |
| +} |
| + |
| +func TestRunProbeThenFinish(t *testing.T) { |
| + open := withNext(tv(StateOpen), VerbFinish) |
| + d := &fakeDoors{views: []View{open, open, open, none(&Outcome{ID: tID, Outcome: OutcomeDone})}} |
| + codes := []int{0, 200} |
| + r, _ := testRunner(d, func() int { c := codes[0]; codes = codes[1:]; return c }) |
| + done, _, err := r.Run(context.Background(), offline(StateLanded, 0), nil) |
| + if err != nil || done.Exit != ExitDone { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,status,status,finish "+tID+",status" { |
| + t.Fatalf("calls %s", got) |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index bbe115138..f8937ab8b 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -223,3 +223,4 @@ plan14-root-reads-platform-mail-submission.tsv edd68225d4f61e5953ecaa710fe07e8c0 |
| plan14-root-reads-drain-quiesce-1062.tsv 66404a2fb26ea541e99d9c3d3bd87cb3f2a346eda95cdb7d7838cab2fcd844f5 |
| plan14-root-reads-flat-plans.tsv 66404a2fb26ea541e99d9c3d3bd87cb3f2a346eda95cdb7d7838cab2fcd844f5 |
| plan14-root-reads-sr-followups.tsv da718fcd010b3c1db861196e0bbb9121723a9857ad16c2a15a329983688b8981 |
| +plan14-root-reads-omr-run.tsv 968faa929b178c571f928f7b3c472360d4e6c60ba0239d771eee520e87ab44e3 |
diff --git a/internal/provision/testdata/plan14-root-reads-omr-run.tsv b/internal/provision/testdata/plan14-root-reads-omr-run.tsv| new file mode 100644 |
| index 000000000..bb533235c |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-omr-run.tsv |
| @@ -0,0 +1,7 @@ |
| +# Census overlay omr-run, written by census-propose (#369). census-ruling-omr-run, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-omr-run.md. |
| +# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 96caba3ca7e3572ea76608ad566ce3ffc57f45eacdc8434a1e3292968c852e37 move_offline_run.go mover.offlineRun legacy accepted-legacy accepted-legacy;rev3=census-ruling-omr-run;basis=new: carlos move offline run (offline move run plan, Task 5). Opens the operator's own --log path to append the run's output (os.OpenFile, O_APPEND|O_CREATE|O_WRONLY, 0600); reads nothing from it. The verb refuses root (moveMain, L25) before it gets here, so this is never a root read. file:OpenFile@112 685caad00fcc6041ece9f4658a2b2356096247ead6537b6018bb09c565dafc8d |
| +move_offline_run.go mover.offlineRun legacy accepted-legacy accepted-legacy;rev3=census-ruling-omr-run;basis=new: carlos move offline run (offline move run plan, Task 5). Opens the operator's own --log path to append the run's output (os.OpenFile, O_APPEND|O_CREATE|O_WRONLY, 0600); reads nothing from it. The verb refuses root (moveMain, L25) before it gets here, so this is never a root read. file:OpenFile@112 685caad00fcc6041ece9f4658a2b2356096247ead6537b6018bb09c565dafc8d |
| +@coverage . e189daf25cf6553e3e6c3299b070bd282e006df8f9bcc7d11fd4c535f1cd84f8 |
| +@coverage internal/moves/offlinerun d7126c127296a9490621fd5119ca3bb4951f9c295266b2bacfe7d9d60f10b4d8 |
diff --git a/move.go b/move.go| index a897a2d3f..d5a5fc043 100644 |
| --- a/move.go |
| +++ b/move.go |
| @@ -119,7 +119,7 @@ func moveCommand() *clireg.Node { |
| }) |
| } |
| var offline []*clireg.Node |
| - for _, name := range []string{"stage", "start", "seal", "flip", "open", "finish", "abort", "status"} { |
| + for _, name := range []string{"stage", "start", "seal", "flip", "open", "finish", "abort", "status", "run"} { |
| offline = append(offline, verb(name, "offline")) |
| } |
| return &clireg.Node{ |
| @@ -159,17 +159,29 @@ type moveDeps struct { |
| // operator's own read-only EC2 seam (awsinv.NewEC2Reader). |
| stdin io.Reader |
| ec2 func(ctx context.Context, region string) (awsinv.ExactEC2API, error) |
| + // offline run's seams (move_offline_run.go), each its real one when |
| + // nil: the wall clock (time.Now, also the monotonic one), the poll |
| + // timer (time.After), the probe (an HTTPS GET) and the Ctrl-C source. |
| + now func() time.Time |
| + after func(time.Duration) <-chan time.Time |
| + probe func(ctx context.Context, url string) int |
| + interrupts func() (<-chan struct{}, func()) |
| } |
| type moveArgs struct { |
| verb string // request | status | cut | abort | resolve | offline |
| - offline string // the offline verb: stage | start | seal | flip | open | finish | abort | status |
| + offline string // the offline verb: stage | start | seal | flip | open | finish | abort | status | run |
| host, to, app string |
| account, accountID string |
| console string |
| manualCut, noWait, wait bool |
| retry bool |
| lostBox string // the box to declare lost (Task 1b) |
| + // offline run's own (move_offline_run.go): --resume, --no-finish, |
| + // --max-offline (0 is the default), --probe-path ("" is /) and --log. |
| + resume, probePath, logPath string |
| + noFinish bool |
| + maxOffline time.Duration |
| } |
| // parseMoveArgs reads `carlos move [status|cut|abort|resolve] <flags>`. Each |
| @@ -213,15 +225,27 @@ func parseMoveArgs(args []string, out io.Writer) (moveArgs, error) { |
| case "cut", "abort": |
| fs.BoolVar(&a.noWait, "no-wait", false, "return once the console has accepted it") |
| case "offline": |
| - if a.offline == "start" || a.offline == "stage" { |
| + if a.offline == "start" || a.offline == "stage" || a.offline == "run" { |
| fs.StringVar(&a.to, "to", "", "the region to move the instance to") |
| } |
| + if a.offline == "run" { |
| + // The defaults are in the usage strings (OR05, OR06), so the |
| + // flags' own are zero and the flag package prints none. |
| + fs.StringVar(&a.resume, "resume", "", "carry on the move with this id from wherever it stands") |
| + fs.BoolVar(&a.noFinish, "no-finish", false, "stop once the instance is served from the new region, before the old region is cleaned up") |
| + fs.DurationVar(&a.maxOffline, "max-offline", 0, "when to move the instance back if it is still offline (default 15m)") |
| + fs.StringVar(&a.probePath, "probe-path", "", "the path run checks after the instance opens (default /)") |
| + fs.StringVar(&a.logPath, "log", "", "also write each step to this file") |
| + } |
| case "resolve": |
| fs.BoolVar(&a.retry, "retry", false, "retry a stuck move once its cause is fixed") |
| fs.StringVar(&a.lostBox, "declare-lost", "", "declare the move's target box lost, once AWS shows it stopped or terminated") |
| fs.BoolVar(&a.noWait, "no-wait", false, "return once the console has accepted it") |
| } |
| if err := fs.Parse(args); err != nil { |
| + if a.offline == "run" { |
| + sayRunUsage(out) |
| + } |
| moveFlagHelp(out, fs, &parsed) |
| return moveArgs{}, err |
| } |
| @@ -233,7 +257,7 @@ func parseMoveArgs(args []string, out io.Writer) (moveArgs, error) { |
| case a.host == "": |
| moveSay(out, moveNeedsHost) |
| return moveArgs{}, errors.New("no --host") |
| - case (a.verb == "request" || a.offline == "start" || a.offline == "stage") && a.to == "": |
| + case (a.verb == "request" || a.offline == "start" || a.offline == "stage" || (a.offline == "run" && a.resume == "")) && a.to == "": |
| moveSay(out, moveNeedsTo) |
| return moveArgs{}, errors.New("no --to") |
| case a.verb == "resolve" && a.retry && a.lostBox != "": |
| @@ -295,6 +319,9 @@ func moveMain(ctx context.Context, args []string, out io.Writer, d moveDeps) int |
| // It has no Phase 1 marker to check: its doors refuse for themselves. |
| if a.verb == "offline" { |
| m.path += "/offline" |
| + if a.offline == "run" { |
| + return m.offlineRun(ctx, a, d) |
| + } |
| return m.offline(ctx, a) |
| } |
| @@ -1041,7 +1068,7 @@ func (m *mover) refusal(r moveReply) int { |
| // or the move waits for the operator, 5 the console refused, 1 an error. |
| // Refusals are the console's own sentences (serverText); the CLI invents none. |
| -// moveOfflineVerbs are the eight verbs after `carlos move offline`: the |
| +// moveOfflineVerbs are the nine verbs after `carlos move offline`: the |
| // children of moveCommand's offline node. |
| func moveOfflineVerbs() []string { |
| var out []string |
diff --git a/move_offline_run.go b/move_offline_run.go| new file mode 100644 |
| index 000000000..51bf8d87f |
| --- /dev/null |
| +++ b/move_offline_run.go |
| @@ -0,0 +1,532 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "os" |
| + "os/signal" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/moves" |
| + "github.com/carlosframework/platform/internal/moves/offlinerun" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// `carlos move offline run` (plan 2026-11-15-offline-move-run, Task 5): |
| +// one offline move carried through from the operator's terminal. It is a |
| +// loop over the same doors the hand verbs post (offlinerun.Runner): read |
| +// status, decide, do at most one thing, sleep 2 s. Before open any failure, |
| +// limit or first Ctrl-C aborts and follows the move back through finish; |
| +// after open nothing is undone. The only state is the console's record and |
| +// this process's memory, so a dead terminal is picked up with status and |
| +// --resume. |
| +// |
| +// Output (the UX pass in docs/drafts/offline-move-run): one line per |
| +// action, `<HH:MM:SSZ> <step> <fact>`, written before the POST goes out |
| +// and completed with its answer; the console's waiting sentence, indented, |
| +// when it changes; --log appends the same bytes as they are written. The |
| +// copy is the OR rows of the moves copy record. Sentences go through |
| +// moveSay (a whole line) or runPiece (part of one); the console's own text |
| +// through saySpoken. The time and step columns (runWatcher.column), the |
| +// separators between pieces (runSep) and the commands printed under a |
| +// sentence (sayRunCommand) are not sentences. |
| + |
| +// runLogTrouble is why --log could not be opened: the OS's own error, |
| +// shown as OR45's <system error> (a diagnostic, not copy). |
| +type runLogTrouble struct { |
| + path string |
| + logReason string |
| +} |
| + |
| +// runPiece says part of a line, with no newline: a copy gate sink, like |
| +// moveSay. |
| +func runPiece(out io.Writer, piece string) { |
| + fmt.Fprint(out, piece) |
| +} |
| + |
| +// runSep writes the punctuation between two pieces of a line. |
| +func runSep(out io.Writer, sep string) { |
| + fmt.Fprint(out, sep) |
| +} |
| + |
| +// sayRunCommand prints a command under the sentence that names it, |
| +// indented two spaces. |
| +func sayRunCommand(out io.Writer, verb, host string, extra ...string) { |
| + fmt.Fprintf(out, " carlos move offline %s --host %s%s\n", verb, host, strings.Join(extra, "")) |
| +} |
| + |
| +// sayRunUsage is OR01 and OR02, before run's flags in its help. |
| +func sayRunUsage(out io.Writer) { |
| + moveSay(out, "carlos move offline run --host <host> --to <region> [--resume <move-id>] [--no-finish] [--max-offline <duration>] [--probe-path <path>] [--log <file>]") |
| + moveSay(out, "run carries the move through each step: it stages the data, takes the instance offline, copies it, starts it in the new region and checks that it answers. If a step fails or takes too long before it opens, it moves the instance back.") |
| +} |
| + |
| +// runDuration is a duration as the run's lines say it: 30 s, 2 min, |
| +// 3 min 12 s. |
| +func runDuration(d time.Duration) string { |
| + s := int(d.Round(time.Second) / time.Second) |
| + switch { |
| + case s < 60: |
| + return fmt.Sprintf("%d s", s) |
| + case s%60 == 0: |
| + return fmt.Sprintf("%d min", s/60) |
| + } |
| + return fmt.Sprintf("%d min %d s", s/60, s%60) |
| +} |
| + |
| +// runClock is a UTC time of day as the run's lines say it: 06:12:03Z. |
| +func runClock(t time.Time) string { return t.UTC().Format("15:04:05Z") } |
| + |
| +// offlineRun carries one `carlos move offline run`. |
| +func (m *mover) offlineRun(ctx context.Context, a moveArgs, d moveDeps) int { |
| + if a.logPath != "" { |
| + f, err := os.OpenFile(a.logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) |
| + if err != nil { |
| + t := runLogTrouble{path: a.logPath, logReason: err.Error()} |
| + moveSay(m.out, fmt.Sprintf("cannot write the log %s: %v", t.path, t.logReason)) |
| + return moveExitError |
| + } |
| + defer f.Close() |
| + // Every write goes to the file as it is made: os.File is |
| + // unbuffered, and the file is opened to append. |
| + m.out = io.MultiWriter(m.out, f) |
| + } |
| + now, after, probe, interrupts := d.now, d.after, d.probe, d.interrupts |
| + if now == nil { |
| + now = time.Now |
| + } |
| + if after == nil { |
| + after = time.After |
| + } |
| + if probe == nil { |
| + probe = probeOnce |
| + } |
| + if interrupts == nil { |
| + interrupts = ctrlC |
| + } |
| + policy := offlinerun.DefaultPolicy() |
| + if a.maxOffline > 0 { |
| + policy.Offline = a.maxOffline |
| + } |
| + policy.NoFinish = a.noFinish |
| + path := a.probePath |
| + if !strings.HasPrefix(path, "/") { |
| + path = "/" + path |
| + } |
| + |
| + w := &offlineRun{m: m, said: map[string]bool{}} |
| + doors := &runDoors{w: w, region: a.to, code: -1} |
| + start := now() |
| + watch := &runWatcher{w: w, doors: doors, now: now, policy: policy, |
| + resume: a.resume, url: "https://" + m.host + path} |
| + watch.clock = func() time.Duration { return now().Sub(start) } |
| + r := &offlinerun.Runner{ |
| + Doors: doors, |
| + Probe: func(ctx context.Context) int { return probe(ctx, watch.url) }, |
| + Policy: policy, |
| + Clock: watch.clock, |
| + After: after, |
| + Poll: offlinerun.DefaultPoll, |
| + Watch: watch, |
| + } |
| + ints, stop := interrupts() |
| + defer stop() |
| + done, _, err := r.Run(ctx, offlinerun.NewMemory(a.resume), ints) |
| + if err != nil { |
| + if doors.code >= 0 { |
| + return doors.code // the first status read said why |
| + } |
| + moveSay(m.out, moveStopped) |
| + return moveExitError |
| + } |
| + return watch.end(done) |
| +} |
| + |
| +// ctrlC is the real Ctrl-C source: each SIGINT is one receive. A hangup |
| +// (the SSH session dropped) is ignored, so the move goes on (unix only). |
| +func ctrlC() (<-chan struct{}, func()) { |
| + ignoreHangup() |
| + sig := make(chan os.Signal, 2) |
| + signal.Notify(sig, os.Interrupt) |
| + out := make(chan struct{}, 2) |
| + quit := make(chan struct{}) |
| + go func() { |
| + for { |
| + select { |
| + case <-sig: |
| + select { |
| + case out <- struct{}{}: |
| + default: |
| + } |
| + case <-quit: |
| + return |
| + } |
| + } |
| + }() |
| + return out, func() { |
| + signal.Stop(sig) |
| + close(quit) |
| + } |
| +} |
| + |
| +// probeOnce GETs url once and answers its status, 0 when nothing answered. |
| +func probeOnce(ctx context.Context, url string) int { |
| + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| + if err != nil { |
| + return 0 |
| + } |
| + res, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + return 0 |
| + } |
| + defer res.Body.Close() |
| + _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<16)) |
| + return res.StatusCode |
| +} |
| + |
| +// errRunStatus is a status read that got no view. |
| +var errRunStatus = errors.New("no status view") |
| + |
| +// runDoors are the offline doors over HTTP, for offlinerun.Runner. They |
| +// keep the full view last read (the run's lines need more of it than |
| +// Decide does) and the last POST's reply (its refusal is server text, |
| +// said by saySpoken; Answer.Sentence stays empty). |
| +type runDoors struct { |
| + w *offlineRun |
| + region string // the region stage and start are sent: --to, then the bound move's |
| + seen bool // a status view was read |
| + code int // the exit code the first status read ended with, -1 for none |
| + last offlineReply // the latest status view |
| + reply moveReply // the latest POST's reply |
| +} |
| + |
| +func (d *runDoors) Status(ctx context.Context) (offlinerun.View, error) { |
| + var r moveReply |
| + if !d.seen { |
| + // The first read rides out a rate limit and a few failures, and |
| + // says why it gave up (the hand verbs' getReply). |
| + var code int |
| + if r, code = d.w.m.getReply(ctx, d.w.m.path); code >= 0 { |
| + d.code = code |
| + return offlinerun.View{}, errRunStatus |
| + } |
| + } else { |
| + // Later ones are ridden out by the loop, silently: the move is |
| + // under way and only a view decides anything. |
| + if r = d.w.m.roundTrip(ctx, http.MethodGet, d.w.m.path, nil); r.failed || r.moved != "" || r.status != http.StatusOK { |
| + return offlinerun.View{}, errRunStatus |
| + } |
| + } |
| + var full offlineView |
| + var v offlinerun.View |
| + if json.Unmarshal(r.body, &full) != nil || json.Unmarshal(r.body, &v) != nil { |
| + if !d.seen { |
| + moveSay(d.w.m.out, moveUnreadable) |
| + d.code = moveExitError |
| + } |
| + return offlinerun.View{}, errRunStatus |
| + } |
| + d.seen = true |
| + d.w.learn(full) |
| + d.last = offlineReply{v: full, waiting: r.answer.waiting, hasWaiting: r.answer.hasWaiting} |
| + return v, nil |
| +} |
| + |
| +// body is a door's request: the move's id once bound, and the region for |
| +// stage and start (the bound move's own, once a view of it named one). |
| +func (d *runDoors) body(verb, id string) map[string]string { |
| + b := map[string]string{} |
| + if id != "" { |
| + b["id"] = id |
| + } |
| + if verb == offlinerun.VerbStage || verb == offlinerun.VerbStart { |
| + region := d.region |
| + if v := d.last.v; id != "" && v.ID == id && v.To != "" { |
| + region = v.To |
| + } |
| + b["region"] = region |
| + } |
| + return b |
| +} |
| + |
| +func (d *runDoors) Post(ctx context.Context, verb, id string) offlinerun.Answer { |
| + tail := "/" + verb |
| + if verb == offlinerun.VerbStart { |
| + tail = "" // start is the offline door itself |
| + } |
| + return d.answer(d.w.m.send(ctx, http.MethodPost, tail, d.body(verb, id))) |
| +} |
| + |
| +func (d *runDoors) Nudge(ctx context.Context, id string) offlinerun.Answer { |
| + return d.answer(d.w.m.send(ctx, http.MethodPost, "/nudge", d.body("nudge", id))) |
| +} |
| + |
| +// answer reads a POST's reply. A 2xx is accepted (and its view teaches the |
| +// move's id and regions); a reply with the console's sentence, or a 4xx, is |
| +// a refusal; anything else (no reply, a redirect, an unreadable body, a 5xx |
| +// with no sentence) says nothing about the write, and the next status read |
| +// decides. |
| +func (d *runDoors) answer(r moveReply) offlinerun.Answer { |
| + d.reply = r |
| + switch { |
| + case r.failed || r.moved != "": |
| + return offlinerun.Answer{} |
| + case r.status >= 200 && r.status <= 299: |
| + var v offlineView |
| + if json.Unmarshal(r.body, &v) == nil { |
| + d.w.learn(v) |
| + } |
| + return offlinerun.Answer{Accepted: true} |
| + case r.refused, r.status >= 400 && r.status <= 499: |
| + return offlinerun.Answer{Refused: true} |
| + } |
| + return offlinerun.Answer{} |
| +} |
| + |
| +// runWatcher prints the run (offlinerun.Watcher). |
| +type runWatcher struct { |
| + w *offlineRun |
| + doors *runDoors |
| + now func() time.Time |
| + clock func() time.Duration |
| + policy offlinerun.Policy |
| + resume string |
| + url string // the probe's |
| + |
| + posted bool // a POST went out |
| + id string // the move this run carries, once the header named it |
| + stageSaid int64 // the staged_at whose round was said |
| + abortSaid bool // why the run aborts was said |
| +} |
| + |
| +func (rw *runWatcher) out() io.Writer { return rw.w.m.out } |
| + |
| +// column starts a step line: the time and the step. |
| +func (rw *runWatcher) column(step string) { |
| + fmt.Fprintf(rw.out(), "%s %-7s ", runClock(rw.now()), step) |
| +} |
| + |
| +// sayHeader is M-C1 and OR10, once, when a view first names the move this |
| +// run is carrying: the one it staged, or --resume's. |
| +func (rw *runWatcher) sayHeader(v offlineView) { |
| + if rw.id != "" || v.ID == "" || (rw.resume != "" && v.ID != rw.resume) || (rw.resume == "" && !rw.posted) { |
| + return |
| + } |
| + rw.id = v.ID |
| + runPiece(rw.out(), moves.MoveStartingLine(rw.w.m.host, v.fromPlace(), v.toPlace())) |
| + runSep(rw.out(), " ") |
| + moveSay(rw.out(), fmt.Sprintf("Move %s.", v.ID)) |
| +} |
| + |
| +func (rw *runWatcher) Saw(offlinerun.View) { |
| + r := rw.doors.last |
| + v := r.v |
| + rw.sayHeader(v) |
| + if v.ID == "" || v.ID != rw.id { |
| + return // another move's view, or none: Decide says what it means |
| + } |
| + if r.hasWaiting && r.waiting != rw.w.lastWaiting { |
| + runSep(rw.out(), " ") |
| + saySpoken(rw.out(), r.waiting) |
| + rw.w.lastWaiting = r.waiting |
| + } |
| + if c := v.Copying; v.State == provision.OfflineStaging && c != nil && c.Answered != 0 && c.Answered == v.StagedAt && |
| + c.Answered != rw.stageSaid && c.Phase != moves.OfflinePhaseFailed { |
| + rw.stageSaid = c.Answered |
| + rw.column(offlinerun.VerbStage) |
| + moveSay(rw.out(), fmt.Sprintf("%d of %d objects (%s of %s MB)", c.Done, c.Total, megabytes(c.DoneBytes), megabytes(c.TotalBytes))) |
| + } |
| +} |
| + |
| +// stepOver is the step a step budget belongs to, as OR21 names it, and |
| +// the budget. |
| +func stepOver(reason string, p offlinerun.Policy) (string, time.Duration, bool) { |
| + switch reason { |
| + case offlinerun.ReasonBudgetStop: |
| + return offlinerun.VerbStart, p.Stop, true |
| + case offlinerun.ReasonBudgetSeal: |
| + return offlinerun.VerbSeal, p.Seal, true |
| + case offlinerun.ReasonBudgetLanding: |
| + return offlinerun.VerbFlip, p.Landing, true |
| + case offlinerun.ReasonBudgetOpenCheck: |
| + return offlinerun.VerbOpen, p.OpenCheck, true |
| + } |
| + return "", 0, false |
| +} |
| + |
| +// sayWhy says, once, why the run moves the instance back. |
| +func (rw *runWatcher) sayWhy(reason string) { |
| + if rw.abortSaid { |
| + return |
| + } |
| + rw.abortSaid = true |
| + v, host := rw.doors.last.v, rw.w.m.host |
| + from := v.fromPlace() |
| + p := rw.policy |
| + switch reason { |
| + case offlinerun.ReasonInterrupted: |
| + // OR28 was said at the Ctrl-C. |
| + case offlinerun.ReasonFailed: |
| + if !rw.w.sayFailure(v) { |
| + rw.w.sayStaged(v) // the staging round failed (MV-O185) |
| + } |
| + rw.column(offlinerun.VerbAbort) |
| + moveSay(rw.out(), fmt.Sprintf("Moving it back to %s.", from)) |
| + case offlinerun.ReasonStageRounds: |
| + rw.column("limit") |
| + moveSay(rw.out(), fmt.Sprintf("Stopped staging after %d rounds: each still copied over 1 MB. %s keeps serving and nothing went offline.", p.MaxStageRounds, host)) |
| + case offlinerun.ReasonBudgetOffline: |
| + rw.column("limit") |
| + moveSay(rw.out(), fmt.Sprintf("offline for %s, over the limit. Moving it back to %s.", runDuration(p.Offline), from)) |
| + default: |
| + step, limit, ok := stepOver(reason, p) |
| + if !ok { |
| + return |
| + } |
| + rw.column("limit") |
| + moveSay(rw.out(), fmt.Sprintf("The %s step took over %s. Moving it back to %s.", step, runDuration(limit), from)) |
| + } |
| +} |
| + |
| +func (rw *runWatcher) Acting(a offlinerun.Action, _ offlinerun.Memory) { |
| + p, ok := a.(offlinerun.Post) |
| + if !ok { |
| + return |
| + } |
| + if p.Verb == offlinerun.VerbAbort && p.Reason != "" { |
| + rw.sayWhy(p.Reason) |
| + } |
| + rw.posted = true |
| + rw.column(p.Verb) |
| + runPiece(rw.out(), "sent") |
| +} |
| + |
| +// sayAnswer completes a step line with how the door answered. |
| +func (rw *runWatcher) sayAnswer(verb string, ans offlinerun.Answer) { |
| + out := rw.out() |
| + runSep(out, ", ") |
| + r := rw.doors.reply |
| + switch { |
| + case ans.Accepted: |
| + runPiece(out, "accepted") |
| + if verb == offlinerun.VerbStart { |
| + runSep(out, ". ") |
| + runPiece(out, "Offline from now.") |
| + } |
| + runSep(out, "\n") |
| + case ans.Refused && r.refused: |
| + runPiece(out, "refused: ") |
| + saySpoken(out, r.refusal) |
| + case ans.Refused: |
| + runPiece(out, "refused: ") |
| + moveSay(out, fmt.Sprintf("The console answered %d and gave no reason.", r.status)) |
| + default: |
| + moveSay(out, "no answer, checking where the move stands") |
| + } |
| +} |
| + |
| +func (rw *runWatcher) Acted(a offlinerun.Action, res offlinerun.Result, m offlinerun.Memory) { |
| + switch a := a.(type) { |
| + case offlinerun.Post: |
| + rw.sayAnswer(a.Verb, res.Answer) |
| + rw.sayHeader(rw.lastPostView()) |
| + case offlinerun.Nudge: |
| + rw.column("waiting") |
| + if res.Accepted { |
| + moveSay(rw.out(), fmt.Sprintf("no change for %s, woke the boxes", runDuration(m.QuietFor(rw.clock())))) |
| + return |
| + } |
| + runPiece(rw.out(), "sent") |
| + rw.sayAnswer("nudge", res.Answer) |
| + case offlinerun.Probe: |
| + if res.Status >= 200 && res.Status <= 299 { |
| + rw.column("check") |
| + moveSay(rw.out(), fmt.Sprintf("%s answered %d", rw.url, res.Status)) |
| + } |
| + } |
| +} |
| + |
| +// lastPostView is the view the last accepted POST answered with. |
| +func (rw *runWatcher) lastPostView() offlineView { |
| + var v offlineView |
| + if r := rw.doors.reply; !r.failed && r.status >= 200 && r.status <= 299 { |
| + _ = json.Unmarshal(r.body, &v) |
| + } |
| + return v |
| +} |
| + |
| +func (rw *runWatcher) Interrupted(i offlinerun.Interrupt, _ offlinerun.Memory) { |
| + host, v := rw.w.m.host, rw.doors.last.v |
| + switch i { |
| + case offlinerun.InterruptAbort: |
| + moveSay(rw.out(), fmt.Sprintf("Moving %s back to %s. Press Ctrl-C again to stop watching.", host, rw.from(v))) |
| + case offlinerun.InterruptStop: |
| + moveSay(rw.out(), "Stopped watching. The move is still running. To see where it is, run:") |
| + sayRunCommand(rw.out(), "status", host) |
| + case offlinerun.InterruptAfterOpen: |
| + moveSay(rw.out(), fmt.Sprintf("%s is already served from %s, so the move is not undone. Stopped watching.", host, rw.to(v))) |
| + } |
| +} |
| + |
| +// from and to are the move's regions as a line names them: the last view's, |
| +// else what the run learnt. |
| +func (rw *runWatcher) from(v offlineView) string { |
| + if p := v.fromPlace(); p != "" { |
| + return p |
| + } |
| + return rw.w.from |
| +} |
| + |
| +func (rw *runWatcher) to(v offlineView) string { |
| + if p := v.toPlace(); p != "" { |
| + return p |
| + } |
| + return rw.w.to |
| +} |
| + |
| +// end says how the run ended and answers its exit code. |
| +func (rw *runWatcher) end(d offlinerun.Done) int { |
| + host, r := rw.w.m.host, rw.doors.last |
| + v := r.v |
| + switch d.Reason { |
| + case offlinerun.ReasonDone, offlinerun.ReasonAborted: |
| + rw.w.ended(v) |
| + case offlinerun.ReasonOpenNoFinish: |
| + rw.w.sayServed(v) |
| + case offlinerun.ReasonOtherMove: |
| + if !rw.posted && rw.resume != "" { |
| + moveSay(rw.out(), fmt.Sprintf("%s's move is %s, not %s. Nothing was sent.", host, v.ID, rw.resume)) |
| + } else { |
| + moveSay(rw.out(), fmt.Sprintf("%s now has a different move (%s). This run sent nothing for that move and stopped.", host, v.ID)) |
| + } |
| + case offlinerun.ReasonHostHasMove: |
| + moveSay(rw.out(), fmt.Sprintf("%s already has a move in flight (%s). See where it is, then carry it on:", host, v.ID)) |
| + sayRunCommand(rw.out(), "status", host) |
| + sayRunCommand(rw.out(), "run", host, " --resume ", v.ID) |
| + case offlinerun.ReasonStageNotWritten: |
| + moveSay(rw.out(), fmt.Sprintf("No move is in flight for %s.", host)) |
| + case offlinerun.ReasonMoveGone: |
| + if rw.posted { |
| + moveSay(rw.out(), moveNotRecorded) |
| + } else { |
| + moveSay(rw.out(), fmt.Sprintf("No move is in flight for %s.", host)) |
| + } |
| + case offlinerun.ReasonProbeFailed: |
| + rw.column("check") |
| + moveSay(rw.out(), fmt.Sprintf("%s did not answer within %s", rw.url, runDuration(rw.policy.Probe))) |
| + moveSay(rw.out(), fmt.Sprintf("%s is open in %s but not finished. Check the site, then run:", host, rw.to(v))) |
| + sayRunCommand(rw.out(), "finish", host) |
| + case offlinerun.ReasonUnexpectedState: |
| + rw.w.headline(r) |
| + case offlinerun.ReasonStoppedWatching: |
| + // said at the Ctrl-C |
| + } |
| + return d.Exit |
| +} |
diff --git a/move_offline_run_other.go b/move_offline_run_other.go| new file mode 100644 |
| index 000000000..f292034b5 |
| --- /dev/null |
| +++ b/move_offline_run_other.go |
| @@ -0,0 +1,7 @@ |
| +//go:build !linux && !darwin |
| + |
| +package main |
| + |
| +// ignoreHangup does nothing here: there is no SIGHUP to ignore (unverified |
| +// whether a closed console window stops the process on Windows). |
| +func ignoreHangup() {} |
diff --git a/move_offline_run_test.go b/move_offline_run_test.go| new file mode 100644 |
| index 000000000..0c34b6592 |
| --- /dev/null |
| +++ b/move_offline_run_test.go |
| @@ -0,0 +1,619 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/awsinv" |
| +) |
| + |
| +// offlineSim is a model of one offline move behind the doors, for |
| +// `carlos move offline run`: the console's record and what the boxes report, |
| +// moved on by the doors' POSTs and by the status reads (each read is one |
| +// tick of the boxes). Each state's box work takes two reads, and the door |
| +// that follows it is ready after them. |
| +type offlineSim struct { |
| + state string // "none" or an offline state |
| + stagedAt int64 // the record's latest stage request |
| + answered int64 // the request the stager's report answers |
| + reads int // status reads since the state was entered |
| + never bool // the move was aborted from staging |
| + last frame // the outcome once the move ended |
| + |
| + failIn string // the state whose box work fails |
| + stallIn string // a state whose box work waits for a nudge |
| + holdIn string // a state whose box work never ends |
| + drop string // the verb whose reply is lost (once), after it commits |
| + refuse map[string]string // verb: the console's refusal, nothing written |
| + nudged bool |
| + started int64 // requested_at |
| + updated int64 // updated_at |
| +} |
| + |
| +const simEpoch = int64(1794724320) // 2026-11-15T06:32:00Z |
| + |
| +func (s *offlineSim) recordID() string { |
| + if s.state == "none" || s.state == "" { |
| + return "" |
| + } |
| + return tMoveID |
| +} |
| + |
| +func (s *offlineSim) enter(state string) { |
| + s.state, s.reads, s.nudged = state, 0, false |
| + s.updated++ |
| +} |
| + |
| +// worked says the state's box work is done. |
| +func (s *offlineSim) worked() bool { |
| + switch { |
| + case s.state == s.holdIn, s.state == s.failIn: |
| + return false |
| + case s.state == s.stallIn && !s.nudged: |
| + return false |
| + } |
| + return s.reads >= 2 |
| +} |
| + |
| +// view is the status view as it stands. |
| +func (s *offlineSim) view() frame { |
| + if s.state == "" || s.state == "none" { |
| + f := frame{"host": oHost, "state": "none"} |
| + if s.last != nil { |
| + f["last"] = s.last |
| + } |
| + return f |
| + } |
| + extra := frame{"requested_at": simEpoch + s.started, "updated_at": simEpoch + s.updated} |
| + ready := s.worked() |
| + switch s.state { |
| + case "offline-staging": |
| + extra["staged_at"] = s.stagedAt |
| + if s.answered != 0 { |
| + st := frame{"box": "ie-box", "phase": "staged", "at": simEpoch, "replica_objects": 1204, "replica_bytes": 48200000, |
| + "staged_objects": 1204, "staged_bytes": 48200000, "round_bytes": 10, "request": s.answered} |
| + if s.failIn == s.state { |
| + st["phase"], st["error"] = "failed", "the staging bucket refused a write" |
| + } |
| + extra["stage"] = st |
| + } |
| + if s.answered == s.stagedAt && s.failIn != s.state { |
| + extra["next"] = "start" |
| + } |
| + extra["can_abort"] = true |
| + case "offline-stopping": |
| + if ready { |
| + extra["next"] = "seal" |
| + } else { |
| + extra["waiting"] = oWaitBox |
| + } |
| + extra["can_abort"] = true |
| + case "offline-sealed": |
| + extra["next"], extra["can_abort"] = "flip", true |
| + case "offline-landed": |
| + extra["next"], extra["can_abort"] = "open", true |
| + case "offline-sealing", "offline-landing": |
| + extra["can_abort"] = true |
| + case "offline-open", "offline-finishing", "offline-reverting": |
| + if ready { |
| + extra["next"] = "finish" |
| + } |
| + } |
| + if s.failIn == s.state && s.state != "offline-staging" { |
| + extra["failed"] = true |
| + extra["reports"] = []frame{{"box": "uk-box", "role": "target", "phase": "failed", "fresh": true, |
| + "items": frame{"release": frame{"ok": false, "reason": "the release did not unpack"}}}} |
| + delete(extra, "next") |
| + } |
| + if s.never { |
| + extra["never_offline"] = true |
| + } |
| + return offView(s.state, extra) |
| +} |
| + |
| +// get is one status read: a tick of the boxes, then the view. |
| +func (s *offlineSim) get() frame { |
| + s.reads++ |
| + if s.state == "offline-staging" && s.reads >= 2 { |
| + s.answered = s.stagedAt |
| + } |
| + if s.worked() { |
| + switch s.state { |
| + case "offline-sealing": |
| + s.enter("offline-sealed") |
| + case "offline-landing": |
| + s.enter("offline-landed") |
| + } |
| + } |
| + return s.view() |
| +} |
| + |
| +// post is one POST of a door: its answer, and whether the reply is lost. |
| +func (s *offlineSim) post(tail string) (int, any, bool) { |
| + verb := strings.TrimPrefix(tail, "/") |
| + if tail == "" { |
| + verb = "start" |
| + } |
| + if why, ok := s.refuse[verb]; ok { |
| + return http.StatusConflict, frame{"error": why}, false |
| + } |
| + wrong := func() (int, any, bool) { |
| + return http.StatusConflict, frame{"error": "this move is " + s.state + ". run carlos move offline status --host " + oHost + " to see what it waits for"}, false |
| + } |
| + ready := s.worked() |
| + switch verb { |
| + case "nudge": |
| + if s.recordID() == "" { |
| + return wrong() |
| + } |
| + s.nudged = true |
| + return http.StatusAccepted, s.view(), false |
| + case "stage": |
| + switch s.state { |
| + case "", "none": |
| + s.enter("offline-staging") |
| + case "offline-staging": |
| + s.reads = 0 |
| + default: |
| + return wrong() |
| + } |
| + s.stagedAt++ |
| + case "start": |
| + if s.state != "offline-staging" || s.answered != s.stagedAt { |
| + return wrong() |
| + } |
| + s.enter("offline-stopping") |
| + s.started = s.updated |
| + case "seal": |
| + if s.state != "offline-stopping" || !ready { |
| + return wrong() |
| + } |
| + s.enter("offline-sealing") |
| + case "flip": |
| + if s.state != "offline-sealed" { |
| + return wrong() |
| + } |
| + s.enter("offline-landing") |
| + case "open": |
| + if s.state != "offline-landed" { |
| + return wrong() |
| + } |
| + s.enter("offline-open") |
| + case "abort": |
| + switch s.state { |
| + case "offline-staging": |
| + s.never = true |
| + case "offline-stopping", "offline-sealing", "offline-sealed", "offline-landing", "offline-landed": |
| + case "offline-reverting": |
| + return http.StatusAccepted, s.view(), false |
| + default: |
| + return wrong() |
| + } |
| + s.failIn, s.stallIn, s.holdIn = "", "", "" |
| + s.enter("offline-reverting") |
| + case "finish": |
| + if !ready { |
| + return wrong() |
| + } |
| + switch s.state { |
| + case "offline-open": |
| + s.enter("offline-finishing") |
| + case "offline-finishing": |
| + s.state, s.last = "none", frame{"id": tMoveID, "outcome": "done", "at": "2026-11-15T06:40:00Z", "offline_s": 78} |
| + case "offline-reverting": |
| + s.state, s.last = "none", frame{"id": tMoveID, "outcome": "aborted", "at": "2026-11-15T06:40:00Z"} |
| + default: |
| + return wrong() |
| + } |
| + default: |
| + return http.StatusNotFound, frame{}, false |
| + } |
| + drop := s.drop == verb |
| + if drop { |
| + s.drop = "" |
| + } |
| + return http.StatusAccepted, s.view(), drop |
| +} |
| + |
| +// runSeams is what a run test controls: the probe's answers and Ctrl-C. |
| +type runSeams struct { |
| + probe func() int |
| + // ctrlC, when set, says at which polls (1-based) a Ctrl-C arrives. |
| + ctrlC func(poll int) bool |
| +} |
| + |
| +// runOfflineRun runs `carlos move offline run` against c on a fake clock |
| +// that starts at 06:12:00Z and moves on by each poll's 2 s. |
| +func runOfflineRun(t *testing.T, c *fakeOfflineConsole, seams runSeams, args ...string) (int, string) { |
| + t.Helper() |
| + ts := httptest.NewServer(c) |
| + t.Cleanup(ts.Close) |
| + var out bytes.Buffer |
| + clock := time.Date(2026, 11, 15, 6, 12, 0, 0, time.UTC) |
| + ints := make(chan struct{}, 4) |
| + polls := 0 |
| + if seams.probe == nil { |
| + seams.probe = func() int { return 200 } |
| + } |
| + deps := moveDeps{ |
| + session: func(string) (*apiSession, error) { |
| + return &apiSession{c: newConsoleClient(ts.URL, "cli-token"), console: ts.URL, address: "op@keymail.dev"}, nil |
| + }, |
| + euid: func() int { return 1000 }, |
| + poll: time.Millisecond, |
| + stdin: strings.NewReader(""), |
| + ec2: func(context.Context, string) (awsinv.ExactEC2API, error) { |
| + t.Error("the EC2 reader was asked for") |
| + return nil, nil |
| + }, |
| + now: func() time.Time { return clock }, |
| + after: func(d time.Duration) <-chan time.Time { |
| + polls++ |
| + clock = clock.Add(d) |
| + if seams.ctrlC != nil && seams.ctrlC(polls) { |
| + // The Ctrl-C lands during this poll's sleep: the |
| + // timer never fires, so the run takes the Ctrl-C. |
| + ints <- struct{}{} |
| + return nil |
| + } |
| + fired := make(chan time.Time, 1) |
| + fired <- clock |
| + return fired |
| + }, |
| + probe: func(_ context.Context, url string) int { |
| + if url != "https://"+oHost+"/" && !strings.HasPrefix(url, "https://"+oHost+"/") { |
| + t.Errorf("probed %q", url) |
| + } |
| + return seams.probe() |
| + }, |
| + interrupts: func() (<-chan struct{}, func()) { return ints, func() {} }, |
| + } |
| + args = append([]string{"offline", "run"}, args...) |
| + args = append(args, "--host", oHost, "--account", "bab", "--app", "shop") |
| + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + defer cancel() |
| + code := moveMain(ctx, args, &out, deps) |
| + return code, out.String() |
| +} |
| + |
| +// posts lists the POSTs the console got, as "<door> <body>". |
| +func (c *fakeOfflineConsole) postsSent() []string { |
| + var out []string |
| + for _, r := range c.requests() { |
| + if strings.HasPrefix(r, "POST ") { |
| + out = append(out, strings.TrimPrefix(strings.TrimPrefix(r, "POST "), "/offline")) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// doors is the doors of postsSent, without bodies. |
| +func doorsOf(posts []string) string { |
| + var out []string |
| + for _, p := range posts { |
| + door, _, _ := strings.Cut(p, " ") |
| + if door == "" { |
| + door = "/start" |
| + } |
| + out = append(out, strings.TrimPrefix(door, "/")) |
| + } |
| + return strings.Join(out, ",") |
| +} |
| + |
| +const ( |
| + orHeader = "Moving acme.shop.example.com from ie to uk. Move " + tMoveID + "." |
| + orMoved = "Moved. acme.shop.example.com is served from uk. It was offline for 78 seconds." |
| + orBack = "acme.shop.example.com is back in ie and serving. Nothing was lost." |
| +) |
| + |
| +func TestMoveOfflineRunHappyPath(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + posts := c.postsSent() |
| + if got := doorsOf(posts); got != "stage,start,seal,flip,open,finish,finish" { |
| + t.Fatalf("doors %s\n%s", got, out) |
| + } |
| + // The first stage names no move (there is none yet); every later POST |
| + // names this one, and start carries the region too. |
| + if posts[0] != `/stage {"region":"uk"}` { |
| + t.Errorf("first POST %q", posts[0]) |
| + } |
| + if posts[1] != ` {"id":"`+tMoveID+`","region":"uk"}` { |
| + t.Errorf("start POST %q", posts[1]) |
| + } |
| + for _, p := range posts[2:] { |
| + if !strings.HasSuffix(p, ` {"id":"`+tMoveID+`"}`) { |
| + t.Errorf("POST %q does not name the move", p) |
| + } |
| + } |
| + wantLines(t, out, |
| + "06:12:00Z stage sent, accepted", |
| + orHeader, |
| + "06:12:04Z stage 1204 of 1204 objects (48.2 of 48.2 MB)", |
| + "06:12:04Z start sent, accepted. Offline from now.", |
| + " "+oWaitBox, |
| + "06:12:18Z check https://acme.shop.example.com/ answered 200", |
| + orMoved, |
| + ) |
| + for _, verb := range []string{"seal", "flip", "open", "finish"} { |
| + if !strings.Contains(out, " "+verb+strings.Repeat(" ", 7-len(verb))+" sent, accepted\n") { |
| + t.Errorf("no %s line:\n%s", verb, out) |
| + } |
| + } |
| + // The header comes after the stage line that made the move, once. |
| + if strings.Count(out, orHeader) != 1 || strings.Index(out, orHeader) < strings.Index(out, "stage sent") { |
| + t.Errorf("header:\n%s", out) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunDroppedSealReply(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{drop: "seal"}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if n := c.posted("/seal"); n != 1 { |
| + t.Fatalf("seal posted %d times:\n%s", n, out) |
| + } |
| + wantLines(t, out, "seal sent, no answer, checking where the move stands", orMoved) |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal,flip,open,finish,finish" { |
| + t.Fatalf("doors %s", got) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunFailureBeforeOpenAborts(t *testing.T) { |
| + for _, state := range []string{"offline-staging", "offline-stopping", "offline-sealing", "offline-sealed", "offline-landing", "offline-landed"} { |
| + t.Run(state, func(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{failIn: state}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + got := doorsOf(c.postsSent()) |
| + if !strings.HasSuffix(got, ",abort,finish") || strings.Contains(got, "open") { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + wantLines(t, out, orBack) |
| + if !strings.Contains(out, " abort Moving it back to ie.\n") { |
| + t.Errorf("no abort reason line:\n%s", out) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunFailedProbeStops(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, out := runOfflineRun(t, c, runSeams{probe: func() int { return 503 }}, "--to", "uk") |
| + if code != 4 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + got := doorsOf(c.postsSent()) |
| + if got != "stage,start,seal,flip,open" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + wantLines(t, out, |
| + "check https://acme.shop.example.com/ did not answer within 2 min", |
| + "acme.shop.example.com is open in uk but not finished. Check the site, then run:", |
| + " carlos move offline finish --host acme.shop.example.com", |
| + ) |
| +} |
| + |
| +func TestMoveOfflineRunResumeWrongIDWritesNothing(t *testing.T) { |
| + sim := &offlineSim{} |
| + sim.enter("offline-stopping") |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--resume", "mv_other") |
| + if code != 4 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if posts := c.postsSent(); len(posts) != 0 { |
| + t.Fatalf("posted %q", posts) |
| + } |
| + if out != "acme.shop.example.com's move is "+tMoveID+", not mv_other. Nothing was sent.\n" { |
| + t.Fatalf("output:\n%s", out) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunResumeCarriesOn(t *testing.T) { |
| + sim := &offlineSim{} |
| + sim.enter("offline-stopping") |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--resume", tMoveID) |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "seal,flip,open,finish,finish" { |
| + t.Fatalf("doors %s", got) |
| + } |
| + if !strings.HasPrefix(out, orHeader+"\n") { |
| + t.Fatalf("output:\n%s", out) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunRefusesAMoveInFlight(t *testing.T) { |
| + sim := &offlineSim{} |
| + sim.enter("offline-sealing") |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 4 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if posts := c.postsSent(); len(posts) != 0 { |
| + t.Fatalf("posted %q", posts) |
| + } |
| + want := "acme.shop.example.com already has a move in flight (" + tMoveID + "). See where it is, then carry it on:\n" + |
| + " carlos move offline status --host acme.shop.example.com\n" + |
| + " carlos move offline run --host acme.shop.example.com --resume " + tMoveID + "\n" |
| + if out != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", out, want) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunStallNudges(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{stallIn: "offline-stopping"}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if n := c.posted("/nudge"); n != 1 { |
| + t.Fatalf("nudged %d times:\n%s", n, out) |
| + } |
| + wantLines(t, out, "waiting no change for 30 s, woke the boxes", orMoved) |
| + for _, p := range c.postsSent() { |
| + if strings.HasPrefix(p, "/nudge") && p != `/nudge {"id":"`+tMoveID+`"}` { |
| + t.Errorf("nudge %q", p) |
| + } |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunFirstStageRefused(t *testing.T) { |
| + const why = "another offline move is in flight. try again shortly" |
| + c := &fakeOfflineConsole{sim: &offlineSim{refuse: map[string]string{"stage": why}}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 5 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage" { |
| + t.Fatalf("doors %s", got) |
| + } |
| + if out != "06:12:00Z stage sent, refused: "+why+"\n" { |
| + t.Fatalf("output:\n%s", out) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunOverTheOfflineLimit(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{holdIn: "offline-sealing"}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk", "--max-offline", "20s") |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal,abort,finish" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + wantLines(t, out, "limit offline for 20 s, over the limit. Moving it back to ie.", orBack) |
| +} |
| + |
| +func TestMoveOfflineRunCtrlC(t *testing.T) { |
| + // The first Ctrl-C before open moves it back and follows through. |
| + c := &fakeOfflineConsole{sim: &offlineSim{holdIn: "offline-sealing"}} |
| + code, out := runOfflineRun(t, c, runSeams{ctrlC: func(poll int) bool { return poll == 5 }}, "--to", "uk") |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); !strings.HasSuffix(got, ",abort,finish") { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + wantLines(t, out, "Moving acme.shop.example.com back to ie. Press Ctrl-C again to stop watching.", orBack) |
| + |
| + // The second stops watching: the move goes on, nothing more is sent. |
| + c = &fakeOfflineConsole{sim: &offlineSim{holdIn: "offline-sealing"}} |
| + code, out = runOfflineRun(t, c, runSeams{ctrlC: func(poll int) bool { return poll == 5 || poll == 6 }}, "--to", "uk") |
| + if code != 4 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + wantLines(t, out, |
| + "Stopped watching. The move is still running. To see where it is, run:", |
| + " carlos move offline status --host acme.shop.example.com", |
| + ) |
| + |
| + // After open a Ctrl-C undoes nothing. |
| + c = &fakeOfflineConsole{sim: &offlineSim{holdIn: "offline-open"}} |
| + code, out = runOfflineRun(t, c, runSeams{probe: func() int { return 0 }, ctrlC: func(poll int) bool { return poll == 14 }}, "--to", "uk") |
| + if code != 4 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); strings.Contains(got, "abort") || strings.Contains(got, "finish") { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + wantLines(t, out, "acme.shop.example.com is already served from uk, so the move is not undone. Stopped watching.") |
| +} |
| + |
| +func TestMoveOfflineRunLog(t *testing.T) { |
| + log := filepath.Join(t.TempDir(), "run.log") |
| + if err := os.WriteFile(log, []byte("earlier\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk", "--log", log) |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + got, err := os.ReadFile(log) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if string(got) != "earlier\n"+out { |
| + t.Fatalf("log:\n%s\nwant the output appended:\n%s", got, out) |
| + } |
| + |
| + // A log that cannot be opened: OR45, exit 1, nothing sent. |
| + c = &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, out = runOfflineRun(t, c, runSeams{}, "--to", "uk", "--log", filepath.Join(t.TempDir(), "no", "such", "dir", "run.log")) |
| + if code != 1 || !strings.HasPrefix(out, "cannot write the log ") || len(c.requests()) != 0 { |
| + t.Fatalf("exit %d, %d requests:\n%s", code, len(c.requests()), out) |
| + } |
| +} |
| + |
| +func TestParseMoveArgsOfflineRun(t *testing.T) { |
| + for _, c := range []struct { |
| + args []string |
| + ok bool |
| + }{ |
| + {[]string{"offline", "run", "--host", oHost, "--to", "uk"}, true}, |
| + {[]string{"offline", "run", "--host", oHost, "--resume", tMoveID}, true}, |
| + {[]string{"offline", "run", "--host", oHost}, false}, |
| + {[]string{"offline", "run", "--host", oHost, "--to", "uk", "--no-finish", "--max-offline", "20m", "--probe-path", "/up", "--log", "x"}, true}, |
| + {[]string{"offline", "run", "--host", oHost, "--to", "uk", "--max-offline", "soon"}, false}, |
| + {[]string{"offline", "seal", "--host", oHost, "--resume", tMoveID}, false}, |
| + } { |
| + got, err := parseMoveArgs(c.args, &bytes.Buffer{}) |
| + if (err == nil) != c.ok || (c.ok && got.offline != "run") { |
| + t.Errorf("parseMoveArgs(%q) = %+v, %v; want ok %v", c.args, got, err, c.ok) |
| + } |
| + } |
| + got, _ := parseMoveArgs([]string{"offline", "run", "--host", oHost, "--to", "uk", "--no-finish", "--max-offline", "20m", "--probe-path", "/up", "--log", "x"}, &bytes.Buffer{}) |
| + if !got.noFinish || got.maxOffline != 20*time.Minute || got.probePath != "/up" || got.logPath != "x" { |
| + t.Errorf("parsed %+v", got) |
| + } |
| + var out bytes.Buffer |
| + _, _ = parseMoveArgs([]string{"offline", "run", "-h"}, &out) |
| + wantLines(t, out.String(), |
| + "carlos move offline run --host <host> --to <region> [--resume <move-id>] [--no-finish] [--max-offline <duration>] [--probe-path <path>] [--log <file>]", |
| + ) |
| + for _, usage := range []string{ |
| + "carry on the move with this id from wherever it stands", |
| + "stop once the instance is served from the new region, before the old region is cleaned up", |
| + "when to move the instance back if it is still offline (default 15m)", |
| + "the path run checks after the instance opens (default /)", |
| + "also write each step to this file", |
| + } { |
| + if !strings.Contains(out.String(), usage) { |
| + t.Errorf("help lacks %q:\n%s", usage, out.String()) |
| + } |
| + } |
| + if strings.Contains(out.String(), "(default 15m0s)") { |
| + t.Errorf("help says the default twice:\n%s", out.String()) |
| + } |
| +} |
| + |
| +func TestMoveOfflineRunNoFinish(t *testing.T) { |
| + c := &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk", "--no-finish") |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal,flip,open" { |
| + t.Fatalf("doors %s", got) |
| + } |
| + wantLines(t, out, oServed) |
| +} |
diff --git a/move_offline_run_unix.go b/move_offline_run_unix.go| new file mode 100644 |
| index 000000000..d133a1d06 |
| --- /dev/null |
| +++ b/move_offline_run_unix.go |
| @@ -0,0 +1,13 @@ |
| +//go:build linux || darwin |
| + |
| +package main |
| + |
| +import ( |
| + "os/signal" |
| + "syscall" |
| +) |
| + |
| +// ignoreHangup keeps `carlos move offline run` going when its terminal |
| +// goes away (an SSH session dropped): the move is under way, and stopping |
| +// the watcher would strand it. |
| +func ignoreHangup() { signal.Ignore(syscall.SIGHUP) } |
diff --git a/move_test.go b/move_test.go| index be2a38120..eb02908e8 100644 |
| --- a/move_test.go |
| +++ b/move_test.go |
| @@ -1114,13 +1114,21 @@ type offPost struct { |
| // status door returns the next scripted view (the last repeats); each POST |
| // returns the next scripted answer of its door. Anything outside the offline |
| // doors is a 404, so a verb that read the Phase 1 door would fail. |
| +// |
| +// As the doors do since the run plan's Task 3, a POST whose body names a |
| +// move id other than the record's answers 409 and writes nothing; the |
| +// record's move is moveID, or the model's. With sim set, every door is |
| +// answered from that model of the move (offlineSim) instead of the |
| +// scripts, the nudge door (Task 4) among them. |
| type fakeOfflineConsole struct { |
| - mu sync.Mutex |
| - gets []frame |
| - i int |
| - posts map[string][]offPost // keyed by the door's tail: "", "/seal", ... |
| - n map[string]int |
| - log []string // method path body |
| + mu sync.Mutex |
| + gets []frame |
| + i int |
| + posts map[string][]offPost // keyed by the door's tail: "", "/seal", ... |
| + n map[string]int |
| + log []string // method path body |
| + moveID string |
| + sim *offlineSim |
| } |
| func (c *fakeOfflineConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| @@ -1137,6 +1145,11 @@ func (c *fakeOfflineConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| + if r.Method == http.MethodGet && r.URL.Path == tOfflinePth && c.sim != nil { |
| + c.i++ |
| + write(http.StatusOK, c.sim.get()) |
| + return |
| + } |
| if r.Method == http.MethodGet && r.URL.Path == tOfflinePth { |
| n := c.i |
| if n >= len(c.gets) { |
| @@ -1147,14 +1160,48 @@ func (c *fakeOfflineConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| tail := strings.TrimPrefix(r.URL.Path, tOfflinePth) |
| + if c.n == nil { |
| + c.n = map[string]int{} |
| + } |
| + if r.Method == http.MethodPost { |
| + var req struct { |
| + ID string `json:"id"` |
| + } |
| + _ = json.Unmarshal(body, &req) |
| + record := c.moveID |
| + if c.sim != nil { |
| + record = c.sim.recordID() |
| + } |
| + if req.ID != "" && req.ID != record { |
| + c.n[tail]++ |
| + write(http.StatusConflict, frame{"error": "the record carries a different offline move"}) |
| + return |
| + } |
| + } |
| + if c.sim != nil { |
| + if r.Method != http.MethodPost { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + c.n[tail]++ |
| + code, v, drop := c.sim.post(tail) |
| + if drop { |
| + // The write committed; the reply is lost on the way back. |
| + if hj, ok := w.(http.Hijacker); ok { |
| + if conn, _, err := hj.Hijack(); err == nil { |
| + conn.Close() |
| + return |
| + } |
| + } |
| + } |
| + write(code, v) |
| + return |
| + } |
| list := c.posts[tail] |
| if r.Method != http.MethodPost || len(list) == 0 { |
| http.NotFound(w, r) |
| return |
| } |
| - if c.n == nil { |
| - c.n = map[string]int{} |
| - } |
| k := c.n[tail] |
| if k >= len(list) { |
| k = len(list) - 1 |
diff --git a/parity/cli.tsv b/parity/cli.tsv| index 5c902ecbc..7531fbd1d 100644 |
| --- a/parity/cli.tsv |
| +++ b/parity/cli.tsv |
| @@ -166,6 +166,7 @@ move offline abort customer - - - - - |
| move offline finish customer - - - - - |
| move offline flip customer - - - - - |
| move offline open customer - - - - - |
| +move offline run customer - - - - - |
| move offline seal customer - - - - - |
| move offline stage customer - - - - - |
| move offline start customer - - - - - |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index a07254a5a..33bf1b6bf 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -76,7 +76,7 @@ instances-label instances cli-only instances label [--box, --dry-run] Ties an |
| steering instances gap steering wp-instances |
| routes instances partial routes GET /a/{sqid}/apps/{app}/instances ; GET /a/{sqid}/apps/{app}/settings/{section} The console shows host and channel but no environment or replication column. |
| restart instances partial restart POST /a/{sqid}/apps/{app}/restart ; POST /a/{sqid}/apps/{app}/instances/{host}/restart The console has no environment scope and no dry-run list. |
| -move instances gap move ; move status ; move cut ; move abort ; move resolve [--retry] ; move offline stage ; move offline start ; move offline seal ; move offline flip ; move offline open ; move offline finish ; move offline abort ; move offline status wp-instances Region moves; the instance page shows only that a move is running. |
| +move instances gap move ; move status ; move cut ; move abort ; move resolve [--retry] ; move offline stage ; move offline start ; move offline seal ; move offline flip ; move offline open ; move offline finish ; move offline abort ; move offline status ; move offline run wp-instances Region moves; the instance page shows only that a move is running. |
| # domains |
| domains-list domains both domains list GET /a/{sqid}/apps/{app}/settings/{section} |
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl| index 34cac3a8a..f1107a104 100644 |
| --- a/testdata/clireg-golden.jsonl |
| +++ b/testdata/clireg-golden.jsonl |
| @@ -529,6 +529,8 @@ |
| {"case":"move offline flip | -h","argv":["move","offline","flip","-h"],"exit":0,"stdout":" -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n","stderr":""} |
| {"case":"move offline open | --zz-unknown-flag","argv":["move","offline","open","--zz-unknown-flag"],"exit":2,"stdout":"flag provided but not defined: -zz-unknown-flag\n -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n","stderr":""} |
| {"case":"move offline open | -h","argv":["move","offline","open","-h"],"exit":0,"stdout":" -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n","stderr":""} |
| +{"case":"move offline run | --zz-unknown-flag","argv":["move","offline","run","--zz-unknown-flag"],"exit":2,"stdout":"carlos move offline run --host <host> --to <region> [--resume <move-id>] [--no-finish] [--max-offline <duration>] [--probe-path <path>] [--log <file>]\nrun carries the move through each step: it stages the data, takes the instance offline, copies it, starts it in the new region and checks that it answers. If a step fails or takes too long before it opens, it moves the instance back.\nflag provided but not defined: -zz-unknown-flag\n -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n -log string\n \talso write each step to this file\n -max-offline duration\n \twhen to move the instance back if it is still offline (default 15m)\n -no-finish\n \tstop once the instance is served from the new region, before the old region is cleaned up\n -probe-path string\n \tthe path run checks after the instance opens (default /)\n -resume string\n \tcarry on the move with this id from wherever it stands\n -to string\n \tthe region to move the instance to\n","stderr":""} |
| +{"case":"move offline run | -h","argv":["move","offline","run","-h"],"exit":0,"stdout":"carlos move offline run --host <host> --to <region> [--resume <move-id>] [--no-finish] [--max-offline <duration>] [--probe-path <path>] [--log <file>]\nrun carries the move through each step: it stages the data, takes the instance offline, copies it, starts it in the new region and checks that it answers. If a step fails or takes too long before it opens, it moves the instance back.\n -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n -log string\n \talso write each step to this file\n -max-offline duration\n \twhen to move the instance back if it is still offline (default 15m)\n -no-finish\n \tstop once the instance is served from the new region, before the old region is cleaned up\n -probe-path string\n \tthe path run checks after the instance opens (default /)\n -resume string\n \tcarry on the move with this id from wherever it stands\n -to string\n \tthe region to move the instance to\n","stderr":""} |
| {"case":"move offline seal | --zz-unknown-flag","argv":["move","offline","seal","--zz-unknown-flag"],"exit":2,"stdout":"flag provided but not defined: -zz-unknown-flag\n -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n","stderr":""} |
| {"case":"move offline seal | -h","argv":["move","offline","seal","-h"],"exit":0,"stdout":" -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n","stderr":""} |
| {"case":"move offline stage | --zz-unknown-flag","argv":["move","offline","stage","--zz-unknown-flag"],"exit":2,"stdout":"flag provided but not defined: -zz-unknown-flag\n -a string\n \tshorthand for --app\n -account string\n \tthe account the app belongs to (default: your default account)\n -account-id string\n \tthe account, by its id\n -app string\n \tthe app the instance belongs to\n -console string\n \tthe console to work through (default: the only logged-in one)\n -host string\n \tthe instance's host name\n -to string\n \tthe region to move the instance to\n","stderr":""} |