add cpucalc, updatecpu method

This commit is contained in:
Bradley Cicenas
2016-12-23 04:16:34 +00:00
parent 132b2b0e32
commit ed4fd26b94

View File

@@ -24,11 +24,26 @@ func NewWidgets(id string) *Widgets {
return &Widgets{cid, mkGauge(), mkGauge()} 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 { type Container struct {
id string id string
widgets *Widgets widgets *Widgets
stats chan *docker.Stats stats chan *docker.Stats
done chan bool done chan bool
cpucalc *CpuCalc
} }
func NewContainer(cid string) *Container { func NewContainer(cid string) *Container {
@@ -37,6 +52,7 @@ func NewContainer(cid string) *Container {
widgets: NewWidgets(cid), widgets: NewWidgets(cid),
stats: make(chan *docker.Stats), stats: make(chan *docker.Stats),
done: make(chan bool), done: make(chan bool),
cpucalc: &CpuCalc{},
} }
} }
@@ -57,14 +73,20 @@ func (c *Container) Collect(client *docker.Client) {
go func() { go func() {
for s := range c.stats { for s := range c.stats {
c.UpdateMem(s.MemoryStats.Usage, s.MemoryStats.Limit) 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) { func (c *Container) UpdateCPU(total uint64, system uint64, ncpus int) {
c.widgets.cpu.BarColor = colorScale(n) util := c.cpucalc.Utilization(total, system, ncpus)
c.widgets.cpu.Percent = n 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) { func (c *Container) UpdateMem(cur uint64, limit uint64) {