github.com/willmtemple/docker@v1.7.0-rc2/integration-cli/docker_api_stats.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"github.com/docker/docker/api/types"
     7  	"github.com/go-check/check"
     8  	"strings"
     9  	"time"
    10  )
    11  
    12  func (s *DockerSuite) TestCliStatsNoStreamGetCpu(c *check.C) {
    13  	out, _ := dockerCmd(c, "run", "-d", "--cpu-quota=2000", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello';done")
    14  
    15  	id := strings.TrimSpace(out)
    16  	if err := waitRun(id); err != nil {
    17  		c.Fatal(err)
    18  	}
    19  	ch := make(chan error)
    20  	var v *types.Stats
    21  	go func() {
    22  		_, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=1", id), nil, "")
    23  		if err != nil {
    24  			ch <- err
    25  		}
    26  		dec := json.NewDecoder(body)
    27  		if err := dec.Decode(&v); err != nil {
    28  			ch <- err
    29  		}
    30  		ch <- nil
    31  	}()
    32  	select {
    33  	case e := <-ch:
    34  		if e == nil {
    35  			var cpuPercent = 0.0
    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  			if cpuPercent < 1.8 || cpuPercent > 2.2 {
    40  				c.Fatal("docker stats with no-stream get cpu usage failed")
    41  			}
    42  
    43  		}
    44  	case <-time.After(4 * time.Second):
    45  		c.Fatal("docker stats with no-stream timeout")
    46  	}
    47  
    48  }