-
Notifications
You must be signed in to change notification settings - Fork 39
/
conn.go
266 lines (223 loc) · 7.13 KB
/
conn.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
package kusto
// conn.go holds the connection to the Kusto server and provides methods to do queries
// and receive Kusto frames back.
import (
"bytes"
"compress/flate"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/Azure/azure-kusto-go/kusto/errors"
"github.com/Azure/go-autorest/autorest"
"github.com/google/uuid"
)
var bufferPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
// conn provides connectivity to a Kusto instance.
type conn struct {
endpoint string
auth autorest.Authorizer
endMgmt, endQuery, streamQuery *url.URL
reqHeaders http.Header
headersPool chan http.Header
client *http.Client
}
// newConn returns a new conn object.
func newConn(endpoint string, auth Authorization, timeout time.Duration) (*conn, error) {
headers := http.Header{}
headers.Add("Accept", "application/json")
headers.Add("Accept-Encoding", "gzip,deflate")
headers.Add("x-ms-client-version", "Kusto.Go.Client: "+version)
u, err := url.Parse(endpoint)
if err != nil {
return nil, errors.E(errors.OpServConn, errors.KClientArgs, fmt.Errorf("could not parse the endpoint(%s): %s", endpoint, err))
}
c := &conn{
auth: auth.Authorizer,
endMgmt: &url.URL{Scheme: u.Scheme, Host: u.Host, Path: "/v1/rest/mgmt"},
endQuery: &url.URL{Scheme: u.Scheme, Host: u.Host, Path: "/v2/rest/query"},
streamQuery: &url.URL{Scheme: u.Scheme, Host: u.Host, Path: "/v1/rest/ingest/"},
reqHeaders: headers,
headersPool: make(chan http.Header, 100),
client: &http.Client{
Timeout: timeout,
},
}
// Fills a pool of headers to alleviate header copying timing at request time.
// These are automatically renewed by spun off goroutines when a header is pulled.
// TODO(jdoak): Decide if a sync.Pool would be better. In 1.13 they aren't triggering GC nearly as much.
for i := 0; i < 100; i++ {
c.headersPool <- copyHeaders(headers)
}
return c, nil
}
type queryMsg struct {
DB string `json:"db"`
CSL string `json:"csl"`
Properties requestProperties `json:"properties,omitempty"`
}
var writeRE = regexp.MustCompile(`(\.set|\.append|\.set-or-append|\.set-or-replace)`)
// query makes a query for the purpose of extracting data from Kusto. Context can be used to set
// a timeout or cancel the query. Queries cannot take longer than 5 minutes.
func (c *conn) query(ctx context.Context, db string, query Stmt, options ...QueryOption) (execResp, error) {
params, err := query.params.toParameters(query.defs)
if err != nil {
return execResp{}, errors.E(errors.OpQuery, errors.KClientArgs, fmt.Errorf("QueryValues in the the Stmt were incorrect: %s", err))
}
opt := &queryOptions{
requestProperties: &requestProperties{
Options: map[string]interface{}{
"results_progressive_enabled": true, // We want progressive frames by default.
},
Parameters: params,
},
}
for _, o := range options {
o(opt)
}
if writeRE.MatchString(query.String()) {
if !opt.canWrite {
return execResp{}, errors.E(
errors.OpQuery,
errors.KClientArgs,
fmt.Errorf("Query() attempted to do a write operation. "+
"This requires the AllowWrite() QueryOption to be passed. "+
"Please see documentation on that option before use"),
)
}
}
return c.execute(ctx, execQuery, db, query, "", *opt.requestProperties)
}
// mgmt is used to do management queries to Kusto.
func (c *conn) mgmt(ctx context.Context, db string, query Stmt, options ...QueryOption) (execResp, error) {
opt := &queryOptions{
requestProperties: &requestProperties{
Options: map[string]interface{}{},
Parameters: map[string]string{},
},
}
for _, o := range options {
o(opt)
}
return c.execute(ctx, execMgmt, db, query, "", *opt.requestProperties)
}
const (
execUnknown = 0
execQuery = 1
execMgmt = 2
)
type execResp struct {
reqHeader http.Header
respHeader http.Header
frameCh chan frame
}
func newKustoRequest(ctx context.Context, c conn, op errors.Op, db string, query Stmt, properties requestProperties) (*http.Request, error) {
headers := <-c.headersPool
go func() {
c.headersPool <- copyHeaders(c.reqHeaders)
}()
var endpoint *url.URL
buff := bufferPool.Get().(*bytes.Buffer)
buff.Reset()
defer bufferPool.Put(buff)
headers.Add("Content-Type", "application/json; charset=utf-8")
headers.Add("x-ms-client-request-id", "KGC.execute;"+uuid.New().String())
var err error
err = json.NewEncoder(buff).Encode(
queryMsg{
DB: db,
CSL: query.String(),
Properties: properties,
},
)
if err != nil {
return nil, errors.E(op, errors.KClientInternal, fmt.Errorf("could not JSON marshal the Query message: %s", err))
}
if op == errors.OpQuery {
endpoint = c.endQuery
} else {
endpoint = c.endMgmt
}
req := &http.Request{
Method: http.MethodPost,
URL: endpoint,
Header: headers,
Body: ioutil.NopCloser(buff),
}
if c.auth != nil {
prep := c.auth.WithAuthorization()
req, err = prep(autorest.CreatePreparer()).Prepare(req)
}
if err != nil {
return nil, errors.E(op, errors.KClientInternal, err)
}
req.WithContext(ctx)
return req, nil
}
func bodyFromResponse(resp http.Response, op errors.Op) (io.Reader, error) {
var err error
body := resp.Body
switch enc := strings.ToLower(resp.Header.Get("Content-Encoding")); enc {
case "":
// Do nothing
case "gzip":
body, err = gzip.NewReader(resp.Body)
if err != nil {
return nil, errors.E(op, errors.KClientInternal, fmt.Errorf("gzip reader error: %s", err))
}
case "deflate":
body = flate.NewReader(resp.Body)
default:
return nil, errors.ES(op, errors.KClientInternal, "Content-Encoding was unrecognized: %s", enc)
}
return body, nil
}
func (c *conn) execute(ctx context.Context, execType int, db string, query Stmt, payload string, properties requestProperties) (execResp, error) {
var op errors.Op
if execType == execQuery {
op = errors.OpQuery
} else if execType == execMgmt {
op = errors.OpMgmt
}
kReq, err := newKustoRequest(ctx, *c, op, db, query, properties)
resp, err := c.client.Do(kReq)
if err != nil {
// TODO(jdoak): We need a http error unwrap function that pulls out an *errors.Error.
return execResp{}, errors.E(op, errors.KHTTPError, err)
}
if resp.StatusCode != 200 {
// TODO(jdoak): We need to make this more verbose to be compliant with API guidelines.
return execResp{}, errors.E(op, errors.KHTTPError, fmt.Errorf("received non 200 (OK) response from server, got: %s", resp.Status))
}
body, err := bodyFromResponse(*resp, op)
dec := newDecoder(body, op)
switch op {
case execQuery:
ch := dec.decodeV2(ctx)
return execResp{frameCh: ch, reqHeader: kReq.Header, respHeader: resp.Header}, nil
case execMgmt:
ch := dec.decodeV1(ctx)
return execResp{frameCh: ch, reqHeader: kReq.Header, respHeader: resp.Header}, nil
default:
panic(errors.E(op, errors.KOther, fmt.Errorf("Unexpected op type")))
}
}
func copyHeaders(header http.Header) http.Header {
headers := make(http.Header, len(header))
for k, v := range header {
headers[k] = v
}
return headers
}