-
Notifications
You must be signed in to change notification settings - Fork 9
/
cache.go
95 lines (84 loc) · 1.93 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
package main
import (
"encoding/gob"
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/gofrs/flock"
)
func lock() *flock.Flock {
return flock.New(filepath.Join(os.TempDir(), "regolancer.lock"))
}
func (r *regolancer) loadNodeCache(filename string, exp int, doLock bool) error {
if filename == "" {
return nil
}
defer func() {
err := recover()
if err == nil {
return
}
log.Printf("Loading failed, cache format might be outdated: %s", err)
r.nodeCache = map[string]cachedNodeInfo{}
}()
if doLock {
log.Printf("Loading node cache from %s", filename)
l := lock()
err := l.RLock()
defer l.Unlock()
if err != nil {
return fmt.Errorf("error taking shared lock on file %s: %s", filename, err)
}
}
f, err := os.Open(filename)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("error opening node cache file: %s", err)
}
return nil
}
defer f.Close()
err = gob.NewDecoder(f).Decode(&r.nodeCache)
if err != nil {
return err
}
for k, v := range r.nodeCache {
since := time.Since(v.Timestamp)
if since > time.Minute*time.Duration(exp) {
delete(r.nodeCache, k)
}
}
return nil
}
func (r *regolancer) saveNodeCache(filename string, exp int) error {
if filename == "" {
return nil
}
log.Printf("Saving node cache to %s", filename)
l := lock()
err := l.Lock()
defer l.Unlock()
if err != nil {
return fmt.Errorf("error taking exclusive lock on file %s: %s", filename, err)
}
old := regolancer{nodeCache: map[string]cachedNodeInfo{}}
err = old.loadNodeCache(filename, exp, false)
if err != nil {
logErrorF("Error merging cache, saving anew: %s", err)
}
for k, v := range old.nodeCache {
if n, ok := r.nodeCache[k]; !ok ||
n.Timestamp.Before(v.Timestamp) {
r.nodeCache[k] = v
}
}
f, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating node cache file: %s", err)
}
defer f.Close()
err = gob.NewEncoder(f).Encode(r.nodeCache)
return err
}