[docker]linux: add CgroupDockerStat (#189)

pull/192/head
Shirou WAKAYAMA 9 years ago
parent f8c7af5565
commit 97e1d05084

@ -39,3 +39,11 @@ type CgroupMemStat struct {
MemLimitInBytes uint64 `json:"memoryLimitInBbytes"`
MemFailCnt uint64 `json:"memoryFailcnt"`
}
type CgroupDockerStat struct {
ContainerID string `json:"containerID"`
Name string `json:"name"`
Image string `json:"image"`
Status string `json:"status"`
Running bool `json:"running"`
}

@ -15,6 +15,48 @@ import (
"github.com/shirou/gopsutil/internal/common"
)
// GetDockerStat returns a list of Docker basic stats.
// This requires certain permission.
func GetDockerStat() ([]CgroupDockerStat, error) {
path, err := exec.LookPath("docker")
if err != nil {
return nil, ErrDockerNotAvailable
}
out, err := exec.Command(path, "ps", "-a", "--no-trunc", "--format", "{{.ID}}|{{.Image}}|{{.Names}}|{{.Status}}").Output()
if err != nil {
return []CgroupDockerStat{}, err
}
lines := strings.Split(string(out), "\n")
ret := make([]CgroupDockerStat, 0, len(lines))
for _, l := range lines {
if l == "" {
continue
}
cols := strings.Split(l, "|")
if len(cols) != 4 {
continue
}
names := strings.Split(cols[2], ",")
stat := CgroupDockerStat{
ContainerID: cols[0],
Name: names[0],
Image: cols[1],
Status: cols[3],
Running: strings.Contains(cols[3], "Up"),
}
ret = append(ret, stat)
}
return ret, nil
}
func (c CgroupDockerStat) String() string {
s, _ := json.Marshal(c)
return string(s)
}
// GetDockerIDList returnes a list of DockerID.
// This requires certain permission.
func GetDockerIDList() ([]string, error) {

@ -15,6 +15,30 @@ func TestGetDockerIDList(t *testing.T) {
*/
}
func TestGetDockerStat(t *testing.T) {
// If there is not docker environment, this test always fail.
// not tested here
/*
ret, err := GetDockerStat()
if err != nil {
t.Errorf("error %v", err)
}
if len(ret) == 0 {
t.Errorf("ret is empty")
}
empty := CgroupDockerStat{}
for _, v := range ret {
if empty == v {
t.Errorf("empty CgroupDockerStat")
}
if v.ContainerID == "" {
t.Errorf("Could not get container id")
}
}
*/
}
func TestCgroupCPU(t *testing.T) {
v, _ := GetDockerIDList()
for _, id := range v {

@ -9,6 +9,12 @@ import (
"github.com/shirou/gopsutil/internal/common"
)
// GetDockerStat returns a list of Docker basic stats.
// This requires certain permission.
func GetDockerStat() ([]CgroupDockerStat, error) {
return nil, ErrDockerNotAvailable
}
// GetDockerIDList returnes a list of DockerID.
// This requires certain permission.
func GetDockerIDList() ([]string, error) {

Loading…
Cancel
Save