From 9ff44a684644952e9973d5aad615259ff7730d36 Mon Sep 17 00:00:00 2001 From: Julien Neuhart Date: Mon, 16 Nov 2026 18:58:28 +0100 Subject: [PATCH] feat: add --libreoffice-max-memory and --chromium-max-memory to kill a runaway conversion before the container is OOM-killed --- Makefile | 2 + compose.yaml | 2 + pkg/gotenberg/cmd.go | 9 + pkg/gotenberg/memory.go | 173 ++++++++++++++++++ pkg/gotenberg/memory_test.go | 141 ++++++++++++++ pkg/modules/chromium/browser.go | 82 ++++++++- pkg/modules/chromium/chromium.go | 10 + pkg/modules/chromium/memory_test.go | 90 +++++++++ pkg/modules/chromium/routes.go | 12 ++ pkg/modules/libreoffice/api/api.go | 9 + pkg/modules/libreoffice/api/libreoffice.go | 39 ++++ .../libreoffice/api/libreoffice_test.go | 64 ++++++- pkg/modules/libreoffice/routes.go | 4 + .../features/chromium_convert_html.feature | 17 ++ test/integration/features/debug.feature | 4 + .../features/libreoffice_convert.feature | 18 ++ 16 files changed, 673 insertions(+), 3 deletions(-) create mode 100644 pkg/gotenberg/memory.go create mode 100644 pkg/gotenberg/memory_test.go create mode 100644 pkg/modules/chromium/memory_test.go diff --git a/Makefile b/Makefile index a19932a5..659749a4 100644 --- a/Makefile +++ b/Makefile @@ -54,6 +54,7 @@ API_DISABLE_VERSION_ROUTE_TELEMETRY=true API_ENABLE_DEBUG_ROUTE=false CHROMIUM_RESTART_AFTER=100 CHROMIUM_MAX_QUEUE_SIZE=0 +CHROMIUM_MAX_MEMORY= CHROMIUM_IDLE_SHUTDOWN_TIMEOUT=0 CHROMIUM_MAX_CONCURRENCY=6 CHROMIUM_AUTO_START=false @@ -78,6 +79,7 @@ CHROMIUM_DISABLE_ROUTES=false CHROMIUM_DEBUG_PROTOCOL=false LIBREOFFICE_RESTART_AFTER=10 LIBREOFFICE_MAX_QUEUE_SIZE=0 +LIBREOFFICE_MAX_MEMORY= LIBREOFFICE_IDLE_SHUTDOWN_TIMEOUT=0 LIBREOFFICE_AUTO_START=false LIBREOFFICE_START_TIMEOUT=20s diff --git a/compose.yaml b/compose.yaml index c9c2b034..5fd5e3ec 100644 --- a/compose.yaml +++ b/compose.yaml @@ -48,6 +48,7 @@ services: - "--chromium-restart-after=${CHROMIUM_RESTART_AFTER}" - "--chromium-auto-start=${CHROMIUM_AUTO_START}" - "--chromium-max-queue-size=${CHROMIUM_MAX_QUEUE_SIZE}" + - "--chromium-max-memory=${CHROMIUM_MAX_MEMORY}" - "--chromium-idle-shutdown-timeout=${CHROMIUM_IDLE_SHUTDOWN_TIMEOUT}" - "--chromium-max-concurrency=${CHROMIUM_MAX_CONCURRENCY}" - "--chromium-start-timeout=${CHROMIUM_START_TIMEOUT}" @@ -71,6 +72,7 @@ services: - "--chromium-debug-protocol=${CHROMIUM_DEBUG_PROTOCOL}" - "--libreoffice-restart-after=${LIBREOFFICE_RESTART_AFTER}" - "--libreoffice-max-queue-size=${LIBREOFFICE_MAX_QUEUE_SIZE}" + - "--libreoffice-max-memory=${LIBREOFFICE_MAX_MEMORY}" - "--libreoffice-idle-shutdown-timeout=${LIBREOFFICE_IDLE_SHUTDOWN_TIMEOUT}" - "--libreoffice-auto-start=${LIBREOFFICE_AUTO_START}" - "--libreoffice-start-timeout=${LIBREOFFICE_START_TIMEOUT}" diff --git a/pkg/gotenberg/cmd.go b/pkg/gotenberg/cmd.go index d638cfed..8a4abe23 100644 --- a/pkg/gotenberg/cmd.go +++ b/pkg/gotenberg/cmd.go @@ -150,6 +150,15 @@ func (cmd *Cmd) Kill() error { return fmt.Errorf("kill unix process: %w", err) } +// Pid returns the process ID of the started process, 0 before it starts. +func (cmd *Cmd) Pid() int { + if cmd.process == nil || cmd.process.Process == nil { + return 0 + } + + return cmd.process.Process.Pid +} + // logCommandOutput creates log entries from the lines of a process output. func logCommandOutput(logger *slog.Logger, reader io.ReadCloser) { r := bufio.NewReader(reader) diff --git a/pkg/gotenberg/memory.go b/pkg/gotenberg/memory.go new file mode 100644 index 00000000..c92f5f9d --- /dev/null +++ b/pkg/gotenberg/memory.go @@ -0,0 +1,173 @@ +package gotenberg + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "strconv" + "time" +) + +// procDir is the proc filesystem the memory of a process tree is read from. +// Tests point it at a fixture. +var procDir = "/proc" + +// MemoryWatchInterval is how often [WatchMemory] reads the memory of the +// process tree it watches. A process that allocates 100 MB per second, as a +// runaway conversion does, goes about 10 MB over the limit before the read +// that catches it. +const MemoryWatchInterval = 100 * time.Millisecond + +// ProcessTreeMemory returns the anonymous resident memory, in bytes, of the +// process pid and of every process it descends from: the RssAnon lines of +// their /proc//status. Anonymous memory is what a process allocates, so a +// runaway allocation shows there, and it leaves out the shared libraries each +// process of a tree maps, which resident memory would count once per process. +// It fails when pid is gone, or when the proc filesystem is missing, as off +// Linux. +func ProcessTreeMemory(pid int) (uint64, error) { + root, err := anonymousMemory(pid) + if err != nil { + return 0, err + } + + entries, err := os.ReadDir(procDir) + if err != nil { + return 0, fmt.Errorf("list processes: %w", err) + } + + children := make(map[int][]int) + for _, entry := range entries { + child, err := strconv.Atoi(entry.Name()) + if err != nil { + continue + } + + parent, err := parentPid(child) + if err != nil { + // The process exited while the list was read. + continue + } + + children[parent] = append(children[parent], child) + } + + total := root + queue := children[pid] + for len(queue) > 0 { + next := queue[0] + queue = queue[1:] + + used, err := anonymousMemory(next) + if err == nil { + total += used + } + + queue = append(queue, children[next]...) + } + + return total, nil +} + +// anonymousMemory returns the RssAnon of the process pid, in bytes. +func anonymousMemory(pid int) (uint64, error) { + status, err := os.ReadFile(filepath.Join(procDir, strconv.Itoa(pid), "status")) + if err != nil { + return 0, fmt.Errorf("read the status of process %d: %w", pid, err) + } + + scanner := bufio.NewScanner(bytes.NewReader(status)) + for scanner.Scan() { + value, found := bytes.CutPrefix(scanner.Bytes(), []byte("RssAnon:")) + if !found { + continue + } + + // The value reads " 123456 kB". + fields := bytes.Fields(value) + if len(fields) != 2 || string(fields[1]) != "kB" { + return 0, fmt.Errorf("read the status of process %d: unexpected RssAnon %q", pid, value) + } + + kb, err := strconv.ParseUint(string(fields[0]), 10, 64) + if err != nil { + return 0, fmt.Errorf("read the status of process %d: %w", pid, err) + } + + return kb * 1024, nil + } + + // A zombie has no memory, and no RssAnon line. + return 0, nil +} + +// parentPid returns the parent of the process pid, from its /proc//stat. +func parentPid(pid int) (int, error) { + stat, err := os.ReadFile(filepath.Join(procDir, strconv.Itoa(pid), "stat")) + if err != nil { + return 0, err + } + + // The command name, in parentheses, may hold spaces and parentheses: the + // fields that follow start after its last closing parenthesis. They are + // the state, then the parent. + end := bytes.LastIndexByte(stat, ')') + if end < 0 { + return 0, errors.New("malformed stat") + } + + fields := bytes.Fields(stat[end+1:]) + if len(fields) < 2 { + return 0, errors.New("malformed stat") + } + + return strconv.Atoi(string(fields[1])) +} + +// WatchMemory calls exceeded once, with the memory used, when the process tree +// of pid holds more than limit bytes of anonymous resident memory (see +// [ProcessTreeMemory]). It reads it at once, then every [MemoryWatchInterval], +// until ctx is done, exceeded runs, or the tree can no longer be read, once pid +// exits. It returns at once when limit is 0. +func WatchMemory(ctx context.Context, logger *slog.Logger, pid int, limit uint64, exceeded func(used uint64)) { + if limit == 0 { + return + } + + ticker := time.NewTicker(MemoryWatchInterval) + defer ticker.Stop() + + for { + if ctx.Err() != nil { + return + } + + used, err := ProcessTreeMemory(pid) + if err != nil { + logger.DebugContext(ctx, fmt.Sprintf("stop watching the memory of process %d: %s", pid, err)) + return + } + + if used > limit { + exceeded(used) + return + } + + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +// FormatMemory writes n bytes in mebibytes, as an operator reads a memory +// limit, such as "900 MiB". +func FormatMemory(n uint64) string { + return fmt.Sprintf("%.0f MiB", float64(n)/(1<<20)) +} diff --git a/pkg/gotenberg/memory_test.go b/pkg/gotenberg/memory_test.go new file mode 100644 index 00000000..a82636f3 --- /dev/null +++ b/pkg/gotenberg/memory_test.go @@ -0,0 +1,141 @@ +package gotenberg + +import ( + "context" + "log/slog" + "os" + "path/filepath" + "strconv" + "testing" + "time" +) + +// fakeProc writes a proc filesystem: each process has a parent and, unless +// it is a zombie, an RssAnon in kB. +func fakeProc(t *testing.T, processes map[int]fakeProcess) { + t.Helper() + + dir := t.TempDir() + for pid, p := range processes { + pidDir := filepath.Join(dir, strconv.Itoa(pid)) + if err := os.MkdirAll(pidDir, 0o755); err != nil { + t.Fatal(err) + } + + // A command name with spaces and parentheses, as Chromium's are. + stat := strconv.Itoa(pid) + " (chrome (renderer) x) S " + strconv.Itoa(p.parent) + " 1 1 0 -1" + if err := os.WriteFile(filepath.Join(pidDir, "stat"), []byte(stat), 0o644); err != nil { + t.Fatal(err) + } + + status := "Name:\tchrome\nState:\tS (sleeping)\n" + if !p.zombie { + status += "VmRSS:\t 999999 kB\nRssAnon:\t " + strconv.Itoa(p.kb) + " kB\nRssFile:\t 777 kB\n" + } + if err := os.WriteFile(filepath.Join(pidDir, "status"), []byte(status), 0o644); err != nil { + t.Fatal(err) + } + } + + // Not a process. + if err := os.MkdirAll(filepath.Join(dir, "sys"), 0o755); err != nil { + t.Fatal(err) + } + + previous := procDir + procDir = dir + t.Cleanup(func() { procDir = previous }) +} + +type fakeProcess = struct { + parent int + kb int + zombie bool +} + +func TestProcessTreeMemory(t *testing.T) { + fakeProc(t, map[int]fakeProcess{ + 1: {parent: 0, kb: 5}, + 10: {parent: 1, kb: 100}, + 11: {parent: 10, kb: 200}, + 12: {parent: 11, kb: 300}, + 13: {parent: 10, zombie: true}, + 20: {parent: 1, kb: 4000}, + }) + + used, err := ProcessTreeMemory(10) + if err != nil { + t.Fatal(err) + } + + if want := uint64(600 * 1024); used != want { + t.Errorf("ProcessTreeMemory(10) = %d, want %d: the process and its descendants, not its siblings", used, want) + } + + _, err = ProcessTreeMemory(99) + if err == nil { + t.Error("ProcessTreeMemory of a process that is gone succeeded") + } +} + +func TestWatchMemory(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + + t.Run("over the limit", func(t *testing.T) { + fakeProc(t, map[int]fakeProcess{10: {parent: 1, kb: 2048}}) + + got := make(chan uint64, 2) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + WatchMemory(ctx, logger, 10, 1<<20, func(used uint64) { got <- used }) + + select { + case used := <-got: + if used != 2048*1024 { + t.Errorf("exceeded(%d), want %d", used, 2048*1024) + } + default: + t.Fatal("exceeded was not called") + } + }) + + t.Run("under the limit until the process exits", func(t *testing.T) { + fakeProc(t, map[int]fakeProcess{10: {parent: 1, kb: 10}}) + + gone := filepath.Join(procDir, "10") + removed := make(chan struct{}) + go func() { + defer close(removed) + time.Sleep(3 * MemoryWatchInterval) + _ = os.RemoveAll(gone) + }() + defer func() { <-removed }() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + WatchMemory(ctx, logger, 10, 1<<20, func(uint64) { t.Error("exceeded was called under the limit") }) + + if ctx.Err() != nil { + t.Fatal("WatchMemory outlived the process") + } + }) + + t.Run("no limit", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + + WatchMemory(ctx, logger, 10, 0, func(uint64) { t.Error("exceeded was called without a limit") }) + + if ctx.Err() != nil { + t.Fatal("WatchMemory waited without a limit") + } + }) +} + +func TestFormatMemory(t *testing.T) { + if got := FormatMemory(900 << 20); got != "900 MiB" { + t.Errorf("FormatMemory = %q, want 900 MiB", got) + } +} diff --git a/pkg/modules/chromium/browser.go b/pkg/modules/chromium/browser.go index f9ba42ab..14f4c29b 100644 --- a/pkg/modules/chromium/browser.go +++ b/pkg/modules/chromium/browser.go @@ -10,6 +10,7 @@ import ( "strings" "sync" "sync/atomic" + "syscall" "time" cdprotobrowser "github.com/chromedp/cdproto/browser" @@ -65,7 +66,10 @@ type browser interface { type browserArguments struct { // Executor args. - binPath string + binPath string + // maxMemory is the anonymous resident memory, in bytes, Chromium may + // hold while it converts, 0 for no limit (see --chromium-max-memory). + maxMemory uint64 allowInsecureLocalhost bool ignoreCertificateErrors bool disableWebSecurity bool @@ -139,6 +143,18 @@ type chromiumBrowser struct { arguments browserArguments fs *gotenberg.FileSystem pinningProxy *pinningProxy + + // pid is the browser process, which the memory watch reads with its + // descendants, the renderers. Set by Start, under ctxMu. + pid int + // watchMu guards inFlight and stopWatching: the memory of Chromium is + // watched while at least one conversion runs. + watchMu sync.Mutex + inFlight int + stopWatching context.CancelFunc + // memoryExceeded holds the memory Chromium held when the watch killed + // it, 0 until then. Start resets it. + memoryExceeded atomic.Uint64 } func newChromiumBrowser(arguments browserArguments) browser { @@ -333,6 +349,11 @@ func (b *chromiumBrowser) Start(ctx context.Context, logger *slog.Logger) (err e cancel() allocatorCancel() } + b.pid = 0 + if c := chromedp.FromContext(browserCtx); c != nil && c.Browser != nil && c.Browser.Process() != nil { + b.pid = c.Browser.Process().Pid + } + b.memoryExceeded.Store(0) b.isStarted.Store(true) return nil @@ -567,7 +588,7 @@ func (b *chromiumBrowser) disposeBrowserContext(logger *slog.Logger, browserCont } } -func (b *chromiumBrowser) do(ctx context.Context, logger *slog.Logger, url string, options Options, aggregate *networkAggregate, tasks chromedp.Tasks) error { +func (b *chromiumBrowser) do(ctx context.Context, logger *slog.Logger, url string, options Options, aggregate *networkAggregate, tasks chromedp.Tasks) (err error) { if !b.isStarted.Load() { return errors.New("browser not started, cannot handle tasks") } @@ -595,6 +616,16 @@ func (b *chromiumBrowser) do(ctx context.Context, logger *slog.Logger, url strin b.ctxMu.RLock() defer b.ctxMu.RUnlock() + defer b.watchMemory(logger)() + + // Killed for its memory, Chromium fails the conversion wherever it was, + // creating the tab included. + defer func() { + if used := b.memoryExceeded.Load(); err != nil && used > 0 { + err = fmt.Errorf("handle tasks: %w: %s held, %s allowed: %w", ErrChromiumMemoryLimitExceeded, gotenberg.FormatMemory(used), gotenberg.FormatMemory(b.arguments.maxMemory), err) + } + }() + // The tab derives from the browser, not from the request, but must not // outlive it: the supervisor holds the request's slot until do returns. // It ends with the request's own cause, so that a wait tells a deadline @@ -630,6 +661,53 @@ func (b *chromiumBrowser) do(ctx context.Context, logger *slog.Logger, url strin return failures.err(runErr, b.ctx.Err() != nil, options.FailOnResourceLoadingFailed) } +// watchMemory counts a conversion in flight, and watches the memory of +// Chromium while one is: a page that never stops allocating would get the +// container OOM-killed, Gotenberg with it, since on cgroup v2 Kubernetes kills +// every process of the container together. Killing Chromium first fails the +// conversions in flight alone, and the supervisor restarts it before the next +// one. An idle Chromium is not watched, so that a limit under its idle memory +// fails conversions rather than restarting it forever. The caller holds ctxMu +// for reading, and calls the returned function once the conversion ends. +func (b *chromiumBrowser) watchMemory(logger *slog.Logger) func() { + if b.arguments.maxMemory == 0 || b.pid == 0 { + return func() {} + } + + b.watchMu.Lock() + defer b.watchMu.Unlock() + + b.inFlight++ + if b.inFlight == 1 { + ctx, cancel := context.WithCancel(context.Background()) + b.stopWatching = cancel + pid := b.pid + + go gotenberg.WatchMemory(ctx, logger, pid, b.arguments.maxMemory, func(used uint64) { + b.memoryExceeded.Store(used) + logger.WarnContext(ctx, fmt.Sprintf("Chromium holds %s of memory, over the %s of --chromium-max-memory (env CHROMIUM_MAX_MEMORY): kill it", gotenberg.FormatMemory(used), gotenberg.FormatMemory(b.arguments.maxMemory))) + + // The renderers exit with the browser, and Stop kills any that + // linger when the supervisor restarts it. + err := syscall.Kill(pid, syscall.SIGKILL) + if err != nil && !errors.Is(err, syscall.ESRCH) { + logger.ErrorContext(ctx, fmt.Sprintf("kill Chromium: %s", err)) + } + }) + } + + return func() { + b.watchMu.Lock() + defer b.watchMu.Unlock() + + b.inFlight-- + if b.inFlight == 0 { + b.stopWatching() + b.stopWatching = nil + } + } +} + // requestError returns the error of a run that ctx, the request's context, // may have ended. The tab is canceled when the request ends, so the run // reports context.Canceled even when the request ran out of time: the diff --git a/pkg/modules/chromium/chromium.go b/pkg/modules/chromium/chromium.go index 0943fcac..97ac8891 100644 --- a/pkg/modules/chromium/chromium.go +++ b/pkg/modules/chromium/chromium.go @@ -85,6 +85,12 @@ var ( // conversion. ErrChromiumCrashed = errors.New("chromium crashed") + // ErrChromiumMemoryLimitExceeded happens when Chromium holds more memory + // than --chromium-max-memory (env CHROMIUM_MAX_MEMORY) allows while it + // converts. Gotenberg kills it, which fails every conversion in flight: + // it cannot tell which page holds the memory. + ErrChromiumMemoryLimitExceeded = errors.New("chromium exceeded its memory limit") + // PDF specific. // ErrOmitBackgroundWithoutPrintBackground happens if @@ -522,6 +528,7 @@ func (mod *Chromium) Descriptor() gotenberg.ModuleDescriptor { fs.Int64("chromium-max-queue-size", 0, "Maximum request queue size for Chromium. Set to 0 to disable this feature") fs.Duration("chromium-idle-shutdown-timeout", 0, "Shutdown Chromium after being idle for the given duration. Set to 0 to disable this feature") fs.Int64("chromium-max-concurrency", 6, "Maximum number of concurrent conversions. Chromium supports up to 6") + fs.String("chromium-max-memory", "", "Set the anonymous resident memory Chromium, all its processes together, may hold while it converts - it accepts values like 1500MB, 2GB, etc. Over it, Gotenberg kills Chromium, which fails every conversion in flight with a 503, and restarts it. Keep it under the container's memory limit, so that a runaway page does not get the container OOM-killed. Empty disables this feature") fs.Bool("chromium-auto-start", false, "Automatically launch Chromium upon initialization if set to true; otherwise, Chromium will start at the time of the first conversion") fs.Duration("chromium-start-timeout", time.Duration(20)*time.Second, "Maximum duration to wait for Chromium to start or restart") fs.Bool("chromium-allow-insecure-localhost", false, "Ignore TLS/SSL errors on localhost") @@ -578,6 +585,7 @@ func (mod *Chromium) Provision(ctx *gotenberg.Context) error { proxyServer: flags.MustString("chromium-proxy-server"), enableEnvironmentProxy: flags.MustBool("chromium-enable-environment-proxy"), wsUrlReadTimeout: flags.MustDuration("chromium-start-timeout"), + maxMemory: uint64(max(flags.MustHumanReadableBytes("chromium-max-memory"), 0)), hyphenDataDirPath: hyphenDataDirPath, debugProtocol: flags.MustBool("chromium-debug-protocol"), @@ -1000,6 +1008,8 @@ func chromiumErrorType(err error) string { errors.Is(err, ErrPageRangesSyntaxError), errors.Is(err, ErrPageRangesExceedsPageCount): return gotenberg.ErrorTypeInvalidInput + case errors.Is(err, ErrChromiumMemoryLimitExceeded): + return "chromium_memory_limit" case errors.Is(err, ErrChromiumCrashed), errors.Is(err, gotenberg.ErrMaximumQueueSizeExceeded), errors.Is(err, gotenberg.ErrProcessAlreadyRestarting): diff --git a/pkg/modules/chromium/memory_test.go b/pkg/modules/chromium/memory_test.go new file mode 100644 index 00000000..ed3157f8 --- /dev/null +++ b/pkg/modules/chromium/memory_test.go @@ -0,0 +1,90 @@ +package chromium + +import ( + "log/slog" + "os/exec" + "runtime" + "testing" + "time" + + "github.com/gotenberg/gotenberg/v9/pkg/gotenberg" +) + +// The memory watch runs while a conversion is in flight, and kills the +// browser process when Chromium holds more than the limit. +func TestChromiumBrowser_WatchMemory(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("the memory limit reads /proc") + } + + logger := slog.New(slog.DiscardHandler) + + start := func(t *testing.T) (*exec.Cmd, <-chan error) { + t.Helper() + + // A stand-in for the browser process: any process holds more than + // one byte of anonymous memory. + cmd := exec.Command("sleep", "30") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cmd.Process.Kill() }) + + exited := make(chan error, 1) + go func() { exited <- cmd.Wait() }() + + return cmd, exited + } + + t.Run("idle, not watched", func(t *testing.T) { + cmd, exited := start(t) + b := &chromiumBrowser{arguments: browserArguments{maxMemory: 1}, pid: cmd.Process.Pid} + + b.watchMemory(logger)() + + select { + case <-exited: + t.Fatal("the watch killed the browser once no conversion was in flight") + case <-time.After(5 * gotenberg.MemoryWatchInterval): + } + + if b.memoryExceeded.Load() != 0 { + t.Fatal("memoryExceeded set without a conversion in flight") + } + }) + + t.Run("in flight, over the limit", func(t *testing.T) { + cmd, exited := start(t) + b := &chromiumBrowser{arguments: browserArguments{maxMemory: 1}, pid: cmd.Process.Pid} + + releaseFirst := b.watchMemory(logger) + releaseSecond := b.watchMemory(logger) + defer releaseSecond() + releaseFirst() + + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Fatal("the browser still runs over the memory limit") + } + + if b.memoryExceeded.Load() == 0 { + t.Fatal("memoryExceeded not set once the browser was killed") + } + }) + + t.Run("no limit", func(t *testing.T) { + b := &chromiumBrowser{pid: 1} + b.watchMemory(logger)() + + if b.inFlight != 0 || b.stopWatching != nil { + t.Fatal("watchMemory counted a conversion without a limit") + } + }) +} + +func TestChromiumErrorType_MemoryLimit(t *testing.T) { + if got := chromiumErrorType(ErrChromiumMemoryLimitExceeded); got != "chromium_memory_limit" { + t.Errorf("error type = %q, want chromium_memory_limit", got) + } +} diff --git a/pkg/modules/chromium/routes.go b/pkg/modules/chromium/routes.go index 53e9c6b3..9fc8a1af 100644 --- a/pkg/modules/chromium/routes.go +++ b/pkg/modules/chromium/routes.go @@ -938,6 +938,18 @@ func handleChromiumError(err error, options Options) error { return nil } + // Gotenberg cannot tell which page held the memory: every conversion in + // flight fails, and each may succeed once retried on its own. + if errors.Is(err, ErrChromiumMemoryLimitExceeded) { + return api.WrapError( + err, + api.NewSentinelHttpError( + http.StatusServiceUnavailable, + "Chromium exceeded its memory limit while processing the request, and Gotenberg restarted it. Retry; if the request alone exceeds it, reduce the page, or raise --chromium-max-memory (env CHROMIUM_MAX_MEMORY) on the server.", + ), + ) + } + if errors.Is(err, ErrChromiumCrashed) { return api.WrapError( err, diff --git a/pkg/modules/libreoffice/api/api.go b/pkg/modules/libreoffice/api/api.go index a197a63f..8db1bff9 100644 --- a/pkg/modules/libreoffice/api/api.go +++ b/pkg/modules/libreoffice/api/api.go @@ -50,6 +50,11 @@ var ( // conversion often succeeds once LibreOffice restarts. // See https://github.com/gotenberg/gotenberg/issues/639. ErrCrashed = errors.New("LibreOffice crashed") + + // ErrMemoryLimitExceeded happens when LibreOffice holds more memory than + // --libreoffice-max-memory (env LIBREOFFICE_MAX_MEMORY) allows during a + // conversion. Gotenberg kills it, and a retry would exceed it again. + ErrMemoryLimitExceeded = errors.New("LibreOffice exceeded its memory limit") ) // Api is a module that provides a [Converter] backed by LibreOffice. @@ -392,6 +397,7 @@ func (a *Api) Descriptor() gotenberg.ModuleDescriptor { fs := flag.NewFlagSet("api", flag.ExitOnError) fs.Int64("libreoffice-restart-after", 10, "Number of conversions after which LibreOffice will automatically restart. Set to 0 to disable this feature") fs.Int64("libreoffice-max-queue-size", 0, "Maximum request queue size for LibreOffice. Set to 0 to disable this feature") + fs.String("libreoffice-max-memory", "", "Set the anonymous resident memory LibreOffice may hold during a conversion - it accepts values like 900MB, 1GB, etc. Over it, Gotenberg kills LibreOffice, answers 422 and restarts it. Keep it under the container's memory limit, so that a runaway conversion fails alone rather than getting the container OOM-killed. Empty disables this feature") fs.Duration("libreoffice-idle-shutdown-timeout", 0, "Shutdown LibreOffice after being idle for the given duration. Set to 0 to disable this feature") fs.Bool("libreoffice-auto-start", false, "Automatically launch LibreOffice upon initialization if set to true; otherwise, LibreOffice will start at the time of the first conversion") fs.Duration("libreoffice-start-timeout", time.Duration(20)*time.Second, "Maximum duration to wait for LibreOffice to start or restart") @@ -427,6 +433,7 @@ func (a *Api) Provision(ctx *gotenberg.Context) error { binPath: libreOfficeBinPath, lokBinPath: lokBinPath, startTimeout: flags.MustDuration("libreoffice-start-timeout"), + maxMemory: uint64(max(flags.MustHumanReadableBytes("libreoffice-max-memory"), 0)), enableMacros: flags.MustBool("libreoffice-enable-macros"), proxyOptions: outboundProxyOptions{ allowList: flags.MustRegexpSlice("libreoffice-allow-list"), @@ -746,6 +753,8 @@ func libreofficeErrorType(err error) string { errors.Is(err, ErrLoadFailed), errors.Is(err, ErrInvalidPassword): return gotenberg.ErrorTypeInvalidInput + case errors.Is(err, ErrMemoryLimitExceeded): + return "libreoffice_memory_limit" case errors.Is(err, ErrSaveFailed), errors.Is(err, ErrCrashed): return "libreoffice_exception" case errors.Is(err, gotenberg.ErrMaximumQueueSizeExceeded), errors.Is(err, gotenberg.ErrProcessAlreadyRestarting): diff --git a/pkg/modules/libreoffice/api/libreoffice.go b/pkg/modules/libreoffice/api/libreoffice.go index 28fbc927..f4f8d087 100644 --- a/pkg/modules/libreoffice/api/libreoffice.go +++ b/pkg/modules/libreoffice/api/libreoffice.go @@ -30,6 +30,9 @@ type libreOfficeArguments struct { binPath string lokBinPath string startTimeout time.Duration + // maxMemory is the anonymous resident memory, in bytes, lok may hold + // during a conversion, 0 for no limit (see --libreoffice-max-memory). + maxMemory uint64 // enableMacros lets lok run the documents' macros. Off by default: a // macro runs code inside the container. enableMacros bool @@ -517,7 +520,43 @@ func (p *libreOfficeProcess) pdf(ctx context.Context, logger *slog.Logger, input logger.DebugContext(ctx, fmt.Sprintf("print to PDF with: %+v", options)) + // A conversion that never stops allocating would get the container + // OOM-killed, Gotenberg with it: on cgroup v2, Kubernetes kills every + // process of the container together. Killing lok first fails this + // conversion alone. Only a conversion is watched, so that a limit under + // lok's idle memory fails conversions rather than restarting lok forever. + var exceeded atomic.Uint64 + watchCtx, cancelWatch := context.WithCancel(ctx) + watched := make(chan struct{}) + // Waiting for the watch to end means a kill it decided reads as the + // memory limit, and none lands once this conversion returns. + stopWatching := func() { + cancelWatch() + <-watched + } + defer cancelWatch() + go func() { + defer close(watched) + gotenberg.WatchMemory(watchCtx, logger, cmd.Pid(), p.arguments.maxMemory, func(used uint64) { + exceeded.Store(used) + logger.WarnContext(ctx, fmt.Sprintf("LibreOffice holds %s of memory, over the %s of --libreoffice-max-memory (env LIBREOFFICE_MAX_MEMORY): kill it", gotenberg.FormatMemory(used), gotenberg.FormatMemory(p.arguments.maxMemory))) + + killErr := cmd.Kill() + if killErr != nil { + logger.ErrorContext(ctx, fmt.Sprintf("kill lok: %s", killErr)) + } + }) + }() + resp, err := exchange(ctx, stdin, stdout, exited, req) + stopWatching() + + if used := exceeded.Load(); used > 0 { + terminate(ctx, logger, cmd, exited) + + return fmt.Errorf("%w: %s held, %s allowed", ErrMemoryLimitExceeded, gotenberg.FormatMemory(used), gotenberg.FormatMemory(p.arguments.maxMemory)) + } + if err != nil { if ctx.Err() != nil { // LibreOfficeKit calls cannot be cancelled: kill lok so that its diff --git a/pkg/modules/libreoffice/api/libreoffice_test.go b/pkg/modules/libreoffice/api/libreoffice_test.go index abd735f6..c8657a4d 100644 --- a/pkg/modules/libreoffice/api/libreoffice_test.go +++ b/pkg/modules/libreoffice/api/libreoffice_test.go @@ -9,9 +9,12 @@ import ( "log/slog" "os" "path/filepath" + "runtime" "strings" "testing" "time" + + "github.com/gotenberg/gotenberg/v9/pkg/gotenberg" ) // fakeLokEnv makes the test binary act as lok's long-running mode, so the @@ -29,7 +32,8 @@ func TestMain(m *testing.M) { // fakeLok answers each request according to the input filename: "ok" writes // the output, "badpass", "unreadable", "destroyed" and "panic" fail with lok's -// codes, "hang" never answers, and "crash" exits. It records its arguments next to its profile. +// codes, "hang" never answers, "hog" allocates until it is killed, and "crash" +// exits. It records its arguments next to its profile. func fakeLok() { for i, arg := range os.Args { if arg == "--user-profile-path" && i+1 < len(os.Args) { @@ -68,6 +72,16 @@ func fakeLok() { time.Sleep(time.Hour) case "crash": os.Exit(3) + case "hog": + var held [][]byte + for { + chunk := make([]byte, 16<<20) + for i := 0; i < len(chunk); i += 4096 { + chunk[i] = 1 + } + held = append(held, chunk) + time.Sleep(10 * time.Millisecond) + } case "destroyed": _ = out.Encode(lokResponse{Code: lokCodeOfficeDestroyed, Error: "office destroyed"}) case "panic": @@ -330,3 +344,51 @@ func TestLibreOfficeProcess_Crash(t *testing.T) { t.Fatal("a crashed lok reports healthy") } } + +func TestLibreOfficeProcess_MemoryLimit(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("the memory limit reads /proc") + } + + p := startFakeLok(t) + p.arguments.maxMemory = 64 << 20 + logger := slog.New(slog.DiscardHandler) + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + err := p.pdf(ctx, logger, "hog.docx", "out.pdf", DefaultOptions()) + if !errors.Is(err, ErrMemoryLimitExceeded) { + t.Fatalf("pdf = %v, want ErrMemoryLimitExceeded", err) + } + + if errors.Is(err, ErrCrashed) { + t.Fatal("a conversion over the memory limit reads as a crash, which the API retries") + } + + if p.Healthy(logger) { + t.Fatal("a lok killed for its memory reports healthy") + } + + if got := libreofficeErrorType(err); got != "libreoffice_memory_limit" { + t.Errorf("error type = %q, want libreoffice_memory_limit", got) + } +} + +// A lok whose idle memory is over the limit is not killed between +// conversions: only a conversion is watched. +func TestLibreOfficeProcess_MemoryLimitWatchesConversionsOnly(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("the memory limit reads /proc") + } + + p := startFakeLok(t) + p.arguments.maxMemory = 1 + logger := slog.New(slog.DiscardHandler) + + time.Sleep(5 * gotenberg.MemoryWatchInterval) + + if !p.Healthy(logger) { + t.Fatal("an idle lok was killed") + } +} diff --git a/pkg/modules/libreoffice/routes.go b/pkg/modules/libreoffice/routes.go index 4e3d4c09..a5f37502 100644 --- a/pkg/modules/libreoffice/routes.go +++ b/pkg/modules/libreoffice/routes.go @@ -188,6 +188,10 @@ func convertRoute(libreOffice libreofficeapi.Converter, processor *pdf.Processor sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("LibreOffice could not read the document '%s'. Ensure the file is not corrupted and that its extension matches its actual format.", filename)) case errors.Is(err, libreofficeapi.ErrSaveFailed) && options.PageRanges != "": sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("LibreOffice could not apply the pages '%s' to the document '%s'. Check the 'nativePages' form field; valid values look like '1-4', '2' or '1,3,5-7'.", options.PageRanges, filename)) + case errors.Is(err, libreofficeapi.ErrMemoryLimitExceeded): + // The same document exceeds the limit again: a 4xx + // tells the client not to retry it as is. + sentinel = api.NewSentinelHttpError(http.StatusUnprocessableEntity, fmt.Sprintf("LibreOffice exceeded its memory limit converting the document '%s'. Reduce the document, or raise --libreoffice-max-memory (env LIBREOFFICE_MAX_MEMORY) on the server.", filename)) case errors.Is(err, libreofficeapi.ErrSaveFailed), errors.Is(err, libreofficeapi.ErrCrashed): sentinel = api.NewSentinelHttpError(http.StatusInternalServerError, fmt.Sprintf(unattributableFailureMessage, filename)) default: diff --git a/test/integration/features/chromium_convert_html.feature b/test/integration/features/chromium_convert_html.feature index c41a529f..efcaad75 100644 --- a/test/integration/features/chromium_convert_html.feature +++ b/test/integration/features/chromium_convert_html.feature @@ -1847,3 +1847,20 @@ Feature: /forms/chromium/convert/html Then the response header "Content-Type" should be "application/pdf" Then there should be 1 PDF(s) in the response Then the "foo.pdf" PDF should have 1 page(s) + + # Over --chromium-max-memory, Gotenberg restarts Chromium, which fails every + # conversion in flight with a 503: it cannot tell which page held the memory. + # 1MB sits under Chromium's own memory, so any conversion exceeds it. + Scenario: POST /forms/chromium/convert/html (Memory Limit) + Given I have a Gotenberg container with the following environment variable(s): + | CHROMIUM_MAX_MEMORY | 1MB | + When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/html" endpoint with the following form data and header(s): + | files | testdata/page-1-html/index.html | file | + Then the response status code should be 503 + Then the response body should match string: + """ + Chromium exceeded its memory limit while processing the request, and Gotenberg restarted it. Retry; if the request alone exceeds it, reduce the page, or raise --chromium-max-memory (env CHROMIUM_MAX_MEMORY) on the server. + """ + When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/html" endpoint with the following form data and header(s): + | files | testdata/page-1-html/index.html | file | + Then the response status code should be 503 diff --git a/test/integration/features/debug.feature b/test/integration/features/debug.feature index 5d3ee3b9..30b0bb9a 100644 --- a/test/integration/features/debug.feature +++ b/test/integration/features/debug.feature @@ -71,6 +71,7 @@ Feature: /debug "chromium-ignore-certificate-errors": "false", "chromium-idle-shutdown-timeout": "0s", "chromium-max-concurrency": "6", + "chromium-max-memory": "", "chromium-max-queue-size": "0", "chromium-proxy-server": "", "chromium-restart-after": "100", @@ -81,6 +82,7 @@ Feature: /debug "libreoffice-auto-start": "false", "libreoffice-disable-routes": "false", "libreoffice-idle-shutdown-timeout": "0s", + "libreoffice-max-memory": "", "libreoffice-max-queue-size": "0", "libreoffice-restart-after": "10", "libreoffice-start-timeout": "20s", @@ -180,6 +182,7 @@ Feature: /debug "chromium-idle-shutdown-timeout": "0s", "chromium-max-queue-size": "0", "chromium-max-concurrency": "6", + "chromium-max-memory": "", "chromium-proxy-server": "", "chromium-restart-after": "100", "chromium-shared-browser-context": "false", @@ -189,6 +192,7 @@ Feature: /debug "libreoffice-auto-start": "false", "libreoffice-disable-routes": "false", "libreoffice-idle-shutdown-timeout": "0s", + "libreoffice-max-memory": "", "libreoffice-max-queue-size": "0", "libreoffice-restart-after": "10", "libreoffice-start-timeout": "20s", diff --git a/test/integration/features/libreoffice_convert.feature b/test/integration/features/libreoffice_convert.feature index dc9b2f07..ef30f640 100644 --- a/test/integration/features/libreoffice_convert.feature +++ b/test/integration/features/libreoffice_convert.feature @@ -1237,3 +1237,21 @@ Feature: /forms/libreoffice/convert """ Invalid form data: form field 'stages' is disabled on this instance; send the request without it """ + + # A conversion over --libreoffice-max-memory fails alone with a 422, which + # tells the client not to retry it as is, and LibreOffice restarts for the + # next one. 1MB sits under LibreOffice's own memory, so any conversion + # exceeds it. + Scenario: POST /forms/libreoffice/convert (Memory Limit) + Given I have a Gotenberg container with the following environment variable(s): + | LIBREOFFICE_MAX_MEMORY | 1MB | + When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s): + | files | testdata/page_1.docx | file | + Then the response status code should be 422 + Then the response body should match string: + """ + LibreOffice exceeded its memory limit converting the document 'page_1.docx'. Reduce the document, or raise --libreoffice-max-memory (env LIBREOFFICE_MAX_MEMORY) on the server. + """ + When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s): + | files | testdata/page_1.docx | file | + Then the response status code should be 422