diff --git a/caddy/go.mod b/caddy/go.mod index 3d97c3f278..2d33a0f7d0 100644 --- a/caddy/go.mod +++ b/caddy/go.mod @@ -7,6 +7,7 @@ replace github.com/dunglas/frankenphp => ../ retract v1.0.0-rc.1 // Human error require ( + github.com/KimMachineGun/automemlimit v1.0.2 github.com/caddyserver/caddy/v2 v2.11.9 github.com/caddyserver/certmagic v0.25.6 github.com/dunglas/caddy-cbrotli v1.0.1 @@ -32,7 +33,6 @@ require ( github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect github.com/BurntSushi/toml v1.6.0 // indirect github.com/DeRuina/timberjack v1.4.10 // indirect - github.com/KimMachineGun/automemlimit v1.0.2 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/Masterminds/sprig/v3 v3.3.0 // indirect diff --git a/caddy/php-server.go b/caddy/php-server.go index bd5fb4da76..24dd56cbbc 100644 --- a/caddy/php-server.go +++ b/caddy/php-server.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/KimMachineGun/automemlimit/memlimit" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" caddycmd "github.com/caddyserver/caddy/v2/cmd" @@ -19,6 +20,7 @@ import ( "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" "github.com/caddyserver/certmagic" "github.com/dunglas/frankenphp" + "go.uber.org/zap/exp/zapslog" "github.com/spf13/cobra" ) @@ -61,6 +63,7 @@ For more advanced use cases, see https://github.com/php/frankenphp/blob/main/doc // cmdPHPServer is freely inspired from the file-server command of the Caddy server (Apache License 2.0, Matthew Holt and The Caddy Authors) func cmdPHPServer(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() + setMemoryLimit() domain := fs.String("domain") root := fs.String("root") @@ -326,3 +329,12 @@ func cmdPHPServer(fs caddycmd.Flags) (int, error) { select {} } + +// setMemoryLimit mirrors what "caddy run" does, as max_threads auto is sized from this limit. +func setMemoryLimit() { + _, _ = memlimit.Set( + // the stacktrace level is above all levels so that errors don't dump traces, as in Caddy + memlimit.WithLogger(slog.New(zapslog.NewHandler(caddy.Log().Core(), zapslog.WithName("memlimit"), zapslog.AddStacktraceAt(slog.Level(127))))), + memlimit.WithProvider(memlimit.ApplyFallback(memlimit.FromCgroup, memlimit.FromSystem)), + ) +} diff --git a/docs/performance.md b/docs/performance.md index 57c9d1b72f..29b9b16ac9 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -29,7 +29,10 @@ 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 by dividing the memory available by the `memory_limit` in your `php.ini`. +The memory available is the system's, capped by the memory limit of the Go runtime: `frankenphp run` and `frankenphp php-server` +set it to 90% of the memory limit of the container, or of the system memory without one (`AUTOMEMLIMIT` changes this ratio), +and `GOMEMLIMIT` sets it explicitly. If not able to do so, for instance outside of Linux without `GOMEMLIMIT`, `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..b8dc2cce47 --- /dev/null +++ b/internal/memory/memory.go @@ -0,0 +1,22 @@ +package memory + +import ( + "math" + "os" + "runtime/debug" +) + +// Available returns the system memory capped by the Go memory limit, which Caddy derives from the container, or 0 if unknown. +func Available() uint64 { + total := TotalSysMemory() + limit := debug.SetMemoryLimit(-1) + // without the system memory, only an explicit GOMEMLIMIT is meaningful: Caddy's own is a fraction of the RAM + if limit <= 0 || limit == math.MaxInt64 || (total == 0 && os.Getenv("GOMEMLIMIT") == "") { + 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..d8283b7f87 --- /dev/null +++ b/internal/memory/memory_test.go @@ -0,0 +1,54 @@ +package memory + +import ( + "math" + "runtime/debug" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +func setMemoryLimit(t *testing.T, limit int64, explicit bool) { + if explicit { + t.Setenv("GOMEMLIMIT", strconv.FormatInt(limit, 10)) + } else { + t.Setenv("GOMEMLIMIT", "") + } + previous := debug.SetMemoryLimit(limit) + t.Cleanup(func() { debug.SetMemoryLimit(previous) }) +} + +func TestAvailableIsTheSystemMemoryWithoutLimit(t *testing.T) { + setMemoryLimit(t, math.MaxInt64, false) + + assert.Equal(t, TotalSysMemory(), Available()) +} + +func TestAvailableIsTheMemoryLimitWhenLower(t *testing.T) { + if total := TotalSysMemory(); total != 0 && total <= 512<<20 { + t.Skip("the system memory is lower than the limit") + } + setMemoryLimit(t, 512<<20, true) + + 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, true) + + assert.Equal(t, total, Available()) +} + +func TestAvailableIgnoresAnImplicitLimitWithoutTheSystemMemory(t *testing.T) { + if TotalSysMemory() != 0 { + t.Skip("the system memory is known") + } + setMemoryLimit(t, 512<<20, false) + + assert.Zero(t, Available()) +} diff --git a/phpmainthread.go b/phpmainthread.go index 40adf13c21..26d5b3ac4c 100644 --- a/phpmainthread.go +++ b/phpmainthread.go @@ -272,23 +272,21 @@ 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 divides the available memory by the memory_limit of php.ini, or doubles num_threads if either is unknown 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) - mainThread.maxThreads = int(maxAllowedThreads) + mainThread.maxThreads = max(int(availableMemory/uint64(perThreadMemoryLimit)), mainThread.numThreads) 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..e66a084958 100644 --- a/phpmainthread_test.go +++ b/phpmainthread_test.go @@ -6,11 +6,13 @@ import ( "net/http/httptest" "path/filepath" "runtime" + "runtime/debug" "sync" "sync/atomic" "testing" "time" + "github.com/dunglas/frankenphp/internal/memory" "github.com/dunglas/frankenphp/internal/state" "github.com/stretchr/testify/assert" ) @@ -388,6 +390,21 @@ func testThreadCalculationError(t *testing.T, o *opt) { assert.Error(t, err, "configuration must error") } +// in a container, the memory limit of Go, which Caddy derives from the cgroup, caps the memory of the host +func TestAutomaticMaxThreadsHonorsTheGoMemoryLimit(t *testing.T) { + if total := memory.TotalSysMemory(); total != 0 && total < 640<<20 { + t.Skip("the system memory is lower than the limit") + } + t.Setenv("GOMEMLIMIT", "640MiB") + 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")