github.com/cvmfs/docker-graphdriver@v0.0.0-20181206110523-155ec6df0521/repository-manager/cmd/garbage_collection.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  
     8  	log "github.com/sirupsen/logrus"
     9  	"github.com/spf13/cobra"
    10  
    11  	"github.com/cvmfs/docker-graphdriver/repository-manager/lib"
    12  )
    13  
    14  func init() {
    15  	rootCmd.AddCommand(garbageCollectionCmd)
    16  }
    17  
    18  var garbageCollectionCmd = &cobra.Command{
    19  	Use:     "garbage-collection",
    20  	Short:   "Removes layers that are not necessary anymore",
    21  	Aliases: []string{"gc"},
    22  	Args:    cobra.ExactArgs(1),
    23  	Run: func(cmd *cobra.Command, args []string) {
    24  
    25  		fmt.Println("Start")
    26  		repo := args[0]
    27  		llog := func(l *log.Entry) *log.Entry {
    28  			return l.WithFields(log.Fields{"action": "garbage collect",
    29  				"repo": repo,
    30  			})
    31  		}
    32  
    33  		manifestToRemove, err := lib.FindImageToGarbageCollect(repo)
    34  		if err != nil {
    35  			llog(lib.LogE(err)).Warning(
    36  				"Error in finding the image to remove from the scheduler, goin on...")
    37  		}
    38  		images2layers := make(map[string][]string)
    39  
    40  		for _, manifest := range manifestToRemove {
    41  			digest := strings.Split(manifest.Config.Digest, ":")[1]
    42  			for _, layerStruct := range manifest.Layers {
    43  				layerName := strings.Split(layerStruct.Digest, ":")[1]
    44  				images2layers[digest] = append(images2layers[digest], layerName)
    45  			}
    46  		}
    47  
    48  		for image, layers := range images2layers {
    49  			for _, layer := range layers {
    50  				err = lib.GarbageCollectSingleLayer(repo, image, layer)
    51  				if err != nil {
    52  					llog(lib.LogE(err)).Warning(
    53  						"Error in removing a single layer from the repository, going on...")
    54  				}
    55  			}
    56  		}
    57  
    58  		os.Exit(0)
    59  	},
    60  }