Skip to content

Commit

Permalink
Merge pull request #115 from Zyqsempai/104-add-oom-notifications
Browse files Browse the repository at this point in the history
Added OOM notification for Memory controller
  • Loading branch information
crosbymichael authored Nov 15, 2019
2 parents 2bd4ae1 + d03d516 commit c4474e8
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions v2/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ import (
"path/filepath"
"strconv"
"strings"
"syscall"
"time"

"golang.org/x/sys/unix"

"github.com/containerd/cgroups/v2/stats"
"github.com/pkg/errors"
)
Expand All @@ -40,6 +43,14 @@ type cgValuer interface {
Values() []Value
}

type Event struct {
Low uint64
High uint64
Max uint64
OOM uint64
OOMKill uint64
}

// Resources for a cgroups v2 unified hierarchy
type Resources struct {
CPU *CPU
Expand Down Expand Up @@ -416,3 +427,54 @@ func (c *Manager) freeze(path string, state State) error {
time.Sleep(1 * time.Millisecond)
}
}

func (c *Manager) MemoryEventFD() (uintptr, error) {
fpath := filepath.Join(c.path, "memory.events")
fd, err := syscall.InotifyInit()
if err != nil {
return 0, errors.Errorf("Failed to create inotify fd")
}
defer syscall.Close(fd)
wd, err := syscall.InotifyAddWatch(fd, fpath, unix.IN_MODIFY)
if wd < 0 {
return 0, errors.Errorf("Failed to add inotify watch for %q", fpath)
}
defer syscall.InotifyRmWatch(fd, uint32(wd))

return uintptr(fd), nil
}

func (c *Manager) EventChan() (<-chan Event, <-chan error) {
ec := make(chan Event)
errCh := make(chan error)
go c.waitForEvents(ec, errCh)

return ec, nil
}

func (c *Manager) waitForEvents(ec chan<- Event, errCh chan<- error) {
fd, err := c.MemoryEventFD()
if err != nil {
errCh <- errors.Errorf("Failed to create memory event fd")
}
for {
buffer := make([]byte, syscall.SizeofInotifyEvent*10)
bytesRead, err := syscall.Read(int(fd), buffer)
if err != nil {
errCh <- err
}
var out map[string]interface{}
if bytesRead >= syscall.SizeofInotifyEvent {
if err := readStatsFile(c.path, "memory.events", out); err != nil {
e := Event{
High: out["high"].(uint64),
Low: out["low"].(uint64),
Max: out["max"].(uint64),
OOM: out["oom"].(uint64),
OOMKill: out["oom_kill"].(uint64),
}
ec <- e
}
}
}
}

0 comments on commit c4474e8

Please sign in to comment.