package adopt import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "strconv" "strings" "sync" "testing" "time" "amadan.net/oficina/alta/carlosop" ) // identity is the fixture's canonical identity, as Observe reads it. func (x *carlosFixture) identity(t *testing.T) Identity { t.Helper() snap, err := Observe(context.Background(), x.c, x.h, x.app) if err != nil { t.Fatalf("Observe: %v", err) } return snap.Identity } // dryRunRewriter puts a proxy in front of the fake console that edits the // routes of every dry-run answer from the restart door, as a console // that resolves a host more widely, or reports it hibernating, would. A // real request passes through untouched. The fixture's client is // replaced by one that speaks to the proxy. func (x *carlosFixture) dryRunRewriter(t *testing.T, edit func(routes []map[string]any) []map[string]any) { t.Helper() target, err := url.Parse(x.f.URL()) if err != nil { t.Fatal(err) } rp := httputil.NewSingleHostReverseProxy(target) rp.ModifyResponse = func(resp *http.Response) error { if !strings.HasSuffix(resp.Request.URL.Path, "/restart/scope") || resp.StatusCode != 200 { return nil } raw, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { return err } var answer map[string]any if err := json.Unmarshal(raw, &answer); err != nil { return err } if answer["dry_run"] == true { var routes []map[string]any for _, r := range answer["routes"].([]any) { routes = append(routes, r.(map[string]any)) } answer["routes"] = edit(routes) if raw, err = json.Marshal(answer); err != nil { return err } } resp.Body = io.NopCloser(bytes.NewReader(raw)) resp.ContentLength = int64(len(raw)) resp.Header.Set("Content-Length", strconv.Itoa(len(raw))) return nil } srv := httptest.NewServer(rp) t.Cleanup(srv.Close) x.c = carlosop.New(srv.URL, fixtureAccount, x.f.Token()) t.Cleanup(x.c.Close) } // noRestarts fails unless the fake saw no restart of any of hosts and no // app-wide restart. func (x *carlosFixture) noRestarts(t *testing.T, hosts ...string) { t.Helper() for _, h := range hosts { if n := x.f.RestartCount(h); n != 0 { t.Fatalf("%s restarted %d times", h, n) } } if n := x.f.AppWideRestarts(); n != 0 { t.Fatalf("app-wide restarts = %d", n) } } // fastPolls shortens RestartAndWait's poll interval and limit for a test. func fastPolls(t *testing.T, every, limit time.Duration) { t.Helper() oldEvery, oldLimit := pollEvery, pollLimit pollEvery, pollLimit = every, limit t.Cleanup(func() { pollEvery, pollLimit = oldEvery, oldLimit }) } func TestRestartAndWaitPollsEveryFiveSecondsForFiveMinutes(t *testing.T) { if pollEvery != 5*time.Second || pollLimit != 5*time.Minute { t.Fatalf("poll every %v for %v", pollEvery, pollLimit) } } func TestRestartCanonicalLeavesOtherInstancesUntouched(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("staging.docs.example", "staging") x.neighbour("bare.docs.example", "") id := x.identity(t) if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil { t.Fatalf("RestartCanonical: %v", err) } if n := x.f.RestartCount(docsRoute); n != 1 { t.Fatalf("canonical host restarted %d times, want 1", n) } x.noRestarts(t, "staging.docs.example", "bare.docs.example") // The dry run comes first, then the one real request. var doors []string for _, r := range x.f.Requests() { if strings.Contains(r, "restart") { doors = append(doors, r) } } if len(doors) != 2 { t.Fatalf("restart requests %q, want a dry run then the request", doors) } } func TestRestartCanonicalDryRunRestartsNothing(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) if err := RestartCanonical(context.Background(), x.c, x.app, id, false); err != nil { t.Fatalf("RestartCanonical dry run: %v", err) } x.noRestarts(t, docsRoute) } func TestRestartCanonicalRefusesWiderDryRun(t *testing.T) { cases := map[string]struct { edit func([]map[string]any) []map[string]any code string }{ "neighbour added": {func(r []map[string]any) []map[string]any { return append(r, map[string]any{"host": "staging.docs.example", "environment": "staging", "hibernate": false}) }, "restart-scope-2"}, "nothing resolved": {func([]map[string]any) []map[string]any { return []map[string]any{} }, "restart-scope-0"}, "another host": {func([]map[string]any) []map[string]any { return []map[string]any{{"host": "staging.docs.example", "hibernate": false}} }, "restart-scope-1"}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("staging.docs.example", "staging") id := x.identity(t) x.dryRunRewriter(t, tc.edit) err := RestartCanonical(context.Background(), x.c, x.app, id, true) if err == nil || err.Error() != tc.code { t.Fatalf("err = %v, want %s", err, tc.code) } x.noRestarts(t, docsRoute, "staging.docs.example") }) } } // A hibernating canonical route is accepted: the probe wakes it, and // Delivered must still pass. func TestRestartCanonicalAcceptsHibernatingRoute(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) x.dryRunRewriter(t, func(r []map[string]any) []map[string]any { r[0]["hibernate"] = true return r }) if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil { t.Fatalf("RestartCanonical: %v", err) } if n := x.f.RestartCount(docsRoute); n != 1 { t.Fatalf("restarted %d times", n) } } func TestRestartCanonicalFailsClosedOnOldConsole(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("staging.docs.example", "staging") id := x.identity(t) x.f.NoScopedRestart() err := RestartCanonical(context.Background(), x.c, x.app, id, true) if !errors.Is(err, carlosop.ErrNoScopedRestart) { t.Fatalf("err = %v, want ErrNoScopedRestart", err) } x.noRestarts(t, docsRoute, "staging.docs.example") for _, r := range x.f.Requests() { if strings.HasSuffix(r, " /restart") { t.Fatalf("fell back to the app-wide door: %q", r) } } } func TestRestartCanonicalStopsOnUnavailableRegistry(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) x.f.FailRestart(http.StatusServiceUnavailable) err := RestartCanonical(context.Background(), x.c, x.app, id, true) var se *carlosop.StatusError if !errors.As(err, &se) || se.Code != http.StatusServiceUnavailable { t.Fatalf("err = %v, want a 503 status error", err) } x.noRestarts(t, docsRoute) } // The saved identity is only what was true when it was saved. The claim // is read again before a restart, and one that no longer binds the // canonical domain to that record restarts nothing, on either record. func TestRestartCanonicalRefusesAMovedClaim(t *testing.T) { const other = "docs-2.bds.oncarlos.com" cases := map[string]struct { edit func(x *carlosFixture) want string }{ "re-pointed": {func(x *carlosFixture) { in := fixtureInstance(x.app) in.Host = other x.f.AddInstance(in) x.f.AttachDomain("docs", "docs.oficina.works", other, "live") }, "restart-binding-changed"}, "detached": {func(x *carlosFixture) { x.f.DetachDomain("docs", "docs.oficina.works") }, "restart-binding-domain-missing"}, "route to a missing record": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", "gone-docs.bds.oncarlos.com", "live") }, "restart-binding-instance-missing"}, } for name, tc := range cases { for _, apply := range []bool{false, true} { t.Run(fmt.Sprintf("%s apply=%v", name, apply), func(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) tc.edit(x) err := RestartCanonical(context.Background(), x.c, x.app, id, apply) if err == nil || !strings.Contains(err.Error(), tc.want) { t.Fatalf("err = %v, want %s", err, tc.want) } x.noRestarts(t, docsRoute, other) }) } } } // The claim moving after the dry run, the last moment before the restart, // is still caught. func TestRestartCanonicalReadsTheClaimAfterTheDryRun(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) x.f.DuringDryRun = func(string) { x.f.DetachDomain("docs", "docs.oficina.works") } err := RestartCanonical(context.Background(), x.c, x.app, id, true) if err == nil || !strings.Contains(err.Error(), "restart-binding-domain-missing") { t.Fatalf("err = %v", err) } x.noRestarts(t, docsRoute) } // A claim that cannot be read is not a claim that held. func TestRestartCanonicalRefusesAnUnreadableClaim(t *testing.T) { for _, door := range []string{"/domains", "/instances"} { t.Run(door, func(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) x.f.FailRead(door, http.StatusBadGateway) if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err == nil { t.Fatal("restarted without reading the claim") } x.noRestarts(t, docsRoute) }) } } // A claim merely not live still binds the same record: a rollback has to // be able to restart it. func TestRestartCanonicalAllowsAnUnchangedClaimNotLive(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "checking") if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil { t.Fatalf("RestartCanonical: %v", err) } if n := x.f.RestartCount(docsRoute); n != 1 { t.Fatalf("restarts = %d", n) } } func TestRestartCanonicalRefusesAnotherAppsIdentity(t *testing.T) { x := newCarlosFixture(t, "docs") id := x.identity(t) cases := map[string]func(*Identity){ "no host": func(i *Identity) { i.RecordHost, i.Route = "", "" }, "other host": func(i *Identity) { i.RecordHost = "staging.docs.example" }, // The canonical domain's claim, but for another record. "other route": func(i *Identity) { i.Route = "staging.docs.example" }, "other domain": func(i *Identity) { i.Domain = "staging.docs.oficina.works" }, "other app": func(i *Identity) { i.App = "sheets" }, } for name, mutate := range cases { t.Run(name, func(t *testing.T) { bad := id mutate(&bad) if err := RestartCanonical(context.Background(), x.c, x.app, bad, true); err == nil { t.Fatal("restarted for an identity that is not the canonical host's") } }) } x.noRestarts(t, docsRoute) for _, r := range x.f.Requests() { if strings.Contains(r, "restart") { t.Fatalf("sent %q for a refused identity", r) } } } func TestRestartAndWaitReturnsOnceUntilPasses(t *testing.T) { fastPolls(t, 5*time.Millisecond, 2*time.Second) x := newCarlosFixture(t, "docs") id := x.identity(t) calls := 0 until := func(d Delivery) error { calls++ if calls < 3 { return errors.New("adopt: not yet") } return nil } d, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true) if err != nil { t.Fatalf("RestartAndWait: %v", err) } if calls != 3 || d.Version != valueVersion || d.Health != 200 { t.Fatalf("calls %d delivery %+v", calls, d.Health) } if n := x.f.RestartCount(docsRoute); n != 1 { t.Fatalf("restarted %d times", n) } } func TestRestartAndWaitTimesOut(t *testing.T) { fastPolls(t, 10*time.Millisecond, 120*time.Millisecond) x := newCarlosFixture(t, "docs") id := x.identity(t) before := x.site.delivery(t, x) // The operations door never becomes agent-shaped. until := func(d Delivery) error { return Delivered(x.app, before, d) } start := time.Now() _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true) if err == nil || !strings.Contains(err.Error(), "restart-timeout") { t.Fatalf("err = %v, want restart-timeout", err) } if !strings.Contains(err.Error(), "the delegated-access door is not answering") { t.Fatalf("err = %v, want the last reason", err) } if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { t.Fatalf("err = %v: the limit read as the caller's context", err) } if el := time.Since(start); el > 2*time.Second { t.Fatalf("waited %v past a 120ms limit", el) } if n := x.f.RestartCount(docsRoute); n != 1 { t.Fatalf("restarted %d times, want 1", n) } } // A probe whose answer never comes is cut off at the limit: the stalled // request is cancelled, and the run stops with restart-timeout well // before the probe client's own 10 s timeout. func TestRestartAndWaitCutsOffStalledProbeAtLimit(t *testing.T) { fastPolls(t, 10*time.Millisecond, 150*time.Millisecond) x := newCarlosFixture(t, "docs") id := x.identity(t) cancelled := make(chan struct{}) var once sync.Once h := clientFor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() once.Do(func() { close(cancelled) }) })) start := time.Now() _, err := RestartAndWait(context.Background(), x.c, h, x.app, id, func(Delivery) error { return nil }, true) if el := time.Since(start); el > 2*time.Second { t.Fatalf("a stalled probe held the wait %v past a 150ms limit", el) } if err == nil || !strings.Contains(err.Error(), "restart-timeout") { t.Fatalf("err = %v, want restart-timeout", err) } if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { t.Fatalf("err = %v: the limit read as the caller's context", err) } // The probe the limit cut off is not reported as the app's failure. if !strings.Contains(err.Error(), "the app was not probed") { t.Fatalf("err = %v, want the reason from before the cut-off", err) } select { case <-cancelled: case <-time.After(2 * time.Second): t.Fatal("the stalled request was never cancelled") } } // clientFor is an http.Client whose every https origin lands on handler. func clientFor(t *testing.T, handler http.Handler) *http.Client { t.Helper() srv := httptest.NewTLSServer(handler) t.Cleanup(srv.Close) tr := srv.Client().Transport.(*http.Transport).Clone() addr := srv.Listener.Addr().String() tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, network, addr) } tr.TLSClientConfig.ServerName = "example.com" t.Cleanup(tr.CloseIdleConnections) return &http.Client{Transport: tr, Timeout: 10 * time.Second} } func TestRestartAndWaitKeepsPollingThroughUnreachable(t *testing.T) { fastPolls(t, 5*time.Millisecond, 2*time.Second) x := newCarlosFixture(t, "docs") id := x.identity(t) probes := 0 h := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.URL.Path == "/api/version" { probes++ } if probes <= 2 { return nil, errors.New("connection refused") } return x.h.Transport.RoundTrip(r) })} d, err := RestartAndWait(context.Background(), x.c, h, x.app, id, func(Delivery) error { return nil }, true) if err != nil || d.Version != valueVersion { t.Fatalf("RestartAndWait: %v", err) } } func TestRestartAndWaitStopsOnCancel(t *testing.T) { fastPolls(t, 10*time.Millisecond, time.Minute) x := newCarlosFixture(t, "docs") id := x.identity(t) ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() start := time.Now() _, err := RestartAndWait(ctx, x.c, x.h, x.app, id, func(Delivery) error { return errors.New("adopt: never") }, true) if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("err = %v, want the context's", err) } if strings.Contains(err.Error(), "restart-timeout") { t.Fatalf("err = %v: the caller's cancellation read as the limit", err) } if time.Since(start) > 5*time.Second { t.Fatal("ignored the context") } } func TestRestartAndWaitDryRunRestartsAndWaitsForNothing(t *testing.T) { fastPolls(t, time.Hour, time.Hour) x := newCarlosFixture(t, "docs") id := x.identity(t) called := false d, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, func(Delivery) error { called = true; return errors.New("x") }, false) if err != nil { t.Fatalf("dry run: %v", err) } if called || d.Version != valueVersion { t.Fatalf("dry run evaluated until (%v) or did not probe", called) } x.noRestarts(t, docsRoute) } func TestRestartAndWaitDoesNotWaitWhenRestartRefused(t *testing.T) { fastPolls(t, time.Hour, time.Hour) x := newCarlosFixture(t, "docs") id := x.identity(t) x.f.NoScopedRestart() _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, func(Delivery) error { return nil }, true) if !errors.Is(err, carlosop.ErrNoScopedRestart) { t.Fatalf("err = %v", err) } } type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } // delivery probes the fixture's site as it stands. func (s *site) delivery(t *testing.T, x *carlosFixture) Delivery { t.Helper() d, err := Probe(context.Background(), x.h, "https://docs.oficina.works") if err != nil { t.Fatalf("Probe: %v", err) } return d } // A success that is only reached after the limit does not count: here the // classification itself finishes past the deadline. func TestRestartAndWaitRefusesSuccessAfterLimit(t *testing.T) { fastPolls(t, 10*time.Millisecond, 100*time.Millisecond) x := newCarlosFixture(t, "docs") id := x.identity(t) until := func(Delivery) error { time.Sleep(200 * time.Millisecond) return nil } _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true) if err == nil || !strings.Contains(err.Error(), "restart-timeout") { t.Fatalf("err = %v, want restart-timeout for a success after the limit", err) } if !strings.Contains(err.Error(), "only after the limit") { t.Fatalf("err = %v, want it to say the success came after the limit", err) } if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { t.Fatalf("err = %v: the limit read as the caller's context", err) } }