github.com/ld86/docker@v1.7.1-rc3/integration-cli/docker_api_stats_test.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os/exec" 7 "strconv" 8 "strings" 9 10 "github.com/docker/docker/api/types" 11 "github.com/go-check/check" 12 ) 13 14 func (s *DockerSuite) TestCliStatsNoStreamGetCpu(c *check.C) { 15 out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello'; usleep 100000; done") 16 17 id := strings.TrimSpace(out) 18 err := waitRun(id) 19 c.Assert(err, check.IsNil) 20 21 resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") 22 c.Assert(err, check.IsNil) 23 c.Assert(resp.ContentLength > 0, check.Equals, true, check.Commentf("should not use chunked encoding")) 24 c.Assert(resp.Header.Get("Content-Type"), check.Equals, "application/json") 25 26 var v *types.Stats 27 err = json.NewDecoder(body).Decode(&v) 28 c.Assert(err, check.IsNil) 29 30 var cpuPercent = 0.0 31 cpuDelta := float64(v.CpuStats.CpuUsage.TotalUsage - v.PreCpuStats.CpuUsage.TotalUsage) 32 systemDelta := float64(v.CpuStats.SystemUsage - v.PreCpuStats.SystemUsage) 33 cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CpuStats.CpuUsage.PercpuUsage)) * 100.0 34 if cpuPercent == 0 { 35 c.Fatalf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent) 36 } 37 } 38 39 func (s *DockerSuite) TestApiNetworkStats(c *check.C) { 40 // Run container for 30 secs 41 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 42 id := strings.TrimSpace(out) 43 err := waitRun(id) 44 c.Assert(err, check.IsNil) 45 46 // Retrieve the container address 47 contIP := findContainerIP(c, id) 48 numPings := 10 49 50 // Get the container networking stats before and after pinging the container 51 nwStatsPre := getNetworkStats(c, id) 52 _, err = exec.Command("ping", contIP, "-c", strconv.Itoa(numPings)).Output() 53 c.Assert(err, check.IsNil) 54 nwStatsPost := getNetworkStats(c, id) 55 56 // Verify the stats contain at least the expected number of packets (account for ARP) 57 expRxPkts := 1 + nwStatsPre.RxPackets + uint64(numPings) 58 expTxPkts := 1 + nwStatsPre.TxPackets + uint64(numPings) 59 c.Assert(nwStatsPost.TxPackets >= expTxPkts, check.Equals, true, 60 check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d", expTxPkts, nwStatsPost.TxPackets)) 61 c.Assert(nwStatsPost.RxPackets >= expRxPkts, check.Equals, true, 62 check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d", expRxPkts, nwStatsPost.RxPackets)) 63 } 64 65 func getNetworkStats(c *check.C, id string) types.Network { 66 var st *types.Stats 67 68 _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") 69 c.Assert(err, check.IsNil) 70 71 err = json.NewDecoder(body).Decode(&st) 72 c.Assert(err, check.IsNil) 73 74 return st.Network 75 }