2018-02-19 04:26:01 +00:00
|
|
|
package counters
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2020-02-25 08:12:54 +00:00
|
|
|
"sync/atomic"
|
2018-02-19 04:26:01 +00:00
|
|
|
|
2019-04-19 06:36:26 +00:00
|
|
|
c "github.com/Azareal/Gosora/common"
|
2019-07-28 04:01:33 +00:00
|
|
|
qgen "github.com/Azareal/Gosora/query_gen"
|
|
|
|
"github.com/pkg/errors"
|
2018-02-19 04:26:01 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var AgentViewCounter *DefaultAgentViewCounter
|
|
|
|
|
|
|
|
type DefaultAgentViewCounter struct {
|
2020-02-25 08:12:54 +00:00
|
|
|
buckets []int64 //[AgentID]count
|
|
|
|
insert *sql.Stmt
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-03-12 09:13:57 +00:00
|
|
|
func NewDefaultAgentViewCounter(acc *qgen.Accumulator) (*DefaultAgentViewCounter, error) {
|
2019-07-28 04:01:33 +00:00
|
|
|
co := &DefaultAgentViewCounter{
|
2020-02-25 08:12:54 +00:00
|
|
|
buckets: make([]int64, len(agentMapEnum)),
|
|
|
|
insert: acc.Insert("viewchunks_agents").Columns("count,createdAt,browser").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 04:01:33 +00:00
|
|
|
return co, acc.FirstError()
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-07-28 04:01:33 +00:00
|
|
|
func (co *DefaultAgentViewCounter) 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
|
|
|
e := co.insertChunk(count, id) // TODO: Bulk insert for speed?
|
|
|
|
if e != nil {
|
|
|
|
return errors.Wrap(errors.WithStack(e), "agent counter")
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-25 08:12:54 +00:00
|
|
|
func (co *DefaultAgentViewCounter) insertChunk(count int64, agent int) error {
|
2018-02-19 04:26:01 +00:00
|
|
|
if count == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2019-07-28 04:01:33 +00:00
|
|
|
agentName := reverseAgentMapEnum[agent]
|
|
|
|
c.DebugLogf("Inserting a vchunk with a count of %d for agent %s (%d)", count, agentName, agent)
|
2021-05-03 00:36:29 +00:00
|
|
|
_, e := co.insert.Exec(count, agentName)
|
|
|
|
return e
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-07-28 04:01:33 +00:00
|
|
|
func (co *DefaultAgentViewCounter) Bump(agent int) {
|
2018-02-19 04:26:01 +00:00
|
|
|
// TODO: Test this check
|
2021-05-03 00:36:29 +00:00
|
|
|
c.DebugDetail("buckets ", agent, ": ", co.buckets[agent])
|
2020-02-25 08:12:54 +00:00
|
|
|
if len(co.buckets) <= agent || agent < 0 {
|
2018-02-19 04:26:01 +00:00
|
|
|
return
|
|
|
|
}
|
2020-02-25 08:12:54 +00:00
|
|
|
atomic.AddInt64(&co.buckets[agent], 1)
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|