-
Notifications
You must be signed in to change notification settings - Fork 51
/
clickhouse.go
205 lines (170 loc) · 4.67 KB
/
clickhouse.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
package clickhouse
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/lomik/graphite-clickhouse/helper/version"
"github.com/lomik/zapwriter"
"go.uber.org/zap"
)
var ErrUvarintRead = errors.New("ReadUvarint: Malformed array")
var ErrUvarintOverflow = errors.New("ReadUvarint: varint overflows a 64-bit integer")
var ErrClickHouseResponse = errors.New("Malformed response from clickhouse")
type Options struct {
Timeout time.Duration
ConnectTimeout time.Duration
}
type loggedReader struct {
reader io.ReadCloser
logger *zap.Logger
start time.Time
finished bool
}
func (r *loggedReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if err != nil && !r.finished {
r.finished = true
r.logger.Info("query", zap.Duration("time", time.Since(r.start)))
}
return n, err
}
func (r *loggedReader) Close() error {
err := r.reader.Close()
if !r.finished {
r.finished = true
r.logger.Info("query", zap.Duration("time", time.Since(r.start)))
}
return err
}
func formatSQL(q string) string {
s := strings.Split(q, "\n")
for i := 0; i < len(s); i++ {
s[i] = strings.TrimSpace(s[i])
}
return strings.Join(s, " ")
}
func Escape(s string) string {
s = strings.Replace(s, `\`, `\\`, -1)
s = strings.Replace(s, `'`, `\'`, -1)
return s
}
func Query(ctx context.Context, dsn string, query string, table string, opts Options) ([]byte, error) {
return Post(ctx, dsn, query, table, nil, opts)
}
func Post(ctx context.Context, dsn string, query string, table string, postBody io.Reader, opts Options) ([]byte, error) {
return do(ctx, dsn, query, table, postBody, false, opts)
}
func PostGzip(ctx context.Context, dsn string, query string, table string, postBody io.Reader, opts Options) ([]byte, error) {
return do(ctx, dsn, query, table, postBody, true, opts)
}
func Reader(ctx context.Context, dsn string, query string, table string, opts Options) (io.ReadCloser, error) {
return reader(ctx, dsn, query, table, nil, false, opts)
}
func reader(ctx context.Context, dsn string, query string, table string, postBody io.Reader, gzip bool, opts Options) (bodyReader io.ReadCloser, err error) {
start := time.Now()
var requestID string
if value, ok := ctx.Value("requestID").(string); ok {
requestID = value
}
queryForLogger := query
if len(queryForLogger) > 500 {
queryForLogger = queryForLogger[:395] + "<...>" + queryForLogger[len(queryForLogger)-100:]
}
logger := zapwriter.Logger("query").With(zap.String("query", formatSQL(queryForLogger)), zap.String("request_id", requestID))
defer func() {
// fmt.Println(time.Since(start), formatSQL(queryForLogger))
if err != nil {
logger.Error("query", zap.Error(err), zap.Duration("time", time.Since(start)))
}
}()
p, err := url.Parse(dsn)
if err != nil {
return
}
var b [8]byte
binary.LittleEndian.PutUint64(b[:], rand.Uint64())
queryID := fmt.Sprintf("%x", b)
q := p.Query()
q.Set("query_id", fmt.Sprintf("%s::%s", requestID, queryID))
p.RawQuery = q.Encode()
if postBody != nil {
q := p.Query()
q.Set("query", query)
p.RawQuery = q.Encode()
} else {
postBody = strings.NewReader(query)
}
url := p.String()
req, err := http.NewRequest("POST", url, postBody)
if err != nil {
return
}
req.Header.Add("User-Agent", fmt.Sprintf("graphite-clickhouse/%s (table:%s)", version.Version, table))
if gzip {
req.Header.Add("Content-Encoding", "gzip")
}
client := &http.Client{
Timeout: opts.Timeout,
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: opts.ConnectTimeout,
}).Dial,
DisableKeepAlives: true,
},
}
resp, err := client.Do(req)
if err != nil {
return
}
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
err = fmt.Errorf("clickhouse response status %d: %s", resp.StatusCode, string(body))
return
}
bodyReader = &loggedReader{
reader: resp.Body,
logger: logger,
start: start,
}
return
}
func do(ctx context.Context, dsn string, query string, table string, postBody io.Reader, gzip bool, opts Options) ([]byte, error) {
bodyReader, err := reader(ctx, dsn, query, table, postBody, gzip, opts)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(bodyReader)
bodyReader.Close()
if err != nil {
return nil, err
}
return body, nil
}
func ReadUvarint(array []byte) (uint64, int, error) {
var x uint64
var s uint
l := len(array) - 1
for i := 0; ; i++ {
if i > l {
return x, i + 1, ErrUvarintRead
}
if array[i] < 0x80 {
if i > 9 || i == 9 && array[i] > 1 {
return x, i + 1, ErrUvarintOverflow
}
return x | uint64(array[i])<<s, i + 1, nil
}
x |= uint64(array[i]&0x7f) << s
s += 7
}
}