2014-06-12 16:15:24 +08:00
|
|
|
// +build linux
|
|
|
|
|
2015-01-27 20:54:19 +08:00
|
|
|
package libcontainer
|
2014-06-12 16:15:24 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2015-01-27 20:54:19 +08:00
|
|
|
"io/ioutil"
|
2014-06-12 16:15:24 +08:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2015-01-27 20:54:19 +08:00
|
|
|
const oomCgroupName = "memory"
|
2014-06-12 16:15:24 +08:00
|
|
|
|
2015-02-12 09:12:03 +08:00
|
|
|
// notifyOnOOM returns channel on which you can expect event about OOM,
|
2015-01-27 20:54:19 +08:00
|
|
|
// if process died without OOM this channel will be closed.
|
|
|
|
// s is current *libcontainer.State for container.
|
2015-02-12 09:12:03 +08:00
|
|
|
func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) {
|
2015-02-07 13:12:27 +08:00
|
|
|
dir := paths[oomCgroupName]
|
2015-01-27 20:54:19 +08:00
|
|
|
if dir == "" {
|
|
|
|
return nil, fmt.Errorf("There is no path for %q in state", oomCgroupName)
|
|
|
|
}
|
|
|
|
oomControl, err := os.Open(filepath.Join(dir, "memory.oom_control"))
|
2014-06-12 16:15:24 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0)
|
|
|
|
if syserr != 0 {
|
|
|
|
return nil, syserr
|
|
|
|
}
|
|
|
|
|
|
|
|
eventfd := os.NewFile(fd, "eventfd")
|
|
|
|
|
2015-01-27 20:54:19 +08:00
|
|
|
eventControlPath := filepath.Join(dir, "cgroup.event_control")
|
|
|
|
data := fmt.Sprintf("%d %d", eventfd.Fd(), oomControl.Fd())
|
|
|
|
if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil {
|
2014-06-12 16:15:24 +08:00
|
|
|
eventfd.Close()
|
|
|
|
oomControl.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ch := make(chan struct{})
|
|
|
|
go func() {
|
2014-06-25 03:08:03 +08:00
|
|
|
defer func() {
|
|
|
|
close(ch)
|
|
|
|
eventfd.Close()
|
|
|
|
oomControl.Close()
|
|
|
|
}()
|
|
|
|
buf := make([]byte, 8)
|
2014-06-12 16:15:24 +08:00
|
|
|
for {
|
|
|
|
if _, err := eventfd.Read(buf); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// When a cgroup is destroyed, an event is sent to eventfd.
|
|
|
|
// So if the control path is gone, return instead of notifying.
|
|
|
|
if _, err := os.Lstat(eventControlPath); os.IsNotExist(err) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ch <- struct{}{}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return ch, nil
|
|
|
|
}
|