containerd.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package containerd // import "github.com/docker/docker/plugin/executor/containerd"
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "sync"
  7. "syscall"
  8. "github.com/containerd/containerd"
  9. "github.com/containerd/containerd/cio"
  10. "github.com/containerd/log"
  11. "github.com/docker/docker/errdefs"
  12. "github.com/docker/docker/libcontainerd"
  13. libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
  14. specs "github.com/opencontainers/runtime-spec/specs-go"
  15. "github.com/pkg/errors"
  16. )
  17. // ExitHandler represents an object that is called when the exit event is received from containerd
  18. type ExitHandler interface {
  19. HandleExitEvent(id string) error
  20. }
  21. // New creates a new containerd plugin executor
  22. func New(ctx context.Context, rootDir string, cli *containerd.Client, ns string, exitHandler ExitHandler, shim string, shimOpts interface{}) (*Executor, error) {
  23. e := &Executor{
  24. rootDir: rootDir,
  25. exitHandler: exitHandler,
  26. shim: shim,
  27. shimOpts: shimOpts,
  28. plugins: make(map[string]*c8dPlugin),
  29. }
  30. client, err := libcontainerd.NewClient(ctx, cli, rootDir, ns, e)
  31. if err != nil {
  32. return nil, errors.Wrap(err, "error creating containerd exec client")
  33. }
  34. e.client = client
  35. return e, nil
  36. }
  37. // Executor is the containerd client implementation of a plugin executor
  38. type Executor struct {
  39. rootDir string
  40. client libcontainerdtypes.Client
  41. exitHandler ExitHandler
  42. shim string
  43. shimOpts interface{}
  44. mu sync.Mutex // Guards plugins map
  45. plugins map[string]*c8dPlugin
  46. }
  47. type c8dPlugin struct {
  48. log *log.Entry
  49. ctr libcontainerdtypes.Container
  50. tsk libcontainerdtypes.Task
  51. }
  52. // deleteTaskAndContainer deletes plugin task and then plugin container from containerd
  53. func (p c8dPlugin) deleteTaskAndContainer(ctx context.Context) {
  54. if p.tsk != nil {
  55. if err := p.tsk.ForceDelete(ctx); err != nil && !errdefs.IsNotFound(err) {
  56. p.log.WithError(err).Error("failed to delete plugin task from containerd")
  57. }
  58. }
  59. if p.ctr != nil {
  60. if err := p.ctr.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
  61. p.log.WithError(err).Error("failed to delete plugin container from containerd")
  62. }
  63. }
  64. }
  65. // Create creates a new container
  66. func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
  67. ctx := context.Background()
  68. ctr, err := libcontainerd.ReplaceContainer(ctx, e.client, id, &spec, e.shim, e.shimOpts)
  69. if err != nil {
  70. return errors.Wrap(err, "error creating containerd container for plugin")
  71. }
  72. p := c8dPlugin{log: log.G(ctx).WithField("plugin", id), ctr: ctr}
  73. p.tsk, err = ctr.NewTask(ctx, "", false, attachStreamsFunc(stdout, stderr))
  74. if err != nil {
  75. p.deleteTaskAndContainer(ctx)
  76. return err
  77. }
  78. if err := p.tsk.Start(ctx); err != nil {
  79. p.deleteTaskAndContainer(ctx)
  80. return err
  81. }
  82. e.mu.Lock()
  83. defer e.mu.Unlock()
  84. e.plugins[id] = &p
  85. return nil
  86. }
  87. // Restore restores a container
  88. func (e *Executor) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
  89. ctx := context.Background()
  90. p := c8dPlugin{log: log.G(ctx).WithField("plugin", id)}
  91. ctr, err := e.client.LoadContainer(ctx, id)
  92. if err != nil {
  93. if errdefs.IsNotFound(err) {
  94. return false, nil
  95. }
  96. return false, err
  97. }
  98. p.tsk, err = ctr.AttachTask(ctx, attachStreamsFunc(stdout, stderr))
  99. if err != nil {
  100. if errdefs.IsNotFound(err) {
  101. p.deleteTaskAndContainer(ctx)
  102. return false, nil
  103. }
  104. return false, err
  105. }
  106. s, err := p.tsk.Status(ctx)
  107. if err != nil {
  108. if errdefs.IsNotFound(err) {
  109. // Task vanished after attaching?
  110. p.tsk = nil
  111. p.deleteTaskAndContainer(ctx)
  112. return false, nil
  113. }
  114. return false, err
  115. }
  116. if s.Status == containerd.Stopped {
  117. p.deleteTaskAndContainer(ctx)
  118. return false, nil
  119. }
  120. e.mu.Lock()
  121. defer e.mu.Unlock()
  122. e.plugins[id] = &p
  123. return true, nil
  124. }
  125. // IsRunning returns if the container with the given id is running
  126. func (e *Executor) IsRunning(id string) (bool, error) {
  127. e.mu.Lock()
  128. p := e.plugins[id]
  129. e.mu.Unlock()
  130. if p == nil {
  131. return false, errdefs.NotFound(fmt.Errorf("unknown plugin %q", id))
  132. }
  133. status, err := p.tsk.Status(context.Background())
  134. return status.Status == containerd.Running, err
  135. }
  136. // Signal sends the specified signal to the container
  137. func (e *Executor) Signal(id string, signal syscall.Signal) error {
  138. e.mu.Lock()
  139. p := e.plugins[id]
  140. e.mu.Unlock()
  141. if p == nil {
  142. return errdefs.NotFound(fmt.Errorf("unknown plugin %q", id))
  143. }
  144. return p.tsk.Kill(context.Background(), signal)
  145. }
  146. // ProcessEvent handles events from containerd
  147. // All events are ignored except the exit event, which is sent of to the stored handler
  148. func (e *Executor) ProcessEvent(id string, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
  149. switch et {
  150. case libcontainerdtypes.EventExit:
  151. e.mu.Lock()
  152. p := e.plugins[id]
  153. e.mu.Unlock()
  154. if p == nil {
  155. log.G(context.TODO()).WithField("id", id).Warn("Received exit event for an unknown plugin")
  156. } else {
  157. p.deleteTaskAndContainer(context.Background())
  158. }
  159. return e.exitHandler.HandleExitEvent(ei.ContainerID)
  160. }
  161. return nil
  162. }
  163. type rio struct {
  164. cio.IO
  165. wg sync.WaitGroup
  166. }
  167. func (c *rio) Wait() {
  168. c.wg.Wait()
  169. c.IO.Wait()
  170. }
  171. func attachStreamsFunc(stdout, stderr io.WriteCloser) libcontainerdtypes.StdioCallback {
  172. return func(iop *cio.DirectIO) (cio.IO, error) {
  173. if iop.Stdin != nil {
  174. iop.Stdin.Close()
  175. // closing stdin shouldn't be needed here, it should never be open
  176. panic("plugin stdin shouldn't have been created!")
  177. }
  178. rio := &rio{IO: iop}
  179. rio.wg.Add(2)
  180. go func() {
  181. io.Copy(stdout, iop.Stdout)
  182. stdout.Close()
  183. rio.wg.Done()
  184. }()
  185. go func() {
  186. io.Copy(stderr, iop.Stderr)
  187. stderr.Close()
  188. rio.wg.Done()
  189. }()
  190. return rio, nil
  191. }
  192. }