-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_sink.go
216 lines (175 loc) · 4.2 KB
/
file_sink.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
package main
import (
"bytes"
"errors"
"fmt"
"path/filepath"
"os"
"time"
)
const (
FILE_TYPE_CSV uint = 1
FILE_TYPE_JSON uint = 2
)
type FileSink struct {
path string
file *os.File
fileType uint
fifo chan *Point
maxAge time.Duration
lastSave time.Time
recordCount uint
}
// Returns a new file sink.
func NewFileSink(path string, fileType uint, fifoSize uint, maxAge time.Duration) (fs *FileSink, err error) {
var writeInterval time.Duration
var fileInfo os.FileInfo
fs = &FileSink{
path: path,
fileType: fileType,
maxAge: maxAge,
}
if fileType != FILE_TYPE_JSON && fileType != FILE_TYPE_CSV {
err = fmt.Errorf("unsupported file type %v", fileType)
return
}
// make sure path is accessible and a directory
fileInfo, err = os.Stat(fs.path)
if err != nil {
fmt.Printf("failed to stat path '%v': %v'\n", fs.path, err)
return
}
if !fileInfo.IsDir() {
err = fmt.Errorf("%s is not a directory", fs.path)
return
}
// default to 1k points
if fifoSize == 0 {
fifoSize = 1000
}
// default to writing once every minute
if fs.maxAge == 0 {
fs.maxAge = 1 * time.Minute
}
if fs.maxAge < 1 * time.Second {
writeInterval = fs.maxAge
} else {
writeInterval = 1 * time.Second
}
fs.fifo = make(chan *Point, fifoSize)
go fs.writer(writeInterval)
return
}
// Buffers points for later disk write. Points are rejected when the fifo is full.
func (fs *FileSink) Save(points []*Point) (acceptedCount uint) {
for _, p := range points {
if len(fs.fifo) < cap(fs.fifo) {
fs.fifo <- p
acceptedCount++
}
}
return
}
// Writer goroutine. Creates one datafile per day and invokes write() as appropriate.
func (fs *FileSink) writer(tickRate time.Duration) {
var err error
var highWaterMark int
var ticker *time.Ticker
var file *os.File
var filePath string
var fileName string
var now time.Time
var dayOfMonth int
highWaterMark = (cap(fs.fifo) * 80) / 100
ticker = time.NewTicker(tickRate)
for {
<-ticker.C
now = time.Now().UTC()
// close the file on day changes
if dayOfMonth != now.Day() {
dayOfMonth = now.Day()
if fs.file != nil {
fs.file.Close()
fs.file = nil
fmt.Printf("saved %d records in %s\n", fs.recordCount, filePath)
fs.recordCount = 0
}
}
// open a log file if needed, in the form path/YYYY-MM-DD.suffix, with suffix
// either csv or json, depending on the file type.
if fs.file == nil {
fileName = now.Format("2006-01-02")
if fs.fileType == FILE_TYPE_JSON {
fileName += ".json"
} else {
fileName += ".csv"
}
filePath = filepath.Join(fs.path, fileName)
file, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
// if we failed to open the file, sleep for 30s before trying again
if err != nil {
fmt.Printf("failed to open file '%s': %v\n", filePath, err)
time.Sleep(30 * time.Second)
continue
}
fs.file = file
fmt.Printf("opened %s for writing\n", filePath)
}
if time.Since(fs.lastSave) >= fs.maxAge || len(fs.fifo) > highWaterMark {
err = fs.write()
if err != nil {
fmt.Printf("failed to write: %v\n", err)
continue
}
fs.lastSave = time.Now()
}
}
return
}
// Flushes the fifo contents to disk.
func (fs *FileSink) write() (err error) {
var buf bytes.Buffer
var count uint
var p *Point
if fs.file == nil {
err = errors.New("sink closed")
return
}
for len(fs.fifo) > 0 {
p = <-fs.fifo
// drop nil points
if p == nil {
continue
}
switch fs.fileType {
case FILE_TYPE_CSV:
_, err = buf.WriteString(
fmt.Sprintf("%d,%s,%v\n",
p.Timestamp.UnixNano() / 1e6,
p.Label,
p.Value))
case FILE_TYPE_JSON:
_, err = buf.WriteString(
fmt.Sprintf("{\"timestamp\":%d,\"label\":\"%s\",\"value\":%v}\n",
p.Timestamp.UnixNano() / 1e6,
p.Label,
p.Value))
default:
err = fmt.Errorf("unknown file type %v", fs.fileType)
return
}
// if we failed to serialize the point for whatever reason, drop it
if err != nil {
fmt.Printf("failed to serialize point (%v): %v\n", p, err)
continue
}
count++
}
_,err = buf.WriteTo(fs.file)
buf.Reset()
// keep track of successful writes
if err == nil {
fs.recordCount += count
}
return
}