-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
137 lines (113 loc) · 2.35 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
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"time"
)
// CommandRunner is a command runner. It maintains a running command in the
// background.
type CommandRunner struct {
Subscriber[struct{}]
args []string
restart chan struct{}
pubsub *Pubsub[struct{}]
}
// NewCommandRunner creates a new command runner.
func NewCommandRunner(args []string) *CommandRunner {
restart := make(chan struct{}, 1)
restart <- struct{}{}
pubsub := NewPubsub[struct{}]()
return &CommandRunner{
pubsub,
args,
restart,
pubsub,
}
}
// Start starts the command runner until the context is canceled.
func (s *CommandRunner) Start(ctx context.Context) error {
var cmd *exec.Cmd
defer func() {
if cmd != nil {
stopCommand(cmd)
}
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-s.restart:
}
log.Println("command runner received restart")
if cmd != nil {
stopCommand(cmd)
cmd = nil
}
log.Printf("starting command %q", s.args)
cmd = exec.Command(s.args[0], s.args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start process: %w", err)
}
// sleep for a bit to wait for the process to start
if err := sleep(ctx, 500*time.Millisecond); err != nil {
return err
}
// drain restart channel
select {
case <-s.restart:
default:
}
s.pubsub.Publish(struct{}{})
}
}
// Restart signals the command runner to restart the command.
func (s *CommandRunner) Restart() {
select {
case s.restart <- struct{}{}:
default:
}
}
func stopCommand(cmd *exec.Cmd) {
if cmd == nil {
return
}
wait := make(chan error, 1)
go func() { wait <- cmd.Wait() }()
select {
case <-wait:
return
default:
cmd.Process.Signal(os.Interrupt)
log.Println("sent SIGINT, waiting 2s")
}
timer := time.NewTimer(2 * time.Second)
defer timer.Stop()
select {
case <-timer.C:
log.Println("timeout waiting for process to exit, killing...")
cmd.Process.Kill()
case <-wait:
log.Println("process exited")
return
}
if err := <-wait; err != nil {
log.Println("error waiting for process to exit:", err)
} else {
log.Println("process exited")
}
}
func sleep(ctx context.Context, d time.Duration) error {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}