query.go 5.1 KB

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