grafana/pkg/services/alerting/reader.go

67 lines
1.3 KiB
Go
Raw Normal View History

2016-06-06 07:24:14 -05:00
package alerting
import (
"sync"
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/metrics"
2016-06-06 07:24:14 -05:00
m "github.com/grafana/grafana/pkg/models"
)
type RuleReader interface {
2016-07-27 09:29:28 -05:00
Fetch() []*Rule
2016-06-06 07:24:14 -05:00
}
2016-07-27 09:29:28 -05:00
type DefaultRuleReader struct {
2016-06-06 07:24:14 -05:00
sync.RWMutex
2018-04-18 15:23:49 -05:00
//serverID string
2016-06-06 07:24:14 -05:00
serverPosition int
clusterSize int
log log.Logger
2016-06-06 07:24:14 -05:00
}
2016-07-27 09:29:28 -05:00
func NewRuleReader() *DefaultRuleReader {
ruleReader := &DefaultRuleReader{
log: log.New("alerting.ruleReader"),
}
2016-06-06 07:24:14 -05:00
go ruleReader.initReader()
return ruleReader
}
2016-07-27 09:29:28 -05:00
func (arr *DefaultRuleReader) initReader() {
2016-06-06 07:24:14 -05:00
heartbeat := time.NewTicker(time.Second * 10)
for range heartbeat.C {
arr.heartbeat()
2016-06-06 07:24:14 -05:00
}
}
2016-07-27 09:29:28 -05:00
func (arr *DefaultRuleReader) Fetch() []*Rule {
2016-06-06 07:24:14 -05:00
cmd := &m.GetAllAlertsQuery{}
if err := bus.Dispatch(cmd); err != nil {
arr.log.Error("Could not load alerts", "error", err)
2016-07-27 09:29:28 -05:00
return []*Rule{}
2016-06-06 07:24:14 -05:00
}
2016-07-27 09:29:28 -05:00
res := make([]*Rule, 0)
for _, ruleDef := range cmd.Result {
2016-07-27 09:29:28 -05:00
if model, err := NewRuleFromDBAlert(ruleDef); err != nil {
arr.log.Error("Could not build alert model for rule", "ruleId", ruleDef.Id, "error", err)
} else {
res = append(res, model)
}
2016-06-06 07:24:14 -05:00
}
2017-09-06 04:23:52 -05:00
metrics.M_Alerting_Active_Alerts.Set(float64(len(res)))
2016-06-06 07:24:14 -05:00
return res
}
2016-07-27 09:29:28 -05:00
func (arr *DefaultRuleReader) heartbeat() {
2016-06-06 07:24:14 -05:00
arr.clusterSize = 1
arr.serverPosition = 1
}