sampler-fork/data/sampler.go

64 lines
1.2 KiB
Go
Raw Normal View History

2019-01-31 00:02:38 +00:00
package data
import (
2019-03-21 02:23:08 +00:00
"github.com/sqshq/sampler/config"
2019-01-31 00:02:38 +00:00
"time"
)
2019-02-03 04:11:26 +00:00
type Sampler struct {
2019-03-16 23:59:28 +00:00
consumer *Consumer
2019-04-07 15:09:24 +00:00
items []*Item
triggers []*Trigger
2019-03-16 23:59:28 +00:00
triggersChannel chan *Sample
2019-01-31 00:02:38 +00:00
}
2019-04-07 15:09:24 +00:00
func NewSampler(consumer *Consumer, items []*Item, triggers []*Trigger, options config.Options, rateMs int) Sampler {
2019-01-31 00:02:38 +00:00
2019-03-21 02:23:08 +00:00
ticker := time.NewTicker(time.Duration(rateMs * int(time.Millisecond)))
sampler := Sampler{
consumer,
items,
triggers,
2019-03-16 23:59:28 +00:00
make(chan *Sample),
}
2019-01-31 00:02:38 +00:00
go func() {
for ; true; <-ticker.C {
for _, item := range sampler.items {
2019-03-21 02:23:08 +00:00
go sampler.sample(item, options)
}
}
}()
go func() {
for {
select {
case sample := <-sampler.triggersChannel:
for _, t := range sampler.triggers {
t.Execute(sample)
}
}
2019-01-31 00:02:38 +00:00
}
}()
2019-02-03 04:11:26 +00:00
return sampler
2019-01-31 00:02:38 +00:00
}
2019-04-07 15:09:24 +00:00
func (s *Sampler) sample(item *Item, options config.Options) {
2019-03-09 01:00:13 +00:00
2019-03-21 02:23:08 +00:00
val, err := item.nextValue(options.Variables)
2019-03-09 01:00:13 +00:00
2019-04-07 15:09:24 +00:00
if len(val) > 0 {
2019-03-16 23:59:28 +00:00
sample := &Sample{Label: item.Label, Value: val, Color: item.Color}
s.consumer.SampleChannel <- sample
s.triggersChannel <- sample
2019-04-07 15:09:24 +00:00
} else if err != nil {
2019-03-16 23:59:28 +00:00
s.consumer.AlertChannel <- &Alert{
Title: "SAMPLING FAILURE",
2019-03-22 03:21:00 +00:00
Text: getErrorMessage(err),
2019-03-13 03:15:55 +00:00
Color: item.Color,
}
2019-03-08 04:04:46 +00:00
}
2019-01-31 00:02:38 +00:00
}