frp/test/e2e/pkg/process/process.go

67 lines
1.2 KiB
Go
Raw Normal View History

2020-06-02 22:48:55 +08:00
package process
import (
"bytes"
"context"
"os/exec"
)
type Process struct {
cmd *exec.Cmd
cancel context.CancelFunc
errorOutput *bytes.Buffer
2020-09-07 14:57:23 +08:00
stdOutput *bytes.Buffer
2020-06-02 22:48:55 +08:00
beforeStopHandler func()
2021-06-18 16:48:36 +08:00
stopped bool
2020-06-02 22:48:55 +08:00
}
func New(path string, params []string) *Process {
2021-06-18 16:48:36 +08:00
return NewWithEnvs(path, params, nil)
}
func NewWithEnvs(path string, params []string, envs []string) *Process {
2020-06-02 22:48:55 +08:00
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, path, params...)
2021-06-18 16:48:36 +08:00
cmd.Env = envs
2020-06-02 22:48:55 +08:00
p := &Process{
cmd: cmd,
cancel: cancel,
}
p.errorOutput = bytes.NewBufferString("")
2020-09-07 14:57:23 +08:00
p.stdOutput = bytes.NewBufferString("")
2020-06-02 22:48:55 +08:00
cmd.Stderr = p.errorOutput
2020-09-07 14:57:23 +08:00
cmd.Stdout = p.stdOutput
2020-06-02 22:48:55 +08:00
return p
}
func (p *Process) Start() error {
return p.cmd.Start()
}
func (p *Process) Stop() error {
2021-06-18 16:48:36 +08:00
if p.stopped {
return nil
}
defer func() {
p.stopped = true
}()
2020-06-02 22:48:55 +08:00
if p.beforeStopHandler != nil {
p.beforeStopHandler()
}
p.cancel()
return p.cmd.Wait()
}
func (p *Process) ErrorOutput() string {
return p.errorOutput.String()
}
2020-09-07 14:57:23 +08:00
func (p *Process) StdOutput() string {
return p.stdOutput.String()
}
2020-06-02 22:48:55 +08:00
func (p *Process) SetBeforeStopHandler(fn func()) {
p.beforeStopHandler = fn
}