github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/netutil/nettype/nettype.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 nettype
    18  
    19  import (
    20  	"fmt"
    21  	"strings"
    22  )
    23  
    24  type Type int
    25  
    26  const (
    27  	Invalid Type = iota
    28  	None
    29  	Host
    30  	CNI
    31  	Container
    32  )
    33  
    34  var netTypeToName = map[interface{}]string{
    35  	Invalid:   "invalid",
    36  	None:      "none",
    37  	Host:      "host",
    38  	CNI:       "cni",
    39  	Container: "container",
    40  }
    41  
    42  func Detect(names []string) (Type, error) {
    43  	var res Type
    44  
    45  	for _, name := range names {
    46  		var tmp Type
    47  
    48  		// In case of using --network=container:<container> to share the network namespace
    49  		networkName := strings.SplitN(name, ":", 2)[0]
    50  		switch networkName {
    51  		case "none":
    52  			tmp = None
    53  		case "host":
    54  			tmp = Host
    55  		case "container":
    56  			tmp = Container
    57  		default:
    58  			tmp = CNI
    59  		}
    60  		if res != Invalid && res != tmp {
    61  			return Invalid, fmt.Errorf("mixed network types: %v and %v", netTypeToName[res], netTypeToName[tmp])
    62  		}
    63  		res = tmp
    64  	}
    65  
    66  	// defaults to CNI
    67  	if res == Invalid {
    68  		res = CNI
    69  	}
    70  
    71  	return res, nil
    72  }