diff --git a/packages/client-proxy/internal/proxy/proxy.go b/packages/client-proxy/internal/proxy/proxy.go index 9d36478edb2..43cb18a73f1 100644 --- a/packages/client-proxy/internal/proxy/proxy.go +++ b/packages/client-proxy/internal/proxy/proxy.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" "go.uber.org/zap" "google.golang.org/grpc/codes" @@ -230,7 +231,18 @@ func NewClientProxy(meterProvider metric.MeterProvider, serviceName string, port resumeCloser = flights } - proxyOptions := []reverseproxy.Option{reverseproxy.WithProbe()} + outcomeCounter, err := telemetry.GetCounter(meter, telemetry.ClientProxyRequestOutcomeCounterName) + if err != nil { + return nil, nil, fmt.Errorf("error registering client proxy request outcome metric (%s): %w", telemetry.ClientProxyRequestOutcomeCounterName, err) + } + recordOutcome := func(ctx context.Context, outcome pool.RequestOutcome) { + outcomeCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", string(outcome)))) + } + + proxyOptions := []reverseproxy.Option{ + reverseproxy.WithProbe(), + reverseproxy.WithOutcomeRecorder(recordOutcome), + } if o.routerHop != nil { proxyOptions = append(proxyOptions, reverseproxy.WithTransportWrap(func(key string, base *http.Transport) *http.Transport { if key == RouterConnectionKey { @@ -357,7 +369,7 @@ func NewClientProxy(meterProvider metric.MeterProvider, serviceName string, port proxyOptions..., ) - _, err := telemetry.GetObservableUpDownCounter( + _, err = telemetry.GetObservableUpDownCounter( meter, telemetry.ClientProxyPoolConnectionsMeterCounterName, func(_ context.Context, observer metric.Int64Observer) error { observer.Observe(proxy.CurrentPoolConnections()) diff --git a/packages/orchestrator/pkg/proxy/proxy.go b/packages/orchestrator/pkg/proxy/proxy.go index 4e46941dbca..6c61dc775a8 100644 --- a/packages/orchestrator/pkg/proxy/proxy.go +++ b/packages/orchestrator/pkg/proxy/proxy.go @@ -13,6 +13,7 @@ import ( "sync" "time" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" "go.uber.org/zap" @@ -116,6 +117,14 @@ func NewSandboxProxy(meterProvider metric.MeterProvider, port uint16, sandboxes OnConnectionBlocked: metrics.RecordConnectionBlocked, } + outcomeCounter, err := telemetry.GetCounter(meter, telemetry.OrchestratorProxyRequestOutcomeCounterName) + if err != nil { + return nil, fmt.Errorf("error registering orchestrator proxy request outcome metric (%s): %w", telemetry.OrchestratorProxyRequestOutcomeCounterName, err) + } + recordOutcome := func(ctx context.Context, outcome pool.RequestOutcome) { + outcomeCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", string(outcome)))) + } + sandboxProxy := &SandboxProxy{limiter: limiter, sandboxes: sandboxes, owners: make(map[string]*pool.Owner), retirement: retirementTimeout} proxy := reverseproxy.New( port, @@ -128,9 +137,10 @@ func NewSandboxProxy(meterProvider metric.MeterProvider, port uint16, sandboxes // because the servers inside of the sandbox can be unstable (restarts), // and we are also on the same host, so the overhead is minimal. true, + reverseproxy.WithOutcomeRecorder(recordOutcome), ) - _, err := telemetry.GetObservableUpDownCounter(meter, telemetry.OrchestratorProxyServerConnectionsMeterCounterName, func(_ context.Context, observer metric.Int64Observer) error { + _, err = telemetry.GetObservableUpDownCounter(meter, telemetry.OrchestratorProxyServerConnectionsMeterCounterName, func(_ context.Context, observer metric.Int64Observer) error { observer.Observe(proxy.CurrentServerConnections()) return nil diff --git a/packages/shared/pkg/proxy/handler.go b/packages/shared/pkg/proxy/handler.go index 5bd11212184..2c5ed84f98b 100644 --- a/packages/shared/pkg/proxy/handler.go +++ b/packages/shared/pkg/proxy/handler.go @@ -54,6 +54,7 @@ func handler(p *pool.ProxyPool, getDestination func(r *http.Request) (*pool.Dest // request ended; a client that is gone reads nothing either way. if ctxErr := ctx.Err(); err != nil && ctxErr != nil && errors.Is(err, ctxErr) { l.Debug(ctx, "request ended before it was routed", zap.String("host", r.Host)) + p.RecordOutcome(ctx, pool.OutcomeClientClosed) cors.Error(w, "Request ended before it was routed", http.StatusRequestTimeout) return @@ -123,6 +124,13 @@ func handler(p *pool.ProxyPool, getDestination func(r *http.Request) (*pool.Dest l.Warn(ctx, sandboxErr.Error(), fields...) } + // A resolver that found no sandbox is the node-churn signal the + // outcome metric exists to show; the other sandbox errors are the + // upstream's own answer and are not an unreachable-node symptom. + if _, ok := sandboxErr.(*SandboxNotFoundError); ok { + p.RecordOutcome(ctx, pool.OutcomeSandboxNotFound) + } + if err := writeSandboxError(w, r, sandboxErr); err != nil { l.Error(ctx, "failed to write the sandbox error page", zap.Error(err), logger.WithSandboxID(sandboxErr.SandboxID())) cors.Error(w, "Failed to write the sandbox error page", http.StatusInternalServerError) @@ -133,6 +141,7 @@ func handler(p *pool.ProxyPool, getDestination func(r *http.Request) (*pool.Dest if err != nil { l.Error(ctx, "failed to route request", zap.Error(err), zap.String("host", r.Host)) + p.RecordOutcome(ctx, pool.OutcomeRoutingFailed) cors.Error(w, fmt.Sprintf("Unexpected error when routing request: %s", err), http.StatusInternalServerError) return @@ -173,6 +182,7 @@ func handler(p *pool.ProxyPool, getDestination func(r *http.Request) (*pool.Dest if uploading { closeUnreadBody(w) } + p.RecordOutcome(ctx, pool.OutcomeUpstreamUnreachable) cors.Error(w, "Failed to route request to sandbox", http.StatusBadGateway) return @@ -218,6 +228,8 @@ func handler(p *pool.ProxyPool, getDestination func(r *http.Request) (*pool.Dest connLimitConfig.OnConnectionBlocked(ctx) } + p.RecordOutcome(ctx, pool.OutcomeTooManyConnections) + // The sandbox is reachable, but the proxy is refusing to dial it, // so the proxy is the only party that can answer this preflight. if cors.HandlePreflight(w, r) { diff --git a/packages/shared/pkg/proxy/outcome_test.go b/packages/shared/pkg/proxy/outcome_test.go new file mode 100644 index 00000000000..157ff8367b5 --- /dev/null +++ b/packages/shared/pkg/proxy/outcome_test.go @@ -0,0 +1,151 @@ +package proxy + +import ( + "context" + "fmt" + "net" + "net/http" + "net/url" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/shared/pkg/logger" + "github.com/e2b-dev/infra/packages/shared/pkg/proxy/pool" +) + +// outcomeRecorder collects the outcomes the proxy reports, concurrency-safe. +type outcomeRecorder struct { + mu sync.Mutex + outcomes []pool.RequestOutcome +} + +func (o *outcomeRecorder) add(_ context.Context, outcome pool.RequestOutcome) { + o.mu.Lock() + defer o.mu.Unlock() + o.outcomes = append(o.outcomes, outcome) +} + +func (o *outcomeRecorder) last() (pool.RequestOutcome, bool) { + o.mu.Lock() + defer o.mu.Unlock() + if len(o.outcomes) == 0 { + return "", false + } + + return o.outcomes[len(o.outcomes)-1], true +} + +// startOutcomeProxy stands up a proxy whose destination resolver returns +// resolve(), recording every request outcome into rec. Returns the proxy URL. +func startOutcomeProxy(t *testing.T, rec *outcomeRecorder, resolve func() (*pool.Destination, error)) string { + t.Helper() + + var lisCfg net.ListenConfig + proxyListener, err := lisCfg.Listen(t.Context(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + proxyAddr := proxyListener.Addr().(*net.TCPAddr) + proxyPort := uint16(proxyAddr.Port) //nolint:gosec // test-only port fits + + proxy := New(proxyPort, 1, time.Second, func(_ *http.Request) (*pool.Destination, error) { + return resolve() + }, nil, false, WithOutcomeRecorder(rec.add)) + + go func() { + serveErr := proxy.Serve(proxyListener) + assert.ErrorIs(t, serveErr, http.ErrServerClosed) + }() + t.Cleanup(func() { assert.NoError(t, proxy.Close()) }) + + return fmt.Sprintf("http://%s", proxyAddr.String()) +} + +func TestProxyRecordsOutcome_OK(t *testing.T) { + t.Parallel() + + var lisCfg net.ListenConfig + backendListener, err := lisCfg.Listen(t.Context(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + backendPort := uint64(backendListener.Addr().(*net.TCPAddr).Port) //nolint:gosec // test-only + backendURL, err := url.Parse(fmt.Sprintf("http://%s", backendListener.Addr().String())) + require.NoError(t, err) + + backend := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })} + go func() { assert.ErrorIs(t, backend.Serve(backendListener), http.ErrServerClosed) }() + t.Cleanup(func() { assert.NoError(t, backend.Close()) }) + + rec := &outcomeRecorder{} + proxyURL := startOutcomeProxy(t, rec, func() (*pool.Destination, error) { + return &pool.Destination{ + Url: backendURL, + SandboxId: "sbx-ok", + SandboxPort: backendPort, + ConnectionKey: "ok", + RequestLogger: logger.L(), + }, nil + }) + + resp, err := http.Get(proxyURL) //nolint:noctx // test + require.NoError(t, err) + _ = resp.Body.Close() + + require.Eventually(t, func() bool { + o, ok := rec.last() + + return ok && o == pool.OutcomeOK + }, 2*time.Second, 10*time.Millisecond, "expected an ok outcome") +} + +func TestProxyRecordsOutcome_UpstreamUnreachable(t *testing.T) { + t.Parallel() + + // Port 1 is reliably closed: the dial fails, so the request is + // upstream-unreachable, not a routing failure. + deadURL, err := url.Parse("http://127.0.0.1:1") + require.NoError(t, err) + + rec := &outcomeRecorder{} + proxyURL := startOutcomeProxy(t, rec, func() (*pool.Destination, error) { + return &pool.Destination{ + Url: deadURL, + SandboxId: "sbx-dead", + SandboxPort: 1, + ConnectionKey: "dead", + RequestLogger: logger.L(), + }, nil + }) + + resp, err := http.Get(proxyURL) //nolint:noctx // test + require.NoError(t, err) + _ = resp.Body.Close() + + require.Eventually(t, func() bool { + o, ok := rec.last() + + return ok && o == pool.OutcomeUpstreamUnreachable + }, 2*time.Second, 10*time.Millisecond, "expected an upstream_unreachable outcome") +} + +func TestProxyRecordsOutcome_SandboxNotFound(t *testing.T) { + t.Parallel() + + rec := &outcomeRecorder{} + proxyURL := startOutcomeProxy(t, rec, func() (*pool.Destination, error) { + return nil, NewErrSandboxNotFound("sbx-missing", PresenceAbsent) + }) + + resp, err := http.Get(proxyURL) //nolint:noctx // test + require.NoError(t, err) + _ = resp.Body.Close() + + require.Eventually(t, func() bool { + o, ok := rec.last() + + return ok && o == pool.OutcomeSandboxNotFound + }, 2*time.Second, 10*time.Millisecond, "expected a sandbox_not_found outcome") +} diff --git a/packages/shared/pkg/proxy/pool/client.go b/packages/shared/pkg/proxy/pool/client.go index 403019c12d9..ac8a78f90f5 100644 --- a/packages/shared/pkg/proxy/pool/client.go +++ b/packages/shared/pkg/proxy/pool/client.go @@ -4,11 +4,13 @@ import ( "context" "crypto/tls" "errors" + "io" "log" "net" "net/http" "net/http/httputil" "sync/atomic" + "syscall" "time" "go.uber.org/zap" @@ -46,9 +48,15 @@ func newProxyClient( l *log.Logger, disableKeepAlives bool, insecureSkipTLSVerify bool, + onOutcome OutcomeRecorder, key string, wrap TransportWrap, ) *ProxyClient { + recordOutcome := func(ctx context.Context, outcome RequestOutcome) { + if onOutcome != nil { + onOutcome(ctx, outcome) + } + } activeConnections := smap.New[*tracking.Connection]() transport := &http.Transport{ @@ -178,6 +186,7 @@ func newProxyClient( t, ok := pc.getDestination(r) if !ok { logger.L().Error(ctx, "proxy request without sandbox received error", zap.Error(err)) + recordOutcome(ctx, OutcomeRoutingFailed) cors.Error(w, "Failed to route request to sandbox", http.StatusInternalServerError) return @@ -185,11 +194,19 @@ func newProxyClient( if r.Host == "" { // kept around for historical reasons, unsure of usefulness. todo: find out if this is useful. t.RequestLogger.Error(ctx, "error handler called from rewrite because of missing DestinationContext", zap.Error(err)) + recordOutcome(ctx, OutcomeRoutingFailed) cors.Error(w, "Failed to route request to sandbox", http.StatusInternalServerError) return } + // A client that went away mid-request (cancel, reset, EOF) is not a + // server fault: classify it apart from a genuine upstream failure so + // the two are separable on dashboards. Matches the Warn/Error split below. + clientGone := errors.Is(err, context.Canceled) || + errors.Is(err, syscall.ECONNRESET) || + errors.Is(err, io.EOF) + if err != nil { if t.SandboxPort == uint64(consts.DefaultEnvdServerPort) { if errors.Is(err, context.Canceled) { @@ -202,6 +219,12 @@ func newProxyClient( } } + if clientGone { + recordOutcome(ctx, OutcomeClientClosed) + } else { + recordOutcome(ctx, OutcomeUpstreamUnreachable) + } + if t.DefaultToPortError { err = template. NewPortClosedError(t.SandboxId, r.Host, t.SandboxPort). @@ -226,6 +249,11 @@ func newProxyClient( return nil } + // The upstream answered and the response is being forwarded: the + // request succeeded as far as the proxy is concerned, whatever the + // backend's own status code. + recordOutcome(ctx, OutcomeOK) + if r.StatusCode >= 500 { t.RequestLogger.Warn( ctx, diff --git a/packages/shared/pkg/proxy/pool/pool.go b/packages/shared/pkg/proxy/pool/pool.go index 661a275d8c3..1dfc35e01ef 100644 --- a/packages/shared/pkg/proxy/pool/pool.go +++ b/packages/shared/pkg/proxy/pool/pool.go @@ -23,6 +23,33 @@ const hostConnectionSplit = 4 // by different sandboxes cause failed connections. const ClientProxyConnectionKey = "client-proxy" +// RequestOutcome names how a proxied request ended. It is reported through the +// OnOutcome callback so each service can count it on its own meter. The shared +// proxy stays telemetry-agnostic: it only classifies, the caller counts. +type RequestOutcome string + +const ( + // OutcomeOK: the upstream answered and the response was forwarded. + OutcomeOK RequestOutcome = "ok" + // OutcomeRoutingFailed: the request could not be routed to a destination + // (no destination resolved, or an input the proxy rejected). Answered 4xx/500. + OutcomeRoutingFailed RequestOutcome = "routing_failed" + // OutcomeUpstreamUnreachable: the destination resolved but the proxy could + // not reach it (dial/transport failure, or a closed sandbox port). Answered 502. + OutcomeUpstreamUnreachable RequestOutcome = "upstream_unreachable" + // OutcomeClientClosed: the client went away before the proxy answered + // (context cancelled, connection reset, EOF). Nobody is left to read a page. + OutcomeClientClosed RequestOutcome = "client_closed" + // OutcomeSandboxNotFound: no sandbox matched the request. + OutcomeSandboxNotFound RequestOutcome = "sandbox_not_found" + // OutcomeTooManyConnections: the per-sandbox connection limit shed the request. + OutcomeTooManyConnections RequestOutcome = "too_many_connections" +) + +// OutcomeRecorder is the callback the proxy calls once per request with its +// terminal outcome. Nil is valid and means "do not record". +type OutcomeRecorder func(ctx context.Context, outcome RequestOutcome) + // TransportWrap returns the transport for the client the pool builds for a // ConnectionKey or Owner, given the pool's own. Like // Destination.InsecureSkipTLSVerify, it runs once, when that client is built, @@ -39,6 +66,14 @@ func WithTransportWrap(w TransportWrap) Option { } } +// WithOutcomeRecorder makes the pool report each request's terminal outcome +// through r. Without it outcomes are not recorded. +func WithOutcomeRecorder(r OutcomeRecorder) Option { + return func(p *ProxyPool) { + p.onOutcome = r + } +} + type ProxyPool struct { clients atomic.Int64 pool *smap.Map[*ProxyClient] @@ -48,6 +83,7 @@ type ProxyPool struct { totalConnsCounter atomic.Uint64 currentConnsCounter atomic.Int64 disableKeepAlives bool + onOutcome OutcomeRecorder transportWrap TransportWrap } @@ -59,6 +95,7 @@ func New(maxClientConns int, maxConnectionAttempts int, idleTimeout time.Duratio idleTimeout: idleTimeout, disableKeepAlives: disableKeepAlives, } + for _, opt := range opts { opt(p) } @@ -66,6 +103,14 @@ func New(maxClientConns int, maxConnectionAttempts int, idleTimeout time.Duratio return p } +// RecordOutcome reports a request outcome through the configured recorder, if +// any. Safe to call with a nil recorder. +func (p *ProxyPool) RecordOutcome(ctx context.Context, outcome RequestOutcome) { + if p.onOutcome != nil { + p.onOutcome(ctx, outcome) + } +} + // NewOwner opens an admission lifetime. func (p *ProxyPool) NewOwner() *Owner { ctx, cancel := context.WithCancel(context.Background()) @@ -126,6 +171,7 @@ func (p *ProxyPool) newClient(ctx context.Context, d *Destination, owner *Owner) stdLogger, p.disableKeepAlives, d.InsecureSkipTLSVerify, + p.onOutcome, d.ConnectionKey, p.transportWrap, ) diff --git a/packages/shared/pkg/proxy/probe.go b/packages/shared/pkg/proxy/probe.go index e92b37f4c05..5359e172939 100644 --- a/packages/shared/pkg/proxy/probe.go +++ b/packages/shared/pkg/proxy/probe.go @@ -20,6 +20,7 @@ type Option func(*options) type options struct { probe bool + onOutcome pool.OutcomeRecorder transportWrap pool.TransportWrap } @@ -31,6 +32,14 @@ func WithProbe() Option { } } +// WithOutcomeRecorder records each request's terminal outcome through r. +// Without it outcomes are not recorded. +func WithOutcomeRecorder(r pool.OutcomeRecorder) Option { + return func(o *options) { + o.onOutcome = r + } +} + // WithTransportWrap makes the proxy build each upstream transport through w. func WithTransportWrap(w pool.TransportWrap) Option { return func(o *options) { diff --git a/packages/shared/pkg/proxy/proxy.go b/packages/shared/pkg/proxy/proxy.go index b2ea0c4f01d..fe96e43c5c5 100644 --- a/packages/shared/pkg/proxy/proxy.go +++ b/packages/shared/pkg/proxy/proxy.go @@ -65,6 +65,7 @@ func New( int(maxConnectionAttempts), idleTimeout, disableKeepAlives, + pool.WithOutcomeRecorder(o.onOutcome), pool.WithTransportWrap(o.transportWrap), ) diff --git a/packages/shared/pkg/proxy/shutdown_test.go b/packages/shared/pkg/proxy/shutdown_test.go index 35772b16b09..160a155c695 100644 --- a/packages/shared/pkg/proxy/shutdown_test.go +++ b/packages/shared/pkg/proxy/shutdown_test.go @@ -227,6 +227,12 @@ func TestProxyShutdownReleasesFailedH2CPreface(t *testing.T) { proxy := New(0, SandboxProxyRetries, time.Minute, func(*http.Request) (*pool.Destination, error) { return nil, errors.New("unexpected proxy request") }, nil, false) + hijacked := make(chan struct{}) + proxy.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateHijacked { + close(hijacked) + } + } var listenConfig net.ListenConfig listener, err := listenConfig.Listen(t.Context(), "tcp", "127.0.0.1:0") require.NoError(t, err) diff --git a/packages/shared/pkg/telemetry/meters.go b/packages/shared/pkg/telemetry/meters.go index d0fbf8d51a6..34ff8cf1fbf 100644 --- a/packages/shared/pkg/telemetry/meters.go +++ b/packages/shared/pkg/telemetry/meters.go @@ -464,6 +464,19 @@ const ( // ClientProxyResumeParkingRejectedCounterName counts callers shed with a // 503 because the parking lot was full when their flight first retried. ClientProxyResumeParkingRejectedCounterName CounterType = "client_proxy.resume.parking.rejected" + + // ClientProxyRequestOutcomeCounterName counts proxied requests by how they + // ended (outcome): ok | routing_failed | upstream_unreachable | + // client_closed | sandbox_not_found | too_many_connections. routing_failed + // vs upstream_unreachable separates a 500 (no destination) from a 502 + // (destination resolved, node unreachable) without scraping logs; a spike + // in upstream_unreachable is the signal for stale routing records pointing + // at a drained node. + ClientProxyRequestOutcomeCounterName CounterType = "client_proxy.request.outcome" + // OrchestratorProxyRequestOutcomeCounterName is the orchestrator sandbox + // proxy's equivalent of ClientProxyRequestOutcomeCounterName, same outcome + // values; upstream_unreachable here is a closed sandbox port / unreachable guest. + OrchestratorProxyRequestOutcomeCounterName CounterType = "orchestrator.proxy.request.outcome" ) const ( @@ -980,6 +993,8 @@ var counterDesc = map[CounterType]string{ ClientProxyResumeFlightCounterName: "Callers of the per-sandbox resume flight at the client proxy (role=leader|joiner|none, result=served|error|canceled)", ClientProxyResumeParkingRejectedCounterName: "Requests shed with a 503 because the client proxy parking lot was full at their flight's first retry", + ClientProxyRequestOutcomeCounterName: "Client proxy requests by terminal outcome (ok | routing_failed | upstream_unreachable | client_closed | sandbox_not_found | too_many_connections).", + OrchestratorProxyRequestOutcomeCounterName: "Orchestrator sandbox proxy requests by terminal outcome (ok | routing_failed | upstream_unreachable | client_closed | sandbox_not_found | too_many_connections).", ApiOrchestratorPlacementsWithoutHugepageCeiling: "Hugepage sandboxes placed under a hugepage limit on a node the limit could not bound, by node and reason (no_capacity | no_page_size).", } @@ -1049,6 +1064,8 @@ var counterUnits = map[CounterType]string{ TCPFirewallErrorsTotal: "{error}", ClientProxyResumeFlightCounterName: "{request}", ClientProxyResumeParkingRejectedCounterName: "{request}", + ClientProxyRequestOutcomeCounterName: "{request}", + OrchestratorProxyRequestOutcomeCounterName: "{request}", TCPFirewallDecisionsTotal: "{decision}", OrchestratorTemplateCacheAncestorResolutionsCounterName: "{ancestor}",