...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils/cidr.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils

     1  // Copyright 2020 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package netutils
    15  
    16  import (
    17  	"net"
    18  	"strings"
    19  )
    20  
    21  // IPToCidr converts from an ip to a full mask cidr
    22  func IPToCidr(ip string) string {
    23  	// TODO: support IPv6
    24  	return ip + "/32"
    25  }
    26  
    27  // ResolveCidrs converts multiple cidrs/ips/domains into cidr
    28  func ResolveCidrs(names []string) ([]string, error) {
    29  	cidrs := []string{}
    30  	for _, target := range names {
    31  		// TODO: resolve ip on every pods but not in controller, in case the dns server of these pods differ
    32  		cidr, err := ResolveCidr(target)
    33  		if err != nil {
    34  			return nil, err
    35  		}
    36  
    37  		cidrs = append(cidrs, cidr...)
    38  	}
    39  
    40  	return cidrs, nil
    41  }
    42  
    43  // ResolveCidr converts cidr/ip/domain into cidr
    44  func ResolveCidr(name string) ([]string, error) {
    45  	_, ipnet, err := net.ParseCIDR(name)
    46  	if err == nil {
    47  		return []string{ipnet.String()}, nil
    48  	}
    49  
    50  	if net.ParseIP(name) != nil {
    51  		return []string{IPToCidr(name)}, nil
    52  	}
    53  
    54  	addrs, err := net.LookupIP(name)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	cidrs := []string{}
    60  	for _, addr := range addrs {
    61  		addr := addr.String()
    62  
    63  		// TODO: support IPv6
    64  		if strings.Contains(addr, ".") {
    65  			cidrs = append(cidrs, IPToCidr(addr))
    66  		}
    67  	}
    68  	return cidrs, nil
    69  }
    70