Skip to content

Commit 4f95510

Browse files
oceanc80Per Goncalves da Silva
authored andcommitted
Clear cache on startup, use tempDir for unpacking
Signed-off-by: Per Goncalves da Silva <pegoncal@redhat.com>
1 parent 037b9e2 commit 4f95510

File tree

3 files changed

+173
-23
lines changed

3 files changed

+173
-23
lines changed

catalogd/cmd/catalogd/main.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,10 @@ func main() {
263263
}
264264

265265
unpackCacheBasePath := filepath.Join(cacheDir, source.UnpackCacheDir)
266+
if err := os.RemoveAll(unpackCacheBasePath); err != nil {
267+
setupLog.Error(err, "unable to clear cache directory for unpacking on startup")
268+
os.Exit(1)
269+
}
266270
if err := os.MkdirAll(unpackCacheBasePath, 0770); err != nil {
267271
setupLog.Error(err, "unable to create cache directory for unpacking")
268272
os.Exit(1)
@@ -290,6 +294,10 @@ func main() {
290294
metrics.Registry.MustRegister(catalogdmetrics.RequestDurationMetric)
291295

292296
storeDir := filepath.Join(cacheDir, storageDir)
297+
if err := os.RemoveAll(storeDir); err != nil {
298+
setupLog.Error(err, "unable to clear storage directory for unpacking on startup")
299+
os.Exit(1)
300+
}
293301
if err := os.MkdirAll(storeDir, 0700); err != nil {
294302
setupLog.Error(err, "unable to create storage directory for catalogs")
295303
os.Exit(1)

catalogd/internal/source/containers_image.go

Lines changed: 76 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"errors"
77
"fmt"
88
"io"
9+
"io/fs"
910
"os"
1011
"path"
1112
"path/filepath"
@@ -80,8 +81,14 @@ func (i *ContainersImageRegistry) Unpack(ctx context.Context, catalog *catalogdv
8081
if !unpackStat.IsDir() {
8182
panic(fmt.Sprintf("unexpected file at unpack path %q: expected a directory", unpackPath))
8283
}
83-
l.Info("image already unpacked", "ref", imgRef.String(), "digest", canonicalRef.Digest().String())
84-
return successResult(unpackPath, canonicalRef, unpackStat.ModTime()), nil
84+
85+
// check unpack directory is read-only
86+
// this should only happen once all the contents have been unpacked and is a good
87+
// indication that unpack completed successfully
88+
if unpackStat.Mode().Perm()&0200 == 0 {
89+
l.Info("image already unpacked", "ref", imgRef.String(), "digest", canonicalRef.Digest().String())
90+
return successResult(unpackPath, canonicalRef, unpackStat.ModTime()), nil
91+
}
8592
}
8693

8794
//////////////////////////////////////////////////////
@@ -296,11 +303,17 @@ func (i *ContainersImageRegistry) unpackImage(ctx context.Context, unpackPath st
296303
return wrapTerminal(fmt.Errorf("catalog image is missing the required label %q", ConfigDirLabel), specIsCanonical)
297304
}
298305

299-
if err := os.MkdirAll(unpackPath, 0700); err != nil {
300-
return fmt.Errorf("error creating unpack directory: %w", err)
301-
}
302306
l := log.FromContext(ctx)
303-
l.Info("unpacking image", "path", unpackPath)
307+
tempUnpackPath, err := os.MkdirTemp("", "unpack-*")
308+
if err != nil {
309+
return fmt.Errorf("error creating temporary unpack directory: %w", err)
310+
}
311+
defer func() {
312+
if err := os.RemoveAll(tempUnpackPath); err != nil {
313+
l.Error(err, "error removing temporary unpack directory")
314+
}
315+
}()
316+
l.Info("unpacking image", "path", unpackPath, "temp path", tempUnpackPath)
304317
for i, layerInfo := range img.LayerInfos() {
305318
if err := func() error {
306319
layerReader, _, err := layoutSrc.GetBlob(ctx, layerInfo, none.NoCache)
@@ -309,21 +322,76 @@ func (i *ContainersImageRegistry) unpackImage(ctx context.Context, unpackPath st
309322
}
310323
defer layerReader.Close()
311324

312-
if err := applyLayer(ctx, unpackPath, dirToUnpack, layerReader); err != nil {
325+
if err := applyLayer(ctx, tempUnpackPath, dirToUnpack, layerReader); err != nil {
313326
return fmt.Errorf("error applying layer[%d]: %w", i, err)
314327
}
315328
l.Info("applied layer", "layer", i)
316329
return nil
317330
}(); err != nil {
318-
return errors.Join(err, deleteRecursive(unpackPath))
331+
return errors.Join(err, deleteRecursive(tempUnpackPath))
319332
}
320333
}
334+
335+
// ensure unpack path is empty
336+
if err := os.RemoveAll(unpackPath); err != nil {
337+
return fmt.Errorf("error removing unpack path: %w", err)
338+
}
339+
if err := copyRecursively(tempUnpackPath, unpackPath, 0700); err != nil {
340+
return fmt.Errorf("error moving temporary unpack directory to final unpack directory: %w", err)
341+
}
321342
if err := setReadOnlyRecursive(unpackPath); err != nil {
322343
return fmt.Errorf("error making unpack directory read-only: %w", err)
323344
}
324345
return nil
325346
}
326347

348+
func copyRecursively(srcPath string, destPath string, perm os.FileMode) error {
349+
// ensure destination path not exist
350+
if _, err := os.Stat(destPath); err == nil {
351+
return fmt.Errorf("destination path %q already exists", destPath)
352+
} else if !os.IsNotExist(err) {
353+
return fmt.Errorf("error checking destination path: %w", err)
354+
}
355+
return filepath.WalkDir(srcPath, func(path string, d fs.DirEntry, err error) error {
356+
if err != nil {
357+
return err
358+
}
359+
relPath, err := filepath.Rel(srcPath, path)
360+
if err != nil {
361+
return err
362+
}
363+
destFullPath := filepath.Join(destPath, relPath)
364+
if d.IsDir() {
365+
return os.MkdirAll(destFullPath, perm)
366+
}
367+
if d.Type()&os.ModeSymlink != 0 {
368+
linkDest, err := os.Readlink(path)
369+
if err != nil {
370+
return err
371+
}
372+
return os.Symlink(linkDest, destFullPath)
373+
}
374+
return copyFile(path, destFullPath)
375+
})
376+
}
377+
378+
func copyFile(src, dest string) error {
379+
in, err := os.Open(src)
380+
if err != nil {
381+
return err
382+
}
383+
defer in.Close()
384+
385+
out, err := os.Create(dest)
386+
if err != nil {
387+
return err
388+
}
389+
defer out.Close()
390+
391+
_, err = io.Copy(out, in)
392+
return err
393+
}
394+
327395
func applyLayer(ctx context.Context, destPath string, srcPath string, layer io.ReadCloser) error {
328396
decompressed, _, err := compression.AutoDecompress(layer)
329397
if err != nil {

catalogd/internal/source/containers_image_test.go

Lines changed: 89 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,13 @@ func TestImageRegistry(t *testing.T) {
3838
// if the Catalog.Spec.Source.Image.Ref field is empty,
3939
// one is injected during test runtime to ensure it
4040
// points to the registry created for the test
41-
catalog *catalogdv1.ClusterCatalog
42-
wantErr bool
43-
terminal bool
44-
image v1.Image
45-
digestAlreadyExists bool
46-
oldDigestExists bool
41+
catalog *catalogdv1.ClusterCatalog
42+
wantErr bool
43+
terminal bool
44+
image v1.Image
45+
unpackPathExists bool
46+
unfinishedUnpack bool
47+
oldDigestExists bool
4748
// refType is the type of image ref this test
4849
// is using. Should be one of "tag","digest"
4950
refType string
@@ -176,8 +177,8 @@ func TestImageRegistry(t *testing.T) {
176177
}
177178
return img
178179
}(),
179-
digestAlreadyExists: true,
180-
refType: "tag",
180+
unpackPathExists: true,
181+
refType: "tag",
181182
},
182183
{
183184
name: "digest based image, digest already exists in cache",
@@ -194,9 +195,9 @@ func TestImageRegistry(t *testing.T) {
194195
},
195196
},
196197
},
197-
wantErr: false,
198-
digestAlreadyExists: true,
199-
refType: "digest",
198+
wantErr: false,
199+
unpackPathExists: true,
200+
refType: "digest",
200201
image: func() v1.Image {
201202
img, err := random.Image(20, 3)
202203
if err != nil {
@@ -239,6 +240,41 @@ func TestImageRegistry(t *testing.T) {
239240
return img
240241
}(),
241242
},
243+
{
244+
name: "tag ref, unpack path exists but is not read-only (possibly uncaught unpack issue)",
245+
catalog: &catalogdv1.ClusterCatalog{
246+
ObjectMeta: metav1.ObjectMeta{
247+
Name: "test",
248+
},
249+
Spec: catalogdv1.ClusterCatalogSpec{
250+
Source: catalogdv1.CatalogSource{
251+
Type: catalogdv1.SourceTypeImage,
252+
Image: &catalogdv1.ImageSource{
253+
Ref: "",
254+
},
255+
},
256+
},
257+
},
258+
wantErr: false,
259+
refType: "tag",
260+
unpackPathExists: true,
261+
unfinishedUnpack: true,
262+
image: func() v1.Image {
263+
img, err := random.Image(20, 3)
264+
if err != nil {
265+
panic(err)
266+
}
267+
img, err = mutate.Config(img, v1.Config{
268+
Labels: map[string]string{
269+
source.ConfigDirLabel: "/configs",
270+
},
271+
})
272+
if err != nil {
273+
panic(err)
274+
}
275+
return img
276+
}(),
277+
},
242278
{
243279
name: "tag ref, happy path",
244280
catalog: &catalogdv1.ClusterCatalog{
@@ -272,6 +308,41 @@ func TestImageRegistry(t *testing.T) {
272308
return img
273309
}(),
274310
},
311+
{
312+
name: "digest ref, unpack path exists but is not read-only (possibly uncaught unpack issue)",
313+
catalog: &catalogdv1.ClusterCatalog{
314+
ObjectMeta: metav1.ObjectMeta{
315+
Name: "test",
316+
},
317+
Spec: catalogdv1.ClusterCatalogSpec{
318+
Source: catalogdv1.CatalogSource{
319+
Type: catalogdv1.SourceTypeImage,
320+
Image: &catalogdv1.ImageSource{
321+
Ref: "",
322+
},
323+
},
324+
},
325+
},
326+
wantErr: false,
327+
refType: "digest",
328+
unpackPathExists: true,
329+
unfinishedUnpack: true,
330+
image: func() v1.Image {
331+
img, err := random.Image(20, 3)
332+
if err != nil {
333+
panic(err)
334+
}
335+
img, err = mutate.Config(img, v1.Config{
336+
Labels: map[string]string{
337+
source.ConfigDirLabel: "/configs",
338+
},
339+
})
340+
if err != nil {
341+
panic(err)
342+
}
343+
return img
344+
}(),
345+
},
275346
{
276347
name: "digest ref, happy path",
277348
catalog: &catalogdv1.ClusterCatalog{
@@ -362,9 +433,12 @@ func TestImageRegistry(t *testing.T) {
362433
require.NoError(t, err)
363434

364435
// if the digest should already exist in the cache, create it
365-
if tt.digestAlreadyExists {
366-
err = os.MkdirAll(filepath.Join(testCache, tt.catalog.Name, digest.String()), os.ModePerm)
367-
require.NoError(t, err)
436+
if tt.unpackPathExists {
437+
unpackPath := filepath.Join(testCache, tt.catalog.Name, digest.String())
438+
require.NoError(t, os.MkdirAll(unpackPath, os.ModePerm))
439+
if !tt.unfinishedUnpack {
440+
require.NoError(t, os.Chmod(unpackPath, 0500))
441+
}
368442
}
369443

370444
err = remote.Write(imgName, tt.image)
@@ -397,7 +471,7 @@ func TestImageRegistry(t *testing.T) {
397471
require.NoError(t, err)
398472
assert.Len(t, entries, 1)
399473
// If the digest should already exist check that we actually hit it
400-
if tt.digestAlreadyExists {
474+
if tt.unpackPathExists && !tt.unfinishedUnpack {
401475
assert.Contains(t, buf.String(), "image already unpacked")
402476
assert.Equal(t, rs.UnpackTime, unpackDirStat.ModTime().Truncate(time.Second))
403477
} else if tt.oldDigestExists {

0 commit comments

Comments
 (0)