docker_api_stats_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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/system"
  16. "github.com/docker/docker/api/types/versions"
  17. "github.com/docker/docker/client"
  18. "github.com/docker/docker/testutil/request"
  19. "gotest.tools/v3/assert"
  20. "gotest.tools/v3/skip"
  21. )
  22. var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
  23. func (s *DockerAPISuite) TestAPIStatsNoStreamGetCpu(c *testing.T) {
  24. skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
  25. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done")
  26. id := strings.TrimSpace(out)
  27. assert.NilError(c, waitRun(id))
  28. resp, body, err := request.Get(fmt.Sprintf("/containers/%s/stats?stream=false", id))
  29. assert.NilError(c, err)
  30. assert.Equal(c, resp.StatusCode, http.StatusOK)
  31. assert.Equal(c, resp.Header.Get("Content-Type"), "application/json")
  32. assert.Equal(c, resp.Header.Get("Content-Type"), "application/json")
  33. var v *types.Stats
  34. err = json.NewDecoder(body).Decode(&v)
  35. assert.NilError(c, err)
  36. body.Close()
  37. cpuPercent := 0.0
  38. if testEnv.DaemonInfo.OSType != "windows" {
  39. cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage)
  40. systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage)
  41. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  42. } else {
  43. // Max number of 100ns intervals between the previous time read and now
  44. possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
  45. possIntervals /= 100 // Convert to number of 100ns intervals
  46. possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
  47. // Intervals used
  48. intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
  49. // Percentage avoiding divide-by-zero
  50. if possIntervals > 0 {
  51. cpuPercent = float64(intervalsUsed) / float64(possIntervals) * 100.0
  52. }
  53. }
  54. assert.Assert(c, cpuPercent != 0.0, "docker stats with no-stream get cpu usage failed: was %v", cpuPercent)
  55. }
  56. func (s *DockerAPISuite) TestAPIStatsStoppedContainerInGoroutines(c *testing.T) {
  57. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
  58. id := strings.TrimSpace(out)
  59. getGoRoutines := func() int {
  60. _, body, err := request.Get("/info")
  61. assert.NilError(c, err)
  62. info := system.Info{}
  63. err = json.NewDecoder(body).Decode(&info)
  64. assert.NilError(c, err)
  65. body.Close()
  66. return info.NGoroutines
  67. }
  68. // When the HTTP connection is closed, the number of goroutines should not increase.
  69. routines := getGoRoutines()
  70. _, body, err := request.Get("/containers/" + id + "/stats")
  71. assert.NilError(c, err)
  72. body.Close()
  73. t := time.After(30 * time.Second)
  74. for {
  75. select {
  76. case <-t:
  77. assert.Assert(c, getGoRoutines() <= routines)
  78. return
  79. default:
  80. if n := getGoRoutines(); n <= routines {
  81. return
  82. }
  83. time.Sleep(200 * time.Millisecond)
  84. }
  85. }
  86. }
  87. func (s *DockerAPISuite) TestAPIStatsNetworkStats(c *testing.T) {
  88. skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
  89. testRequires(c, testEnv.IsLocalDaemon)
  90. out := runSleepingContainer(c)
  91. id := strings.TrimSpace(out)
  92. assert.NilError(c, waitRun(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. out := runSleepingContainer(c)
  150. id := strings.TrimSpace(out)
  151. assert.NilError(c, waitRun(id))
  152. wg := sync.WaitGroup{}
  153. for i := 17; i <= 21; i++ {
  154. wg.Add(1)
  155. go func(i int) {
  156. defer wg.Done()
  157. apiVersion := fmt.Sprintf("v1.%d", i)
  158. statsJSONBlob := getVersionedStats(c, id, apiVersion)
  159. if versions.LessThan(apiVersion, "v1.21") {
  160. assert.Assert(c, jsonBlobHasLTv121NetworkStats(statsJSONBlob), "Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob)
  161. } else {
  162. assert.Assert(c, jsonBlobHasGTE121NetworkStats(statsJSONBlob), "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 *testing.T, id string) map[string]types.NetworkStats {
  169. var st *types.StatsJSON
  170. _, body, err := request.Get("/containers/" + id + "/stats?stream=false")
  171. assert.NilError(c, err)
  172. err = json.NewDecoder(body).Decode(&st)
  173. assert.NilError(c, err)
  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 *testing.T, id string, apiVersion string) map[string]interface{} {
  182. stats := make(map[string]interface{})
  183. _, body, err := request.Get("/" + apiVersion + "/containers/" + id + "/stats?stream=false")
  184. assert.NilError(c, err)
  185. defer body.Close()
  186. err = json.NewDecoder(body).Decode(&stats)
  187. assert.NilError(c, err, "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 *DockerAPISuite) TestAPIStatsContainerNotFound(c *testing.T) {
  229. testRequires(c, DaemonIsLinux)
  230. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  231. assert.NilError(c, err)
  232. defer apiClient.Close()
  233. expected := "No such container: nonexistent"
  234. _, err = apiClient.ContainerStats(context.Background(), "nonexistent", true)
  235. assert.ErrorContains(c, err, expected)
  236. _, err = apiClient.ContainerStats(context.Background(), "nonexistent", false)
  237. assert.ErrorContains(c, err, expected)
  238. }
  239. func (s *DockerAPISuite) TestAPIStatsNoStreamConnectedContainers(c *testing.T) {
  240. testRequires(c, DaemonIsLinux)
  241. out1 := runSleepingContainer(c)
  242. id1 := strings.TrimSpace(out1)
  243. assert.NilError(c, waitRun(id1))
  244. out2 := runSleepingContainer(c, "--net", "container:"+id1)
  245. id2 := strings.TrimSpace(out2)
  246. assert.NilError(c, waitRun(id2))
  247. ch := make(chan error, 1)
  248. go func() {
  249. resp, body, err := request.Get("/containers/" + id2 + "/stats?stream=false")
  250. defer body.Close()
  251. if err != nil {
  252. ch <- err
  253. }
  254. if resp.StatusCode != http.StatusOK {
  255. ch <- fmt.Errorf("Invalid StatusCode %v", resp.StatusCode)
  256. }
  257. if resp.Header.Get("Content-Type") != "application/json" {
  258. ch <- fmt.Errorf("Invalid 'Content-Type' %v", resp.Header.Get("Content-Type"))
  259. }
  260. var v *types.Stats
  261. if err := json.NewDecoder(body).Decode(&v); err != nil {
  262. ch <- err
  263. }
  264. ch <- nil
  265. }()
  266. select {
  267. case err := <-ch:
  268. assert.NilError(c, err, "Error in stats Engine API: %v", err)
  269. case <-time.After(15 * time.Second):
  270. c.Fatalf("Stats did not return after timeout")
  271. }
  272. }