2016-09-21 00:01:53 -05:00
|
|
|
package prometheus
|
|
|
|
|
|
|
|
import (
|
2016-10-03 02:38:03 -05:00
|
|
|
"context"
|
2021-08-09 04:11:19 -05:00
|
|
|
"encoding/json"
|
2020-11-26 06:38:36 -06:00
|
|
|
"errors"
|
2016-09-21 06:30:41 -05:00
|
|
|
"fmt"
|
2021-08-23 08:25:40 -05:00
|
|
|
"net/http"
|
2016-09-21 04:17:29 -05:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2016-09-21 00:01:53 -05:00
|
|
|
"time"
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
|
|
|
"github.com/grafana/grafana-plugin-sdk-go/backend/datasource"
|
|
|
|
sdkhttpclient "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
|
|
|
|
"github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt"
|
2021-03-18 01:40:26 -05:00
|
|
|
"github.com/grafana/grafana-plugin-sdk-go/data"
|
2021-08-09 04:11:19 -05:00
|
|
|
"github.com/grafana/grafana/pkg/components/simplejson"
|
2021-05-19 16:53:41 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/httpclient"
|
2019-05-13 01:45:54 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/log"
|
2021-08-09 04:11:19 -05:00
|
|
|
"github.com/grafana/grafana/pkg/plugins/backendplugin"
|
|
|
|
"github.com/grafana/grafana/pkg/plugins/backendplugin/coreplugin"
|
|
|
|
"github.com/grafana/grafana/pkg/registry"
|
|
|
|
"github.com/grafana/grafana/pkg/tsdb"
|
2021-05-27 05:43:21 -05:00
|
|
|
"github.com/opentracing/opentracing-go"
|
2020-11-26 06:38:36 -06:00
|
|
|
"github.com/prometheus/client_golang/api"
|
2017-09-04 12:16:35 -05:00
|
|
|
apiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
|
|
|
|
"github.com/prometheus/common/model"
|
2016-09-21 00:01:53 -05:00
|
|
|
)
|
|
|
|
|
2021-05-27 05:43:21 -05:00
|
|
|
var (
|
2021-08-09 04:11:19 -05:00
|
|
|
plog = log.New("tsdb.prometheus")
|
|
|
|
legendFormat = regexp.MustCompile(`\{\{\s*(.+?)\s*\}\}`)
|
|
|
|
safeRes = 11000
|
2021-05-27 05:43:21 -05:00
|
|
|
)
|
2021-05-12 12:30:41 -05:00
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
type DatasourceInfo struct {
|
|
|
|
ID int64
|
|
|
|
HTTPClientOpts sdkhttpclient.Options
|
|
|
|
URL string
|
|
|
|
HTTPMethod string
|
2021-08-11 13:34:51 -05:00
|
|
|
TimeInterval string
|
2021-08-09 04:11:19 -05:00
|
|
|
}
|
|
|
|
|
2021-05-27 05:43:21 -05:00
|
|
|
func init() {
|
2021-08-09 04:11:19 -05:00
|
|
|
registry.Register(®istry.Descriptor{
|
|
|
|
Name: "PrometheusService",
|
|
|
|
InitPriority: registry.Low,
|
|
|
|
Instance: &Service{},
|
|
|
|
})
|
2017-02-06 08:22:09 -06:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
type Service struct {
|
|
|
|
BackendPluginManager backendplugin.Manager `inject:""`
|
|
|
|
HTTPClientProvider httpclient.Provider `inject:""`
|
|
|
|
intervalCalculator tsdb.Calculator
|
|
|
|
im instancemgmt.InstanceManager
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) Init() error {
|
|
|
|
plog.Debug("initializing")
|
|
|
|
im := datasource.NewInstanceManager(newInstanceSettings())
|
|
|
|
factory := coreplugin.New(backend.ServeOpts{
|
|
|
|
QueryDataHandler: newService(im, s.HTTPClientProvider),
|
|
|
|
})
|
|
|
|
if err := s.BackendPluginManager.Register("prometheus", factory); err != nil {
|
|
|
|
plog.Error("Failed to register plugin", "error", err)
|
|
|
|
}
|
|
|
|
return nil
|
2017-02-06 08:22:09 -06:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
func newInstanceSettings() datasource.InstanceFactoryFunc {
|
|
|
|
return func(settings backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) {
|
2021-08-23 08:25:40 -05:00
|
|
|
defaultHttpMethod := http.MethodPost
|
2021-08-09 04:11:19 -05:00
|
|
|
jsonData := map[string]interface{}{}
|
|
|
|
err := json.Unmarshal(settings.JSONData, &jsonData)
|
2021-05-27 05:43:21 -05:00
|
|
|
if err != nil {
|
2021-08-09 04:11:19 -05:00
|
|
|
return nil, fmt.Errorf("error reading settings: %w", err)
|
|
|
|
}
|
|
|
|
httpCliOpts, err := settings.HTTPClientOptions()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error getting http options: %w", err)
|
2021-05-27 05:43:21 -05:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
httpMethod, ok := jsonData["httpMethod"].(string)
|
|
|
|
if !ok {
|
2021-08-23 08:25:40 -05:00
|
|
|
httpMethod = defaultHttpMethod
|
2021-05-27 05:43:21 -05:00
|
|
|
}
|
|
|
|
|
2021-08-16 02:20:58 -05:00
|
|
|
// timeInterval can be a string or can be missing.
|
|
|
|
// if it is missing, we set it to empty-string
|
|
|
|
|
|
|
|
timeInterval := ""
|
|
|
|
|
|
|
|
timeIntervalJson := jsonData["timeInterval"]
|
|
|
|
if timeIntervalJson != nil {
|
|
|
|
// if it is not nil, it must be a string
|
|
|
|
timeInterval, ok = timeIntervalJson.(string)
|
|
|
|
if !ok {
|
|
|
|
return nil, errors.New("invalid time-interval provided")
|
|
|
|
}
|
2021-08-11 13:34:51 -05:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
mdl := DatasourceInfo{
|
|
|
|
ID: settings.ID,
|
|
|
|
URL: settings.URL,
|
|
|
|
HTTPClientOpts: httpCliOpts,
|
|
|
|
HTTPMethod: httpMethod,
|
2021-08-11 13:34:51 -05:00
|
|
|
TimeInterval: timeInterval,
|
2021-05-19 16:53:41 -05:00
|
|
|
}
|
2021-08-09 04:11:19 -05:00
|
|
|
return mdl, nil
|
|
|
|
}
|
|
|
|
}
|
2021-05-19 16:53:41 -05:00
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
// newService creates a new executor func.
|
|
|
|
func newService(im instancemgmt.InstanceManager, httpClientProvider httpclient.Provider) *Service {
|
|
|
|
return &Service{
|
|
|
|
im: im,
|
|
|
|
HTTPClientProvider: httpClientProvider,
|
|
|
|
intervalCalculator: tsdb.NewCalculator(),
|
2021-05-19 16:53:41 -05:00
|
|
|
}
|
2016-09-21 00:01:53 -05:00
|
|
|
}
|
|
|
|
|
2021-04-22 20:03:11 -05:00
|
|
|
//nolint: staticcheck // plugins.DataResponse deprecated
|
2021-08-09 04:11:19 -05:00
|
|
|
func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
|
|
|
|
if len(req.Queries) == 0 {
|
|
|
|
return &backend.QueryDataResponse{}, fmt.Errorf("query contains no queries")
|
|
|
|
}
|
|
|
|
|
|
|
|
dsInfo, err := s.getDSInfo(req.PluginContext)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
client, err := getClient(dsInfo, s)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
result := backend.QueryDataResponse{
|
|
|
|
Responses: backend.Responses{},
|
2017-12-22 05:22:42 -06:00
|
|
|
}
|
2016-09-21 00:01:53 -05:00
|
|
|
|
2021-08-11 13:34:51 -05:00
|
|
|
queries, err := s.parseQuery(req.Queries, dsInfo)
|
2016-09-21 04:31:56 -05:00
|
|
|
if err != nil {
|
2021-08-09 04:11:19 -05:00
|
|
|
return &result, err
|
2016-09-21 04:31:56 -05:00
|
|
|
}
|
2016-09-21 04:17:29 -05:00
|
|
|
|
2018-09-21 04:51:26 -05:00
|
|
|
for _, query := range queries {
|
2017-12-22 05:22:42 -06:00
|
|
|
timeRange := apiv1.Range{
|
|
|
|
Start: query.Start,
|
|
|
|
End: query.End,
|
|
|
|
Step: query.Step,
|
|
|
|
}
|
2016-09-21 00:01:53 -05:00
|
|
|
|
2017-12-22 05:22:42 -06:00
|
|
|
plog.Debug("Sending query", "start", timeRange.Start, "end", timeRange.End, "step", timeRange.Step, "query", query.Expr)
|
2017-09-10 15:05:11 -05:00
|
|
|
|
2021-05-27 05:43:21 -05:00
|
|
|
span, ctx := opentracing.StartSpanFromContext(ctx, "datasource.prometheus")
|
2017-12-22 05:22:42 -06:00
|
|
|
span.SetTag("expr", query.Expr)
|
2018-04-16 13:04:58 -05:00
|
|
|
span.SetTag("start_unixnano", query.Start.UnixNano())
|
|
|
|
span.SetTag("stop_unixnano", query.End.UnixNano())
|
2017-12-22 05:22:42 -06:00
|
|
|
defer span.Finish()
|
2016-09-21 00:01:53 -05:00
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
value, _, err := client.QueryRange(ctx, query.Expr, timeRange)
|
2016-09-21 00:01:53 -05:00
|
|
|
|
2017-12-22 05:22:42 -06:00
|
|
|
if err != nil {
|
2021-08-09 04:11:19 -05:00
|
|
|
return &result, err
|
2017-12-22 05:22:42 -06:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
frame, err := parseResponse(value, query)
|
2017-12-22 05:22:42 -06:00
|
|
|
if err != nil {
|
2021-08-09 04:11:19 -05:00
|
|
|
return &result, err
|
|
|
|
}
|
|
|
|
result.Responses[query.RefId] = backend.DataResponse{
|
|
|
|
Frames: frame,
|
2017-12-22 05:22:42 -06:00
|
|
|
}
|
2016-09-21 06:30:41 -05:00
|
|
|
}
|
2017-12-22 05:22:42 -06:00
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
return &result, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getClient(dsInfo *DatasourceInfo, s *Service) (apiv1.API, error) {
|
|
|
|
opts := &sdkhttpclient.Options{
|
|
|
|
Timeouts: dsInfo.HTTPClientOpts.Timeouts,
|
|
|
|
TLS: dsInfo.HTTPClientOpts.TLS,
|
|
|
|
}
|
|
|
|
|
|
|
|
customMiddlewares := customQueryParametersMiddleware(plog)
|
|
|
|
opts.Middlewares = []sdkhttpclient.Middleware{customMiddlewares}
|
|
|
|
|
|
|
|
roundTripper, err := s.HTTPClientProvider.GetTransport(*opts)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
cfg := api.Config{
|
|
|
|
Address: dsInfo.URL,
|
|
|
|
RoundTripper: roundTripper,
|
|
|
|
}
|
|
|
|
|
|
|
|
client, err := api.NewClient(cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return apiv1.NewAPI(client), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) getDSInfo(pluginCtx backend.PluginContext) (*DatasourceInfo, error) {
|
|
|
|
i, err := s.im.Get(pluginCtx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
instance := i.(DatasourceInfo)
|
|
|
|
|
|
|
|
return &instance, nil
|
2016-09-21 00:01:53 -05:00
|
|
|
}
|
|
|
|
|
2017-09-04 12:16:35 -05:00
|
|
|
func formatLegend(metric model.Metric, query *PrometheusQuery) string {
|
2016-11-03 12:04:09 -05:00
|
|
|
if query.LegendFormat == "" {
|
|
|
|
return metric.String()
|
|
|
|
}
|
|
|
|
|
2016-11-08 12:56:57 -06:00
|
|
|
result := legendFormat.ReplaceAllFunc([]byte(query.LegendFormat), func(in []byte) []byte {
|
2016-10-19 01:57:58 -05:00
|
|
|
labelName := strings.Replace(string(in), "{{", "", 1)
|
|
|
|
labelName = strings.Replace(labelName, "}}", "", 1)
|
|
|
|
labelName = strings.TrimSpace(labelName)
|
2017-09-04 12:16:35 -05:00
|
|
|
if val, exists := metric[model.LabelName(labelName)]; exists {
|
2016-09-21 04:17:29 -05:00
|
|
|
return []byte(val)
|
|
|
|
}
|
2020-03-18 13:57:11 -05:00
|
|
|
return []byte{}
|
2016-09-21 04:17:29 -05:00
|
|
|
})
|
|
|
|
|
|
|
|
return string(result)
|
|
|
|
}
|
|
|
|
|
2021-08-11 13:34:51 -05:00
|
|
|
func (s *Service) parseQuery(queries []backend.DataQuery, dsInfo *DatasourceInfo) (
|
2021-03-08 00:02:49 -06:00
|
|
|
[]*PrometheusQuery, error) {
|
2021-08-05 02:09:49 -05:00
|
|
|
var intervalMode string
|
|
|
|
var adjustedInterval time.Duration
|
|
|
|
|
2017-12-22 05:22:42 -06:00
|
|
|
qs := []*PrometheusQuery{}
|
2021-08-09 04:11:19 -05:00
|
|
|
for _, queryModel := range queries {
|
|
|
|
jsonModel, err := simplejson.NewJson(queryModel.JSON)
|
2017-12-22 05:22:42 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-09 04:11:19 -05:00
|
|
|
expr, err := jsonModel.Get("expr").String()
|
2017-12-22 05:22:42 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-09-21 04:31:56 -05:00
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
format := jsonModel.Get("legendFormat").MustString("")
|
|
|
|
|
|
|
|
start := queryModel.TimeRange.From
|
|
|
|
end := queryModel.TimeRange.To
|
|
|
|
queryInterval := jsonModel.Get("interval").MustString("")
|
2016-09-21 06:17:36 -05:00
|
|
|
|
2021-08-11 13:34:51 -05:00
|
|
|
foundInterval, err := tsdb.GetIntervalFrom(dsInfo.TimeInterval, queryInterval, 0, 15*time.Second)
|
2021-08-09 04:11:19 -05:00
|
|
|
hasQueryInterval := queryInterval != ""
|
2021-08-05 02:09:49 -05:00
|
|
|
// Only use stepMode if we have interval in query, otherwise use "min"
|
|
|
|
if hasQueryInterval {
|
2021-08-09 04:11:19 -05:00
|
|
|
intervalMode = jsonModel.Get("stepMode").MustString("min")
|
2021-08-05 02:09:49 -05:00
|
|
|
} else {
|
|
|
|
intervalMode = "min"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Calculate interval value from query or data source settings or use default value
|
2017-12-22 05:22:42 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-09-21 06:17:36 -05:00
|
|
|
|
2021-08-11 13:34:51 -05:00
|
|
|
calculatedInterval, err := s.intervalCalculator.Calculate(queries[0].TimeRange, foundInterval, tsdb.IntervalMode(intervalMode))
|
2021-08-05 02:09:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-09 04:11:19 -05:00
|
|
|
safeInterval := s.intervalCalculator.CalculateSafeInterval(queries[0].TimeRange, int64(safeRes))
|
2021-08-05 02:09:49 -05:00
|
|
|
|
|
|
|
if calculatedInterval.Value > safeInterval.Value {
|
|
|
|
adjustedInterval = calculatedInterval.Value
|
|
|
|
} else {
|
|
|
|
adjustedInterval = safeInterval.Value
|
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
intervalFactor := jsonModel.Get("intervalFactor").MustInt64(1)
|
2021-08-05 02:09:49 -05:00
|
|
|
step := time.Duration(int64(adjustedInterval) * intervalFactor)
|
2017-11-15 04:22:00 -06:00
|
|
|
|
2017-12-22 05:22:42 -06:00
|
|
|
qs = append(qs, &PrometheusQuery{
|
|
|
|
Expr: expr,
|
|
|
|
Step: step,
|
|
|
|
LegendFormat: format,
|
|
|
|
Start: start,
|
|
|
|
End: end,
|
2021-03-08 00:02:49 -06:00
|
|
|
RefId: queryModel.RefID,
|
2017-12-22 05:22:42 -06:00
|
|
|
})
|
|
|
|
}
|
2017-11-15 04:22:00 -06:00
|
|
|
|
2017-12-22 05:22:42 -06:00
|
|
|
return qs, nil
|
2016-09-21 04:17:29 -05:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
func parseResponse(value model.Value, query *PrometheusQuery) (data.Frames, error) {
|
2021-03-18 01:40:26 -05:00
|
|
|
frames := data.Frames{}
|
2016-09-21 00:01:53 -05:00
|
|
|
|
2021-03-18 01:40:26 -05:00
|
|
|
matrix, ok := value.(model.Matrix)
|
2016-09-21 06:30:41 -05:00
|
|
|
if !ok {
|
2021-08-09 04:11:19 -05:00
|
|
|
return frames, fmt.Errorf("unsupported result format: %q", value.Type().String())
|
2016-09-21 06:30:41 -05:00
|
|
|
}
|
2016-09-21 00:01:53 -05:00
|
|
|
|
2021-03-18 01:40:26 -05:00
|
|
|
for _, v := range matrix {
|
|
|
|
name := formatLegend(v.Metric, query)
|
|
|
|
tags := make(map[string]string, len(v.Metric))
|
|
|
|
timeVector := make([]time.Time, 0, len(v.Values))
|
|
|
|
values := make([]float64, 0, len(v.Values))
|
2017-02-06 08:25:15 -06:00
|
|
|
|
|
|
|
for k, v := range v.Metric {
|
2021-03-18 01:40:26 -05:00
|
|
|
tags[string(k)] = string(v)
|
2016-09-28 02:15:48 -05:00
|
|
|
}
|
|
|
|
|
2016-09-21 00:01:53 -05:00
|
|
|
for _, k := range v.Values {
|
2021-03-18 01:40:26 -05:00
|
|
|
timeVector = append(timeVector, time.Unix(k.Timestamp.Unix(), 0).UTC())
|
|
|
|
values = append(values, float64(k.Value))
|
2016-09-21 00:01:53 -05:00
|
|
|
}
|
2021-03-18 01:40:26 -05:00
|
|
|
frames = append(frames, data.NewFrame(name,
|
|
|
|
data.NewField("time", nil, timeVector),
|
2021-03-26 09:20:46 -05:00
|
|
|
data.NewField("value", tags, values).SetConfig(&data.FieldConfig{DisplayNameFromDS: name})))
|
2016-09-21 00:01:53 -05:00
|
|
|
}
|
|
|
|
|
2021-08-09 04:11:19 -05:00
|
|
|
return frames, nil
|
2016-09-21 00:01:53 -05:00
|
|
|
}
|
2020-11-26 06:38:36 -06:00
|
|
|
|
2020-11-27 05:05:49 -06:00
|
|
|
// IsAPIError returns whether err is or wraps a Prometheus error.
|
2020-11-26 06:38:36 -06:00
|
|
|
func IsAPIError(err error) bool {
|
2020-11-27 05:05:49 -06:00
|
|
|
// Check if the right error type is in err's chain.
|
2020-11-26 06:38:36 -06:00
|
|
|
var e *apiv1.Error
|
|
|
|
return errors.As(err, &e)
|
|
|
|
}
|
|
|
|
|
|
|
|
func ConvertAPIError(err error) error {
|
|
|
|
var e *apiv1.Error
|
|
|
|
if errors.As(err, &e) {
|
|
|
|
return fmt.Errorf("%s: %s", e.Msg, e.Detail)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|