forked from hashicorp/consul-template
/
file.go
98 lines (79 loc) · 1.69 KB
/
file.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
package dependency
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"sync"
"time"
)
type File struct {
mutex sync.RWMutex
rawKey string
lastStat os.FileInfo
}
func (d *File) Fetch(clients *ClientSet, opts *QueryOptions) (interface{}, *ResponseMetadata, error) {
var err error = nil
var data []byte
log.Printf("[DEBUG] (%s) querying file", d.Display())
newStat, err := d.watch()
if err != nil {
return "", nil, fmt.Errorf("file: error watching: %s", err)
}
d.mutex.Lock()
defer d.mutex.Unlock()
d.lastStat = newStat
ts := time.Now().Unix()
rm := &ResponseMetadata{
LastContact: time.Duration(ts),
LastIndex: uint64(ts),
}
if data, err = ioutil.ReadFile(d.rawKey); err == nil {
return string(data), rm, nil
}
return nil, nil, fmt.Errorf("file: error reading: %s", err)
}
func (d *File) HashCode() string {
return fmt.Sprintf("StoreKeyPrefix|%s", d.rawKey)
}
func (d *File) Display() string {
return fmt.Sprintf(`"file(%s)"`, d.rawKey)
}
// watch watchers the file for changes
func (d *File) watch() (os.FileInfo, error) {
for {
stat, err := os.Stat(d.rawKey)
if err != nil {
return nil, err
}
changed := func(d *File, stat os.FileInfo) bool {
d.mutex.RLock()
defer d.mutex.RUnlock()
if d.lastStat == nil {
return true
}
if d.lastStat.Size() != stat.Size() {
return true
}
if d.lastStat.ModTime() != stat.ModTime() {
return true
}
return false
}(d, stat)
if changed {
return stat, nil
} else {
time.Sleep(3 * time.Second)
}
}
}
func ParseFile(s string) (*File, error) {
if len(s) == 0 {
return nil, errors.New("cannot specify empty file dependency")
}
kd := &File{
rawKey: s,
}
return kd, nil
}