query.go 4.7 KB

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