Skip to content

Instantly share code, notes, and snippets.

@panda1100
Forked from lizrice/main.go
Created October 29, 2021 08:54
Show Gist options
  • Save panda1100/7e5282715ee8c303b7bb941e90f778f4 to your computer and use it in GitHub Desktop.
Save panda1100/7e5282715ee8c303b7bb941e90f778f4 to your computer and use it in GitHub Desktop.
Container from scratch
package main
// @lizrice, mostly copied from @doctor_julz: https://gist.github.com/julz/c0017fa7a40de0543001
import (
"fmt"
"os"
"os/exec"
"syscall"
)
// docker run <container> command args
// go run main.go run command args
func main() {
switch os.Args[1] {
case "run":
run()
case "child":
child()
default:
panic("what?")
}
}
func run() {
cmd := exec.Command("/proc/self/exe", append([]string{"child"}, os.Args[2:]...)...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS,
}
must(cmd.Run())
}
func child() {
fmt.Printf("running %v as pid %d\n", os.Args[2:], os.Getpid())
cmd := exec.Command(os.Args[2], os.Args[3:]...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
must(syscall.Chroot("/home/rootfs"))
must(os.Chdir("/"))
must(syscall.Mount("proc", "proc", "proc", 0, ""))
must(cmd.Run())
}
func must(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment