docker_api_stats_test.go 9.7 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. "testing"
  13. "time"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/versions"
  16. "github.com/docker/docker/client"
  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, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done")
  25. id := strings.TrimSpace(out)
  26. assert.NilError(c, waitRun(id))
  27. resp, body, err := request.Get(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. var cpuPercent = 0.0
  37. if testEnv.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, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
  57. id := strings.TrimSpace(out)
  58. getGoRoutines := func() int {
  59. _, body, err := request.Get("/info")
  60. assert.NilError(c, err)
  61. info := types.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("/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. out := runSleepingContainer(c)
  90. id := strings.TrimSpace(out)
  91. assert.NilError(c, waitRun(id))
  92. // Retrieve the container address
  93. net := "bridge"
  94. if testEnv.OSType == "windows" {
  95. net = "nat"
  96. }
  97. contIP := findContainerIP(c, id, net)
  98. numPings := 1
  99. var preRxPackets uint64
  100. var preTxPackets uint64
  101. var postRxPackets uint64
  102. var postTxPackets uint64
  103. // Get the container networking stats before and after pinging the container
  104. nwStatsPre := getNetworkStats(c, id)
  105. for _, v := range nwStatsPre {
  106. preRxPackets += v.RxPackets
  107. preTxPackets += v.TxPackets
  108. }
  109. countParam := "-c"
  110. if runtime.GOOS == "windows" {
  111. countParam = "-n" // Ping count parameter is -n on Windows
  112. }
  113. pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).CombinedOutput()
  114. if err != nil && runtime.GOOS == "linux" {
  115. // If it fails then try a work-around, but just for linux.
  116. // If this fails too then go back to the old error for reporting.
  117. //
  118. // The ping will sometimes fail due to an apparmor issue where it
  119. // denies access to the libc.so.6 shared library - running it
  120. // via /lib64/ld-linux-x86-64.so.2 seems to work around it.
  121. pingout2, err2 := exec.Command("/lib64/ld-linux-x86-64.so.2", "/bin/ping", contIP, "-c", strconv.Itoa(numPings)).CombinedOutput()
  122. if err2 == nil {
  123. pingout = pingout2
  124. err = err2
  125. }
  126. }
  127. assert.NilError(c, err)
  128. pingouts := string(pingout[:])
  129. nwStatsPost := getNetworkStats(c, id)
  130. for _, v := range nwStatsPost {
  131. postRxPackets += v.RxPackets
  132. postTxPackets += v.TxPackets
  133. }
  134. // Verify the stats contain at least the expected number of packets
  135. // On Linux, account for ARP.
  136. expRxPkts := preRxPackets + uint64(numPings)
  137. expTxPkts := preTxPackets + uint64(numPings)
  138. if testEnv.OSType != "windows" {
  139. expRxPkts++
  140. expTxPkts++
  141. }
  142. assert.Assert(c, postTxPackets >= expTxPkts, "Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts)
  143. assert.Assert(c, postRxPackets >= expRxPkts, "Reported less RxPackets than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts)
  144. }
  145. func (s *DockerAPISuite) TestAPIStatsNetworkStatsVersioning(c *testing.T) {
  146. // Windows doesn't support API versions less than 1.25, so no point testing 1.17 .. 1.21
  147. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  148. out := runSleepingContainer(c)
  149. id := strings.TrimSpace(out)
  150. assert.NilError(c, waitRun(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("/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("/" + 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. cli, err := client.NewClientWithOpts(client.FromEnv)
  230. assert.NilError(c, err)
  231. defer cli.Close()
  232. expected := "No such container: nonexistent"
  233. _, err = cli.ContainerStats(context.Background(), "nonexistent", true)
  234. assert.ErrorContains(c, err, expected)
  235. _, err = cli.ContainerStats(context.Background(), "nonexistent", false)
  236. assert.ErrorContains(c, err, expected)
  237. }
  238. func (s *DockerAPISuite) TestAPIStatsNoStreamConnectedContainers(c *testing.T) {
  239. testRequires(c, DaemonIsLinux)
  240. out1 := runSleepingContainer(c)
  241. id1 := strings.TrimSpace(out1)
  242. assert.NilError(c, waitRun(id1))
  243. out2 := runSleepingContainer(c, "--net", "container:"+id1)
  244. id2 := strings.TrimSpace(out2)
  245. assert.NilError(c, waitRun(id2))
  246. ch := make(chan error, 1)
  247. go func() {
  248. resp, body, err := request.Get("/containers/" + id2 + "/stats?stream=false")
  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. assert.NilError(c, err, "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. }