Created
December 14, 2017 05:30
-
-
Save kunalkushwaha/dcc23b31c1d7d6d41c0c5fc51b0afca7 to your computer and use it in GitHub Desktop.
sample code for using containerd.
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 ( | |
| "context" | |
| "fmt" | |
| "log" | |
| "syscall" | |
| "time" | |
| "github.com/containerd/containerd" | |
| "github.com/containerd/containerd/cio" | |
| "github.com/containerd/containerd/namespaces" | |
| "github.com/containerd/containerd/oci" | |
| ) | |
| const ( | |
| address = "/run/containerd/containerd.sock" | |
| alpine = "docker.io/library/alpine:latest" | |
| ) | |
| func main() { | |
| if err := helloContainerd(); err != nil { | |
| log.Fatal(err) | |
| } | |
| } | |
| func helloContainerd() error { | |
| ctx := namespaces.WithNamespace(context.Background(), "demo") | |
| // WithNamespace is a placeholder while we get namespace support in the daemon | |
| client, err := containerd.New(address) | |
| if err != nil { | |
| return err | |
| } | |
| defer client.Close() | |
| log.Printf("pulling image %s...\n", alpine) | |
| // make sure we unpack the image for use after the pull | |
| image, err := client.Pull(ctx, alpine, containerd.WithPullUnpack) | |
| if err != nil { | |
| return err | |
| } | |
| log.Println("finished pulling image...") | |
| id := "hello-containerd1" | |
| container, err := client.NewContainer(ctx, id, containerd.WithNewSpec(oci.WithImageConfig(image), oci.WithProcessArgs("echo", "Hello containerd")), containerd.WithNewSnapshot(id, image)) | |
| if err != nil { | |
| return err | |
| } | |
| defer container.Delete(ctx) | |
| log.Println("created new container...") | |
| // lets get the container's stdio in our current process | |
| task, err := container.NewTask(ctx, cio.Stdio) | |
| if err != nil { | |
| return err | |
| } | |
| defer task.Delete(ctx) | |
| fmt.Printf("container pid %d\n", task.Pid()) | |
| // you can do network namespace setup here or whatever you want without hooks | |
| if err := task.Start(ctx); err != nil { | |
| return err | |
| } | |
| // let it run for 5 seconds and then kill it | |
| go func() { | |
| time.Sleep(5 * time.Second) | |
| log.Println("killing task...") | |
| if err := task.Kill(ctx, syscall.SIGTERM); err != nil { | |
| log.Println(err) | |
| } | |
| }() | |
| status, err := task.Wait(ctx) | |
| if err != nil { | |
| return err | |
| } | |
| fmt.Printf("task exited with status %d\n", status) | |
| // all done | |
| return nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment