graphite.go 2.3 KB

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