File size: 1,221 Bytes
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package orchestrator

import (
	"context"
	"io"
	"os/exec"
)

type HostRunner interface {
	Run(ctx context.Context, binary string, args []string, env []string, stdout, stderr io.Writer) (Cmd, error)
	IsPortAvailable(port string) bool
}

type Cmd interface {
	Wait() error
	PID() int
	Cancel()
}

type LocalRunner struct{}

type localCmd struct {
	execCmd *exec.Cmd
	cancel  context.CancelFunc
}

func (r *LocalRunner) Run(ctx context.Context, binary string, args []string, env []string, stdout, stderr io.Writer) (Cmd, error) {
	runCtx, cancel := context.WithCancel(ctx)
	cmd := exec.CommandContext(runCtx, binary, args...) // #nosec G204 -- binary is the pinchtab executable path, args are internal subcommands
	cmd.Env = env
	cmd.Stdout = stdout
	cmd.Stderr = stderr
	setProcGroup(cmd)

	if err := cmd.Start(); err != nil {
		cancel()
		return nil, err
	}

	return &localCmd{execCmd: cmd, cancel: cancel}, nil
}

func (r *LocalRunner) IsPortAvailable(port string) bool {
	return isPortAvailable(port)
}

func (c *localCmd) Wait() error {
	return c.execCmd.Wait()
}

func (c *localCmd) PID() int {
	if c.execCmd.Process != nil {
		return c.execCmd.Process.Pid
	}
	return 0
}

func (c *localCmd) Cancel() {
	c.cancel()
}