docker_api_stats_test.go 8.8 KB

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