From ed4fd26b940c9e971f2b8bf2c2af8b5b913ced6e Mon Sep 17 00:00:00 2001 From: Bradley Cicenas Date: Fri, 23 Dec 2016 04:16:34 +0000 Subject: [PATCH] add cpucalc, updatecpu method --- container.go | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/container.go b/container.go index 2a6454e..19082e4 100644 --- a/container.go +++ b/container.go @@ -24,11 +24,26 @@ func NewWidgets(id string) *Widgets { return &Widgets{cid, mkGauge(), mkGauge()} } +type CpuCalc struct { + lastCpu uint64 + lastSysCpu uint64 +} + +func (c *CpuCalc) Utilization(cpu uint64, syscpu uint64, ncpus int) int { + cpudiff := float64(cpu) - float64(c.lastCpu) + syscpudiff := float64(syscpu) - float64(c.lastSysCpu) + util := round((cpudiff / syscpudiff * 100) * float64(ncpus)) + c.lastCpu = cpu + c.lastSysCpu = syscpu + return util +} + type Container struct { id string widgets *Widgets stats chan *docker.Stats done chan bool + cpucalc *CpuCalc } func NewContainer(cid string) *Container { @@ -37,6 +52,7 @@ func NewContainer(cid string) *Container { widgets: NewWidgets(cid), stats: make(chan *docker.Stats), done: make(chan bool), + cpucalc: &CpuCalc{}, } } @@ -57,14 +73,20 @@ func (c *Container) Collect(client *docker.Client) { go func() { for s := range c.stats { c.UpdateMem(s.MemoryStats.Usage, s.MemoryStats.Limit) + c.UpdateCPU(s.CPUStats.CPUUsage.TotalUsage, s.CPUStats.SystemCPUUsage, len(s.CPUStats.CPUUsage.PercpuUsage)) } }() } -func (c *Container) UpdateCPU(total uint64, system uint64) { - c.widgets.cpu.BarColor = colorScale(n) - c.widgets.cpu.Percent = n +func (c *Container) UpdateCPU(total uint64, system uint64, ncpus int) { + util := c.cpucalc.Utilization(total, system, ncpus) + c.widgets.cpu.Label = fmt.Sprintf("%s%%", strconv.Itoa(util)) + c.widgets.cpu.BarColor = colorScale(util) + if util < 5 && util > 0 { + util = 5 + } + c.widgets.cpu.Percent = util } func (c *Container) UpdateMem(cur uint64, limit uint64) {