E2B Sandbox Metrics Alignment and Gateway/Podd Observability
此内容尚不支持你的语言。
- Source:
docs/enhancements/0029-e2b-sandbox-metrics/README.md- Status:
implemented- Area:
gateway- Milestone:
v0.7.0
| Stage | Status | Created | Updated | Owning Area |
|---|---|---|---|---|
alpha |
implemented |
2026-11-16 |
2026-11-16 |
gateway |
Table of Contents
Section titled “Table of Contents”- Release Signoff Checklist
- Summary
- Motivation
- Proposal
- Design Details
- Production Readiness Review Questionnaire (PRR)
- Implementation History
- Drawbacks
- Alternatives
Release Signoff Checklist
Section titled “Release Signoff Checklist”- Enhancement is scoped clearly with explicit Goals and Non-Goals.
- API / OpenAPI changes are additive and backward-compatible.
- Security invariants (zero-dependency Rust
podd, single-threadedpodd-init, zero-trust secret isolation) are preserved. - Dual-runtime behavior (Production Kubernetes
Kata + CSI Blockand Local DevelopmentDocker + Loopback ext4) is specified. - Test plan covers Rust unit tests (
cargo test) and Go race-checked tests (go test -race). - Graduation criteria for Alpha, Beta, and Stable are defined.
Summary
Section titled “Summary”CEP-0029 aligns CubePod with the upstream E2B Sandbox Metrics API (GET /sandboxes/{sandboxID}/metrics and GET /sandboxes/metrics) and closes observability gaps across podd-init, podd, and cubepod-gateway. It introduces in-guest resource sampling in podd (GET /metrics JSON SandboxMetric plus GET /v1/prometheus Prometheus text exposition), records volume bind-mount duration (volume_bind_duration_ms) in podd-init’s /run/cubepod/init-state.json, adds Gateway time-range filtering and per-sandbox bounded ring-buffer caching, and implements the Prometheus counters, gauges, and histograms specified across prior CEPs (CEP-0001, CEP-0002, CEP-0004, CEP-0018, CEP-0021, CEP-0022, CEP-0026, CEP-0027).
Motivation
Section titled “Motivation”- E2B SDK Compatibility Gap: Upstream E2B SDKs expose
sbx.get_metrics(start, end)(GET /sandboxes/{sandboxID}/metrics) and batch metrics (GET /sandboxes/metrics?sandboxIds=...) returningSandboxMetricsnapshots (timestamp,timestampUnix,cpuCount,cpuUsedPct,memUsed,memTotal,memCache,diskUsed,diskTotal). CubePod currently lacks both Gateway routes and in-guest/metricssampling inpodd. - Prometheus Metric Drift: Several earlier CEPs declared Prometheus metric names (such as
cubepod_e2b_requests_total,cubepod_e2b_request_duration_seconds,cubepod_panel_active_sessions,cubepod_secrets_operations_total,cubepod_secrets_store_count,cubepod_volume_mounts_total,cubepod_sandbox_forks_total,cubepod_gateway_crd_resyncs_total,cubepod_podd_active_processes,cubepod_podd_init_duration_milliseconds, andcubepod_podd_init_volume_bind_duration_ms) that were either not yet exported or differed slightly frommetrics.gonames (cubepod_gateway_http_requests_totalvscubepod_gateway_requests_total).
- E2B Single & Batch Sandbox Metrics: Implement
GET /sandboxes/{sandboxID}/metrics(?start=,?end=, optional?autoResume=false) returning[]SandboxMetric, andGET /sandboxes/metrics(?sandboxIds=a,b) returning{"sandboxes": {id: SandboxMetric}}. - Zero-Dependency Guest Resource Sampling (
podd): ImplementGET /metricsincrates/poddusing onlystdandlibcto sample/proc/stat,/proc/meminfo, cgroup v2/v1 limits, andlibc::statvfs, plus Prometheus exposition onGET /v1/prometheus(and/metrics?format=prometheusorAccept: text/plain). podd-initBind Timing: Measure volume bind-mount duration incrates/podd-initand persistvolume_bind_duration_msin/run/cubepod/init-state.json.- Complete Gateway Prometheus Exposition: Export all missing CEP metrics on
cubepod-gatewayGET /metricswhile keeping existingcubepod_gateway_http_requests_totalandcubepod_gateway_autoresume_totalintact for backward compatibility.
Non-Goals
Section titled “Non-Goals”- Long-term time-series database retention inside
cubepod-gateway(Alpha uses a bounded in-memory ring buffer per sandbox; long-term retention belongs to Prometheus/ClickHouse scraping). - Adding external HTTP or Prometheus client crates to
crates/podd(must remainstd+libconly). - Modifying
PodBoxCRD schemas.
Proposal
Section titled “Proposal”User Stories
Section titled “User Stories”- Story 1 (Agent / SDK Consumer): As an E2B SDK user, I call
sbx.get_metrics(start=..., end=...)and receive accurate CPU, memory, cache, and disk utilization sampled from inside the sandbox MicroVM. - Story 2 (Platform Operator): As a Kubernetes operator, I scrape
cubepod-gateway/metricsandpodd/v1/prometheusto alert on E2B request latency, panel proxy concurrency, secret store operations, E2B volume bind latency, and fork duration.
Notes / Constraints / Caveats
Section titled “Notes / Constraints / Caveats”- Dual-Runtime Behavior:
- Production Kubernetes (
Kata + CSI Block):cubepod-gatewayquerieshttp://<PodIP>:49983/metricsdirectly on the Kata pod;poddreads guest/proc/stat,/proc/meminfo, cgroup limits,statvfs("/workspace"), and/run/cubepod/init-state.json. - Local Development (
Docker + Loopback ext4): When a localpoddURL is registered,cubepod-gatewayqueriespodd/metrics. When running in unit/mock mode without a livepoddupstream (PoddURL == ""),cubepod-gatewayfalls back cleanly using host/workspacestatfsand configuredCPUCount/MemoryMB/DiskSizeMBbounds without failing requests.
- Production Kubernetes (
- Single-Threaded
podd-init: Timing usesstd::time::Instanton the main thread beforepivot_root(2)andexecvp(3), introducing zero threads.
Risks and Mitigations
Section titled “Risks and Mitigations”| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
Unbounded Prometheus label cardinality from sandbox IDs in endpoint |
Medium | High | Normalize route paths (e.g., /sandboxes/{sandboxID}/metrics) before recording cubepod_e2b_requests_total{endpoint,status}. |
Batch metrics query waking up all Paused sandboxes |
Medium | Medium | GET /sandboxes/metrics never calls ensureRunning; it queries live Running sandboxes and returns cached ring-buffer samples for Paused sandboxes. |
| Unbounded memory growth in per-sandbox metric cache | Low | Medium | Cap each sandbox’s in-memory ring buffer to a fixed capacity (120 samples) and evict on sandbox deletion. |
podd /proc/stat first-call delta returning 0% |
Medium | Low | Maintain previous CPU sample in podd process state; if none exists, perform a brief 20ms delta read before computing cpuUsedPct. |
Design Details
Section titled “Design Details”API / CRD / Wire Changes
Section titled “API / CRD / Wire Changes”1. SandboxMetric Schema (api/openapi/cubepod-v1.yaml)
Section titled “1. SandboxMetric Schema (api/openapi/cubepod-v1.yaml)”{ "timestamp": "2026-11-16T12:00:00Z", "timestampUnix": 1794830400, "cpuCount": 2, "cpuUsedPct": 14.25, "memUsed": 536870912, "memTotal": 2147483648, "memCache": 134217728, "diskUsed": 1073741824, "diskTotal": 10737418240}GET /sandboxes/{sandboxID}/metrics:- Optional query params:
start(Unix seconds or RFC3339),end(Unix seconds or RFC3339),autoResume(truedefault;falsereads cached samples without waking aPausedsandbox). - Returns
200 OKwith[]SandboxMetricfiltered to[start, end].
- Optional query params:
GET /sandboxes/metrics:- Optional query params:
sandboxIds(comma-separated or repeated query params). If omitted, returns metrics for all known active sandboxes. - Returns
200 OKwith{"sandboxes": { "<sandboxID>": SandboxMetric }}.
- Optional query params:
2. podd Endpoints (crates/podd)
Section titled “2. podd Endpoints (crates/podd)”GET /metrics: Returns JSONSandboxMetric(or Prometheus text format if?format=prometheusorAccept: text/plainwithoutapplication/json).GET /v1/prometheus: Returns Prometheus text exposition (text/plain; version=0.0.4; charset=utf-8) containing:cubepod_podd_active_processes(gauge)cubepod_podd_init_duration_milliseconds(gauge, from/run/cubepod/init-state.jsonduration_ms)cubepod_podd_init_volume_bind_duration_ms(gauge, from/run/cubepod/init-state.jsonvolume_bind_duration_ms)
3. podd-init State File (crates/podd-init)
Section titled “3. podd-init State File (crates/podd-init)”Adds "volume_bind_duration_ms": <u64> to /run/cubepod/init-state.json:
{ "pivoted": true, "rootfs_device": "/dev/cubepod-rootfs", "rootfs_action": "mounted", "workspace_device": "/dev/cubepod-workspace", "workspace_action": "mounted", "duration_ms": 42, "volume_bind_duration_ms": 3}4. Gateway Prometheus Metrics (pkg/gateway/metrics.go, pkg/gateway/panel.go)
Section titled “4. Gateway Prometheus Metrics (pkg/gateway/metrics.go, pkg/gateway/panel.go)”cubepod_e2b_requests_total{endpoint,status}(counter)cubepod_e2b_request_duration_seconds(histogram)cubepod_gateway_requests_total(counter, alongsidecubepod_gateway_http_requests_total)cubepod_gateway_auto_resumes_total(counter, alongsidecubepod_gateway_autoresume_total)cubepod_panel_active_sessions(gauge, tracked inpanel.goaroundproxy.ServeHTTP)cubepod_secrets_operations_total{op,status}(counter)cubepod_secrets_store_count(gauge)cubepod_volume_mounts_total(counter)cubepod_volume_mount_errors_total(counter)cubepod_sandbox_forks_total{mode,result}(counter)cubepod_sandbox_fork_duration_seconds(histogram)cubepod_gateway_crd_resyncs_total(counter)cubepod_sandbox_metrics_samples_total{result="ok|error"}(counter, Beta v0.7: background sampler health)cubepod_sandbox_{cpu_count,cpu_used_pct,memory_used_bytes,memory_total_bytes,disk_used_bytes,disk_total_bytes}{sandbox_id}(gauges, latest sample per sandbox, Beta v0.7)
5. Background Sampler (Beta, v0.7)
Section titled “5. Background Sampler (Beta, v0.7)”Server.StartMetricsSampler(ctx, interval) / StopMetricsSampler() (pkg/gateway/sandbox_metrics.go) tick every --metrics-sample-interval (env CUBEPOD_METRICS_SAMPLE_INTERVAL, Helm gateway.metricsSampleInterval, default 10s, 0 disables). Each tick snapshots Running sandboxes under s.mu.RLock(), releases the lock, then polls podd /metrics (or the local fallback when no PoddURL) with at most 8 concurrent workers and records into the ring buffers. Paused/terminated sandboxes are skipped; errors increment result="error" and never block the loop.
6. Prometheus Rules & Grafana Dashboard (GA, v1.0)
Section titled “6. Prometheus Rules & Grafana Dashboard (GA, v1.0)”deploy/monitoring/sandbox-metrics-rules.yaml (PrometheusRule: cubepod:sandbox_cpu_used_pct:avg5m, cubepod:sandbox_memory_utilization_ratio, cubepod:sandbox_disk_utilization_ratio; alerts CubePodSandboxHighMemoryPressure, CubePodSandboxDiskNearFull, CubePodMetricsSamplerFailing) and deploy/monitoring/sandbox-metrics-dashboard.json.
State Machine & Data Flow
Section titled “State Machine & Data Flow”flowchart LR
SDK["E2B SDK / Client"] -->|"GET /sandboxes/{id}/metrics?start=&end="| GW["cubepod-gateway"]
SDK -->|"GET /sandboxes/metrics?sandboxIds=..."| GW
GW -->|"Running + PoddURL"| Podd["podd :49983 GET /metrics"]
GW -->|"Local/Mock Fallback"| Host["Workspace statfs + /proc"]
Podd -->|"Read"| Proc["/proc/stat, /proc/meminfo, cgroup, statvfs"]
Podd -->|"GET /v1/prometheus"| InitState["/run/cubepod/init-state.json"]
GW -->|"Cache"| Ring["Per-Sandbox Ring Buffer (cap=120)"]Boundary Conditions & Failure Recovery
Section titled “Boundary Conditions & Failure Recovery”- Invalid
start/endorstart > end: Gateway returns400 Bad Request. - Unknown sandbox:
GET /sandboxes/{sandboxID}/metricsreturns404 Not Found;GET /sandboxes/metricsomits unknown IDs from"sandboxes". - Transient
podd/metricstimeout/error: Gateway falls back to the latest cached sample or local workspace/sandbox spec estimation so monitoring polls degrade gracefully. - Missing
/run/cubepod/init-state.json:poddreports0for init duration gauges rather than failing Prometheus scrapes.
Test Plan
Section titled “Test Plan”- Unit Tests (Rust):
podd-init: Verifyvolume_bind_duration_msserialization inInitState::to_jsonandsetup_and_pivot.podd: Verify RFC3339 formatting,/proc/statdelta CPU calculation,/proc/meminfo& cgroup memory parsing,statvfsdisk reporting,GET /metricsJSON schema, andGET /v1/prometheusexposition includinginit-state.jsongauges.
- Unit Tests (Go,
-race):sandbox_metrics_test.go: VerifyGET /sandboxes/{id}/metricsagainst a mockpoddserver, local fallback mode,?start=/?end=filtering (unix seconds & RFC3339), invalid range400, pausedautoResume=falsevs auto-resume, andGET /sandboxes/metricsbatch filtering.sandbox_metrics_test.go(sampler): background ticks populate history with no HTTP polling, paused sandboxes skipped, podd errors counted without blocking, clean stop without goroutine leaks.metrics_test.go: Verify all newly added Prometheus counters, gauges, histograms, andcubepod_panel_active_sessionstracking under concurrent requests with-race.
Graduation Criteria
Section titled “Graduation Criteria”- Alpha (
v0.6):GET /sandboxes/{sandboxID}/metrics,GET /sandboxes/metrics,podd/metrics&/v1/prometheus,podd-initvolume_bind_duration_ms, and all Gateway Prometheus metrics implemented and verified viacargo testandgo test -race. - Beta (
v0.7) (implemented): Background periodic sampler in Gateway/Controller populating ring buffers continuously for running sandboxes; livemake test-k8s-e2emetrics assertions enabled. - GA (
v1.0): Production soak in CubePlex with Prometheus recording rules and alerting dashboards (manifests shipped indeploy/monitoring/; soak pending).
Upgrade / Downgrade Strategy
Section titled “Upgrade / Downgrade Strategy”- All API additions (
GET /sandboxes/{sandboxID}/metrics,GET /sandboxes/metrics,podd/metrics,podd/v1/prometheus) andinit-state.jsonfield (volume_bind_duration_ms) are strictly additive. - Existing Prometheus series (
cubepod_gateway_http_requests_total,cubepod_gateway_autoresume_total) remain emitted alongside the new CEP-aligned names so existing Grafana dashboards continue working without modification.
Production Readiness Review Questionnaire (PRR)
Section titled “Production Readiness Review Questionnaire (PRR)”- Feature Enablement and Rollback: Always enabled in
v0.6; additive HTTP routes and additive JSON/Prometheus fields require no data migration and can be rolled back safely by downgrading binaries. - Rollout, Upgrade and Rollback Planning: In-memory ring buffers are ephemeral per gateway replica; rolling upgrades immediately resume sampling live
poddinstances without disruptingRunningorPausedsandboxes or/workspacePVCs. - Monitoring Requirements:
cubepod_e2b_requests_total,cubepod_e2b_request_duration_seconds,cubepod_panel_active_sessions,cubepod_podd_active_processes,cubepod_podd_init_duration_milliseconds,cubepod_podd_init_volume_bind_duration_ms. - Dependencies: Linux
/proc(stat,meminfo),statvfs(2), optional cgroup v2/v1 files; zero new third-party dependencies in Rust or Go. - Scalability: Bounded
120-entry ring buffer per sandbox keeps memory overhead negligible (< 15 KiBper sandbox);endpointlabel normalization prevents Prometheus cardinality explosion. - Troubleshooting: Scrape
GET /v1/prometheusonpodd(:49983) orGET /metricsoncubepod-gateway(:8080); inspect/run/cubepod/init-state.jsoninside the guest forduration_msandvolume_bind_duration_ms.
Implementation History
Section titled “Implementation History”- 2026-11-16: CEP-0029 drafted and marked
implementableforv0.6. - 2026-11-16: Alpha implementation completed across
podd-init,podd,cubepod-gateway, andapi/openapi/cubepod-v1.yaml; markedimplemented. - 2026-11-17: Beta: background sampler, live K8s E2E assertions (
TestK8sLiveE2ESandboxMetrics), and Prometheus rules/Grafana dashboard added (#98).
Drawbacks
Section titled “Drawbacks”- Exposing both
cubepod_gateway_http_requests_total/cubepod_gateway_autoresume_totalandcubepod_gateway_requests_total/cubepod_gateway_auto_resumes_totaltemporarily duplicates two counter series until legacy names are deprecated inv1.0.
Alternatives
Section titled “Alternatives”- Sidecar Metrics Exporter (cAdvisor / node_exporter): Rejected because adding another daemon inside each Kata MicroVM increases boot latency and memory footprint; sampling directly inside
poddadds zero extra processes and negligible overhead. - Replacing Legacy Metric Names Immediately: Rejected because existing tests and dashboards scrape
cubepod_gateway_http_requests_totalandcubepod_gateway_autoresume_total.