-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
75 lines (62 loc) · 1.88 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
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/Zioyi/zocker/container"
log "github.com/sirupsen/logrus"
_ "github.com/Zioyi/zocker/nsenter"
)
const ENV_EXEC_PID = "zocker_pid"
const ENV_EXEC_CMD = "zocker_cmd"
func ExecContainer(containerName string, commandArray []string) {
pid, err := getContainerPidByName(containerName)
if err != nil {
log.Errorf("Exec container getContainerPidByName %s error %v", containerName, err)
}
cmdStr := strings.Join(commandArray, " ")
log.Infof("container pid %s, comand %s", pid, cmdStr)
cmd := exec.Command("/proc/self/exe", "exec")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = os.Setenv(ENV_EXEC_PID, pid)
if err != nil {
log.Errorf("Exec container setenv %s error %v", ENV_EXEC_PID, err)
}
err = os.Setenv(ENV_EXEC_CMD, cmdStr)
if err != nil {
log.Errorf("Exec container setnv %s error %v", ENV_EXEC_CMD, err)
}
envs := getEnvsByPid(pid)
cmd.Env = append(os.Environ(), envs...)
if err := cmd.Run(); err != nil {
log.Errorf("Exec container %s error %v", containerName, err)
}
}
func getContainerPidByName(containerName string) (string, error) {
dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
configFilePath := dirURL + container.ConfigName
content, err := ioutil.ReadFile(configFilePath)
if err != nil {
return "", err
}
var containerInfo container.ContainerInfo
if err = json.Unmarshal(content, &containerInfo); err != nil {
return "", err
}
return containerInfo.Pid, nil
}
func getEnvsByPid(pid string) []string {
// 进程环境变量保存的位置 /proc/PID/environ
path := fmt.Sprintf("/proc/%s/environ", pid)
contentBytes, err := ioutil.ReadFile(path)
if err != nil {
log.Errorf("[getEnvsByPid] read environ file [%s] failed, err = %v", path, err)
}
envs := strings.Split(string(contentBytes), "\u0000")
return envs
}