-
Notifications
You must be signed in to change notification settings - Fork 0
/
fate.go
126 lines (100 loc) · 2.36 KB
/
fate.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
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v2"
)
type Fate struct {
client VaultClientInterface
}
type Watcher interface {
Close() error
Add(name string) error
Events() chan fsnotify.Event
Errors() chan error
}
type FsWatcher struct {
watcher *fsnotify.Watcher
}
func (w *FsWatcher) Close() error { return w.watcher.Close() }
func (w *FsWatcher) Add(name string) error { return w.watcher.Add(name) }
func (w *FsWatcher) Events() chan fsnotify.Event { return w.watcher.Events }
func (w *FsWatcher) Errors() chan error { return w.watcher.Errors }
func (v *Fate) read(file string) {
v.delayRead(file, 0)
}
func (v *Fate) delayRead(file string, d time.Duration) {
if !strings.HasSuffix(file, ".yml") {
log.Printf("Not a yaml file. Ignored %s", file)
return
}
if d != 0 {
time.Sleep(d)
}
path := filepath.Base(file)
dest := make(map[string]interface{})
str, _ := readFile(file)
if err := yaml.Unmarshal(str, &dest); err != nil {
log.Printf("invalid YAML %s, %v", file, err)
return
}
data := Flatten(dest)
path = strings.TrimSuffix(path, filepath.Ext(path))
log.Printf("Writing path %s", path)
if e := v.client.Write("secret/"+path, data); e != nil {
log.Fatal(e)
}
}
func scanDir(dir string) {
log.Print("Scanning ...")
files, err := readDir(dir)
if err != nil {
log.Fatal(err)
}
for _, f := range files {
log.Println(f.Name())
fate.read(fmt.Sprintf("%s/%s", dir, f.Name()))
}
log.Print("Scan completed.")
}
func watchDir(dir string, watcher Watcher) {
defer watcher.Close()
done := make(chan os.Signal)
signalNotify(done, os.Interrupt, syscall.SIGTERM)
go func() {
for {
select {
case event, ok := <-watcher.Events():
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("Modified file:", event.Name)
go fate.delayRead(event.Name, delayReadDuration)
}
if event.Op&fsnotify.Create == fsnotify.Create {
log.Println("Created file:", event.Name)
go fate.delayRead(event.Name, delayReadDuration)
}
case err, ok := <-watcher.Errors():
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err := watcher.Add(dir)
if err != nil {
log.Fatal(err)
}
log.Printf("Watching dir: %s", dir)
<-done
log.Println("Exiting")
}