docker_api_stats_test.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os/exec"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/docker/docker/pkg/integration/checker"
  13. "github.com/docker/engine-api/types"
  14. "github.com/docker/engine-api/types/versions"
  15. "github.com/go-check/check"
  16. )
  17. var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
  18. func (s *DockerSuite) TestApiStatsNoStreamGetCpu(c *check.C) {
  19. testRequires(c, DaemonIsLinux)
  20. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello'; usleep 100000; done")
  21. id := strings.TrimSpace(out)
  22. c.Assert(waitRun(id), checker.IsNil)
  23. resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
  24. c.Assert(err, checker.IsNil)
  25. c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
  26. c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json")
  27. var v *types.Stats
  28. err = json.NewDecoder(body).Decode(&v)
  29. c.Assert(err, checker.IsNil)
  30. body.Close()
  31. var cpuPercent = 0.0
  32. cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage)
  33. systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage)
  34. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  35. c.Assert(cpuPercent, check.Not(checker.Equals), 0.0, check.Commentf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent))
  36. }
  37. func (s *DockerSuite) TestApiStatsStoppedContainerInGoroutines(c *check.C) {
  38. testRequires(c, DaemonIsLinux)
  39. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
  40. id := strings.TrimSpace(out)
  41. getGoRoutines := func() int {
  42. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/info"), nil, "")
  43. c.Assert(err, checker.IsNil)
  44. info := types.Info{}
  45. err = json.NewDecoder(body).Decode(&info)
  46. c.Assert(err, checker.IsNil)
  47. body.Close()
  48. return info.NGoroutines
  49. }
  50. // When the HTTP connection is closed, the number of goroutines should not increase.
  51. routines := getGoRoutines()
  52. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "")
  53. c.Assert(err, checker.IsNil)
  54. body.Close()
  55. t := time.After(30 * time.Second)
  56. for {
  57. select {
  58. case <-t:
  59. c.Assert(getGoRoutines(), checker.LessOrEqualThan, routines)
  60. return
  61. default:
  62. if n := getGoRoutines(); n <= routines {
  63. return
  64. }
  65. time.Sleep(200 * time.Millisecond)
  66. }
  67. }
  68. }
  69. func (s *DockerSuite) TestApiStatsNetworkStats(c *check.C) {
  70. testRequires(c, SameHostDaemon)
  71. testRequires(c, DaemonIsLinux)
  72. out, _ := runSleepingContainer(c)
  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 := 1
  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)).CombinedOutput()
  93. if err != nil && runtime.GOOS == "linux" {
  94. // If it fails then try a work-around, but just for linux.
  95. // If this fails too then go back to the old error for reporting.
  96. //
  97. // The ping will sometimes fail due to an apparmor issue where it
  98. // denies access to the libc.so.6 shared library - running it
  99. // via /lib64/ld-linux-x86-64.so.2 seems to work around it.
  100. pingout2, err2 := exec.Command("/lib64/ld-linux-x86-64.so.2", "/bin/ping", contIP, "-c", strconv.Itoa(numPings)).CombinedOutput()
  101. if err2 == nil {
  102. pingout = pingout2
  103. err = err2
  104. }
  105. }
  106. c.Assert(err, checker.IsNil)
  107. pingouts := string(pingout[:])
  108. nwStatsPost := getNetworkStats(c, id)
  109. for _, v := range nwStatsPost {
  110. postRxPackets += v.RxPackets
  111. postTxPackets += v.TxPackets
  112. }
  113. // Verify the stats contain at least the expected number of packets (account for ARP)
  114. expRxPkts := 1 + preRxPackets + uint64(numPings)
  115. expTxPkts := 1 + preTxPackets + uint64(numPings)
  116. c.Assert(postTxPackets, checker.GreaterOrEqualThan, expTxPkts,
  117. check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts))
  118. c.Assert(postRxPackets, checker.GreaterOrEqualThan, expRxPkts,
  119. check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts))
  120. }
  121. func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
  122. testRequires(c, SameHostDaemon)
  123. testRequires(c, DaemonIsLinux)
  124. out, _ := runSleepingContainer(c)
  125. id := strings.TrimSpace(out)
  126. c.Assert(waitRun(id), checker.IsNil)
  127. wg := sync.WaitGroup{}
  128. for i := 17; i <= 21; i++ {
  129. wg.Add(1)
  130. go func() {
  131. defer wg.Done()
  132. apiVersion := fmt.Sprintf("v1.%d", i)
  133. statsJSONBlob := getVersionedStats(c, id, apiVersion)
  134. if versions.LessThan(apiVersion, "v1.21") {
  135. c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true,
  136. check.Commentf("Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob))
  137. } else {
  138. c.Assert(jsonBlobHasGTE121NetworkStats(statsJSONBlob), checker.Equals, true,
  139. check.Commentf("Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob))
  140. }
  141. }()
  142. }
  143. wg.Wait()
  144. }
  145. func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
  146. var st *types.StatsJSON
  147. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
  148. c.Assert(err, checker.IsNil)
  149. err = json.NewDecoder(body).Decode(&st)
  150. c.Assert(err, checker.IsNil)
  151. body.Close()
  152. return st.Networks
  153. }
  154. // getVersionedStats returns stats result for the
  155. // container with id using an API call with version apiVersion. Since the
  156. // stats result type differs between API versions, we simply return
  157. // map[string]interface{}.
  158. func getVersionedStats(c *check.C, id string, apiVersion string) map[string]interface{} {
  159. stats := make(map[string]interface{})
  160. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/%s/containers/%s/stats?stream=false", apiVersion, id), nil, "")
  161. c.Assert(err, checker.IsNil)
  162. defer body.Close()
  163. err = json.NewDecoder(body).Decode(&stats)
  164. c.Assert(err, checker.IsNil, check.Commentf("failed to decode stat: %s", err))
  165. return stats
  166. }
  167. func jsonBlobHasLTv121NetworkStats(blob map[string]interface{}) bool {
  168. networkStatsIntfc, ok := blob["network"]
  169. if !ok {
  170. return false
  171. }
  172. networkStats, ok := networkStatsIntfc.(map[string]interface{})
  173. if !ok {
  174. return false
  175. }
  176. for _, expectedKey := range expectedNetworkInterfaceStats {
  177. if _, ok := networkStats[expectedKey]; !ok {
  178. return false
  179. }
  180. }
  181. return true
  182. }
  183. func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
  184. networksStatsIntfc, ok := blob["networks"]
  185. if !ok {
  186. return false
  187. }
  188. networksStats, ok := networksStatsIntfc.(map[string]interface{})
  189. if !ok {
  190. return false
  191. }
  192. for _, networkInterfaceStatsIntfc := range networksStats {
  193. networkInterfaceStats, ok := networkInterfaceStatsIntfc.(map[string]interface{})
  194. if !ok {
  195. return false
  196. }
  197. for _, expectedKey := range expectedNetworkInterfaceStats {
  198. if _, ok := networkInterfaceStats[expectedKey]; !ok {
  199. return false
  200. }
  201. }
  202. }
  203. return true
  204. }
  205. func (s *DockerSuite) TestApiStatsContainerNotFound(c *check.C) {
  206. testRequires(c, DaemonIsLinux)
  207. status, _, err := sockRequest("GET", "/containers/nonexistent/stats", nil)
  208. c.Assert(err, checker.IsNil)
  209. c.Assert(status, checker.Equals, http.StatusNotFound)
  210. status, _, err = sockRequest("GET", "/containers/nonexistent/stats?stream=0", nil)
  211. c.Assert(err, checker.IsNil)
  212. c.Assert(status, checker.Equals, http.StatusNotFound)
  213. }
  214. func (s *DockerSuite) TestApiStatsNoStreamConnectedContainers(c *check.C) {
  215. testRequires(c, DaemonIsLinux)
  216. out1, _ := runSleepingContainer(c)
  217. id1 := strings.TrimSpace(out1)
  218. c.Assert(waitRun(id1), checker.IsNil)
  219. out2, _ := runSleepingContainer(c, "--net", "container:"+id1)
  220. id2 := strings.TrimSpace(out2)
  221. c.Assert(waitRun(id2), checker.IsNil)
  222. ch := make(chan error)
  223. go func() {
  224. resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id2), nil, "")
  225. defer body.Close()
  226. if err != nil {
  227. ch <- err
  228. }
  229. if resp.StatusCode != http.StatusOK {
  230. ch <- fmt.Errorf("Invalid StatusCode %v", resp.StatusCode)
  231. }
  232. if resp.Header.Get("Content-Type") != "application/json" {
  233. ch <- fmt.Errorf("Invalid 'Content-Type' %v", resp.Header.Get("Content-Type"))
  234. }
  235. var v *types.Stats
  236. if err := json.NewDecoder(body).Decode(&v); err != nil {
  237. ch <- err
  238. }
  239. ch <- nil
  240. }()
  241. select {
  242. case err := <-ch:
  243. c.Assert(err, checker.IsNil, check.Commentf("Error in stats remote API: %v", err))
  244. case <-time.After(15 * time.Second):
  245. c.Fatalf("Stats did not return after timeout")
  246. }
  247. }