github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/e2e/framework/provisioning/linux_runner.go (about) 1 package provisioning 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os/exec" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/pkg/errors" 13 ) 14 15 // LinuxRunner is a ProvisioningRunner that runs on the executing host only. 16 // The Nomad configurations used with this runner will need to avoid port 17 // conflicts! 18 // 19 // Must call Open before other methods. 20 type LinuxRunner struct { 21 // populated on Open. 22 t *testing.T 23 } 24 25 // Open sets up the LinuxRunner to run using t as a logging mechanism. 26 func (runner *LinuxRunner) Open(t *testing.T) error { 27 runner.t = t 28 return nil 29 } 30 31 func parseCommand(command string) (string, []string) { 32 fields := strings.Fields(strings.TrimSpace(command)) 33 if len(fields) == 1 { 34 return fields[0], nil 35 } 36 return fields[0], fields[1:] 37 } 38 39 // Run the script (including any arguments) 40 func (runner *LinuxRunner) Run(script string) error { 41 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) 42 defer cancel() 43 44 commands := strings.Split(script, "\n") 45 for _, command := range commands { 46 executable, args := parseCommand(command) 47 response, err := exec.CommandContext(ctx, executable, args...).CombinedOutput() 48 49 // Nothing fancy around separating stdin from stdout, or failed vs 50 // successful commands for now. 51 runner.LogOutput(string(response)) 52 53 if err != nil { 54 return errors.Wrapf(err, "failed to execute command %q", command) 55 } 56 } 57 return nil 58 } 59 60 func (runner *LinuxRunner) Copy(local, remote string) error { 61 cmd := exec.Command("cp", "-rf", local, remote) 62 return cmd.Run() 63 } 64 65 func (runner *LinuxRunner) Close() {} 66 67 func (runner *LinuxRunner) Logf(format string, args ...interface{}) { 68 if runner.t == nil { 69 log.Fatal("no t.Testing configured for LinuxRunner") 70 } 71 if testing.Verbose() { 72 fmt.Printf("[local] "+format+"\n", args...) 73 } else { 74 runner.t.Logf("[local] "+format, args...) 75 } 76 } 77 78 func (runner *LinuxRunner) LogOutput(output string) { 79 if testing.Verbose() { 80 fmt.Println("\033[32m" + output + "\033[0m") 81 } else { 82 runner.t.Log(output) 83 } 84 }