forked from altipla-consulting/reloader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_run.go
More file actions
341 lines (286 loc) · 7.88 KB
/
cmd_run.go
File metadata and controls
341 lines (286 loc) · 7.88 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package main
import (
"context"
"go/build"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/altipla-consulting/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
"libs.altipla.consulting/watch"
)
var defaultIgnoreFolders = []string{
"node_modules",
".git",
"tmp",
}
type empty struct{}
var cmdRun = &cobra.Command{
Use: "run",
Example: "reloader run -r ./backend",
Short: "Run a command everytime the package changes.",
Args: cobra.MinimumNArgs(1),
}
func init() {
var flagWatch, flagIgnore []string
var flagRestartExts []string
var flagRestart bool
cmdRun.PersistentFlags().StringSliceVarP(&flagWatch, "watch", "w", nil, "Folders to watch recursively for changes.")
cmdRun.PersistentFlags().StringSliceVarP(&flagIgnore, "ignore", "g", nil, "Folders to ignore.")
cmdRun.PersistentFlags().BoolVarP(&flagRestart, "restart", "r", false, "Automatic restart in case of failure.")
cmdRun.PersistentFlags().StringSliceVarP(&flagRestartExts, "restart-exts", "e", nil, "List of extensions that cause the app to restart.")
cmdRun.RunE = func(cmd *cobra.Command, args []string) error {
grp, ctx := errgroup.WithContext(cmd.Context())
changes := make(chan string)
for _, folder := range flagWatch {
grp.Go(watchFolder(ctx, changes, flagIgnore, folder))
}
grp.Go(watchFolder(ctx, changes, flagIgnore, args[0]))
rebuild := make(chan empty)
restart := make(chan empty, 1)
grp.Go(receiveWatchChanges(ctx, changes, flagRestartExts, rebuild, restart))
grp.Go(appManager(ctx, args, flagRestart, rebuild, restart))
return errors.Trace(grp.Wait())
}
}
func watchFolder(ctx context.Context, changes chan string, ignore []string, folder string) func() error {
return func() error {
var paths []string
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
return nil
}
return errors.Trace(err)
}
if !info.IsDir() {
return nil
}
// Ignore default and custom folders.
if slices.Contains(defaultIgnoreFolders, filepath.Base(path)) {
return filepath.SkipDir
}
for _, ig := range ignore {
if strings.HasPrefix(path, ig) {
return filepath.SkipDir
}
}
paths = append(paths, path)
return nil
}
if err := filepath.Walk(folder, walkFn); err != nil {
return errors.Trace(err)
}
log.WithField("path", folder).Debug("Watching changes")
return errors.Trace(watch.Files(ctx, changes, paths...))
}
}
func receiveWatchChanges(ctx context.Context, changes chan string, restartExts []string, rebuild, restart chan empty) func() error {
return func() error {
// Batch changes with a short timer to avoid concurrency issues with atomic saving.
// Also depending on the changed file we need a build or only to restart the app.
var buildPending bool
var waitNextChange *time.Timer
for {
var ch <-chan time.Time
if waitNextChange != nil {
ch = waitNextChange.C
}
select {
case <-ctx.Done():
return nil
case change := <-changes:
if filepath.Ext(change) == ".go" {
log.WithField("path", change).Debug("File change detected, rebuild")
buildPending = true
} else if slices.Contains(restartExts, filepath.Ext(change)) {
log.WithField("path", change).Debug("File change detected, restart")
} else {
log.WithField("path", change).Debug("File change detected, but no action performed")
continue
}
if waitNextChange == nil {
waitNextChange = time.NewTimer(50 * time.Millisecond)
} else {
if !waitNextChange.Stop() {
<-waitNextChange.C
}
waitNextChange.Reset(50 * time.Millisecond)
}
case <-ch:
waitNextChange = nil
if buildPending {
select {
case rebuild <- empty{}:
default:
}
buildPending = false
} else {
select {
case restart <- empty{}:
default:
}
}
}
}
}
}
var errBuildFailed = errors.New("reloader: build failed")
func buildApp(ctx context.Context, app string, restart chan empty) error {
log.Info(">>> build...")
cmd := exec.CommandContext(ctx, "go", "install", app)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
log.Error(">>> build command failed!")
return errors.Trace(errBuildFailed)
}
return errors.Trace(err)
}
select {
case restart <- empty{}:
default:
}
return nil
}
func appManager(ctx context.Context, args []string, shouldRestart bool, rebuild, restart chan empty) func() error {
return func() error {
// Build the application for the first time when starting up.
if err := buildApp(ctx, args[0], restart); err != nil && !errors.Is(err, errBuildFailed) {
return errors.Trace(err)
}
var cmd *exec.Cmd
runerr := make(chan error, 1)
secs := 1 * time.Second
for {
select {
case <-ctx.Done():
return nil
case <-rebuild:
if err := stopProcess(ctx, cmd, runerr); err != nil {
return errors.Trace(err)
}
cmd = nil
if err := buildApp(ctx, args[0], restart); err != nil {
if errors.Is(err, errBuildFailed) {
continue
}
return errors.Trace(err)
}
// Reset the restart timer after a successful build.
secs = 1 * time.Second
select {
case restart <- empty{}:
default:
}
case <-restart:
if err := stopProcess(ctx, cmd, runerr); err != nil {
return errors.Trace(err)
}
log.Info(">>> run...")
var err error
cmd, err = startProcess(ctx, runerr, args)
if err != nil {
return errors.Trace(err)
}
case appErr := <-runerr:
cmd = nil
if shouldRestart {
if appErr != nil {
log.WithField("error", appErr.Error()).Errorf(">>> command failed, restarting in %s", secs)
} else {
log.Errorf(">>> command exited, restarting in %s", secs)
}
// Wait a little bit before restarting the failing process.
select {
case <-ctx.Done():
return nil
case <-time.After(secs):
}
secs = secs * 2
if secs > 8*time.Second {
secs = 8 * time.Second
}
// Run application again.
restart <- empty{}
} else {
if appErr != nil {
log.WithField("error", appErr.Error()).Errorf(">>> command failed")
}
}
}
}
}
}
func startProcess(ctx context.Context, runerr chan error, args []string) (*exec.Cmd, error) {
name := filepath.Base(args[0])
if args[0] == "." {
wd, err := os.Getwd()
if err != nil {
return nil, errors.Trace(err)
}
name = filepath.Base(wd)
}
cmd := exec.CommandContext(ctx, filepath.Join(build.Default.GOPATH, "bin", name), args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, errors.Trace(err)
}
go func() {
runerr <- errors.Trace(cmd.Wait())
}()
return cmd, nil
}
func stopProcess(ctx context.Context, cmd *exec.Cmd, runerr chan error) error {
if cmd == nil {
return nil
}
logger := log.WithField("pid", cmd.Process.Pid)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
grp, ctx := errgroup.WithContext(ctx)
grp.Go(func() error {
logger.Trace("Send interrupt signal")
return errors.Trace(cmd.Process.Signal(os.Interrupt))
})
grp.Go(func() error {
appErr := <-runerr
logger.WithField("error", appErr).Trace("Process close detected")
cancel()
return nil
})
grp.Go(func() error {
select {
case <-ctx.Done():
case <-time.After(3 * time.Second):
log.Info(">>> close process...")
}
return nil
})
grp.Go(func() error {
select {
case <-ctx.Done():
logger.Trace("Process closed before the timeout")
return nil
case <-time.After(15 * time.Second):
logger.Warning("Kill process after timeout")
return errors.Trace(cmd.Process.Kill())
}
})
if err := grp.Wait(); err != nil {
if errors.Is(err, os.ErrProcessDone) {
return nil
}
return errors.Trace(err)
}
return nil
}