2017-03-10 00:07:35 +00:00
|
|
|
package reaper
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"os/exec"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/docker/containerd/utils"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Reap should be called when the process receives an SIGCHLD. Reap will reap
|
|
|
|
// all exited processes and close their wait channels
|
2017-03-10 00:11:57 +00:00
|
|
|
func Reap() ([]utils.Exit, error) {
|
2017-03-10 00:07:35 +00:00
|
|
|
exits, err := utils.Reap(false)
|
|
|
|
for _, e := range exits {
|
|
|
|
Default.mu.Lock()
|
|
|
|
c, ok := Default.cmds[e.Pid]
|
|
|
|
Default.mu.Unlock()
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// after we get an exit, call wait on the go process to make sure all
|
|
|
|
// pipes are closed and finalizers are run on the process
|
|
|
|
c.c.Wait()
|
|
|
|
c.exitCh <- e.Status
|
|
|
|
Default.mu.Lock()
|
|
|
|
delete(Default.cmds, e.Pid)
|
|
|
|
Default.mu.Unlock()
|
|
|
|
}
|
2017-03-10 00:11:57 +00:00
|
|
|
return exits, err
|
2017-03-10 00:07:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var Default = &Monitor{
|
|
|
|
cmds: make(map[int]*cmd),
|
|
|
|
}
|
|
|
|
|
|
|
|
type Monitor struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
cmds map[int]*cmd
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Monitor) Output(c *exec.Cmd) ([]byte, error) {
|
|
|
|
var b bytes.Buffer
|
|
|
|
c.Stdout = &b
|
|
|
|
if err := m.Run(c); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return b.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Monitor) CombinedOutput(c *exec.Cmd) ([]byte, error) {
|
|
|
|
var b bytes.Buffer
|
|
|
|
c.Stdout = &b
|
|
|
|
c.Stderr = &b
|
|
|
|
if err := m.Run(c); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return b.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start starts the command a registers the process with the reaper
|
|
|
|
func (m *Monitor) Start(c *exec.Cmd) error {
|
|
|
|
rc := &cmd{
|
|
|
|
c: c,
|
|
|
|
exitCh: make(chan int, 1),
|
|
|
|
}
|
|
|
|
m.mu.Lock()
|
|
|
|
// start the process
|
|
|
|
if err := rc.c.Start(); err != nil {
|
|
|
|
m.mu.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
m.cmds[rc.c.Process.Pid] = rc
|
|
|
|
m.mu.Unlock()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run runs and waits for the command to finish
|
|
|
|
func (m *Monitor) Run(c *exec.Cmd) error {
|
|
|
|
if err := m.Start(c); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err := m.Wait(c)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Monitor) Wait(c *exec.Cmd) (int, error) {
|
2017-03-10 00:38:27 +00:00
|
|
|
m.mu.Lock()
|
2017-03-10 00:07:35 +00:00
|
|
|
rc, ok := m.cmds[c.Process.Pid]
|
2017-03-10 00:38:27 +00:00
|
|
|
m.mu.Unlock()
|
2017-03-10 00:07:35 +00:00
|
|
|
if !ok {
|
|
|
|
return 255, fmt.Errorf("process does not exist")
|
|
|
|
}
|
|
|
|
return <-rc.exitCh, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type cmd struct {
|
|
|
|
c *exec.Cmd
|
|
|
|
exitCh chan int
|
|
|
|
}
|