2019-01-31 00:02:38 +00:00
|
|
|
package data
|
|
|
|
|
|
|
|
import (
|
2019-03-17 03:13:14 +00:00
|
|
|
"os/exec"
|
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-03-10 04:41:23 +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-03-16 23:59:28 +00:00
|
|
|
func NewSampler(consumer *Consumer, items []Item, triggers []Trigger, rateMs int) Sampler {
|
2019-01-31 00:02:38 +00:00
|
|
|
|
2019-03-10 04:41:23 +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-03-10 04:41:23 +00:00
|
|
|
}
|
2019-01-31 00:02:38 +00:00
|
|
|
|
|
|
|
go func() {
|
2019-02-17 01:54:48 +00:00
|
|
|
for ; true; <-ticker.C {
|
2019-03-10 04:41:23 +00:00
|
|
|
for _, item := range sampler.items {
|
|
|
|
go sampler.sample(item)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
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-03-10 04:41:23 +00:00
|
|
|
func (s *Sampler) sample(item Item) {
|
2019-03-09 01:00:13 +00:00
|
|
|
|
2019-03-10 04:41:23 +00:00
|
|
|
val, err := item.nextValue()
|
2019-03-09 01:00:13 +00:00
|
|
|
|
2019-03-10 04:41:23 +00:00
|
|
|
if err == nil {
|
2019-03-16 23:59:28 +00:00
|
|
|
sample := &Sample{Label: item.Label, Value: val, Color: item.Color}
|
2019-03-10 04:41:23 +00:00
|
|
|
s.consumer.SampleChannel <- sample
|
|
|
|
s.triggersChannel <- sample
|
2019-03-08 04:04:46 +00:00
|
|
|
} else {
|
2019-03-16 23:59:28 +00:00
|
|
|
s.consumer.AlertChannel <- &Alert{
|
2019-03-10 04:41:23 +00:00
|
|
|
Title: "SAMPLING FAILURE",
|
2019-03-17 03:13:14 +00:00
|
|
|
Text: getErrorMessage(err.(*exec.ExitError)),
|
2019-03-13 03:15:55 +00:00
|
|
|
Color: item.Color,
|
2019-03-10 04:41:23 +00:00
|
|
|
}
|
2019-03-08 04:04:46 +00:00
|
|
|
}
|
2019-01-31 00:02:38 +00:00
|
|
|
}
|