oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package adopt
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net"
11 "net/http"
12 "net/http/httptest"
13 "net/http/httputil"
14 "net/url"
15 "strconv"
16 "strings"
17 "sync"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/alta/carlosop"
22)
23
24// identity is the fixture's canonical identity, as Observe reads it.
25func (x *carlosFixture) identity(t *testing.T) Identity {
26 t.Helper()
27 snap, err := Observe(context.Background(), x.c, x.h, x.app)
28 if err != nil {
29 t.Fatalf("Observe: %v", err)
30 }
31 return snap.Identity
32}
33
34// dryRunRewriter puts a proxy in front of the fake console that edits the
35// routes of every dry-run answer from the restart door, as a console
36// that resolves a host more widely, or reports it hibernating, would. A
37// real request passes through untouched. The fixture's client is
38// replaced by one that speaks to the proxy.
39func (x *carlosFixture) dryRunRewriter(t *testing.T, edit func(routes []map[string]any) []map[string]any) {
40 t.Helper()
41 target, err := url.Parse(x.f.URL())
42 if err != nil {
43 t.Fatal(err)
44 }
45 rp := httputil.NewSingleHostReverseProxy(target)
46 rp.ModifyResponse = func(resp *http.Response) error {
47 if !strings.HasSuffix(resp.Request.URL.Path, "/restart/scope") || resp.StatusCode != 200 {
48 return nil
49 }
50 raw, err := io.ReadAll(resp.Body)
51 resp.Body.Close()
52 if err != nil {
53 return err
54 }
55 var answer map[string]any
56 if err := json.Unmarshal(raw, &answer); err != nil {
57 return err
58 }
59 if answer["dry_run"] == true {
60 var routes []map[string]any
61 for _, r := range answer["routes"].([]any) {
62 routes = append(routes, r.(map[string]any))
63 }
64 answer["routes"] = edit(routes)
65 if raw, err = json.Marshal(answer); err != nil {
66 return err
67 }
68 }
69 resp.Body = io.NopCloser(bytes.NewReader(raw))
70 resp.ContentLength = int64(len(raw))
71 resp.Header.Set("Content-Length", strconv.Itoa(len(raw)))
72 return nil
73 }
74 srv := httptest.NewServer(rp)
75 t.Cleanup(srv.Close)
76 x.c = carlosop.New(srv.URL, fixtureAccount, x.f.Token())
77 t.Cleanup(x.c.Close)
78}
79
80// noRestarts fails unless the fake saw no restart of any of hosts and no
81// app-wide restart.
82func (x *carlosFixture) noRestarts(t *testing.T, hosts ...string) {
83 t.Helper()
84 for _, h := range hosts {
85 if n := x.f.RestartCount(h); n != 0 {
86 t.Fatalf("%s restarted %d times", h, n)
87 }
88 }
89 if n := x.f.AppWideRestarts(); n != 0 {
90 t.Fatalf("app-wide restarts = %d", n)
91 }
92}
93
94// fastPolls shortens RestartAndWait's poll interval and limit for a test.
95func fastPolls(t *testing.T, every, limit time.Duration) {
96 t.Helper()
97 oldEvery, oldLimit := pollEvery, pollLimit
98 pollEvery, pollLimit = every, limit
99 t.Cleanup(func() { pollEvery, pollLimit = oldEvery, oldLimit })
100}
101
102func TestRestartAndWaitPollsEveryFiveSecondsForFiveMinutes(t *testing.T) {
103 if pollEvery != 5*time.Second || pollLimit != 5*time.Minute {
104 t.Fatalf("poll every %v for %v", pollEvery, pollLimit)
105 }
106}
107
108func TestRestartCanonicalLeavesOtherInstancesUntouched(t *testing.T) {
109 x := newCarlosFixture(t, "docs")
110 x.neighbour("staging.docs.example", "staging")
111 x.neighbour("bare.docs.example", "")
112 id := x.identity(t)
113 if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil {
114 t.Fatalf("RestartCanonical: %v", err)
115 }
116 if n := x.f.RestartCount(docsRoute); n != 1 {
117 t.Fatalf("canonical host restarted %d times, want 1", n)
118 }
119 x.noRestarts(t, "staging.docs.example", "bare.docs.example")
120 // The dry run comes first, then the one real request.
121 var doors []string
122 for _, r := range x.f.Requests() {
123 if strings.Contains(r, "restart") {
124 doors = append(doors, r)
125 }
126 }
127 if len(doors) != 2 {
128 t.Fatalf("restart requests %q, want a dry run then the request", doors)
129 }
130}
131
132func TestRestartCanonicalDryRunRestartsNothing(t *testing.T) {
133 x := newCarlosFixture(t, "docs")
134 id := x.identity(t)
135 if err := RestartCanonical(context.Background(), x.c, x.app, id, false); err != nil {
136 t.Fatalf("RestartCanonical dry run: %v", err)
137 }
138 x.noRestarts(t, docsRoute)
139}
140
141func TestRestartCanonicalRefusesWiderDryRun(t *testing.T) {
142 cases := map[string]struct {
143 edit func([]map[string]any) []map[string]any
144 code string
145 }{
146 "neighbour added": {func(r []map[string]any) []map[string]any {
147 return append(r, map[string]any{"host": "staging.docs.example", "environment": "staging", "hibernate": false})
148 }, "restart-scope-2"},
149 "nothing resolved": {func([]map[string]any) []map[string]any { return []map[string]any{} }, "restart-scope-0"},
150 "another host": {func([]map[string]any) []map[string]any {
151 return []map[string]any{{"host": "staging.docs.example", "hibernate": false}}
152 }, "restart-scope-1"},
153 }
154 for name, tc := range cases {
155 t.Run(name, func(t *testing.T) {
156 x := newCarlosFixture(t, "docs")
157 x.neighbour("staging.docs.example", "staging")
158 id := x.identity(t)
159 x.dryRunRewriter(t, tc.edit)
160 err := RestartCanonical(context.Background(), x.c, x.app, id, true)
161 if err == nil || err.Error() != tc.code {
162 t.Fatalf("err = %v, want %s", err, tc.code)
163 }
164 x.noRestarts(t, docsRoute, "staging.docs.example")
165 })
166 }
167}
168
169// A hibernating canonical route is accepted: the probe wakes it, and
170// Delivered must still pass.
171func TestRestartCanonicalAcceptsHibernatingRoute(t *testing.T) {
172 x := newCarlosFixture(t, "docs")
173 id := x.identity(t)
174 x.dryRunRewriter(t, func(r []map[string]any) []map[string]any {
175 r[0]["hibernate"] = true
176 return r
177 })
178 if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil {
179 t.Fatalf("RestartCanonical: %v", err)
180 }
181 if n := x.f.RestartCount(docsRoute); n != 1 {
182 t.Fatalf("restarted %d times", n)
183 }
184}
185
186func TestRestartCanonicalFailsClosedOnOldConsole(t *testing.T) {
187 x := newCarlosFixture(t, "docs")
188 x.neighbour("staging.docs.example", "staging")
189 id := x.identity(t)
190 x.f.NoScopedRestart()
191 err := RestartCanonical(context.Background(), x.c, x.app, id, true)
192 if !errors.Is(err, carlosop.ErrNoScopedRestart) {
193 t.Fatalf("err = %v, want ErrNoScopedRestart", err)
194 }
195 x.noRestarts(t, docsRoute, "staging.docs.example")
196 for _, r := range x.f.Requests() {
197 if strings.HasSuffix(r, " /restart") {
198 t.Fatalf("fell back to the app-wide door: %q", r)
199 }
200 }
201}
202
203func TestRestartCanonicalStopsOnUnavailableRegistry(t *testing.T) {
204 x := newCarlosFixture(t, "docs")
205 id := x.identity(t)
206 x.f.FailRestart(http.StatusServiceUnavailable)
207 err := RestartCanonical(context.Background(), x.c, x.app, id, true)
208 var se *carlosop.StatusError
209 if !errors.As(err, &se) || se.Code != http.StatusServiceUnavailable {
210 t.Fatalf("err = %v, want a 503 status error", err)
211 }
212 x.noRestarts(t, docsRoute)
213}
214
215// The saved identity is only what was true when it was saved. The claim
216// is read again before a restart, and one that no longer binds the
217// canonical domain to that record restarts nothing, on either record.
218func TestRestartCanonicalRefusesAMovedClaim(t *testing.T) {
219 const other = "docs-2.bds.oncarlos.com"
220 cases := map[string]struct {
221 edit func(x *carlosFixture)
222 want string
223 }{
224 "re-pointed": {func(x *carlosFixture) {
225 in := fixtureInstance(x.app)
226 in.Host = other
227 x.f.AddInstance(in)
228 x.f.AttachDomain("docs", "docs.oficina.works", other, "live")
229 }, "restart-binding-changed"},
230 "detached": {func(x *carlosFixture) { x.f.DetachDomain("docs", "docs.oficina.works") }, "restart-binding-domain-missing"},
231 "route to a missing record": {func(x *carlosFixture) {
232 x.f.AttachDomain("docs", "docs.oficina.works", "gone-docs.bds.oncarlos.com", "live")
233 }, "restart-binding-instance-missing"},
234 }
235 for name, tc := range cases {
236 for _, apply := range []bool{false, true} {
237 t.Run(fmt.Sprintf("%s apply=%v", name, apply), func(t *testing.T) {
238 x := newCarlosFixture(t, "docs")
239 id := x.identity(t)
240 tc.edit(x)
241 err := RestartCanonical(context.Background(), x.c, x.app, id, apply)
242 if err == nil || !strings.Contains(err.Error(), tc.want) {
243 t.Fatalf("err = %v, want %s", err, tc.want)
244 }
245 x.noRestarts(t, docsRoute, other)
246 })
247 }
248 }
249}
250
251// The claim moving after the dry run, the last moment before the restart,
252// is still caught.
253func TestRestartCanonicalReadsTheClaimAfterTheDryRun(t *testing.T) {
254 x := newCarlosFixture(t, "docs")
255 id := x.identity(t)
256 x.f.DuringDryRun = func(string) { x.f.DetachDomain("docs", "docs.oficina.works") }
257 err := RestartCanonical(context.Background(), x.c, x.app, id, true)
258 if err == nil || !strings.Contains(err.Error(), "restart-binding-domain-missing") {
259 t.Fatalf("err = %v", err)
260 }
261 x.noRestarts(t, docsRoute)
262}
263
264// A claim that cannot be read is not a claim that held.
265func TestRestartCanonicalRefusesAnUnreadableClaim(t *testing.T) {
266 for _, door := range []string{"/domains", "/instances"} {
267 t.Run(door, func(t *testing.T) {
268 x := newCarlosFixture(t, "docs")
269 id := x.identity(t)
270 x.f.FailRead(door, http.StatusBadGateway)
271 if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err == nil {
272 t.Fatal("restarted without reading the claim")
273 }
274 x.noRestarts(t, docsRoute)
275 })
276 }
277}
278
279// A claim merely not live still binds the same record: a rollback has to
280// be able to restart it.
281func TestRestartCanonicalAllowsAnUnchangedClaimNotLive(t *testing.T) {
282 x := newCarlosFixture(t, "docs")
283 id := x.identity(t)
284 x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "checking")
285 if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil {
286 t.Fatalf("RestartCanonical: %v", err)
287 }
288 if n := x.f.RestartCount(docsRoute); n != 1 {
289 t.Fatalf("restarts = %d", n)
290 }
291}
292
293func TestRestartCanonicalRefusesAnotherAppsIdentity(t *testing.T) {
294 x := newCarlosFixture(t, "docs")
295 id := x.identity(t)
296 cases := map[string]func(*Identity){
297 "no host": func(i *Identity) { i.RecordHost, i.Route = "", "" },
298 "other host": func(i *Identity) { i.RecordHost = "staging.docs.example" },
299 // The canonical domain's claim, but for another record.
300 "other route": func(i *Identity) { i.Route = "staging.docs.example" },
301 "other domain": func(i *Identity) { i.Domain = "staging.docs.oficina.works" },
302 "other app": func(i *Identity) { i.App = "sheets" },
303 }
304 for name, mutate := range cases {
305 t.Run(name, func(t *testing.T) {
306 bad := id
307 mutate(&bad)
308 if err := RestartCanonical(context.Background(), x.c, x.app, bad, true); err == nil {
309 t.Fatal("restarted for an identity that is not the canonical host's")
310 }
311 })
312 }
313 x.noRestarts(t, docsRoute)
314 for _, r := range x.f.Requests() {
315 if strings.Contains(r, "restart") {
316 t.Fatalf("sent %q for a refused identity", r)
317 }
318 }
319}
320
321func TestRestartAndWaitReturnsOnceUntilPasses(t *testing.T) {
322 fastPolls(t, 5*time.Millisecond, 2*time.Second)
323 x := newCarlosFixture(t, "docs")
324 id := x.identity(t)
325 calls := 0
326 until := func(d Delivery) error {
327 calls++
328 if calls < 3 {
329 return errors.New("adopt: not yet")
330 }
331 return nil
332 }
333 d, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true)
334 if err != nil {
335 t.Fatalf("RestartAndWait: %v", err)
336 }
337 if calls != 3 || d.Version != valueVersion || d.Health != 200 {
338 t.Fatalf("calls %d delivery %+v", calls, d.Health)
339 }
340 if n := x.f.RestartCount(docsRoute); n != 1 {
341 t.Fatalf("restarted %d times", n)
342 }
343}
344
345func TestRestartAndWaitTimesOut(t *testing.T) {
346 fastPolls(t, 10*time.Millisecond, 120*time.Millisecond)
347 x := newCarlosFixture(t, "docs")
348 id := x.identity(t)
349 before := x.site.delivery(t, x)
350 // The operations door never becomes agent-shaped.
351 until := func(d Delivery) error { return Delivered(x.app, before, d) }
352 start := time.Now()
353 _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true)
354 if err == nil || !strings.Contains(err.Error(), "restart-timeout") {
355 t.Fatalf("err = %v, want restart-timeout", err)
356 }
357 if !strings.Contains(err.Error(), "the delegated-access door is not answering") {
358 t.Fatalf("err = %v, want the last reason", err)
359 }
360 if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
361 t.Fatalf("err = %v: the limit read as the caller's context", err)
362 }
363 if el := time.Since(start); el > 2*time.Second {
364 t.Fatalf("waited %v past a 120ms limit", el)
365 }
366 if n := x.f.RestartCount(docsRoute); n != 1 {
367 t.Fatalf("restarted %d times, want 1", n)
368 }
369}
370
371// A probe whose answer never comes is cut off at the limit: the stalled
372// request is cancelled, and the run stops with restart-timeout well
373// before the probe client's own 10 s timeout.
374func TestRestartAndWaitCutsOffStalledProbeAtLimit(t *testing.T) {
375 fastPolls(t, 10*time.Millisecond, 150*time.Millisecond)
376 x := newCarlosFixture(t, "docs")
377 id := x.identity(t)
378 cancelled := make(chan struct{})
379 var once sync.Once
380 h := clientFor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
381 <-r.Context().Done()
382 once.Do(func() { close(cancelled) })
383 }))
384 start := time.Now()
385 _, err := RestartAndWait(context.Background(), x.c, h, x.app, id, func(Delivery) error { return nil }, true)
386 if el := time.Since(start); el > 2*time.Second {
387 t.Fatalf("a stalled probe held the wait %v past a 150ms limit", el)
388 }
389 if err == nil || !strings.Contains(err.Error(), "restart-timeout") {
390 t.Fatalf("err = %v, want restart-timeout", err)
391 }
392 if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
393 t.Fatalf("err = %v: the limit read as the caller's context", err)
394 }
395 // The probe the limit cut off is not reported as the app's failure.
396 if !strings.Contains(err.Error(), "the app was not probed") {
397 t.Fatalf("err = %v, want the reason from before the cut-off", err)
398 }
399 select {
400 case <-cancelled:
401 case <-time.After(2 * time.Second):
402 t.Fatal("the stalled request was never cancelled")
403 }
404}
405
406// clientFor is an http.Client whose every https origin lands on handler.
407func clientFor(t *testing.T, handler http.Handler) *http.Client {
408 t.Helper()
409 srv := httptest.NewTLSServer(handler)
410 t.Cleanup(srv.Close)
411 tr := srv.Client().Transport.(*http.Transport).Clone()
412 addr := srv.Listener.Addr().String()
413 tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
414 var d net.Dialer
415 return d.DialContext(ctx, network, addr)
416 }
417 tr.TLSClientConfig.ServerName = "example.com"
418 t.Cleanup(tr.CloseIdleConnections)
419 return &http.Client{Transport: tr, Timeout: 10 * time.Second}
420}
421
422func TestRestartAndWaitKeepsPollingThroughUnreachable(t *testing.T) {
423 fastPolls(t, 5*time.Millisecond, 2*time.Second)
424 x := newCarlosFixture(t, "docs")
425 id := x.identity(t)
426 probes := 0
427 h := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
428 if r.URL.Path == "/api/version" {
429 probes++
430 }
431 if probes <= 2 {
432 return nil, errors.New("connection refused")
433 }
434 return x.h.Transport.RoundTrip(r)
435 })}
436 d, err := RestartAndWait(context.Background(), x.c, h, x.app, id, func(Delivery) error { return nil }, true)
437 if err != nil || d.Version != valueVersion {
438 t.Fatalf("RestartAndWait: %v", err)
439 }
440}
441
442func TestRestartAndWaitStopsOnCancel(t *testing.T) {
443 fastPolls(t, 10*time.Millisecond, time.Minute)
444 x := newCarlosFixture(t, "docs")
445 id := x.identity(t)
446 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
447 defer cancel()
448 start := time.Now()
449 _, err := RestartAndWait(ctx, x.c, x.h, x.app, id, func(Delivery) error { return errors.New("adopt: never") }, true)
450 if !errors.Is(err, context.DeadlineExceeded) {
451 t.Fatalf("err = %v, want the context's", err)
452 }
453 if strings.Contains(err.Error(), "restart-timeout") {
454 t.Fatalf("err = %v: the caller's cancellation read as the limit", err)
455 }
456 if time.Since(start) > 5*time.Second {
457 t.Fatal("ignored the context")
458 }
459}
460
461func TestRestartAndWaitDryRunRestartsAndWaitsForNothing(t *testing.T) {
462 fastPolls(t, time.Hour, time.Hour)
463 x := newCarlosFixture(t, "docs")
464 id := x.identity(t)
465 called := false
466 d, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, func(Delivery) error { called = true; return errors.New("x") }, false)
467 if err != nil {
468 t.Fatalf("dry run: %v", err)
469 }
470 if called || d.Version != valueVersion {
471 t.Fatalf("dry run evaluated until (%v) or did not probe", called)
472 }
473 x.noRestarts(t, docsRoute)
474}
475
476func TestRestartAndWaitDoesNotWaitWhenRestartRefused(t *testing.T) {
477 fastPolls(t, time.Hour, time.Hour)
478 x := newCarlosFixture(t, "docs")
479 id := x.identity(t)
480 x.f.NoScopedRestart()
481 _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, func(Delivery) error { return nil }, true)
482 if !errors.Is(err, carlosop.ErrNoScopedRestart) {
483 t.Fatalf("err = %v", err)
484 }
485}
486
487type roundTripFunc func(*http.Request) (*http.Response, error)
488
489func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
490
491// delivery probes the fixture's site as it stands.
492func (s *site) delivery(t *testing.T, x *carlosFixture) Delivery {
493 t.Helper()
494 d, err := Probe(context.Background(), x.h, "https://docs.oficina.works")
495 if err != nil {
496 t.Fatalf("Probe: %v", err)
497 }
498 return d
499}
500
501// A success that is only reached after the limit does not count: here the
502// classification itself finishes past the deadline.
503func TestRestartAndWaitRefusesSuccessAfterLimit(t *testing.T) {
504 fastPolls(t, 10*time.Millisecond, 100*time.Millisecond)
505 x := newCarlosFixture(t, "docs")
506 id := x.identity(t)
507 until := func(Delivery) error {
508 time.Sleep(200 * time.Millisecond)
509 return nil
510 }
511 _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true)
512 if err == nil || !strings.Contains(err.Error(), "restart-timeout") {
513 t.Fatalf("err = %v, want restart-timeout for a success after the limit", err)
514 }
515 if !strings.Contains(err.Error(), "only after the limit") {
516 t.Fatalf("err = %v, want it to say the success came after the limit", err)
517 }
518 if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
519 t.Fatalf("err = %v: the limit read as the caller's context", err)
520 }
521}
522