docker_api_stats_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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/api/types"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/docker/integration-cli/checker"
  15. "github.com/docker/docker/integration-cli/request"
  16. "github.com/go-check/check"
  17. )
  18. var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
  19. func (s *DockerSuite) TestAPIStatsNoStreamGetCpu(c *check.C) {
  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 := request.Get(daemonHost(), fmt.Sprintf("/containers/%s/stats?stream=false", id))
  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. if testEnv.DaemonPlatform() != "windows" {
  33. cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage)
  34. systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage)
  35. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  36. } else {
  37. // Max number of 100ns intervals between the previous time read and now
  38. possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
  39. possIntervals /= 100 // Convert to number of 100ns intervals
  40. possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
  41. // Intervals used
  42. intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
  43. // Percentage avoiding divide-by-zero
  44. if possIntervals > 0 {
  45. cpuPercent = float64(intervalsUsed) / float64(possIntervals) * 100.0
  46. }
  47. }
  48. c.Assert(cpuPercent, check.Not(checker.Equals), 0.0, check.Commentf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent))
  49. }
  50. func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) {
  51. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
  52. id := strings.TrimSpace(out)
  53. getGoRoutines := func() int {
  54. _, body, err := request.Get(daemonHost(), fmt.Sprintf("/info"))
  55. c.Assert(err, checker.IsNil)
  56. info := types.Info{}
  57. err = json.NewDecoder(body).Decode(&info)
  58. c.Assert(err, checker.IsNil)
  59. body.Close()
  60. return info.NGoroutines
  61. }
  62. // When the HTTP connection is closed, the number of goroutines should not increase.
  63. routines := getGoRoutines()
  64. _, body, err := request.Get(daemonHost(), fmt.Sprintf("/containers/%s/stats", id))
  65. c.Assert(err, checker.IsNil)
  66. body.Close()
  67. t := time.After(30 * time.Second)
  68. for {
  69. select {
  70. case <-t:
  71. c.Assert(getGoRoutines(), checker.LessOrEqualThan, routines)
  72. return
  73. default:
  74. if n := getGoRoutines(); n <= routines {
  75. return
  76. }
  77. time.Sleep(200 * time.Millisecond)
  78. }
  79. }
  80. }
  81. func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) {
  82. testRequires(c, SameHostDaemon)
  83. out, _ := runSleepingContainer(c)
  84. id := strings.TrimSpace(out)
  85. c.Assert(waitRun(id), checker.IsNil)
  86. // Retrieve the container address
  87. net := "bridge"
  88. if testEnv.DaemonPlatform() == "windows" {
  89. net = "nat"
  90. }
  91. contIP := findContainerIP(c, id, net)
  92. numPings := 1
  93. var preRxPackets uint64
  94. var preTxPackets uint64
  95. var postRxPackets uint64
  96. var postTxPackets uint64
  97. // Get the container networking stats before and after pinging the container
  98. nwStatsPre := getNetworkStats(c, id)
  99. for _, v := range nwStatsPre {
  100. preRxPackets += v.RxPackets
  101. preTxPackets += v.TxPackets
  102. }
  103. countParam := "-c"
  104. if runtime.GOOS == "windows" {
  105. countParam = "-n" // Ping count parameter is -n on Windows
  106. }
  107. pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).CombinedOutput()
  108. if err != nil && runtime.GOOS == "linux" {
  109. // If it fails then try a work-around, but just for linux.
  110. // If this fails too then go back to the old error for reporting.
  111. //
  112. // The ping will sometimes fail due to an apparmor issue where it
  113. // denies access to the libc.so.6 shared library - running it
  114. // via /lib64/ld-linux-x86-64.so.2 seems to work around it.
  115. pingout2, err2 := exec.Command("/lib64/ld-linux-x86-64.so.2", "/bin/ping", contIP, "-c", strconv.Itoa(numPings)).CombinedOutput()
  116. if err2 == nil {
  117. pingout = pingout2
  118. err = err2
  119. }
  120. }
  121. c.Assert(err, checker.IsNil)
  122. pingouts := string(pingout[:])
  123. nwStatsPost := getNetworkStats(c, id)
  124. for _, v := range nwStatsPost {
  125. postRxPackets += v.RxPackets
  126. postTxPackets += v.TxPackets
  127. }
  128. // Verify the stats contain at least the expected number of packets
  129. // On Linux, account for ARP.
  130. expRxPkts := preRxPackets + uint64(numPings)
  131. expTxPkts := preTxPackets + uint64(numPings)
  132. if testEnv.DaemonPlatform() != "windows" {
  133. expRxPkts++
  134. expTxPkts++
  135. }
  136. c.Assert(postTxPackets, checker.GreaterOrEqualThan, expTxPkts,
  137. check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts))
  138. c.Assert(postRxPackets, checker.GreaterOrEqualThan, expRxPkts,
  139. check.Commentf("Reported less RxPackets than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts))
  140. }
  141. func (s *DockerSuite) TestAPIStatsNetworkStatsVersioning(c *check.C) {
  142. // Windows doesn't support API versions less than 1.25, so no point testing 1.17 .. 1.21
  143. testRequires(c, SameHostDaemon, DaemonIsLinux)
  144. out, _ := runSleepingContainer(c)
  145. id := strings.TrimSpace(out)
  146. c.Assert(waitRun(id), checker.IsNil)
  147. wg := sync.WaitGroup{}
  148. for i := 17; i <= 21; i++ {
  149. wg.Add(1)
  150. go func(i int) {
  151. defer wg.Done()
  152. apiVersion := fmt.Sprintf("v1.%d", i)
  153. statsJSONBlob := getVersionedStats(c, id, apiVersion)
  154. if versions.LessThan(apiVersion, "v1.21") {
  155. c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true,
  156. check.Commentf("Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob))
  157. } else {
  158. c.Assert(jsonBlobHasGTE121NetworkStats(statsJSONBlob), checker.Equals, true,
  159. check.Commentf("Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob))
  160. }
  161. }(i)
  162. }
  163. wg.Wait()
  164. }
  165. func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
  166. var st *types.StatsJSON
  167. _, body, err := request.Get(daemonHost(), fmt.Sprintf("/containers/%s/stats?stream=false", id))
  168. c.Assert(err, checker.IsNil)
  169. err = json.NewDecoder(body).Decode(&st)
  170. c.Assert(err, checker.IsNil)
  171. body.Close()
  172. return st.Networks
  173. }
  174. // getVersionedStats returns stats result for the
  175. // container with id using an API call with version apiVersion. Since the
  176. // stats result type differs between API versions, we simply return
  177. // map[string]interface{}.
  178. func getVersionedStats(c *check.C, id string, apiVersion string) map[string]interface{} {
  179. stats := make(map[string]interface{})
  180. _, body, err := request.Get(daemonHost(), fmt.Sprintf("/%s/containers/%s/stats?stream=false", apiVersion, id))
  181. c.Assert(err, checker.IsNil)
  182. defer body.Close()
  183. err = json.NewDecoder(body).Decode(&stats)
  184. c.Assert(err, checker.IsNil, check.Commentf("failed to decode stat: %s", err))
  185. return stats
  186. }
  187. func jsonBlobHasLTv121NetworkStats(blob map[string]interface{}) bool {
  188. networkStatsIntfc, ok := blob["network"]
  189. if !ok {
  190. return false
  191. }
  192. networkStats, ok := networkStatsIntfc.(map[string]interface{})
  193. if !ok {
  194. return false
  195. }
  196. for _, expectedKey := range expectedNetworkInterfaceStats {
  197. if _, ok := networkStats[expectedKey]; !ok {
  198. return false
  199. }
  200. }
  201. return true
  202. }
  203. func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
  204. networksStatsIntfc, ok := blob["networks"]
  205. if !ok {
  206. return false
  207. }
  208. networksStats, ok := networksStatsIntfc.(map[string]interface{})
  209. if !ok {
  210. return false
  211. }
  212. for _, networkInterfaceStatsIntfc := range networksStats {
  213. networkInterfaceStats, ok := networkInterfaceStatsIntfc.(map[string]interface{})
  214. if !ok {
  215. return false
  216. }
  217. for _, expectedKey := range expectedNetworkInterfaceStats {
  218. if _, ok := networkInterfaceStats[expectedKey]; !ok {
  219. return false
  220. }
  221. }
  222. }
  223. return true
  224. }
  225. func (s *DockerSuite) TestAPIStatsContainerNotFound(c *check.C) {
  226. testRequires(c, DaemonIsLinux)
  227. status, _, err := request.SockRequest("GET", "/containers/nonexistent/stats", nil, daemonHost())
  228. c.Assert(err, checker.IsNil)
  229. c.Assert(status, checker.Equals, http.StatusNotFound)
  230. status, _, err = request.SockRequest("GET", "/containers/nonexistent/stats?stream=0", nil, daemonHost())
  231. c.Assert(err, checker.IsNil)
  232. c.Assert(status, checker.Equals, http.StatusNotFound)
  233. }
  234. func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) {
  235. testRequires(c, DaemonIsLinux)
  236. out1, _ := runSleepingContainer(c)
  237. id1 := strings.TrimSpace(out1)
  238. c.Assert(waitRun(id1), checker.IsNil)
  239. out2, _ := runSleepingContainer(c, "--net", "container:"+id1)
  240. id2 := strings.TrimSpace(out2)
  241. c.Assert(waitRun(id2), checker.IsNil)
  242. ch := make(chan error)
  243. go func() {
  244. resp, body, err := request.Get(daemonHost(), fmt.Sprintf("/containers/%s/stats?stream=false", id2))
  245. defer body.Close()
  246. if err != nil {
  247. ch <- err
  248. }
  249. if resp.StatusCode != http.StatusOK {
  250. ch <- fmt.Errorf("Invalid StatusCode %v", resp.StatusCode)
  251. }
  252. if resp.Header.Get("Content-Type") != "application/json" {
  253. ch <- fmt.Errorf("Invalid 'Content-Type' %v", resp.Header.Get("Content-Type"))
  254. }
  255. var v *types.Stats
  256. if err := json.NewDecoder(body).Decode(&v); err != nil {
  257. ch <- err
  258. }
  259. ch <- nil
  260. }()
  261. select {
  262. case err := <-ch:
  263. c.Assert(err, checker.IsNil, check.Commentf("Error in stats Engine API: %v", err))
  264. case <-time.After(15 * time.Second):
  265. c.Fatalf("Stats did not return after timeout")
  266. }
  267. }