-
Notifications
You must be signed in to change notification settings - Fork 0
/
reload.go
72 lines (69 loc) · 1.83 KB
/
reload.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
package reload
import (
"context"
"github.com/fsnotify/fsnotify"
"github.com/lahabana/api-play/pkg/api"
"gopkg.in/yaml.v3"
"log/slog"
"os"
"path/filepath"
)
func reload(ctx context.Context, log *slog.Logger, configFile string, reloader api.Reloader) error {
log.InfoContext(ctx, "reloading file", "conf", configFile)
b, err := os.ReadFile(configFile)
if err != nil {
return err
}
apis := api.ParamsAPI{}
if err := yaml.Unmarshal(b, &apis); err != nil {
return err
}
if err := reloader.Reload(ctx, apis); err != nil {
return err
}
return nil
}
func BackgroundConfigReload(ctx context.Context, log *slog.Logger, configFile string, reloader api.Reloader) {
if err := reload(ctx, log, configFile, reloader); err != nil {
log.ErrorContext(ctx, "config loading failed, server will start with empty config", "error", err)
}
w, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
dirPath := filepath.Dir(configFile)
if err := w.Add(dirPath); err != nil {
panic(err)
}
go func() {
log.InfoContext(ctx, "listening for config change events", "path", dirPath)
defer func() {
_ = w.Close()
log.InfoContext(ctx, "stopping watcher")
}()
for {
select {
case e, ok := <-w.Events:
if !ok {
return
}
// For k8s we react to reload of the config map which is similar to a symlink change
if e.Name == filepath.Base(configFile) || (filepath.Base(e.Name) == "..data" && e.Has(fsnotify.Create)) {
err := reload(ctx, log, configFile, reloader)
if err != nil {
log.ErrorContext(ctx, "reloading config failed", "error", err)
} else {
log.InfoContext(ctx, "config successfully reloaded")
}
}
case err, ok := <-w.Errors:
if !ok {
return
}
log.ErrorContext(ctx, "watcher received error failed", "error", err)
case <-ctx.Done():
return
}
}
}()
}