-
Notifications
You must be signed in to change notification settings - Fork 51
/
run.go
89 lines (80 loc) · 2.26 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
86
87
88
89
package main
import (
"go-docker/network"
"os"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"go-docker/cgroups"
"go-docker/cgroups/subsystem"
"go-docker/container"
)
func Run(cmdArray []string, tty bool, res *subsystem.ResourceConfig, containerName, imageName, volume, net string, envs, ports []string) {
containerID := container.GenContainerID(10)
if containerName == "" {
containerName = containerID
}
parent, writePipe := container.NewParentProcess(tty, volume, containerName, imageName, envs)
if parent == nil {
logrus.Errorf("failed to new parent process")
return
}
if err := parent.Start(); err != nil {
logrus.Errorf("parent start failed, err: %v", err)
return
}
// 记录容器信息
err := container.RecordContainerInfo(parent.Process.Pid, cmdArray, containerName, containerID)
if err != nil {
logrus.Errorf("record container info, err: %v", err)
}
// 添加资源限制
cgroupMananger := cgroups.NewCGroupManager("go-docker")
// 删除资源限制
defer cgroupMananger.Destroy()
// 设置资源限制
cgroupMananger.Set(res)
// 将容器进程,加入到各个subsystem挂载对应的cgroup中
cgroupMananger.Apply(parent.Process.Pid)
// 设置网络
if net != "" {
// 初始化容器网络
err = network.Init()
if err != nil {
logrus.Errorf("network init failed, err: %v", err)
return
}
containerInfo := &container.ContainerInfo{
Id: containerID,
Pid: strconv.Itoa(parent.Process.Pid),
Name: containerName,
PortMapping: ports,
}
if err := network.Connect(net, containerInfo); err != nil {
logrus.Errorf("connect network, err: %v", err)
return
}
}
// 设置初始化命令
sendInitCommand(cmdArray, writePipe)
if tty {
// 等待父进程结束
err := parent.Wait()
if err != nil {
logrus.Errorf("parent wait, err: %v", err)
}
// 删除容器工作空间
err = container.DeleteWorkSpace(containerName, volume)
if err != nil {
logrus.Errorf("delete work space, err: %v", err)
}
// 删除容器信息
container.DeleteContainerInfo(containerName)
}
}
func sendInitCommand(comArray []string, writePipe *os.File) {
command := strings.Join(comArray, " ")
logrus.Infof("command all is %s", command)
_, _ = writePipe.WriteString(command)
_ = writePipe.Close()
}