github.com/gondor/docker@v1.9.0-rc1/daemon/top_unix.go (about) 1 //+build !windows 2 3 package daemon 4 5 import ( 6 "os/exec" 7 "strconv" 8 "strings" 9 10 "github.com/docker/docker/api/types" 11 derr "github.com/docker/docker/errors" 12 ) 13 14 // ContainerTop lists the processes running inside of the given 15 // container by calling ps with the given args, or with the flags 16 // "-ef" if no args are given. An error is returned if the container 17 // is not found, or is not running, or if there are any problems 18 // running ps, or parsing the output. 19 func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) { 20 if psArgs == "" { 21 psArgs = "-ef" 22 } 23 24 container, err := daemon.Get(name) 25 if err != nil { 26 return nil, err 27 } 28 29 if !container.IsRunning() { 30 return nil, derr.ErrorCodeNotRunning.WithArgs(name) 31 } 32 33 pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID) 34 if err != nil { 35 return nil, err 36 } 37 38 output, err := exec.Command("ps", strings.Split(psArgs, " ")...).Output() 39 if err != nil { 40 return nil, derr.ErrorCodePSError.WithArgs(err) 41 } 42 43 procList := &types.ContainerProcessList{} 44 45 lines := strings.Split(string(output), "\n") 46 procList.Titles = strings.Fields(lines[0]) 47 48 pidIndex := -1 49 for i, name := range procList.Titles { 50 if name == "PID" { 51 pidIndex = i 52 } 53 } 54 if pidIndex == -1 { 55 return nil, derr.ErrorCodeNoPID 56 } 57 58 // loop through the output and extract the PID from each line 59 for _, line := range lines[1:] { 60 if len(line) == 0 { 61 continue 62 } 63 fields := strings.Fields(line) 64 p, err := strconv.Atoi(fields[pidIndex]) 65 if err != nil { 66 return nil, derr.ErrorCodeBadPID.WithArgs(fields[pidIndex], err) 67 } 68 69 for _, pid := range pids { 70 if pid == p { 71 // Make sure number of fields equals number of header titles 72 // merging "overhanging" fields 73 process := fields[:len(procList.Titles)-1] 74 process = append(process, strings.Join(fields[len(procList.Titles)-1:], " ")) 75 procList.Processes = append(procList.Processes, process) 76 } 77 } 78 } 79 container.logEvent("top") 80 return procList, nil 81 }