-
Notifications
You must be signed in to change notification settings - Fork 370
/
clickhouseclient.go
494 lines (457 loc) · 14.7 KB
/
clickhouseclient.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
// Copyright 2022 Antrea Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package clickhouseclient
import (
"context"
"crypto/tls"
"crypto/x509"
"database/sql"
"fmt"
"net/url"
"sync"
"time"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/gammazero/deque"
ipfixentities "github.com/vmware/go-ipfix/pkg/entities"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
"antrea.io/antrea/pkg/flowaggregator/flowrecord"
)
const (
ProtocolUnknown = -1
maxQueueSize = 1 << 19 // 524288. ~500MB assuming 1KB per record
queueFlushTimeout = 10 * time.Second
insertQuery = `INSERT INTO flows (
flowStartSeconds,
flowEndSeconds,
flowEndSecondsFromSourceNode,
flowEndSecondsFromDestinationNode,
flowEndReason,
sourceIP,
destinationIP,
sourceTransportPort,
destinationTransportPort,
protocolIdentifier,
packetTotalCount,
octetTotalCount,
packetDeltaCount,
octetDeltaCount,
reversePacketTotalCount,
reverseOctetTotalCount,
reversePacketDeltaCount,
reverseOctetDeltaCount,
sourcePodName,
sourcePodNamespace,
sourceNodeName,
destinationPodName,
destinationPodNamespace,
destinationNodeName,
destinationClusterIP,
destinationServicePort,
destinationServicePortName,
ingressNetworkPolicyName,
ingressNetworkPolicyNamespace,
ingressNetworkPolicyRuleName,
ingressNetworkPolicyRuleAction,
ingressNetworkPolicyType,
egressNetworkPolicyName,
egressNetworkPolicyNamespace,
egressNetworkPolicyRuleName,
egressNetworkPolicyRuleAction,
egressNetworkPolicyType,
tcpState,
flowType,
sourcePodLabels,
destinationPodLabels,
throughput,
reverseThroughput,
throughputFromSourceNode,
throughputFromDestinationNode,
reverseThroughputFromSourceNode,
reverseThroughputFromDestinationNode,
clusterUUID,
egressName,
egressIP,
appProtocolName,
httpVals,
egressNodeName)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?)`
)
// PrepareClickHouseConnection is used for unit testing
var PrepareClickHouseConnection = prepareConnection
type stopPayload struct {
flushQueue bool
}
type ClickHouseExportProcess struct {
// db holds sql connection struct to clickhouse db.
db *sql.DB
config ClickHouseConfig
// deque buffers flows records between batch commits.
deque deque.Deque[*flowrecord.FlowRecord]
// dequeMutex is for concurrency between adding and removing records from deque.
dequeMutex sync.Mutex
// queueSize is the max size of deque
queueSize int
// stopCh is the channel to receive stop message
stopCh chan stopPayload
// exportWg is to ensure that all messages have been flushed from the queue when we stop
exportWg sync.WaitGroup
// commitTicker is a ticker, containing a channel used to trigger batchCommitAll() for every commitInterval period
commitTicker *time.Ticker
exportProcessRunning bool
// mutex protects configuration state from concurrent access
mutex sync.Mutex
clusterUUID string
}
type ClickHouseConfig struct {
Username string
Password string
Database string
DatabaseURL string
Debug bool
Compress *bool
CommitInterval time.Duration
CACert bool
InsecureSkipVerify bool
Certificate []byte
}
func NewClickHouseClient(config ClickHouseConfig, clusterUUID string) (*ClickHouseExportProcess, error) {
if len(config.DatabaseURL) == 0 || len(config.Username) == 0 || len(config.Password) == 0 {
return nil, fmt.Errorf("DatabaseURL, Username or Password missing in ClickHouse config")
}
connect, err := PrepareClickHouseConnection(config)
if err != nil {
return nil, err
}
chClient := &ClickHouseExportProcess{
db: connect,
config: config,
queueSize: maxQueueSize,
clusterUUID: clusterUUID,
}
return chClient, nil
}
func (ch *ClickHouseExportProcess) CacheRecord(record ipfixentities.Record) {
chRow := flowrecord.GetFlowRecord(record)
ch.dequeMutex.Lock()
defer ch.dequeMutex.Unlock()
for ch.deque.Len() >= ch.queueSize {
ch.deque.PopFront()
}
ch.deque.PushBack(chRow)
}
func (ch *ClickHouseExportProcess) Start() {
ch.startExportProcess()
}
func (ch *ClickHouseExportProcess) Stop() {
ch.stopExportProcess(true)
}
func (ch *ClickHouseExportProcess) startExportProcess() {
ch.mutex.Lock()
defer ch.mutex.Unlock()
if ch.exportProcessRunning {
return
}
ch.exportProcessRunning = true
ch.commitTicker = time.NewTicker(ch.config.CommitInterval)
ch.stopCh = make(chan stopPayload, 1)
ch.exportWg.Add(1)
go func() {
defer ch.exportWg.Done()
ch.flowRecordPeriodicCommit()
}()
}
func (ch *ClickHouseExportProcess) stopExportProcess(flushQueue bool) {
ch.mutex.Lock()
defer ch.mutex.Unlock()
if !ch.exportProcessRunning {
return
}
ch.exportProcessRunning = false
defer ch.commitTicker.Stop()
ch.stopCh <- stopPayload{
flushQueue: flushQueue,
}
ch.exportWg.Wait()
}
func (ch *ClickHouseExportProcess) flowRecordPeriodicCommit() {
klog.InfoS("Starting ClickHouse exporting process")
ctx := context.Background()
logTicker := time.NewTicker(time.Minute)
defer logTicker.Stop()
committedRec := 0
for {
select {
case stop := <-ch.stopCh:
klog.InfoS("Stopping ClickHouse exporting process")
if !stop.flushQueue {
return
}
ctx, cancelFn := context.WithTimeout(ctx, queueFlushTimeout)
defer cancelFn()
committed, err := ch.batchCommitAll(ctx)
if err != nil {
klog.ErrorS(err, "Error when doing batchCommitAll on stop")
} else {
committedRec += committed
klog.V(4).InfoS("Total number of records committed to DB", "count", committedRec)
}
return
case <-ch.commitTicker.C:
committed, err := ch.batchCommitAll(ctx)
if err == nil {
committedRec += committed
}
case <-logTicker.C:
klog.V(4).InfoS("Total number of records committed to DB", "count", committedRec)
committedRec = 0
}
}
}
// batchCommitAll commits all flow records cached in local deque in one INSERT query.
// Returns the number of records successfully committed, and error if encountered.
// Cached records will be removed only after successful commit.
func (ch *ClickHouseExportProcess) batchCommitAll(ctx context.Context) (int, error) {
ch.dequeMutex.Lock()
currSize := ch.deque.Len()
ch.dequeMutex.Unlock()
if currSize == 0 {
return 0, nil
}
var stmt *sql.Stmt
// start new connection
tx, err := ch.db.BeginTx(ctx, nil)
if err == nil {
stmt, err = tx.PrepareContext(ctx, insertQuery)
}
if err != nil {
klog.ErrorS(err, "Error when preparing insert statement")
_ = tx.Rollback()
return 0, err
}
// populate items from deque
ch.dequeMutex.Lock()
// currSize could have increased due to CacheRecord being called in between.
currSize = ch.deque.Len()
recordsToExport := make([]*flowrecord.FlowRecord, 0, currSize)
for range currSize {
recordsToExport = append(recordsToExport, ch.deque.PopFront())
}
ch.dequeMutex.Unlock()
for _, record := range recordsToExport {
_, err := stmt.ExecContext(
ctx,
record.FlowStartSeconds,
record.FlowEndSeconds,
record.FlowEndSecondsFromSourceNode,
record.FlowEndSecondsFromDestinationNode,
record.FlowEndReason,
record.SourceIP,
record.DestinationIP,
record.SourceTransportPort,
record.DestinationTransportPort,
record.ProtocolIdentifier,
record.PacketTotalCount,
record.OctetTotalCount,
record.PacketDeltaCount,
record.OctetDeltaCount,
record.ReversePacketTotalCount,
record.ReverseOctetTotalCount,
record.ReversePacketDeltaCount,
record.ReverseOctetDeltaCount,
record.SourcePodName,
record.SourcePodNamespace,
record.SourceNodeName,
record.DestinationPodName,
record.DestinationPodNamespace,
record.DestinationNodeName,
record.DestinationClusterIP,
record.DestinationServicePort,
record.DestinationServicePortName,
record.IngressNetworkPolicyName,
record.IngressNetworkPolicyNamespace,
record.IngressNetworkPolicyRuleName,
record.IngressNetworkPolicyRuleAction,
record.IngressNetworkPolicyType,
record.EgressNetworkPolicyName,
record.EgressNetworkPolicyNamespace,
record.EgressNetworkPolicyRuleName,
record.EgressNetworkPolicyRuleAction,
record.EgressNetworkPolicyType,
record.TcpState,
record.FlowType,
record.SourcePodLabels,
record.DestinationPodLabels,
record.Throughput,
record.ReverseThroughput,
record.ThroughputFromSourceNode,
record.ThroughputFromDestinationNode,
record.ReverseThroughputFromSourceNode,
record.ReverseThroughputFromDestinationNode,
ch.clusterUUID,
record.EgressName,
record.EgressIP,
record.AppProtocolName,
record.HttpVals,
record.EgressNodeName,
)
if err != nil {
klog.ErrorS(err, "Error when adding record")
ch.pushRecordsToFrontOfQueue(recordsToExport)
_ = tx.Rollback()
return 0, err
}
}
if err := tx.Commit(); err != nil {
klog.ErrorS(err, "Error when committing record")
ch.pushRecordsToFrontOfQueue(recordsToExport)
return 0, err
}
return len(recordsToExport), nil
}
// pushRecordsToFrontOfQueue pushes records to the front of deque without exceeding its capacity.
// Items with lower index (older records) will be dropped first if deque is to be filled.
func (ch *ClickHouseExportProcess) pushRecordsToFrontOfQueue(records []*flowrecord.FlowRecord) {
ch.dequeMutex.Lock()
defer ch.dequeMutex.Unlock()
for i := len(records) - 1; i >= 0; i-- {
if ch.deque.Len() >= ch.queueSize {
break
}
ch.deque.PushFront(records[i])
}
}
func prepareConnection(config ClickHouseConfig) (*sql.DB, error) {
connect, err := ConnectClickHouse(&config)
if err != nil {
return nil, fmt.Errorf("error when connecting to ClickHouse, %w", err)
}
// Test open Transaction
tx, err := connect.Begin()
if err == nil {
_, err = tx.Prepare(insertQuery)
}
if err != nil {
return nil, fmt.Errorf("error when preparing insert statement, %v", err)
}
_ = tx.Commit()
return connect, err
}
func (ch *ClickHouseExportProcess) UpdateCH(config ClickHouseConfig, connect *sql.DB) {
ch.stopExportProcess(false) // do not flush the queue
defer ch.startExportProcess()
ch.mutex.Lock()
defer ch.mutex.Unlock()
ch.config = config
ch.db = connect
}
func (ch *ClickHouseExportProcess) GetCommitInterval() time.Duration {
ch.mutex.Lock()
defer ch.mutex.Unlock()
return ch.config.CommitInterval
}
func (ch *ClickHouseExportProcess) SetCommitInterval(commitInterval time.Duration) {
ch.mutex.Lock()
defer ch.mutex.Unlock()
ch.config.CommitInterval = commitInterval
if ch.commitTicker != nil {
ch.commitTicker.Reset(ch.config.CommitInterval)
}
}
func (ch *ClickHouseExportProcess) GetClickHouseConfig() ClickHouseConfig {
ch.mutex.Lock()
defer ch.mutex.Unlock()
return ch.config
}
func ConnectClickHouse(config *ClickHouseConfig) (*sql.DB, error) {
proto, addr, enableTLS, err := parseDatabaseURL(config.DatabaseURL)
if err != nil {
return nil, fmt.Errorf("error when parsing database url: %w", err)
}
var connect *sql.DB
var connErr error
connRetryInterval := 1 * time.Second
connTimeout := 10 * time.Second
// Connect to ClickHouse in a loop
if err := wait.PollUntilContextTimeout(context.TODO(), connRetryInterval, connTimeout, true, func(ctx context.Context) (bool, error) {
// Open the database and ping it
opt := clickhouse.Options{
Addr: []string{addr},
Auth: clickhouse.Auth{
Username: config.Username,
Password: config.Password,
Database: config.Database,
},
Protocol: proto,
}
var compression clickhouse.CompressionMethod
if *config.Compress {
compression = clickhouse.CompressionLZ4
}
opt.Compression = &clickhouse.Compression{
Method: compression,
}
if enableTLS { // #nosec G402: ignore insecure options
opt.TLS = &tls.Config{
InsecureSkipVerify: config.InsecureSkipVerify,
}
if config.CACert {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(config.Certificate)
if !ok {
connErr = fmt.Errorf("failed to add the custom CA certificate")
return false, nil
}
opt.TLS.RootCAs = caCertPool
}
}
connect = clickhouse.OpenDB(&opt)
if err := connect.Ping(); err != nil {
if exception, ok := err.(*clickhouse.Exception); ok {
connErr = fmt.Errorf("failed to ping ClickHouse: %v", exception.Message)
} else {
connErr = fmt.Errorf("failed to ping ClickHouse: %v", err)
}
return false, nil
} else {
return true, nil
}
}); err != nil {
return nil, fmt.Errorf("failed to connect to ClickHouse after %s: %v", connTimeout, connErr)
}
return connect, nil
}
func parseDatabaseURL(dbUrl string) (clickhouse.Protocol, string, bool, error) {
u, err := url.Parse(dbUrl)
if err != nil {
return ProtocolUnknown, "", false, fmt.Errorf("failed to parse ClickHouse database URL: %w", err)
}
if u.Path != "" || u.RawQuery != "" || u.User != nil {
return ProtocolUnknown, "", false, fmt.Errorf("invalid ClickHouse database URL '%s': path, query string or user info should not be set", dbUrl)
}
switch u.Scheme {
case "http":
return clickhouse.HTTP, u.Host, false, nil
case "https":
return clickhouse.HTTP, u.Host, true, nil
case "tcp":
return clickhouse.Native, u.Host, false, nil
case "tls":
return clickhouse.Native, u.Host, true, nil
default:
return ProtocolUnknown, "", false, fmt.Errorf("connection over %s transport protocol is not supported", u.Scheme)
}
}