/
buffer.go
291 lines (240 loc) · 5.38 KB
/
buffer.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
// Package buffer provides an io.Writer as a 1:N on-disk buffer,
// publishing flushed files to a channel for processing.
//
// Files may be flushed via interval, write count, or byte size.
//
// All exported methods are thread-safe.
package buffer
import (
"bufio"
"fmt"
"log"
"os"
"sync"
"sync/atomic"
"time"
)
// PID for unique filename.
var pid = os.Getpid()
// Ids for unique filename.
var ids = int64(0)
// Reason for flush.
type Reason string
// Flush reasons.
const (
Forced Reason = "forced"
Writes Reason = "writes"
Bytes Reason = "bytes"
Interval Reason = "interval"
)
// Flush represents a flushed file.
type Flush struct {
Reason Reason `json:"reason"`
Path string `json:"path"`
Writes int64 `json:"writes"`
Bytes int64 `json:"bytes"`
Opened time.Time `json:"opened"`
Closed time.Time `json:"closed"`
Age time.Duration `json:"age"`
}
// Config for disk buffer.
type Config struct {
FlushWrites int64 // Flush after N writes, zero to disable
FlushBytes int64 // Flush after N bytes, zero to disable
FlushInterval time.Duration // Flush after duration, zero to disable
BufferSize int // Buffer size for writes
Queue chan *Flush // Queue of flushed files
Verbosity int // Verbosity level, 0-3
Logger *log.Logger // Logger instance
}
// Validate the configuration.
func (c *Config) Validate() error {
switch {
case c.FlushBytes == 0 && c.FlushWrites == 0 && c.FlushInterval == 0:
return fmt.Errorf("at least one flush mechanism must be non-zero")
default:
return nil
}
}
// Buffer represents a 1:N on-disk buffer.
type Buffer struct {
*Config
verbosity int
path string
ids int64
id int64
sync.RWMutex
buf *bufio.Writer
opened time.Time
writes int64
bytes int64
file *os.File
tick *time.Ticker
}
// New buffer at `path`. The path given is used for the base
// of the filenames created, which append ".{pid}.{id}.{fid}".
func New(path string, config *Config) (*Buffer, error) {
id := atomic.AddInt64(&ids, 1)
b := &Buffer{
Config: config,
path: path,
id: id,
verbosity: 1,
}
if b.Logger == nil {
prefix := fmt.Sprintf("buffer #%d %q ", b.id, path)
b.Logger = log.New(os.Stderr, prefix, log.LstdFlags)
}
if b.Queue == nil {
b.Queue = make(chan *Flush)
}
if b.FlushInterval != 0 {
b.tick = time.NewTicker(config.FlushInterval)
go b.loop()
}
err := config.Validate()
if err != nil {
return nil, err
}
return b, b.open()
}
// Write implements io.Writer.
func (b *Buffer) Write(data []byte) (int, error) {
b.log(3, "write %s", data)
b.Lock()
defer b.Unlock()
n, err := b.write(data)
if err != nil {
return n, err
}
if b.FlushWrites != 0 && b.writes >= b.FlushWrites {
err := b.flush(Writes)
if err != nil {
return n, err
}
}
if b.FlushBytes != 0 && b.bytes >= b.FlushBytes {
err := b.flush(Bytes)
if err != nil {
return n, err
}
}
return n, err
}
// Close the underlying file after flushing.
func (b *Buffer) Close() error {
b.Lock()
defer b.Unlock()
if b.tick != nil {
b.tick.Stop()
}
return b.flush(Forced)
}
// Flush forces a flush.
func (b *Buffer) Flush() error {
b.Lock()
defer b.Unlock()
return b.flush(Forced)
}
// Writes returns the number of writes made to the current file.
func (b *Buffer) Writes() int64 {
b.RLock()
defer b.RUnlock()
return b.writes
}
// Bytes returns the number of bytes made to the current file.
func (b *Buffer) Bytes() int64 {
b.RLock()
defer b.RUnlock()
return b.bytes
}
// Loop for flush interval.
func (b *Buffer) loop() {
for range b.tick.C {
b.Lock()
b.flush(Interval)
b.Unlock()
}
}
// Open a new buffer.
func (b *Buffer) open() error {
path := b.pathname()
b.log(1, "opening %s", path)
f, err := os.Create(path)
if err != nil {
return err
}
b.log(2, "buffer size %d", b.BufferSize)
if b.BufferSize != 0 {
b.buf = bufio.NewWriterSize(f, b.BufferSize)
}
b.log(2, "reset state")
b.opened = time.Now()
b.writes = 0
b.bytes = 0
b.file = f
return nil
}
// Write with metrics.
func (b *Buffer) write(data []byte) (int, error) {
b.writes++
b.bytes += int64(len(data))
if b.BufferSize != 0 {
return b.buf.Write(data)
}
return b.file.Write(data)
}
// Flush for the given reason and re-open.
func (b *Buffer) flush(reason Reason) error {
b.log(1, "flushing (%s)", reason)
if b.writes == 0 {
b.log(2, "nothing to flush")
return nil
}
err := b.close()
if err != nil {
return err
}
b.Queue <- &Flush{
Reason: reason,
Writes: b.writes,
Bytes: b.bytes,
Opened: b.opened,
Closed: time.Now(),
Path: b.file.Name() + ".closed",
Age: time.Since(b.opened),
}
return b.open()
}
// Close existing file after a rename.
func (b *Buffer) close() error {
if b.file == nil {
return nil
}
path := b.file.Name()
b.log(2, "renaming %q", path)
err := os.Rename(path, path+".closed")
if err != nil {
return err
}
if b.BufferSize != 0 {
b.log(2, "flushing %q", path)
err = b.buf.Flush()
if err != nil {
return err
}
}
b.log(2, "closing %q", path)
return b.file.Close()
}
// Pathname for a new buffer.
func (b *Buffer) pathname() string {
fid := atomic.AddInt64(&b.ids, 1)
return fmt.Sprintf("%s.%d.%d.%d", b.path, pid, b.id, fid)
}
// Log helper.
func (b *Buffer) log(n int, msg string, args ...interface{}) {
if b.Verbosity >= n {
b.Logger.Printf(msg, args...)
}
}