client.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. package remote // import "github.com/docker/docker/libcontainerd/remote"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. "github.com/containerd/containerd"
  15. apievents "github.com/containerd/containerd/api/events"
  16. "github.com/containerd/containerd/api/types"
  17. "github.com/containerd/containerd/archive"
  18. "github.com/containerd/containerd/cio"
  19. "github.com/containerd/containerd/content"
  20. containerderrors "github.com/containerd/containerd/errdefs"
  21. "github.com/containerd/containerd/events"
  22. "github.com/containerd/containerd/images"
  23. v2runcoptions "github.com/containerd/containerd/runtime/v2/runc/options"
  24. "github.com/containerd/typeurl"
  25. "github.com/docker/docker/errdefs"
  26. "github.com/docker/docker/libcontainerd/queue"
  27. libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
  28. "github.com/docker/docker/pkg/ioutils"
  29. v1 "github.com/opencontainers/image-spec/specs-go/v1"
  30. specs "github.com/opencontainers/runtime-spec/specs-go"
  31. "github.com/pkg/errors"
  32. "github.com/sirupsen/logrus"
  33. "google.golang.org/grpc/codes"
  34. "google.golang.org/grpc/status"
  35. )
  36. // DockerContainerBundlePath is the label key pointing to the container's bundle path
  37. const DockerContainerBundlePath = "com.docker/engine.bundle.path"
  38. type client struct {
  39. client *containerd.Client
  40. stateDir string
  41. logger *logrus.Entry
  42. ns string
  43. backend libcontainerdtypes.Backend
  44. eventQ queue.Queue
  45. }
  46. type container struct {
  47. client *client
  48. c8dCtr containerd.Container
  49. v2runcoptions *v2runcoptions.Options
  50. }
  51. type task struct {
  52. containerd.Task
  53. ctr *container
  54. }
  55. type process struct {
  56. containerd.Process
  57. }
  58. // NewClient creates a new libcontainerd client from a containerd client
  59. func NewClient(ctx context.Context, cli *containerd.Client, stateDir, ns string, b libcontainerdtypes.Backend) (libcontainerdtypes.Client, error) {
  60. c := &client{
  61. client: cli,
  62. stateDir: stateDir,
  63. logger: logrus.WithField("module", "libcontainerd").WithField("namespace", ns),
  64. ns: ns,
  65. backend: b,
  66. }
  67. go c.processEventStream(ctx, ns)
  68. return c, nil
  69. }
  70. func (c *client) Version(ctx context.Context) (containerd.Version, error) {
  71. return c.client.Version(ctx)
  72. }
  73. func (c *container) newTask(t containerd.Task) *task {
  74. return &task{Task: t, ctr: c}
  75. }
  76. func (c *container) AttachTask(ctx context.Context, attachStdio libcontainerdtypes.StdioCallback) (_ libcontainerdtypes.Task, err error) {
  77. var dio *cio.DirectIO
  78. defer func() {
  79. if err != nil && dio != nil {
  80. dio.Cancel()
  81. dio.Close()
  82. }
  83. }()
  84. attachIO := func(fifos *cio.FIFOSet) (cio.IO, error) {
  85. // dio must be assigned to the previously defined dio for the defer above
  86. // to handle cleanup
  87. dio, err = c.client.newDirectIO(ctx, fifos)
  88. if err != nil {
  89. return nil, err
  90. }
  91. return attachStdio(dio)
  92. }
  93. t, err := c.c8dCtr.Task(ctx, attachIO)
  94. if err != nil {
  95. return nil, errors.Wrap(wrapError(err), "error getting containerd task for container")
  96. }
  97. return c.newTask(t), nil
  98. }
  99. func (c *client) NewContainer(ctx context.Context, id string, ociSpec *specs.Spec, shim string, runtimeOptions interface{}, opts ...containerd.NewContainerOpts) (libcontainerdtypes.Container, error) {
  100. bdir := c.bundleDir(id)
  101. c.logger.WithField("bundle", bdir).WithField("root", ociSpec.Root.Path).Debug("bundle dir created")
  102. newOpts := []containerd.NewContainerOpts{
  103. containerd.WithSpec(ociSpec),
  104. containerd.WithRuntime(shim, runtimeOptions),
  105. WithBundle(bdir, ociSpec),
  106. }
  107. opts = append(opts, newOpts...)
  108. ctr, err := c.client.NewContainer(ctx, id, opts...)
  109. if err != nil {
  110. if containerderrors.IsAlreadyExists(err) {
  111. return nil, errors.WithStack(errdefs.Conflict(errors.New("id already in use")))
  112. }
  113. return nil, wrapError(err)
  114. }
  115. created := container{
  116. client: c,
  117. c8dCtr: ctr,
  118. }
  119. if x, ok := runtimeOptions.(*v2runcoptions.Options); ok {
  120. created.v2runcoptions = x
  121. }
  122. return &created, nil
  123. }
  124. // Start create and start a task for the specified containerd id
  125. func (c *container) Start(ctx context.Context, checkpointDir string, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (libcontainerdtypes.Task, error) {
  126. var (
  127. cp *types.Descriptor
  128. t containerd.Task
  129. rio cio.IO
  130. stdinCloseSync = make(chan containerd.Process, 1)
  131. )
  132. if checkpointDir != "" {
  133. // write checkpoint to the content store
  134. tar := archive.Diff(ctx, "", checkpointDir)
  135. cp, err := c.client.writeContent(ctx, images.MediaTypeContainerd1Checkpoint, checkpointDir, tar)
  136. // remove the checkpoint when we're done
  137. defer func() {
  138. if cp != nil {
  139. err := c.client.client.ContentStore().Delete(ctx, cp.Digest)
  140. if err != nil {
  141. c.client.logger.WithError(err).WithFields(logrus.Fields{
  142. "ref": checkpointDir,
  143. "digest": cp.Digest,
  144. }).Warnf("failed to delete temporary checkpoint entry")
  145. }
  146. }
  147. }()
  148. if err := tar.Close(); err != nil {
  149. return nil, errors.Wrap(err, "failed to close checkpoint tar stream")
  150. }
  151. if err != nil {
  152. return nil, errors.Wrapf(err, "failed to upload checkpoint to containerd")
  153. }
  154. }
  155. // Optimization: assume the relevant metadata has not changed in the
  156. // moment since the container was created. Elide redundant RPC requests
  157. // to refresh the metadata separately for spec and labels.
  158. md, err := c.c8dCtr.Info(ctx, containerd.WithoutRefreshedMetadata)
  159. if err != nil {
  160. return nil, errors.Wrap(err, "failed to retrieve metadata")
  161. }
  162. bundle := md.Labels[DockerContainerBundlePath]
  163. var spec specs.Spec
  164. if err := json.Unmarshal(md.Spec.GetValue(), &spec); err != nil {
  165. return nil, errors.Wrap(err, "failed to retrieve spec")
  166. }
  167. uid, gid := getSpecUser(&spec)
  168. taskOpts := []containerd.NewTaskOpts{
  169. func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
  170. info.Checkpoint = cp
  171. return nil
  172. },
  173. }
  174. if runtime.GOOS != "windows" {
  175. taskOpts = append(taskOpts, func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
  176. if c.v2runcoptions != nil {
  177. opts := *c.v2runcoptions
  178. opts.IoUid = uint32(uid)
  179. opts.IoGid = uint32(gid)
  180. info.Options = &opts
  181. }
  182. return nil
  183. })
  184. } else {
  185. taskOpts = append(taskOpts, withLogLevel(c.client.logger.Level))
  186. }
  187. t, err = c.c8dCtr.NewTask(ctx,
  188. func(id string) (cio.IO, error) {
  189. fifos := newFIFOSet(bundle, id, withStdin, spec.Process.Terminal)
  190. rio, err = c.createIO(fifos, stdinCloseSync, attachStdio)
  191. return rio, err
  192. },
  193. taskOpts...,
  194. )
  195. if err != nil {
  196. close(stdinCloseSync)
  197. if rio != nil {
  198. rio.Cancel()
  199. rio.Close()
  200. }
  201. return nil, errors.Wrap(wrapError(err), "failed to create task for container")
  202. }
  203. // Signal c.createIO that it can call CloseIO
  204. stdinCloseSync <- t
  205. if err := t.Start(ctx); err != nil {
  206. // Only Stopped tasks can be deleted. Created tasks have to be
  207. // killed first, to transition them to Stopped.
  208. if _, err := t.Delete(ctx, containerd.WithProcessKill); err != nil {
  209. c.client.logger.WithError(err).WithField("container", c.c8dCtr.ID()).
  210. Error("failed to delete task after fail start")
  211. }
  212. return nil, wrapError(err)
  213. }
  214. return c.newTask(t), nil
  215. }
  216. // Exec creates exec process.
  217. //
  218. // The containerd client calls Exec to register the exec config in the shim side.
  219. // When the client calls Start, the shim will create stdin fifo if needs. But
  220. // for the container main process, the stdin fifo will be created in Create not
  221. // the Start call. stdinCloseSync channel should be closed after Start exec
  222. // process.
  223. func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (libcontainerdtypes.Process, error) {
  224. var (
  225. p containerd.Process
  226. rio cio.IO
  227. stdinCloseSync = make(chan containerd.Process, 1)
  228. )
  229. // Optimization: assume the DockerContainerBundlePath label has not been
  230. // updated since the container metadata was last loaded/refreshed.
  231. md, err := t.ctr.c8dCtr.Info(ctx, containerd.WithoutRefreshedMetadata)
  232. if err != nil {
  233. return nil, wrapError(err)
  234. }
  235. fifos := newFIFOSet(md.Labels[DockerContainerBundlePath], processID, withStdin, spec.Terminal)
  236. defer func() {
  237. if err != nil {
  238. if rio != nil {
  239. rio.Cancel()
  240. rio.Close()
  241. }
  242. }
  243. }()
  244. p, err = t.Task.Exec(ctx, processID, spec, func(id string) (cio.IO, error) {
  245. rio, err = t.ctr.createIO(fifos, stdinCloseSync, attachStdio)
  246. return rio, err
  247. })
  248. if err != nil {
  249. close(stdinCloseSync)
  250. if containerderrors.IsAlreadyExists(err) {
  251. return nil, errors.WithStack(errdefs.Conflict(errors.New("id already in use")))
  252. }
  253. return nil, wrapError(err)
  254. }
  255. // Signal c.createIO that it can call CloseIO
  256. //
  257. // the stdin of exec process will be created after p.Start in containerd
  258. defer func() { stdinCloseSync <- p }()
  259. if err = p.Start(ctx); err != nil {
  260. // use new context for cleanup because old one may be cancelled by user, but leave a timeout to make sure
  261. // we are not waiting forever if containerd is unresponsive or to work around fifo cancelling issues in
  262. // older containerd-shim
  263. ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
  264. defer cancel()
  265. p.Delete(ctx)
  266. return nil, wrapError(err)
  267. }
  268. return process{p}, nil
  269. }
  270. func (t *task) Kill(ctx context.Context, signal syscall.Signal) error {
  271. return wrapError(t.Task.Kill(ctx, signal))
  272. }
  273. func (p process) Kill(ctx context.Context, signal syscall.Signal) error {
  274. return wrapError(p.Process.Kill(ctx, signal))
  275. }
  276. func (t *task) Pause(ctx context.Context) error {
  277. return wrapError(t.Task.Pause(ctx))
  278. }
  279. func (t *task) Resume(ctx context.Context) error {
  280. return wrapError(t.Task.Resume(ctx))
  281. }
  282. func (t *task) Stats(ctx context.Context) (*libcontainerdtypes.Stats, error) {
  283. m, err := t.Metrics(ctx)
  284. if err != nil {
  285. return nil, err
  286. }
  287. v, err := typeurl.UnmarshalAny(m.Data)
  288. if err != nil {
  289. return nil, err
  290. }
  291. return libcontainerdtypes.InterfaceToStats(m.Timestamp, v), nil
  292. }
  293. func (t *task) Summary(ctx context.Context) ([]libcontainerdtypes.Summary, error) {
  294. pis, err := t.Pids(ctx)
  295. if err != nil {
  296. return nil, err
  297. }
  298. var infos []libcontainerdtypes.Summary
  299. for _, pi := range pis {
  300. i, err := typeurl.UnmarshalAny(pi.Info)
  301. if err != nil {
  302. return nil, errors.Wrap(err, "unable to decode process details")
  303. }
  304. s, err := summaryFromInterface(i)
  305. if err != nil {
  306. return nil, err
  307. }
  308. infos = append(infos, *s)
  309. }
  310. return infos, nil
  311. }
  312. func (t *task) Delete(ctx context.Context) (*containerd.ExitStatus, error) {
  313. s, err := t.Task.Delete(ctx)
  314. return s, wrapError(err)
  315. }
  316. func (p process) Delete(ctx context.Context) (*containerd.ExitStatus, error) {
  317. s, err := p.Process.Delete(ctx)
  318. return s, wrapError(err)
  319. }
  320. func (c *container) Delete(ctx context.Context) error {
  321. // Optimization: assume the DockerContainerBundlePath label has not been
  322. // updated since the container metadata was last loaded/refreshed.
  323. md, err := c.c8dCtr.Info(ctx, containerd.WithoutRefreshedMetadata)
  324. if err != nil {
  325. return err
  326. }
  327. bundle := md.Labels[DockerContainerBundlePath]
  328. if err := c.c8dCtr.Delete(ctx); err != nil {
  329. return wrapError(err)
  330. }
  331. if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" {
  332. if err := os.RemoveAll(bundle); err != nil {
  333. c.client.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{
  334. "container": c.c8dCtr.ID(),
  335. "bundle": bundle,
  336. }).Error("failed to remove state dir")
  337. }
  338. }
  339. return nil
  340. }
  341. func (t *task) ForceDelete(ctx context.Context) error {
  342. _, err := t.Task.Delete(ctx, containerd.WithProcessKill)
  343. return wrapError(err)
  344. }
  345. func (t *task) Status(ctx context.Context) (containerd.Status, error) {
  346. s, err := t.Task.Status(ctx)
  347. return s, wrapError(err)
  348. }
  349. func (p process) Status(ctx context.Context) (containerd.Status, error) {
  350. s, err := p.Process.Status(ctx)
  351. return s, wrapError(err)
  352. }
  353. func (c *container) getCheckpointOptions(exit bool) containerd.CheckpointTaskOpts {
  354. return func(r *containerd.CheckpointTaskInfo) error {
  355. if r.Options == nil && c.v2runcoptions != nil {
  356. r.Options = &v2runcoptions.CheckpointOptions{}
  357. }
  358. switch opts := r.Options.(type) {
  359. case *v2runcoptions.CheckpointOptions:
  360. opts.Exit = exit
  361. }
  362. return nil
  363. }
  364. }
  365. func (t *task) CreateCheckpoint(ctx context.Context, checkpointDir string, exit bool) error {
  366. img, err := t.Task.Checkpoint(ctx, t.ctr.getCheckpointOptions(exit))
  367. if err != nil {
  368. return wrapError(err)
  369. }
  370. // Whatever happens, delete the checkpoint from containerd
  371. defer func() {
  372. err := t.ctr.client.client.ImageService().Delete(ctx, img.Name())
  373. if err != nil {
  374. t.ctr.client.logger.WithError(err).WithField("digest", img.Target().Digest).
  375. Warnf("failed to delete checkpoint image")
  376. }
  377. }()
  378. b, err := content.ReadBlob(ctx, t.ctr.client.client.ContentStore(), img.Target())
  379. if err != nil {
  380. return errdefs.System(errors.Wrapf(err, "failed to retrieve checkpoint data"))
  381. }
  382. var index v1.Index
  383. if err := json.Unmarshal(b, &index); err != nil {
  384. return errdefs.System(errors.Wrapf(err, "failed to decode checkpoint data"))
  385. }
  386. var cpDesc *v1.Descriptor
  387. for _, m := range index.Manifests {
  388. m := m
  389. if m.MediaType == images.MediaTypeContainerd1Checkpoint {
  390. cpDesc = &m //nolint:gosec
  391. break
  392. }
  393. }
  394. if cpDesc == nil {
  395. return errdefs.System(errors.Wrapf(err, "invalid checkpoint"))
  396. }
  397. rat, err := t.ctr.client.client.ContentStore().ReaderAt(ctx, *cpDesc)
  398. if err != nil {
  399. return errdefs.System(errors.Wrapf(err, "failed to get checkpoint reader"))
  400. }
  401. defer rat.Close()
  402. _, err = archive.Apply(ctx, checkpointDir, content.NewReader(rat))
  403. if err != nil {
  404. return errdefs.System(errors.Wrapf(err, "failed to read checkpoint reader"))
  405. }
  406. return err
  407. }
  408. // LoadContainer loads the containerd container.
  409. func (c *client) LoadContainer(ctx context.Context, id string) (libcontainerdtypes.Container, error) {
  410. ctr, err := c.client.LoadContainer(ctx, id)
  411. if err != nil {
  412. if containerderrors.IsNotFound(err) {
  413. return nil, errors.WithStack(errdefs.NotFound(errors.New("no such container")))
  414. }
  415. return nil, wrapError(err)
  416. }
  417. return &container{client: c, c8dCtr: ctr}, nil
  418. }
  419. func (c *container) Task(ctx context.Context) (libcontainerdtypes.Task, error) {
  420. t, err := c.c8dCtr.Task(ctx, nil)
  421. if err != nil {
  422. return nil, wrapError(err)
  423. }
  424. return c.newTask(t), nil
  425. }
  426. // createIO creates the io to be used by a process
  427. // This needs to get a pointer to interface as upon closure the process may not have yet been registered
  428. func (c *container) createIO(fifos *cio.FIFOSet, stdinCloseSync chan containerd.Process, attachStdio libcontainerdtypes.StdioCallback) (cio.IO, error) {
  429. var (
  430. io *cio.DirectIO
  431. err error
  432. )
  433. io, err = c.client.newDirectIO(context.Background(), fifos)
  434. if err != nil {
  435. return nil, err
  436. }
  437. if io.Stdin != nil {
  438. var (
  439. err error
  440. stdinOnce sync.Once
  441. )
  442. pipe := io.Stdin
  443. io.Stdin = ioutils.NewWriteCloserWrapper(pipe, func() error {
  444. stdinOnce.Do(func() {
  445. err = pipe.Close()
  446. // Do the rest in a new routine to avoid a deadlock if the
  447. // Exec/Start call failed.
  448. go func() {
  449. p, ok := <-stdinCloseSync
  450. if !ok {
  451. return
  452. }
  453. err = p.CloseIO(context.Background(), containerd.WithStdinCloser)
  454. if err != nil && strings.Contains(err.Error(), "transport is closing") {
  455. err = nil
  456. }
  457. }()
  458. })
  459. return err
  460. })
  461. }
  462. rio, err := attachStdio(io)
  463. if err != nil {
  464. io.Cancel()
  465. io.Close()
  466. }
  467. return rio, err
  468. }
  469. func (c *client) processEvent(ctx context.Context, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) {
  470. c.eventQ.Append(ei.ContainerID, func() {
  471. err := c.backend.ProcessEvent(ei.ContainerID, et, ei)
  472. if err != nil {
  473. c.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{
  474. "container": ei.ContainerID,
  475. "event": et,
  476. "event-info": ei,
  477. }).Error("failed to process event")
  478. }
  479. })
  480. }
  481. func (c *client) waitServe(ctx context.Context) bool {
  482. t := 100 * time.Millisecond
  483. delay := time.NewTimer(t)
  484. if !delay.Stop() {
  485. <-delay.C
  486. }
  487. defer delay.Stop()
  488. // `IsServing` will actually block until the service is ready.
  489. // However it can return early, so we'll loop with a delay to handle it.
  490. for {
  491. serving, err := c.client.IsServing(ctx)
  492. if err != nil {
  493. if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
  494. return false
  495. }
  496. logrus.WithError(err).Warn("Error while testing if containerd API is ready")
  497. }
  498. if serving {
  499. return true
  500. }
  501. delay.Reset(t)
  502. select {
  503. case <-ctx.Done():
  504. return false
  505. case <-delay.C:
  506. }
  507. }
  508. }
  509. func (c *client) processEventStream(ctx context.Context, ns string) {
  510. var (
  511. err error
  512. ev *events.Envelope
  513. et libcontainerdtypes.EventType
  514. ei libcontainerdtypes.EventInfo
  515. )
  516. // Create a new context specifically for this subscription.
  517. // The context must be cancelled to cancel the subscription.
  518. // In cases where we have to restart event stream processing,
  519. // we'll need the original context b/c this one will be cancelled
  520. subCtx, cancel := context.WithCancel(ctx)
  521. defer cancel()
  522. // Filter on both namespace *and* topic. To create an "and" filter,
  523. // this must be a single, comma-separated string
  524. eventStream, errC := c.client.EventService().Subscribe(subCtx, "namespace=="+ns+",topic~=|^/tasks/|")
  525. c.logger.Debug("processing event stream")
  526. for {
  527. select {
  528. case err = <-errC:
  529. if err != nil {
  530. errStatus, ok := status.FromError(err)
  531. if !ok || errStatus.Code() != codes.Canceled {
  532. c.logger.WithError(err).Error("Failed to get event")
  533. c.logger.Info("Waiting for containerd to be ready to restart event processing")
  534. if c.waitServe(ctx) {
  535. go c.processEventStream(ctx, ns)
  536. return
  537. }
  538. }
  539. c.logger.WithError(ctx.Err()).Info("stopping event stream following graceful shutdown")
  540. }
  541. return
  542. case ev = <-eventStream:
  543. if ev.Event == nil {
  544. c.logger.WithField("event", ev).Warn("invalid event")
  545. continue
  546. }
  547. v, err := typeurl.UnmarshalAny(ev.Event)
  548. if err != nil {
  549. c.logger.WithError(err).WithField("event", ev).Warn("failed to unmarshal event")
  550. continue
  551. }
  552. c.logger.WithField("topic", ev.Topic).Debug("event")
  553. switch t := v.(type) {
  554. case *apievents.TaskCreate:
  555. et = libcontainerdtypes.EventCreate
  556. ei = libcontainerdtypes.EventInfo{
  557. ContainerID: t.ContainerID,
  558. ProcessID: t.ContainerID,
  559. Pid: t.Pid,
  560. }
  561. case *apievents.TaskStart:
  562. et = libcontainerdtypes.EventStart
  563. ei = libcontainerdtypes.EventInfo{
  564. ContainerID: t.ContainerID,
  565. ProcessID: t.ContainerID,
  566. Pid: t.Pid,
  567. }
  568. case *apievents.TaskExit:
  569. et = libcontainerdtypes.EventExit
  570. ei = libcontainerdtypes.EventInfo{
  571. ContainerID: t.ContainerID,
  572. ProcessID: t.ID,
  573. Pid: t.Pid,
  574. ExitCode: t.ExitStatus,
  575. ExitedAt: t.ExitedAt,
  576. }
  577. case *apievents.TaskOOM:
  578. et = libcontainerdtypes.EventOOM
  579. ei = libcontainerdtypes.EventInfo{
  580. ContainerID: t.ContainerID,
  581. }
  582. case *apievents.TaskExecAdded:
  583. et = libcontainerdtypes.EventExecAdded
  584. ei = libcontainerdtypes.EventInfo{
  585. ContainerID: t.ContainerID,
  586. ProcessID: t.ExecID,
  587. }
  588. case *apievents.TaskExecStarted:
  589. et = libcontainerdtypes.EventExecStarted
  590. ei = libcontainerdtypes.EventInfo{
  591. ContainerID: t.ContainerID,
  592. ProcessID: t.ExecID,
  593. Pid: t.Pid,
  594. }
  595. case *apievents.TaskPaused:
  596. et = libcontainerdtypes.EventPaused
  597. ei = libcontainerdtypes.EventInfo{
  598. ContainerID: t.ContainerID,
  599. }
  600. case *apievents.TaskResumed:
  601. et = libcontainerdtypes.EventResumed
  602. ei = libcontainerdtypes.EventInfo{
  603. ContainerID: t.ContainerID,
  604. }
  605. case *apievents.TaskDelete:
  606. c.logger.WithFields(logrus.Fields{
  607. "topic": ev.Topic,
  608. "type": reflect.TypeOf(t),
  609. "container": t.ContainerID},
  610. ).Info("ignoring event")
  611. continue
  612. default:
  613. c.logger.WithFields(logrus.Fields{
  614. "topic": ev.Topic,
  615. "type": reflect.TypeOf(t)},
  616. ).Info("ignoring event")
  617. continue
  618. }
  619. c.processEvent(ctx, et, ei)
  620. }
  621. }
  622. }
  623. func (c *client) writeContent(ctx context.Context, mediaType, ref string, r io.Reader) (*types.Descriptor, error) {
  624. writer, err := c.client.ContentStore().Writer(ctx, content.WithRef(ref))
  625. if err != nil {
  626. return nil, err
  627. }
  628. defer writer.Close()
  629. size, err := io.Copy(writer, r)
  630. if err != nil {
  631. return nil, err
  632. }
  633. labels := map[string]string{
  634. "containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339),
  635. }
  636. if err := writer.Commit(ctx, 0, "", content.WithLabels(labels)); err != nil {
  637. return nil, err
  638. }
  639. return &types.Descriptor{
  640. MediaType: mediaType,
  641. Digest: writer.Digest(),
  642. Size_: size,
  643. }, nil
  644. }
  645. func (c *client) bundleDir(id string) string {
  646. return filepath.Join(c.stateDir, id)
  647. }
  648. func wrapError(err error) error {
  649. switch {
  650. case err == nil:
  651. return nil
  652. case containerderrors.IsNotFound(err):
  653. return errdefs.NotFound(err)
  654. }
  655. msg := err.Error()
  656. for _, s := range []string{"container does not exist", "not found", "no such container"} {
  657. if strings.Contains(msg, s) {
  658. return errdefs.NotFound(err)
  659. }
  660. }
  661. return err
  662. }