diff --git a/docs/performance.md b/docs/performance.md index 57c9d1b72f..f3fdb319aa 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -29,7 +29,9 @@ To change the number of workers, use the `num` option of the `worker` section of While it's always better to know exactly what your traffic will look like, real-life applications tend to be more unpredictable. The `max_threads` [configuration](config.md#caddyfile-config) allows FrankenPHP to automatically spawn additional threads at runtime up to the specified limit. `max_threads` can help you figure out how many threads you need to handle your traffic and can make the server more resilient to latency spikes. -If set to `auto`, the limit will be estimated based on the `memory_limit` in your `php.ini`. If not able to do so, +If set to `auto`, the limit will be estimated based on the `memory_limit` in your `php.ini` and the memory available: +the system's, or the memory limit of the Go runtime when it is lower. In a container, Caddy derives that limit from +the memory limit of the container, and `GOMEMLIMIT` sets it explicitly when the container doesn't expose it. If not able to do so, `auto` will instead default to twice the threads started at boot. Keep in mind that `auto` might strongly underestimate the number of threads needed. `max_threads` is similar to PHP-FPM's [pm.max_children](https://www.php.net/manual/install.fpm.configuration.php#pm.max-children). The main difference is that FrankenPHP uses threads instead of processes and automatically delegates them across different worker scripts and 'classic mode' as needed. diff --git a/internal/memory/memory.go b/internal/memory/memory.go new file mode 100644 index 0000000000..780b6c1bda --- /dev/null +++ b/internal/memory/memory.go @@ -0,0 +1,24 @@ +package memory + +import ( + "math" + "runtime/debug" +) + +// Available returns the memory the process may use, 0 if it cannot be +// determined: the total system memory, or the memory limit of the Go runtime +// when it is lower. In a container, the system memory is that of the host, +// while the limit comes from the container: Caddy derives it from the cgroup, +// GOMEMLIMIT sets it explicitly. +func Available() uint64 { + total := TotalSysMemory() + limit := debug.SetMemoryLimit(-1) + if limit <= 0 || limit == math.MaxInt64 { + return total + } + if total == 0 || uint64(limit) < total { + return uint64(limit) + } + + return total +} diff --git a/internal/memory/memory_test.go b/internal/memory/memory_test.go new file mode 100644 index 0000000000..2885540069 --- /dev/null +++ b/internal/memory/memory_test.go @@ -0,0 +1,36 @@ +package memory + +import ( + "math" + "runtime/debug" + "testing" + + "github.com/stretchr/testify/assert" +) + +func setMemoryLimit(t *testing.T, limit int64) { + previous := debug.SetMemoryLimit(limit) + t.Cleanup(func() { debug.SetMemoryLimit(previous) }) +} + +func TestAvailableIsTheSystemMemoryWithoutLimit(t *testing.T) { + setMemoryLimit(t, math.MaxInt64) + + assert.Equal(t, TotalSysMemory(), Available()) +} + +func TestAvailableIsTheMemoryLimitWhenLower(t *testing.T) { + setMemoryLimit(t, 512<<20) + + assert.Equal(t, uint64(512<<20), Available()) +} + +func TestAvailableIsTheSystemMemoryWhenTheLimitIsHigher(t *testing.T) { + total := TotalSysMemory() + if total == 0 || total > math.MaxInt64/2 { + t.Skip("the system memory is unknown") + } + setMemoryLimit(t, int64(total)*2) + + assert.Equal(t, total, Available()) +} diff --git a/phpmainthread.go b/phpmainthread.go index 40adf13c21..cb7a05f500 100644 --- a/phpmainthread.go +++ b/phpmainthread.go @@ -272,23 +272,24 @@ func go_frankenphp_main_thread_is_ready() { } // max_threads = auto -// setAutomaticMaxThreads estimates the amount of threads based on php.ini and system memory_limit -// If unable to get the system's memory limit, simply double num_threads +// setAutomaticMaxThreads estimates the amount of threads based on the memory_limit of php.ini and the memory +// available: the system's, or the memory limit of Go when lower, which Caddy derives from the cgroup of a container. +// If unable to get either, simply double num_threads func (mainThread *phpMainThread) setAutomaticMaxThreads() { if mainThread.maxThreads >= 0 { return } perThreadMemoryLimit := int64(C.frankenphp_get_current_memory_limit()) - totalSysMemory := memory.TotalSysMemory() - if perThreadMemoryLimit <= 0 || totalSysMemory == 0 { + availableMemory := memory.Available() + if perThreadMemoryLimit <= 0 || availableMemory == 0 { mainThread.maxThreads = mainThread.numThreads * 2 return } - maxAllowedThreads := totalSysMemory / uint64(perThreadMemoryLimit) + maxAllowedThreads := availableMemory / uint64(perThreadMemoryLimit) mainThread.maxThreads = int(maxAllowedThreads) if globalLogger.Enabled(globalCtx, slog.LevelDebug) { - globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "Automatic thread limit", slog.Int("perThreadMemoryLimitMB", int(perThreadMemoryLimit/1024/1024)), slog.Int("maxThreads", mainThread.maxThreads)) + globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "Automatic thread limit", slog.Int("perThreadMemoryLimitMB", int(perThreadMemoryLimit/1024/1024)), slog.Int("availableMemoryMB", int(availableMemory/1024/1024)), slog.Int("maxThreads", mainThread.maxThreads)) } } diff --git a/phpmainthread_test.go b/phpmainthread_test.go index a0682f092f..50c1a433ce 100644 --- a/phpmainthread_test.go +++ b/phpmainthread_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "path/filepath" "runtime" + "runtime/debug" "sync" "sync/atomic" "testing" @@ -388,6 +389,18 @@ func testThreadCalculationError(t *testing.T, o *opt) { assert.Error(t, err, "configuration must error") } +// in a container, the memory of the host is not the memory FrankenPHP may use: +// the memory limit of Go, which Caddy derives from the cgroup, caps it +func TestAutomaticMaxThreadsHonorsTheGoMemoryLimit(t *testing.T) { + previous := debug.SetMemoryLimit(640 << 20) + t.Cleanup(func() { debug.SetMemoryLimit(previous) }) + + assert.NoError(t, Init(WithNumThreads(2), WithMaxThreads(-1), WithPhpIni(map[string]string{"memory_limit": "64M"}))) + defer Shutdown() + + assert.Equal(t, 10, mainThread.maxThreads, "640 MB for threads of 64 MB") +} + func TestContextAndLoggerMustNotBeNil(t *testing.T) { log, ctx := getLogger(0) assert.NotNil(t, log, "logger is defined if all threads are inactive")