2016-12-25 22:39:16 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-01-06 12:02:56 +00:00
|
|
|
"math"
|
|
|
|
|
2016-12-25 22:39:16 +00:00
|
|
|
"github.com/fsouza/go-dockerclient"
|
|
|
|
)
|
|
|
|
|
2017-01-09 14:09:26 +00:00
|
|
|
type Metrics struct {
|
2017-01-06 12:02:56 +00:00
|
|
|
CPUUtil int
|
|
|
|
NetTx int64
|
|
|
|
NetRx int64
|
|
|
|
MemLimit int64
|
|
|
|
MemPercent int
|
|
|
|
MemUsage int64
|
2017-01-09 14:09:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type MetricsReader struct {
|
|
|
|
Metrics
|
2016-12-25 22:39:16 +00:00
|
|
|
lastCpu float64
|
|
|
|
lastSysCpu float64
|
|
|
|
}
|
|
|
|
|
2017-01-09 14:09:26 +00:00
|
|
|
func NewMetricsReader() *MetricsReader {
|
|
|
|
return &MetricsReader{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MetricsReader) Read(statsCh chan *docker.Stats) chan Metrics {
|
|
|
|
stream := make(chan Metrics)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for s := range statsCh {
|
|
|
|
m.ReadCPU(s)
|
|
|
|
m.ReadMem(s)
|
|
|
|
m.ReadNet(s)
|
|
|
|
stream <- m.Metrics
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return stream
|
2016-12-25 22:39:16 +00:00
|
|
|
}
|
|
|
|
|
2017-01-09 14:09:26 +00:00
|
|
|
func (m *MetricsReader) ReadCPU(stats *docker.Stats) {
|
2016-12-25 22:39:16 +00:00
|
|
|
ncpus := float64(len(stats.CPUStats.CPUUsage.PercpuUsage))
|
|
|
|
total := float64(stats.CPUStats.CPUUsage.TotalUsage)
|
|
|
|
system := float64(stats.CPUStats.SystemCPUUsage)
|
|
|
|
|
2017-01-09 14:09:26 +00:00
|
|
|
cpudiff := total - m.lastCpu
|
|
|
|
syscpudiff := system - m.lastSysCpu
|
|
|
|
m.CPUUtil = round((cpudiff / syscpudiff * 100) * ncpus)
|
|
|
|
m.lastCpu = total
|
|
|
|
m.lastSysCpu = system
|
2016-12-25 22:39:16 +00:00
|
|
|
}
|
|
|
|
|
2017-01-09 14:09:26 +00:00
|
|
|
func (m *MetricsReader) ReadMem(stats *docker.Stats) {
|
|
|
|
m.MemUsage = int64(stats.MemoryStats.Usage)
|
|
|
|
m.MemLimit = int64(stats.MemoryStats.Limit)
|
|
|
|
m.MemPercent = round((float64(m.MemUsage) / float64(m.MemLimit)) * 100)
|
2016-12-25 22:39:16 +00:00
|
|
|
}
|
2016-12-26 17:57:55 +00:00
|
|
|
|
2017-01-09 14:09:26 +00:00
|
|
|
func (m *MetricsReader) ReadNet(stats *docker.Stats) {
|
|
|
|
var rx, tx int64
|
2016-12-26 17:57:55 +00:00
|
|
|
for _, network := range stats.Networks {
|
2017-01-09 14:09:26 +00:00
|
|
|
rx += int64(network.RxBytes)
|
|
|
|
tx += int64(network.TxBytes)
|
2016-12-26 17:57:55 +00:00
|
|
|
}
|
2017-01-09 14:09:26 +00:00
|
|
|
m.NetRx, m.NetTx = rx, tx
|
2016-12-26 17:57:55 +00:00
|
|
|
}
|
2017-01-06 12:02:56 +00:00
|
|
|
|
|
|
|
func round(num float64) int {
|
|
|
|
return int(num + math.Copysign(0.5, num))
|
|
|
|
}
|