mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
feat: add --libreoffice-max-memory and --chromium-max-memory to kill a runaway conversion before the container is OOM-killed
This commit is contained in:
2
Makefile
2
Makefile
@@ -54,6 +54,7 @@ API_DISABLE_VERSION_ROUTE_TELEMETRY=true
|
|||||||
API_ENABLE_DEBUG_ROUTE=false
|
API_ENABLE_DEBUG_ROUTE=false
|
||||||
CHROMIUM_RESTART_AFTER=100
|
CHROMIUM_RESTART_AFTER=100
|
||||||
CHROMIUM_MAX_QUEUE_SIZE=0
|
CHROMIUM_MAX_QUEUE_SIZE=0
|
||||||
|
CHROMIUM_MAX_MEMORY=
|
||||||
CHROMIUM_IDLE_SHUTDOWN_TIMEOUT=0
|
CHROMIUM_IDLE_SHUTDOWN_TIMEOUT=0
|
||||||
CHROMIUM_MAX_CONCURRENCY=6
|
CHROMIUM_MAX_CONCURRENCY=6
|
||||||
CHROMIUM_AUTO_START=false
|
CHROMIUM_AUTO_START=false
|
||||||
@@ -78,6 +79,7 @@ CHROMIUM_DISABLE_ROUTES=false
|
|||||||
CHROMIUM_DEBUG_PROTOCOL=false
|
CHROMIUM_DEBUG_PROTOCOL=false
|
||||||
LIBREOFFICE_RESTART_AFTER=10
|
LIBREOFFICE_RESTART_AFTER=10
|
||||||
LIBREOFFICE_MAX_QUEUE_SIZE=0
|
LIBREOFFICE_MAX_QUEUE_SIZE=0
|
||||||
|
LIBREOFFICE_MAX_MEMORY=
|
||||||
LIBREOFFICE_IDLE_SHUTDOWN_TIMEOUT=0
|
LIBREOFFICE_IDLE_SHUTDOWN_TIMEOUT=0
|
||||||
LIBREOFFICE_AUTO_START=false
|
LIBREOFFICE_AUTO_START=false
|
||||||
LIBREOFFICE_START_TIMEOUT=20s
|
LIBREOFFICE_START_TIMEOUT=20s
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ services:
|
|||||||
- "--chromium-restart-after=${CHROMIUM_RESTART_AFTER}"
|
- "--chromium-restart-after=${CHROMIUM_RESTART_AFTER}"
|
||||||
- "--chromium-auto-start=${CHROMIUM_AUTO_START}"
|
- "--chromium-auto-start=${CHROMIUM_AUTO_START}"
|
||||||
- "--chromium-max-queue-size=${CHROMIUM_MAX_QUEUE_SIZE}"
|
- "--chromium-max-queue-size=${CHROMIUM_MAX_QUEUE_SIZE}"
|
||||||
|
- "--chromium-max-memory=${CHROMIUM_MAX_MEMORY}"
|
||||||
- "--chromium-idle-shutdown-timeout=${CHROMIUM_IDLE_SHUTDOWN_TIMEOUT}"
|
- "--chromium-idle-shutdown-timeout=${CHROMIUM_IDLE_SHUTDOWN_TIMEOUT}"
|
||||||
- "--chromium-max-concurrency=${CHROMIUM_MAX_CONCURRENCY}"
|
- "--chromium-max-concurrency=${CHROMIUM_MAX_CONCURRENCY}"
|
||||||
- "--chromium-start-timeout=${CHROMIUM_START_TIMEOUT}"
|
- "--chromium-start-timeout=${CHROMIUM_START_TIMEOUT}"
|
||||||
@@ -71,6 +72,7 @@ services:
|
|||||||
- "--chromium-debug-protocol=${CHROMIUM_DEBUG_PROTOCOL}"
|
- "--chromium-debug-protocol=${CHROMIUM_DEBUG_PROTOCOL}"
|
||||||
- "--libreoffice-restart-after=${LIBREOFFICE_RESTART_AFTER}"
|
- "--libreoffice-restart-after=${LIBREOFFICE_RESTART_AFTER}"
|
||||||
- "--libreoffice-max-queue-size=${LIBREOFFICE_MAX_QUEUE_SIZE}"
|
- "--libreoffice-max-queue-size=${LIBREOFFICE_MAX_QUEUE_SIZE}"
|
||||||
|
- "--libreoffice-max-memory=${LIBREOFFICE_MAX_MEMORY}"
|
||||||
- "--libreoffice-idle-shutdown-timeout=${LIBREOFFICE_IDLE_SHUTDOWN_TIMEOUT}"
|
- "--libreoffice-idle-shutdown-timeout=${LIBREOFFICE_IDLE_SHUTDOWN_TIMEOUT}"
|
||||||
- "--libreoffice-auto-start=${LIBREOFFICE_AUTO_START}"
|
- "--libreoffice-auto-start=${LIBREOFFICE_AUTO_START}"
|
||||||
- "--libreoffice-start-timeout=${LIBREOFFICE_START_TIMEOUT}"
|
- "--libreoffice-start-timeout=${LIBREOFFICE_START_TIMEOUT}"
|
||||||
|
|||||||
@@ -150,6 +150,15 @@ func (cmd *Cmd) Kill() error {
|
|||||||
return fmt.Errorf("kill unix process: %w", err)
|
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.
|
// logCommandOutput creates log entries from the lines of a process output.
|
||||||
func logCommandOutput(logger *slog.Logger, reader io.ReadCloser) {
|
func logCommandOutput(logger *slog.Logger, reader io.ReadCloser) {
|
||||||
r := bufio.NewReader(reader)
|
r := bufio.NewReader(reader)
|
||||||
|
|||||||
173
pkg/gotenberg/memory.go
Normal file
173
pkg/gotenberg/memory.go
Normal file
@@ -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/<pid>/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/<pid>/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))
|
||||||
|
}
|
||||||
141
pkg/gotenberg/memory_test.go
Normal file
141
pkg/gotenberg/memory_test.go
Normal file
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
cdprotobrowser "github.com/chromedp/cdproto/browser"
|
cdprotobrowser "github.com/chromedp/cdproto/browser"
|
||||||
@@ -65,7 +66,10 @@ type browser interface {
|
|||||||
|
|
||||||
type browserArguments struct {
|
type browserArguments struct {
|
||||||
// Executor args.
|
// 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
|
allowInsecureLocalhost bool
|
||||||
ignoreCertificateErrors bool
|
ignoreCertificateErrors bool
|
||||||
disableWebSecurity bool
|
disableWebSecurity bool
|
||||||
@@ -139,6 +143,18 @@ type chromiumBrowser struct {
|
|||||||
arguments browserArguments
|
arguments browserArguments
|
||||||
fs *gotenberg.FileSystem
|
fs *gotenberg.FileSystem
|
||||||
pinningProxy *pinningProxy
|
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 {
|
func newChromiumBrowser(arguments browserArguments) browser {
|
||||||
@@ -333,6 +349,11 @@ func (b *chromiumBrowser) Start(ctx context.Context, logger *slog.Logger) (err e
|
|||||||
cancel()
|
cancel()
|
||||||
allocatorCancel()
|
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)
|
b.isStarted.Store(true)
|
||||||
|
|
||||||
return nil
|
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() {
|
if !b.isStarted.Load() {
|
||||||
return errors.New("browser not started, cannot handle tasks")
|
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()
|
b.ctxMu.RLock()
|
||||||
defer b.ctxMu.RUnlock()
|
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
|
// 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.
|
// 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
|
// 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)
|
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,
|
// 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
|
// 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
|
// reports context.Canceled even when the request ran out of time: the
|
||||||
|
|||||||
@@ -85,6 +85,12 @@ var (
|
|||||||
// conversion.
|
// conversion.
|
||||||
ErrChromiumCrashed = errors.New("chromium crashed")
|
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.
|
// PDF specific.
|
||||||
|
|
||||||
// ErrOmitBackgroundWithoutPrintBackground happens if
|
// 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.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.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.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.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.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")
|
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"),
|
proxyServer: flags.MustString("chromium-proxy-server"),
|
||||||
enableEnvironmentProxy: flags.MustBool("chromium-enable-environment-proxy"),
|
enableEnvironmentProxy: flags.MustBool("chromium-enable-environment-proxy"),
|
||||||
wsUrlReadTimeout: flags.MustDuration("chromium-start-timeout"),
|
wsUrlReadTimeout: flags.MustDuration("chromium-start-timeout"),
|
||||||
|
maxMemory: uint64(max(flags.MustHumanReadableBytes("chromium-max-memory"), 0)),
|
||||||
hyphenDataDirPath: hyphenDataDirPath,
|
hyphenDataDirPath: hyphenDataDirPath,
|
||||||
debugProtocol: flags.MustBool("chromium-debug-protocol"),
|
debugProtocol: flags.MustBool("chromium-debug-protocol"),
|
||||||
|
|
||||||
@@ -1000,6 +1008,8 @@ func chromiumErrorType(err error) string {
|
|||||||
errors.Is(err, ErrPageRangesSyntaxError),
|
errors.Is(err, ErrPageRangesSyntaxError),
|
||||||
errors.Is(err, ErrPageRangesExceedsPageCount):
|
errors.Is(err, ErrPageRangesExceedsPageCount):
|
||||||
return gotenberg.ErrorTypeInvalidInput
|
return gotenberg.ErrorTypeInvalidInput
|
||||||
|
case errors.Is(err, ErrChromiumMemoryLimitExceeded):
|
||||||
|
return "chromium_memory_limit"
|
||||||
case errors.Is(err, ErrChromiumCrashed),
|
case errors.Is(err, ErrChromiumCrashed),
|
||||||
errors.Is(err, gotenberg.ErrMaximumQueueSizeExceeded),
|
errors.Is(err, gotenberg.ErrMaximumQueueSizeExceeded),
|
||||||
errors.Is(err, gotenberg.ErrProcessAlreadyRestarting):
|
errors.Is(err, gotenberg.ErrProcessAlreadyRestarting):
|
||||||
|
|||||||
90
pkg/modules/chromium/memory_test.go
Normal file
90
pkg/modules/chromium/memory_test.go
Normal file
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -938,6 +938,18 @@ func handleChromiumError(err error, options Options) error {
|
|||||||
return nil
|
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) {
|
if errors.Is(err, ErrChromiumCrashed) {
|
||||||
return api.WrapError(
|
return api.WrapError(
|
||||||
err,
|
err,
|
||||||
|
|||||||
@@ -50,6 +50,11 @@ var (
|
|||||||
// conversion often succeeds once LibreOffice restarts.
|
// conversion often succeeds once LibreOffice restarts.
|
||||||
// See https://github.com/gotenberg/gotenberg/issues/639.
|
// See https://github.com/gotenberg/gotenberg/issues/639.
|
||||||
ErrCrashed = errors.New("LibreOffice crashed")
|
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.
|
// 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 := 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-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.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.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.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")
|
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,
|
binPath: libreOfficeBinPath,
|
||||||
lokBinPath: lokBinPath,
|
lokBinPath: lokBinPath,
|
||||||
startTimeout: flags.MustDuration("libreoffice-start-timeout"),
|
startTimeout: flags.MustDuration("libreoffice-start-timeout"),
|
||||||
|
maxMemory: uint64(max(flags.MustHumanReadableBytes("libreoffice-max-memory"), 0)),
|
||||||
enableMacros: flags.MustBool("libreoffice-enable-macros"),
|
enableMacros: flags.MustBool("libreoffice-enable-macros"),
|
||||||
proxyOptions: outboundProxyOptions{
|
proxyOptions: outboundProxyOptions{
|
||||||
allowList: flags.MustRegexpSlice("libreoffice-allow-list"),
|
allowList: flags.MustRegexpSlice("libreoffice-allow-list"),
|
||||||
@@ -746,6 +753,8 @@ func libreofficeErrorType(err error) string {
|
|||||||
errors.Is(err, ErrLoadFailed),
|
errors.Is(err, ErrLoadFailed),
|
||||||
errors.Is(err, ErrInvalidPassword):
|
errors.Is(err, ErrInvalidPassword):
|
||||||
return gotenberg.ErrorTypeInvalidInput
|
return gotenberg.ErrorTypeInvalidInput
|
||||||
|
case errors.Is(err, ErrMemoryLimitExceeded):
|
||||||
|
return "libreoffice_memory_limit"
|
||||||
case errors.Is(err, ErrSaveFailed), errors.Is(err, ErrCrashed):
|
case errors.Is(err, ErrSaveFailed), errors.Is(err, ErrCrashed):
|
||||||
return "libreoffice_exception"
|
return "libreoffice_exception"
|
||||||
case errors.Is(err, gotenberg.ErrMaximumQueueSizeExceeded), errors.Is(err, gotenberg.ErrProcessAlreadyRestarting):
|
case errors.Is(err, gotenberg.ErrMaximumQueueSizeExceeded), errors.Is(err, gotenberg.ErrProcessAlreadyRestarting):
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ type libreOfficeArguments struct {
|
|||||||
binPath string
|
binPath string
|
||||||
lokBinPath string
|
lokBinPath string
|
||||||
startTimeout time.Duration
|
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
|
// enableMacros lets lok run the documents' macros. Off by default: a
|
||||||
// macro runs code inside the container.
|
// macro runs code inside the container.
|
||||||
enableMacros bool
|
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))
|
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)
|
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 err != nil {
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
// LibreOfficeKit calls cannot be cancelled: kill lok so that its
|
// LibreOfficeKit calls cannot be cancelled: kill lok so that its
|
||||||
|
|||||||
@@ -9,9 +9,12 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakeLokEnv makes the test binary act as lok's long-running mode, so the
|
// 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
|
// fakeLok answers each request according to the input filename: "ok" writes
|
||||||
// the output, "badpass", "unreadable", "destroyed" and "panic" fail with lok's
|
// 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() {
|
func fakeLok() {
|
||||||
for i, arg := range os.Args {
|
for i, arg := range os.Args {
|
||||||
if arg == "--user-profile-path" && i+1 < len(os.Args) {
|
if arg == "--user-profile-path" && i+1 < len(os.Args) {
|
||||||
@@ -68,6 +72,16 @@ func fakeLok() {
|
|||||||
time.Sleep(time.Hour)
|
time.Sleep(time.Hour)
|
||||||
case "crash":
|
case "crash":
|
||||||
os.Exit(3)
|
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":
|
case "destroyed":
|
||||||
_ = out.Encode(lokResponse{Code: lokCodeOfficeDestroyed, Error: "office destroyed"})
|
_ = out.Encode(lokResponse{Code: lokCodeOfficeDestroyed, Error: "office destroyed"})
|
||||||
case "panic":
|
case "panic":
|
||||||
@@ -330,3 +344,51 @@ func TestLibreOfficeProcess_Crash(t *testing.T) {
|
|||||||
t.Fatal("a crashed lok reports healthy")
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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))
|
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 != "":
|
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))
|
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):
|
case errors.Is(err, libreofficeapi.ErrSaveFailed), errors.Is(err, libreofficeapi.ErrCrashed):
|
||||||
sentinel = api.NewSentinelHttpError(http.StatusInternalServerError, fmt.Sprintf(unattributableFailureMessage, filename))
|
sentinel = api.NewSentinelHttpError(http.StatusInternalServerError, fmt.Sprintf(unattributableFailureMessage, filename))
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -1847,3 +1847,20 @@ Feature: /forms/chromium/convert/html
|
|||||||
Then the response header "Content-Type" should be "application/pdf"
|
Then the response header "Content-Type" should be "application/pdf"
|
||||||
Then there should be 1 PDF(s) in the response
|
Then there should be 1 PDF(s) in the response
|
||||||
Then the "foo.pdf" PDF should have 1 page(s)
|
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
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ Feature: /debug
|
|||||||
"chromium-ignore-certificate-errors": "false",
|
"chromium-ignore-certificate-errors": "false",
|
||||||
"chromium-idle-shutdown-timeout": "0s",
|
"chromium-idle-shutdown-timeout": "0s",
|
||||||
"chromium-max-concurrency": "6",
|
"chromium-max-concurrency": "6",
|
||||||
|
"chromium-max-memory": "",
|
||||||
"chromium-max-queue-size": "0",
|
"chromium-max-queue-size": "0",
|
||||||
"chromium-proxy-server": "",
|
"chromium-proxy-server": "",
|
||||||
"chromium-restart-after": "100",
|
"chromium-restart-after": "100",
|
||||||
@@ -81,6 +82,7 @@ Feature: /debug
|
|||||||
"libreoffice-auto-start": "false",
|
"libreoffice-auto-start": "false",
|
||||||
"libreoffice-disable-routes": "false",
|
"libreoffice-disable-routes": "false",
|
||||||
"libreoffice-idle-shutdown-timeout": "0s",
|
"libreoffice-idle-shutdown-timeout": "0s",
|
||||||
|
"libreoffice-max-memory": "",
|
||||||
"libreoffice-max-queue-size": "0",
|
"libreoffice-max-queue-size": "0",
|
||||||
"libreoffice-restart-after": "10",
|
"libreoffice-restart-after": "10",
|
||||||
"libreoffice-start-timeout": "20s",
|
"libreoffice-start-timeout": "20s",
|
||||||
@@ -180,6 +182,7 @@ Feature: /debug
|
|||||||
"chromium-idle-shutdown-timeout": "0s",
|
"chromium-idle-shutdown-timeout": "0s",
|
||||||
"chromium-max-queue-size": "0",
|
"chromium-max-queue-size": "0",
|
||||||
"chromium-max-concurrency": "6",
|
"chromium-max-concurrency": "6",
|
||||||
|
"chromium-max-memory": "",
|
||||||
"chromium-proxy-server": "",
|
"chromium-proxy-server": "",
|
||||||
"chromium-restart-after": "100",
|
"chromium-restart-after": "100",
|
||||||
"chromium-shared-browser-context": "false",
|
"chromium-shared-browser-context": "false",
|
||||||
@@ -189,6 +192,7 @@ Feature: /debug
|
|||||||
"libreoffice-auto-start": "false",
|
"libreoffice-auto-start": "false",
|
||||||
"libreoffice-disable-routes": "false",
|
"libreoffice-disable-routes": "false",
|
||||||
"libreoffice-idle-shutdown-timeout": "0s",
|
"libreoffice-idle-shutdown-timeout": "0s",
|
||||||
|
"libreoffice-max-memory": "",
|
||||||
"libreoffice-max-queue-size": "0",
|
"libreoffice-max-queue-size": "0",
|
||||||
"libreoffice-restart-after": "10",
|
"libreoffice-restart-after": "10",
|
||||||
"libreoffice-start-timeout": "20s",
|
"libreoffice-start-timeout": "20s",
|
||||||
|
|||||||
@@ -1237,3 +1237,21 @@ Feature: /forms/libreoffice/convert
|
|||||||
"""
|
"""
|
||||||
Invalid form data: form field 'stages' is disabled on this instance; send the request without it
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user