2018-02-19 04:26:01 +00:00
|
|
|
package counters
|
|
|
|
|
2018-12-31 09:03:49 +00:00
|
|
|
import (
|
|
|
|
"database/sql"
|
2020-02-25 08:12:54 +00:00
|
|
|
"sync/atomic"
|
2018-12-31 09:03:49 +00:00
|
|
|
|
2022-02-21 03:53:13 +00:00
|
|
|
c "git.tuxpa.in/a/gosora/common"
|
|
|
|
qgen "git.tuxpa.in/a/gosora/query_gen"
|
2019-07-28 03:46:19 +00:00
|
|
|
"github.com/pkg/errors"
|
2018-12-31 09:03:49 +00:00
|
|
|
)
|
2018-02-19 04:26:01 +00:00
|
|
|
|
|
|
|
var OSViewCounter *DefaultOSViewCounter
|
|
|
|
|
|
|
|
type DefaultOSViewCounter struct {
|
2020-02-25 08:12:54 +00:00
|
|
|
buckets []int64 //[OSID]count
|
2018-03-08 03:59:47 +00:00
|
|
|
insert *sql.Stmt
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-03-21 22:59:41 +00:00
|
|
|
func NewDefaultOSViewCounter(acc *qgen.Accumulator) (*DefaultOSViewCounter, error) {
|
2019-07-28 03:46:19 +00:00
|
|
|
co := &DefaultOSViewCounter{
|
2020-02-25 08:12:54 +00:00
|
|
|
buckets: make([]int64, len(osMapEnum)),
|
|
|
|
insert: acc.Insert("viewchunks_systems").Columns("count,createdAt,system").Fields("?,UTC_TIMESTAMP(),?").Prepare(),
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
2021-05-03 00:36:29 +00:00
|
|
|
c.Tasks.FifteenMin.Add(co.Tick)
|
|
|
|
//c.Tasks.Sec.Add(co.Tick)
|
|
|
|
c.Tasks.Shutdown.Add(co.Tick)
|
2019-07-28 03:46:19 +00:00
|
|
|
return co, acc.FirstError()
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-07-28 03:46:19 +00:00
|
|
|
func (co *DefaultOSViewCounter) Tick() error {
|
2020-02-25 08:12:54 +00:00
|
|
|
for id, _ := range co.buckets {
|
|
|
|
count := atomic.SwapInt64(&co.buckets[id], 0)
|
2021-05-03 00:36:29 +00:00
|
|
|
if e := co.insertChunk(count, id); e != nil { // TODO: Bulk insert for speed?
|
|
|
|
return errors.Wrap(errors.WithStack(e), "system counter")
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-25 08:12:54 +00:00
|
|
|
func (co *DefaultOSViewCounter) insertChunk(count int64, os int) error {
|
2018-02-19 04:26:01 +00:00
|
|
|
if count == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2019-07-28 03:46:19 +00:00
|
|
|
osName := reverseOSMapEnum[os]
|
|
|
|
c.DebugLogf("Inserting a vchunk with a count of %d for OS %s (%d)", count, osName, os)
|
|
|
|
_, err := co.insert.Exec(count, osName)
|
2018-02-19 04:26:01 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-28 03:46:19 +00:00
|
|
|
func (co *DefaultOSViewCounter) Bump(id int) {
|
2018-02-19 04:26:01 +00:00
|
|
|
// TODO: Test this check
|
2020-03-01 06:22:43 +00:00
|
|
|
c.DebugDetail("bucket ", id, ": ", co.buckets[id])
|
2019-07-28 03:46:19 +00:00
|
|
|
if len(co.buckets) <= id || id < 0 {
|
2018-02-19 04:26:01 +00:00
|
|
|
return
|
|
|
|
}
|
2020-02-25 08:12:54 +00:00
|
|
|
atomic.AddInt64(&co.buckets[id], 1)
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|