grafana/pkg/services/alerting/test_rule.go
Marcus Efraimsson 5713048f48
Alerting: Improve alert rule testing (#16286)
* tsdb: add support for setting debug flag of tsdb query

* alerting: adds debug flag in eval context

Debug flag is set when testing an alert rule and this debug
flag is used to return more debug information in test aler rule
response. This debug flag is also provided to tsdb queries so
datasources can optionally add support for returning additional
debug data

* alerting: improve test alert rule ui

Adds buttons for expand/collapse json and copy json to clipboard,
very similar to how the query inspector works.

* elasticsearch: implement support for tsdb query debug flag

* elasticsearch: embedding client response in struct

* alerting: return proper query model when testing rule
2019-06-25 08:52:17 +02:00

64 lines
1.2 KiB
Go

package alerting
import (
"context"
"fmt"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
)
// AlertTestCommand initiates an test evaluation
// of an alert rule.
type AlertTestCommand struct {
Dashboard *simplejson.Json
PanelID int64
OrgID int64
User *models.SignedInUser
Result *EvalContext
}
func init() {
bus.AddHandler("alerting", handleAlertTestCommand)
}
func handleAlertTestCommand(cmd *AlertTestCommand) error {
dash := models.NewDashboardFromJson(cmd.Dashboard)
extractor := NewDashAlertExtractor(dash, cmd.OrgID, cmd.User)
alerts, err := extractor.GetAlerts()
if err != nil {
return err
}
for _, alert := range alerts {
if alert.PanelId == cmd.PanelID {
rule, err := NewRuleFromDBAlert(alert)
if err != nil {
return err
}
cmd.Result = testAlertRule(rule)
return nil
}
}
return fmt.Errorf("Could not find alert with panel id %d", cmd.PanelID)
}
func testAlertRule(rule *Rule) *EvalContext {
handler := NewEvalHandler()
context := NewEvalContext(context.Background(), rule)
context.IsTestRun = true
context.IsDebug = true
handler.Eval(context)
context.Rule.State = context.GetNewState()
return context
}