mirror/merlin/common/process_manager.go

71 lines
1.8 KiB
Go

package common
import (
"fmt"
"os/exec"
"syscall"
"time"
)
// SpawnProcess spawns a child process for the given repo. The process will
// be stopped early if the repo receives a stop signal, or if the process
// runs for longer than the repo's MaxTime.
// It returns a channel through which a Cmd will be sent once it has finished,
// or nil if it was unable to start a process.
func SpawnProcess(repo *Repo, args []string) (ch <-chan *exec.Cmd) {
// startTime and time took will be handled in common.go by SyncExit
cmd := exec.Command(args[0], args[1:]...)
repo.Logger.Debug("Starting process")
if err := cmd.Start(); err != nil {
repo.Logger.Error(fmt.Errorf("could not start process for %s: %w", repo.Name, err).Error())
return
}
cmdChan := make(chan *exec.Cmd)
ch = cmdChan
cmdDoneChan := make(chan struct{})
killProcess := func() {
err := cmd.Process.Signal(syscall.SIGTERM)
if err != nil {
repo.Logger.Error("Could not send signal to process:", err)
return
}
select {
case <-time.After(30 * time.Second):
repo.Logger.Warning("Process still hasn't stopped after 30 seconds; sending SIGKILL")
cmd.Process.Signal(syscall.SIGKILL)
case <-cmdDoneChan:
repo.Logger.Debug("Process has been stopped.")
}
}
go func() {
cmd.Wait()
close(cmdDoneChan)
}()
go func() {
defer func() {
cmdChan <- cmd
}()
select {
case <-cmdDoneChan:
if !cmd.ProcessState.Success() {
repo.Logger.Warning("Process ended with status code", cmd.ProcessState.ExitCode())
}
case <-repo.StopChan:
repo.Logger.Debug("Received signal to stop, killing process...")
killProcess()
case <-time.After(time.Duration(repo.MaxTime) * time.Second):
repo.Logger.Warning("Process has exceeded its max time; killing now")
killProcess()
}
}()
return
}