-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
91 lines (77 loc) · 1.96 KB
/
main.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
90
91
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path"
"syscall"
)
func main() {
switch os.Args[1] {
case "run":
parent()
case "child":
child()
default:
panic("what should I do")
}
}
func parent() {
cmd := exec.Command(os.Args[0], append([]string{"child"}, os.Args[2:]...)...)
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS | syscall.CLONE_NEWNET,
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
panic(fmt.Sprintf("start parent err: %v", err))
}
log.Printf("container PID: %d", cmd.Process.Pid)
// set bridge and veth pair for container.
if err := putIface(cmd.Process.Pid); err != nil {
panic(fmt.Sprintf("putIface err: %v", err))
}
if err := cmd.Wait(); err != nil {
panic(fmt.Sprintf("wait parent err: %v\n", err))
}
}
func child() {
fmt.Printf("start child......, pid %v\n", syscall.Getpid())
cmd := exec.Command(os.Args[2], os.Args[3:]...)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
// setup environment for container.
setup()
if err := cmd.Run(); err != nil {
panic(fmt.Sprintf("child panic: %v", err))
}
}
func setup() {
if err := syscall.Sethostname([]byte("container")); err != nil {
panic(fmt.Sprintf("Sethostname: %v", err))
}
pwd, err := os.Getwd()
if err != nil {
panic(fmt.Sprintf("get pwd err: %v\n", err))
}
target := path.Join(pwd, "rootfs")
if err := syscall.Chroot(target); err != nil {
panic(fmt.Sprintf("chroot err: %v\n", err))
}
if err := os.Chdir("/"); err != nil {
panic(fmt.Sprintf("chdir err: %v\n", err))
}
if err := syscall.Mount("proc", "proc", "proc", 0, ""); err != nil {
panic(fmt.Sprintf("failed to mount proc to %s: %v", target, err))
}
lnk, err := waitForIface()
if err != nil {
panic(fmt.Sprintf("waitForIface err: %v", err))
}
if err := setupIface(lnk); err != nil {
panic(fmt.Sprintf("setupIface err: %v", err))
}
}