docker_api_stats_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os/exec"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/docker/docker/pkg/integration/checker"
  12. "github.com/docker/docker/pkg/version"
  13. "github.com/docker/engine-api/types"
  14. "github.com/go-check/check"
  15. )
  16. var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
  17. func (s *DockerSuite) TestApiStatsNoStreamGetCpu(c *check.C) {
  18. testRequires(c, DaemonIsLinux)
  19. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello'; usleep 100000; done")
  20. id := strings.TrimSpace(out)
  21. c.Assert(waitRun(id), checker.IsNil)
  22. resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
  23. c.Assert(err, checker.IsNil)
  24. c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
  25. c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json")
  26. var v *types.Stats
  27. err = json.NewDecoder(body).Decode(&v)
  28. c.Assert(err, checker.IsNil)
  29. body.Close()
  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. c.Assert(cpuPercent, check.Not(checker.Equals), 0.0, check.Commentf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent))
  35. }
  36. func (s *DockerSuite) TestApiStatsStoppedContainerInGoroutines(c *check.C) {
  37. testRequires(c, DaemonIsLinux)
  38. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
  39. id := strings.TrimSpace(out)
  40. getGoRoutines := func() int {
  41. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/info"), nil, "")
  42. c.Assert(err, checker.IsNil)
  43. info := types.Info{}
  44. err = json.NewDecoder(body).Decode(&info)
  45. c.Assert(err, checker.IsNil)
  46. body.Close()
  47. return info.NGoroutines
  48. }
  49. // When the HTTP connection is closed, the number of goroutines should not increase.
  50. routines := getGoRoutines()
  51. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "")
  52. c.Assert(err, checker.IsNil)
  53. body.Close()
  54. t := time.After(30 * time.Second)
  55. for {
  56. select {
  57. case <-t:
  58. c.Assert(getGoRoutines(), checker.LessOrEqualThan, routines)
  59. return
  60. default:
  61. if n := getGoRoutines(); n <= routines {
  62. return
  63. }
  64. time.Sleep(200 * time.Millisecond)
  65. }
  66. }
  67. }
  68. func (s *DockerSuite) TestApiStatsNetworkStats(c *check.C) {
  69. testRequires(c, SameHostDaemon)
  70. testRequires(c, DaemonIsLinux)
  71. // Run container for 30 secs
  72. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  73. id := strings.TrimSpace(out)
  74. c.Assert(waitRun(id), checker.IsNil)
  75. // Retrieve the container address
  76. contIP := findContainerIP(c, id, "bridge")
  77. numPings := 10
  78. var preRxPackets uint64
  79. var preTxPackets uint64
  80. var postRxPackets uint64
  81. var postTxPackets uint64
  82. // Get the container networking stats before and after pinging the container
  83. nwStatsPre := getNetworkStats(c, id)
  84. for _, v := range nwStatsPre {
  85. preRxPackets += v.RxPackets
  86. preTxPackets += v.TxPackets
  87. }
  88. countParam := "-c"
  89. if runtime.GOOS == "windows" {
  90. countParam = "-n" // Ping count parameter is -n on Windows
  91. }
  92. pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).Output()
  93. pingouts := string(pingout[:])
  94. c.Assert(err, checker.IsNil)
  95. nwStatsPost := getNetworkStats(c, id)
  96. for _, v := range nwStatsPost {
  97. postRxPackets += v.RxPackets
  98. postTxPackets += v.TxPackets
  99. }
  100. // Verify the stats contain at least the expected number of packets (account for ARP)
  101. expRxPkts := 1 + preRxPackets + uint64(numPings)
  102. expTxPkts := 1 + preTxPackets + uint64(numPings)
  103. c.Assert(postTxPackets, checker.GreaterOrEqualThan, expTxPkts,
  104. check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts))
  105. c.Assert(postRxPackets, checker.GreaterOrEqualThan, expRxPkts,
  106. check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts))
  107. }
  108. func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
  109. testRequires(c, SameHostDaemon)
  110. testRequires(c, DaemonIsLinux)
  111. // Run container for 30 secs
  112. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  113. id := strings.TrimSpace(out)
  114. c.Assert(waitRun(id), checker.IsNil)
  115. for i := 17; i <= 21; i++ {
  116. apiVersion := fmt.Sprintf("v1.%d", i)
  117. for _, statsJSONBlob := range getVersionedStats(c, id, 3, apiVersion) {
  118. if version.Version(apiVersion).LessThan("v1.21") {
  119. c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true,
  120. check.Commentf("Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob))
  121. } else {
  122. c.Assert(jsonBlobHasGTE121NetworkStats(statsJSONBlob), checker.Equals, true,
  123. check.Commentf("Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob))
  124. }
  125. }
  126. }
  127. }
  128. func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
  129. var st *types.StatsJSON
  130. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
  131. c.Assert(err, checker.IsNil)
  132. err = json.NewDecoder(body).Decode(&st)
  133. c.Assert(err, checker.IsNil)
  134. body.Close()
  135. return st.Networks
  136. }
  137. // getVersionedNetworkStats returns a slice of numStats stats results for the
  138. // container with id id using an API call with version apiVersion. Since the
  139. // stats result type differs between API versions, we simply return
  140. // []map[string]interface{}.
  141. func getVersionedStats(c *check.C, id string, numStats int, apiVersion string) []map[string]interface{} {
  142. stats := make([]map[string]interface{}, numStats)
  143. requestPath := fmt.Sprintf("/%s/containers/%s/stats?stream=true", apiVersion, id)
  144. _, body, err := sockRequestRaw("GET", requestPath, nil, "")
  145. c.Assert(err, checker.IsNil)
  146. defer body.Close()
  147. statsDecoder := json.NewDecoder(body)
  148. for i := range stats {
  149. err = statsDecoder.Decode(&stats[i])
  150. c.Assert(err, checker.IsNil, check.Commentf("failed to decode %dth stat: %s", i, err))
  151. }
  152. return stats
  153. }
  154. func jsonBlobHasLTv121NetworkStats(blob map[string]interface{}) bool {
  155. networkStatsIntfc, ok := blob["network"]
  156. if !ok {
  157. return false
  158. }
  159. networkStats, ok := networkStatsIntfc.(map[string]interface{})
  160. if !ok {
  161. return false
  162. }
  163. for _, expectedKey := range expectedNetworkInterfaceStats {
  164. if _, ok := networkStats[expectedKey]; !ok {
  165. return false
  166. }
  167. }
  168. return true
  169. }
  170. func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
  171. networksStatsIntfc, ok := blob["networks"]
  172. if !ok {
  173. return false
  174. }
  175. networksStats, ok := networksStatsIntfc.(map[string]interface{})
  176. if !ok {
  177. return false
  178. }
  179. for _, networkInterfaceStatsIntfc := range networksStats {
  180. networkInterfaceStats, ok := networkInterfaceStatsIntfc.(map[string]interface{})
  181. if !ok {
  182. return false
  183. }
  184. for _, expectedKey := range expectedNetworkInterfaceStats {
  185. if _, ok := networkInterfaceStats[expectedKey]; !ok {
  186. return false
  187. }
  188. }
  189. }
  190. return true
  191. }
  192. func (s *DockerSuite) TestApiStatsContainerNotFound(c *check.C) {
  193. testRequires(c, DaemonIsLinux)
  194. status, _, err := sockRequest("GET", "/containers/nonexistent/stats", nil)
  195. c.Assert(err, checker.IsNil)
  196. c.Assert(status, checker.Equals, http.StatusNotFound)
  197. status, _, err = sockRequest("GET", "/containers/nonexistent/stats?stream=0", nil)
  198. c.Assert(err, checker.IsNil)
  199. c.Assert(status, checker.Equals, http.StatusNotFound)
  200. }