Repository navigation
Expand file tree
/
Copy pathmonitoring.go
More file actions
680 lines (605 loc) · 21.1 KB
/
Copy pathmonitoring.go
File metadata and controls
680 lines (605 loc) · 21.1 KB
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"bytes"
"context"
"database/sql/driver"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"runtime"
"strconv"
"time"
"golang.org/x/xerrors"
)
const urlQueriesResultFmt = "/queries/%s/result"
// queryResultStatus is status returned from server
type queryResultStatus int
// Query Status defined at server side
const (
SFQueryRunning queryResultStatus = iota
SFQueryAborting
SFQuerySuccess
SFQueryFailedWithError
SFQueryAborted
SFQueryQueued
SFQueryFailedWithIncident
SFQueryDisconnected
SFQueryResumingWarehouse
// SFQueryQueueRepairingWarehouse present in QueryDTO.java.
SFQueryQueueRepairingWarehouse
SFQueryRestarted
// SFQueryBlocked is when a statement is waiting on a lock on resource held
// by another statement.
SFQueryBlocked
SFQueryNoData
)
func (qs queryResultStatus) String() string {
return [...]string{"RUNNING", "ABORTING", "SUCCESS", "FAILED_WITH_ERROR",
"ABORTED", "QUEUED", "FAILED_WITH_INCIDENT", "DISCONNECTED",
"RESUMING_WAREHOUSE", "QUEUED_REPAIRING_WAREHOUSE", "RESTARTED",
"BLOCKED", "NO_DATA"}[qs]
}
func (qs queryResultStatus) isRunning() bool {
switch qs {
case SFQueryRunning, SFQueryResumingWarehouse, SFQueryQueued,
SFQueryQueueRepairingWarehouse, SFQueryNoData:
return true
default:
return false
}
}
func (qs queryResultStatus) isError() bool {
switch qs {
case SFQueryAborting, SFQueryFailedWithError, SFQueryAborted,
SFQueryFailedWithIncident, SFQueryDisconnected, SFQueryBlocked:
return true
default:
return false
}
}
var strQueryStatusMap = map[string]queryResultStatus{"RUNNING": SFQueryRunning,
"ABORTING": SFQueryAborting, "SUCCESS": SFQuerySuccess,
"FAILED_WITH_ERROR": SFQueryFailedWithError, "ABORTED": SFQueryAborted,
"QUEUED": SFQueryQueued, "FAILED_WITH_INCIDENT": SFQueryFailedWithIncident,
"DISCONNECTED": SFQueryDisconnected,
"RESUMING_WAREHOUSE": SFQueryResumingWarehouse,
"QUEUED_REPAIRING_WAREHOUSE": SFQueryQueueRepairingWarehouse,
"RESTARTED": SFQueryRestarted,
"BLOCKED": SFQueryBlocked, "NO_DATA": SFQueryNoData}
type retStatus struct {
Status string `json:"status"`
SQLText string `json:"sqlText"`
StartTime int64 `json:"startTime"`
EndTime int64 `json:"endTime"`
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
Stats retStats `json:"stats"`
}
type retStats struct {
ScanBytes int64 `json:"scanBytes"`
ProducedRows int64 `json:"producedRows"`
}
type statusResponse struct {
Data struct {
Queries []retStatus `json:"queries"`
} `json:"data"`
Message string `json:"message"`
Code string `json:"code"`
Success bool `json:"success"`
}
func strToQueryStatus(in string) queryResultStatus {
return strQueryStatusMap[in]
}
// SnowflakeQueryStatus is the query status metadata of a snowflake query
type SnowflakeQueryStatus struct {
SQLText string
StartTime int64
EndTime int64
ErrorCode string
ErrorMessage string
ScanBytes int64
ProducedRows int64
Status string
}
// SnowflakeConnection is a wrapper to snowflakeConn that exposes API functions
type SnowflakeConnection interface {
GetQueryStatus(ctx context.Context, queryID string) (*SnowflakeQueryStatus, error)
}
// checkQueryStatus returns the status given the query ID. If successful,
// the error will be nil, indicating there is a complete query result to fetch.
// Other than nil, there are three error types that can be returned:
// 1. ErrQueryStatus, if GS cannot return any kind of status due to any reason,
// i.e. connection, permission, if a query was just submitted, etc.
// 2, ErrQueryReportedError, if the requested query was terminated or aborted
// and GS returned an error status included in query. SFQueryFailedWithError
// 3, ErrQueryIsRunning, if the requested query is still running and might have
// a complete result later, these statuses were listed in query. SFQueryRunning
func (sc *snowflakeConn) checkQueryStatus(
ctx context.Context,
qid string) (
*retStatus, error) {
var statusResp statusResponse
r, err := sc.getMonitoringResult(ctx, "queries", qid, &statusResp)
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response. err: %v", err)
return nil, err
}
headers := make(map[string]string)
param := make(url.Values)
param.Add(requestGUIDKey, NewUUID().String())
if tok, _, _ := sc.rest.TokenAccessor.GetTokens(); tok != "" {
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, tok)
}
resultPath := fmt.Sprintf("/monitoring/queries/%s", qid)
url := sc.rest.getFullURL(resultPath, ¶m)
res, err := sc.rest.FuncGet(ctx, sc.rest, url, headers, sc.rest.RequestTimeout)
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response. err: %v", err)
return nil, err
}
defer res.Body.Close()
if err = json.NewDecoder(res.Body).Decode(&statusResp); err != nil {
logger.WithContext(ctx).Errorf("failed to decode JSON. err: %v", err)
return nil, err
}
_ = r.Body.Close()
if !statusResp.Success || len(statusResp.Data.Queries) == 0 {
logger.WithContext(ctx).Errorf("status query returned not-success or no status returned.")
return nil, (&SnowflakeError{
Number: ErrQueryStatus,
Message: "status query returned not-success or no status returned. Please retry",
}).exceptionTelemetry(sc)
}
queryRet := statusResp.Data.Queries[0]
if queryRet.ErrorCode != "" {
return &queryRet, (&SnowflakeError{
Number: ErrQueryStatus,
Message: errMsgQueryStatus,
MessageArgs: []interface{}{queryRet.ErrorCode, queryRet.ErrorMessage},
IncludeQueryID: true,
QueryID: qid,
}).exceptionTelemetry(sc)
}
// returned errorCode is 0. Now check what is the returned status of the query.
qStatus := strToQueryStatus(queryRet.Status)
if qStatus.isError() {
return &queryRet, (&SnowflakeError{
Number: ErrQueryReportedError,
Message: fmt.Sprintf("%s: status from server: [%s]",
queryRet.ErrorMessage, queryRet.Status),
IncludeQueryID: true,
QueryID: qid,
}).exceptionTelemetry(sc)
}
if qStatus.isRunning() {
return &queryRet, (&SnowflakeError{
Number: ErrQueryIsRunning,
Message: fmt.Sprintf("%s: status from server: [%s]",
queryRet.ErrorMessage, queryRet.Status),
IncludeQueryID: true,
QueryID: qid,
}).exceptionTelemetry(sc)
}
//success
return &queryRet, nil
}
// try using the cache, log the cached result, but return the non
// cached result
func shouldSkipCache(ctx context.Context) bool {
val := ctx.Value(skipCache)
if val == nil {
return false
}
a, ok := val.(bool)
return a && ok
}
// check if we want to log sf response for debugging cache bug
func shouldLogSfResponseForCacheBug(ctx context.Context) bool {
val := ctx.Value(logSfResponseForCacheBug)
if val == nil {
return false
}
a, ok := val.(bool)
return a && ok
}
// Waits 45 seconds for a query response; return early if query finishes
func (sc *snowflakeConn) getQueryResultResp(
ctx context.Context,
resultPath string,
qid string,
) (*execResponse, error) {
var cachedResponse *execResponse
cachedResponse = nil
if respd, ok := sc.execRespCache.load(resultPath); ok {
cachedResponse = respd
// return the cached response, unless we pass the flag saying to
// bypass the cache
if !shouldSkipCache(ctx) {
return respd, nil
}
}
headers := getHeaders()
paramsMutex.Lock()
if serviceName, ok := sc.cfg.Params[serviceName]; ok {
headers[httpHeaderServiceName] = *serviceName
}
paramsMutex.Unlock()
param := make(url.Values)
param.Add(requestIDKey, getOrGenerateRequestIDFromContext(ctx).String())
param.Add("clientStartTime", strconv.FormatInt(sc.currentTimeProvider.currentTime(), 10))
param.Add(requestGUIDKey, NewUUID().String())
token, _, _ := sc.rest.TokenAccessor.GetTokens()
if token != "" {
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, token)
}
url := sc.rest.getFullURL(resultPath, ¶m)
res, err := sc.rest.FuncGet(ctx, sc.rest, url, headers, sc.rest.RequestTimeout)
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response. err: %v", err)
return nil, err
}
// defer for logging sf cache bug if logging is enabled
if res.Body != nil {
defer func() { _ = res.Body.Close() }()
}
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
logger.WithContext(ctx).Errorf("failed to read bytes from result body. err: %v", err)
return nil, err
}
var respd *execResponse
if err = json.NewDecoder(bytes.NewReader(bodyBytes)).Decode(&respd); err != nil {
logger.WithContext(ctx).Errorf("failed to decode JSON. err: %v", err)
return nil, err
}
// log when Success is false but body has data
if !respd.Success && respd.Code == "" && respd.Message == "" {
logger.WithContext(ctx).Errorf("Response body is non-empty but isSuccess is false")
return nil, &SnowflakeError{
Number: ErrBadDriverResponse,
QueryID: qid,
Message: "We received a bad response from the server. Success was false but the code/error body empty",
MessageArgs: nil,
IncludeQueryID: true,
}
}
// log to get data points for sf to debug cache issue, should log only for staging org
if shouldLogSfResponseForCacheBug(ctx) {
logHeader, errHeader := json.Marshal(res.Header)
if errHeader != nil {
logger.WithContext(ctx).Errorf("failed to read header from result header. errHeader: %v", errHeader)
return nil, errHeader
}
// log for debugging header and response when Success is false but body has data
if !respd.Success && respd.Code == "" && respd.Message == "" {
logger.WithContext(ctx).Errorf("request url: %s, headers: %+v", url, headers)
logger.WithContext(ctx).Errorf("failed to build a proper exec response. received body: %s with header %s", string(bodyBytes), string(logHeader))
}
}
// if we are skipping the cache, log difference between cached and non cached result
if shouldSkipCache(ctx) {
qid := respd.Data.QueryID
// if there was no response in the cache anyway, log that and dont try to log anything else
if cachedResponse == nil {
logger.WithContext(ctx).Errorf("cached queryId: %v did not use cache", qid)
} else {
// log if there are any differences in the arrow encooded first chunk
arrowCached := cachedResponse.Data.RowSetBase64
arrowNonCached := respd.Data.RowSetBase64
if arrowCached != arrowNonCached {
logger.WithContext(ctx).Errorf("cached queryId arrow not equal: %v, arrowCached: %v, arrowNonCached: %v", qid, arrowCached, arrowNonCached)
} else {
logger.WithContext(ctx).Errorf("cached queryId: %v arrow portion is the same", qid)
}
// see how many rows there are in the cached chunks
chunksCached := cachedResponse.Data.Chunks
rowsCached := 0
for _, chunk := range chunksCached {
rowsCached += chunk.RowCount
}
// see how many rows there are in non cached chunks
chunksNonCached := cachedResponse.Data.Chunks
rowsNonCached := 0
for _, chunk := range chunksNonCached {
rowsNonCached += chunk.RowCount
}
if rowsNonCached == rowsCached {
logger.WithContext(ctx).Errorf("cached queryId: %v rows from chunks is the same", qid)
} else {
logger.WithContext(ctx).Errorf("cached queryId rows from chunks not equal: %v, rowsCached: %v, rowsNonCached: %v", qid, rowsCached, rowsNonCached)
}
}
}
if respd.Success {
sc.execRespCache.store(resultPath, respd)
}
return respd, nil
}
// Waits for the query to complete, then returns the response
func (sc *snowflakeConn) waitForCompletedQueryResultResp(
ctx context.Context,
resultPath string,
qid string,
) (*execResponse, error) {
// if we already have the response; return that
cachedResponse, ok := sc.execRespCache.load(resultPath)
logger.WithContext(ctx).Errorf("use cache: %v", ok)
if ok {
return cachedResponse, nil
}
requestID := getOrGenerateRequestIDFromContext(ctx)
headers := getHeaders()
if serviceName, ok := sc.cfg.Params[serviceName]; ok {
headers[httpHeaderServiceName] = *serviceName
}
param := make(url.Values)
param.Add(requestIDKey, requestID.String())
param.Add("clientStartTime", strconv.FormatInt(time.Now().Unix(), 10))
param.Add(requestGUIDKey, NewUUID().String())
token, _, _ := sc.rest.TokenAccessor.GetTokens()
if token != "" {
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, token)
}
url := sc.rest.getFullURL(resultPath, ¶m)
// internally, pulls on FuncGet until we have a result at the result location (queryID)
var response *execResponse
var err error
retries := 0
startTime := time.Now()
for response == nil || isQueryInProgress(response) || badResponse(ctx, response, qid, &retries, err) {
response, err = sc.rest.getAsyncOrStatus(WithReportAsyncError(ctx), url, headers, sc.rest.RequestTimeout)
// if the context is canceled, we have to cancel it manually now
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response. err: %v", err)
if err == context.Canceled || err == context.DeadlineExceeded {
// use the default top level 1 sec timeout for cancellation as throughout the driver
if err := cancelQuery(context.TODO(), sc.rest, requestID, time.Second); err != nil {
logger.WithContext(ctx).Errorf("failed to cancel async query, err: %v", err)
}
}
return nil, err
}
}
if response.Success {
sc.execRespCache.store(resultPath, response)
} else {
logEverything(ctx, qid, response, startTime)
}
return response, nil
}
// we want to retry if the query was not successful, but also did not fail
func badResponse(ctx context.Context, response *execResponse, qid string, retries *int, err error) bool {
retryable := false
// retry if query failed but there is no error
if (!response.Success) && (err == nil) && (*retries < 3) {
*retries++
retryable = true
}
logger.WithContext(ctx).Errorf("should retry queryId: %v, retryable: %v", qid, retryable)
return retryable
}
func logEverything(ctx context.Context, qid string, response *execResponse, startTime time.Time) {
deadline, ok := ctx.Deadline()
logger.WithContext(ctx).Errorf("failed queryId: %v, deadline: %v, ok: %v", qid, deadline, ok)
logger.WithContext(ctx).Errorf("failed queryId: %v, runtime: %v", qid, time.Now().Sub(startTime))
var pcs [32]uintptr
stackEntries := runtime.Callers(1, pcs[:])
stackTrace := pcs[0:stackEntries]
logger.WithContext(ctx).Errorf("failed queryId: %v, stackTrace: %v", qid, stackTrace)
select {
case <-ctx.Done():
cancelReason := ctx.Err()
logger.WithContext(ctx).Errorf("failed queryId: %v, cancel reason: %v", qid, cancelReason)
default:
logger.WithContext(ctx).Errorf("failed queryId: %v, query not canceled", qid)
}
logger.WithContext(ctx).Errorf("failed queryId: %v, response message: %v", qid, response.Message)
logger.WithContext(ctx).Errorf("failed queryId: %v, response code: %v", qid, response.Code)
}
// Fetch query result for a query id from /queries/<qid>/result endpoint.
func (sc *snowflakeConn) rowsForRunningQuery(
ctx context.Context, qid string,
rows *snowflakeRows) error {
resultPath := fmt.Sprintf(urlQueriesResultFmt, qid)
resp, err := sc.getQueryResultResp(ctx, resultPath, qid)
if err != nil {
logger.WithContext(ctx).Errorf("error: %v", err)
return err
}
// the result response sometimes contains only Data and not anything else. We parse the error code only
// if it's set in the response
if !resp.Success && resp.Code != "" {
message := resp.Message
code, err := strconv.Atoi(resp.Code)
if err != nil {
code = ErrQueryStatus
message = fmt.Sprintf("%s: (failed to parse original code: %s: %s)", message, resp.Code, err.Error())
}
return (&SnowflakeError{
Number: code,
SQLState: resp.Data.SQLState,
Message: message,
QueryID: resp.Data.QueryID,
}).exceptionTelemetry(sc)
}
rows.addDownloader(populateChunkDownloader(ctx, sc, resp.Data))
return nil
}
// Wait for query to complete from a query id from /queries/<qid>/result endpoint.
func (sc *snowflakeConn) blockOnRunningQuery(
ctx context.Context, qid string) error {
resultPath := fmt.Sprintf(urlQueriesResultFmt, qid)
resp, err := sc.waitForCompletedQueryResultResp(ctx, resultPath, qid)
if err != nil {
logger.WithContext(ctx).Errorf("error: %v", err)
if resp != nil {
code := -1
if resp.Code != "" {
code, err = strconv.Atoi(resp.Code)
if err != nil {
return err
}
return (&SnowflakeError{
Number: code,
SQLState: resp.Data.SQLState,
Message: err.Error(),
QueryID: resp.Data.QueryID,
}).exceptionTelemetry(sc)
}
if code == -1 {
ok, deadline := ctx.Deadline()
logger.WithContext(ctx).Errorf("deadline: %v, ok: %v, queryId: %v", deadline, ok, resp.Data.QueryID)
logger.WithContext(ctx).Errorf("resp.success: %v, message: %v, error: %v, queryId: %v", resp.Success, resp.Message, err, resp.Data.QueryID)
if sc.rest == nil {
logger.WithContext(ctx).Errorf("sullSnowflakeRestful")
}
}
}
return err
}
if !resp.Success {
message := resp.Message
code := -1
if resp.Code != "" {
code, err = strconv.Atoi(resp.Code)
if err != nil {
code = ErrQueryStatus
message = fmt.Sprintf("%s: (failed to parse original code: %s: %s)", message, resp.Code, err.Error())
}
return (&SnowflakeError{
Number: code,
SQLState: resp.Data.SQLState,
Message: message,
QueryID: resp.Data.QueryID,
}).exceptionTelemetry(sc)
}
if code == -1 {
ok, deadline := ctx.Deadline()
logger.WithContext(ctx).Errorf("deadline: %v, ok: %v, queryId: %v", deadline, ok, resp.Data.QueryID)
logger.WithContext(ctx).Errorf("resp.success: %v, message: %v, error: %v, queryId: %v", resp.Success, resp.Message, err, resp.Data.QueryID)
if sc.rest == nil {
logger.WithContext(ctx).Errorf("sullSnowflakeRestful")
}
}
}
return nil
}
// prepare a Rows object to return for query of 'qid'
func (sc *snowflakeConn) buildRowsForRunningQuery(
ctx context.Context,
qid string) (
driver.Rows, error) {
rows := new(snowflakeRows)
rows.sc = sc
rows.queryID = qid
if err := sc.rowsForRunningQuery(ctx, qid, rows); err != nil {
return nil, err
}
if err := rows.ChunkDownloader.start(); err != nil {
return nil, err
}
return rows, nil
}
func (sc *snowflakeConn) blockOnQueryCompletion(
ctx context.Context,
qid string,
) error {
if err := sc.blockOnRunningQuery(ctx, qid); err != nil {
return err
}
return nil
}
func mkMonitoringFetcher(sc *snowflakeConn, qid string, runtime time.Duration) *monitoringResult {
// Exit early if this was a "fast" query
if runtime < sc.cfg.MonitoringFetcher.QueryRuntimeThreshold {
return nil
}
queryGraphChan := make(chan *QueryGraphData, 1)
go queryGraph(sc, qid, queryGraphChan)
monitoringChan := make(chan *QueryMonitoringData, 1)
go monitoring(sc, qid, monitoringChan)
return &monitoringResult{
monitoringChan: monitoringChan,
queryGraphChan: queryGraphChan,
}
}
func monitoring(
sc *snowflakeConn,
qid string,
resp chan<- *QueryMonitoringData,
) {
defer close(resp)
ctx, cancel := context.WithTimeout(context.Background(), sc.cfg.MonitoringFetcher.MaxDuration)
defer cancel()
var queryMonitoringData *QueryMonitoringData
for {
var m monitoringResponse
res, err := sc.getMonitoringResult(ctx, "queries", qid, &m)
if err != nil {
break
}
_ = res.Body.Close()
if len(m.Data.Queries) == 1 {
queryMonitoringData = &m.Data.Queries[0]
if !strToQueryStatus(queryMonitoringData.Status).isRunning() {
break
}
}
time.Sleep(sc.cfg.MonitoringFetcher.RetrySleepDuration)
}
if queryMonitoringData != nil {
resp <- queryMonitoringData
}
return
}
func queryGraph(
sc *snowflakeConn,
qid string,
resp chan<- *QueryGraphData,
) {
defer close(resp)
// Bound the GET request to 1 second in the absolute worst case.
ctx, cancel := context.WithTimeout(context.Background(), sc.cfg.MonitoringFetcher.MaxDuration)
defer cancel()
var qg queryGraphResponse
res, err := sc.getMonitoringResult(ctx, "query-plan-data", qid, &qg)
if err == nil {
res.Body.Close()
if qg.Success {
resp <- &qg.Data
}
}
}
// getMonitoringResult fetches the result at /monitoring/queries/qid and
// deserializes it into the provided res (which is given as a generic interface
// to allow different callers to request different views on the raw response)
func (sc *snowflakeConn) getMonitoringResult(ctx context.Context, endpoint, qid string, res interface{}) (*http.Response, error) {
sc.restMu.RLock()
defer sc.restMu.RUnlock()
headers := make(map[string]string)
param := make(url.Values)
param.Add(requestGUIDKey, NewUUID().String())
if sc.rest == nil || sc.rest.TokenAccessor == nil {
return nil, xerrors.Errorf("missing token accessor when getting monitoring data")
}
if tok, _, _ := sc.rest.TokenAccessor.GetTokens(); tok != "" {
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, tok)
}
resultPath := fmt.Sprintf("/monitoring/%s/%s", endpoint, qid)
url := sc.rest.getFullURL(resultPath, ¶m)
resp, err := sc.rest.FuncGet(ctx, sc.rest, url, headers, sc.rest.RequestTimeout)
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response for %s. err: %v", endpoint, err)
return nil, err
}
err = json.NewDecoder(resp.Body).Decode(res)
if err != nil {
logger.WithContext(ctx).Errorf("failed to decode JSON. err: %v", err)
resp.Body.Close()
return nil, err
}
return resp, nil
}