client_daemon.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. // +build !windows
  2. package libcontainerd
  3. import (
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "syscall"
  15. "time"
  16. "google.golang.org/grpc"
  17. "github.com/containerd/containerd"
  18. eventsapi "github.com/containerd/containerd/api/services/events/v1"
  19. "github.com/containerd/containerd/api/types"
  20. "github.com/containerd/containerd/archive"
  21. "github.com/containerd/containerd/content"
  22. "github.com/containerd/containerd/images"
  23. "github.com/containerd/containerd/linux/runcopts"
  24. "github.com/containerd/typeurl"
  25. "github.com/docker/docker/pkg/ioutils"
  26. "github.com/opencontainers/image-spec/specs-go/v1"
  27. "github.com/opencontainers/runtime-spec/specs-go"
  28. "github.com/pkg/errors"
  29. "github.com/sirupsen/logrus"
  30. )
  31. // InitProcessName is the name given to the first process of a
  32. // container
  33. const InitProcessName = "init"
  34. type container struct {
  35. sync.Mutex
  36. bundleDir string
  37. ctr containerd.Container
  38. task containerd.Task
  39. execs map[string]containerd.Process
  40. oomKilled bool
  41. }
  42. type client struct {
  43. sync.RWMutex // protects containers map
  44. remote *containerd.Client
  45. stateDir string
  46. logger *logrus.Entry
  47. namespace string
  48. backend Backend
  49. eventQ queue
  50. containers map[string]*container
  51. }
  52. func (c *client) Version(ctx context.Context) (containerd.Version, error) {
  53. return c.remote.Version(ctx)
  54. }
  55. func (c *client) Restore(ctx context.Context, id string, attachStdio StdioCallback) (alive bool, pid int, err error) {
  56. c.Lock()
  57. defer c.Unlock()
  58. var cio containerd.IO
  59. defer func() {
  60. err = wrapError(err)
  61. }()
  62. ctr, err := c.remote.LoadContainer(ctx, id)
  63. if err != nil {
  64. return false, -1, errors.WithStack(err)
  65. }
  66. defer func() {
  67. if err != nil && cio != nil {
  68. cio.Cancel()
  69. cio.Close()
  70. }
  71. }()
  72. t, err := ctr.Task(ctx, func(fifos *containerd.FIFOSet) (containerd.IO, error) {
  73. io, err := newIOPipe(fifos)
  74. if err != nil {
  75. return nil, err
  76. }
  77. cio, err = attachStdio(io)
  78. return cio, err
  79. })
  80. if err != nil && !strings.Contains(err.Error(), "no running task found") {
  81. return false, -1, err
  82. }
  83. if t != nil {
  84. s, err := t.Status(ctx)
  85. if err != nil {
  86. return false, -1, err
  87. }
  88. alive = s.Status != containerd.Stopped
  89. pid = int(t.Pid())
  90. }
  91. c.containers[id] = &container{
  92. bundleDir: filepath.Join(c.stateDir, id),
  93. ctr: ctr,
  94. task: t,
  95. // TODO(mlaventure): load execs
  96. }
  97. c.logger.WithFields(logrus.Fields{
  98. "container": id,
  99. "alive": alive,
  100. "pid": pid,
  101. }).Debug("restored container")
  102. return alive, pid, nil
  103. }
  104. func (c *client) Create(ctx context.Context, id string, ociSpec *specs.Spec, runtimeOptions interface{}) error {
  105. if ctr := c.getContainer(id); ctr != nil {
  106. return errors.WithStack(newConflictError("id already in use"))
  107. }
  108. bdir, err := prepareBundleDir(filepath.Join(c.stateDir, id), ociSpec)
  109. if err != nil {
  110. return wrapSystemError(errors.Wrap(err, "prepare bundle dir failed"))
  111. }
  112. c.logger.WithField("bundle", bdir).WithField("root", ociSpec.Root.Path).Debug("bundle dir created")
  113. cdCtr, err := c.remote.NewContainer(ctx, id,
  114. containerd.WithSpec(ociSpec),
  115. // TODO(mlaventure): when containerd support lcow, revisit runtime value
  116. containerd.WithRuntime(fmt.Sprintf("io.containerd.runtime.v1.%s", runtime.GOOS), runtimeOptions))
  117. if err != nil {
  118. return err
  119. }
  120. c.Lock()
  121. c.containers[id] = &container{
  122. bundleDir: bdir,
  123. ctr: cdCtr,
  124. }
  125. c.Unlock()
  126. return nil
  127. }
  128. // Start create and start a task for the specified containerd id
  129. func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin bool, attachStdio StdioCallback) (int, error) {
  130. ctr := c.getContainer(id)
  131. switch {
  132. case ctr == nil:
  133. return -1, errors.WithStack(newNotFoundError("no such container"))
  134. case ctr.task != nil:
  135. return -1, errors.WithStack(newConflictError("container already started"))
  136. }
  137. var (
  138. cp *types.Descriptor
  139. t containerd.Task
  140. cio containerd.IO
  141. err error
  142. stdinCloseSync = make(chan struct{})
  143. )
  144. if checkpointDir != "" {
  145. // write checkpoint to the content store
  146. tar := archive.Diff(ctx, "", checkpointDir)
  147. cp, err = c.writeContent(ctx, images.MediaTypeContainerd1Checkpoint, checkpointDir, tar)
  148. // remove the checkpoint when we're done
  149. defer func() {
  150. if cp != nil {
  151. err := c.remote.ContentStore().Delete(context.Background(), cp.Digest)
  152. if err != nil {
  153. c.logger.WithError(err).WithFields(logrus.Fields{
  154. "ref": checkpointDir,
  155. "digest": cp.Digest,
  156. }).Warnf("failed to delete temporary checkpoint entry")
  157. }
  158. }
  159. }()
  160. if err := tar.Close(); err != nil {
  161. return -1, errors.Wrap(err, "failed to close checkpoint tar stream")
  162. }
  163. if err != nil {
  164. return -1, errors.Wrapf(err, "failed to upload checkpoint to containerd")
  165. }
  166. }
  167. spec, err := ctr.ctr.Spec(ctx)
  168. if err != nil {
  169. return -1, errors.Wrap(err, "failed to retrieve spec")
  170. }
  171. uid, gid := getSpecUser(spec)
  172. t, err = ctr.ctr.NewTask(ctx,
  173. func(id string) (containerd.IO, error) {
  174. cio, err = c.createIO(ctr.bundleDir, id, InitProcessName, stdinCloseSync, withStdin, spec.Process.Terminal, attachStdio)
  175. return cio, err
  176. },
  177. func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
  178. info.Checkpoint = cp
  179. info.Options = &runcopts.CreateOptions{
  180. IoUid: uint32(uid),
  181. IoGid: uint32(gid),
  182. }
  183. return nil
  184. })
  185. if err != nil {
  186. close(stdinCloseSync)
  187. if cio != nil {
  188. cio.Cancel()
  189. cio.Close()
  190. }
  191. return -1, err
  192. }
  193. c.Lock()
  194. c.containers[id].task = t
  195. c.Unlock()
  196. // Signal c.createIO that it can call CloseIO
  197. close(stdinCloseSync)
  198. if err := t.Start(ctx); err != nil {
  199. if _, err := t.Delete(ctx); err != nil {
  200. c.logger.WithError(err).WithField("container", id).
  201. Error("failed to delete task after fail start")
  202. }
  203. c.Lock()
  204. c.containers[id].task = nil
  205. c.Unlock()
  206. return -1, err
  207. }
  208. return int(t.Pid()), nil
  209. }
  210. func (c *client) Exec(ctx context.Context, containerID, processID string, spec *specs.Process, withStdin bool, attachStdio StdioCallback) (int, error) {
  211. ctr := c.getContainer(containerID)
  212. switch {
  213. case ctr == nil:
  214. return -1, errors.WithStack(newNotFoundError("no such container"))
  215. case ctr.task == nil:
  216. return -1, errors.WithStack(newInvalidParameterError("container is not running"))
  217. case ctr.execs != nil && ctr.execs[processID] != nil:
  218. return -1, errors.WithStack(newConflictError("id already in use"))
  219. }
  220. var (
  221. p containerd.Process
  222. cio containerd.IO
  223. err error
  224. stdinCloseSync = make(chan struct{})
  225. )
  226. defer func() {
  227. if err != nil {
  228. if cio != nil {
  229. cio.Cancel()
  230. cio.Close()
  231. }
  232. }
  233. }()
  234. p, err = ctr.task.Exec(ctx, processID, spec, func(id string) (containerd.IO, error) {
  235. cio, err = c.createIO(ctr.bundleDir, containerID, processID, stdinCloseSync, withStdin, spec.Terminal, attachStdio)
  236. return cio, err
  237. })
  238. if err != nil {
  239. close(stdinCloseSync)
  240. if cio != nil {
  241. cio.Cancel()
  242. cio.Close()
  243. }
  244. return -1, err
  245. }
  246. ctr.Lock()
  247. if ctr.execs == nil {
  248. ctr.execs = make(map[string]containerd.Process)
  249. }
  250. ctr.execs[processID] = p
  251. ctr.Unlock()
  252. // Signal c.createIO that it can call CloseIO
  253. close(stdinCloseSync)
  254. if err = p.Start(ctx); err != nil {
  255. p.Delete(context.Background())
  256. ctr.Lock()
  257. delete(ctr.execs, processID)
  258. ctr.Unlock()
  259. return -1, err
  260. }
  261. return int(p.Pid()), nil
  262. }
  263. func (c *client) SignalProcess(ctx context.Context, containerID, processID string, signal int) error {
  264. p, err := c.getProcess(containerID, processID)
  265. if err != nil {
  266. return err
  267. }
  268. return p.Kill(ctx, syscall.Signal(signal))
  269. }
  270. func (c *client) ResizeTerminal(ctx context.Context, containerID, processID string, width, height int) error {
  271. p, err := c.getProcess(containerID, processID)
  272. if err != nil {
  273. return err
  274. }
  275. return p.Resize(ctx, uint32(width), uint32(height))
  276. }
  277. func (c *client) CloseStdin(ctx context.Context, containerID, processID string) error {
  278. p, err := c.getProcess(containerID, processID)
  279. if err != nil {
  280. return err
  281. }
  282. return p.CloseIO(ctx, containerd.WithStdinCloser)
  283. }
  284. func (c *client) Pause(ctx context.Context, containerID string) error {
  285. p, err := c.getProcess(containerID, InitProcessName)
  286. if err != nil {
  287. return err
  288. }
  289. return p.(containerd.Task).Pause(ctx)
  290. }
  291. func (c *client) Resume(ctx context.Context, containerID string) error {
  292. p, err := c.getProcess(containerID, InitProcessName)
  293. if err != nil {
  294. return err
  295. }
  296. return p.(containerd.Task).Resume(ctx)
  297. }
  298. func (c *client) Stats(ctx context.Context, containerID string) (*Stats, error) {
  299. p, err := c.getProcess(containerID, InitProcessName)
  300. if err != nil {
  301. return nil, err
  302. }
  303. m, err := p.(containerd.Task).Metrics(ctx)
  304. if err != nil {
  305. return nil, err
  306. }
  307. v, err := typeurl.UnmarshalAny(m.Data)
  308. if err != nil {
  309. return nil, err
  310. }
  311. return interfaceToStats(m.Timestamp, v), nil
  312. }
  313. func (c *client) ListPids(ctx context.Context, containerID string) ([]uint32, error) {
  314. p, err := c.getProcess(containerID, InitProcessName)
  315. if err != nil {
  316. return nil, err
  317. }
  318. pis, err := p.(containerd.Task).Pids(ctx)
  319. if err != nil {
  320. return nil, err
  321. }
  322. var pids []uint32
  323. for _, i := range pis {
  324. pids = append(pids, i.Pid)
  325. }
  326. return pids, nil
  327. }
  328. func (c *client) Summary(ctx context.Context, containerID string) ([]Summary, error) {
  329. p, err := c.getProcess(containerID, InitProcessName)
  330. if err != nil {
  331. return nil, err
  332. }
  333. pis, err := p.(containerd.Task).Pids(ctx)
  334. if err != nil {
  335. return nil, err
  336. }
  337. var infos []Summary
  338. for _, pi := range pis {
  339. i, err := typeurl.UnmarshalAny(pi.Info)
  340. if err != nil {
  341. return nil, errors.Wrap(err, "unable to decode process details")
  342. }
  343. s, err := summaryFromInterface(i)
  344. if err != nil {
  345. return nil, err
  346. }
  347. infos = append(infos, *s)
  348. }
  349. return infos, nil
  350. }
  351. func (c *client) DeleteTask(ctx context.Context, containerID string) (uint32, time.Time, error) {
  352. p, err := c.getProcess(containerID, InitProcessName)
  353. if err != nil {
  354. return 255, time.Now(), nil
  355. }
  356. status, err := p.(containerd.Task).Delete(ctx)
  357. if err != nil {
  358. return 255, time.Now(), nil
  359. }
  360. c.Lock()
  361. if ctr, ok := c.containers[containerID]; ok {
  362. ctr.task = nil
  363. }
  364. c.Unlock()
  365. return status.ExitCode(), status.ExitTime(), nil
  366. }
  367. func (c *client) Delete(ctx context.Context, containerID string) error {
  368. ctr := c.getContainer(containerID)
  369. if ctr == nil {
  370. return errors.WithStack(newNotFoundError("no such container"))
  371. }
  372. if err := ctr.ctr.Delete(ctx); err != nil {
  373. return err
  374. }
  375. if os.Getenv("LIBCONTAINERD_NOCLEAN") == "1" {
  376. if err := os.RemoveAll(ctr.bundleDir); err != nil {
  377. c.logger.WithError(err).WithFields(logrus.Fields{
  378. "container": containerID,
  379. "bundle": ctr.bundleDir,
  380. }).Error("failed to remove state dir")
  381. }
  382. }
  383. c.removeContainer(containerID)
  384. return nil
  385. }
  386. func (c *client) Status(ctx context.Context, containerID string) (Status, error) {
  387. ctr := c.getContainer(containerID)
  388. if ctr == nil {
  389. return StatusUnknown, errors.WithStack(newNotFoundError("no such container"))
  390. }
  391. s, err := ctr.task.Status(ctx)
  392. if err != nil {
  393. return StatusUnknown, err
  394. }
  395. return Status(s.Status), nil
  396. }
  397. func (c *client) CreateCheckpoint(ctx context.Context, containerID, checkpointDir string, exit bool) error {
  398. p, err := c.getProcess(containerID, InitProcessName)
  399. if err != nil {
  400. return err
  401. }
  402. img, err := p.(containerd.Task).Checkpoint(ctx)
  403. if err != nil {
  404. return err
  405. }
  406. // Whatever happens, delete the checkpoint from containerd
  407. defer func() {
  408. err := c.remote.ImageService().Delete(context.Background(), img.Name())
  409. if err != nil {
  410. c.logger.WithError(err).WithField("digest", img.Target().Digest).
  411. Warnf("failed to delete checkpoint image")
  412. }
  413. }()
  414. b, err := content.ReadBlob(ctx, c.remote.ContentStore(), img.Target().Digest)
  415. if err != nil {
  416. return wrapSystemError(errors.Wrapf(err, "failed to retrieve checkpoint data"))
  417. }
  418. var index v1.Index
  419. if err := json.Unmarshal(b, &index); err != nil {
  420. return wrapSystemError(errors.Wrapf(err, "failed to decode checkpoint data"))
  421. }
  422. var cpDesc *v1.Descriptor
  423. for _, m := range index.Manifests {
  424. if m.MediaType == images.MediaTypeContainerd1Checkpoint {
  425. cpDesc = &m
  426. break
  427. }
  428. }
  429. if cpDesc == nil {
  430. return wrapSystemError(errors.Wrapf(err, "invalid checkpoint"))
  431. }
  432. rat, err := c.remote.ContentStore().ReaderAt(ctx, cpDesc.Digest)
  433. if err != nil {
  434. return wrapSystemError(errors.Wrapf(err, "failed to get checkpoint reader"))
  435. }
  436. defer rat.Close()
  437. _, err = archive.Apply(ctx, checkpointDir, content.NewReader(rat))
  438. if err != nil {
  439. return wrapSystemError(errors.Wrapf(err, "failed to read checkpoint reader"))
  440. }
  441. return err
  442. }
  443. func (c *client) getContainer(id string) *container {
  444. c.RLock()
  445. ctr := c.containers[id]
  446. c.RUnlock()
  447. return ctr
  448. }
  449. func (c *client) removeContainer(id string) {
  450. c.Lock()
  451. delete(c.containers, id)
  452. c.Unlock()
  453. }
  454. func (c *client) getProcess(containerID, processID string) (containerd.Process, error) {
  455. ctr := c.getContainer(containerID)
  456. switch {
  457. case ctr == nil:
  458. return nil, errors.WithStack(newNotFoundError("no such container"))
  459. case ctr.task == nil:
  460. return nil, errors.WithStack(newNotFoundError("container is not running"))
  461. case processID == InitProcessName:
  462. return ctr.task, nil
  463. default:
  464. ctr.Lock()
  465. defer ctr.Unlock()
  466. if ctr.execs == nil {
  467. return nil, errors.WithStack(newNotFoundError("no execs"))
  468. }
  469. }
  470. p := ctr.execs[processID]
  471. if p == nil {
  472. return nil, errors.WithStack(newNotFoundError("no such exec"))
  473. }
  474. return p, nil
  475. }
  476. // createIO creates the io to be used by a process
  477. // This needs to get a pointer to interface as upon closure the process may not have yet been registered
  478. func (c *client) createIO(bundleDir, containerID, processID string, stdinCloseSync chan struct{}, withStdin, withTerminal bool, attachStdio StdioCallback) (containerd.IO, error) {
  479. fifos := newFIFOSet(bundleDir, containerID, processID, withStdin, withTerminal)
  480. io, err := newIOPipe(fifos)
  481. if err != nil {
  482. return nil, err
  483. }
  484. if io.Stdin != nil {
  485. var (
  486. err error
  487. stdinOnce sync.Once
  488. )
  489. pipe := io.Stdin
  490. io.Stdin = ioutils.NewWriteCloserWrapper(pipe, func() error {
  491. stdinOnce.Do(func() {
  492. err = pipe.Close()
  493. // Do the rest in a new routine to avoid a deadlock if the
  494. // Exec/Start call failed.
  495. go func() {
  496. <-stdinCloseSync
  497. p, err := c.getProcess(containerID, processID)
  498. if err == nil {
  499. err = p.CloseIO(context.Background(), containerd.WithStdinCloser)
  500. if err != nil && strings.Contains(err.Error(), "transport is closing") {
  501. err = nil
  502. }
  503. }
  504. }()
  505. })
  506. return err
  507. })
  508. }
  509. cio, err := attachStdio(io)
  510. if err != nil {
  511. io.Cancel()
  512. io.Close()
  513. }
  514. return cio, err
  515. }
  516. func (c *client) processEvent(ctr *container, et EventType, ei EventInfo) {
  517. c.eventQ.append(ei.ContainerID, func() {
  518. err := c.backend.ProcessEvent(ei.ContainerID, et, ei)
  519. if err != nil {
  520. c.logger.WithError(err).WithFields(logrus.Fields{
  521. "container": ei.ContainerID,
  522. "event": et,
  523. "event-info": ei,
  524. }).Error("failed to process event")
  525. }
  526. if et == EventExit && ei.ProcessID != ei.ContainerID {
  527. var p containerd.Process
  528. ctr.Lock()
  529. if ctr.execs != nil {
  530. p = ctr.execs[ei.ProcessID]
  531. }
  532. ctr.Unlock()
  533. if p == nil {
  534. c.logger.WithError(errors.New("no such process")).
  535. WithFields(logrus.Fields{
  536. "container": ei.ContainerID,
  537. "process": ei.ProcessID,
  538. }).Error("exit event")
  539. return
  540. }
  541. _, err = p.Delete(context.Background())
  542. if err != nil {
  543. c.logger.WithError(err).WithFields(logrus.Fields{
  544. "container": ei.ContainerID,
  545. "process": ei.ProcessID,
  546. }).Warn("failed to delete process")
  547. }
  548. c.Lock()
  549. delete(ctr.execs, ei.ProcessID)
  550. c.Unlock()
  551. }
  552. })
  553. }
  554. func (c *client) processEventStream(ctx context.Context) {
  555. var (
  556. err error
  557. eventStream eventsapi.Events_SubscribeClient
  558. ev *eventsapi.Envelope
  559. et EventType
  560. ei EventInfo
  561. ctr *container
  562. )
  563. defer func() {
  564. if err != nil {
  565. select {
  566. case <-ctx.Done():
  567. c.logger.WithError(ctx.Err()).
  568. Info("stopping event stream following graceful shutdown")
  569. default:
  570. go c.processEventStream(ctx)
  571. }
  572. }
  573. }()
  574. eventStream, err = c.remote.EventService().Subscribe(ctx, &eventsapi.SubscribeRequest{
  575. Filters: []string{"namespace==" + c.namespace + ",topic~=/tasks/.+"},
  576. }, grpc.FailFast(false))
  577. if err != nil {
  578. return
  579. }
  580. var oomKilled bool
  581. for {
  582. ev, err = eventStream.Recv()
  583. if err != nil {
  584. c.logger.WithError(err).Error("failed to get event")
  585. return
  586. }
  587. if ev.Event == nil {
  588. c.logger.WithField("event", ev).Warn("invalid event")
  589. continue
  590. }
  591. v, err := typeurl.UnmarshalAny(ev.Event)
  592. if err != nil {
  593. c.logger.WithError(err).WithField("event", ev).Warn("failed to unmarshal event")
  594. continue
  595. }
  596. c.logger.WithField("topic", ev.Topic).Debug("event")
  597. switch t := v.(type) {
  598. case *eventsapi.TaskCreate:
  599. et = EventCreate
  600. ei = EventInfo{
  601. ContainerID: t.ContainerID,
  602. ProcessID: t.ContainerID,
  603. Pid: t.Pid,
  604. }
  605. case *eventsapi.TaskStart:
  606. et = EventStart
  607. ei = EventInfo{
  608. ContainerID: t.ContainerID,
  609. ProcessID: t.ContainerID,
  610. Pid: t.Pid,
  611. }
  612. case *eventsapi.TaskExit:
  613. et = EventExit
  614. ei = EventInfo{
  615. ContainerID: t.ContainerID,
  616. ProcessID: t.ID,
  617. Pid: t.Pid,
  618. ExitCode: t.ExitStatus,
  619. ExitedAt: t.ExitedAt,
  620. }
  621. case *eventsapi.TaskOOM:
  622. et = EventOOM
  623. ei = EventInfo{
  624. ContainerID: t.ContainerID,
  625. OOMKilled: true,
  626. }
  627. oomKilled = true
  628. case *eventsapi.TaskExecAdded:
  629. et = EventExecAdded
  630. ei = EventInfo{
  631. ContainerID: t.ContainerID,
  632. ProcessID: t.ExecID,
  633. }
  634. case *eventsapi.TaskExecStarted:
  635. et = EventExecStarted
  636. ei = EventInfo{
  637. ContainerID: t.ContainerID,
  638. ProcessID: t.ExecID,
  639. Pid: t.Pid,
  640. }
  641. case *eventsapi.TaskPaused:
  642. et = EventPaused
  643. ei = EventInfo{
  644. ContainerID: t.ContainerID,
  645. }
  646. case *eventsapi.TaskResumed:
  647. et = EventResumed
  648. ei = EventInfo{
  649. ContainerID: t.ContainerID,
  650. }
  651. default:
  652. c.logger.WithFields(logrus.Fields{
  653. "topic": ev.Topic,
  654. "type": reflect.TypeOf(t)},
  655. ).Info("ignoring event")
  656. continue
  657. }
  658. ctr = c.getContainer(ei.ContainerID)
  659. if ctr == nil {
  660. c.logger.WithField("container", ei.ContainerID).Warn("unknown container")
  661. continue
  662. }
  663. if oomKilled {
  664. ctr.oomKilled = true
  665. oomKilled = false
  666. }
  667. ei.OOMKilled = ctr.oomKilled
  668. c.processEvent(ctr, et, ei)
  669. }
  670. }
  671. func (c *client) writeContent(ctx context.Context, mediaType, ref string, r io.Reader) (*types.Descriptor, error) {
  672. writer, err := c.remote.ContentStore().Writer(ctx, ref, 0, "")
  673. if err != nil {
  674. return nil, err
  675. }
  676. defer writer.Close()
  677. size, err := io.Copy(writer, r)
  678. if err != nil {
  679. return nil, err
  680. }
  681. labels := map[string]string{
  682. "containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339),
  683. }
  684. if err := writer.Commit(ctx, 0, "", content.WithLabels(labels)); err != nil {
  685. return nil, err
  686. }
  687. return &types.Descriptor{
  688. MediaType: mediaType,
  689. Digest: writer.Digest(),
  690. Size_: size,
  691. }, nil
  692. }
  693. func wrapError(err error) error {
  694. if err != nil {
  695. msg := err.Error()
  696. for _, s := range []string{"container does not exist", "not found", "no such container"} {
  697. if strings.Contains(msg, s) {
  698. return wrapNotFoundError(err)
  699. }
  700. }
  701. }
  702. return err
  703. }