client_daemon.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. specs "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. fifos := newFIFOSet(ctr.bundleDir, id, InitProcessName, withStdin, spec.Process.Terminal)
  175. cio, err = c.createIO(fifos, id, InitProcessName, stdinCloseSync, attachStdio)
  176. return cio, err
  177. },
  178. func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
  179. info.Checkpoint = cp
  180. info.Options = &runcopts.CreateOptions{
  181. IoUid: uint32(uid),
  182. IoGid: uint32(gid),
  183. }
  184. return nil
  185. })
  186. if err != nil {
  187. close(stdinCloseSync)
  188. if cio != nil {
  189. cio.Cancel()
  190. cio.Close()
  191. }
  192. return -1, err
  193. }
  194. c.Lock()
  195. c.containers[id].task = t
  196. c.Unlock()
  197. // Signal c.createIO that it can call CloseIO
  198. close(stdinCloseSync)
  199. if err := t.Start(ctx); err != nil {
  200. if _, err := t.Delete(ctx); err != nil {
  201. c.logger.WithError(err).WithField("container", id).
  202. Error("failed to delete task after fail start")
  203. }
  204. c.Lock()
  205. c.containers[id].task = nil
  206. c.Unlock()
  207. return -1, err
  208. }
  209. return int(t.Pid()), nil
  210. }
  211. func (c *client) Exec(ctx context.Context, containerID, processID string, spec *specs.Process, withStdin bool, attachStdio StdioCallback) (int, error) {
  212. ctr := c.getContainer(containerID)
  213. switch {
  214. case ctr == nil:
  215. return -1, errors.WithStack(newNotFoundError("no such container"))
  216. case ctr.task == nil:
  217. return -1, errors.WithStack(newInvalidParameterError("container is not running"))
  218. case ctr.execs != nil && ctr.execs[processID] != nil:
  219. return -1, errors.WithStack(newConflictError("id already in use"))
  220. }
  221. var (
  222. p containerd.Process
  223. cio containerd.IO
  224. err error
  225. stdinCloseSync = make(chan struct{})
  226. )
  227. fifos := newFIFOSet(ctr.bundleDir, containerID, processID, withStdin, spec.Terminal)
  228. defer func() {
  229. if err != nil {
  230. if cio != nil {
  231. cio.Cancel()
  232. cio.Close()
  233. }
  234. rmFIFOSet(fifos)
  235. }
  236. }()
  237. p, err = ctr.task.Exec(ctx, processID, spec, func(id string) (containerd.IO, error) {
  238. cio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio)
  239. return cio, err
  240. })
  241. if err != nil {
  242. close(stdinCloseSync)
  243. if cio != nil {
  244. cio.Cancel()
  245. cio.Close()
  246. }
  247. return -1, err
  248. }
  249. ctr.Lock()
  250. if ctr.execs == nil {
  251. ctr.execs = make(map[string]containerd.Process)
  252. }
  253. ctr.execs[processID] = p
  254. ctr.Unlock()
  255. // Signal c.createIO that it can call CloseIO
  256. close(stdinCloseSync)
  257. if err = p.Start(ctx); err != nil {
  258. p.Delete(context.Background())
  259. ctr.Lock()
  260. delete(ctr.execs, processID)
  261. ctr.Unlock()
  262. return -1, err
  263. }
  264. return int(p.Pid()), nil
  265. }
  266. func (c *client) SignalProcess(ctx context.Context, containerID, processID string, signal int) error {
  267. p, err := c.getProcess(containerID, processID)
  268. if err != nil {
  269. return err
  270. }
  271. return p.Kill(ctx, syscall.Signal(signal))
  272. }
  273. func (c *client) ResizeTerminal(ctx context.Context, containerID, processID string, width, height int) error {
  274. p, err := c.getProcess(containerID, processID)
  275. if err != nil {
  276. return err
  277. }
  278. return p.Resize(ctx, uint32(width), uint32(height))
  279. }
  280. func (c *client) CloseStdin(ctx context.Context, containerID, processID string) error {
  281. p, err := c.getProcess(containerID, processID)
  282. if err != nil {
  283. return err
  284. }
  285. return p.CloseIO(ctx, containerd.WithStdinCloser)
  286. }
  287. func (c *client) Pause(ctx context.Context, containerID string) error {
  288. p, err := c.getProcess(containerID, InitProcessName)
  289. if err != nil {
  290. return err
  291. }
  292. return p.(containerd.Task).Pause(ctx)
  293. }
  294. func (c *client) Resume(ctx context.Context, containerID string) error {
  295. p, err := c.getProcess(containerID, InitProcessName)
  296. if err != nil {
  297. return err
  298. }
  299. return p.(containerd.Task).Resume(ctx)
  300. }
  301. func (c *client) Stats(ctx context.Context, containerID string) (*Stats, error) {
  302. p, err := c.getProcess(containerID, InitProcessName)
  303. if err != nil {
  304. return nil, err
  305. }
  306. m, err := p.(containerd.Task).Metrics(ctx)
  307. if err != nil {
  308. return nil, err
  309. }
  310. v, err := typeurl.UnmarshalAny(m.Data)
  311. if err != nil {
  312. return nil, err
  313. }
  314. return interfaceToStats(m.Timestamp, v), nil
  315. }
  316. func (c *client) ListPids(ctx context.Context, containerID string) ([]uint32, error) {
  317. p, err := c.getProcess(containerID, InitProcessName)
  318. if err != nil {
  319. return nil, err
  320. }
  321. pis, err := p.(containerd.Task).Pids(ctx)
  322. if err != nil {
  323. return nil, err
  324. }
  325. var pids []uint32
  326. for _, i := range pis {
  327. pids = append(pids, i.Pid)
  328. }
  329. return pids, nil
  330. }
  331. func (c *client) Summary(ctx context.Context, containerID string) ([]Summary, error) {
  332. p, err := c.getProcess(containerID, InitProcessName)
  333. if err != nil {
  334. return nil, err
  335. }
  336. pis, err := p.(containerd.Task).Pids(ctx)
  337. if err != nil {
  338. return nil, err
  339. }
  340. var infos []Summary
  341. for _, pi := range pis {
  342. i, err := typeurl.UnmarshalAny(pi.Info)
  343. if err != nil {
  344. return nil, errors.Wrap(err, "unable to decode process details")
  345. }
  346. s, err := summaryFromInterface(i)
  347. if err != nil {
  348. return nil, err
  349. }
  350. infos = append(infos, *s)
  351. }
  352. return infos, nil
  353. }
  354. func (c *client) DeleteTask(ctx context.Context, containerID string) (uint32, time.Time, error) {
  355. p, err := c.getProcess(containerID, InitProcessName)
  356. if err != nil {
  357. return 255, time.Now(), nil
  358. }
  359. status, err := p.(containerd.Task).Delete(ctx)
  360. if err != nil {
  361. return 255, time.Now(), nil
  362. }
  363. c.Lock()
  364. if ctr, ok := c.containers[containerID]; ok {
  365. ctr.task = nil
  366. }
  367. c.Unlock()
  368. return status.ExitCode(), status.ExitTime(), nil
  369. }
  370. func (c *client) Delete(ctx context.Context, containerID string) error {
  371. ctr := c.getContainer(containerID)
  372. if ctr == nil {
  373. return errors.WithStack(newNotFoundError("no such container"))
  374. }
  375. if err := ctr.ctr.Delete(ctx); err != nil {
  376. return err
  377. }
  378. if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" {
  379. if err := os.RemoveAll(ctr.bundleDir); err != nil {
  380. c.logger.WithError(err).WithFields(logrus.Fields{
  381. "container": containerID,
  382. "bundle": ctr.bundleDir,
  383. }).Error("failed to remove state dir")
  384. }
  385. }
  386. c.removeContainer(containerID)
  387. return nil
  388. }
  389. func (c *client) Status(ctx context.Context, containerID string) (Status, error) {
  390. ctr := c.getContainer(containerID)
  391. if ctr == nil {
  392. return StatusUnknown, errors.WithStack(newNotFoundError("no such container"))
  393. }
  394. s, err := ctr.task.Status(ctx)
  395. if err != nil {
  396. return StatusUnknown, err
  397. }
  398. return Status(s.Status), nil
  399. }
  400. func (c *client) CreateCheckpoint(ctx context.Context, containerID, checkpointDir string, exit bool) error {
  401. p, err := c.getProcess(containerID, InitProcessName)
  402. if err != nil {
  403. return err
  404. }
  405. img, err := p.(containerd.Task).Checkpoint(ctx)
  406. if err != nil {
  407. return err
  408. }
  409. // Whatever happens, delete the checkpoint from containerd
  410. defer func() {
  411. err := c.remote.ImageService().Delete(context.Background(), img.Name())
  412. if err != nil {
  413. c.logger.WithError(err).WithField("digest", img.Target().Digest).
  414. Warnf("failed to delete checkpoint image")
  415. }
  416. }()
  417. b, err := content.ReadBlob(ctx, c.remote.ContentStore(), img.Target().Digest)
  418. if err != nil {
  419. return wrapSystemError(errors.Wrapf(err, "failed to retrieve checkpoint data"))
  420. }
  421. var index v1.Index
  422. if err := json.Unmarshal(b, &index); err != nil {
  423. return wrapSystemError(errors.Wrapf(err, "failed to decode checkpoint data"))
  424. }
  425. var cpDesc *v1.Descriptor
  426. for _, m := range index.Manifests {
  427. if m.MediaType == images.MediaTypeContainerd1Checkpoint {
  428. cpDesc = &m
  429. break
  430. }
  431. }
  432. if cpDesc == nil {
  433. return wrapSystemError(errors.Wrapf(err, "invalid checkpoint"))
  434. }
  435. rat, err := c.remote.ContentStore().ReaderAt(ctx, cpDesc.Digest)
  436. if err != nil {
  437. return wrapSystemError(errors.Wrapf(err, "failed to get checkpoint reader"))
  438. }
  439. defer rat.Close()
  440. _, err = archive.Apply(ctx, checkpointDir, content.NewReader(rat))
  441. if err != nil {
  442. return wrapSystemError(errors.Wrapf(err, "failed to read checkpoint reader"))
  443. }
  444. return err
  445. }
  446. func (c *client) getContainer(id string) *container {
  447. c.RLock()
  448. ctr := c.containers[id]
  449. c.RUnlock()
  450. return ctr
  451. }
  452. func (c *client) removeContainer(id string) {
  453. c.Lock()
  454. delete(c.containers, id)
  455. c.Unlock()
  456. }
  457. func (c *client) getProcess(containerID, processID string) (containerd.Process, error) {
  458. ctr := c.getContainer(containerID)
  459. switch {
  460. case ctr == nil:
  461. return nil, errors.WithStack(newNotFoundError("no such container"))
  462. case ctr.task == nil:
  463. return nil, errors.WithStack(newNotFoundError("container is not running"))
  464. case processID == InitProcessName:
  465. return ctr.task, nil
  466. default:
  467. ctr.Lock()
  468. defer ctr.Unlock()
  469. if ctr.execs == nil {
  470. return nil, errors.WithStack(newNotFoundError("no execs"))
  471. }
  472. }
  473. p := ctr.execs[processID]
  474. if p == nil {
  475. return nil, errors.WithStack(newNotFoundError("no such exec"))
  476. }
  477. return p, nil
  478. }
  479. // createIO creates the io to be used by a process
  480. // This needs to get a pointer to interface as upon closure the process may not have yet been registered
  481. func (c *client) createIO(fifos *containerd.FIFOSet, containerID, processID string, stdinCloseSync chan struct{}, attachStdio StdioCallback) (containerd.IO, error) {
  482. io, err := newIOPipe(fifos)
  483. if err != nil {
  484. return nil, err
  485. }
  486. if io.Stdin != nil {
  487. var (
  488. err error
  489. stdinOnce sync.Once
  490. )
  491. pipe := io.Stdin
  492. io.Stdin = ioutils.NewWriteCloserWrapper(pipe, func() error {
  493. stdinOnce.Do(func() {
  494. err = pipe.Close()
  495. // Do the rest in a new routine to avoid a deadlock if the
  496. // Exec/Start call failed.
  497. go func() {
  498. <-stdinCloseSync
  499. p, err := c.getProcess(containerID, processID)
  500. if err == nil {
  501. err = p.CloseIO(context.Background(), containerd.WithStdinCloser)
  502. if err != nil && strings.Contains(err.Error(), "transport is closing") {
  503. err = nil
  504. }
  505. }
  506. }()
  507. })
  508. return err
  509. })
  510. }
  511. cio, err := attachStdio(io)
  512. if err != nil {
  513. io.Cancel()
  514. io.Close()
  515. }
  516. return cio, err
  517. }
  518. func (c *client) processEvent(ctr *container, et EventType, ei EventInfo) {
  519. c.eventQ.append(ei.ContainerID, func() {
  520. err := c.backend.ProcessEvent(ei.ContainerID, et, ei)
  521. if err != nil {
  522. c.logger.WithError(err).WithFields(logrus.Fields{
  523. "container": ei.ContainerID,
  524. "event": et,
  525. "event-info": ei,
  526. }).Error("failed to process event")
  527. }
  528. if et == EventExit && ei.ProcessID != ei.ContainerID {
  529. var p containerd.Process
  530. ctr.Lock()
  531. if ctr.execs != nil {
  532. p = ctr.execs[ei.ProcessID]
  533. }
  534. ctr.Unlock()
  535. if p == nil {
  536. c.logger.WithError(errors.New("no such process")).
  537. WithFields(logrus.Fields{
  538. "container": ei.ContainerID,
  539. "process": ei.ProcessID,
  540. }).Error("exit event")
  541. return
  542. }
  543. _, err = p.Delete(context.Background())
  544. if err != nil {
  545. c.logger.WithError(err).WithFields(logrus.Fields{
  546. "container": ei.ContainerID,
  547. "process": ei.ProcessID,
  548. }).Warn("failed to delete process")
  549. }
  550. c.Lock()
  551. delete(ctr.execs, ei.ProcessID)
  552. c.Unlock()
  553. ctr := c.getContainer(ei.ContainerID)
  554. if ctr == nil {
  555. c.logger.WithFields(logrus.Fields{
  556. "container": ei.ContainerID,
  557. }).Error("failed to find container")
  558. } else {
  559. rmFIFOSet(newFIFOSet(ctr.bundleDir, ei.ContainerID, ei.ProcessID, true, false))
  560. }
  561. }
  562. })
  563. }
  564. func (c *client) processEventStream(ctx context.Context) {
  565. var (
  566. err error
  567. eventStream eventsapi.Events_SubscribeClient
  568. ev *eventsapi.Envelope
  569. et EventType
  570. ei EventInfo
  571. ctr *container
  572. )
  573. defer func() {
  574. if err != nil {
  575. select {
  576. case <-ctx.Done():
  577. c.logger.WithError(ctx.Err()).
  578. Info("stopping event stream following graceful shutdown")
  579. default:
  580. go c.processEventStream(ctx)
  581. }
  582. }
  583. }()
  584. eventStream, err = c.remote.EventService().Subscribe(ctx, &eventsapi.SubscribeRequest{
  585. Filters: []string{"namespace==" + c.namespace + ",topic~=/tasks/.+"},
  586. }, grpc.FailFast(false))
  587. if err != nil {
  588. return
  589. }
  590. var oomKilled bool
  591. for {
  592. ev, err = eventStream.Recv()
  593. if err != nil {
  594. c.logger.WithError(err).Error("failed to get event")
  595. return
  596. }
  597. if ev.Event == nil {
  598. c.logger.WithField("event", ev).Warn("invalid event")
  599. continue
  600. }
  601. v, err := typeurl.UnmarshalAny(ev.Event)
  602. if err != nil {
  603. c.logger.WithError(err).WithField("event", ev).Warn("failed to unmarshal event")
  604. continue
  605. }
  606. c.logger.WithField("topic", ev.Topic).Debug("event")
  607. switch t := v.(type) {
  608. case *eventsapi.TaskCreate:
  609. et = EventCreate
  610. ei = EventInfo{
  611. ContainerID: t.ContainerID,
  612. ProcessID: t.ContainerID,
  613. Pid: t.Pid,
  614. }
  615. case *eventsapi.TaskStart:
  616. et = EventStart
  617. ei = EventInfo{
  618. ContainerID: t.ContainerID,
  619. ProcessID: t.ContainerID,
  620. Pid: t.Pid,
  621. }
  622. case *eventsapi.TaskExit:
  623. et = EventExit
  624. ei = EventInfo{
  625. ContainerID: t.ContainerID,
  626. ProcessID: t.ID,
  627. Pid: t.Pid,
  628. ExitCode: t.ExitStatus,
  629. ExitedAt: t.ExitedAt,
  630. }
  631. case *eventsapi.TaskOOM:
  632. et = EventOOM
  633. ei = EventInfo{
  634. ContainerID: t.ContainerID,
  635. OOMKilled: true,
  636. }
  637. oomKilled = true
  638. case *eventsapi.TaskExecAdded:
  639. et = EventExecAdded
  640. ei = EventInfo{
  641. ContainerID: t.ContainerID,
  642. ProcessID: t.ExecID,
  643. }
  644. case *eventsapi.TaskExecStarted:
  645. et = EventExecStarted
  646. ei = EventInfo{
  647. ContainerID: t.ContainerID,
  648. ProcessID: t.ExecID,
  649. Pid: t.Pid,
  650. }
  651. case *eventsapi.TaskPaused:
  652. et = EventPaused
  653. ei = EventInfo{
  654. ContainerID: t.ContainerID,
  655. }
  656. case *eventsapi.TaskResumed:
  657. et = EventResumed
  658. ei = EventInfo{
  659. ContainerID: t.ContainerID,
  660. }
  661. default:
  662. c.logger.WithFields(logrus.Fields{
  663. "topic": ev.Topic,
  664. "type": reflect.TypeOf(t)},
  665. ).Info("ignoring event")
  666. continue
  667. }
  668. ctr = c.getContainer(ei.ContainerID)
  669. if ctr == nil {
  670. c.logger.WithField("container", ei.ContainerID).Warn("unknown container")
  671. continue
  672. }
  673. if oomKilled {
  674. ctr.oomKilled = true
  675. oomKilled = false
  676. }
  677. ei.OOMKilled = ctr.oomKilled
  678. c.processEvent(ctr, et, ei)
  679. }
  680. }
  681. func (c *client) writeContent(ctx context.Context, mediaType, ref string, r io.Reader) (*types.Descriptor, error) {
  682. writer, err := c.remote.ContentStore().Writer(ctx, ref, 0, "")
  683. if err != nil {
  684. return nil, err
  685. }
  686. defer writer.Close()
  687. size, err := io.Copy(writer, r)
  688. if err != nil {
  689. return nil, err
  690. }
  691. labels := map[string]string{
  692. "containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339),
  693. }
  694. if err := writer.Commit(ctx, 0, "", content.WithLabels(labels)); err != nil {
  695. return nil, err
  696. }
  697. return &types.Descriptor{
  698. MediaType: mediaType,
  699. Digest: writer.Digest(),
  700. Size_: size,
  701. }, nil
  702. }
  703. func wrapError(err error) error {
  704. if err != nil {
  705. msg := err.Error()
  706. for _, s := range []string{"container does not exist", "not found", "no such container"} {
  707. if strings.Contains(msg, s) {
  708. return wrapNotFoundError(err)
  709. }
  710. }
  711. }
  712. return err
  713. }