github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/volume/prune.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package volume
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	"github.com/containerd/containerd"
    24  	"github.com/containerd/nerdctl/v2/pkg/api/types"
    25  	"github.com/containerd/nerdctl/v2/pkg/labels"
    26  )
    27  
    28  func Prune(ctx context.Context, client *containerd.Client, options types.VolumePruneOptions) error {
    29  	volStore, err := Store(options.GOptions.Namespace, options.GOptions.DataRoot, options.GOptions.Address)
    30  	if err != nil {
    31  		return err
    32  	}
    33  	volumes, err := volStore.List(false)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	containers, err := client.Containers(ctx)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	usedVolumes, err := usedVolumes(ctx, containers)
    43  	if err != nil {
    44  		return err
    45  	}
    46  	var removeNames []string // nolint: prealloc
    47  	for _, volume := range volumes {
    48  		if _, ok := usedVolumes[volume.Name]; ok {
    49  			continue
    50  		}
    51  		if !options.All {
    52  			val, ok := (*volume.Labels)[labels.AnonymousVolumes]
    53  			//skip the named volume and only remove the anonymous volume
    54  			if !ok || val != "" {
    55  				continue
    56  			}
    57  		}
    58  		removeNames = append(removeNames, volume.Name)
    59  	}
    60  	removedNames, err := volStore.Remove(removeNames)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	if len(removedNames) > 0 {
    65  		fmt.Fprintln(options.Stdout, "Deleted Volumes:")
    66  		for _, name := range removedNames {
    67  			fmt.Fprintln(options.Stdout, name)
    68  		}
    69  		fmt.Fprintln(options.Stdout, "")
    70  	}
    71  	return nil
    72  }