2021-06-09 11:20:38 +02:00
|
|
|
package datasource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
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.Values = append(m.Values, last[0])
|
|
|
|
m.Timestamps = append(m.Timestamps, int64(last[1]))
|
|
|
|
for k, v := range res.Tags {
|
|
|
|
m.AddLabel(k, v)
|
|
|
|
}
|
|
|
|
ms = append(ms, m)
|
|
|
|
}
|
|
|
|
return ms
|
|
|
|
}
|
|
|
|
|
2023-05-08 09:36:39 +02:00
|
|
|
func parseGraphiteResponse(req *http.Request, resp *http.Response) (Result, error) {
|
2021-06-09 11:20:38 +02:00
|
|
|
r := &graphiteResponse{}
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(r); err != nil {
|
2023-05-08 09:36:39 +02:00
|
|
|
return Result{}, fmt.Errorf("error parsing graphite metrics for %s: %w", req.URL.Redacted(), err)
|
2021-06-09 11:20:38 +02:00
|
|
|
}
|
2023-05-08 09:36:39 +02:00
|
|
|
return Result{Data: r.metrics()}, nil
|
2021-06-09 11:20:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
graphitePath = "/render"
|
|
|
|
graphitePrefix = "/graphite"
|
|
|
|
)
|
|
|
|
|
2024-11-14 12:23:39 +01:00
|
|
|
func (c *Client) setGraphiteReqParams(r *http.Request, query string) {
|
|
|
|
if c.appendTypePrefix {
|
2021-06-09 11:20:38 +02:00
|
|
|
r.URL.Path += graphitePrefix
|
|
|
|
}
|
|
|
|
r.URL.Path += graphitePath
|
|
|
|
q := r.URL.Query()
|
2023-07-21 12:28:10 +02:00
|
|
|
from := "-5min"
|
|
|
|
q.Set("from", from)
|
|
|
|
q.Set("format", "json")
|
|
|
|
q.Set("target", query)
|
|
|
|
q.Set("until", "now")
|
|
|
|
|
2024-11-14 12:23:39 +01:00
|
|
|
for k, vs := range c.extraParams {
|
2021-12-02 13:45:08 +01:00
|
|
|
if q.Has(k) { // extraParams are prior to params in URL
|
|
|
|
q.Del(k)
|
|
|
|
}
|
|
|
|
for _, v := range vs {
|
|
|
|
q.Add(k, v)
|
|
|
|
}
|
|
|
|
}
|
2023-07-21 12:28:10 +02:00
|
|
|
|
2021-06-09 11:20:38 +02:00
|
|
|
r.URL.RawQuery = q.Encode()
|
|
|
|
}
|