github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/network/remove.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/nerdctl/v2/pkg/api/types"
    25  	"github.com/containerd/nerdctl/v2/pkg/idutil/netwalker"
    26  	"github.com/containerd/nerdctl/v2/pkg/netutil"
    27  )
    28  
    29  func Remove(ctx context.Context, client *containerd.Client, options types.NetworkRemoveOptions) error {
    30  	e, err := netutil.NewCNIEnv(options.GOptions.CNIPath, options.GOptions.CNINetConfPath)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	usedNetworkInfo, err := netutil.UsedNetworks(ctx, client)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	walker := netwalker.NetworkWalker{
    41  		Client: e,
    42  		OnFound: func(ctx context.Context, found netwalker.Found) error {
    43  			if found.MatchCount > 1 {
    44  				return fmt.Errorf("multiple IDs found with provided prefix: %s", found.Req)
    45  			}
    46  			if value, ok := usedNetworkInfo[found.Network.Name]; ok {
    47  				return fmt.Errorf("network %q is in use by container %q", found.Req, value)
    48  			}
    49  			if found.Network.NerdctlID == nil {
    50  				return fmt.Errorf("%s is managed outside nerdctl and cannot be removed", found.Req)
    51  			}
    52  			if found.Network.File == "" {
    53  				return fmt.Errorf("%s is a pre-defined network and cannot be removed", found.Req)
    54  			}
    55  			if err := e.RemoveNetwork(found.Network); err != nil {
    56  				return err
    57  			}
    58  			fmt.Fprintln(options.Stdout, found.Req)
    59  			return nil
    60  		},
    61  	}
    62  
    63  	return walker.WalkAll(ctx, options.Networks, true, false)
    64  }