docker_api_stats_test.go 9.8 KB

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