-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
67 lines (59 loc) · 1.67 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
package main
import (
"encoding/json"
"fmt"
"github.com/sirupsen/logrus"
"io/ioutil"
"mydocker/container"
_ "mydocker/nsenter"
"os"
"os/exec"
"strings"
)
const ENV_EXEC_PID = "mydocker_pid"
const ENV_EXEC_CMD = "mydocker_cmd"
func ExecContainer(containerName string, comArray []string) {
pid, err := GetContainerPidByName(containerName)
if err != nil {
logrus.Errorf("Exec container getContainerPidByName %s error %v", containerName, err)
return
}
cmdStr := strings.Join(comArray, " ")
logrus.Infof("container pid %s", pid)
logrus.Infof("command %s", cmdStr)
cmd := exec.Command("/proc/self/exe", "exec")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
os.Setenv(ENV_EXEC_PID, pid)
os.Setenv(ENV_EXEC_CMD, cmdStr)
containerEnvs := getEnvsByPid(pid)
cmd.Env = append(os.Environ(), containerEnvs...)
if err := cmd.Run(); err != nil {
logrus.Errorf("Exec container %s error %v", containerName, err)
}
}
func GetContainerPidByName(containerName string) (string, error) {
dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
configFilePath := dirURL + container.ConfigName
contentBytes, err := ioutil.ReadFile(configFilePath)
if err != nil {
return "", err
}
var containerInfo container.ContainerInfo
if err := json.Unmarshal(contentBytes, &containerInfo); err != nil {
return "", err
}
return containerInfo.Pid, nil
}
func getEnvsByPid(pid string) []string {
path := fmt.Sprintf("/proc/%s/environ", pid)
contentBytes, err := ioutil.ReadFile(path)
if err != nil {
logrus.Errorf("Read file %s error %v", path, err)
return nil
}
//env split by \u0000
envs := strings.Split(string(contentBytes), "\u0000")
return envs
}