Skip to content

Commit 4f99cbf

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 3724a5a commit 4f99cbf

File tree

6 files changed

+100
-16
lines changed

6 files changed

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

+55-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 (
@@ -157,10 +159,32 @@ func readEstargzChunkedManifest(blobStream ImageSourceSeekable, blobSize int64,
157159
return manifestUncompressed, tocOffset, nil
158160
}
159161

162+
func openTmpFile(tmpDir string) (*os.File, error) {
163+
file, err := os.OpenFile(tmpDir, unix.O_TMPFILE|unix.O_RDWR|unix.O_CLOEXEC|unix.O_EXCL, 0o600)
164+
if err == nil {
165+
return file, nil
166+
}
167+
return openTmpFileNoTmpFile(tmpDir)
168+
}
169+
170+
// openTmpFileNoTmpFile is a fallback used by openTmpFile when the underlying file system does not
171+
// support O_TMPFILE.
172+
func openTmpFileNoTmpFile(tmpDir string) (*os.File, error) {
173+
file, err := os.CreateTemp(tmpDir, ".tmpfile")
174+
if err != nil {
175+
return nil, err
176+
}
177+
// Unlink the file immediately so that only the open fd refers to it.
178+
_ = os.Remove(file.Name())
179+
return file, nil
180+
}
181+
160182
// readZstdChunkedManifest reads the zstd:chunked manifest from the seekable stream blobStream.
183+
// tmpDir is a directory where the tar-split temporary file is written to. The file is opened with
184+
// O_TMPFILE so that it is automatically removed when it is closed.
161185
// Returns (manifest blob, parsed manifest, tar-split blob or nil, manifest offset).
162186
// 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) {
187+
func readZstdChunkedManifest(tmpDir string, blobStream ImageSourceSeekable, tocDigest digest.Digest, annotations map[string]string) (_ []byte, _ *minimal.TOC, _ *os.File, _ int64, retErr error) {
164188
offsetMetadata := annotations[minimal.ManifestInfoKey]
165189
if offsetMetadata == "" {
166190
return nil, nil, nil, 0, fmt.Errorf("%q annotation missing", minimal.ManifestInfoKey)
@@ -245,7 +269,7 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
245269
return nil, nil, nil, 0, fmt.Errorf("unmarshaling TOC: %w", err)
246270
}
247271

248-
var decodedTarSplit []byte = nil
272+
var decodedTarSplit *os.File
249273
if toc.TarSplitDigest != "" {
250274
if tarSplitChunk.Offset <= 0 {
251275
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 +278,19 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
254278
if err != nil {
255279
return nil, nil, nil, 0, err
256280
}
257-
decodedTarSplit, err = decodeAndValidateBlob(tarSplit, tarSplitLengthUncompressed, toc.TarSplitDigest.String())
281+
decodedTarSplit, err = openTmpFile(tmpDir)
258282
if err != nil {
283+
return nil, nil, nil, 0, err
284+
}
285+
if err := decodeAndValidateBlobToStream(tarSplit, decodedTarSplit, toc.TarSplitDigest.String()); err != nil {
286+
decodedTarSplit.Close()
259287
return nil, nil, nil, 0, fmt.Errorf("validating and decompressing tar-split: %w", err)
260288
}
261289
// We use the TOC for creating on-disk files, but the tar-split for creating metadata
262290
// when exporting the layer contents. Ensure the two match, otherwise local inspection of a container
263291
// might be misleading about the exported contents.
264292
if err := ensureTOCMatchesTarSplit(toc, decodedTarSplit); err != nil {
293+
decodedTarSplit.Close()
265294
return nil, nil, nil, 0, fmt.Errorf("tar-split and TOC data is inconsistent: %w", err)
266295
}
267296
} else if tarSplitChunk.Offset > 0 {
@@ -278,7 +307,7 @@ func readZstdChunkedManifest(blobStream ImageSourceSeekable, tocDigest digest.Di
278307
}
279308

280309
// ensureTOCMatchesTarSplit validates that toc and tarSplit contain _exactly_ the same entries.
281-
func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
310+
func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit *os.File) error {
282311
pendingFiles := map[string]*minimal.FileMetadata{} // Name -> an entry in toc.Entries
283312
for i := range toc.Entries {
284313
e := &toc.Entries[i]
@@ -290,7 +319,11 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
290319
}
291320
}
292321

293-
unpacker := storage.NewJSONUnpacker(bytes.NewReader(tarSplit))
322+
if _, err := tarSplit.Seek(0, 0); err != nil {
323+
return err
324+
}
325+
326+
unpacker := storage.NewJSONUnpacker(tarSplit)
294327
if err := asm.IterateHeaders(unpacker, func(hdr *tar.Header) error {
295328
e, ok := pendingFiles[hdr.Name]
296329
if !ok {
@@ -320,10 +353,10 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
320353
}
321354

322355
// tarSizeFromTarSplit computes the total tarball size, using only the tarSplit metadata
323-
func tarSizeFromTarSplit(tarSplit []byte) (int64, error) {
356+
func tarSizeFromTarSplit(tarSplit io.Reader) (int64, error) {
324357
var res int64 = 0
325358

326-
unpacker := storage.NewJSONUnpacker(bytes.NewReader(tarSplit))
359+
unpacker := storage.NewJSONUnpacker(tarSplit)
327360
for {
328361
entry, err := unpacker.Next()
329362
if err != nil {
@@ -464,3 +497,18 @@ func decodeAndValidateBlob(blob []byte, lengthUncompressed uint64, expectedCompr
464497
b := make([]byte, 0, lengthUncompressed)
465498
return decoder.DecodeAll(blob, b)
466499
}
500+
501+
func decodeAndValidateBlobToStream(blob []byte, w *os.File, expectedCompressedChecksum string) error {
502+
if err := validateBlob(blob, expectedCompressedChecksum); err != nil {
503+
return err
504+
}
505+
506+
decoder, err := zstd.NewReader(bytes.NewReader(blob)) //nolint:contextcheck
507+
if err != nil {
508+
return err
509+
}
510+
defer decoder.Close()
511+
512+
_, err = decoder.WriteTo(w)
513+
return err
514+
}

pkg/chunked/compression_linux_test.go

+23-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package chunked
22

33
import (
44
"bytes"
5+
"fmt"
56
"io"
7+
"os"
68
"testing"
79

810
"github.com/stretchr/testify/assert"
@@ -39,7 +41,27 @@ func TestTarSizeFromTarSplit(t *testing.T) {
3941
_, err = io.Copy(io.Discard, tsReader)
4042
require.NoError(t, err)
4143

42-
res, err := tarSizeFromTarSplit(tarSplit.Bytes())
44+
res, err := tarSizeFromTarSplit(&tarSplit)
4345
require.NoError(t, err)
4446
assert.Equal(t, expectedTarSize, res)
4547
}
48+
49+
func TestOpenTmpFile(t *testing.T) {
50+
for i := 0; i < 1000; i++ {
51+
// scope for cleanup
52+
f := func(fn func(tmpDir string) (*os.File, error)) {
53+
file, err := fn(t.TempDir())
54+
assert.NoError(t, err)
55+
defer file.Close()
56+
57+
path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", file.Fd()))
58+
assert.NoError(t, err)
59+
60+
// the path under /proc/self/fd/$FD has the prefix "(deleted)" when the file
61+
// is unlinked
62+
assert.Contains(t, path, "(deleted)")
63+
}
64+
f(openTmpFile)
65+
f(openTmpFileNoTmpFile)
66+
}
67+
}

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)