2019-05-01 06:59:51 +00:00
|
|
|
package counters
|
|
|
|
|
|
|
|
import (
|
2019-05-01 23:14:07 +00:00
|
|
|
"time"
|
|
|
|
"sync"
|
2019-05-01 06:59:51 +00:00
|
|
|
"runtime"
|
|
|
|
"database/sql"
|
|
|
|
|
|
|
|
c "github.com/Azareal/Gosora/common"
|
|
|
|
"github.com/Azareal/Gosora/query_gen"
|
|
|
|
)
|
|
|
|
|
|
|
|
var MemoryCounter *DefaultMemoryCounter
|
|
|
|
|
|
|
|
type DefaultMemoryCounter struct {
|
|
|
|
insert *sql.Stmt
|
2019-05-01 23:14:07 +00:00
|
|
|
totMem uint64
|
|
|
|
totCount uint64
|
|
|
|
sync.Mutex
|
2019-05-01 06:59:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewMemoryCounter(acc *qgen.Accumulator) (*DefaultMemoryCounter, error) {
|
|
|
|
co := &DefaultMemoryCounter{
|
|
|
|
insert: acc.Insert("memchunks").Columns("count, createdAt").Fields("?,UTC_TIMESTAMP()").Prepare(),
|
|
|
|
}
|
|
|
|
c.AddScheduledFifteenMinuteTask(co.Tick)
|
|
|
|
//c.AddScheduledSecondTask(co.Tick)
|
|
|
|
c.AddShutdownTask(co.Tick)
|
2019-05-01 23:14:07 +00:00
|
|
|
ticker := time.NewTicker(time.Minute)
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
var m runtime.MemStats
|
|
|
|
runtime.ReadMemStats(&m)
|
|
|
|
co.Lock()
|
|
|
|
co.totCount++
|
|
|
|
co.totMem += m.Sys
|
|
|
|
co.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2019-05-01 06:59:51 +00:00
|
|
|
return co, acc.FirstError()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (co *DefaultMemoryCounter) Tick() (err error) {
|
|
|
|
var m runtime.MemStats
|
|
|
|
runtime.ReadMemStats(&m)
|
2019-05-01 23:14:07 +00:00
|
|
|
var avgMem uint64
|
|
|
|
co.Lock()
|
|
|
|
co.totCount++
|
|
|
|
co.totMem += m.Sys
|
|
|
|
avgMem = co.totMem / co.totCount
|
|
|
|
co.totMem = 0
|
|
|
|
co.totCount = 0
|
|
|
|
co.Unlock()
|
|
|
|
c.DebugLogf("Inserting a memchunk with a value of %d", avgMem)
|
|
|
|
_, err = co.insert.Exec(avgMem)
|
2019-05-01 06:59:51 +00:00
|
|
|
return err
|
|
|
|
}
|