graphite.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package graphite
  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. "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.AlertRule) (m.TimeSeriesSlice, error) {
  20. query := &m.GetDataSourceByIdQuery{Id: rule.DatasourceId, OrgId: rule.OrgId}
  21. if err := bus.Dispatch(query); err != nil {
  22. return nil, err
  23. }
  24. v := url.Values{
  25. "format": []string{"json"},
  26. "target": []string{getTargetFromRule(rule)},
  27. "until": []string{"now"},
  28. "from": []string{"-" + strconv.Itoa(rule.QueryRange) + "s"},
  29. }
  30. res, err := goreq.Request{
  31. Method: "POST",
  32. Uri: query.Result.Url + "/render",
  33. Body: v.Encode(),
  34. Timeout: 500 * time.Millisecond,
  35. }.Do()
  36. response := GraphiteResponse{}
  37. res.Body.FromJsonTo(&response)
  38. if err != nil {
  39. return nil, err
  40. }
  41. if res.StatusCode != http.StatusOK {
  42. return nil, fmt.Errorf("expected httpstatus 200, found %d", res.StatusCode)
  43. }
  44. timeSeries := make([]*m.TimeSeries, 0)
  45. for _, v := range response {
  46. timeSeries = append(timeSeries, m.NewTimeSeries(v.Target, v.Datapoints))
  47. }
  48. return timeSeries, nil
  49. }
  50. func getTargetFromRule(rule m.AlertRule) string {
  51. json, _ := simplejson.NewJson([]byte(rule.Query))
  52. return json.Get("target").MustString()
  53. }