Files
bugswatch-agent/internal/aggregate/window.go

156 lines
2.8 KiB
Go

package aggregate
import "time"
type Window struct {
start time.Time
cpuSum float64
cpuCount uint64
memSum float64
memCount uint64
diskSum float64
diskCount uint64
uptime uint64
load float64
// DB metrics. populated only when a DB collector is registered.
hasDB bool
dbDriver uint8
dbConnPctSum float64
dbConnPctCount uint64
dbThreadsSum float64
dbThreadsCount uint64
dbSlowQueriesDelta uint64
dbSizeBytes uint64
}
type Snapshot struct {
Timestamp time.Time
CPUAvg float64
MemAvg float64
DiskAvg float64
Uptime uint64
Load float64
// nil when DB monitoring is not enabled.
DBDriver *uint8
DBConnPct *float64
DBThreadsRunning *float64
DBSlowQueries *uint64
DBSizeBytes *uint64
}
func NewWindow() *Window {
return &Window{start: time.Now()}
}
func (w *Window) AddCPU(value float64) {
w.cpuSum += value
w.cpuCount++
}
func (w *Window) AddMemory(value float64) {
w.memSum += value
w.memCount++
}
func (w *Window) AddDisk(value float64) {
w.diskSum += value
w.diskCount++
}
func (w *Window) SetUptime(value uint64) {
w.uptime = value
}
func (w *Window) SetLoad(value float64) {
w.load = value
}
func (w *Window) AddDBConnPct(v float64) {
w.dbConnPctSum += v
w.dbConnPctCount++
w.hasDB = true
}
func (w *Window) AddDBThreadsRunning(v float64) {
w.dbThreadsSum += v
w.dbThreadsCount++
}
func (w *Window) AddDBSlowQueriesDelta(v uint64) {
w.dbSlowQueriesDelta += v
}
func (w *Window) SetDBSizeBytes(v uint64) {
w.dbSizeBytes = v
w.hasDB = true
}
// SetDBDriver records the numeric driver identifier (see dbmanager.Driver* constants).
// When multiple collectors are active this is called once per window by the manager.
func (w *Window) SetDBDriver(v uint8) {
w.dbDriver = v
}
func (w *Window) Ready(windowDuration time.Duration) bool {
return time.Since(w.start) >= windowDuration
}
func (w *Window) Snapshot() Snapshot {
var cpuAvg float64
if w.cpuCount > 0 {
cpuAvg = w.cpuSum / float64(w.cpuCount)
}
var memAvg float64
if w.memCount > 0 {
memAvg = w.memSum / float64(w.memCount)
}
var diskAvg float64
if w.diskCount > 0 {
diskAvg = w.diskSum / float64(w.diskCount)
}
snap := Snapshot{
Timestamp: time.Now(),
CPUAvg: cpuAvg,
MemAvg: memAvg,
DiskAvg: diskAvg,
Uptime: w.uptime,
Load: w.load,
}
if w.hasDB {
driver := w.dbDriver
var connPct float64
if w.dbConnPctCount > 0 {
connPct = w.dbConnPctSum / float64(w.dbConnPctCount)
}
var threads float64
if w.dbThreadsCount > 0 {
threads = w.dbThreadsSum / float64(w.dbThreadsCount)
}
slow := w.dbSlowQueriesDelta
sizeBytes := w.dbSizeBytes
snap.DBDriver = &driver
snap.DBConnPct = &connPct
snap.DBThreadsRunning = &threads
snap.DBSlowQueries = &slow
snap.DBSizeBytes = &sizeBytes
}
return snap
}