-
Notifications
You must be signed in to change notification settings - Fork 154
/
to.go
497 lines (449 loc) · 13.3 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
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
package mqtt
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"sort"
"strings"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/influxdata/flux"
"github.com/influxdata/flux/execute"
"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"
)
const (
ToMQTTKind = "toMQTT"
DefaultToMQTTTimeout = 1 * time.Second
)
func init() {
toMQTTSignature := runtime.MustLookupBuiltinType("experimental/mqtt", "to")
runtime.RegisterPackageValue("experimental/mqtt", "to", flux.MustValue(flux.FunctionValueWithSideEffect(ToMQTTKind, createToMQTTOpSpec, toMQTTSignature)))
flux.RegisterOpSpec(ToMQTTKind, func() flux.OperationSpec { return &ToMQTTOpSpec{} })
plan.RegisterProcedureSpecWithSideEffect(ToMQTTKind, newToMQTTProcedure, ToMQTTKind)
execute.RegisterTransformation(ToMQTTKind, createToMQTTTransformation)
}
// DefaultToMQTTUserAgent is the default user agent used by ToMqtt
var DefaultToMQTTUserAgent = "fluxd/dev"
// this is used so we can get better validation on marshaling, innerToMQTTOpSpec and ToMQTTOpSpec
// need to have identical fields
type innerToMQTTOpSpec ToMQTTOpSpec
type ToMQTTOpSpec struct {
Broker string `json:"broker"`
Name string `json:"name"`
Topic string `json:"topic"`
Message string `json:"message"`
ClientID string `json:"clientid"`
Username string `json:"username"`
Password string `json:"password"`
QoS int `json:"qos"`
NameColumn string `json:"nameColumn"` // either name or name_column must be set, if none is set try to use the "_measurement" column.
Timeout time.Duration `json:"timeout"` // default to something reasonable if zero
NoKeepAlive bool `json:"noKeepAlive"`
TimeColumn string `json:"timeColumn"`
TagColumns []string `json:"tagColumns"`
ValueColumns []string `json:"valueColumns"`
}
// ReadArgs loads a flux.Arguments into ToMQTTOpSpec. 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 *ToMQTTOpSpec) ReadArgs(args flux.Arguments) error {
var err error
o.Broker, err = args.GetRequiredString("broker")
if err != nil {
return err
}
var ok bool
o.Message, _, err = args.GetString("message")
if err != nil {
return err
}
o.Topic, _, err = args.GetString("topic")
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.ClientID, ok, err = args.GetString("clientid")
if err != nil {
return err
}
if !ok {
o.ClientID = "flux-mqtt"
}
o.Username, ok, err = args.GetString("username")
if err != nil {
return err
}
if ok {
o.Password, ok, err = args.GetString("password")
if err != nil {
return err
}
if !ok {
return fmt.Errorf("password required with username %s", o.Username)
}
}
q, ok, err := args.GetInt("qos")
if err != nil {
return err
}
if !ok {
o.QoS = 0
} else {
o.QoS = int(q)
}
if o.QoS < 0 || o.QoS > 3 {
o.QoS = 0 // default to 0 if some random value is passed
}
timeout, ok, err := args.GetDuration("timeout")
if err != nil {
return err
}
if !ok {
o.Timeout = DefaultToMQTTTimeout
} else {
o.Timeout = values.Duration(timeout).Duration()
}
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.ValueColumns = append(o.ValueColumns, valueColumns.Get(i).Str())
}
sort.Strings(o.ValueColumns)
}
return err
}
func createToMQTTOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) {
if err := a.AddParentFromArgs(args); err != nil {
return nil, err
}
s := new(ToMQTTOpSpec)
if err := s.ReadArgs(args); err != nil {
return nil, err
}
return s, nil
}
// UnmarshalJSON unmarshals and validates toMQTTOpSpec into JSON.
func (o *ToMQTTOpSpec) UnmarshalJSON(b []byte) (err error) {
if err = json.Unmarshal(b, (*innerToMQTTOpSpec)(o)); err != nil {
return err
}
u, err := url.ParseRequestURI(o.Broker)
if err != nil {
return err
}
if !(u.Scheme == "tcp" || u.Scheme == "ws" || u.Scheme == "tls") {
return fmt.Errorf("scheme must be tcp or ws or tls but was %s", u.Scheme)
}
return nil
}
func (ToMQTTOpSpec) Kind() flux.OperationKind {
return ToMQTTKind
}
type ToMQTTProcedureSpec struct {
plan.DefaultCost
Spec *ToMQTTOpSpec
}
func (o *ToMQTTProcedureSpec) Kind() plan.ProcedureKind {
return ToMQTTKind
}
func (o *ToMQTTProcedureSpec) Copy() plan.ProcedureSpec {
s := o.Spec
res := &ToMQTTProcedureSpec{
Spec: &ToMQTTOpSpec{
Broker: s.Broker,
Topic: s.Topic,
Name: s.Name,
QoS: s.QoS,
Username: s.Username,
Password: s.Password,
NameColumn: s.NameColumn,
Timeout: s.Timeout,
NoKeepAlive: s.NoKeepAlive,
TimeColumn: s.TimeColumn,
TagColumns: append([]string(nil), s.TagColumns...),
ValueColumns: append([]string(nil), s.ValueColumns...),
},
}
return res
}
func newToMQTTProcedure(qs flux.OperationSpec, a plan.Administration) (plan.ProcedureSpec, error) {
spec, ok := qs.(*ToMQTTOpSpec)
if !ok && spec != nil {
return nil, fmt.Errorf("invalid spec type %T", qs)
}
return &ToMQTTProcedureSpec{Spec: spec}, nil
}
func createToMQTTTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*ToMQTTProcedureSpec)
if !ok {
return nil, nil, fmt.Errorf("invalid spec type %T", spec)
}
cache := execute.NewTableBuilderCache(a.Allocator())
d := execute.NewDataset(id, mode, cache)
t := NewToMQTTTransformation(d, cache, s)
return t, d, nil
}
type ToMQTTTransformation struct {
d execute.Dataset
cache execute.TableBuilderCache
spec *ToMQTTProcedureSpec
}
func (t *ToMQTTTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return t.d.RetractTable(key)
}
func NewToMQTTTransformation(d execute.Dataset, cache execute.TableBuilderCache, spec *ToMQTTProcedureSpec) *ToMQTTTransformation {
return &ToMQTTTransformation{
d: d,
cache: cache,
spec: spec,
}
}
type toMqttMetric struct {
tags []*protocol.Tag
fields []*protocol.Field
name string
t time.Time
}
func (m *toMqttMetric) TagList() []*protocol.Tag {
return m.tags
}
func (m *toMqttMetric) FieldList() []*protocol.Field {
return m.fields
}
func (m *toMqttMetric) truncateTagsAndFields() {
m.fields = m.fields[:0]
m.tags = m.tags[:0]
}
func (m *toMqttMetric) Name() string {
return m.name
}
func (m *toMqttMetric) Time() time.Time {
return m.t
}
type idxType struct {
Idx int
Type flux.ColType
}
func (t *ToMQTTTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
// set up the MQTT options.
opts := MQTT.NewClientOptions().AddBroker(t.spec.Spec.Broker)
if t.spec.Spec.ClientID != "" {
opts.SetClientID(t.spec.Spec.ClientID)
} else {
opts.SetClientID("flux-mqtt")
}
if t.spec.Spec.Timeout > 0 {
opts.SetConnectTimeout(t.spec.Spec.Timeout)
}
if t.spec.Spec.Username != "" {
opts.SetUsername(t.spec.Spec.Username)
}
if t.spec.Spec.Password != "" {
opts.SetPassword(t.spec.Spec.Password)
}
mqttTopic := t.spec.Spec.Topic
client := MQTT.NewClient(opts)
if t.spec.Spec.Message != "" {
//create and start a client using the above ClientOptions
if token := client.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
token := client.Publish(t.spec.Spec.Topic, 0, false, t.spec.Spec.Message)
token.Wait()
client.Disconnect(250)
return nil
}
pr, pw := io.Pipe() // TODO: replce the pipe with something faster
m := &toMqttMetric{}
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}
}
timeColLabel := t.spec.Spec.TimeColumn
timeColIdx, ok := labels[timeColLabel]
if !ok {
return errors.New("could not get time column")
}
if timeColIdx.Type != flux.TTime {
return fmt.Errorf("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 {
valIdx := sort.SearchStrings(t.spec.Spec.ValueColumns, col.Label)
isValue[i] = valIdx < len(t.spec.Spec.ValueColumns) && t.spec.Spec.ValueColumns[valIdx] == col.Label
tagIdx := sort.SearchStrings(t.spec.Spec.TagColumns, col.Label)
isTag[i] = tagIdx < len(t.spec.Spec.TagColumns) && t.spec.Spec.TagColumns[tagIdx] == col.Label
}
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 {
m.name = t.spec.Spec.Name
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("invalid type for measurement column")
}
m.name = er.Strings(j).ValueString(i)
case isTag[j]:
if col.Type != flux.TString {
return errors.New("invalid type for tag column")
}
m.tags = append(m.tags, &protocol.Tag{Key: col.Label, Value: er.Strings(j).ValueString(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).ValueString(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 fmt.Errorf("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
})
if e := pw.Close(); e != nil && err == nil {
err = e
}
return err
})
//start a client using the above ClientOptions
if token := client.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
p := make([]byte, 2024)
var message strings.Builder
for {
n, err := pr.Read(p)
if err != nil {
if err == io.EOF {
message.WriteString(string(p[:n]))
break
}
client.Disconnect(250)
return err
}
message.WriteString(string(p[:n]))
}
if message.String() != "" {
if mqttTopic == "" {
mqttTopic = m.createTopic(message.String())
}
token := client.Publish(mqttTopic, 0, false, message.String())
token.Wait()
}
if err := wg.Wait(); err != nil {
client.Disconnect(250)
return err
}
client.Disconnect(250)
return nil
}
// creates a topic consisting of measurement/tagname/tagvalue for all tags
func (t *toMqttMetric) createTopic(topicString string) string {
var top strings.Builder
tt := strings.Split(topicString, " ")
tt = strings.Split(tt[0], ",")
top.WriteString("/")
top.WriteString(tt[0])
l := len(tt) - 1
for i := 1; i < l; i++ {
toke := strings.Split(tt[i], "=")
top.WriteString("/")
top.WriteString(toke[0])
top.WriteString("/")
top.WriteString(toke[1])
}
return top.String()
}
func (t *ToMQTTTransformation) UpdateWatermark(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateWatermark(pt)
}
func (t *ToMQTTTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *ToMQTTTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
}