-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdk.go
297 lines (262 loc) · 8.57 KB
/
sdk.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
/*
Copyright AppsCode Inc. and Contributors
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.
*/
package grafana_sdk
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"github.com/go-resty/resty/v2"
"gomodules.xyz/pointer"
"k8s.io/apimachinery/pkg/runtime"
)
// AuthConfig configures an HTTP client.
type AuthConfig struct {
// The HTTP basic authentication credentials for the targets.
BasicAuth *BasicAuth
// The bearer token for the targets.
BearerToken string
}
// BasicAuth contains basic HTTP authentication credentials.
type BasicAuth struct {
Username string `yaml:"username" json:"username"`
Password string `yaml:"password,omitempty" json:"password,omitempty"`
}
type Client struct {
baseURL string
auth *AuthConfig
client *resty.Client
}
type GrafanaDashboard struct {
Dashboard *runtime.RawExtension `json:"dashboard,omitempty"`
FolderId int `json:"folderId,omitempty"`
FolderUid string `json:"FolderUid,omitempty"`
Message string `json:"message,omitempty"`
Overwrite bool `json:"overwrite,omitempty"`
}
type GrafanaResponse struct {
ID *int `json:"id,omitempty"`
UID *string `json:"uid,omitempty"`
URL *string `json:"url,omitempty"`
Title *string `json:"title,omitempty"`
Name *string `json:"name,omitempty"`
Message *string `json:"message,omitempty"`
Status *string `json:"status,omitempty"`
Version *int `json:"version,omitempty"`
Slug *string `json:"slug,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
}
type Org struct {
ID *int `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
}
type HealthResponse struct {
Commit string `json:"commit,omitempty"`
Database string `json:"database,omitempty"`
Version string `json:"version,omitempty"`
}
// Datasource as described in the doc
// http://docs.grafana.org/reference/http_api/#get-all-datasources
type Datasource struct {
ID uint `json:"id"`
OrgID uint `json:"orgId"`
Name string `json:"name"`
Type string `json:"type"`
Access string `json:"access"` // direct or proxy
URL string `json:"url"`
Password *string `json:"password,omitempty"`
User *string `json:"user,omitempty"`
Database *string `json:"database,omitempty"`
BasicAuth *bool `json:"basicAuth,omitempty"`
BasicAuthUser *string `json:"basicAuthUser,omitempty"`
BasicAuthPassword *string `json:"basicAuthPassword,omitempty"`
IsDefault bool `json:"isDefault"`
JSONData interface{} `json:"jsonData"`
SecureJSONData interface{} `json:"secureJsonData"`
}
// NewClient initializes client for interacting with an instance of Grafana server;
// apiKeyOrBasicAuth accepts either 'username:password' basic authentication credentials,
// or a Grafana API key. If it is an empty string then no authentication is used.
func NewClient(hostURL string, auth *AuthConfig, httpClient *resty.Client) (*Client, error) {
baseURL, err := url.Parse(hostURL)
if err != nil {
return nil, err
}
client := &Client{
baseURL: baseURL.String(),
auth: auth,
}
if httpClient == nil {
client.client = resty.New()
} else {
client.client = httpClient
}
return client, nil
}
// SetDashboard will create or update grafana dashboard
func (c *Client) SetDashboard(ctx context.Context, db *GrafanaDashboard) (*GrafanaResponse, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, "api/dashboards/db")
resp, err := c.do(ctx, http.MethodPost, u.String(), db)
if err != nil {
return nil, err
}
gResp := &GrafanaResponse{}
err = json.Unmarshal(resp.Body(), gResp)
if err != nil {
return nil, err
}
gResp.StatusCode = resp.StatusCode()
if resp.StatusCode() != http.StatusOK {
return gResp, fmt.Errorf("failed to set dashboard, reason: %v", pointer.String(gResp.Message))
}
return gResp, nil
}
// DeleteDashboardByUID will delete the grafana dashboard with the given uid
func (c *Client) DeleteDashboardByUID(ctx context.Context, uid string) (*GrafanaResponse, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, fmt.Sprintf("api/dashboards/uid/%v", uid))
resp, err := c.do(ctx, http.MethodDelete, u.String(), nil)
if err != nil {
return nil, err
}
gResp := &GrafanaResponse{}
err = json.Unmarshal(resp.Body(), gResp)
if err != nil {
return nil, err
}
gResp.StatusCode = resp.StatusCode()
if resp.StatusCode() != http.StatusOK {
return gResp, fmt.Errorf("failed to delete dashboard, reason: %v", pointer.String(gResp.Message))
}
return gResp, nil
}
// GetCurrentOrg gets current organization.
// It reflects GET /api/org/ API call.
func (c *Client) GetCurrentOrg(ctx context.Context) (*Org, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, "api/org/")
resp, err := c.do(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
if resp.StatusCode() != http.StatusOK {
return nil, fmt.Errorf("failed to get current org, Status Code: %v", resp.StatusCode())
}
org := &Org{}
err = json.Unmarshal(resp.Body(), org)
if err != nil {
return nil, err
}
return org, nil
}
// GetHealth returns the current health status
func (c *Client) GetHealth(ctx context.Context) (*HealthResponse, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, "api/health")
resp, err := c.do(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
health := &HealthResponse{}
err = json.Unmarshal(resp.Body(), health)
if err != nil {
return nil, err
}
return health, nil
}
func (c *Client) do(ctx context.Context, method string, url string, body interface{}) (*resty.Response, error) {
req := c.client.R().SetContext(ctx).SetBody(body)
if c.auth != nil {
if c.auth.BasicAuth != nil {
req = req.SetBasicAuth(c.auth.BasicAuth.Username, c.auth.BasicAuth.Password)
} else {
req = req.SetAuthToken(c.auth.BearerToken)
}
}
var resp *resty.Response
var err error
switch method {
case http.MethodGet:
resp, err = req.Get(url)
case http.MethodPost:
resp, err = req.Post(url)
case http.MethodDelete:
resp, err = req.Delete(url)
case http.MethodPut:
resp, err = req.Put(url)
default:
return nil, errors.New("unsupported http method")
}
if err != nil {
return nil, err
}
return resp, nil
}
func (c *Client) CreateDatasource(ctx context.Context, ds *Datasource) (*GrafanaResponse, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, "api/datasources")
resp, err := c.do(ctx, http.MethodPost, u.String(), ds)
if err != nil {
return nil, err
}
gResp := &GrafanaResponse{}
err = json.Unmarshal(resp.Body(), gResp)
if err != nil {
return nil, err
}
gResp.StatusCode = resp.StatusCode()
if resp.StatusCode() != http.StatusOK {
return gResp, fmt.Errorf("failed to create datasource, reason: %v", pointer.String(gResp.Message))
}
return gResp, nil
}
func (c *Client) UpdateDatasource(ctx context.Context, ds Datasource) (*GrafanaResponse, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, fmt.Sprintf("api/datasources/%v", ds.ID))
resp, err := c.do(ctx, http.MethodPut, u.String(), ds)
if err != nil {
return nil, err
}
gResp := &GrafanaResponse{}
err = json.Unmarshal(resp.Body(), gResp)
if err != nil {
return nil, err
}
gResp.StatusCode = resp.StatusCode()
if resp.StatusCode() != http.StatusOK {
return gResp, fmt.Errorf("failed to update datasource, reason: %v", pointer.String(gResp.Message))
}
return gResp, nil
}
func (c *Client) DeleteDatasource(ctx context.Context, id int) (*GrafanaResponse, error) {
u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, fmt.Sprintf("api/datasources/%v", id))
resp, err := c.do(ctx, http.MethodDelete, u.String(), nil)
if err != nil {
return nil, err
}
gResp := &GrafanaResponse{}
err = json.Unmarshal(resp.Body(), gResp)
if err != nil {
return nil, err
}
gResp.StatusCode = resp.StatusCode()
if resp.StatusCode() != http.StatusOK {
return gResp, fmt.Errorf("failed to delete datasource, reason: %v", pointer.String(gResp.Message))
}
return gResp, nil
}