-
Notifications
You must be signed in to change notification settings - Fork 3
/
watcher.go
78 lines (62 loc) · 1.42 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
package config
import (
"context"
"time"
stime "github.com/alexfalkowski/go-service/time"
"github.com/fsnotify/fsnotify"
"go.uber.org/fx"
"go.uber.org/zap"
)
// RandomWaitTime that will be used to shutdown the system.
var RandomWaitTime = stime.RandomWaitTime()
// WatchParams for config.
type WatchParams struct {
fx.In
Lifecycle fx.Lifecycle
Shutdowner fx.Shutdowner
Logger *zap.Logger
}
// Watch the configuration. If it changes terminate the application.
func Watch(params WatchParams) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
params.Lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
go watch(params.Shutdowner, watcher, params.Logger)
return watcher.Add(File())
},
OnStop: func(ctx context.Context) error {
return watcher.Close()
},
})
return nil
}
func watch(sh fx.Shutdowner, w *fsnotify.Watcher, logger *zap.Logger) {
for {
select {
case e, ok := <-w.Events:
if !ok {
return
}
if e.Op&fsnotify.Write == fsnotify.Write {
shutdown(sh, logger)
return
}
case err, ok := <-w.Errors:
if !ok {
return
}
if err != nil {
logger.Error("watching configuration", zap.Error(err))
return
}
}
}
}
func shutdown(sh fx.Shutdowner, logger *zap.Logger) error {
logger.Info("configuration has been modified", zap.Duration("duration", RandomWaitTime))
time.Sleep(RandomWaitTime)
return sh.Shutdown()
}