-
Notifications
You must be signed in to change notification settings - Fork 0
/
datasource.go
267 lines (217 loc) · 8.04 KB
/
datasource.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
package grafana
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/google/uuid"
"github.com/valyala/fasthttp"
)
var (
ErrGrafanaDatasourceAlreadyExists = errors.New("grafana datasource already exists")
ErrGrafanaDatasourceNotFound = errors.New("grafana datasource not found")
)
// DatasourceId define a unique dashboard identifier.
type DatasourceId uuid.UUID
// ParseDatasourceId parses the given string and return a DatasourceId if its valid.
// A valid DatasourceId is a valid UUID v4.
func ParseDatasourceId(datasourceID string) (DatasourceId, error) {
id, err := uuid.Parse(datasourceID)
if err != nil {
return DatasourceId{}, err
}
return DatasourceId(id), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (did *DatasourceId) UnmarshalJSON(rawJSON []byte) error {
rawJSON = bytes.TrimPrefix(rawJSON, []byte(`"`))
rawJSON = bytes.TrimSuffix(rawJSON, []byte(`"`))
var err error
*did, err = ParseDatasourceId(string(rawJSON))
if err != nil {
return err
}
return nil
}
// MarshalJSON implements json.Marshaler.
func (did DatasourceId) MarshalJSON() ([]byte, error) {
return json.Marshal(uuid.UUID(did))
}
// String implements fmt.Stringer.
func (did DatasourceId) String() string {
return uuid.UUID(did).String()
}
// Datasource define data sources for grafana dashboards.
type Datasource struct {
Access string `json:"access,omitempty"`
BasicAuth bool `json:"basicAuth,omitempty"`
Database string `json:"database,omitempty"`
Id int64 `json:"id,omitempty"`
IsDefault bool `json:"isDefault,omitempty"`
JSONData map[string]any `json:"jsonData,omitempty"`
SecureJSONData map[string]any `json:"secureJsonData"`
Name string `json:"name,omitempty"`
OrgId OrgId `json:"orgId,omitempty"`
ReadOnly bool `json:"readOnly,omitempty"`
Type string `json:"type,omitempty"`
TypeLogoUrl string `json:"typeLogoUrl,omitempty"`
TypeName string `json:"typeName,omitempty"`
Uid DatasourceId `json:"uid,omitempty"`
URL string `json:"url,omitempty"`
User string `json:"user,omitempty"`
Version uint `json:"version,omitempty"`
}
// CreateDatasource creates a datasource in the given organization.
func (c Client) CreateDatasource(ctx context.Context, orgId OrgId, name string, srcType string, isDefault bool) (Datasource, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("POST")
req.SetRequestURI(c.cfg.Url + "/api/datasources")
req.Header.Set(GrafanaOrgIdHeader, fmt.Sprint(orgId))
type requestBody struct {
Access string `json:"access"`
IsDefault bool `json:"isDefault"`
Name string `json:"name"`
Type string `json:"type"`
}
jsonBody, err := json.Marshal(requestBody{
Access: "proxy",
IsDefault: isDefault,
Name: name,
Type: srcType,
})
if err != nil {
panic(err)
}
req.Header.SetContentType("application/json")
req.SetBody(jsonBody)
c.addAuthorizationHeader(req)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err = c.do(ctx, req, resp)
if err != nil {
return Datasource{}, fmt.Errorf("failed to query grafana to create a datasource: %w", err)
}
// Handle errors.
if resp.StatusCode() == 409 && strings.Contains(string(resp.Body()), "data source with the same name already exists") {
return Datasource{}, ErrGrafanaDatasourceAlreadyExists
} else if resp.StatusCode() != 200 {
return Datasource{}, fmt.Errorf("failed to create grafana datasource: %v %v", resp.StatusCode(), string(resp.Body()))
}
type responseBody struct {
Datasource Datasource `json:"datasource"`
}
respBody := responseBody{}
err = json.Unmarshal(resp.Body(), &respBody)
if err != nil {
return Datasource{}, fmt.Errorf("failed to parse grafana response: %w", err)
}
return respBody.Datasource, nil
}
// UpdateDatasource updates datasource in the given organization.
func (c Client) UpdateDatasource(ctx context.Context, orgId OrgId, datasource Datasource) error {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("PUT")
req.SetRequestURI(fmt.Sprintf("%v/api/datasources/uid/%v", c.cfg.Url, datasource.Uid))
req.Header.Set(GrafanaOrgIdHeader, fmt.Sprint(orgId))
jsonBody, err := json.Marshal(datasource)
if err != nil {
panic(err)
}
req.Header.SetContentType("application/json")
req.SetBody(jsonBody)
c.addAuthorizationHeader(req)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err = c.do(ctx, req, resp)
if err != nil {
return fmt.Errorf("failed to query grafana to update a datasource: %w", err)
}
// Handle errors.
if resp.StatusCode() != 200 {
return fmt.Errorf("failed to update grafana datasource: %v %v", resp.StatusCode(), string(resp.Body()))
}
respBody := Datasource{}
err = json.Unmarshal(resp.Body(), &respBody)
if err != nil {
return fmt.Errorf("failed to parse grafana response: %w", err)
}
return nil
}
// ListDatasources returns a list of datasource present in the given organization.
func (c Client) ListDatasources(ctx context.Context, orgId OrgId) ([]Datasource, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("GET")
req.SetRequestURI(fmt.Sprintf("%v/api/datasources", c.cfg.Url))
c.addAuthorizationHeader(req)
req.Header.Set(GrafanaOrgIdHeader, fmt.Sprint(orgId))
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.do(ctx, req, resp)
if err != nil {
return nil, fmt.Errorf("failed to query grafana to update a datasource: %w", err)
}
// Handle errors.
if resp.StatusCode() != 200 {
return nil, fmt.Errorf("failed to create grafana organization: %v %v", resp.StatusCode(), string(resp.Body()))
}
var respBody []Datasource
err = json.Unmarshal(resp.Body(), &respBody)
if err != nil {
return nil, fmt.Errorf("failed to parse grafana response: %w", err)
}
return respBody, nil
}
// DeleteDatasourceByName deletes datasource with the given name inside the given organization.
func (c Client) DeleteDatasourceByName(ctx context.Context, orgId OrgId, name string) error {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("DELETE")
req.SetRequestURI(fmt.Sprintf("%v/api/datasources/name/%v", c.cfg.Url, name))
c.addAuthorizationHeader(req)
req.Header.Set(GrafanaOrgIdHeader, fmt.Sprint(orgId))
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.do(ctx, req, resp)
if err != nil {
return fmt.Errorf("failed to query grafana to update a datasource: %w", err)
}
// Handle errors.
if resp.StatusCode() == 404 {
return ErrGrafanaDatasourceNotFound
} else if resp.StatusCode() != 200 {
return fmt.Errorf("failed to create grafana organization: %v %v", resp.StatusCode(), string(resp.Body()))
}
return nil
}
// GetDatasourceByName retrieves datasource with the given name.
func (c Client) GetDatasourceByName(ctx context.Context, orgId OrgId, name string) (Datasource, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("GET")
req.SetRequestURI(fmt.Sprintf("%v/api/datasources/name/%v", c.cfg.Url, name))
c.addAuthorizationHeader(req)
req.Header.Set(GrafanaOrgIdHeader, fmt.Sprint(orgId))
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.do(ctx, req, resp)
if err != nil {
return Datasource{}, fmt.Errorf("failed to query grafana to retrieve a datasource by name: %w", err)
}
// Handle errors.
if resp.StatusCode() == 404 {
return Datasource{}, ErrGrafanaDatasourceNotFound
} else if resp.StatusCode() != 200 {
return Datasource{}, fmt.Errorf("failed to retrieve grafana datasource by name: %v %v", resp.StatusCode(), string(resp.Body()))
}
respBody := Datasource{}
err = json.Unmarshal(resp.Body(), &respBody)
if err != nil {
return Datasource{}, fmt.Errorf("failed to parse grafana response: %w", err)
}
return respBody, nil
}