query.go 4.9 KB

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