Skip to content

Commit c0bf892

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 833c0e2 commit c0bf892

File tree

6 files changed

+86
-16
lines changed

6 files changed

+86
-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

+63-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ import (
66
"errors"
77
"fmt"
88
"io"
9+
"io/fs"
910
"maps"
11+
"math/rand"
12+
"os"
13+
"path/filepath"
1014
"slices"
1115
"strconv"
1216
"time"
@@ -18,6 +22,7 @@ import (
1822
"github.com/vbatts/tar-split/archive/tar"
1923
"github.com/vbatts/tar-split/tar/asm"
2024
"github.com/vbatts/tar-split/tar/storage"
25+
"golang.org/x/sys/unix"
2126
)
2227

2328
const (
@@ -157,10 +162,36 @@ func readEstargzChunkedManifest(blobStream ImageSourceSeekable, blobSize int64,
157162
return manifestUncompressed, tocOffset, nil
158163
}
159164

165+
func openTmpFile(tmpDir string) (fd int, err error) {
166+
fd, err = unix.Open(tmpDir, unix.O_TMPFILE|unix.O_RDWR|unix.O_CLOEXEC, 0o600)
167+
if err == nil {
168+
return fd, nil
169+
}
170+
rand.Seed(int64(os.Getpid()))
171+
for i := 0; i < 100; i++ {
172+
name := fmt.Sprintf(".tmpfile-%d", rand.Int63())
173+
path := filepath.Join(tmpDir, name)
174+
175+
fd, err := unix.Open(path, unix.O_RDWR|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC, 0o600)
176+
if err == nil {
177+
// Unlink the file immediately so that only the open fd refers to it.
178+
_ = os.Remove(path)
179+
return fd, nil
180+
}
181+
if !errors.Is(err, os.ErrNotExist) {
182+
return -1, &fs.PathError{Op: "open", Path: tmpDir, Err: err}
183+
}
184+
}
185+
// report the original error if the fallback failed
186+
return -1, &fs.PathError{Op: "open O_TMPFILE", Path: tmpDir, Err: err}
187+
}
188+
160189
// readZstdChunkedManifest reads the zstd:chunked manifest from the seekable stream blobStream.
190+
// tmpDir is a directory where the tar-split temporary file is written to. The file is opened with
191+
// O_TMPFILE so that it is automatically removed when it is closed.
161192
// Returns (manifest blob, parsed manifest, tar-split blob or nil, manifest offset).
162193
// 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) {
194+
func readZstdChunkedManifest(tmpDir string, blobStream ImageSourceSeekable, tocDigest digest.Digest, annotations map[string]string) (_ []byte, _ *minimal.TOC, _ *os.File, _ int64, retErr error) {
164195
offsetMetadata := annotations[minimal.ManifestInfoKey]
165196
if offsetMetadata == "" {
166197
return nil, nil, nil, 0, fmt.Errorf("%q annotation missing", minimal.ManifestInfoKey)
@@ -245,7 +276,7 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
245276
return nil, nil, nil, 0, fmt.Errorf("unmarshaling TOC: %w", err)
246277
}
247278

248-
var decodedTarSplit []byte = nil
279+
var decodedTarSplit *os.File
249280
if toc.TarSplitDigest != "" {
250281
if tarSplitChunk.Offset <= 0 {
251282
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 +285,20 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
254285
if err != nil {
255286
return nil, nil, nil, 0, err
256287
}
257-
decodedTarSplit, err = decodeAndValidateBlob(tarSplit, tarSplitLengthUncompressed, toc.TarSplitDigest.String())
288+
fd, err := openTmpFile(tmpDir)
258289
if err != nil {
290+
return nil, nil, nil, 0, err
291+
}
292+
decodedTarSplit = os.NewFile(uintptr(fd), "decoded-tar-split")
293+
if err := decodeAndValidateBlobToStream(tarSplit, decodedTarSplit, toc.TarSplitDigest.String()); err != nil {
294+
decodedTarSplit.Close()
259295
return nil, nil, nil, 0, fmt.Errorf("validating and decompressing tar-split: %w", err)
260296
}
261297
// We use the TOC for creating on-disk files, but the tar-split for creating metadata
262298
// when exporting the layer contents. Ensure the two match, otherwise local inspection of a container
263299
// might be misleading about the exported contents.
264300
if err := ensureTOCMatchesTarSplit(toc, decodedTarSplit); err != nil {
301+
decodedTarSplit.Close()
265302
return nil, nil, nil, 0, fmt.Errorf("tar-split and TOC data is inconsistent: %w", err)
266303
}
267304
} else if tarSplitChunk.Offset > 0 {
@@ -278,7 +315,7 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
278315
}
279316

280317
// ensureTOCMatchesTarSplit validates that toc and tarSplit contain _exactly_ the same entries.
281-
func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
318+
func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit *os.File) error {
282319
pendingFiles := map[string]*minimal.FileMetadata{} // Name -> an entry in toc.Entries
283320
for i := range toc.Entries {
284321
e := &toc.Entries[i]
@@ -290,7 +327,11 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
290327
}
291328
}
292329

293-
unpacker := storage.NewJSONUnpacker(bytes.NewReader(tarSplit))
330+
if _, err := tarSplit.Seek(0, 0); err != nil {
331+
return err
332+
}
333+
334+
unpacker := storage.NewJSONUnpacker(tarSplit)
294335
if err := asm.IterateHeaders(unpacker, func(hdr *tar.Header) error {
295336
e, ok := pendingFiles[hdr.Name]
296337
if !ok {
@@ -320,10 +361,10 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
320361
}
321362

322363
// tarSizeFromTarSplit computes the total tarball size, using only the tarSplit metadata
323-
func tarSizeFromTarSplit(tarSplit []byte) (int64, error) {
364+
func tarSizeFromTarSplit(tarSplit io.Reader) (int64, error) {
324365
var res int64 = 0
325366

326-
unpacker := storage.NewJSONUnpacker(bytes.NewReader(tarSplit))
367+
unpacker := storage.NewJSONUnpacker(tarSplit)
327368
for {
328369
entry, err := unpacker.Next()
329370
if err != nil {
@@ -464,3 +505,18 @@ func decodeAndValidateBlob(blob []byte, lengthUncompressed uint64, expectedCompr
464505
b := make([]byte, 0, lengthUncompressed)
465506
return decoder.DecodeAll(blob, b)
466507
}
508+
509+
func decodeAndValidateBlobToStream(blob []byte, w *os.File, expectedCompressedChecksum string) error {
510+
if err := validateBlob(blob, expectedCompressedChecksum); err != nil {
511+
return err
512+
}
513+
514+
decoder, err := zstd.NewReader(bytes.NewReader(blob)) //nolint:contextcheck
515+
if err != nil {
516+
return err
517+
}
518+
defer decoder.Close()
519+
520+
_, err = decoder.WriteTo(w)
521+
return err
522+
}

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)