forked from symfony-cli/symfony-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
302 lines (256 loc) · 8.4 KB
/
runner.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
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
/*
* Copyright (c) 2021-present Fabien Potencier <fabien@symfony.com>
*
* This file is part of Symfony CLI project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package local
import (
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/symfony-cli/console"
"github.com/symfony-cli/symfony-cli/inotify"
"github.com/symfony-cli/symfony-cli/local/pid"
"github.com/symfony-cli/symfony-cli/reexec"
"github.com/symfony-cli/symfony-cli/util"
"github.com/symfony-cli/terminal"
)
type runnerMode int
const (
RunnerModeOnce runnerMode = iota // run once
RunnerModeLoopAttached // run in the foreground and restart automatically in case of an error except if the first run failed
RunnerModeLoopDetached // run as a daemon (run in the background, restarted automatically in case of an error except if the first run failed)
)
const RunnerReliefDuration = 2 * time.Second
type RunnerWentToBackground struct{}
func (RunnerWentToBackground) Error() string { return "" }
type Runner struct {
binary string
mode runnerMode
pidFile *pid.PidFile
BuildCmdHook func(*exec.Cmd) error
SuccessHook func(*Runner, *exec.Cmd)
AlwaysRestartOnExit bool
}
func NewRunner(pidFile *pid.PidFile, mode runnerMode) (*Runner, error) {
var err error
r := &Runner{
mode: mode,
pidFile: pidFile,
}
r.binary, err = exec.LookPath(pidFile.Binary())
if err != nil {
r.pidFile.Remove()
return nil, errors.WithStack(err)
}
return r, nil
}
func (r *Runner) Run() error {
if r.mode == RunnerModeLoopDetached {
if !reexec.IsChild() {
varDir := filepath.Join(util.GetHomeDir(), "var")
if err := os.MkdirAll(varDir, 0755); err != nil {
return errors.Wrap(err, "Could not create status file")
}
err := reexec.Background(varDir)
if err == nil {
return RunnerWentToBackground{}
}
if _, isExitCoder := err.(console.ExitCoder); isExitCoder {
return err
}
terminal.Printfln("Impossible to go to the background: %s", err)
terminal.Println("Continue in foreground")
r.mode = RunnerModeOnce
} else {
if err := reexec.NotifyForeground("boot"); err != nil {
return console.Exit(fmt.Sprintf("Unable to go to the background: %s, aborting", err), 1)
}
}
}
// We want those NOT to be buffered on purpose to be able to skip events when restarting
cmdExitChan := make(chan error) // receives command exit status, allow to cmd.Wait() in non-blocking way
restartChan := make(chan bool) // receives requests to restart the command
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Kill, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM)
defer signal.Stop(sigChan)
if len(r.pidFile.Watched) > 0 {
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
c := make(chan inotify.EventInfo, 10)
defer inotify.Stop(c)
go func() {
for {
event := <-c
// ignore vim temporary files events
if strings.HasSuffix(filepath.Ext(event.Path()), "~") {
continue
}
terminal.Logger.Debug().Msg("Got event: " + event.Event().String())
select {
case restartChan <- true:
default:
}
}
}()
for _, watched := range r.pidFile.Watched {
if fi, err := os.Stat(watched); err != nil {
continue
} else if fi.IsDir() {
terminal.Logger.Info().Msg("Watching directory " + watched)
watched = filepath.Join(watched, "...")
} else {
terminal.Logger.Info().Msg("Watching file " + watched)
}
if err := inotify.Watch(watched, c, inotify.All); err != nil {
return errors.Wrapf(err, `could not watch "%s"`, watched)
}
}
}
firstBoot := r.mode != RunnerModeOnce
looping := r.mode != RunnerModeOnce || len(r.pidFile.Watched) > 0
// duration is not really important here, we just need enough time to stop
// the timer to be sure no event is fired and got stocked in the channel
timer := time.NewTimer(time.Hour)
timer.Stop()
pid := os.Getpid()
for {
cmd, err := r.buildCmd()
if err != nil {
return errors.Wrap(err, "unable to build cmd")
}
if err := cmd.Start(); err != nil {
return errors.Wrapf(err, `command "%s" failed to start`, r.pidFile)
}
go func() { cmdExitChan <- cmd.Wait() }()
if firstBoot {
timer.Reset(RunnerReliefDuration)
if r.mode == RunnerModeLoopDetached {
reexec.NotifyForeground("started")
}
select {
case err := <-cmdExitChan:
if err != nil {
return errors.Wrapf(err, `command "%s" failed early`, r.pidFile)
}
timer.Stop()
// when the command is really fast to run, it will be already
// done here, so we need to forward exit status as if it has
// finished later one
go func() { cmdExitChan <- err }()
case <-timer.C:
}
}
if r.mode == RunnerModeLoopAttached {
pid = cmd.Process.Pid
}
if firstBoot || r.mode == RunnerModeLoopAttached {
if err := r.pidFile.Write(pid, 0, ""); err != nil {
return errors.Wrap(err, "unable to write pid file")
}
}
if firstBoot && r.mode == RunnerModeLoopDetached {
terminal.RemapOutput(cmd.Stdout, cmd.Stderr).SetDecorated(true)
reexec.NotifyForeground(reexec.UP)
}
firstBoot = false
select {
case sig := <-sigChan:
terminal.Logger.Info().Msgf("Signal \"%s\" received, forwarding to command and exiting\n", sig)
err := cmd.Process.Signal(sig)
if err != nil && runtime.GOOS == "windows" && strings.Contains(err.Error(), "not supported by windows") {
return exec.Command("CMD", "/C", "TASKKILL", "/F", "/PID", strconv.Itoa(cmd.Process.Pid)).Run()
}
return err
case <-restartChan:
// We use SIGTERM here because it's nicer and thus when we use our
// wrappers, signal will be nicely forwarded
cmd.Process.Signal(syscall.SIGTERM)
// we need to drain cmdExit channel to unblock cmd channel receiver
<-cmdExitChan
// Command exited
case err := <-cmdExitChan:
err = errors.Wrapf(err, `command "%s" failed`, r.pidFile)
if err == nil && r.SuccessHook != nil {
r.SuccessHook(r, cmd)
}
// Command is NOT set up to loop, stop here and remove the pidFile
// if the command is successful
if !looping {
if err != nil {
return err
}
return r.pidFile.Remove()
}
// Command is set up to restart on exit (usually PHP builtin
// server), so we restart immediately without waiting
if r.AlwaysRestartOnExit {
terminal.Logger.Error().Msgf(`command "%s" exited, restarting it immediately`, r.pidFile)
continue
}
// In case of error we want to wait up-to 5 seconds before
// restarting the command, this avoids overloading the system with a
// failing command
if err != nil {
terminal.Logger.Error().Msgf("%s, waiting 5 seconds before restarting it", err)
timer.Reset(5 * time.Second)
}
// Wait for a timer to expire or a file to be changed to restart
// or a signal to be received to exit
select {
case sig := <-sigChan:
terminal.Logger.Info().Msgf(`Signal "%s" received, exiting`, sig)
return nil
case <-restartChan:
timer.Stop()
case <-timer.C:
}
}
terminal.Logger.Info().Msgf(`Restarting command "%s"`, r.pidFile)
}
}
func (r *Runner) buildCmd() (*exec.Cmd, error) {
cmd := exec.Command(r.binary, r.pidFile.Args[1:]...)
cmd.Env = os.Environ()
cmd.Dir = r.pidFile.Dir
if err := buildCmd(cmd, r.mode == RunnerModeOnce); err != nil {
return nil, err
}
if r.mode == RunnerModeOnce {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
} else if logWriter, err := r.pidFile.LogWriter(); err != nil {
return nil, errors.WithStack(err)
} else {
cmd.Stdout = logWriter
cmd.Stderr = logWriter
}
if r.BuildCmdHook != nil {
if err := r.BuildCmdHook(cmd); err != nil {
return cmd, errors.WithStack(err)
}
}
return cmd, nil
}