Skip to content

Instantly share code, notes, and snippets.

@dbafromthecold
Last active May 15, 2021 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbafromthecold/139e93907f7eab45a20944d0eaffeb3a to your computer and use it in GitHub Desktop.
Save dbafromthecold/139e93907f7eab45a20944d0eaffeb3a to your computer and use it in GitHub Desktop.
SqlContainerFromScratch
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"syscall"
)
// go run main.go run <cmd> <args>
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("sqlcontainer1")))
must(syscall.Chroot("/home/dbafromthecold/sqlcontainer1"))
must(os.Chdir("/"))
must(syscall.Mount("proc", "proc", "proc", 0, ""))
must(cmd.Run())
must(syscall.Unmount("proc", 0))
}
func cg() {
cgroups := "/sys/fs/cgroup/"
memory := filepath.Join(cgroups, "memory")
os.Mkdir(filepath.Join(memory, "sqlcontainer1"), 0755)
must(ioutil.WriteFile(filepath.Join(memory, "sqlcontainer1/memory.limit_in_bytes"), []byte("2147483648"), 0700))
cpu := filepath.Join(cgroups, "cpu,cpuacct")
os.Mkdir(filepath.Join(cpu, "sqlcontainer1"), 0755)
must(ioutil.WriteFile(filepath.Join(cpu, "sqlcontainer1/cpu.cfs_quota_us"), []byte("200000"), 0700))
// Removes the new cgroup in place after the container exits
must(ioutil.WriteFile(filepath.Join(memory, "sqlcontainer1/notify_on_release"), []byte("1"), 0700))
must(ioutil.WriteFile(filepath.Join(memory, "sqlcontainer1/cgroup.procs"), []byte(strconv.Itoa(os.Getpid())), 0700))
must(ioutil.WriteFile(filepath.Join(cpu, "sqlcontainer1/notify_on_release"), []byte("1"), 0700))
must(ioutil.WriteFile(filepath.Join(cpu, "sqlcontainer1/cgroup.procs"), []byte(strconv.Itoa(os.Getpid())), 0700))
}
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