From 9ccedc0407bea680717e49167a4f58c29a2f8d62 Mon Sep 17 00:00:00 2001 From: Owen Diehl Date: Wed, 22 Jul 2020 10:19:34 -0400 Subject: [PATCH] Arbitrary rule & group loading (#7569) * allows loading rule groups via an interface Signed-off-by: Owen Diehl --- rules/manager.go | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/rules/manager.go b/rules/manager.go index 8cfb07164..c4344fa68 100644 --- a/rules/manager.go +++ b/rules/manager.go @@ -852,6 +852,7 @@ type ManagerOptions struct { OutageTolerance time.Duration ForGracePeriod time.Duration ResendDelay time.Duration + GroupLoader GroupLoader Metrics *Metrics } @@ -863,6 +864,10 @@ func NewManager(o *ManagerOptions) *Manager { o.Metrics = NewGroupMetrics(o.Registerer) } + if o.GroupLoader == nil { + o.GroupLoader = FileLoader{} + } + m := &Manager{ groups: map[string]*Group{}, opts: o, @@ -974,6 +979,22 @@ func (m *Manager) Update(interval time.Duration, files []string, externalLabels return nil } +// GroupLoader is responsible for loading rule groups from arbitrary sources and parsing them. +type GroupLoader interface { + Load(identifier string) (*rulefmt.RuleGroups, []error) + Parse(query string) (parser.Expr, error) +} + +// FileLoader is the default GroupLoader implementation. It defers to rulefmt.ParseFile +// and parser.ParseExpr +type FileLoader struct{} + +func (FileLoader) Load(identifier string) (*rulefmt.RuleGroups, []error) { + return rulefmt.ParseFile(identifier) +} + +func (FileLoader) Parse(query string) (parser.Expr, error) { return parser.ParseExpr(query) } + // LoadGroups reads groups from a list of files. func (m *Manager) LoadGroups( interval time.Duration, externalLabels labels.Labels, filenames ...string, @@ -983,7 +1004,7 @@ func (m *Manager) LoadGroups( shouldRestore := !m.restored for _, fn := range filenames { - rgs, errs := rulefmt.ParseFile(fn) + rgs, errs := m.opts.GroupLoader.Load(fn) if errs != nil { return nil, errs } @@ -996,7 +1017,7 @@ func (m *Manager) LoadGroups( rules := make([]Rule, 0, len(rg.Rules)) for _, r := range rg.Rules { - expr, err := parser.ParseExpr(r.Expr.Value) + expr, err := m.opts.GroupLoader.Parse(r.Expr.Value) if err != nil { return nil, []error{errors.Wrap(err, fn)} }