docker_api_stats_test.go 9.4 KB

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