diff --git a/README.md b/README.md index d152b736..72745bcc 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,20 @@ response = ctx.cortex_api_call( When you are ready to invoke Cortex APIs, set the `CORTEX_API_TOKEN` enviornment variable and omit `DRYRUN`. For on-premise installs you'll also need to add `CORTEX_API_BASE_URL` which is the DNS name of your cortex instance eg `https://api.cortex.internal` +### Read timeouts + +The agent gives each incoming request a limited time to arrive. Raise a limit +when large or slow requests fail before they are complete. + +| Setting | Default | Raise it when | +|---------|---------|---------------| +| `WEBHOOK_READ_TIMEOUT` | 30s | Large or slow webhook deliveries to port 8081 fail. | +| `CORTEX_API_PROXY_READ_TIMEOUT` | 30s | Large requests to `http://localhost/cortex-api` fail. | + +Set the value as an environment variable on the agent container, as a Go +duration such as `45s` or `2m`. The agent does not start if the value is not +a valid duration greater than zero. + ## Handling Proxy and TLS The agent supports the following environment variables to handle proxy and TLS: diff --git a/README.relay.md b/README.relay.md index be17f7a2..150e2436 100644 --- a/README.relay.md +++ b/README.relay.md @@ -238,14 +238,6 @@ exists, takes precedence. | Idle connection kept in the pool | 90s | | Relay registration (`/register`) | 30s | -The agent's own HTTP servers bound how long they take to read an incoming -request, headers and body, counted from when the connection is accepted. - -| Server | Read bound | -|--------|------------| -| Webhook server | 30s | -| Main server | 1s (30s for a `/cortex-api/` request body) | - ## How it works The agent opens a gRPC tunnel from the internal network to the cloud-hosted diff --git a/agent/config/config.go b/agent/config/config.go index fd9524c9..d118e1ea 100644 --- a/agent/config/config.go +++ b/agent/config/config.go @@ -40,6 +40,14 @@ type AgentConfig struct { HttpDisableTLS bool HttpCaCertFilePath string + // Read timeouts bound how long a server takes to read a request. The + // webhook bound counts from when the connection is accepted. The Cortex + // API proxy bound covers only the request body after the headers, and + // counts from when its handler starts. The headers keep the main server's + // 1s bound. Zero means DefaultReadTimeout. + WebhookReadTimeout time.Duration + CortexApiProxyReadTimeout time.Duration + // TunnelConns is how many gRPC connections the agent opens outbound, and // the only tunnel dial there is. Each is load-balanced round-robin // across every server instance, so this is a blast-radius decision: @@ -147,6 +155,27 @@ func envFirst(names ...string) string { return "" } +// DefaultReadTimeout is the read timeout of the webhook server and the Cortex +// API proxy when no setting overrides it. +const DefaultReadTimeout = 30 * time.Second + +// positiveDurationEnv reads a duration from the named variable. Zero is +// rejected because it would silently mean the 30s default. +func positiveDurationEnv(name string, def time.Duration) time.Duration { + v := os.Getenv(name) + if v == "" { + return def + } + d, err := time.ParseDuration(v) + if err != nil { + panic(fmt.Sprintf("%s: %v", name, err)) + } + if d <= 0 { + panic(fmt.Sprintf("%s must be greater than zero, got %q", name, v)) + } + return d +} + func NewAgentEnvConfig() AgentConfig { baseUrl := os.Getenv("CORTEX_API_BASE_URL") @@ -284,6 +313,9 @@ func NewAgentEnvConfig() AgentConfig { cfg.HttpCaCertFilePath = filepath.Clean(cfg.HttpCaCertFilePath) } + cfg.WebhookReadTimeout = positiveDurationEnv("WEBHOOK_READ_TIMEOUT", DefaultReadTimeout) + cfg.CortexApiProxyReadTimeout = positiveDurationEnv("CORTEX_API_PROXY_READ_TIMEOUT", DefaultReadTimeout) + cfg.TunnelConns = 4 if v := os.Getenv("AXON_GRPC_TUNNEL_CONNS"); v != "" { n, err := strconv.Atoi(v) diff --git a/agent/config/config_test.go b/agent/config/config_test.go index 876f3f28..53d68825 100644 --- a/agent/config/config_test.go +++ b/agent/config/config_test.go @@ -75,3 +75,24 @@ func TestEnvConfig_MaxRequestTimeout(t *testing.T) { t.Setenv("AXON_GRPC_TUNNEL_MAX_REQUEST_TIMEOUT", "90s") assert.Equal(t, "1m30s", NewAgentEnvConfig().MaxRequestTimeout.String()) } + +func TestEnvConfig_ReadTimeouts(t *testing.T) { + cfg := NewAgentEnvConfig() + assert.Equal(t, DefaultReadTimeout, cfg.WebhookReadTimeout) + assert.Equal(t, DefaultReadTimeout, cfg.CortexApiProxyReadTimeout) + + t.Setenv("WEBHOOK_READ_TIMEOUT", "2m") + t.Setenv("CORTEX_API_PROXY_READ_TIMEOUT", "90s") + cfg = NewAgentEnvConfig() + assert.Equal(t, "2m0s", cfg.WebhookReadTimeout.String()) + assert.Equal(t, "1m30s", cfg.CortexApiProxyReadTimeout.String()) +} + +func TestEnvConfig_ReadTimeoutRejectsBadValues(t *testing.T) { + for _, v := range []string{"0s", "-5s", "thirty"} { + t.Run(v, func(t *testing.T) { + t.Setenv("WEBHOOK_READ_TIMEOUT", v) + assert.Panics(t, func() { NewAgentEnvConfig() }) + }) + } +} diff --git a/agent/server/api/cortex_api_proxy_handler.go b/agent/server/api/cortex_api_proxy_handler.go index 64610efa..681b233f 100644 --- a/agent/server/api/cortex_api_proxy_handler.go +++ b/agent/server/api/cortex_api_proxy_handler.go @@ -2,6 +2,7 @@ package api import ( "bytes" + "cmp" "compress/gzip" "fmt" "io" @@ -25,11 +26,6 @@ import ( const cortexApiRoot = "cortex-api" const cortexApiPathRoot = "/cortex-api/" -// apiProxyReadTimeout bounds reading a proxied request body. The main server -// keeps a short read timeout for its own fast endpoints, and a large body for -// the Cortex API can take longer to arrive. -const apiProxyReadTimeout = 30 * time.Second - func NewApiProxyHandler(config config.AgentConfig, logger *zap.Logger, httpTransport *http.Transport) cortex_http.RegisterableHandler { targetURL, err := url.Parse(config.CortexApiBaseUrl) if err != nil { @@ -72,7 +68,10 @@ func (a *apiProxyHandler) RegisterRoutes(mux *mux.Router) error { } func (a *apiProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(apiProxyReadTimeout)) + // The main server keeps a short read timeout for its own fast endpoints, + // and a large body for the Cortex API can take longer to arrive. + readTimeout := cmp.Or(a.config.CortexApiProxyReadTimeout, config.DefaultReadTimeout) + _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(readTimeout)) if strings.HasPrefix(r.URL.Path, cortexApiPathRoot) { r.URL.Path = r.URL.Path[len(cortexApiPathRoot):] @@ -117,6 +116,10 @@ func (a *apiProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } r.Body.Close() } + // The bound is for the body only. net/http's background read of the + // connection also uses the deadline, and when it fires it cancels + // r.Context(), which the upstream call uses. + _ = http.NewResponseController(w).SetReadDeadline(time.Time{}) for { diff --git a/agent/server/api/cortex_api_proxy_read_timeout_test.go b/agent/server/api/cortex_api_proxy_read_timeout_test.go index 341c487e..9600dc13 100644 --- a/agent/server/api/cortex_api_proxy_read_timeout_test.go +++ b/agent/server/api/cortex_api_proxy_read_timeout_test.go @@ -7,6 +7,7 @@ import ( "net" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -52,3 +53,85 @@ func TestServeHTTP_ReadsLateBodyPastServerReadTimeout(t *testing.T) { defer resp.Body.Close() require.Equal(t, http.StatusAccepted, resp.StatusCode) } + +// A shorter configured value must replace the default, so a body that arrives +// after it never reaches the Cortex API. +func TestServeHTTP_UsesConfiguredReadTimeout(t *testing.T) { + reached := make(chan struct{}, 1) + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if body, err := io.ReadAll(r.Body); err == nil && string(body) == "hello" { + reached <- struct{}{} + } + w.WriteHeader(http.StatusAccepted) + })) + defer backend.Close() + + cfg := config.AgentConfig{ + CortexApiBaseUrl: backend.URL, + CortexApiToken: "test_token", + CortexApiProxyReadTimeout: 100 * time.Millisecond, + } + srv := cortex_http.NewHttpServer(cortex_http.HttpServerParams{ + Logger: zap.NewNop(), + Config: cfg, + Handlers: []cortex_http.RegisterableHandler{NewApiProxyHandler(cfg, zap.NewNop(), nil)}, + }) + port, err := srv.Start() + require.NoError(t, err) + defer srv.Close() + + conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + require.NoError(t, err) + defer conn.Close() + + _, err = fmt.Fprintf(conn, "POST /cortex-api/test HTTP/1.1\r\nHost: localhost\r\nContent-Length: 5\r\n\r\n") + require.NoError(t, err) + time.Sleep(time.Second) + _, _ = io.WriteString(conn, "hello") + + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err == nil { + resp.Body.Close() + require.NotEqual(t, http.StatusAccepted, resp.StatusCode) + } + select { + case <-reached: + t.Fatal("the body reached the Cortex API after the configured read timeout") + default: + } +} + +// The bound covers only the request body, so an upstream that answers after it +// must still reach the caller. The request without a body is the one at risk: +// net/http's background read is already running when the deadline is set. +func TestServeHTTP_SlowUpstreamPastReadTimeout(t *testing.T) { + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(500 * time.Millisecond) + w.WriteHeader(http.StatusAccepted) + })) + defer backend.Close() + + cfg := config.AgentConfig{ + CortexApiBaseUrl: backend.URL, + CortexApiToken: "test_token", + CortexApiProxyReadTimeout: 100 * time.Millisecond, + } + srv := cortex_http.NewHttpServer(cortex_http.HttpServerParams{ + Logger: zap.NewNop(), + Config: cfg, + Handlers: []cortex_http.RegisterableHandler{NewApiProxyHandler(cfg, zap.NewNop(), nil)}, + }) + port, err := srv.Start() + require.NoError(t, err) + defer srv.Close() + + url := fmt.Sprintf("http://127.0.0.1:%d/cortex-api/test", port) + for name, body := range map[string]io.Reader{"no body": nil, "body": strings.NewReader("hello")} { + req, err := http.NewRequest(http.MethodPost, url, body) + require.NoError(t, err) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + resp.Body.Close() + require.Equal(t, http.StatusAccepted, resp.StatusCode, name) + } +} diff --git a/agent/server/http/module.go b/agent/server/http/module.go index 4df42070..1b9e88f3 100644 --- a/agent/server/http/module.go +++ b/agent/server/http/module.go @@ -1,8 +1,8 @@ package http import ( + "cmp" "context" - "time" "github.com/cortexapps/axon/config" "github.com/cortexapps/axon/server/cron" @@ -18,26 +18,25 @@ var Module = fx.Module("handler", fx.Invoke(createWebhookHttpServer), ) -// webhookReadTimeout bounds reading a webhook delivery. Senders are outside -// the agent's network and may upload large payloads slowly. -const webhookReadTimeout = 30 * time.Second - -func createWebhookHttpServer(lifecycle fx.Lifecycle, config config.AgentConfig, logger *zap.Logger, handlerManager handler.Manager, registry *prometheus.Registry) Server { +func createWebhookHttpServer(lifecycle fx.Lifecycle, agentConfig config.AgentConfig, logger *zap.Logger, handlerManager handler.Manager, registry *prometheus.Registry) Server { params := HttpServerParams{ Logger: logger, Registry: registry, Handlers: []RegisterableHandler{ - NewWebhookHandler(config, logger, handlerManager, registry), + NewWebhookHandler(agentConfig, logger, handlerManager, registry), }, - Config: config, + Config: agentConfig, } - httpServer := NewHttpServer(params, WithName("webhook"), WithPort(config.WebhookServerPort), WithReadTimeout(webhookReadTimeout)) + // Webhook senders are outside the agent's network and may upload large + // payloads slowly. + readTimeout := cmp.Or(agentConfig.WebhookReadTimeout, config.DefaultReadTimeout) + httpServer := NewHttpServer(params, WithName("webhook"), WithPort(agentConfig.WebhookServerPort), WithReadTimeout(readTimeout)) lifecycle.Append(fx.Hook{ OnStart: func(ctx context.Context) error { _, err := httpServer.Start() - logger.Info("Webhook server started", zap.Int("port", config.WebhookServerPort), zap.Error(err)) + logger.Info("Webhook server started", zap.Int("port", agentConfig.WebhookServerPort), zap.Error(err)) return err },