-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdatasource.go
284 lines (239 loc) · 8.31 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package sqlds
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/grafana/grafana-plugin-sdk-go/data/sqlutil"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt"
"github.com/grafana/grafana-plugin-sdk-go/backend/resource/httpadapter"
"github.com/grafana/grafana-plugin-sdk-go/data"
)
const defaultKeySuffix = "default"
var (
ErrorMissingMultipleConnectionsConfig = PluginError(errors.New("received connection arguments but the feature is not enabled"))
ErrorMissingDBConnection = PluginError(errors.New("unable to get default db connection"))
HeaderKey = "grafana-http-headers"
// Deprecated: ErrorMissingMultipleConnectionsConfig should be used instead
MissingMultipleConnectionsConfig = ErrorMissingMultipleConnectionsConfig
// Deprecated: ErrorMissingDBConnection should be used instead
MissingDBConnection = ErrorMissingDBConnection
)
func defaultKey(datasourceUID string) string {
return fmt.Sprintf("%s-%s", datasourceUID, defaultKeySuffix)
}
func keyWithConnectionArgs(datasourceUID string, connArgs json.RawMessage) string {
return fmt.Sprintf("%s-%s", datasourceUID, string(connArgs))
}
type dbConnection struct {
db *sql.DB
settings backend.DataSourceInstanceSettings
}
type SQLDatasource struct {
Completable
connector *Connector
backend.CallResourceHandler
CustomRoutes map[string]func(http.ResponseWriter, *http.Request)
// Enabling multiple connections may cause that concurrent connection limits
// are hit. The datasource enabling this should make sure connections are cached
// if necessary.
EnableMultipleConnections bool
metrics Metrics
}
// NewDatasource creates a new `SQLDatasource`.
// It uses the provided settings argument to call the ds.Driver to connect to the SQL server
func (ds *SQLDatasource) NewDatasource(ctx context.Context, settings backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) {
conn, err := NewConnector(ctx, ds.driver(), settings, ds.EnableMultipleConnections)
if err != nil {
return nil, DownstreamError(err)
}
ds.connector = conn
mux := http.NewServeMux()
err = ds.registerRoutes(mux)
if err != nil {
return nil, PluginError(err)
}
ds.CallResourceHandler = httpadapter.New(mux)
ds.metrics = NewMetrics(settings.Name, settings.Type, EndpointQuery)
return ds, nil
}
// NewDatasource initializes the Datasource wrapper and instance manager
func NewDatasource(c Driver) *SQLDatasource {
return &SQLDatasource{
connector: &Connector{driver: c},
}
}
// Dispose cleans up datasource instance resources.
// Note: Called when testing and saving a datasource
func (ds *SQLDatasource) Dispose() {
}
// QueryData creates the Responses list and executes each query
func (ds *SQLDatasource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
headers := req.GetHTTPHeaders()
var (
response = NewResponse(backend.NewQueryDataResponse())
wg = sync.WaitGroup{}
)
wg.Add(len(req.Queries))
if queryDataMutator, ok := ds.driver().(QueryDataMutator); ok {
ctx, req = queryDataMutator.MutateQueryData(ctx, req)
}
// Execute each query and store the results by query RefID
for _, q := range req.Queries {
go func(query backend.DataQuery) {
frames, err := ds.handleQuery(ctx, query, headers)
if err == nil {
if responseMutator, ok := ds.driver().(ResponseMutator); ok {
frames, err = responseMutator.MutateResponse(ctx, frames)
if err != nil {
err = PluginError(err)
}
}
}
response.Set(query.RefID, backend.DataResponse{
Frames: frames,
Error: err,
ErrorSource: ErrorSource(err),
})
wg.Done()
}(q)
}
wg.Wait()
errs := ds.errors(response)
if ds.DriverSettings().Errors {
return response.Response(), errs
}
return response.Response(), nil
}
func (ds *SQLDatasource) GetDBFromQuery(ctx context.Context, q *Query) (*sql.DB, error) {
_, dbConn, err := ds.connector.GetConnectionFromQuery(ctx, q)
return dbConn.db, err
}
// handleQuery will call query, and attempt to reconnect if the query failed
func (ds *SQLDatasource) handleQuery(ctx context.Context, req backend.DataQuery, headers http.Header) (data.Frames, error) {
if queryMutator, ok := ds.driver().(QueryMutator); ok {
ctx, req = queryMutator.MutateQuery(ctx, req)
}
// Convert the backend.DataQuery into a Query object
q, err := GetQuery(req, headers, ds.DriverSettings().ForwardHeaders)
if err != nil {
return nil, err
}
// Apply supported macros to the query
q.RawSQL, err = Interpolate(ds.driver(), q)
if err != nil {
return sqlutil.ErrorFrameFromQuery(q), fmt.Errorf("%s: %w", "Could not apply macros", err)
}
// Apply the default FillMode, overwritting it if the query specifies it
fillMode := ds.DriverSettings().FillMode
if q.FillMissing != nil {
fillMode = q.FillMissing
}
// Retrieve the database connection
cacheKey, dbConn, err := ds.connector.GetConnectionFromQuery(ctx, q)
if err != nil {
return sqlutil.ErrorFrameFromQuery(q), err
}
if ds.DriverSettings().Timeout != 0 {
tctx, cancel := context.WithTimeout(ctx, ds.DriverSettings().Timeout)
defer cancel()
ctx = tctx
}
var args []interface{}
if argSetter, ok := ds.driver().(QueryArgSetter); ok {
args = argSetter.SetQueryArgs(ctx, headers)
}
// FIXES:
// * Some datasources (snowflake) expire connections or have an authentication token that expires if not used in 1 or 4 hours.
// Because the datasource driver does not include an option for permanent connections, we retry the connection
// if the query fails. NOTE: this does not include some errors like "ErrNoRows"
dbQuery := NewQuery(dbConn.db, dbConn.settings, ds.driver().Converters(), fillMode)
res, err := dbQuery.Run(ctx, q, args...)
if err == nil {
return res, nil
}
if errors.Is(err, ErrorNoResults) {
return res, nil
}
// If there's a query error that didn't exceed the
// context deadline retry the query
if errors.Is(err, ErrorQuery) && !errors.Is(err, context.DeadlineExceeded) {
// only retry on messages that contain specific errors
if shouldRetry(ds.DriverSettings().RetryOn, err.Error()) {
for i := 0; i < ds.DriverSettings().Retries; i++ {
backend.Logger.Warn(fmt.Sprintf("query failed: %s. Retrying %d times", err.Error(), i))
db, err := ds.connector.Reconnect(ctx, dbConn, q, cacheKey)
if err != nil {
return nil, DownstreamError(err)
}
if ds.DriverSettings().Pause > 0 {
time.Sleep(time.Duration(ds.DriverSettings().Pause * int(time.Second)))
}
dbQuery := NewQuery(db, dbConn.settings, ds.driver().Converters(), fillMode)
res, err = dbQuery.Run(ctx, q, args...)
if err == nil {
return res, err
}
if !shouldRetry(ds.DriverSettings().RetryOn, err.Error()) {
return res, err
}
backend.Logger.Warn(fmt.Sprintf("Retry failed: %s", err.Error()))
}
}
}
// allow retries on timeouts
if errors.Is(err, context.DeadlineExceeded) {
for i := 0; i < ds.DriverSettings().Retries; i++ {
backend.Logger.Warn(fmt.Sprintf("connection timed out. retrying %d times", i))
db, err := ds.connector.Reconnect(ctx, dbConn, q, cacheKey)
if err != nil {
continue
}
dbQuery := NewQuery(db, dbConn.settings, ds.driver().Converters(), fillMode)
res, err = dbQuery.Run(ctx, q, args...)
if err == nil {
return res, err
}
}
}
return res, err
}
// CheckHealth pings the connected SQL database
func (ds *SQLDatasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) {
if checkHealthMutator, ok := ds.driver().(CheckHealthMutator); ok {
ctx, req = checkHealthMutator.MutateCheckHealth(ctx, req)
}
healthChecker := &HealthChecker{
Connector: ds.connector,
Metrics: ds.metrics.WithEndpoint(EndpointHealth),
}
return healthChecker.Check(ctx, req)
}
func (ds *SQLDatasource) DriverSettings() DriverSettings {
return ds.connector.driverSettings
}
func (ds *SQLDatasource) driver() Driver {
return ds.connector.driver
}
func (ds *SQLDatasource) errors(response *Response) error {
if response == nil {
return nil
}
res := response.Response()
if res == nil {
return nil
}
var err error
for _, r := range res.Responses {
err = errors.Join(err, r.Error)
}
if err != nil {
backend.Logger.Error(err.Error())
}
return err
}