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. "testing"
  12. "time"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/api/types/system"
  15. "github.com/docker/docker/api/types/versions"
  16. "github.com/docker/docker/client"
  17. "github.com/docker/docker/integration-cli/cli"
  18. "github.com/docker/docker/testutil"
  19. "github.com/docker/docker/testutil/request"
  20. "gotest.tools/v3/assert"
  21. "gotest.tools/v3/skip"
  22. )
  23. var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
  24. func (s *DockerAPISuite) TestAPIStatsNoStreamGetCpu(c *testing.T) {
  25. skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
  26. out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done").Stdout()
  27. id := strings.TrimSpace(out)
  28. cli.WaitRun(c, id)
  29. resp, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/stats?stream=false", id))
  30. assert.NilError(c, err)
  31. assert.Equal(c, resp.StatusCode, http.StatusOK)
  32. assert.Equal(c, resp.Header.Get("Content-Type"), "application/json")
  33. assert.Equal(c, resp.Header.Get("Content-Type"), "application/json")
  34. var v *types.Stats
  35. err = json.NewDecoder(body).Decode(&v)
  36. assert.NilError(c, err)
  37. body.Close()
  38. cpuPercent := 0.0
  39. if testEnv.DaemonInfo.OSType != "windows" {
  40. cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage)
  41. systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage)
  42. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  43. } else {
  44. // Max number of 100ns intervals between the previous time read and now
  45. possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
  46. possIntervals /= 100 // Convert to number of 100ns intervals
  47. possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
  48. // Intervals used
  49. intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
  50. // Percentage avoiding divide-by-zero
  51. if possIntervals > 0 {
  52. cpuPercent = float64(intervalsUsed) / float64(possIntervals) * 100.0
  53. }
  54. }
  55. assert.Assert(c, cpuPercent != 0.0, "docker stats with no-stream get cpu usage failed: was %v", cpuPercent)
  56. }
  57. func (s *DockerAPISuite) TestAPIStatsStoppedContainerInGoroutines(c *testing.T) {
  58. out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1").Stdout()
  59. id := strings.TrimSpace(out)
  60. getGoRoutines := func() int {
  61. _, body, err := request.Get(testutil.GetContext(c), "/info")
  62. assert.NilError(c, err)
  63. info := system.Info{}
  64. err = json.NewDecoder(body).Decode(&info)
  65. assert.NilError(c, err)
  66. body.Close()
  67. return info.NGoroutines
  68. }
  69. // When the HTTP connection is closed, the number of goroutines should not increase.
  70. routines := getGoRoutines()
  71. _, body, err := request.Get(testutil.GetContext(c), "/containers/"+id+"/stats")
  72. assert.NilError(c, err)
  73. body.Close()
  74. t := time.After(30 * time.Second)
  75. for {
  76. select {
  77. case <-t:
  78. assert.Assert(c, getGoRoutines() <= routines)
  79. return
  80. default:
  81. if n := getGoRoutines(); n <= routines {
  82. return
  83. }
  84. time.Sleep(200 * time.Millisecond)
  85. }
  86. }
  87. }
  88. func (s *DockerAPISuite) TestAPIStatsNetworkStats(c *testing.T) {
  89. skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
  90. testRequires(c, testEnv.IsLocalDaemon)
  91. id := runSleepingContainer(c)
  92. cli.WaitRun(c, id)
  93. // Retrieve the container address
  94. net := "bridge"
  95. if testEnv.DaemonInfo.OSType == "windows" {
  96. net = "nat"
  97. }
  98. contIP := findContainerIP(c, id, net)
  99. numPings := 1
  100. var preRxPackets uint64
  101. var preTxPackets uint64
  102. var postRxPackets uint64
  103. var postTxPackets uint64
  104. // Get the container networking stats before and after pinging the container
  105. nwStatsPre := getNetworkStats(c, id)
  106. for _, v := range nwStatsPre {
  107. preRxPackets += v.RxPackets
  108. preTxPackets += v.TxPackets
  109. }
  110. countParam := "-c"
  111. if runtime.GOOS == "windows" {
  112. countParam = "-n" // Ping count parameter is -n on Windows
  113. }
  114. pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).CombinedOutput()
  115. if err != nil && runtime.GOOS == "linux" {
  116. // If it fails then try a work-around, but just for linux.
  117. // If this fails too then go back to the old error for reporting.
  118. //
  119. // The ping will sometimes fail due to an apparmor issue where it
  120. // denies access to the libc.so.6 shared library - running it
  121. // via /lib64/ld-linux-x86-64.so.2 seems to work around it.
  122. pingout2, err2 := exec.Command("/lib64/ld-linux-x86-64.so.2", "/bin/ping", contIP, "-c", strconv.Itoa(numPings)).CombinedOutput()
  123. if err2 == nil {
  124. pingout = pingout2
  125. err = err2
  126. }
  127. }
  128. assert.NilError(c, err)
  129. pingouts := string(pingout[:])
  130. nwStatsPost := getNetworkStats(c, id)
  131. for _, v := range nwStatsPost {
  132. postRxPackets += v.RxPackets
  133. postTxPackets += v.TxPackets
  134. }
  135. // Verify the stats contain at least the expected number of packets
  136. // On Linux, account for ARP.
  137. expRxPkts := preRxPackets + uint64(numPings)
  138. expTxPkts := preTxPackets + uint64(numPings)
  139. if testEnv.DaemonInfo.OSType != "windows" {
  140. expRxPkts++
  141. expTxPkts++
  142. }
  143. assert.Assert(c, postTxPackets >= expTxPkts, "Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts)
  144. assert.Assert(c, postRxPackets >= expRxPkts, "Reported less RxPackets than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts)
  145. }
  146. func (s *DockerAPISuite) TestAPIStatsNetworkStatsVersioning(c *testing.T) {
  147. // Windows doesn't support API versions less than 1.25, so no point testing 1.17 .. 1.21
  148. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  149. id := runSleepingContainer(c)
  150. cli.WaitRun(c, id)
  151. wg := sync.WaitGroup{}
  152. for i := 17; i <= 21; i++ {
  153. wg.Add(1)
  154. go func(i int) {
  155. defer wg.Done()
  156. apiVersion := fmt.Sprintf("v1.%d", i)
  157. statsJSONBlob := getVersionedStats(c, id, apiVersion)
  158. if versions.LessThan(apiVersion, "v1.21") {
  159. assert.Assert(c, jsonBlobHasLTv121NetworkStats(statsJSONBlob), "Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob)
  160. } else {
  161. assert.Assert(c, jsonBlobHasGTE121NetworkStats(statsJSONBlob), "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 *testing.T, id string) map[string]types.NetworkStats {
  168. var st *types.StatsJSON
  169. _, body, err := request.Get(testutil.GetContext(c), "/containers/"+id+"/stats?stream=false")
  170. assert.NilError(c, err)
  171. err = json.NewDecoder(body).Decode(&st)
  172. assert.NilError(c, err)
  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 *testing.T, id string, apiVersion string) map[string]interface{} {
  181. stats := make(map[string]interface{})
  182. _, body, err := request.Get(testutil.GetContext(c), "/"+apiVersion+"/containers/"+id+"/stats?stream=false")
  183. assert.NilError(c, err)
  184. defer body.Close()
  185. err = json.NewDecoder(body).Decode(&stats)
  186. assert.NilError(c, err, "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 *DockerAPISuite) TestAPIStatsContainerNotFound(c *testing.T) {
  228. testRequires(c, DaemonIsLinux)
  229. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  230. assert.NilError(c, err)
  231. defer apiClient.Close()
  232. expected := "No such container: nonexistent"
  233. _, err = apiClient.ContainerStats(testutil.GetContext(c), "nonexistent", true)
  234. assert.ErrorContains(c, err, expected)
  235. _, err = apiClient.ContainerStats(testutil.GetContext(c), "nonexistent", false)
  236. assert.ErrorContains(c, err, expected)
  237. }
  238. func (s *DockerAPISuite) TestAPIStatsNoStreamConnectedContainers(c *testing.T) {
  239. testRequires(c, DaemonIsLinux)
  240. id1 := runSleepingContainer(c)
  241. cli.WaitRun(c, id1)
  242. id2 := runSleepingContainer(c, "--net", "container:"+id1)
  243. cli.WaitRun(c, id2)
  244. ch := make(chan error, 1)
  245. go func() {
  246. resp, body, err := request.Get(testutil.GetContext(c), "/containers/"+id2+"/stats?stream=false")
  247. defer body.Close()
  248. if err != nil {
  249. ch <- err
  250. }
  251. if resp.StatusCode != http.StatusOK {
  252. ch <- fmt.Errorf("Invalid StatusCode %v", resp.StatusCode)
  253. }
  254. if resp.Header.Get("Content-Type") != "application/json" {
  255. ch <- fmt.Errorf("Invalid 'Content-Type' %v", resp.Header.Get("Content-Type"))
  256. }
  257. var v *types.Stats
  258. if err := json.NewDecoder(body).Decode(&v); err != nil {
  259. ch <- err
  260. }
  261. ch <- nil
  262. }()
  263. select {
  264. case err := <-ch:
  265. assert.NilError(c, err, "Error in stats Engine API: %v", err)
  266. case <-time.After(15 * time.Second):
  267. c.Fatalf("Stats did not return after timeout")
  268. }
  269. }