github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/network/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 network
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	"github.com/containerd/containerd"
    24  	"github.com/containerd/log"
    25  	"github.com/containerd/nerdctl/v2/pkg/api/types"
    26  	"github.com/containerd/nerdctl/v2/pkg/netutil"
    27  	"github.com/containerd/nerdctl/v2/pkg/strutil"
    28  )
    29  
    30  func Prune(ctx context.Context, client *containerd.Client, options types.NetworkPruneOptions) error {
    31  	e, err := netutil.NewCNIEnv(options.GOptions.CNIPath, options.GOptions.CNINetConfPath)
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	usedNetworks, err := netutil.UsedNetworks(ctx, client)
    37  	if err != nil {
    38  		return err
    39  	}
    40  
    41  	networkConfigs, err := e.NetworkList()
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	var removedNetworks []string // nolint: prealloc
    47  	for _, net := range networkConfigs {
    48  		if strutil.InStringSlice(options.NetworkDriversToKeep, net.Name) {
    49  			continue
    50  		}
    51  		if net.NerdctlID == nil || net.File == "" {
    52  			continue
    53  		}
    54  		if _, ok := usedNetworks[net.Name]; ok {
    55  			continue
    56  		}
    57  		if err := e.RemoveNetwork(net); err != nil {
    58  			log.G(ctx).WithError(err).Errorf("failed to remove network %s", net.Name)
    59  			continue
    60  		}
    61  		removedNetworks = append(removedNetworks, net.Name)
    62  	}
    63  
    64  	if len(removedNetworks) > 0 {
    65  		fmt.Fprintln(options.Stdout, "Deleted Networks:")
    66  		for _, name := range removedNetworks {
    67  			fmt.Fprintln(options.Stdout, name)
    68  		}
    69  		fmt.Fprintln(options.Stdout, "")
    70  	}
    71  	return nil
    72  }