cmd: add a CLI wrapper for GarbageCollect

Add "gc" as an action for the CLI wrapper, for running the
GarbageCollect() method.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>
This commit is contained in:
Nalin Dahyabhai 2023-01-25 13:23:56 -05:00
parent c9b3bdc284
commit 6d91bc12f3
5 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,37 @@
package main
import (
"fmt"
"os"
"github.com/containers/storage"
"github.com/containers/storage/pkg/mflag"
)
func gc(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) {
defer func() {
if _, err := m.Shutdown(true); err != nil {
fmt.Fprintf(os.Stderr, "shutdown: %v\n", err)
}
}()
if err := m.GarbageCollect(); err != nil {
return 1, err
}
if jsonOutput {
return outputJSON(string(""))
}
return 0, nil
}
func init() {
commands = append(commands, command{
names: []string{"gc"},
usage: "Perform garbage collection",
minArgs: 0,
maxArgs: 0,
action: gc,
addFlags: func(flags *mflag.FlagSet, cmd *command) {
flags.BoolVar(&jsonOutput, []string{"-json", "j"}, jsonOutput, "Prefer JSON output")
},
})
}

View File

@ -14,6 +14,7 @@ import (
"github.com/containers/storage/pkg/stringid"
"github.com/containers/storage/pkg/truncindex"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
type containerLocations uint8
@ -420,6 +421,7 @@ func (r *containerStore) GarbageCollect() error {
}
// Otherwise remove datadir
logrus.Debugf("removing %q", filepath.Join(r.dir, id))
moreErr := os.RemoveAll(filepath.Join(r.dir, id))
// Propagate first error
if moreErr != nil && err == nil {

View File

@ -0,0 +1,16 @@
## containers-storage-gc 1 "January 2023"
## NAME
containers-storage gc - Garbage collect leftovers from partial layers/images/contianers
## SYNOPSIS
**containers-storage** **gc**
## DESCRIPTION
Removes additional data for layers, images, and containers which would
correspond to layers, images, and containers which don't actually exist, but
which may have been left on the filesystem after canceled attempts to create
those layers, images, or containers.
## EXAMPLE
**containers-storage gc**

View File

@ -14,6 +14,7 @@ import (
"github.com/containers/storage/pkg/stringutils"
"github.com/containers/storage/pkg/truncindex"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
const (
@ -423,6 +424,7 @@ func (r *imageStore) GarbageCollect() error {
}
// Otherwise remove datadir
logrus.Debugf("removing %q", filepath.Join(r.dir, id))
moreErr := os.RemoveAll(filepath.Join(r.dir, id))
// Propagate first error
if moreErr != nil && err == nil {

View File

@ -678,10 +678,13 @@ func (r *layerStore) GarbageCollect() error {
// Remove layer and any related data of unreferenced id
if err := r.driver.Remove(id); err != nil {
logrus.Debugf("removing driver layer %q", id)
return err
}
logrus.Debugf("removing %q", r.tspath(id))
os.Remove(r.tspath(id))
logrus.Debugf("removing %q", r.datadir(id))
os.RemoveAll(r.datadir(id))
}
return nil