forked from K-Phoen/grabana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
307 lines (246 loc) · 7.51 KB
/
client.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package grabana
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/breeze7086/grabana/alert"
"github.com/breeze7086/grabana/dashboard"
"github.com/grafana-tools/sdk"
)
// ErrFolderNotFound is returned when the given folder can not be found.
var ErrFolderNotFound = errors.New("folder not found")
// ErrAlertChannelNotFound is returned when the given alert notification
// channel can not be found.
var ErrAlertChannelNotFound = errors.New("alert channel not found")
// Dashboard represents a Grafana dashboard.
type Dashboard struct {
ID uint `json:"id"`
UID string `json:"uid"`
URL string `json:"url"`
}
// Folder represents a dashboard folder.
// See https://grafana.com/docs/grafana/latest/reference/dashboard_folders/
type Folder struct {
ID uint `json:"id"`
UID string `json:"uid"`
Title string `json:"title"`
}
// Option represents an option that can be used to configure a client.
type Option func(client *Client)
type requestModifier func(request *http.Request)
// Client represents a Grafana HTTP client.
type Client struct {
http *http.Client
host string
requestModifiers []requestModifier
}
// NewClient creates a new Grafana HTTP client, using an API token.
func NewClient(http *http.Client, host string, options ...Option) *Client {
client := &Client{
http: http,
host: host,
}
for _, opt := range options {
opt(client)
}
return client
}
// WithAPIToken sets up the client to use the given token to authenticate.
func WithAPIToken(token string) Option {
return func(client *Client) {
client.requestModifiers = append(client.requestModifiers, func(request *http.Request) {
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
})
}
}
// WithBasicAuth sets up the client to use the given credentials to authenticate.
func WithBasicAuth(username string, password string) Option {
return func(client *Client) {
client.requestModifiers = append(client.requestModifiers, func(request *http.Request) {
request.SetBasicAuth(username, password)
})
}
}
func (client *Client) modifyRequest(request *http.Request) {
for _, modifier := range client.requestModifiers {
modifier(request)
}
}
// FindOrCreateFolder returns the folder by its name or creates it if it doesn't exist.
func (client *Client) FindOrCreateFolder(ctx context.Context, name string) (*Folder, error) {
folder, err := client.GetFolderByTitle(ctx, name)
if err != nil && err != ErrFolderNotFound {
return nil, fmt.Errorf("could not find or create folder: %w", err)
}
if folder == nil {
folder, err = client.CreateFolder(ctx, name)
if err != nil {
return nil, fmt.Errorf("could not find create folder: %w", err)
}
}
return folder, nil
}
// CreateFolder creates a dashboard folder.
// See https://grafana.com/docs/grafana/latest/reference/dashboard_folders/
func (client *Client) CreateFolder(ctx context.Context, name string) (*Folder, error) {
buf, err := json.Marshal(struct {
Title string `json:"title"`
}{
Title: name,
})
if err != nil {
return nil, err
}
resp, err := client.postJSON(ctx, "/api/folders", buf)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("could not create folder: %s (HTTP status %d)", body, resp.StatusCode)
}
var folder Folder
if err := decodeJSON(resp.Body, &folder); err != nil {
return nil, err
}
return &folder, nil
}
// GetFolderByTitle finds a folder, given its title.
func (client *Client) GetFolderByTitle(ctx context.Context, title string) (*Folder, error) {
resp, err := client.get(ctx, "/api/folders?limit=100")
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("could list folders: %s (HTTP status %d)", body, resp.StatusCode)
}
var folders []Folder
if err := decodeJSON(resp.Body, &folders); err != nil {
return nil, err
}
for i := range folders {
if strings.EqualFold(folders[i].Title, title) {
return &folders[i], nil
}
}
return nil, ErrFolderNotFound
}
// GetAlertChannelByName finds an alert notification channel, given its name.
func (client *Client) GetAlertChannelByName(ctx context.Context, name string) (*alert.Channel, error) {
resp, err := client.get(ctx, "/api/alert-notifications")
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("could lookup alert channels: %s (HTTP status %d)", body, resp.StatusCode)
}
var channels []alert.Channel
if err := decodeJSON(resp.Body, &channels); err != nil {
return nil, err
}
for i := range channels {
if strings.EqualFold(channels[i].Name, name) {
return &channels[i], nil
}
}
return nil, ErrAlertChannelNotFound
}
// UpsertDashboard creates or replaces a dashboard, in the given folder.
func (client *Client) UpsertDashboard(ctx context.Context, folder *Folder, builder dashboard.Builder) (*Dashboard, error) {
buf, err := json.Marshal(struct {
Dashboard *sdk.Board `json:"dashboard"`
FolderID uint `json:"folderId"`
Overwrite bool `json:"overwrite"`
}{
Dashboard: builder.Internal(),
FolderID: folder.ID,
Overwrite: true,
})
if err != nil {
return nil, err
}
resp, err := client.postJSON(ctx, "/api/dashboards/db", buf)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("could not create dashboard: %s", body)
}
var model Dashboard
if err := decodeJSON(resp.Body, &model); err != nil {
return nil, err
}
return &model, nil
}
// DeleteDashboard deletes a dashboard given its UID.
func (client *Client) DeleteDashboard(ctx context.Context, uid string) error {
resp, err := client.delete(ctx, "/api/dashboards/uid/"+uid)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("could not delete dashboard: %s", body)
}
return nil
}
func (client Client) delete(ctx context.Context, path string) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, client.url(path), nil)
if err != nil {
return nil, err
}
client.modifyRequest(request)
return client.http.Do(request)
}
func (client Client) postJSON(ctx context.Context, path string, body []byte) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodPost, client.url(path), bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", "application/json")
client.modifyRequest(request)
return client.http.Do(request)
}
func (client Client) get(ctx context.Context, path string) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, client.url(path), nil)
if err != nil {
return nil, err
}
client.modifyRequest(request)
return client.http.Do(request)
}
func (client Client) url(path string) string {
return client.host + path
}
func decodeJSON(input io.Reader, data interface{}) error {
return json.NewDecoder(input).Decode(data)
}