docker_api_stats_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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/engine-api/types"
  13. "github.com/docker/engine-api/types/versions"
  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. out, _ := runSleepingContainer(c)
  72. id := strings.TrimSpace(out)
  73. c.Assert(waitRun(id), checker.IsNil)
  74. // Retrieve the container address
  75. contIP := findContainerIP(c, id, "bridge")
  76. numPings := 4
  77. var preRxPackets uint64
  78. var preTxPackets uint64
  79. var postRxPackets uint64
  80. var postTxPackets uint64
  81. // Get the container networking stats before and after pinging the container
  82. nwStatsPre := getNetworkStats(c, id)
  83. for _, v := range nwStatsPre {
  84. preRxPackets += v.RxPackets
  85. preTxPackets += v.TxPackets
  86. }
  87. countParam := "-c"
  88. if runtime.GOOS == "windows" {
  89. countParam = "-n" // Ping count parameter is -n on Windows
  90. }
  91. pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).CombinedOutput()
  92. if err != nil && runtime.GOOS == "linux" {
  93. // If it fails then try a work-around, but just for linux.
  94. // If this fails too then go back to the old error for reporting.
  95. //
  96. // The ping will sometimes fail due to an apparmor issue where it
  97. // denies access to the libc.so.6 shared library - running it
  98. // via /lib64/ld-linux-x86-64.so.2 seems to work around it.
  99. pingout2, err2 := exec.Command("/lib64/ld-linux-x86-64.so.2", "/bin/ping", contIP, "-c", strconv.Itoa(numPings)).CombinedOutput()
  100. if err2 == nil {
  101. pingout = pingout2
  102. err = err2
  103. }
  104. }
  105. c.Assert(err, checker.IsNil)
  106. pingouts := string(pingout[:])
  107. nwStatsPost := getNetworkStats(c, id)
  108. for _, v := range nwStatsPost {
  109. postRxPackets += v.RxPackets
  110. postTxPackets += v.TxPackets
  111. }
  112. // Verify the stats contain at least the expected number of packets (account for ARP)
  113. expRxPkts := 1 + preRxPackets + uint64(numPings)
  114. expTxPkts := 1 + preTxPackets + uint64(numPings)
  115. c.Assert(postTxPackets, checker.GreaterOrEqualThan, expTxPkts,
  116. check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts))
  117. c.Assert(postRxPackets, checker.GreaterOrEqualThan, expRxPkts,
  118. check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts))
  119. }
  120. func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
  121. testRequires(c, SameHostDaemon)
  122. testRequires(c, DaemonIsLinux)
  123. out, _ := runSleepingContainer(c)
  124. id := strings.TrimSpace(out)
  125. c.Assert(waitRun(id), checker.IsNil)
  126. for i := 17; i <= 21; i++ {
  127. apiVersion := fmt.Sprintf("v1.%d", i)
  128. statsJSONBlob := getVersionedStats(c, id, apiVersion)
  129. if versions.LessThan(apiVersion, "v1.21") {
  130. c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true,
  131. check.Commentf("Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob))
  132. } else {
  133. c.Assert(jsonBlobHasGTE121NetworkStats(statsJSONBlob), checker.Equals, true,
  134. check.Commentf("Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob))
  135. }
  136. }
  137. }
  138. func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
  139. var st *types.StatsJSON
  140. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
  141. c.Assert(err, checker.IsNil)
  142. err = json.NewDecoder(body).Decode(&st)
  143. c.Assert(err, checker.IsNil)
  144. body.Close()
  145. return st.Networks
  146. }
  147. // getVersionedStats returns stats result for the
  148. // container with id using an API call with version apiVersion. Since the
  149. // stats result type differs between API versions, we simply return
  150. // map[string]interface{}.
  151. func getVersionedStats(c *check.C, id string, apiVersion string) map[string]interface{} {
  152. stats := make(map[string]interface{})
  153. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/%s/containers/%s/stats?stream=false", apiVersion, id), nil, "")
  154. c.Assert(err, checker.IsNil)
  155. defer body.Close()
  156. err = json.NewDecoder(body).Decode(&stats)
  157. c.Assert(err, checker.IsNil, check.Commentf("failed to decode stat: %s", err))
  158. return stats
  159. }
  160. func jsonBlobHasLTv121NetworkStats(blob map[string]interface{}) bool {
  161. networkStatsIntfc, ok := blob["network"]
  162. if !ok {
  163. return false
  164. }
  165. networkStats, ok := networkStatsIntfc.(map[string]interface{})
  166. if !ok {
  167. return false
  168. }
  169. for _, expectedKey := range expectedNetworkInterfaceStats {
  170. if _, ok := networkStats[expectedKey]; !ok {
  171. return false
  172. }
  173. }
  174. return true
  175. }
  176. func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
  177. networksStatsIntfc, ok := blob["networks"]
  178. if !ok {
  179. return false
  180. }
  181. networksStats, ok := networksStatsIntfc.(map[string]interface{})
  182. if !ok {
  183. return false
  184. }
  185. for _, networkInterfaceStatsIntfc := range networksStats {
  186. networkInterfaceStats, ok := networkInterfaceStatsIntfc.(map[string]interface{})
  187. if !ok {
  188. return false
  189. }
  190. for _, expectedKey := range expectedNetworkInterfaceStats {
  191. if _, ok := networkInterfaceStats[expectedKey]; !ok {
  192. return false
  193. }
  194. }
  195. }
  196. return true
  197. }
  198. func (s *DockerSuite) TestApiStatsContainerNotFound(c *check.C) {
  199. testRequires(c, DaemonIsLinux)
  200. status, _, err := sockRequest("GET", "/containers/nonexistent/stats", nil)
  201. c.Assert(err, checker.IsNil)
  202. c.Assert(status, checker.Equals, http.StatusNotFound)
  203. status, _, err = sockRequest("GET", "/containers/nonexistent/stats?stream=0", nil)
  204. c.Assert(err, checker.IsNil)
  205. c.Assert(status, checker.Equals, http.StatusNotFound)
  206. }
  207. func (s *DockerSuite) TestApiStatsNoStreamConnectedContainers(c *check.C) {
  208. testRequires(c, DaemonIsLinux)
  209. out1, _ := runSleepingContainer(c)
  210. id1 := strings.TrimSpace(out1)
  211. c.Assert(waitRun(id1), checker.IsNil)
  212. out2, _ := runSleepingContainer(c, "--net", "container:"+id1)
  213. id2 := strings.TrimSpace(out2)
  214. c.Assert(waitRun(id2), checker.IsNil)
  215. ch := make(chan error)
  216. go func() {
  217. resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id2), nil, "")
  218. defer body.Close()
  219. if err != nil {
  220. ch <- err
  221. }
  222. if resp.StatusCode != http.StatusOK {
  223. ch <- fmt.Errorf("Invalid StatusCode %v", resp.StatusCode)
  224. }
  225. if resp.Header.Get("Content-Type") != "application/json" {
  226. ch <- fmt.Errorf("Invalid 'Content-Type' %v", resp.Header.Get("Content-Type"))
  227. }
  228. var v *types.Stats
  229. if err := json.NewDecoder(body).Decode(&v); err != nil {
  230. ch <- err
  231. }
  232. ch <- nil
  233. }()
  234. select {
  235. case err := <-ch:
  236. c.Assert(err, checker.IsNil, check.Commentf("Error in stats remote API: %v", err))
  237. case <-time.After(15 * time.Second):
  238. c.Fatalf("Stats did not return after timeout")
  239. }
  240. }