docker_api_stats_test.go 9.8 KB

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