2020-10-13 22:02:55 +00:00
|
|
|
package externalcmd
|
2020-09-19 15:49:44 +00:00
|
|
|
|
|
|
|
import (
|
2020-10-31 15:36:09 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2021-07-04 16:13:49 +00:00
|
|
|
restartPause = 5 * time.Second
|
2020-09-19 15:49:44 +00:00
|
|
|
)
|
|
|
|
|
2020-11-21 12:35:33 +00:00
|
|
|
// Environment is a Cmd environment.
|
2021-12-08 19:50:09 +00:00
|
|
|
type Environment map[string]string
|
2020-11-01 16:33:06 +00:00
|
|
|
|
2020-11-21 12:35:33 +00:00
|
|
|
// Cmd is an external command.
|
|
|
|
type Cmd struct {
|
2020-11-01 16:33:06 +00:00
|
|
|
cmdstr string
|
|
|
|
restart bool
|
|
|
|
env Environment
|
2021-12-08 20:23:45 +00:00
|
|
|
onExit func(int)
|
2020-10-31 15:36:09 +00:00
|
|
|
|
|
|
|
// in
|
|
|
|
terminate chan struct{}
|
|
|
|
|
|
|
|
// out
|
|
|
|
done chan struct{}
|
|
|
|
}
|
|
|
|
|
2020-11-21 12:35:33 +00:00
|
|
|
// New allocates an Cmd.
|
2021-12-08 20:23:45 +00:00
|
|
|
func New(
|
|
|
|
cmdstr string,
|
|
|
|
restart bool,
|
|
|
|
env Environment,
|
|
|
|
onExit func(int),
|
|
|
|
) *Cmd {
|
2020-11-21 12:35:33 +00:00
|
|
|
e := &Cmd{
|
2020-10-31 15:36:09 +00:00
|
|
|
cmdstr: cmdstr,
|
|
|
|
restart: restart,
|
2020-11-01 16:33:06 +00:00
|
|
|
env: env,
|
2021-12-08 20:23:45 +00:00
|
|
|
onExit: onExit,
|
2020-10-31 15:36:09 +00:00
|
|
|
terminate: make(chan struct{}),
|
|
|
|
done: make(chan struct{}),
|
|
|
|
}
|
|
|
|
|
|
|
|
go e.run()
|
2021-08-01 14:58:46 +00:00
|
|
|
|
2020-10-31 15:36:09 +00:00
|
|
|
return e
|
|
|
|
}
|
|
|
|
|
2020-11-21 12:35:33 +00:00
|
|
|
// Close closes an Cmd.
|
|
|
|
func (e *Cmd) Close() {
|
2020-10-31 15:36:09 +00:00
|
|
|
close(e.terminate)
|
|
|
|
<-e.done
|
|
|
|
}
|
|
|
|
|
2020-11-21 12:35:33 +00:00
|
|
|
func (e *Cmd) run() {
|
2020-10-31 15:36:09 +00:00
|
|
|
defer close(e.done)
|
|
|
|
|
|
|
|
for {
|
2020-10-31 16:03:03 +00:00
|
|
|
ok := func() bool {
|
2021-12-08 20:23:45 +00:00
|
|
|
c, ok := e.runInner()
|
2020-10-31 16:03:03 +00:00
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
2020-10-31 15:36:09 +00:00
|
|
|
|
2021-12-08 20:23:45 +00:00
|
|
|
e.onExit(c)
|
|
|
|
|
2020-10-31 16:03:03 +00:00
|
|
|
if !e.restart {
|
|
|
|
<-e.terminate
|
|
|
|
return false
|
|
|
|
}
|
2020-10-31 15:36:09 +00:00
|
|
|
|
2020-10-31 16:03:03 +00:00
|
|
|
select {
|
2021-07-04 16:13:49 +00:00
|
|
|
case <-time.After(restartPause):
|
2020-10-31 16:03:03 +00:00
|
|
|
return true
|
|
|
|
case <-e.terminate:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
if !ok {
|
|
|
|
break
|
|
|
|
}
|
2020-10-31 15:36:09 +00:00
|
|
|
}
|
2020-09-19 15:49:44 +00:00
|
|
|
}
|