client.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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, libcontainerdtypes.InitProcessName, withStdin, spec.Process.Terminal)
  190. rio, err = c.createIO(fifos, libcontainerdtypes.InitProcessName, 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. if _, err := t.Delete(ctx); err != nil {
  207. c.client.logger.WithError(err).WithField("container", c.c8dCtr.ID()).
  208. Error("failed to delete task after fail start")
  209. }
  210. return nil, wrapError(err)
  211. }
  212. return c.newTask(t), nil
  213. }
  214. // Exec creates exec process.
  215. //
  216. // The containerd client calls Exec to register the exec config in the shim side.
  217. // When the client calls Start, the shim will create stdin fifo if needs. But
  218. // for the container main process, the stdin fifo will be created in Create not
  219. // the Start call. stdinCloseSync channel should be closed after Start exec
  220. // process.
  221. func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (libcontainerdtypes.Process, error) {
  222. var (
  223. p containerd.Process
  224. rio cio.IO
  225. stdinCloseSync = make(chan containerd.Process, 1)
  226. )
  227. // Optimization: assume the DockerContainerBundlePath label has not been
  228. // updated since the container metadata was last loaded/refreshed.
  229. md, err := t.ctr.c8dCtr.Info(ctx, containerd.WithoutRefreshedMetadata)
  230. if err != nil {
  231. return nil, wrapError(err)
  232. }
  233. fifos := newFIFOSet(md.Labels[DockerContainerBundlePath], processID, withStdin, spec.Terminal)
  234. defer func() {
  235. if err != nil {
  236. if rio != nil {
  237. rio.Cancel()
  238. rio.Close()
  239. }
  240. }
  241. }()
  242. p, err = t.Task.Exec(ctx, processID, spec, func(id string) (cio.IO, error) {
  243. rio, err = t.ctr.createIO(fifos, processID, stdinCloseSync, attachStdio)
  244. return rio, err
  245. })
  246. if err != nil {
  247. close(stdinCloseSync)
  248. if containerderrors.IsAlreadyExists(err) {
  249. return nil, errors.WithStack(errdefs.Conflict(errors.New("id already in use")))
  250. }
  251. return nil, wrapError(err)
  252. }
  253. // Signal c.createIO that it can call CloseIO
  254. //
  255. // the stdin of exec process will be created after p.Start in containerd
  256. defer func() { stdinCloseSync <- p }()
  257. if err = p.Start(ctx); err != nil {
  258. // use new context for cleanup because old one may be cancelled by user, but leave a timeout to make sure
  259. // we are not waiting forever if containerd is unresponsive or to work around fifo cancelling issues in
  260. // older containerd-shim
  261. ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
  262. defer cancel()
  263. p.Delete(ctx)
  264. return nil, wrapError(err)
  265. }
  266. return process{p}, nil
  267. }
  268. func (t *task) Kill(ctx context.Context, signal syscall.Signal) error {
  269. return wrapError(t.Task.Kill(ctx, signal))
  270. }
  271. func (p process) Kill(ctx context.Context, signal syscall.Signal) error {
  272. return wrapError(p.Process.Kill(ctx, signal))
  273. }
  274. func (t *task) Pause(ctx context.Context) error {
  275. return wrapError(t.Task.Pause(ctx))
  276. }
  277. func (t *task) Resume(ctx context.Context) error {
  278. return wrapError(t.Task.Resume(ctx))
  279. }
  280. func (t *task) Stats(ctx context.Context) (*libcontainerdtypes.Stats, error) {
  281. m, err := t.Metrics(ctx)
  282. if err != nil {
  283. return nil, err
  284. }
  285. v, err := typeurl.UnmarshalAny(m.Data)
  286. if err != nil {
  287. return nil, err
  288. }
  289. return libcontainerdtypes.InterfaceToStats(m.Timestamp, v), nil
  290. }
  291. func (t *task) Summary(ctx context.Context) ([]libcontainerdtypes.Summary, error) {
  292. pis, err := t.Pids(ctx)
  293. if err != nil {
  294. return nil, err
  295. }
  296. var infos []libcontainerdtypes.Summary
  297. for _, pi := range pis {
  298. i, err := typeurl.UnmarshalAny(pi.Info)
  299. if err != nil {
  300. return nil, errors.Wrap(err, "unable to decode process details")
  301. }
  302. s, err := summaryFromInterface(i)
  303. if err != nil {
  304. return nil, err
  305. }
  306. infos = append(infos, *s)
  307. }
  308. return infos, nil
  309. }
  310. func (t *task) Delete(ctx context.Context) (*containerd.ExitStatus, error) {
  311. s, err := t.Task.Delete(ctx)
  312. return s, wrapError(err)
  313. }
  314. func (p process) Delete(ctx context.Context) (*containerd.ExitStatus, error) {
  315. s, err := p.Process.Delete(ctx)
  316. return s, wrapError(err)
  317. }
  318. func (c *container) Delete(ctx context.Context) error {
  319. // Optimization: assume the DockerContainerBundlePath label has not been
  320. // updated since the container metadata was last loaded/refreshed.
  321. md, err := c.c8dCtr.Info(ctx, containerd.WithoutRefreshedMetadata)
  322. if err != nil {
  323. return err
  324. }
  325. bundle := md.Labels[DockerContainerBundlePath]
  326. if err := c.c8dCtr.Delete(ctx); err != nil {
  327. return wrapError(err)
  328. }
  329. if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" {
  330. if err := os.RemoveAll(bundle); err != nil {
  331. c.client.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{
  332. "container": c.c8dCtr.ID(),
  333. "bundle": bundle,
  334. }).Error("failed to remove state dir")
  335. }
  336. }
  337. return nil
  338. }
  339. func (t *task) ForceDelete(ctx context.Context) error {
  340. _, err := t.Task.Delete(ctx, containerd.WithProcessKill)
  341. return wrapError(err)
  342. }
  343. func (t *task) Status(ctx context.Context) (containerd.Status, error) {
  344. s, err := t.Task.Status(ctx)
  345. return s, wrapError(err)
  346. }
  347. func (p process) Status(ctx context.Context) (containerd.Status, error) {
  348. s, err := p.Process.Status(ctx)
  349. return s, wrapError(err)
  350. }
  351. func (c *container) getCheckpointOptions(exit bool) containerd.CheckpointTaskOpts {
  352. return func(r *containerd.CheckpointTaskInfo) error {
  353. if r.Options == nil && c.v2runcoptions != nil {
  354. r.Options = &v2runcoptions.CheckpointOptions{}
  355. }
  356. switch opts := r.Options.(type) {
  357. case *v2runcoptions.CheckpointOptions:
  358. opts.Exit = exit
  359. }
  360. return nil
  361. }
  362. }
  363. func (t *task) CreateCheckpoint(ctx context.Context, checkpointDir string, exit bool) error {
  364. img, err := t.Task.Checkpoint(ctx, t.ctr.getCheckpointOptions(exit))
  365. if err != nil {
  366. return wrapError(err)
  367. }
  368. // Whatever happens, delete the checkpoint from containerd
  369. defer func() {
  370. err := t.ctr.client.client.ImageService().Delete(ctx, img.Name())
  371. if err != nil {
  372. t.ctr.client.logger.WithError(err).WithField("digest", img.Target().Digest).
  373. Warnf("failed to delete checkpoint image")
  374. }
  375. }()
  376. b, err := content.ReadBlob(ctx, t.ctr.client.client.ContentStore(), img.Target())
  377. if err != nil {
  378. return errdefs.System(errors.Wrapf(err, "failed to retrieve checkpoint data"))
  379. }
  380. var index v1.Index
  381. if err := json.Unmarshal(b, &index); err != nil {
  382. return errdefs.System(errors.Wrapf(err, "failed to decode checkpoint data"))
  383. }
  384. var cpDesc *v1.Descriptor
  385. for _, m := range index.Manifests {
  386. m := m
  387. if m.MediaType == images.MediaTypeContainerd1Checkpoint {
  388. cpDesc = &m //nolint:gosec
  389. break
  390. }
  391. }
  392. if cpDesc == nil {
  393. return errdefs.System(errors.Wrapf(err, "invalid checkpoint"))
  394. }
  395. rat, err := t.ctr.client.client.ContentStore().ReaderAt(ctx, *cpDesc)
  396. if err != nil {
  397. return errdefs.System(errors.Wrapf(err, "failed to get checkpoint reader"))
  398. }
  399. defer rat.Close()
  400. _, err = archive.Apply(ctx, checkpointDir, content.NewReader(rat))
  401. if err != nil {
  402. return errdefs.System(errors.Wrapf(err, "failed to read checkpoint reader"))
  403. }
  404. return err
  405. }
  406. // LoadContainer loads the containerd container.
  407. func (c *client) LoadContainer(ctx context.Context, id string) (libcontainerdtypes.Container, error) {
  408. ctr, err := c.client.LoadContainer(ctx, id)
  409. if err != nil {
  410. if containerderrors.IsNotFound(err) {
  411. return nil, errors.WithStack(errdefs.NotFound(errors.New("no such container")))
  412. }
  413. return nil, wrapError(err)
  414. }
  415. return &container{client: c, c8dCtr: ctr}, nil
  416. }
  417. func (c *container) Task(ctx context.Context) (libcontainerdtypes.Task, error) {
  418. t, err := c.c8dCtr.Task(ctx, nil)
  419. if err != nil {
  420. return nil, wrapError(err)
  421. }
  422. return c.newTask(t), nil
  423. }
  424. // createIO creates the io to be used by a process
  425. // This needs to get a pointer to interface as upon closure the process may not have yet been registered
  426. func (c *container) createIO(fifos *cio.FIFOSet, processID string, stdinCloseSync chan containerd.Process, attachStdio libcontainerdtypes.StdioCallback) (cio.IO, error) {
  427. var (
  428. io *cio.DirectIO
  429. err error
  430. )
  431. io, err = c.client.newDirectIO(context.Background(), fifos)
  432. if err != nil {
  433. return nil, err
  434. }
  435. if io.Stdin != nil {
  436. var (
  437. err error
  438. stdinOnce sync.Once
  439. )
  440. pipe := io.Stdin
  441. io.Stdin = ioutils.NewWriteCloserWrapper(pipe, func() error {
  442. stdinOnce.Do(func() {
  443. err = pipe.Close()
  444. // Do the rest in a new routine to avoid a deadlock if the
  445. // Exec/Start call failed.
  446. go func() {
  447. p, ok := <-stdinCloseSync
  448. if !ok {
  449. return
  450. }
  451. err = p.CloseIO(context.Background(), containerd.WithStdinCloser)
  452. if err != nil && strings.Contains(err.Error(), "transport is closing") {
  453. err = nil
  454. }
  455. }()
  456. })
  457. return err
  458. })
  459. }
  460. rio, err := attachStdio(io)
  461. if err != nil {
  462. io.Cancel()
  463. io.Close()
  464. }
  465. return rio, err
  466. }
  467. func (c *client) processEvent(ctx context.Context, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) {
  468. c.eventQ.Append(ei.ContainerID, func() {
  469. err := c.backend.ProcessEvent(ei.ContainerID, et, ei)
  470. if err != nil {
  471. c.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{
  472. "container": ei.ContainerID,
  473. "event": et,
  474. "event-info": ei,
  475. }).Error("failed to process event")
  476. }
  477. })
  478. }
  479. func (c *client) waitServe(ctx context.Context) bool {
  480. t := 100 * time.Millisecond
  481. delay := time.NewTimer(t)
  482. if !delay.Stop() {
  483. <-delay.C
  484. }
  485. defer delay.Stop()
  486. // `IsServing` will actually block until the service is ready.
  487. // However it can return early, so we'll loop with a delay to handle it.
  488. for {
  489. serving, err := c.client.IsServing(ctx)
  490. if err != nil {
  491. if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
  492. return false
  493. }
  494. logrus.WithError(err).Warn("Error while testing if containerd API is ready")
  495. }
  496. if serving {
  497. return true
  498. }
  499. delay.Reset(t)
  500. select {
  501. case <-ctx.Done():
  502. return false
  503. case <-delay.C:
  504. }
  505. }
  506. }
  507. func (c *client) processEventStream(ctx context.Context, ns string) {
  508. var (
  509. err error
  510. ev *events.Envelope
  511. et libcontainerdtypes.EventType
  512. ei libcontainerdtypes.EventInfo
  513. )
  514. // Create a new context specifically for this subscription.
  515. // The context must be cancelled to cancel the subscription.
  516. // In cases where we have to restart event stream processing,
  517. // we'll need the original context b/c this one will be cancelled
  518. subCtx, cancel := context.WithCancel(ctx)
  519. defer cancel()
  520. // Filter on both namespace *and* topic. To create an "and" filter,
  521. // this must be a single, comma-separated string
  522. eventStream, errC := c.client.EventService().Subscribe(subCtx, "namespace=="+ns+",topic~=|^/tasks/|")
  523. c.logger.Debug("processing event stream")
  524. for {
  525. select {
  526. case err = <-errC:
  527. if err != nil {
  528. errStatus, ok := status.FromError(err)
  529. if !ok || errStatus.Code() != codes.Canceled {
  530. c.logger.WithError(err).Error("Failed to get event")
  531. c.logger.Info("Waiting for containerd to be ready to restart event processing")
  532. if c.waitServe(ctx) {
  533. go c.processEventStream(ctx, ns)
  534. return
  535. }
  536. }
  537. c.logger.WithError(ctx.Err()).Info("stopping event stream following graceful shutdown")
  538. }
  539. return
  540. case ev = <-eventStream:
  541. if ev.Event == nil {
  542. c.logger.WithField("event", ev).Warn("invalid event")
  543. continue
  544. }
  545. v, err := typeurl.UnmarshalAny(ev.Event)
  546. if err != nil {
  547. c.logger.WithError(err).WithField("event", ev).Warn("failed to unmarshal event")
  548. continue
  549. }
  550. c.logger.WithField("topic", ev.Topic).Debug("event")
  551. switch t := v.(type) {
  552. case *apievents.TaskCreate:
  553. et = libcontainerdtypes.EventCreate
  554. ei = libcontainerdtypes.EventInfo{
  555. ContainerID: t.ContainerID,
  556. ProcessID: t.ContainerID,
  557. Pid: t.Pid,
  558. }
  559. case *apievents.TaskStart:
  560. et = libcontainerdtypes.EventStart
  561. ei = libcontainerdtypes.EventInfo{
  562. ContainerID: t.ContainerID,
  563. ProcessID: t.ContainerID,
  564. Pid: t.Pid,
  565. }
  566. case *apievents.TaskExit:
  567. et = libcontainerdtypes.EventExit
  568. ei = libcontainerdtypes.EventInfo{
  569. ContainerID: t.ContainerID,
  570. ProcessID: t.ID,
  571. Pid: t.Pid,
  572. ExitCode: t.ExitStatus,
  573. ExitedAt: t.ExitedAt,
  574. }
  575. case *apievents.TaskOOM:
  576. et = libcontainerdtypes.EventOOM
  577. ei = libcontainerdtypes.EventInfo{
  578. ContainerID: t.ContainerID,
  579. }
  580. case *apievents.TaskExecAdded:
  581. et = libcontainerdtypes.EventExecAdded
  582. ei = libcontainerdtypes.EventInfo{
  583. ContainerID: t.ContainerID,
  584. ProcessID: t.ExecID,
  585. }
  586. case *apievents.TaskExecStarted:
  587. et = libcontainerdtypes.EventExecStarted
  588. ei = libcontainerdtypes.EventInfo{
  589. ContainerID: t.ContainerID,
  590. ProcessID: t.ExecID,
  591. Pid: t.Pid,
  592. }
  593. case *apievents.TaskPaused:
  594. et = libcontainerdtypes.EventPaused
  595. ei = libcontainerdtypes.EventInfo{
  596. ContainerID: t.ContainerID,
  597. }
  598. case *apievents.TaskResumed:
  599. et = libcontainerdtypes.EventResumed
  600. ei = libcontainerdtypes.EventInfo{
  601. ContainerID: t.ContainerID,
  602. }
  603. case *apievents.TaskDelete:
  604. c.logger.WithFields(logrus.Fields{
  605. "topic": ev.Topic,
  606. "type": reflect.TypeOf(t),
  607. "container": t.ContainerID},
  608. ).Info("ignoring event")
  609. continue
  610. default:
  611. c.logger.WithFields(logrus.Fields{
  612. "topic": ev.Topic,
  613. "type": reflect.TypeOf(t)},
  614. ).Info("ignoring event")
  615. continue
  616. }
  617. c.processEvent(ctx, et, ei)
  618. }
  619. }
  620. }
  621. func (c *client) writeContent(ctx context.Context, mediaType, ref string, r io.Reader) (*types.Descriptor, error) {
  622. writer, err := c.client.ContentStore().Writer(ctx, content.WithRef(ref))
  623. if err != nil {
  624. return nil, err
  625. }
  626. defer writer.Close()
  627. size, err := io.Copy(writer, r)
  628. if err != nil {
  629. return nil, err
  630. }
  631. labels := map[string]string{
  632. "containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339),
  633. }
  634. if err := writer.Commit(ctx, 0, "", content.WithLabels(labels)); err != nil {
  635. return nil, err
  636. }
  637. return &types.Descriptor{
  638. MediaType: mediaType,
  639. Digest: writer.Digest(),
  640. Size_: size,
  641. }, nil
  642. }
  643. func (c *client) bundleDir(id string) string {
  644. return filepath.Join(c.stateDir, id)
  645. }
  646. func wrapError(err error) error {
  647. switch {
  648. case err == nil:
  649. return nil
  650. case containerderrors.IsNotFound(err):
  651. return errdefs.NotFound(err)
  652. }
  653. msg := err.Error()
  654. for _, s := range []string{"container does not exist", "not found", "no such container"} {
  655. if strings.Contains(msg, s) {
  656. return errdefs.NotFound(err)
  657. }
  658. }
  659. return err
  660. }