Skip to content

Instantly share code, notes, and snippets.

@kunalkushwaha
Created February 26, 2015 11:41
Show Gist options
  • Save kunalkushwaha/8397bb01950355e0e7ca to your computer and use it in GitHub Desktop.
Save kunalkushwaha/8397bb01950355e0e7ca to your computer and use it in GitHub Desktop.
Container management using libcontainer.
package main
import (
"fmt"
"os"
"log"
"syscall"
"github.com/docker/libcontainer"
"github.com/docker/libcontainer/configs"
_ "github.com/docker/libcontainer/devices"
//_ "github.com/docker/libcontainer/mount/nodes"
//_ "github.com/docker/libcontainer/namespaces"
)
func main() {
initArgs := libcontainer.InitArgs(os.Args[0], "/bin/bash")
root, err := libcontainer.New("/home/kunal/container", initArgs)
if err != nil {
log.Fatal(err)
}
fmt.Println(root)
rootfs := "/home/kunal/testcont"
config := &configs.Config{
Rootfs: rootfs,
Capabilities: []string{
"CHOWN",
"DAC_OVERRIDE",
"FSETID",
"FOWNER",
"MKNOD",
"NET_RAW",
"SETGID",
"SETUID",
"SETFCAP",
"SETPCAP",
"NET_BIND_SERVICE",
"SYS_CHROOT",
"KILL",
"AUDIT_WRITE",
},
Namespaces: configs.Namespaces([]configs.Namespace{
{Type: configs.NEWNS},
{Type: configs.NEWUTS},
{Type: configs.NEWIPC},
{Type: configs.NEWPID},
{Type: configs.NEWNET},
}),
Cgroups: &configs.Cgroup{
Name: "test-container",
Parent: "system",
AllowAllDevices: false,
AllowedDevices: configs.DefaultAllowedDevices,
},
Devices: configs.DefaultAutoCreatedDevices,
Hostname: "testing",
Networks: []*configs.Network{
{
Type: "loopback",
Address: "127.0.0.1/0",
Gateway: "localhost",
},
},
Rlimits: []configs.Rlimit{
{
Type: syscall.RLIMIT_NOFILE,
Hard: uint64(1024),
Soft: uint64(1024),
},
},
}
_ = config
// os.Exit(0)
// fmt.Println(config)
// container, err := root.Load("34")
container, err := root.Create("34", config)
if err!= nil {
fmt.Println(err)
os.Exit(1)
}
process := &libcontainer.Process{
Args: []string{"/bin/bash"},
Env: []string{"PATH=/bin"},
User: "daemon",
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
fmt.Println(container)
fmt.Println(" -- conatiner -- ")
fmt.Println(process)
fmt.Println(" -- Process --- ")
err = container.Start(process)
if err != nil {
fmt.Println("Error in Starting container ---")
log.Fatal(err)
os.Exit(1)
}
// wait for the process to finish.
process.Wait()
// destroy the container.
container.Destroy()
// return all the pids for all processes running inside the container.
processes, err := container.Processes()
_ = processes
// get detailed cpu, memory, io, and network statistics for the container and
// it's processes.
stats, err := container.Stats()
fmt.Println(stats)
// pause all processes inside the container.
container.Pause()
// resume all paused processes.
container.Resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment