/
cache.go
218 lines (175 loc) · 4.99 KB
/
cache.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
package zbxscr
import (
"encoding/json"
"io/ioutil"
"os"
"strings"
"time"
fslock "github.com/juju/fslock"
)
const (
cacheTTLDefault = 60
cacheFileName = "cache"
)
// Cache contains data cache
type Cache struct {
// This field indicates for ability to retrieve data from instance endpoint.
// If true - data successfully retrieved from from cache file (if it's actual) or exeporter without any errors.
// If false - some errors occurs while processing data retrieve (from cache or exporter)
InstanceAlive bool `json:"instance_alive"`
// This field contains data was obtained from cache (if it's actual) or exporter.
Data []byte `json:"data"`
}
// CacheGet retrieves data either from cache file if it's actual, or from exporter if cache rotted (in this case cache will be updated)
// If cache processing fails by any reasons, `InstanceAlive` field will be set to false.
// If `forceUpdate` argument is true, cache will be force updated.
func (s *Settings) CacheGet(name string, ctx interface{}, forceUpdate bool) Cache {
// Check exporter function defined
if s.Exporter == nil {
s.DebugPrint("Cache processing error: null exporter function\n")
return Cache{}
}
actual, c, err := s.cacheRead(s.cacheFilePath(name))
if err != nil {
s.DebugPrint("Cache read error: %s\n", err)
return Cache{}
}
// If cache exists, actual and forceUpdate is false
if forceUpdate == false && actual == true {
s.DebugPrint("Cache is actual\n")
return c
}
s.DebugPrint("Cache is outdated\n")
s.DebugPrint("Calling exporter\n")
if d, err := s.Exporter(s, ctx, c); err != nil {
// Cleanup cache struct
c = Cache{}
s.DebugPrint("Exporter error: %s\n", err)
} else {
// Fill cache struct with new data
c.InstanceAlive = true
c.Data = d
s.DebugPrint("Got data from exporter (InstanceAlive: %t)\n", c.InstanceAlive)
}
s.DebugPrint("Writing retrieved data to cache\n")
if err := s.cacheWrite(name, c); err != nil {
s.DebugPrint("Cache write error: %s\n", err)
return Cache{}
}
s.DebugPrint("Return cache data (InstanceAlive: %t)\n", c.InstanceAlive)
return c
}
// Create full cache file path string
func (s *Settings) cacheFilePath(name string) string {
return strings.Join([]string{s.CacheRoot, name, cacheFileName}, "/")
}
// Create directory path string where cache file will be located
func (s *Settings) cacheDirPath(name string) string {
return strings.Join([]string{s.CacheRoot, name}, "/")
}
// cacheCheckState checks cache file state (existence and actual)
func (s *Settings) cacheCheckState(file string) (bool, bool, error) {
var ttl float64
ttl = s.CacheTTL
if ttl == 0 {
ttl = cacheTTLDefault
}
// Get cache file stat to check last modified time
i, err := os.Stat(file)
if err != nil {
if os.IsNotExist(err) == false {
// If the problem is not related of the file
// existence (e.g. permissions error)
return false, false, err
}
// Cache file not exists
return false, false, nil
}
// Check cache file last modified time
if time.Now().Sub(i.ModTime()).Seconds() > ttl {
// Cache exist but rotted
return true, false, nil
}
// Cache exist and actual
return true, true, nil
}
// cacheRead reads data from cache file
func (s *Settings) cacheRead(file string) (bool, Cache, error) {
var c Cache
e, a, err := s.cacheCheckState(file)
if err != nil {
return false, Cache{}, err
}
if e == false {
return false, Cache{}, nil
}
// Tries to lock the lock until the timeout expires
lock := fslock.New(file)
if err := lock.LockWithTimeout(time.Second * 30); err != nil {
return false, Cache{}, err
}
defer lock.Unlock()
// Read cache data
d, err := ioutil.ReadFile(file)
if err != nil {
return false, Cache{}, err
}
// Unmarshal retrived data
if err := json.Unmarshal(d, &c); err != nil {
return false, Cache{}, err
}
// Success
return a, c, nil
}
// cacheWrite writes cache to file
func (s *Settings) cacheWrite(name string, c Cache) error {
// Marshal data
d, err := json.Marshal(c)
if err != nil {
return err
}
uid, gid, _, _, err := s.getGUID()
if err != nil {
return err
}
// Create cache dir
dir := s.cacheDirPath(name)
if err := cacheMkdirWithChown(dir, uid, gid); err != nil {
return err
}
// Write cache file
file := s.cacheFilePath(name)
// Tries to lock the lock until the timeout expires
lock := fslock.New(file)
if err := lock.LockWithTimeout(time.Second * 30); err != nil {
return err
}
defer lock.Unlock()
if err := ioutil.WriteFile(file, d, 0640); err != nil {
return err
}
if err := os.Chown(file, uid, gid); err != nil {
return err
}
// Success
return nil
}
// cacheMkdirWithChown create and chown for cache dir
func cacheMkdirWithChown(path string, uid, gid int) error {
p := ""
parts := strings.Split(path, "/")
for _, d := range parts {
if d != "" {
p = strings.Join([]string{p, d}, "/")
if _, err := os.Stat(p); os.IsNotExist(err) {
if err := os.Mkdir(p, 0750); err != nil {
return err
}
if err := os.Chown(p, uid, gid); err != nil {
return err
}
}
}
}
return nil
}