graphite.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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{formatTimeRange(context.TimeRange.To)},
  28. "format": []string{"json"},
  29. "maxDataPoints": []string{"500"},
  30. }
  31. for _, query := range queries {
  32. params["target"] = []string{query.Query}
  33. glog.Debug("Graphite request", "query", query.Query)
  34. }
  35. client := http.Client{Timeout: time.Duration(10 * time.Second)}
  36. res, err := client.PostForm(e.Url+"/render?", params)
  37. if err != nil {
  38. result.Error = err
  39. return result
  40. }
  41. defer res.Body.Close()
  42. body, err := ioutil.ReadAll(res.Body)
  43. if err != nil {
  44. result.Error = err
  45. return result
  46. }
  47. var data []TargetResponseDTO
  48. err = json.Unmarshal(body, &data)
  49. if err != nil {
  50. glog.Info("Failed to unmarshal graphite response", "error", err, "body", string(body))
  51. result.Error = err
  52. return result
  53. }
  54. result.QueryResults = make(map[string]*tsdb.QueryResult)
  55. queryRes := &tsdb.QueryResult{}
  56. for _, series := range data {
  57. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  58. Name: series.Target,
  59. Points: series.DataPoints,
  60. })
  61. }
  62. result.QueryResults["A"] = queryRes
  63. return result
  64. }
  65. func formatTimeRange(input string) string {
  66. if input == "now" {
  67. return input
  68. }
  69. return strings.Replace(strings.Replace(input, "m", "min", -1), "M", "mon", -1)
  70. }