graphite.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package graphite
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "strconv"
  7. "time"
  8. "github.com/franela/goreq"
  9. "github.com/grafana/grafana/pkg/cmd/grafana-cli/log"
  10. "github.com/grafana/grafana/pkg/components/simplejson"
  11. m "github.com/grafana/grafana/pkg/models"
  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, datasource m.DataSource) (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: 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. }