Skip to content

Commit 0a2ce9c

Browse files
author
David Currie
committedNov 28, 2016
Initial version
1 parent bf3c994 commit 0a2ce9c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
 

‎Dockerfile

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
FROM scratch
2+
COPY cpu-usage /cpu-usage
3+
CMD ["/cpu-usage"]

‎usage.go

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"io/ioutil"
8+
"strings"
9+
"time"
10+
11+
"github.com/docker/docker/api/types"
12+
"github.com/docker/docker/client"
13+
)
14+
15+
func main() {
16+
cli, err := client.NewClient("unix:///var/run/docker.sock", "", nil, nil)
17+
if err != nil {
18+
panic(err)
19+
}
20+
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
21+
if err != nil {
22+
panic(err)
23+
}
24+
25+
for _, container := range containers {
26+
if strings.HasSuffix(container.Image, "cpu-usage") {
27+
continue
28+
}
29+
inspect, err := cli.ContainerInspect(context.Background(), container.ID)
30+
if err != nil {
31+
panic(err)
32+
}
33+
started, err := time.Parse(time.RFC3339Nano, inspect.State.StartedAt)
34+
if err != nil {
35+
panic(err)
36+
}
37+
resp, err := cli.ContainerStats(context.Background(), container.ID, false)
38+
if err != nil {
39+
panic(err)
40+
}
41+
defer resp.Body.Close()
42+
content, err := ioutil.ReadAll(resp.Body)
43+
if err != nil {
44+
panic(err)
45+
}
46+
var stats types.StatsJSON
47+
err = json.Unmarshal(content, &stats)
48+
if err != nil {
49+
panic(err)
50+
}
51+
usage := time.Duration(stats.Stats.CPUStats.CPUUsage.TotalUsage)*time.Nanosecond
52+
read := stats.Stats.Read
53+
elapsed := read.Sub(started)
54+
fmt.Printf("%s - CPU: %s Elapsed: %s\n", container.Names[0][1:], usage, elapsed)
55+
}
56+
}

0 commit comments

Comments
 (0)
Please sign in to comment.