-
Notifications
You must be signed in to change notification settings - Fork 11
/
record_pump.go
80 lines (71 loc) · 1.63 KB
/
record_pump.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
package ik
import (
"time"
)
type RecordPump struct {
port Port
ch chan FluentRecord
control chan bool
buffer map[string]*FluentRecordSet
heartbeat *time.Ticker
}
func (pump *RecordPump) Port() Port {
return pump.port
}
func (pump *RecordPump) EmitOne(record FluentRecord) {
pump.ch <- record
}
func (pump *RecordPump) flush() error {
recordSets := make([]FluentRecordSet, 0, len(pump.buffer))
for _, recordSet := range pump.buffer {
recordSets = append(recordSets, *recordSet)
}
pump.buffer = make(map[string]*FluentRecordSet)
return pump.port.Emit(recordSets)
}
func (pump *RecordPump) Run() error {
for {
select {
case record := <-pump.ch:
buffer := pump.buffer
recordSet, ok := buffer[record.Tag]
if !ok {
recordSet = &FluentRecordSet{
Tag: record.Tag,
Records: make([]TinyFluentRecord, 0, 16),
}
buffer[record.Tag] = recordSet
}
recordSet.Records = append(recordSet.Records, TinyFluentRecord{
Timestamp: record.Timestamp,
Data: record.Data,
})
break
case <-pump.heartbeat.C:
err := pump.flush()
if err != nil {
return err
}
break
case needsToBeStopped := <-pump.control:
if needsToBeStopped {
pump.heartbeat.Stop()
}
return pump.flush()
}
}
return Continue
}
func (pump *RecordPump) Shutdown() error {
pump.control <- true
return nil
}
func NewRecordPump(port Port, backlog int) *RecordPump {
return &RecordPump{
port: port,
ch: make(chan FluentRecord, backlog),
control: make(chan bool, 1),
buffer: make(map[string]*FluentRecordSet),
heartbeat: time.NewTicker(time.Duration(1000000000)),
}
}