Repository navigation
Conversation
There was a problem hiding this comment.
Pull request overview
This PR optimizes the cgroup v2 OOM watcher in internal/oom to reduce steady-state allocation and parsing overhead in long-running containerd-shim-runc-v2 processes, especially on workloads that frequently update memory.events due to reclaim activity.
Changes:
- Reuse per-watcher inotify and
memory.eventsread buffers to avoid per-wakeup allocations. - Replace full
memory.eventsparsing with a focused parser that extracts only theoom_killcounter. - Add unit tests for the new
oom_killparser.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
internal/oom/watcher.go |
Reuses buffers and switches watcher logic to read only the oom_kill counter. |
internal/oom/utils.go |
Introduces a lightweight memory.events parser (readMemoryOOMKill) and supporting constants. |
internal/oom/utils_test.go |
Adds unit tests validating readMemoryOOMKill behavior. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
46c7ce0 to
f955b24
Compare
|
The only failing check is Vagrant integration (almalinux/8, cgroupfs, runc), which fails at the test-cri-integration step (the preceding test-integration step passes). This looks like an unrelated flake rather than something introduced by this PR:
Could a maintainer re-run the failed job? I don't have permission to re-run it on a fork PR. Happy to dig into the log if it reproduces. Thanks! |
| // updates on every low/high/max reclaim event, not only on OOM kills), | ||
| // so avoiding per-wakeup allocations keeps long-running shims with | ||
| // stable workloads from accumulating CPU and GC overhead. | ||
| // See https://github.com/containerd/containerd/issues/13558. |
There was a problem hiding this comment.
I don't think the issue you mentioned could wake it up multiple times because v1.29 doesn't enable like low/high setting on cgroups, if I understand it correctly.
| // TODO: We should export MemoryEventsStat function | ||
| out := make(map[string]uint64) | ||
| if err := readKVStatsFile(w.cgroupPath, "memory.events", out); err != nil { | ||
| oomKill, err := readMemoryOOMKill(w.cgroupPath, statsBuf) |
There was a problem hiding this comment.
I would like to keep it as it's right now and file change on cgroupv3 first and then update here.
| for !shouldExit { | ||
| buffer := make([]byte, unix.SizeofInotifyEvent*10) | ||
| bytesRead, err := w.eventFD.Read(buffer) | ||
| bytesRead, err := w.eventFD.Read(eventBuf) |
There was a problem hiding this comment.
before we reuse it, let's use clear(eventBuf) first.
| // line) on each wakeup, which otherwise accumulates measurable CPU and GC | ||
| // overhead over the lifetime of the shim. | ||
| // See https://github.com/containerd/containerd/issues/13558. | ||
| func readMemoryOOMKill(cgroupPath string, buf []byte) (uint64, error) { |
There was a problem hiding this comment.
I think we can go with buf bytes.Buffer here. There is method ReadFrom which will increase the length if original size is not good enough. After increasing it, we can reuse it in the follow-up.
func (w *watcher) start() {
...
var (
statsBuf bytes.Buffer
)
readMemoryOOMKill(cgroupPath string, buf *bytes.Buffer)
}
func readMemoryOOMKill(memoryEventsPath string, buf *bytes.Buffer) (uint64, error) {
buf.Reset()
f, err := os.Open(memoryEventsPath)
if err != nil {
return 0, err
}
defer f.Close()
if _, err := buf.ReadFrom(f); err != nil {
return 0, err
}
v, err := parseOOMKill(buf.Bytes())
if err != nil {
return 0, fmt.Errorf("error while parsing %s: %w", memoryEventsPath, err)
}
return v, nil
}| var ( | ||
| oomKills uint64 | ||
| shouldExit bool | ||
| eventBuf = make([]byte, unix.SizeofInotifyEvent*10) |
There was a problem hiding this comment.
we can go with eventBuf = [unix.SizeofInotifyEvent*10]byte which won't be escaped to heap.
|
Hi @KeyMoad Thanks for the patch. It's helpful. Please let us know if you still want to work on this. |
|
Hi @fuweid, Sure I would like to continue working on this. Sorry for the late response. |
|
@KeyMoad sure! Please update it when you have chance. Thanks! |
|
kindly ping @KeyMoad any update? |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.
Suppressed comments (2)
internal/oom/watcher.go:115
clear(eventBuf[:])runs on every wakeup and zeros the entire buffer even though onlybytesReadbytes are relevant. This adds avoidable work to a hot loop; consider removing theclear(...)and ensuring downstream parsing only examines theeventBuf[:bytesRead]slice.
eventBuf [unix.SizeofInotifyEvent * 10]byte
)
for !shouldExit {
clear(eventBuf[:])
bytesRead, err := w.eventFD.Read(eventBuf[:])
internal/oom/watcher.go:122
- When
errisos.ErrClosed, the code setsshouldExit = truebut still falls through and may processeventBufusing an invalid/partialbytesReadvalue from the failedRead. Add abreakorcontinueafter settingshouldExit = true(or return) to avoid processing after the FD is closed.
if err != nil {
if !errors.Is(err, os.ErrClosed) {
w.errCh <- err
return
}
shouldExit = true
} else if bytesRead < unix.SizeofInotifyEvent {
continue
}
44094c8 to
b466c67
Compare
fuweid
left a comment
There was a problem hiding this comment.
Could you please confirm this? probably we need benchmark testcase to confirm there is no extra allocations.
| shouldExit bool | ||
| eventBuf [unix.SizeofInotifyEvent * 10]byte | ||
| ) | ||
| for !shouldExit { |
There was a problem hiding this comment.
I revisit this part and found that go doesn't recreate it.
In amd64, I got this. I think the main reason is that we don't read content and just check bytes.
So, go compile uses stack memory for us.
➜ containerd git:(main) GOTOOLCHAIN=go1.26.6 go build \
-o /tmp/containerd-shim-runc-v2-base \
-gcflags='github.com/containerd/containerd/v2/internal/oom=-m=2' \
./cmd/containerd-shim-runc-v2 2>&1 |
ag 'watcher.go.*(escape|does not escape)'
...
internal/oom/watcher.go:112:18: make([]byte, 160) does not escape
...$ GOTOOLCHAIN=go1.26.6 go tool objdump \
-s 'github.com/containerd/containerd/v2/internal/oom\.\(\*watcher\)\.start\.func1$' \
/tmp/containerd-shim-runc-v2-base
...
watcher.go:112 0x987c18 488d5c2430 LEAQ 0x30(SP), BX
watcher.go:112 0x987c1d 440f113b MOVUPS X15, 0(BX)
watcher.go:112 0x987c21 440f117b10 MOVUPS X15, 0x10(BX)
watcher.go:112 0x987c26 440f117b20 MOVUPS X15, 0x20(BX)
watcher.go:112 0x987c2b 440f117b30 MOVUPS X15, 0x30(BX)
watcher.go:112 0x987c30 440f117b40 MOVUPS X15, 0x40(BX)
watcher.go:112 0x987c35 440f117b50 MOVUPS X15, 0x50(BX)
watcher.go:112 0x987c3a 440f117b60 MOVUPS X15, 0x60(BX)
watcher.go:112 0x987c3f 440f117b70 MOVUPS X15, 0x70(BX)
watcher.go:112 0x987c44 440f11bb80000000 MOVUPS X15, 0x80(BX)
watcher.go:112 0x987c4c 440f11bb90000000 MOVUPS X15, 0x90(BX)
watcher.go:113 0x987c54 440f11bc2438020000 MOVUPS X15, 0x238(SP)
We don't need to cleanup it as well.
So, I don't think we need to update this part.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (2)
internal/oom/watcher.go:113
- The watcher loop still allocates a new
map[string]uint64on every inotify wakeup (out := make(...)), which undermines the goal of reducing steady per-wakeup allocations/GC pressure. Consider moving the map allocation outside the loop andclear-ing it each iteration before callingreadKVStatsFile.
var (
oomKills uint64
shouldExit bool
eventBuf [unix.SizeofInotifyEvent * 10]byte
)
internal/oom/watcher_test.go:122
- This benchmark currently includes one-time map growth allocations (and
readKVStatsFilealso allocates viabufio.Scanner/strings.Fields), so the comment stating it "does not allocate" is misleading and the measurement is noisy. Pre-size/warm the map beforeResetTimer, and adjust the comment to reflect that it measures allocations rather than asserting zero allocs.
// BenchmarkReadKVStatsFile confirms that reading the oom_kill counter from
// memory.events via readKVStatsFile does not allocate on the reused-map path.
// Run with: go test -bench=BenchmarkReadKVStatsFile -benchmem ./internal/oom/
func BenchmarkReadKVStatsFile(b *testing.B) {
dir := b.TempDir()
The cgroup v2 OOM watcher arms an inotify IN_MODIFY watch on a container's memory.events file. The kernel rewrites/notifies that file on every change to any of its counters (low/high/max/oom/oom_kill/ oom_group_kill), not only on OOM kills. For workloads running near their memory limit the low/high/max reclaim counters churn continuously, so the watcher goroutine is woken very frequently. On every wakeup the watcher allocated a fresh inotify read buffer and a new map[string]uint64, then opened and fully parsed memory.events with a bufio.Scanner + strings.Fields, only to read the single oom_kill counter. On long-running nodes with stable workloads this steady allocation churn accumulates measurable CPU and GC overhead in each shim, contributing to the slowly growing shim CPU usage reported in containerd#13558. Hoist both buffers out of the loop so they are reused for the lifetime of the watcher, and read only the oom_kill counter via a small allocation-light parser instead of building a map and re-parsing every line. No behavior change: oom_kill detection and cgroup-deletion handling are preserved. Adds a unit test for the new parser. Fixes: containerd#13558 Signed-off-by: KeyMoad <[email protected]>
The previous change read memory.events into a fixed-size reusable buffer. If the file were ever larger than that buffer (e.g. a future kernel adds counters, or very large values), the oom_kill line could fall beyond what was read and an OOM event would be silently missed. Keep the allocation-free fast path for the common case where the file fits in the buffer, but when io.ReadFull fills the buffer completely (meaning the file may be larger) fall back to reading the remainder so the oom_kill counter is never truncated away. A genuinely absent oom_kill line still reports 0, matching the previous Scanner-based behavior. Adds a regression test that parses a normal file through an undersized buffer to exercise the fallback. Addresses review feedback on containerd#13558. Signed-off-by: KeyMoad <[email protected]>
Keep readKVStatsFile for memory.events parsing until a helper is exported from cgroups/v3, and reuse a stack-allocated inotify buffer cleared before each read so the hot path avoids heap allocations. Signed-off-by: KeyMoad <[email protected]>
Go zero-initializes the stack-allocated eventBuf array so clear is redundant; remove it. Add a continue after setting shouldExit to avoid calling readKVStatsFile on a closed fd. Add BenchmarkReadKVStatsFile to confirm per-wakeup allocation behaviour of the reused-map path. Signed-off-by: KeyMoad <[email protected]>
0acfd89 to
2020b34
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (1)
internal/oom/watcher.go:114
- The watcher loop still allocates
out := make(map[string]uint64)on every inotify wakeup, which defeats the stated goal of avoiding per-wakeup allocations (and makes the new benchmark’s “reused-map path” not reflect the watcher’s behavior). Allocate the map once for the lifetime of the watcher andclear(out)each iteration before reuse.
var (
oomKills uint64
shouldExit bool
eventBuf [unix.SizeofInotifyEvent * 10]byte
)
|
Hey @fuweid, thanks for the detailed investigation. Updated in the latest commit:
|
|
Hi @KeyMoad The original code (main branch) doesn't escape to heap. It already uses stack memory for it. We don't need such change if you have chance to check out my last comment. Thanks |
What this does
Reduces continuous CPU/GC overhead of the per-container cgroup v2 OOM
watcher (
internal/oom), which is the only steadily-active, workload-proportional code path in
containerd-shim-runc-v2on a static workload.Background (#13558)
The watcher arms an inotify
IN_MODIFYwatch onmemory.events. The kernelnotifies that file on every counter change (
low/high/max/oom/oom_kill/oom_group_kill), not just OOM kills. Containers running neartheir memory limit churn
high/maxconstantly (and increasingly as pagecache fills toward the limit over the node's uptime), waking the watcher
goroutine very frequently.
Previously each wakeup allocated a new read buffer and a
map[string]uint64, then opened and fully parsedmemory.eventswithbufio.Scanner/strings.Fieldsjust to readoom_kill. Across ~50–60shims this steady allocation churn is avoidable CPU and GC pressure that
accumulates on long-running nodes.
Change
memory.eventsread buffers once per watcher andreuse them.
oom_killcounter with a small allocation-light parser.identical; covered by the existing
TestWatcherplus a new parser unit test.