prometheus.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package prometheus
  2. import (
  3. "context"
  4. "net/http"
  5. "regexp"
  6. "strings"
  7. "time"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/tsdb"
  10. "github.com/prometheus/client_golang/api/prometheus"
  11. pmodel "github.com/prometheus/common/model"
  12. )
  13. type PrometheusExecutor struct {
  14. *tsdb.DataSourceInfo
  15. }
  16. func NewPrometheusExecutor(dsInfo *tsdb.DataSourceInfo) tsdb.Executor {
  17. return &PrometheusExecutor{dsInfo}
  18. }
  19. var (
  20. plog log.Logger
  21. HttpClient http.Client
  22. )
  23. func init() {
  24. plog = log.New("tsdb.prometheus")
  25. tsdb.RegisterExecutor("prometheus", NewPrometheusExecutor)
  26. }
  27. func (e *PrometheusExecutor) getClient() (prometheus.QueryAPI, error) {
  28. cfg := prometheus.Config{
  29. Address: e.DataSourceInfo.Url,
  30. }
  31. client, err := prometheus.New(cfg)
  32. if err != nil {
  33. return nil, err
  34. }
  35. return prometheus.NewQueryAPI(client), nil
  36. }
  37. func (e *PrometheusExecutor) Execute(queries tsdb.QuerySlice, queryContext *tsdb.QueryContext) *tsdb.BatchResult {
  38. result := &tsdb.BatchResult{}
  39. client, err := e.getClient()
  40. if err != nil {
  41. return resultWithError(result, err)
  42. }
  43. from, _ := queryContext.TimeRange.FromTime()
  44. to, _ := queryContext.TimeRange.ToTime()
  45. query, err := parseQuery(queries)
  46. if err != nil {
  47. return resultWithError(result, err)
  48. }
  49. timeRange := prometheus.Range{
  50. Start: from,
  51. End: to,
  52. Step: query.Step,
  53. }
  54. value, err := client.QueryRange(context.Background(), query.Expr, timeRange)
  55. if err != nil {
  56. return resultWithError(result, err)
  57. }
  58. result.QueryResults = parseResponse(value, query)
  59. return result
  60. }
  61. func formatLegend(metric pmodel.Metric, query *PrometheusQuery) string {
  62. r, _ := regexp.Compile(`\{\{\s*(.+?)\s*\}\}`)
  63. result := r.ReplaceAllFunc([]byte(query.LegendFormat), func(in []byte) []byte {
  64. ind := strings.Replace(strings.Replace(string(in), "{{", "", 1), "}}", "", 1)
  65. if val, exists := metric[pmodel.LabelName(ind)]; exists {
  66. return []byte(val)
  67. }
  68. return in
  69. })
  70. return string(result)
  71. }
  72. func parseQuery(queries tsdb.QuerySlice) (*PrometheusQuery, error) {
  73. queryModel := queries[0]
  74. expr, err := queryModel.Model.Get("expr").String()
  75. if err != nil {
  76. return nil, err
  77. }
  78. step, err := queryModel.Model.Get("step").Int64()
  79. if err != nil {
  80. return nil, err
  81. }
  82. format, err := queryModel.Model.Get("legendFormat").String()
  83. if err != nil {
  84. return nil, err
  85. }
  86. return &PrometheusQuery{
  87. Expr: expr,
  88. Step: time.Second * time.Duration(step),
  89. LegendFormat: format,
  90. }, nil
  91. }
  92. func parseResponse(value pmodel.Value, query *PrometheusQuery) map[string]*tsdb.QueryResult {
  93. queryResults := make(map[string]*tsdb.QueryResult)
  94. queryRes := &tsdb.QueryResult{}
  95. data := value.(pmodel.Matrix)
  96. for _, v := range data {
  97. var points [][2]*float64
  98. for _, k := range v.Values {
  99. dummie := float64(k.Timestamp)
  100. d2 := float64(k.Value)
  101. points = append(points, [2]*float64{&d2, &dummie})
  102. }
  103. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  104. Name: formatLegend(v.Metric, query),
  105. Points: points,
  106. })
  107. }
  108. queryResults["A"] = queryRes
  109. return queryResults
  110. }
  111. func resultWithError(result *tsdb.BatchResult, err error) *tsdb.BatchResult {
  112. result.Error = err
  113. return result
  114. }