docker_api_stats_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/docker/docker/api/types"
  8. "github.com/go-check/check"
  9. )
  10. func (s *DockerSuite) TestCliStatsNoStreamGetCpu(c *check.C) {
  11. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello'; usleep 100000; done")
  12. id := strings.TrimSpace(out)
  13. err := waitRun(id)
  14. c.Assert(err, check.IsNil)
  15. resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
  16. c.Assert(err, check.IsNil)
  17. c.Assert(resp.ContentLength > 0, check.Equals, true, check.Commentf("should not use chunked encoding"))
  18. c.Assert(resp.Header.Get("Content-Type"), check.Equals, "application/json")
  19. var v *types.Stats
  20. err = json.NewDecoder(body).Decode(&v)
  21. c.Assert(err, check.IsNil)
  22. var cpuPercent = 0.0
  23. cpuDelta := float64(v.CpuStats.CpuUsage.TotalUsage - v.PreCpuStats.CpuUsage.TotalUsage)
  24. systemDelta := float64(v.CpuStats.SystemUsage - v.PreCpuStats.SystemUsage)
  25. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CpuStats.CpuUsage.PercpuUsage)) * 100.0
  26. if cpuPercent == 0 {
  27. c.Fatalf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent)
  28. }
  29. }
  30. func (s *DockerSuite) TestStoppedContainerStatsGoroutines(c *check.C) {
  31. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
  32. id := strings.TrimSpace(out)
  33. getGoRoutines := func() int {
  34. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/info"), nil, "")
  35. c.Assert(err, check.IsNil)
  36. info := types.Info{}
  37. err = json.NewDecoder(body).Decode(&info)
  38. c.Assert(err, check.IsNil)
  39. body.Close()
  40. return info.NGoroutines
  41. }
  42. // When the HTTP connection is closed, the number of goroutines should not increase.
  43. routines := getGoRoutines()
  44. _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "")
  45. c.Assert(err, check.IsNil)
  46. body.Close()
  47. t := time.After(30 * time.Second)
  48. for {
  49. select {
  50. case <-t:
  51. c.Assert(getGoRoutines() <= routines, check.Equals, true)
  52. return
  53. default:
  54. if n := getGoRoutines(); n <= routines {
  55. return
  56. }
  57. time.Sleep(200 * time.Millisecond)
  58. }
  59. }
  60. }