graphite.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package graphite
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "time"
  11. "github.com/grafana/grafana/pkg/components/simplejson"
  12. "github.com/grafana/grafana/pkg/log"
  13. m "github.com/grafana/grafana/pkg/models"
  14. "github.com/grafana/grafana/pkg/util"
  15. )
  16. type GraphiteClient struct{}
  17. type GraphiteSerie struct {
  18. Datapoints [][2]float64
  19. Target string
  20. }
  21. var DefaultClient = &http.Client{
  22. Timeout: time.Minute,
  23. }
  24. type GraphiteResponse []GraphiteSerie
  25. func (client GraphiteClient) GetSeries(rule m.AlertJob, datasource m.DataSource) (m.TimeSeriesSlice, error) {
  26. v := url.Values{
  27. "format": []string{"json"},
  28. "target": []string{getTargetFromRule(rule.Rule)},
  29. "until": []string{"now"},
  30. "from": []string{"-" + strconv.Itoa(rule.Rule.QueryRange) + "s"},
  31. }
  32. log.Trace("Graphite: sending request with querystring: ", v.Encode())
  33. req, err := http.NewRequest("POST", datasource.Url+"/render", nil)
  34. if err != nil {
  35. return nil, fmt.Errorf("Could not create request")
  36. }
  37. req.Body = ioutil.NopCloser(bytes.NewReader([]byte(v.Encode())))
  38. if datasource.BasicAuth {
  39. req.Header.Add("Authorization", util.GetBasicAuthHeader(datasource.User, datasource.Password))
  40. }
  41. res, err := DefaultClient.Do(req)
  42. if err != nil {
  43. return nil, err
  44. }
  45. if res.StatusCode != http.StatusOK {
  46. return nil, fmt.Errorf("expected httpstatus 200, found %d", res.StatusCode)
  47. }
  48. response := GraphiteResponse{}
  49. json.NewDecoder(res.Body).Decode(&response)
  50. var timeSeries []*m.TimeSeries
  51. for _, v := range response {
  52. timeSeries = append(timeSeries, m.NewTimeSeries(v.Target, v.Datapoints))
  53. }
  54. return timeSeries, nil
  55. }
  56. func getTargetFromRule(rule m.AlertRule) string {
  57. json, _ := simplejson.NewJson([]byte(rule.Query))
  58. return json.Get("target").MustString()
  59. }