package main import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "strings" "sync/atomic" "testing" "time" ) func TestSeedCell(t *testing.T) { for _, c := range []struct { seed *apiSeed want string }{ {nil, "-"}, {&apiSeed{Kind: "replica", State: "reserving", From: "www.example.com"}, "copying from www.example.com"}, {&apiSeed{Kind: "replica", State: "ready", From: "www.example.com", TXID: "4211"}, "seeded from www.example.com at txid 4211"}, {&apiSeed{Kind: "replica", State: "placed", From: "www.example.com", TXID: "4211"}, "seeded from www.example.com at txid 4211"}, {&apiSeed{Kind: "import", State: "awaiting-upload"}, "import awaiting upload"}, {&apiSeed{Kind: "import", State: "uploaded"}, "awaiting stop"}, {&apiSeed{Kind: "import", State: "ready"}, "awaiting stop"}, {&apiSeed{Kind: "import", State: "swapped"}, "swapped, awaiting verify"}, {&apiSeed{Kind: "import", State: "committed", SHA256: "0123456789abcdef0123"}, "imported 0123456789ab"}, {&apiSeed{Kind: "import", State: "refused", Reason: "the route belongs to app kass"}, "refused: the route belongs to app kass"}, {&apiSeed{Kind: "import", State: "aborted"}, "aborting"}, {&apiSeed{Kind: "replica", State: "rolled-back"}, "aborting"}, } { if got := seedCell(apiInstanceRecord{Seed: c.seed}); got != c.want { t.Errorf("seedCell(%+v) = %q, want %q", c.seed, got, c.want) } } } func TestInstanceCreateFromSendsTheSource(t *testing.T) { var body map[string]any ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(r.Body) _ = json.Unmarshal(raw, &body) w.WriteHeader(http.StatusAccepted) w.Write([]byte(`{"host":"canary.example.com","channel":"stable","seed":{"id":"sd_x","kind":"replica","from":"www.example.com","state":"reserving"}}`)) })) defer ts.Close() rec, accepted, err := newTestSession(ts.URL).instanceCreateFrom(context.Background(), apiAcct{Seg: "bab"}, "shop", "canary.example.com", "", "", "", "www.example.com", 4200) if err != nil { t.Fatal(err) } from, _ := body["from"].(map[string]any) if from["host"] != "www.example.com" || from["txid"] != float64(4200) || body["host"] != "canary.example.com" { t.Fatalf("body = %v", body) } if !accepted || rec.Seed == nil || rec.Seed.State != "reserving" { t.Fatalf("accepted = %v, record = %+v", accepted, rec) } } // seedConsole is a console whose create answers 202 and whose record then // walks through the given GET answers, one per look. type seedConsole struct { createStatus int createBody string gets []func(w http.ResponseWriter) looks atomic.Int32 } func (c *seedConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { w.WriteHeader(c.createStatus) io.WriteString(w, c.createBody) return } i := int(c.looks.Add(1)) - 1 if i >= len(c.gets) { i = len(c.gets) - 1 } c.gets[i](w) } func seedRecord(state, reason string) func(w http.ResponseWriter) { return func(w http.ResponseWriter) { fmt.Fprintf(w, `{"host":"canary.example.com","channel":"stable","environment":"canary-env","seed":{"id":"sd_x","kind":"replica","from":"www.example.com","txid":"4211","state":%q,"reason":%q}}`, state, reason) } } func answerWith(code int, body string) func(w http.ResponseWriter) { return func(w http.ResponseWriter) { w.WriteHeader(code) io.WriteString(w, body) } } const reservingBody = `{"host":"canary.example.com","channel":"stable","region_name":"Ireland","seed":{"id":"sd_x","kind":"replica","from":"www.example.com","state":"reserving"}}` // runSeeded runs a --from create against c with the wait faked, returning // the output, the error and the sleeps taken. func runSeeded(t *testing.T, c *seedConsole) (string, error, []time.Duration) { t.Helper() ts := httptest.NewServer(c) defer ts.Close() var waits []time.Duration oldWait, oldEvery := seedWait, seedPollEvery seedWait = func(ctx context.Context, d time.Duration) error { waits = append(waits, d); return ctx.Err() } seedPollEvery = 2 * time.Second defer func() { seedWait, seedPollEvery = oldWait, oldEvery }() var out bytes.Buffer err := newTestSession(ts.URL).runSeededCreate(context.Background(), &out, apiAcct{Seg: "bab"}, "shop", "canary.example.com", "", "", "", "www.example.com", 0, "") return out.String(), err, waits } func TestSeededCreateFollowsTheRecordToReady(t *testing.T) { out, err, waits := runSeeded(t, &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){seedRecord("reserving", ""), seedRecord("reserving", ""), seedRecord("ready", "")}}) if err != nil { t.Fatal(err) } if !strings.HasPrefix(out, "copying www.example.com into canary.example.com. A large database can take several minutes.\ncreated instance canary.example.com") || !strings.Contains(out, "seeded from www.example.com at txid 4211") || !strings.Contains(out, "the host comes live on the next reconcile pass on its box") { t.Fatalf("output = %q", out) } if len(waits) != 3 || waits[0] != 2*time.Second { t.Fatalf("waits = %v, want three waits of 2s", waits) } } func TestSeededCreateAbortedReturnsTheReason(t *testing.T) { const reason = "copying www.example.com took longer than 30 minutes, so no instance was created." out, err, _ := runSeeded(t, &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){seedRecord("reserving", ""), seedRecord("aborted", reason)}}) if err == nil || err.Error() != reason { t.Fatalf("err = %v, want exactly %q", err, reason) } if strings.Contains(out, "created instance") { t.Fatalf("output = %q", out) } } func TestSeededCreateAbortedWithoutAReasonNamesTheSource(t *testing.T) { _, err, _ := runSeeded(t, &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){seedRecord("aborted", "")}}) if err == nil || err.Error() != "could not copy www.example.com. Nothing was created. Try again." { t.Fatalf("err = %v", err) } } func TestSeededCreateRefusalPrintsLikeAnyCreateRefusal(t *testing.T) { out, err, waits := runSeeded(t, &seedConsole{createStatus: 409, createBody: `{"error":"instance canary.example.com already exists"}`}) if err == nil || err.Error() != "instance canary.example.com already exists" { t.Fatalf("err = %v", err) } if out != "" || len(waits) != 0 { t.Fatalf("a refusal says nothing and waits for nothing: out = %q, waits = %v", out, waits) } } func TestSeededCreateRetriesATransientPollError(t *testing.T) { out, err, waits := runSeeded(t, &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){answerWith(502, `{"error":"could not read the instance"}`), answerWith(503, ""), seedRecord("reserving", ""), answerWith(502, ""), seedRecord("placed", "")}}) if err != nil { t.Fatal(err) } if !strings.Contains(out, "created instance canary.example.com") || len(waits) != 5 { t.Fatalf("out = %q, waits = %v", out, waits) } } func TestSeededCreateGivesUpAfterFiveFailedLooks(t *testing.T) { c := &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){answerWith(502, `{"error":"could not read the instance"}`)}} _, err, _ := runSeeded(t, c) if err == nil || err.Error() != "could not read the instance" { t.Fatalf("err = %v", err) } if n := c.looks.Load(); n != 5 { t.Fatalf("looks = %d, want 5", n) } } func TestSeededCreateFailedLooksMustBeConsecutive(t *testing.T) { bad := answerWith(502, "") _, err, _ := runSeeded(t, &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){bad, bad, bad, bad, seedRecord("reserving", ""), bad, bad, bad, bad, seedRecord("ready", "")}}) if err != nil { t.Fatalf("four failures, a good look, four more: err = %v", err) } } func TestSeededCreateAMissingRecordEndsAtOnce(t *testing.T) { c := &seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){answerWith(404, "")}} _, err, _ := runSeeded(t, c) if err == nil || err.Error() != notFoundErr().Error() || c.looks.Load() != 1 { t.Fatalf("err = %v, looks = %d", err, c.looks.Load()) } } func TestSeededCreateStopsWhenTheContextEnds(t *testing.T) { ts := httptest.NewServer(&seedConsole{createStatus: 202, createBody: reservingBody, gets: []func(http.ResponseWriter){seedRecord("reserving", "")}}) defer ts.Close() ctx, cancel := context.WithCancel(context.Background()) oldWait := seedWait seedWait = func(ctx context.Context, d time.Duration) error { cancel(); return ctx.Err() } defer func() { seedWait = oldWait }() err := newTestSession(ts.URL).runSeededCreate(ctx, io.Discard, apiAcct{Seg: "bab"}, "shop", "canary.example.com", "", "", "", "www.example.com", 0, "") if !errors.Is(err, context.Canceled) { t.Fatalf("err = %v", err) } }