graphite.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package graphite
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "time"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/tsdb"
  11. )
  12. type GraphiteExecutor struct {
  13. *tsdb.DataSourceInfo
  14. }
  15. func NewGraphiteExecutor(dsInfo *tsdb.DataSourceInfo) tsdb.Executor {
  16. return &GraphiteExecutor{dsInfo}
  17. }
  18. var glog log.Logger
  19. func init() {
  20. glog = log.New("tsdb.graphite")
  21. tsdb.RegisterExecutor("graphite", NewGraphiteExecutor)
  22. }
  23. func (e *GraphiteExecutor) Execute(queries tsdb.QuerySlice, context *tsdb.QueryContext) *tsdb.BatchResult {
  24. result := &tsdb.BatchResult{}
  25. params := url.Values{
  26. "from": []string{formatTimeRange(context.TimeRange.From)},
  27. "until": []string{context.TimeRange.To},
  28. "format": []string{"json"},
  29. "maxDataPoints": []string{"500"},
  30. }
  31. for _, query := range queries {
  32. params["target"] = []string{
  33. query.Query,
  34. }
  35. }
  36. client := http.Client{Timeout: time.Duration(10 * time.Second)}
  37. res, err := client.PostForm(e.Url+"/render?", params)
  38. if err != nil {
  39. result.Error = err
  40. return result
  41. }
  42. defer res.Body.Close()
  43. body, err := ioutil.ReadAll(res.Body)
  44. if err != nil {
  45. result.Error = err
  46. return result
  47. }
  48. var data []TargetResponseDTO
  49. err = json.Unmarshal(body, &data)
  50. if err != nil {
  51. glog.Info("Failed to unmarshal graphite response", "error", err, "body", string(body))
  52. result.Error = err
  53. return result
  54. }
  55. result.QueryResults = make(map[string]*tsdb.QueryResult)
  56. queryRes := &tsdb.QueryResult{}
  57. for _, series := range data {
  58. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  59. Name: series.Target,
  60. Points: series.DataPoints,
  61. })
  62. }
  63. result.QueryResults["A"] = queryRes
  64. return result
  65. }
  66. func formatTimeRange(input string) string {
  67. return strings.Replace(strings.Replace(input, "m", "min", -1), "M", "mon", -1)
  68. }