-
Notifications
You must be signed in to change notification settings - Fork 12
/
out_clickhouse.go
330 lines (272 loc) · 7.23 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
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
package main
import (
"C"
"database/sql"
"fmt"
"os"
"strconv"
"sync"
//"reflect"
"time"
"unsafe"
"github.com/fluent/fluent-bit-go/output"
//"github.com/ugorji/go/codec"
"github.com/kshvakov/clickhouse"
klog "k8s.io/klog"
)
var (
client *sql.DB
database string
table string
batchSize int
insertSQL = "INSERT INTO %s.%s(date, cluster, namespace, app, pod_name, container_name, host, log, ts) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
rw sync.RWMutex
buffer = make([]Log, 0)
)
const (
DefaultWriteTimeout string = "20"
DefaultReadTimeout string = "10"
DefaultBatchSize int = 1024
)
type Log struct {
Cluster string
Namespace string
App string
Pod string
Container string
Host string
Log string
Ts time.Time
}
//export FLBPluginRegister
func FLBPluginRegister(ctx unsafe.Pointer) int {
return output.FLBPluginRegister(ctx, "clickhouse", "Clickhouse Output Plugin.!")
}
//export FLBPluginInit
// ctx (context) pointer to fluentbit context (state/ c code)
func FLBPluginInit(ctx unsafe.Pointer) int {
// init log
//klog.InitFlags(nil)
//flag.Set("stderrthreshold", "3")
//flag.Parse()
//
//defer klog.Flush()
// get config
var host string
if v := os.Getenv("CLICKHOUSE_HOST"); v != "" {
host = v
} else {
klog.Error("you must set host of clickhouse!")
return output.FLB_ERROR
}
var user string
if v := os.Getenv("CLICKHOUSE_USER"); v != "" {
user = v
} else {
klog.Error("you must set user of clickhouse!")
return output.FLB_ERROR
}
var password string
if v := os.Getenv("CLICKHOUSE_PASSWORD"); v != "" {
password = v
} else {
klog.Error("you must set password of clickhouse!")
return output.FLB_ERROR
}
if v := os.Getenv("CLICKHOUSE_DATABASE"); v != "" {
database = v
} else {
klog.Error("you must set database of clickhouse!")
return output.FLB_ERROR
}
if v := os.Getenv("CLICKHOUSE_TABLE"); v != "" {
table = v
} else {
klog.Error("you must set table of clickhouse!")
return output.FLB_ERROR
}
if v := os.Getenv("CLICKHOUSE_BATCH_SIZE"); v != "" {
size ,err:=strconv.Atoi(v)
if err != nil {
klog.Infof("you set the default bacth_size: %d", DefaultBatchSize)
batchSize = DefaultBatchSize
}
batchSize = size
} else {
klog.Infof("you set the default bacth_size: %d", DefaultBatchSize)
batchSize = DefaultBatchSize
}
var writeTimeout string
if v := os.Getenv("CLICKHOUSE_WRITE_TIMEOUT"); v != "" {
writeTimeout = v
} else {
klog.Infof("you set the default write_timeout: %s", DefaultWriteTimeout)
writeTimeout = DefaultWriteTimeout
}
var readTimeout string
if v := os.Getenv("CLICKHOUSE_READ_TIMEOUT"); v != "" {
readTimeout = v
} else {
klog.Infof("you set the default read_timeout: %s", DefaultReadTimeout)
readTimeout = DefaultReadTimeout
}
dsn := "tcp://" + host + "?username=" + user + "&password=" + password + "&database=" + database + "&write_timeout=" + writeTimeout + "&read_timeout=" + readTimeout
db, err := sql.Open("clickhouse", dsn)
if err != nil {
klog.Error("connecting to clickhouse: %v", err)
return output.FLB_ERROR
}
if err := db.Ping(); err != nil {
if exception, ok := err.(*clickhouse.Exception); ok {
klog.Errorf("[%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
} else {
klog.Errorf("Failed to ping clickhouse: %v", err)
}
return output.FLB_ERROR
}
// ==
client = db
return output.FLB_OK
}
//export FLBPluginFlush
// FLBPluginFlush is called from fluent-bit when data need to be sent. is called from fluent-bit when data need to be sent.
func FLBPluginFlush(data unsafe.Pointer, length C.int, tag *C.char) int {
rw.Lock()
defer rw.Unlock()
// ping
if err := client.Ping(); err != nil {
if exception, ok := err.(*clickhouse.Exception); ok {
klog.Errorf("[%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
} else {
klog.Errorf("Failed to ping clickhouse: %v", err)
}
return output.FLB_ERROR
}
// prepare data
//var h codec.Handle = new(codec.MsgpackHandle)
//var b []byte
//var m interface{}
//var err error
//b = C.GoBytes(data, length)
//dec := codec.NewDecoderBytes(b, h)
var ret int
var timestampData interface{}
var mapData map[interface{}]interface{}
// Create Fluent Bit decoder
dec := output.NewDecoder(data, int(length))
for {
//// decode the msgpack data
//err = dec.Decode(&m)
//if err != nil {
// break
//}
ret, timestampData, mapData = output.GetRecord(dec)
if ret != 0 {
break
}
// Get a slice and their two entries: timestamp and map
//slice := reflect.ValueOf(m)
//timestampData := slice.Index(0).Interface()
//data := slice.Index(1)
//timestamp, ok := timestampData.Interface().(uint64)
//if !ok {
// klog.Errorf("Unable to convert timestamp: %+v", timestampData)
// return output.FLB_ERROR
//}
var timestamp time.Time
switch t := timestampData.(type) {
case output.FLBTime:
timestamp = timestampData.(output.FLBTime).Time
case uint64:
timestamp = time.Unix(int64(t), 0)
default:
//klog.Infof("msg", "timestamp isn't known format. Use current time.")
timestamp = time.Now()
}
// Convert slice data to a real map and iterate
//mapData := data.Interface().(map[interface{}]interface{})
flattenData, err := Flatten(mapData, "", UnderscoreStyle)
if err != nil {
break
}
log := Log{}
for k, v := range flattenData {
value := ""
switch t := v.(type) {
case string:
value = t
case []byte:
value = string(t)
default:
value = fmt.Sprintf("%v", v)
}
switch k {
case "cluster":
log.Cluster = value
case "kubernetes_namespace_name":
log.Namespace = value
case "kubernetes_labels_app":
log.App = value
case "kubernetes_labels_k8s-app":
log.App = value
case "kubernetes_pod_name":
log.Pod = value
case "kubernetes_container_name":
log.Container = value
case "kubernetes_host":
log.Host = value
case "log":
log.Log = value
}
}
if log.App == "" {
break
}
//log.Ts = time.Unix(int64(timestamp), 0)
log.Ts = timestamp
buffer = append(buffer, log)
}
// sink data
if len(buffer) < batchSize {
return output.FLB_OK
}
sql := fmt.Sprintf(insertSQL, database, table)
//start := time.Now()
// post them to db all at once
tx, err := client.Begin()
if err != nil {
klog.Errorf("begin transaction failure: %s", err.Error())
return output.FLB_ERROR
}
// build statements
smt, err := tx.Prepare(sql)
if err != nil {
klog.Errorf("prepare statement failure: %s", err.Error())
return output.FLB_ERROR
}
for _, l := range buffer {
// ensure tags are inserted in the same order each time
// possibly/probably impacts indexing?
_, err = smt.Exec(l.Ts, l.Cluster, l.Namespace, l.App, l.Pod, l.Container, l.Host,
l.Log, l.Ts)
if err != nil {
klog.Errorf("statement exec failure: %s", err.Error())
return output.FLB_ERROR
}
}
// commit and record metrics
if err = tx.Commit(); err != nil {
klog.Errorf("commit failed failure: %s", err.Error())
return output.FLB_ERROR
}
//end := time.Now()
//klog.Infof("Exported %d log to clickhouse in %s", len(buffer), end.Sub(start))
buffer = make([]Log, 0)
return output.FLB_OK
}
//export FLBPluginExit
func FLBPluginExit() int {
return output.FLB_OK
}
func main() {
}