github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/counters/agents.go (about)

     1  package counters
     2  
     3  import (
     4  	"database/sql"
     5  	"sync/atomic"
     6  
     7  	c "github.com/Azareal/Gosora/common"
     8  	qgen "github.com/Azareal/Gosora/query_gen"
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  var AgentViewCounter *DefaultAgentViewCounter
    13  
    14  type DefaultAgentViewCounter struct {
    15  	buckets []int64 //[AgentID]count
    16  	insert  *sql.Stmt
    17  }
    18  
    19  func NewDefaultAgentViewCounter(acc *qgen.Accumulator) (*DefaultAgentViewCounter, error) {
    20  	co := &DefaultAgentViewCounter{
    21  		buckets: make([]int64, len(agentMapEnum)),
    22  		insert:  acc.Insert("viewchunks_agents").Columns("count,createdAt,browser").Fields("?,UTC_TIMESTAMP(),?").Prepare(),
    23  	}
    24  	c.Tasks.FifteenMin.Add(co.Tick)
    25  	//c.Tasks.Sec.Add(co.Tick)
    26  	c.Tasks.Shutdown.Add(co.Tick)
    27  	return co, acc.FirstError()
    28  }
    29  
    30  func (co *DefaultAgentViewCounter) Tick() error {
    31  	for id, _ := range co.buckets {
    32  		count := atomic.SwapInt64(&co.buckets[id], 0)
    33  		e := co.insertChunk(count, id) // TODO: Bulk insert for speed?
    34  		if e != nil {
    35  			return errors.Wrap(errors.WithStack(e), "agent counter")
    36  		}
    37  	}
    38  	return nil
    39  }
    40  
    41  func (co *DefaultAgentViewCounter) insertChunk(count int64, agent int) error {
    42  	if count == 0 {
    43  		return nil
    44  	}
    45  	agentName := reverseAgentMapEnum[agent]
    46  	c.DebugLogf("Inserting a vchunk with a count of %d for agent %s (%d)", count, agentName, agent)
    47  	_, e := co.insert.Exec(count, agentName)
    48  	return e
    49  }
    50  
    51  func (co *DefaultAgentViewCounter) Bump(agent int) {
    52  	// TODO: Test this check
    53  	c.DebugDetail("buckets ", agent, ": ", co.buckets[agent])
    54  	if len(co.buckets) <= agent || agent < 0 {
    55  		return
    56  	}
    57  	atomic.AddInt64(&co.buckets[agent], 1)
    58  }