image_commit.go 10 KB

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