/
file_watcher.go
112 lines (97 loc) · 2.29 KB
/
file_watcher.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
package ledgerbackend
import (
"bytes"
"crypto/sha1"
"io"
"os"
"sync"
"time"
"github.com/sanjayhashcash/go/support/errors"
"github.com/sanjayhashcash/go/support/log"
)
type hash []byte
func (h hash) Equals(other hash) bool {
return bytes.Equal(h, other)
}
type fileWatcher struct {
pathToFile string
duration time.Duration
onChange func()
exit <-chan struct{}
log *log.Entry
hashFile func(string) (hash, error)
lastHash hash
}
func hashFile(filename string) (hash, error) {
f, err := os.Open(filename)
if err != nil {
return hash{}, errors.Wrapf(err, "unable to open %v", f)
}
defer f.Close()
h := sha1.New()
if _, err := io.Copy(h, f); err != nil {
return hash{}, errors.Wrapf(err, "unable to copy %v into buffer", f)
}
return h.Sum(nil), nil
}
func newFileWatcher(runner *hcnetCoreRunner) (*fileWatcher, error) {
return newFileWatcherWithOptions(runner, hashFile, 10*time.Second)
}
func newFileWatcherWithOptions(
runner *hcnetCoreRunner,
hashFile func(string) (hash, error),
tickerDuration time.Duration,
) (*fileWatcher, error) {
hashResult, err := hashFile(runner.executablePath)
if err != nil {
return nil, errors.Wrap(err, "could not hash captive core binary")
}
once := &sync.Once{}
return &fileWatcher{
pathToFile: runner.executablePath,
duration: tickerDuration,
onChange: func() {
once.Do(func() {
runner.log.Warnf("detected new version of captive core binary %s , aborting session.", runner.executablePath)
if err := runner.close(); err != nil {
runner.log.Warnf("could not close captive core %v", err)
}
})
},
exit: runner.ctx.Done(),
log: runner.log,
hashFile: hashFile,
lastHash: hashResult,
}, nil
}
func (f *fileWatcher) loop() {
ticker := time.NewTicker(f.duration)
for {
select {
case <-f.exit:
ticker.Stop()
return
case <-ticker.C:
if f.fileChanged() {
f.onChange()
}
}
}
}
func (f *fileWatcher) fileChanged() bool {
hashResult, err := f.hashFile(f.pathToFile)
if err != nil {
f.log.Warnf("could not hash contents of %s: %v", f.pathToFile, err)
return false
}
if !f.lastHash.Equals(hashResult) {
f.log.Infof(
"detected update to %s. previous file hash was %v current hash is %v",
f.pathToFile,
f.lastHash,
hashResult,
)
return true
}
return false
}