Skip to content

Commit a9f24a1

Browse files
committed
http impl of memory limiter
1 parent 6002665 commit a9f24a1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

config/confighttp/confighttp.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"time"
1313

1414
"github.com/rs/cors"
15+
"go.opentelemetry.io/collector/extension/memorylimiter"
1516
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
1617
"go.opentelemetry.io/otel"
1718
"golang.org/x/net/http2"
@@ -234,6 +235,10 @@ type HTTPServerSettings struct {
234235
// Additional headers attached to each HTTP response sent to the client.
235236
// Header values are opaque since they may be sensitive.
236237
ResponseHeaders map[string]configopaque.String `mapstructure:"response_headers"`
238+
239+
// IsLimitMemory is use to enable memory limiter extension if the extension exists. Memory limiter checks
240+
// total memory usage restricted by the extension and return an error if memory exceeds.
241+
EnableMemoryLimiter bool `mapstructure:"limit_memory"`
237242
}
238243

239244
// ToListener creates a net.Listener.
@@ -294,6 +299,14 @@ func (hss *HTTPServerSettings) ToServer(host component.Host, settings component.
294299
o(serverOpts)
295300
}
296301

302+
if hss.EnableMemoryLimiter {
303+
if ext, err := memorylimiter.GetMemoryLimiterExtension(host.GetExtensions()); err != nil {
304+
handler = memoryLimiterInterceptor(handler, ext)
305+
} else {
306+
return nil, err
307+
}
308+
}
309+
297310
handler = httpContentDecompressor(handler, serverOpts.errHandler, serverOpts.decoders)
298311

299312
if hss.MaxRequestBodySize > 0 {
@@ -400,3 +413,13 @@ func maxRequestBodySizeInterceptor(next http.Handler, maxRecvSize int64) http.Ha
400413
next.ServeHTTP(w, r)
401414
})
402415
}
416+
417+
func memoryLimiterInterceptor(next http.Handler, ml memorylimiter.MemoryLimiter) http.Handler {
418+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
419+
if err := ml.CheckMemory(); err != nil {
420+
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
421+
return
422+
}
423+
next.ServeHTTP(w, r)
424+
})
425+
}

0 commit comments

Comments
 (0)