Skip to content

Commit 13cbaef

Browse files
committed
chunked: use temporary file for tar-split data
Replace the in-memory buffer with a O_TMPFILE file. This reduces the memory requirements for a partial pull since the tar-split data can be written to disk. Signed-off-by: Giuseppe Scrivano <[email protected]>
1 parent 06ab9ae commit 13cbaef

File tree

6 files changed

+59
-16
lines changed

6 files changed

+59
-16
lines changed

drivers/driver.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ type DriverWithDifferOutput struct {
216216
CompressedDigest digest.Digest
217217
Metadata string
218218
BigData map[string][]byte
219-
TarSplit []byte // nil if not available
219+
TarSplit *os.File // nil if not available
220220
TOCDigest digest.Digest
221221
// RootDirMode is the mode of the root directory of the layer, if specified.
222222
RootDirMode *os.FileMode

layers.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -2550,10 +2550,14 @@ func (r *layerStore) applyDiffFromStagingDirectory(id string, diffOutput *driver
25502550
if err != nil {
25512551
compressor = pgzip.NewWriter(&tsdata)
25522552
}
2553+
if _, err := diffOutput.TarSplit.Seek(0, 0); err != nil {
2554+
return err
2555+
}
2556+
25532557
if err := compressor.SetConcurrency(1024*1024, 1); err != nil { // 1024*1024 is the hard-coded default; we're not changing that
25542558
logrus.Infof("setting compression concurrency threads to 1: %v; ignoring", err)
25552559
}
2556-
if _, err := compressor.Write(diffOutput.TarSplit); err != nil {
2560+
if _, err := diffOutput.TarSplit.WriteTo(compressor); err != nil {
25572561
compressor.Close()
25582562
return err
25592563
}

pkg/chunked/compression_linux.go

+36-7
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"io"
99
"maps"
10+
"os"
1011
"slices"
1112
"strconv"
1213
"time"
@@ -18,6 +19,7 @@ import (
1819
"github.com/vbatts/tar-split/archive/tar"
1920
"github.com/vbatts/tar-split/tar/asm"
2021
"github.com/vbatts/tar-split/tar/storage"
22+
"golang.org/x/sys/unix"
2123
)
2224

2325
const (
@@ -158,9 +160,11 @@ func readEstargzChunkedManifest(blobStream ImageSourceSeekable, blobSize int64,
158160
}
159161

160162
// readZstdChunkedManifest reads the zstd:chunked manifest from the seekable stream blobStream.
163+
// tmpDir is a directory where the tar-split temporary file is written to. The file is opened with
164+
// O_TMPFILE so that it is automatically removed when it is closed.
161165
// Returns (manifest blob, parsed manifest, tar-split blob or nil, manifest offset).
162166
// It may return an error matching ErrFallbackToOrdinaryLayerDownload / errFallbackCanConvert.
163-
func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Digest, annotations map[string]string) (_ []byte, _ *minimal.TOC, _ []byte, _ int64, retErr error) {
167+
func readZstdChunkedManifest(tmpDir string, blobStream ImageSourceSeekable, tocDigest digest.Digest, annotations map[string]string) (_ []byte, _ *minimal.TOC, _ *os.File, _ int64, retErr error) {
164168
offsetMetadata := annotations[minimal.ManifestInfoKey]
165169
if offsetMetadata == "" {
166170
return nil, nil, nil, 0, fmt.Errorf("%q annotation missing", minimal.ManifestInfoKey)
@@ -245,7 +249,7 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
245249
return nil, nil, nil, 0, fmt.Errorf("unmarshaling TOC: %w", err)
246250
}
247251

248-
var decodedTarSplit []byte = nil
252+
var decodedTarSplit *os.File
249253
if toc.TarSplitDigest != "" {
250254
if tarSplitChunk.Offset <= 0 {
251255
return nil, nil, nil, 0, fmt.Errorf("TOC requires a tar-split, but the %s annotation does not describe a position", minimal.TarSplitInfoKey)
@@ -254,14 +258,20 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
254258
if err != nil {
255259
return nil, nil, nil, 0, err
256260
}
257-
decodedTarSplit, err = decodeAndValidateBlob(tarSplit, tarSplitLengthUncompressed, toc.TarSplitDigest.String())
261+
fd, err := unix.Open(tmpDir, unix.O_TMPFILE|unix.O_RDWR|unix.O_CLOEXEC, 0o600)
258262
if err != nil {
263+
return nil, nil, nil, 0, err
264+
}
265+
decodedTarSplit = os.NewFile(uintptr(fd), "decoded-tar-split")
266+
if err := decodeAndValidateBlobToStream(tarSplit, decodedTarSplit, toc.TarSplitDigest.String()); err != nil {
267+
decodedTarSplit.Close()
259268
return nil, nil, nil, 0, fmt.Errorf("validating and decompressing tar-split: %w", err)
260269
}
261270
// We use the TOC for creating on-disk files, but the tar-split for creating metadata
262271
// when exporting the layer contents. Ensure the two match, otherwise local inspection of a container
263272
// might be misleading about the exported contents.
264273
if err := ensureTOCMatchesTarSplit(toc, decodedTarSplit); err != nil {
274+
decodedTarSplit.Close()
265275
return nil, nil, nil, 0, fmt.Errorf("tar-split and TOC data is inconsistent: %w", err)
266276
}
267277
} else if tarSplitChunk.Offset > 0 {
@@ -278,7 +288,7 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
278288
}
279289

280290
// ensureTOCMatchesTarSplit validates that toc and tarSplit contain _exactly_ the same entries.
281-
func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
291+
func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit *os.File) error {
282292
pendingFiles := map[string]*minimal.FileMetadata{} // Name -> an entry in toc.Entries
283293
for i := range toc.Entries {
284294
e := &toc.Entries[i]
@@ -290,7 +300,11 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
290300
}
291301
}
292302

293-
unpacker := storage.NewJSONUnpacker(bytes.NewReader(tarSplit))
303+
if _, err := tarSplit.Seek(0, 0); err != nil {
304+
return err
305+
}
306+
307+
unpacker := storage.NewJSONUnpacker(tarSplit)
294308
if err := asm.IterateHeaders(unpacker, func(hdr *tar.Header) error {
295309
e, ok := pendingFiles[hdr.Name]
296310
if !ok {
@@ -320,10 +334,10 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
320334
}
321335

322336
// tarSizeFromTarSplit computes the total tarball size, using only the tarSplit metadata
323-
func tarSizeFromTarSplit(tarSplit []byte) (int64, error) {
337+
func tarSizeFromTarSplit(tarSplit io.Reader) (int64, error) {
324338
var res int64 = 0
325339

326-
unpacker := storage.NewJSONUnpacker(bytes.NewReader(tarSplit))
340+
unpacker := storage.NewJSONUnpacker(tarSplit)
327341
for {
328342
entry, err := unpacker.Next()
329343
if err != nil {
@@ -464,3 +478,18 @@ func decodeAndValidateBlob(blob []byte, lengthUncompressed uint64, expectedCompr
464478
b := make([]byte, 0, lengthUncompressed)
465479
return decoder.DecodeAll(blob, b)
466480
}
481+
482+
func decodeAndValidateBlobToStream(blob []byte, w *os.File, expectedCompressedChecksum string) error {
483+
if err := validateBlob(blob, expectedCompressedChecksum); err != nil {
484+
return err
485+
}
486+
487+
decoder, err := zstd.NewReader(bytes.NewReader(blob)) //nolint:contextcheck
488+
if err != nil {
489+
return err
490+
}
491+
defer decoder.Close()
492+
493+
_, err = decoder.WriteTo(w)
494+
return err
495+
}

pkg/chunked/compression_linux_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func TestTarSizeFromTarSplit(t *testing.T) {
3939
_, err = io.Copy(io.Discard, tsReader)
4040
require.NoError(t, err)
4141

42-
res, err := tarSizeFromTarSplit(tarSplit.Bytes())
42+
res, err := tarSizeFromTarSplit(&tarSplit)
4343
require.NoError(t, err)
4444
assert.Equal(t, expectedTarSize, res)
4545
}

pkg/chunked/storage_linux.go

+15-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package chunked
22

33
import (
44
archivetar "archive/tar"
5-
"bytes"
65
"context"
76
"encoding/base64"
87
"errors"
@@ -89,7 +88,7 @@ type chunkedDiffer struct {
8988
tocOffset int64
9089
manifest []byte
9190
toc *minimal.TOC // The parsed contents of manifest, or nil if not yet available
92-
tarSplit []byte
91+
tarSplit *os.File
9392
uncompressedTarSize int64 // -1 if unknown
9493
// skipValidation is set to true if the individual files in
9594
// the layer are trusted and should not be validated.
@@ -194,6 +193,11 @@ func (c *chunkedDiffer) convertTarToZstdChunked(destDirectory string, payload *o
194193
}
195194

196195
func (c *chunkedDiffer) Close() error {
196+
if c.tarSplit != nil {
197+
err := c.tarSplit.Close()
198+
c.tarSplit = nil
199+
return err
200+
}
197201
return nil
198202
}
199203

@@ -337,13 +341,16 @@ func makeConvertFromRawDiffer(store storage.Store, blobDigest digest.Digest, blo
337341
// makeZstdChunkedDiffer sets up a chunkedDiffer for a zstd:chunked layer.
338342
// It may return an error matching ErrFallbackToOrdinaryLayerDownload / errFallbackCanConvert.
339343
func makeZstdChunkedDiffer(store storage.Store, blobSize int64, tocDigest digest.Digest, annotations map[string]string, iss ImageSourceSeekable, pullOptions pullOptions) (*chunkedDiffer, error) {
340-
manifest, toc, tarSplit, tocOffset, err := readZstdChunkedManifest(iss, tocDigest, annotations)
344+
manifest, toc, tarSplit, tocOffset, err := readZstdChunkedManifest(store.RunRoot(), iss, tocDigest, annotations)
341345
if err != nil { // May be ErrFallbackToOrdinaryLayerDownload / errFallbackCanConvert
342346
return nil, fmt.Errorf("read zstd:chunked manifest: %w", err)
343347
}
344348

345349
var uncompressedTarSize int64 = -1
346350
if tarSplit != nil {
351+
if _, err := tarSplit.Seek(0, 0); err != nil {
352+
return nil, err
353+
}
347354
uncompressedTarSize, err = tarSizeFromTarSplit(tarSplit)
348355
if err != nil {
349356
return nil, fmt.Errorf("computing size from tar-split: %w", err)
@@ -1439,7 +1446,7 @@ func (c *chunkedDiffer) ApplyDiff(dest string, options *archive.TarOptions, diff
14391446
if tocDigest == nil {
14401447
return graphdriver.DriverWithDifferOutput{}, fmt.Errorf("internal error: just-created zstd:chunked missing TOC digest")
14411448
}
1442-
manifest, toc, tarSplit, tocOffset, err := readZstdChunkedManifest(fileSource, *tocDigest, annotations)
1449+
manifest, toc, tarSplit, tocOffset, err := readZstdChunkedManifest(dest, fileSource, *tocDigest, annotations)
14431450
if err != nil {
14441451
return graphdriver.DriverWithDifferOutput{}, fmt.Errorf("read zstd:chunked manifest: %w", err)
14451452
}
@@ -1846,7 +1853,10 @@ func (c *chunkedDiffer) ApplyDiff(dest string, options *archive.TarOptions, diff
18461853
case c.pullOptions.insecureAllowUnpredictableImageContents:
18471854
// Oh well. Skip the costly digest computation.
18481855
case output.TarSplit != nil:
1849-
metadata := tsStorage.NewJSONUnpacker(bytes.NewReader(output.TarSplit))
1856+
if _, err := output.TarSplit.Seek(0, 0); err != nil {
1857+
return output, err
1858+
}
1859+
metadata := tsStorage.NewJSONUnpacker(output.TarSplit)
18501860
fg := newStagedFileGetter(dirFile, flatPathNameMap)
18511861
digester := digest.Canonical.Digester()
18521862
if err := asm.WriteOutputTarStream(fg, metadata, digester.Hash()); err != nil {

pkg/chunked/zstdchunked_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ func TestGenerateAndParseManifest(t *testing.T) {
179179
tocDigest, err := toc.GetTOCDigest(annotations)
180180
require.NoError(t, err)
181181
require.NotNil(t, tocDigest)
182-
manifest, decodedTOC, _, _, err := readZstdChunkedManifest(s, *tocDigest, annotations)
182+
manifest, decodedTOC, _, _, err := readZstdChunkedManifest(t.TempDir(), s, *tocDigest, annotations)
183183
require.NoError(t, err)
184184

185185
var toc minimal.TOC

0 commit comments

Comments
 (0)