Alerting: Display query from grafana-managed alert rules on /api/v1/rules (#45969)

* Aleting: Extract query from alerting rule model for api/v1/rules

* more changes and fixtures

* appease the linter
This commit is contained in:
gotjosh
2022-03-14 10:39:20 +00:00
committed by GitHub
parent ecf84be65a
commit a75d4fcbd8
7 changed files with 533 additions and 28 deletions
+57 -4
View File
@@ -34,8 +34,9 @@ func NewFakeRuleStore(t *testing.T) *FakeRuleStore {
// FakeRuleStore mocks the RuleStore of the scheduler.
type FakeRuleStore struct {
t *testing.T
mtx sync.Mutex
t *testing.T
mtx sync.Mutex
// OrgID -> RuleGroup -> Namespace -> Rules
Rules map[int64]map[string]map[string][]*models.AlertRule
Hook func(cmd interface{}) error // use Hook if you need to intercept some query and return an error
RecordedOps []interface{}
@@ -141,10 +142,25 @@ func (f *FakeRuleStore) GetAlertRulesForScheduling(_ context.Context, q *models.
return nil
}
func (f *FakeRuleStore) GetOrgAlertRules(_ context.Context, q *models.ListAlertRulesQuery) error {
f.mtx.Lock()
defer f.mtx.Unlock()
f.RecordedOps = append(f.RecordedOps, *q)
if _, ok := f.Rules[q.OrgID]; !ok {
return nil
}
var rules []*models.AlertRule
for ruleGroup := range f.Rules[q.OrgID] {
for _, storedRules := range f.Rules[q.OrgID][ruleGroup] {
rules = append(rules, storedRules...)
}
}
q.Result = rules
return nil
}
func (f *FakeRuleStore) GetNamespaceAlertRules(_ context.Context, q *models.ListNamespaceAlertRulesQuery) error {
@@ -185,8 +201,24 @@ func (f *FakeRuleStore) GetRuleGroupAlertRules(_ context.Context, q *models.List
return nil
}
func (f *FakeRuleStore) GetNamespaces(_ context.Context, _ int64, _ *models2.SignedInUser) (map[string]*models2.Folder, error) {
return nil, nil
func (f *FakeRuleStore) GetNamespaces(_ context.Context, orgID int64, _ *models2.SignedInUser) (map[string]*models2.Folder, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
namespacesMap := map[string]*models2.Folder{}
_, ok := f.Rules[orgID]
if !ok {
return namespacesMap, nil
}
for rg := range f.Rules[orgID] {
for namespace := range f.Rules[orgID][rg] {
namespacesMap[namespace] = &models2.Folder{}
}
}
return namespacesMap, nil
}
func (f *FakeRuleStore) GetNamespaceByTitle(_ context.Context, _ string, _ int64, _ *models2.SignedInUser, _ bool) (*models2.Folder, error) {
return nil, nil
@@ -198,6 +230,27 @@ func (f *FakeRuleStore) GetOrgRuleGroups(_ context.Context, q *models.ListOrgRul
if err := f.Hook(*q); err != nil {
return err
}
// If we have namespaces, we want to try and retrieve the list of rules stored.
if len(q.NamespaceUIDs) != 0 {
_, ok := f.Rules[q.OrgID]
if !ok {
return nil
}
var ruleGroups [][]string
for rg := range f.Rules[q.OrgID] {
for storedNamespace := range f.Rules[q.OrgID][rg] {
for _, namespace := range q.NamespaceUIDs {
if storedNamespace == namespace { // if they match, they should go in.
ruleGroups = append(ruleGroups, []string{rg, storedNamespace, storedNamespace})
}
}
}
}
q.Result = ruleGroups
}
return nil
}