tendermint/process/process.go

98 lines
2.1 KiB
Go
Raw Normal View History

package process
import (
2015-04-10 02:12:17 -07:00
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"time"
)
type Process struct {
2015-04-10 02:12:17 -07:00
Label string
ExecPath string
2015-04-16 09:46:35 -07:00
Pid int
2015-04-10 02:12:17 -07:00
StartTime time.Time
2015-04-16 09:46:35 -07:00
EndTime time.Time
2015-04-10 02:12:17 -07:00
OutputPath string
Cmd *exec.Cmd `json:"-"`
ExitState *os.ProcessState `json:"-"`
OutputFile *os.File `json:"-"`
2015-04-16 10:54:07 -07:00
WaitCh chan struct{} `json:"-"`
}
const (
ProcessModeStd = iota
ProcessModeDaemon
)
2015-04-08 11:35:17 -07:00
// execPath: command name
// args: args to command. (should not include name)
func Create(mode int, label string, execPath string, args []string, input string, outPath string) (*Process, error) {
2015-04-20 14:47:59 -07:00
outFile, err := os.OpenFile(outPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return nil, err
}
2015-04-08 11:35:17 -07:00
cmd := exec.Command(execPath, args...)
switch mode {
case ProcessModeStd:
2015-04-10 02:12:17 -07:00
cmd.Stdout = io.MultiWriter(os.Stdout, outFile)
cmd.Stderr = io.MultiWriter(os.Stderr, outFile)
cmd.Stdin = nil
case ProcessModeDaemon:
2015-04-10 02:12:17 -07:00
cmd.Stdout = outFile
cmd.Stderr = outFile
cmd.Stdin = nil
}
2015-04-10 02:12:17 -07:00
if input != "" {
cmd.Stdin = bytes.NewReader([]byte(input))
}
if err := cmd.Start(); err != nil {
2015-04-16 09:46:35 -07:00
return nil, err
}
2015-04-16 09:46:35 -07:00
proc := &Process{
2015-04-10 02:12:17 -07:00
Label: label,
ExecPath: execPath,
2015-04-16 09:46:35 -07:00
Pid: cmd.Process.Pid,
2015-04-10 02:12:17 -07:00
StartTime: time.Now(),
OutputPath: outPath,
Cmd: cmd,
ExitState: nil,
OutputFile: outFile,
2015-04-16 10:54:07 -07:00
WaitCh: make(chan struct{}),
}
2015-04-16 09:46:35 -07:00
go func() {
2015-04-16 10:54:07 -07:00
err := proc.Cmd.Wait()
if err != nil {
fmt.Printf("Process exit: %v\n", err)
if exitError, ok := err.(*exec.ExitError); ok {
proc.ExitState = exitError.ProcessState
}
}
2015-04-16 09:46:35 -07:00
proc.EndTime = time.Now() // TODO make this goroutine-safe
2015-04-16 10:54:07 -07:00
close(proc.WaitCh)
2015-04-16 09:46:35 -07:00
}()
return proc, nil
}
func ReadOutput(proc *Process) string {
output, err := ioutil.ReadFile(proc.OutputPath)
if err != nil {
return fmt.Sprintf("ERROR READING OUTPUT: %v", err)
}
return string(output)
}
2015-04-08 11:35:17 -07:00
func Stop(proc *Process, kill bool) error {
defer proc.OutputFile.Close()
2015-04-08 11:35:17 -07:00
if kill {
2015-04-16 18:35:27 -07:00
fmt.Printf("Killing process %v\n", proc.Cmd.Process)
2015-04-08 11:35:17 -07:00
return proc.Cmd.Process.Kill()
} else {
2015-04-16 18:35:27 -07:00
fmt.Printf("Stopping process %v\n", proc.Cmd.Process)
2015-04-08 11:35:17 -07:00
return proc.Cmd.Process.Signal(os.Interrupt)
}
}