forked from enuan/grafana-tools-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest-dashboard.go
634 lines (582 loc) · 20.3 KB
/
rest-dashboard.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package sdk
/*
Copyright 2016 Alexander I.Grafov <grafov@gmail.com>
Copyright 2016-2019 The Grafana SDK authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
ॐ तारे तुत्तारे तुरे स्व
*/
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
)
// DefaultFolderId is the id of the general folder
// that is pre-created and cannot be removed.
const DefaultFolderId = 0
// BoardProperties keeps metadata of a dashboard.
type BoardProperties struct {
IsStarred bool `json:"isStarred,omitempty"`
IsHome bool `json:"isHome,omitempty"`
IsSnapshot bool `json:"isSnapshot,omitempty"`
Type string `json:"type,omitempty"`
CanSave bool `json:"canSave"`
CanEdit bool `json:"canEdit"`
CanStar bool `json:"canStar"`
Slug string `json:"slug"`
Expires time.Time `json:"expires"`
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
UpdatedBy string `json:"updatedBy"`
CreatedBy string `json:"createdBy"`
Version int `json:"version"`
FolderID int `json:"folderId"`
FolderTitle string `json:"folderTitle"`
FolderURL string `json:"folderUrl"`
}
//RawBoardRequest struct that wraps Board and parameters being sent
type RawBoardRequest struct {
Dashboard []byte
Parameters SetDashboardParams
}
//MarshalJSON serializes the request to match the expectations of the grafana API.
// Additionally, if preseveID is false, then the dashboard id is set to 0
func (d RawBoardRequest) MarshalJSON() ([]byte, error) {
var raw []byte
if d.Parameters.PreserveId {
raw = d.Dashboard
} else {
var plain map[string]interface{} = make(map[string]interface{})
if err := json.Unmarshal(d.Dashboard, &plain); err != nil {
return nil, err
}
plain["id"] = 0
raw, _ = json.Marshal(plain)
}
var output struct {
Dashboard map[string]interface{} `json:"dashboard"`
SetDashboardParams
}
err := json.Unmarshal(raw, &output.Dashboard)
if err != nil {
return nil, err
}
output.SetDashboardParams = d.Parameters
result, err := json.Marshal(&output)
if err != nil {
return nil, err
}
return result, nil
}
// GetDashboardByUID loads a dashboard and its metadata from Grafana by dashboard uid.
//
// Reflects GET /api/dashboards/uid/:uid API call.
func (r *Client) GetDashboardByUID(ctx context.Context, uid string) (Board, BoardProperties, error) {
return r.getDashboard(ctx, "uid/"+uid)
}
// GetDashboardBySlug loads a dashboard and its metadata from Grafana by dashboard slug.
//
// For dashboards from a filesystem set "file/" prefix for slug. By default dashboards from
// a database assumed. Database dashboards may have "db/" prefix or may have not, it will
// be appended automatically.
//
// Reflects GET /api/dashboards/db/:slug API call.
// Deprecated: since Grafana v5 you should use uids. Use GetDashboardByUID() for that.
func (r *Client) GetDashboardBySlug(ctx context.Context, slug string) (Board, BoardProperties, error) {
path := setPrefix(slug)
return r.getDashboard(ctx, path)
}
// DashboardVersion represents a response from /api/dashboards/id/:dashboardId/versions API
type DashboardVersion struct {
ID uint `json:"id"`
DashboardID uint `json:"dashboardId"`
ParentVersion uint `json:"parentVersion"`
RestoredFrom uint `json:"restoredFrom"`
Version uint `json:"version"`
Created time.Time `json:"created"`
CreatedBy string `json:"createdBy"`
Message string `json:"message"`
}
// GetDashboardVersionsByDashboardID reflects /api/dashboards/id/:dashboardId/versions API call
func (r *Client) GetDashboardVersionsByDashboardID(ctx context.Context, dashboardID uint, params ...QueryParam) ([]DashboardVersion, error) {
var (
raw []byte
code int
err error
)
if raw, code, err = r.get(ctx, fmt.Sprintf("api/dashboards/id/%d/versions", dashboardID), queryParams(params...)); err != nil {
return nil, err
}
if code != 200 {
return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw)
}
var versions []DashboardVersion
err = json.Unmarshal(raw, &versions)
return versions, err
}
// getDashboard loads a dashboard from Grafana instance along with metadata for a dashboard.
// For dashboards from a filesystem set "file/" prefix for slug. By default dashboards from
// a database assumed. Database dashboards may have "db/" prefix or may have not, it will
// be appended automatically.
//
// Reflects GET /api/dashboards/db/:slug API call.
func (r *Client) getDashboard(ctx context.Context, path string) (Board, BoardProperties, error) {
raw, bp, err := r.getRawDashboard(ctx, path)
if err != nil {
return Board{}, BoardProperties{}, errors.Wrap(err, "get raw dashboard")
}
var (
result struct {
Meta BoardProperties `json:"meta"`
Board Board `json:"dashboard"`
}
)
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&result.Board); err != nil {
return Board{}, BoardProperties{}, errors.Wrap(err, "unmarshal board")
}
return result.Board, bp, err
}
// GetRawDashboard loads a dashboard JSON from Grafana instance along with metadata for a dashboard.
// Contrary to GetDashboard() it not unpack loaded JSON to Board structure. Instead it
// returns it as byte slice. It guarantee that data of dashboard returned untouched by conversion
// with Board so no matter how properly fields from a current version of Grafana mapped to
// our Board fields. It useful for backuping purposes when you want a dashboard exactly with
// same data as it exported by Grafana.
//
// For dashboards from a filesystem set "file/" prefix for slug. By default dashboards from
// a database assumed. Database dashboards may have "db/" prefix or may have not, it will
// be appended automatically.
//
// Reflects GET /api/dashboards/db/:slug API call.
// Deprecated: since Grafana v5 you should use uids. Use GetRawDashboardByUID() for that.
func (r *Client) getRawDashboard(ctx context.Context, path string) ([]byte, BoardProperties, error) {
var (
raw []byte
result struct {
Meta BoardProperties `json:"meta"`
Board json.RawMessage `json:"dashboard"`
}
code int
err error
)
if raw, code, err = r.get(ctx, fmt.Sprintf("api/dashboards/%s", path), nil); err != nil {
return nil, BoardProperties{}, err
}
if code != 200 {
return nil, BoardProperties{}, fmt.Errorf("HTTP error %d: returns %s", code, raw)
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&result); err != nil {
return nil, BoardProperties{}, errors.Wrap(err, "unmarshal board")
}
return []byte(result.Board), result.Meta, err
}
// GetDashboardPerms loads a dashboard from Grafana instance.
//
// Reflects GET /api/dashboards/id/:dashboardId/permissions API call.
func (r *Client) GetDashboardPerms(ctx context.Context, boardId uint) ([]Permission, error) {
var perms []Permission
raw, err := r.GetRawDashboardPerms(ctx, boardId)
if err != nil {
return perms, errors.Wrap(err, "get raw dashboard permissions")
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&perms); err != nil {
return perms, errors.Wrap(err, "unmarshal board permissions")
}
return perms, err
}
// GetRawDashboardPerms loads dashboard permissions JSON from Grafana instance.
// Contrary to GetDashboard() it not unpack loaded JSON to Board structure.
// Instead it returns it as byte slice.
// It guarantee that data of dashboard permissions returned untouched by conversion
// with Permission so no matter how properly fields from a current version of Grafana mapped to
// our Board fields.
// It useful for backuping purposes when you want a dashboard permission exactly with
// same data as it exported by Grafana.
//
// Reflects GET /api/dashboards/id/:dashboardId/permissions API call.
func (r *Client) GetRawDashboardPerms(ctx context.Context, boardId uint) ([]byte, error) {
var (
raw []byte
result interface{}
code int
err error
)
if raw, code, err = r.get(ctx, fmt.Sprintf("/api/dashboards/id/%d/permissions", boardId), nil); err != nil {
return nil, err
}
if code != 200 {
return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw)
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unmarshal board")
}
return []byte(raw), err
}
// GetRawDashboardByUID loads a dashboard and its metadata from Grafana by dashboard uid.
//
// Reflects GET /api/dashboards/uid/:uid API call.
func (r *Client) GetRawDashboardByUID(ctx context.Context, uid string) ([]byte, BoardProperties, error) {
return r.getRawDashboard(ctx, "uid/"+uid)
}
// GetRawDashboardBySlug loads a dashboard and its metadata from Grafana by dashboard slug.
//
// For dashboards from a filesystem set "file/" prefix for slug. By default dashboards from
// a database assumed. Database dashboards may have "db/" prefix or may have not, it will
// be appended automatically.
//
// Reflects GET /api/dashboards/db/:slug API call.
// Deprecated: since Grafana v5 you should use uids. Use GetRawDashboardByUID() for that.
func (r *Client) GetRawDashboardBySlug(ctx context.Context, slug string) ([]byte, BoardProperties, error) {
path := setPrefix(slug)
return r.getRawDashboard(ctx, path)
}
// FoundBoard keeps result of search with metadata of a dashboard.
type FoundBoard struct {
ID uint `json:"id"`
UID string `json:"uid"`
Title string `json:"title"`
URI string `json:"uri"`
URL string `json:"url"`
Slug string `json:"slug"`
Type string `json:"type"`
Tags []string `json:"tags"`
IsStarred bool `json:"isStarred"`
FolderID int `json:"folderId"`
FolderUID string `json:"folderUid"`
FolderTitle string `json:"folderTitle"`
FolderURL string `json:"folderUrl"`
}
// SearchDashboards search dashboards by substring of their title. It allows restrict the result set with
// only starred dashboards and only for tags (logical OR applied to multiple tags).
//
// Reflects GET /api/search API call.
// Deprecated: This interface does not allow for API extension and is out of date.
// Please use Search(SearchType(SearchTypeDashboard))
func (r *Client) SearchDashboards(ctx context.Context, query string, starred bool, tags ...string) ([]FoundBoard, error) {
params := []SearchParam{
SearchType(SearchTypeDashboard),
SearchQuery(query),
SearchStarred(starred),
}
for _, tag := range tags {
params = append(params, SearchTag(tag))
}
return r.Search(ctx, params...)
}
// Search searches folders and dashboards with query params specified.
//
// Reflects GET /api/search API call.
func (r *Client) Search(ctx context.Context, params ...SearchParam) ([]FoundBoard, error) {
var (
raw []byte
boards []FoundBoard
code int
err error
)
u := url.URL{}
q := u.Query()
for _, p := range params {
p(&q)
}
if raw, code, err = r.get(ctx, "api/search", q); err != nil {
return nil, err
}
if code != 200 {
return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw)
}
err = json.Unmarshal(raw, &boards)
return boards, err
}
// SetDashboardParams contains the extra parameters
// that affects where and how the dashboard will be stored
type SetDashboardParams struct {
FolderID int
Overwrite bool
PreserveId bool `json:"-"`
}
// SetDashboard updates existing dashboard or creates a new one.
// Set dasboard ID to nil to create a new dashboard.
// Set overwrite to true if you want to overwrite existing dashboard with
// newer version or with same dashboard title.
// Grafana only can create or update a dashboard in a database. File dashboards
// may be only loaded with HTTP API but not created or updated.
//
// Reflects POST /api/dashboards/db API call.
func (r *Client) SetDashboard(ctx context.Context, board Board, params SetDashboardParams) (StatusMessage, error) {
var (
isBoardFromDB bool
newBoard struct {
Dashboard Board `json:"dashboard"`
FolderID int `json:"folderId"`
Overwrite bool `json:"overwrite"`
}
raw []byte
resp StatusMessage
code int
err error
)
if board.Slug, isBoardFromDB = cleanPrefix(board.Slug); !isBoardFromDB {
return StatusMessage{}, errors.New("only database dashboard (with 'db/' prefix in a slug) can be set")
}
newBoard.Dashboard = board
newBoard.FolderID = params.FolderID
newBoard.Overwrite = params.Overwrite
if !params.Overwrite {
newBoard.Dashboard.ID = 0
}
if raw, err = json.Marshal(newBoard); err != nil {
return StatusMessage{}, err
}
if raw, code, err = r.post(ctx, "api/dashboards/db", nil, raw); err != nil {
return StatusMessage{}, err
}
if err = json.Unmarshal(raw, &resp); err != nil {
return StatusMessage{}, err
}
if code != 200 {
return resp, fmt.Errorf("HTTP error %d: returns %s", code, *resp.Message)
}
return resp, nil
}
//SetRawDashboardWithParam sends the serialized along with request parameters
func (r *Client) SetRawDashboardWithParam(ctx context.Context, request RawBoardRequest) (StatusMessage, error) {
var (
rawResp []byte
resp StatusMessage
code int
err error
)
raw, err := json.Marshal(request)
if err != nil {
return StatusMessage{}, errors.New(err.Error())
}
if rawResp, code, err = r.post(ctx, "api/dashboards/db", nil, raw); err != nil {
return StatusMessage{}, err
}
if err = json.Unmarshal(rawResp, &resp); err != nil {
return StatusMessage{}, err
}
if code != 200 {
return StatusMessage{}, fmt.Errorf("HTTP error %d: returns %s", code, *resp.Message)
}
return resp, nil
}
// SetRawDashboard updates existing dashboard or creates a new one.
// Contrary to SetDashboard() it accepts raw JSON instead of Board structure.
// Grafana only can create or update a dashboard in a database. File dashboards
// may be only loaded with HTTP API but not created or updated.
//
// Reflects POST /api/dashboards/db API call.
func (r *Client) SetRawDashboard(ctx context.Context, raw []byte) (StatusMessage, error) {
defaultParams := SetDashboardParams{
Overwrite: true,
FolderID: DefaultFolderId,
}
request := RawBoardRequest{
Parameters: defaultParams,
Dashboard: raw,
}
return r.SetRawDashboardWithParam(ctx, request)
}
// DeleteDashboard deletes dashboard that selected by slug string.
// Grafana only can delete a dashboard in a database. File dashboards
// may be only loaded with HTTP API but not deteled.
//
// Reflects DELETE /api/dashboards/db/:slug API call.
func (r *Client) DeleteDashboard(ctx context.Context, slug string) (StatusMessage, error) {
var (
isBoardFromDB bool
raw []byte
reply StatusMessage
err error
)
if slug, isBoardFromDB = cleanPrefix(slug); !isBoardFromDB {
return StatusMessage{}, errors.New("only database dashboards (with 'db/' prefix in a slug) can be removed")
}
if raw, _, err = r.delete(ctx, fmt.Sprintf("api/dashboards/db/%s", slug)); err != nil {
return StatusMessage{}, err
}
err = json.Unmarshal(raw, &reply)
return reply, err
}
// DeleteDashboard deletes dashboard by UID
// Reflects DELETE /api/dashboards/uid/:uid API call.
func (r *Client) DeleteDashboardByUID(ctx context.Context, uid string) (StatusMessage, error) {
var (
raw []byte
reply StatusMessage
err error
)
if raw, _, err = r.delete(ctx, fmt.Sprintf("api/dashboards/uid/%s", uid)); err != nil {
return StatusMessage{}, err
}
err = json.Unmarshal(raw, &reply)
return reply, err
}
//UpdateDashboardPermissions updates the permissions of the dashboard specified by boardId.
// Reflects POST /api/dashboards/id/:dashboardId/permissions API call.
func (r *Client) UpdateDashboardPermissions(ctx context.Context, boardPerms BoardPermissions, boardId uint) (StatusMessage, error) {
var (
raw []byte
resp StatusMessage
code int
err error
)
if raw, err = json.Marshal(boardPerms); err != nil {
return StatusMessage{}, err
}
fmt.Printf("boardPerms: %s", raw)
if raw, code, err = r.post(ctx, fmt.Sprintf("api/dashboards/id/%d/permissions", boardId), nil, raw); err != nil {
return StatusMessage{}, err
}
if err = json.Unmarshal(raw, &resp); err != nil {
return StatusMessage{}, err
}
if code != 200 {
return resp, fmt.Errorf("HTTP error %d: returns %s", code, *resp.Message)
}
return resp, err
}
type (
// SearchParam is a type for specifying Search params.
SearchParam func(*url.Values)
// SearchParamType is a type accepted by SearchType func.
SearchParamType string
// QueryParam is a type for specifying arbitrary API parameters
QueryParam func(*url.Values)
)
// queryParams returns url.Values built from multiple QueryParam
func queryParams(params ...QueryParam) url.Values {
u := url.URL{}
q := u.Query()
for _, p := range params {
p(&q)
}
return q
}
// QueryParamStart sets `start` parameter
func QueryParamStart(start uint) QueryParam {
return func(v *url.Values) {
v.Set("start", strconv.Itoa(int(start)))
}
}
// QueryParamLimit sets `limit` parameter
func QueryParamLimit(limit uint) QueryParam {
return func(v *url.Values) {
v.Set("limit", strconv.Itoa(int(limit)))
}
}
// Search entities to be used with SearchType().
const (
SearchTypeFolder SearchParamType = "dash-folder"
SearchTypeDashboard SearchParamType = "dash-db"
)
// SearchQuery specifies Search search query.
// Empty query is silently ignored.
// Specifying it multiple times is futile, only last one will be sent.
func SearchQuery(query string) SearchParam {
return func(v *url.Values) {
if query != "" {
v.Set("query", query)
}
}
}
// SearchTag specifies Search tag to search for.
// Empty tag is silently ignored.
// Can be specified multiple times, logical OR is applied.
func SearchTag(tag string) SearchParam {
return func(v *url.Values) {
if tag != "" {
v.Add("tag", tag)
}
}
}
// SearchType specifies Search type to search for.
// Specifying it multiple times is futile, only last one will be sent.
func SearchType(searchType SearchParamType) SearchParam {
return func(v *url.Values) {
v.Set("type", string(searchType))
}
}
// SearchDashboardID specifies Search dashboard id's to search for.
// Can be specified multiple times, logical OR is applied.
func SearchDashboardID(dashboardID int) SearchParam {
return func(v *url.Values) {
v.Add("dashboardIds", strconv.Itoa(dashboardID))
}
}
// SearchFolderID specifies Search folder id's to search for.
// Can be specified multiple times, logical OR is applied.
func SearchFolderID(folderID int) SearchParam {
return func(v *url.Values) {
v.Add("folderIds", strconv.Itoa(folderID))
}
}
// SearchStarred specifies if Search should search for starred dashboards only.
// Specifying it multiple times is futile, only last one will be sent.
func SearchStarred(starred bool) SearchParam {
return func(v *url.Values) {
v.Set("starred", strconv.FormatBool(starred))
}
}
// SearchLimit specifies maximum number of results from Search query.
// As of grafana 6.7 it has to be <= 5000. 0 stands for absence of parameter in a query.
// Specifying it multiple times is futile, only last one will be sent.
func SearchLimit(limit uint) SearchParam {
return func(v *url.Values) {
if limit > 0 {
v.Set("limit", strconv.FormatUint(uint64(limit), 10))
}
}
}
// SearchPage specifies Search page number to be queried for.
// Zero page is silently ignored, page numbers start from one.
// Specifying it multiple times is futile, only last one will be sent.
func SearchPage(page uint) SearchParam {
return func(v *url.Values) {
if page > 0 {
v.Set("page", strconv.FormatUint(uint64(page), 10))
}
}
}
// implicitly use dashboards from Grafana DB not from a file system
func setPrefix(slug string) string {
if strings.HasPrefix(slug, "db") {
return slug
}
if strings.HasPrefix(slug, "file/") {
return slug
}
return fmt.Sprintf("db/%s", slug)
}
// assume we use database dashboard by default
func cleanPrefix(slug string) (string, bool) {
if strings.HasPrefix(slug, "db") {
return slug[3:], true
}
if strings.HasPrefix(slug, "file") {
return slug[3:], false
}
return slug, true
}