forked from iyacontrol/fluent-bit-clickhouse
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathout_clickhouse.go
301 lines (270 loc) · 7.49 KB
/
out_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
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
package main
import (
"C"
"context"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"unsafe"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
"github.com/fluent/fluent-bit-go/output"
"github.com/sirupsen/logrus"
)
type Clickhouse struct {
logger *logrus.Entry
hosts []string
database string
username string
password string
table string
columns []string
conn driver.Conn
insertSQL string
buffer []map[interface{}]interface{}
bufferSize int
}
const InsertSQLExpr = "INSERT INTO %s (%s) VALUES (%s)"
var config = make(map[string]*Clickhouse, 0)
//export FLBPluginRegister
func FLBPluginRegister(def unsafe.Pointer) int {
return output.FLBPluginRegister(def, "clickhouse", "Clickhouse Output Plugin.")
}
//export FLBPluginInit
func FLBPluginInit(plugin unsafe.Pointer) int {
ch := &Clickhouse{
logger: logrus.NewEntry(logrus.New()),
}
id := output.FLBPluginConfigKey(plugin, "id")
if id != "" {
ch.logger.Infof("plugin clickhouse context id = %s", id)
output.FLBPluginSetContext(plugin, id)
} else {
ch.logger.Error("you must set id of clickhouse!")
return output.FLB_ERROR
}
logLevel := output.FLBPluginConfigKey(plugin, "clickhouse_log_level")
if logLevel != "" {
ch.logger.Infof("plugin clickhouse_log_level = %s", logLevel)
ch.logger = initLogger(id, logLevel)
} else {
ch.logger.Error("you must set log_level of clickhouse!")
return output.FLB_ERROR
}
hosts := output.FLBPluginConfigKey(plugin, "clickhouse_hosts")
if hosts != "" {
ch.logger.Infof("plugin clickhouse_hosts = %s", hosts)
ch.hosts = strings.Split(hosts, ",")
} else {
ch.logger.Error("you must set hosts of clickhouse!")
return output.FLB_ERROR
}
database := output.FLBPluginConfigKey(plugin, "clickhouse_database")
if database != "" {
ch.database = database
ch.logger.Infof("plugin clickhouse_database = %s", ch.database)
} else {
ch.logger.Error("you must set database of clickhouse!")
return output.FLB_ERROR
}
username := output.FLBPluginConfigKey(plugin, "clickhouse_username")
if username != "" {
ch.username = username
ch.logger.Infof("plugin clickhouse_username = %s", ch.username)
} else {
ch.logger.Error("you must set username of clickhouse!")
return output.FLB_ERROR
}
password := output.FLBPluginConfigKey(plugin, "clickhouse_password")
if password != "" {
ch.password = password
ch.logger.Infof("plugin clickhouse_password = %s", ch.password)
} else {
ch.logger.Error("you must set password of clickhouse!")
return output.FLB_ERROR
}
table := output.FLBPluginConfigKey(plugin, "clickhouse_table")
if table != "" {
ch.table = table
ch.logger.Infof("plugin clickhouse_table = %s", ch.table)
} else {
ch.logger.Error("you must set table of clickhouse!")
return output.FLB_ERROR
}
columns := output.FLBPluginConfigKey(plugin, "clickhouse_columns")
if columns != "" {
ch.columns = strings.Split(columns, ",")
ch.logger.Infof("plugin clickhouse_columns = %s", ch.columns)
// init insertSQL
ch.insertSQL = formatInsertSQL(ch.columns, ch.table)
ch.logger.Infof("insertSQL = %s", ch.insertSQL)
} else {
ch.logger.Errorf("you must set columns of %v!", ch.table)
return output.FLB_ERROR
}
bufferSize := output.FLBPluginConfigKey(plugin, "clickhouse_buffer_size")
if bufferSize != "" {
intBufferSize, err := strconv.Atoi(bufferSize)
if err != nil {
ch.logger.Errorf("convert clickhouse_buffer_size to int error: %v!", err)
}
ch.bufferSize = intBufferSize
ch.logger.Infof("plugin clickhouse_buffer_size = %v", ch.bufferSize)
}
// init conn
conn, err := clickhouse.Open(&clickhouse.Options{
Addr: ch.hosts,
Auth: clickhouse.Auth{
Database: ch.database,
Username: ch.username,
Password: ch.password,
},
DialContext: func(ctx context.Context, addr string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "tcp", addr)
},
Debug: true,
Debugf: func(format string, v ...any) {
ch.logger.Debugf(format, v)
},
Settings: clickhouse.Settings{
"max_execution_time": 60,
},
Compression: &clickhouse.Compression{
Method: clickhouse.CompressionLZ4,
},
DialTimeout: time.Duration(10) * time.Second,
MaxOpenConns: 5,
MaxIdleConns: 5,
ConnMaxLifetime: time.Duration(10) * time.Minute,
ConnOpenStrategy: clickhouse.ConnOpenInOrder,
BlockBufferSize: 10,
})
if err != nil {
ch.logger.Errorf("failed to open clickhouse: %v", err)
return output.FLB_ERROR
}
err = conn.Ping(context.Background())
if err != nil {
ch.logger.Errorf("failed to ping clickhouse: %v", err)
return output.FLB_ERROR
}
ch.conn = conn
ch.buffer = make([]map[interface{}]interface{}, 0)
config[id] = ch
return output.FLB_OK
}
//export FLBPluginFlushCtx
func FLBPluginFlushCtx(ctx, data unsafe.Pointer, length C.int, tag *C.char) int {
id := output.FLBPluginGetContext(ctx).(string)
ch, ok := config[id]
if !ok {
return output.FLB_ERROR
}
ch.logger.Infof("flush called for id = %s", id)
// create Fluent Bit decoder
dec := output.NewDecoder(data, int(length))
// extract record and buffer
for {
ret, _, record := output.GetRecord(dec)
if ret != 0 {
break
}
ch.buffer = append(ch.buffer, record)
}
// sink data
if len(ch.buffer) < ch.bufferSize {
return output.FLB_OK
}
// post them to db all at once
start := time.Now()
batch, err := ch.conn.PrepareBatch(context.Background(), ch.insertSQL)
if err != nil {
ch.logger.Errorf("prepare batch failure: %v", err)
return output.FLB_OK
}
for _, record := range ch.buffer {
values := fieldValues(record, ch.columns)
ch.logger.Tracef("values: %v", values)
err = batch.Append(values...)
if err != nil {
ch.logger.Errorf("batch append failure: %v", err)
return output.FLB_OK
}
}
err = batch.Send()
if err != nil {
ch.logger.Errorf("batch send failure: %v", err)
return output.FLB_OK
}
end := time.Now()
ch.logger.Infof("exported %d logs to clickhouse in %s", len(ch.buffer), end.Sub(start))
// clear buffer
ch.buffer = make([]map[interface{}]interface{}, 0)
return output.FLB_OK
}
//export FLBPluginExit
func FLBPluginExit() int {
return output.FLB_OK
}
func initLogger(id, logLevel string) *logrus.Entry {
logger := logrus.New()
logger.SetOutput(os.Stdout)
// trace, debug, info, warning, error, fatal and panic
switch logLevel {
case "trace":
logger.SetLevel(logrus.TraceLevel)
case "debug":
logger.SetLevel(logrus.DebugLevel)
case "info":
logger.SetLevel(logrus.InfoLevel)
case "warning":
logger.SetLevel(logrus.WarnLevel)
case "error":
logger.SetLevel(logrus.ErrorLevel)
case "fatal":
logger.SetLevel(logrus.FatalLevel)
case "panic":
logger.SetLevel(logrus.PanicLevel)
default:
logger.SetLevel(logrus.WarnLevel)
}
return logger.WithFields(logrus.Fields{"id": id})
}
func formatInsertSQL(columns []string, table string) string {
values := ""
for i := range columns {
values += "?"
if i < len(columns)-1 {
values += ","
}
}
return fmt.Sprintf(InsertSQLExpr, table, strings.Join(columns, ","), values)
}
func fieldValues(record map[interface{}]interface{}, fields []string) (values []interface{}) {
values = make([]interface{}, len(fields))
var row = make(map[string]interface{})
for k, v := range record {
row[k.(string)] = v
}
for index, field := range fields {
if v, ok := row[field]; ok {
switch tv := v.(type) {
case string:
values[index] = tv
case []byte:
values[index] = string(tv)
default:
values[index] = fmt.Sprintf("%v", v)
}
} else {
values[index] = nil
}
}
return
}
func main() {
}