forked from hashicorp/nomad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linux_runner.go
84 lines (71 loc) · 1.96 KB
/
linux_runner.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package provisioning
import (
"context"
"fmt"
"log"
"os/exec"
"strings"
"testing"
"time"
"github.com/pkg/errors"
)
// LinuxRunner is a ProvisioningRunner that runs on the executing host only.
// The Nomad configurations used with this runner will need to avoid port
// conflicts!
//
// Must call Open before other methods.
type LinuxRunner struct {
// populated on Open.
t *testing.T
}
// Open sets up the LinuxRunner to run using t as a logging mechanism.
func (runner *LinuxRunner) Open(t *testing.T) error {
runner.t = t
return nil
}
func parseCommand(command string) (string, []string) {
fields := strings.Fields(strings.TrimSpace(command))
if len(fields) == 1 {
return fields[0], nil
}
return fields[0], fields[1:]
}
// Run the script (including any arguments)
func (runner *LinuxRunner) Run(script string) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
commands := strings.Split(script, "\n")
for _, command := range commands {
executable, args := parseCommand(command)
response, err := exec.CommandContext(ctx, executable, args...).CombinedOutput()
// Nothing fancy around separating stdin from stdout, or failed vs
// successful commands for now.
runner.LogOutput(string(response))
if err != nil {
return errors.Wrapf(err, "failed to execute command %q", command)
}
}
return nil
}
func (runner *LinuxRunner) Copy(local, remote string) error {
cmd := exec.Command("cp", "-rf", local, remote)
return cmd.Run()
}
func (runner *LinuxRunner) Close() {}
func (runner *LinuxRunner) Logf(format string, args ...interface{}) {
if runner.t == nil {
log.Fatal("no t.Testing configured for LinuxRunner")
}
if testing.Verbose() {
fmt.Printf("[local] "+format+"\n", args...)
} else {
runner.t.Logf("[local] "+format, args...)
}
}
func (runner *LinuxRunner) LogOutput(output string) {
if testing.Verbose() {
fmt.Println("\033[32m" + output + "\033[0m")
} else {
runner.t.Log(output)
}
}