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
|
|
|
|
2019-07-28 03:46:19 +00:00
|
|
|
c "github.com/Azareal/Gosora/common"
|
|
|
|
qgen "github.com/Azareal/Gosora/query_gen"
|
|
|
|
"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
|
|
|
}
|
2019-07-28 03:46:19 +00:00
|
|
|
c.AddScheduledFifteenMinuteTask(co.Tick)
|
|
|
|
//c.AddScheduledSecondTask(co.Tick)
|
|
|
|
c.AddShutdownTask(co.Tick)
|
|
|
|
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)
|
2019-07-28 03:46:19 +00:00
|
|
|
err := co.insertChunk(count, id) // TODO: Bulk insert for speed?
|
2018-02-19 04:26:01 +00:00
|
|
|
if err != nil {
|
2019-07-28 03:46:19 +00:00
|
|
|
return errors.Wrap(errors.WithStack(err), "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
|
|
|
}
|