github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/counters/systems.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 OSViewCounter *DefaultOSViewCounter
    13  
    14  type DefaultOSViewCounter struct {
    15  	buckets []int64 //[OSID]count
    16  	insert  *sql.Stmt
    17  }
    18  
    19  func NewDefaultOSViewCounter(acc *qgen.Accumulator) (*DefaultOSViewCounter, error) {
    20  	co := &DefaultOSViewCounter{
    21  		buckets: make([]int64, len(osMapEnum)),
    22  		insert:  acc.Insert("viewchunks_systems").Columns("count,createdAt,system").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 *DefaultOSViewCounter) Tick() error {
    31  	for id, _ := range co.buckets {
    32  		count := atomic.SwapInt64(&co.buckets[id], 0)
    33  		if e := co.insertChunk(count, id); e != nil { // TODO: Bulk insert for speed?
    34  			return errors.Wrap(errors.WithStack(e), "system counter")
    35  		}
    36  	}
    37  	return nil
    38  }
    39  
    40  func (co *DefaultOSViewCounter) insertChunk(count int64, os int) error {
    41  	if count == 0 {
    42  		return nil
    43  	}
    44  	osName := reverseOSMapEnum[os]
    45  	c.DebugLogf("Inserting a vchunk with a count of %d for OS %s (%d)", count, osName, os)
    46  	_, err := co.insert.Exec(count, osName)
    47  	return err
    48  }
    49  
    50  func (co *DefaultOSViewCounter) Bump(id int) {
    51  	// TODO: Test this check
    52  	c.DebugDetail("bucket ", id, ": ", co.buckets[id])
    53  	if len(co.buckets) <= id || id < 0 {
    54  		return
    55  	}
    56  	atomic.AddInt64(&co.buckets[id], 1)
    57  }