graphite_executor.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package alerting
  2. import (
  3. "fmt"
  4. "github.com/franela/goreq"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "net/http"
  9. "net/url"
  10. "time"
  11. )
  12. type GraphiteExecutor struct{}
  13. type GraphiteSerie struct {
  14. Datapoints [][2]float64
  15. Target string
  16. }
  17. type GraphiteResponse []GraphiteSerie
  18. func (this *GraphiteExecutor) Execute(rule m.AlertRule, responseQueue chan *AlertResult) {
  19. response, err := this.getSeries(rule)
  20. if err != nil {
  21. responseQueue <- &AlertResult{State: "CRITICAL", Id: rule.Id}
  22. }
  23. responseQueue <- this.executeRules(response, rule)
  24. }
  25. func (this *GraphiteExecutor) getSeries(rule m.AlertRule) (GraphiteResponse, error) {
  26. query := &m.GetDataSourceByIdQuery{Id: rule.DatasourceId, OrgId: rule.OrgId}
  27. if err := bus.Dispatch(query); err != nil {
  28. return nil, err
  29. }
  30. v := url.Values{
  31. "format": []string{"json"},
  32. "target": []string{getTargetFromRule(rule)},
  33. "until": []string{"now"},
  34. "from": []string{"-" + rule.QueryRange},
  35. }
  36. res, err := goreq.Request{
  37. Method: "POST",
  38. Uri: query.Result.Url + "/render",
  39. Body: v.Encode(),
  40. Timeout: 500 * time.Millisecond,
  41. }.Do()
  42. response := GraphiteResponse{}
  43. res.Body.FromJsonTo(&response)
  44. if err != nil {
  45. return nil, err
  46. }
  47. if res.StatusCode != http.StatusOK {
  48. return nil, fmt.Errorf("error!")
  49. }
  50. return response, nil
  51. }
  52. func getTargetFromRule(rule m.AlertRule) string {
  53. json, _ := simplejson.NewJson([]byte(rule.Query))
  54. return json.Get("target").MustString()
  55. }