forked from ContentSquare/chproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
232 lines (207 loc) · 5.03 KB
/
utils.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
package main
import (
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"sort"
"strings"
"time"
"github.com/Vertamedia/chproxy/chdecompressor"
"github.com/Vertamedia/chproxy/log"
)
func respondWith(rw http.ResponseWriter, err error, status int) {
log.ErrorWithCallDepth(err, 1)
rw.WriteHeader(status)
fmt.Fprintf(rw, "%s\n", err)
}
// getAuth retrieves auth credentials from request
// according to CH documentation @see "http://clickhouse.readthedocs.io/en/latest/reference_en.html#HTTP interface"
func getAuth(req *http.Request) (string, string) {
if name, pass, ok := req.BasicAuth(); ok {
return name, pass
}
// if basicAuth is empty - check URL params `user` and `password`
params := req.URL.Query()
if name := params.Get("user"); name != "" {
pass := params.Get("password")
return name, pass
}
// if still no credentials - treat it as `default` user request
return "default", ""
}
const (
okResponse = "Ok.\n"
isHealthyTimeout = 3 * time.Second
)
func isHealthy(addr string) error {
req, err := http.NewRequest("GET", addr, nil)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), isHealthyTimeout)
defer cancel()
req = req.WithContext(ctx)
startTime := time.Now()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("cannot send request in %s: %s", time.Since(startTime), err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("non-200 status code: %s", resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("cannot read response in %s: %s", time.Since(startTime), err)
}
r := string(body)
if r != okResponse {
return fmt.Errorf("unexpected response: %s", r)
}
return nil
}
// getQuerySnippet returns query snippet.
//
// getQuerySnippet must be called only for error reporting.
func getQuerySnippet(req *http.Request) string {
if req.Method == http.MethodGet {
return req.URL.Query().Get("query")
}
crc, ok := req.Body.(*cachedReadCloser)
if !ok {
crc = &cachedReadCloser{
ReadCloser: req.Body,
}
}
// 'read' request body, so it traps into to crc.
// Ignore any errors, since getQuerySnippet is called only
// during error reporting.
io.Copy(ioutil.Discard, crc)
data := crc.String()
u := getDecompressor(req)
if u == nil {
return data
}
bs := bytes.NewBufferString(data)
b, err := u.decompress(bs)
if err == nil {
return string(b)
}
// It is better to return partially decompressed data instead of an empty string.
if len(b) > 0 {
return string(b)
}
// The data failed to be decompressed. Return compressed data
// instead of an empty string.
return data
}
// getFullQuery returns full query from req.
func getFullQuery(req *http.Request) ([]byte, error) {
if req.Method == http.MethodGet {
return []byte(req.URL.Query().Get("query")), nil
}
data, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
// restore body for further reading
req.Body = ioutil.NopCloser(bytes.NewBuffer(data))
u := getDecompressor(req)
if u == nil {
return data, nil
}
br := bytes.NewReader(data)
b, err := u.decompress(br)
if err != nil {
return nil, fmt.Errorf("cannot uncompress query: %s", err)
}
return b, nil
}
// canCacheQuery returns true if q can be cached.
func canCacheQuery(q []byte) bool {
q = skipLeadingComments(q)
// Currently only SELECT queries may be cached.
if len(q) < len("SELECT") {
return false
}
q = bytes.ToUpper(q[:len("SELECT")])
return bytes.HasPrefix(q, []byte("SELECT"))
}
func skipLeadingComments(q []byte) []byte {
for len(q) > 0 {
switch q[0] {
case '\t', '\n', '\v', '\f', '\r', ' ':
q = q[1:]
case '-':
if len(q) < 2 || q[1] != '-' {
return q
}
// skip `-- comment`
n := bytes.IndexByte(q, '\n')
if n < 0 {
return nil
}
q = q[n+1:]
case '/':
if len(q) < 2 || q[1] != '*' {
return q
}
// skip `/* comment */`
for {
n := bytes.IndexByte(q, '*')
if n < 0 {
return nil
}
q = q[n+1:]
if len(q) == 0 {
return nil
}
if q[0] == '/' {
q = q[1:]
break
}
}
default:
return q
}
}
return nil
}
// splits header string in sorted slice
func sortHeader(header string) string {
h := strings.Split(header, ",")
for i, v := range h {
h[i] = strings.TrimSpace(v)
}
sort.Strings(h)
return strings.Join(h, ",")
}
func getDecompressor(req *http.Request) decompressor {
if req.Header.Get("Content-Encoding") == "gzip" {
return gzipDecompressor{}
}
if req.URL.Query().Get("decompress") == "1" {
return chDecompressor{}
}
return nil
}
type decompressor interface {
decompress(r io.Reader) ([]byte, error)
}
type gzipDecompressor struct{}
func (dc gzipDecompressor) decompress(r io.Reader) ([]byte, error) {
gr, err := gzip.NewReader(r)
if err != nil {
return nil, fmt.Errorf("cannot ungzip query: %s", err)
}
return ioutil.ReadAll(gr)
}
type chDecompressor struct{}
func (dc chDecompressor) decompress(r io.Reader) ([]byte, error) {
lr := chdecompressor.NewReader(r)
return ioutil.ReadAll(lr)
}