forked from thecubed/gogstash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sincedb.go
104 lines (87 loc) · 2.17 KB
/
sincedb.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
package inputfile
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"time"
log "github.com/Sirupsen/logrus"
"github.com/tsaikd/KDGoLib/futil"
)
type SinceDBInfo struct {
Offset int64 `json:"offset,omitempty"`
}
func (self *InputConfig) LoadSinceDBInfos() (err error) {
var (
raw []byte
)
log.Debug("LoadSinceDBInfos")
self.SinceDBInfos = map[string]*SinceDBInfo{}
if self.SinceDBPath == "" || self.SinceDBPath == "/dev/null" {
log.Warnf("No valid sincedb path")
return
}
if !futil.IsExist(self.SinceDBPath) {
log.Debugf("sincedb not found: %q", self.SinceDBPath)
return
}
if raw, err = ioutil.ReadFile(self.SinceDBPath); err != nil {
log.Errorf("Read sincedb failed: %q\n%s", self.SinceDBPath, err)
return
}
if err = json.Unmarshal(raw, &self.SinceDBInfos); err != nil {
log.Errorf("Unmarshal sincedb failed: %q\n%s", self.SinceDBPath, err)
return
}
return
}
func (self *InputConfig) SaveSinceDBInfos() (err error) {
var (
raw []byte
)
log.Debug("SaveSinceDBInfos")
self.SinceDBLastSaveTime = time.Now()
if self.SinceDBPath == "" || self.SinceDBPath == "/dev/null" {
log.Warnf("No valid sincedb path")
return
}
if raw, err = json.Marshal(self.SinceDBInfos); err != nil {
log.Errorf("Marshal sincedb failed: %s", err)
return
}
self.sinceDBLastInfosRaw = raw
if err = ioutil.WriteFile(self.SinceDBPath, raw, 0664); err != nil {
log.Errorf("Write sincedb failed: %q\n%s", self.SinceDBPath, err)
return
}
return
}
func (t *InputConfig) CheckSaveSinceDBInfos() (err error) {
var (
raw []byte
)
if time.Since(t.SinceDBLastSaveTime) > time.Duration(t.SinceDBWriteInterval)*time.Second {
if raw, err = json.Marshal(t.SinceDBInfos); err != nil {
log.Errorf("Marshal sincedb failed: %s", err)
return
}
if bytes.Compare(raw, t.sinceDBLastInfosRaw) != 0 {
err = t.SaveSinceDBInfos()
}
}
return
}
func (t *InputConfig) CheckSaveSinceDBInfosLoop(ctx context.Context) (err error) {
ticker := time.NewTicker(time.Duration(t.SinceDBWriteInterval) * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
if err = t.CheckSaveSinceDBInfos(); err != nil {
return
}
}
}
}