github.com/opencontainers/umoci@v0.4.8-0.20240508124516-656e4836fb0d/cmd/umoci/gc.go (about)

     1  /*
     2   * umoci: Umoci Modifies Open Containers' Images
     3   * Copyright (C) 2016-2020 SUSE LLC
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *    http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package main
    19  
    20  import (
    21  	"context"
    22  
    23  	"github.com/opencontainers/umoci/oci/cas/dir"
    24  	"github.com/opencontainers/umoci/oci/casext"
    25  	"github.com/pkg/errors"
    26  	"github.com/urfave/cli"
    27  )
    28  
    29  var gcCommand = cli.Command{
    30  	Name:  "gc",
    31  	Usage: "garbage-collects an OCI image's blobs",
    32  	ArgsUsage: `--layout <image-path>
    33  
    34  Where "<image-path>" is the path to the OCI image.
    35  
    36  This command will do a mark-and-sweep garbage collection of the provided OCI
    37  image, only retaining blobs which can be reached by a descriptor path from the
    38  root set of references. All other blobs will be removed.`,
    39  
    40  	// create modifies an image layout.
    41  	Category: "layout",
    42  
    43  	Before: func(ctx *cli.Context) error {
    44  		if ctx.NArg() != 0 {
    45  			return errors.Errorf("invalid number of positional arguments: expected none")
    46  		}
    47  		if _, ok := ctx.App.Metadata["--image-path"]; !ok {
    48  			return errors.Errorf("missing mandatory argument: --layout")
    49  		}
    50  		return nil
    51  	},
    52  
    53  	Action: gc,
    54  }
    55  
    56  func gc(ctx *cli.Context) error {
    57  	imagePath := ctx.App.Metadata["--image-path"].(string)
    58  
    59  	// Get a reference to the CAS.
    60  	engine, err := dir.Open(imagePath)
    61  	if err != nil {
    62  		return errors.Wrap(err, "open CAS")
    63  	}
    64  	engineExt := casext.NewEngine(engine)
    65  	defer engine.Close()
    66  
    67  	// Run the GC.
    68  	return errors.Wrap(engineExt.GC(context.Background()), "gc")
    69  }