-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathcache_clean.go
More file actions
82 lines (74 loc) · 2.44 KB
/
cache_clean.go
File metadata and controls
82 lines (74 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"os"
namepkg "github.com/google/go-containerregistry/pkg/name"
cachepkg "github.com/linuxkit/linuxkit/src/cmd/linuxkit/cache"
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/registry"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func cacheCleanCmd() *cobra.Command {
var (
publishedOnly bool
)
cmd := &cobra.Command{
Use: "clean",
Short: "empty the linuxkit cache",
Long: `Empty the linuxkit cache.`,
RunE: func(cmd *cobra.Command, args []string) error {
// did we limit to published only?
if !publishedOnly {
if err := os.RemoveAll(cacheDir); err != nil {
return fmt.Errorf("uUnable to clean cache %s: %v", cacheDir, err)
}
log.Infof("Cache emptied: %s", cacheDir)
return nil
}
// list all of the images and content in the cache
p, err := cachepkg.NewProvider(cacheDir)
if err != nil {
return fmt.Errorf("unable to read a local cache: %v", err)
}
images, err := p.List()
if err != nil {
return fmt.Errorf("error reading image names: %v", err)
}
removeImagesFromCache(images, p, publishedOnly)
return nil
},
}
cmd.Flags().BoolVar(&publishedOnly, "published-only", false, "Only clean images that linuxkit can confirm at the time of running have been published to the registry")
return cmd
}
// removeImagesFromCache removes images from the cache.
func removeImagesFromCache(images map[string]string, p *cachepkg.Provider, publishedOnly bool) {
// check each image in the registry. If it exists, remove it here.
for name, hash := range images {
if publishedOnly {
ref, err := namepkg.ParseReference(name)
if err != nil {
continue
}
desc, err := registry.GetRemote().Get(ref)
if err != nil {
log.Debugf("image %s not found in remote registry or error, leaving in cache: %v", name, err)
fmt.Fprintf(os.Stderr, "image %s not found in remote registry, leaving in cache", name)
continue
}
if desc == nil {
fmt.Fprintf(os.Stderr, "image %s not found in remote registry, leaving in cache", name)
continue
}
if desc.Digest.String() != hash {
fmt.Fprintf(os.Stderr, "image %s has mismatched hashes, cache %s vs remote registry %s, leaving in cache", name, hash, desc.Digest.String())
continue
}
}
// we have a match, remove it
fmt.Fprintf(os.Stderr, "removing image %s from cache", name)
if err := p.Remove(name); err != nil {
log.Warnf("Unable to remove image %s: %v", name, err)
}
}
}