graphite.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. req, _ := http.NewRequest(http.MethodPost, e.Url+"/render?", strings.NewReader(params.Encode()))
  37. if e.BasicAuth {
  38. req.SetBasicAuth("carl", "carl")
  39. }
  40. res, err := client.Do(req)
  41. if err != nil {
  42. result.Error = err
  43. return result
  44. }
  45. defer res.Body.Close()
  46. body, err := ioutil.ReadAll(res.Body)
  47. if err != nil {
  48. result.Error = err
  49. return result
  50. }
  51. var data []TargetResponseDTO
  52. err = json.Unmarshal(body, &data)
  53. if err != nil {
  54. glog.Info("Failed to unmarshal graphite response", "error", err, "body", string(body))
  55. result.Error = err
  56. return result
  57. }
  58. result.QueryResults = make(map[string]*tsdb.QueryResult)
  59. queryRes := &tsdb.QueryResult{}
  60. for _, series := range data {
  61. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  62. Name: series.Target,
  63. Points: series.DataPoints,
  64. })
  65. }
  66. result.QueryResults["A"] = queryRes
  67. return result
  68. }
  69. func formatTimeRange(input string) string {
  70. if input == "now" {
  71. return input
  72. }
  73. return strings.Replace(strings.Replace(input, "m", "min", -1), "M", "mon", -1)
  74. }