carlos / platform Public

cli: carlos instances create --seed-file

Begin comes before the uploading line, then the streamed upload and a
wait until the seed leaves reserving. Aborted seeds, and a 422 on the
upload, end with the hold line. The SEED column gains the file rows.
instanceDelete moves to instances_seedfile.go unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev fe49fdb0c821b661d2fe1f2751590badb1939d57 parent 7b98282
8 files changed, +507 −24
  • apimode.go +0 −13
  • docs/parity.md +2 −2
  • docs/site/cli.md +7 −1
  • instances_cli.go +8 −7
  • instances_seed.go +3 −0
  • instances_seedfile.go +244 −0
  • instances_seedfile_test.go +242 −0
  • parity/parity.tsv +1 −1

CI failed — run details

diff --git a/apimode.go b/apimode.go
index e7048ac17..0548a4b34 100644
--- a/apimode.go
+++ b/apimode.go
@@ -4473,19 +4473,6 @@ func (s *apiSession) telemetryGet(ctx context.Context, a apiAcct, app string) (t
return st, nil
}
-// instanceDelete retires one instance record. Idempotent server-side (the
-// caller's goal is "not there"), so a 200 is the only success shape.
-func (s *apiSession) instanceDelete(ctx context.Context, a apiAcct, app, host string, messages ...string) error {
- status, body, err := s.deleteJSON(ctx, apiPath(a, app, "/instances/"+url.PathEscape(host)), messages...)
- if err != nil {
- return err
- }
- if status != http.StatusOK {
- return apiErrorFromBody(status, body)
- }
- return nil
-}
-
// instanceGet reads ONE instance record (GET …/instances/{host}). found is
// false only on a 404, the console's answer for a host with no record; any
// other failure is an error, never "absent" (canary --region relies on
diff --git a/docs/parity.md b/docs/parity.md
index 4561ba2dd..6c04942bc 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -150,7 +150,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
|---|---|---|---|---|---|
| instances-list | both | `instances list` | `GET /a/{sqid}/apps/{app}/instances`<br>`GET /a/{sqid}/apps/{app}/instances/{host}` | | |
| instances-enable | gap | `instances enable` | | [wp-instances](#wp-instances) | |
-| instances-create | gap | `instances create [host, channel, environment, region, role, --from, --at, --restore]` | | [wp-instances](#wp-instances) | The empty Running page prints the CLI command. |
+| instances-create | gap | `instances create [host, channel, environment, region, role, --from, --seed-file, --at, --restore]` | | [wp-instances](#wp-instances) | The empty Running page prints the CLI command. |
| instances-delete | gap | `instances delete` | | [wp-instances](#wp-instances) | |
| instances-set-channel | gap | `instances set-channel` | | [wp-instances](#wp-instances) | |
| instances-set-environment | gap | `instances set-environment` | | [wp-instances](#wp-instances) | |
@@ -273,7 +273,7 @@ Discussion #734.
- `canary-rm` (releases), CLI has `canary rm`
- `instances-enable` (instances), CLI has `instances enable`
-- `instances-create` (instances), CLI has `instances create [host, channel, environment, region, role, --from, --at, --restore]`
+- `instances-create` (instances), CLI has `instances create [host, channel, environment, region, role, --from, --seed-file, --at, --restore]`
- `instances-delete` (instances), CLI has `instances delete`
- `instances-set-channel` (instances), CLI has `instances set-channel`
- `instances-set-environment` (instances), CLI has `instances set-environment`
diff --git a/docs/site/cli.md b/docs/site/cli.md
index bcad4e8c1..0f6de959b 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1400,6 +1400,12 @@ carlos instances create --app shop --host canary.example.com --from www.example.
carlos instances create --app shop --host canary.example.com --from www.example.com --at 4211
```
+To start a new instance from a SQLite database file you already have, add --seed-file. The file can be up to 4 GiB. The CLI uploads it, the console checks that it is a sound database, and the new instance starts from it the first time it wakes. This is for an app that runs in a region. You can't combine it with --from, and the new instance is an ordinary one, so --kind, --addr and --role don't apply. If the upload or the check fails, nothing is created, and the hostname is free again once its box has cleaned up.
+
+```sh
+carlos instances create --app shop --host new.example.com --seed-file shop.db
+```
+
carlos instances import moves an instance the platform never ran onto the platform. Stop the old process, take a consistent snapshot of its database (VACUUM INTO works), and run the import with the address of the route it replaces. The console checks the file, the box swaps the route on its next pass, and from then until you commit, the host answers only requests that carry the verify token. With --verify, the CLI requests that path with the token and commits on a 2xx or aborts otherwise. Without it, the CLI prints the token and the two commands to finish by hand. Aborting puts the old route back exactly as it was.
```sh
@@ -3617,7 +3623,7 @@ Ops account owners and `CARLOS_SYSTEM_OPERATORS`.
#### The seeds floor
-carlos system seeds-floor publish sets the first release whose boxes can place a seed. Publish it once every box runs that release. Each box arms it within the hour, and from then on a box never recovers to an older build. Until every box in a region has armed it, carlos instances create --from and carlos instances import refuse there.
+carlos system seeds-floor publish sets the first release whose boxes can place a seed. Publish it once every box runs that release. Each box arms it within the hour, and from then on a box never recovers to an older build. Until every box in a region has armed it, carlos instances create --from, carlos instances create --seed-file and carlos instances import refuse there.
```sh
carlos system seeds-floor publish --min-release v0.27.0
diff --git a/instances_cli.go b/instances_cli.go
index faa60138d..f9c10e0df 100644
--- a/instances_cli.go
+++ b/instances_cli.go
@@ -332,6 +332,7 @@ func runInstancesCreate(args []string) {
role := fs.String("role", "", "instance role (default: the serving home); \"replica\" provisions a second instance of the account holding a one-way mirror of it, selling near the buyer — needs --region naming the replica's placement")
from := fs.String("from", "", "copy this instance's database into the new one. The source must be an instance of the same app, in this console's region")
at := fs.Int64("at", 0, "with --from, the transaction id to copy at (default: the latest)")
+ seedFile := fs.String("seed-file", "", cliSeedFileCopyFlag)
replicas := fs.String("replicas", "", "comma-separated placement codes the account's replicas live in (the HOME record's opt-in; e.g. ie,uk) — this instance's own replica must be --role replica with --region")
restore := fs.Bool("restore", false, "bring back a deleted instance on this host with the data it kept: the same app's plain instance, created and deleted after restore was available")
fs.Usage = flagUsage(fs, instancesRecordsUsage)
@@ -343,14 +344,14 @@ func runInstancesCreate(args []string) {
fs.Visit(func(f *flag.Flag) { set[f.Name] = true })
addrs := parseAddrList(*addr, set["addr"])
probe := parseProbeFlags(*healthPath, *healthStatus, set["health-path"], set["health-status"])
- if *restore && (*from != "" || *kind != "" || set["addr"] || *role != "") {
- log.Fatalf("instances create: %s", "a restore is a plain instance. Drop --from, --kind, --addr and --role.")
+ if *restore && (*from != "" || *seedFile != "" || *kind != "" || set["addr"] || *role != "") {
+ log.Fatalf("instances create: %s", restoreRefusal(*seedFile))
}
if set["at"] && (*at <= 0 || *from == "") {
log.Fatalf("instances create: %s", "at must be a transaction id, a whole number above 0")
}
- if *from != "" && (*kind != "" || set["addr"] || *role != "" || *replicas != "") {
- log.Fatalf("instances create: %s", "a seeded instance is an ordinary instance. Drop --kind, --addr and --role.")
+ if msg := seededFlagsRefusal(*from, *seedFile, *kind, set["addr"], *role, *replicas); msg != "" {
+ log.Fatalf("instances create: %s", msg)
}
sess := requireAPISession("create", *consoleFlag)
printUsing(stdout, sess)
@@ -360,9 +361,9 @@ func runInstancesCreate(args []string) {
if merr != nil {
log.Fatalf("instances create: %v", merr)
}
- if *from != "" {
- if err := sess.runSeededCreate(context.Background(), stdout, acct, app2, strings.TrimSpace(*host), strings.TrimSpace(*region),
- strings.TrimSpace(*channel), strings.TrimSpace(*environment), strings.TrimSpace(*from), uint64(*at), message); err != nil {
+ if *from != "" || *seedFile != "" {
+ if err := sess.runSeededAny(context.Background(), stdout, acct, app2, strings.TrimSpace(*host), strings.TrimSpace(*region),
+ strings.TrimSpace(*channel), strings.TrimSpace(*environment), strings.TrimSpace(*from), strings.TrimSpace(*seedFile), uint64(*at), message); err != nil {
log.Fatalf("instances create: %v", err)
}
return
diff --git a/instances_seed.go b/instances_seed.go
index bd15aefdf..678d6b49f 100644
--- a/instances_seed.go
+++ b/instances_seed.go
@@ -34,6 +34,9 @@ func seedCell(r apiInstanceRecord) string {
if s.Kind == "demo-claim" {
return s.Kind + " " + s.State
}
+ if cell, ok := fileSeedCell(s); ok {
+ return cell
+ }
switch s.State {
case "reserving":
return fmt.Sprintf("copying from %s", s.From)
diff --git a/instances_seedfile.go b/instances_seedfile.go
new file mode 100644
index 000000000..7f2fd0233
--- /dev/null
+++ b/instances_seedfile.go
@@ -0,0 +1,244 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+)
+
+// `carlos instances create --seed-file` (#1139): the new instance's
+// database starts as an uploaded file. The begin and the upload ride the
+// import door (import{kind:"file"}, PUT .../import?seed=<id>); the seed then
+// follows --from's states, so the wait is the same poller. The copy is the
+// approved table of docs/superpowers/plans/2026-11-20-fleet-seeded-create.md
+// (FS-1 to FS-12, FS-14, FS-17).
+const (
+ // seedFileMaxBytes is the console's cap on one seed file.
+ seedFileMaxBytes = 4 << 30
+
+ cliSeedFileCopyFlag = "start the new instance from this SQLite database file, at most 4 GiB. Not with --from" // FS-1
+ cliSeedFileCopyBoth = "use --seed-file or --from, not both" // FS-2
+ cliSeedFileCopyRead = "could not read %s. Check the path, then try again." // FS-3
+ cliSeedFileCopySize = "%s must be more than 0 bytes and at most 4 GiB" // FS-4
+ cliSeedFileCopyChecking = "checking %s. A large database can take several minutes." // FS-6
+ cliSeedFileCopyAwaiting = "seed file awaiting upload" // FS-7
+ cliSeedFileCopyReady = "seed file awaiting first start" // FS-8
+ cliSeedFileCopyPlaced = "seeded from a file %s" // FS-9
+ cliSeedFileCopyNotMade = "not created: %s" // FS-10
+ cliSeedFileCopyNotKept = "the seed file was not kept, so %s was not created. Try again." // FS-11
+ cliSeedFileCopyHeld = "the hostname is free again once its box has cleaned up" // FS-12
+ cliSeedFileCopyRestore = "a restore is a plain instance. Drop --seed-file." // FS-14
+)
+
+// restoreRefusal is the sentence for --restore beside a seeded flag: FS-14
+// for --seed-file, the existing one (which names --from) otherwise.
+func restoreRefusal(seedFile string) string {
+ if seedFile != "" {
+ return cliSeedFileCopyRestore
+ }
+ return "a restore is a plain instance. Drop --from, --kind, --addr and --role."
+}
+
+// seededFlagsRefusal is the flags' check for a seeded create (--from or
+// --seed-file), "" when the flags are fine: FS-2 for both, then the
+// existing SD-N36 for any flag a seeded instance does not take.
+func seededFlagsRefusal(from, seedFile, kind string, addrSet bool, role, replicas string) string {
+ if from != "" && seedFile != "" {
+ return cliSeedFileCopyBoth
+ }
+ if (from != "" || seedFile != "") && (kind != "" || addrSet || role != "" || replicas != "") {
+ return "a seeded instance is an ordinary instance. Drop --kind, --addr and --role."
+ }
+ return ""
+}
+
+// runSeededAny is the one seeded-create call: --seed-file, else --from.
+func (s *apiSession) runSeededAny(ctx context.Context, w io.Writer, a apiAcct, app, host, region, channel, environment, from, seedFile string, at uint64, message string) error {
+ if seedFile != "" {
+ return s.runSeedFileCreate(ctx, w, a, app, host, region, channel, environment, seedFile, message)
+ }
+ return s.runSeededCreate(ctx, w, a, app, host, region, channel, environment, from, at, message)
+}
+
+// seedFileSizeRefusal is FS-4: a seed file is more than 0 bytes and at most
+// 4 GiB.
+func seedFileSizeRefusal(name string, size int64) error {
+ if size <= 0 || size > seedFileMaxBytes {
+ return fmt.Errorf(cliSeedFileCopySize, name)
+ }
+ return nil
+}
+
+// seedFileBegin is the begin of a file seed: the ordinary create body plus
+// import{kind:"file",sha256,bytes}, with no replaces and no verify token.
+// Begin may provision a private store, so it gets importBegin's longer
+// client.
+func (s *apiSession) seedFileBegin(ctx context.Context, a apiAcct, app, host, region, channel, environment, sha string, size int64, message string) (apiInstanceRecord, error) {
+ in := struct {
+ Host string `json:"host"`
+ Region string `json:"region,omitempty"`
+ Channel string `json:"channel,omitempty"`
+ Environment string `json:"environment,omitempty"`
+ Message string `json:"message,omitempty"`
+ Import struct {
+ Kind string `json:"kind"`
+ SHA256 string `json:"sha256"`
+ Bytes int64 `json:"bytes"`
+ } `json:"import"`
+ }{Host: host, Region: region, Channel: channel, Environment: environment, Message: message}
+ in.Import.Kind, in.Import.SHA256, in.Import.Bytes = "file", sha, size
+ clone := *s
+ client := *s.c
+ httpc := *s.c.httpc
+ httpc.Timeout = storeProvisionHTTPTimeout
+ client.httpc = &httpc
+ clone.c = &client
+ status, body, err := clone.postJSON(ctx, apiPath(a, app, "/instances"), in)
+ if err != nil {
+ return apiInstanceRecord{}, err
+ }
+ if status != http.StatusCreated {
+ return apiInstanceRecord{}, apiErrorFromBody(status, body)
+ }
+ var rec apiInstanceRecord
+ if err := json.Unmarshal(body, &rec); err != nil {
+ return apiInstanceRecord{}, fmt.Errorf("instances create: unreadable response: %w", err)
+ }
+ if rec.Seed == nil || rec.Seed.ID == "" {
+ return apiInstanceRecord{}, errors.New("instances create: unreadable response")
+ }
+ return rec, nil
+}
+
+// seedFileUpload is importUpload that also returns the status of a
+// refusal: a 422 means the door aborted the seed (FS-17), which the caller
+// must tell apart from a refusal that left it waiting.
+func (s *apiSession) seedFileUpload(ctx context.Context, a apiAcct, app, host, id string, f *os.File, size int64) (int, error) {
+ ctx, cancel := context.WithTimeout(ctx, importUploadDeadline)
+ defer cancel()
+ res, err := s.c.doStream(ctx, http.MethodPut, apiPath(a, app, importDoor(host, "", id)), f, size,
+ http.Header{"Content-Type": {"application/octet-stream"}, "Expect": {"100-continue"}})
+ if err != nil {
+ return 0, err
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ if res.StatusCode != http.StatusAccepted {
+ return res.StatusCode, apiErrorFromBody(res.StatusCode, raw)
+ }
+ return res.StatusCode, nil
+}
+
+// withHeldLine appends FS-12 to an error as its indented second line.
+func withHeldLine(err error) error {
+ return fmt.Errorf("%v\n %s", err, cliSeedFileCopyHeld)
+}
+
+// runSeedFileCreate is the --seed-file create end to end: size and hash the
+// file, begin, upload, then follow the seed until it leaves reserving. Begin
+// comes before the uploading line, so a refusal prints no upload line. An
+// aborted seed returns its reason followed by FS-12, on a region and a
+// fleet alike; so does a 422 on the upload, which aborted it. No other
+// upload refusal does: those leave the seed reserving.
+func (s *apiSession) runSeedFileCreate(ctx context.Context, w io.Writer, a apiAcct, app, host, region, channel, environment, file, message string) error {
+ f, err := os.Open(file)
+ if err != nil {
+ return fmt.Errorf(cliSeedFileCopyRead, file)
+ }
+ defer f.Close()
+ h := sha256.New()
+ size, err := io.Copy(h, f)
+ if err != nil {
+ return fmt.Errorf(cliSeedFileCopyRead, file)
+ }
+ if err := seedFileSizeRefusal(file, size); err != nil {
+ return err
+ }
+ rec, err := s.seedFileBegin(ctx, a, app, host, region, channel, environment, hex.EncodeToString(h.Sum(nil)), size, message)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintln(w, fmt.Sprintf("uploading %s (%s)", file, humanBytes(&size)))
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
+ return err
+ }
+ if status, err := s.seedFileUpload(ctx, a, app, host, rec.Seed.ID, f, size); err != nil {
+ if status == http.StatusUnprocessableEntity {
+ return withHeldLine(err)
+ }
+ return err
+ }
+ fmt.Fprintln(w, fmt.Sprintf(cliSeedFileCopyChecking, file))
+ id := rec.Seed.ID
+ final, err := s.pollSeed(ctx, a, app, host, 0, func(r apiInstanceRecord) (bool, error) {
+ if r.Seed == nil || r.Seed.ID != id {
+ return false, withHeldLine(fmt.Errorf(cliSeedFileCopyNotKept, host))
+ }
+ switch r.Seed.State {
+ case "reserving":
+ return false, nil
+ case "aborted", "rolled-back", "refused":
+ if r.Seed.Reason != "" {
+ return false, withHeldLine(errors.New(r.Seed.Reason))
+ }
+ return false, withHeldLine(fmt.Errorf(cliSeedFileCopyNotKept, host))
+ }
+ return true, nil
+ })
+ if err != nil {
+ return err
+ }
+ // The look at one record does not carry where the create placed it: the
+ // begin answer's are kept, as --from's create does.
+ final.RegionName, final.RegionFrom, final.RegionLabel = rec.RegionName, rec.RegionFrom, rec.RegionLabel
+ fmt.Fprintf(w, "%s %s\n", colorFor(w).ok("created instance"), instanceCreatedLine(final, environmentSuffix(final.Environment)))
+ mutedf(w, " %s", seedCell(final))
+ mutedf(w, " the host comes live on the next reconcile pass on its box")
+ return nil
+}
+
+// fileSeedCell is the SEED cell of a file seed (FS-7 to FS-10); ok is false
+// for any other kind. An aborted seed without a reason, and a rolled-back
+// one, read "aborting" as every seed does.
+func fileSeedCell(s *apiSeed) (string, bool) {
+ if s.Kind != "file" {
+ return "", false
+ }
+ switch s.State {
+ case "reserving":
+ return cliSeedFileCopyAwaiting, true
+ case "ready":
+ return cliSeedFileCopyReady, true
+ case "placed":
+ sha := s.SHA256
+ if len(sha) > 12 {
+ sha = sha[:12]
+ }
+ return fmt.Sprintf(cliSeedFileCopyPlaced, sha), true
+ case "aborted":
+ if s.Reason != "" {
+ return fmt.Sprintf(cliSeedFileCopyNotMade, s.Reason), true
+ }
+ }
+ return "", false
+}
+
+// instanceDelete retires one instance record. Idempotent server-side (the
+// caller's goal is "not there"), so a 200 is the only success shape.
+func (s *apiSession) instanceDelete(ctx context.Context, a apiAcct, app, host string, messages ...string) error {
+ status, body, err := s.deleteJSON(ctx, apiPath(a, app, "/instances/"+url.PathEscape(host)), messages...)
+ if err != nil {
+ return err
+ }
+ if status != http.StatusOK {
+ return apiErrorFromBody(status, body)
+ }
+ return nil
+}
diff --git a/instances_seedfile_test.go b/instances_seedfile_test.go
new file mode 100644
index 000000000..c8b1caf66
--- /dev/null
+++ b/instances_seedfile_test.go
@@ -0,0 +1,242 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// seedFileConsole is a console for one --seed-file create: begin, the
+// upload and the record looks answer as configured, and the order of the
+// requests is kept.
+type seedFileConsole struct {
+ mu sync.Mutex
+ calls []string
+ begin map[string]any
+ beginStatus int
+ beginBody string
+ uploadCode int
+ uploadBody string
+ uploaded string
+ gets []string // record bodies, one per look; the last repeats
+ looks int
+}
+
+func newSeedFileConsole(gets ...string) *seedFileConsole {
+ return &seedFileConsole{beginStatus: http.StatusCreated, uploadCode: http.StatusAccepted, gets: gets,
+ beginBody: `{"host":"new.example.com","channel":"stable","region_name":"fleet main","seed":{"id":"sd_f","kind":"file","state":"reserving"}}`}
+}
+
+func (c *seedFileConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ raw, _ := io.ReadAll(r.Body)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch {
+ case r.Method == http.MethodPost:
+ c.calls = append(c.calls, "begin")
+ _ = json.Unmarshal(raw, &c.begin)
+ w.WriteHeader(c.beginStatus)
+ io.WriteString(w, c.beginBody)
+ case r.Method == http.MethodPut:
+ c.calls = append(c.calls, "upload")
+ c.uploaded = string(raw)
+ w.WriteHeader(c.uploadCode)
+ io.WriteString(w, c.uploadBody)
+ default:
+ c.calls = append(c.calls, "get")
+ i := c.looks
+ if c.looks++; i >= len(c.gets) {
+ i = len(c.gets) - 1
+ }
+ io.WriteString(w, c.gets[i])
+ }
+}
+
+func seedFileRec(state, reason string) string {
+ return fmt.Sprintf(`{"host":"new.example.com","channel":"stable","seed":{"id":"sd_f","kind":"file","sha256":"3f2a9c1e0b7d55aa","bytes":3,"state":%q,"reason":%q}}`, state, reason)
+}
+
+func runSeedFile(t *testing.T, c *seedFileConsole, body string) (string, error) {
+ t.Helper()
+ fakeSeedWait(t, 0)
+ ts := httptest.NewServer(c)
+ defer ts.Close()
+ file := filepath.Join(t.TempDir(), "shop.db")
+ if err := os.WriteFile(file, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ err := newTestSession(ts.URL).runSeedFileCreate(context.Background(), &out, apiAcct{Seg: "bab"}, "shop", "new.example.com", "", "", "", file, "")
+ return strings.ReplaceAll(out.String(), filepath.Dir(file)+"/", ""), err
+}
+
+func TestSeedFileCreateBeginsThenUploadsThenWaits(t *testing.T) {
+ c := newSeedFileConsole(seedFileRec("reserving", ""), seedFileRec("ready", ""))
+ out, err := runSeedFile(t, c, "abc")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(c.calls, ","); got != "begin,upload,get,get" {
+ t.Fatalf("requests = %s", got)
+ }
+ sum := sha256.Sum256([]byte("abc"))
+ imp, _ := c.begin["import"].(map[string]any)
+ if imp["kind"] != "file" || imp["sha256"] != hex.EncodeToString(sum[:]) || imp["bytes"] != float64(3) || imp["replaces"] != nil {
+ t.Fatalf("begin import = %v", imp)
+ }
+ if c.uploaded != "abc" {
+ t.Fatalf("uploaded %q", c.uploaded)
+ }
+ want := "uploading shop.db (3B)\n" +
+ "checking shop.db. A large database can take several minutes.\n" +
+ "created instance new.example.com (channel stable, fleet main)\n" +
+ " seed file awaiting first start\n" +
+ " the host comes live on the next reconcile pass on its box\n"
+ if out != want {
+ t.Fatalf("output:\n%s\nwant:\n%s", out, want)
+ }
+}
+
+func TestSeedFileCreatePlacedPrintsTheShortHash(t *testing.T) {
+ out, err := runSeedFile(t, newSeedFileConsole(seedFileRec("placed", "")), "abc")
+ if err != nil || !strings.Contains(out, "\n seeded from a file 3f2a9c1e0b7d\n") {
+ t.Fatalf("err %v out %q", err, out)
+ }
+}
+
+func TestSeedFileCreateRefusalBeforeUploadPrintsNoUploadLine(t *testing.T) {
+ c := newSeedFileConsole()
+ c.beginStatus = http.StatusConflict
+ c.beginBody = `{"error":"fleet main has more than one active box. A seeded instance needs a fleet with one active box for now."}`
+ out, err := runSeedFile(t, c, "abc")
+ if err == nil || err.Error() != "fleet main has more than one active box. A seeded instance needs a fleet with one active box for now." {
+ t.Fatalf("err = %v", err)
+ }
+ if out != "" || strings.Join(c.calls, ",") != "begin" {
+ t.Fatalf("out %q calls %v", out, c.calls)
+ }
+}
+
+func TestSeedFileCreateAbortedPrintsReason(t *testing.T) {
+ const hold = "\n the hostname is free again once its box has cleaned up"
+ for _, tc := range []struct{ name, rec, want string }{
+ {"reason", seedFileRec("aborted", "the seed file on the box failed its integrity check"), "the seed file on the box failed its integrity check" + hold},
+ {"no reason", seedFileRec("rolled-back", ""), "the seed file was not kept, so new.example.com was not created. Try again." + hold},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := runSeedFile(t, newSeedFileConsole(seedFileRec("reserving", ""), tc.rec), "abc")
+ if err == nil || err.Error() != tc.want {
+ t.Fatalf("err = %v, want %q", err, tc.want)
+ }
+ })
+ }
+}
+
+func TestSeedFileCreateAbortedAddsHoldLine(t *testing.T) {
+ const hold = "\n the hostname is free again once its box has cleaned up"
+ // A 422 (FS-17, the door aborted the seed) gets the hold line.
+ c := newSeedFileConsole()
+ c.uploadCode = http.StatusUnprocessableEntity
+ c.uploadBody = `{"error":"the upload does not match the file this create began with, so it was not kept."}`
+ out, err := runSeedFile(t, c, "abc")
+ if err == nil || err.Error() != "the upload does not match the file this create began with, so it was not kept."+hold {
+ t.Fatalf("422: err = %v", err)
+ }
+ if out != "uploading shop.db (3B)\n" {
+ t.Fatalf("422: out %q", out)
+ }
+ // A 503 left the seed reserving: no hold line.
+ c = newSeedFileConsole()
+ c.uploadCode = http.StatusServiceUnavailable
+ c.uploadBody = `{"error":"could not store the upload. Try again."}`
+ _, err = runSeedFile(t, c, "abc")
+ if err == nil || err.Error() != "could not store the upload. Try again." {
+ t.Fatalf("503: err = %v", err)
+ }
+}
+
+func TestSeedFileEmptyOrTooLargeRefusedBeforeBegin(t *testing.T) {
+ c := newSeedFileConsole()
+ _, err := runSeedFile(t, c, "")
+ if err == nil || !strings.HasSuffix(err.Error(), "/shop.db must be more than 0 bytes and at most 4 GiB") || len(c.calls) != 0 {
+ t.Fatalf("empty: err %v calls %v", err, c.calls)
+ }
+ if err := seedFileSizeRefusal("big.db", seedFileMaxBytes+1); err == nil || err.Error() != "big.db must be more than 0 bytes and at most 4 GiB" {
+ t.Fatalf("large: %v", err)
+ }
+ if err := seedFileSizeRefusal("ok.db", seedFileMaxBytes); err != nil {
+ t.Fatalf("exactly 4 GiB: %v", err)
+ }
+}
+
+func TestSeedFileUnreadableRefusedBeforeBegin(t *testing.T) {
+ fakeSeedWait(t, 0)
+ c := newSeedFileConsole()
+ ts := httptest.NewServer(c)
+ defer ts.Close()
+ err := newTestSession(ts.URL).runSeedFileCreate(context.Background(), io.Discard, apiAcct{Seg: "bab"}, "shop", "new.example.com", "", "", "", "/nope/shop.db", "")
+ if err == nil || err.Error() != "could not read /nope/shop.db. Check the path, then try again." || len(c.calls) != 0 {
+ t.Fatalf("err %v calls %v", err, c.calls)
+ }
+}
+
+func TestSeedFileAndFromRefused(t *testing.T) {
+ tests := []struct {
+ name string
+ from, seedFile, kind, rol string
+ addr, restore bool
+ want string
+ }{
+ {"both", "a.example.com", "x.db", "", "", false, false, "use --seed-file or --from, not both"},
+ {"seed file with kind", "", "x.db", "static", "", false, false, "a seeded instance is an ordinary instance. Drop --kind, --addr and --role."},
+ {"from with role", "a.example.com", "", "", "replica", false, false, "a seeded instance is an ordinary instance. Drop --kind, --addr and --role."},
+ {"restore", "", "x.db", "", "", false, true, "a restore is a plain instance. Drop --seed-file."},
+ {"plain", "", "", "", "", false, false, ""},
+ {"seed file alone", "", "x.db", "", "", false, false, ""},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var got string
+ if tc.restore {
+ got = restoreRefusal(tc.seedFile)
+ } else {
+ got = seededFlagsRefusal(tc.from, tc.seedFile, tc.kind, tc.addr, tc.rol, "")
+ }
+ if got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+ if got := restoreRefusal(""); got != "a restore is a plain instance. Drop --from, --kind, --addr and --role." {
+ t.Fatalf("existing restore sentence changed: %q", got)
+ }
+}
+
+func TestSeedCellFileRows(t *testing.T) {
+ cell := func(state, reason string) string {
+ return seedCell(apiInstanceRecord{Seed: &apiSeed{Kind: "file", State: state, Reason: reason, SHA256: "3f2a9c1e0b7d55aa"}})
+ }
+ for _, tc := range []struct{ state, reason, want string }{
+ {"reserving", "", "seed file awaiting upload"},
+ {"ready", "", "seed file awaiting first start"},
+ {"placed", "", "seeded from a file 3f2a9c1e0b7d"},
+ {"aborted", "a copy of data already exists for this hostname", "not created: a copy of data already exists for this hostname"},
+ {"aborted", "", "aborting"},
+ {"rolled-back", "", "aborting"},
+ } {
+ if got := cell(tc.state, tc.reason); got != tc.want {
+ t.Errorf("%s/%q: %q, want %q", tc.state, tc.reason, got, tc.want)
+ }
+ }
+}
diff --git a/parity/parity.tsv b/parity/parity.tsv
index f504b790a..c0d2b7110 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -64,7 +64,7 @@ features-set config gap features set wp-settings The Features section prints t
# instances
instances-list instances both instances list GET /a/{sqid}/apps/{app}/instances ; GET /a/{sqid}/apps/{app}/instances/{host}
instances-enable instances gap instances enable wp-instances
-instances-create instances gap instances create [host, channel, environment, region, role, --from, --at, --restore] wp-instances The empty Running page prints the CLI command.
+instances-create instances gap instances create [host, channel, environment, region, role, --from, --seed-file, --at, --restore] wp-instances The empty Running page prints the CLI command.
instances-delete instances gap instances delete wp-instances
instances-set-channel instances gap instances set-channel wp-instances
instances-set-environment instances gap instances set-environment wp-instances