2016-04-25 23:49:06 +00:00
|
|
|
package buffer
|
|
|
|
|
|
|
|
import (
|
2016-10-18 11:22:23 +00:00
|
|
|
"sync"
|
|
|
|
|
2016-04-25 23:49:06 +00:00
|
|
|
"github.com/influxdata/telegraf"
|
2016-11-07 08:34:46 +00:00
|
|
|
"github.com/influxdata/telegraf/selfstat"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
MetricsWritten = selfstat.Register("agent", "metrics_written", map[string]string{})
|
|
|
|
MetricsDropped = selfstat.Register("agent", "metrics_dropped", map[string]string{})
|
2016-04-25 23:49:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Buffer is an object for storing metrics in a circular buffer.
|
|
|
|
type Buffer struct {
|
|
|
|
buf chan telegraf.Metric
|
2016-10-18 11:22:23 +00:00
|
|
|
|
2016-10-24 15:15:46 +00:00
|
|
|
mu sync.Mutex
|
2016-04-25 23:49:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewBuffer returns a Buffer
|
|
|
|
// size is the maximum number of metrics that Buffer will cache. If Add is
|
|
|
|
// called when the buffer is full, then the oldest metric(s) will be dropped.
|
|
|
|
func NewBuffer(size int) *Buffer {
|
|
|
|
return &Buffer{
|
|
|
|
buf: make(chan telegraf.Metric, size),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsEmpty returns true if Buffer is empty.
|
|
|
|
func (b *Buffer) IsEmpty() bool {
|
|
|
|
return len(b.buf) == 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// Len returns the current length of the buffer.
|
|
|
|
func (b *Buffer) Len() int {
|
|
|
|
return len(b.buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add adds metrics to the buffer.
|
|
|
|
func (b *Buffer) Add(metrics ...telegraf.Metric) {
|
|
|
|
for i, _ := range metrics {
|
2016-11-07 08:34:46 +00:00
|
|
|
MetricsWritten.Incr(1)
|
2016-04-25 23:49:06 +00:00
|
|
|
select {
|
|
|
|
case b.buf <- metrics[i]:
|
|
|
|
default:
|
2017-03-31 19:45:28 +00:00
|
|
|
b.mu.Lock()
|
2016-11-07 08:34:46 +00:00
|
|
|
MetricsDropped.Incr(1)
|
2016-04-25 23:49:06 +00:00
|
|
|
<-b.buf
|
|
|
|
b.buf <- metrics[i]
|
2017-03-31 19:45:28 +00:00
|
|
|
b.mu.Unlock()
|
2016-04-25 23:49:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Batch returns a batch of metrics of size batchSize.
|
|
|
|
// the batch will be of maximum length batchSize. It can be less than batchSize,
|
|
|
|
// if the length of Buffer is less than batchSize.
|
|
|
|
func (b *Buffer) Batch(batchSize int) []telegraf.Metric {
|
2016-10-24 15:15:46 +00:00
|
|
|
b.mu.Lock()
|
2016-04-25 23:49:06 +00:00
|
|
|
n := min(len(b.buf), batchSize)
|
|
|
|
out := make([]telegraf.Metric, n)
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
out[i] = <-b.buf
|
|
|
|
}
|
2016-10-24 15:15:46 +00:00
|
|
|
b.mu.Unlock()
|
2016-04-25 23:49:06 +00:00
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
|
|
|
func min(a, b int) int {
|
|
|
|
if b < a {
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
return a
|
|
|
|
}
|