github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/controller/pkg/counters/counters.go (about)

     1  package counters
     2  
     3  import (
     4  	"sync/atomic"
     5  
     6  	"go.aporeto.io/enforcerd/trireme-lib/collector"
     7  )
     8  
     9  // NewCounters initializes new counters handler. Thread safe.
    10  func NewCounters() *Counters {
    11  	return &Counters{}
    12  }
    13  
    14  // CounterNames returns an array of names
    15  func CounterNames() []string {
    16  	names := make([]string, errMax+1)
    17  	var ct CounterType
    18  	for ct = 0; ct <= errMax; ct++ {
    19  		names[ct] = ct.String()
    20  	}
    21  	return names[:errMax]
    22  }
    23  
    24  // CounterError is a convinence function which returns error as well as increments the counter.
    25  func (c *Counters) CounterError(t CounterType, err error) error {
    26  	c.IncrementCounter(t)
    27  	return err
    28  }
    29  
    30  // IncrementCounter increments counters for a given PU
    31  func (c *Counters) IncrementCounter(t CounterType) {
    32  	atomic.AddUint32(&c.counters[int(t)], 1)
    33  }
    34  
    35  // GetErrorCounters returns the error counters and resets the counters to zero
    36  func (c *Counters) GetErrorCounters() []collector.Counters {
    37  
    38  	c.Lock()
    39  
    40  	report := make([]collector.Counters, errMax+1)
    41  	for index := range c.counters {
    42  		report[index] = collector.Counters(atomic.SwapUint32(&c.counters[index], 0))
    43  	}
    44  
    45  	c.Unlock()
    46  	return report[:errMax]
    47  }