graphite.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package graphite
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. "github.com/Unknwon/log"
  9. "github.com/grafana/grafana/pkg/components/simplejson"
  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. func init() {
  19. tsdb.RegisterExecutor("graphite", NewGraphiteExecutor)
  20. }
  21. func (e *GraphiteExecutor) Execute(queries tsdb.QuerySlice, context *tsdb.QueryContext) *tsdb.BatchResult {
  22. result := &tsdb.BatchResult{}
  23. params := url.Values{
  24. "from": []string{context.TimeRange.From},
  25. "until": []string{context.TimeRange.To},
  26. "format": []string{"json"},
  27. "maxDataPoints": []string{"500"},
  28. }
  29. for _, query := range queries {
  30. params["target"] = []string{
  31. getTargetFromQuery(query.Query),
  32. }
  33. }
  34. client := http.Client{Timeout: time.Duration(10 * time.Second)}
  35. res, err := client.PostForm(e.Url+"/render?", params)
  36. if err != nil {
  37. result.Error = err
  38. return result
  39. }
  40. defer res.Body.Close()
  41. body, err := ioutil.ReadAll(res.Body)
  42. if err != nil {
  43. result.Error = err
  44. return result
  45. }
  46. var data []TargetResponseDTO
  47. err = json.Unmarshal(body, &data)
  48. if err != nil {
  49. log.Info("Error: %v", string(body))
  50. result.Error = err
  51. return result
  52. }
  53. result.QueryResults = make(map[string]*tsdb.QueryResult)
  54. queryRes := &tsdb.QueryResult{}
  55. for _, series := range data {
  56. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  57. Name: series.Target,
  58. Points: series.DataPoints,
  59. })
  60. }
  61. result.QueryResults["A"] = queryRes
  62. return result
  63. }
  64. func getTargetFromQuery(query string) string {
  65. json, _ := simplejson.NewJson([]byte(query))
  66. return json.Get("target").MustString()
  67. }