From b513dc4c1e9094cf1bc60aa86b2c71e2bccb857d Mon Sep 17 00:00:00 2001 From: Ashley Cui Date: Fri, 8 Jul 2022 20:10:25 -0400 Subject: Clean up cached machine images When initing machines, we download a machine image, and uncompress and copy the image for the actual vm image. When a user constantly pulls new machines, there may be a buildup of old, unused machine images. This commit cleans ups the unused cached images. Changes: - If the machine is pulled from a URL or from the FCOS releases, we pull them into XDG_DATA_HOME/containers/podman/machine/vmType/cache - Cache cleanups only happen if there is a cache miss, and we need to pull a new image - For Fedora and FCOS, we actually use the cache, so we go through the cache dir and remove any images older than 2 weeks (FCOS's release cycle), on a cache miss. - For generic files pulled from a URL, we don't actually cache, so we delete the pulled file immediately after creating a machine image - For generic files from a local path, the original file will never be cleaned up Note that because we cache in a different dir, this will not clean up old images pulled before this commit. [NO NEW TESTS NEEDED] Signed-off-by: Ashley Cui --- pkg/machine/fcos.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'pkg/machine/fcos.go') diff --git a/pkg/machine/fcos.go b/pkg/machine/fcos.go index 4ccb99e96..246f92a19 100644 --- a/pkg/machine/fcos.go +++ b/pkg/machine/fcos.go @@ -13,6 +13,7 @@ import ( "path/filepath" "runtime" "strings" + "time" "github.com/coreos/stream-metadata-go/fedoracoreos" "github.com/coreos/stream-metadata-go/release" @@ -53,7 +54,7 @@ func NewFcosDownloader(vmType, vmName, imageStream string) (DistributionDownload return nil, err } - dataDir, err := GetDataDir(vmType) + cacheDir, err := GetCacheDir(vmType) if err != nil { return nil, err } @@ -62,15 +63,20 @@ func NewFcosDownloader(vmType, vmName, imageStream string) (DistributionDownload Download: Download{ Arch: getFcosArch(), Artifact: artifact, + CacheDir: cacheDir, Format: Format, ImageName: imageName, - LocalPath: filepath.Join(dataDir, imageName), + LocalPath: filepath.Join(cacheDir, imageName), Sha256sum: info.Sha256Sum, URL: url, VMName: vmName, }, } - fcd.Download.LocalUncompressedFile = fcd.getLocalUncompressedName() + dataDir, err := GetDataDir(vmType) + if err != nil { + return nil, err + } + fcd.Download.LocalUncompressedFile = fcd.getLocalUncompressedFile(dataDir) return fcd, nil } @@ -108,6 +114,13 @@ func (f FcosDownload) HasUsableCache() (bool, error) { return sum.Encoded() == f.Sha256sum, nil } +func (f FcosDownload) CleanCache() error { + // Set cached image to expire after 2 weeks + // FCOS refreshes around every 2 weeks, assume old images aren't needed + expire := 14 * 24 * time.Hour + return removeImageAfterExpire(f.CacheDir, expire) +} + func getFcosArch() string { var arch string // TODO fill in more architectures -- cgit v1.2.3-54-g00ecf