394 lines
16 KiB
Go
394 lines
16 KiB
Go
package main
|
|
|
|
// Deadline round 5: the last two handlers that answer only after work that
|
|
// can outlive the server-wide WriteTimeout (120s, armed once per request).
|
|
//
|
|
// - handleCreateServer answers only after its synchronous prepare phase —
|
|
// preflight and up to two docker image pulls (installer and runtime),
|
|
// each under its own 10-minute context — and on the synchronous
|
|
// direct-API path after the whole create chain (the 30-minute minecraft
|
|
// jar download, or a template install under its 30-minute default
|
|
// context, plus the container start). A cold first pull that outlived
|
|
// 120s lost the response while the create kept running: the panel's
|
|
// recovery poll then committed the row without the daemon's meta, so it
|
|
// never carried the installing marker while the daemon 409-gated actions
|
|
// with server_installing.
|
|
// - handleNodeUpdateInstall armed its 12-minute extension only after the
|
|
// body decode (up to 20MB), the nodeUpdateInstallMu queue wait and the
|
|
// source-file write loop — all of which still ran under the stock 120s —
|
|
// so the arm moved to the top of the handler.
|
|
//
|
|
// Layering matches the earlier rounds: the mechanism (SetWriteDeadline
|
|
// beating a server-wide WriteTimeout) is proven end-to-end on a real listener
|
|
// in upload_url_write_deadline_test.go, whose harness these tests reuse; the
|
|
// wiring tests pin that each handler arms the extension with the right budget
|
|
// at the right place; the two end-to-end regressions run the real handlers
|
|
// against delays the stock WriteTimeout cannot carry. The docker engine
|
|
// client (a package singleton over /var/run/docker.sock) is stubbed to fail
|
|
// instantly, so the prepare-phase pulls fail fast and deterministically
|
|
// whether or not the host runs docker.
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// failingDockerEngineTransport makes every docker engine API call fail
|
|
// instantly, so pullSetupImage (10-minute pull contexts in production) fails
|
|
// in microseconds and the create tests stay hermetic.
|
|
type failingDockerEngineTransport struct{}
|
|
|
|
func (failingDockerEngineTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
|
return nil, errors.New("docker engine unavailable (test stub)")
|
|
}
|
|
|
|
// stubDockerEngineUnavailable swaps the package docker engine client for the
|
|
// failing transport and restores the previously captured client at cleanup.
|
|
// The lazy sync.Once init MUST be forced first: dockerEngineClient() assigns
|
|
// the real client inside Once.Do on its first call, so stubbing before that
|
|
// first call would be silently overwritten and the tests would reach the
|
|
// real docker daemon (real pulls, real background setup goroutines).
|
|
// Restoring the captured pointer (not nil) is required in both states: once
|
|
// the Once has fired it never re-runs, so a nil restore would leave later
|
|
// callers a nil client.
|
|
func stubDockerEngineUnavailable(t *testing.T) {
|
|
t.Helper()
|
|
_ = dockerEngineClient()
|
|
prev := dockerEngineHTTPClient
|
|
dockerEngineHTTPClient = &http.Client{Transport: failingDockerEngineTransport{}}
|
|
t.Cleanup(func() { dockerEngineHTTPClient = prev })
|
|
// Guard: the stub must actually be live. Without this, a silently
|
|
// skipped stub would let the create tests pull real images and spawn
|
|
// real background setup goroutines that race the temp-dir cleanup.
|
|
if _, err := dockerEngineHTTPClient.Transport.RoundTrip(nil); err == nil {
|
|
t.Fatalf("docker engine stub not in effect; refusing to run create tests against the real docker daemon")
|
|
}
|
|
}
|
|
|
|
// stubDockerCLIToolchain shadows the docker CLI with a failing stub on PATH.
|
|
// imageExistsLocally shells out to `docker image inspect` (not the engine
|
|
// API), so on a host with a live docker daemon a locally cached runtime
|
|
// image (e.g. eclipse-temurin) would pass the existence check and the
|
|
// prepare phase would succeed — spawning real background setup goroutines
|
|
// that race the test's temp-dir cleanup. With the shim, the existence check
|
|
// fails and prepare fails fast whether or not the host runs docker.
|
|
func stubDockerCLIToolchain(t *testing.T) {
|
|
t.Helper()
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil {
|
|
t.Fatalf("write docker CLI stub: %v", err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
// Guard: the shim must win PATH lookup, like the engine stub above.
|
|
if out, err := exec.LookPath("docker"); err != nil || filepath.Dir(out) != binDir {
|
|
t.Fatalf("docker CLI stub not in effect (looked up %q, err %v)", out, err)
|
|
}
|
|
}
|
|
|
|
// newCreateDeadlineTestAgent builds a minimal agent with BOTH docker paths
|
|
// stubbed dead: the engine API client (pulls) and the docker CLI on PATH
|
|
// (image existence checks). readJSON caps the create body by a.uploadLimit,
|
|
// which is zero on the bare test agent and would fail every request body
|
|
// before validation.
|
|
func newCreateDeadlineTestAgent(t *testing.T) *Agent {
|
|
t.Helper()
|
|
stubDockerEngineUnavailable(t)
|
|
stubDockerCLIToolchain(t)
|
|
a, _ := newTestAgent(t)
|
|
a.uploadLimit = 32 << 20
|
|
return a
|
|
}
|
|
|
|
// freeTestHostPort returns a TCP port that was free a moment ago, so the
|
|
// create handler's availability check answers "available" (the docker stub
|
|
// already keeps the docker ownership lookup out of the picture).
|
|
func freeTestHostPort(t *testing.T) int {
|
|
t.Helper()
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatalf("probe free port: %v", err)
|
|
}
|
|
port := l.Addr().(*net.TCPAddr).Port
|
|
_ = l.Close()
|
|
return port
|
|
}
|
|
|
|
// Both asyncSetup create flows arm the extension to createCallerWaitBudget
|
|
// before the prepare phase and answer 200 with the daemon's meta. Minecraft
|
|
// prepare pulls one image; the custom flow pulls the runtime image — both
|
|
// flow shapes exercise the arm ahead of their (stubbed) pulls.
|
|
func TestAsyncCreateSetupDefersDelete(testCtx *testing.T) {
|
|
agent, _ := newTestAgent(testCtx)
|
|
const serverName = "setup-delete"
|
|
done := make(chan struct{})
|
|
release := make(chan struct{})
|
|
defer close(release)
|
|
opMu := agent.getServerOpLock(serverName)
|
|
opMu.Lock()
|
|
continueCreateSetup(func() {
|
|
opMu.Unlock()
|
|
close(done)
|
|
}, func() { <-release })
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodDelete, "/v1/servers/setup-delete?async=true", nil)
|
|
agent.handleDeleteServer(response, request, serverName)
|
|
if response.Code != http.StatusConflict {
|
|
testCtx.Fatalf("delete must retry while setup owns the server, got %d: %s", response.Code, response.Body)
|
|
}
|
|
select {
|
|
case <-done:
|
|
testCtx.Fatal("setup lock released before the worker finished")
|
|
default:
|
|
}
|
|
}
|
|
|
|
func TestCreateServerAsyncMinecraft_ExtendsWriteDeadlineToCallerBudget(t *testing.T) {
|
|
a := newCreateDeadlineTestAgent(t)
|
|
|
|
w := &deadlineRecordingWriter{ResponseRecorder: httptest.NewRecorder()}
|
|
a.handleCreateServer(w, wiringJSONRequest(t, "/v1/servers/create", map[string]any{
|
|
"name": "wdsrvmc",
|
|
"templateId": "minecraft",
|
|
"hostPort": freeTestHostPort(t),
|
|
"asyncSetup": true,
|
|
}))
|
|
if code := assertSingleExtension(t, w, createCallerWaitBudget, "create(minecraft, asyncSetup)"); code != 200 {
|
|
t.Fatalf("create: status %d (%s)", code, w.Body.String())
|
|
}
|
|
assertAsyncSetupResponse(t, w, "wdsrvmc")
|
|
}
|
|
|
|
func TestCreateServerAsyncCustom_ExtendsWriteDeadlineToCallerBudget(t *testing.T) {
|
|
a := newCreateDeadlineTestAgent(t)
|
|
|
|
w := &deadlineRecordingWriter{ResponseRecorder: httptest.NewRecorder()}
|
|
a.handleCreateServer(w, wiringJSONRequest(t, "/v1/servers/create", map[string]any{
|
|
"name": "wdsrcustom",
|
|
"templateId": "nodejs",
|
|
"hostPort": freeTestHostPort(t),
|
|
"asyncSetup": true,
|
|
"docker": map[string]any{
|
|
"image": "docker.io/library/node:20-alpine",
|
|
},
|
|
}))
|
|
if code := assertSingleExtension(t, w, createCallerWaitBudget, "create(custom, asyncSetup)"); code != 200 {
|
|
t.Fatalf("create: status %d (%s)", code, w.Body.String())
|
|
}
|
|
assertAsyncSetupResponse(t, w, "wdsrcustom")
|
|
}
|
|
|
|
// assertAsyncSetupResponse pins the response shape the panel row's markers
|
|
// come from: ok, the server name, asyncSetup true, and a daemon meta carrying
|
|
// setupStatus "failed" — with the dead docker stub the prepare pull fails
|
|
// fast, which also guarantees no background finish*CreateSetup goroutine is
|
|
// spawned to outlive the test's temp dir.
|
|
func assertAsyncSetupResponse(t *testing.T, w *deadlineRecordingWriter, name string) {
|
|
t.Helper()
|
|
var out map[string]any
|
|
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
|
t.Fatalf("decode create response %q: %v", w.Body.String(), err)
|
|
}
|
|
if out["ok"] != true || out["asyncSetup"] != true || out["name"] != name {
|
|
t.Fatalf("create response = %s, want ok/name %s/asyncSetup", w.Body.String(), name)
|
|
}
|
|
meta, _ := out["meta"].(map[string]any)
|
|
if meta == nil || meta["setupStatus"] != "failed" {
|
|
t.Fatalf("create response meta = %v, want setupStatus \"failed\" (the stubbed prepare pull must fail fast, not reach a live docker)", meta)
|
|
}
|
|
}
|
|
|
|
// The arm must sit after the fast validation writes: requests that fail
|
|
// validation keep the stock 120s deadline (zero extensions recorded). The
|
|
// port-in-use case holds the port with a real listener, so the 409 comes from
|
|
// the availability check that directly precedes the arm point.
|
|
func TestCreateServer_NoExtensionBeforeValidation(t *testing.T) {
|
|
a := newCreateDeadlineTestAgent(t)
|
|
|
|
w := &deadlineRecordingWriter{ResponseRecorder: httptest.NewRecorder()}
|
|
a.handleCreateServer(w, httptest.NewRequest("POST", "/v1/servers/create", bytes.NewReader([]byte("{not json"))))
|
|
if w.Code != 400 || len(w.deadlines) != 0 {
|
|
t.Fatalf("bad json: status %d, %d extensions recorded, want 400/0", w.Code, len(w.deadlines))
|
|
}
|
|
|
|
w = &deadlineRecordingWriter{ResponseRecorder: httptest.NewRecorder()}
|
|
a.handleCreateServer(w, wiringJSONRequest(t, "/v1/servers/create", map[string]any{
|
|
"name": "wdsrcustom",
|
|
}))
|
|
if w.Code != 400 || len(w.deadlines) != 0 {
|
|
t.Fatalf("missing template: status %d, %d extensions recorded, want 400/0", w.Code, len(w.deadlines))
|
|
}
|
|
|
|
port := freeTestHostPort(t)
|
|
held, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
|
|
if err != nil {
|
|
t.Fatalf("hold port: %v", err)
|
|
}
|
|
defer held.Close()
|
|
w = &deadlineRecordingWriter{ResponseRecorder: httptest.NewRecorder()}
|
|
a.handleCreateServer(w, wiringJSONRequest(t, "/v1/servers/create", map[string]any{
|
|
"name": "wdsrvmc",
|
|
"templateId": "minecraft",
|
|
"hostPort": port,
|
|
"asyncSetup": true,
|
|
}))
|
|
if w.Code != 409 || len(w.deadlines) != 0 {
|
|
t.Fatalf("port in use: status %d, %d extensions recorded, want 409/0 (%s)", w.Code, len(w.deadlines), w.Body.String())
|
|
}
|
|
}
|
|
|
|
// The regression: handleCreateServer must deliver its asyncSetup 200 even
|
|
// when the response lands past the server-wide WriteTimeout. The real
|
|
// handler blocks on the per-server op lock AFTER the arm point (a concurrent
|
|
// same-name create holds it across its whole prepare phase), so the lock
|
|
// holder released after deadlineHarnessSleep pushes the response past the
|
|
// 120ms/120s WriteTimeout; before the fix the daemon dropped it and the
|
|
// panel's recovery poll committed the row without the meta that carries the
|
|
// installing marker.
|
|
func TestCreateServerResponseSurvivesServerWriteTimeout(t *testing.T) {
|
|
a := newCreateDeadlineTestAgent(t)
|
|
name := "wdsrve2e"
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
go func() {
|
|
// Hold the lock well past the harness WriteTimeout — the scaled-down
|
|
// shape of a concurrent create's full prepare phase.
|
|
time.Sleep(deadlineHarnessSleep)
|
|
opMu.Unlock()
|
|
}()
|
|
|
|
srv := startDeadlineTestServer(t, http.HandlerFunc(a.handleCreateServer))
|
|
payload, err := json.Marshal(map[string]any{
|
|
"name": name,
|
|
"templateId": "minecraft",
|
|
"hostPort": freeTestHostPort(t),
|
|
"asyncSetup": true,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("marshal payload: %v", err)
|
|
}
|
|
// Fresh client: no connection reuse, so the outcome is not confounded by
|
|
// retry-on-reused-connection semantics.
|
|
client := &http.Client{Timeout: 30 * time.Second}
|
|
resp, err := client.Post(srv.URL, "application/json", bytes.NewReader(payload))
|
|
if err != nil {
|
|
t.Fatalf("response lost after a %v op-lock wait under a %v WriteTimeout: %v",
|
|
deadlineHarnessSleep, deadlineHarnessWriteTimeout, err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != 200 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
t.Fatalf("create after op-lock wait: status %d body %s", resp.StatusCode, body)
|
|
}
|
|
var out map[string]any
|
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil || out["ok"] != true || out["asyncSetup"] != true {
|
|
t.Fatalf("create response = (%v, %v), want ok+asyncSetup", out, err)
|
|
}
|
|
}
|
|
|
|
// --- handleNodeUpdateInstall: the arm moved to the top of the handler ---
|
|
|
|
// slowRecordingBody delays the first Read and records when it happened, so
|
|
// the wiring test can prove the deadline extension is armed BEFORE the body
|
|
// decode starts reading (the old position armed it only after the decode,
|
|
// the queue wait and the file writes).
|
|
type slowRecordingBody struct {
|
|
r io.Reader
|
|
delay time.Duration
|
|
firstRead time.Time
|
|
read bool
|
|
}
|
|
|
|
func (b *slowRecordingBody) Read(p []byte) (int, error) {
|
|
if !b.read {
|
|
b.read = true
|
|
time.Sleep(b.delay)
|
|
b.firstRead = time.Now()
|
|
}
|
|
return b.r.Read(p)
|
|
}
|
|
|
|
// handleNodeUpdateInstall arms its 12-minute extension as the first
|
|
// statement: the body decode (up to 20MB), the nodeUpdateInstallMu queue
|
|
// wait and the file-write loop all precede the response and would otherwise
|
|
// run under the stock 120s. This 400 path (invalid version, reached after
|
|
// the full decode) proves the arm fires on the earliest exit too — under the
|
|
// old placement zero extensions were recorded here.
|
|
func TestNodeUpdateInstall_ExtendsWriteDeadlineAtHandlerTop(t *testing.T) {
|
|
a, _ := newTestAgent(t)
|
|
|
|
body := &slowRecordingBody{
|
|
r: bytes.NewReader([]byte(`{"version":"not-a-version","files":[]}`)),
|
|
delay: 150 * time.Millisecond,
|
|
}
|
|
w := &deadlineRecordingWriter{ResponseRecorder: httptest.NewRecorder()}
|
|
a.handleNodeUpdateInstall(w, httptest.NewRequest("POST", "/v1/update/install", body))
|
|
|
|
if w.Code != 400 {
|
|
t.Fatalf("update install: status %d (%s), want 400 for the invalid version after the full decode", w.Code, w.Body.String())
|
|
}
|
|
if len(w.deadlines) != 1 {
|
|
t.Fatalf("update install: %d deadline extensions recorded, want exactly 1 (armed at the top, before validation)", len(w.deadlines))
|
|
}
|
|
delta := w.deadlines[0].Sub(w.observed[0])
|
|
if delta < 11*time.Minute || delta > 13*time.Minute {
|
|
t.Fatalf("update install: extension armed %.0fs out, want ~12m", delta.Seconds())
|
|
}
|
|
if w.observed[0].After(body.firstRead) {
|
|
t.Fatalf("deadline armed %v after the first body byte was read — the arm must sit at the top of the handler, before the body decode",
|
|
w.observed[0].Sub(body.firstRead))
|
|
}
|
|
}
|
|
|
|
// The regression: with the arm at the top, the 400 after a slow-dribbled
|
|
// body still reaches the client although the body decode outlives the
|
|
// server-wide WriteTimeout. Under the old placement (arm after the decode)
|
|
// the write deadline expired mid-decode and the response was lost.
|
|
func TestNodeUpdateInstallResponseSurvivesServerWriteTimeout(t *testing.T) {
|
|
a, _ := newTestAgent(t)
|
|
|
|
srv := startDeadlineTestServer(t, http.HandlerFunc(a.handleNodeUpdateInstall))
|
|
|
|
payload := []byte(`{"version":"not-a-version","files":[]}`)
|
|
pr, pw := io.Pipe()
|
|
go func() {
|
|
// Dribble the body over 4 chunks spaced 100ms apart: the server-side
|
|
// decode spans ~300ms, well past the 120ms WriteTimeout.
|
|
for _, chunk := range [][]byte{payload[:6], payload[6:12], payload[12:24], payload[24:]} {
|
|
if _, err := pw.Write(chunk); err != nil {
|
|
return
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
}
|
|
_ = pw.Close()
|
|
}()
|
|
// Fresh client: no connection reuse, so the outcome is not confounded by
|
|
// retry-on-reused-connection semantics.
|
|
client := &http.Client{Timeout: 30 * time.Second}
|
|
req, err := http.NewRequest(http.MethodPost, srv.URL, pr)
|
|
if err != nil {
|
|
t.Fatalf("new request: %v", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
t.Fatalf("response lost after a slow body decode under a %v WriteTimeout: %v", deadlineHarnessWriteTimeout, err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != 400 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
t.Fatalf("update install after slow body: status %d body %s, want 400", resp.StatusCode, body)
|
|
}
|
|
}
|