containerd.go 5.5 KB

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