-
Notifications
You must be signed in to change notification settings - Fork 0
/
grafana.go
163 lines (136 loc) · 4.35 KB
/
grafana.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"golang.org/x/exp/slog"
)
type GrafanaQueryRequestInJSON struct {
Queries []any `json:"queries"`
From string `json:"from"`
To string `json:"to"`
}
type GrafanaPrometheusQueryJSON struct {
RefID string `json:"refId"`
Expression string `json:"expr"`
Format string `json:"format"` // time_series or table
Range bool `json:"range"`
Instant bool `json:"instant"`
Datasource GrafanaQueryDatasourceJSON `json:"datasource"`
MaxDataPoints int `json:"maxDataPoints"`
Interval string `json:"interval"`
IntervalMs int `json:"intervalMs,omitempty"`
}
type GrafanaQueryDatasourceJSON struct {
UID string `json:"uid"`
}
type GrafanaQueryRequestOutJSON struct {
Results map[string]GrafanaResultJSON `json:"results"`
}
type GrafanaResultJSON struct {
Status int `json:"status"`
Frames []GrafanaFrameJSON `json:"frames"`
}
type GrafanaFrameJSON struct {
Schema any `json:"schema"`
Data GrafanaDataJSON `json:"data"`
}
type GrafanaDataJSON struct {
Values [2][]float64 `json:"values"`
}
type GrafanaCloudQuerier struct {
api string
dsuid string
dstype string
bearerToken string
}
var _ Querier = (*GrafanaCloudQuerier)(nil)
func NewGrafanaCloudQuerier(api string, dsuid string, dstype QueryType, bearerToken string) (*GrafanaCloudQuerier, error) {
u, err := url.Parse(api)
if err != nil {
return nil, fmt.Errorf("invalid api url: %w", err)
}
u.Path = "/api/ds/query"
return &GrafanaCloudQuerier{
api: u.String(),
dsuid: dsuid,
dstype: string(dstype),
bearerToken: bearerToken,
}, nil
}
func (g *GrafanaCloudQuerier) Execute(ctx context.Context, query string, fromTime, toTime time.Time, interval QueryInterval) ([]DataPoint, error) {
fromTime = fromTime.Add(1)
var intervalStr string
var maxPoints int
switch interval {
case QueryIntervalHourly:
intervalStr = "1h"
maxPoints = int(toTime.Sub(fromTime)/time.Hour) + 1
case QueryIntervalDaily:
intervalStr = "1d"
maxPoints = int(toTime.Sub(fromTime)/(24*time.Hour)) + 1
default:
return nil, fmt.Errorf("unsupported query interval: %q", interval)
}
slog.Debug("executing grafana query", "uid", g.dsuid, "type", g.dstype, "query", query, "from", fromTime, "to", toTime)
q := GrafanaQueryRequestInJSON{
Queries: []any{
GrafanaPrometheusQueryJSON{
RefID: "A",
Expression: query,
Instant: true,
Format: "table",
Datasource: GrafanaQueryDatasourceJSON{UID: g.dsuid},
MaxDataPoints: maxPoints,
Interval: intervalStr,
},
},
From: strconv.FormatInt(fromTime.Unix()*1000, 10), // milliseconds
To: strconv.FormatInt(toTime.Unix()*1000, 10), // milliseconds
}
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(q); err != nil {
return nil, fmt.Errorf("failed to encode query request: %w", err)
}
slog.Debug("sending request", "body", buf.String())
hc := http.Client{}
req, err := http.NewRequest("POST", g.api, buf)
if err != nil {
return nil, fmt.Errorf("failed to create new request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", g.bearerToken))
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("request failed: %s", resp.Status)
}
defer resp.Body.Close()
// read body fully so we have it for diagnosis during development
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body request: %w", err)
}
slog.Debug("received response", "body", string(body))
var out GrafanaQueryRequestOutJSON
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&out); err != nil {
return nil, fmt.Errorf("failed to decode query response: %w", err)
}
values := out.Results["A"].Frames[0].Data.Values
points := make([]DataPoint, len(values[0]))
for i := range values[0] {
points[i] = DataPoint{
Time: time.Unix(0, int64(values[0][i])*1e6).UTC(),
Value: values[1][i],
}
}
return points, nil
}