Guest User

Untitled

a guest
Nov 17th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "context"
  5. "syscall"
  6. "time"
  7.  
  8. "github.com/Sirupsen/logrus"
  9. "github.com/containerd/containerd"
  10. "github.com/containerd/containerd/namespaces"
  11. )
  12.  
  13. const (
  14. address = "/run/containerd/containerd.sock"
  15. redis = "docker.io/library/redis:alpine"
  16. )
  17.  
  18. func main() {
  19. ctx := context.Background()
  20. // name your own namespace
  21. ctx = namespaces.WithNamespace(ctx, "mystuff")
  22. if err := runRedis(ctx, "redis"); err != nil {
  23. logrus.Error(err)
  24. }
  25. }
  26.  
  27. func runRedis(ctx context.Context, id string) error {
  28. client, err := containerd.New(address)
  29. if err != nil {
  30. return err
  31. }
  32. defer client.Close()
  33.  
  34. image, err := client.Pull(ctx, redis, containerd.WithPullUnpack)
  35. if err != nil {
  36. return err
  37. }
  38. container, err := client.NewContainer(
  39. ctx,
  40. id,
  41. containerd.WithNewSpec(containerd.WithImageConfig(image)),
  42. containerd.WithNewSnapshot(id, image),
  43. )
  44. if err != nil {
  45. return err
  46. }
  47. // delete the snapshot with the container
  48. defer container.Delete(ctx, containerd.WithSnapshotCleanup)
  49.  
  50. // use our stdio for the container's stdio
  51. task, err := container.NewTask(ctx, containerd.Stdio)
  52. if err != nil {
  53. return err
  54. }
  55. // get the exit channel
  56. exit, err := task.Wait(ctx)
  57. if err != nil {
  58. return err
  59. }
  60. defer task.Delete(ctx)
  61.  
  62. // start the task
  63. if err := task.Start(ctx); err != nil {
  64. return err
  65. }
  66. // for the example run for 3 sec then kill the redis container
  67. time.Sleep(3 * time.Second)
  68. if err := task.Kill(ctx, syscall.SIGTERM); err != nil {
  69. return err
  70. }
  71. // wait for the task to exit
  72. <-exit
  73. return nil
  74. }
Add Comment
Please, Sign In to add comment