query.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package conditions
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/components/simplejson"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/services/alerting"
  10. "github.com/grafana/grafana/pkg/tsdb"
  11. )
  12. func init() {
  13. alerting.RegisterCondition("query", func(model *simplejson.Json, index int) (alerting.Condition, error) {
  14. return NewQueryCondition(model, index)
  15. })
  16. }
  17. type QueryCondition struct {
  18. Index int
  19. Query AlertQuery
  20. Reducer QueryReducer
  21. Evaluator AlertEvaluator
  22. Operator string
  23. HandleRequest tsdb.HandleRequestFunc
  24. }
  25. type AlertQuery struct {
  26. Model *simplejson.Json
  27. DatasourceId int64
  28. From string
  29. To string
  30. }
  31. func (c *QueryCondition) Eval(context *alerting.EvalContext) (*alerting.ConditionResult, error) {
  32. timeRange := tsdb.NewTimeRange(c.Query.From, c.Query.To)
  33. seriesList, err := c.executeQuery(context, timeRange)
  34. if err != nil {
  35. return nil, err
  36. }
  37. emptySerieCount := 0
  38. evalMatchCount := 0
  39. var matches []*alerting.EvalMatch
  40. for _, series := range seriesList {
  41. reducedValue := c.Reducer.Reduce(series)
  42. evalMatch := c.Evaluator.Eval(reducedValue)
  43. if reducedValue.Valid == false {
  44. emptySerieCount++
  45. continue
  46. }
  47. if context.IsTestRun {
  48. context.Logs = append(context.Logs, &alerting.ResultLogEntry{
  49. Message: fmt.Sprintf("Condition[%d]: Eval: %v, Metric: %s, Value: %1.3f", c.Index, evalMatch, series.Name, reducedValue.Float64),
  50. })
  51. }
  52. if evalMatch {
  53. evalMatchCount++
  54. matches = append(matches, &alerting.EvalMatch{
  55. Metric: series.Name,
  56. Value: reducedValue.Float64,
  57. })
  58. }
  59. }
  60. return &alerting.ConditionResult{
  61. Firing: evalMatchCount > 0,
  62. NoDataFound: emptySerieCount == len(seriesList),
  63. Operator: c.Operator,
  64. EvalMatches: matches,
  65. }, nil
  66. }
  67. func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *tsdb.TimeRange) (tsdb.TimeSeriesSlice, error) {
  68. getDsInfo := &m.GetDataSourceByIdQuery{
  69. Id: c.Query.DatasourceId,
  70. OrgId: context.Rule.OrgId,
  71. }
  72. if err := bus.Dispatch(getDsInfo); err != nil {
  73. return nil, fmt.Errorf("Could not find datasource")
  74. }
  75. req := c.getRequestForAlertRule(getDsInfo.Result, timeRange)
  76. result := make(tsdb.TimeSeriesSlice, 0)
  77. resp, err := c.HandleRequest(context.Ctx, req)
  78. if err != nil {
  79. return nil, fmt.Errorf("tsdb.HandleRequest() error %v", err)
  80. }
  81. for _, v := range resp.Results {
  82. if v.Error != nil {
  83. return nil, fmt.Errorf("tsdb.HandleRequest() response error %v", v)
  84. }
  85. result = append(result, v.Series...)
  86. if context.IsTestRun {
  87. context.Logs = append(context.Logs, &alerting.ResultLogEntry{
  88. Message: fmt.Sprintf("Condition[%d]: Query Result", c.Index),
  89. Data: v.Series,
  90. })
  91. }
  92. }
  93. return result, nil
  94. }
  95. func (c *QueryCondition) getRequestForAlertRule(datasource *m.DataSource, timeRange *tsdb.TimeRange) *tsdb.Request {
  96. req := &tsdb.Request{
  97. TimeRange: timeRange,
  98. Queries: []*tsdb.Query{
  99. {
  100. RefId: "A",
  101. Model: c.Query.Model,
  102. DataSource: datasource,
  103. },
  104. },
  105. }
  106. return req
  107. }
  108. func NewQueryCondition(model *simplejson.Json, index int) (*QueryCondition, error) {
  109. condition := QueryCondition{}
  110. condition.Index = index
  111. condition.HandleRequest = tsdb.HandleRequest
  112. queryJson := model.Get("query")
  113. condition.Query.Model = queryJson.Get("model")
  114. condition.Query.From = queryJson.Get("params").MustArray()[1].(string)
  115. condition.Query.To = queryJson.Get("params").MustArray()[2].(string)
  116. if err := validateFromValue(condition.Query.From); err != nil {
  117. return nil, err
  118. }
  119. if err := validateToValue(condition.Query.To); err != nil {
  120. return nil, err
  121. }
  122. condition.Query.DatasourceId = queryJson.Get("datasourceId").MustInt64()
  123. reducerJson := model.Get("reducer")
  124. condition.Reducer = NewSimpleReducer(reducerJson.Get("type").MustString())
  125. evaluatorJson := model.Get("evaluator")
  126. evaluator, err := NewAlertEvaluator(evaluatorJson)
  127. if err != nil {
  128. return nil, err
  129. }
  130. condition.Evaluator = evaluator
  131. operatorJson := model.Get("operator")
  132. operator := operatorJson.Get("type").MustString("and")
  133. condition.Operator = operator
  134. return &condition, nil
  135. }
  136. func validateFromValue(from string) error {
  137. fromRaw := strings.Replace(from, "now-", "", 1)
  138. _, err := time.ParseDuration("-" + fromRaw)
  139. return err
  140. }
  141. func validateToValue(to string) error {
  142. if to == "now" {
  143. return nil
  144. } else if strings.HasPrefix(to, "now-") {
  145. withoutNow := strings.Replace(to, "now-", "", 1)
  146. _, err := time.ParseDuration("-" + withoutNow)
  147. if err == nil {
  148. return nil
  149. }
  150. }
  151. _, err := time.ParseDuration(to)
  152. return err
  153. }