Repository navigation
shim: send event to a queue to reduce lock contention - #13653
ningmingxiao wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR aims to prevent shim exit events from being lost under load by decoupling reaper event consumption from the heavier per-exit handling logic (i.e., drain reaper.Default.Subscribe() quickly and process exits asynchronously).
Changes:
- Introduces a mutex/cond-backed queue (
safeList) to buffer reaper exit events. - Splits exit handling into a fast producer loop (draining
s.ec) and a consumer goroutine (processing queued exits). - Adds a package-level
eventQueueused byprocessExits().
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
de1780b to
9882c05
Compare
9882c05 to
c9468e3
Compare
c9468e3 to
037857f
Compare
|
Hi @ningmingxiao, thanks for working on this!
|
|
I'm not sure ,this is very likely the reason. |
|
ping @samuelkarp @mikebrow can you take a look? |
037857f to
53c353b
Compare
53c353b to
6d5feef
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (1)
cmd/containerd-shim-runc-v2/task/service.go:696
processExitsnow starts a long-lived consumer goroutine that blocks indequeue()and never observess.shutdown.Done(). AfterShutdown()the shim will continue to enqueue/dequeue and takelifecycleMueven thoughsend()drops events once shutdown is triggered, which adds unnecessary work and makes shutdown behavior harder to reason about. Consider wiring the queue/consumer tos.shutdown.Done()(and optionally unsubscribing fromreaper.Default) so both goroutines can exit promptly on shutdown.
func (s *service) processExits() {
go func() {
for {
event := s.dequeue()
if e, ok := event.(runcC.Exit); ok {
// While unlikely, it is not impossible for a container process to exit
6d5feef to
5926e34
Compare
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.
Comments suppressed due to low confidence (3)
cmd/containerd-shim-runc-v2/task/service.go:696
- The exit-processing goroutine runs
for { e := s.dequeue() }anddequeue()blocks oncond.Wait()with no shutdown/close path. Ifs.ecis closed (or the shim is shutting down) and the queue is empty, this goroutine will block forever, leaking and potentially holding references toservicestate longer than needed. Consider adding a close mechanism toeventQueue(e.g.,closedflag +Broadcast) and makeprocessExitsstop the consumer when<-s.shutdown.Done()fires and/or afters.ecis closed and the queue is drained.
go func() {
for {
e := s.dequeue()
// While unlikely, it is not impossible for a container process to exit
// and have its PID be recycled for a new container process before we
cmd/containerd-shim-runc-v2/task/service.go:672
eventQueue.bufis an unbounded slice that only ever grows viaappend. Under sustained exit rates (e.g., many short-lived execs) if handling is slower than enqueueing, memory usage can grow without bound; additionally, usings.buf = s.buf[1:]retains the peak backing array capacity even after the queue drains. Consider a ring-buffer implementation, or periodically resetting/shrinking the buffer when it becomes empty to avoid retaining a large backing array indefinitely.
func (s *eventQueue) enqueue(e runcC.Exit) {
s.qmu.Lock()
defer s.qmu.Unlock()
s.buf = append(s.buf, e)
s.cond.Signal()
}
cmd/containerd-shim-runc-v2/task/service.go:735
- Grammar: "prevent event to be dropped" reads awkwardly and is easy to misread. Suggest "prevent events from being dropped".
// send events to a queue to prevent event to be dropped because of timeout.
s.enqueue(e)
5926e34 to
f4900e4
Compare
f4900e4 to
e0e3bdc
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (2)
cmd/containerd-shim-runc-v2/task/service.go:699
- The dequeue/processing goroutine has no termination path. After shutdown (or if the reaper subscription is ever unsubscribed/closed), it can block forever in dequeue() and leak a goroutine, potentially continuing to call handleInitExit/handleProcessExit after shutdown has begun.
// While unlikely, it is not impossible for a container process to exit
// and have its PID be recycled for a new container process before we
// have a chance to process the first exit. As we have no way to tell
// for sure which of the processes the exit event corresponds to (until
// pidfd support is implemented) there is no way for us to handle the
cmd/containerd-shim-runc-v2/task/service.go:738
- Grammar: “prevent event to be dropped” is ungrammatical; consider rephrasing for clarity.
}
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.
Comments suppressed due to low confidence (2)
cmd/containerd-shim-runc-v2/task/service.go:682
- dequeue() pops from the front by reslicing (s.buf = s.buf[1:]). After a large burst drains, the slice can still keep the old backing array alive (even when len==0), retaining memory unnecessarily. Consider nil-ing the slice when it becomes empty to allow GC to reclaim the backing array sooner.
event := s.buf[0]
s.buf = s.buf[1:]
return event
cmd/containerd-shim-runc-v2/task/service.go:734
- Grammar in this comment is a bit unclear; tightening it will make the rationale easier to understand for future readers.
// send events to a queue to prevent event to be dropped because of timeout.
e0e3bdc to
95e7768
Compare
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.
Comments suppressed due to low confidence (2)
cmd/containerd-shim-runc-v2/task/service.go:694
processExitsstarts a consumer goroutine that loops forever and blocks indequeue()/cond.Wait(). There is no shutdown/close path to unblock the wait, so the goroutine can leak and keep running afterShutdown()(or after theecsubscription stops). Consider adding a close/cancel mechanism toeventQueue(e.g.,closedflag +Broadcast()), havedequeue()return(exit, ok)and exit the consumer loop when closed, and stop enqueueing when<-s.shutdown.Done()fires.
go func() {
for {
e := s.dequeue()
cmd/containerd-shim-runc-v2/task/service.go:665
eventQueue.bufis an unbounded slice, so if exit processing is delayed (e.g.,lifecycleMucontention) the shim can accumulate an arbitrarily large number of exit events and potentially run out of memory. If dropping is unacceptable, consider adding backpressure (bounded queue + blocking enqueue), configurability, and/or logging/metrics so pathological growth is observable and controllable.
type eventQueue struct {
qmu sync.Mutex
cond *sync.Cond
buf []runcC.Exit
}
cpuguy83
left a comment
There was a problem hiding this comment.
This doesn't seem like a correct change.
The channel in reap is a done notification, its not dropping the exit its just no longer waiting for the event to be delivered.
The delivery still happens, though.
|
yes you are right the goroutine will exited until send event sucessfully but the disadvantage is that we can't keep the event in order, how about delete the goroutine and send events synchronously(send event to a queue at producer or consumer side ) but waitpid may can't keep the event in right order after reviewing some references @cpuguy83 |
|
I'm not sure of the decision that brought us the current implementation. Probably worthwhile to dig into the history here. I would say doing the whole thing synchronously would be the way to go to give the proper back pressure on a busy system. |
Signed-off-by: ningmingxiao <[email protected]>
95e7768 to
9e514d5
Compare
| s.handleProcessExit(e, cp.Container, cp.Process) | ||
| for _, cp := range cps { | ||
| if ip, ok := cp.Process.(*process.Init); ok { | ||
| s.handleInitExit(e, cp.Container, ip) |
There was a problem hiding this comment.
Did you consider just putting
if runc.ShouldKillAllOnExit(s.context, c.Bundle) {
if err := p.KillAll(s.context); err != nil {
log.G(s.context).WithError(err).WithField("id", p.ID()).
Error("failed to kill init's children")
}
}
in a goroutine in s.handleInitExit()? I think that would make the producer and consumer async. Then, we wouldn't need to add the queue to this part of the code?
There was a problem hiding this comment.
docker need to keep these events in order and main process exited in container should be send at last @adamwathieu
|
It depends on how large of a change you want to make this PR (a band-aid fix for just |
@dmcgowan @fuweid @mxpv can you take a look.
fix #12678
because notify will stop wait notify if consumer use more than 1s (events will not be droped)
I create a queue to add this event into it it will make consumer consume event quickly
It's easy to reproduce it add some sleep here (simulate high-load scenarios because sometimes wait lifecycleMu lock may quite a while)
reproduce
crictl run --no-pull container.json pod.json
66abdf4d13
go run main.go
cat main.go
container is still running even main process is exited (it will keep runing in long time and It will eventually work normally)
@evgfitil