forked from sensorbee/sensorbee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
115 lines (101 loc) · 2.05 KB
/
io.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
package exp
import (
"bufio"
"bytes"
"encoding/json"
"gopkg.in/sensorbee/sensorbee.v0/core"
"gopkg.in/sensorbee/sensorbee.v0/data"
"io"
"os"
"time"
)
type jsonlRecord struct {
Timestamp data.Timestamp `json:"t"`
Data data.Map `json:"d"`
}
type jsonlSource struct {
filename string
}
func newJSONLSource(filename string) (*jsonlSource, error) {
if _, err := os.Stat(filename); err != nil {
return nil, err
}
return &jsonlSource{
filename: filename,
}, nil
}
func (s *jsonlSource) GenerateStream(ctx *core.Context, w core.Writer) error {
f, err := os.Open(s.filename)
if err != nil {
return err
}
defer f.Close()
r := bufio.NewReader(f)
for {
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 {
return nil
}
continue
}
var jr jsonlRecord
if err := json.Unmarshal(line, &jr); err != nil {
ctx.ErrLog(err).WithField("body", string(line)).Error("Cannot parse a json object")
continue
}
t := &core.Tuple{
Timestamp: time.Time(jr.Timestamp),
ProcTimestamp: time.Now(),
Data: jr.Data,
}
w.Write(ctx, t)
}
return nil
}
func (s *jsonlSource) Stop(ctx *core.Context) error {
// TODO: support graceful stop on interruption
return nil
}
type jsonlSink struct {
f *os.File
buf *bufio.Writer
}
func newJSONLSink(filename string) (*jsonlSink, error) {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return nil, err
}
return &jsonlSink{
f: f,
buf: bufio.NewWriter(f),
}, nil
}
func (s *jsonlSink) Write(ctx *core.Context, t *core.Tuple) error {
data, err := json.Marshal(&jsonlRecord{
Timestamp: data.Timestamp(t.Timestamp),
Data: t.Data,
})
if err != nil {
return err
}
_, err = s.buf.Write(data)
if err != nil {
return err
}
_, err = s.buf.Write([]byte("\n"))
return err
}
func (s *jsonlSink) Close(ctx *core.Context) error {
if s.f == nil {
return nil
}
s.buf.Flush()
err := s.f.Close()
s.f = nil
return err
}