query.go 5.6 KB

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