-
Notifications
You must be signed in to change notification settings - Fork 153
/
to.go
440 lines (408 loc) · 12.9 KB
/
to.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
package kafka
import (
"bufio"
"context"
"encoding/binary"
"io"
"net/url"
"sort"
"time"
"github.com/cespare/xxhash/v2"
"github.com/influxdata/flux"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/execute"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/internal/pkg/syncutil"
"github.com/influxdata/flux/plan"
"github.com/influxdata/flux/runtime"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
protocol "github.com/influxdata/line-protocol"
"github.com/segmentio/kafka-go"
)
const (
// ToKafkaKind is the Kind for the ToKafka Flux function
ToKafkaKind = "toKafka"
)
type ToKafkaOpSpec struct {
Brokers []string `json:"brokers"`
Topic string `json:"topic"`
Balancer string `json:"balancer"`
Name string `json:"name"`
NameColumn string `json:"nameColumn"` // either name or name_column must be set, if none is set try to use the "_measurement" column.
TimeColumn string `json:"timeColumn"`
TagColumns []string `json:"tagColumns"`
ValueColumns []string `json:"valueColumns"`
MsgBufSize int `json:"msgBufferSize"` // the maximim number of messages to buffer before sending to kafka, the library we use defaults to 100
}
func init() {
toKafkaSignature := runtime.MustLookupBuiltinType("kafka", "to")
runtime.RegisterPackageValue("kafka", "to", flux.MustValue(flux.FunctionValueWithSideEffect(ToKafkaKind, createToKafkaOpSpec, toKafkaSignature)))
flux.RegisterOpSpec(ToKafkaKind, func() flux.OperationSpec { return &ToKafkaOpSpec{} })
plan.RegisterProcedureSpecWithSideEffect(ToKafkaKind, newToKafkaProcedure, ToKafkaKind)
execute.RegisterTransformation(ToKafkaKind, createToKafkaTransformation)
}
// DefaultKafkaWriterFactory is a terrible name for a way to make a kafkaWriter that is injectable for testing
var DefaultKafkaWriterFactory = func(conf kafka.WriterConfig) KafkaWriter {
return kafka.NewWriter(conf)
}
// KafkaWriter is an interface for what we need fromDefaultKafkaWriterFactory
type KafkaWriter interface {
io.Closer
WriteMessages(context.Context, ...kafka.Message) error
}
// ReadArgs loads a flux.Arguments into ToKafkaOpSpec. It sets several default values.
// If the time_column isn't set, it defaults to execute.TimeColLabel.
// If the value_column isn't set it defaults to a []string{execute.DefaultValueColLabel}.
func (o *ToKafkaOpSpec) ReadArgs(args flux.Arguments) error {
var err error
var ok bool
brokers, err := args.GetRequiredArray("brokers", semantic.String)
if err != nil {
return err
}
l := brokers.Len()
o.Brokers = make([]string, l)
if brokers.Len() < 1 {
return errors.New(codes.Invalid, "at least one broker is required")
}
for i := 0; i < l; i++ {
o.Brokers[i] = brokers.Get(i).Str()
}
o.Topic, err = args.GetRequiredString("topic")
if err != nil {
return err
}
if len(o.Topic) == 0 {
return errors.New(codes.Invalid, "invalid topic name")
}
o.Balancer, _, err = args.GetString("balancer")
if err != nil {
return err
}
o.Name, ok, err = args.GetString("name")
if err != nil {
return err
}
if !ok {
o.NameColumn, ok, err = args.GetString("nameColumn")
if err != nil {
return err
}
if !ok {
o.NameColumn = "_measurement"
}
}
o.TimeColumn, ok, err = args.GetString("timeColumn")
if err != nil {
return err
}
if !ok {
o.TimeColumn = execute.DefaultTimeColLabel
}
tagColumns, ok, err := args.GetArray("tagColumns", semantic.String)
if err != nil {
return err
}
o.TagColumns = o.TagColumns[:0]
if ok {
for i := 0; i < tagColumns.Len(); i++ {
o.TagColumns = append(o.TagColumns, tagColumns.Get(i).Str())
}
sort.Strings(o.TagColumns)
}
valueColumns, ok, err := args.GetArray("valueColumns", semantic.String)
if err != nil {
return err
}
o.ValueColumns = o.ValueColumns[:0]
if !ok || valueColumns.Len() == 0 {
o.ValueColumns = append(o.ValueColumns, execute.DefaultValueColLabel)
} else {
for i := 0; i < valueColumns.Len(); i++ {
o.TagColumns = append(o.ValueColumns, valueColumns.Get(i).Str())
}
sort.Strings(o.TagColumns)
}
msgBufSize, ok, err := args.GetInt("msgBufferSize")
o.MsgBufSize = int(msgBufSize)
if err != nil {
return err
}
if o.MsgBufSize < 0 || !ok {
o.MsgBufSize = 0 // so the library will set it to the default
}
return err
}
func createToKafkaOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) {
if err := a.AddParentFromArgs(args); err != nil {
return nil, err
}
s := new(ToKafkaOpSpec)
if err := s.ReadArgs(args); err != nil {
return nil, err
}
return s, nil
}
func (ToKafkaOpSpec) Kind() flux.OperationKind {
return ToKafkaKind
}
type ToKafkaProcedureSpec struct {
plan.DefaultCost
Spec *ToKafkaOpSpec
balancer kafka.Balancer
}
func (o *ToKafkaProcedureSpec) Kind() plan.ProcedureKind {
return ToKafkaKind
}
func (o *ToKafkaProcedureSpec) Copy() plan.ProcedureSpec {
s := o.Spec
res := &ToKafkaProcedureSpec{
Spec: &ToKafkaOpSpec{
Brokers: append([]string(nil), s.Brokers...),
Topic: s.Topic,
Balancer: s.Balancer,
Name: s.Name,
NameColumn: s.NameColumn,
TimeColumn: s.TimeColumn,
TagColumns: append([]string(nil), s.TagColumns...),
ValueColumns: append([]string(nil), s.ValueColumns...),
},
}
switch s.Balancer {
case "hash", "": //hash is default for compatibility with enterprise
res.balancer = &kafka.Hash{}
case "round-robin":
res.balancer = &kafka.RoundRobin{}
case "least-bytes":
res.balancer = &kafka.LeastBytes{}
}
return res
}
func newToKafkaProcedure(qs flux.OperationSpec, a plan.Administration) (plan.ProcedureSpec, error) {
spec, ok := qs.(*ToKafkaOpSpec)
if !ok && spec != nil {
return nil, errors.Newf(codes.Internal, "invalid spec type %T", qs)
}
return &ToKafkaProcedureSpec{Spec: spec}, nil
}
func createToKafkaTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*ToKafkaProcedureSpec)
if !ok {
return nil, nil, errors.Newf(codes.Internal, "invalid spec type %T", spec)
}
cache := execute.NewTableBuilderCache(a.Allocator())
d := execute.NewDataset(id, mode, cache)
deps := flux.GetDependencies(a.Context())
t, err := NewToKafkaTransformation(d, deps, cache, s)
return t, d, err
}
type ToKafkaTransformation struct {
execute.ExecutionNode
d execute.Dataset
cache execute.TableBuilderCache
spec *ToKafkaProcedureSpec
}
func (t *ToKafkaTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return t.d.RetractTable(key)
}
func NewToKafkaTransformation(d execute.Dataset, deps flux.Dependencies, cache execute.TableBuilderCache, spec *ToKafkaProcedureSpec) (*ToKafkaTransformation, error) {
validator, err := deps.URLValidator()
if err != nil {
return nil, err
}
for _, b := range spec.Spec.Brokers {
u, err := url.Parse(b)
if err != nil {
return nil, errors.Newf(codes.Invalid, "invalid kafka broker url: %v", err)
}
if err := validator.Validate(u); err != nil {
return nil, errors.Newf(codes.Invalid, "kafka broker url did not pass validation: %v", err)
}
}
return &ToKafkaTransformation{
d: d,
cache: cache,
spec: spec,
}, nil
}
type toKafkaMetric struct {
tags []*protocol.Tag
fields []*protocol.Field
name string
t time.Time
}
func (m *toKafkaMetric) TagList() []*protocol.Tag {
return m.tags
}
func (m *toKafkaMetric) FieldList() []*protocol.Field {
return m.fields
}
func (m *toKafkaMetric) truncateTagsAndFields() {
m.fields = m.fields[:0]
m.tags = m.tags[:0]
}
func (m *toKafkaMetric) Name() string {
return m.name
}
func (m *toKafkaMetric) Time() time.Time {
return m.t
}
type idxType struct {
Idx int
Type flux.ColType
}
func (t *ToKafkaTransformation) Process(id execute.DatasetID, tbl flux.Table) (err error) {
w := DefaultKafkaWriterFactory(kafka.WriterConfig{
Brokers: t.spec.Spec.Brokers,
Topic: t.spec.Spec.Topic,
Balancer: t.spec.balancer,
BatchSize: t.spec.Spec.MsgBufSize,
QueueCapacity: t.spec.Spec.MsgBufSize,
})
defer func() {
err2 := w.Close()
// don't overwrite current error
if err != nil {
return
}
if err2 != nil {
// allow Process to return the error from the defered Close()
err = err2
return
}
}()
pr, pw := io.Pipe() // TODO: replce the pipe with something faster
// I'd like a linereader in line-protocol
m := &toKafkaMetric{}
e := protocol.NewEncoder(pw)
e.FailOnFieldErr(true)
e.SetFieldSortOrder(protocol.SortFields)
cols := tbl.Cols()
labels := make(map[string]idxType, len(cols))
for i, col := range cols {
labels[col.Label] = idxType{Idx: i, Type: col.Type}
}
// do time
timeColLabel := t.spec.Spec.TimeColumn
timeColIdx, ok := labels[timeColLabel]
if !ok {
return errors.New(codes.FailedPrecondition, "could not get time column")
}
if timeColIdx.Type != flux.TTime {
return errors.Newf(codes.FailedPrecondition, "column %s is not of type %s", timeColLabel, timeColIdx.Type)
}
var measurementNameCol string
if t.spec.Spec.Name == "" {
measurementNameCol = t.spec.Spec.NameColumn
}
// check if each col is a tag or value and cache this value for the loop
colMetadatas := tbl.Cols()
isTag := make([]bool, len(colMetadatas))
isValue := make([]bool, len(colMetadatas))
for i, col := range colMetadatas {
isValue[i] = sort.SearchStrings(t.spec.Spec.ValueColumns, col.Label) < len(t.spec.Spec.ValueColumns) && t.spec.Spec.ValueColumns[sort.SearchStrings(t.spec.Spec.ValueColumns, col.Label)] == col.Label
isTag[i] = sort.SearchStrings(t.spec.Spec.TagColumns, col.Label) < len(t.spec.Spec.TagColumns) && t.spec.Spec.TagColumns[sort.SearchStrings(t.spec.Spec.TagColumns, col.Label)] == col.Label
}
m.name = t.spec.Spec.Name
builder, new := t.cache.TableBuilder(tbl.Key())
if new {
if err := execute.AddTableCols(tbl, builder); err != nil {
return err
}
}
var wg syncutil.WaitGroup
wg.Do(func() error {
if err := tbl.Do(func(er flux.ColReader) error {
l := er.Len()
for i := 0; i < l; i++ {
m.truncateTagsAndFields()
for j, col := range er.Cols() {
switch {
case col.Label == timeColLabel:
m.t = values.Time(er.Times(j).Value(i)).Time()
case measurementNameCol != "" && measurementNameCol == col.Label:
if col.Type != flux.TString {
return errors.New(codes.FailedPrecondition, "invalid type for measurement column")
}
m.name = er.Strings(j).Value(i)
case isTag[j]:
if col.Type != flux.TString {
return errors.New(codes.FailedPrecondition, "invalid type for measurement column")
}
m.tags = append(m.tags, &protocol.Tag{Key: col.Label, Value: er.Strings(j).Value(i)})
case isValue[j]:
switch col.Type {
case flux.TFloat:
m.fields = append(m.fields, &protocol.Field{Key: col.Label, Value: er.Floats(j).Value(i)})
case flux.TInt:
m.fields = append(m.fields, &protocol.Field{Key: col.Label, Value: er.Ints(j).Value(i)})
case flux.TUInt:
m.fields = append(m.fields, &protocol.Field{Key: col.Label, Value: er.UInts(j).Value(i)})
case flux.TString:
m.fields = append(m.fields, &protocol.Field{Key: col.Label, Value: er.Strings(j).Value(i)})
case flux.TTime:
m.fields = append(m.fields, &protocol.Field{Key: col.Label, Value: values.Time(er.Times(j).Value(i))})
case flux.TBool:
m.fields = append(m.fields, &protocol.Field{Key: col.Label, Value: er.Bools(j).Value(i)})
default:
return errors.Newf(codes.FailedPrecondition, "invalid type for column %s", col.Label)
}
}
}
_, err := e.Encode(m)
if err != nil {
return err
}
if err := execute.AppendRecord(i, er, builder); err != nil {
return err
}
}
return nil
}); err != nil {
_ = pw.Close()
return err
}
return pw.Close()
})
// write the data to kafka
{
scan := bufio.NewScanner(pr)
msgBuf := make([]kafka.Message, 128)
i := 0
// todo, make this a little more async
for scan.Scan() {
v := append([]byte(nil), scan.Bytes()...) // we do this since scan.Bytes()'s result can be overwritten by calls to Scan()
if cap(msgBuf[i].Key) != 8 {
msgBuf[i].Key = make([]byte, 8)
}
binary.LittleEndian.PutUint64(msgBuf[i].Key, xxhash.Sum64(v))
msgBuf[i].Value = v
if i == t.spec.Spec.MsgBufSize-1 {
if err = w.WriteMessages(context.Background(), msgBuf...); err != nil {
return err
}
msgBuf = msgBuf[:0]
i = 0
}
i++
}
// send the remainder of the messages
if len(msgBuf) > 0 {
err = w.WriteMessages(context.Background(), msgBuf[:i]...)
}
}
if err := wg.Wait(); err != nil {
return err
}
return err
}
func (t *ToKafkaTransformation) UpdateWatermark(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateWatermark(pt)
}
func (t *ToKafkaTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *ToKafkaTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
}