graphite.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package graphite
  2. import (
  3. "fmt"
  4. "github.com/franela/goreq"
  5. "github.com/grafana/grafana/pkg/cmd/grafana-cli/log"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "time"
  12. )
  13. type GraphiteClient struct{}
  14. type GraphiteSerie struct {
  15. Datapoints [][2]float64
  16. Target string
  17. }
  18. type GraphiteResponse []GraphiteSerie
  19. func (this GraphiteClient) GetSeries(rule *m.AlertJob) (m.TimeSeriesSlice, error) {
  20. v := url.Values{
  21. "format": []string{"json"},
  22. "target": []string{getTargetFromRule(rule.Rule)},
  23. "until": []string{"now"},
  24. "from": []string{"-" + strconv.Itoa(rule.Rule.QueryRange) + "s"},
  25. }
  26. log.Debug("Graphite: sending request with querystring: ", v.Encode())
  27. res, err := goreq.Request{
  28. Method: "POST",
  29. Uri: rule.Datasource.Url + "/render",
  30. Body: v.Encode(),
  31. Timeout: 5 * time.Second,
  32. }.Do()
  33. response := GraphiteResponse{}
  34. res.Body.FromJsonTo(&response)
  35. if err != nil {
  36. return nil, err
  37. }
  38. if res.StatusCode != http.StatusOK {
  39. return nil, fmt.Errorf("expected httpstatus 200, found %d", res.StatusCode)
  40. }
  41. timeSeries := make([]*m.TimeSeries, 0)
  42. for _, v := range response {
  43. timeSeries = append(timeSeries, m.NewTimeSeries(v.Target, v.Datapoints))
  44. }
  45. return timeSeries, nil
  46. }
  47. func getTargetFromRule(rule m.AlertRule) string {
  48. json, _ := simplejson.NewJson([]byte(rule.Query))
  49. return json.Get("target").MustString()
  50. }