forked from ClickHouse/ch-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
563 lines (491 loc) · 13.3 KB
/
client.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
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
package ch
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"github.com/ClickHouse/ch-go/compress"
pkgVersion "github.com/ClickHouse/ch-go/internal/version"
"github.com/ClickHouse/ch-go/otelch"
"github.com/ClickHouse/ch-go/proto"
)
// Client implements ClickHouse binary protocol client on top of
// single TCP connection.
type Client struct {
lg *zap.Logger
conn net.Conn
buf *proto.Buffer
reader *proto.Reader
info proto.ClientHello
server proto.ServerHello
version clientVersion
quotaKey string
mux sync.Mutex
closed bool
// Single packet read timeout.
readTimeout time.Duration
otel bool
tracer trace.Tracer
meter metric.Meter
// TCP Binary protocol version.
protocolVersion int
// compressor performs block compression,
// see encodeBlock.
compressor *compress.Writer
compression proto.Compression
compressionMethod compress.Method
settings []Setting
}
// Setting to send to server.
type Setting struct {
Key, Value string
Important bool
}
// SettingInt returns Setting with integer value v.
func SettingInt(k string, v int) Setting {
return Setting{
Key: k,
Value: strconv.Itoa(v),
Important: true,
}
}
// ServerInfo returns server information.
func (c *Client) ServerInfo() proto.ServerHello { return c.server }
// ErrClosed means that client was already closed.
var ErrClosed = errors.New("client is closed")
// Close closes underlying connection and frees all resources,
// rendering Client to unusable state.
func (c *Client) Close() error {
c.mux.Lock()
defer c.mux.Unlock()
if c.closed {
return ErrClosed
}
c.closed = true
if err := c.conn.Close(); err != nil {
return errors.Wrap(err, "conn")
}
return nil
}
// IsClosed indicates that connection is closed.
func (c *Client) IsClosed() bool {
c.mux.Lock()
defer c.mux.Unlock()
return c.closed
}
// Exception is server-side error.
type Exception struct {
Code proto.Error
Name string
Message string
Stack string
Next []Exception // non-nil only for top exception
}
func (e *Exception) IsCode(codes ...proto.Error) bool {
if e == nil || len(codes) == 0 {
return false
}
for _, c := range codes {
if e.Code == c {
return true
}
}
return false
}
func (e *Exception) Error() string {
msg := strings.TrimPrefix(e.Message, e.Name+":")
msg = strings.TrimSpace(msg)
return fmt.Sprintf("%s: %s: %s", e.Code, e.Name, msg)
}
// AsException finds first *Exception in err chain.
func AsException(err error) (*Exception, bool) {
var e *Exception
if !errors.As(err, &e) {
return nil, false
}
return e, true
}
// IsErr reports whether err is error with provided exception codes.
func IsErr(err error, codes ...proto.Error) bool {
if e, ok := AsException(err); ok {
return e.IsCode(codes...)
}
return false
}
// IsException reports whether err is Exception.
func IsException(err error) bool {
_, ok := AsException(err)
return ok
}
// Exception reads exception from server.
func (c *Client) exception() (*Exception, error) {
var list []proto.Exception
for {
var ex proto.Exception
if err := c.decode(&ex); err != nil {
return nil, errors.Wrap(err, "decode")
}
list = append(list, ex)
if !ex.Nested {
break
}
}
top := list[0]
e := &Exception{
Code: top.Code,
Name: top.Name,
Message: top.Message,
Stack: top.Stack,
}
for _, next := range list[1:] {
e.Next = append(e.Next, Exception{
Code: next.Code,
Name: next.Name,
Message: next.Message,
Stack: next.Stack,
})
}
return e, nil
}
func (c *Client) decode(v proto.AwareDecoder) error {
return v.DecodeAware(c.reader, c.protocolVersion)
}
func (c *Client) progress() (proto.Progress, error) {
var p proto.Progress
if err := c.decode(&p); err != nil {
return proto.Progress{}, errors.Wrap(err, "decode")
}
return p, nil
}
func (c *Client) profile() (proto.Profile, error) {
var p proto.Profile
if err := c.decode(&p); err != nil {
return proto.Profile{}, errors.Wrap(err, "decode")
}
return p, nil
}
// packet reads server code.
func (c *Client) packet(ctx context.Context) (proto.ServerCode, error) {
timeout := c.readTimeout
var deadline time.Time
if timeout > 0 {
deadline = time.Now().Add(timeout)
}
if d, ok := ctx.Deadline(); ok && (d.Before(deadline) || deadline.IsZero()) {
// Use context deadline if it is earlier than default timeout or
// no timeout is set.
//
// Otherwise, we can get stuck for a long time in case of network issues.
// Ref: https://github.com/ClickHouse/ch-go/issues/274
deadline = d
}
if !deadline.IsZero() {
if err := c.conn.SetReadDeadline(deadline); err != nil {
return 0, errors.Wrap(err, "set read deadline")
}
defer func() {
// Reset deadline.
_ = c.conn.SetReadDeadline(time.Time{})
}()
}
n, err := c.reader.UVarInt()
if err != nil {
return 0, errors.Wrap(err, "uvarint")
}
code := proto.ServerCode(n)
if ce := c.lg.Check(zap.DebugLevel, "Packet"); ce != nil {
ce.Write(
zap.Uint64("packet_code", n),
zap.Stringer("packet", code),
)
}
if !code.IsAServerCode() {
return 0, errors.Errorf("bad server packet type %d", n)
}
return code, nil
}
func (c *Client) flushBuf(ctx context.Context, b *proto.Buffer) error {
if err := ctx.Err(); err != nil {
return errors.Wrap(err, "context")
}
if len(b.Buf) == 0 {
// Nothing to flush.
return nil
}
if deadline, ok := ctx.Deadline(); ok {
if err := c.conn.SetWriteDeadline(deadline); err != nil {
return errors.Wrap(err, "set write deadline")
}
// Reset deadline.
defer func() { _ = c.conn.SetWriteDeadline(time.Time{}) }()
}
n, err := c.conn.Write(b.Buf)
if err != nil {
return errors.Wrap(err, "write")
}
if n != len(b.Buf) {
return errors.Wrap(io.ErrShortWrite, "wrote less than expected")
}
if ce := c.lg.Check(zap.DebugLevel, "Flush"); ce != nil {
ce.Write(zap.Int("bytes", n))
}
b.Reset()
return nil
}
func (c *Client) flush(ctx context.Context) error {
return c.flushBuf(ctx, c.buf)
}
func (c *Client) encode(v proto.AwareEncoder) {
v.EncodeAware(c.buf, c.protocolVersion)
}
//go:generate go run github.com/dmarkham/enumer -transform upper -type Compression -trimprefix Compression -output compression_enum.go
// Compression setting.
//
// Trade bandwidth for CPU.
type Compression byte
const (
// CompressionDisabled disables compression. Lowest CPU overhead.
CompressionDisabled Compression = iota
// CompressionLZ4 enables LZ4 compression for data. Medium CPU overhead.
CompressionLZ4
// CompressionZSTD enables ZStandard compression. High CPU overhead.
CompressionZSTD
// CompressionNone uses no compression but data has checksums.
CompressionNone
// CompressionLZ4HC enables LZ4HC compression for data. High CPU overhead.
CompressionLZ4HC
)
// CompressionLevel setting. A level == 0 is invalid and resolves to the default.
//
// Supported by: LZ4HC.
type CompressionLevel uint32
// Options for Client. Zero value is valid.
type Options struct {
Logger *zap.Logger // defaults to Nop.
Address string // 127.0.0.1:9000
Database string // "default"
User string // "default"
Password string // blank string by default
QuotaKey string // blank string by default
Compression Compression // disabled by default
CompressionLevel CompressionLevel // compression algorithm specific default
ClientName string // blank string by default
Settings []Setting // none by default
// ReadTimeout is a timeout for reading a single packet from the server.
//
// Defaults to 3s. No timeout if negative (you can use NoTimeout const).
ReadTimeout time.Duration
Dialer Dialer // defaults to net.Dialer
DialTimeout time.Duration // defaults to 1s
TLS *tls.Config // no TLS is used by default
ProtocolVersion int // force protocol version, optional
HandshakeTimeout time.Duration // longer lasting handshake is a case for ClickHouse cloud idle instances, defaults to 5m
// Additional OpenTelemetry instrumentation that will capture query body
// and other parameters.
//
// Note: OpenTelemetry context propagation works without this option too.
OpenTelemetryInstrumentation bool
TracerProvider trace.TracerProvider
MeterProvider metric.MeterProvider
meter metric.Meter
tracer trace.Tracer
}
// Defaults for connection.
const (
DefaultDatabase = "default"
DefaultUser = "default"
DefaultHost = "127.0.0.1"
DefaultPort = 9000
DefaultDialTimeout = 1 * time.Second
DefaultHandshakeTimeout = 300 * time.Second
DefaultReadTimeout = 3 * time.Second
)
// NoTimeout is a value for Options.ReadTimeout that disables timeout.
const NoTimeout = time.Duration(-1)
func (o *Options) setDefaults() {
if o.ProtocolVersion == 0 {
o.ProtocolVersion = proto.Version
}
if o.HandshakeTimeout == 0 {
o.HandshakeTimeout = DefaultHandshakeTimeout
}
if o.Database == "" {
o.Database = DefaultDatabase
}
if o.User == "" {
o.User = DefaultUser
}
if o.Logger == nil {
o.Logger = zap.NewNop()
}
if o.Address == "" {
o.Address = net.JoinHostPort(DefaultHost, strconv.Itoa(DefaultPort))
}
if o.DialTimeout == 0 {
o.DialTimeout = DefaultDialTimeout
}
if o.Dialer == nil {
o.Dialer = &net.Dialer{
Timeout: o.DialTimeout,
}
}
if o.MeterProvider == nil {
o.MeterProvider = otel.GetMeterProvider()
}
if o.TracerProvider == nil {
o.TracerProvider = otel.GetTracerProvider()
}
if o.meter == nil {
o.meter = o.MeterProvider.Meter(otelch.Name)
}
if o.tracer == nil {
o.tracer = o.TracerProvider.Tracer(otelch.Name,
trace.WithInstrumentationVersion(otelch.SemVersion()),
)
}
if o.ReadTimeout == 0 {
o.ReadTimeout = DefaultReadTimeout
}
if o.ReadTimeout < 0 || o.ReadTimeout == NoTimeout {
o.ReadTimeout = 0
}
}
type clientVersion struct {
Name string
Major int
Minor int
Patch int
}
// Connect performs handshake with ClickHouse server and initializes
// application level connection.
func Connect(ctx context.Context, conn net.Conn, opt Options) (*Client, error) {
opt.setDefaults()
clientName := proto.Name
pkg := pkgVersion.Get()
if opt.ClientName == "" {
if pkg.Name != "" {
clientName = fmt.Sprintf("%s (%s)", clientName, pkg.Name)
}
} else {
clientName = fmt.Sprintf("%s %s", clientName, opt.ClientName)
}
ver := clientVersion{
Name: clientName,
Major: pkg.Major,
Minor: pkg.Minor,
Patch: pkg.Patch,
}
if opt.OpenTelemetryInstrumentation {
newCtx, span := opt.tracer.Start(ctx, "Connect",
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
semconv.DBNameKey.String(opt.Database),
),
)
ctx = newCtx
defer span.End()
}
c := &Client{
conn: conn,
buf: new(proto.Buffer),
reader: proto.NewReader(conn),
settings: opt.Settings,
lg: opt.Logger,
otel: opt.OpenTelemetryInstrumentation,
tracer: opt.tracer,
meter: opt.meter,
quotaKey: opt.QuotaKey,
readTimeout: opt.ReadTimeout,
compressor: compress.NewWriterWithLevel(compress.Level(opt.CompressionLevel)),
version: ver,
protocolVersion: opt.ProtocolVersion,
info: proto.ClientHello{
Name: clientName,
Major: ver.Major,
Minor: ver.Minor,
ProtocolVersion: opt.ProtocolVersion,
Database: opt.Database,
User: opt.User,
Password: opt.Password,
},
}
switch opt.Compression {
case CompressionLZ4:
c.compression = proto.CompressionEnabled
c.compressionMethod = compress.LZ4
case CompressionLZ4HC:
c.compression = proto.CompressionEnabled
c.compressionMethod = compress.LZ4HC
case CompressionZSTD:
c.compression = proto.CompressionEnabled
c.compressionMethod = compress.ZSTD
case CompressionNone:
c.compression = proto.CompressionEnabled
c.compressionMethod = compress.None
default:
c.compression = proto.CompressionDisabled
}
handshakeCtx, cancel := context.WithTimeout(ctx, opt.HandshakeTimeout)
defer cancel()
if err := c.handshake(handshakeCtx); err != nil {
return nil, errors.Wrap(err, "handshake")
}
return c, nil
}
// A Dialer dials using a context.
type Dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
// Dial dials requested address and establishes TCP connection to ClickHouse
// server, performing handshake.
func Dial(ctx context.Context, opt Options) (c *Client, err error) {
opt.setDefaults()
if opt.OpenTelemetryInstrumentation {
newCtx, span := opt.tracer.Start(ctx, "Dial",
trace.WithSpanKind(trace.SpanKindClient),
)
ctx = newCtx
defer func() {
if err != nil {
span.RecordError(err)
}
span.End()
}()
}
if opt.TLS != nil {
netDialer := &net.Dialer{
Timeout: opt.DialTimeout,
}
if opt.Dialer != nil {
d, ok := opt.Dialer.(*net.Dialer)
if !ok {
return nil, errors.Errorf("tls dialer should be *net.Dialer, got %T", opt.Dialer)
}
netDialer = d
}
opt.Dialer = &tls.Dialer{
NetDialer: netDialer,
Config: opt.TLS,
}
}
conn, err := opt.Dialer.DialContext(ctx, "tcp", opt.Address)
if err != nil {
return nil, errors.Wrap(err, "dial")
}
client, err := Connect(ctx, conn, opt)
if err != nil {
return nil, errors.Wrap(err, "connect")
}
return client, nil
}