-
-
Notifications
You must be signed in to change notification settings - Fork 517
/
run.go
85 lines (76 loc) · 1.94 KB
/
run.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
85
package cli
import (
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
// nolint:depguard // TODO: switch this stuff over to dexec
"os/exec"
"github.com/telepresenceio/telepresence/v2/pkg/client/logging"
)
func runAsRoot(exe string, args []string) error {
if os.Geteuid() != 0 {
if err := exec.Command("sudo", "-n", "true").Run(); err != nil {
fmt.Printf("Need root privileges to run %q\n", logging.ShellString(exe, args))
if err = exec.Command("sudo", "true").Run(); err != nil {
return err
}
}
args = append([]string{"-n", "-E", exe}, args...)
exe = "sudo"
}
return start(exe, args, false, nil, nil, nil)
}
func envPairs(env map[string]string) []string {
pairs := make([]string, len(env))
i := 0
for k, v := range env {
pairs[i] = k + "=" + v
i++
}
return pairs
}
func start(exe string, args []string, wait bool, stdin io.Reader, stdout, stderr io.Writer, env ...string) error {
cmd := exec.Command(exe, args...)
cmd.Stdout = stdout
cmd.Stderr = stderr
cmd.Stdin = stdin
if len(env) > 0 {
cmd.Env = append(os.Environ(), env...)
}
if !wait {
// Process must live in a process group of its own to prevent
// getting affected by <ctrl-c> in the terminal
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
var err error
if err = cmd.Start(); err != nil {
return fmt.Errorf("%s: %v", logging.ShellString(exe, args), err)
}
if !wait {
_ = cmd.Process.Release()
return nil
}
// Ensure that SIGINT and SIGTERM are propagated to the child process
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigCh
if sig == nil {
return
}
_ = cmd.Process.Signal(sig)
}()
s, err := cmd.Process.Wait()
if err != nil {
return fmt.Errorf("%s: %v", logging.ShellString(exe, args), err)
}
sigCh <- nil
exitCode := s.ExitCode()
if exitCode != 0 {
return fmt.Errorf("%s %s: exited with %d", exe, strings.Join(args, " "), exitCode)
}
return nil
}