image_commit.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. "github.com/docker/docker/internal/compatcontext"
  22. "github.com/docker/docker/pkg/archive"
  23. imagespec "github.com/moby/docker-image-spec/specs-go/v1"
  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, *cc.ContainerConfig)
  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. }
  130. }
  131. // createDiff creates a layer diff into containerd's content store.
  132. // If the diff is empty it returns nil empty digest and no error.
  133. func (i *ImageService) createDiff(ctx context.Context, name string, sn snapshots.Snapshotter, cs content.Store, comparer diff.Comparer) (*ocispec.Descriptor, digest.Digest, error) {
  134. info, err := sn.Stat(ctx, name)
  135. if err != nil {
  136. return nil, "", err
  137. }
  138. var upper []mount.Mount
  139. if !i.idMapping.Empty() {
  140. // The rootfs of the container is remapped if an id mapping exists, we
  141. // need to "unremap" it before committing the snapshot
  142. rootPair := i.idMapping.RootPair()
  143. usernsID := fmt.Sprintf("%s-%d-%d-%s", name, rootPair.UID, rootPair.GID, uniquePart())
  144. remappedID := usernsID + remapSuffix
  145. baseName := name
  146. if info.Kind == snapshots.KindActive {
  147. source, err := sn.Mounts(ctx, name)
  148. if err != nil {
  149. return nil, "", err
  150. }
  151. // No need to use parent since the whole snapshot is copied.
  152. // Using parent would require doing diff/apply while starting
  153. // from empty can just copy the whole snapshot.
  154. // TODO: Optimize this for overlay mounts, can use parent
  155. // and just copy upper directories without mounting
  156. upper, err = sn.Prepare(ctx, remappedID, "")
  157. if err != nil {
  158. return nil, "", err
  159. }
  160. if err := i.copyAndUnremapRootFS(ctx, upper, source); err != nil {
  161. return nil, "", err
  162. }
  163. } else {
  164. upper, err = sn.Prepare(ctx, remappedID, baseName)
  165. if err != nil {
  166. return nil, "", err
  167. }
  168. if err := i.unremapRootFS(ctx, upper); err != nil {
  169. return nil, "", err
  170. }
  171. }
  172. } else {
  173. if info.Kind == snapshots.KindActive {
  174. upper, err = sn.Mounts(ctx, name)
  175. if err != nil {
  176. return nil, "", err
  177. }
  178. } else {
  179. upperKey := fmt.Sprintf("%s-view-%s", name, uniquePart())
  180. upper, err = sn.View(ctx, upperKey, name)
  181. if err != nil {
  182. return nil, "", err
  183. }
  184. defer cleanup.Do(ctx, func(ctx context.Context) {
  185. sn.Remove(ctx, upperKey)
  186. })
  187. }
  188. }
  189. lowerKey := fmt.Sprintf("%s-parent-view-%s", info.Parent, uniquePart())
  190. lower, err := sn.View(ctx, lowerKey, info.Parent)
  191. if err != nil {
  192. return nil, "", err
  193. }
  194. defer cleanup.Do(ctx, func(ctx context.Context) {
  195. sn.Remove(ctx, lowerKey)
  196. })
  197. newDesc, err := comparer.Compare(ctx, lower, upper)
  198. if err != nil {
  199. return nil, "", errors.Wrap(err, "CreateDiff")
  200. }
  201. ra, err := cs.ReaderAt(ctx, newDesc)
  202. if err != nil {
  203. return nil, "", fmt.Errorf("failed to read diff archive: %w", err)
  204. }
  205. defer ra.Close()
  206. empty, err := archive.IsEmpty(content.NewReader(ra))
  207. if err != nil {
  208. return nil, "", fmt.Errorf("failed to check if archive is empty: %w", err)
  209. }
  210. if empty {
  211. return nil, "", nil
  212. }
  213. cinfo, err := cs.Info(ctx, newDesc.Digest)
  214. if err != nil {
  215. return nil, "", fmt.Errorf("failed to get content info: %w", err)
  216. }
  217. diffIDStr, ok := cinfo.Labels["containerd.io/uncompressed"]
  218. if !ok {
  219. return nil, "", fmt.Errorf("invalid differ response with no diffID")
  220. }
  221. diffID, err := digest.Parse(diffIDStr)
  222. if err != nil {
  223. return nil, "", err
  224. }
  225. return &ocispec.Descriptor{
  226. MediaType: ocispec.MediaTypeImageLayerGzip,
  227. Digest: newDesc.Digest,
  228. Size: cinfo.Size,
  229. }, diffID, nil
  230. }
  231. // applyDiffLayer will apply diff layer content created by createDiff into the snapshotter.
  232. func (i *ImageService) applyDiffLayer(ctx context.Context, name string, containerID string, sn snapshots.Snapshotter, differ diff.Applier, diffDesc ocispec.Descriptor) (retErr error) {
  233. // Let containerd know that this snapshot is only for diff-applying.
  234. key := snapshots.UnpackKeyPrefix + "-" + uniquePart() + "-" + name
  235. info, err := sn.Stat(ctx, containerID)
  236. if err != nil {
  237. return err
  238. }
  239. mounts, err := sn.Prepare(ctx, key, info.Parent)
  240. if err != nil {
  241. return fmt.Errorf("failed to prepare snapshot: %w", err)
  242. }
  243. defer func() {
  244. if retErr != nil {
  245. // NOTE: the snapshotter should be held by lease. Even
  246. // if the cleanup fails, the containerd gc can delete it.
  247. if err := sn.Remove(ctx, key); err != nil {
  248. log.G(ctx).Warnf("failed to cleanup aborted apply %s: %s", key, err)
  249. }
  250. }
  251. }()
  252. if _, err = differ.Apply(ctx, diffDesc, mounts); err != nil {
  253. return err
  254. }
  255. if err = sn.Commit(ctx, name, key); err != nil {
  256. if cerrdefs.IsAlreadyExists(err) {
  257. return nil
  258. }
  259. return err
  260. }
  261. return nil
  262. }
  263. // copied from github.com/containerd/containerd/rootfs/apply.go
  264. func uniquePart() string {
  265. t := time.Now()
  266. var b [3]byte
  267. // Ignore read failures, just decreases uniqueness
  268. rand.Read(b[:])
  269. return fmt.Sprintf("%d-%s", t.Nanosecond(), base64.URLEncoding.EncodeToString(b[:]))
  270. }
  271. // CommitBuildStep is used by the builder to create an image for each step in
  272. // the build.
  273. //
  274. // This method is different from CreateImageFromContainer:
  275. // - it doesn't attempt to validate container state
  276. // - it doesn't send a commit action to metrics
  277. // - it doesn't log a container commit event
  278. //
  279. // This is a temporary shim. Should be removed when builder stops using commit.
  280. func (i *ImageService) CommitBuildStep(ctx context.Context, c backend.CommitConfig) (image.ID, error) {
  281. ctr := i.containers.Get(c.ContainerID)
  282. if ctr == nil {
  283. // TODO: use typed error
  284. return "", fmt.Errorf("container not found: %s", c.ContainerID)
  285. }
  286. c.ContainerMountLabel = ctr.MountLabel
  287. c.ContainerOS = ctr.OS
  288. c.ParentImageID = string(ctr.ImageID)
  289. return i.CommitImage(ctx, c)
  290. }