forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restful.go
420 lines (382 loc) · 12.1 KB
/
restful.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
// Copyright (c) 2017-2018 Snowflake Computing Inc. All right reserved.
package gosnowflake
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
"github.com/satori/go.uuid"
)
const (
headerSnowflakeToken = "Snowflake Token=\"%v\""
headerAuthorizationKey = "Authorization"
headerContentTypeApplicationJSON = "application/json"
headerAcceptTypeApplicationSnowflake = "application/snowflake"
sessionExpiredCode = "390112"
queryInProgressCode = "333333"
queryInProgressAsyncCode = "333334"
)
type snowflakeRestful struct {
Host string
Port int
Protocol string
LoginTimeout time.Duration // Login timeout
RequestTimeout time.Duration // request timeout
Authenticator string
Client *http.Client
Token string
MasterToken string
SessionID int
Connection *snowflakeConn
FuncPostQuery func(context.Context, *snowflakeRestful, *url.Values, map[string]string, []byte, time.Duration) (*execResponse, error)
FuncPostQueryHelper func(context.Context, *snowflakeRestful, *url.Values, map[string]string, []byte, time.Duration, string) (*execResponse, error)
FuncPost func(context.Context, *snowflakeRestful, string, map[string]string, []byte, time.Duration, bool) (*http.Response, error)
FuncGet func(context.Context, *snowflakeRestful, string, map[string]string, time.Duration) (*http.Response, error)
FuncRenewSession func(context.Context, *snowflakeRestful) error
FuncPostAuth func(*snowflakeRestful, *url.Values, map[string]string, []byte, time.Duration) (*authResponse, error)
FuncCloseSession func(*snowflakeRestful) error
FuncCancelQuery func(*snowflakeRestful, string) error
FuncPostAuthSAML func(*snowflakeRestful, map[string]string, []byte, time.Duration) (*authResponse, error)
FuncPostAuthOKTA func(*snowflakeRestful, map[string]string, []byte, string, time.Duration) (*authOKTAResponse, error)
FuncGetSSO func(*snowflakeRestful, *url.Values, map[string]string, string, time.Duration) ([]byte, error)
}
type renewSessionResponse struct {
Data renewSessionResponseMain `json:"data"`
Message string `json:"message"`
Code string `json:"code"`
Success bool `json:"success"`
}
type renewSessionResponseMain struct {
SessionToken string `json:"sessionToken"`
ValidityInSecondsST time.Duration `json:"validityInSecondsST"`
MasterToken string `json:"masterToken"`
ValidityInSecondsMT time.Duration `json:"validityInSecondsMT"`
SessionID int `json:"sessionId"`
}
type cancelQueryResponse struct {
Data interface{} `json:"data"`
Message string `json:"message"`
Code string `json:"code"`
Success bool `json:"success"`
}
func postRestful(
ctx context.Context,
sr *snowflakeRestful,
fullURL string,
headers map[string]string,
body []byte,
timeout time.Duration,
raise4XX bool) (
*http.Response, error) {
return retryHTTP(ctx, sr.Client, http.NewRequest, "POST", fullURL, headers, body, timeout, raise4XX)
}
func getRestful(
ctx context.Context,
sr *snowflakeRestful,
fullURL string,
headers map[string]string,
timeout time.Duration) (
*http.Response, error) {
return retryHTTP(ctx, sr.Client, http.NewRequest, "GET", fullURL, headers, nil, timeout, false)
}
type execResponseAndErr struct {
resp *execResponse
err error
}
func postRestfulQuery(
ctx context.Context,
sr *snowflakeRestful,
params *url.Values,
headers map[string]string,
body []byte,
timeout time.Duration) (
data *execResponse, err error) {
requestID := uuid.Must(uuid.NewV4()).String()
execResponseChan := make(chan execResponseAndErr)
go func() {
data, err := sr.FuncPostQueryHelper(ctx, sr, params, headers, body, timeout, requestID)
execResp := execResponseAndErr{data, err}
execResponseChan <- execResp
close(execResponseChan)
}()
select {
case <-ctx.Done():
err := sr.FuncCancelQuery(sr, requestID)
if err != nil {
return nil, err
}
return nil, ctx.Err()
case respAndErr := <-execResponseChan:
return respAndErr.resp, respAndErr.err
}
}
func postRestfulQueryHelper(
ctx context.Context,
sr *snowflakeRestful,
params *url.Values,
headers map[string]string,
body []byte,
timeout time.Duration,
requestID string) (
data *execResponse, err error) {
glog.V(2).Infof("params: %v", params)
params.Add("requestId", requestID)
if sr.Token != "" {
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, sr.Token)
}
fullURL := fmt.Sprintf(
"%s://%s:%d%s", sr.Protocol, sr.Host, sr.Port,
"/queries/v1/query-request?"+params.Encode())
resp, err := sr.FuncPost(ctx, sr, fullURL, headers, body, timeout, false)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
glog.V(2).Infof("postQuery: resp: %v", resp)
var respd execResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return nil, err
}
if respd.Code == sessionExpiredCode {
err = sr.FuncRenewSession(ctx, sr)
if err != nil {
return nil, err
}
return sr.FuncPostQuery(ctx, sr, params, headers, body, timeout)
}
var resultURL string
isSessionRenewed := false
for isSessionRenewed || respd.Code == queryInProgressCode ||
respd.Code == queryInProgressAsyncCode {
if !isSessionRenewed {
resultURL = respd.Data.GetResultURL
}
glog.V(2).Info("ping pong")
glog.Flush()
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, sr.Token)
fullURL := fmt.Sprintf(
"%s://%s:%d%s", sr.Protocol, sr.Host, sr.Port, resultURL)
resp, err = sr.FuncGet(ctx, sr, fullURL, headers, 0)
respd = execResponse{} // reset the response
err = json.NewDecoder(resp.Body).Decode(&respd)
resp.Body.Close()
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return nil, err
}
if respd.Code == sessionExpiredCode {
err = sr.FuncRenewSession(ctx, sr)
if err != nil {
return nil, err
}
isSessionRenewed = true
} else {
isSessionRenewed = false
}
}
return &respd, nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
return nil, err
}
glog.V(1).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
glog.V(1).Infof("Header: %v", resp.Header)
glog.Flush()
return nil, &SnowflakeError{
Number: ErrFailedToPostQuery,
SQLState: SQLStateConnectionFailure,
Message: errMsgFailedToPostQuery,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
func closeSession(sr *snowflakeRestful) error {
glog.V(2).Info("close session")
params := &url.Values{}
params.Add("delete", "true")
params.Add("requestId", uuid.Must(uuid.NewV4()).String())
fullURL := fmt.Sprintf(
"%s://%s:%d%s", sr.Protocol, sr.Host, sr.Port, "/session?"+params.Encode())
headers := make(map[string]string)
headers["Content-Type"] = headerContentTypeApplicationJSON
headers["accept"] = headerAcceptTypeApplicationSnowflake
headers["User-Agent"] = userAgent
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, sr.Token)
resp, err := sr.FuncPost(context.TODO(), sr, fullURL, headers, nil, 5*time.Second, false)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var respd renewSessionResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return err
}
if !respd.Success && respd.Code != sessionExpiredCode {
c, err := strconv.Atoi(respd.Code)
if err != nil {
return err
}
return &SnowflakeError{
Number: c,
Message: respd.Message,
}
}
return nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
glog.Flush()
return err
}
glog.V(1).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
glog.V(1).Infof("Header: %v", resp.Header)
glog.Flush()
return &SnowflakeError{
Number: ErrFailedToCloseSession,
SQLState: SQLStateConnectionFailure,
Message: errMsgFailedToCloseSession,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
func renewRestfulSession(ctx context.Context, sr *snowflakeRestful) error {
glog.V(2).Info("start renew session")
params := &url.Values{}
params.Add("requestId", uuid.Must(uuid.NewV4()).String())
fullURL := fmt.Sprintf(
"%s://%s:%d%s", sr.Protocol, sr.Host, sr.Port, "/session/token-request?"+params.Encode())
headers := make(map[string]string)
headers["Content-Type"] = headerContentTypeApplicationJSON
headers["accept"] = headerAcceptTypeApplicationSnowflake
headers["User-Agent"] = userAgent
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, sr.MasterToken)
body := make(map[string]string)
body["oldSessionToken"] = sr.Token
body["requestType"] = "RENEW"
var reqBody []byte
reqBody, err := json.Marshal(body)
if err != nil {
return err
}
resp, err := sr.FuncPost(ctx, sr, fullURL, headers, reqBody, sr.RequestTimeout, false)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var respd renewSessionResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return err
}
if !respd.Success {
c, err := strconv.Atoi(respd.Code)
if err != nil {
return err
}
return &SnowflakeError{
Number: c,
Message: respd.Message,
}
}
sr.Token = respd.Data.SessionToken
sr.MasterToken = respd.Data.MasterToken
return nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
glog.Flush()
return err
}
glog.V(1).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
glog.V(1).Infof("Header: %v", resp.Header)
glog.Flush()
return &SnowflakeError{
Number: ErrFailedToRenewSession,
SQLState: SQLStateConnectionFailure,
Message: errMsgFailedToRenew,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
func cancelQuery(sr *snowflakeRestful, requestID string) error {
glog.V(2).Info("cancel query")
params := &url.Values{}
params.Add("requestId", uuid.Must(uuid.NewV4()).String())
fullURL := fmt.Sprintf(
"%s://%s:%d%s", sr.Protocol, sr.Host, sr.Port, "/queries/v1/abort-request?"+params.Encode())
headers := make(map[string]string)
headers["Content-Type"] = headerContentTypeApplicationJSON
headers["accept"] = headerAcceptTypeApplicationSnowflake
headers["User-Agent"] = userAgent
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, sr.Token)
req := make(map[string]string)
req["requestId"] = requestID
reqByte, err := json.Marshal(req)
if err != nil {
return err
}
resp, err := sr.FuncPost(context.TODO(), sr, fullURL, headers, reqByte, 0, false)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var respd cancelQueryResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return err
}
if !respd.Success && respd.Code == sessionExpiredCode {
err := sr.FuncRenewSession(context.TODO(), sr)
if err != nil {
return err
}
return sr.FuncCancelQuery(sr, requestID)
} else if respd.Success {
return nil
} else {
c, err := strconv.Atoi(respd.Code)
if err != nil {
return err
}
return &SnowflakeError{
Number: c,
Message: respd.Message,
}
}
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
glog.Flush()
return err
}
glog.V(1).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
glog.V(1).Infof("Header: %v", resp.Header)
glog.Flush()
return &SnowflakeError{
Number: ErrFailedToCancelQuery,
SQLState: SQLStateConnectionFailure,
Message: errMsgFailedToCancelQuery,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}