-
Notifications
You must be signed in to change notification settings - Fork 22
/
watcher.go
217 lines (184 loc) · 5.39 KB
/
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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.VEGA file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package config
import (
"context"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/paths"
"github.com/fsnotify/fsnotify"
)
const (
namedLogger = "cfgwatcher"
)
// Watcher is looking for updates in the configurations files.
type Watcher struct {
log *logging.Logger
cfg Config
configFilePath string
// to be used as an atomic
hasChanged atomic.Bool
cfgUpdateListeners []func(Config)
cfgHandlers []func(*Config) error
// listeners with IDs
cfgUpdateListenersWithID map[int]func(Config)
currentID int
mu sync.Mutex
}
type Option func(w *Watcher)
func Use(use func(*Config) error) Option {
fn := func(w *Watcher) {
w.Use(use)
}
return fn
}
// NewWatcher instantiate a new watcher from the vega config files.
func NewWatcher(ctx context.Context, log *logging.Logger, vegaPaths paths.Paths, opts ...Option) (*Watcher, error) {
watcherLog := log.Named(namedLogger)
// set this logger to debug level as we want to be notified for any configuration changes at any time
watcherLog.SetLevel(logging.DebugLevel)
configFilePath, err := vegaPaths.CreateConfigPathFor(paths.NodeDefaultConfigFile)
if err != nil {
return nil, fmt.Errorf("couldn't get path for %s: %w", paths.NodeDefaultConfigFile, err)
}
w := &Watcher{
log: watcherLog,
cfg: NewDefaultConfig(),
configFilePath: configFilePath,
cfgUpdateListeners: []func(Config){},
cfgUpdateListenersWithID: map[int]func(Config){},
}
for _, opt := range opts {
opt(w)
}
err = w.load()
if err != nil {
return nil, err
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
err = watcher.Add(w.configFilePath)
if err != nil {
return nil, err
}
go w.watch(ctx, watcher)
return w, nil
}
func (w *Watcher) OnTimeUpdate(_ context.Context, _ time.Time) {
if !w.hasChanged.Load() {
// no changes we can return straight away
return
}
// get the config and updates listeners
cfg := w.Get()
for _, f := range w.cfgUpdateListeners {
f(cfg)
}
ids := []int{}
for k := range w.cfgUpdateListenersWithID {
ids = append(ids, k)
}
sort.Ints(ids)
for id := range ids {
w.cfgUpdateListenersWithID[id](cfg)
}
// reset the atomic
w.hasChanged.Store(false)
}
// Get return the last update of the configuration.
func (w *Watcher) Get() Config {
w.mu.Lock()
conf := w.cfg
w.mu.Unlock()
return conf
}
// OnConfigUpdate register a function to be called when the configuration is getting updated.
func (w *Watcher) OnConfigUpdate(fns ...func(Config)) {
w.mu.Lock()
w.cfgUpdateListeners = append(w.cfgUpdateListeners, fns...)
w.mu.Unlock()
}
// OnConfigUpdate register a function to be called when the configuration is getting updated.
func (w *Watcher) OnConfigUpdateWithID(fns ...func(Config)) []int {
w.mu.Lock()
// w.cfgUpdateListeners = append(w.cfgUpdateListeners, fns...)
ids := []int{}
for _, f := range fns {
id := w.currentID
ids = append(ids, id)
w.cfgUpdateListenersWithID[id] = f
w.currentID++
}
w.mu.Unlock()
return ids
}
func (w *Watcher) Unregister(ids []int) {
for _, id := range ids {
delete(w.cfgUpdateListenersWithID, id)
}
}
// Use registers a function that modify the config when the configuration is updated.
func (w *Watcher) Use(fns ...func(*Config) error) {
w.mu.Lock()
w.cfgHandlers = append(w.cfgHandlers, fns...)
w.mu.Unlock()
}
func (w *Watcher) load() error {
w.mu.Lock()
defer w.mu.Unlock()
if err := paths.ReadStructuredFile(w.configFilePath, &w.cfg); err != nil {
return fmt.Errorf("couldn't read configuration file at %s: %w", w.configFilePath, err)
}
for _, f := range w.cfgHandlers {
if err := f(&w.cfg); err != nil {
return err
}
}
return nil
}
func (w *Watcher) watch(ctx context.Context, watcher *fsnotify.Watcher) {
defer watcher.Close()
for {
select {
case event := <-watcher.Events:
if event.Has(fsnotify.Write) || event.Has(fsnotify.Rename) {
if event.Has(fsnotify.Rename) {
// add a small sleep here in order to handle vi
// vi do not send a write event / edit the file in place,
// it always create a temporary file, then delete the original one,
// and then rename the temp file with the name of the original file.
// if we try to update the conf as soon as we get the event, the file is not
// always created and we get a no such file or directory error
time.Sleep(50 * time.Millisecond)
}
w.log.Info("configuration updated", logging.String("event", event.Name))
err := w.load()
if err != nil {
w.log.Error("unable to load configuration", logging.Error(err))
continue
}
w.hasChanged.Store(true)
}
case err := <-watcher.Errors:
w.log.Error("config watcher received error event", logging.Error(err))
case <-ctx.Done():
w.log.Error("config watcher ctx done")
return
}
}
}