Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions packages/client-proxy/internal/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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())

Expand Down
12 changes: 11 additions & 1 deletion packages/orchestrator/pkg/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"sync"
"time"

"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.uber.org/zap"

Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions packages/shared/pkg/proxy/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
151 changes: 151 additions & 0 deletions packages/shared/pkg/proxy/outcome_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
28 changes: 28 additions & 0 deletions packages/shared/pkg/proxy/pool/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -178,18 +186,27 @@ 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
}

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) {
Expand All @@ -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).
Expand All @@ -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,
Expand Down
Loading