make container

https://github.com/lizrice/containers-from-scratch





package main



import (
“fmt”
“io/ioutil”
“os”
“os/exec”
“path/filepath”
“strconv”
“syscall”
)



// go run main.go run
func main() {
switch os.Args[1] {
case "run":
run()
case "child":
child()
default:
panic("help")
}
}



func run() {
fmt.Printf(“Running %v \n”, os.Args[2:])



cmd := exec.Command("/proc/self/exe", append([]string{"child"}, os.Args[2:]...)...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS,
Unshareflags: syscall.CLONE_NEWNS,
}

must(cmd.Run()) }


func child() {
fmt.Printf(“Running %v \n”, os.Args[2:])



cg()

cmd := exec.Command(os.Args[2], os.Args[3:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

must(syscall.Sethostname([]byte("container")))
must(syscall.Chroot("/home/liz/ubuntufs"))
must(os.Chdir("/"))
must(syscall.Mount("proc", "proc", "proc", 0, ""))
must(syscall.Mount("thing", "mytemp", "tmpfs", 0, ""))

must(cmd.Run())

must(syscall.Unmount("proc", 0))
must(syscall.Unmount("thing", 0)) }


func cg() {
cgroups := “/sys/fs/cgroup/”
pids := filepath.Join(cgroups, “pids”)
os.Mkdir(filepath.Join(pids, “liz”), 0755)
must(ioutil.WriteFile(filepath.Join(pids, “liz/pids.max”), []byte(“20”), 0700))
// Removes the new cgroup in place after the container exits
must(ioutil.WriteFile(filepath.Join(pids, “liz/notify_on_release”), []byte(“1”), 0700))
must(ioutil.WriteFile(filepath.Join(pids, “liz/cgroup.procs”), []byte(strconv.Itoa(os.Getpid())), 0700))
}



func must(err error) {
if err != nil {
panic(err)
}
}



https://www.bilibili.com/video/av201598179/



https://www.bilibili.com/video/av15302453/



https://zhuanlan.zhihu.com/p/137395088



https://github.com/lizrice/containers-from-scratch



https://github.com/jizg/containers-from-scratch



https://gotoams.nl/2018/sessions/429/containers-from-scratch



https://man7.org/linux/man-pages/man7/namespaces.7.html



https://man7.org/linux/man-pages/man7/cgroups.7.html



https://segmentfault.com/a/1190000006245007


Category docker