-
Notifications
You must be signed in to change notification settings - Fork 1
/
command.go
250 lines (225 loc) · 5.88 KB
/
command.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
package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"syscall"
"go.uber.org/zap"
)
// Command holds data about process to be executed
type Command struct {
Command string `toml:"cmd"`
Template Template `toml:"config, omitempty"`
RunAs string `toml:"user, omitempty"`
Enabled Enabler `toml:"enabled, omitempty"`
SafeEnv bool `toml:"safeEnv, omitempty"`
uid int
gid int
user string
}
type logger struct {
Kind string
Command string
}
func (l logger) Write(data []byte) (int, error) {
// if we got json data just write it out
if string(data[0]) == "{" {
return os.Stdout.Write(data)
}
// wrap in json otherwise
log.Warn(
string(data),
zap.String("kind", l.Kind),
zap.String("cmd", l.Command),
)
return len(data), nil
}
// RunBlocking runs command in blocking mode
func (c *Command) RunBlocking(fatal bool, stripEnv bool, ctx context.Context) {
args := strings.Split(c.Command, " ")
process := exec.Command(args[0], args[1:]...)
process.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if stripEnv {
process.Env = []string{
fmt.Sprintf("HOST=%s", os.Getenv("HOST")),
fmt.Sprintf("PATH=%s", os.Getenv("PATH")),
fmt.Sprintf("EDITOR=%s", os.Getenv("EDITOR")),
fmt.Sprintf("SHELL=%s", os.Getenv("SHELL")),
fmt.Sprintf("TERM=%s", os.Getenv("TERM")),
fmt.Sprintf("TMP=%s", os.Getenv("TMP")),
fmt.Sprintf("TEMP=%s", os.Getenv("TEMP")),
}
}
if c.RunAs != "" {
currentUser, err := user.Lookup(c.RunAs)
if err != nil {
log.Fatal(
"Failed getting user",
zap.String("run_as", c.RunAs),
zap.String("cmd", c.Command),
zap.Error(err),
)
}
c.user = currentUser.Username
c.uid, _ = strconv.Atoi(currentUser.Uid)
c.gid, _ = strconv.Atoi(currentUser.Gid)
process.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(c.uid), Gid: uint32(c.gid)}
}
process.Stdout = logger{"stdout", c.Command}
process.Stderr = logger{"stderr", c.Command}
process.Stdin = nil
log.Info("Starting blocking", zap.Strings("args", args), zap.String("user", c.user))
err := process.Start()
if err != nil {
log.Fatal(
"Failed starting command",
zap.String("cmd", c.Command),
zap.Error(err),
)
}
innerCtx, cancelWatcher := context.WithCancel(context.Background())
go func() {
for {
select {
case <-innerCtx.Done():
log.Debug("Done", zap.Int("pid", process.Process.Pid))
return
case <-ctx.Done():
log.Debug("Terminating blocking", zap.Int("pid", process.Process.Pid))
err := process.Process.Kill()
if err != nil {
log.Debug("Terminating blocking failed", zap.Int("pid", process.Process.Pid), zap.Error(err))
}
return
}
}
}()
err = process.Wait()
cancelWatcher()
// no *child processes is normal error* when we are pid 1
if err != nil && !strings.Contains(err.Error(), "no child processes") {
if fatal {
log.Fatal(
"Process terminated",
zap.String("cmd", c.Command),
zap.Error(err),
)
} else {
log.Info(
"Process terminated",
zap.String("cmd", c.Command),
zap.Error(err),
)
}
} else {
log.Info(
"Process ended",
zap.String("cmd", c.Command),
)
}
}
// RunBlockingNonFatal runs command in blocking mode
func (c *Command) RunBlockingNonFatal(ctx context.Context) {
c.RunBlocking(false, false, ctx)
}
// RunBlockingNonFatalSafeEnv runs command in blocking mode with non essential env variables stripped
func (c *Command) RunBlockingNonFatalSafeEnv(ctx context.Context) {
c.RunBlocking(false, true, ctx)
}
// Run executes process and redirects pipes
func (c *Command) Run(ctx context.Context, doRestart bool) {
// Register chan to receive system signals
if !doRestart {
wg.Add(1)
}
if c.Template.Enabled() {
log.Info(
"Parsing",
zap.String("src", c.Template.Source),
zap.String("dst", c.Template.Target),
)
if err := c.Template.Process(); err != nil {
log.Fatal(
"template parsing failed",
zap.String("src", c.Template.Source),
zap.String("dst", c.Template.Target),
zap.Error(err),
)
}
}
args := strings.Split(c.Command, " ")
process := exec.Command(args[0], args[1:]...)
process.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if c.RunAs != "" {
currentUser, err := user.Lookup(c.RunAs)
if err != nil {
log.Fatal(
"Failed getting user",
zap.String("run_as", c.RunAs),
zap.String("cmd", c.Command),
zap.Error(err),
)
}
c.user = currentUser.Username
c.uid, _ = strconv.Atoi(currentUser.Uid)
c.gid, _ = strconv.Atoi(currentUser.Gid)
process.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(c.uid), Gid: uint32(c.gid)}
}
process.Stdout = logger{"stdout", c.Command}
process.Stderr = logger{"stderr", c.Command}
process.Stdin = nil
go func(pc *exec.Cmd) {
<-ctx.Done()
// Done returns a channel that's closed when work done on behalf of this context is canceled
log.Debug("Terminating forked", zap.String("cmd", c.Command))
if pc == nil {
return
}
if pc.Process == nil {
return
}
err := pc.Process.Kill()
if err != nil {
log.Debug("Terminating forked failed", zap.Error(err))
}
}(process)
go func() {
log.Info("Starting forked", zap.Strings("args", args), zap.String("user", c.user))
// start the process
err := process.Start()
if err != nil {
log.Error(
"Failed starting command",
zap.String("cmd", c.Command),
zap.Error(err),
)
}
restartProcess := false
err = process.Wait()
if err != nil {
// if proccess crashed context.Canceled will be nil
// if we got signal to finnish the work cty will be in context.Canceled error state
restartProcess = !errors.Is(ctx.Err(), context.Canceled)
log.Info(
"Process terminated",
zap.String("cmd", c.Command),
zap.Error(ctx.Err()),
zap.Error(err),
)
}
if restartProcess {
log.Info(
"Process gonna restart",
zap.String("cmd", c.Command),
)
go c.Run(ctx, true)
} else {
wg.Done()
}
}()
}