containerd.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/docker/docker/api/types"
  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, runtime types.Runtime) (*Executor, error) {
  24. e := &Executor{
  25. rootDir: rootDir,
  26. exitHandler: exitHandler,
  27. runtime: runtime,
  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. runtime types.Runtime
  43. mu sync.Mutex // Guards plugins map
  44. plugins map[string]*c8dPlugin
  45. }
  46. type c8dPlugin struct {
  47. log *logrus.Entry
  48. ctr libcontainerdtypes.Container
  49. tsk libcontainerdtypes.Task
  50. }
  51. // deleteTaskAndContainer deletes plugin task and then plugin container from containerd
  52. func (p c8dPlugin) deleteTaskAndContainer(ctx context.Context) {
  53. if p.tsk != nil {
  54. if _, err := p.tsk.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
  55. p.log.WithError(err).Error("failed to delete plugin task from containerd")
  56. }
  57. }
  58. if p.ctr != nil {
  59. if err := p.ctr.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
  60. p.log.WithError(err).Error("failed to delete plugin container from containerd")
  61. }
  62. }
  63. }
  64. // Create creates a new container
  65. func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
  66. ctx := context.Background()
  67. log := logrus.WithField("plugin", id)
  68. ctr, err := e.client.NewContainer(ctx, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
  69. if err != nil {
  70. ctr2, err2 := e.client.LoadContainer(ctx, id)
  71. if err2 != nil {
  72. if !errdefs.IsNotFound(err2) {
  73. log.WithError(err2).Warn("Received an error while attempting to load containerd container for plugin")
  74. }
  75. } else {
  76. status := containerd.Unknown
  77. t, err2 := ctr2.Task(ctx)
  78. if err2 != nil {
  79. if !errdefs.IsNotFound(err2) {
  80. log.WithError(err2).Warn("Received an error while attempting to load containerd task for plugin")
  81. }
  82. } else {
  83. s, err2 := t.Status(ctx)
  84. if err2 != nil {
  85. log.WithError(err2).Warn("Received an error while attempting to read plugin status")
  86. } else {
  87. status = s.Status
  88. }
  89. }
  90. if status != containerd.Running && status != containerd.Unknown {
  91. if err2 := ctr2.Delete(ctx); err2 != nil && !errdefs.IsNotFound(err2) {
  92. log.WithError(err2).Error("Error cleaning up containerd container")
  93. }
  94. ctr, err = e.client.NewContainer(ctx, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
  95. }
  96. }
  97. if err != nil {
  98. return errors.Wrap(err, "error creating containerd container")
  99. }
  100. }
  101. p := c8dPlugin{log: log, ctr: ctr}
  102. p.tsk, err = ctr.Start(ctx, "", false, attachStreamsFunc(stdout, stderr))
  103. if err != nil {
  104. p.deleteTaskAndContainer(ctx)
  105. return err
  106. }
  107. e.mu.Lock()
  108. defer e.mu.Unlock()
  109. e.plugins[id] = &p
  110. return nil
  111. }
  112. // Restore restores a container
  113. func (e *Executor) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
  114. ctx := context.Background()
  115. p := c8dPlugin{log: logrus.WithField("plugin", id)}
  116. ctr, err := e.client.LoadContainer(ctx, id)
  117. if err != nil {
  118. if errdefs.IsNotFound(err) {
  119. return false, nil
  120. }
  121. return false, err
  122. }
  123. p.tsk, err = ctr.AttachTask(ctx, attachStreamsFunc(stdout, stderr))
  124. if err != nil {
  125. if errdefs.IsNotFound(err) {
  126. p.deleteTaskAndContainer(ctx)
  127. return false, nil
  128. }
  129. return false, err
  130. }
  131. s, err := p.tsk.Status(ctx)
  132. if err != nil {
  133. if errdefs.IsNotFound(err) {
  134. // Task vanished after attaching?
  135. p.tsk = nil
  136. p.deleteTaskAndContainer(ctx)
  137. return false, nil
  138. }
  139. return false, err
  140. }
  141. if s.Status == containerd.Stopped {
  142. p.deleteTaskAndContainer(ctx)
  143. return false, nil
  144. }
  145. e.mu.Lock()
  146. defer e.mu.Unlock()
  147. e.plugins[id] = &p
  148. return true, nil
  149. }
  150. // IsRunning returns if the container with the given id is running
  151. func (e *Executor) IsRunning(id string) (bool, error) {
  152. e.mu.Lock()
  153. p := e.plugins[id]
  154. e.mu.Unlock()
  155. if p == nil {
  156. return false, errdefs.NotFound(fmt.Errorf("unknown plugin %q", id))
  157. }
  158. status, err := p.tsk.Status(context.Background())
  159. return status.Status == containerd.Running, err
  160. }
  161. // Signal sends the specified signal to the container
  162. func (e *Executor) Signal(id string, signal syscall.Signal) error {
  163. e.mu.Lock()
  164. p := e.plugins[id]
  165. e.mu.Unlock()
  166. if p == nil {
  167. return errdefs.NotFound(fmt.Errorf("unknown plugin %q", id))
  168. }
  169. return p.tsk.Kill(context.Background(), signal)
  170. }
  171. // ProcessEvent handles events from containerd
  172. // All events are ignored except the exit event, which is sent of to the stored handler
  173. func (e *Executor) ProcessEvent(id string, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
  174. switch et {
  175. case libcontainerdtypes.EventExit:
  176. e.mu.Lock()
  177. p := e.plugins[id]
  178. e.mu.Unlock()
  179. if p == nil {
  180. logrus.WithField("id", id).Warn("Received exit event for an unknown plugin")
  181. } else {
  182. p.deleteTaskAndContainer(context.Background())
  183. }
  184. return e.exitHandler.HandleExitEvent(ei.ContainerID)
  185. }
  186. return nil
  187. }
  188. type rio struct {
  189. cio.IO
  190. wg sync.WaitGroup
  191. }
  192. func (c *rio) Wait() {
  193. c.wg.Wait()
  194. c.IO.Wait()
  195. }
  196. func attachStreamsFunc(stdout, stderr io.WriteCloser) libcontainerdtypes.StdioCallback {
  197. return func(iop *cio.DirectIO) (cio.IO, error) {
  198. if iop.Stdin != nil {
  199. iop.Stdin.Close()
  200. // closing stdin shouldn't be needed here, it should never be open
  201. panic("plugin stdin shouldn't have been created!")
  202. }
  203. rio := &rio{IO: iop}
  204. rio.wg.Add(2)
  205. go func() {
  206. io.Copy(stdout, iop.Stdout)
  207. stdout.Close()
  208. rio.wg.Done()
  209. }()
  210. go func() {
  211. io.Copy(stderr, iop.Stderr)
  212. stderr.Close()
  213. rio.wg.Done()
  214. }()
  215. return rio, nil
  216. }
  217. }