96123a1f |
package main
import (
"encoding/json"
"fmt" |
66be81b1 |
"net/http" |
8b40e44c |
"os/exec" |
c1b52448 |
"runtime" |
8b40e44c |
"strconv" |
4fde1cb6 |
"strings" |
1cbf5a54 |
"time" |
4fde1cb6 |
|
710817a7 |
"github.com/docker/docker/pkg/integration/checker" |
8ceded6d |
"github.com/docker/docker/pkg/version" |
907407d0 |
"github.com/docker/engine-api/types" |
96123a1f |
"github.com/go-check/check"
)
|
8ceded6d |
var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
|
66be81b1 |
func (s *DockerSuite) TestApiStatsNoStreamGetCpu(c *check.C) { |
f9a3558a |
testRequires(c, DaemonIsLinux) |
855a056a |
out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello'; usleep 100000; done") |
96123a1f |
id := strings.TrimSpace(out) |
710817a7 |
c.Assert(waitRun(id), checker.IsNil) |
4fde1cb6 |
|
855a056a |
resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") |
710817a7 |
c.Assert(err, checker.IsNil)
c.Assert(resp.ContentLength, checker.GreaterThan, int64(0), check.Commentf("should not use chunked encoding"))
c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json") |
4fde1cb6 |
|
96123a1f |
var v *types.Stats |
4fde1cb6 |
err = json.NewDecoder(body).Decode(&v) |
710817a7 |
c.Assert(err, checker.IsNil) |
18faf6f9 |
body.Close() |
96123a1f |
|
4fde1cb6 |
var cpuPercent = 0.0 |
3d6617ff |
cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage)
systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage)
cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0 |
710817a7 |
c.Assert(cpuPercent, check.Not(checker.Equals), 0.0, check.Commentf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent)) |
96123a1f |
} |
1cbf5a54 |
|
66be81b1 |
func (s *DockerSuite) TestApiStatsStoppedContainerInGoroutines(c *check.C) { |
f9a3558a |
testRequires(c, DaemonIsLinux) |
1cbf5a54 |
out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
id := strings.TrimSpace(out)
getGoRoutines := func() int {
_, body, err := sockRequestRaw("GET", fmt.Sprintf("/info"), nil, "") |
710817a7 |
c.Assert(err, checker.IsNil) |
1cbf5a54 |
info := types.Info{}
err = json.NewDecoder(body).Decode(&info) |
710817a7 |
c.Assert(err, checker.IsNil) |
1cbf5a54 |
body.Close()
return info.NGoroutines
}
// When the HTTP connection is closed, the number of goroutines should not increase.
routines := getGoRoutines()
_, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "") |
710817a7 |
c.Assert(err, checker.IsNil) |
1cbf5a54 |
body.Close()
t := time.After(30 * time.Second)
for {
select {
case <-t: |
710817a7 |
c.Assert(getGoRoutines(), checker.LessOrEqualThan, routines) |
1cbf5a54 |
return
default:
if n := getGoRoutines(); n <= routines {
return
}
time.Sleep(200 * time.Millisecond)
}
}
} |
8b40e44c |
|
66be81b1 |
func (s *DockerSuite) TestApiStatsNetworkStats(c *check.C) { |
c1b52448 |
testRequires(c, SameHostDaemon) |
f9a3558a |
testRequires(c, DaemonIsLinux) |
8b40e44c |
// Run container for 30 secs
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
id := strings.TrimSpace(out) |
710817a7 |
c.Assert(waitRun(id), checker.IsNil) |
8b40e44c |
// Retrieve the container address |
1b9a08e7 |
contIP := findContainerIP(c, id, "bridge") |
8b40e44c |
numPings := 10
|
d3379946 |
var preRxPackets uint64
var preTxPackets uint64
var postRxPackets uint64
var postTxPackets uint64
|
8b40e44c |
// Get the container networking stats before and after pinging the container
nwStatsPre := getNetworkStats(c, id) |
d3379946 |
for _, v := range nwStatsPre {
preRxPackets += v.RxPackets
preTxPackets += v.TxPackets
}
|
c1b52448 |
countParam := "-c"
if runtime.GOOS == "windows" {
countParam = "-n" // Ping count parameter is -n on Windows
}
pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).Output()
pingouts := string(pingout[:]) |
710817a7 |
c.Assert(err, checker.IsNil) |
8b40e44c |
nwStatsPost := getNetworkStats(c, id) |
d3379946 |
for _, v := range nwStatsPost {
postRxPackets += v.RxPackets
postTxPackets += v.TxPackets
} |
8b40e44c |
// Verify the stats contain at least the expected number of packets (account for ARP) |
d3379946 |
expRxPkts := 1 + preRxPackets + uint64(numPings)
expTxPkts := 1 + preTxPackets + uint64(numPings) |
710817a7 |
c.Assert(postTxPackets, checker.GreaterOrEqualThan, expTxPkts, |
d3379946 |
check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts)) |
710817a7 |
c.Assert(postRxPackets, checker.GreaterOrEqualThan, expRxPkts, |
d3379946 |
check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts)) |
8b40e44c |
}
|
8ceded6d |
func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
testRequires(c, SameHostDaemon)
testRequires(c, DaemonIsLinux)
// Run container for 30 secs
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
id := strings.TrimSpace(out)
c.Assert(waitRun(id), checker.IsNil)
for i := 17; i <= 21; i++ {
apiVersion := fmt.Sprintf("v1.%d", i)
for _, statsJSONBlob := range getVersionedStats(c, id, 3, apiVersion) {
if version.Version(apiVersion).LessThan("v1.21") {
c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true,
check.Commentf("Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob))
} else {
c.Assert(jsonBlobHasGTE121NetworkStats(statsJSONBlob), checker.Equals, true,
check.Commentf("Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob))
}
}
}
}
|
d3379946 |
func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
var st *types.StatsJSON |
8b40e44c |
_, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") |
710817a7 |
c.Assert(err, checker.IsNil) |
8b40e44c |
err = json.NewDecoder(body).Decode(&st) |
710817a7 |
c.Assert(err, checker.IsNil) |
18faf6f9 |
body.Close() |
8b40e44c |
|
d3379946 |
return st.Networks |
8b40e44c |
} |
66be81b1 |
|
8ceded6d |
// getVersionedNetworkStats returns a slice of numStats stats results for the
// container with id id using an API call with version apiVersion. Since the
// stats result type differs between API versions, we simply return
// []map[string]interface{}.
func getVersionedStats(c *check.C, id string, numStats int, apiVersion string) []map[string]interface{} {
stats := make([]map[string]interface{}, numStats)
requestPath := fmt.Sprintf("/%s/containers/%s/stats?stream=true", apiVersion, id)
_, body, err := sockRequestRaw("GET", requestPath, nil, "")
c.Assert(err, checker.IsNil)
defer body.Close()
statsDecoder := json.NewDecoder(body)
for i := range stats {
err = statsDecoder.Decode(&stats[i])
c.Assert(err, checker.IsNil, check.Commentf("failed to decode %dth stat: %s", i, err))
}
return stats
}
func jsonBlobHasLTv121NetworkStats(blob map[string]interface{}) bool {
networkStatsIntfc, ok := blob["network"]
if !ok {
return false
}
networkStats, ok := networkStatsIntfc.(map[string]interface{})
if !ok {
return false
}
for _, expectedKey := range expectedNetworkInterfaceStats {
if _, ok := networkStats[expectedKey]; !ok {
return false
}
}
return true
}
func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
networksStatsIntfc, ok := blob["networks"]
if !ok {
return false
}
networksStats, ok := networksStatsIntfc.(map[string]interface{})
if !ok {
return false
}
for _, networkInterfaceStatsIntfc := range networksStats {
networkInterfaceStats, ok := networkInterfaceStatsIntfc.(map[string]interface{})
if !ok {
return false
}
for _, expectedKey := range expectedNetworkInterfaceStats {
if _, ok := networkInterfaceStats[expectedKey]; !ok {
return false
}
}
}
return true
}
|
66be81b1 |
func (s *DockerSuite) TestApiStatsContainerNotFound(c *check.C) {
testRequires(c, DaemonIsLinux)
status, _, err := sockRequest("GET", "/containers/nonexistent/stats", nil) |
710817a7 |
c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNotFound) |
66be81b1 |
status, _, err = sockRequest("GET", "/containers/nonexistent/stats?stream=0", nil) |
710817a7 |
c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNotFound) |
66be81b1 |
} |