From ceb7edd3fa83e5ba04fdd61fff17bf9a16555e8c Mon Sep 17 00:00:00 2001 From: Rasmus Larsen Date: Wed, 2 Dec 2026 07:36:16 +0000 Subject: [PATCH 1/2] Add Go ucloud-gatewayd fast-path front door and cap store chunk-index RAM (Phase 2) 1. Add runtime/gatewayd (pure Go stdlib, CGO_ENABLED=0): fast-path HTTP front door in front of Python control_plane that handles /v1/exec/* statelessly via HMAC + fresh worker map, proxies running-sandbox POST /exec, GET /jobs, GET/PUT /files, and PUT /archive directly to ucloud-noded with zero-copy streaming, evicts cached routes immediately on park/wake/delete/migration/ worker-reboot, and falls back transparently to Python on miss/parked/stale. 2. Emit internal X-UCloud-Gateway-Route hint from control_plane/create and sandbox_proxy only when fronted by X-UCloud-Gateway-Front-Door: 1. 3. Bound chunk_index.py caches (META_CACHE_BYTES, TAIL_CACHE_IDS, locator_cache, PRAGMA cache_size=-8000) to eliminate multi-GB RSS growth on the store node. 4. Fix standalone exec_front.rs to return 400 directly on malformed/partial exec payloads instead of falling through to 404. 5. Support Linux bind mounts in systemd.py require_registry_mount via /proc/self/mountinfo, update stale diagram in docs/architecture.md, and wire runtime/gatewayd into scripts/check.sh. --- docs/architecture.md | 8 +- runtime/gatewayd/auth.go | 165 ++++++++++ runtime/gatewayd/gatewayd_test.go | 406 ++++++++++++++++++++++++ runtime/gatewayd/go.mod | 3 + runtime/gatewayd/main.go | 101 ++++++ runtime/gatewayd/proxy.go | 489 +++++++++++++++++++++++++++++ runtime/gatewayd/routes.go | 355 +++++++++++++++++++++ runtime/noded/src/exec_front.rs | 16 +- sandboxes/chunk_index.py | 13 +- sandboxes/gateway/create.py | 5 +- sandboxes/gateway/sandbox_proxy.py | 33 ++ sandboxes/systemd.py | 16 +- scripts/check.sh | 5 + tests/test_gatewayd_contract.py | 203 ++++++++++++ tests/test_systemd.py | 11 + 15 files changed, 1817 insertions(+), 12 deletions(-) create mode 100644 runtime/gatewayd/auth.go create mode 100644 runtime/gatewayd/gatewayd_test.go create mode 100644 runtime/gatewayd/go.mod create mode 100644 runtime/gatewayd/main.go create mode 100644 runtime/gatewayd/proxy.go create mode 100644 runtime/gatewayd/routes.go create mode 100644 tests/test_gatewayd_contract.py diff --git a/docs/architecture.md b/docs/architecture.md index cc36ba43..d83cbb08 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -26,7 +26,6 @@ flowchart LR end subgraph Node[Sandbox node] Noded[ucloud-noded] - Agent[Python node agent / Warden] Storage[storage-native daemon] EnvIO[environment I/O] Runsc[runsc sandboxes] @@ -41,12 +40,11 @@ flowchart LR Relay --> PG API -->|node-control token| Noded Placement -->|node-control token| Noded - Noded -->|Unix socket| Agent - Agent --> Storage - Agent --> Runsc + Noded --> Storage + Noded --> EnvIO Noded --> Runsc Runsc --> EnvIO --> Store --> S3 - Agent -->|heartbeats| API + Noded -->|heartbeats| API Runsc -->|model calls| Relay Relay -->|park / wake| API Autoscaler --> Provider diff --git a/runtime/gatewayd/auth.go b/runtime/gatewayd/auth.go new file mode 100644 index 00000000..232eca7b --- /dev/null +++ b/runtime/gatewayd/auth.go @@ -0,0 +1,165 @@ +package main + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "regexp" + "strings" +) + +const ( + execSessionPrefixHeader = "X-UCloud-Exec-Session-Prefix" + execRouteVersion = "xr1" + execRouteMACBytes = 16 + execRouteKeyContext = "ucloud-sandboxes exec session route v1" + maxPrefixLength = 768 +) + +var ( + prefixRE = regexp.MustCompile(`^xr1\.[A-Za-z0-9_-]{1,700}\.[A-Za-z0-9_-]{22}$`) + sessionRE = regexp.MustCompile(`^(xr1\.[A-Za-z0-9_-]{1,700}\.[A-Za-z0-9_-]{22})\.[0-9a-f]{32}$`) +) + +// SignedExecRoute mirrors sandboxes/exec_session_routes.py SignedExecRoute. +type SignedExecRoute struct { + SandboxID string + SandboxGeneration int64 + NodeID string + JobID string + IssuedAt int64 +} + +// ExecSessionRoutes implements byte-for-byte compatible HMAC signing and +// verification with sandboxes/exec_session_routes.py. +type ExecSessionRoutes struct { + key []byte +} + +func NewExecSessionRoutes(gatewaySecret string) (*ExecSessionRoutes, error) { + trimmed := strings.TrimSpace(gatewaySecret) + if trimmed == "" { + return nil, errors.New("exec session routes require a gateway secret") + } + mac := hmac.New(sha256.New, []byte(trimmed)) + mac.Write([]byte(execRouteKeyContext)) + return &ExecSessionRoutes{key: mac.Sum(nil)}, nil +} + +func (e *ExecSessionRoutes) computeMAC(payload string) string { + mac := hmac.New(sha256.New, e.key) + mac.Write([]byte(execRouteVersion + "." + payload)) + sum := mac.Sum(nil) + return base64.RawURLEncoding.EncodeToString(sum[:execRouteMACBytes]) +} + +func (e *ExecSessionRoutes) Prefix(route SignedExecRoute) (string, error) { + // Python json.dumps([sandbox_id, generation, node_id, job_id, issued_at], separators=(",", ":"), ensure_ascii=False) + raw, err := json.Marshal([]any{ + route.SandboxID, + route.SandboxGeneration, + route.NodeID, + route.JobID, + route.IssuedAt, + }) + if err != nil { + return "", err + } + payload := base64.RawURLEncoding.EncodeToString(raw) + prefix := fmt.Sprintf("%s.%s.%s", execRouteVersion, payload, e.computeMAC(payload)) + if len(prefix) > maxPrefixLength || !prefixRE.MatchString(prefix) { + return "", errors.New("exec route identity is too long for a session prefix") + } + return prefix, nil +} + +func (e *ExecSessionRoutes) Decode(sessionID string) (SignedExecRoute, bool) { + matches := sessionRE.FindStringSubmatch(sessionID) + if len(matches) != 2 { + return SignedExecRoute{}, false + } + parts := strings.Split(matches[1], ".") + if len(parts) != 3 { + return SignedExecRoute{}, false + } + payload, mac := parts[1], parts[2] + expected := e.computeMAC(payload) + if !hmac.Equal([]byte(mac), []byte(expected)) { + return SignedExecRoute{}, false + } + decoded, err := base64.RawURLEncoding.DecodeString(payload) + if err != nil { + return SignedExecRoute{}, false + } + var values []json.RawMessage + if err := json.Unmarshal(decoded, &values); err != nil || len(values) != 5 { + return SignedExecRoute{}, false + } + var sandboxID, nodeID, jobID string + var generation, issuedAt int64 + if err := json.Unmarshal(values[0], &sandboxID); err != nil || sandboxID == "" { + return SignedExecRoute{}, false + } + if err := json.Unmarshal(values[1], &generation); err != nil || generation <= 0 { + return SignedExecRoute{}, false + } + if err := json.Unmarshal(values[2], &nodeID); err != nil || nodeID == "" { + return SignedExecRoute{}, false + } + if err := json.Unmarshal(values[3], &jobID); err != nil || jobID == "" { + return SignedExecRoute{}, false + } + if err := json.Unmarshal(values[4], &issuedAt); err != nil || issuedAt <= 0 { + return SignedExecRoute{}, false + } + return SignedExecRoute{ + SandboxID: sandboxID, + SandboxGeneration: generation, + NodeID: nodeID, + JobID: jobID, + IssuedAt: issuedAt, + }, true +} + +type Credentials struct { + GatewayToken string + SandboxAPIToken string + NodeControlToken string +} + +func tokenMatches(headers http.Header, expected string, allowSandboxHeader bool) bool { + if expected == "" { + return false + } + auth := headers.Get("Authorization") + if strings.HasPrefix(auth, "Bearer ") { + bearer := auth[len("Bearer "):] + if bearer != "" && hmac.Equal([]byte(bearer), []byte(expected)) { + return true + } + } + if allowSandboxHeader { + tok := headers.Get("X-UCloud-Sandbox-Token") + if tok != "" && hmac.Equal([]byte(tok), []byte(expected)) { + return true + } + } + return false +} + +// AuthorizeSDKRoute returns true if the request carries either the gateway +// control token or the public sandbox API key (matching sandboxes/gateway/auth.py). +func (c Credentials) AuthorizeSDKRoute(headers http.Header) bool { + if tokenMatches(headers, c.GatewayToken, false) { + return true + } + return tokenMatches(headers, c.SandboxAPIToken, true) +} + +func (c Credentials) AuthorizeGatewayToken(headers http.Header) bool { + return tokenMatches(headers, c.GatewayToken, false) +} diff --git a/runtime/gatewayd/gatewayd_test.go b/runtime/gatewayd/gatewayd_test.go new file mode 100644 index 00000000..29d8909f --- /dev/null +++ b/runtime/gatewayd/gatewayd_test.go @@ -0,0 +1,406 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func testCreds() Credentials { + return Credentials{ + GatewayToken: "gw-secret-test", + SandboxAPIToken: "sdk-secret-test", + NodeControlToken: "node-secret-test", + } +} + +func TestExecSessionRoutesPythonParity(t *testing.T) { + signer, err := NewExecSessionRoutes("gw-secret-test") + if err != nil { + t.Fatal(err) + } + route := SignedExecRoute{ + SandboxID: "sb-alpha", + SandboxGeneration: 3, + NodeID: "node-1", + JobID: "job-42", + IssuedAt: 1700000000, + } + got, err := signer.Prefix(route) + if err != nil { + t.Fatal(err) + } + // Exact output pinned from sandboxes.exec_session_routes.ExecSessionRoutes. + want := "xr1.WyJzYi1hbHBoYSIsMywibm9kZS0xIiwiam9iLTQyIiwxNzAwMDAwMDAwXQ.DMfyeJb1JfplwiF_Ck6GAg" + if got != want { + t.Fatalf("prefix mismatch:\n got: %s\nwant: %s", got, want) + } + + sessionID := got + ".0123456789abcdef0123456789abcdef" + decoded, ok := signer.Decode(sessionID) + if !ok { + t.Fatalf("expected valid session decode for %s", sessionID) + } + if decoded != route { + t.Fatalf("decoded mismatch: got %+v want %+v", decoded, route) + } + + // Tampered MAC must fail. + tampered := got[:len(got)-1] + "Z.0123456789abcdef0123456789abcdef" + if _, ok := signer.Decode(tampered); ok { + t.Fatalf("expected tampered session to fail decode") + } +} + +func TestFastPathExecSessionAndCredentialStripping(t *testing.T) { + var upstreamHits atomic.Int64 + var workerHits atomic.Int64 + var seenAuth string + + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + workerHits.Add(1) + seenAuth = r.Header.Get("Authorization") + if r.Header.Get("X-UCloud-Sandbox-Token") != "" { + t.Errorf("client sandbox token leaked to worker") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"events":[{"sequence":1,"kind":"exit","exit_code":0}]}`)) + })) + defer worker.Close() + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamHits.Add(1) + if r.URL.Path == "/v1/nodes" { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "nodes": []map[string]any{{ + "job_id": "job-1", + "node_id": "node-1", + "node_url": worker.URL, + "node_epoch": "epoch-a", + "received_at": time.Now().UTC().Format(time.RFC3339Nano), + }}, + }) + return + } + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"from-upstream"}`)) + })) + defer upstream.Close() + + fd, err := NewGatewayFrontDoor(upstream.URL, testCreds(), 45*time.Second, 30*time.Second) + if err != nil { + t.Fatal(err) + } + if err := fd.SeedWorkers(context.Background()); err != nil { + t.Fatal(err) + } + upstreamHits.Store(0) + + gw := httptest.NewServer(fd) + defer gw.Close() + + prefix, err := fd.execSigner.Prefix(SignedExecRoute{ + SandboxID: "sb-1", SandboxGeneration: 1, NodeID: "node-1", JobID: "job-1", IssuedAt: time.Now().Unix(), + }) + if err != nil { + t.Fatal(err) + } + sessionID := prefix + ".aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + req, _ := http.NewRequest(http.MethodGet, gw.URL+"/v1/exec/"+sessionID+"/events?after=0&wait_seconds=1", nil) + req.Header.Set("Authorization", "Bearer sdk-secret-test") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", resp.StatusCode) + } + if workerHits.Load() != 1 || upstreamHits.Load() != 0 { + t.Fatalf("expected direct worker hit (worker=%d upstream=%d)", workerHits.Load(), upstreamHits.Load()) + } + if seenAuth != "Bearer node-secret-test" { + t.Fatalf("expected node-control auth, got %q", seenAuth) + } + + // Unknown job_id falls back cleanly to upstream Python. + unknownPrefix, _ := fd.execSigner.Prefix(SignedExecRoute{ + SandboxID: "sb-1", SandboxGeneration: 1, NodeID: "node-9", JobID: "job-missing", IssuedAt: time.Now().Unix(), + }) + req2, _ := http.NewRequest(http.MethodGet, gw.URL+"/v1/exec/"+unknownPrefix+".bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/events", nil) + req2.Header.Set("Authorization", "Bearer sdk-secret-test") + resp2, err := http.DefaultClient.Do(req2) + if err != nil { + t.Fatal(err) + } + resp2.Body.Close() + if resp2.StatusCode != http.StatusNotFound || upstreamHits.Load() != 1 { + t.Fatalf("expected fallback to upstream (status=%d upstream=%d)", resp2.StatusCode, upstreamHits.Load()) + } +} + +func TestRouteCacheLifecycleEvictionAndFallback(t *testing.T) { + var upstreamHits atomic.Int64 + var workerExecHits atomic.Int64 + var workerUploadBytes atomic.Int64 + var workerGenHeader string + var workerReturnsParked atomic.Bool + + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if workerReturnsParked.Load() { + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"error":"direct sandbox is in state parked"}`)) + return + } + switch { + case strings.HasSuffix(r.URL.Path, "/exec"): + workerExecHits.Add(1) + if r.Header.Get(execSessionPrefixHeader) == "" { + t.Errorf("missing %s on fast exec start", execSessionPrefixHeader) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"session":{"id":"ok"}}`)) + case strings.HasSuffix(r.URL.Path, "/files") && r.Method == http.MethodPut: + workerGenHeader = r.Header.Get(sandboxGenerationHeader) + n, _ := io.Copy(io.Discard, r.Body) + workerUploadBytes.Add(n) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"ok":true}`)) + case strings.Contains(r.URL.Path, "/jobs/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"job":{"state":"running"}}`)) + default: + w.WriteHeader(http.StatusOK) + } + })) + defer worker.Close() + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamHits.Add(1) + switch { + case r.Method == http.MethodPost && r.URL.Path == "/v1/nodes/heartbeat": + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"ok":true}`)) + case r.Method == http.MethodPost && r.URL.Path == "/v1/sandboxes": + if r.Header.Get(frontDoorHeader) != "1" { + t.Errorf("expected %s header on upstream request", frontDoorHeader) + } + w.Header().Set(routeHintHeader, fmt.Sprintf("sb-1|node-1|job-1|2|%s", worker.URL)) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"sandbox":{"id":"sb-1","state":"running"}}`)) + case strings.HasSuffix(r.URL.Path, "/park"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"sandbox":{"id":"sb-1","state":"parked"}}`)) + case strings.Contains(r.URL.Path, "/jobs/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"job":{"state":"exited","from":"python-cache"}}`)) + case strings.HasSuffix(r.URL.Path, "/exec"): + // Python woke the sandbox and returned 201! + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"session":{"id":"woken-by-python"}}`)) + default: + w.WriteHeader(http.StatusOK) + } + })) + defer upstream.Close() + + fd, err := NewGatewayFrontDoor(upstream.URL, testCreds(), 45*time.Second, 30*time.Second) + if err != nil { + t.Fatal(err) + } + gw := httptest.NewServer(fd) + defer gw.Close() + + // 1. Worker posts heartbeat through gatewayd -> populates fresh worker table. + hbBody := fmt.Sprintf(`{"job_id":"job-1","node_id":"node-1","node_url":%q,"node_epoch":"ep1"}`, worker.URL) + hbReq, _ := http.NewRequest(http.MethodPost, gw.URL+"/v1/nodes/heartbeat", strings.NewReader(hbBody)) + hbResp, err := http.DefaultClient.Do(hbReq) + if err != nil || hbResp.StatusCode != 200 { + t.Fatalf("heartbeat failed: %v", err) + } + hbResp.Body.Close() + + // 2. Create sandbox via upstream -> caches route, strips internal route hint header! + createReq, _ := http.NewRequest(http.MethodPost, gw.URL+"/v1/sandboxes", strings.NewReader(`{"id":"sb-1"}`)) + createReq.Header.Set("Authorization", "Bearer sdk-secret-test") + createResp, err := http.DefaultClient.Do(createReq) + if err != nil || createResp.StatusCode != 201 { + t.Fatalf("create failed: %v", err) + } + if createResp.Header.Get(routeHintHeader) != "" { + t.Fatalf("internal %s header leaked to client!", routeHintHeader) + } + createResp.Body.Close() + + upstreamBefore := upstreamHits.Load() + + // 3. Exec start hits worker directly (0 upstream hits)! + execReq, _ := http.NewRequest(http.MethodPost, gw.URL+"/v1/sandboxes/sb-1/exec", strings.NewReader(`{"command":["true"]}`)) + execReq.Header.Set("Authorization", "Bearer sdk-secret-test") + execResp, err := http.DefaultClient.Do(execReq) + if err != nil || execResp.StatusCode != 201 { + t.Fatalf("fast exec start failed: %v status=%d", err, execResp.StatusCode) + } + execResp.Body.Close() + if workerExecHits.Load() != 1 || upstreamHits.Load() != upstreamBefore { + t.Fatalf("exec start did not use fast path (worker=%d upstreamDelta=%d)", workerExecHits.Load(), upstreamHits.Load()-upstreamBefore) + } + + // 4. Streaming file PUT hits worker directly with X-UCloud-Sandbox-Generation: 2! + payload := bytes.Repeat([]byte("A"), 256*1024) + putReq, _ := http.NewRequest(http.MethodPut, gw.URL+"/v1/sandboxes/sb-1/files?path=/tmp/big", bytes.NewReader(payload)) + putReq.Header.Set("Authorization", "Bearer sdk-secret-test") + putResp, err := http.DefaultClient.Do(putReq) + if err != nil || putResp.StatusCode != 200 { + t.Fatalf("fast upload failed: %v", err) + } + putResp.Body.Close() + if workerUploadBytes.Load() != int64(len(payload)) || workerGenHeader != "2" || upstreamHits.Load() != upstreamBefore { + t.Fatalf("upload mismatch bytes=%d gen=%q upstreamDelta=%d", workerUploadBytes.Load(), workerGenHeader, upstreamHits.Load()-upstreamBefore) + } + + // 5. If worker rejects with 409 (sandbox parked externally), exec start seamlessly replays via upstream Python! + workerReturnsParked.Store(true) + execReq2, _ := http.NewRequest(http.MethodPost, gw.URL+"/v1/sandboxes/sb-1/exec", strings.NewReader(`{"command":["echo","hi"]}`)) + execReq2.Header.Set("Authorization", "Bearer sdk-secret-test") + execResp2, err := http.DefaultClient.Do(execReq2) + if err != nil || execResp2.StatusCode != 201 { + t.Fatalf("fallback exec start failed: %v", err) + } + body2, _ := io.ReadAll(execResp2.Body) + execResp2.Body.Close() + if !strings.Contains(string(body2), "woken-by-python") { + t.Fatalf("expected python wake fallback, got %s", body2) + } + + // 6. Explicit park evicts route BEFORE forwarding so subsequent job read goes straight to Python cache! + fd.state.SetSandboxRoute(SandboxRouteEntry{ + SandboxID: "sb-1", NodeID: "node-1", JobID: "job-1", Generation: 2, NodeURL: worker.URL, + }, time.Now()) + workerReturnsParked.Store(false) + parkReq, _ := http.NewRequest(http.MethodPost, gw.URL+"/v1/sandboxes/sb-1/park", strings.NewReader(`{"operation_id":"p1"}`)) + parkReq.Header.Set("Authorization", "Bearer gw-secret-test") + parkResp, err := http.DefaultClient.Do(parkReq) + if err != nil || parkResp.StatusCode != 200 { + t.Fatalf("park failed: %v", err) + } + parkResp.Body.Close() + + jobReq, _ := http.NewRequest(http.MethodGet, gw.URL+"/v1/sandboxes/sb-1/jobs/j1", nil) + jobReq.Header.Set("Authorization", "Bearer sdk-secret-test") + jobResp, err := http.DefaultClient.Do(jobReq) + if err != nil || jobResp.StatusCode != 200 { + t.Fatalf("parked job read failed: %v", err) + } + jobBody, _ := io.ReadAll(jobResp.Body) + jobResp.Body.Close() + if !strings.Contains(string(jobBody), "python-cache") { + t.Fatalf("expected parked job read to bypass evicted route and hit python cache, got %s", jobBody) + } + + // 7. Worker reboot (new node_epoch) evicts all cached routes for that job_id! + fd.state.SetSandboxRoute(SandboxRouteEntry{ + SandboxID: "sb-1", NodeID: "node-1", JobID: "job-1", Generation: 2, NodeURL: worker.URL, + }, time.Now()) + fd.state.UpsertWorker(WorkerEntry{ + JobID: "job-1", NodeID: "node-1", NodeURL: worker.URL, NodeEpoch: "ep2", + }, time.Now()) + if _, _, ok := fd.state.LookupSandbox("sb-1", time.Now()); ok { + t.Fatalf("expected worker reboot to evict cached sandbox routes") + } +} + +func TestHighConcurrency1500FastPathPolls(t *testing.T) { + var upstreamHits atomic.Int64 + var workerHits atomic.Int64 + + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + workerHits.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"events":[]}`)) + })) + defer worker.Close() + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamHits.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + defer upstream.Close() + + fd, err := NewGatewayFrontDoor(upstream.URL, testCreds(), 45*time.Second, 30*time.Second) + if err != nil { + t.Fatal(err) + } + now := time.Now() + fd.state.UpsertWorker(WorkerEntry{ + JobID: "job-1", NodeID: "node-1", NodeURL: worker.URL, NodeEpoch: "ep1", + }, now) + for i := 0; i < 1500; i++ { + fd.state.SetSandboxRoute(SandboxRouteEntry{ + SandboxID: fmt.Sprintf("sb-%d", i), NodeID: "node-1", JobID: "job-1", Generation: 1, NodeURL: worker.URL, + }, now) + } + + gw := httptest.NewServer(fd) + defer gw.Close() + + prefix, _ := fd.execSigner.Prefix(SignedExecRoute{ + SandboxID: "sb-0", SandboxGeneration: 1, NodeID: "node-1", JobID: "job-1", IssuedAt: now.Unix(), + }) + sessionID := prefix + ".0123456789abcdef0123456789abcdef" + + client := &http.Client{ + Transport: &http.Transport{MaxIdleConnsPerHost: 256}, + Timeout: 15 * time.Second, + } + + const total = 1500 + var wg sync.WaitGroup + var failed atomic.Int64 + sem := make(chan struct{}, 200) + for i := 0; i < total; i++ { + wg.Add(1) + sem <- struct{}{} + go func(idx int) { + defer wg.Done() + defer func() { <-sem }() + var target string + if idx%2 == 0 { + target = gw.URL + "/v1/exec/" + sessionID + "/events?after=0" + } else { + target = fmt.Sprintf("%s/v1/sandboxes/sb-%d/jobs/j1", gw.URL, idx) + } + req, _ := http.NewRequest(http.MethodGet, target, nil) + req.Header.Set("Authorization", "Bearer sdk-secret-test") + resp, err := client.Do(req) + if err != nil { + failed.Add(1) + return + } + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + failed.Add(1) + } + }(i) + } + wg.Wait() + + if failed.Load() != 0 { + t.Fatalf("%d of %d concurrent requests failed", failed.Load(), total) + } + if workerHits.Load() != total || upstreamHits.Load() != 0 { + t.Fatalf("expected all %d requests on fast path (worker=%d upstream=%d)", total, workerHits.Load(), upstreamHits.Load()) + } +} diff --git a/runtime/gatewayd/go.mod b/runtime/gatewayd/go.mod new file mode 100644 index 00000000..9478080d --- /dev/null +++ b/runtime/gatewayd/go.mod @@ -0,0 +1,3 @@ +module github.com/rasmus/ucloud-gatewayd + +go 1.22 diff --git a/runtime/gatewayd/main.go b/runtime/gatewayd/main.go new file mode 100644 index 00000000..c0c9d8e9 --- /dev/null +++ b/runtime/gatewayd/main.go @@ -0,0 +1,101 @@ +package main + +import ( + "context" + "flag" + "log" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + "time" +) + +func readTokenFile(path string) (string, error) { + raw, err := os.ReadFile(path) + if err != nil { + return "", err + } + return strings.TrimSpace(string(raw)), nil +} + +func main() { + listen := flag.String("listen", "0.0.0.0:8090", "TCP listen address") + upstream := flag.String("upstream", "http://127.0.0.1:18090", "Upstream Python control-plane base URL") + gatewayTokenFile := flag.String("gateway-token-file", "", "Path to gateway control bearer token") + sandboxTokenFile := flag.String("sandbox-api-token-file", "", "Path to public sandbox API bearer token") + nodeControlTokenFile := flag.String("node-control-token-file", "", "Path to worker node-control bearer token") + heartbeatTTL := flag.Duration("heartbeat-ttl", 45*time.Second, "Worker heartbeat freshness TTL") + routeTTL := flag.Duration("route-cache-ttl", 30*time.Second, "Bounded TTL for cached live sandbox routes") + seedInterval := flag.Duration("seed-interval", 10*time.Second, "Interval to refresh worker table from upstream /v1/nodes") + flag.Parse() + + if *gatewayTokenFile == "" || *sandboxTokenFile == "" || *nodeControlTokenFile == "" { + log.Fatal("ucloud-gatewayd: --gateway-token-file, --sandbox-api-token-file, and --node-control-token-file are required") + } + gwTok, err := readTokenFile(*gatewayTokenFile) + if err != nil { + log.Fatalf("ucloud-gatewayd: read gateway token: %v", err) + } + sbTok, err := readTokenFile(*sandboxTokenFile) + if err != nil { + log.Fatalf("ucloud-gatewayd: read sandbox API token: %v", err) + } + ncTok, err := readTokenFile(*nodeControlTokenFile) + if err != nil { + log.Fatalf("ucloud-gatewayd: read node-control token: %v", err) + } + + fd, err := NewGatewayFrontDoor( + *upstream, + Credentials{ + GatewayToken: gwTok, + SandboxAPIToken: sbTok, + NodeControlToken: ncTok, + }, + *heartbeatTTL, + *routeTTL, + ) + if err != nil { + log.Fatalf("ucloud-gatewayd: init failed: %v", err) + } + + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + + // Warm worker table immediately and refresh periodically in background. + go func() { + _ = fd.SeedWorkers(ctx) + ticker := time.NewTicker(*seedInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + _ = fd.SeedWorkers(ctx) + } + } + }() + + srv := &http.Server{ + Addr: *listen, + Handler: fd, + ReadHeaderTimeout: 30 * time.Second, + IdleTimeout: 120 * time.Second, + } + + go func() { + <-ctx.Done() + shutCtx, shutCancel := context.WithTimeout(context.Background(), 15*time.Second) + defer shutCancel() + _ = srv.Shutdown(shutCtx) + }() + + log.Printf("ucloud-gatewayd: listening on %s -> upstream %s (heartbeat_ttl=%s route_ttl=%s)", + *listen, *upstream, *heartbeatTTL, *routeTTL) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("ucloud-gatewayd: serve failed: %v", err) + } +} diff --git a/runtime/gatewayd/proxy.go b/runtime/gatewayd/proxy.go new file mode 100644 index 00000000..10574e75 --- /dev/null +++ b/runtime/gatewayd/proxy.go @@ -0,0 +1,489 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httputil" + "net/url" + "strconv" + "strings" + "sync/atomic" + "time" +) + +const ( + maxExecStartBodyBytes = 1 * 1024 * 1024 // 1 MiB (matches DEFAULT_MAX_JSON_BODY_BYTES) + maxHeartbeatBodyBytes = 16 * 1024 * 1024 +) + +var hopByHopHeaders = map[string]struct{}{ + "Connection": {}, + "Keep-Alive": {}, + "Proxy-Authenticate": {}, + "Proxy-Authorization": {}, + "Te": {}, + "Trailers": {}, + "Transfer-Encoding": {}, + "Upgrade": {}, +} + +type Stats struct { + FastExecSession atomic.Int64 + FastExecStart atomic.Int64 + FastJobRead atomic.Int64 + FastFileGet atomic.Int64 + FastUpload atomic.Int64 + UpstreamFallbacks atomic.Int64 + UpstreamDirect atomic.Int64 + ActiveRequests atomic.Int64 +} + +type GatewayFrontDoor struct { + upstreamURL *url.URL + upstreamProxy *httputil.ReverseProxy + workerClient *http.Client + seedClient *http.Client + creds Credentials + execSigner *ExecSessionRoutes + state *RouteState + stats Stats + now func() time.Time +} + +func NewGatewayFrontDoor( + upstreamRaw string, + creds Credentials, + heartbeatTTL time.Duration, + routeTTL time.Duration, +) (*GatewayFrontDoor, error) { + upstreamURL, err := url.Parse(upstreamRaw) + if err != nil { + return nil, err + } + signer, err := NewExecSessionRoutes(creds.GatewayToken) + if err != nil { + return nil, err + } + workerTransport := &http.Transport{ + Proxy: nil, + DialContext: (&net.Dialer{ + Timeout: 5 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + MaxIdleConns: 4096, + MaxIdleConnsPerHost: 512, + MaxConnsPerHost: 0, + IdleConnTimeout: 90 * time.Second, + ResponseHeaderTimeout: 95 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + DisableCompression: true, + } + upstreamTransport := &http.Transport{ + Proxy: nil, + DialContext: (&net.Dialer{ + Timeout: 5 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + MaxIdleConns: 256, + MaxIdleConnsPerHost: 256, + IdleConnTimeout: 90 * time.Second, + ResponseHeaderTimeout: 360 * time.Second, + DisableCompression: true, + } + state := NewRouteState(heartbeatTTL, routeTTL) + fd := &GatewayFrontDoor{ + upstreamURL: upstreamURL, + workerClient: &http.Client{ + Transport: workerTransport, + }, + seedClient: &http.Client{ + Transport: upstreamTransport, + Timeout: 10 * time.Second, + }, + creds: creds, + execSigner: signer, + state: state, + now: time.Now, + } + proxy := &httputil.ReverseProxy{ + Director: func(req *http.Request) { + req.URL.Scheme = upstreamURL.Scheme + req.URL.Host = upstreamURL.Host + req.Host = upstreamURL.Host + req.Header.Del(routeHintHeader) + req.Header.Set(frontDoorHeader, "1") + }, + Transport: upstreamTransport, + ModifyResponse: func(resp *http.Response) error { + if hint := resp.Header.Get(routeHintHeader); hint != "" { + resp.Header.Del(routeHintHeader) + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + if entry, ok := ParseRouteHint(hint); ok { + fd.state.SetSandboxRoute(entry, fd.now()) + } + } + } + return nil + }, + ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { + writeJSON(w, http.StatusBadGateway, map[string]any{ + "error": "gateway upstream unavailable", + "error_code": "gateway_upstream_unavailable", + "retryable": true, + }) + }, + } + fd.upstreamProxy = proxy + return fd, nil +} + +// SeedWorkers fetches /v1/nodes from upstream Python to warm the worker table. +func (g *GatewayFrontDoor) SeedWorkers(ctx context.Context) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(g.upstreamURL.String(), "/")+"/v1/nodes", nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+g.creds.GatewayToken) + resp, err := g.seedClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil + } + body, err := io.ReadAll(io.LimitReader(resp.Body, 16*1024*1024)) + if err != nil { + return err + } + now := g.now() + for _, w := range parseNodesList(body, now, g.state.heartbeatTTL) { + g.state.UpsertWorker(w, now) + } + return nil +} + +func (g *GatewayFrontDoor) ServeHTTP(w http.ResponseWriter, r *http.Request) { + g.stats.ActiveRequests.Add(1) + defer g.stats.ActiveRequests.Add(-1) + + // Never trust internal headers from external callers. + r.Header.Del(routeHintHeader) + r.Header.Del(frontDoorHeader) + + parsed := classifyRequest(r.Method, r.URL.Path) + switch parsed.Kind { + case RouteStats: + g.handleStats(w, r) + return + case RouteHeartbeat: + g.handleHeartbeat(w, r) + return + case RouteSandboxEvict: + g.state.EvictSandbox(parsed.SandboxID) + g.stats.UpstreamDirect.Add(1) + g.upstreamProxy.ServeHTTP(w, r) + return + case RouteBatchEvict: + g.state.EvictAllSandboxes() + g.stats.UpstreamDirect.Add(1) + g.upstreamProxy.ServeHTTP(w, r) + return + case RouteExecSession: + if g.tryExecSessionFastPath(w, r, parsed) { + return + } + case RouteSandboxExecStart: + if g.tryExecStartFastPath(w, r, parsed) { + return + } + case RouteSandboxJobRead: + if g.tryDirectGetFastPath(w, r, parsed, &g.stats.FastJobRead) { + return + } + case RouteSandboxFileGet: + if g.tryDirectGetFastPath(w, r, parsed, &g.stats.FastFileGet) { + return + } + case RouteSandboxUpload: + if g.tryUploadFastPath(w, r, parsed) { + return + } + } + + g.stats.UpstreamDirect.Add(1) + g.upstreamProxy.ServeHTTP(w, r) +} + +func (g *GatewayFrontDoor) handleStats(w http.ResponseWriter, r *http.Request) { + if !g.creds.AuthorizeGatewayToken(r.Header) { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "unauthorized"}) + return + } + freshWorkers, cachedRoutes := g.state.Counts(g.now()) + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "fresh_workers": freshWorkers, + "cached_routes": cachedRoutes, + "active_requests": g.stats.ActiveRequests.Load(), + "fast_exec_session": g.stats.FastExecSession.Load(), + "fast_exec_start": g.stats.FastExecStart.Load(), + "fast_job_read": g.stats.FastJobRead.Load(), + "fast_file_get": g.stats.FastFileGet.Load(), + "fast_upload": g.stats.FastUpload.Load(), + "upstream_fallbacks": g.stats.UpstreamFallbacks.Load(), + "upstream_direct": g.stats.UpstreamDirect.Load(), + }) +} + +func (g *GatewayFrontDoor) handleHeartbeat(w http.ResponseWriter, r *http.Request) { + // Tee the heartbeat body so we update our in-memory worker table only after + // upstream Python verifies the heartbeat token and accepts it (HTTP 200). + body, err := io.ReadAll(io.LimitReader(r.Body, maxHeartbeatBodyBytes+1)) + if err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "failed to read heartbeat body"}) + return + } + if int64(len(body)) > maxHeartbeatBodyBytes { + writeJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": "heartbeat body too large"}) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + g.stats.UpstreamDirect.Add(1) + g.upstreamProxy.ServeHTTP(rec, r) + if rec.status >= 200 && rec.status < 300 { + now := g.now() + if worker, ok := parseHeartbeatBody(body, now, g.state.heartbeatTTL); ok { + g.state.UpsertWorker(worker, now) + } + } +} + +func (g *GatewayFrontDoor) tryExecSessionFastPath(w http.ResponseWriter, r *http.Request, parsed ParsedRoute) bool { + if !g.creds.AuthorizeSDKRoute(r.Header) { + return false // Let upstream emit exact auth error format. + } + signed, ok := g.execSigner.Decode(parsed.SessionID) + if !ok { + return false // Let upstream emit 404 exec_session_not_found. + } + worker, ok := g.state.FreshWorker(signed.JobID, g.now()) + if !ok { + g.stats.UpstreamFallbacks.Add(1) + return false + } + // Reject event polls with non-empty body (matches control_plane.py). + if parsed.Action == "events" { + if len(r.TransferEncoding) > 0 || (r.ContentLength > 0) { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "event polls must not contain a request body"}) + return true + } + } + resp, err := g.doWorkerRequest(r.Context(), r.Method, worker.NodeURL, r.URL.RequestURI(), r.Header, r.Body, r.ContentLength, nil) + if err != nil { + // For safe GETs, fall back to Python so HeartbeatIngest.refresh runs. + if r.Method == http.MethodGet { + g.stats.UpstreamFallbacks.Add(1) + return false + } + writeJSON(w, http.StatusServiceUnavailable, map[string]any{ + "error": "sandbox worker transport failed", + "error_code": "sandbox_worker_unreachable", + "retryable": true, + }) + return true + } + defer resp.Body.Close() + g.stats.FastExecSession.Add(1) + copyResponse(w, resp) + return true +} + +func (g *GatewayFrontDoor) tryExecStartFastPath(w http.ResponseWriter, r *http.Request, parsed ParsedRoute) bool { + if !g.creds.AuthorizeSDKRoute(r.Header) { + return false + } + route, worker, ok := g.state.LookupSandbox(parsed.SandboxID, g.now()) + if !ok { + return false + } + if r.ContentLength > maxExecStartBodyBytes { + return false + } + body, err := io.ReadAll(io.LimitReader(r.Body, maxExecStartBodyBytes+1)) + if err != nil || len(body) > maxExecStartBodyBytes { + r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(body), r.Body)) + return false + } + prefix, err := g.execSigner.Prefix(SignedExecRoute{ + SandboxID: route.SandboxID, + SandboxGeneration: route.Generation, + NodeID: route.NodeID, + JobID: route.JobID, + IssuedAt: g.now().Unix(), + }) + if err != nil { + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + return false + } + extra := map[string]string{execSessionPrefixHeader: prefix} + resp, err := g.doWorkerRequest(r.Context(), r.Method, worker.NodeURL, r.URL.RequestURI(), r.Header, bytes.NewReader(body), int64(len(body)), extra) + if err != nil || shouldFallbackStatus(resp.StatusCode) { + if resp != nil { + io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024)) + resp.Body.Close() + } + g.state.EvictSandbox(parsed.SandboxID) + g.stats.UpstreamFallbacks.Add(1) + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + return false + } + defer resp.Body.Close() + g.stats.FastExecStart.Add(1) + copyResponse(w, resp) + return true +} + +func (g *GatewayFrontDoor) tryDirectGetFastPath(w http.ResponseWriter, r *http.Request, parsed ParsedRoute, counter *atomic.Int64) bool { + if !g.creds.AuthorizeSDKRoute(r.Header) { + return false + } + _, worker, ok := g.state.LookupSandbox(parsed.SandboxID, g.now()) + if !ok { + return false + } + resp, err := g.doWorkerRequest(r.Context(), r.Method, worker.NodeURL, r.URL.RequestURI(), r.Header, nil, 0, nil) + if err != nil || shouldFallbackStatus(resp.StatusCode) { + if resp != nil { + io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024)) + resp.Body.Close() + } + g.state.EvictSandbox(parsed.SandboxID) + g.stats.UpstreamFallbacks.Add(1) + return false + } + defer resp.Body.Close() + counter.Add(1) + copyResponse(w, resp) + return true +} + +func (g *GatewayFrontDoor) tryUploadFastPath(w http.ResponseWriter, r *http.Request, parsed ParsedRoute) bool { + if !g.creds.AuthorizeSDKRoute(r.Header) { + return false + } + route, worker, ok := g.state.LookupSandbox(parsed.SandboxID, g.now()) + if !ok { + return false + } + // Require known Content-Length for zero-copy framed upload streaming. + if r.ContentLength < 0 { + return false + } + extra := map[string]string{ + sandboxGenerationHeader: strconv.FormatInt(route.Generation, 10), + } + resp, err := g.doWorkerRequest(r.Context(), r.Method, worker.NodeURL, r.URL.RequestURI(), r.Header, r.Body, r.ContentLength, extra) + if err != nil { + g.state.EvictSandbox(parsed.SandboxID) + writeJSON(w, http.StatusServiceUnavailable, map[string]any{ + "error": "sandbox worker transport failed during upload", + "error_code": "sandbox_worker_unreachable", + "retryable": true, + }) + return true + } + defer resp.Body.Close() + if shouldFallbackStatus(resp.StatusCode) { + g.state.EvictSandbox(parsed.SandboxID) + } + g.stats.FastUpload.Add(1) + copyResponse(w, resp) + return true +} + +func shouldFallbackStatus(code int) bool { + return code == http.StatusNotFound || code == http.StatusConflict || code == http.StatusServiceUnavailable +} + +func (g *GatewayFrontDoor) doWorkerRequest( + ctx context.Context, + method string, + workerBase string, + requestURI string, + incomingHeaders http.Header, + body io.Reader, + contentLength int64, + extra map[string]string, +) (*http.Response, error) { + targetURL := strings.TrimRight(workerBase, "/") + requestURI + req, err := http.NewRequestWithContext(ctx, method, targetURL, body) + if err != nil { + return nil, err + } + if contentLength > 0 { + req.ContentLength = contentLength + } + for k, vals := range incomingHeaders { + ck := http.CanonicalHeaderKey(k) + if _, skip := hopByHopHeaders[ck]; skip { + continue + } + // Strip client credentials and internal headers before forwarding. + if ck == "Authorization" || ck == "X-Ucloud-Sandbox-Token" || ck == "Host" || ck == "Content-Length" { + continue + } + for _, v := range vals { + req.Header.Add(k, v) + } + } + req.Header.Set("Authorization", "Bearer "+g.creds.NodeControlToken) + for k, v := range extra { + req.Header.Set(k, v) + } + return g.workerClient.Do(req) +} + +func copyResponse(w http.ResponseWriter, resp *http.Response) { + for k, vals := range resp.Header { + ck := http.CanonicalHeaderKey(k) + if _, skip := hopByHopHeaders[ck]; skip { + continue + } + if ck == http.CanonicalHeaderKey(routeHintHeader) { + continue + } + for _, v := range vals { + w.Header().Add(k, v) + } + } + w.WriteHeader(resp.StatusCode) + _, _ = io.Copy(w, resp.Body) +} + +func writeJSON(w http.ResponseWriter, status int, payload map[string]any) { + encoded, _ := json.Marshal(payload) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(len(encoded))) + w.WriteHeader(status) + _, _ = w.Write(encoded) +} + +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (r *statusRecorder) WriteHeader(code int) { + r.status = code + r.ResponseWriter.WriteHeader(code) +} diff --git a/runtime/gatewayd/routes.go b/runtime/gatewayd/routes.go new file mode 100644 index 00000000..fec53efa --- /dev/null +++ b/runtime/gatewayd/routes.go @@ -0,0 +1,355 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +const ( + frontDoorHeader = "X-UCloud-Gateway-Front-Door" + routeHintHeader = "X-UCloud-Gateway-Route" + sandboxGenerationHeader = "X-UCloud-Sandbox-Generation" + maxCachedRoutes = 65536 +) + +type RouteKind int + +const ( + RoutePassthrough RouteKind = iota + RouteExecSession + RouteSandboxExecStart + RouteSandboxJobRead + RouteSandboxFileGet + RouteSandboxUpload + RouteSandboxEvict + RouteBatchEvict + RouteHeartbeat + RouteStats +) + +type ParsedRoute struct { + Kind RouteKind + SandboxID string + SessionID string + Action string +} + +func classifyRequest(method, rawPath string) ParsedRoute { + method = strings.ToUpper(method) + if method == http.MethodGet && rawPath == "/_gatewayd/stats" { + return ParsedRoute{Kind: RouteStats} + } + if method == http.MethodPost && rawPath == "/v1/nodes/heartbeat" { + return ParsedRoute{Kind: RouteHeartbeat} + } + if method == http.MethodDelete && strings.HasPrefix(rawPath, "/v1/sandboxes:batch/") { + return ParsedRoute{Kind: RouteBatchEvict} + } + if strings.HasPrefix(rawPath, "/v1/exec/") { + rest := rawPath[len("/v1/exec/"):] + parts := strings.Split(rest, "/") + if len(parts) >= 1 && parts[0] != "" { + sessionID, err := url.PathUnescape(parts[0]) + if err == nil && !strings.Contains(sessionID, "/") { + if len(parts) == 1 && method == http.MethodGet { + return ParsedRoute{Kind: RouteExecSession, SessionID: sessionID, Action: "status"} + } + if len(parts) == 2 { + switch { + case parts[1] == "events" && method == http.MethodGet: + return ParsedRoute{Kind: RouteExecSession, SessionID: sessionID, Action: "events"} + case (parts[1] == "stdin" || parts[1] == "close-stdin" || parts[1] == "signal") && method == http.MethodPost: + return ParsedRoute{Kind: RouteExecSession, SessionID: sessionID, Action: parts[1]} + } + } + } + } + return ParsedRoute{Kind: RoutePassthrough} + } + if !strings.HasPrefix(rawPath, "/v1/sandboxes/") { + return ParsedRoute{Kind: RoutePassthrough} + } + rest := rawPath[len("/v1/sandboxes/"):] + rawParts := strings.Split(rest, "/") + if len(rawParts) == 0 { + return ParsedRoute{Kind: RoutePassthrough} + } + parts := make([]string, len(rawParts)) + for i, seg := range rawParts { + if seg == "" { + return ParsedRoute{Kind: RoutePassthrough} + } + decoded, err := url.PathUnescape(seg) + if err != nil || strings.Contains(decoded, "/") { + return ParsedRoute{Kind: RoutePassthrough} + } + parts[i] = decoded + } + sandboxID := parts[0] + suffix := parts[1:] + + switch { + case len(suffix) == 0 && method == http.MethodDelete: + return ParsedRoute{Kind: RouteSandboxEvict, SandboxID: sandboxID, Action: "delete"} + case len(suffix) == 1 && (suffix[0] == "park" || suffix[0] == "wake" || suffix[0] == "detach" || suffix[0] == "migration") && (method == http.MethodPost || method == http.MethodDelete): + return ParsedRoute{Kind: RouteSandboxEvict, SandboxID: sandboxID, Action: suffix[0]} + case len(suffix) == 1 && suffix[0] == "exec" && method == http.MethodPost: + return ParsedRoute{Kind: RouteSandboxExecStart, SandboxID: sandboxID, Action: "exec"} + case len(suffix) == 1 && suffix[0] == "files" && method == http.MethodGet: + return ParsedRoute{Kind: RouteSandboxFileGet, SandboxID: sandboxID, Action: "files"} + case len(suffix) == 1 && (suffix[0] == "files" || suffix[0] == "archive") && method == http.MethodPut: + return ParsedRoute{Kind: RouteSandboxUpload, SandboxID: sandboxID, Action: suffix[0]} + case len(suffix) == 2 && suffix[0] == "jobs" && method == http.MethodGet: + return ParsedRoute{Kind: RouteSandboxJobRead, SandboxID: sandboxID, Action: "job_status"} + case len(suffix) == 4 && suffix[0] == "jobs" && suffix[2] == "logs" && (suffix[3] == "stdout" || suffix[3] == "stderr") && method == http.MethodGet: + return ParsedRoute{Kind: RouteSandboxJobRead, SandboxID: sandboxID, Action: "job_logs"} + default: + return ParsedRoute{Kind: RoutePassthrough, SandboxID: sandboxID} + } +} + +type WorkerEntry struct { + JobID string + NodeID string + NodeURL string + NodeEpoch string + FreshUntil time.Time + Draining bool +} + +type SandboxRouteEntry struct { + SandboxID string + NodeID string + JobID string + Generation int64 + NodeURL string + ExpiresAt time.Time +} + +type RouteState struct { + mu sync.RWMutex + workers map[string]WorkerEntry + routes map[string]SandboxRouteEntry + heartbeatTTL time.Duration + routeTTL time.Duration +} + +func NewRouteState(heartbeatTTL, routeTTL time.Duration) *RouteState { + return &RouteState{ + workers: make(map[string]WorkerEntry), + routes: make(map[string]SandboxRouteEntry), + heartbeatTTL: heartbeatTTL, + routeTTL: routeTTL, + } +} + +func (s *RouteState) UpsertWorker(w WorkerEntry, now time.Time) { + if w.JobID == "" || w.NodeURL == "" { + return + } + w.NodeURL = strings.TrimRight(w.NodeURL, "/") + if w.FreshUntil.IsZero() { + w.FreshUntil = now.Add(s.heartbeatTTL) + } + s.mu.Lock() + defer s.mu.Unlock() + prev, exists := s.workers[w.JobID] + s.workers[w.JobID] = w + if exists && prev.NodeEpoch != "" && w.NodeEpoch != "" && prev.NodeEpoch != w.NodeEpoch { + // Rebooted worker: immediately evict every cached sandbox route on it. + for id, r := range s.routes { + if r.JobID == w.JobID { + delete(s.routes, id) + } + } + } +} + +func (s *RouteState) FreshWorker(jobID string, now time.Time) (WorkerEntry, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + w, ok := s.workers[jobID] + if !ok || w.NodeURL == "" || !now.Before(w.FreshUntil) { + return WorkerEntry{}, false + } + return w, true +} + +func (s *RouteState) SetSandboxRoute(entry SandboxRouteEntry, now time.Time) { + if entry.SandboxID == "" || entry.JobID == "" || entry.NodeURL == "" || entry.Generation <= 0 { + return + } + entry.NodeURL = strings.TrimRight(entry.NodeURL, "/") + entry.ExpiresAt = now.Add(s.routeTTL) + s.mu.Lock() + defer s.mu.Unlock() + if len(s.routes) >= maxCachedRoutes { + // Evict expired entries first; if still full, drop arbitrary entries to keep memory bounded. + for id, r := range s.routes { + if !now.Before(r.ExpiresAt) { + delete(s.routes, id) + } + } + if len(s.routes) >= maxCachedRoutes { + for id := range s.routes { + delete(s.routes, id) + if len(s.routes) < maxCachedRoutes*3/4 { + break + } + } + } + } + s.routes[entry.SandboxID] = entry +} + +func (s *RouteState) LookupSandbox(sandboxID string, now time.Time) (SandboxRouteEntry, WorkerEntry, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + r, ok := s.routes[sandboxID] + if !ok || !now.Before(r.ExpiresAt) { + return SandboxRouteEntry{}, WorkerEntry{}, false + } + w, ok := s.workers[r.JobID] + if !ok || w.NodeURL == "" || !now.Before(w.FreshUntil) { + return SandboxRouteEntry{}, WorkerEntry{}, false + } + // Always prefer the freshest heartbeat URL for the worker. + r.NodeURL = w.NodeURL + return r, w, true +} + +func (s *RouteState) EvictSandbox(sandboxID string) { + if sandboxID == "" { + return + } + s.mu.Lock() + delete(s.routes, sandboxID) + s.mu.Unlock() +} + +func (s *RouteState) EvictAllSandboxes() { + s.mu.Lock() + clear(s.routes) + s.mu.Unlock() +} + +func (s *RouteState) Counts(now time.Time) (freshWorkers int, cachedRoutes int) { + s.mu.RLock() + defer s.mu.RUnlock() + for _, w := range s.workers { + if now.Before(w.FreshUntil) { + freshWorkers++ + } + } + for _, r := range s.routes { + if now.Before(r.ExpiresAt) { + cachedRoutes++ + } + } + return freshWorkers, cachedRoutes +} + +// ParseRouteHint parses "sandbox_id|node_id|job_id|generation|node_url". +func ParseRouteHint(raw string) (SandboxRouteEntry, bool) { + parts := strings.SplitN(strings.TrimSpace(raw), "|", 5) + if len(parts) != 5 { + return SandboxRouteEntry{}, false + } + gen, err := strconv.ParseInt(parts[3], 10, 64) + if err != nil || gen <= 0 { + return SandboxRouteEntry{}, false + } + if parts[0] == "" || parts[1] == "" || parts[2] == "" || parts[4] == "" { + return SandboxRouteEntry{}, false + } + return SandboxRouteEntry{ + SandboxID: parts[0], + NodeID: parts[1], + JobID: parts[2], + Generation: gen, + NodeURL: strings.TrimRight(parts[4], "/"), + }, true +} + +type heartbeatBody struct { + JobID string `json:"job_id"` + NodeID string `json:"node_id"` + NodeURL string `json:"node_url"` + NodeEpoch string `json:"node_epoch"` + Draining bool `json:"draining"` + ReceivedAt string `json:"received_at"` + UpdatedAt string `json:"updated_at"` +} + +func parseHeartbeatBody(body []byte, now time.Time, ttl time.Duration) (WorkerEntry, bool) { + var hb heartbeatBody + if err := json.Unmarshal(body, &hb); err != nil { + return WorkerEntry{}, false + } + if hb.JobID == "" || hb.NodeURL == "" { + return WorkerEntry{}, false + } + ts := now + for _, raw := range []string{hb.ReceivedAt, hb.UpdatedAt} { + if raw == "" { + continue + } + if parsed, err := time.Parse(time.RFC3339Nano, raw); err == nil { + ts = parsed + break + } + } + // For live incoming POST /v1/nodes/heartbeat, received_at isn't set yet; use now. + if hb.ReceivedAt == "" { + ts = now + } + return WorkerEntry{ + JobID: hb.JobID, + NodeID: hb.NodeID, + NodeURL: strings.TrimRight(hb.NodeURL, "/"), + NodeEpoch: hb.NodeEpoch, + FreshUntil: ts.Add(ttl), + Draining: hb.Draining, + }, true +} + +type nodesListResponse struct { + Nodes []heartbeatBody `json:"nodes"` +} + +func parseNodesList(body []byte, now time.Time, ttl time.Duration) []WorkerEntry { + var resp nodesListResponse + if err := json.Unmarshal(body, &resp); err != nil { + return nil + } + out := make([]WorkerEntry, 0, len(resp.Nodes)) + for _, n := range resp.Nodes { + if n.JobID == "" || n.NodeURL == "" { + continue + } + ts := now + for _, raw := range []string{n.ReceivedAt, n.UpdatedAt} { + if raw == "" { + continue + } + if parsed, err := time.Parse(time.RFC3339Nano, raw); err == nil { + ts = parsed + break + } + } + out = append(out, WorkerEntry{ + JobID: n.JobID, + NodeID: n.NodeID, + NodeURL: strings.TrimRight(n.NodeURL, "/"), + NodeEpoch: n.NodeEpoch, + FreshUntil: ts.Add(ttl), + Draining: n.Draining, + }) + } + return out +} diff --git a/runtime/noded/src/exec_front.rs b/runtime/noded/src/exec_front.rs index 290215d9..c47c1df4 100644 --- a/runtime/noded/src/exec_front.rs +++ b/runtime/noded/src/exec_front.rs @@ -222,12 +222,26 @@ impl ExecFront { // Python's own answer for anything malformed, tty and post-fence checks. let exec = match ExecRequest::parse(&sandbox_id, &bytes, query, prefix) { Ok(exec) => exec, + Err(err) if self.standalone => return Outcome::Response(respond(err.reply())), Err(_) => { forwarded("request"); return forward(bytes); } }; - if exec.tty || exec.check_direct().is_err() { + if let Err(err) = exec.check_direct() { + if self.standalone { + return Outcome::Response(respond(err.reply())); + } + forwarded("tty or post-fence checks"); + return forward(bytes); + } + if exec.tty { + if self.standalone { + return Outcome::Response(respond(Reply::new( + 400, + serde_json::json!({"error": "interactive tty exec is not supported"}), + ))); + } forwarded("tty or post-fence checks"); return forward(bytes); } diff --git a/sandboxes/chunk_index.py b/sandboxes/chunk_index.py index 15eac0a4..d2571635 100644 --- a/sandboxes/chunk_index.py +++ b/sandboxes/chunk_index.py @@ -58,9 +58,11 @@ # Bootstraps and chunk maps are named by their digest, so they never change: # each process keeps the recently read and written ones (parents of sandbox # builds are read for every build on them). -META_CACHE_BYTES = 256 * 1024 ** 2 -# The index keeps blobs' tail tables (chunk ids, 32 bytes each) the same way. -TAIL_CACHE_IDS = 2_000_000 +META_CACHE_BYTES = 64 * 1024 ** 2 +# The index keeps blobs' tail tables (chunk ids, 32 bytes each) the same way; +# bounded so Python object overhead stays under ~40 MiB and leaves host RAM for +# Linux page cache serving ucloud-chunk-serve reads. +TAIL_CACHE_IDS = 250_000 _SCHEMA = """ CREATE TABLE IF NOT EXISTS chunks (id BLOB PRIMARY KEY, pack INTEGER, off INTEGER, clen INTEGER, ulen INTEGER, flags INTEGER, condemned INTEGER DEFAULT 0) WITHOUT ROWID; @@ -360,6 +362,9 @@ def _connect(self): connection.execute("PRAGMA journal_mode=WAL") # A commit reply promises the rows exist; keep them across power loss. connection.execute("PRAGMA synchronous=FULL") + # Cap per-thread SQLite page cache at 8 MiB so long-lived multi-thread + # index servers do not starve the store node's Linux page cache. + connection.execute("PRAGMA cache_size=-8000") return connection def _reader(self): @@ -552,7 +557,7 @@ class ChunkIndexService: since builders hold the S3 key. """ - def __init__(self, index, store, *, locator_cache=64, store_url=None): + def __init__(self, index, store, *, locator_cache=16, store_url=None): self.index, self.store, self.store_url = index, store, store_url and store_url.rstrip("/") self._maps, self._locators, self._guard = OrderedDict(), OrderedDict(), threading.Lock() self._locator_cache = locator_cache diff --git a/sandboxes/gateway/create.py b/sandboxes/gateway/create.py index 8488d853..7c1c03d6 100644 --- a/sandboxes/gateway/create.py +++ b/sandboxes/gateway/create.py @@ -279,7 +279,10 @@ def _attempt( self.registry_refs.record_image_used(spec.image) root.set_attribute("outcome", "scheduled") root.set_attribute("node_id", heartbeat.node_id) - ex._send_proxied_response(response) + from .sandbox_proxy import gateway_route_hint_headers + ex._send_proxied_response( + response, extra_headers=gateway_route_hint_headers(ex, confirmed), + ) return None rejected = node_create_rejection_reason(response) if rejected is not None: diff --git a/sandboxes/gateway/sandbox_proxy.py b/sandboxes/gateway/sandbox_proxy.py index 2a33c4c6..899f7c66 100644 --- a/sandboxes/gateway/sandbox_proxy.py +++ b/sandboxes/gateway/sandbox_proxy.py @@ -84,6 +84,31 @@ SANDBOX_OPERATION_ID_HEADER = "X-UCloud-Sandbox-Operation-Id" SANDBOX_TRANSPORT_RESET_HEADER = "X-UCloud-Sandbox-Transport-Reset" SANDBOX_TRANSPORT_EPOCH_HEADER = "X-UCloud-Sandbox-Transport-Epoch" +GATEWAY_FRONT_DOOR_HEADER = "X-UCloud-Gateway-Front-Door" +GATEWAY_ROUTE_HINT_HEADER = "X-UCloud-Gateway-Route" + + +def gateway_route_hint_headers(ex: Any, route: SandboxRoute | None) -> dict[str, str] | None: + """Emit an internal live-route hint only when fronted by ucloud-gatewayd.""" + headers = getattr(ex, "headers", None) + if route is None or headers is None or headers.get(GATEWAY_FRONT_DOOR_HEADER) != "1": + return None + if ( + not route.delete_operation_id + and route.worker_state == "attached" + and (route.state or "").lower() == "running" + and route.node_id + and route.job_id + and route.node_url + and route.generation > 0 + ): + return { + GATEWAY_ROUTE_HINT_HEADER: ( + f"{route.sandbox_id}|{route.node_id}|{route.job_id}|" + f"{route.generation}|{route.node_url}" + ) + } + return None # --------------------------------------------------------------------------- @@ -840,6 +865,14 @@ def finalize_sandbox_proxy_response( } if transport_reset: response_headers[SANDBOX_TRANSPORT_RESET_HEADER] = "true" + if ( + 200 <= response.status < 300 + and ex.command != "DELETE" + and lifecycle_action != "park" + ): + hint = gateway_route_hint_headers(ex, route) + if hint: + response_headers = {**(response_headers or {}), **hint} ex._send_proxied_response(response, extra_headers=response_headers) def route_sandbox_request_admitted( diff --git a/sandboxes/systemd.py b/sandboxes/systemd.py index c530415a..f8dfaac6 100644 --- a/sandboxes/systemd.py +++ b/sandboxes/systemd.py @@ -85,11 +85,25 @@ def run_registry_process(config, *, writer_lock: Path = REGISTRY_WRITER_LOCK, env=registry_process_environment(config, environ=environ)).returncode +def _is_mountpoint(mount_point: Path) -> bool: + if mount_point.is_mount(): + return True + try: + target = str(mount_point.resolve()) + for line in Path("/proc/self/mountinfo").read_text(encoding="utf-8").splitlines(): + parts = line.split(" ") + if len(parts) >= 5 and parts[4].replace("\\040", " ") == target: + return True + except OSError: + return False + return False + + def require_registry_mount(config: DeploymentConfig) -> None: if config.registry_store.kind != "filesystem": return mount_point = Path(config.registry_mount_point) - if not mount_point.is_mount(): + if not _is_mountpoint(mount_point): raise RuntimeError(f"registry storage is not mounted at {mount_point}") diff --git a/scripts/check.sh b/scripts/check.sh index 24b627c1..cf44a7a5 100644 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -84,6 +84,11 @@ if command -v go >/dev/null 2>&1; then CGO_ENABLED=0 GOTOOLCHAIN=local go vet ./... CGO_ENABLED=0 GOTOOLCHAIN=local go test ./... ) + ( + cd runtime/gatewayd + CGO_ENABLED=0 GOTOOLCHAIN=local go vet ./... + CGO_ENABLED=0 GOTOOLCHAIN=local go test ./... + ) else echo "Go is required for the managed-process contract tests" >&2 exit 1 diff --git a/tests/test_gatewayd_contract.py b/tests/test_gatewayd_contract.py new file mode 100644 index 00000000..b2eba32e --- /dev/null +++ b/tests/test_gatewayd_contract.py @@ -0,0 +1,203 @@ +"""Contract tests for the Go ucloud-gatewayd front door in front of LocalFleet.""" + +from __future__ import annotations + +from http.client import HTTPConnection +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +from tempfile import TemporaryDirectory +import unittest +from urllib.parse import urlparse + +from tests.harness import LocalFleet +from tests.support import wait_until + +TEST_TIER = "contract" +REPO_ROOT = Path(__file__).resolve().parents[1] +GATEWAYD_DIR = REPO_ROOT / "runtime" / "gatewayd" + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def _http_call( + base_url: str, + method: str, + path: str, + *, + token: str = "", + body: bytes | None = None, + content_type: str = "application/json", + timeout: float = 30.0, +) -> tuple[int, dict[str, str], bytes]: + parsed = urlparse(base_url) + conn = HTTPConnection(parsed.hostname, parsed.port, timeout=timeout) + headers: dict[str, str] = {} + if token: + headers["Authorization"] = f"Bearer {token}" + if body is not None: + headers["Content-Type"] = content_type + headers["Content-Length"] = str(len(body)) + try: + conn.request(method, path, body=body, headers=headers) + resp = conn.getresponse() + return resp.status, {k.lower(): v for k, v in resp.getheaders()}, resp.read() + finally: + conn.close() + + +@unittest.skipUnless(shutil.which("go") is not None, "Go toolchain required") +class GatewaydContractTests(unittest.TestCase): + def test_fast_path_exec_files_jobs_and_eviction_over_real_local_fleet(self) -> None: + with TemporaryDirectory() as raw_dir: + root = Path(raw_dir) + binary = root / "ucloud-gatewayd" + build = subprocess.run( + ["go", "build", "-o", str(binary), "."], + cwd=str(GATEWAYD_DIR), + env={**os.environ, "CGO_ENABLED": "0", "GOTOOLCHAIN": "local"}, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(build.returncode, 0, build.stdout + build.stderr) + + with LocalFleet(nodes=1) as fleet: + gw_tok = root / "gateway.token" + sb_tok = root / "sandbox.token" + nc_tok = root / "node-control.token" + gw_tok.write_text(fleet.tokens.gateway, encoding="utf-8") + sb_tok.write_text(fleet.tokens.sandbox_api, encoding="utf-8") + nc_tok.write_text(fleet.tokens.node_control, encoding="utf-8") + + port = _free_port() + gd_url = f"http://127.0.0.1:{port}" + proc = subprocess.Popen( + [ + str(binary), + "--listen", f"127.0.0.1:{port}", + "--upstream", fleet.gateway_url, + "--gateway-token-file", str(gw_tok), + "--sandbox-api-token-file", str(sb_tok), + "--node-control-token-file", str(nc_tok), + "--heartbeat-ttl", "45s", + "--route-cache-ttl", "30s", + "--seed-interval", "2s", + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + try: + def ready() -> bool: + try: + st, _, raw = _http_call(gd_url, "GET", "/_gatewayd/stats", token=fleet.tokens.gateway) + return st == 200 and json.loads(raw).get("fresh_workers", 0) >= 1 + except OSError: + return False + + wait_until(ready, timeout=15.0, message="ucloud-gatewayd did not seed fresh workers") + + # 1. Create sandbox through gatewayd -> populates route cache, strips internal route header. + create_body = json.dumps({ + "id": "gd-e2e-1", + "image": fleet.image, + "cpus": 1, + "memory_mb": 256, + "disk_mb": 1024, + "network": "none", + "parkable": True, + }).encode("utf-8") + st, hdrs, raw = _http_call( + gd_url, "POST", "/v1/sandboxes", + token=fleet.tokens.sandbox_api, body=create_body, + ) + self.assertEqual(st, 201, raw.decode(errors="replace")) + self.assertNotIn("x-ucloud-gateway-route", hdrs) + + # 2. Malformed exec payload hits standalone ucloud-noded -> 400 (not 404). + st, _, raw = _http_call( + gd_url, "POST", "/v1/sandboxes/gd-e2e-1/exec", + token=fleet.tokens.sandbox_api, + body=json.dumps({"command": ["echo", "bad"]}).encode("utf-8"), + ) + self.assertEqual(st, 400, raw.decode(errors="replace")) + + # 3. Valid exec start + events poll both run on the Go fast path. + exec_payload = json.dumps({ + "command": ["echo", "hello-gatewayd"], + "env": {}, + "working_dir": None, + "stdin": False, + "tty": False, + }).encode("utf-8") + st, _, raw = _http_call( + gd_url, "POST", "/v1/sandboxes/gd-e2e-1/exec", + token=fleet.tokens.sandbox_api, body=exec_payload, + ) + self.assertEqual(st, 201, raw.decode(errors="replace")) + session_id = json.loads(raw)["session"]["id"] + + st, _, raw = _http_call( + gd_url, "GET", f"/v1/exec/{session_id}/events?after=0&wait_seconds=5", + token=fleet.tokens.sandbox_api, + ) + self.assertEqual(st, 200, raw.decode(errors="replace")) + + # 4. File PUT + GET both stream directly on the Go fast path. + file_bytes = b"streamed-via-gatewayd\n" + st, _, raw = _http_call( + gd_url, "PUT", "/v1/sandboxes/gd-e2e-1/files?path=%2Fworkspace%2Fgd.txt", + token=fleet.tokens.sandbox_api, body=file_bytes, + content_type="application/octet-stream", + ) + self.assertIn(st, (200, 201, 204), raw.decode(errors="replace")) + + st, _, got_bytes = _http_call( + gd_url, "GET", "/v1/sandboxes/gd-e2e-1/files?path=%2Fworkspace%2Fgd.txt", + token=fleet.tokens.sandbox_api, + ) + self.assertEqual(st, 200, got_bytes.decode(errors="replace")) + self.assertEqual(got_bytes, file_bytes) + + # Verify Go fast-path counters incremented across all hot paths. + st, _, stats_raw = _http_call(gd_url, "GET", "/_gatewayd/stats", token=fleet.tokens.gateway) + self.assertEqual(st, 200) + stats = json.loads(stats_raw) + self.assertGreaterEqual(stats["fast_exec_start"], 2) + self.assertGreaterEqual(stats["fast_exec_session"], 1) + self.assertGreaterEqual(stats["fast_upload"], 1) + self.assertGreaterEqual(stats["fast_file_get"], 1) + + # 5. Park evicts cached route immediately; delete cleans up. + st, _, raw = _http_call( + gd_url, "POST", "/v1/sandboxes/gd-e2e-1/park", + token=fleet.tokens.gateway, + body=json.dumps({"operation_id": "park-gd-1"}).encode("utf-8"), + ) + self.assertIn(st, (200, 202), raw.decode(errors="replace")) + st, _, stats_after_park = _http_call(gd_url, "GET", "/_gatewayd/stats", token=fleet.tokens.gateway) + self.assertEqual(json.loads(stats_after_park)["cached_routes"], 0) + + st, _, raw = _http_call( + gd_url, "DELETE", "/v1/sandboxes/gd-e2e-1", + token=fleet.tokens.sandbox_api, + ) + self.assertIn(st, (200, 204), raw.decode(errors="replace")) + finally: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_systemd.py b/tests/test_systemd.py index cb57cfd6..23a1f509 100644 --- a/tests/test_systemd.py +++ b/tests/test_systemd.py @@ -91,6 +91,7 @@ def test_registry_mount_fails_closed(self) -> None: config = DeploymentConfig.default() with ( patch.object(Path, "is_mount", return_value=False), + patch.object(Path, "read_text", return_value="1 0 8:1 / / rw - ext4 /dev/sda1 rw\n"), self.assertRaisesRegex( RuntimeError, "registry storage is not mounted", @@ -98,6 +99,16 @@ def test_registry_mount_fails_closed(self) -> None: ): require_registry_mount(config) + def test_registry_mount_accepts_linux_bind_mount_via_mountinfo(self) -> None: + config = DeploymentConfig.default() + mount_path = str(Path(config.registry_mount_point).resolve()) + mountinfo = f"99 1 8:1 /var/lib/ucloud-registry-local {mount_path} rw - ext4 /dev/sda1 rw\n" + with ( + patch.object(Path, "is_mount", return_value=False), + patch.object(Path, "read_text", return_value=mountinfo), + ): + require_registry_mount(config) + def test_registry_gc_restarts_registry_after_gc_failure(self) -> None: calls: list[list[str]] = [] From 9d94a7ce246e4bfa94e385c213ef0eb1cba0029d Mon Sep 17 00:00:00 2001 From: Rasmus Larsen Date: Wed, 2 Dec 2026 12:15:02 +0000 Subject: [PATCH 2/2] Add --port override to serve-control-plane for gatewayd fronting --- sandboxes/cli.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sandboxes/cli.py b/sandboxes/cli.py index 487c9b41..cbf9e703 100644 --- a/sandboxes/cli.py +++ b/sandboxes/cli.py @@ -319,6 +319,7 @@ def build_parser() -> argparse.ArgumentParser: ) add_config_args(serve) serve.add_argument("--host", default="0.0.0.0", help="Bind host.") + serve.add_argument("--port", type=int, default=None, help="Override bind port (defaults to config gateway_port).") serve.add_argument("--placement-worker", action="store_true", help="Run the private durable placement executor.") serve.add_argument("--check-placement-enabled", action="store_true", help=argparse.SUPPRESS) add_environment_registry_args(serve) @@ -955,9 +956,10 @@ def cmd_serve_control_plane(args: argparse.Namespace) -> int: attributes={"service.instance.id": f"{socket.gethostname()}-" + ("placement" if placement_role else f"gateway-{replica}")}, ) + listen_port = config.gateway_port + 1 if placement_role else (args.port if args.port is not None else config.gateway_port) server = build_server( '127.0.0.1' if placement_role else args.host, - config.gateway_port+1 if placement_role else config.gateway_port, + listen_port, config.control_state_file(), routing_file=config.routing_file(), gateway_bearer_token=read_required_token_file(