-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.go
63 lines (54 loc) · 1.56 KB
/
exec.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
package main
import (
"fmt"
log "github.com/Sirupsen/logrus"
_ "github.com/seagullbird/mydocker/nsenter"
"io/ioutil"
"os"
"os/exec"
"strings"
)
const ENV_EXEC_PID = "mydocker_pid"
const ENV_EXEC_CMD = "mydocker_cmd"
func ExecContainer(containerName string, cmdArray []string) {
pid, err := getContainerPidByName(containerName)
if err != nil {
log.Errorf("Exec container getContainerPidByName %s error: %v", containerName, err)
return
}
cmdStr := strings.Join(cmdArray, " ")
log.Infof("container pid %s", pid)
log.Infof("command %s", cmdStr)
cmd := exec.Command("/proc/self/exe", "exec")
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
os.Setenv(ENV_EXEC_PID, pid)
os.Setenv(ENV_EXEC_CMD, cmdStr)
// get container envs
containerEnvs := getEnvsByPid(pid)
cmd.Env = append(os.Environ(), containerEnvs...)
if err := cmd.Run(); err != nil {
log.Errorf("Exec container %s error: %v", containerName, err)
}
}
func getContainerPidByName(containerName string) (string, error) {
containerInfo, err := GetContainerInfoByName(containerName)
if err != nil {
log.Errorf("GetContainerInfoByName with name %s error: %v", containerName, err)
return "", err
}
return containerInfo.Pid, nil
}
func getEnvsByPid(pid string) []string {
// /proc/PID/environ saves process's env
path := fmt.Sprintf("/proc/%s/environ", pid)
contentBytes, err := ioutil.ReadFile(path)
if err != nil {
log.Errorf("Read file %s error: %v", path, err)
return nil
}
// \u0000 separates multiple envs
envs := strings.Split(string(contentBytes), "\u0000")
return envs
}