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