-
-
Save agners/1450f8a87d8d35b894f4e18d28bfb1ab to your computer and use it in GitHub Desktop.
Containerisation in 100 Lines of Go Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"os/exec" | |
"syscall" | |
) | |
func main() { | |
if len(os.Args) > 1 { | |
switch os.Args[1] { | |
case "run": | |
parent() | |
case "child": | |
child() | |
default: | |
fmt.Printf("Usage\n\t%s <run | child> executable\n", os.Args[0]) | |
os.Exit(1) | |
} | |
} | |
} | |
func parent() { | |
cmd := exec.Command("/proc/self/exe", append([]string{"child"}, os.Args[2:]...)...) | |
cmd.SysProcAttr = &syscall.SysProcAttr{ | |
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS, | |
} | |
cmd.Stdin = os.Stdin | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
if err := cmd.Run(); err != nil { | |
fmt.Println("ERROR", err) | |
os.Exit(1) | |
} | |
} | |
func child() { | |
must(syscall.Mount("rootfs", "rootfs", "bind", syscall.MS_BIND, "")) | |
must(os.MkdirAll("rootfs/oldrootfs", 0777)) | |
// Also make sure / is mounted privatly (sudo mount --make-rprivate /) | |
must(syscall.PivotRoot("rootfs", "rootfs/oldrootfs")) | |
must(os.Chdir("/")) | |
syscall.Exec(os.Args[2], os.Args[3:], nil) | |
} | |
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