-
Notifications
You must be signed in to change notification settings - Fork 3
/
goproc.go
528 lines (465 loc) · 12.8 KB
/
goproc.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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package goproc
import (
"bufio"
"bytes"
"errors"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/kokizzu/gotro/A"
"github.com/kokizzu/gotro/S"
"github.com/kokizzu/gotro/I"
"github.com/kokizzu/gotro/L"
)
type CommandId int
type CmdState int
type StringCallback func(*Cmd, string) error
type IntCallback func(*Cmd, int64)
type CmdStateCallback func(*Cmd, CmdState, CmdState)
type ParameterlessCallback func(*Cmd)
type IntReturningCallback func(*Cmd) int64
const (
NoRestart = 0
RestartForever = -1
)
const (
NotStarted CmdState = iota // program can be started (again)
Started // program running
Killed // program killed using API
Crashed // program terminated with error
Exited // program terminated without error
)
type Cmd struct {
Program string // program name, could be full path or only the program name, depends on PATH environment variables
Parameters []string // program parameters
WorkDir string // starting directory
PrefixLabel string // prefix label instead of goprocID
InheritEnv bool // inherit current console's env
Env []string // environment variables
StartDelayMs int64 // delay before starting process
RestartDelayMs int64 // delay before restarting process, <0 if you don't want to restart this process
HideStdout bool // disable stdout logging
HideStderr bool // disable stderr logging
MaxRestart int // -1 = always restart, 0 = only run once, >0 run N times
LastExecutionError error // last execution error, useful for OnProcessCompleted or ProcessCompletedChannel
LastExitCode int // last exit code, will be set before OnProcessCompleted
RestartCount int // can be overwritten for early exit or restart from 0
OnStdout StringCallback // one line fetched from stdout
OnStderr StringCallback // one line fetched from stderr
OnRestart IntReturningCallback // this overwrites RestartDelayMs
OnExit ParameterlessCallback // when max restart reached, or manually killed
OnProcessCompleted IntCallback // when 1x process done, can be restarting depends on RestartCount and MaxCount
OnStateChanged CmdStateCallback // triggered when stated changed
state CmdState
strCache string
// channel API
UseChannelApi bool
StdoutChanLength int
StdoutChannel chan string
StderrChanLength int
StderrChannel chan string
ProcesssCompletedChannel chan int64
ExitChannel chan bool
StateChangedChannel chan CmdState
}
func (cmd *Cmd) String() string {
if len(cmd.Parameters) == 0 {
return cmd.Program
}
if len(cmd.strCache) > 0 {
return cmd.strCache
}
// escape parameters
cmd.strCache += cmd.Program
arr := []string{}
for _, param := range cmd.Parameters {
if strings.Contains(param, `"`) {
param = strings.Replace(param, `"`, `\"`, -1)
}
arr = append(arr, param)
}
cmd.strCache += ` "` + strings.Join(arr, `" "`) + `"`
return cmd.strCache
}
func (g *Cmd) GetState() CmdState {
return g.state
}
func (cmd *Cmd) setState(newState CmdState) {
oldState := cmd.state
cmd.state = newState
if cmd.OnStateChanged != nil {
cmd.OnStateChanged(cmd, oldState, newState)
}
if cmd.UseChannelApi {
go (func() {
cmd.StateChangedChannel <- newState
})()
}
}
type Process struct {
exe *exec.Cmd
}
type Goproc struct {
cmds []*Cmd
procs []*Process
lock sync.Mutex
HasErrFunc func(err error, fmt string, args ...any) bool
}
// LogHasErr to log if error occurred, must return true if err not nil
func LogHasErr(err error, fmt string, args ...any) bool {
if err != nil {
log.Printf(fmt, args...)
return true
}
return false
}
// PrintHasErr to log using fmt if error occurred, must return true if err not nil
func PrintHasErr(err error, msg string, args ...any) bool {
if err != nil {
fmt.Printf(msg+"\n", args...)
return true
}
return false
}
// DiscardHasErr to ignore if error occurred, must return true if err not nil
func DiscardHasErr(err error, _ string, _ ...any) bool {
return err != nil
}
func New() *Goproc {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
res := &Goproc{
cmds: []*Cmd{},
HasErrFunc: L.IsError,
}
go func() {
<-c
res.Cleanup()
os.Exit(1)
}()
return res
}
// AddCommand add a new command to run, not yet started until Start called
// returns command id
func (g *Goproc) AddCommand(cmd *Cmd) CommandId {
g.lock.Lock()
defer g.lock.Unlock()
g.cmds = append(g.cmds, cmd)
cmd.StdoutChannel = make(chan string, cmd.StdoutChanLength)
cmd.StderrChannel = make(chan string, cmd.StderrChanLength)
cmd.ExitChannel = make(chan bool)
cmd.ProcesssCompletedChannel = make(chan int64)
cmd.StateChangedChannel = make(chan CmdState)
cmd.state = NotStarted
// * start processes with given arguments and environment variables;
g.procs = append(g.procs, &Process{
exe: nil,
})
cmdId := len(g.cmds) - 1
return CommandId(cmdId)
}
func (g *Goproc) Kill(cmdId CommandId) error {
return g.Signal(cmdId, os.Kill)
}
// Signal send signal to process
func (g *Goproc) Signal(cmdId CommandId, signal os.Signal) error {
idx := int(cmdId)
if idx >= len(g.cmds) || idx < 0 {
return fmt.Errorf(`invalid command index, should be zero to %d`, len(g.cmds)-1)
}
prefix := `cmd` + I.ToStr(idx) + `: `
cmd := g.cmds[idx]
proc := g.procs[idx]
log.Printf(prefix+`signalling %s\n`, cmd)
if cmd.state != Started {
return fmt.Errorf(`process not started: %d`, cmd.state)
}
if signal == os.Kill {
// * stop them; signal=os.Kill
err := proc.exe.Process.Kill()
cmd.setState(Killed)
if g.HasErrFunc(err, `error proc.exe.Process.Kill`) {
return err
}
} else {
// * relay termination signals;
err := proc.exe.Process.Signal(signal)
if g.HasErrFunc(err, `error proc.exe.Process.Signal %d`, signal) {
return err
}
}
return nil
}
// Start start certain command
func (g *Goproc) Start(cmdId CommandId) error {
idx := int(cmdId)
if idx >= len(g.cmds) || idx < 0 {
return fmt.Errorf(`invalid command index, should be zero to %d`, len(g.cmds)-1)
}
cmd := g.cmds[idx]
cmd.strCache = `` // reset cache
prefix := S.IfEmpty(cmd.PrefixLabel, `CMD:`+I.ToStr(idx)) + `: `
if cmd.state != NotStarted {
return fmt.Errorf(`invalid command state=%d already started`, cmd.state)
}
time.Sleep(time.Millisecond * time.Duration(cmd.StartDelayMs))
for {
// refill process
proc := g.procs[idx]
proc.exe = exec.Command(cmd.Program, cmd.Parameters...)
proc.exe.Dir = cmd.WorkDir
if cmd.InheritEnv {
proc.exe.Env = append(os.Environ(), cmd.Env...)
} else {
proc.exe.Env = cmd.Env
}
// get output buffer and start
stderr, err := proc.exe.StderrPipe()
if g.HasErrFunc(err, prefix+`error proc.exe.StderrPipe %s`, cmd) {
return err
}
stdout, err := proc.exe.StdoutPipe()
if g.HasErrFunc(err, prefix+`error proc.exe.StdoutPipe %s`, cmd) {
return err
}
log.Printf(prefix + `starting: ` + cmd.String())
start := time.Now()
err = proc.exe.Start()
if g.HasErrFunc(err, prefix+`error proc.exe.Start %s`, cmd) {
cmd.LastExecutionError = err
if cmd.OnProcessCompleted != nil {
durationMs := time.Since(start).Milliseconds()
cmd.OnProcessCompleted(cmd, durationMs)
if cmd.UseChannelApi {
go (func() {
cmd.ProcesssCompletedChannel <- durationMs
})()
}
}
return err
}
cmd.setState(Started)
if cmd.UseChannelApi {
go (func() {
scanner := bufio.NewScanner(stdout)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
cmd.StdoutChannel <- scanner.Text()
}
})()
go (func() {
scanner := bufio.NewScanner(stderr)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
cmd.StderrChannel <- scanner.Text()
}
})()
}
// call callback or pipe
// * read their stdout and stderr;
hasErrCallback := cmd.OnStderr != nil
if hasErrCallback || !cmd.HideStderr || cmd.UseChannelApi {
go (func() {
scanner := bufio.NewScanner(stderr)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
if hasErrCallback {
err := cmd.OnStderr(cmd, line)
g.HasErrFunc(err, prefix+`error OnStderr: `+line)
}
if !cmd.HideStdout {
log.Println(prefix + line)
}
}
})()
}
hasOutCallback := cmd.OnStdout != nil
if hasOutCallback || !cmd.HideStdout || cmd.UseChannelApi {
go (func() {
scanner := bufio.NewScanner(stdout)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
if hasOutCallback {
err := cmd.OnStdout(cmd, line)
g.HasErrFunc(err, prefix+`error OnStdout: `+line)
}
if !cmd.HideStdout {
log.Println(prefix + line)
}
}
})()
}
// wait for exit
err = proc.exe.Wait()
if g.HasErrFunc(err, prefix+`error proc.exe.Wait %s`, cmd) {
if cmd.state != Killed {
cmd.setState(Crashed)
}
} else {
log.Println("exited")
if cmd.state != Killed {
cmd.setState(Exited)
}
}
cmd.LastExecutionError = err
var ee *exec.ExitError
if errors.As(err, &ee) {
cmd.LastExitCode = ee.ExitCode()
} else {
cmd.LastExitCode = 0
}
if cmd.OnProcessCompleted != nil {
durationMs := time.Since(start).Milliseconds()
cmd.OnProcessCompleted(cmd, durationMs)
if cmd.UseChannelApi {
go (func() {
cmd.ProcesssCompletedChannel <- durationMs
})()
}
}
_ = stderr.Close()
_ = stdout.Close()
// * restart them when they crash;
cmd.RestartCount += 1
if cmd.MaxRestart > RestartForever && cmd.RestartCount > cmd.MaxRestart {
log.Printf(prefix+`max restart reached %d`, cmd.MaxRestart)
break
}
delayMs := cmd.RestartDelayMs
if cmd.OnRestart != nil {
delayMs = cmd.OnRestart(cmd)
}
time.Sleep(time.Millisecond * time.Duration(delayMs))
log.Printf(prefix+`restarting.. x%d %s`, cmd.RestartCount, cmd)
}
cmd.setState(NotStarted)
cmd.RestartCount = 0
if cmd.OnExit != nil {
cmd.OnExit(cmd)
}
if cmd.UseChannelApi {
go (func() {
cmd.ExitChannel <- true
})()
}
return nil
}
// StartAll start all that not yet started
func (g *Goproc) StartAll() {
g.lock.Lock()
defer g.lock.Unlock()
for idx, cmd := range g.cmds {
if cmd.state == NotStarted {
g.Start(CommandId(idx))
}
}
}
// StartAllParallel start all that not yet started in parallel
func (g *Goproc) StartAllParallel() *sync.WaitGroup {
g.lock.Lock()
defer g.lock.Unlock()
wg := &sync.WaitGroup{}
for idx, cmd := range g.cmds {
if cmd.state == NotStarted {
wg.Add(1)
id := CommandId(idx)
go func() {
defer wg.Done()
_ = g.Start(id)
}()
}
}
return wg
}
// Cleanup kill all process
func (g *Goproc) Cleanup() {
g.lock.Lock()
defer g.lock.Unlock()
for idx := range g.cmds {
g.HasErrFunc(g.Kill(CommandId(idx)), "")
}
}
// Terminate kill program
func (g *Goproc) Terminate(cmdId CommandId) error {
return exec.Command(`kill`, I.ToS(int64(g.procs[cmdId].exe.Process.Pid))).Run()
}
// CommandString return the command string with agruments
func (g *Goproc) CommandString(cmdId CommandId) string {
if cmdId < 0 || cmdId >= CommandId(len(g.cmds)) {
return ``
}
cmd := g.cmds[cmdId]
return cmd.Program + ` ` + A.StrJoin(cmd.Parameters, ` `)
}
// Run1 execute one command and get stdout stderr output
func Run1(cmd *Cmd) (string, string, error, int) {
proc := New()
onStdout := cmd.OnStdout
onStderr := cmd.OnStderr
stdoutBuff := bytes.Buffer{}
stdoutLock := &sync.Mutex{}
stderrBuff := bytes.Buffer{}
stderrMutex := &sync.Mutex{}
cmd.OnStdout = func(cmd *Cmd, s string) error {
stdoutLock.Lock()
stdoutBuff.WriteString(s)
stdoutBuff.WriteString("\n")
stdoutLock.Unlock()
if onStdout != nil {
return onStdout(cmd, s)
}
return nil
}
cmd.OnStderr = func(cmd *Cmd, s string) error {
stderrMutex.Lock()
stderrBuff.WriteString(s)
stderrBuff.WriteString("\n")
stderrMutex.Unlock()
if onStderr != nil {
return onStderr(cmd, s)
}
return nil
}
proc.AddCommand(cmd)
proc.StartAll()
return stdoutBuff.String(), stderrBuff.String(), cmd.LastExecutionError, cmd.LastExitCode
}
// Run1 execute one command and get stdout stderr output
func RunLines(cmd *Cmd) ([]string, []string, error, int) {
proc := New()
onStdout := cmd.OnStdout
onStderr := cmd.OnStderr
stdoutBuff := []string{}
stdoutLock := &sync.Mutex{}
stderrBuff := []string{}
stderrMutex := &sync.Mutex{}
cmd.OnStdout = func(cmd *Cmd, s string) error {
stdoutLock.Lock()
stdoutBuff = append(stdoutBuff, s)
stdoutLock.Unlock()
if onStdout != nil {
return onStdout(cmd, s)
}
return nil
}
cmd.OnStderr = func(cmd *Cmd, s string) error {
stderrMutex.Lock()
stderrBuff = append(stderrBuff, s)
stderrMutex.Unlock()
if onStderr != nil {
return onStderr(cmd, s)
}
return nil
}
proc.AddCommand(cmd)
proc.StartAll()
return stdoutBuff, stderrBuff, cmd.LastExecutionError, cmd.LastExitCode
}