/
reload.go
194 lines (171 loc) · 4.9 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
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
// Package reload offers lightweight automatic reloading of running processes.
//
// After initialisation with reload.Do() any changes to the binary will
// restart the process.
//
// Example:
//
// go func() {
// err := reload.Do(log.Printf)
// if err != nil {
// panic(err)
// }
// }()
//
// A list of additional directories to watch can be added:
//
// go func() {
// err := reload.Do(log.Printf, reload.Dir("tpl", reloadTpl)
// if err != nil {
// panic(err)
// }
// }()
//
// Note that this package won't prevent race conditions (e.g. when assigning to
// a global templates variable). You'll need to use sync.RWMutex yourself.
package serv
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
)
var binSelf string
type dir struct {
path string
cb func()
}
// Dir is an additional directory to watch for changes. Directories are watched
// non-recursively.
//
// The second argument is the callback that to run when the directory changes.
// Use reload.ReExec(servConf) to restart the process.
func Dir(path string, cb func()) dir { return dir{path, cb} } // nolint: golint
// Do reload the current process when its binary changes.
//
// The log function is used to display an informational startup message and
// errors. It works well with e.g. the standard log package or Logrus.
//
// The error return will only return initialisation errors. Once initialized it
// will use the log function to print errors, rather than return.
func Do(servConf *ServConfig, log func(string, ...interface{}), additional ...dir) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return errors.Wrap(err, "cannot setup watcher")
}
defer watcher.Close() // nolint: errcheck
binSelf, err = self()
if err != nil {
return err
}
// Watch the directory, because a recompile renames the existing
// file (rather than rewriting it), so we won't get events for that.
dirs := make([]string, len(additional)+1)
dirs[0] = filepath.Dir(binSelf)
for i := range additional {
path, err := filepath.Abs(additional[i].path)
if err != nil {
return errors.Wrapf(err, "cannot get absolute path to %q: %v",
additional[i].path, err)
}
s, err := os.Stat(path)
if err != nil {
return errors.Wrap(err, "os.Stat")
}
if !s.IsDir() {
return errors.Errorf("not a directory: %q; can only watch directories",
additional[i].path)
}
additional[i].path = path
dirs[i+1] = path
}
done := make(chan bool)
go func() {
for {
select {
case err := <-watcher.Errors:
// Standard logger doesn't have anything other than Print,
// Panic, and Fatal :-/ Printf() is probably best.
log("reload error: %v", err)
case event := <-watcher.Events:
// Ensure that we use the correct events, as they are not uniform across
// platforms. See https://github.com/fsnotify/fsnotify/issues/74
if servConf.conf != nil && strings.HasSuffix(event.Name, "/allow.list") {
continue
}
if servConf.conf.Production {
continue
}
log("INF Reloading, file changed detected: %s", event)
var trigger bool
switch runtime.GOOS {
case "darwin", "freebsd", "openbsd", "netbsd", "dragonfly":
trigger = event.Op&fsnotify.Create == fsnotify.Create
case "linux":
trigger = event.Op&fsnotify.Write == fsnotify.Write
default:
trigger = event.Op&fsnotify.Create == fsnotify.Create
log("reload: untested GOOS %q; this package may not work correctly", runtime.GOOS)
}
if !trigger {
continue
}
if event.Name == binSelf {
// Wait for writes to finish.
time.Sleep(100 * time.Millisecond)
ReExec(servConf)()
}
for _, a := range additional {
if strings.HasPrefix(event.Name, a.path) {
time.Sleep(100 * time.Millisecond)
a.cb()
}
}
}
}
}()
for _, d := range dirs {
if err := watcher.Add(d); err != nil {
return errors.Wrapf(err, "cannot add %q to watcher", d)
}
}
add := ""
if len(additional) > 0 {
reldirs := make([]string, len(dirs)-1)
for i := range dirs[1:] {
reldirs[i] = relpath(dirs[i+1])
}
add = fmt.Sprintf(" (additional dirs: %s)", strings.Join(reldirs, ", "))
}
log("restarting %q when it changes%s", relpath(binSelf), add)
<-done
return nil
}
// Exec replaces the current process with a new copy of itself.
func ReExec(servConf *ServConfig) func() {
return func() {
err := syscall.Exec(binSelf, append([]string{binSelf}, os.Args[1:]...), os.Environ())
if err != nil {
servConf.log.Fatalf("ERR cannot restart: %s", err)
}
}
}
// Get location to executable.
func self() (string, error) {
bin := os.Args[0]
if !filepath.IsAbs(bin) {
var err error
bin, err = os.Executable()
if err != nil {
return "", errors.Wrapf(err,
"cannot get path to binary %q (launch with absolute path): %v",
os.Args[0], err)
}
}
return bin, nil
}