/
builtin.go
489 lines (433 loc) · 12.2 KB
/
builtin.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
package bql
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/sensorbee/sensorbee.v0/core"
"gopkg.in/sensorbee/sensorbee.v0/data"
)
// TODO: create bql/builtin directory and move components in this file to there
func createSharedStateSink(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Sink, error) {
// Get only name parameter from params
name, ok := params["name"]
if !ok {
return nil, fmt.Errorf("cannot find 'name' parameter")
}
nameStr, err := data.AsString(name)
if err != nil {
return nil, err
}
// TODO: Support cascading delete. Because it isn't supported yet,
// the sink will be running even after the target state is dropped.
// Moreover, creating a state having the same name after dropping
// the previous state might result in a confusing behavior.
return core.NewSharedStateSink(ctx, nameStr)
}
func init() {
MustRegisterGlobalSinkCreator("uds", SinkCreatorFunc(createSharedStateSink))
}
type readerSource struct {
filename string
tsField data.Path
ioParams *IOParams
// repeat is the number of times that the input data is read. When its value
// is less than 0, the source will read the input again and again until it's
// stopped. When the value is 0, the source only read the input once. When
// the value is k (> 0), the input is read k+1 times including the first run.
repeat int64
// interval is the interval between emissions of two consecutive tuples.
// When its value is less than or equal to 0, the source tries to emit
// tuples as fast as possible.
interval time.Duration
stopCh chan struct{}
}
func (s *readerSource) GenerateStream(ctx *core.Context, w core.Writer) error {
for r := int64(0); s.repeat < 0 || r <= s.repeat; r++ {
if err := s.generateStream(ctx, w); err != nil {
return err
}
}
return nil
}
func (s *readerSource) generateStream(ctx *core.Context, w core.Writer) error {
f, err := os.Open(s.filename)
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
ctx.ErrLog(err).WithField("node_name", s.ioParams.Name).
Warning("Cannot close the file")
}
}()
r := bufio.NewReader(f)
next := time.Now()
for lineNumber := 0; ; lineNumber++ {
line, err := r.ReadBytes('\n')
if err != nil && err != io.EOF {
return err
}
line = bytes.TrimSpace(line)
if len(line) == 0 {
if err == io.EOF {
break
}
continue
}
m := data.Map{}
if err := json.Unmarshal(line, &m); err != nil {
ctx.ErrLog(err).WithField("node_name", s.ioParams.Name).
WithField("jsonl_line_number", lineNumber).
WithField("body", string(line)).Warning("Ignoring the line due to a json parse error")
continue
}
t := core.NewTuple(m)
if s.interval > 0 {
// When the interval parameter is given, a proper application
// timestamp should be assigned to each tuple.
t.Timestamp = next
}
if s.tsField != nil {
if v, err := t.Data.Get(s.tsField); err == nil {
if ts, err := data.ToTimestamp(v); err != nil {
ctx.ErrLog(err).WithField("node_name", s.ioParams.Name).
WithField("jsonl_line_number", lineNumber).
WithField("timestamp_field", s.tsField).
WithField("timestamp_field_value", v).
Warning("Cannot convert a value in timestamp_field to a timestamp")
} else {
t.Timestamp = ts
}
}
}
if err := w.Write(ctx, t); err != nil {
return err
}
if s.interval > 0 {
// wait as accurate as possible
now := time.Now()
next = next.Add(s.interval)
if next.Before(now) {
// delayed too much and should be rescheduled.
next = now.Add(s.interval)
}
select {
case <-s.stopCh:
// This works as long as createFileSource returns a source
// wrapped with core.NewRewindableSource or core.ImplementSourceStop.
return core.ErrSourceStopped
case <-time.After(next.Sub(now)):
}
}
}
return nil
}
func (s *readerSource) Stop(ctx *core.Context) error {
close(s.stopCh)
return nil
}
func createFileSource(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Source, error) {
// TODO: add format parameter
v := &struct {
Path string `bql:",required"`
Rewindable bool
TimestampField string
Repeat int64
Interval time.Duration
}{
Rewindable: false,
TimestampField: "",
Repeat: 0,
}
dec := data.NewDecoder(nil)
if err := dec.Decode(params, v); err != nil {
return nil, err
}
var tsField data.Path
if v.TimestampField != "" {
var err error
if tsField, err = data.CompilePath(v.TimestampField); err != nil {
return nil, fmt.Errorf("'timestamp_field' parameter doesn't have a valid path: %v", err)
}
}
s := &readerSource{
filename: v.Path,
tsField: tsField,
ioParams: ioParams,
repeat: v.Repeat,
interval: v.Interval,
stopCh: make(chan struct{}),
}
if v.Rewindable {
return core.NewRewindableSource(s), nil
}
return core.ImplementSourceStop(s), nil
}
func init() {
MustRegisterGlobalSourceCreator("file", SourceCreatorFunc(createFileSource))
}
type writerSink struct {
m sync.Mutex
w io.Writer
shouldClose bool
}
func (s *writerSink) Write(ctx *core.Context, t *core.Tuple) error {
// TODO: support custom formatting. There're several things that need to
// be considered such as concurrent formatting, zero-copy write, and so on.
// While encoding tuples outside the lock supports concurrent formatting,
// it makes it difficult to support zero-copy write.
js := t.Data.String() // Format this outside the lock
// This lock is required to avoid interleaving JSONs.
s.m.Lock()
defer s.m.Unlock()
if s.w == nil {
return errors.New("the sink is already closed")
}
_, err := fmt.Fprintln(s.w, js)
return err
}
func (s *writerSink) Close(ctx *core.Context) error {
s.m.Lock()
defer s.m.Unlock()
if s.w == nil {
return nil
}
if s.shouldClose {
if c, ok := s.w.(io.Closer); ok {
return c.Close()
}
}
return nil
}
func createStdoutSink(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Sink, error) {
return &writerSink{
w: os.Stdout,
}, nil
}
func createFileSink(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Sink, error) {
// TODO: currently this sink isn't secure because it accepts any path.
// TODO: support buffering
// TODO: provide "format" parameter to support output formats other than "jsonl".
// "jsonl" should be the default value.
// TODO: support "compression" parameter with values like "gz".
v := &struct {
Path string `bql:",required"`
Truncate bool
// rotate information
MaxSize int
MaxAge int
MaxBackups int
}{
Truncate: false,
MaxSize: 0,
}
dec := data.NewDecoder(nil)
if err := dec.Decode(params, v); err != nil {
return nil, err
}
var w io.Writer
if v.MaxSize > 0 {
l := lumberjack.Logger{
Filename: v.Path,
}
if v.MaxAge > 0 {
l.MaxAge = v.MaxAge
}
if v.MaxBackups > 0 {
l.MaxBackups = v.MaxBackups
}
if _, err := os.Stat(v.Path); err == nil && v.Truncate {
if err := os.Truncate(v.Path, 0); err != nil {
return nil, err
}
}
w = &l
} else {
flags := os.O_WRONLY | os.O_APPEND | os.O_CREATE
if v.Truncate {
flags |= os.O_TRUNC
}
file, err := os.OpenFile(v.Path, flags, 0644)
if err != nil {
return nil, err
}
w = file
}
return &writerSink{
w: w,
shouldClose: true,
}, nil
}
func init() {
MustRegisterGlobalSinkCreator("stdout", SinkCreatorFunc(createStdoutSink))
MustRegisterGlobalSinkCreator("file", SinkCreatorFunc(createFileSink))
}
func createDroppedTupleCollectorSource(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Source, error) {
return core.NewDroppedTupleCollectorSource(), nil
}
func init() {
MustRegisterGlobalSourceCreator("dropped_tuples", SourceCreatorFunc(createDroppedTupleCollectorSource))
}
type nodeStatusSource struct {
topology core.Topology
interval time.Duration
stopCh chan struct{}
}
func (s *nodeStatusSource) GenerateStream(ctx *core.Context, w core.Writer) error {
next := time.Now().Add(s.interval)
for {
select {
case <-s.stopCh:
return nil
case <-time.After(next.Sub(time.Now())):
}
now := time.Now()
for name, n := range s.topology.Nodes() {
t := &core.Tuple{
Timestamp: now,
ProcTimestamp: now,
Data: n.Status(),
}
t.Data["node_name"] = data.String(name)
t.Data["node_type"] = data.String(n.Type().String())
w.Write(ctx, t)
}
next = next.Add(s.interval)
if next.Before(now) {
// delayed too much and should be rescheduled.
next = now.Add(s.interval)
}
}
}
func (s *nodeStatusSource) Stop(ctx *core.Context) error {
close(s.stopCh)
return nil
}
// createNodeStatusSourceCreator creates a SourceCreator which creates
// nodeStatusSource. Because it requires core.Topology, it cannot be registered
// statically. It'll be registered in a function like NewTopologyBuilder.
func createNodeStatusSourceCreator(t core.Topology) SourceCreator {
return SourceCreatorFunc(func(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Source, error) {
interval := 1 * time.Second
if v, ok := params["interval"]; !ok {
} else if d, err := data.ToDuration(v); err != nil {
return nil, err
} else {
interval = d
}
return &nodeStatusSource{
topology: t,
interval: interval,
stopCh: make(chan struct{}),
}, nil
})
}
type edgeStatusSource struct {
topology core.Topology
interval time.Duration
stopCh chan struct{}
}
func (s *edgeStatusSource) GenerateStream(ctx *core.Context, w core.Writer) error {
next := time.Now().Add(s.interval)
inputPath := data.MustCompilePath("input_stats.inputs")
for {
select {
case <-s.stopCh:
return nil
case <-time.After(next.Sub(time.Now())):
}
now := time.Now()
// collect all nodes that can receive data
receivers := map[string]core.Node{}
for name, b := range s.topology.Boxes() {
receivers[name] = b
}
for name, s := range s.topology.Sinks() {
receivers[name] = s
}
// loop over those receiver nodes and consider all of
// their incoming edges
for name, n := range receivers {
nodeStatus := n.Status()
// get the input status
inputs, err := nodeStatus.Get(inputPath)
if err != nil {
ctx.ErrLog(err).WithField("node_status", nodeStatus).
WithField("node_name", name).
Error("No input_stats present in node status")
continue
}
inputMap, err := data.AsMap(inputs)
if err != nil {
ctx.ErrLog(err).WithField("inputs", inputs).
WithField("node_name", name).
Error("input_stats.inputs is not a Map")
continue
}
// loop over the input nodes to get an edge-centric view
for inputName, inputStats := range inputMap {
inputNode, err := s.topology.Node(inputName)
if err != nil {
ctx.ErrLog(err).WithField("sender", inputName).
WithField("receiver", name).
Error("Node listens to non-existing node")
continue
}
edgeData := data.Map{
"sender": data.Map{
"node_name": data.String(inputName),
"node_type": data.String(inputNode.Type().String()),
},
"receiver": data.Map{
"node_name": data.String(name),
"node_type": data.String(n.Type().String()),
},
// use the input statistics for that edge from the
// receiver as edge statistics. the data is correct,
// but the wording may be a bit weird, e.g. "num_received"
// should maybe rather be "num_transferred"
"stats": inputStats,
}
// write tuple
t := &core.Tuple{
Timestamp: now,
ProcTimestamp: now,
Data: edgeData,
}
w.Write(ctx, t)
}
}
next = next.Add(s.interval)
if next.Before(now) {
// delayed too much and should be rescheduled.
next = now.Add(s.interval)
}
}
}
func (s *edgeStatusSource) Stop(ctx *core.Context) error {
close(s.stopCh)
return nil
}
func createEdgeStatusSourceCreator(t core.Topology) SourceCreator {
return SourceCreatorFunc(func(ctx *core.Context, ioParams *IOParams, params data.Map) (core.Source, error) {
interval := 1 * time.Second
if v, ok := params["interval"]; !ok {
} else if d, err := data.ToDuration(v); err != nil {
return nil, err
} else {
interval = d
}
return &edgeStatusSource{
topology: t,
interval: interval,
stopCh: make(chan struct{}),
}, nil
})
}