prometheus.go 3.6 KB

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