-
Notifications
You must be signed in to change notification settings - Fork 241
/
updater.go
195 lines (179 loc) · 5.49 KB
/
updater.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
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
// Package kubernetes provides an a K8S ConfigMap watcher for the jobs systems.
package configmap
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"path"
"strings"
"fortio.org/fortio/dflag"
"fortio.org/fortio/log"
"github.com/fsnotify/fsnotify"
)
const (
k8sInternalsPrefix = ".."
k8sDataSymlink = "..data"
)
var (
errFlagNotDynamic = fmt.Errorf("flag is not dynamic")
errFlagNotFound = fmt.Errorf("flag not found")
)
// Updater is the encapsulation of the directory watcher.
// TODO: hide details, just return opaque interface.
type Updater struct {
started bool
dirPath string
parentPath string
watcher *fsnotify.Watcher
flagSet *flag.FlagSet
done chan bool
}
// Setup is a combination/shortcut for New+Initialize+Start.
func Setup(flagSet *flag.FlagSet, dirPath string) (*Updater, error) {
u, err := New(flagSet, dirPath)
if err != nil {
return nil, err
}
err = u.Initialize()
if err != nil {
return nil, err
}
if err := u.Start(); err != nil {
return nil, err
}
log.Infof("Configmap flag value watching initialized on %v", dirPath)
return u, nil
}
// New creates an Updater for the directory.
func New(flagSet *flag.FlagSet, dirPath string) (*Updater, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, fmt.Errorf("dflag: error initializing fsnotify watcher")
}
return &Updater{
flagSet: flagSet,
dirPath: path.Clean(dirPath),
parentPath: path.Clean(path.Join(dirPath, "..")), // add parent in case the dirPath is a symlink itself
watcher: watcher,
}, nil
}
// Initialize reads the values from the directory for the first time.
func (u *Updater) Initialize() error {
if u.started {
return fmt.Errorf("dflag: already initialized updater")
}
return u.readAll( /* allowNonDynamic */ false)
}
// Start kicks off the go routine that watches the directory for updates of values.
func (u *Updater) Start() error {
if u.started {
return fmt.Errorf("dflag: updater already started")
}
if err := u.watcher.Add(u.parentPath); err != nil {
return fmt.Errorf("unable to add parent dir %v to watch: %w", u.parentPath, err)
}
if err := u.watcher.Add(u.dirPath); err != nil { // add the dir itself.
return fmt.Errorf("unable to add config dir %v to watch: %w", u.dirPath, err)
}
log.Infof("Now watching %v and %v", u.parentPath, u.dirPath)
u.started = true
u.done = make(chan bool)
go u.watchForUpdates()
return nil
}
// Stop stops the auto-updating go-routine.
func (u *Updater) Stop() error {
if !u.started {
return fmt.Errorf("dflag: not updating")
}
u.done <- true
_ = u.watcher.Remove(u.dirPath)
_ = u.watcher.Remove(u.parentPath)
return nil
}
func (u *Updater) readAll(dynamicOnly bool) error {
files, err := ioutil.ReadDir(u.dirPath)
if err != nil {
return fmt.Errorf("dflag: updater initialization: %w", err)
}
errorStrings := []string{}
for _, f := range files {
if strings.HasPrefix(path.Base(f.Name()), ".") {
// skip random ConfigMap internals and dot files
continue
}
fullPath := path.Join(u.dirPath, f.Name())
if err := u.readFlagFile(fullPath, dynamicOnly); err != nil {
if errors.Is(err, errFlagNotDynamic) && dynamicOnly {
// ignore
} else {
errorStrings = append(errorStrings, fmt.Sprintf("flag %v: %v", f.Name(), err.Error()))
}
}
}
if len(errorStrings) > 0 {
return fmt.Errorf("encountered %d errors while parsing flags from directory \n %v",
len(errorStrings), strings.Join(errorStrings, "\n"))
}
return nil
}
func (u *Updater) readFlagFile(fullPath string, dynamicOnly bool) error {
flagName := path.Base(fullPath)
flag := u.flagSet.Lookup(flagName)
if flag == nil {
return errFlagNotFound
}
if dynamicOnly && !dflag.IsFlagDynamic(flag) {
return errFlagNotDynamic
}
content, err := ioutil.ReadFile(fullPath)
if err != nil {
return err
}
str := string(content)
log.Infof("updating %v to %q", flagName, str)
// do not call flag.Value.Set, instead go through flagSet.Set to change "changed" state.
return u.flagSet.Set(flagName, str)
}
func (u *Updater) watchForUpdates() {
log.Infof("Starting watching")
for {
select {
case event := <-u.watcher.Events:
log.LogVf("ConfigMap got fsnotify %v ", event)
if event.Name == u.dirPath || event.Name == path.Join(u.dirPath, k8sDataSymlink) { // nolint: nestif
// case of the whole directory being re-symlinked
switch event.Op {
case fsnotify.Create:
if err := u.watcher.Add(u.dirPath); err != nil { // add the dir itself.
log.Errf("unable to add config dir %v to watch: %v", u.dirPath, err)
}
log.Infof("dflag: Re-reading flags after ConfigMap update.")
if err := u.readAll( /* dynamicOnly */ true); err != nil {
log.Errf("dflag: directory reload yielded errors: %v", err.Error())
}
case fsnotify.Remove, fsnotify.Chmod, fsnotify.Rename, fsnotify.Write:
}
} else if strings.HasPrefix(event.Name, u.dirPath) && !isK8sInternalDirectory(event.Name) {
log.LogVf("ConfigMap got prefix %v", event)
switch event.Op {
case fsnotify.Create, fsnotify.Write, fsnotify.Rename, fsnotify.Remove:
flagName := path.Base(event.Name)
if err := u.readFlagFile(event.Name, true); err != nil {
log.Errf("dflag: failed setting flag %s: %v", flagName, err.Error())
}
case fsnotify.Chmod:
}
}
case <-u.done:
return
}
}
}
func isK8sInternalDirectory(filePath string) bool {
basePath := path.Base(filePath)
return strings.HasPrefix(basePath, k8sInternalsPrefix)
}