sampler-fork/data/sampler.go

79 lines
1.6 KiB
Go
Raw Normal View History

2019-01-31 00:02:38 +00:00
package data
import (
2019-04-09 02:04:08 +00:00
"fmt"
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-04-09 02:04:08 +00:00
variables []string
2019-01-31 00:02:38 +00:00
}
2019-04-09 02:04:08 +00:00
func NewSampler(consumer *Consumer, items []*Item, triggers []*Trigger, options config.Options, fileVariables map[string]string, 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-05-24 02:58:46 +00:00
mergeVariables(fileVariables, options.Environment),
}
2019-01-31 00:02:38 +00:00
go func() {
for ; true; <-ticker.C {
for _, item := range sampler.items {
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-04-09 02:04:08 +00:00
val, err := item.nextValue(s.variables)
2019-03-09 01:00:13 +00:00
2019-04-07 15:09:24 +00:00
if len(val) > 0 {
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),
Color: item.color,
}
2019-03-08 04:04:46 +00:00
}
2019-01-31 00:02:38 +00:00
}
2019-04-09 02:04:08 +00:00
// option variables takes precedence over the file variables with the same name
func mergeVariables(fileVariables map[string]string, optionsVariables []string) []string {
result := optionsVariables
for key, value := range fileVariables {
result = append([]string{fmt.Sprintf("%s=%s", key, value)}, result...)
}
return result
}