client_daemon.go 20 KB

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