2020-04-27 23:19:27 +02:00
|
|
|
package datasource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2020-09-21 14:53:49 +02:00
|
|
|
"time"
|
2020-04-27 23:19:27 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type response struct {
|
|
|
|
Status string `json:"status"`
|
|
|
|
Data struct {
|
|
|
|
ResultType string `json:"resultType"`
|
|
|
|
Result []struct {
|
|
|
|
Labels map[string]string `json:"metric"`
|
|
|
|
TV [2]interface{} `json:"value"`
|
|
|
|
} `json:"result"`
|
|
|
|
} `json:"data"`
|
|
|
|
ErrorType string `json:"errorType"`
|
|
|
|
Error string `json:"error"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r response) metrics() ([]Metric, error) {
|
|
|
|
var ms []Metric
|
|
|
|
var m Metric
|
|
|
|
var f float64
|
|
|
|
var err error
|
|
|
|
for i, res := range r.Data.Result {
|
|
|
|
f, err = strconv.ParseFloat(res.TV[1].(string), 64)
|
|
|
|
if err != nil {
|
2020-06-30 21:58:18 +02:00
|
|
|
return nil, fmt.Errorf("metric %v, unable to parse float64 from %s: %w", res, res.TV[1], err)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
m.Labels = nil
|
|
|
|
for k, v := range r.Data.Result[i].Labels {
|
2020-11-09 23:27:32 +01:00
|
|
|
m.AddLabel(k, v)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
m.Timestamp = int64(res.TV[0].(float64))
|
|
|
|
m.Value = f
|
|
|
|
ms = append(ms, m)
|
|
|
|
}
|
|
|
|
return ms, nil
|
|
|
|
}
|
|
|
|
|
2021-02-01 14:02:44 +01:00
|
|
|
type graphiteResponse []graphiteResponseTarget
|
|
|
|
|
|
|
|
type graphiteResponseTarget struct {
|
|
|
|
Target string `json:"target"`
|
|
|
|
Tags map[string]string `json:"tags"`
|
|
|
|
DataPoints [][2]float64 `json:"datapoints"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r graphiteResponse) metrics() []Metric {
|
|
|
|
var ms []Metric
|
|
|
|
for _, res := range r {
|
|
|
|
if len(res.DataPoints) < 1 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
var m Metric
|
|
|
|
// add only last value to the result.
|
|
|
|
last := res.DataPoints[len(res.DataPoints)-1]
|
|
|
|
m.Value = last[0]
|
|
|
|
m.Timestamp = int64(last[1])
|
|
|
|
for k, v := range res.Tags {
|
|
|
|
m.AddLabel(k, v)
|
|
|
|
}
|
|
|
|
ms = append(ms, m)
|
|
|
|
}
|
|
|
|
return ms
|
|
|
|
}
|
|
|
|
|
2020-04-27 23:19:27 +02:00
|
|
|
// VMStorage represents vmstorage entity with ability to read and write metrics
|
|
|
|
type VMStorage struct {
|
2020-06-29 21:21:03 +02:00
|
|
|
c *http.Client
|
2021-02-01 14:02:44 +01:00
|
|
|
datasourceURL string
|
2020-06-29 21:21:03 +02:00
|
|
|
basicAuthUser string
|
|
|
|
basicAuthPass string
|
2020-09-21 14:53:49 +02:00
|
|
|
lookBack time.Duration
|
2021-01-26 09:12:04 +01:00
|
|
|
queryStep time.Duration
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
|
2021-02-01 14:02:44 +01:00
|
|
|
const queryPath = "/api/v1/query"
|
|
|
|
const graphitePath = "/render"
|
2020-09-21 14:53:49 +02:00
|
|
|
|
2020-04-27 23:19:27 +02:00
|
|
|
// NewVMStorage is a constructor for VMStorage
|
2021-01-26 09:12:04 +01:00
|
|
|
func NewVMStorage(baseURL, basicAuthUser, basicAuthPass string, lookBack time.Duration, queryStep time.Duration, c *http.Client) *VMStorage {
|
2020-04-27 23:19:27 +02:00
|
|
|
return &VMStorage{
|
|
|
|
c: c,
|
|
|
|
basicAuthUser: basicAuthUser,
|
|
|
|
basicAuthPass: basicAuthPass,
|
2021-02-01 14:02:44 +01:00
|
|
|
datasourceURL: strings.TrimSuffix(baseURL, "/"),
|
2020-09-21 14:53:49 +02:00
|
|
|
lookBack: lookBack,
|
2021-01-26 09:12:04 +01:00
|
|
|
queryStep: queryStep,
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-01 14:02:44 +01:00
|
|
|
// Query reads metrics from datasource by given query and type
|
|
|
|
func (s *VMStorage) Query(ctx context.Context, query string, dataSourceType Type) ([]Metric, error) {
|
|
|
|
switch dataSourceType.name {
|
|
|
|
case "", prometheusType:
|
|
|
|
return s.queryDataSource(ctx, query, s.setPrometheusReqParams, parsePrometheusResponse)
|
|
|
|
case graphiteType:
|
|
|
|
return s.queryDataSource(ctx, query, s.setGraphiteReqParams, parseGraphiteResponse)
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("engine not found: %q", dataSourceType)
|
2021-01-26 09:12:04 +01:00
|
|
|
}
|
2021-02-01 14:02:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *VMStorage) queryDataSource(
|
|
|
|
ctx context.Context,
|
|
|
|
query string,
|
|
|
|
setReqParams func(r *http.Request, query string),
|
|
|
|
processResponse func(r *http.Request, resp *http.Response,
|
|
|
|
) ([]Metric, error)) ([]Metric, error) {
|
|
|
|
req, err := http.NewRequest("POST", s.datasourceURL, nil)
|
2020-04-27 23:19:27 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-11-13 09:25:39 +01:00
|
|
|
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
2020-04-27 23:19:27 +02:00
|
|
|
if s.basicAuthPass != "" {
|
|
|
|
req.SetBasicAuth(s.basicAuthUser, s.basicAuthPass)
|
|
|
|
}
|
2021-02-01 14:02:44 +01:00
|
|
|
setReqParams(req, query)
|
2020-04-27 23:19:27 +02:00
|
|
|
resp, err := s.c.Do(req.WithContext(ctx))
|
|
|
|
if err != nil {
|
2020-06-30 21:58:18 +02:00
|
|
|
return nil, fmt.Errorf("error getting response from %s: %w", req.URL, err)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
body, _ := ioutil.ReadAll(resp.Body)
|
2020-10-07 16:59:50 +02:00
|
|
|
return nil, fmt.Errorf("datasource returns unexpected response code %d for %s. Response body %s", resp.StatusCode, req.URL, body)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
2021-02-01 14:02:44 +01:00
|
|
|
return processResponse(req, resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *VMStorage) setPrometheusReqParams(r *http.Request, query string) {
|
|
|
|
r.URL.Path += queryPath
|
|
|
|
q := r.URL.Query()
|
|
|
|
q.Set("query", query)
|
|
|
|
if s.lookBack > 0 {
|
|
|
|
lookBack := time.Now().Add(-s.lookBack)
|
|
|
|
q.Set("time", fmt.Sprintf("%d", lookBack.Unix()))
|
|
|
|
}
|
|
|
|
if s.queryStep > 0 {
|
|
|
|
q.Set("step", s.queryStep.String())
|
|
|
|
}
|
|
|
|
r.URL.RawQuery = q.Encode()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *VMStorage) setGraphiteReqParams(r *http.Request, query string) {
|
|
|
|
r.URL.Path += graphitePath
|
|
|
|
q := r.URL.Query()
|
|
|
|
q.Set("format", "json")
|
|
|
|
q.Set("target", query)
|
|
|
|
from := "-5min"
|
|
|
|
if s.lookBack > 0 {
|
|
|
|
lookBack := time.Now().Add(-s.lookBack)
|
|
|
|
from = strconv.FormatInt(lookBack.Unix(), 10)
|
|
|
|
}
|
|
|
|
q.Set("from", from)
|
|
|
|
q.Set("until", "now")
|
|
|
|
r.URL.RawQuery = q.Encode()
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
statusSuccess, statusError, rtVector = "success", "error", "vector"
|
|
|
|
)
|
|
|
|
|
|
|
|
func parsePrometheusResponse(req *http.Request, resp *http.Response) ([]Metric, error) {
|
2020-04-27 23:19:27 +02:00
|
|
|
r := &response{}
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(r); err != nil {
|
2021-02-01 14:02:44 +01:00
|
|
|
return nil, fmt.Errorf("error parsing prometheus metrics for %s: %w", req.URL, err)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
if r.Status == statusError {
|
|
|
|
return nil, fmt.Errorf("response error, query: %s, errorType: %s, error: %s", req.URL, r.ErrorType, r.Error)
|
|
|
|
}
|
|
|
|
if r.Status != statusSuccess {
|
2020-06-30 21:58:18 +02:00
|
|
|
return nil, fmt.Errorf("unknown status: %s, Expected success or error ", r.Status)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
if r.Data.ResultType != rtVector {
|
2020-10-07 16:59:50 +02:00
|
|
|
return nil, fmt.Errorf("unknown result type:%s. Expected vector", r.Data.ResultType)
|
2020-04-27 23:19:27 +02:00
|
|
|
}
|
|
|
|
return r.metrics()
|
|
|
|
}
|
2021-02-01 14:02:44 +01:00
|
|
|
|
|
|
|
func parseGraphiteResponse(req *http.Request, resp *http.Response) ([]Metric, error) {
|
|
|
|
r := &graphiteResponse{}
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(r); err != nil {
|
|
|
|
return nil, fmt.Errorf("error parsing graphite metrics for %s: %w", req.URL, err)
|
|
|
|
}
|
|
|
|
return r.metrics(), nil
|
|
|
|
}
|