image_commit.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package containerd
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "runtime"
  9. "strings"
  10. "time"
  11. "github.com/containerd/containerd/content"
  12. "github.com/containerd/containerd/diff"
  13. cerrdefs "github.com/containerd/containerd/errdefs"
  14. "github.com/containerd/containerd/leases"
  15. "github.com/containerd/containerd/mount"
  16. "github.com/containerd/containerd/pkg/cleanup"
  17. "github.com/containerd/containerd/snapshots"
  18. "github.com/containerd/log"
  19. "github.com/docker/docker/api/types/backend"
  20. "github.com/docker/docker/image"
  21. imagespec "github.com/docker/docker/image/spec/specs-go/v1"
  22. "github.com/docker/docker/internal/compatcontext"
  23. "github.com/docker/docker/pkg/archive"
  24. "github.com/opencontainers/go-digest"
  25. "github.com/opencontainers/image-spec/identity"
  26. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  27. "github.com/pkg/errors"
  28. )
  29. /*
  30. This code is based on `commit` support in nerdctl, under Apache License
  31. https://github.com/containerd/nerdctl/blob/master/pkg/imgutil/commit/commit.go
  32. with adaptations to match the Moby data model and services.
  33. */
  34. // CommitImage creates a new image from a commit config.
  35. func (i *ImageService) CommitImage(ctx context.Context, cc backend.CommitConfig) (image.ID, error) {
  36. container := i.containers.Get(cc.ContainerID)
  37. cs := i.client.ContentStore()
  38. var parentManifest ocispec.Manifest
  39. var parentImage imagespec.DockerOCIImage
  40. // ImageManifest can be nil when committing an image with base FROM scratch
  41. if container.ImageManifest != nil {
  42. imageManifestBytes, err := content.ReadBlob(ctx, cs, *container.ImageManifest)
  43. if err != nil {
  44. return "", err
  45. }
  46. if err := json.Unmarshal(imageManifestBytes, &parentManifest); err != nil {
  47. return "", err
  48. }
  49. imageConfigBytes, err := content.ReadBlob(ctx, cs, parentManifest.Config)
  50. if err != nil {
  51. return "", err
  52. }
  53. if err := json.Unmarshal(imageConfigBytes, &parentImage); err != nil {
  54. return "", err
  55. }
  56. }
  57. var (
  58. differ = i.client.DiffService()
  59. sn = i.client.SnapshotService(container.Driver)
  60. )
  61. // Don't gc me and clean the dirty data after 1 hour!
  62. ctx, release, err := i.client.WithLease(ctx, leases.WithRandomID(), leases.WithExpiration(1*time.Hour))
  63. if err != nil {
  64. return "", fmt.Errorf("failed to create lease for commit: %w", err)
  65. }
  66. defer func() {
  67. if err := release(compatcontext.WithoutCancel(ctx)); err != nil {
  68. log.G(ctx).WithError(err).Warn("failed to release lease created for commit")
  69. }
  70. }()
  71. diffLayerDesc, diffID, err := i.createDiff(ctx, cc.ContainerID, sn, cs, differ)
  72. if err != nil {
  73. return "", fmt.Errorf("failed to export layer: %w", err)
  74. }
  75. imageConfig := generateCommitImageConfig(parentImage, diffID, cc)
  76. layers := parentManifest.Layers
  77. if diffLayerDesc != nil {
  78. rootfsID := identity.ChainID(imageConfig.RootFS.DiffIDs).String()
  79. if err := i.applyDiffLayer(ctx, rootfsID, cc.ContainerID, sn, differ, *diffLayerDesc); err != nil {
  80. return "", fmt.Errorf("failed to apply diff: %w", err)
  81. }
  82. layers = append(layers, *diffLayerDesc)
  83. }
  84. return i.createImageOCI(ctx, imageConfig, digest.Digest(cc.ParentImageID), layers)
  85. }
  86. // generateCommitImageConfig generates an OCI Image config based on the
  87. // container's image and the CommitConfig options.
  88. func generateCommitImageConfig(baseConfig imagespec.DockerOCIImage, diffID digest.Digest, opts backend.CommitConfig) imagespec.DockerOCIImage {
  89. if opts.Author == "" {
  90. opts.Author = baseConfig.Author
  91. }
  92. createdTime := time.Now()
  93. arch := baseConfig.Architecture
  94. if arch == "" {
  95. arch = runtime.GOARCH
  96. log.G(context.TODO()).Warnf("assuming arch=%q", arch)
  97. }
  98. os := baseConfig.OS
  99. if os == "" {
  100. os = runtime.GOOS
  101. log.G(context.TODO()).Warnf("assuming os=%q", os)
  102. }
  103. log.G(context.TODO()).Debugf("generateCommitImageConfig(): arch=%q, os=%q", arch, os)
  104. diffIds := baseConfig.RootFS.DiffIDs
  105. if diffID != "" {
  106. diffIds = append(diffIds, diffID)
  107. }
  108. return imagespec.DockerOCIImage{
  109. Image: ocispec.Image{
  110. Platform: ocispec.Platform{
  111. Architecture: arch,
  112. OS: os,
  113. },
  114. Created: &createdTime,
  115. Author: opts.Author,
  116. RootFS: ocispec.RootFS{
  117. Type: "layers",
  118. DiffIDs: diffIds,
  119. },
  120. History: append(baseConfig.History, ocispec.History{
  121. Created: &createdTime,
  122. CreatedBy: strings.Join(opts.ContainerConfig.Cmd, " "),
  123. Author: opts.Author,
  124. Comment: opts.Comment,
  125. EmptyLayer: diffID == "",
  126. }),
  127. },
  128. Config: containerConfigToDockerOCIImageConfig(opts.Config),
  129. ContainerConfig: containerConfigToDockerOCIImageConfig(opts.ContainerConfig),
  130. }
  131. }
  132. // createDiff creates a layer diff into containerd's content store.
  133. // If the diff is empty it returns nil empty digest and no error.
  134. func (i *ImageService) createDiff(ctx context.Context, name string, sn snapshots.Snapshotter, cs content.Store, comparer diff.Comparer) (*ocispec.Descriptor, digest.Digest, error) {
  135. info, err := sn.Stat(ctx, name)
  136. if err != nil {
  137. return nil, "", err
  138. }
  139. var upper []mount.Mount
  140. if !i.idMapping.Empty() {
  141. // The rootfs of the container is remapped if an id mapping exists, we
  142. // need to "unremap" it before committing the snapshot
  143. rootPair := i.idMapping.RootPair()
  144. usernsID := fmt.Sprintf("%s-%d-%d-%s", name, rootPair.UID, rootPair.GID, uniquePart())
  145. remappedID := usernsID + remapSuffix
  146. baseName := name
  147. if info.Kind == snapshots.KindActive {
  148. source, err := sn.Mounts(ctx, name)
  149. if err != nil {
  150. return nil, "", err
  151. }
  152. // No need to use parent since the whole snapshot is copied.
  153. // Using parent would require doing diff/apply while starting
  154. // from empty can just copy the whole snapshot.
  155. // TODO: Optimize this for overlay mounts, can use parent
  156. // and just copy upper directories without mounting
  157. upper, err = sn.Prepare(ctx, remappedID, "")
  158. if err != nil {
  159. return nil, "", err
  160. }
  161. if err := i.copyAndUnremapRootFS(ctx, upper, source); err != nil {
  162. return nil, "", err
  163. }
  164. } else {
  165. upper, err = sn.Prepare(ctx, remappedID, baseName)
  166. if err != nil {
  167. return nil, "", err
  168. }
  169. if err := i.unremapRootFS(ctx, upper); err != nil {
  170. return nil, "", err
  171. }
  172. }
  173. } else {
  174. if info.Kind == snapshots.KindActive {
  175. upper, err = sn.Mounts(ctx, name)
  176. if err != nil {
  177. return nil, "", err
  178. }
  179. } else {
  180. upperKey := fmt.Sprintf("%s-view-%s", name, uniquePart())
  181. upper, err = sn.View(ctx, upperKey, name)
  182. if err != nil {
  183. return nil, "", err
  184. }
  185. defer cleanup.Do(ctx, func(ctx context.Context) {
  186. sn.Remove(ctx, upperKey)
  187. })
  188. }
  189. }
  190. lowerKey := fmt.Sprintf("%s-parent-view-%s", info.Parent, uniquePart())
  191. lower, err := sn.View(ctx, lowerKey, info.Parent)
  192. if err != nil {
  193. return nil, "", err
  194. }
  195. defer cleanup.Do(ctx, func(ctx context.Context) {
  196. sn.Remove(ctx, lowerKey)
  197. })
  198. newDesc, err := comparer.Compare(ctx, lower, upper)
  199. if err != nil {
  200. return nil, "", errors.Wrap(err, "CreateDiff")
  201. }
  202. ra, err := cs.ReaderAt(ctx, newDesc)
  203. if err != nil {
  204. return nil, "", fmt.Errorf("failed to read diff archive: %w", err)
  205. }
  206. defer ra.Close()
  207. empty, err := archive.IsEmpty(content.NewReader(ra))
  208. if err != nil {
  209. return nil, "", fmt.Errorf("failed to check if archive is empty: %w", err)
  210. }
  211. if empty {
  212. return nil, "", nil
  213. }
  214. cinfo, err := cs.Info(ctx, newDesc.Digest)
  215. if err != nil {
  216. return nil, "", fmt.Errorf("failed to get content info: %w", err)
  217. }
  218. diffIDStr, ok := cinfo.Labels["containerd.io/uncompressed"]
  219. if !ok {
  220. return nil, "", fmt.Errorf("invalid differ response with no diffID")
  221. }
  222. diffID, err := digest.Parse(diffIDStr)
  223. if err != nil {
  224. return nil, "", err
  225. }
  226. return &ocispec.Descriptor{
  227. MediaType: ocispec.MediaTypeImageLayerGzip,
  228. Digest: newDesc.Digest,
  229. Size: cinfo.Size,
  230. }, diffID, nil
  231. }
  232. // applyDiffLayer will apply diff layer content created by createDiff into the snapshotter.
  233. func (i *ImageService) applyDiffLayer(ctx context.Context, name string, containerID string, sn snapshots.Snapshotter, differ diff.Applier, diffDesc ocispec.Descriptor) (retErr error) {
  234. var (
  235. key = uniquePart() + "-" + name
  236. mounts []mount.Mount
  237. err error
  238. )
  239. info, err := sn.Stat(ctx, containerID)
  240. if err != nil {
  241. return err
  242. }
  243. mounts, err = sn.Prepare(ctx, key, info.Parent)
  244. if err != nil {
  245. return fmt.Errorf("failed to prepare snapshot: %w", err)
  246. }
  247. defer func() {
  248. if retErr != nil {
  249. // NOTE: the snapshotter should be held by lease. Even
  250. // if the cleanup fails, the containerd gc can delete it.
  251. if err := sn.Remove(ctx, key); err != nil {
  252. log.G(ctx).Warnf("failed to cleanup aborted apply %s: %s", key, err)
  253. }
  254. }
  255. }()
  256. if _, err = differ.Apply(ctx, diffDesc, mounts); err != nil {
  257. return err
  258. }
  259. if err = sn.Commit(ctx, name, key); err != nil {
  260. if cerrdefs.IsAlreadyExists(err) {
  261. return nil
  262. }
  263. return err
  264. }
  265. return nil
  266. }
  267. // copied from github.com/containerd/containerd/rootfs/apply.go
  268. func uniquePart() string {
  269. t := time.Now()
  270. var b [3]byte
  271. // Ignore read failures, just decreases uniqueness
  272. rand.Read(b[:])
  273. return fmt.Sprintf("%d-%s", t.Nanosecond(), base64.URLEncoding.EncodeToString(b[:]))
  274. }
  275. // CommitBuildStep is used by the builder to create an image for each step in
  276. // the build.
  277. //
  278. // This method is different from CreateImageFromContainer:
  279. // - it doesn't attempt to validate container state
  280. // - it doesn't send a commit action to metrics
  281. // - it doesn't log a container commit event
  282. //
  283. // This is a temporary shim. Should be removed when builder stops using commit.
  284. func (i *ImageService) CommitBuildStep(ctx context.Context, c backend.CommitConfig) (image.ID, error) {
  285. ctr := i.containers.Get(c.ContainerID)
  286. if ctr == nil {
  287. // TODO: use typed error
  288. return "", fmt.Errorf("container not found: %s", c.ContainerID)
  289. }
  290. c.ContainerMountLabel = ctr.MountLabel
  291. c.ContainerOS = ctr.OS
  292. c.ParentImageID = string(ctr.ImageID)
  293. return i.CommitImage(ctx, c)
  294. }