Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
}
@lizrice

This comment has been minimized.

Copy link
Owner Author

lizrice commented Aug 25, 2016

Note that this expects to find a file system in /home/rootfs

@wmark

This comment has been minimized.

Copy link

wmark commented Aug 26, 2016

-       Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS,
+       Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWUTS |
+                         syscall.CLONE_NEWPID | syscall.CLONE_NEWNS,
+                 Credential:  &syscall.Credential{Uid: 0, Gid: 0},
+                 UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getuid(), Size: 1}},
+                 GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getgid(), Size: 1}},
@mikeschinkel

This comment has been minimized.

Copy link

mikeschinkel commented Jul 7, 2018

Hi @lizrice,

Watching your presentation on video and following along I have run into an issue with none of syscall.CLONE_NEWUTS syscall.CLONE_NEWPID or syscall.CLONE_NEWNS being found. I am a Go newbie, using Go 1.10.3 and JetBrains GoLand. What am I missing, or has Go changed since your presentation?

Thanks in advance for your reply.

@mugli

This comment has been minimized.

Copy link

mugli commented Sep 9, 2018

@mikeschinkel Are you using Linux as your development machine?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.