diff --git a/cluster/images/etcd/migrate/integration_test.go b/cluster/images/etcd/migrate/integration_test.go index ff3b2959e7f..f181c1f864a 100644 --- a/cluster/images/etcd/migrate/integration_test.go +++ b/cluster/images/etcd/migrate/integration_test.go @@ -39,6 +39,7 @@ import ( "github.com/blang/semver" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) var ( @@ -307,7 +308,7 @@ func getOrCreateTestCertFiles(certFileName, keyFileName string, spec TestCertSpe func parseIPList(ips []string) []net.IP { var netIPs []net.IP for _, ip := range ips { - netIPs = append(netIPs, net.ParseIP(ip)) + netIPs = append(netIPs, netutils.ParseIPSloppy(ip)) } return netIPs } @@ -335,7 +336,7 @@ func generateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS IsCA: true, } - if ip := net.ParseIP(host); ip != nil { + if ip := netutils.ParseIPSloppy(host); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, host) diff --git a/cmd/cloud-controller-manager/nodeipamcontroller.go b/cmd/cloud-controller-manager/nodeipamcontroller.go index 31e5e242809..76c302f8b8f 100644 --- a/cmd/cloud-controller-manager/nodeipamcontroller.go +++ b/cmd/cloud-controller-manager/nodeipamcontroller.go @@ -96,14 +96,14 @@ func startNodeIpamController(ccmConfig *cloudcontrollerconfig.CompletedConfig, n // service cidr processing if len(strings.TrimSpace(nodeIPAMConfig.ServiceCIDR)) != 0 { - _, serviceCIDR, err = net.ParseCIDR(nodeIPAMConfig.ServiceCIDR) + _, serviceCIDR, err = netutils.ParseCIDRSloppy(nodeIPAMConfig.ServiceCIDR) if err != nil { klog.Warningf("Unsuccessful parsing of service CIDR %v: %v", nodeIPAMConfig.ServiceCIDR, err) } } if len(strings.TrimSpace(nodeIPAMConfig.SecondaryServiceCIDR)) != 0 { - _, secondaryServiceCIDR, err = net.ParseCIDR(nodeIPAMConfig.SecondaryServiceCIDR) + _, secondaryServiceCIDR, err = netutils.ParseCIDRSloppy(nodeIPAMConfig.SecondaryServiceCIDR) if err != nil { klog.Warningf("Unsuccessful parsing of service CIDR %v: %v", nodeIPAMConfig.SecondaryServiceCIDR, err) } diff --git a/cmd/kube-apiserver/app/options/options_test.go b/cmd/kube-apiserver/app/options/options_test.go index 912285fd4bf..09214ae41db 100644 --- a/cmd/kube-apiserver/app/options/options_test.go +++ b/cmd/kube-apiserver/app/options/options_test.go @@ -39,6 +39,7 @@ import ( "k8s.io/kubernetes/pkg/controlplane/reconcilers" kubeoptions "k8s.io/kubernetes/pkg/kubeapiserver/options" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" + netutils "k8s.io/utils/net" ) func TestAddFlags(t *testing.T) { @@ -124,12 +125,12 @@ func TestAddFlags(t *testing.T) { // This is a snapshot of expected options parsed by args. expected := &ServerRunOptions{ ServiceNodePortRange: kubeoptions.DefaultServiceNodePortRange, - ServiceClusterIPRanges: (&net.IPNet{IP: net.ParseIP("192.168.128.0"), Mask: net.CIDRMask(17, 32)}).String(), + ServiceClusterIPRanges: (&net.IPNet{IP: netutils.ParseIPSloppy("192.168.128.0"), Mask: net.CIDRMask(17, 32)}).String(), MasterCount: 5, EndpointReconcilerType: string(reconcilers.LeaseEndpointReconcilerType), AllowPrivileged: false, GenericServerRunOptions: &apiserveroptions.ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -175,7 +176,7 @@ func TestAddFlags(t *testing.T) { DefaultWatchCacheSize: 100, }, SecureServing: (&apiserveroptions.SecureServingOptions{ - BindAddress: net.ParseIP("192.168.10.20"), + BindAddress: netutils.ParseIPSloppy("192.168.10.20"), BindPort: 6443, ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/var/run/kubernetes", diff --git a/cmd/kube-apiserver/app/options/validation_test.go b/cmd/kube-apiserver/app/options/validation_test.go index d3d323c97d8..396f8557f24 100644 --- a/cmd/kube-apiserver/app/options/validation_test.go +++ b/cmd/kube-apiserver/app/options/validation_test.go @@ -23,6 +23,7 @@ import ( utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/kubernetes/pkg/features" + netutils "k8s.io/utils/net" ) func makeOptionsWithCIDRs(serviceCIDR string, secondaryServiceCIDR string) *ServerRunOptions { @@ -33,14 +34,14 @@ func makeOptionsWithCIDRs(serviceCIDR string, secondaryServiceCIDR string) *Serv var primaryCIDR, secondaryCIDR net.IPNet if len(serviceCIDR) > 0 { - _, cidr, _ := net.ParseCIDR(serviceCIDR) + _, cidr, _ := netutils.ParseCIDRSloppy(serviceCIDR) if cidr != nil { primaryCIDR = *(cidr) } } if len(secondaryServiceCIDR) > 0 { - _, cidr, _ := net.ParseCIDR(secondaryServiceCIDR) + _, cidr, _ := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if cidr != nil { secondaryCIDR = *(cidr) } @@ -151,7 +152,7 @@ func TestClusterServiceIPRange(t *testing.T) { } func getIPnetFromCIDR(cidr string) *net.IPNet { - _, ipnet, _ := net.ParseCIDR(cidr) + _, ipnet, _ := netutils.ParseCIDRSloppy(cidr) return ipnet } diff --git a/cmd/kube-apiserver/app/server.go b/cmd/kube-apiserver/app/server.go index 25d92b152d0..b33a6a2150f 100644 --- a/cmd/kube-apiserver/app/server.go +++ b/cmd/kube-apiserver/app/server.go @@ -61,6 +61,7 @@ import ( "k8s.io/klog/v2" aggregatorapiserver "k8s.io/kube-aggregator/pkg/apiserver" aggregatorscheme "k8s.io/kube-aggregator/pkg/apiserver/scheme" + netutils "k8s.io/utils/net" "k8s.io/kubernetes/cmd/kube-apiserver/app/options" "k8s.io/kubernetes/pkg/api/legacyscheme" @@ -670,7 +671,7 @@ func getServiceIPAndRanges(serviceClusterIPRanges string) (net.IP, net.IPNet, ne return apiServerServiceIP, primaryServiceIPRange, net.IPNet{}, nil } - _, primaryServiceClusterCIDR, err := net.ParseCIDR(serviceClusterIPRangeList[0]) + _, primaryServiceClusterCIDR, err := netutils.ParseCIDRSloppy(serviceClusterIPRangeList[0]) if err != nil { return net.IP{}, net.IPNet{}, net.IPNet{}, fmt.Errorf("service-cluster-ip-range[0] is not a valid cidr") } @@ -683,7 +684,7 @@ func getServiceIPAndRanges(serviceClusterIPRanges string) (net.IP, net.IPNet, ne // user provided at least two entries // note: validation asserts that the list is max of two dual stack entries if len(serviceClusterIPRangeList) > 1 { - _, secondaryServiceClusterCIDR, err := net.ParseCIDR(serviceClusterIPRangeList[1]) + _, secondaryServiceClusterCIDR, err := netutils.ParseCIDRSloppy(serviceClusterIPRangeList[1]) if err != nil { return net.IP{}, net.IPNet{}, net.IPNet{}, fmt.Errorf("service-cluster-ip-range[1] is not an ip net") } diff --git a/cmd/kube-controller-manager/app/core.go b/cmd/kube-controller-manager/app/core.go index b546a218734..4736a504305 100644 --- a/cmd/kube-controller-manager/app/core.go +++ b/cmd/kube-controller-manager/app/core.go @@ -127,14 +127,14 @@ func startNodeIpamController(ctx ControllerContext) (http.Handler, bool, error) // service cidr processing if len(strings.TrimSpace(ctx.ComponentConfig.NodeIPAMController.ServiceCIDR)) != 0 { - _, serviceCIDR, err = net.ParseCIDR(ctx.ComponentConfig.NodeIPAMController.ServiceCIDR) + _, serviceCIDR, err = netutils.ParseCIDRSloppy(ctx.ComponentConfig.NodeIPAMController.ServiceCIDR) if err != nil { klog.Warningf("Unsuccessful parsing of service CIDR %v: %v", ctx.ComponentConfig.NodeIPAMController.ServiceCIDR, err) } } if len(strings.TrimSpace(ctx.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR)) != 0 { - _, secondaryServiceCIDR, err = net.ParseCIDR(ctx.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR) + _, secondaryServiceCIDR, err = netutils.ParseCIDRSloppy(ctx.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR) if err != nil { klog.Warningf("Unsuccessful parsing of service CIDR %v: %v", ctx.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR, err) } diff --git a/cmd/kube-controller-manager/app/options/options.go b/cmd/kube-controller-manager/app/options/options.go index c3a756e7e2f..a4dfdce8a44 100644 --- a/cmd/kube-controller-manager/app/options/options.go +++ b/cmd/kube-controller-manager/app/options/options.go @@ -45,6 +45,7 @@ import ( kubectrlmgrconfigscheme "k8s.io/kubernetes/pkg/controller/apis/config/scheme" "k8s.io/kubernetes/pkg/controller/garbagecollector" garbagecollectorconfig "k8s.io/kubernetes/pkg/controller/garbagecollector/config" + netutils "k8s.io/utils/net" // add the kubernetes feature gates _ "k8s.io/kubernetes/pkg/features" @@ -427,7 +428,7 @@ func (s KubeControllerManagerOptions) Config(allControllers []string, disabledBy return nil, err } - if err := s.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil { + if err := s.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil { return nil, fmt.Errorf("error creating self-signed certificates: %v", err) } diff --git a/cmd/kube-controller-manager/app/options/options_test.go b/cmd/kube-controller-manager/app/options/options_test.go index 2101bad0bce..bc1d40bf12d 100644 --- a/cmd/kube-controller-manager/app/options/options_test.go +++ b/cmd/kube-controller-manager/app/options/options_test.go @@ -17,7 +17,6 @@ limitations under the License. package options import ( - "net" "reflect" "sort" "testing" @@ -61,6 +60,7 @@ import ( attachdetachconfig "k8s.io/kubernetes/pkg/controller/volume/attachdetach/config" ephemeralvolumeconfig "k8s.io/kubernetes/pkg/controller/volume/ephemeral/config" persistentvolumeconfig "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/config" + netutils "k8s.io/utils/net" ) var args = []string{ @@ -403,7 +403,7 @@ func TestAddFlags(t *testing.T) { }, SecureServing: (&apiserveroptions.SecureServingOptions{ BindPort: 10001, - BindAddress: net.ParseIP("192.168.4.21"), + BindAddress: netutils.ParseIPSloppy("192.168.4.21"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/a/b/c", PairName: "kube-controller-manager", diff --git a/cmd/kube-proxy/app/server.go b/cmd/kube-proxy/app/server.go index 278a489a9fa..5befe4448e7 100644 --- a/cmd/kube-proxy/app/server.go +++ b/cmd/kube-proxy/app/server.go @@ -86,7 +86,7 @@ import ( utilipvs "k8s.io/kubernetes/pkg/util/ipvs" "k8s.io/kubernetes/pkg/util/oom" "k8s.io/utils/exec" - utilsnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" ) @@ -836,13 +836,13 @@ func (s *ProxyServer) CleanupAndExit() error { // 2. the primary IP from the Node object, if set // 3. if no IP is found it defaults to 127.0.0.1 and IPv4 func detectNodeIP(client clientset.Interface, hostname, bindAddress string) net.IP { - nodeIP := net.ParseIP(bindAddress) + nodeIP := netutils.ParseIPSloppy(bindAddress) if nodeIP.IsUnspecified() { nodeIP = utilnode.GetNodeIP(client, hostname) } if nodeIP == nil { klog.V(0).Infof("can't determine this node's IP, assuming 127.0.0.1; if this is incorrect, please set the --bind-address flag") - nodeIP = net.ParseIP("127.0.0.1") + nodeIP = netutils.ParseIPSloppy("127.0.0.1") } return nodeIP } @@ -853,8 +853,8 @@ func detectNodeIP(client clientset.Interface, hostname, bindAddress string) net. func nodeIPTuple(bindAddress string) [2]net.IP { nodes := [2]net.IP{net.IPv4zero, net.IPv6zero} - adr := net.ParseIP(bindAddress) - if utilsnet.IsIPv6(adr) { + adr := netutils.ParseIPSloppy(bindAddress) + if netutils.IsIPv6(adr) { nodes[1] = adr } else { nodes[0] = adr diff --git a/cmd/kube-proxy/app/server_others.go b/cmd/kube-proxy/app/server_others.go index 1f21822c90a..d4603f522f1 100644 --- a/cmd/kube-proxy/app/server_others.go +++ b/cmd/kube-proxy/app/server_others.go @@ -24,7 +24,6 @@ import ( "context" "errors" "fmt" - "net" goruntime "runtime" "strings" "time" @@ -65,7 +64,7 @@ import ( utilnode "k8s.io/kubernetes/pkg/util/node" utilsysctl "k8s.io/kubernetes/pkg/util/sysctl" "k8s.io/utils/exec" - utilsnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" "k8s.io/klog/v2" ) @@ -177,7 +176,7 @@ func newProxyServer( klog.V(2).InfoS("DetectLocalMode", "LocalMode", string(detectLocalMode)) primaryProtocol := utiliptables.ProtocolIPv4 - if utilsnet.IsIPv6(nodeIP) { + if netutils.IsIPv6(nodeIP) { primaryProtocol = utiliptables.ProtocolIPv6 } iptInterface = utiliptables.New(execer, primaryProtocol) @@ -350,7 +349,7 @@ func newProxyServer( // TODO this has side effects that should only happen when Run() is invoked. proxier, err = userspace.NewProxier( userspace.NewLoadBalancerRR(), - net.ParseIP(config.BindAddress), + netutils.ParseIPSloppy(config.BindAddress), iptInterface, execer, *utilnet.ParsePortRangeOrDie(config.PortRange), @@ -504,7 +503,7 @@ func getDualStackLocalDetectorTuple(mode proxyconfigapi.LocalMode, config *proxy } // localDetectors, like ipt, need to be of the order [IPv4, IPv6], but PodCIDRs is setup so that PodCIDRs[0] == PodCIDR. // so have to handle the case where PodCIDR can be IPv6 and set that to localDetectors[1] - if utilsnet.IsIPv6CIDRString(nodeInfo.Spec.PodCIDR) { + if netutils.IsIPv6CIDRString(nodeInfo.Spec.PodCIDR) { localDetectors[1], err = proxyutiliptables.NewDetectLocalByCIDR(nodeInfo.Spec.PodCIDR, ipt[1]) if err != nil { return localDetectors, err @@ -538,7 +537,7 @@ func cidrTuple(cidrList string) [2]string { foundIPv6 := false for _, cidr := range strings.Split(cidrList, ",") { - if utilsnet.IsIPv6CIDRString(cidr) && !foundIPv6 { + if netutils.IsIPv6CIDRString(cidr) && !foundIPv6 { cidrs[1] = cidr foundIPv6 = true } else if !foundIPv4 { diff --git a/cmd/kube-proxy/app/server_others_test.go b/cmd/kube-proxy/app/server_others_test.go index 8cdb354f824..00d0accb2b9 100644 --- a/cmd/kube-proxy/app/server_others_test.go +++ b/cmd/kube-proxy/app/server_others_test.go @@ -26,6 +26,7 @@ import ( v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + netutils "k8s.io/utils/net" clientsetfake "k8s.io/client-go/kubernetes/fake" @@ -232,21 +233,21 @@ func Test_detectNodeIP(t *testing.T) { nodeInfo: makeNodeWithAddresses("", "", ""), hostname: "fakeHost", bindAddress: "10.0.0.1", - expectedIP: net.ParseIP("10.0.0.1"), + expectedIP: netutils.ParseIPSloppy("10.0.0.1"), }, { name: "Bind address IPv6 unicast address and no Node object", nodeInfo: makeNodeWithAddresses("", "", ""), hostname: "fakeHost", bindAddress: "fd00:4321::2", - expectedIP: net.ParseIP("fd00:4321::2"), + expectedIP: netutils.ParseIPSloppy("fd00:4321::2"), }, { name: "No Valid IP found", nodeInfo: makeNodeWithAddresses("", "", ""), hostname: "fakeHost", bindAddress: "", - expectedIP: net.ParseIP("127.0.0.1"), + expectedIP: netutils.ParseIPSloppy("127.0.0.1"), }, // Disabled because the GetNodeIP method has a backoff retry mechanism // and the test takes more than 30 seconds @@ -256,63 +257,63 @@ func Test_detectNodeIP(t *testing.T) { // nodeInfo: makeNodeWithAddresses("", "", ""), // hostname: "fakeHost", // bindAddress: "0.0.0.0", - // expectedIP: net.ParseIP("127.0.0.1"), + // expectedIP: net.IP{127,0,0,1), // }, { name: "Bind address 0.0.0.0 and node with IPv4 InternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "192.168.1.1", "90.90.90.90"), hostname: "fakeHost", bindAddress: "0.0.0.0", - expectedIP: net.ParseIP("192.168.1.1"), + expectedIP: netutils.ParseIPSloppy("192.168.1.1"), }, { name: "Bind address :: and node with IPv4 InternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "192.168.1.1", "90.90.90.90"), hostname: "fakeHost", bindAddress: "::", - expectedIP: net.ParseIP("192.168.1.1"), + expectedIP: netutils.ParseIPSloppy("192.168.1.1"), }, { name: "Bind address 0.0.0.0 and node with IPv6 InternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "fd00:1234::1", "2001:db8::2"), hostname: "fakeHost", bindAddress: "0.0.0.0", - expectedIP: net.ParseIP("fd00:1234::1"), + expectedIP: netutils.ParseIPSloppy("fd00:1234::1"), }, { name: "Bind address :: and node with IPv6 InternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "fd00:1234::1", "2001:db8::2"), hostname: "fakeHost", bindAddress: "::", - expectedIP: net.ParseIP("fd00:1234::1"), + expectedIP: netutils.ParseIPSloppy("fd00:1234::1"), }, { name: "Bind address 0.0.0.0 and node with only IPv4 ExternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "", "90.90.90.90"), hostname: "fakeHost", bindAddress: "0.0.0.0", - expectedIP: net.ParseIP("90.90.90.90"), + expectedIP: netutils.ParseIPSloppy("90.90.90.90"), }, { name: "Bind address :: and node with only IPv4 ExternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "", "90.90.90.90"), hostname: "fakeHost", bindAddress: "::", - expectedIP: net.ParseIP("90.90.90.90"), + expectedIP: netutils.ParseIPSloppy("90.90.90.90"), }, { name: "Bind address 0.0.0.0 and node with only IPv6 ExternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "", "2001:db8::2"), hostname: "fakeHost", bindAddress: "0.0.0.0", - expectedIP: net.ParseIP("2001:db8::2"), + expectedIP: netutils.ParseIPSloppy("2001:db8::2"), }, { name: "Bind address :: and node with only IPv6 ExternalIP set", nodeInfo: makeNodeWithAddresses("fakeHost", "", "2001:db8::2"), hostname: "fakeHost", bindAddress: "::", - expectedIP: net.ParseIP("2001:db8::2"), + expectedIP: netutils.ParseIPSloppy("2001:db8::2"), }, } for _, c := range cases { diff --git a/cmd/kube-proxy/app/server_windows.go b/cmd/kube-proxy/app/server_windows.go index 7a9ee8fd36e..f85d7a51830 100644 --- a/cmd/kube-proxy/app/server_windows.go +++ b/cmd/kube-proxy/app/server_windows.go @@ -23,7 +23,6 @@ package app import ( "errors" "fmt" - "net" goruntime "runtime" // Enable pprof HTTP handlers. @@ -45,6 +44,7 @@ import ( utilnetsh "k8s.io/kubernetes/pkg/util/netsh" utilnode "k8s.io/kubernetes/pkg/util/node" "k8s.io/utils/exec" + netutils "k8s.io/utils/net" ) // NewProxyServer returns a new ProxyServer. @@ -148,7 +148,7 @@ func newProxyServer(config *proxyconfigapi.KubeProxyConfiguration, cleanupAndExi proxier, err = winuserspace.NewProxier( winuserspace.NewLoadBalancerRR(), - net.ParseIP(config.BindAddress), + netutils.ParseIPSloppy(config.BindAddress), netshInterface, *utilnet.ParsePortRangeOrDie(config.PortRange), // TODO @pires replace below with default values, if applicable diff --git a/cmd/kube-scheduler/app/options/insecure_serving.go b/cmd/kube-scheduler/app/options/insecure_serving.go index 449ba266d91..4acf5db3284 100644 --- a/cmd/kube-scheduler/app/options/insecure_serving.go +++ b/cmd/kube-scheduler/app/options/insecure_serving.go @@ -26,6 +26,7 @@ import ( apiserveroptions "k8s.io/apiserver/pkg/server/options" schedulerappconfig "k8s.io/kubernetes/cmd/kube-scheduler/app/config" kubeschedulerconfig "k8s.io/kubernetes/pkg/scheduler/apis/config" + netutils "k8s.io/utils/net" ) // CombinedInsecureServingOptions sets up to two insecure listeners for healthz and metrics. The flags @@ -78,11 +79,11 @@ func (o *CombinedInsecureServingOptions) ApplyTo(c *schedulerappconfig.Config, c if o.Healthz != nil { o.Healthz.BindPort = o.BindPort - o.Healthz.BindAddress = net.ParseIP(o.BindAddress) + o.Healthz.BindAddress = netutils.ParseIPSloppy(o.BindAddress) } if o.Metrics != nil { o.Metrics.BindPort = o.BindPort - o.Metrics.BindAddress = net.ParseIP(o.BindAddress) + o.Metrics.BindAddress = netutils.ParseIPSloppy(o.BindAddress) } return o.applyTo(c, componentConfig) @@ -125,7 +126,7 @@ func updateDeprecatedInsecureServingOptionsFromAddress(is *apiserveroptions.Depr } else { // In the previous `validate` process, we can ensure that the `addr` is legal, so ignore the error host, portInt, _ := splitHostIntPort(addr) - is.BindAddress = net.ParseIP(host) + is.BindAddress = netutils.ParseIPSloppy(host) is.BindPort = portInt } } @@ -142,7 +143,7 @@ func (o *CombinedInsecureServingOptions) Validate() []error { errors = append(errors, fmt.Errorf("--port %v must be between 0 and 65535, inclusive. 0 for turning off insecure (HTTP) port", o.BindPort)) } - if len(o.BindAddress) > 0 && net.ParseIP(o.BindAddress) == nil { + if len(o.BindAddress) > 0 && netutils.ParseIPSloppy(o.BindAddress) == nil { errors = append(errors, fmt.Errorf("--address %v is an invalid IP address", o.BindAddress)) } diff --git a/cmd/kube-scheduler/app/options/options.go b/cmd/kube-scheduler/app/options/options.go index 801cf7b7df1..9b78cd09bba 100644 --- a/cmd/kube-scheduler/app/options/options.go +++ b/cmd/kube-scheduler/app/options/options.go @@ -45,6 +45,7 @@ import ( kubeschedulerconfig "k8s.io/kubernetes/pkg/scheduler/apis/config" "k8s.io/kubernetes/pkg/scheduler/apis/config/latest" "k8s.io/kubernetes/pkg/scheduler/apis/config/validation" + netutils "k8s.io/utils/net" ) // Options has all the params needed to run a Scheduler @@ -286,7 +287,7 @@ func (o *Options) Validate() []error { // Config return a scheduler config object func (o *Options) Config() (*schedulerappconfig.Config, error) { if o.SecureServing != nil { - if err := o.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil { + if err := o.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil { return nil, fmt.Errorf("error creating self-signed certificates: %v", err) } } diff --git a/cmd/kubeadm/app/apis/kubeadm/apiendpoint.go b/cmd/kubeadm/app/apis/kubeadm/apiendpoint.go index 50be2a813ed..5715d58ff16 100644 --- a/cmd/kubeadm/app/apis/kubeadm/apiendpoint.go +++ b/cmd/kubeadm/app/apis/kubeadm/apiendpoint.go @@ -20,6 +20,8 @@ import ( "net" "strconv" + netutils "k8s.io/utils/net" + "github.com/pkg/errors" ) @@ -29,7 +31,7 @@ func APIEndpointFromString(apiEndpoint string) (APIEndpoint, error) { if err != nil { return APIEndpoint{}, errors.Wrapf(err, "invalid advertise address endpoint: %s", apiEndpoint) } - if net.ParseIP(apiEndpointHost) == nil { + if netutils.ParseIPSloppy(apiEndpointHost) == nil { return APIEndpoint{}, errors.Errorf("invalid API endpoint IP: %s", apiEndpointHost) } apiEndpointPort, err := net.LookupPort("tcp", apiEndpointPortStr) diff --git a/cmd/kubeadm/app/apis/kubeadm/validation/validation.go b/cmd/kubeadm/app/apis/kubeadm/validation/validation.go index 37001d9d7ef..552ac177ac4 100644 --- a/cmd/kubeadm/app/apis/kubeadm/validation/validation.go +++ b/cmd/kubeadm/app/apis/kubeadm/validation/validation.go @@ -34,7 +34,7 @@ import ( bootstrapapi "k8s.io/cluster-bootstrap/token/api" bootstraputil "k8s.io/cluster-bootstrap/token/util" "k8s.io/klog/v2" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" bootstraptokenv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/bootstraptoken/v1" "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" @@ -319,7 +319,7 @@ func ValidateCertSANs(altnames []string, fldPath *field.Path) field.ErrorList { for _, altname := range altnames { if errs := validation.IsDNS1123Subdomain(altname); len(errs) != 0 { if errs2 := validation.IsWildcardDNS1123Subdomain(altname); len(errs2) != 0 { - if net.ParseIP(altname) == nil { + if netutils.ParseIPSloppy(altname) == nil { allErrs = append(allErrs, field.Invalid(fldPath, altname, fmt.Sprintf("altname is not a valid IP address, DNS label or a DNS label with subdomain wildcards: %s; %s", strings.Join(errs, "; "), strings.Join(errs2, "; ")))) } } @@ -350,7 +350,7 @@ func ValidateURLs(urls []string, requireHTTPS bool, fldPath *field.Path) field.E // ValidateIPFromString validates ip address func ValidateIPFromString(ipaddr string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - if net.ParseIP(ipaddr) == nil { + if netutils.ParseIPSloppy(ipaddr) == nil { allErrs = append(allErrs, field.Invalid(fldPath, ipaddr, "ip address is not valid")) } return allErrs @@ -377,7 +377,7 @@ func ValidateHostPort(endpoint string, fldPath *field.Path) field.ErrorList { // ValidateIPNetFromString validates network portion of ip address func ValidateIPNetFromString(subnetStr string, minAddrs int64, isDualStack bool, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - subnets, err := utilnet.ParseCIDRs(strings.Split(subnetStr, ",")) + subnets, err := netutils.ParseCIDRs(strings.Split(subnetStr, ",")) if err != nil { allErrs = append(allErrs, field.Invalid(fldPath, subnetStr, "couldn't parse subnet")) return allErrs @@ -388,7 +388,7 @@ func ValidateIPNetFromString(subnetStr string, minAddrs int64, isDualStack bool, allErrs = append(allErrs, field.Invalid(fldPath, subnetStr, "expected one (IPv4 or IPv6) CIDR or two CIDRs from each family for dual-stack networking")) // if DualStack and there are 2 CIDRs validate if there is at least one of each IP family case isDualStack && len(subnets) == 2: - areDualStackCIDRs, err := utilnet.IsDualStackCIDRs(subnets) + areDualStackCIDRs, err := netutils.IsDualStackCIDRs(subnets) if err != nil { allErrs = append(allErrs, field.Invalid(fldPath, subnetStr, err.Error())) } else if !areDualStackCIDRs { @@ -400,13 +400,13 @@ func ValidateIPNetFromString(subnetStr string, minAddrs int64, isDualStack bool, } // validate the subnet/s for _, s := range subnets { - numAddresses := utilnet.RangeSize(s) + numAddresses := netutils.RangeSize(s) if numAddresses < minAddrs { allErrs = append(allErrs, field.Invalid(fldPath, s.String(), fmt.Sprintf("subnet with %d address(es) is too small, the minimum is %d", numAddresses, minAddrs))) } // Warn when the subnet is in site-local range - i.e. contains addresses that belong to fec0::/10 - _, siteLocalNet, _ := net.ParseCIDR("fec0::/10") + _, siteLocalNet, _ := netutils.ParseCIDRSloppy("fec0::/10") if siteLocalNet.Contains(s.IP) || s.Contains(siteLocalNet.IP) { klog.Warningf("the subnet %v contains IPv6 site-local addresses that belong to fec0::/10 which has been deprecated by rfc3879", s) } @@ -422,7 +422,7 @@ func ValidateIPNetFromString(subnetStr string, minAddrs int64, isDualStack bool, func ValidateServiceSubnetSize(subnetStr string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} // subnets were already validated - subnets, _ := utilnet.ParseCIDRs(strings.Split(subnetStr, ",")) + subnets, _ := netutils.ParseCIDRs(strings.Split(subnetStr, ",")) for _, serviceSubnet := range subnets { ones, bits := serviceSubnet.Mask.Size() if bits-ones > constants.MaximumBitsForServiceSubnet { @@ -437,13 +437,13 @@ func ValidateServiceSubnetSize(subnetStr string, fldPath *field.Path) field.Erro func ValidatePodSubnetNodeMask(subnetStr string, c *kubeadm.ClusterConfiguration, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} // subnets were already validated - subnets, _ := utilnet.ParseCIDRs(strings.Split(subnetStr, ",")) + subnets, _ := netutils.ParseCIDRs(strings.Split(subnetStr, ",")) for _, podSubnet := range subnets { // obtain podSubnet mask mask := podSubnet.Mask maskSize, _ := mask.Size() // obtain node-cidr-mask - nodeMask, err := getClusterNodeMask(c, utilnet.IsIPv6(podSubnet.IP)) + nodeMask, err := getClusterNodeMask(c, netutils.IsIPv6(podSubnet.IP)) if err != nil { allErrs = append(allErrs, field.Invalid(fldPath, podSubnet.String(), err.Error())) continue diff --git a/cmd/kubeadm/app/componentconfigs/kubeproxy.go b/cmd/kubeadm/app/componentconfigs/kubeproxy.go index ac3703a977b..1036f77f5fe 100644 --- a/cmd/kubeadm/app/componentconfigs/kubeproxy.go +++ b/cmd/kubeadm/app/componentconfigs/kubeproxy.go @@ -17,10 +17,9 @@ limitations under the License. package componentconfigs import ( - "net" - clientset "k8s.io/client-go/kubernetes" kubeproxyconfig "k8s.io/kube-proxy/config/v1alpha1" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmapiv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta3" @@ -76,7 +75,7 @@ func (kp *kubeProxyConfig) Unmarshal(docmap kubeadmapi.DocumentMap) error { } func kubeProxyDefaultBindAddress(localAdvertiseAddress string) string { - ip := net.ParseIP(localAdvertiseAddress) + ip := netutils.ParseIPSloppy(localAdvertiseAddress) if ip.To4() != nil { return kubeadmapiv1.DefaultProxyBindAddressv4 } diff --git a/cmd/kubeadm/app/constants/constants.go b/cmd/kubeadm/app/constants/constants.go index e3249f2b7c1..df55609e90d 100644 --- a/cmd/kubeadm/app/constants/constants.go +++ b/cmd/kubeadm/app/constants/constants.go @@ -34,7 +34,7 @@ import ( apimachineryversion "k8s.io/apimachinery/pkg/version" bootstrapapi "k8s.io/cluster-bootstrap/token/api" componentversion "k8s.io/component-base/version" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) const ( @@ -635,7 +635,7 @@ func GetDNSIP(svcSubnetList string, isDualStack bool) (net.IP, error) { } // Selects the 10th IP in service subnet CIDR range as dnsIP - dnsIP, err := utilnet.GetIndexedIP(svcSubnetCIDR, 10) + dnsIP, err := netutils.GetIndexedIP(svcSubnetCIDR, 10) if err != nil { return nil, errors.Wrap(err, "unable to get internal Kubernetes Service IP from the given service CIDR") } @@ -649,7 +649,7 @@ func GetKubernetesServiceCIDR(svcSubnetList string, isDualStack bool) (*net.IPNe // The default service address family for the cluster is the address family of the first // service cluster IP range configured via the `--service-cluster-ip-range` flag // of the kube-controller-manager and kube-apiserver. - svcSubnets, err := utilnet.ParseCIDRs(strings.Split(svcSubnetList, ",")) + svcSubnets, err := netutils.ParseCIDRs(strings.Split(svcSubnetList, ",")) if err != nil { return nil, errors.Wrapf(err, "unable to parse ServiceSubnet %v", svcSubnetList) } @@ -659,7 +659,7 @@ func GetKubernetesServiceCIDR(svcSubnetList string, isDualStack bool) (*net.IPNe return svcSubnets[0], nil } // internal IP address for the API server - _, svcSubnet, err := net.ParseCIDR(svcSubnetList) + _, svcSubnet, err := netutils.ParseCIDRSloppy(svcSubnetList) if err != nil { return nil, errors.Wrapf(err, "unable to parse ServiceSubnet %v", svcSubnetList) } @@ -672,7 +672,7 @@ func GetAPIServerVirtualIP(svcSubnetList string, isDualStack bool) (net.IP, erro if err != nil { return nil, errors.Wrap(err, "unable to get internal Kubernetes Service IP from the given service CIDR") } - internalAPIServerVirtualIP, err := utilnet.GetIndexedIP(svcSubnet, 1) + internalAPIServerVirtualIP, err := netutils.GetIndexedIP(svcSubnet, 1) if err != nil { return nil, errors.Wrapf(err, "unable to get the first IP address from the given CIDR: %s", svcSubnet.String()) } diff --git a/cmd/kubeadm/app/phases/certs/renewal/manager_test.go b/cmd/kubeadm/app/phases/certs/renewal/manager_test.go index 4cb75750069..ca9640049e5 100644 --- a/cmd/kubeadm/app/phases/certs/renewal/manager_test.go +++ b/cmd/kubeadm/app/phases/certs/renewal/manager_test.go @@ -27,6 +27,7 @@ import ( "time" certutil "k8s.io/client-go/util/cert" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" certtestutil "k8s.io/kubernetes/cmd/kubeadm/app/util/certs" @@ -46,7 +47,7 @@ var ( CommonName: "test-common-name", Organization: []string{"sig-cluster-lifecycle"}, AltNames: certutil.AltNames{ - IPs: []net.IP{net.ParseIP("10.100.0.1")}, + IPs: []net.IP{netutils.ParseIPSloppy("10.100.0.1")}, DNSNames: []string{"test-domain.space"}, }, Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, @@ -234,7 +235,7 @@ func TestCertToConfig(t *testing.T) { CommonName: "test-common-name", Organization: []string{"sig-cluster-lifecycle"}, AltNames: certutil.AltNames{ - IPs: []net.IP{net.ParseIP("10.100.0.1")}, + IPs: []net.IP{netutils.ParseIPSloppy("10.100.0.1")}, DNSNames: []string{"test-domain.space"}, }, Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, @@ -247,7 +248,7 @@ func TestCertToConfig(t *testing.T) { }, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, DNSNames: []string{"test-domain.space"}, - IPAddresses: []net.IP{net.ParseIP("10.100.0.1")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("10.100.0.1")}, } cfg := certToConfig(cert) diff --git a/cmd/kubeadm/app/phases/certs/renewal/readwriter_test.go b/cmd/kubeadm/app/phases/certs/renewal/readwriter_test.go index 46593683667..cf75f464c90 100644 --- a/cmd/kubeadm/app/phases/certs/renewal/readwriter_test.go +++ b/cmd/kubeadm/app/phases/certs/renewal/readwriter_test.go @@ -27,6 +27,7 @@ import ( "k8s.io/client-go/tools/clientcmd" certutil "k8s.io/client-go/util/cert" "k8s.io/client-go/util/keyutil" + netutils "k8s.io/utils/net" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig" @@ -161,7 +162,7 @@ func writeTestKubeconfig(t *testing.T, dir, name string, caCert *x509.Certificat Organization: []string{"sig-cluster-lifecycle"}, Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, AltNames: certutil.AltNames{ - IPs: []net.IP{net.ParseIP("10.100.0.1")}, + IPs: []net.IP{netutils.ParseIPSloppy("10.100.0.1")}, DNSNames: []string{"test-domain.space"}, }, }, diff --git a/cmd/kubeadm/app/preflight/checks.go b/cmd/kubeadm/app/preflight/checks.go index ff379ff9c8d..28926fc6c11 100644 --- a/cmd/kubeadm/app/preflight/checks.go +++ b/cmd/kubeadm/app/preflight/checks.go @@ -46,7 +46,7 @@ import ( "k8s.io/klog/v2" system "k8s.io/system-validators/validators" utilsexec "k8s.io/utils/exec" - utilsnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" "k8s.io/kubernetes/cmd/kubeadm/app/constants" @@ -432,7 +432,7 @@ func (hst HTTPProxyCheck) Name() string { func (hst HTTPProxyCheck) Check() (warnings, errorList []error) { klog.V(1).Infoln("validating if the connectivity type is via proxy or direct") u := &url.URL{Scheme: hst.Proto, Host: hst.Host} - if utilsnet.IsIPv6String(hst.Host) { + if netutils.IsIPv6String(hst.Host) { u.Host = net.JoinHostPort(hst.Host, "1234") } @@ -474,12 +474,12 @@ func (subnet HTTPProxyCIDRCheck) Check() (warnings, errorList []error) { return nil, nil } - _, cidr, err := net.ParseCIDR(subnet.CIDR) + _, cidr, err := netutils.ParseCIDRSloppy(subnet.CIDR) if err != nil { return nil, []error{errors.Wrapf(err, "error parsing CIDR %q", subnet.CIDR)} } - testIP, err := utilsnet.GetIndexedIP(cidr, 1) + testIP, err := netutils.GetIndexedIP(cidr, 1) if err != nil { return nil, []error{errors.Wrapf(err, "unable to get first IP address from the given CIDR (%s)", cidr.String())} } @@ -941,8 +941,8 @@ func RunInitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfigura checks = addCommonChecks(execer, cfg.KubernetesVersion, &cfg.NodeRegistration, checks) // Check if Bridge-netfilter and IPv6 relevant flags are set - if ip := net.ParseIP(cfg.LocalAPIEndpoint.AdvertiseAddress); ip != nil { - if utilsnet.IsIPv6(ip) { + if ip := netutils.ParseIPSloppy(cfg.LocalAPIEndpoint.AdvertiseAddress); ip != nil { + if netutils.IsIPv6(ip) { checks = append(checks, FileContentCheck{Path: bridgenf6, Content: []byte{'1'}}, FileContentCheck{Path: ipv6DefaultForwarding, Content: []byte{'1'}}, @@ -1006,8 +1006,8 @@ func RunJoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfigura checks = append(checks, HTTPProxyCheck{Proto: "https", Host: ipstr}, ) - if ip := net.ParseIP(ipstr); ip != nil { - if utilsnet.IsIPv6(ip) { + if ip := netutils.ParseIPSloppy(ipstr); ip != nil { + if netutils.IsIPv6(ip) { addIPv6Checks = true } } diff --git a/cmd/kubeadm/app/util/apiclient/init_dryrun.go b/cmd/kubeadm/app/util/apiclient/init_dryrun.go index 6b46dd73b08..16d117177e4 100644 --- a/cmd/kubeadm/app/util/apiclient/init_dryrun.go +++ b/cmd/kubeadm/app/util/apiclient/init_dryrun.go @@ -17,18 +17,17 @@ limitations under the License. package apiclient import ( - "net" "strings" "github.com/pkg/errors" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" core "k8s.io/client-go/testing" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" "k8s.io/kubernetes/cmd/kubeadm/app/constants" ) @@ -88,12 +87,12 @@ func (idr *InitDryRunGetter) handleKubernetesService(action core.GetAction) (boo return false, nil, nil } - _, svcSubnet, err := net.ParseCIDR(idr.serviceSubnet) + _, svcSubnet, err := netutils.ParseCIDRSloppy(idr.serviceSubnet) if err != nil { return true, nil, errors.Wrapf(err, "error parsing CIDR %q", idr.serviceSubnet) } - internalAPIServerVirtualIP, err := utilnet.GetIndexedIP(svcSubnet, 1) + internalAPIServerVirtualIP, err := netutils.GetIndexedIP(svcSubnet, 1) if err != nil { return true, nil, errors.Wrapf(err, "unable to get first IP address from the given CIDR (%s)", svcSubnet.String()) } diff --git a/cmd/kubeadm/app/util/config/common.go b/cmd/kubeadm/app/util/config/common.go index 9f3b17812a3..9d48f40bc3d 100644 --- a/cmd/kubeadm/app/util/config/common.go +++ b/cmd/kubeadm/app/util/config/common.go @@ -31,6 +31,7 @@ import ( apimachineryversion "k8s.io/apimachinery/pkg/version" componentversion "k8s.io/component-base/version" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmscheme "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme" @@ -139,7 +140,7 @@ func LowercaseSANs(sans []string) { // VerifyAPIServerBindAddress can be used to verify if a bind address for the API Server is 0.0.0.0, // in which case this address is not valid and should not be used. func VerifyAPIServerBindAddress(address string) error { - ip := net.ParseIP(address) + ip := netutils.ParseIPSloppy(address) if ip == nil { return errors.Errorf("cannot parse IP address: %s", address) } @@ -164,7 +165,7 @@ func ChooseAPIServerBindAddress(bindAddress net.IP) (net.IP, error) { if err != nil { if netutil.IsNoRoutesError(err) { klog.Warningf("WARNING: could not obtain a bind address for the API Server: %v; using: %s", err, constants.DefaultAPIServerBindAddress) - defaultIP := net.ParseIP(constants.DefaultAPIServerBindAddress) + defaultIP := netutils.ParseIPSloppy(constants.DefaultAPIServerBindAddress) if defaultIP == nil { return nil, errors.Errorf("cannot parse default IP address: %s", constants.DefaultAPIServerBindAddress) } diff --git a/cmd/kubeadm/app/util/config/initconfiguration.go b/cmd/kubeadm/app/util/config/initconfiguration.go index 9010a369ba6..b461b2388bf 100644 --- a/cmd/kubeadm/app/util/config/initconfiguration.go +++ b/cmd/kubeadm/app/util/config/initconfiguration.go @@ -31,6 +31,7 @@ import ( netutil "k8s.io/apimachinery/pkg/util/net" bootstraputil "k8s.io/cluster-bootstrap/token/util" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" bootstraptokenv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/bootstraptoken/v1" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" @@ -122,7 +123,7 @@ func SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, // SetAPIEndpointDynamicDefaults checks and sets configuration values for the APIEndpoint object func SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error { // validate cfg.API.AdvertiseAddress. - addressIP := net.ParseIP(cfg.AdvertiseAddress) + addressIP := netutils.ParseIPSloppy(cfg.AdvertiseAddress) if addressIP == nil && cfg.AdvertiseAddress != "" { return errors.Errorf("couldn't use \"%s\" as \"apiserver-advertise-address\", must be ipv4 or ipv6 address", cfg.AdvertiseAddress) } diff --git a/cmd/kubeadm/app/util/endpoint.go b/cmd/kubeadm/app/util/endpoint.go index 327038692ab..ecc9f00bc7e 100644 --- a/cmd/kubeadm/app/util/endpoint.go +++ b/cmd/kubeadm/app/util/endpoint.go @@ -25,7 +25,7 @@ import ( "github.com/pkg/errors" "k8s.io/apimachinery/pkg/util/validation" - utilsnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" ) @@ -100,7 +100,7 @@ func ParseHostPort(hostport string) (string, string, error) { } // if host is a valid IP, returns it - if ip := net.ParseIP(host); ip != nil { + if ip := netutils.ParseIPSloppy(host); ip != nil { return host, port, nil } @@ -115,7 +115,7 @@ func ParseHostPort(hostport string) (string, string, error) { // ParsePort parses a string representing a TCP port. // If the string is not a valid representation of a TCP port, ParsePort returns an error. func ParsePort(port string) (int, error) { - portInt, err := utilsnet.ParsePort(port, true) + portInt, err := netutils.ParsePort(port, true) if err == nil && (1 <= portInt && portInt <= 65535) { return portInt, nil } @@ -133,7 +133,7 @@ func parseAPIEndpoint(localEndpoint *kubeadmapi.APIEndpoint) (net.IP, string, er } // parse the AdvertiseAddress - var ip = net.ParseIP(localEndpoint.AdvertiseAddress) + var ip = netutils.ParseIPSloppy(localEndpoint.AdvertiseAddress) if ip == nil { return nil, "", errors.Errorf("invalid value `%s` given for api.advertiseAddress", localEndpoint.AdvertiseAddress) } diff --git a/cmd/kubeadm/app/util/pkiutil/pki_helpers.go b/cmd/kubeadm/app/util/pkiutil/pki_helpers.go index 645cde98a63..d9bcd7ad8e7 100644 --- a/cmd/kubeadm/app/util/pkiutil/pki_helpers.go +++ b/cmd/kubeadm/app/util/pkiutil/pki_helpers.go @@ -41,6 +41,7 @@ import ( "k8s.io/apimachinery/pkg/util/validation" certutil "k8s.io/client-go/util/cert" "k8s.io/client-go/util/keyutil" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" @@ -417,7 +418,7 @@ func pathForCSR(pkiPath, name string) string { // GetAPIServerAltNames builds an AltNames object for to be used when generating apiserver certificate func GetAPIServerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) { // advertise address - advertiseAddress := net.ParseIP(cfg.LocalAPIEndpoint.AdvertiseAddress) + advertiseAddress := netutils.ParseIPSloppy(cfg.LocalAPIEndpoint.AdvertiseAddress) if advertiseAddress == nil { return nil, errors.Errorf("error parsing LocalAPIEndpoint AdvertiseAddress %v: is not a valid textual representation of an IP address", cfg.LocalAPIEndpoint.AdvertiseAddress) @@ -446,7 +447,7 @@ func GetAPIServerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames // add cluster controlPlaneEndpoint if present (dns or ip) if len(cfg.ControlPlaneEndpoint) > 0 { if host, _, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint); err == nil { - if ip := net.ParseIP(host); ip != nil { + if ip := netutils.ParseIPSloppy(host); ip != nil { altNames.IPs = append(altNames.IPs, ip) } else { altNames.DNSNames = append(altNames.DNSNames, host) @@ -478,7 +479,7 @@ func GetEtcdPeerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, // getAltNames builds an AltNames object with the cfg and certName. func getAltNames(cfg *kubeadmapi.InitConfiguration, certName string) (*certutil.AltNames, error) { // advertise address - advertiseAddress := net.ParseIP(cfg.LocalAPIEndpoint.AdvertiseAddress) + advertiseAddress := netutils.ParseIPSloppy(cfg.LocalAPIEndpoint.AdvertiseAddress) if advertiseAddress == nil { return nil, errors.Errorf("error parsing LocalAPIEndpoint AdvertiseAddress %v: is not a valid textual representation of an IP address", cfg.LocalAPIEndpoint.AdvertiseAddress) @@ -508,7 +509,7 @@ func getAltNames(cfg *kubeadmapi.InitConfiguration, certName string) (*certutil. // certNames is used to print user facing warnings and should be the name of the cert the altNames will be used for func appendSANsToAltNames(altNames *certutil.AltNames, SANs []string, certName string) { for _, altname := range SANs { - if ip := net.ParseIP(altname); ip != nil { + if ip := netutils.ParseIPSloppy(altname); ip != nil { altNames.IPs = append(altNames.IPs, ip) } else if len(validation.IsDNS1123Subdomain(altname)) == 0 { altNames.DNSNames = append(altNames.DNSNames, altname) diff --git a/cmd/kubeadm/app/util/pkiutil/pki_helpers_test.go b/cmd/kubeadm/app/util/pkiutil/pki_helpers_test.go index cfa79295608..a18fa9b8f69 100644 --- a/cmd/kubeadm/app/util/pkiutil/pki_helpers_test.go +++ b/cmd/kubeadm/app/util/pkiutil/pki_helpers_test.go @@ -30,6 +30,7 @@ import ( "testing" certutil "k8s.io/client-go/util/cert" + netutils "k8s.io/utils/net" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" ) @@ -633,7 +634,7 @@ func TestGetAPIServerAltNames(t *testing.T) { for _, IPAddress := range rt.expectedIPAddresses { found := false for _, val := range altNames.IPs { - if val.Equal(net.ParseIP(IPAddress)) { + if val.Equal(netutils.ParseIPSloppy(IPAddress)) { found = true break } @@ -698,7 +699,7 @@ func TestGetEtcdAltNames(t *testing.T) { t.Run(IPAddress, func(t *testing.T) { found := false for _, val := range altNames.IPs { - if val.Equal(net.ParseIP(IPAddress)) { + if val.Equal(netutils.ParseIPSloppy(IPAddress)) { found = true break } @@ -757,7 +758,7 @@ func TestGetEtcdPeerAltNames(t *testing.T) { for _, IPAddress := range expectedIPAddresses { found := false for _, val := range altNames.IPs { - if val.Equal(net.ParseIP(IPAddress)) { + if val.Equal(netutils.ParseIPSloppy(IPAddress)) { found = true break } diff --git a/cmd/kubelet/app/server.go b/cmd/kubelet/app/server.go index 7f11a0ff6f7..0522aae5141 100644 --- a/cmd/kubelet/app/server.go +++ b/cmd/kubelet/app/server.go @@ -103,7 +103,7 @@ import ( "k8s.io/kubernetes/pkg/volume/util/hostutil" "k8s.io/kubernetes/pkg/volume/util/subpath" "k8s.io/utils/exec" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) const ( @@ -1122,7 +1122,7 @@ func RunKubelet(kubeServer *options.KubeletServer, kubeDeps *kubelet.Dependencie var nodeIPs []net.IP if kubeServer.NodeIP != "" { for _, ip := range strings.Split(kubeServer.NodeIP, ",") { - parsedNodeIP := net.ParseIP(strings.TrimSpace(ip)) + parsedNodeIP := netutils.ParseIPSloppy(strings.TrimSpace(ip)) if parsedNodeIP == nil { klog.InfoS("Could not parse --node-ip ignoring", "IP", ip) } else { @@ -1132,7 +1132,7 @@ func RunKubelet(kubeServer *options.KubeletServer, kubeDeps *kubelet.Dependencie } if !utilfeature.DefaultFeatureGate.Enabled(features.IPv6DualStack) && len(nodeIPs) > 1 { return fmt.Errorf("dual-stack --node-ip %q not supported in a single-stack cluster", kubeServer.NodeIP) - } else if len(nodeIPs) > 2 || (len(nodeIPs) == 2 && utilnet.IsIPv6(nodeIPs[0]) == utilnet.IsIPv6(nodeIPs[1])) { + } else if len(nodeIPs) > 2 || (len(nodeIPs) == 2 && netutils.IsIPv6(nodeIPs[0]) == netutils.IsIPv6(nodeIPs[1])) { return fmt.Errorf("bad --node-ip %q; must contain either a single IP or a dual-stack pair of IPs", kubeServer.NodeIP) } else if len(nodeIPs) == 2 && kubeServer.CloudProvider != "" { return fmt.Errorf("dual-stack --node-ip %q not supported when using a cloud provider", kubeServer.NodeIP) @@ -1224,7 +1224,7 @@ func startKubelet(k kubelet.Bootstrap, podCfg *config.PodConfig, kubeCfg *kubele go k.ListenAndServe(kubeCfg, kubeDeps.TLSOptions, kubeDeps.Auth) } if kubeCfg.ReadOnlyPort > 0 { - go k.ListenAndServeReadOnly(net.ParseIP(kubeCfg.Address), uint(kubeCfg.ReadOnlyPort)) + go k.ListenAndServeReadOnly(netutils.ParseIPSloppy(kubeCfg.Address), uint(kubeCfg.ReadOnlyPort)) } if utilfeature.DefaultFeatureGate.Enabled(features.KubeletPodResources) { go k.ListenAndServePodResources() diff --git a/pkg/apis/core/validation/validation.go b/pkg/apis/core/validation/validation.go index 4ea4f0c7318..a072d7cee28 100644 --- a/pkg/apis/core/validation/validation.go +++ b/pkg/apis/core/validation/validation.go @@ -3112,7 +3112,7 @@ func validatePodDNSConfig(dnsConfig *core.PodDNSConfig, dnsPolicy *core.DNSPolic allErrs = append(allErrs, field.Invalid(fldPath.Child("nameservers"), dnsConfig.Nameservers, fmt.Sprintf("must not have more than %v nameservers", MaxDNSNameservers))) } for i, ns := range dnsConfig.Nameservers { - if ip := net.ParseIP(ns); ip == nil { + if ip := netutils.ParseIPSloppy(ns); ip == nil { allErrs = append(allErrs, field.Invalid(fldPath.Child("nameservers").Index(i), ns, "must be valid IP address")) } } @@ -3246,7 +3246,7 @@ func validateOnlyAddedTolerations(newTolerations []core.Toleration, oldToleratio func ValidateHostAliases(hostAliases []core.HostAlias, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} for _, hostAlias := range hostAliases { - if ip := net.ParseIP(hostAlias.IP); ip == nil { + if ip := netutils.ParseIPSloppy(hostAlias.IP); ip == nil { allErrs = append(allErrs, field.Invalid(fldPath.Child("ip"), hostAlias.IP, "must be valid IP address")) } for _, hostname := range hostAlias.Hostnames { @@ -5840,7 +5840,7 @@ func validateEndpointAddress(address *core.EndpointAddress, fldPath *field.Path) // - https://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xhtml func ValidateNonSpecialIP(ipAddress string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - ip := net.ParseIP(ipAddress) + ip := netutils.ParseIPSloppy(ipAddress) if ip == nil { allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "must be a valid IP address")) return allErrs @@ -6160,7 +6160,7 @@ func ValidateLoadBalancerStatus(status *core.LoadBalancerStatus, fldPath *field. for i, ingress := range status.Ingress { idxPath := fldPath.Child("ingress").Index(i) if len(ingress.IP) > 0 { - if isIP := (net.ParseIP(ingress.IP) != nil); !isIP { + if isIP := (netutils.ParseIPSloppy(ingress.IP) != nil); !isIP { allErrs = append(allErrs, field.Invalid(idxPath.Child("ip"), ingress.IP, "must be a valid IP address")) } } @@ -6168,7 +6168,7 @@ func ValidateLoadBalancerStatus(status *core.LoadBalancerStatus, fldPath *field. for _, msg := range validation.IsDNS1123Subdomain(ingress.Hostname) { allErrs = append(allErrs, field.Invalid(idxPath.Child("hostname"), ingress.Hostname, msg)) } - if isIP := (net.ParseIP(ingress.Hostname) != nil); isIP { + if isIP := (netutils.ParseIPSloppy(ingress.Hostname) != nil); isIP { allErrs = append(allErrs, field.Invalid(idxPath.Child("hostname"), ingress.Hostname, "must be a DNS name, not an IP address")) } } @@ -6198,7 +6198,7 @@ func validateVolumeNodeAffinity(nodeAffinity *core.VolumeNodeAffinity, fldPath * // ValidateCIDR validates whether a CIDR matches the conventions expected by net.ParseCIDR func ValidateCIDR(cidr string) (*net.IPNet, error) { - _, net, err := net.ParseCIDR(cidr) + _, net, err := netutils.ParseCIDRSloppy(cidr) if err != nil { return nil, err } diff --git a/pkg/apis/networking/validation/validation.go b/pkg/apis/networking/validation/validation.go index ccccea6ec43..6ce045d7a39 100644 --- a/pkg/apis/networking/validation/validation.go +++ b/pkg/apis/networking/validation/validation.go @@ -18,7 +18,6 @@ package validation import ( "fmt" - "net" "strings" apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" @@ -33,6 +32,7 @@ import ( apivalidation "k8s.io/kubernetes/pkg/apis/core/validation" "k8s.io/kubernetes/pkg/apis/networking" "k8s.io/kubernetes/pkg/features" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" ) @@ -327,7 +327,7 @@ func validateIngressRules(ingressRules []networking.IngressRule, fldPath *field. for i, ih := range ingressRules { wildcardHost := false if len(ih.Host) > 0 { - if isIP := (net.ParseIP(ih.Host) != nil); isIP { + if isIP := (netutils.ParseIPSloppy(ih.Host) != nil); isIP { allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, "must be a DNS name, not an IP address")) } // TODO: Ports and ips are allowed in the host part of a url diff --git a/pkg/controller/endpointslicemirroring/utils.go b/pkg/controller/endpointslicemirroring/utils.go index 1af6115b999..45888664b62 100644 --- a/pkg/controller/endpointslicemirroring/utils.go +++ b/pkg/controller/endpointslicemirroring/utils.go @@ -18,7 +18,6 @@ package endpointslicemirroring import ( "fmt" - "net" "strings" corev1 "k8s.io/api/core/v1" @@ -30,6 +29,7 @@ import ( "k8s.io/client-go/tools/leaderelection/resourcelock" "k8s.io/kubernetes/pkg/apis/discovery/validation" endpointutil "k8s.io/kubernetes/pkg/controller/util/endpoint" + netutils "k8s.io/utils/net" ) // addrTypePortMapKey is used to uniquely identify groups of endpoint ports and @@ -50,7 +50,7 @@ func (pk addrTypePortMapKey) addressType() discovery.AddressType { } func getAddressType(address string) *discovery.AddressType { - ip := net.ParseIP(address) + ip := netutils.ParseIPSloppy(address) if ip == nil { return nil } diff --git a/pkg/controller/nodeipam/ipam/adapter.go b/pkg/controller/nodeipam/ipam/adapter.go index cc78e12396f..387246c76ca 100644 --- a/pkg/controller/nodeipam/ipam/adapter.go +++ b/pkg/controller/nodeipam/ipam/adapter.go @@ -25,6 +25,7 @@ import ( "net" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -80,7 +81,7 @@ func (a *adapter) Alias(ctx context.Context, node *v1.Node) (*net.IPNet, error) klog.Warningf("Node %q has more than one alias assigned (%v), defaulting to the first", node.Name, cidrs) } - _, cidrRange, err := net.ParseCIDR(cidrs[0]) + _, cidrRange, err := netutils.ParseCIDRSloppy(cidrs[0]) if err != nil { return nil, err } diff --git a/pkg/controller/nodeipam/ipam/cidrset/cidr_set_test.go b/pkg/controller/nodeipam/ipam/cidrset/cidr_set_test.go index 52bb209d7d6..b934baa4c56 100644 --- a/pkg/controller/nodeipam/ipam/cidrset/cidr_set_test.go +++ b/pkg/controller/nodeipam/ipam/cidrset/cidr_set_test.go @@ -24,6 +24,7 @@ import ( "k8s.io/component-base/metrics/testutil" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) func TestCIDRSetFullyAllocated(t *testing.T) { @@ -47,7 +48,7 @@ func TestCIDRSetFullyAllocated(t *testing.T) { }, } for _, tc := range cases { - _, clusterCIDR, _ := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, tc.subNetMaskSize) if err != nil { t.Fatalf("unexpected error: %v for %v", err, tc.description) @@ -198,7 +199,7 @@ func TestIndexToCIDRBlock(t *testing.T) { }, } for _, tc := range cases { - _, clusterCIDR, _ := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, tc.subnetMaskSize) if err != nil { t.Fatalf("error for %v ", tc.description) @@ -225,7 +226,7 @@ func TestCIDRSet_RandomishAllocation(t *testing.T) { }, } for _, tc := range cases { - _, clusterCIDR, _ := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, 24) if err != nil { t.Fatalf("Error allocating CIDRSet for %v", tc.description) @@ -286,7 +287,7 @@ func TestCIDRSet_AllocationOccupied(t *testing.T) { }, } for _, tc := range cases { - _, clusterCIDR, _ := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, 24) if err != nil { t.Fatalf("Error allocating CIDRSet for %v", tc.description) @@ -399,7 +400,7 @@ func TestDoubleOccupyRelease(t *testing.T) { // operations have been executed. numAllocatable24s := (1 << 8) - 3 - _, clusterCIDR, _ := net.ParseCIDR(clusterCIDRStr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, 24) if err != nil { t.Fatalf("Error allocating CIDRSet") @@ -407,7 +408,7 @@ func TestDoubleOccupyRelease(t *testing.T) { // Execute the operations for _, op := range operations { - _, cidr, _ := net.ParseCIDR(op.cidrStr) + _, cidr, _ := netutils.ParseCIDRSloppy(op.cidrStr) switch op.operation { case "occupy": a.Occupy(cidr) @@ -557,7 +558,7 @@ func TestGetBitforCIDR(t *testing.T) { } for _, tc := range cases { - _, clusterCIDR, err := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, err := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) if err != nil { t.Fatalf("unexpected error: %v for %v", err, tc.description) } @@ -566,7 +567,7 @@ func TestGetBitforCIDR(t *testing.T) { if err != nil { t.Fatalf("Error allocating CIDRSet for %v", tc.description) } - _, subnetCIDR, err := net.ParseCIDR(tc.subNetCIDRStr) + _, subnetCIDR, err := netutils.ParseCIDRSloppy(tc.subNetCIDRStr) if err != nil { t.Fatalf("unexpected error: %v for %v", err, tc.description) } @@ -727,7 +728,7 @@ func TestOccupy(t *testing.T) { } for _, tc := range cases { - _, clusterCIDR, err := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, err := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) if err != nil { t.Fatalf("unexpected error: %v for %v", err, tc.description) } @@ -737,7 +738,7 @@ func TestOccupy(t *testing.T) { t.Fatalf("Error allocating CIDRSet for %v", tc.description) } - _, subnetCIDR, err := net.ParseCIDR(tc.subNetCIDRStr) + _, subnetCIDR, err := netutils.ParseCIDRSloppy(tc.subNetCIDRStr) if err != nil { t.Fatalf("unexpected error: %v for %v", err, tc.description) } @@ -796,7 +797,7 @@ func TestCIDRSetv6(t *testing.T) { } for _, tc := range cases { t.Run(tc.description, func(t *testing.T) { - _, clusterCIDR, _ := net.ParseCIDR(tc.clusterCIDRStr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(tc.clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, tc.subNetMaskSize) if gotErr := err != nil; gotErr != tc.expectErr { t.Fatalf("NewCIDRSet(%v, %v) = %v, %v; gotErr = %t, want %t", clusterCIDR, tc.subNetMaskSize, a, err, gotErr, tc.expectErr) @@ -834,7 +835,7 @@ func TestCIDRSetv6(t *testing.T) { func TestCidrSetMetrics(t *testing.T) { cidr := "10.0.0.0/16" - _, clusterCIDR, _ := net.ParseCIDR(cidr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(cidr) // We have 256 free cidrs a, err := NewCIDRSet(clusterCIDR, 24) if err != nil { @@ -880,7 +881,7 @@ func TestCidrSetMetrics(t *testing.T) { func TestCidrSetMetricsHistogram(t *testing.T) { cidr := "10.0.0.0/16" - _, clusterCIDR, _ := net.ParseCIDR(cidr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(cidr) // We have 256 free cidrs a, err := NewCIDRSet(clusterCIDR, 24) if err != nil { @@ -890,7 +891,7 @@ func TestCidrSetMetricsHistogram(t *testing.T) { // Allocate half of the range // Occupy does not update the nextCandidate - _, halfClusterCIDR, _ := net.ParseCIDR("10.0.0.0/17") + _, halfClusterCIDR, _ := netutils.ParseCIDRSloppy("10.0.0.0/17") a.Occupy(halfClusterCIDR) em := testMetrics{ usage: 0.5, @@ -917,7 +918,7 @@ func TestCidrSetMetricsHistogram(t *testing.T) { func TestCidrSetMetricsDual(t *testing.T) { // create IPv4 cidrSet cidrIPv4 := "10.0.0.0/16" - _, clusterCIDRv4, _ := net.ParseCIDR(cidrIPv4) + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy(cidrIPv4) a, err := NewCIDRSet(clusterCIDRv4, 24) if err != nil { t.Fatalf("unexpected error creating CidrSet: %v", err) @@ -925,7 +926,7 @@ func TestCidrSetMetricsDual(t *testing.T) { clearMetrics(map[string]string{"clusterCIDR": cidrIPv4}) // create IPv6 cidrSet cidrIPv6 := "2001:db8::/48" - _, clusterCIDRv6, _ := net.ParseCIDR(cidrIPv6) + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy(cidrIPv6) b, err := NewCIDRSet(clusterCIDRv6, 64) if err != nil { t.Fatalf("unexpected error creating CidrSet: %v", err) @@ -1012,7 +1013,7 @@ func expectMetrics(t *testing.T, label string, em testMetrics) { // Benchmarks func benchmarkAllocateAllIPv6(cidr string, subnetMaskSize int, b *testing.B) { - _, clusterCIDR, _ := net.ParseCIDR(cidr) + _, clusterCIDR, _ := netutils.ParseCIDRSloppy(cidr) a, _ := NewCIDRSet(clusterCIDR, subnetMaskSize) for n := 0; n < b.N; n++ { // Allocate the whole range + 1 diff --git a/pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go b/pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go index 656216aec29..30c78d4100c 100644 --- a/pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go +++ b/pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go @@ -318,7 +318,7 @@ func needPodCIDRsUpdate(node *v1.Node, podCIDRs []*net.IPNet) (bool, error) { if node.Spec.PodCIDR == "" { return true, nil } - _, nodePodCIDR, err := net.ParseCIDR(node.Spec.PodCIDR) + _, nodePodCIDR, err := netutils.ParseCIDRSloppy(node.Spec.PodCIDR) if err != nil { klog.ErrorS(err, "Found invalid node.Spec.PodCIDR", "node.Spec.PodCIDR", node.Spec.PodCIDR) // We will try to overwrite with new CIDR(s) diff --git a/pkg/controller/nodeipam/ipam/controller_legacyprovider.go b/pkg/controller/nodeipam/ipam/controller_legacyprovider.go index 9e37c606884..cd1a4977717 100644 --- a/pkg/controller/nodeipam/ipam/controller_legacyprovider.go +++ b/pkg/controller/nodeipam/ipam/controller_legacyprovider.go @@ -25,8 +25,9 @@ import ( "time" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" informers "k8s.io/client-go/informers/core/v1" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" @@ -119,7 +120,7 @@ func (c *Controller) Start(nodeInformer informers.NodeInformer) error { } for _, node := range nodes.Items { if node.Spec.PodCIDR != "" { - _, cidrRange, err := net.ParseCIDR(node.Spec.PodCIDR) + _, cidrRange, err := netutils.ParseCIDRSloppy(node.Spec.PodCIDR) if err == nil { c.set.Occupy(cidrRange) klog.V(3).Infof("Occupying CIDR for node %q (%v)", node.Name, node.Spec.PodCIDR) diff --git a/pkg/controller/nodeipam/ipam/range_allocator.go b/pkg/controller/nodeipam/ipam/range_allocator.go index 695c19c4c49..e5603341ab8 100644 --- a/pkg/controller/nodeipam/ipam/range_allocator.go +++ b/pkg/controller/nodeipam/ipam/range_allocator.go @@ -21,8 +21,9 @@ import ( "net" "sync" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" @@ -224,7 +225,7 @@ func (r *rangeAllocator) occupyCIDRs(node *v1.Node) error { return nil } for idx, cidr := range node.Spec.PodCIDRs { - _, podCIDR, err := net.ParseCIDR(cidr) + _, podCIDR, err := netutils.ParseCIDRSloppy(cidr) if err != nil { return fmt.Errorf("failed to parse node %s, CIDR %s", node.Name, node.Spec.PodCIDR) } @@ -286,7 +287,7 @@ func (r *rangeAllocator) ReleaseCIDR(node *v1.Node) error { } for idx, cidr := range node.Spec.PodCIDRs { - _, podCIDR, err := net.ParseCIDR(cidr) + _, podCIDR, err := netutils.ParseCIDRSloppy(cidr) if err != nil { return fmt.Errorf("failed to parse CIDR %s on Node %v: %v", cidr, node.Name, err) } diff --git a/pkg/controller/nodeipam/ipam/range_allocator_test.go b/pkg/controller/nodeipam/ipam/range_allocator_test.go index ff34d4b7a18..0e7c452e01f 100644 --- a/pkg/controller/nodeipam/ipam/range_allocator_test.go +++ b/pkg/controller/nodeipam/ipam/range_allocator_test.go @@ -30,6 +30,7 @@ import ( "k8s.io/client-go/kubernetes/fake" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/testutil" + netutils "k8s.io/utils/net" ) const testNodePollInterval = 10 * time.Millisecond @@ -86,7 +87,7 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") return []*net.IPNet{clusterCIDRv4} }(), ServiceCIDR: nil, @@ -111,8 +112,8 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/8") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/8") return []*net.IPNet{clusterCIDRv4, clusterCIDRv6} }(), ServiceCIDR: nil, @@ -140,7 +141,7 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") return []*net.IPNet{clusterCIDRv4} }(), ServiceCIDR: nil, @@ -168,8 +169,8 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/8") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/8") return []*net.IPNet{clusterCIDRv4, clusterCIDRv6} }(), ServiceCIDR: nil, @@ -198,7 +199,7 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") return []*net.IPNet{clusterCIDRv4} }(), ServiceCIDR: nil, @@ -227,7 +228,7 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") return []*net.IPNet{clusterCIDRv4} }(), ServiceCIDR: nil, @@ -256,8 +257,8 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/8") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/8") return []*net.IPNet{clusterCIDRv4, clusterCIDRv6} }(), ServiceCIDR: nil, @@ -286,8 +287,8 @@ func TestOccupyPreExistingCIDR(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("10.10.0.0/16") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/8") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("10.10.0.0/16") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/8") return []*net.IPNet{clusterCIDRv4, clusterCIDRv6} }(), ServiceCIDR: nil, @@ -341,7 +342,7 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("127.123.234.0/24") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/24") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: nil, @@ -366,11 +367,11 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("127.123.234.0/24") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/24") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: func() *net.IPNet { - _, serviceCIDR, _ := net.ParseCIDR("127.123.234.0/26") + _, serviceCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/26") return serviceCIDR }(), SecondaryServiceCIDR: nil, @@ -395,11 +396,11 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("127.123.234.0/24") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/24") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: func() *net.IPNet { - _, serviceCIDR, _ := net.ParseCIDR("127.123.234.0/26") + _, serviceCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/26") return serviceCIDR }(), SecondaryServiceCIDR: nil, @@ -426,12 +427,12 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("127.123.234.0/8") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/84") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("127.123.234.0/8") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/84") return []*net.IPNet{clusterCIDRv4, clusterCIDRv6} }(), ServiceCIDR: func() *net.IPNet { - _, serviceCIDR, _ := net.ParseCIDR("127.123.234.0/26") + _, serviceCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/26") return serviceCIDR }(), SecondaryServiceCIDR: nil, @@ -452,12 +453,12 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("127.123.234.0/8") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/84") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("127.123.234.0/8") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/84") return []*net.IPNet{clusterCIDRv6, clusterCIDRv4} }(), ServiceCIDR: func() *net.IPNet { - _, serviceCIDR, _ := net.ParseCIDR("127.123.234.0/26") + _, serviceCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/26") return serviceCIDR }(), SecondaryServiceCIDR: nil, @@ -478,13 +479,13 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDRv4, _ := net.ParseCIDR("127.123.234.0/8") - _, clusterCIDRv6, _ := net.ParseCIDR("ace:cab:deca::/84") - _, clusterCIDRv4_2, _ := net.ParseCIDR("10.0.0.0/8") + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy("127.123.234.0/8") + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/84") + _, clusterCIDRv4_2, _ := netutils.ParseCIDRSloppy("10.0.0.0/8") return []*net.IPNet{clusterCIDRv4, clusterCIDRv6, clusterCIDRv4_2} }(), ServiceCIDR: func() *net.IPNet { - _, serviceCIDR, _ := net.ParseCIDR("127.123.234.0/26") + _, serviceCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/26") return serviceCIDR }(), SecondaryServiceCIDR: nil, @@ -521,7 +522,7 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("10.10.0.0/22") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("10.10.0.0/22") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: nil, @@ -557,7 +558,7 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { // pre allocate the cidrs as per the test for idx, allocatedList := range tc.allocatedCIDRs { for _, allocated := range allocatedList { - _, cidr, err := net.ParseCIDR(allocated) + _, cidr, err := netutils.ParseCIDRSloppy(allocated) if err != nil { t.Fatalf("%v: unexpected error when parsing CIDR %v: %v", tc.description, allocated, err) } @@ -623,7 +624,7 @@ func TestAllocateOrOccupyCIDRFailure(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("127.123.234.0/28") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/28") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: nil, @@ -654,7 +655,7 @@ func TestAllocateOrOccupyCIDRFailure(t *testing.T) { // this is a bit of white box testing for setIdx, allocatedList := range tc.allocatedCIDRs { for _, allocated := range allocatedList { - _, cidr, err := net.ParseCIDR(allocated) + _, cidr, err := netutils.ParseCIDRSloppy(allocated) if err != nil { t.Fatalf("%v: unexpected error when parsing CIDR %v: %v", tc.description, cidr, err) } @@ -727,7 +728,7 @@ func TestReleaseCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("127.123.234.0/28") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/28") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: nil, @@ -759,7 +760,7 @@ func TestReleaseCIDRSuccess(t *testing.T) { }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { - _, clusterCIDR, _ := net.ParseCIDR("127.123.234.0/28") + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("127.123.234.0/28") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: nil, @@ -796,7 +797,7 @@ func TestReleaseCIDRSuccess(t *testing.T) { // this is a bit of white box testing for setIdx, allocatedList := range tc.allocatedCIDRs { for _, allocated := range allocatedList { - _, cidr, err := net.ParseCIDR(allocated) + _, cidr, err := netutils.ParseCIDRSloppy(allocated) if err != nil { t.Fatalf("%v: unexpected error when parsing CIDR %v: %v", tc.description, allocated, err) } diff --git a/pkg/controller/nodeipam/ipam/sync/sync.go b/pkg/controller/nodeipam/ipam/sync/sync.go index 3150aebe8ed..2e736ab20d0 100644 --- a/pkg/controller/nodeipam/ipam/sync/sync.go +++ b/pkg/controller/nodeipam/ipam/sync/sync.go @@ -23,8 +23,9 @@ import ( "time" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/kubernetes/pkg/controller/nodeipam/ipam/cidrset" ) @@ -281,7 +282,7 @@ func (op *updateOp) updateAliasFromNode(ctx context.Context, sync *NodeSync, nod return fmt.Errorf("cannot sync to cloud in mode %q", sync.mode) } - _, aliasRange, err := net.ParseCIDR(node.Spec.PodCIDR) + _, aliasRange, err := netutils.ParseCIDRSloppy(node.Spec.PodCIDR) if err != nil { klog.Errorf("Could not parse PodCIDR (%q) for node %q: %v", node.Spec.PodCIDR, node.Name, err) @@ -364,7 +365,7 @@ func (op *deleteOp) run(sync *NodeSync) error { return nil } - _, cidrRange, err := net.ParseCIDR(op.node.Spec.PodCIDR) + _, cidrRange, err := netutils.ParseCIDRSloppy(op.node.Spec.PodCIDR) if err != nil { klog.Errorf("Deleted node %q has an invalid podCIDR %q: %v", op.node.Name, op.node.Spec.PodCIDR, err) diff --git a/pkg/controller/nodeipam/ipam/sync/sync_test.go b/pkg/controller/nodeipam/ipam/sync/sync_test.go index 60ae1d53838..df1ddd192fc 100644 --- a/pkg/controller/nodeipam/ipam/sync/sync_test.go +++ b/pkg/controller/nodeipam/ipam/sync/sync_test.go @@ -28,12 +28,13 @@ import ( "k8s.io/klog/v2" "k8s.io/kubernetes/pkg/controller/nodeipam/ipam/cidrset" "k8s.io/kubernetes/pkg/controller/nodeipam/ipam/test" + netutils "k8s.io/utils/net" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" ) var ( - _, clusterCIDRRange, _ = net.ParseCIDR("10.1.0.0/16") + _, clusterCIDRRange, _ = netutils.ParseCIDRSloppy("10.1.0.0/16") ) type fakeEvent struct { diff --git a/pkg/controller/nodeipam/ipam/test/utils.go b/pkg/controller/nodeipam/ipam/test/utils.go index 14fd6663086..42242e1899b 100644 --- a/pkg/controller/nodeipam/ipam/test/utils.go +++ b/pkg/controller/nodeipam/ipam/test/utils.go @@ -18,12 +18,14 @@ package test import ( "net" + + netutils "k8s.io/utils/net" ) // MustParseCIDR returns the CIDR range parsed from s or panics if the string // cannot be parsed. func MustParseCIDR(s string) *net.IPNet { - _, ret, err := net.ParseCIDR(s) + _, ret, err := netutils.ParseCIDRSloppy(s) if err != nil { panic(err) } diff --git a/pkg/controller/nodeipam/node_ipam_controller_test.go b/pkg/controller/nodeipam/node_ipam_controller_test.go index 117e7709f73..45b84480c89 100644 --- a/pkg/controller/nodeipam/node_ipam_controller_test.go +++ b/pkg/controller/nodeipam/node_ipam_controller_test.go @@ -89,8 +89,8 @@ func TestNewNodeIpamControllerWithCIDRMasks(t *testing.T) { } { t.Run(tc.desc, func(t *testing.T) { clusterCidrs, _ := netutils.ParseCIDRs(strings.Split(tc.clusterCIDR, ",")) - _, serviceCIDRIpNet, _ := net.ParseCIDR(tc.serviceCIDR) - _, secondaryServiceCIDRIpNet, _ := net.ParseCIDR(tc.secondaryServiceCIDR) + _, serviceCIDRIpNet, _ := netutils.ParseCIDRSloppy(tc.serviceCIDR) + _, secondaryServiceCIDRIpNet, _ := netutils.ParseCIDRSloppy(tc.secondaryServiceCIDR) if os.Getenv("EXIT_ON_FATAL") == "1" { // This is the subprocess which runs the actual code. diff --git a/pkg/controlplane/controller_test.go b/pkg/controlplane/controller_test.go index f5d7452ed0b..58a85688f65 100644 --- a/pkg/controlplane/controller_test.go +++ b/pkg/controlplane/controller_test.go @@ -17,7 +17,6 @@ limitations under the License. package controlplane import ( - "net" "reflect" "testing" @@ -28,6 +27,7 @@ import ( "k8s.io/client-go/kubernetes/fake" core "k8s.io/client-go/testing" "k8s.io/kubernetes/pkg/controlplane/reconcilers" + netutils "k8s.io/utils/net" ) func TestReconcileEndpoints(t *testing.T) { @@ -401,7 +401,7 @@ func TestReconcileEndpoints(t *testing.T) { } epAdapter := reconcilers.NewEndpointsAdapter(fakeClient.CoreV1(), nil) reconciler := reconcilers.NewMasterCountEndpointReconciler(test.additionalMasters+1, epAdapter) - err := reconciler.ReconcileEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts, true) + err := reconciler.ReconcileEndpoints(test.serviceName, netutils.ParseIPSloppy(test.ip), test.endpointPorts, true) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } @@ -520,7 +520,7 @@ func TestReconcileEndpoints(t *testing.T) { } epAdapter := reconcilers.NewEndpointsAdapter(fakeClient.CoreV1(), nil) reconciler := reconcilers.NewMasterCountEndpointReconciler(test.additionalMasters+1, epAdapter) - err := reconciler.ReconcileEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts, false) + err := reconciler.ReconcileEndpoints(test.serviceName, netutils.ParseIPSloppy(test.ip), test.endpointPorts, false) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } @@ -585,7 +585,7 @@ func TestEmptySubsets(t *testing.T) { endpointPorts := []corev1.EndpointPort{ {Name: "foo", Port: 8080, Protocol: "TCP"}, } - err := reconciler.RemoveEndpoints("foo", net.ParseIP("1.2.3.4"), endpointPorts) + err := reconciler.RemoveEndpoints("foo", netutils.ParseIPSloppy("1.2.3.4"), endpointPorts) if err != nil { t.Errorf("unexpected error: %v", err) } @@ -631,7 +631,7 @@ func TestCreateOrUpdateMasterService(t *testing.T) { master := Controller{} fakeClient := fake.NewSimpleClientset() master.ServiceClient = fakeClient.CoreV1() - master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, net.ParseIP("1.2.3.4"), test.servicePorts, test.serviceType, false) + master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, netutils.ParseIPSloppy("1.2.3.4"), test.servicePorts, test.serviceType, false) creates := []core.CreateAction{} for _, action := range fakeClient.Actions() { if action.GetVerb() == "create" { @@ -913,7 +913,7 @@ func TestCreateOrUpdateMasterService(t *testing.T) { master := Controller{} fakeClient := fake.NewSimpleClientset(test.service) master.ServiceClient = fakeClient.CoreV1() - err := master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, net.ParseIP("1.2.3.4"), test.servicePorts, test.serviceType, true) + err := master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, netutils.ParseIPSloppy("1.2.3.4"), test.servicePorts, test.serviceType, true) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } @@ -972,7 +972,7 @@ func TestCreateOrUpdateMasterService(t *testing.T) { master := Controller{} fakeClient := fake.NewSimpleClientset(test.service) master.ServiceClient = fakeClient.CoreV1() - err := master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, net.ParseIP("1.2.3.4"), test.servicePorts, test.serviceType, false) + err := master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, netutils.ParseIPSloppy("1.2.3.4"), test.servicePorts, test.serviceType, false) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } diff --git a/pkg/controlplane/instance_test.go b/pkg/controlplane/instance_test.go index 22eba219409..bd57ec46808 100644 --- a/pkg/controlplane/instance_test.go +++ b/pkg/controlplane/instance_test.go @@ -57,6 +57,7 @@ import ( certificatesrest "k8s.io/kubernetes/pkg/registry/certificates/rest" corerest "k8s.io/kubernetes/pkg/registry/core/rest" "k8s.io/kubernetes/pkg/registry/registrytest" + netutils "k8s.io/utils/net" "github.com/stretchr/testify/assert" ) @@ -72,7 +73,7 @@ func setUp(t *testing.T) (*etcd3testing.EtcdTestServer, Config, *assert.Assertio APIServerServicePort: 443, MasterCount: 1, EndpointReconcilerType: reconcilers.MasterCountReconcilerType, - ServiceIPRange: net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(24, 32)}, + ServiceIPRange: net.IPNet{IP: netutils.ParseIPSloppy("10.0.0.0"), Mask: net.CIDRMask(24, 32)}, }, } @@ -101,7 +102,7 @@ func setUp(t *testing.T) (*etcd3testing.EtcdTestServer, Config, *assert.Assertio config.GenericConfig.Version = &kubeVersion config.ExtraConfig.StorageFactory = storageFactory config.GenericConfig.LoopbackClientConfig = &restclient.Config{APIPath: "/api", ContentConfig: restclient.ContentConfig{NegotiatedSerializer: legacyscheme.Codecs}} - config.GenericConfig.PublicAddress = net.ParseIP("192.168.10.4") + config.GenericConfig.PublicAddress = netutils.ParseIPSloppy("192.168.10.4") config.GenericConfig.LegacyAPIGroupPrefixes = sets.NewString("/api") config.ExtraConfig.KubeletClientConfig = kubeletclient.KubeletClientConfig{Port: 10250} config.ExtraConfig.ProxyTransport = utilnet.SetTransportDefaults(&http.Transport{ diff --git a/pkg/controlplane/reconcilers/lease_test.go b/pkg/controlplane/reconcilers/lease_test.go index 21fdde8865f..1d27f1c0361 100644 --- a/pkg/controlplane/reconcilers/lease_test.go +++ b/pkg/controlplane/reconcilers/lease_test.go @@ -23,7 +23,6 @@ https://github.com/openshift/origin/blob/bb340c5dd5ff72718be86fb194dedc0faed7f4c import ( "context" - "net" "reflect" "testing" @@ -31,6 +30,7 @@ import ( discoveryv1 "k8s.io/api/discovery/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" + netutils "k8s.io/utils/net" ) type fakeLeases struct { @@ -459,7 +459,7 @@ func TestLeaseEndpointReconciler(t *testing.T) { epAdapter := EndpointsAdapter{endpointClient: clientset.CoreV1()} r := NewLeaseEndpointReconciler(epAdapter, fakeLeases) - err := r.ReconcileEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts, true) + err := r.ReconcileEndpoints(test.serviceName, netutils.ParseIPSloppy(test.ip), test.endpointPorts, true) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } @@ -560,7 +560,7 @@ func TestLeaseEndpointReconciler(t *testing.T) { } epAdapter := EndpointsAdapter{endpointClient: clientset.CoreV1()} r := NewLeaseEndpointReconciler(epAdapter, fakeLeases) - err := r.ReconcileEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts, false) + err := r.ReconcileEndpoints(test.serviceName, netutils.ParseIPSloppy(test.ip), test.endpointPorts, false) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } @@ -680,7 +680,7 @@ func TestLeaseRemoveEndpoints(t *testing.T) { } epAdapter := EndpointsAdapter{endpointClient: clientset.CoreV1()} r := NewLeaseEndpointReconciler(epAdapter, fakeLeases) - err := r.RemoveEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts) + err := r.RemoveEndpoints(test.serviceName, netutils.ParseIPSloppy(test.ip), test.endpointPorts) if err != nil { t.Errorf("case %q: unexpected error: %v", test.testName, err) } diff --git a/pkg/kubeapiserver/options/options.go b/pkg/kubeapiserver/options/options.go index 1314e52c05f..7f172208bcd 100644 --- a/pkg/kubeapiserver/options/options.go +++ b/pkg/kubeapiserver/options/options.go @@ -20,13 +20,14 @@ import ( "net" utilnet "k8s.io/apimachinery/pkg/util/net" + netutils "k8s.io/utils/net" ) // DefaultServiceNodePortRange is the default port range for NodePort services. var DefaultServiceNodePortRange = utilnet.PortRange{Base: 30000, Size: 2768} // DefaultServiceIPCIDR is a CIDR notation of IP range from which to allocate service cluster IPs -var DefaultServiceIPCIDR = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(24, 32)} +var DefaultServiceIPCIDR = net.IPNet{IP: netutils.ParseIPSloppy("10.0.0.0"), Mask: net.CIDRMask(24, 32)} // DefaultEtcdPathPrefix is the default key prefix of etcd for API Server const DefaultEtcdPathPrefix = "/registry" diff --git a/pkg/kubeapiserver/options/serving.go b/pkg/kubeapiserver/options/serving.go index 09d14703711..29d9415d416 100644 --- a/pkg/kubeapiserver/options/serving.go +++ b/pkg/kubeapiserver/options/serving.go @@ -18,16 +18,15 @@ limitations under the License. package options import ( - "net" - genericoptions "k8s.io/apiserver/pkg/server/options" + netutils "k8s.io/utils/net" ) // NewSecureServingOptions gives default values for the kube-apiserver which are not the options wanted by // "normal" API servers running on the platform func NewSecureServingOptions() *genericoptions.SecureServingOptionsWithLoopback { o := genericoptions.SecureServingOptions{ - BindAddress: net.ParseIP("0.0.0.0"), + BindAddress: netutils.ParseIPSloppy("0.0.0.0"), BindPort: 6443, Required: true, ServerCert: genericoptions.GeneratableKeyCert{ diff --git a/pkg/kubelet/certificate/kubelet.go b/pkg/kubelet/certificate/kubelet.go index 61f34191d10..5f370e11c30 100644 --- a/pkg/kubelet/certificate/kubelet.go +++ b/pkg/kubelet/certificate/kubelet.go @@ -35,6 +35,7 @@ import ( "k8s.io/component-base/metrics/legacyregistry" kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config" "k8s.io/kubernetes/pkg/kubelet/metrics" + netutils "k8s.io/utils/net" ) // NewKubeletServerCertificateManager creates a certificate manager for the kubelet when retrieving a server certificate @@ -159,13 +160,13 @@ func addressesToHostnamesAndIPs(addresses []v1.NodeAddress) (dnsNames []string, switch address.Type { case v1.NodeHostName: - if ip := net.ParseIP(address.Address); ip != nil { + if ip := netutils.ParseIPSloppy(address.Address); ip != nil { seenIPs[address.Address] = true } else { seenDNSNames[address.Address] = true } case v1.NodeExternalIP, v1.NodeInternalIP: - if ip := net.ParseIP(address.Address); ip != nil { + if ip := netutils.ParseIPSloppy(address.Address); ip != nil { seenIPs[address.Address] = true } case v1.NodeExternalDNS, v1.NodeInternalDNS: @@ -177,7 +178,7 @@ func addressesToHostnamesAndIPs(addresses []v1.NodeAddress) (dnsNames []string, dnsNames = append(dnsNames, dnsName) } for ip := range seenIPs { - ips = append(ips, net.ParseIP(ip)) + ips = append(ips, netutils.ParseIPSloppy(ip)) } // return in stable order diff --git a/pkg/kubelet/certificate/kubelet_test.go b/pkg/kubelet/certificate/kubelet_test.go index 3d8778f4473..755f07a6798 100644 --- a/pkg/kubelet/certificate/kubelet_test.go +++ b/pkg/kubelet/certificate/kubelet_test.go @@ -21,7 +21,8 @@ import ( "reflect" "testing" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" + netutils "k8s.io/utils/net" ) func TestAddressesToHostnamesAndIPs(t *testing.T) { @@ -62,7 +63,7 @@ func TestAddressesToHostnamesAndIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, }, wantDNSNames: []string{"hostname"}, - wantIPs: []net.IP{net.ParseIP("1.1.1.1")}, + wantIPs: []net.IP{netutils.ParseIPSloppy("1.1.1.1")}, }, { name: "order values", @@ -75,7 +76,7 @@ func TestAddressesToHostnamesAndIPs(t *testing.T) { {Type: v1.NodeInternalIP, Address: "3.3.3.3"}, }, wantDNSNames: []string{"hostname-1", "hostname-2", "hostname-3"}, - wantIPs: []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("2.2.2.2"), net.ParseIP("3.3.3.3")}, + wantIPs: []net.IP{netutils.ParseIPSloppy("1.1.1.1"), netutils.ParseIPSloppy("2.2.2.2"), netutils.ParseIPSloppy("3.3.3.3")}, }, { name: "handle IP and DNS hostnames", @@ -84,7 +85,7 @@ func TestAddressesToHostnamesAndIPs(t *testing.T) { {Type: v1.NodeHostName, Address: "1.1.1.1"}, }, wantDNSNames: []string{"hostname"}, - wantIPs: []net.IP{net.ParseIP("1.1.1.1")}, + wantIPs: []net.IP{netutils.ParseIPSloppy("1.1.1.1")}, }, } for _, tt := range tests { diff --git a/pkg/kubelet/dockershim/network/hostport/fake_iptables.go b/pkg/kubelet/dockershim/network/hostport/fake_iptables.go index e4715c2be58..e3d6fd0ecd7 100644 --- a/pkg/kubelet/dockershim/network/hostport/fake_iptables.go +++ b/pkg/kubelet/dockershim/network/hostport/fake_iptables.go @@ -21,12 +21,12 @@ package hostport import ( "bytes" "fmt" - "net" "strings" "time" "k8s.io/apimachinery/pkg/util/sets" utiliptables "k8s.io/kubernetes/pkg/util/iptables" + netutils "k8s.io/utils/net" ) type fakeChain struct { @@ -192,7 +192,7 @@ func normalizeRule(rule string) (string, error) { arg := remaining[:end] // Normalize un-prefixed IP addresses like iptables does - if net.ParseIP(arg) != nil { + if netutils.ParseIPSloppy(arg) != nil { arg += "/32" } diff --git a/pkg/kubelet/dockershim/network/hostport/hostport_manager_test.go b/pkg/kubelet/dockershim/network/hostport/hostport_manager_test.go index 1613b0d633a..c222c98ff55 100644 --- a/pkg/kubelet/dockershim/network/hostport/hostport_manager_test.go +++ b/pkg/kubelet/dockershim/network/hostport/hostport_manager_test.go @@ -20,7 +20,6 @@ package hostport import ( "bytes" - "net" "strings" "testing" @@ -28,6 +27,7 @@ import ( v1 "k8s.io/api/core/v1" utiliptables "k8s.io/kubernetes/pkg/util/iptables" "k8s.io/utils/exec" + netutils "k8s.io/utils/net" ) func TestOpenCloseHostports(t *testing.T) { @@ -249,7 +249,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod1", Namespace: "ns1", - IP: net.ParseIP("10.1.1.2"), + IP: netutils.ParseIPSloppy("10.1.1.2"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -276,7 +276,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod2", Namespace: "ns1", - IP: net.ParseIP("10.1.1.3"), + IP: netutils.ParseIPSloppy("10.1.1.3"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -303,7 +303,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod3", Namespace: "ns1", - IP: net.ParseIP("10.1.1.4"), + IP: netutils.ParseIPSloppy("10.1.1.4"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -320,7 +320,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod3", Namespace: "ns1", - IP: net.ParseIP("192.168.12.12"), + IP: netutils.ParseIPSloppy("192.168.12.12"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -337,7 +337,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod4", Namespace: "ns1", - IP: net.ParseIP("2001:beef::2"), + IP: netutils.ParseIPSloppy("2001:beef::2"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -356,7 +356,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod5", Namespace: "ns5", - IP: net.ParseIP("10.1.1.5"), + IP: netutils.ParseIPSloppy("10.1.1.5"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -380,7 +380,7 @@ func TestHostportManager(t *testing.T) { mapping: &PodPortMapping{ Name: "pod6", Namespace: "ns1", - IP: net.ParseIP("10.1.1.2"), + IP: netutils.ParseIPSloppy("10.1.1.2"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -555,7 +555,7 @@ func TestHostportManagerIPv6(t *testing.T) { mapping: &PodPortMapping{ Name: "pod1", Namespace: "ns1", - IP: net.ParseIP("2001:beef::2"), + IP: netutils.ParseIPSloppy("2001:beef::2"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -581,7 +581,7 @@ func TestHostportManagerIPv6(t *testing.T) { mapping: &PodPortMapping{ Name: "pod2", Namespace: "ns1", - IP: net.ParseIP("2001:beef::3"), + IP: netutils.ParseIPSloppy("2001:beef::3"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -607,7 +607,7 @@ func TestHostportManagerIPv6(t *testing.T) { mapping: &PodPortMapping{ Name: "pod3", Namespace: "ns1", - IP: net.ParseIP("2001:beef::4"), + IP: netutils.ParseIPSloppy("2001:beef::4"), HostNetwork: false, PortMappings: []*PortMapping{ { @@ -623,7 +623,7 @@ func TestHostportManagerIPv6(t *testing.T) { mapping: &PodPortMapping{ Name: "pod4", Namespace: "ns2", - IP: net.ParseIP("192.168.2.2"), + IP: netutils.ParseIPSloppy("192.168.2.2"), HostNetwork: false, PortMappings: []*PortMapping{ { diff --git a/pkg/kubelet/dockershim/network/kubenet/kubenet_linux.go b/pkg/kubelet/dockershim/network/kubenet/kubenet_linux.go index 2f82a157d25..e3457151a4f 100644 --- a/pkg/kubelet/dockershim/network/kubenet/kubenet_linux.go +++ b/pkg/kubelet/dockershim/network/kubenet/kubenet_linux.go @@ -259,7 +259,7 @@ func (plugin *kubenetNetworkPlugin) Event(name string, details map[string]interf } for idx, currentPodCIDR := range podCIDRs { - _, cidr, err := net.ParseCIDR(currentPodCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(currentPodCIDR) if nil != err { klog.InfoS("Failed to generate CNI network config with cidr at the index", "podCIDR", currentPodCIDR, "index", idx, "err", err) return @@ -451,7 +451,7 @@ func (plugin *kubenetNetworkPlugin) addPortMapping(id kubecontainer.ContainerID, Namespace: namespace, Name: name, PortMappings: portMappings, - IP: net.ParseIP(ip), + IP: netutils.ParseIPSloppy(ip), HostNetwork: false, } if netutils.IsIPv6(pm.IP) { @@ -635,7 +635,7 @@ func (plugin *kubenetNetworkPlugin) getNetworkStatus(id kubecontainer.ContainerI ips := make([]net.IP, 0, len(iplist)) for _, ip := range iplist { - ips = append(ips, net.ParseIP(ip)) + ips = append(ips, netutils.ParseIPSloppy(ip)) } return &network.PodNetworkStatus{ diff --git a/pkg/kubelet/dockershim/network/kubenet/kubenet_linux_test.go b/pkg/kubelet/dockershim/network/kubenet/kubenet_linux_test.go index 460e78960c9..b2811a6d56c 100644 --- a/pkg/kubelet/dockershim/network/kubenet/kubenet_linux_test.go +++ b/pkg/kubelet/dockershim/network/kubenet/kubenet_linux_test.go @@ -40,6 +40,7 @@ import ( sysctltest "k8s.io/kubernetes/pkg/util/sysctl/testing" "k8s.io/utils/exec" fakeexec "k8s.io/utils/exec/testing" + netutils "k8s.io/utils/net" ) // test it fulfills the NetworkPlugin interface @@ -337,7 +338,7 @@ func TestGetRoutesConfig(t *testing.T) { } { var cidrs []*net.IPNet for _, c := range test.cidrs { - _, cidr, err := net.ParseCIDR(c) + _, cidr, err := netutils.ParseCIDRSloppy(c) assert.NoError(t, err) cidrs = append(cidrs, cidr) } @@ -378,7 +379,7 @@ func TestGetRangesConfig(t *testing.T) { } { var cidrs []*net.IPNet for _, c := range test.cidrs { - _, cidr, err := net.ParseCIDR(c) + _, cidr, err := netutils.ParseCIDRSloppy(c) assert.NoError(t, err) cidrs = append(cidrs, cidr) } diff --git a/pkg/kubelet/dockershim/network/plugins.go b/pkg/kubelet/dockershim/network/plugins.go index ce715f5d05a..01de45de5f3 100644 --- a/pkg/kubelet/dockershim/network/plugins.go +++ b/pkg/kubelet/dockershim/network/plugins.go @@ -36,6 +36,7 @@ import ( "k8s.io/kubernetes/pkg/kubelet/dockershim/network/metrics" utilsysctl "k8s.io/kubernetes/pkg/util/sysctl" utilexec "k8s.io/utils/exec" + netutils "k8s.io/utils/net" utilfeature "k8s.io/apiserver/pkg/util/feature" kubefeatures "k8s.io/kubernetes/pkg/features" @@ -248,7 +249,7 @@ func getOnePodIP(execer utilexec.Interface, nsenterPath, netnsPath, interfaceNam if len(fields) < 4 { return nil, fmt.Errorf("unexpected address output %s ", lines[0]) } - ip, _, err := net.ParseCIDR(fields[3]) + ip, _, err := netutils.ParseCIDRSloppy(fields[3]) if err != nil { return nil, fmt.Errorf("CNI failed to parse ip from output %s due to %v", output, err) } diff --git a/pkg/kubelet/dockershim/network/testing/plugins_test.go b/pkg/kubelet/dockershim/network/testing/plugins_test.go index 8943197afe1..072fe5e1497 100644 --- a/pkg/kubelet/dockershim/network/testing/plugins_test.go +++ b/pkg/kubelet/dockershim/network/testing/plugins_test.go @@ -20,7 +20,6 @@ package testing import ( "fmt" - "net" "sync" "testing" @@ -29,6 +28,7 @@ import ( kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/dockershim/network" sysctltest "k8s.io/kubernetes/pkg/util/sysctl/testing" + netutils "k8s.io/utils/net" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" @@ -96,7 +96,7 @@ func TestPluginManager(t *testing.T) { containerID := kubecontainer.ContainerID{ID: podName} fnp.EXPECT().SetUpPod("", podName, containerID).Return(nil).Times(4) - fnp.EXPECT().GetPodNetworkStatus("", podName, containerID).Return(&network.PodNetworkStatus{IP: net.ParseIP("1.2.3.4")}, nil).Times(4) + fnp.EXPECT().GetPodNetworkStatus("", podName, containerID).Return(&network.PodNetworkStatus{IP: netutils.ParseIPSloppy("1.2.3.4")}, nil).Times(4) fnp.EXPECT().TearDownPod("", podName, containerID).Return(nil).Times(4) for x := 0; x < 4; x++ { @@ -173,7 +173,7 @@ func (p *hookableFakeNetworkPlugin) TearDownPod(string, string, kubecontainer.Co } func (p *hookableFakeNetworkPlugin) GetPodNetworkStatus(string, string, kubecontainer.ContainerID) (*network.PodNetworkStatus, error) { - return &network.PodNetworkStatus{IP: net.ParseIP("10.1.2.3")}, nil + return &network.PodNetworkStatus{IP: netutils.ParseIPSloppy("10.1.2.3")}, nil } func (p *hookableFakeNetworkPlugin) Status() error { diff --git a/pkg/kubelet/kubelet.go b/pkg/kubelet/kubelet.go index fa72f734208..844074eb3ad 100644 --- a/pkg/kubelet/kubelet.go +++ b/pkg/kubelet/kubelet.go @@ -38,6 +38,7 @@ import ( libcontaineruserns "github.com/opencontainers/runc/libcontainer/userns" "k8s.io/mount-utils" "k8s.io/utils/integer" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -505,7 +506,7 @@ func NewMainKubelet(kubeCfg *kubeletconfiginternal.KubeletConfiguration, clusterDNS := make([]net.IP, 0, len(kubeCfg.ClusterDNS)) for _, ipEntry := range kubeCfg.ClusterDNS { - ip := net.ParseIP(ipEntry) + ip := netutils.ParseIPSloppy(ipEntry) if ip == nil { klog.InfoS("Invalid clusterDNS IP", "IP", ipEntry) } else { diff --git a/pkg/kubelet/kubelet_node_status_test.go b/pkg/kubelet/kubelet_node_status_test.go index aa9c56b6d38..eef40762b2c 100644 --- a/pkg/kubelet/kubelet_node_status_test.go +++ b/pkg/kubelet/kubelet_node_status_test.go @@ -58,6 +58,7 @@ import ( kubeletvolume "k8s.io/kubernetes/pkg/kubelet/volumemanager" taintutil "k8s.io/kubernetes/pkg/util/taints" "k8s.io/kubernetes/pkg/volume/util" + netutils "k8s.io/utils/net" ) const ( @@ -2484,7 +2485,7 @@ func TestValidateNodeIPParam(t *testing.T) { tests = append(tests, successTest) } for _, test := range tests { - err := validateNodeIP(net.ParseIP(test.nodeIP)) + err := validateNodeIP(netutils.ParseIPSloppy(test.nodeIP)) if test.success { assert.NoError(t, err, "test %s", test.testName) } else { diff --git a/pkg/kubelet/kubelet_pods_test.go b/pkg/kubelet/kubelet_pods_test.go index b059864d8a4..1dd1da19744 100644 --- a/pkg/kubelet/kubelet_pods_test.go +++ b/pkg/kubelet/kubelet_pods_test.go @@ -42,6 +42,7 @@ import ( core "k8s.io/client-go/testing" "k8s.io/client-go/tools/record" featuregatetesting "k8s.io/component-base/featuregate/testing" + netutils "k8s.io/utils/net" // TODO: remove this import if // api.Registry.GroupOrDie(v1.GroupName).GroupVersions[0].String() is changed @@ -3426,7 +3427,7 @@ func TestGenerateAPIPodStatusPodIPs(t *testing.T) { defer testKubelet.Cleanup() kl := testKubelet.kubelet if tc.nodeIP != "" { - kl.nodeIPs = []net.IP{net.ParseIP(tc.nodeIP)} + kl.nodeIPs = []net.IP{netutils.ParseIPSloppy(tc.nodeIP)} } pod := podWithUIDNameNs("12345", "test-pod", "test-namespace") @@ -3530,7 +3531,7 @@ func TestSortPodIPs(t *testing.T) { defer testKubelet.Cleanup() kl := testKubelet.kubelet if tc.nodeIP != "" { - kl.nodeIPs = []net.IP{net.ParseIP(tc.nodeIP)} + kl.nodeIPs = []net.IP{netutils.ParseIPSloppy(tc.nodeIP)} } podIPs := kl.sortPodIPs(tc.podIPs) diff --git a/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go b/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go index 95832f9f13e..f5ada096d16 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go @@ -18,7 +18,6 @@ package kuberuntime import ( "fmt" - "net" "net/url" "runtime" "sort" @@ -33,6 +32,7 @@ import ( "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/kubelet/util" "k8s.io/kubernetes/pkg/kubelet/util/format" + netutils "k8s.io/utils/net" ) // createPodSandbox creates a pod sandbox and returns (podSandBoxID, message, error). @@ -298,7 +298,7 @@ func (m *kubeGenericRuntimeManager) determinePodSandboxIPs(podNamespace, podName // pick primary IP if len(podSandbox.Network.Ip) != 0 { - if net.ParseIP(podSandbox.Network.Ip) == nil { + if netutils.ParseIPSloppy(podSandbox.Network.Ip) == nil { klog.InfoS("Pod Sandbox reported an unparseable primary IP", "pod", klog.KRef(podNamespace, podName), "IP", podSandbox.Network.Ip) return nil } @@ -307,7 +307,7 @@ func (m *kubeGenericRuntimeManager) determinePodSandboxIPs(podNamespace, podName // pick additional ips, if cri reported them for _, podIP := range podSandbox.Network.AdditionalIps { - if nil == net.ParseIP(podIP.Ip) { + if nil == netutils.ParseIPSloppy(podIP.Ip) { klog.InfoS("Pod Sandbox reported an unparseable additional IP", "pod", klog.KRef(podNamespace, podName), "IP", podIP.Ip) return nil } diff --git a/pkg/kubelet/network/dns/dns_test.go b/pkg/kubelet/network/dns/dns_test.go index fb84ca11678..8d781b8deb7 100644 --- a/pkg/kubelet/network/dns/dns_test.go +++ b/pkg/kubelet/network/dns/dns_test.go @@ -35,6 +35,7 @@ import ( runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2" "k8s.io/kubernetes/pkg/apis/core/validation" "k8s.io/kubernetes/pkg/features" + netutils "k8s.io/utils/net" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -350,7 +351,7 @@ func TestGetPodDNSType(t *testing.T) { } testClusterDNSDomain := "TEST" clusterNS := "203.0.113.1" - testClusterDNS := []net.IP{net.ParseIP(clusterNS)} + testClusterDNS := []net.IP{netutils.ParseIPSloppy(clusterNS)} configurer := NewConfigurer(recorder, nodeRef, nil, nil, testClusterDNSDomain, "") @@ -477,7 +478,7 @@ func testGetPodDNS(t *testing.T) { } clusterNS := "203.0.113.1" testClusterDNSDomain := "kubernetes.io" - testClusterDNS := []net.IP{net.ParseIP(clusterNS)} + testClusterDNS := []net.IP{netutils.ParseIPSloppy(clusterNS)} configurer := NewConfigurer(recorder, nodeRef, nil, testClusterDNS, testClusterDNSDomain, "") @@ -606,7 +607,7 @@ func TestGetPodDNSCustom(t *testing.T) { t.Fatal(err) } - configurer := NewConfigurer(recorder, nodeRef, nil, []net.IP{net.ParseIP(testClusterNameserver)}, testClusterDNSDomain, tmpfile.Name()) + configurer := NewConfigurer(recorder, nodeRef, nil, []net.IP{netutils.ParseIPSloppy(testClusterNameserver)}, testClusterDNSDomain, tmpfile.Name()) testCases := []struct { desc string diff --git a/pkg/kubelet/nodestatus/setters.go b/pkg/kubelet/nodestatus/setters.go index 0ff7f6fced9..c062327ba8e 100644 --- a/pkg/kubelet/nodestatus/setters.go +++ b/pkg/kubelet/nodestatus/setters.go @@ -42,6 +42,7 @@ import ( kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/volume" + netutils "k8s.io/utils/net" "k8s.io/klog/v2" ) @@ -149,13 +150,13 @@ func NodeAddress(nodeIPs []net.IP, // typically Kubelet.nodeIPs // prefer addresses of the matching family sortedAddresses := make([]v1.NodeAddress, 0, len(cloudNodeAddresses)) for _, nodeAddress := range cloudNodeAddresses { - ip := net.ParseIP(nodeAddress.Address) + ip := netutils.ParseIPSloppy(nodeAddress.Address) if ip == nil || isPreferredIPFamily(ip) { sortedAddresses = append(sortedAddresses, nodeAddress) } } for _, nodeAddress := range cloudNodeAddresses { - ip := net.ParseIP(nodeAddress.Address) + ip := netutils.ParseIPSloppy(nodeAddress.Address) if ip != nil && !isPreferredIPFamily(ip) { sortedAddresses = append(sortedAddresses, nodeAddress) } @@ -219,7 +220,7 @@ func NodeAddress(nodeIPs []net.IP, // typically Kubelet.nodeIPs // unless nodeIP is "::", in which case it is reversed. if nodeIPSpecified { ipAddr = nodeIP - } else if addr := net.ParseIP(hostname); addr != nil { + } else if addr := netutils.ParseIPSloppy(hostname); addr != nil { ipAddr = addr } else { var addrs []net.IP diff --git a/pkg/kubelet/nodestatus/setters_test.go b/pkg/kubelet/nodestatus/setters_test.go index 0547446adba..83485d33df8 100644 --- a/pkg/kubelet/nodestatus/setters_test.go +++ b/pkg/kubelet/nodestatus/setters_test.go @@ -27,7 +27,7 @@ import ( cadvisorapiv1 "github.com/google/cadvisor/info/v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -44,6 +44,7 @@ import ( "k8s.io/kubernetes/pkg/kubelet/util/sliceutils" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" + netutils "k8s.io/utils/net" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -66,7 +67,7 @@ func TestNodeAddress(t *testing.T) { }{ { name: "A single InternalIP", - nodeIP: net.ParseIP("10.1.1.1"), + nodeIP: netutils.ParseIPSloppy("10.1.1.1"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeHostName, Address: testKubeletHostname}, @@ -79,7 +80,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "NodeIP is external", - nodeIP: net.ParseIP("55.55.55.55"), + nodeIP: netutils.ParseIPSloppy("55.55.55.55"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeExternalIP, Address: "55.55.55.55"}, @@ -95,7 +96,7 @@ func TestNodeAddress(t *testing.T) { { // Accommodating #45201 and #49202 name: "InternalIP and ExternalIP are the same", - nodeIP: net.ParseIP("55.55.55.55"), + nodeIP: netutils.ParseIPSloppy("55.55.55.55"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "44.44.44.44"}, {Type: v1.NodeExternalIP, Address: "44.44.44.44"}, @@ -112,7 +113,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "An Internal/ExternalIP, an Internal/ExternalDNS", - nodeIP: net.ParseIP("10.1.1.1"), + nodeIP: netutils.ParseIPSloppy("10.1.1.1"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeExternalIP, Address: "55.55.55.55"}, @@ -131,7 +132,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "An Internal with multiple internal IPs", - nodeIP: net.ParseIP("10.1.1.1"), + nodeIP: netutils.ParseIPSloppy("10.1.1.1"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeInternalIP, Address: "10.2.2.2"}, @@ -148,7 +149,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "An InternalIP that isn't valid: should error", - nodeIP: net.ParseIP("10.2.2.2"), + nodeIP: netutils.ParseIPSloppy("10.2.2.2"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeExternalIP, Address: "55.55.55.55"}, @@ -181,7 +182,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "cloud reports hostname, nodeIP is set, no override", - nodeIP: net.ParseIP("10.1.1.1"), + nodeIP: netutils.ParseIPSloppy("10.1.1.1"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeExternalIP, Address: "55.55.55.55"}, @@ -211,7 +212,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "cloud provider is external", - nodeIP: net.ParseIP("10.0.0.1"), + nodeIP: netutils.ParseIPSloppy("10.0.0.1"), nodeAddresses: []v1.NodeAddress{}, externalCloudProvider: true, expectedAddresses: []v1.NodeAddress{ @@ -250,7 +251,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "cloud doesn't report hostname, nodeIP is set, no override, detected hostname match", - nodeIP: net.ParseIP("10.1.1.1"), + nodeIP: netutils.ParseIPSloppy("10.1.1.1"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeExternalIP, Address: "55.55.55.55"}, @@ -266,7 +267,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "cloud doesn't report hostname, nodeIP is set, no override, detected hostname match with same type as nodeIP", - nodeIP: net.ParseIP("10.1.1.1"), + nodeIP: netutils.ParseIPSloppy("10.1.1.1"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeInternalIP, Address: testKubeletHostname}, // cloud-reported address value matches detected hostname @@ -323,7 +324,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "Dual-stack cloud, IPv4 first, request IPv4", - nodeIP: net.ParseIP("0.0.0.0"), + nodeIP: netutils.ParseIPSloppy("0.0.0.0"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeInternalIP, Address: "fc01:1234::5678"}, @@ -338,7 +339,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "Dual-stack cloud, IPv6 first, request IPv4", - nodeIP: net.ParseIP("0.0.0.0"), + nodeIP: netutils.ParseIPSloppy("0.0.0.0"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "fc01:1234::5678"}, {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, @@ -353,7 +354,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "Dual-stack cloud, IPv4 first, request IPv6", - nodeIP: net.ParseIP("::"), + nodeIP: netutils.ParseIPSloppy("::"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeInternalIP, Address: "fc01:1234::5678"}, @@ -368,7 +369,7 @@ func TestNodeAddress(t *testing.T) { }, { name: "Dual-stack cloud, IPv6 first, request IPv6", - nodeIP: net.ParseIP("::"), + nodeIP: netutils.ParseIPSloppy("::"), nodeAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "fc01:1234::5678"}, {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, @@ -448,7 +449,7 @@ func TestNodeAddress_NoCloudProvider(t *testing.T) { }{ { name: "Single --node-ip", - nodeIPs: []net.IP{net.ParseIP("10.1.1.1")}, + nodeIPs: []net.IP{netutils.ParseIPSloppy("10.1.1.1")}, expectedAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeHostName, Address: testKubeletHostname}, @@ -456,7 +457,7 @@ func TestNodeAddress_NoCloudProvider(t *testing.T) { }, { name: "Dual --node-ips", - nodeIPs: []net.IP{net.ParseIP("10.1.1.1"), net.ParseIP("fd01::1234")}, + nodeIPs: []net.IP{netutils.ParseIPSloppy("10.1.1.1"), netutils.ParseIPSloppy("fd01::1234")}, expectedAddresses: []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, {Type: v1.NodeInternalIP, Address: "fd01::1234"}, diff --git a/pkg/kubelet/server/server.go b/pkg/kubelet/server/server.go index 67e9469ad30..f234c48cf23 100644 --- a/pkg/kubelet/server/server.go +++ b/pkg/kubelet/server/server.go @@ -41,6 +41,7 @@ import ( "k8s.io/klog/v2" "k8s.io/kubernetes/pkg/kubelet/metrics/collectors" "k8s.io/utils/clock" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -144,7 +145,7 @@ func ListenAndServeKubeletServer( tlsOptions *TLSOptions, auth AuthInterface) { - address := net.ParseIP(kubeCfg.Address) + address := netutils.ParseIPSloppy(kubeCfg.Address) port := uint(kubeCfg.Port) klog.InfoS("Starting to listen", "address", address, "port", port) handler := NewServer(host, resourceAnalyzer, auth, kubeCfg) diff --git a/pkg/kubemark/hollow_proxy.go b/pkg/kubemark/hollow_proxy.go index c3e7a845bc8..4c2cee5cb5d 100644 --- a/pkg/kubemark/hollow_proxy.go +++ b/pkg/kubemark/hollow_proxy.go @@ -18,7 +18,6 @@ package kubemark import ( "fmt" - "net" "time" v1 "k8s.io/api/core/v1" @@ -35,6 +34,7 @@ import ( utilnode "k8s.io/kubernetes/pkg/util/node" utilsysctl "k8s.io/kubernetes/pkg/util/sysctl" utilexec "k8s.io/utils/exec" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" "k8s.io/klog/v2" @@ -83,7 +83,7 @@ func NewHollowProxyOrDie( nodeIP := utilnode.GetNodeIP(client, nodeName) if nodeIP == nil { klog.V(0).Infof("can't determine this node's IP, assuming 127.0.0.1") - nodeIP = net.ParseIP("127.0.0.1") + nodeIP = netutils.ParseIPSloppy("127.0.0.1") } // Real proxier with fake iptables, sysctl, etc underneath it. //var err error diff --git a/pkg/proxy/apis/config/v1alpha1/defaults.go b/pkg/proxy/apis/config/v1alpha1/defaults.go index f80e1836a62..30d677d7f0f 100644 --- a/pkg/proxy/apis/config/v1alpha1/defaults.go +++ b/pkg/proxy/apis/config/v1alpha1/defaults.go @@ -18,7 +18,6 @@ package v1alpha1 import ( "fmt" - "net" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -28,6 +27,7 @@ import ( "k8s.io/kubernetes/pkg/cluster/ports" "k8s.io/kubernetes/pkg/kubelet/qos" proxyutil "k8s.io/kubernetes/pkg/proxy/util" + netutils "k8s.io/utils/net" "k8s.io/utils/pointer" ) @@ -131,7 +131,7 @@ func SetDefaults_KubeProxyConfiguration(obj *kubeproxyconfigv1alpha1.KubeProxyCo // based on the given bind address. IPv6 addresses are enclosed in square // brackets for appending port. func getDefaultAddresses(bindAddress string) (defaultHealthzAddress, defaultMetricsAddress string) { - if net.ParseIP(bindAddress).To4() != nil { + if netutils.ParseIPSloppy(bindAddress).To4() != nil { return "0.0.0.0", "127.0.0.1" } return "[::]", "[::1]" diff --git a/pkg/proxy/apis/config/validation/validation.go b/pkg/proxy/apis/config/validation/validation.go index 8c49dd18ebd..5d179769a50 100644 --- a/pkg/proxy/apis/config/validation/validation.go +++ b/pkg/proxy/apis/config/validation/validation.go @@ -66,7 +66,7 @@ func Validate(config *kubeproxyconfig.KubeProxyConfiguration) field.ErrorList { allErrs = append(allErrs, field.Invalid(newPath.Child("ConfigSyncPeriod"), config.ConfigSyncPeriod, "must be greater than 0")) } - if net.ParseIP(config.BindAddress) == nil { + if netutils.ParseIPSloppy(config.BindAddress) == nil { allErrs = append(allErrs, field.Invalid(newPath.Child("BindAddress"), config.BindAddress, "not a valid textual representation of an IP address")) } @@ -94,7 +94,7 @@ func Validate(config *kubeproxyconfig.KubeProxyConfiguration) field.ErrorList { allErrs = append(allErrs, field.Invalid(newPath.Child("ClusterCIDR"), config.ClusterCIDR, "only one CIDR allowed (e.g. 10.100.0.0/16 or fde4:8dba:82e1::/48)")) // if we are here means that len(cidrs) == 1, we need to validate it default: - if _, _, err := net.ParseCIDR(config.ClusterCIDR); err != nil { + if _, _, err := netutils.ParseCIDRSloppy(config.ClusterCIDR); err != nil { allErrs = append(allErrs, field.Invalid(newPath.Child("ClusterCIDR"), config.ClusterCIDR, "must be a valid CIDR block (e.g. 10.100.0.0/16 or fde4:8dba:82e1::/48)")) } } @@ -228,7 +228,7 @@ func validateHostPort(input string, fldPath *field.Path) field.ErrorList { return allErrs } - if ip := net.ParseIP(hostIP); ip == nil { + if ip := netutils.ParseIPSloppy(hostIP); ip == nil { allErrs = append(allErrs, field.Invalid(fldPath, hostIP, "must be a valid IP")) } @@ -275,7 +275,7 @@ func validateKubeProxyNodePortAddress(nodePortAddresses []string, fldPath *field allErrs := field.ErrorList{} for i := range nodePortAddresses { - if _, _, err := net.ParseCIDR(nodePortAddresses[i]); err != nil { + if _, _, err := netutils.ParseCIDRSloppy(nodePortAddresses[i]); err != nil { allErrs = append(allErrs, field.Invalid(fldPath.Index(i), nodePortAddresses[i], "must be a valid CIDR")) } } @@ -305,7 +305,7 @@ func validateIPVSExcludeCIDRs(excludeCIDRs []string, fldPath *field.Path) field. allErrs := field.ErrorList{} for i := range excludeCIDRs { - if _, _, err := net.ParseCIDR(excludeCIDRs[i]); err != nil { + if _, _, err := netutils.ParseCIDRSloppy(excludeCIDRs[i]); err != nil { allErrs = append(allErrs, field.Invalid(fldPath.Index(i), excludeCIDRs[i], "must be a valid CIDR")) } } diff --git a/pkg/proxy/iptables/proxier.go b/pkg/proxy/iptables/proxier.go index a94d90022d9..8605b536bfa 100644 --- a/pkg/proxy/iptables/proxier.go +++ b/pkg/proxy/iptables/proxier.go @@ -53,7 +53,7 @@ import ( utiliptables "k8s.io/kubernetes/pkg/util/iptables" utilsysctl "k8s.io/kubernetes/pkg/util/sysctl" utilexec "k8s.io/utils/exec" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) const ( @@ -189,7 +189,7 @@ type Proxier struct { mu sync.Mutex // protects the following fields serviceMap proxy.ServiceMap endpointsMap proxy.EndpointsMap - portsMap map[utilnet.LocalPort]utilnet.Closeable + portsMap map[netutils.LocalPort]netutils.Closeable nodeLabels map[string]string // endpointSlicesSynced, and servicesSynced are set to true // when corresponding objects are synced after startup. This is used to avoid @@ -208,7 +208,7 @@ type Proxier struct { localDetector proxyutiliptables.LocalTrafficDetector hostname string nodeIP net.IP - portMapper utilnet.PortOpener + portMapper netutils.PortOpener recorder events.EventRecorder serviceHealthServer healthcheck.ServiceHealthServer @@ -295,7 +295,7 @@ func NewProxier(ipt utiliptables.Interface, } proxier := &Proxier{ - portsMap: make(map[utilnet.LocalPort]utilnet.Closeable), + portsMap: make(map[netutils.LocalPort]netutils.Closeable), serviceMap: make(proxy.ServiceMap), serviceChanges: proxy.NewServiceChangeTracker(newServiceInfo, ipFamily, recorder, nil), endpointsMap: make(proxy.EndpointsMap), @@ -308,7 +308,7 @@ func NewProxier(ipt utiliptables.Interface, localDetector: localDetector, hostname: hostname, nodeIP: nodeIP, - portMapper: &utilnet.ListenPortOpener, + portMapper: &netutils.ListenPortOpener, recorder: recorder, serviceHealthServer: serviceHealthServer, healthzServer: healthzServer, @@ -966,7 +966,7 @@ func (proxier *Proxier) syncProxyRules() { activeNATChains := map[utiliptables.Chain]bool{} // use a map as a set // Accumulate the set of local ports that we will be holding open once this update is complete - replacementPortsMap := map[utilnet.LocalPort]utilnet.Closeable{} + replacementPortsMap := map[netutils.LocalPort]netutils.Closeable{} // We are creating those slices ones here to avoid memory reallocations // in every loop. Note that reuse the memory, instead of doing: @@ -1006,10 +1006,10 @@ func (proxier *Proxier) syncProxyRules() { klog.ErrorS(nil, "Failed to cast serviceInfo", "svcName", svcName.String()) continue } - isIPv6 := utilnet.IsIPv6(svcInfo.ClusterIP()) - localPortIPFamily := utilnet.IPv4 + isIPv6 := netutils.IsIPv6(svcInfo.ClusterIP()) + localPortIPFamily := netutils.IPv4 if isIPv6 { - localPortIPFamily = utilnet.IPv6 + localPortIPFamily = netutils.IPv6 } protocol := strings.ToLower(string(svcInfo.Protocol())) svcNameString := svcInfo.serviceNameString @@ -1082,13 +1082,13 @@ func (proxier *Proxier) syncProxyRules() { // If the "external" IP happens to be an IP that is local to this // machine, hold the local port open so no other process can open it // (because the socket might open but it would never work). - if (svcInfo.Protocol() != v1.ProtocolSCTP) && localAddrSet.Has(net.ParseIP(externalIP)) { - lp := utilnet.LocalPort{ + if (svcInfo.Protocol() != v1.ProtocolSCTP) && localAddrSet.Has(netutils.ParseIPSloppy(externalIP)) { + lp := netutils.LocalPort{ Description: "externalIP for " + svcNameString, IP: externalIP, IPFamily: localPortIPFamily, Port: svcInfo.Port(), - Protocol: utilnet.Protocol(svcInfo.Protocol()), + Protocol: netutils.Protocol(svcInfo.Protocol()), } if proxier.portsMap[lp] != nil { klog.V(4).InfoS("Port was open before and is still needed", "port", lp.String()) @@ -1117,7 +1117,7 @@ func (proxier *Proxier) syncProxyRules() { args = append(args[:0], "-m", "comment", "--comment", fmt.Sprintf(`"%s external IP"`, svcNameString), "-m", protocol, "-p", protocol, - "-d", utilproxy.ToCIDR(net.ParseIP(externalIP)), + "-d", utilproxy.ToCIDR(netutils.ParseIPSloppy(externalIP)), "--dport", strconv.Itoa(svcInfo.Port()), ) @@ -1144,7 +1144,7 @@ func (proxier *Proxier) syncProxyRules() { "-A", string(kubeExternalServicesChain), "-m", "comment", "--comment", fmt.Sprintf(`"%s has no endpoints"`, svcNameString), "-m", protocol, "-p", protocol, - "-d", utilproxy.ToCIDR(net.ParseIP(externalIP)), + "-d", utilproxy.ToCIDR(netutils.ParseIPSloppy(externalIP)), "--dport", strconv.Itoa(svcInfo.Port()), "-j", "REJECT", ) @@ -1171,7 +1171,7 @@ func (proxier *Proxier) syncProxyRules() { "-A", string(kubeServicesChain), "-m", "comment", "--comment", fmt.Sprintf(`"%s loadbalancer IP"`, svcNameString), "-m", protocol, "-p", protocol, - "-d", utilproxy.ToCIDR(net.ParseIP(ingress)), + "-d", utilproxy.ToCIDR(netutils.ParseIPSloppy(ingress)), "--dport", strconv.Itoa(svcInfo.Port()), ) // jump to service firewall chain @@ -1199,7 +1199,7 @@ func (proxier *Proxier) syncProxyRules() { allowFromNode := false for _, src := range svcInfo.LoadBalancerSourceRanges() { utilproxy.WriteLine(proxier.natRules, append(args, "-s", src, "-j", string(chosenChain))...) - _, cidr, err := net.ParseCIDR(src) + _, cidr, err := netutils.ParseCIDRSloppy(src) if err != nil { klog.ErrorS(err, "Error parsing CIDR in LoadBalancerSourceRanges, dropping it", "cidr", cidr) } else if cidr.Contains(proxier.nodeIP) { @@ -1210,7 +1210,7 @@ func (proxier *Proxier) syncProxyRules() { // loadbalancer's backend hosts. In this case, request will not hit the loadbalancer but loop back directly. // Need to add the following rule to allow request on host. if allowFromNode { - utilproxy.WriteLine(proxier.natRules, append(args, "-s", utilproxy.ToCIDR(net.ParseIP(ingress)), "-j", string(chosenChain))...) + utilproxy.WriteLine(proxier.natRules, append(args, "-s", utilproxy.ToCIDR(netutils.ParseIPSloppy(ingress)), "-j", string(chosenChain))...) } } @@ -1223,7 +1223,7 @@ func (proxier *Proxier) syncProxyRules() { "-A", string(kubeExternalServicesChain), "-m", "comment", "--comment", fmt.Sprintf(`"%s has no endpoints"`, svcNameString), "-m", protocol, "-p", protocol, - "-d", utilproxy.ToCIDR(net.ParseIP(ingress)), + "-d", utilproxy.ToCIDR(netutils.ParseIPSloppy(ingress)), "--dport", strconv.Itoa(svcInfo.Port()), "-j", "REJECT", ) @@ -1241,14 +1241,14 @@ func (proxier *Proxier) syncProxyRules() { continue } - lps := make([]utilnet.LocalPort, 0) + lps := make([]netutils.LocalPort, 0) for address := range nodeAddresses { - lp := utilnet.LocalPort{ + lp := netutils.LocalPort{ Description: "nodePort for " + svcNameString, IP: address, IPFamily: localPortIPFamily, Port: svcInfo.NodePort(), - Protocol: utilnet.Protocol(svcInfo.Protocol()), + Protocol: netutils.Protocol(svcInfo.Protocol()), } if utilproxy.IsZeroCIDR(address) { // Empty IP address means all @@ -1441,7 +1441,7 @@ func (proxier *Proxier) syncProxyRules() { args = proxier.appendServiceCommentLocked(args, svcNameString) // Handle traffic that loops back to the originator with SNAT. utilproxy.WriteLine(proxier.natRules, append(args, - "-s", utilproxy.ToCIDR(net.ParseIP(epIP)), + "-s", utilproxy.ToCIDR(netutils.ParseIPSloppy(epIP)), "-j", string(KubeMarkMasqChain))...) // Update client-affinity lists. if svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP { @@ -1564,7 +1564,7 @@ func (proxier *Proxier) syncProxyRules() { break } // Ignore IP addresses with incorrect version - if isIPv6 && !utilnet.IsIPv6String(address) || !isIPv6 && utilnet.IsIPv6String(address) { + if isIPv6 && !netutils.IsIPv6String(address) || !isIPv6 && netutils.IsIPv6String(address) { klog.ErrorS(nil, "IP has incorrect IP version", "ip", address) continue } diff --git a/pkg/proxy/iptables/proxier_test.go b/pkg/proxy/iptables/proxier_test.go index 325f2a71aae..32400ec2b56 100644 --- a/pkg/proxy/iptables/proxier_test.go +++ b/pkg/proxy/iptables/proxier_test.go @@ -51,7 +51,7 @@ import ( iptablestest "k8s.io/kubernetes/pkg/util/iptables/testing" "k8s.io/utils/exec" fakeexec "k8s.io/utils/exec/testing" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" ) @@ -285,7 +285,7 @@ func TestDeleteEndpointConnectionsIPv4(t *testing.T) { var expExecs int if conntrack.IsClearConntrackNeeded(tc.protocol) { isIPv6 := func(ip string) bool { - netIP := net.ParseIP(ip) + netIP := netutils.ParseIPSloppy(ip) return netIP.To4() == nil } endpointIP := utilproxy.IPPart(tc.endpoint) @@ -428,7 +428,7 @@ func TestDeleteEndpointConnectionsIPv6(t *testing.T) { var expExecs int if conntrack.IsClearConntrackNeeded(tc.protocol) { isIPv6 := func(ip string) bool { - netIP := net.ParseIP(ip) + netIP := netutils.ParseIPSloppy(ip) return netIP.To4() == nil } endpointIP := utilproxy.IPPart(tc.endpoint) @@ -471,12 +471,12 @@ func (f *fakeCloseable) Close() error { // fakePortOpener implements portOpener. type fakePortOpener struct { - openPorts []*utilnet.LocalPort + openPorts []*netutils.LocalPort } // OpenLocalPort fakes out the listen() and bind() used by syncProxyRules // to lock a local port. -func (f *fakePortOpener) OpenLocalPort(lp *utilnet.LocalPort) (utilnet.Closeable, error) { +func (f *fakePortOpener) OpenLocalPort(lp *netutils.LocalPort) (netutils.Closeable, error) { f.openPorts = append(f.openPorts, lp) return &fakeCloseable{}, nil } @@ -501,8 +501,8 @@ func NewFakeProxier(ipt utiliptables.Interface) *Proxier { masqueradeMark: "0x4000", localDetector: detectLocal, hostname: testHostname, - portsMap: make(map[utilnet.LocalPort]utilnet.Closeable), - portMapper: &fakePortOpener{[]*utilnet.LocalPort{}}, + portsMap: make(map[netutils.LocalPort]netutils.Closeable), + portMapper: &fakePortOpener{[]*netutils.LocalPort{}}, serviceHealthServer: healthcheck.NewFakeServiceHealthServer(), precomputedProbabilities: make([]string, 0, 1001), iptablesData: bytes.NewBuffer(nil), @@ -1123,9 +1123,9 @@ func TestNodePort(t *testing.T) { ) itf := net.Interface{Index: 0, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0} - addrs := []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(16, 32)}} + addrs := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.0.1"), Mask: net.CIDRMask(16, 32)}} itf1 := net.Interface{Index: 1, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0} - addrs1 := []net.Addr{&net.IPNet{IP: net.ParseIP("::1/128"), Mask: net.CIDRMask(128, 128)}} + addrs1 := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1/128"), Mask: net.CIDRMask(128, 128)}} fp.networkInterfacer.(*utilproxytest.FakeNetwork).AddInterfaceAddr(&itf, addrs) fp.networkInterfacer.(*utilproxytest.FakeNetwork).AddInterfaceAddr(&itf1, addrs1) fp.nodePortAddresses = []string{} @@ -1175,9 +1175,9 @@ func TestHealthCheckNodePort(t *testing.T) { ) itf := net.Interface{Index: 0, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0} - addrs := []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(16, 32)}} + addrs := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.0.1"), Mask: net.CIDRMask(16, 32)}} itf1 := net.Interface{Index: 1, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0} - addrs1 := []net.Addr{&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)}} + addrs1 := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1"), Mask: net.CIDRMask(128, 128)}} fp.networkInterfacer.(*utilproxytest.FakeNetwork).AddInterfaceAddr(&itf, addrs) fp.networkInterfacer.(*utilproxytest.FakeNetwork).AddInterfaceAddr(&itf1, addrs1) fp.nodePortAddresses = []string{"127.0.0.1/16"} @@ -1615,7 +1615,7 @@ func onlyLocalNodePorts(t *testing.T, fp *Proxier, ipt *iptablestest.FakeIPTable ) itf := net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0} - addrs := []net.Addr{&net.IPNet{IP: net.ParseIP("10.20.30.51"), Mask: net.CIDRMask(24, 32)}} + addrs := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("10.20.30.51"), Mask: net.CIDRMask(24, 32)}} fp.networkInterfacer.(*utilproxytest.FakeNetwork).AddInterfaceAddr(&itf, addrs) fp.nodePortAddresses = []string{"10.20.30.0/24"} diff --git a/pkg/proxy/ipvs/graceful_termination_test.go b/pkg/proxy/ipvs/graceful_termination_test.go index 626bef565bf..b48e1342824 100644 --- a/pkg/proxy/ipvs/graceful_termination_test.go +++ b/pkg/proxy/ipvs/graceful_termination_test.go @@ -17,12 +17,12 @@ limitations under the License. package ipvs import ( - "net" "reflect" "testing" utilipvs "k8s.io/kubernetes/pkg/util/ipvs" utilipvstest "k8s.io/kubernetes/pkg/util/ipvs/testing" + netutils "k8s.io/utils/net" ) func Test_GracefulDeleteRS(t *testing.T) { @@ -37,12 +37,12 @@ func Test_GracefulDeleteRS(t *testing.T) { { name: "graceful delete, no connections results in deleting the real server immediatetly", vs: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, rs: &utilipvs.RealServer{ - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 0, @@ -55,7 +55,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -67,7 +67,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 0, @@ -83,7 +83,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -101,12 +101,12 @@ func Test_GracefulDeleteRS(t *testing.T) { { name: "graceful delete, real server has active connections, weight should be 0 but don't delete", vs: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, rs: &utilipvs.RealServer{ - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 10, @@ -119,7 +119,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -131,7 +131,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 10, @@ -147,7 +147,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -159,7 +159,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 0, ActiveConn: 10, @@ -173,12 +173,12 @@ func Test_GracefulDeleteRS(t *testing.T) { { name: "graceful delete, real server has in-active connections, weight should be 0 but don't delete", vs: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, rs: &utilipvs.RealServer{ - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 0, @@ -191,7 +191,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -203,7 +203,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 0, @@ -219,7 +219,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -231,7 +231,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 0, ActiveConn: 0, @@ -245,12 +245,12 @@ func Test_GracefulDeleteRS(t *testing.T) { { name: "graceful delete, real server has connections, but udp connections are deleted immediately", vs: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "udp", Port: uint16(80), }, rs: &utilipvs.RealServer{ - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 10, @@ -263,7 +263,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "udp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "udp", Port: uint16(80), }, @@ -275,7 +275,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "udp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 10, @@ -291,7 +291,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "udp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "udp", Port: uint16(80), }, @@ -309,12 +309,12 @@ func Test_GracefulDeleteRS(t *testing.T) { { name: "graceful delete, real server mismatch should be no-op", vs: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, rs: &utilipvs.RealServer{ - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(81), // port mismatched Weight: 100, ActiveConn: 0, @@ -327,7 +327,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -339,7 +339,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 0, @@ -355,7 +355,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Port: 80, Protocol: "tcp", }: { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: "tcp", Port: uint16(80), }, @@ -367,7 +367,7 @@ func Test_GracefulDeleteRS(t *testing.T) { Protocol: "tcp", }: { { - Address: net.ParseIP("10.0.0.1"), + Address: netutils.ParseIPSloppy("10.0.0.1"), Port: uint16(80), Weight: 100, ActiveConn: 0, diff --git a/pkg/proxy/ipvs/netlink_linux.go b/pkg/proxy/ipvs/netlink_linux.go index 156c1f0733c..06f1aad7bed 100644 --- a/pkg/proxy/ipvs/netlink_linux.go +++ b/pkg/proxy/ipvs/netlink_linux.go @@ -20,9 +20,9 @@ package ipvs import ( "fmt" - "net" "k8s.io/apimachinery/pkg/util/sets" + netutils "k8s.io/utils/net" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" @@ -44,7 +44,7 @@ func (h *netlinkHandle) EnsureAddressBind(address, devName string) (exist bool, if err != nil { return false, fmt.Errorf("error get interface: %s, err: %v", devName, err) } - addr := net.ParseIP(address) + addr := netutils.ParseIPSloppy(address) if addr == nil { return false, fmt.Errorf("error parse ip address: %s", address) } @@ -64,7 +64,7 @@ func (h *netlinkHandle) UnbindAddress(address, devName string) error { if err != nil { return fmt.Errorf("error get interface: %s, err: %v", devName, err) } - addr := net.ParseIP(address) + addr := netutils.ParseIPSloppy(address) if addr == nil { return fmt.Errorf("error parse ip address: %s", address) } diff --git a/pkg/proxy/ipvs/proxier.go b/pkg/proxy/ipvs/proxier.go index 9b1a076f7a9..f67d6200664 100644 --- a/pkg/proxy/ipvs/proxier.go +++ b/pkg/proxy/ipvs/proxier.go @@ -34,7 +34,7 @@ import ( "k8s.io/klog/v2" utilexec "k8s.io/utils/exec" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" discovery "k8s.io/api/discovery/v1" @@ -222,7 +222,7 @@ type Proxier struct { mu sync.Mutex // protects the following fields serviceMap proxy.ServiceMap endpointsMap proxy.EndpointsMap - portsMap map[utilnet.LocalPort]utilnet.Closeable + portsMap map[netutils.LocalPort]netutils.Closeable nodeLabels map[string]string // endpointSlicesSynced, and servicesSynced are set to true when // corresponding objects are synced after startup. This is used to avoid updating @@ -248,7 +248,7 @@ type Proxier struct { localDetector proxyutiliptables.LocalTrafficDetector hostname string nodeIP net.IP - portMapper utilnet.PortOpener + portMapper netutils.PortOpener recorder events.EventRecorder serviceHealthServer healthcheck.ServiceHealthServer @@ -312,7 +312,7 @@ func (r *realIPGetter) NodeIPs() (ips []net.IP, err error) { } // translate ip string to IP for _, ipStr := range nodeAddress.UnsortedList() { - a := net.ParseIP(ipStr) + a := netutils.ParseIPSloppy(ipStr) if a.IsLoopback() { continue } @@ -451,11 +451,11 @@ func NewProxier(ipt utiliptables.Interface, } // excludeCIDRs has been validated before, here we just parse it to IPNet list - parsedExcludeCIDRs, _ := utilnet.ParseCIDRs(excludeCIDRs) + parsedExcludeCIDRs, _ := netutils.ParseCIDRs(excludeCIDRs) proxier := &Proxier{ ipFamily: ipFamily, - portsMap: make(map[utilnet.LocalPort]utilnet.Closeable), + portsMap: make(map[netutils.LocalPort]netutils.Closeable), serviceMap: make(proxy.ServiceMap), serviceChanges: proxy.NewServiceChangeTracker(newServiceInfo, ipFamily, recorder, nil), endpointsMap: make(proxy.EndpointsMap), @@ -470,7 +470,7 @@ func NewProxier(ipt utiliptables.Interface, localDetector: localDetector, hostname: hostname, nodeIP: nodeIP, - portMapper: &utilnet.ListenPortOpener, + portMapper: &netutils.ListenPortOpener, recorder: recorder, serviceHealthServer: serviceHealthServer, healthzServer: healthzServer, @@ -558,7 +558,7 @@ func NewDualStackProxier( func filterCIDRs(wantIPv6 bool, cidrs []string) []string { var filteredCIDRs []string for _, cidr := range cidrs { - if utilnet.IsIPv6CIDRString(cidr) == wantIPv6 { + if netutils.IsIPv6CIDRString(cidr) == wantIPv6 { filteredCIDRs = append(filteredCIDRs, cidr) } } @@ -1077,7 +1077,7 @@ func (proxier *Proxier) syncProxyRules() { } // Accumulate the set of local ports that we will be holding open once this update is complete - replacementPortsMap := map[utilnet.LocalPort]utilnet.Closeable{} + replacementPortsMap := map[netutils.LocalPort]netutils.Closeable{} // activeIPVSServices represents IPVS service successfully created in this round of sync activeIPVSServices := map[string]bool{} // currentIPVSServices represent IPVS services listed from the system @@ -1115,7 +1115,7 @@ func (proxier *Proxier) syncProxyRules() { } else { nodeAddresses = nodeAddrSet.List() for _, address := range nodeAddresses { - a := net.ParseIP(address) + a := netutils.ParseIPSloppy(address) if a.IsLoopback() { continue } @@ -1134,7 +1134,7 @@ func (proxier *Proxier) syncProxyRules() { // filter node IPs by proxier ipfamily idx := 0 for _, nodeIP := range nodeIPs { - if (proxier.ipFamily == v1.IPv6Protocol) == utilnet.IsIPv6(nodeIP) { + if (proxier.ipFamily == v1.IPv6Protocol) == netutils.IsIPv6(nodeIP) { nodeIPs[idx] = nodeIP idx++ } @@ -1151,10 +1151,10 @@ func (proxier *Proxier) syncProxyRules() { klog.ErrorS(nil, "Failed to cast serviceInfo", "svcName", svcName.String()) continue } - isIPv6 := utilnet.IsIPv6(svcInfo.ClusterIP()) - localPortIPFamily := utilnet.IPv4 + isIPv6 := netutils.IsIPv6(svcInfo.ClusterIP()) + localPortIPFamily := netutils.IPv4 if isIPv6 { - localPortIPFamily = utilnet.IPv6 + localPortIPFamily = netutils.IPv6 } protocol := strings.ToLower(string(svcInfo.Protocol())) // Precompute svcNameString; with many services the many calls @@ -1240,14 +1240,14 @@ func (proxier *Proxier) syncProxyRules() { // If the "external" IP happens to be an IP that is local to this // machine, hold the local port open so no other process can open it // (because the socket might open but it would never work). - if (svcInfo.Protocol() != v1.ProtocolSCTP) && localAddrSet.Has(net.ParseIP(externalIP)) { + if (svcInfo.Protocol() != v1.ProtocolSCTP) && localAddrSet.Has(netutils.ParseIPSloppy(externalIP)) { // We do not start listening on SCTP ports, according to our agreement in the SCTP support KEP - lp := utilnet.LocalPort{ + lp := netutils.LocalPort{ Description: "externalIP for " + svcNameString, IP: externalIP, IPFamily: localPortIPFamily, Port: svcInfo.Port(), - Protocol: utilnet.Protocol(svcInfo.Protocol()), + Protocol: netutils.Protocol(svcInfo.Protocol()), } if proxier.portsMap[lp] != nil { klog.V(4).InfoS("Port was open before and is still needed", "port", lp.String()) @@ -1297,7 +1297,7 @@ func (proxier *Proxier) syncProxyRules() { // ipvs call serv := &utilipvs.VirtualServer{ - Address: net.ParseIP(externalIP), + Address: netutils.ParseIPSloppy(externalIP), Port: uint16(svcInfo.Port()), Protocol: string(svcInfo.Protocol()), Scheduler: proxier.ipvsScheduler, @@ -1372,7 +1372,7 @@ func (proxier *Proxier) syncProxyRules() { proxier.ipsetList[kubeLoadBalancerSourceCIDRSet].activeEntries.Insert(entry.String()) // ignore error because it has been validated - _, cidr, _ := net.ParseCIDR(src) + _, cidr, _ := netutils.ParseCIDRSloppy(src) if cidr.Contains(proxier.nodeIP) { allowFromNode = true } @@ -1399,7 +1399,7 @@ func (proxier *Proxier) syncProxyRules() { // ipvs call serv := &utilipvs.VirtualServer{ - Address: net.ParseIP(ingress), + Address: netutils.ParseIPSloppy(ingress), Port: uint16(svcInfo.Port()), Protocol: string(svcInfo.Protocol()), Scheduler: proxier.ipvsScheduler, @@ -1427,14 +1427,14 @@ func (proxier *Proxier) syncProxyRules() { continue } - var lps []utilnet.LocalPort + var lps []netutils.LocalPort for _, address := range nodeAddresses { - lp := utilnet.LocalPort{ + lp := netutils.LocalPort{ Description: "nodePort for " + svcNameString, IP: address, IPFamily: localPortIPFamily, Port: svcInfo.NodePort(), - Protocol: utilnet.Protocol(svcInfo.Protocol()), + Protocol: netutils.Protocol(svcInfo.Protocol()), } if utilproxy.IsZeroCIDR(address) { // Empty IP address means all @@ -1470,7 +1470,7 @@ func (proxier *Proxier) syncProxyRules() { } klog.V(2).InfoS("Opened local port", "port", lp.String()) - if lp.Protocol == utilnet.UDP { + if lp.Protocol == netutils.UDP { conntrack.ClearEntriesForPort(proxier.exec, lp.Port, isIPv6, v1.ProtocolUDP) } replacementPortsMap[lp] = socket @@ -2111,7 +2111,7 @@ func (proxier *Proxier) syncEndpoint(svcPortName proxy.ServicePortName, onlyNode } newDest := &utilipvs.RealServer{ - Address: net.ParseIP(ip), + Address: netutils.ParseIPSloppy(ip), Port: uint16(portNum), Weight: 1, } @@ -2154,7 +2154,7 @@ func (proxier *Proxier) syncEndpoint(svcPortName proxy.ServicePortName, onlyNode } delDest := &utilipvs.RealServer{ - Address: net.ParseIP(ip), + Address: netutils.ParseIPSloppy(ip), Port: uint16(portNum), } @@ -2169,13 +2169,13 @@ func (proxier *Proxier) syncEndpoint(svcPortName proxy.ServicePortName, onlyNode } func (proxier *Proxier) cleanLegacyService(activeServices map[string]bool, currentServices map[string]*utilipvs.VirtualServer, legacyBindAddrs map[string]bool) { - isIPv6 := utilnet.IsIPv6(proxier.nodeIP) + isIPv6 := netutils.IsIPv6(proxier.nodeIP) for cs := range currentServices { svc := currentServices[cs] if proxier.isIPInExcludeCIDRs(svc.Address) { continue } - if utilnet.IsIPv6(svc.Address) != isIPv6 { + if netutils.IsIPv6(svc.Address) != isIPv6 { // Not our family continue } @@ -2210,9 +2210,9 @@ func (proxier *Proxier) isIPInExcludeCIDRs(ip net.IP) bool { func (proxier *Proxier) getLegacyBindAddr(activeBindAddrs map[string]bool, currentBindAddrs []string) map[string]bool { legacyAddrs := make(map[string]bool) - isIPv6 := utilnet.IsIPv6(proxier.nodeIP) + isIPv6 := netutils.IsIPv6(proxier.nodeIP) for _, addr := range currentBindAddrs { - addrIsIPv6 := utilnet.IsIPv6(net.ParseIP(addr)) + addrIsIPv6 := netutils.IsIPv6(netutils.ParseIPSloppy(addr)) if addrIsIPv6 && !isIPv6 || !addrIsIPv6 && isIPv6 { continue } diff --git a/pkg/proxy/ipvs/proxier_test.go b/pkg/proxy/ipvs/proxier_test.go index e8796654054..a7bd9e51fa8 100644 --- a/pkg/proxy/ipvs/proxier_test.go +++ b/pkg/proxy/ipvs/proxier_test.go @@ -50,9 +50,8 @@ import ( ipvstest "k8s.io/kubernetes/pkg/util/ipvs/testing" "k8s.io/utils/exec" fakeexec "k8s.io/utils/exec/testing" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" - - utilnet "k8s.io/utils/net" ) const testHostname = "test-hostname" @@ -72,12 +71,12 @@ func (f *fakeIPGetter) BindedIPs() (sets.String, error) { // fakePortOpener implements portOpener. type fakePortOpener struct { - openPorts []*utilnet.LocalPort + openPorts []*netutils.LocalPort } // OpenLocalPort fakes out the listen() and bind() used by syncProxyRules // to lock a local port. -func (f *fakePortOpener) OpenLocalPort(lp *utilnet.LocalPort) (utilnet.Closeable, error) { +func (f *fakePortOpener) OpenLocalPort(lp *netutils.LocalPort) (netutils.Closeable, error) { f.openPorts = append(f.openPorts, lp) return nil, nil } @@ -113,7 +112,7 @@ func NewFakeProxier(ipt utiliptables.Interface, ipvs utilipvs.Interface, ipset u // filter node IPs by proxier ipfamily idx := 0 for _, nodeIP := range nodeIPs { - if (ipFamily == v1.IPv6Protocol) == utilnet.IsIPv6(nodeIP) { + if (ipFamily == v1.IPv6Protocol) == netutils.IsIPv6(nodeIP) { nodeIPs[idx] = nodeIP idx++ } @@ -153,8 +152,8 @@ func NewFakeProxier(ipt utiliptables.Interface, ipvs utilipvs.Interface, ipset u strictARP: false, localDetector: proxyutiliptables.NewNoOpLocalDetector(), hostname: testHostname, - portsMap: make(map[utilnet.LocalPort]utilnet.Closeable), - portMapper: &fakePortOpener{[]*utilnet.LocalPort{}}, + portsMap: make(map[netutils.LocalPort]netutils.Closeable), + portMapper: &fakePortOpener{[]*netutils.LocalPort{}}, serviceHealthServer: healthcheck.NewFakeServiceHealthServer(), ipvsScheduler: DefaultScheduler, ipGetter: &fakeIPGetter{nodeIPs: nodeIPs}, @@ -513,8 +512,8 @@ func TestNodePortIPv4(t *testing.T) { }), }, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), - net.ParseIP("2001:db8::1:1"), + netutils.ParseIPSloppy("100.101.102.103"), + netutils.ParseIPSloppy("2001:db8::1:1"), }, nodePortAddresses: []string{}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -524,7 +523,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -534,7 +533,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 3001, Protocol: "TCP", }: { - Address: net.ParseIP("100.101.102.103"), + Address: netutils.ParseIPSloppy("100.101.102.103"), Protocol: "TCP", Port: uint16(3001), Scheduler: "rr", @@ -547,7 +546,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "TCP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -558,7 +557,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "TCP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -594,7 +593,7 @@ func TestNodePortIPv4(t *testing.T) { }), }, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), + netutils.ParseIPSloppy("100.101.102.103"), }, nodePortAddresses: []string{"0.0.0.0/0"}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -604,7 +603,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 80, Protocol: "UDP", }: { - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "UDP", Port: uint16(80), Scheduler: "rr", @@ -614,7 +613,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 3001, Protocol: "UDP", }: { - Address: net.ParseIP("100.101.102.103"), + Address: netutils.ParseIPSloppy("100.101.102.103"), Protocol: "UDP", Port: uint16(3001), Scheduler: "rr", @@ -627,7 +626,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "UDP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -638,7 +637,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "UDP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -677,7 +676,7 @@ func TestNodePortIPv4(t *testing.T) { }, endpoints: []*discovery.EndpointSlice{}, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), + netutils.ParseIPSloppy("100.101.102.103"), }, nodePortAddresses: []string{}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -687,7 +686,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -697,7 +696,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 3001, Protocol: "TCP", }: { - Address: net.ParseIP("100.101.102.103"), + Address: netutils.ParseIPSloppy("100.101.102.103"), Protocol: "TCP", Port: uint16(3001), Scheduler: "rr", @@ -745,12 +744,12 @@ func TestNodePortIPv4(t *testing.T) { }), }, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), - net.ParseIP("100.101.102.104"), - net.ParseIP("100.101.102.105"), - net.ParseIP("2001:db8::1:1"), - net.ParseIP("2001:db8::1:2"), - net.ParseIP("2001:db8::1:3"), + netutils.ParseIPSloppy("100.101.102.103"), + netutils.ParseIPSloppy("100.101.102.104"), + netutils.ParseIPSloppy("100.101.102.105"), + netutils.ParseIPSloppy("2001:db8::1:1"), + netutils.ParseIPSloppy("2001:db8::1:2"), + netutils.ParseIPSloppy("2001:db8::1:3"), }, nodePortAddresses: []string{}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -760,7 +759,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 80, Protocol: "SCTP", }: { - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "SCTP", Port: uint16(80), Scheduler: "rr", @@ -770,7 +769,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 3001, Protocol: "SCTP", }: { - Address: net.ParseIP("100.101.102.103"), + Address: netutils.ParseIPSloppy("100.101.102.103"), Protocol: "SCTP", Port: uint16(3001), Scheduler: "rr", @@ -780,7 +779,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 3001, Protocol: "SCTP", }: { - Address: net.ParseIP("100.101.102.104"), + Address: netutils.ParseIPSloppy("100.101.102.104"), Protocol: "SCTP", Port: uint16(3001), Scheduler: "rr", @@ -790,7 +789,7 @@ func TestNodePortIPv4(t *testing.T) { Port: 3001, Protocol: "SCTP", }: { - Address: net.ParseIP("100.101.102.105"), + Address: netutils.ParseIPSloppy("100.101.102.105"), Protocol: "SCTP", Port: uint16(3001), Scheduler: "rr", @@ -803,7 +802,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -814,7 +813,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -825,7 +824,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -836,7 +835,7 @@ func TestNodePortIPv4(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -951,8 +950,8 @@ func TestNodePortIPv6(t *testing.T) { }), }, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), - net.ParseIP("2001:db8::1:1"), + netutils.ParseIPSloppy("100.101.102.103"), + netutils.ParseIPSloppy("2001:db8::1:1"), }, nodePortAddresses: []string{}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -962,7 +961,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 3001, Protocol: "TCP", }: { - Address: net.ParseIP("2001:db8::1:1"), + Address: netutils.ParseIPSloppy("2001:db8::1:1"), Protocol: "TCP", Port: uint16(3001), Scheduler: "rr", @@ -972,7 +971,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("2020::1"), + Address: netutils.ParseIPSloppy("2020::1"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -985,7 +984,7 @@ func TestNodePortIPv6(t *testing.T) { Protocol: "TCP", }: { { - Address: net.ParseIP("1002:ab8::2:10"), + Address: netutils.ParseIPSloppy("1002:ab8::2:10"), Port: uint16(80), Weight: 1, }, @@ -997,7 +996,7 @@ func TestNodePortIPv6(t *testing.T) { Protocol: "TCP", }: { { - Address: net.ParseIP("1002:ab8::2:10"), + Address: netutils.ParseIPSloppy("1002:ab8::2:10"), Port: uint16(80), Weight: 1, }, @@ -1034,7 +1033,7 @@ func TestNodePortIPv6(t *testing.T) { }), }, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), + netutils.ParseIPSloppy("100.101.102.103"), }, nodePortAddresses: []string{"0.0.0.0/0"}, /*since this is a node with only IPv4, proxier should not do anything */ @@ -1062,8 +1061,8 @@ func TestNodePortIPv6(t *testing.T) { }, endpoints: []*discovery.EndpointSlice{}, nodeIPs: []net.IP{ - net.ParseIP("100.101.102.103"), - net.ParseIP("2001:db8::1:1"), + netutils.ParseIPSloppy("100.101.102.103"), + netutils.ParseIPSloppy("2001:db8::1:1"), }, nodePortAddresses: []string{}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -1073,7 +1072,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 3001, Protocol: "TCP", }: { - Address: net.ParseIP("2001:db8::1:1"), + Address: netutils.ParseIPSloppy("2001:db8::1:1"), Protocol: "TCP", Port: uint16(3001), Scheduler: "rr", @@ -1083,7 +1082,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("2020::1"), + Address: netutils.ParseIPSloppy("2020::1"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -1132,8 +1131,8 @@ func TestNodePortIPv6(t *testing.T) { }), }, nodeIPs: []net.IP{ - net.ParseIP("2001:db8::1:1"), - net.ParseIP("2001:db8::1:2"), + netutils.ParseIPSloppy("2001:db8::1:1"), + netutils.ParseIPSloppy("2001:db8::1:2"), }, nodePortAddresses: []string{}, expectedIPVS: &ipvstest.FakeIPVS{ @@ -1143,7 +1142,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 3001, Protocol: "SCTP", }: { - Address: net.ParseIP("2001:db8::1:1"), + Address: netutils.ParseIPSloppy("2001:db8::1:1"), Protocol: "SCTP", Port: uint16(3001), Scheduler: "rr", @@ -1153,7 +1152,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 3001, Protocol: "SCTP", }: { - Address: net.ParseIP("2001:db8::1:2"), + Address: netutils.ParseIPSloppy("2001:db8::1:2"), Protocol: "SCTP", Port: uint16(3001), Scheduler: "rr", @@ -1163,7 +1162,7 @@ func TestNodePortIPv6(t *testing.T) { Port: 80, Protocol: "SCTP", }: { - Address: net.ParseIP("2020::1"), + Address: netutils.ParseIPSloppy("2020::1"), Protocol: "SCTP", Port: uint16(80), Scheduler: "rr", @@ -1176,7 +1175,7 @@ func TestNodePortIPv6(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("2001::1"), + Address: netutils.ParseIPSloppy("2001::1"), Port: uint16(80), Weight: 1, }, @@ -1187,7 +1186,7 @@ func TestNodePortIPv6(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("2001::1"), + Address: netutils.ParseIPSloppy("2001::1"), Port: uint16(80), Weight: 1, }, @@ -1198,7 +1197,7 @@ func TestNodePortIPv6(t *testing.T) { Protocol: "SCTP", }: { { - Address: net.ParseIP("2001::1"), + Address: netutils.ParseIPSloppy("2001::1"), Port: uint16(80), Weight: 1, }, @@ -1313,7 +1312,7 @@ func TestIPv4Proxier(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -1326,7 +1325,7 @@ func TestIPv4Proxier(t *testing.T) { Protocol: "TCP", }: { { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(80), Weight: 1, }, @@ -1354,7 +1353,7 @@ func TestIPv4Proxier(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -1451,7 +1450,7 @@ func TestIPv6Proxier(t *testing.T) { Port: 8080, Protocol: "TCP", }: { - Address: net.ParseIP("1002:ab8::2:1"), + Address: netutils.ParseIPSloppy("1002:ab8::2:1"), Protocol: "TCP", Port: uint16(8080), Scheduler: "rr", @@ -1464,7 +1463,7 @@ func TestIPv6Proxier(t *testing.T) { Protocol: "TCP", }: { { - Address: net.ParseIP("1009:ab8::5:6"), + Address: netutils.ParseIPSloppy("1009:ab8::5:6"), Port: uint16(8080), Weight: 1, }, @@ -1492,7 +1491,7 @@ func TestIPv6Proxier(t *testing.T) { Port: 80, Protocol: "TCP", }: { - Address: net.ParseIP("2001::1"), + Address: netutils.ParseIPSloppy("2001::1"), Protocol: "TCP", Port: uint16(80), Scheduler: "rr", @@ -1832,7 +1831,7 @@ func TestLoadBalancer(t *testing.T) { } func TestOnlyLocalNodePorts(t *testing.T) { - nodeIP := net.ParseIP("100.101.102.103") + nodeIP := netutils.ParseIPSloppy("100.101.102.103") ipt, fp := buildFakeProxier() svcIP := "10.20.30.41" @@ -1882,9 +1881,9 @@ func TestOnlyLocalNodePorts(t *testing.T) { ) itf := net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0} - addrs := []net.Addr{&net.IPNet{IP: net.ParseIP("100.101.102.103"), Mask: net.CIDRMask(24, 32)}} + addrs := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("100.101.102.103"), Mask: net.CIDRMask(24, 32)}} itf1 := net.Interface{Index: 1, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0} - addrs1 := []net.Addr{&net.IPNet{IP: net.ParseIP("2001:db8::"), Mask: net.CIDRMask(64, 128)}} + addrs1 := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("2001:db8::"), Mask: net.CIDRMask(64, 128)}} fp.networkInterfacer.(*proxyutiltest.FakeNetwork).AddInterfaceAddr(&itf, addrs) fp.networkInterfacer.(*proxyutiltest.FakeNetwork).AddInterfaceAddr(&itf1, addrs1) fp.nodePortAddresses = []string{"100.101.102.0/24", "2001:db8::0/64"} @@ -1962,9 +1961,9 @@ func TestHealthCheckNodePort(t *testing.T) { ) itf := net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0} - addrs := []net.Addr{&net.IPNet{IP: net.ParseIP("100.101.102.103"), Mask: net.CIDRMask(24, 32)}} + addrs := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("100.101.102.103"), Mask: net.CIDRMask(24, 32)}} itf1 := net.Interface{Index: 1, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0} - addrs1 := []net.Addr{&net.IPNet{IP: net.ParseIP("2001:db8::"), Mask: net.CIDRMask(64, 128)}} + addrs1 := []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("2001:db8::"), Mask: net.CIDRMask(64, 128)}} fp.networkInterfacer.(*proxyutiltest.FakeNetwork).AddInterfaceAddr(&itf, addrs) fp.networkInterfacer.(*proxyutiltest.FakeNetwork).AddInterfaceAddr(&itf1, addrs1) fp.nodePortAddresses = []string{"100.101.102.0/24", "2001:db8::0/64"} @@ -2528,7 +2527,7 @@ func TestSessionAffinity(t *testing.T) { ipt := iptablestest.NewFake() ipvs := ipvstest.NewFake() ipset := ipsettest.NewFake(testIPSetVersion) - nodeIP := net.ParseIP("100.101.102.103") + nodeIP := netutils.ParseIPSloppy("100.101.102.103") fp := NewFakeProxier(ipt, ipvs, ipset, []net.IP{nodeIP}, nil, v1.IPv4Protocol) svcIP := "10.20.30.41" svcPort := 80 @@ -3432,7 +3431,7 @@ func Test_syncService(t *testing.T) { { // case 0, old virtual server is same as new virtual server oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolTCP), Port: 80, Scheduler: "rr", @@ -3440,7 +3439,7 @@ func Test_syncService(t *testing.T) { }, svcName: "foo", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolTCP), Port: 80, Scheduler: "rr", @@ -3452,7 +3451,7 @@ func Test_syncService(t *testing.T) { { // case 1, old virtual server is different from new virtual server oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolTCP), Port: 8080, Scheduler: "rr", @@ -3460,7 +3459,7 @@ func Test_syncService(t *testing.T) { }, svcName: "bar", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolTCP), Port: 8080, Scheduler: "rr", @@ -3472,7 +3471,7 @@ func Test_syncService(t *testing.T) { { // case 2, old virtual server is different from new virtual server oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolTCP), Port: 8080, Scheduler: "rr", @@ -3480,7 +3479,7 @@ func Test_syncService(t *testing.T) { }, svcName: "bar", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolTCP), Port: 8080, Scheduler: "wlc", @@ -3494,7 +3493,7 @@ func Test_syncService(t *testing.T) { oldVirtualServer: nil, svcName: "baz", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolUDP), Port: 53, Scheduler: "rr", @@ -3506,7 +3505,7 @@ func Test_syncService(t *testing.T) { { // case 4, SCTP, old virtual server is same as new virtual server oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 80, Scheduler: "rr", @@ -3514,7 +3513,7 @@ func Test_syncService(t *testing.T) { }, svcName: "foo", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 80, Scheduler: "rr", @@ -3526,7 +3525,7 @@ func Test_syncService(t *testing.T) { { // case 5, old virtual server is different from new virtual server oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 8080, Scheduler: "rr", @@ -3534,7 +3533,7 @@ func Test_syncService(t *testing.T) { }, svcName: "bar", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 8080, Scheduler: "rr", @@ -3546,7 +3545,7 @@ func Test_syncService(t *testing.T) { { // case 6, old virtual server is different from new virtual server oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 8080, Scheduler: "rr", @@ -3554,7 +3553,7 @@ func Test_syncService(t *testing.T) { }, svcName: "bar", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 8080, Scheduler: "wlc", @@ -3568,7 +3567,7 @@ func Test_syncService(t *testing.T) { oldVirtualServer: nil, svcName: "baz", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 53, Scheduler: "rr", @@ -3580,7 +3579,7 @@ func Test_syncService(t *testing.T) { { // case 8, virtual server address already binded, skip sync oldVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 53, Scheduler: "rr", @@ -3588,7 +3587,7 @@ func Test_syncService(t *testing.T) { }, svcName: "baz", newVirtualServer: &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: string(v1.ProtocolSCTP), Port: 53, Scheduler: "rr", @@ -3720,7 +3719,7 @@ func TestCleanLegacyService(t *testing.T) { ipt := iptablestest.NewFake() ipvs := ipvstest.NewFake() ipset := ipsettest.NewFake(testIPSetVersion) - excludeCIDRs, _ := utilnet.ParseCIDRs([]string{"3.3.3.0/24", "4.4.4.0/24"}) + excludeCIDRs, _ := netutils.ParseCIDRs([]string{"3.3.3.0/24", "4.4.4.0/24"}) fp := NewFakeProxier(ipt, ipvs, ipset, nil, excludeCIDRs, v1.IPv4Protocol) // All ipvs services that were processed in the latest sync loop. @@ -3729,7 +3728,7 @@ func TestCleanLegacyService(t *testing.T) { currentServices := map[string]*utilipvs.VirtualServer{ // Created by kube-proxy. "ipvs0": { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: string(v1.ProtocolUDP), Port: 53, Scheduler: "rr", @@ -3737,7 +3736,7 @@ func TestCleanLegacyService(t *testing.T) { }, // Created by kube-proxy. "ipvs1": { - Address: net.ParseIP("2.2.2.2"), + Address: netutils.ParseIPSloppy("2.2.2.2"), Protocol: string(v1.ProtocolUDP), Port: 54, Scheduler: "rr", @@ -3745,7 +3744,7 @@ func TestCleanLegacyService(t *testing.T) { }, // Created by an external party. "ipvs2": { - Address: net.ParseIP("3.3.3.3"), + Address: netutils.ParseIPSloppy("3.3.3.3"), Protocol: string(v1.ProtocolUDP), Port: 55, Scheduler: "rr", @@ -3753,7 +3752,7 @@ func TestCleanLegacyService(t *testing.T) { }, // Created by an external party. "ipvs3": { - Address: net.ParseIP("4.4.4.4"), + Address: netutils.ParseIPSloppy("4.4.4.4"), Protocol: string(v1.ProtocolUDP), Port: 56, Scheduler: "rr", @@ -3761,7 +3760,7 @@ func TestCleanLegacyService(t *testing.T) { }, // Created by an external party. "ipvs4": { - Address: net.ParseIP("5.5.5.5"), + Address: netutils.ParseIPSloppy("5.5.5.5"), Protocol: string(v1.ProtocolUDP), Port: 57, Scheduler: "rr", @@ -3769,7 +3768,7 @@ func TestCleanLegacyService(t *testing.T) { }, // Created by kube-proxy, but now stale. "ipvs5": { - Address: net.ParseIP("6.6.6.6"), + Address: netutils.ParseIPSloppy("6.6.6.6"), Protocol: string(v1.ProtocolUDP), Port: 58, Scheduler: "rr", @@ -3812,7 +3811,7 @@ func TestCleanLegacyService(t *testing.T) { // check that address "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4" are bound, ignore ipv6 addresses remainingAddrsMap := make(map[string]bool) for _, a := range remainingAddrs { - if net.ParseIP(a).To4() == nil { + if netutils.ParseIPSloppy(a).To4() == nil { continue } remainingAddrsMap[a] = true @@ -3834,21 +3833,21 @@ func TestCleanLegacyServiceWithRealServers(t *testing.T) { // All ipvs services in the system. currentServices := map[string]*utilipvs.VirtualServer{ "ipvs0": { // deleted with real servers - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: string(v1.ProtocolUDP), Port: 53, Scheduler: "rr", Flags: utilipvs.FlagHashed, }, "ipvs1": { // deleted no real server - Address: net.ParseIP("2.2.2.2"), + Address: netutils.ParseIPSloppy("2.2.2.2"), Protocol: string(v1.ProtocolUDP), Port: 54, Scheduler: "rr", Flags: utilipvs.FlagHashed, }, "ipvs2": { // not deleted - Address: net.ParseIP("3.3.3.3"), + Address: netutils.ParseIPSloppy("3.3.3.3"), Protocol: string(v1.ProtocolUDP), Port: 54, Scheduler: "rr", @@ -3859,13 +3858,13 @@ func TestCleanLegacyServiceWithRealServers(t *testing.T) { // "ipvs0" has a real server, but it should still be deleted since the Service is deleted realServers := map[*utilipvs.VirtualServer]*utilipvs.RealServer{ { - Address: net.ParseIP("1.1.1.1"), + Address: netutils.ParseIPSloppy("1.1.1.1"), Protocol: string(v1.ProtocolUDP), Port: 53, Scheduler: "rr", Flags: utilipvs.FlagHashed, }: { - Address: net.ParseIP("10.180.0.1"), + Address: netutils.ParseIPSloppy("10.180.0.1"), Port: uint16(53), Weight: 1, }, @@ -3905,7 +3904,7 @@ func TestCleanLegacyServiceWithRealServers(t *testing.T) { // check that address is "3.3.3.3" remainingAddrsMap := make(map[string]bool) for _, a := range remainingAddrs { - if net.ParseIP(a).To4() == nil { + if netutils.ParseIPSloppy(a).To4() == nil { continue } remainingAddrsMap[a] = true @@ -3921,12 +3920,12 @@ func TestCleanLegacyRealServersExcludeCIDRs(t *testing.T) { ipvs := ipvstest.NewFake() ipset := ipsettest.NewFake(testIPSetVersion) gtm := NewGracefulTerminationManager(ipvs) - excludeCIDRs, _ := utilnet.ParseCIDRs([]string{"4.4.4.4/32"}) + excludeCIDRs, _ := netutils.ParseCIDRs([]string{"4.4.4.4/32"}) fp := NewFakeProxier(ipt, ipvs, ipset, nil, excludeCIDRs, v1.IPv4Protocol) fp.gracefuldeleteManager = gtm vs := &utilipvs.VirtualServer{ - Address: net.ParseIP("4.4.4.4"), + Address: netutils.ParseIPSloppy("4.4.4.4"), Protocol: string(v1.ProtocolUDP), Port: 56, Scheduler: "rr", @@ -3937,13 +3936,13 @@ func TestCleanLegacyRealServersExcludeCIDRs(t *testing.T) { rss := []*utilipvs.RealServer{ { - Address: net.ParseIP("10.10.10.10"), + Address: netutils.ParseIPSloppy("10.10.10.10"), Port: 56, ActiveConn: 0, InactiveConn: 0, }, { - Address: net.ParseIP("11.11.11.11"), + Address: netutils.ParseIPSloppy("11.11.11.11"), Port: 56, ActiveConn: 0, InactiveConn: 0, @@ -3976,9 +3975,9 @@ func TestCleanLegacyService6(t *testing.T) { ipt := iptablestest.NewFake() ipvs := ipvstest.NewFake() ipset := ipsettest.NewFake(testIPSetVersion) - excludeCIDRs, _ := utilnet.ParseCIDRs([]string{"3000::/64", "4000::/64"}) + excludeCIDRs, _ := netutils.ParseCIDRs([]string{"3000::/64", "4000::/64"}) fp := NewFakeProxier(ipt, ipvs, ipset, nil, excludeCIDRs, v1.IPv4Protocol) - fp.nodeIP = net.ParseIP("::1") + fp.nodeIP = netutils.ParseIPSloppy("::1") // All ipvs services that were processed in the latest sync loop. activeServices := map[string]bool{"ipvs0": true, "ipvs1": true} @@ -3986,7 +3985,7 @@ func TestCleanLegacyService6(t *testing.T) { currentServices := map[string]*utilipvs.VirtualServer{ // Created by kube-proxy. "ipvs0": { - Address: net.ParseIP("1000::1"), + Address: netutils.ParseIPSloppy("1000::1"), Protocol: string(v1.ProtocolUDP), Port: 53, Scheduler: "rr", @@ -3994,7 +3993,7 @@ func TestCleanLegacyService6(t *testing.T) { }, // Created by kube-proxy. "ipvs1": { - Address: net.ParseIP("1000::2"), + Address: netutils.ParseIPSloppy("1000::2"), Protocol: string(v1.ProtocolUDP), Port: 54, Scheduler: "rr", @@ -4002,7 +4001,7 @@ func TestCleanLegacyService6(t *testing.T) { }, // Created by an external party. "ipvs2": { - Address: net.ParseIP("3000::1"), + Address: netutils.ParseIPSloppy("3000::1"), Protocol: string(v1.ProtocolUDP), Port: 55, Scheduler: "rr", @@ -4010,7 +4009,7 @@ func TestCleanLegacyService6(t *testing.T) { }, // Created by an external party. "ipvs3": { - Address: net.ParseIP("4000::1"), + Address: netutils.ParseIPSloppy("4000::1"), Protocol: string(v1.ProtocolUDP), Port: 56, Scheduler: "rr", @@ -4018,7 +4017,7 @@ func TestCleanLegacyService6(t *testing.T) { }, // Created by an external party. "ipvs4": { - Address: net.ParseIP("5000::1"), + Address: netutils.ParseIPSloppy("5000::1"), Protocol: string(v1.ProtocolUDP), Port: 57, Scheduler: "rr", @@ -4026,7 +4025,7 @@ func TestCleanLegacyService6(t *testing.T) { }, // Created by kube-proxy, but now stale. "ipvs5": { - Address: net.ParseIP("1000::6"), + Address: netutils.ParseIPSloppy("1000::6"), Protocol: string(v1.ProtocolUDP), Port: 58, Scheduler: "rr", @@ -4069,7 +4068,7 @@ func TestCleanLegacyService6(t *testing.T) { // check that address "1000::1", "1000::2", "3000::1", "4000::1" are still bound, ignore ipv4 addresses remainingAddrsMap := make(map[string]bool) for _, a := range remainingAddrs { - if net.ParseIP(a).To4() != nil { + if netutils.ParseIPSloppy(a).To4() != nil { continue } remainingAddrsMap[a] = true diff --git a/pkg/proxy/service.go b/pkg/proxy/service.go index 95e9bfa015c..bd08fbea6c2 100644 --- a/pkg/proxy/service.go +++ b/pkg/proxy/service.go @@ -25,6 +25,7 @@ import ( "k8s.io/client-go/tools/events" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -155,7 +156,7 @@ func (sct *ServiceChangeTracker) newBaseServiceInfo(port *v1.ServicePort, servic clusterIP := utilproxy.GetClusterIPByFamily(sct.ipFamily, service) info := &BaseServiceInfo{ - clusterIP: net.ParseIP(clusterIP), + clusterIP: netutils.ParseIPSloppy(clusterIP), port: int(port.Port), protocol: port.Protocol, nodePort: int(port.NodePort), diff --git a/pkg/proxy/service_test.go b/pkg/proxy/service_test.go index dbb98bf0e01..0f35b5dc386 100644 --- a/pkg/proxy/service_test.go +++ b/pkg/proxy/service_test.go @@ -17,7 +17,6 @@ limitations under the License. package proxy import ( - "net" "reflect" "testing" "time" @@ -29,13 +28,14 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/sets" + netutils "k8s.io/utils/net" ) const testHostname = "test-hostname" func makeTestServiceInfo(clusterIP string, port int, protocol string, healthcheckNodePort int, svcInfoFuncs ...func(*BaseServiceInfo)) *BaseServiceInfo { info := &BaseServiceInfo{ - clusterIP: net.ParseIP(clusterIP), + clusterIP: netutils.ParseIPSloppy(clusterIP), port: port, protocol: v1.Protocol(protocol), } diff --git a/pkg/proxy/userspace/proxier.go b/pkg/proxy/userspace/proxier.go index 381fa842a2f..13789d36f53 100644 --- a/pkg/proxy/userspace/proxier.go +++ b/pkg/proxy/userspace/proxier.go @@ -527,7 +527,7 @@ func (proxier *Proxier) mergeService(service *v1.Service) sets.String { continue } - serviceIP := net.ParseIP(service.Spec.ClusterIP) + serviceIP := netutils.ParseIPSloppy(service.Spec.ClusterIP) klog.V(1).InfoS("Adding new service", "serviceName", serviceName, "addr", net.JoinHostPort(serviceIP.String(), strconv.Itoa(int(servicePort.Port))), "protocol", servicePort.Protocol) info, err = proxier.addServiceOnPortInternal(serviceName, servicePort.Protocol, proxyPort, proxier.udpIdleTimeout) if err != nil { @@ -711,7 +711,7 @@ func sameConfig(info *ServiceInfo, service *v1.Service, port *v1.ServicePort) bo if info.protocol != port.Protocol || info.portal.port != int(port.Port) || info.nodePort != int(port.NodePort) { return false } - if !info.portal.ip.Equal(net.ParseIP(service.Spec.ClusterIP)) { + if !info.portal.ip.Equal(netutils.ParseIPSloppy(service.Spec.ClusterIP)) { return false } if !ipsEqual(info.externalIPs, service.Spec.ExternalIPs) { @@ -744,14 +744,14 @@ func (proxier *Proxier) openPortal(service proxy.ServicePortName, info *ServiceI return err } for _, publicIP := range info.externalIPs { - err = proxier.openOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service) + err = proxier.openOnePortal(portal{netutils.ParseIPSloppy(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service) if err != nil { return err } } for _, ingress := range info.loadBalancerStatus.Ingress { if ingress.IP != "" { - err = proxier.openOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service) + err = proxier.openOnePortal(portal{netutils.ParseIPSloppy(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service) if err != nil { return err } @@ -923,11 +923,11 @@ func (proxier *Proxier) closePortal(service proxy.ServicePortName, info *Service // Collect errors and report them all at the end. el := proxier.closeOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service) for _, publicIP := range info.externalIPs { - el = append(el, proxier.closeOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)...) + el = append(el, proxier.closeOnePortal(portal{netutils.ParseIPSloppy(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)...) } for _, ingress := range info.loadBalancerStatus.Ingress { if ingress.IP != "" { - el = append(el, proxier.closeOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)...) + el = append(el, proxier.closeOnePortal(portal{netutils.ParseIPSloppy(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)...) } } if info.nodePort != 0 { @@ -1116,11 +1116,11 @@ func iptablesFlush(ipt iptables.Interface) error { } // Used below. -var zeroIPv4 = net.ParseIP("0.0.0.0") -var localhostIPv4 = net.ParseIP("127.0.0.1") +var zeroIPv4 = netutils.ParseIPSloppy("0.0.0.0") +var localhostIPv4 = netutils.ParseIPSloppy("127.0.0.1") -var zeroIPv6 = net.ParseIP("::") -var localhostIPv6 = net.ParseIP("::1") +var zeroIPv6 = netutils.ParseIPSloppy("::") +var localhostIPv6 = netutils.ParseIPSloppy("::1") // Build a slice of iptables args that are common to from-container and from-host portal rules. func iptablesCommonPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol v1.Protocol, service proxy.ServicePortName) []string { diff --git a/pkg/proxy/userspace/proxier_test.go b/pkg/proxy/userspace/proxier_test.go index a9eca668962..fd89886b1dc 100644 --- a/pkg/proxy/userspace/proxier_test.go +++ b/pkg/proxy/userspace/proxier_test.go @@ -39,6 +39,7 @@ import ( ipttest "k8s.io/kubernetes/pkg/util/iptables/testing" "k8s.io/utils/exec" fakeexec "k8s.io/utils/exec/testing" + netutils "k8s.io/utils/net" ) const ( @@ -328,7 +329,7 @@ func TestTCPProxy(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -353,7 +354,7 @@ func TestUDPProxy(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -378,7 +379,7 @@ func TestUDPProxyTimeout(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -417,7 +418,7 @@ func TestMultiPortProxy(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -440,7 +441,7 @@ func TestMultiPortOnServiceAdd(t *testing.T) { lb := NewLoadBalancerRR() fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -473,7 +474,7 @@ func TestTCPProxyStop(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -505,7 +506,7 @@ func TestUDPProxyStop(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -537,7 +538,7 @@ func TestTCPProxyUpdateDelete(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -569,7 +570,7 @@ func TestUDPProxyUpdateDelete(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -602,7 +603,7 @@ func TestTCPProxyUpdateDeleteUpdate(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -640,7 +641,7 @@ func TestUDPProxyUpdateDeleteUpdate(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -678,7 +679,7 @@ func TestTCPProxyUpdatePort(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -716,7 +717,7 @@ func TestUDPProxyUpdatePort(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -754,7 +755,7 @@ func TestProxyUpdatePublicIPs(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -793,7 +794,7 @@ func TestProxyUpdatePortal(t *testing.T) { fexec := makeFakeExec() - p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(lb, netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } @@ -851,7 +852,7 @@ func TestOnServiceAddChangeMap(t *testing.T) { fexec := makeFakeExec() // Use long minSyncPeriod so we can test that immediate syncs work - p, err := createProxier(NewLoadBalancerRR(), net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Minute, udpIdleTimeoutForTest, newProxySocket) + p, err := createProxier(NewLoadBalancerRR(), netutils.ParseIPSloppy("0.0.0.0"), ipttest.NewFake(), fexec, netutils.ParseIPSloppy("127.0.0.1"), nil, time.Minute, time.Minute, udpIdleTimeoutForTest, newProxySocket) if err != nil { t.Fatal(err) } diff --git a/pkg/proxy/util/endpoints.go b/pkg/proxy/util/endpoints.go index 0e017c54b11..28d0d9da71d 100644 --- a/pkg/proxy/util/endpoints.go +++ b/pkg/proxy/util/endpoints.go @@ -22,13 +22,14 @@ import ( "strconv" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) // IPPart returns just the IP part of an IP or IP:port or endpoint string. If the IP // part is an IPv6 address enclosed in brackets (e.g. "[fd00:1::5]:9999"), // then the brackets are stripped as well. func IPPart(s string) string { - if ip := net.ParseIP(s); ip != nil { + if ip := netutils.ParseIPSloppy(s); ip != nil { // IP address without port return s } @@ -39,7 +40,7 @@ func IPPart(s string) string { return "" } // Check if host string is a valid IP address - ip := net.ParseIP(host) + ip := netutils.ParseIPSloppy(host) if ip == nil { klog.Errorf("invalid IP part '%s'", host) return "" diff --git a/pkg/proxy/util/endpoints_test.go b/pkg/proxy/util/endpoints_test.go index 2d23b5b0b5d..f248e46e91e 100644 --- a/pkg/proxy/util/endpoints_test.go +++ b/pkg/proxy/util/endpoints_test.go @@ -17,8 +17,9 @@ limitations under the License. package util import ( - "net" "testing" + + netutils "k8s.io/utils/net" ) func TestIPPart(t *testing.T) { @@ -112,7 +113,7 @@ func TestToCIDR(t *testing.T) { } for _, tc := range testCases { - ip := net.ParseIP(tc.ip) + ip := netutils.ParseIPSloppy(tc.ip) addr := ToCIDR(ip) if addr != tc.expectedAddr { t.Errorf("Unexpected host address for %s: Expected: %s, Got %s", tc.ip, tc.expectedAddr, addr) diff --git a/pkg/proxy/util/iptables/traffic.go b/pkg/proxy/util/iptables/traffic.go index d630bedf5ad..28e019673ab 100644 --- a/pkg/proxy/util/iptables/traffic.go +++ b/pkg/proxy/util/iptables/traffic.go @@ -18,11 +18,10 @@ package iptables import ( "fmt" - "net" "k8s.io/klog/v2" utiliptables "k8s.io/kubernetes/pkg/util/iptables" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) // LocalTrafficDetector in a interface to take action (jump) based on whether traffic originated locally @@ -66,10 +65,10 @@ type detectLocalByCIDR struct { // NewDetectLocalByCIDR implements the LocalTrafficDetector interface using a CIDR. This can be used when a single CIDR // range can be used to capture the notion of local traffic. func NewDetectLocalByCIDR(cidr string, ipt utiliptables.Interface) (LocalTrafficDetector, error) { - if utilnet.IsIPv6CIDRString(cidr) != ipt.IsIPv6() { + if netutils.IsIPv6CIDRString(cidr) != ipt.IsIPv6() { return nil, fmt.Errorf("CIDR %s has incorrect IP version: expect isIPv6=%t", cidr, ipt.IsIPv6()) } - _, _, err := net.ParseCIDR(cidr) + _, _, err := netutils.ParseCIDRSloppy(cidr) if err != nil { return nil, err } diff --git a/pkg/proxy/util/utils.go b/pkg/proxy/util/utils.go index c1286029a01..12ab03c6376 100644 --- a/pkg/proxy/util/utils.go +++ b/pkg/proxy/util/utils.go @@ -32,7 +32,7 @@ import ( "k8s.io/client-go/tools/events" helper "k8s.io/kubernetes/pkg/apis/core/v1/helper" utilsysctl "k8s.io/kubernetes/pkg/util/sysctl" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" "k8s.io/klog/v2" ) @@ -88,7 +88,7 @@ func IsZeroCIDR(cidr string) bool { // IsProxyableIP checks if a given IP address is permitted to be proxied func IsProxyableIP(ip string) error { - netIP := net.ParseIP(ip) + netIP := netutils.ParseIPSloppy(ip) if netIP == nil { return ErrAddressNotAllowed } @@ -146,7 +146,7 @@ func GetLocalAddrs() ([]net.IP, error) { } for _, addr := range addrs { - ip, _, err := net.ParseCIDR(addr.String()) + ip, _, err := netutils.ParseCIDRSloppy(addr.String()) if err != nil { return nil, err } @@ -159,7 +159,7 @@ func GetLocalAddrs() ([]net.IP, error) { // GetLocalAddrSet return a local IPSet. // If failed to get local addr, will assume no local ips. -func GetLocalAddrSet() utilnet.IPSet { +func GetLocalAddrSet() netutils.IPSet { localAddrs, err := GetLocalAddrs() if err != nil { klog.ErrorS(err, "Failed to get local addresses assuming no local IPs") @@ -167,7 +167,7 @@ func GetLocalAddrSet() utilnet.IPSet { klog.InfoS("No local addresses were found") } - localAddrSet := utilnet.IPSet{} + localAddrSet := netutils.IPSet{} localAddrSet.Insert(localAddrs...) return localAddrSet } @@ -220,7 +220,7 @@ func GetNodeAddresses(cidrs []string, nw NetworkInterfacer) (sets.String, error) continue } - _, ipNet, _ := net.ParseCIDR(cidr) + _, ipNet, _ := netutils.ParseCIDRSloppy(cidr) for _, addr := range addrs { var ip net.IP // nw.InterfaceAddrs may return net.IPAddr or net.IPNet on windows, and it will return net.IPNet on linux. @@ -234,10 +234,10 @@ func GetNodeAddresses(cidrs []string, nw NetworkInterfacer) (sets.String, error) } if ipNet.Contains(ip) { - if utilnet.IsIPv6(ip) && !uniqueAddressList.Has(IPv6ZeroCIDR) { + if netutils.IsIPv6(ip) && !uniqueAddressList.Has(IPv6ZeroCIDR) { uniqueAddressList.Insert(ip.String()) } - if !utilnet.IsIPv6(ip) && !uniqueAddressList.Has(IPv4ZeroCIDR) { + if !netutils.IsIPv6(ip) && !uniqueAddressList.Has(IPv4ZeroCIDR) { uniqueAddressList.Insert(ip.String()) } } @@ -295,23 +295,23 @@ func MapCIDRsByIPFamily(cidrStrings []string) map[v1.IPFamily][]string { } func getIPFamilyFromIP(ipStr string) (v1.IPFamily, error) { - netIP := net.ParseIP(ipStr) + netIP := netutils.ParseIPSloppy(ipStr) if netIP == nil { return "", ErrAddressNotAllowed } - if utilnet.IsIPv6(netIP) { + if netutils.IsIPv6(netIP) { return v1.IPv6Protocol, nil } return v1.IPv4Protocol, nil } func getIPFamilyFromCIDR(cidrStr string) (v1.IPFamily, error) { - _, netCIDR, err := net.ParseCIDR(cidrStr) + _, netCIDR, err := netutils.ParseCIDRSloppy(cidrStr) if err != nil { return "", ErrAddressNotAllowed } - if utilnet.IsIPv6CIDR(netCIDR) { + if netutils.IsIPv6CIDR(netCIDR) { return v1.IPv6Protocol, nil } return v1.IPv4Protocol, nil @@ -335,7 +335,7 @@ func AppendPortIfNeeded(addr string, port int32) string { } // Simply return for invalid case. This should be caught by validation instead. - ip := net.ParseIP(addr) + ip := netutils.ParseIPSloppy(addr) if ip == nil { return addr } @@ -441,7 +441,7 @@ func GetClusterIPByFamily(ipFamily v1.IPFamily, service *v1.Service) string { } IsIPv6Family := (ipFamily == v1.IPv6Protocol) - if IsIPv6Family == utilnet.IsIPv6String(service.Spec.ClusterIP) { + if IsIPv6Family == netutils.IsIPv6String(service.Spec.ClusterIP) { return service.Spec.ClusterIP } @@ -492,7 +492,7 @@ func WriteBytesLine(buf *bytes.Buffer, bytes []byte) { // RevertPorts is closing ports in replacementPortsMap but not in originalPortsMap. In other words, it only // closes the ports opened in this sync. -func RevertPorts(replacementPortsMap, originalPortsMap map[utilnet.LocalPort]utilnet.Closeable) { +func RevertPorts(replacementPortsMap, originalPortsMap map[netutils.LocalPort]netutils.Closeable) { for k, v := range replacementPortsMap { // Only close newly opened local ports - leave ones that were open before this update if originalPortsMap[k] == nil { diff --git a/pkg/proxy/util/utils_test.go b/pkg/proxy/util/utils_test.go index a0ee3761ee5..dff2dbb97be 100644 --- a/pkg/proxy/util/utils_test.go +++ b/pkg/proxy/util/utils_test.go @@ -30,7 +30,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" fake "k8s.io/kubernetes/pkg/proxy/util/testing" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) func TestValidateWorks(t *testing.T) { @@ -141,7 +141,7 @@ func (r *dummyResolver) LookupIPAddr(ctx context.Context, host string) ([]net.IP } resp := []net.IPAddr{} for _, ipString := range r.ips { - resp = append(resp, net.IPAddr{IP: net.ParseIP(ipString)}) + resp = append(resp, net.IPAddr{IP: netutils.ParseIPSloppy(ipString)}) } return resp, nil } @@ -187,13 +187,13 @@ func TestIsAllowedHost(t *testing.T) { for i := range testCases { var denyList []*net.IPNet for _, cidrStr := range testCases[i].denied { - _, ipNet, err := net.ParseCIDR(cidrStr) + _, ipNet, err := netutils.ParseCIDRSloppy(cidrStr) if err != nil { t.Fatalf("bad IP for test case: %v: %v", cidrStr, err) } denyList = append(denyList, ipNet) } - got := IsAllowedHost(net.ParseIP(testCases[i].ip), denyList) + got := IsAllowedHost(netutils.ParseIPSloppy(testCases[i].ip), denyList) if testCases[i].want != got { t.Errorf("case %d: expected %v, got %v", i, testCases[i].want, got) } @@ -281,7 +281,7 @@ func TestShouldSkipService(t *testing.T) { func TestNewFilteredDialContext(t *testing.T) { - _, cidr, _ := net.ParseCIDR("1.1.1.1/28") + _, cidr, _ := netutils.ParseCIDRSloppy("1.1.1.1/28") testCases := []struct { name string @@ -324,7 +324,7 @@ func TestNewFilteredDialContext(t *testing.T) { opts: &FilteredDialOptions{AllowLocalLoopback: false}, dial: "127.0.0.1:8080", expectResolve: "127.0.0.1", - resolveTo: []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, + resolveTo: []net.IPAddr{{IP: netutils.ParseIPSloppy("127.0.0.1")}}, expectWrappedDial: false, expectErr: "address not allowed", }, @@ -333,7 +333,7 @@ func TestNewFilteredDialContext(t *testing.T) { opts: &FilteredDialOptions{AllowLocalLoopback: false, DialHostCIDRDenylist: []*net.IPNet{cidr}}, dial: "foo.com:8080", expectResolve: "foo.com", - resolveTo: []net.IPAddr{{IP: net.ParseIP("1.1.1.1")}}, + resolveTo: []net.IPAddr{{IP: netutils.ParseIPSloppy("1.1.1.1")}}, expectWrappedDial: false, expectErr: "address not allowed", }, @@ -342,7 +342,7 @@ func TestNewFilteredDialContext(t *testing.T) { opts: &FilteredDialOptions{AllowLocalLoopback: false, DialHostCIDRDenylist: []*net.IPNet{cidr}}, dial: "foo.com:8080", expectResolve: "foo.com", - resolveTo: []net.IPAddr{{IP: net.ParseIP("2.2.2.2")}}, + resolveTo: []net.IPAddr{{IP: netutils.ParseIPSloppy("2.2.2.2")}}, expectWrappedDial: true, expectErr: "", }, @@ -417,11 +417,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, }, { itf: net.Interface{Index: 2, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("100.200.201.1"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("100.200.201.1"), Mask: net.CIDRMask(24, 32)}}, }, }, expected: sets.NewString("10.20.30.51"), @@ -432,11 +432,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, }, }, expected: sets.NewString("0.0.0.0/0"), @@ -447,11 +447,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("2001:db8::1"), Mask: net.CIDRMask(32, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("2001:db8::1"), Mask: net.CIDRMask(32, 128)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1"), Mask: net.CIDRMask(128, 128)}}, }, }, expected: sets.NewString("2001:db8::1", "::1"), @@ -462,11 +462,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("2001:db8::1"), Mask: net.CIDRMask(32, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("2001:db8::1"), Mask: net.CIDRMask(32, 128)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1"), Mask: net.CIDRMask(128, 128)}}, }, }, expected: sets.NewString("::/0"), @@ -477,11 +477,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, }, }, expected: sets.NewString("127.0.0.1"), @@ -492,7 +492,7 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.1.1"), Mask: net.CIDRMask(8, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.1.1"), Mask: net.CIDRMask(8, 32)}}, }, }, expected: sets.NewString("127.0.1.1"), @@ -503,11 +503,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("10.20.30.51"), Mask: net.CIDRMask(24, 32)}}, }, { itf: net.Interface{Index: 2, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("100.200.201.1"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("100.200.201.1"), Mask: net.CIDRMask(24, 32)}}, }, }, expected: sets.NewString("10.20.30.51", "100.200.201.1"), @@ -518,11 +518,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("192.168.1.2"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("192.168.1.2"), Mask: net.CIDRMask(24, 32)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, }, }, expected: nil, @@ -534,11 +534,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("192.168.1.2"), Mask: net.CIDRMask(24, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("192.168.1.2"), Mask: net.CIDRMask(24, 32)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("127.0.0.1"), Mask: net.CIDRMask(8, 32)}}, }, }, expected: sets.NewString("0.0.0.0/0", "::/0"), @@ -549,11 +549,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("2001:db8::1"), Mask: net.CIDRMask(32, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("2001:db8::1"), Mask: net.CIDRMask(32, 128)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1"), Mask: net.CIDRMask(128, 128)}}, }, }, expected: sets.NewString("0.0.0.0/0", "::/0"), @@ -564,7 +564,7 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("1.2.3.4"), Mask: net.CIDRMask(30, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("1.2.3.4"), Mask: net.CIDRMask(30, 32)}}, }, }, expected: sets.NewString("0.0.0.0/0"), @@ -575,11 +575,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("1.2.3.4"), Mask: net.CIDRMask(30, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("1.2.3.4"), Mask: net.CIDRMask(30, 32)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1"), Mask: net.CIDRMask(128, 128)}}, }, }, expected: sets.NewString("0.0.0.0/0", "::1"), @@ -590,11 +590,11 @@ func TestGetNodeAddresses(t *testing.T) { itfAddrsPairs: []InterfaceAddrsPair{ { itf: net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("1.2.3.4"), Mask: net.CIDRMask(30, 32)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("1.2.3.4"), Mask: net.CIDRMask(30, 32)}}, }, { itf: net.Interface{Index: 1, MTU: 0, Name: "lo", HardwareAddr: nil, Flags: 0}, - addrs: []net.Addr{&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)}}, + addrs: []net.Addr{&net.IPNet{IP: netutils.ParseIPSloppy("::1"), Mask: net.CIDRMask(128, 128)}}, }, }, expected: sets.NewString("::/0", "1.2.3.4"), @@ -1063,22 +1063,22 @@ func (c *fakeClosable) Close() error { func TestRevertPorts(t *testing.T) { testCases := []struct { - replacementPorts []utilnet.LocalPort - existingPorts []utilnet.LocalPort + replacementPorts []netutils.LocalPort + existingPorts []netutils.LocalPort expectToBeClose []bool }{ { - replacementPorts: []utilnet.LocalPort{ + replacementPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, }, - existingPorts: []utilnet.LocalPort{}, + existingPorts: []netutils.LocalPort{}, expectToBeClose: []bool{true, true, true}, }, { - replacementPorts: []utilnet.LocalPort{}, - existingPorts: []utilnet.LocalPort{ + replacementPorts: []netutils.LocalPort{}, + existingPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, @@ -1086,12 +1086,12 @@ func TestRevertPorts(t *testing.T) { expectToBeClose: []bool{}, }, { - replacementPorts: []utilnet.LocalPort{ + replacementPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, }, - existingPorts: []utilnet.LocalPort{ + existingPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, @@ -1099,24 +1099,24 @@ func TestRevertPorts(t *testing.T) { expectToBeClose: []bool{false, false, false}, }, { - replacementPorts: []utilnet.LocalPort{ + replacementPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, }, - existingPorts: []utilnet.LocalPort{ + existingPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5003}, }, expectToBeClose: []bool{false, true, false}, }, { - replacementPorts: []utilnet.LocalPort{ + replacementPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, }, - existingPorts: []utilnet.LocalPort{ + existingPorts: []netutils.LocalPort{ {Port: 5001}, {Port: 5002}, {Port: 5003}, @@ -1127,11 +1127,11 @@ func TestRevertPorts(t *testing.T) { } for i, tc := range testCases { - replacementPortsMap := make(map[utilnet.LocalPort]utilnet.Closeable) + replacementPortsMap := make(map[netutils.LocalPort]netutils.Closeable) for _, lp := range tc.replacementPorts { replacementPortsMap[lp] = &fakeClosable{} } - existingPortsMap := make(map[utilnet.LocalPort]utilnet.Closeable) + existingPortsMap := make(map[netutils.LocalPort]netutils.Closeable) for _, lp := range tc.existingPorts { existingPortsMap[lp] = &fakeClosable{} } diff --git a/pkg/proxy/winkernel/hnsV1.go b/pkg/proxy/winkernel/hnsV1.go index 6c9c8c68464..173ef3dd4fd 100644 --- a/pkg/proxy/winkernel/hnsV1.go +++ b/pkg/proxy/winkernel/hnsV1.go @@ -21,10 +21,11 @@ package winkernel import ( "encoding/json" "fmt" + "strings" + "github.com/Microsoft/hcsshim" "k8s.io/klog/v2" - "net" - "strings" + netutils "k8s.io/utils/net" ) type HostNetworkService interface { @@ -113,7 +114,7 @@ func (hns hnsV1) createEndpoint(ep *endpointsInfo, networkName string) (*endpoin } hnsEndpoint := &hcsshim.HNSEndpoint{ MacAddress: ep.macAddress, - IPAddress: net.ParseIP(ep.ip), + IPAddress: netutils.ParseIPSloppy(ep.ip), } var createdEndpoint *hcsshim.HNSEndpoint diff --git a/pkg/proxy/winkernel/proxier.go b/pkg/proxy/winkernel/proxier.go index e49fd514e88..7e380370663 100644 --- a/pkg/proxy/winkernel/proxier.go +++ b/pkg/proxy/winkernel/proxier.go @@ -52,7 +52,7 @@ import ( "k8s.io/kubernetes/pkg/proxy/metaproxier" "k8s.io/kubernetes/pkg/proxy/metrics" "k8s.io/kubernetes/pkg/util/async" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) // KernelCompatTester tests whether the required kernel capabilities are @@ -424,7 +424,7 @@ func (proxier *Proxier) newEndpointInfo(baseInfo *proxy.BaseEndpointInfo) proxy. ip: baseInfo.IP(), port: uint16(portNumber), isLocal: baseInfo.GetIsLocal(), - macAddress: conjureMac("02-11", net.ParseIP(baseInfo.IP())), + macAddress: conjureMac("02-11", netutils.ParseIPSloppy(baseInfo.IP())), refCount: new(uint16), hnsID: "", hns: proxier.hns, @@ -510,7 +510,7 @@ func (proxier *Proxier) newServiceInfo(port *v1.ServicePort, service *v1.Service } for _, ingress := range service.Status.LoadBalancer.Ingress { - if net.ParseIP(ingress.IP) != nil { + if netutils.ParseIPSloppy(ingress.IP) != nil { info.loadBalancerIngressIPs = append(info.loadBalancerIngressIPs, &loadBalancerIngressInfo{ip: ingress.IP}) } } @@ -520,11 +520,11 @@ func (proxier *Proxier) newServiceInfo(port *v1.ServicePort, service *v1.Service func (network hnsNetworkInfo) findRemoteSubnetProviderAddress(ip string) string { var providerAddress string for _, rs := range network.remoteSubnets { - _, ipNet, err := net.ParseCIDR(rs.destinationPrefix) + _, ipNet, err := netutils.ParseCIDRSloppy(rs.destinationPrefix) if err != nil { klog.ErrorS(err, "Failed to parse CIDR") } - if ipNet.Contains(net.ParseIP(ip)) { + if ipNet.Contains(netutils.ParseIPSloppy(ip)) { providerAddress = rs.providerAddress } if ip == rs.providerAddress { @@ -634,7 +634,7 @@ func NewProxier( if nodeIP == nil { klog.InfoS("invalid nodeIP, initializing kube-proxy with 127.0.0.1 as nodeIP") - nodeIP = net.ParseIP("127.0.0.1") + nodeIP = netutils.ParseIPSloppy("127.0.0.1") } if len(clusterCIDR) == 0 { @@ -705,7 +705,7 @@ func NewProxier( for _, inter := range interfaces { addresses, _ := inter.Addrs() for _, addr := range addresses { - addrIP, _, _ := net.ParseCIDR(addr.String()) + addrIP, _, _ := netutils.ParseCIDRSloppy(addr.String()) if addrIP.String() == nodeIP.String() { klog.V(2).InfoS("record Host MAC address", "addr", inter.HardwareAddr.String()) hostMac = inter.HardwareAddr.String() @@ -717,7 +717,7 @@ func NewProxier( } } - isIPv6 := utilnet.IsIPv6(nodeIP) + isIPv6 := netutils.IsIPv6(nodeIP) proxier := &Proxier{ endPointsRefCount: make(endPointsReferenceCountMap), serviceMap: make(proxy.ServiceMap), @@ -1179,7 +1179,7 @@ func (proxier *Proxier) syncProxyRules() { hnsEndpoint := &endpointsInfo{ ip: ep.ip, isLocal: false, - macAddress: conjureMac("02-11", net.ParseIP(ep.ip)), + macAddress: conjureMac("02-11", netutils.ParseIPSloppy(ep.ip)), providerAddress: providerAddress, } diff --git a/pkg/proxy/winkernel/proxier_test.go b/pkg/proxy/winkernel/proxier_test.go index 86b435b01ef..ac29614a6ee 100644 --- a/pkg/proxy/winkernel/proxier_test.go +++ b/pkg/proxy/winkernel/proxier_test.go @@ -33,6 +33,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/proxy" "k8s.io/kubernetes/pkg/proxy/healthcheck" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" ) @@ -73,9 +74,9 @@ func (hns fakeHNS) getEndpointByID(id string) (*endpointsInfo, error) { } func (hns fakeHNS) getEndpointByIpAddress(ip string, networkName string) (*endpointsInfo, error) { - _, ipNet, _ := net.ParseCIDR(destinationPrefix) + _, ipNet, _ := netutils.ParseCIDRSloppy(destinationPrefix) - if ipNet.Contains(net.ParseIP(ip)) { + if ipNet.Contains(netutils.ParseIPSloppy(ip)) { return &endpointsInfo{ ip: ip, isLocal: false, @@ -144,7 +145,7 @@ func NewFakeProxier(syncPeriod time.Duration, minSyncPeriod time.Duration, clust func TestCreateServiceVip(t *testing.T) { syncPeriod := 30 * time.Second - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), NETWORK_TYPE_OVERLAY) + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), NETWORK_TYPE_OVERLAY) if proxier == nil { t.Error() } @@ -199,7 +200,7 @@ func TestCreateServiceVip(t *testing.T) { func TestCreateRemoteEndpointOverlay(t *testing.T) { syncPeriod := 30 * time.Second - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), NETWORK_TYPE_OVERLAY) + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), NETWORK_TYPE_OVERLAY) if proxier == nil { t.Error() } @@ -264,7 +265,7 @@ func TestCreateRemoteEndpointOverlay(t *testing.T) { func TestCreateRemoteEndpointL2Bridge(t *testing.T) { syncPeriod := 30 * time.Second - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "L2Bridge") + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), "L2Bridge") if proxier == nil { t.Error() } @@ -328,7 +329,7 @@ func TestCreateRemoteEndpointL2Bridge(t *testing.T) { func TestSharedRemoteEndpointDelete(t *testing.T) { syncPeriod := 30 * time.Second tcpProtocol := v1.ProtocolTCP - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "L2Bridge") + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), "L2Bridge") if proxier == nil { t.Error() } @@ -470,7 +471,7 @@ func TestSharedRemoteEndpointDelete(t *testing.T) { } func TestSharedRemoteEndpointUpdate(t *testing.T) { syncPeriod := 30 * time.Second - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "L2Bridge") + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), "L2Bridge") if proxier == nil { t.Error() } @@ -645,7 +646,7 @@ func TestSharedRemoteEndpointUpdate(t *testing.T) { func TestCreateLoadBalancer(t *testing.T) { syncPeriod := 30 * time.Second tcpProtocol := v1.ProtocolTCP - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), NETWORK_TYPE_OVERLAY) + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), NETWORK_TYPE_OVERLAY) if proxier == nil { t.Error() } @@ -703,7 +704,7 @@ func TestCreateLoadBalancer(t *testing.T) { func TestCreateDsrLoadBalancer(t *testing.T) { syncPeriod := 30 * time.Second - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), NETWORK_TYPE_OVERLAY) + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), NETWORK_TYPE_OVERLAY) if proxier == nil { t.Error() } @@ -765,7 +766,7 @@ func TestCreateDsrLoadBalancer(t *testing.T) { func TestEndpointSlice(t *testing.T) { syncPeriod := 30 * time.Second - proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), NETWORK_TYPE_OVERLAY) + proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", netutils.ParseIPSloppy("10.0.0.1"), NETWORK_TYPE_OVERLAY) if proxier == nil { t.Error() } diff --git a/pkg/proxy/winuserspace/proxier.go b/pkg/proxy/winuserspace/proxier.go index 3a4dff95c1f..0713542f261 100644 --- a/pkg/proxy/winuserspace/proxier.go +++ b/pkg/proxy/winuserspace/proxier.go @@ -26,6 +26,7 @@ import ( "time" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -106,8 +107,8 @@ var ( ) // Used below. -var localhostIPv4 = net.ParseIP("127.0.0.1") -var localhostIPv6 = net.ParseIP("::1") +var localhostIPv4 = netutils.ParseIPSloppy("127.0.0.1") +var localhostIPv6 = netutils.ParseIPSloppy("::1") // NewProxier returns a new Proxier given a LoadBalancer and an address on // which to listen. It is assumed that there is only a single Proxier active @@ -208,7 +209,7 @@ func (proxier *Proxier) setServiceInfo(service ServicePortPortalName, info *serv func (proxier *Proxier) addServicePortPortal(servicePortPortalName ServicePortPortalName, protocol v1.Protocol, listenIP string, port int, timeout time.Duration) (*serviceInfo, error) { var serviceIP net.IP if listenIP != allAvailableInterfaces { - if serviceIP = net.ParseIP(listenIP); serviceIP == nil { + if serviceIP = netutils.ParseIPSloppy(listenIP); serviceIP == nil { return nil, fmt.Errorf("could not parse ip '%q'", listenIP) } // add the IP address. Node port binds to all interfaces. @@ -259,7 +260,7 @@ func (proxier *Proxier) closeServicePortPortal(servicePortPortalName ServicePort // close the PortalProxy by deleting the service IP address if info.portal.ip != allAvailableInterfaces { - serviceIP := net.ParseIP(info.portal.ip) + serviceIP := netutils.ParseIPSloppy(info.portal.ip) args := proxier.netshIPv4AddressDeleteArgs(serviceIP) if err := proxier.netsh.DeleteIPAddress(args); err != nil { return err diff --git a/pkg/proxy/winuserspace/proxier_test.go b/pkg/proxy/winuserspace/proxier_test.go index f24d6f2507d..e4eea5348f6 100644 --- a/pkg/proxy/winuserspace/proxier_test.go +++ b/pkg/proxy/winuserspace/proxier_test.go @@ -36,6 +36,7 @@ import ( "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/kubernetes/pkg/proxy" netshtest "k8s.io/kubernetes/pkg/util/netsh/testing" + netutils "k8s.io/utils/net" ) const ( @@ -251,7 +252,7 @@ func TestTCPProxy(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -278,7 +279,7 @@ func TestUDPProxy(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -305,7 +306,7 @@ func TestUDPProxyTimeout(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -344,7 +345,7 @@ func TestMultiPortProxy(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -374,7 +375,7 @@ func TestMultiPortOnServiceAdd(t *testing.T) { serviceX := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: "testnamespace", Name: "echo"}, Port: "x"} listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -440,7 +441,7 @@ func TestTCPProxyStop(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -484,7 +485,7 @@ func TestUDPProxyStop(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -522,7 +523,7 @@ func TestTCPProxyUpdateDelete(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -567,7 +568,7 @@ func TestUDPProxyUpdateDelete(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -612,7 +613,7 @@ func TestTCPProxyUpdateDeleteUpdate(t *testing.T) { lb.OnEndpointsAdd(endpoint) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -674,7 +675,7 @@ func TestUDPProxyUpdateDeleteUpdate(t *testing.T) { lb.OnEndpointsAdd(endpoint) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -735,7 +736,7 @@ func TestTCPProxyUpdatePort(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -783,7 +784,7 @@ func TestUDPProxyUpdatePort(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -828,7 +829,7 @@ func TestProxyUpdatePublicIPs(t *testing.T) { }) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } @@ -881,7 +882,7 @@ func TestProxyUpdatePortal(t *testing.T) { lb.OnEndpointsAdd(endpoint) listenIP := "0.0.0.0" - p, err := createProxier(lb, net.ParseIP(listenIP), netshtest.NewFake(), net.ParseIP("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) + p, err := createProxier(lb, netutils.ParseIPSloppy(listenIP), netshtest.NewFake(), netutils.ParseIPSloppy("127.0.0.1"), time.Minute, udpIdleTimeoutForTest) if err != nil { t.Fatal(err) } diff --git a/pkg/registry/core/service/ipallocator/allocator.go b/pkg/registry/core/service/ipallocator/allocator.go index a5adae5a257..df8a2841ac0 100644 --- a/pkg/registry/core/service/ipallocator/allocator.go +++ b/pkg/registry/core/service/ipallocator/allocator.go @@ -24,7 +24,7 @@ import ( api "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/registry/core/service/allocator" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) // Interface manages the allocation of IP addresses out of a range. Interface @@ -85,12 +85,12 @@ type Range struct { func New(cidr *net.IPNet, allocatorFactory allocator.AllocatorFactory) (*Range, error) { registerMetrics() - max := utilnet.RangeSize(cidr) - base := utilnet.BigForIP(cidr.IP) + max := netutils.RangeSize(cidr) + base := netutils.BigForIP(cidr.IP) rangeSpec := cidr.String() var family api.IPFamily - if utilnet.IsIPv6CIDR(cidr) { + if netutils.IsIPv6CIDR(cidr) { family = api.IPv6Protocol // Limit the max size, since the allocator keeps a bitmap of that size. if max > 65536 { @@ -126,7 +126,7 @@ func NewInMemory(cidr *net.IPNet) (*Range, error) { // NewFromSnapshot allocates a Range and initializes it from a snapshot. func NewFromSnapshot(snap *api.RangeAllocation) (*Range, error) { - _, ipnet, err := net.ParseCIDR(snap.Range) + _, ipnet, err := netutils.ParseCIDRSloppy(snap.Range) if err != nil { return nil, err } @@ -219,7 +219,7 @@ func (r *Range) AllocateNext() (net.IP, error) { clusterIPAllocated.WithLabelValues(label.String()).Set(float64(r.Used())) clusterIPAvailable.WithLabelValues(label.String()).Set(float64(r.Free())) - return utilnet.AddIPOffset(r.base, offset), nil + return netutils.AddIPOffset(r.base, offset), nil } // Release releases the IP back to the pool. Releasing an @@ -244,7 +244,7 @@ func (r *Range) Release(ip net.IP) error { // ForEach calls the provided function for each allocated IP. func (r *Range) ForEach(fn func(net.IP)) { r.alloc.ForEach(func(offset int) { - ip, _ := utilnet.GetIndexedIP(r.net, offset+1) // +1 because Range doesn't store IP 0 + ip, _ := netutils.GetIndexedIP(r.net, offset+1) // +1 because Range doesn't store IP 0 fn(ip) }) } @@ -310,5 +310,5 @@ func (r *Range) contains(ip net.IP) (bool, int) { // calculateIPOffset calculates the integer offset of ip from base such that // base + offset = ip. It requires ip >= base. func calculateIPOffset(base *big.Int, ip net.IP) int { - return int(big.NewInt(0).Sub(utilnet.BigForIP(ip), base).Int64()) + return int(big.NewInt(0).Sub(netutils.BigForIP(ip), base).Int64()) } diff --git a/pkg/registry/core/service/ipallocator/allocator_test.go b/pkg/registry/core/service/ipallocator/allocator_test.go index 2a4e3b40da4..8580303adb4 100644 --- a/pkg/registry/core/service/ipallocator/allocator_test.go +++ b/pkg/registry/core/service/ipallocator/allocator_test.go @@ -23,6 +23,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/component-base/metrics/testutil" api "k8s.io/kubernetes/pkg/apis/core" + netutils "k8s.io/utils/net" ) func TestAllocate(t *testing.T) { @@ -65,7 +66,7 @@ func TestAllocate(t *testing.T) { }, } for _, tc := range testCases { - _, cidr, err := net.ParseCIDR(tc.cidr) + _, cidr, err := netutils.ParseCIDRSloppy(tc.cidr) if err != nil { t.Fatal(err) } @@ -110,7 +111,7 @@ func TestAllocate(t *testing.T) { t.Fatal(err) } - released := net.ParseIP(tc.released) + released := netutils.ParseIPSloppy(tc.released) if err := r.Release(released); err != nil { t.Fatal(err) } @@ -132,12 +133,12 @@ func TestAllocate(t *testing.T) { t.Fatal(err) } for _, outOfRange := range tc.outOfRange { - err = r.Allocate(net.ParseIP(outOfRange)) + err = r.Allocate(netutils.ParseIPSloppy(outOfRange)) if _, ok := err.(*ErrNotInRange); !ok { t.Fatal(err) } } - if err := r.Allocate(net.ParseIP(tc.alreadyAllocated)); err != ErrAllocated { + if err := r.Allocate(netutils.ParseIPSloppy(tc.alreadyAllocated)); err != ErrAllocated { t.Fatal(err) } if f := r.Free(); f != 1 { @@ -159,7 +160,7 @@ func TestAllocate(t *testing.T) { } func TestAllocateTiny(t *testing.T) { - _, cidr, err := net.ParseCIDR("192.168.1.0/32") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.1.0/32") if err != nil { t.Fatal(err) } @@ -176,7 +177,7 @@ func TestAllocateTiny(t *testing.T) { } func TestAllocateSmall(t *testing.T) { - _, cidr, err := net.ParseCIDR("192.168.1.240/30") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.1.240/30") if err != nil { t.Fatal(err) } @@ -199,10 +200,10 @@ func TestAllocateSmall(t *testing.T) { found.Insert(ip.String()) } for s := range found { - if !r.Has(net.ParseIP(s)) { + if !r.Has(netutils.ParseIPSloppy(s)) { t.Fatalf("missing: %s", s) } - if err := r.Allocate(net.ParseIP(s)); err != ErrAllocated { + if err := r.Allocate(netutils.ParseIPSloppy(s)); err != ErrAllocated { t.Fatal(err) } } @@ -220,7 +221,7 @@ func TestAllocateSmall(t *testing.T) { } func TestForEach(t *testing.T) { - _, cidr, err := net.ParseCIDR("192.168.1.0/24") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.1.0/24") if err != nil { t.Fatal(err) } @@ -238,7 +239,7 @@ func TestForEach(t *testing.T) { t.Fatal(err) } for ips := range tc { - ip := net.ParseIP(ips) + ip := netutils.ParseIPSloppy(ips) if err := r.Allocate(ip); err != nil { t.Errorf("[%d] error allocating IP %v: %v", i, ip, err) } @@ -260,7 +261,7 @@ func TestForEach(t *testing.T) { } func TestSnapshot(t *testing.T) { - _, cidr, err := net.ParseCIDR("192.168.1.0/24") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.1.0/24") if err != nil { t.Fatal(err) } @@ -283,7 +284,7 @@ func TestSnapshot(t *testing.T) { t.Fatal(err) } - _, network, err := net.ParseCIDR(dst.Range) + _, network, err := netutils.ParseCIDRSloppy(dst.Range) if err != nil { t.Fatal(err) } @@ -292,7 +293,7 @@ func TestSnapshot(t *testing.T) { t.Fatalf("mismatched networks: %s : %s", network, cidr) } - _, otherCidr, err := net.ParseCIDR("192.168.2.0/24") + _, otherCidr, err := netutils.ParseCIDRSloppy("192.168.2.0/24") if err != nil { t.Fatal(err) } @@ -322,7 +323,7 @@ func TestSnapshot(t *testing.T) { } func TestNewFromSnapshot(t *testing.T) { - _, cidr, err := net.ParseCIDR("192.168.0.0/24") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.0.0/24") if err != nil { t.Fatal(err) } @@ -366,7 +367,7 @@ func TestNewFromSnapshot(t *testing.T) { func TestClusterIPMetrics(t *testing.T) { // create IPv4 allocator cidrIPv4 := "10.0.0.0/24" - _, clusterCIDRv4, _ := net.ParseCIDR(cidrIPv4) + _, clusterCIDRv4, _ := netutils.ParseCIDRSloppy(cidrIPv4) a, err := NewInMemory(clusterCIDRv4) if err != nil { t.Fatalf("unexpected error creating CidrSet: %v", err) @@ -374,7 +375,7 @@ func TestClusterIPMetrics(t *testing.T) { clearMetrics(map[string]string{"cidr": cidrIPv4}) // create IPv6 allocator cidrIPv6 := "2001:db8::/112" - _, clusterCIDRv6, _ := net.ParseCIDR(cidrIPv6) + _, clusterCIDRv6, _ := netutils.ParseCIDRSloppy(cidrIPv6) b, err := NewInMemory(clusterCIDRv6) if err != nil { t.Fatalf("unexpected error creating CidrSet: %v", err) @@ -420,10 +421,10 @@ func TestClusterIPMetrics(t *testing.T) { // try to allocate the same IP addresses for s := range found { - if !a.Has(net.ParseIP(s)) { + if !a.Has(netutils.ParseIPSloppy(s)) { t.Fatalf("missing: %s", s) } - if err := a.Allocate(net.ParseIP(s)); err != ErrAllocated { + if err := a.Allocate(netutils.ParseIPSloppy(s)); err != ErrAllocated { t.Fatal(err) } } @@ -437,10 +438,10 @@ func TestClusterIPMetrics(t *testing.T) { // release the addresses allocated for s := range found { - if !a.Has(net.ParseIP(s)) { + if !a.Has(netutils.ParseIPSloppy(s)) { t.Fatalf("missing: %s", s) } - if err := a.Release(net.ParseIP(s)); err != nil { + if err := a.Release(netutils.ParseIPSloppy(s)); err != nil { t.Fatal(err) } } diff --git a/pkg/registry/core/service/ipallocator/controller/repair.go b/pkg/registry/core/service/ipallocator/controller/repair.go index b760f181afc..37b0a78f777 100644 --- a/pkg/registry/core/service/ipallocator/controller/repair.go +++ b/pkg/registry/core/service/ipallocator/controller/repair.go @@ -35,7 +35,7 @@ import ( "k8s.io/kubernetes/pkg/apis/core/v1/helper" "k8s.io/kubernetes/pkg/registry/core/rangeallocation" "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" - netutil "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) // Repair is a controller loop that periodically examines all service ClusterIP allocations @@ -82,7 +82,7 @@ func NewRepair(interval time.Duration, serviceClient corev1client.ServicesGetter primary := v1.IPv4Protocol secondary := v1.IPv6Protocol - if netutil.IsIPv6(network.IP) { + if netutils.IsIPv6(network.IP) { primary = v1.IPv6Protocol } @@ -196,7 +196,7 @@ func (c *Repair) runOnce() error { } getFamilyByIP := func(ip net.IP) v1.IPFamily { - if netutil.IsIPv6(ip) { + if netutils.IsIPv6(ip) { return v1.IPv6Protocol } return v1.IPv4Protocol @@ -210,7 +210,7 @@ func (c *Repair) runOnce() error { } for _, ip := range svc.Spec.ClusterIPs { - ip := net.ParseIP(ip) + ip := netutils.ParseIPSloppy(ip) if ip == nil { // cluster IP is corrupt c.recorder.Eventf(&svc, v1.EventTypeWarning, "ClusterIPNotValid", "Cluster IP %s is not a valid IP; please recreate service", ip) diff --git a/pkg/registry/core/service/ipallocator/controller/repair_test.go b/pkg/registry/core/service/ipallocator/controller/repair_test.go index 14bbe3aa192..3b3cdeabd7d 100644 --- a/pkg/registry/core/service/ipallocator/controller/repair_test.go +++ b/pkg/registry/core/service/ipallocator/controller/repair_test.go @@ -28,6 +28,7 @@ import ( "k8s.io/client-go/kubernetes/fake" api "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" + netutils "k8s.io/utils/net" utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" @@ -60,7 +61,7 @@ func TestRepair(t *testing.T) { ipregistry := &mockRangeRegistry{ item: &api.RangeAllocation{Range: "192.168.1.0/24"}, } - _, cidr, _ := net.ParseCIDR(ipregistry.item.Range) + _, cidr, _ := netutils.ParseCIDRSloppy(ipregistry.item.Range) r := NewRepair(0, fakeClient.CoreV1(), fakeClient.CoreV1(), cidr, ipregistry, nil, nil) if err := r.RunOnce(); err != nil { @@ -81,12 +82,12 @@ func TestRepair(t *testing.T) { } func TestRepairLeak(t *testing.T) { - _, cidr, _ := net.ParseCIDR("192.168.1.0/24") + _, cidr, _ := netutils.ParseCIDRSloppy("192.168.1.0/24") previous, err := ipallocator.NewInMemory(cidr) if err != nil { t.Fatal(err) } - previous.Allocate(net.ParseIP("192.168.1.10")) + previous.Allocate(netutils.ParseIPSloppy("192.168.1.10")) var dst api.RangeAllocation err = previous.Snapshot(&dst) @@ -115,7 +116,7 @@ func TestRepairLeak(t *testing.T) { if err != nil { t.Fatal(err) } - if !after.Has(net.ParseIP("192.168.1.10")) { + if !after.Has(netutils.ParseIPSloppy("192.168.1.10")) { t.Errorf("expected ipallocator to still have leaked IP") } } @@ -127,13 +128,13 @@ func TestRepairLeak(t *testing.T) { if err != nil { t.Fatal(err) } - if after.Has(net.ParseIP("192.168.1.10")) { + if after.Has(netutils.ParseIPSloppy("192.168.1.10")) { t.Errorf("expected ipallocator to not have leaked IP") } } func TestRepairWithExisting(t *testing.T) { - _, cidr, _ := net.ParseCIDR("192.168.1.0/24") + _, cidr, _ := netutils.ParseCIDRSloppy("192.168.1.0/24") previous, err := ipallocator.NewInMemory(cidr) if err != nil { t.Fatal(err) @@ -211,7 +212,7 @@ func TestRepairWithExisting(t *testing.T) { if err != nil { t.Fatal(err) } - if !after.Has(net.ParseIP("192.168.1.1")) || !after.Has(net.ParseIP("192.168.1.100")) { + if !after.Has(netutils.ParseIPSloppy("192.168.1.1")) || !after.Has(netutils.ParseIPSloppy("192.168.1.100")) { t.Errorf("unexpected ipallocator state: %#v", after) } if free := after.Free(); free != 252 { @@ -220,7 +221,7 @@ func TestRepairWithExisting(t *testing.T) { } func makeRangeRegistry(t *testing.T, cidrRange string) *mockRangeRegistry { - _, cidr, _ := net.ParseCIDR(cidrRange) + _, cidr, _ := netutils.ParseCIDRSloppy(cidrRange) previous, err := ipallocator.NewInMemory(cidr) if err != nil { t.Fatal(err) @@ -247,7 +248,7 @@ func makeFakeClientSet() *fake.Clientset { return fake.NewSimpleClientset() } func makeIPNet(cidr string) *net.IPNet { - _, net, _ := net.ParseCIDR(cidr) + _, net, _ := netutils.ParseCIDRSloppy(cidr) return net } func TestShouldWorkOnSecondary(t *testing.T) { @@ -337,8 +338,8 @@ func TestRepairDualStack(t *testing.T) { item: &api.RangeAllocation{Range: "2000::/108"}, } - _, cidr, _ := net.ParseCIDR(ipregistry.item.Range) - _, secondaryCIDR, _ := net.ParseCIDR(secondaryIPRegistry.item.Range) + _, cidr, _ := netutils.ParseCIDRSloppy(ipregistry.item.Range) + _, secondaryCIDR, _ := netutils.ParseCIDRSloppy(secondaryIPRegistry.item.Range) r := NewRepair(0, fakeClient.CoreV1(), fakeClient.CoreV1(), cidr, ipregistry, secondaryCIDR, secondaryIPRegistry) if err := r.RunOnce(); err != nil { @@ -369,20 +370,20 @@ func TestRepairDualStack(t *testing.T) { func TestRepairLeakDualStack(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() - _, cidr, _ := net.ParseCIDR("192.168.1.0/24") + _, cidr, _ := netutils.ParseCIDRSloppy("192.168.1.0/24") previous, err := ipallocator.NewInMemory(cidr) if err != nil { t.Fatal(err) } - previous.Allocate(net.ParseIP("192.168.1.10")) + previous.Allocate(netutils.ParseIPSloppy("192.168.1.10")) - _, secondaryCIDR, _ := net.ParseCIDR("2000::/108") + _, secondaryCIDR, _ := netutils.ParseCIDRSloppy("2000::/108") secondaryPrevious, err := ipallocator.NewInMemory(secondaryCIDR) if err != nil { t.Fatal(err) } - secondaryPrevious.Allocate(net.ParseIP("2000::1")) + secondaryPrevious.Allocate(netutils.ParseIPSloppy("2000::1")) var dst api.RangeAllocation err = previous.Snapshot(&dst) @@ -427,14 +428,14 @@ func TestRepairLeakDualStack(t *testing.T) { if err != nil { t.Fatal(err) } - if !after.Has(net.ParseIP("192.168.1.10")) { + if !after.Has(netutils.ParseIPSloppy("192.168.1.10")) { t.Errorf("expected ipallocator to still have leaked IP") } secondaryAfter, err := ipallocator.NewFromSnapshot(secondaryIPRegistry.updated) if err != nil { t.Fatal(err) } - if !secondaryAfter.Has(net.ParseIP("2000::1")) { + if !secondaryAfter.Has(netutils.ParseIPSloppy("2000::1")) { t.Errorf("expected ipallocator to still have leaked IP") } } @@ -447,14 +448,14 @@ func TestRepairLeakDualStack(t *testing.T) { if err != nil { t.Fatal(err) } - if after.Has(net.ParseIP("192.168.1.10")) { + if after.Has(netutils.ParseIPSloppy("192.168.1.10")) { t.Errorf("expected ipallocator to not have leaked IP") } secondaryAfter, err := ipallocator.NewFromSnapshot(secondaryIPRegistry.updated) if err != nil { t.Fatal(err) } - if secondaryAfter.Has(net.ParseIP("2000::1")) { + if secondaryAfter.Has(netutils.ParseIPSloppy("2000::1")) { t.Errorf("expected ipallocator to not have leaked IP") } } @@ -466,13 +467,13 @@ func TestRepairWithExistingDualStack(t *testing.T) { // this will work every where except alloc & validation defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() - _, cidr, _ := net.ParseCIDR("192.168.1.0/24") + _, cidr, _ := netutils.ParseCIDRSloppy("192.168.1.0/24") previous, err := ipallocator.NewInMemory(cidr) if err != nil { t.Fatal(err) } - _, secondaryCIDR, _ := net.ParseCIDR("2000::/108") + _, secondaryCIDR, _ := netutils.ParseCIDRSloppy("2000::/108") secondaryPrevious, err := ipallocator.NewInMemory(secondaryCIDR) if err != nil { t.Fatal(err) @@ -613,7 +614,7 @@ func TestRepairWithExistingDualStack(t *testing.T) { t.Fatal(err) } - if !after.Has(net.ParseIP("192.168.1.1")) || !after.Has(net.ParseIP("192.168.1.100")) { + if !after.Has(netutils.ParseIPSloppy("192.168.1.1")) || !after.Has(netutils.ParseIPSloppy("192.168.1.100")) { t.Errorf("unexpected ipallocator state: %#v", after) } if free := after.Free(); free != 251 { @@ -624,7 +625,7 @@ func TestRepairWithExistingDualStack(t *testing.T) { if err != nil { t.Fatal(err) } - if !secondaryAfter.Has(net.ParseIP("2000::1")) || !secondaryAfter.Has(net.ParseIP("2000::2")) { + if !secondaryAfter.Has(netutils.ParseIPSloppy("2000::1")) || !secondaryAfter.Has(netutils.ParseIPSloppy("2000::2")) { t.Errorf("unexpected ipallocator state: %#v", secondaryAfter) } if free := secondaryAfter.Free(); free != 65533 { diff --git a/pkg/registry/core/service/ipallocator/storage/storage_test.go b/pkg/registry/core/service/ipallocator/storage/storage_test.go index 7aba8873119..7771e77135d 100644 --- a/pkg/registry/core/service/ipallocator/storage/storage_test.go +++ b/pkg/registry/core/service/ipallocator/storage/storage_test.go @@ -18,7 +18,6 @@ package storage import ( "context" - "net" "strings" "testing" @@ -32,11 +31,12 @@ import ( allocatorstore "k8s.io/kubernetes/pkg/registry/core/service/allocator/storage" "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" "k8s.io/kubernetes/pkg/registry/registrytest" + netutils "k8s.io/utils/net" ) func newStorage(t *testing.T) (*etcd3testing.EtcdTestServer, ipallocator.Interface, allocator.Interface, storage.Interface, factory.DestroyFunc) { etcdStorage, server := registrytest.NewEtcdStorage(t, "") - _, cidr, err := net.ParseCIDR("192.168.1.0/24") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.1.0/24") if err != nil { t.Fatal(err) } @@ -66,7 +66,7 @@ func newStorage(t *testing.T) (*etcd3testing.EtcdTestServer, ipallocator.Interfa } func validNewRangeAllocation() *api.RangeAllocation { - _, cidr, _ := net.ParseCIDR("192.168.1.0/24") + _, cidr, _ := netutils.ParseCIDRSloppy("192.168.1.0/24") return &api.RangeAllocation{ Range: cidr.String(), } @@ -79,7 +79,7 @@ func key() string { func TestEmpty(t *testing.T) { _, storage, _, _, destroyFunc := newStorage(t) defer destroyFunc() - if err := storage.Allocate(net.ParseIP("192.168.1.2")); !strings.Contains(err.Error(), "cannot allocate resources of type serviceipallocations at this time") { + if err := storage.Allocate(netutils.ParseIPSloppy("192.168.1.2")); !strings.Contains(err.Error(), "cannot allocate resources of type serviceipallocations at this time") { t.Fatal(err) } } @@ -87,7 +87,7 @@ func TestEmpty(t *testing.T) { func TestErrors(t *testing.T) { _, storage, _, _, destroyFunc := newStorage(t) defer destroyFunc() - err := storage.Allocate(net.ParseIP("192.168.0.0")) + err := storage.Allocate(netutils.ParseIPSloppy("192.168.0.0")) if _, ok := err.(*ipallocator.ErrNotInRange); !ok { t.Fatal(err) } @@ -100,7 +100,7 @@ func TestStore(t *testing.T) { t.Fatalf("unexpected error: %v", err) } - if err := storage.Allocate(net.ParseIP("192.168.1.2")); err != nil { + if err := storage.Allocate(netutils.ParseIPSloppy("192.168.1.2")); err != nil { t.Fatal(err) } ok, err := backing.Allocate(1) @@ -110,7 +110,7 @@ func TestStore(t *testing.T) { if ok { t.Fatal("Expected allocation to fail") } - if err := storage.Allocate(net.ParseIP("192.168.1.2")); err != ipallocator.ErrAllocated { + if err := storage.Allocate(netutils.ParseIPSloppy("192.168.1.2")); err != ipallocator.ErrAllocated { t.Fatal(err) } } diff --git a/pkg/registry/core/service/storage/rest.go b/pkg/registry/core/service/storage/rest.go index be029edc557..313a41417eb 100644 --- a/pkg/registry/core/service/storage/rest.go +++ b/pkg/registry/core/service/storage/rest.go @@ -45,7 +45,7 @@ import ( registry "k8s.io/kubernetes/pkg/registry/core/service" "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" "k8s.io/kubernetes/pkg/registry/core/service/portallocator" - netutil "k8s.io/utils/net" + netutils "k8s.io/utils/net" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) @@ -108,7 +108,7 @@ func NewREST( // detect this cluster default Service IPFamily (ipfamily of --service-cluster-ip-range[0]) serviceIPFamily := api.IPv4Protocol cidr := serviceIPs.CIDR() - if netutil.IsIPv6CIDR(&cidr) { + if netutils.IsIPv6CIDR(&cidr) { serviceIPFamily = api.IPv6Protocol } @@ -612,7 +612,7 @@ func (rs *REST) allocClusterIPs(service *api.Service, toAlloc map[api.IPFamily]s } allocated[family] = allocatedIP.String() } else { - parsedIP := net.ParseIP(ip) + parsedIP := netutils.ParseIPSloppy(ip) if err := allocator.Allocate(parsedIP); err != nil { el := field.ErrorList{field.Invalid(field.NewPath("spec", "clusterIPs"), service.Spec.ClusterIPs, fmt.Sprintf("failed to allocate IP %v: %v", ip, err))} return allocated, errors.NewInvalid(api.Kind("Service"), service.Name, el) @@ -638,7 +638,7 @@ func (rs *REST) releaseClusterIPs(toRelease map[api.IPFamily]string) (map[api.IP continue } - parsedIP := net.ParseIP(ip) + parsedIP := netutils.ParseIPSloppy(ip) if err := allocator.Release(parsedIP); err != nil { return released, err } @@ -825,7 +825,7 @@ func (rs *REST) releaseServiceClusterIP(service *api.Service) (released map[api. // we need to do that to handle cases where allocator is no longer configured on // cluster - if netutil.IsIPv6String(service.Spec.ClusterIP) { + if netutils.IsIPv6String(service.Spec.ClusterIP) { toRelease[api.IPv6Protocol] = service.Spec.ClusterIP } else { toRelease[api.IPv4Protocol] = service.Spec.ClusterIP @@ -852,7 +852,7 @@ func (rs *REST) releaseServiceClusterIPs(service *api.Service) (released map[api toRelease := make(map[api.IPFamily]string) for _, ip := range service.Spec.ClusterIPs { - if netutil.IsIPv6String(ip) { + if netutils.IsIPv6String(ip) { toRelease[api.IPv6Protocol] = ip } else { toRelease[api.IPv4Protocol] = ip @@ -974,7 +974,7 @@ func (rs *REST) tryDefaultValidateServiceClusterIPFields(oldService, service *ap // we have previously validated for ip correctness and if family exist it will match ip family // so the following is safe to do - isIPv6 := netutil.IsIPv6String(ip) + isIPv6 := netutils.IsIPv6String(ip) // Family is not specified yet. if i >= len(service.Spec.IPFamilies) { diff --git a/pkg/registry/core/service/storage/rest_test.go b/pkg/registry/core/service/storage/rest_test.go index 8112d0cfa04..d317444fcbc 100644 --- a/pkg/registry/core/service/storage/rest_test.go +++ b/pkg/registry/core/service/storage/rest_test.go @@ -49,7 +49,7 @@ import ( "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" "k8s.io/kubernetes/pkg/registry/core/service/portallocator" "k8s.io/kubernetes/pkg/registry/registrytest" - netutil "k8s.io/utils/net" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) @@ -245,14 +245,14 @@ func NewTestRESTWithPods(t *testing.T, endpoints []*api.Endpoints, pods []api.Po } func makeIPNet(t *testing.T) *net.IPNet { - _, net, err := net.ParseCIDR("1.2.3.0/24") + _, net, err := netutils.ParseCIDRSloppy("1.2.3.0/24") if err != nil { t.Error(err) } return net } func makeIPNet6(t *testing.T) *net.IPNet { - _, net, err := net.ParseCIDR("2000::/108") + _, net, err := netutils.ParseCIDRSloppy("2000::/108") if err != nil { t.Error(err) } @@ -261,7 +261,7 @@ func makeIPNet6(t *testing.T) *net.IPNet { func ipIsAllocated(t *testing.T, alloc ipallocator.Interface, ipstr string) bool { t.Helper() - ip := net.ParseIP(ipstr) + ip := netutils.ParseIPSloppy(ipstr) if ip == nil { t.Errorf("error parsing IP %q", ipstr) return false @@ -334,7 +334,7 @@ func TestServiceRegistryCreate(t *testing.T) { allocator := storage.serviceIPAllocatorsByFamily[family] c := allocator.CIDR() cidr := &c - if !cidr.Contains(net.ParseIP(createdService.Spec.ClusterIPs[i])) { + if !cidr.Contains(netutils.ParseIPSloppy(createdService.Spec.ClusterIPs[i])) { t.Errorf("Unexpected ClusterIP: %s", createdService.Spec.ClusterIPs[i]) } } @@ -1309,7 +1309,7 @@ func TestServiceRegistryIPAllocation(t *testing.T) { if createdSvc1.Name != "foo" { t.Errorf("Expected foo, but got %v", createdSvc1.Name) } - if !makeIPNet(t).Contains(net.ParseIP(createdSvc1.Spec.ClusterIPs[0])) { + if !makeIPNet(t).Contains(netutils.ParseIPSloppy(createdSvc1.Spec.ClusterIPs[0])) { t.Errorf("Unexpected ClusterIP: %s", createdSvc1.Spec.ClusterIPs[0]) } @@ -1323,7 +1323,7 @@ func TestServiceRegistryIPAllocation(t *testing.T) { if createdSvc2.Name != "bar" { t.Errorf("Expected bar, but got %v", createdSvc2.Name) } - if !makeIPNet(t).Contains(net.ParseIP(createdSvc2.Spec.ClusterIPs[0])) { + if !makeIPNet(t).Contains(netutils.ParseIPSloppy(createdSvc2.Spec.ClusterIPs[0])) { t.Errorf("Unexpected ClusterIP: %s", createdSvc2.Spec.ClusterIPs[0]) } @@ -1362,7 +1362,7 @@ func TestServiceRegistryIPReallocation(t *testing.T) { if createdSvc1.Name != "foo" { t.Errorf("Expected foo, but got %v", createdSvc1.Name) } - if !makeIPNet(t).Contains(net.ParseIP(createdSvc1.Spec.ClusterIPs[0])) { + if !makeIPNet(t).Contains(netutils.ParseIPSloppy(createdSvc1.Spec.ClusterIPs[0])) { t.Errorf("Unexpected ClusterIP: %s", createdSvc1.Spec.ClusterIPs[0]) } @@ -1381,7 +1381,7 @@ func TestServiceRegistryIPReallocation(t *testing.T) { if createdSvc2.Name != "bar" { t.Errorf("Expected bar, but got %v", createdSvc2.Name) } - if !makeIPNet(t).Contains(net.ParseIP(createdSvc2.Spec.ClusterIPs[0])) { + if !makeIPNet(t).Contains(netutils.ParseIPSloppy(createdSvc2.Spec.ClusterIPs[0])) { t.Errorf("Unexpected ClusterIP: %s", createdSvc2.Spec.ClusterIPs[0]) } } @@ -1400,7 +1400,7 @@ func TestServiceRegistryIPUpdate(t *testing.T) { if createdService.Spec.Ports[0].Port != svc.Spec.Ports[0].Port { t.Errorf("Expected port %d, but got %v", svc.Spec.Ports[0].Port, createdService.Spec.Ports[0].Port) } - if !makeIPNet(t).Contains(net.ParseIP(createdService.Spec.ClusterIPs[0])) { + if !makeIPNet(t).Contains(netutils.ParseIPSloppy(createdService.Spec.ClusterIPs[0])) { t.Errorf("Unexpected ClusterIP: %s", createdService.Spec.ClusterIPs[0]) } @@ -1451,7 +1451,7 @@ func TestServiceRegistryIPLoadBalancer(t *testing.T) { if createdService.Spec.Ports[0].Port != svc.Spec.Ports[0].Port { t.Errorf("Expected port %d, but got %v", svc.Spec.Ports[0].Port, createdService.Spec.Ports[0].Port) } - if !makeIPNet(t).Contains(net.ParseIP(createdService.Spec.ClusterIPs[0])) { + if !makeIPNet(t).Contains(netutils.ParseIPSloppy(createdService.Spec.ClusterIPs[0])) { t.Errorf("Unexpected ClusterIP: %s", createdService.Spec.ClusterIPs[0]) } @@ -1797,7 +1797,7 @@ func TestInitClusterIP(t *testing.T) { if !ok { t.Fatalf("test is incorrect, allocator does not exist on rest") } - if err := allocator.Allocate(net.ParseIP(ip)); err != nil { + if err := allocator.Allocate(netutils.ParseIPSloppy(ip)); err != nil { t.Fatalf("test is incorrect, allocator failed to pre allocate IP with error:%v", err) } } @@ -1821,7 +1821,7 @@ func TestInitClusterIP(t *testing.T) { if newSvc.Spec.ClusterIPs[0] != api.ClusterIPNone { for _, ip := range newSvc.Spec.ClusterIPs { family := api.IPv4Protocol - if netutil.IsIPv6String(ip) { + if netutils.IsIPv6String(ip) { family = api.IPv6Protocol } allocator := storage.serviceIPAllocatorsByFamily[family] @@ -2225,7 +2225,7 @@ func TestServiceUpgrade(t *testing.T) { // allocated IP for family, ip := range testCase.allocateIPsBeforeUpdate { alloc := storage.serviceIPAllocatorsByFamily[family] - if err := alloc.Allocate(net.ParseIP(ip)); err != nil { + if err := alloc.Allocate(netutils.ParseIPSloppy(ip)); err != nil { t.Fatalf("test is incorrect, unable to preallocate ip:%v", ip) } } @@ -3653,7 +3653,7 @@ func isValidClusterIPFields(t *testing.T, storage *REST, pre *api.Service, post } // ips must match families for i, ip := range post.Spec.ClusterIPs { - isIPv6 := netutil.IsIPv6String(ip) + isIPv6 := netutils.IsIPv6String(ip) if isIPv6 && post.Spec.IPFamilies[i] != api.IPv6Protocol { t.Fatalf("ips does not match assigned families %+v %+v", post.Spec.ClusterIPs, post.Spec.IPFamilies) } diff --git a/pkg/registry/core/service/storage/storage_test.go b/pkg/registry/core/service/storage/storage_test.go index 9aab79788a5..b9f3d5534be 100644 --- a/pkg/registry/core/service/storage/storage_test.go +++ b/pkg/registry/core/service/storage/storage_test.go @@ -17,7 +17,6 @@ limitations under the License. package storage import ( - "net" "reflect" "testing" @@ -31,6 +30,7 @@ import ( etcd3testing "k8s.io/apiserver/pkg/storage/etcd3/testing" api "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/registry/registrytest" + netutils "k8s.io/utils/net" utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" @@ -421,7 +421,7 @@ func TestServiceDefaultOnRead(t *testing.T) { ResourcePrefix: "services", } - _, cidr, err := net.ParseCIDR("10.0.0.0/24") + _, cidr, err := netutils.ParseCIDRSloppy("10.0.0.0/24") if err != nil { t.Fatalf("failed to parse CIDR") } @@ -479,7 +479,7 @@ func TestServiceDefaulting(t *testing.T) { ResourcePrefix: "services", } - _, cidr, err := net.ParseCIDR(primaryCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(primaryCIDR) if err != nil { t.Fatalf("failed to parse CIDR %s", primaryCIDR) } diff --git a/pkg/registry/core/service/strategy_test.go b/pkg/registry/core/service/strategy_test.go index 91c4b6e50ed..b1bcefbbc8c 100644 --- a/pkg/registry/core/service/strategy_test.go +++ b/pkg/registry/core/service/strategy_test.go @@ -17,7 +17,6 @@ limitations under the License. package service import ( - "net" "reflect" "testing" @@ -34,11 +33,12 @@ import ( utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/kubernetes/pkg/features" + netutils "k8s.io/utils/net" utilpointer "k8s.io/utils/pointer" ) func newStrategy(cidr string, hasSecondary bool) (testStrategy Strategy, testStatusStrategy Strategy) { - _, testCIDR, err := net.ParseCIDR(cidr) + _, testCIDR, err := netutils.ParseCIDRSloppy(cidr) if err != nil { panic("invalid CIDR") } diff --git a/pkg/scheduler/apis/config/v1beta1/defaults.go b/pkg/scheduler/apis/config/v1beta1/defaults.go index 8afd5b6cb8f..8ccec6c810f 100644 --- a/pkg/scheduler/apis/config/v1beta1/defaults.go +++ b/pkg/scheduler/apis/config/v1beta1/defaults.go @@ -28,6 +28,7 @@ import ( "k8s.io/kube-scheduler/config/v1beta1" "k8s.io/kubernetes/pkg/features" "k8s.io/kubernetes/pkg/scheduler/apis/config" + netutils "k8s.io/utils/net" "k8s.io/utils/pointer" ) @@ -143,7 +144,7 @@ func SetDefaults_KubeSchedulerConfiguration(obj *v1beta1.KubeSchedulerConfigurat } else { // Something went wrong splitting the host/port, could just be a missing port so check if the // existing value is a valid IP address. If so, use that with the default scheduler port - if host := net.ParseIP(*obj.HealthzBindAddress); host != nil { + if host := netutils.ParseIPSloppy(*obj.HealthzBindAddress); host != nil { hostPort := net.JoinHostPort(*obj.HealthzBindAddress, strconv.Itoa(config.DefaultInsecureSchedulerPort)) obj.HealthzBindAddress = &hostPort } else { @@ -165,7 +166,7 @@ func SetDefaults_KubeSchedulerConfiguration(obj *v1beta1.KubeSchedulerConfigurat } else { // Something went wrong splitting the host/port, could just be a missing port so check if the // existing value is a valid IP address. If so, use that with the default scheduler port - if host := net.ParseIP(*obj.MetricsBindAddress); host != nil { + if host := netutils.ParseIPSloppy(*obj.MetricsBindAddress); host != nil { hostPort := net.JoinHostPort(*obj.MetricsBindAddress, strconv.Itoa(config.DefaultInsecureSchedulerPort)) obj.MetricsBindAddress = &hostPort } else { diff --git a/pkg/scheduler/apis/config/v1beta2/defaults.go b/pkg/scheduler/apis/config/v1beta2/defaults.go index 8d577e15bcb..d42be645b34 100644 --- a/pkg/scheduler/apis/config/v1beta2/defaults.go +++ b/pkg/scheduler/apis/config/v1beta2/defaults.go @@ -28,6 +28,7 @@ import ( "k8s.io/kube-scheduler/config/v1beta2" "k8s.io/kubernetes/pkg/features" "k8s.io/kubernetes/pkg/scheduler/apis/config" + netutils "k8s.io/utils/net" "k8s.io/utils/pointer" ) @@ -141,7 +142,7 @@ func SetDefaults_KubeSchedulerConfiguration(obj *v1beta2.KubeSchedulerConfigurat } else { // Something went wrong splitting the host/port, could just be a missing port so check if the // existing value is a valid IP address. If so, use that with the default scheduler port - if host := net.ParseIP(*obj.HealthzBindAddress); host != nil { + if host := netutils.ParseIPSloppy(*obj.HealthzBindAddress); host != nil { hostPort := net.JoinHostPort(*obj.HealthzBindAddress, strconv.Itoa(config.DefaultInsecureSchedulerPort)) obj.HealthzBindAddress = &hostPort } @@ -160,7 +161,7 @@ func SetDefaults_KubeSchedulerConfiguration(obj *v1beta2.KubeSchedulerConfigurat } else { // Something went wrong splitting the host/port, could just be a missing port so check if the // existing value is a valid IP address. If so, use that with the default scheduler port - if host := net.ParseIP(*obj.MetricsBindAddress); host != nil { + if host := netutils.ParseIPSloppy(*obj.MetricsBindAddress); host != nil { hostPort := net.JoinHostPort(*obj.MetricsBindAddress, strconv.Itoa(config.DefaultInsecureSchedulerPort)) obj.MetricsBindAddress = &hostPort } diff --git a/pkg/util/bandwidth/linux.go b/pkg/util/bandwidth/linux.go index c105fdea5c2..a347b21860f 100644 --- a/pkg/util/bandwidth/linux.go +++ b/pkg/util/bandwidth/linux.go @@ -30,6 +30,7 @@ import ( "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/utils/exec" + netutils "k8s.io/utils/net" "k8s.io/klog/v2" ) @@ -103,7 +104,7 @@ func (t *tcShaper) nextClassID() (int, error) { // Convert a CIDR from text to a hex representation // Strips any masked parts of the IP, so 1.2.3.4/16 becomes hex(1.2.0.0)/ffffffff func hexCIDR(cidr string) (string, error) { - ip, ipnet, err := net.ParseCIDR(cidr) + ip, ipnet, err := netutils.ParseCIDRSloppy(cidr) if err != nil { return "", err } diff --git a/pkg/util/flag/flags.go b/pkg/util/flag/flags.go index 9a4241d67bb..9113769fcf9 100644 --- a/pkg/util/flag/flags.go +++ b/pkg/util/flag/flags.go @@ -30,7 +30,7 @@ import ( utilnet "k8s.io/apimachinery/pkg/util/net" corev1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper" kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config" - utilsnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) // TODO(mikedanese): remove these flag wrapper types when we remove command line flags @@ -53,7 +53,7 @@ func (v IPVar) Set(s string) error { v.Val = nil return nil } - if net.ParseIP(s) == nil { + if netutils.ParseIPSloppy(s) == nil { return fmt.Errorf("%q is not a valid IP address", s) } if v.Val == nil { @@ -96,7 +96,7 @@ func (v IPPortVar) Set(s string) error { // Both IP and IP:port are valid. // Attempt to parse into IP first. - if net.ParseIP(s) != nil { + if netutils.ParseIPSloppy(s) != nil { *v.Val = s return nil } @@ -106,10 +106,10 @@ func (v IPPortVar) Set(s string) error { if err != nil { return fmt.Errorf("%q is not in a valid format (ip or ip:port): %v", s, err) } - if net.ParseIP(host) == nil { + if netutils.ParseIPSloppy(host) == nil { return fmt.Errorf("%q is not a valid IP address", host) } - if _, err := utilsnet.ParsePort(port, true); err != nil { + if _, err := netutils.ParsePort(port, true); err != nil { return fmt.Errorf("%q is not a valid number", port) } *v.Val = s diff --git a/pkg/util/ipset/ipset.go b/pkg/util/ipset/ipset.go index 52b646c231d..3481480dedd 100644 --- a/pkg/util/ipset/ipset.go +++ b/pkg/util/ipset/ipset.go @@ -19,13 +19,13 @@ package ipset import ( "bytes" "fmt" - "net" "regexp" "strconv" "strings" "k8s.io/klog/v2" utilexec "k8s.io/utils/exec" + netutils "k8s.io/utils/net" ) // Interface is an injectable interface for running ipset commands. Implementations must be goroutine-safe. @@ -183,7 +183,7 @@ func (e *Entry) Validate(set *IPSet) bool { } // IP2 can not be empty for `hash:ip,port,ip` type ip set - if net.ParseIP(e.IP2) == nil { + if netutils.ParseIPSloppy(e.IP2) == nil { klog.Errorf("Error parsing entry %v second ip address %v for ipset %v", e, e.IP2, set) return false } @@ -194,7 +194,7 @@ func (e *Entry) Validate(set *IPSet) bool { } // Net can not be empty for `hash:ip,port,net` type ip set - if _, ipNet, err := net.ParseCIDR(e.Net); ipNet == nil { + if _, ipNet, err := netutils.ParseCIDRSloppy(e.Net); ipNet == nil { klog.Errorf("Error parsing entry %v ip net %v for ipset %v, error: %v", e, e.Net, set, err) return false } @@ -250,7 +250,7 @@ func (e *Entry) checkIPandProtocol(set *IPSet) bool { return false } - if net.ParseIP(e.IP) == nil { + if netutils.ParseIPSloppy(e.IP) == nil { klog.Errorf("Error parsing entry %v ip address %v for ipset %v", e, e.IP, set) return false } diff --git a/pkg/util/ipvs/ipvs_linux_test.go b/pkg/util/ipvs/ipvs_linux_test.go index f1b7559a570..d14aaca790c 100644 --- a/pkg/util/ipvs/ipvs_linux_test.go +++ b/pkg/util/ipvs/ipvs_linux_test.go @@ -20,11 +20,12 @@ package ipvs import ( "fmt" - "net" "reflect" "syscall" "testing" + netutils "k8s.io/utils/net" + libipvs "github.com/moby/ipvs" ) @@ -65,7 +66,7 @@ func Test_toVirtualServer(t *testing.T) { PEName: "", }, VirtualServer{ - Address: net.ParseIP("0.0.0.0"), + Address: netutils.ParseIPSloppy("0.0.0.0"), Protocol: "TCP", Port: 80, Scheduler: "", @@ -85,11 +86,11 @@ func Test_toVirtualServer(t *testing.T) { Timeout: 100, Netmask: 128, AddressFamily: syscall.AF_INET6, - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), PEName: "", }, VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "UDP", Port: 33434, Scheduler: "wlc", @@ -109,11 +110,11 @@ func Test_toVirtualServer(t *testing.T) { Timeout: 0, Netmask: 0xffffffff, AddressFamily: syscall.AF_INET, - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), PEName: "", }, VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "", Port: 0, Scheduler: "lc", @@ -137,7 +138,7 @@ func Test_toVirtualServer(t *testing.T) { PEName: "", }, VirtualServer{ - Address: net.ParseIP("::0"), + Address: netutils.ParseIPSloppy("::0"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -161,7 +162,7 @@ func Test_toVirtualServer(t *testing.T) { PEName: "", }, VirtualServer{ - Address: net.ParseIP("0.0.0.0"), + Address: netutils.ParseIPSloppy("0.0.0.0"), Protocol: "SCTP", Port: 80, Scheduler: "", @@ -204,11 +205,11 @@ func Test_toIPVSService(t *testing.T) { Timeout: 0, Netmask: 0xffffffff, AddressFamily: syscall.AF_INET, - Address: net.ParseIP("0.0.0.0"), + Address: netutils.ParseIPSloppy("0.0.0.0"), PEName: "", }, VirtualServer{ - Address: net.ParseIP("0.0.0.0"), + Address: netutils.ParseIPSloppy("0.0.0.0"), Protocol: "TCP", Port: 80, Scheduler: "", @@ -226,11 +227,11 @@ func Test_toIPVSService(t *testing.T) { Timeout: 100, Netmask: 128, AddressFamily: syscall.AF_INET6, - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), PEName: "", }, VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "UDP", Port: 33434, Scheduler: "wlc", @@ -248,11 +249,11 @@ func Test_toIPVSService(t *testing.T) { Timeout: 0, Netmask: 0xffffffff, AddressFamily: syscall.AF_INET, - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), PEName: "", }, VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "", Port: 0, Scheduler: "lc", @@ -270,11 +271,11 @@ func Test_toIPVSService(t *testing.T) { Timeout: 0, Netmask: 128, AddressFamily: syscall.AF_INET6, - Address: net.ParseIP("::0"), + Address: netutils.ParseIPSloppy("::0"), PEName: "", }, VirtualServer{ - Address: net.ParseIP("::0"), + Address: netutils.ParseIPSloppy("::0"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -305,10 +306,10 @@ func Test_toRealServer(t *testing.T) { Port: 54321, ConnectionFlags: 0, Weight: 1, - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), }, RealServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Port: 54321, Weight: 1, }, @@ -318,10 +319,10 @@ func Test_toRealServer(t *testing.T) { Port: 53, ConnectionFlags: 0, Weight: 1, - Address: net.ParseIP("2002::cafe"), + Address: netutils.ParseIPSloppy("2002::cafe"), }, RealServer{ - Address: net.ParseIP("2002::cafe"), + Address: netutils.ParseIPSloppy("2002::cafe"), Port: 53, Weight: 1, }, @@ -345,7 +346,7 @@ func Test_toIPVSDestination(t *testing.T) { }{ { RealServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Port: 54321, Weight: 1, }, @@ -353,12 +354,12 @@ func Test_toIPVSDestination(t *testing.T) { Port: 54321, ConnectionFlags: 0, Weight: 1, - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), }, }, { RealServer{ - Address: net.ParseIP("2002::cafe"), + Address: netutils.ParseIPSloppy("2002::cafe"), Port: 53, Weight: 1, }, @@ -366,7 +367,7 @@ func Test_toIPVSDestination(t *testing.T) { Port: 53, ConnectionFlags: 0, Weight: 1, - Address: net.ParseIP("2002::cafe"), + Address: netutils.ParseIPSloppy("2002::cafe"), }, }, } diff --git a/pkg/util/ipvs/ipvs_test.go b/pkg/util/ipvs/ipvs_test.go index 408966818f3..64a10b2a5cd 100644 --- a/pkg/util/ipvs/ipvs_test.go +++ b/pkg/util/ipvs/ipvs_test.go @@ -17,12 +17,12 @@ limitations under the License. package ipvs import ( - "net" "reflect" "sort" "testing" "k8s.io/apimachinery/pkg/util/version" + netutils "k8s.io/utils/net" ) func TestVirtualServerEqual(t *testing.T) { @@ -34,7 +34,7 @@ func TestVirtualServerEqual(t *testing.T) { }{ { svcA: &VirtualServer{ - Address: net.ParseIP("10.20.30.40"), + Address: netutils.ParseIPSloppy("10.20.30.40"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -42,7 +42,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -54,7 +54,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -62,7 +62,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("2017::beef"), + Address: netutils.ParseIPSloppy("2017::beef"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -74,7 +74,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "TCP", Port: 0, Scheduler: "wrr", @@ -82,7 +82,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("2012::beeef"), + Address: netutils.ParseIPSloppy("2012::beeef"), Protocol: "UDP", Port: 0, Scheduler: "wrr", @@ -94,7 +94,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "TCP", Port: 80, Scheduler: "wrr", @@ -102,7 +102,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "TCP", Port: 8080, Scheduler: "wrr", @@ -114,7 +114,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "TCP", Port: 80, Scheduler: "rr", @@ -122,7 +122,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "TCP", Port: 80, Scheduler: "wlc", @@ -134,7 +134,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "TCP", Port: 80, Scheduler: "rr", @@ -142,7 +142,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "TCP", Port: 80, Scheduler: "rr", @@ -154,7 +154,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -162,7 +162,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "", Port: 0, Scheduler: "wrr", @@ -174,7 +174,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "TCP", Port: 80, Scheduler: "rr", @@ -182,7 +182,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 10800, }, svcB: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "TCP", Port: 80, Scheduler: "rr", @@ -194,7 +194,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "TCP", Port: 0, Scheduler: "wrr", @@ -202,7 +202,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 0, }, svcB: &VirtualServer{ - Address: net.ParseIP("2012::beeef"), + Address: netutils.ParseIPSloppy("2012::beeef"), Protocol: "SCTP", Port: 0, Scheduler: "wrr", @@ -214,7 +214,7 @@ func TestVirtualServerEqual(t *testing.T) { }, { svcA: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "SCTP", Port: 80, Scheduler: "rr", @@ -222,7 +222,7 @@ func TestVirtualServerEqual(t *testing.T) { Timeout: 10800, }, svcB: &VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Protocol: "SCTP", Port: 80, Scheduler: "rr", @@ -251,11 +251,11 @@ func TestRealServerEqual(t *testing.T) { }{ { rsA: &RealServer{ - Address: net.ParseIP("10.20.30.40"), + Address: netutils.ParseIPSloppy("10.20.30.40"), Port: 80, }, rsB: &RealServer{ - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Port: 80, }, equal: false, @@ -263,11 +263,11 @@ func TestRealServerEqual(t *testing.T) { }, { rsA: &RealServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Port: 80, }, rsB: &RealServer{ - Address: net.ParseIP("2017::beef"), + Address: netutils.ParseIPSloppy("2017::beef"), Port: 80, }, equal: false, @@ -275,11 +275,11 @@ func TestRealServerEqual(t *testing.T) { }, { rsA: &RealServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Port: 80, }, rsB: &RealServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Port: 8080, }, equal: false, @@ -287,11 +287,11 @@ func TestRealServerEqual(t *testing.T) { }, { rsA: &RealServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Port: 3080, }, rsB: &RealServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Port: 3080, }, equal: true, @@ -299,11 +299,11 @@ func TestRealServerEqual(t *testing.T) { }, { rsA: &RealServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Port: 3080, }, rsB: &RealServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Port: 3080, }, equal: true, @@ -326,7 +326,7 @@ func TestFrontendServiceString(t *testing.T) { }{ { svc: &VirtualServer{ - Address: net.ParseIP("10.20.30.40"), + Address: netutils.ParseIPSloppy("10.20.30.40"), Protocol: "TCP", Port: 80, }, @@ -334,7 +334,7 @@ func TestFrontendServiceString(t *testing.T) { }, { svc: &VirtualServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Protocol: "UDP", Port: 8080, }, @@ -342,7 +342,7 @@ func TestFrontendServiceString(t *testing.T) { }, { svc: &VirtualServer{ - Address: net.ParseIP("10.20.30.41"), + Address: netutils.ParseIPSloppy("10.20.30.41"), Protocol: "ESP", Port: 1234, }, @@ -364,14 +364,14 @@ func TestFrontendDestinationString(t *testing.T) { }{ { svc: &RealServer{ - Address: net.ParseIP("10.20.30.40"), + Address: netutils.ParseIPSloppy("10.20.30.40"), Port: 80, }, expected: "10.20.30.40:80", }, { svc: &RealServer{ - Address: net.ParseIP("2012::beef"), + Address: netutils.ParseIPSloppy("2012::beef"), Port: 8080, }, expected: "[2012::beef]:8080", diff --git a/pkg/util/ipvs/testing/fake_test.go b/pkg/util/ipvs/testing/fake_test.go index 1d576151bb1..e8489087643 100644 --- a/pkg/util/ipvs/testing/fake_test.go +++ b/pkg/util/ipvs/testing/fake_test.go @@ -17,10 +17,10 @@ limitations under the License. package testing import ( - "net" "testing" utilipvs "k8s.io/kubernetes/pkg/util/ipvs" + netutils "k8s.io/utils/net" ) func TestVirtualServer(t *testing.T) { @@ -28,7 +28,7 @@ func TestVirtualServer(t *testing.T) { fake := NewFake() // Add a virtual server vs1 := &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Port: uint16(80), Protocol: string("TCP"), Flags: utilipvs.FlagHashed, @@ -47,7 +47,7 @@ func TestVirtualServer(t *testing.T) { } // Update virtual server vs12 := &utilipvs.VirtualServer{ - Address: net.ParseIP("1.2.3.4"), + Address: netutils.ParseIPSloppy("1.2.3.4"), Port: uint16(80), Protocol: string("TCP"), Flags: utilipvs.FlagPersistent, @@ -66,7 +66,7 @@ func TestVirtualServer(t *testing.T) { } // Add another virtual server vs2 := &utilipvs.VirtualServer{ - Address: net.ParseIP("10::40"), + Address: netutils.ParseIPSloppy("10::40"), Port: uint16(8080), Protocol: string("UDP"), } @@ -76,7 +76,7 @@ func TestVirtualServer(t *testing.T) { } // Add another virtual server vs3 := &utilipvs.VirtualServer{ - Address: net.ParseIP("10::40"), + Address: netutils.ParseIPSloppy("10::40"), Port: uint16(7777), Protocol: string("SCTP"), } @@ -122,14 +122,14 @@ func TestRealServer(t *testing.T) { fake := NewFake() // Add a virtual server vs := &utilipvs.VirtualServer{ - Address: net.ParseIP("10.20.30.40"), + Address: netutils.ParseIPSloppy("10.20.30.40"), Port: uint16(80), Protocol: string("TCP"), } rss := []*utilipvs.RealServer{ - {Address: net.ParseIP("172.16.2.1"), Port: 8080, Weight: 1}, - {Address: net.ParseIP("172.16.2.2"), Port: 8080, Weight: 2}, - {Address: net.ParseIP("172.16.2.3"), Port: 8080, Weight: 3}, + {Address: netutils.ParseIPSloppy("172.16.2.1"), Port: 8080, Weight: 1}, + {Address: netutils.ParseIPSloppy("172.16.2.2"), Port: 8080, Weight: 2}, + {Address: netutils.ParseIPSloppy("172.16.2.3"), Port: 8080, Weight: 3}, } err := fake.AddVirtualServer(vs) if err != nil { @@ -173,7 +173,7 @@ func TestRealServer(t *testing.T) { } // Test delete real server that not exist rs := &utilipvs.RealServer{ - Address: net.ParseIP("172.16.2.4"), + Address: netutils.ParseIPSloppy("172.16.2.4"), Port: uint16(8080), Weight: 1, } diff --git a/pkg/util/node/node.go b/pkg/util/node/node.go index 1f0e2f0f56c..ff11b087a64 100644 --- a/pkg/util/node/node.go +++ b/pkg/util/node/node.go @@ -37,7 +37,7 @@ import ( clientset "k8s.io/client-go/kubernetes" v1core "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/kubernetes/pkg/features" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) const ( @@ -103,7 +103,7 @@ func GetNodeHostIPs(node *v1.Node) ([]net.IP, error) { allIPs := make([]net.IP, 0, len(node.Status.Addresses)) for _, addr := range node.Status.Addresses { if addr.Type == v1.NodeInternalIP { - ip := net.ParseIP(addr.Address) + ip := netutils.ParseIPSloppy(addr.Address) if ip != nil { allIPs = append(allIPs, ip) } @@ -111,7 +111,7 @@ func GetNodeHostIPs(node *v1.Node) ([]net.IP, error) { } for _, addr := range node.Status.Addresses { if addr.Type == v1.NodeExternalIP { - ip := net.ParseIP(addr.Address) + ip := netutils.ParseIPSloppy(addr.Address) if ip != nil { allIPs = append(allIPs, ip) } @@ -124,7 +124,7 @@ func GetNodeHostIPs(node *v1.Node) ([]net.IP, error) { nodeIPs := []net.IP{allIPs[0]} if utilfeature.DefaultFeatureGate.Enabled(features.IPv6DualStack) { for _, ip := range allIPs { - if utilnet.IsIPv6(ip) != utilnet.IsIPv6(nodeIPs[0]) { + if netutils.IsIPv6(ip) != netutils.IsIPv6(nodeIPs[0]) { nodeIPs = append(nodeIPs, ip) break } diff --git a/pkg/util/node/node_test.go b/pkg/util/node/node_test.go index 21be30520d8..c5c089873d1 100644 --- a/pkg/util/node/node_test.go +++ b/pkg/util/node/node_test.go @@ -26,6 +26,7 @@ import ( utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/kubernetes/pkg/features" + netutils "k8s.io/utils/net" ) func TestGetPreferredAddress(t *testing.T) { @@ -120,7 +121,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "4.3.2.1"}, {Type: v1.NodeExternalIP, Address: "4.3.2.2"}, }, - expectIPs: []net.IP{net.ParseIP("1.2.3.4")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("1.2.3.4")}, }, { name: "IPv4-only, external-first", @@ -129,7 +130,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "4.3.2.2"}, {Type: v1.NodeInternalIP, Address: "1.2.3.4"}, }, - expectIPs: []net.IP{net.ParseIP("1.2.3.4")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("1.2.3.4")}, }, { name: "IPv4-only, no internal", @@ -137,7 +138,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "4.3.2.1"}, {Type: v1.NodeExternalIP, Address: "4.3.2.2"}, }, - expectIPs: []net.IP{net.ParseIP("4.3.2.1")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("4.3.2.1")}, }, { name: "dual-stack node, single-stack cluster", @@ -148,7 +149,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeInternalIP, Address: "a:b::c:d"}, {Type: v1.NodeExternalIP, Address: "d:c::b:a"}, }, - expectIPs: []net.IP{net.ParseIP("1.2.3.4")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("1.2.3.4")}, }, { name: "dual-stack node, dual-stack cluster", @@ -160,7 +161,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "d:c::b:a"}, }, dualStack: true, - expectIPs: []net.IP{net.ParseIP("1.2.3.4"), net.ParseIP("a:b::c:d")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("1.2.3.4"), netutils.ParseIPSloppy("a:b::c:d")}, }, { name: "dual-stack node, different order, single-stack cluster", @@ -171,7 +172,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "4.3.2.2"}, {Type: v1.NodeExternalIP, Address: "d:c::b:a"}, }, - expectIPs: []net.IP{net.ParseIP("1.2.3.4")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("1.2.3.4")}, }, { name: "dual-stack node, different order, dual-stack cluster", @@ -183,7 +184,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "d:c::b:a"}, }, dualStack: true, - expectIPs: []net.IP{net.ParseIP("1.2.3.4"), net.ParseIP("a:b::c:d")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("1.2.3.4"), netutils.ParseIPSloppy("a:b::c:d")}, }, { name: "dual-stack node, IPv6-first, no internal IPv4, single-stack cluster", @@ -193,7 +194,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "4.3.2.1"}, {Type: v1.NodeExternalIP, Address: "4.3.2.2"}, }, - expectIPs: []net.IP{net.ParseIP("a:b::c:d")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("a:b::c:d")}, }, { name: "dual-stack node, IPv6-first, no internal IPv4, dual-stack cluster", @@ -204,7 +205,7 @@ func TestGetNodeHostIPs(t *testing.T) { {Type: v1.NodeExternalIP, Address: "4.3.2.2"}, }, dualStack: true, - expectIPs: []net.IP{net.ParseIP("a:b::c:d"), net.ParseIP("4.3.2.1")}, + expectIPs: []net.IP{netutils.ParseIPSloppy("a:b::c:d"), netutils.ParseIPSloppy("4.3.2.1")}, }, } diff --git a/pkg/volume/glusterfs/glusterfs.go b/pkg/volume/glusterfs/glusterfs.go index 2e731c7da87..2a91164836d 100644 --- a/pkg/volume/glusterfs/glusterfs.go +++ b/pkg/volume/glusterfs/glusterfs.go @@ -22,7 +22,6 @@ import ( "fmt" "math" "math/rand" - "net" "net/http" "os" "path/filepath" @@ -35,6 +34,7 @@ import ( gapi "github.com/heketi/heketi/pkg/glusterfs/api" "k8s.io/klog/v2" "k8s.io/mount-utils" + netutils "k8s.io/utils/net" utilstrings "k8s.io/utils/strings" v1 "k8s.io/api/core/v1" @@ -992,7 +992,7 @@ func getClusterNodes(cli *gcli.Client, cluster string) (dynamicHostIps []string, } ipaddr := dstrings.Join(nodeInfo.NodeAddRequest.Hostnames.Storage, "") // IP validates if a string is a valid IP address. - ip := net.ParseIP(ipaddr) + ip := netutils.ParseIPSloppy(ipaddr) if ip == nil { return nil, fmt.Errorf("glusterfs server node ip address %s must be a valid IP address, (e.g. 10.9.8.7)", ipaddr) } diff --git a/staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go b/staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go index f4e98e39017..975da555ecb 100644 --- a/staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go +++ b/staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go @@ -36,6 +36,7 @@ import ( "k8s.io/apiserver/pkg/util/proxy" "k8s.io/apiserver/pkg/util/webhook" corev1 "k8s.io/client-go/listers/core/v1" + netutils "k8s.io/utils/net" ) const defaultEtcdPathPrefix = "/registry/apiextensions.kubernetes.io" @@ -91,7 +92,7 @@ func (o *CustomResourceDefinitionsServerOptions) Complete() error { // Config returns an apiextensions-apiserver configuration. func (o CustomResourceDefinitionsServerOptions) Config() (*apiserver.Config, error) { // TODO have a "real" external address - if err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil { + if err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil { return nil, fmt.Errorf("error creating self-signed certificates: %v", err) } diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/http.go b/staging/src/k8s.io/apimachinery/pkg/util/net/http.go index d75ac6efa2d..42d66d3164a 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/http.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/http.go @@ -39,6 +39,7 @@ import ( "golang.org/x/net/http2" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) // JoinPreservingTrailingSlash does a path.Join of the specified elements, @@ -289,7 +290,7 @@ func SourceIPs(req *http.Request) []net.IP { // Use the first valid one. parts := strings.Split(hdrForwardedFor, ",") for _, part := range parts { - ip := net.ParseIP(strings.TrimSpace(part)) + ip := netutils.ParseIPSloppy(strings.TrimSpace(part)) if ip != nil { srcIPs = append(srcIPs, ip) } @@ -299,7 +300,7 @@ func SourceIPs(req *http.Request) []net.IP { // Try the X-Real-Ip header. hdrRealIp := hdr.Get("X-Real-Ip") if hdrRealIp != "" { - ip := net.ParseIP(hdrRealIp) + ip := netutils.ParseIPSloppy(hdrRealIp) // Only append the X-Real-Ip if it's not already contained in the X-Forwarded-For chain. if ip != nil && !containsIP(srcIPs, ip) { srcIPs = append(srcIPs, ip) @@ -311,11 +312,11 @@ func SourceIPs(req *http.Request) []net.IP { // Remote Address in Go's HTTP server is in the form host:port so we need to split that first. host, _, err := net.SplitHostPort(req.RemoteAddr) if err == nil { - remoteIP = net.ParseIP(host) + remoteIP = netutils.ParseIPSloppy(host) } // Fallback if Remote Address was just IP. if remoteIP == nil { - remoteIP = net.ParseIP(req.RemoteAddr) + remoteIP = netutils.ParseIPSloppy(req.RemoteAddr) } // Don't duplicate remote IP if it's already the last address in the chain. @@ -382,7 +383,7 @@ func NewProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error cidrs := []*net.IPNet{} for _, noProxyRule := range noProxyRules { - _, cidr, _ := net.ParseCIDR(noProxyRule) + _, cidr, _ := netutils.ParseCIDRSloppy(noProxyRule) if cidr != nil { cidrs = append(cidrs, cidr) } @@ -393,7 +394,7 @@ func NewProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error } return func(req *http.Request) (*url.URL, error) { - ip := net.ParseIP(req.URL.Hostname()) + ip := netutils.ParseIPSloppy(req.URL.Hostname()) if ip == nil { return delegate(req) } diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go b/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go index 9411bfa7ddf..3d3043a7afc 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go @@ -37,11 +37,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/util/wait" + netutils "k8s.io/utils/net" ) func TestGetClientIP(t *testing.T) { ipString := "10.0.0.1" - ip := net.ParseIP(ipString) + ip := netutils.ParseIPSloppy(ipString) invalidIPString := "invalidIPString" testCases := []struct { Request http.Request diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/interface.go b/staging/src/k8s.io/apimachinery/pkg/util/net/interface.go index 9adf4cfe477..82241680648 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/interface.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/interface.go @@ -27,6 +27,7 @@ import ( "strings" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) type AddressFamily uint @@ -221,7 +222,7 @@ func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) if len(addrs) > 0 { for i := range addrs { klog.V(4).Infof("Checking addr %s.", addrs[i].String()) - ip, _, err := net.ParseCIDR(addrs[i].String()) + ip, _, err := netutils.ParseCIDRSloppy(addrs[i].String()) if err != nil { return nil, err } @@ -336,7 +337,7 @@ func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFam continue } for _, addr := range addrs { - ip, _, err := net.ParseCIDR(addr.String()) + ip, _, err := netutils.ParseCIDRSloppy(addr.String()) if err != nil { return nil, fmt.Errorf("Unable to parse CIDR for interface %q: %s", intf.Name, err) } diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/interface_test.go b/staging/src/k8s.io/apimachinery/pkg/util/net/interface_test.go index fac078d20f2..c4d543cda0a 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/interface_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/interface_test.go @@ -23,6 +23,8 @@ import ( "os" "strings" "testing" + + netutils "k8s.io/utils/net" ) const gatewayfirst = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT @@ -119,8 +121,8 @@ var ( ) var ( - ipv4Route = Route{Interface: "eth3", Destination: net.ParseIP("0.0.0.0"), Gateway: net.ParseIP("10.254.0.1"), Family: familyIPv4} - ipv6Route = Route{Interface: "eth3", Destination: net.ParseIP("::"), Gateway: net.ParseIP("2001:1::1"), Family: familyIPv6} + ipv4Route = Route{Interface: "eth3", Destination: netutils.ParseIPSloppy("0.0.0.0"), Gateway: netutils.ParseIPSloppy("10.254.0.1"), Family: familyIPv4} + ipv6Route = Route{Interface: "eth3", Destination: netutils.ParseIPSloppy("::"), Gateway: netutils.ParseIPSloppy("2001:1::1"), Family: familyIPv6} ) var ( @@ -282,8 +284,8 @@ func TestFinalIP(t *testing.T) { {"loopbackv6", []net.Addr{addrStruct{val: "::1/128"}}, familyIPv6, nil}, {"link local v4", []net.Addr{addrStruct{val: "169.254.1.10/16"}}, familyIPv4, nil}, {"link local v6", []net.Addr{addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}}, familyIPv6, nil}, - {"ip4", []net.Addr{addrStruct{val: "10.254.12.132/17"}}, familyIPv4, net.ParseIP("10.254.12.132")}, - {"ip6", []net.Addr{addrStruct{val: "2001::5/64"}}, familyIPv6, net.ParseIP("2001::5")}, + {"ip4", []net.Addr{addrStruct{val: "10.254.12.132/17"}}, familyIPv4, netutils.ParseIPSloppy("10.254.12.132")}, + {"ip6", []net.Addr{addrStruct{val: "2001::5/64"}}, familyIPv6, netutils.ParseIPSloppy("2001::5")}, {"no addresses", []net.Addr{}, familyIPv4, nil}, } @@ -556,8 +558,8 @@ func TestGetIPFromInterface(t *testing.T) { expected net.IP errStrFrag string }{ - {"ipv4", "eth3", familyIPv4, validNetworkInterface{}, net.ParseIP("10.254.71.145"), ""}, - {"ipv6", "eth3", familyIPv6, ipv6NetworkInterface{}, net.ParseIP("2001::200"), ""}, + {"ipv4", "eth3", familyIPv4, validNetworkInterface{}, netutils.ParseIPSloppy("10.254.71.145"), ""}, + {"ipv6", "eth3", familyIPv6, ipv6NetworkInterface{}, netutils.ParseIPSloppy("2001::200"), ""}, {"no ipv4", "eth3", familyIPv4, ipv6NetworkInterface{}, nil, ""}, {"no ipv6", "eth3", familyIPv6, validNetworkInterface{}, nil, ""}, {"I/F down", "eth3", familyIPv4, downNetworkInterface{}, nil, ""}, @@ -587,8 +589,8 @@ func TestGetIPFromLoopbackInterface(t *testing.T) { expected net.IP errStrFrag string }{ - {"ipv4", familyIPv4, linkLocalLoopbackNetworkInterface{}, net.ParseIP("10.1.1.1"), ""}, - {"ipv6", familyIPv6, linkLocalLoopbackNetworkInterface{}, net.ParseIP("fd00:1:1::1"), ""}, + {"ipv4", familyIPv4, linkLocalLoopbackNetworkInterface{}, netutils.ParseIPSloppy("10.1.1.1"), ""}, + {"ipv6", familyIPv6, linkLocalLoopbackNetworkInterface{}, netutils.ParseIPSloppy("fd00:1:1::1"), ""}, {"no global ipv4", familyIPv4, loopbackNetworkInterface{}, nil, ""}, {"no global ipv6", familyIPv6, loopbackNetworkInterface{}, nil, ""}, } @@ -614,21 +616,21 @@ func TestChooseHostInterfaceFromRoute(t *testing.T) { order AddressFamilyPreference expected net.IP }{ - {"single-stack ipv4", routeV4, validNetworkInterface{}, preferIPv4, net.ParseIP("10.254.71.145")}, - {"single-stack ipv4, prefer v6", routeV4, validNetworkInterface{}, preferIPv6, net.ParseIP("10.254.71.145")}, - {"single-stack ipv6", routeV6, ipv6NetworkInterface{}, preferIPv4, net.ParseIP("2001::200")}, - {"single-stack ipv6, prefer v6", routeV6, ipv6NetworkInterface{}, preferIPv6, net.ParseIP("2001::200")}, - {"dual stack", bothRoutes, v4v6NetworkInterface{}, preferIPv4, net.ParseIP("10.254.71.145")}, - {"dual stack, prefer v6", bothRoutes, v4v6NetworkInterface{}, preferIPv6, net.ParseIP("2001::10")}, - {"LLA and loopback with global, IPv4", routeV4, linkLocalLoopbackNetworkInterface{}, preferIPv4, net.ParseIP("10.1.1.1")}, - {"LLA and loopback with global, IPv6", routeV6, linkLocalLoopbackNetworkInterface{}, preferIPv6, net.ParseIP("fd00:1:1::1")}, - {"LLA and loopback with global, dual stack prefer IPv4", bothRoutes, linkLocalLoopbackNetworkInterface{}, preferIPv4, net.ParseIP("10.1.1.1")}, - {"LLA and loopback with global, dual stack prefer IPv6", bothRoutes, linkLocalLoopbackNetworkInterface{}, preferIPv6, net.ParseIP("fd00:1:1::1")}, + {"single-stack ipv4", routeV4, validNetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("10.254.71.145")}, + {"single-stack ipv4, prefer v6", routeV4, validNetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("10.254.71.145")}, + {"single-stack ipv6", routeV6, ipv6NetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("2001::200")}, + {"single-stack ipv6, prefer v6", routeV6, ipv6NetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("2001::200")}, + {"dual stack", bothRoutes, v4v6NetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("10.254.71.145")}, + {"dual stack, prefer v6", bothRoutes, v4v6NetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("2001::10")}, + {"LLA and loopback with global, IPv4", routeV4, linkLocalLoopbackNetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("10.1.1.1")}, + {"LLA and loopback with global, IPv6", routeV6, linkLocalLoopbackNetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("fd00:1:1::1")}, + {"LLA and loopback with global, dual stack prefer IPv4", bothRoutes, linkLocalLoopbackNetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("10.1.1.1")}, + {"LLA and loopback with global, dual stack prefer IPv6", bothRoutes, linkLocalLoopbackNetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("fd00:1:1::1")}, {"LLA and loopback with global, no routes", noRoutes, linkLocalLoopbackNetworkInterface{}, preferIPv6, nil}, - {"interface and loopback with global, IPv4", routeV4, globalsNetworkInterface{}, preferIPv4, net.ParseIP("192.168.1.1")}, - {"interface and loopback with global, IPv6", routeV6, globalsNetworkInterface{}, preferIPv6, net.ParseIP("fd00::200")}, - {"interface and loopback with global, dual stack prefer IPv4", bothRoutes, globalsNetworkInterface{}, preferIPv4, net.ParseIP("192.168.1.1")}, - {"interface and loopback with global, dual stack prefer IPv6", bothRoutes, globalsNetworkInterface{}, preferIPv6, net.ParseIP("fd00::200")}, + {"interface and loopback with global, IPv4", routeV4, globalsNetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("192.168.1.1")}, + {"interface and loopback with global, IPv6", routeV6, globalsNetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("fd00::200")}, + {"interface and loopback with global, dual stack prefer IPv4", bothRoutes, globalsNetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("192.168.1.1")}, + {"interface and loopback with global, dual stack prefer IPv6", bothRoutes, globalsNetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("fd00::200")}, {"interface and loopback with global, no routes", noRoutes, globalsNetworkInterface{}, preferIPv6, nil}, {"all LLA", routeV4, networkInterfaceWithOnlyLinkLocals{}, preferIPv4, nil}, {"no routes", noRoutes, validNetworkInterface{}, preferIPv4, nil}, @@ -649,10 +651,10 @@ func TestMemberOf(t *testing.T) { family AddressFamily expected bool }{ - {"ipv4 is 4", net.ParseIP("10.20.30.40"), familyIPv4, true}, - {"ipv4 is 6", net.ParseIP("10.10.10.10"), familyIPv6, false}, - {"ipv6 is 4", net.ParseIP("2001::100"), familyIPv4, false}, - {"ipv6 is 6", net.ParseIP("2001::100"), familyIPv6, true}, + {"ipv4 is 4", netutils.ParseIPSloppy("10.20.30.40"), familyIPv4, true}, + {"ipv4 is 6", netutils.ParseIPSloppy("10.10.10.10"), familyIPv6, false}, + {"ipv6 is 4", netutils.ParseIPSloppy("2001::100"), familyIPv4, false}, + {"ipv6 is 6", netutils.ParseIPSloppy("2001::100"), familyIPv6, true}, } for _, tc := range testCases { if memberOf(tc.ip, tc.family) != tc.expected { @@ -678,12 +680,12 @@ func TestGetIPFromHostInterfaces(t *testing.T) { {"no addresses", networkInterfaceWithNoAddrs{}, preferIPv4, nil, "no acceptable"}, {"invalid addr", networkInterfaceWithInvalidAddr{}, preferIPv4, nil, "invalid CIDR"}, {"no matches", networkInterfaceWithOnlyLinkLocals{}, preferIPv4, nil, "no acceptable"}, - {"single-stack ipv4", validNetworkInterface{}, preferIPv4, net.ParseIP("10.254.71.145"), ""}, - {"single-stack ipv4, prefer ipv6", validNetworkInterface{}, preferIPv6, net.ParseIP("10.254.71.145"), ""}, - {"single-stack ipv6", ipv6NetworkInterface{}, preferIPv4, net.ParseIP("2001::200"), ""}, - {"single-stack ipv6, prefer ipv6", ipv6NetworkInterface{}, preferIPv6, net.ParseIP("2001::200"), ""}, - {"dual stack", v4v6NetworkInterface{}, preferIPv4, net.ParseIP("10.254.71.145"), ""}, - {"dual stack, prefer ipv6", v4v6NetworkInterface{}, preferIPv6, net.ParseIP("2001::10"), ""}, + {"single-stack ipv4", validNetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("10.254.71.145"), ""}, + {"single-stack ipv4, prefer ipv6", validNetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("10.254.71.145"), ""}, + {"single-stack ipv6", ipv6NetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("2001::200"), ""}, + {"single-stack ipv6, prefer ipv6", ipv6NetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("2001::200"), ""}, + {"dual stack", v4v6NetworkInterface{}, preferIPv4, netutils.ParseIPSloppy("10.254.71.145"), ""}, + {"dual stack, prefer ipv6", v4v6NetworkInterface{}, preferIPv6, netutils.ParseIPSloppy("2001::10"), ""}, } for _, tc := range testCases { diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/util_test.go b/staging/src/k8s.io/apimachinery/pkg/util/net/util_test.go index 9e175fcb37b..029f2f7116c 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/util_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/util_test.go @@ -22,10 +22,12 @@ import ( "os" "syscall" "testing" + + netutils "k8s.io/utils/net" ) func getIPNet(cidr string) *net.IPNet { - _, ipnet, _ := net.ParseCIDR(cidr) + _, ipnet, _ := netutils.ParseCIDRSloppy(cidr) return ipnet } diff --git a/staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go b/staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go index c8b41998405..83df4fb8d42 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go @@ -25,6 +25,7 @@ import ( "strings" "k8s.io/apimachinery/pkg/util/validation/field" + netutils "k8s.io/utils/net" ) const qnameCharFmt string = "[A-Za-z0-9]" @@ -346,7 +347,7 @@ func IsValidPortName(port string) []string { // IsValidIP tests that the argument is a valid IP address. func IsValidIP(value string) []string { - if net.ParseIP(value) == nil { + if netutils.ParseIPSloppy(value) == nil { return []string{"must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)"} } return nil @@ -355,7 +356,7 @@ func IsValidIP(value string) []string { // IsValidIPv4Address tests that the argument is a valid IPv4 address. func IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList - ip := net.ParseIP(value) + ip := netutils.ParseIPSloppy(value) if ip == nil || ip.To4() == nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv4 address")) } @@ -365,7 +366,7 @@ func IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList { // IsValidIPv6Address tests that the argument is a valid IPv6 address. func IsValidIPv6Address(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList - ip := net.ParseIP(value) + ip := netutils.ParseIPSloppy(value) if ip == nil || ip.To4() != nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv6 address")) } diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/discovery/addresses_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/discovery/addresses_test.go index 4c811ffac0e..79540795ea6 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/discovery/addresses_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/discovery/addresses_test.go @@ -17,13 +17,13 @@ limitations under the License. package discovery import ( - "net" "net/http" "reflect" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" utilnet "k8s.io/apimachinery/pkg/util/net" + netutils "k8s.io/utils/net" ) func TestGetServerAddressByClientCIDRs(t *testing.T) { @@ -103,7 +103,7 @@ func TestGetServerAddressByClientCIDRs(t *testing.T) { }, } - _, ipRange, _ := net.ParseCIDR("10.0.0.0/24") + _, ipRange, _ := netutils.ParseCIDRSloppy("10.0.0.0/24") discoveryAddresses := DefaultAddresses{DefaultAddress: "ExternalAddress"} discoveryAddresses.CIDRRules = append(discoveryAddresses.CIDRRules, CIDRRule{IPRange: *ipRange, Address: "serviceIP"}) diff --git a/staging/src/k8s.io/apiserver/pkg/server/config_selfclient_test.go b/staging/src/k8s.io/apiserver/pkg/server/config_selfclient_test.go index 4d811c64104..5e646d735f1 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/config_selfclient_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/config_selfclient_test.go @@ -47,7 +47,7 @@ func TestLoopbackHostPortIPv4(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { + if ip := netutils.ParseIPSloppy(host); ip == nil || !ip.IsLoopback() { t.Fatalf("expected host to be loopback, got %q", host) } if port != "443" { @@ -78,7 +78,7 @@ func TestLoopbackHostPortIPv6(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() || ip.To4() != nil { + if ip := netutils.ParseIPSloppy(host); ip == nil || !ip.IsLoopback() || ip.To4() != nil { t.Fatalf("expected IPv6 host to be loopback, got %q", host) } if port != "443" { diff --git a/staging/src/k8s.io/apiserver/pkg/server/config_test.go b/staging/src/k8s.io/apiserver/pkg/server/config_test.go index 6982f95ced7..283b915fe85 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/config_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/config_test.go @@ -19,7 +19,6 @@ package server import ( "fmt" "io/ioutil" - "net" "net/http" "net/http/httptest" "net/http/httputil" @@ -43,6 +42,7 @@ import ( "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" "k8s.io/client-go/rest" + netutils "k8s.io/utils/net" ) func TestAuthorizeClientBearerTokenNoops(t *testing.T) { @@ -81,7 +81,7 @@ func TestAuthorizeClientBearerTokenNoops(t *testing.T) { func TestNewWithDelegate(t *testing.T) { delegateConfig := NewConfig(codecs) delegateConfig.ExternalAddress = "192.168.10.4:443" - delegateConfig.PublicAddress = net.ParseIP("192.168.10.4") + delegateConfig.PublicAddress = netutils.ParseIPSloppy("192.168.10.4") delegateConfig.LegacyAPIGroupPrefixes = sets.NewString("/api") delegateConfig.LoopbackClientConfig = &rest.Config{} clientset := fake.NewSimpleClientset() @@ -113,7 +113,7 @@ func TestNewWithDelegate(t *testing.T) { wrappingConfig := NewConfig(codecs) wrappingConfig.ExternalAddress = "192.168.10.4:443" - wrappingConfig.PublicAddress = net.ParseIP("192.168.10.4") + wrappingConfig.PublicAddress = netutils.ParseIPSloppy("192.168.10.4") wrappingConfig.LegacyAPIGroupPrefixes = sets.NewString("/api") wrappingConfig.LoopbackClientConfig = &rest.Config{} diff --git a/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates.go b/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates.go index ee0aa8de0f1..e8be133c02e 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates.go +++ b/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates.go @@ -20,12 +20,12 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "net" "strings" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) // BuildNamedCertificates returns a map of *tls.Certificate by name. It's @@ -77,7 +77,7 @@ func getCertificateNames(cert *x509.Certificate) []string { var names []string cn := cert.Subject.CommonName - cnIsIP := net.ParseIP(cn) != nil + cnIsIP := netutils.ParseIPSloppy(cn) != nil cnIsValidDomain := cn == "*" || len(validation.IsDNS1123Subdomain(strings.TrimPrefix(cn, "*."))) == 0 // don't use the CN if it is a valid IP because our IP serving detection may unexpectedly use it to terminate the connection. if !cnIsIP && cnIsValidDomain { diff --git a/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates_test.go b/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates_test.go index 56848723337..e240830608b 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates_test.go @@ -31,6 +31,8 @@ import ( "testing" "time" + netutils "k8s.io/utils/net" + "github.com/stretchr/testify/assert" ) @@ -246,7 +248,7 @@ NextTest: func parseIPList(ips []string) []net.IP { var netIPs []net.IP for _, ip := range ips { - netIPs = append(netIPs, net.ParseIP(ip)) + netIPs = append(netIPs, netutils.ParseIPSloppy(ip)) } return netIPs } @@ -302,7 +304,7 @@ func generateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS IsCA: true, } - if ip := net.ParseIP(host); ip != nil { + if ip := netutils.ParseIPSloppy(host); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, host) diff --git a/staging/src/k8s.io/apiserver/pkg/server/genericapiserver_test.go b/staging/src/k8s.io/apiserver/pkg/server/genericapiserver_test.go index 7a8f2a7f90b..17f8d810409 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/genericapiserver_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/genericapiserver_test.go @@ -54,6 +54,7 @@ import ( restclient "k8s.io/client-go/rest" kubeopenapi "k8s.io/kube-openapi/pkg/common" "k8s.io/kube-openapi/pkg/validation/spec" + netutils "k8s.io/utils/net" ) const ( @@ -127,7 +128,7 @@ func testGetOpenAPIDefinitions(_ kubeopenapi.ReferenceCallback) map[string]kubeo func setUp(t *testing.T) (Config, *assert.Assertions) { config := NewConfig(codecs) config.ExternalAddress = "192.168.10.4:443" - config.PublicAddress = net.ParseIP("192.168.10.4") + config.PublicAddress = netutils.ParseIPSloppy("192.168.10.4") config.LegacyAPIGroupPrefixes = sets.NewString("/api") config.LoopbackClientConfig = &restclient.Config{} diff --git a/staging/src/k8s.io/apiserver/pkg/server/options/server_run_options_test.go b/staging/src/k8s.io/apiserver/pkg/server/options/server_run_options_test.go index 871af5f909e..b5d0ecd8ef8 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/options/server_run_options_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/options/server_run_options_test.go @@ -17,12 +17,12 @@ limitations under the License. package options import ( - "net" "strings" "testing" "time" utilerrors "k8s.io/apimachinery/pkg/util/errors" + netutils "k8s.io/utils/net" ) func TestServerRunOptionsValidate(t *testing.T) { @@ -34,7 +34,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when MaxRequestsInFlight is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: -400, MaxMutatingRequestsInFlight: 200, @@ -48,7 +48,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when MaxMutatingRequestsInFlight is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: -200, @@ -62,7 +62,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when RequestTimeout is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -76,7 +76,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when MinRequestTimeout is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -90,7 +90,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when JSONPatchMaxCopyBytes is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -104,7 +104,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when MaxRequestBodyBytes is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -118,7 +118,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when LivezGracePeriod is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -133,7 +133,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when MinimalShutdownDuration is negative value", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, @@ -148,7 +148,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when HSTSHeaders is valid", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, HSTSDirectives: []string{"fakevalue", "includeSubDomains", "preload"}, MaxRequestsInFlight: 400, @@ -163,7 +163,7 @@ func TestServerRunOptionsValidate(t *testing.T) { { name: "Test when ServerRunOptions is valid", testOptions: &ServerRunOptions{ - AdvertiseAddress: net.ParseIP("192.168.10.10"), + AdvertiseAddress: netutils.ParseIPSloppy("192.168.10.10"), CorsAllowedOriginList: []string{"10.10.10.100", "10.10.10.200"}, HSTSDirectives: []string{"max-age=31536000", "includeSubDomains", "preload"}, MaxRequestsInFlight: 400, diff --git a/staging/src/k8s.io/apiserver/pkg/server/options/serving.go b/staging/src/k8s.io/apiserver/pkg/server/options/serving.go index f435ba5b8d9..c64798b4f96 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/options/serving.go +++ b/staging/src/k8s.io/apiserver/pkg/server/options/serving.go @@ -27,6 +27,7 @@ import ( "github.com/spf13/pflag" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apiserver/pkg/server" @@ -108,7 +109,7 @@ type GeneratableKeyCert struct { func NewSecureServingOptions() *SecureServingOptions { return &SecureServingOptions{ - BindAddress: net.ParseIP("0.0.0.0"), + BindAddress: netutils.ParseIPSloppy("0.0.0.0"), BindPort: 443, ServerCert: GeneratableKeyCert{ PairName: "apiserver", diff --git a/staging/src/k8s.io/apiserver/pkg/server/options/serving_test.go b/staging/src/k8s.io/apiserver/pkg/server/options/serving_test.go index 2e811653dee..f1ca80cb2e8 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/options/serving_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/options/serving_test.go @@ -44,6 +44,7 @@ import ( "k8s.io/client-go/discovery" restclient "k8s.io/client-go/rest" cliflag "k8s.io/component-base/cli/flag" + netutils "k8s.io/utils/net" ) func setUp(t *testing.T) server.Config { @@ -277,7 +278,7 @@ func TestServerRunWithSNI(t *testing.T) { config.EnableIndex = true secureOptions := (&SecureServingOptions{ - BindAddress: net.ParseIP("127.0.0.1"), + BindAddress: netutils.ParseIPSloppy("127.0.0.1"), BindPort: 6443, ServerCert: GeneratableKeyCert{ CertKey: CertKey{ @@ -381,7 +382,7 @@ func TestServerRunWithSNI(t *testing.T) { func parseIPList(ips []string) []net.IP { var netIPs []net.IP for _, ip := range ips { - netIPs = append(netIPs, net.ParseIP(ip)) + netIPs = append(netIPs, netutils.ParseIPSloppy(ip)) } return netIPs } @@ -488,7 +489,7 @@ func generateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS IsCA: true, } - if ip := net.ParseIP(host); ip != nil { + if ip := netutils.ParseIPSloppy(host); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, host) diff --git a/staging/src/k8s.io/apiserver/pkg/server/options/serving_with_loopback_test.go b/staging/src/k8s.io/apiserver/pkg/server/options/serving_with_loopback_test.go index f87b2fafe44..c4b0c57b568 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/options/serving_with_loopback_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/options/serving_with_loopback_test.go @@ -22,6 +22,7 @@ import ( "k8s.io/apiserver/pkg/server" "k8s.io/client-go/rest" + netutils "k8s.io/utils/net" ) func TestEmptyMainCert(t *testing.T) { @@ -29,7 +30,7 @@ func TestEmptyMainCert(t *testing.T) { var loopbackClientConfig *rest.Config s := (&SecureServingOptions{ - BindAddress: net.ParseIP("127.0.0.1"), + BindAddress: netutils.ParseIPSloppy("127.0.0.1"), }).WithLoopback() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { diff --git a/staging/src/k8s.io/client-go/tools/portforward/portforward.go b/staging/src/k8s.io/client-go/tools/portforward/portforward.go index ffc0bcac7d4..1c3985f3f71 100644 --- a/staging/src/k8s.io/client-go/tools/portforward/portforward.go +++ b/staging/src/k8s.io/client-go/tools/portforward/portforward.go @@ -28,9 +28,10 @@ import ( "strings" "sync" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/runtime" + netutils "k8s.io/utils/net" ) // PortForwardProtocolV1Name is the subprotocol used for port forwarding. @@ -131,9 +132,9 @@ func parseAddresses(addressesToParse []string) ([]listenAddress, error) { ip := listenAddress{address: "::1", protocol: "tcp6", failureMode: "all"} parsed[ip.address] = ip } - } else if net.ParseIP(address).To4() != nil { + } else if netutils.ParseIPSloppy(address).To4() != nil { parsed[address] = listenAddress{address: address, protocol: "tcp4", failureMode: "any"} - } else if net.ParseIP(address) != nil { + } else if netutils.ParseIPSloppy(address) != nil { parsed[address] = listenAddress{address: address, protocol: "tcp6", failureMode: "any"} } else { return nil, fmt.Errorf("%s is not a valid IP", address) diff --git a/staging/src/k8s.io/client-go/util/cert/cert.go b/staging/src/k8s.io/client-go/util/cert/cert.go index bffb1526272..75143ec0717 100644 --- a/staging/src/k8s.io/client-go/util/cert/cert.go +++ b/staging/src/k8s.io/client-go/util/cert/cert.go @@ -33,6 +33,7 @@ import ( "time" "k8s.io/client-go/util/keyutil" + netutils "k8s.io/utils/net" ) const duration365d = time.Hour * 24 * 365 @@ -157,7 +158,7 @@ func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, a BasicConstraintsValid: true, } - if ip := net.ParseIP(host); ip != nil { + if ip := netutils.ParseIPSloppy(host); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, host) diff --git a/staging/src/k8s.io/client-go/util/cert/csr_test.go b/staging/src/k8s.io/client-go/util/cert/csr_test.go index d546ec792f5..e81f25e9047 100644 --- a/staging/src/k8s.io/client-go/util/cert/csr_test.go +++ b/staging/src/k8s.io/client-go/util/cert/csr_test.go @@ -25,6 +25,7 @@ import ( "testing" "k8s.io/client-go/util/keyutil" + netutils "k8s.io/utils/net" ) func TestMakeCSR(t *testing.T) { @@ -33,7 +34,7 @@ func TestMakeCSR(t *testing.T) { CommonName: "kube-worker", } dnsSANs := []string{"localhost"} - ipSANs := []net.IP{net.ParseIP("127.0.0.1")} + ipSANs := []net.IP{netutils.ParseIPSloppy("127.0.0.1")} keyData, err := ioutil.ReadFile(keyFile) if err != nil { diff --git a/staging/src/k8s.io/client-go/util/certificate/certificate_manager_test.go b/staging/src/k8s.io/client-go/util/certificate/certificate_manager_test.go index baced0ab201..291c72452be 100644 --- a/staging/src/k8s.io/client-go/util/certificate/certificate_manager_test.go +++ b/staging/src/k8s.io/client-go/util/certificate/certificate_manager_test.go @@ -38,6 +38,7 @@ import ( "k8s.io/client-go/kubernetes/fake" certificatesclient "k8s.io/client-go/kubernetes/typed/certificates/v1beta1" clienttesting "k8s.io/client-go/testing" + netutils "k8s.io/utils/net" ) var storeCertData = newCertificateData(`-----BEGIN CERTIFICATE----- @@ -394,11 +395,11 @@ func TestCertSatisfiesTemplate(t *testing.T) { name: "Missing IP addresses in certificate", cert: &x509.Certificate{ Subject: pkix.Name{}, - IPAddresses: []net.IP{net.ParseIP("192.168.1.1")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("192.168.1.1")}, }, template: &x509.CertificateRequest{ Subject: pkix.Name{}, - IPAddresses: []net.IP{net.ParseIP("192.168.1.1"), net.ParseIP("192.168.1.2")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("192.168.1.1"), netutils.ParseIPSloppy("192.168.1.2")}, }, shouldSatisfy: false, }, @@ -406,11 +407,11 @@ func TestCertSatisfiesTemplate(t *testing.T) { name: "Extra IP addresses in certificate", cert: &x509.Certificate{ Subject: pkix.Name{}, - IPAddresses: []net.IP{net.ParseIP("192.168.1.1"), net.ParseIP("192.168.1.2")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("192.168.1.1"), netutils.ParseIPSloppy("192.168.1.2")}, }, template: &x509.CertificateRequest{ Subject: pkix.Name{}, - IPAddresses: []net.IP{net.ParseIP("192.168.1.1")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("192.168.1.1")}, }, shouldSatisfy: true, }, @@ -422,7 +423,7 @@ func TestCertSatisfiesTemplate(t *testing.T) { Organization: []string{"system:nodes"}, }, DNSNames: []string{"foo.example.com"}, - IPAddresses: []net.IP{net.ParseIP("192.168.1.1")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("192.168.1.1")}, }, template: &x509.CertificateRequest{ Subject: pkix.Name{ @@ -430,7 +431,7 @@ func TestCertSatisfiesTemplate(t *testing.T) { Organization: []string{"system:nodes"}, }, DNSNames: []string{"foo.example.com"}, - IPAddresses: []net.IP{net.ParseIP("192.168.1.1")}, + IPAddresses: []net.IP{netutils.ParseIPSloppy("192.168.1.1")}, }, shouldSatisfy: true, }, diff --git a/staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go b/staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go index 6f934223144..a594b1c71c1 100644 --- a/staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go +++ b/staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go @@ -24,8 +24,9 @@ import ( "time" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" @@ -340,7 +341,7 @@ func (rc *RouteController) updateNetworkingCondition(node *v1.Node, routesCreate } func (rc *RouteController) isResponsibleForRoute(route *cloudprovider.Route) bool { - _, cidr, err := net.ParseCIDR(route.DestinationCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(route.DestinationCIDR) if err != nil { klog.Errorf("Ignoring route %s, unparsable CIDR: %v", route.Name, err) return false diff --git a/staging/src/k8s.io/cloud-provider/controllers/route/route_controller_test.go b/staging/src/k8s.io/cloud-provider/controllers/route/route_controller_test.go index 44b1489ea3c..9f0cc3c084b 100644 --- a/staging/src/k8s.io/cloud-provider/controllers/route/route_controller_test.go +++ b/staging/src/k8s.io/cloud-provider/controllers/route/route_controller_test.go @@ -22,7 +22,7 @@ import ( "testing" "time" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/informers" @@ -31,6 +31,7 @@ import ( cloudprovider "k8s.io/cloud-provider" fakecloud "k8s.io/cloud-provider/fake" cloudnodeutil "k8s.io/cloud-provider/node/helpers" + netutils "k8s.io/utils/net" ) func alwaysReady() bool { return true } @@ -60,7 +61,7 @@ func TestIsResponsibleForRoute(t *testing.T) { {"a00:100::/10", myClusterRoute, "b00:100::/24", false}, } for i, testCase := range testCases { - _, cidr, err := net.ParseCIDR(testCase.clusterCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(testCase.clusterCIDR) if err != nil { t.Errorf("%d. Error in test case: unparsable cidr %q", i, testCase.clusterCIDR) } @@ -359,10 +360,10 @@ func TestReconcile(t *testing.T) { t.Error("Error in test: fakecloud doesn't support Routes()") } cidrs := make([]*net.IPNet, 0) - _, cidr, _ := net.ParseCIDR("10.120.0.0/16") + _, cidr, _ := netutils.ParseCIDRSloppy("10.120.0.0/16") cidrs = append(cidrs, cidr) if testCase.dualStack { - _, cidrv6, _ := net.ParseCIDR("ace:cab:deca::/8") + _, cidrv6, _ := netutils.ParseCIDRSloppy("ace:cab:deca::/8") cidrs = append(cidrs, cidrv6) } diff --git a/staging/src/k8s.io/cloud-provider/options/options.go b/staging/src/k8s.io/cloud-provider/options/options.go index bc7940b7312..1371600c827 100644 --- a/staging/src/k8s.io/cloud-provider/options/options.go +++ b/staging/src/k8s.io/cloud-provider/options/options.go @@ -42,6 +42,7 @@ import ( cliflag "k8s.io/component-base/cli/flag" cmoptions "k8s.io/controller-manager/options" "k8s.io/controller-manager/pkg/clientbuilder" + netutils "k8s.io/utils/net" // add the related feature gates _ "k8s.io/controller-manager/pkg/features/register" @@ -88,7 +89,7 @@ func NewCloudControllerManagerOptions() (*CloudControllerManagerOptions, error) }, SecureServing: apiserveroptions.NewSecureServingOptions().WithLoopback(), InsecureServing: (&apiserveroptions.DeprecatedInsecureServingOptions{ - BindAddress: net.ParseIP(componentConfig.Generic.Address), + BindAddress: netutils.ParseIPSloppy(componentConfig.Generic.Address), BindPort: int(componentConfig.Generic.Port), BindNetwork: "tcp", }).WithLoopback(), @@ -247,7 +248,7 @@ func (o *CloudControllerManagerOptions) Config(allControllers, disabledByDefault return nil, err } - if err := o.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil { + if err := o.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil { return nil, fmt.Errorf("error creating self-signed certificates: %v", err) } diff --git a/staging/src/k8s.io/cloud-provider/options/options_test.go b/staging/src/k8s.io/cloud-provider/options/options_test.go index 70c91c21454..bc5efdba206 100644 --- a/staging/src/k8s.io/cloud-provider/options/options_test.go +++ b/staging/src/k8s.io/cloud-provider/options/options_test.go @@ -17,7 +17,6 @@ limitations under the License. package options import ( - "net" "reflect" "testing" "time" @@ -32,6 +31,7 @@ import ( cmconfig "k8s.io/controller-manager/config" cmoptions "k8s.io/controller-manager/options" migration "k8s.io/controller-manager/pkg/leadermigration/options" + netutils "k8s.io/utils/net" ) func TestDefaultFlags(t *testing.T) { @@ -92,7 +92,7 @@ func TestDefaultFlags(t *testing.T) { }, SecureServing: (&apiserveroptions.SecureServingOptions{ BindPort: 10258, - BindAddress: net.ParseIP("0.0.0.0"), + BindAddress: netutils.ParseIPSloppy("0.0.0.0"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "", PairName: "cloud-controller-manager", @@ -100,7 +100,7 @@ func TestDefaultFlags(t *testing.T) { HTTP2MaxStreamsPerConnection: 0, }).WithLoopback(), InsecureServing: (&apiserveroptions.DeprecatedInsecureServingOptions{ - BindAddress: net.ParseIP("0.0.0.0"), + BindAddress: netutils.ParseIPSloppy("0.0.0.0"), BindPort: int(0), BindNetwork: "tcp", }).WithLoopback(), @@ -231,7 +231,7 @@ func TestAddFlags(t *testing.T) { }, SecureServing: (&apiserveroptions.SecureServingOptions{ BindPort: 10001, - BindAddress: net.ParseIP("192.168.4.21"), + BindAddress: netutils.ParseIPSloppy("192.168.4.21"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/a/b/c", PairName: "cloud-controller-manager", @@ -239,7 +239,7 @@ func TestAddFlags(t *testing.T) { HTTP2MaxStreamsPerConnection: 47, }).WithLoopback(), InsecureServing: (&apiserveroptions.DeprecatedInsecureServingOptions{ - BindAddress: net.ParseIP("192.168.4.10"), + BindAddress: netutils.ParseIPSloppy("192.168.4.10"), BindPort: int(10000), BindNetwork: "tcp", }).WithLoopback(), diff --git a/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go b/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go index 0ba278fcefe..f4a6ddd6c5d 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go +++ b/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "net" "path" "regexp" "sort" @@ -50,6 +49,7 @@ import ( "gopkg.in/gcfg.v1" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -1583,7 +1583,7 @@ func extractNodeAddresses(instance *ec2.Instance) ([]v1.NodeAddress, error) { for _, internalIP := range networkInterface.PrivateIpAddresses { if ipAddress := aws.StringValue(internalIP.PrivateIpAddress); ipAddress != "" { - ip := net.ParseIP(ipAddress) + ip := netutils.ParseIPSloppy(ipAddress) if ip == nil { return nil, fmt.Errorf("EC2 instance had invalid private address: %s (%q)", aws.StringValue(instance.InstanceId), ipAddress) } @@ -1595,7 +1595,7 @@ func extractNodeAddresses(instance *ec2.Instance) ([]v1.NodeAddress, error) { // TODO: Other IP addresses (multiple ips)? publicIPAddress := aws.StringValue(instance.PublicIpAddress) if publicIPAddress != "" { - ip := net.ParseIP(publicIPAddress) + ip := netutils.ParseIPSloppy(publicIPAddress) if ip == nil { return nil, fmt.Errorf("EC2 instance had invalid public address: %s (%s)", aws.StringValue(instance.InstanceId), publicIPAddress) } diff --git a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go index 5e4bb55f817..edce6b41cec 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go +++ b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go @@ -22,20 +22,19 @@ import ( "context" "flag" "fmt" - "net" "sort" "strings" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" "github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud" cloudprovider "k8s.io/cloud-provider" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) type cidrs struct { - ipn utilnet.IPNetSet + ipn netutils.IPNetSet isSet bool } @@ -47,12 +46,12 @@ var ( func init() { var err error // L3/4 health checkers have client addresses within these known CIDRs. - l4LbSrcRngsFlag.ipn, err = utilnet.ParseIPNets([]string{"130.211.0.0/22", "35.191.0.0/16", "209.85.152.0/22", "209.85.204.0/22"}...) + l4LbSrcRngsFlag.ipn, err = netutils.ParseIPNets([]string{"130.211.0.0/22", "35.191.0.0/16", "209.85.152.0/22", "209.85.204.0/22"}...) if err != nil { panic("Incorrect default GCE L3/4 source ranges") } // L7 health checkers have client addresses within these known CIDRs. - l7lbSrcRngsFlag.ipn, err = utilnet.ParseIPNets([]string{"130.211.0.0/22", "35.191.0.0/16"}...) + l7lbSrcRngsFlag.ipn, err = netutils.ParseIPNets([]string{"130.211.0.0/22", "35.191.0.0/16"}...) if err != nil { panic("Incorrect default GCE L7 source ranges") } @@ -73,13 +72,13 @@ func (c *cidrs) Set(value string) error { // On first Set(), clear the original defaults if !c.isSet { c.isSet = true - c.ipn = make(utilnet.IPNetSet) + c.ipn = make(netutils.IPNetSet) } else { return fmt.Errorf("GCE LB CIDRs have already been set") } for _, cidr := range strings.Split(value, ",") { - _, ipnet, err := net.ParseCIDR(cidr) + _, ipnet, err := netutils.ParseCIDRSloppy(cidr) if err != nil { return err } diff --git a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go index fd2989a3adc..1e402c074b0 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go +++ b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go @@ -38,12 +38,13 @@ import ( compute "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes/fake" v1core "k8s.io/client-go/kubernetes/typed/core/v1" servicehelper "k8s.io/cloud-provider/service/helpers" + netutils "k8s.io/utils/net" ) func fakeGCECloud(vals TestClusterValues) (*Cloud, error) { @@ -120,7 +121,7 @@ type gceInstance struct { var ( autoSubnetIPRange = &net.IPNet{ - IP: net.ParseIP("10.128.0.0"), + IP: netutils.ParseIPSloppy("10.128.0.0"), Mask: net.CIDRMask(9, 32), } ) @@ -305,7 +306,7 @@ func lastIPInRange(cidr *net.IPNet) net.IP { func subnetsInCIDR(subnets []*compute.Subnetwork, cidr *net.IPNet) ([]*compute.Subnetwork, error) { var res []*compute.Subnetwork for _, subnet := range subnets { - _, subnetRange, err := net.ParseCIDR(subnet.IpCidrRange) + _, subnetRange, err := netutils.ParseCIDRSloppy(subnet.IpCidrRange) if err != nil { return nil, fmt.Errorf("unable to parse CIDR %q for subnet %q: %v", subnet.IpCidrRange, subnet.Name, err) } diff --git a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util_test.go b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util_test.go index dce79beeb13..95396ca869d 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util_test.go +++ b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_util_test.go @@ -20,12 +20,12 @@ package gce import ( "context" - "net" "reflect" "testing" compute "google.golang.org/api/compute/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + netutils "k8s.io/utils/net" ) func TestLastIPInRange(t *testing.T) { @@ -42,7 +42,7 @@ func TestLastIPInRange(t *testing.T) { {"::0/126", "::3"}, {"::0/120", "::ff"}, } { - _, c, err := net.ParseCIDR(tc.cidr) + _, c, err := netutils.ParseCIDRSloppy(tc.cidr) if err != nil { t.Errorf("can't parse CIDR %v = _, %v, %v; want nil", tc.cidr, c, err) continue diff --git a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack.go b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack.go index 3dda71948ab..0462b2dd2a1 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack.go +++ b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack.go @@ -25,7 +25,6 @@ import ( "fmt" "io" "io/ioutil" - "net" "net/http" "os" "reflect" @@ -53,6 +52,7 @@ import ( cloudprovider "k8s.io/cloud-provider" nodehelpers "k8s.io/cloud-provider/node/helpers" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) const ( @@ -642,14 +642,14 @@ func getAddressByName(client *gophercloud.ServiceClient, name types.NodeName, ne } for _, addr := range addrs { - isIPv6 := net.ParseIP(addr.Address).To4() == nil + isIPv6 := netutils.ParseIPSloppy(addr.Address).To4() == nil if (addr.Type == v1.NodeInternalIP) && (isIPv6 == needIPv6) { return addr.Address, nil } } for _, addr := range addrs { - isIPv6 := net.ParseIP(addr.Address).To4() == nil + isIPv6 := netutils.ParseIPSloppy(addr.Address).To4() == nil if (addr.Type == v1.NodeExternalIP) && (isIPv6 == needIPv6) { return addr.Address, nil } diff --git a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_loadbalancer.go b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_loadbalancer.go index 73d33fa46e0..d891b59b085 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_loadbalancer.go +++ b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_loadbalancer.go @@ -21,7 +21,6 @@ package openstack import ( "context" "fmt" - "net" "reflect" "strings" "time" @@ -40,6 +39,7 @@ import ( neutronports "github.com/gophercloud/gophercloud/openstack/networking/v2/ports" "github.com/gophercloud/gophercloud/pagination" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -1059,7 +1059,7 @@ func (lbaas *LbaasV2) ensureSecurityGroup(clusterName string, apiService *v1.Ser for _, port := range ports { for _, sourceRange := range sourceRanges.StringSlice() { ethertype := rules.EtherType4 - network, _, err := net.ParseCIDR(sourceRange) + network, _, err := netutils.ParseCIDRSloppy(sourceRange) if err != nil { return fmt.Errorf("error parsing source range %s as a CIDR: %v", sourceRange, err) diff --git a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes.go b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes.go index de8eb08ac75..6fcbaf2cc9f 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes.go +++ b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes.go @@ -21,7 +21,6 @@ package openstack import ( "context" "errors" - "net" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" @@ -31,6 +30,7 @@ import ( "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" ) var errNoRouterID = errors.New("router-id not set in cloud provider config") @@ -154,7 +154,7 @@ func (r *Routes) CreateRoute(ctx context.Context, clusterName string, nameHint s onFailure := newCaller() - ip, _, _ := net.ParseCIDR(route.DestinationCIDR) + ip, _, _ := netutils.ParseCIDRSloppy(route.DestinationCIDR) isCIDRv6 := ip.To4() == nil addr, err := getAddressByName(r.compute, route.TargetNode, isCIDRv6) @@ -230,7 +230,7 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo onFailure := newCaller() - ip, _, _ := net.ParseCIDR(route.DestinationCIDR) + ip, _, _ := netutils.ParseCIDRSloppy(route.DestinationCIDR) isCIDRv6 := ip.To4() == nil var addr string diff --git a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes_test.go b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes_test.go index db180838fcc..a4db15406c2 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes_test.go +++ b/staging/src/k8s.io/legacy-cloud-providers/openstack/openstack_routes_test.go @@ -20,13 +20,13 @@ package openstack import ( "context" - "net" "testing" "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/routers" "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" + netutils "k8s.io/utils/net" ) func TestRoutes(t *testing.T) { @@ -73,7 +73,7 @@ func TestRoutes(t *testing.T) { t.Fatalf("ListRoutes() error: %v", err) } for _, route := range routelist { - _, cidr, err := net.ParseCIDR(route.DestinationCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(route.DestinationCIDR) if err != nil { t.Logf("Ignoring route %s, unparsable CIDR: %v", route.Name, err) continue diff --git a/staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go b/staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go index 59160e2a7ec..41463a035e1 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go +++ b/staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go @@ -52,6 +52,7 @@ import ( volerr "k8s.io/cloud-provider/volume/errors" volumehelpers "k8s.io/cloud-provider/volume/helpers" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" "k8s.io/legacy-cloud-providers/vsphere/vclib" "k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers" @@ -718,7 +719,7 @@ func (vs *VSphere) getNodeAddressesFromVM(ctx context.Context, nodeName k8stypes for _, v := range vmMoList[0].Guest.Net { if vs.cfg.Network.PublicNetwork == v.Network { for _, ip := range v.IpAddress { - if !net.ParseIP(ip).IsLinkLocalUnicast() { + if !netutils.ParseIPSloppy(ip).IsLinkLocalUnicast() { nodehelpers.AddToNodeAddresses(&addrs, v1.NodeAddress{ Type: v1.NodeExternalIP, diff --git a/staging/src/k8s.io/sample-apiserver/pkg/cmd/server/start.go b/staging/src/k8s.io/sample-apiserver/pkg/cmd/server/start.go index c3a21389aa2..7683490f9fc 100644 --- a/staging/src/k8s.io/sample-apiserver/pkg/cmd/server/start.go +++ b/staging/src/k8s.io/sample-apiserver/pkg/cmd/server/start.go @@ -39,6 +39,7 @@ import ( clientset "k8s.io/sample-apiserver/pkg/generated/clientset/versioned" informers "k8s.io/sample-apiserver/pkg/generated/informers/externalversions" sampleopenapi "k8s.io/sample-apiserver/pkg/generated/openapi" + netutils "k8s.io/utils/net" ) const defaultEtcdPathPrefix = "/registry/wardle.example.com" @@ -116,7 +117,7 @@ func (o *WardleServerOptions) Complete() error { // Config returns config for the api server given WardleServerOptions func (o *WardleServerOptions) Config() (*apiserver.Config, error) { // TODO have a "real" external address - if err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil { + if err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil { return nil, fmt.Errorf("error creating self-signed certificates: %v", err) } diff --git a/test/e2e/framework/ingress/ingress_utils.go b/test/e2e/framework/ingress/ingress_utils.go index 4ca56738f02..50673171e43 100644 --- a/test/e2e/framework/ingress/ingress_utils.go +++ b/test/e2e/framework/ingress/ingress_utils.go @@ -38,6 +38,7 @@ import ( compute "google.golang.org/api/compute/v1" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" @@ -332,7 +333,7 @@ func GenerateRSACerts(host string, isCA bool) ([]byte, []byte, error) { hosts := strings.Split(host, ",") for _, h := range hosts { - if ip := net.ParseIP(h); ip != nil { + if ip := netutils.ParseIPSloppy(h); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, h) diff --git a/test/e2e/framework/service/jig.go b/test/e2e/framework/service/jig.go index 13175e98725..1fa21f6860c 100644 --- a/test/e2e/framework/service/jig.go +++ b/test/e2e/framework/service/jig.go @@ -48,7 +48,7 @@ import ( e2erc "k8s.io/kubernetes/test/e2e/framework/rc" testutils "k8s.io/kubernetes/test/utils" imageutils "k8s.io/kubernetes/test/utils/image" - utilsnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) // NodePortRange should match whatever the default/configured range is @@ -821,7 +821,7 @@ func testReachabilityOverServiceName(serviceName string, sp v1.ServicePort, exec func testReachabilityOverClusterIP(clusterIP string, sp v1.ServicePort, execPod *v1.Pod) error { // If .spec.clusterIP is set to "" or "None" for service, ClusterIP is not created, so reachability can not be tested over clusterIP:servicePort - if net.ParseIP(clusterIP) == nil { + if netutils.ParseIPSloppy(clusterIP) == nil { return fmt.Errorf("unable to parse ClusterIP: %s", clusterIP) } return testEndpointReachability(clusterIP, sp.Port, sp.Protocol, execPod) @@ -833,7 +833,7 @@ func testReachabilityOverExternalIP(externalIP string, sp v1.ServicePort, execPo func testReachabilityOverNodePorts(nodes *v1.NodeList, sp v1.ServicePort, pod *v1.Pod, clusterIP string, externalIPs bool) error { internalAddrs := e2enode.CollectAddresses(nodes, v1.NodeInternalIP) - isClusterIPV4 := utilsnet.IsIPv4String(clusterIP) + isClusterIPV4 := netutils.IsIPv4String(clusterIP) for _, internalAddr := range internalAddrs { // If the node's internal address points to localhost, then we are not @@ -843,7 +843,7 @@ func testReachabilityOverNodePorts(nodes *v1.NodeList, sp v1.ServicePort, pod *v continue } // Check service reachability on the node internalIP which is same family as clusterIP - if isClusterIPV4 != utilsnet.IsIPv4String(internalAddr) { + if isClusterIPV4 != netutils.IsIPv4String(internalAddr) { framework.Logf("skipping testEndpointReachability() for internal adddress %s as it does not match clusterIP (%s) family", internalAddr, clusterIP) continue } @@ -856,7 +856,7 @@ func testReachabilityOverNodePorts(nodes *v1.NodeList, sp v1.ServicePort, pod *v if externalIPs { externalAddrs := e2enode.CollectAddresses(nodes, v1.NodeExternalIP) for _, externalAddr := range externalAddrs { - if isClusterIPV4 != utilsnet.IsIPv4String(externalAddr) { + if isClusterIPV4 != netutils.IsIPv4String(externalAddr) { framework.Logf("skipping testEndpointReachability() for external adddress %s as it does not match clusterIP (%s) family", externalAddr, clusterIP) continue } @@ -872,7 +872,7 @@ func testReachabilityOverNodePorts(nodes *v1.NodeList, sp v1.ServicePort, pod *v // isInvalidOrLocalhostAddress returns `true` if the provided `ip` is either not // parsable or the loopback address. Otherwise it will return `false`. func isInvalidOrLocalhostAddress(ip string) bool { - parsedIP := net.ParseIP(ip) + parsedIP := netutils.ParseIPSloppy(ip) if parsedIP == nil || parsedIP.IsLoopback() { return true } diff --git a/test/e2e/framework/util.go b/test/e2e/framework/util.go index 2040604a816..c14b86c9266 100644 --- a/test/e2e/framework/util.go +++ b/test/e2e/framework/util.go @@ -63,6 +63,7 @@ import ( testutils "k8s.io/kubernetes/test/utils" imageutils "k8s.io/kubernetes/test/utils/image" uexec "k8s.io/utils/exec" + netutils "k8s.io/utils/net" // TODO: Remove the following imports (ref: https://github.com/kubernetes/kubernetes/issues/81245) e2ekubectl "k8s.io/kubernetes/test/e2e/framework/kubectl" @@ -1265,7 +1266,7 @@ func getControlPlaneAddresses(c clientset.Interface) ([]string, []string, []stri if err != nil { Failf("Failed to parse hostname: %v", err) } - if net.ParseIP(hostURL.Host) != nil { + if netutils.ParseIPSloppy(hostURL.Host) != nil { externalIPs = append(externalIPs, hostURL.Host) } else { hostnames = append(hostnames, hostURL.Host) diff --git a/test/e2e/network/netpol/kubemanager.go b/test/e2e/network/netpol/kubemanager.go index d6c786df27c..ddb0ee3e345 100644 --- a/test/e2e/network/netpol/kubemanager.go +++ b/test/e2e/network/netpol/kubemanager.go @@ -24,6 +24,7 @@ import ( "strings" e2epod "k8s.io/kubernetes/test/e2e/framework/pod" + netutils "k8s.io/utils/net" v1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" @@ -73,7 +74,7 @@ func (k *kubeManager) initializeCluster(model *Model) error { if err != nil { return err } - if net.ParseIP(svc.Spec.ClusterIP) == nil { + if netutils.ParseIPSloppy(svc.Spec.ClusterIP) == nil { return fmt.Errorf("empty IP address found for service %s/%s", svc.Namespace, svc.Name) } pod.ServiceIP = svc.Spec.ClusterIP diff --git a/test/e2e/network/netpol/network_legacy.go b/test/e2e/network/netpol/network_legacy.go index fb52460560c..2956e3da876 100644 --- a/test/e2e/network/netpol/network_legacy.go +++ b/test/e2e/network/netpol/network_legacy.go @@ -20,13 +20,14 @@ import ( "context" "encoding/json" "fmt" - "k8s.io/kubernetes/test/e2e/storage/utils" "net" "regexp" "strconv" "strings" "time" + "k8s.io/kubernetes/test/e2e/storage/utils" + "github.com/onsi/ginkgo" v1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" @@ -42,7 +43,7 @@ import ( e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper" "k8s.io/kubernetes/test/e2e/network/common" imageutils "k8s.io/kubernetes/test/utils/image" - utilnet "k8s.io/utils/net" + netutils "k8s.io/utils/net" ) /* @@ -1346,7 +1347,7 @@ var _ = common.SIGDescribe("NetworkPolicyLegacy [LinuxOnly]", func() { framework.ExpectNoError(err, "Error occurred while getting pod status.") } hostMask := 32 - if utilnet.IsIPv6String(podServerStatus.Status.PodIP) { + if netutils.IsIPv6String(podServerStatus.Status.PodIP) { hostMask = 128 } podServerCIDR := fmt.Sprintf("%s/%d", podServerStatus.Status.PodIP, hostMask) @@ -1416,11 +1417,11 @@ var _ = common.SIGDescribe("NetworkPolicyLegacy [LinuxOnly]", func() { allowMask := 24 hostMask := 32 - if utilnet.IsIPv6String(podServerStatus.Status.PodIP) { + if netutils.IsIPv6String(podServerStatus.Status.PodIP) { allowMask = 64 hostMask = 128 } - _, podServerAllowSubnet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", podServerStatus.Status.PodIP, allowMask)) + _, podServerAllowSubnet, err := netutils.ParseCIDRSloppy(fmt.Sprintf("%s/%d", podServerStatus.Status.PodIP, allowMask)) framework.ExpectNoError(err, "could not parse allow subnet") podServerAllowCIDR := podServerAllowSubnet.String() @@ -1479,11 +1480,11 @@ var _ = common.SIGDescribe("NetworkPolicyLegacy [LinuxOnly]", func() { allowMask := 24 hostMask := 32 - if utilnet.IsIPv6String(podServerStatus.Status.PodIP) { + if netutils.IsIPv6String(podServerStatus.Status.PodIP) { allowMask = 64 hostMask = 128 } - _, podServerAllowSubnet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", podServerStatus.Status.PodIP, allowMask)) + _, podServerAllowSubnet, err := netutils.ParseCIDRSloppy(fmt.Sprintf("%s/%d", podServerStatus.Status.PodIP, allowMask)) framework.ExpectNoError(err, "could not parse allow subnet") podServerAllowCIDR := podServerAllowSubnet.String() diff --git a/test/e2e/network/netpol/probe.go b/test/e2e/network/netpol/probe.go index 9073703eea8..2bd2fa78fc3 100644 --- a/test/e2e/network/netpol/probe.go +++ b/test/e2e/network/netpol/probe.go @@ -18,11 +18,11 @@ package netpol import ( "fmt" - "net" "github.com/onsi/ginkgo" v1 "k8s.io/api/core/v1" "k8s.io/kubernetes/test/e2e/framework" + netutils "k8s.io/utils/net" ) // decouple us from k8smanager.go @@ -95,7 +95,7 @@ func probeWorker(prober Prober, jobs <-chan *ProbeJob, results chan<- *ProbeJobR defer ginkgo.GinkgoRecover() for job := range jobs { podFrom := job.PodFrom - if net.ParseIP(job.PodTo.ServiceIP) == nil { + if netutils.ParseIPSloppy(job.PodTo.ServiceIP) == nil { results <- &ProbeJobResults{ Job: job, IsConnected: false, diff --git a/test/e2e_kubeadm/networking_test.go b/test/e2e_kubeadm/networking_test.go index 97bd66e19a5..3dd08c5af9c 100644 --- a/test/e2e_kubeadm/networking_test.go +++ b/test/e2e_kubeadm/networking_test.go @@ -18,12 +18,12 @@ package kubeadm import ( "context" - "net" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/kubernetes/test/e2e/framework" e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper" + netutils "k8s.io/utils/net" "github.com/onsi/ginkgo" ) @@ -163,14 +163,14 @@ var _ = Describe("networking [setup-networking]", func() { // ipWithinSubnet returns true if an IP (targetIP) falls within the reference subnet (refIPNet) func ipWithinSubnet(refIPNet, targetIP string) bool { - _, rNet, _ := net.ParseCIDR(refIPNet) - tIP := net.ParseIP(targetIP) + _, rNet, _ := netutils.ParseCIDRSloppy(refIPNet) + tIP := netutils.ParseIPSloppy(targetIP) return rNet.Contains(tIP) } // subnetWithinSubnet returns true if a subnet (targetNet) falls within the reference subnet (refIPNet) func subnetWithinSubnet(refIPNet, targetNet string) bool { - _, rNet, _ := net.ParseCIDR(refIPNet) - tNet, _, _ := net.ParseCIDR(targetNet) + _, rNet, _ := netutils.ParseCIDRSloppy(refIPNet) + tNet, _, _ := netutils.ParseCIDRSloppy(targetNet) return rNet.Contains(tNet) } diff --git a/test/e2e_node/services/apiserver.go b/test/e2e_node/services/apiserver.go index 4a37dd18995..7d2ab8c578f 100644 --- a/test/e2e_node/services/apiserver.go +++ b/test/e2e_node/services/apiserver.go @@ -19,10 +19,10 @@ package services import ( "fmt" "io/ioutil" - "net" "os" "k8s.io/apiserver/pkg/storage/storagebackend" + netutils "k8s.io/utils/net" utilerrors "k8s.io/apimachinery/pkg/util/errors" apiserver "k8s.io/kubernetes/cmd/kube-apiserver/app" @@ -60,14 +60,14 @@ func (a *APIServer) Start() error { o := options.NewServerRunOptions() o.Etcd.StorageConfig = a.storageConfig - _, ipnet, err := net.ParseCIDR(clusterIPRange) + _, ipnet, err := netutils.ParseCIDRSloppy(clusterIPRange) if err != nil { return err } if len(framework.TestContext.RuntimeConfig) > 0 { o.APIEnablement.RuntimeConfig = framework.TestContext.RuntimeConfig } - o.SecureServing.BindAddress = net.ParseIP("127.0.0.1") + o.SecureServing.BindAddress = netutils.ParseIPSloppy("127.0.0.1") o.ServiceClusterIPRanges = ipnet.String() o.AllowPrivileged = true if err := generateTokenFile(tokenFilePath); err != nil { diff --git a/test/images/agnhost/netexec/netexec.go b/test/images/agnhost/netexec/netexec.go index acf4a52aac9..18619b4f502 100644 --- a/test/images/agnhost/netexec/netexec.go +++ b/test/images/agnhost/netexec/netexec.go @@ -38,6 +38,7 @@ import ( utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/util/sets" + netutils "k8s.io/utils/net" ) var ( @@ -660,7 +661,7 @@ func parseAddresses(addresses string) ([]string, error) { res := make([]string, 0) split := strings.Split(addresses, ",") for _, address := range split { - netAddr := net.ParseIP(address) + netAddr := netutils.ParseIPSloppy(address) if netAddr == nil { return nil, fmt.Errorf("parseAddress: invalid address %s", address) } diff --git a/test/images/agnhost/no-snat-test/main.go b/test/images/agnhost/no-snat-test/main.go index da534743c4d..bfc520d5e5c 100644 --- a/test/images/agnhost/no-snat-test/main.go +++ b/test/images/agnhost/no-snat-test/main.go @@ -19,13 +19,13 @@ package nosnat import ( "fmt" "io/ioutil" - "net" "net/http" "os" "strings" "github.com/spf13/cobra" "k8s.io/component-base/logs" + netutils "k8s.io/utils/net" ) // CmdNoSnatTest is used by agnhost Cobra. @@ -83,10 +83,10 @@ func (m *masqTester) Run() error { } // validate that pip and nip are ip addresses. - if net.ParseIP(pip) == nil { + if netutils.ParseIPSloppy(pip) == nil { return fmt.Errorf("POD_IP env var contained %q, which is not an IP address", pip) } - if net.ParseIP(nip) == nil { + if netutils.ParseIPSloppy(nip) == nil { return fmt.Errorf("NODE_IP env var contained %q, which is not an IP address", nip) } diff --git a/test/images/regression-issue-74839/main.go b/test/images/regression-issue-74839/main.go index 19065e98056..f2d3d8a62a0 100644 --- a/test/images/regression-issue-74839/main.go +++ b/test/images/regression-issue-74839/main.go @@ -23,6 +23,8 @@ import ( "os" "strings" "time" + + netutils "k8s.io/utils/net" ) // TCP port to listen @@ -120,8 +122,8 @@ func probe(ip string) { } data := []byte("boom!!!") - remoteIP := net.ParseIP(addr.String()) - localIP := net.ParseIP(conn.LocalAddr().String()) + remoteIP := netutils.ParseIPSloppy(addr.String()) + localIP := netutils.ParseIPSloppy(conn.LocalAddr().String()) _, err := conn.WriteTo(badPkt.encode(localIP, remoteIP, data[:]), addr) if err != nil { log.Printf("conn.WriteTo() error: %v", err) @@ -141,10 +143,10 @@ func getIPs() []net.IP { podIP, podIPs := os.Getenv("POD_IP"), os.Getenv("POD_IPS") if podIPs != "" { for _, ip := range strings.Split(podIPs, ",") { - ips = append(ips, net.ParseIP(ip)) + ips = append(ips, netutils.ParseIPSloppy(ip)) } } else if podIP != "" { - ips = append(ips, net.ParseIP(podIP)) + ips = append(ips, netutils.ParseIPSloppy(podIP)) } return ips } diff --git a/test/integration/controlplane/synthetic_controlplane_test.go b/test/integration/controlplane/synthetic_controlplane_test.go index 45b1aaf8037..a37d255cdf2 100644 --- a/test/integration/controlplane/synthetic_controlplane_test.go +++ b/test/integration/controlplane/synthetic_controlplane_test.go @@ -22,7 +22,6 @@ import ( "encoding/json" "fmt" "io/ioutil" - "net" "net/http" "os" "path" @@ -51,6 +50,7 @@ import ( "k8s.io/kubernetes/pkg/controlplane" "k8s.io/kubernetes/test/integration" "k8s.io/kubernetes/test/integration/framework" + netutils "k8s.io/utils/net" ) const ( @@ -638,7 +638,7 @@ func TestAPIServerService(t *testing.T) { func TestServiceAlloc(t *testing.T) { cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR("192.168.0.0/29") + _, cidr, err := netutils.ParseCIDRSloppy("192.168.0.0/29") if err != nil { t.Fatalf("bad cidr: %v", err) } diff --git a/test/integration/dualstack/dualstack_endpoints_test.go b/test/integration/dualstack/dualstack_endpoints_test.go index e71b280bb24..22710cbf179 100644 --- a/test/integration/dualstack/dualstack_endpoints_test.go +++ b/test/integration/dualstack/dualstack_endpoints_test.go @@ -19,7 +19,6 @@ package dualstack import ( "context" "fmt" - "net" "testing" "time" @@ -38,6 +37,7 @@ import ( "k8s.io/kubernetes/pkg/controller/endpointslice" "k8s.io/kubernetes/pkg/features" "k8s.io/kubernetes/test/integration/framework" + netutils "k8s.io/utils/net" ) func TestDualStackEndpoints(t *testing.T) { @@ -52,13 +52,13 @@ func TestDualStackEndpoints(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, dualStack)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("Bad cidr: %v", err) } cfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("Bad cidr: %v", err) } diff --git a/test/integration/dualstack/dualstack_test.go b/test/integration/dualstack/dualstack_test.go index 16a446a381e..a5738c916c2 100644 --- a/test/integration/dualstack/dualstack_test.go +++ b/test/integration/dualstack/dualstack_test.go @@ -54,7 +54,7 @@ func TestCreateServiceSingleStackIPv4(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -271,7 +271,7 @@ func TestCreateServiceDualStackIPv6(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -491,13 +491,13 @@ func TestCreateServiceDualStackIPv4IPv6(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } cfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -718,13 +718,13 @@ func TestCreateServiceDualStackIPv6IPv4(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } cfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -948,13 +948,13 @@ func TestUpgradeDowngrade(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } cfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1063,13 +1063,13 @@ func TestConvertToFromExternalName(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } cfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1153,7 +1153,7 @@ func TestExistingServiceDefaulting(t *testing.T) { // Create an IPv4IPv6 dual stack control-plane serviceCIDR := "10.0.0.0/16" cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1236,13 +1236,13 @@ func TestPreferDualStack(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } cfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1321,7 +1321,7 @@ func TestServiceUpdate(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, false)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1486,7 +1486,7 @@ func TestUpgradeServicePreferToDualStack(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() cfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1545,7 +1545,7 @@ func TestUpgradeServicePreferToDualStack(t *testing.T) { closeFn() secondaryServiceCIDR := "2001:db8:1::/48" - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } @@ -1582,12 +1582,12 @@ func TestDowngradeServicePreferToDualStack(t *testing.T) { secondaryServiceCIDR := "2001:db8:1::/48" defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, true)() dualStackCfg := framework.NewIntegrationTestControlPlaneConfig() - _, cidr, err := net.ParseCIDR(serviceCIDR) + _, cidr, err := netutils.ParseCIDRSloppy(serviceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } dualStackCfg.ExtraConfig.ServiceIPRange = *cidr - _, secCidr, err := net.ParseCIDR(secondaryServiceCIDR) + _, secCidr, err := netutils.ParseCIDRSloppy(secondaryServiceCIDR) if err != nil { t.Fatalf("bad cidr: %v", err) } diff --git a/test/integration/etcd/server.go b/test/integration/etcd/server.go index 6760c4d6702..39aa7797c31 100644 --- a/test/integration/etcd/server.go +++ b/test/integration/etcd/server.go @@ -49,6 +49,7 @@ import ( "k8s.io/kubernetes/cmd/kube-apiserver/app/options" "k8s.io/kubernetes/test/integration" "k8s.io/kubernetes/test/integration/framework" + netutils "k8s.io/utils/net" // install all APIs _ "k8s.io/kubernetes/pkg/controlplane" @@ -68,7 +69,7 @@ func StartRealAPIServerOrDie(t *testing.T, configFuncs ...func(*options.ServerRu t.Fatal(err) } - _, defaultServiceClusterIPRange, err := net.ParseCIDR("10.0.0.0/24") + _, defaultServiceClusterIPRange, err := netutils.ParseCIDRSloppy("10.0.0.0/24") if err != nil { t.Fatal(err) } diff --git a/test/integration/examples/apiserver_test.go b/test/integration/examples/apiserver_test.go index 9b8923c2851..3f869220a67 100644 --- a/test/integration/examples/apiserver_test.go +++ b/test/integration/examples/apiserver_test.go @@ -50,6 +50,7 @@ import ( wardlev1alpha1 "k8s.io/sample-apiserver/pkg/apis/wardle/v1alpha1" wardlev1beta1 "k8s.io/sample-apiserver/pkg/apis/wardle/v1beta1" sampleserver "k8s.io/sample-apiserver/pkg/cmd/server" + netutils "k8s.io/utils/net" ) func TestAggregatedAPIServer(t *testing.T) { @@ -80,7 +81,7 @@ func TestAggregatedAPIServer(t *testing.T) { go func() { o := sampleserver.NewWardleServerOptions(os.Stdout, os.Stderr) o.RecommendedOptions.SecureServing.Listener = listener - o.RecommendedOptions.SecureServing.BindAddress = net.ParseIP("127.0.0.1") + o.RecommendedOptions.SecureServing.BindAddress = netutils.ParseIPSloppy("127.0.0.1") wardleCmd := sampleserver.NewCommandStartWardleServer(o, stopCh) wardleCmd.SetArgs([]string{ "--authentication-kubeconfig", wardleToKASKubeConfigFile, diff --git a/test/integration/framework/controlplane_utils.go b/test/integration/framework/controlplane_utils.go index 85284393b27..53f09f309d4 100644 --- a/test/integration/framework/controlplane_utils.go +++ b/test/integration/framework/controlplane_utils.go @@ -57,6 +57,7 @@ import ( "k8s.io/kubernetes/pkg/generated/openapi" "k8s.io/kubernetes/pkg/kubeapiserver" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" + netutils "k8s.io/utils/net" ) // Config is a struct of configuration directives for NewControlPlaneComponents. @@ -205,7 +206,7 @@ func startAPIServerOrDie(controlPlaneConfig *controlplane.Config, incomingServer } if controlPlaneConfig.ExtraConfig.ServiceIPRange.IP == nil { - controlPlaneConfig.ExtraConfig.ServiceIPRange = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(24, 32)} + controlPlaneConfig.ExtraConfig.ServiceIPRange = net.IPNet{IP: netutils.ParseIPSloppy("10.0.0.0"), Mask: net.CIDRMask(24, 32)} } m, err = controlPlaneConfig.Complete().New(genericapiserver.NewEmptyDelegate()) if err != nil { @@ -263,7 +264,7 @@ func NewIntegrationTestControlPlaneConfig() *controlplane.Config { // configured with the provided options. func NewIntegrationTestControlPlaneConfigWithOptions(opts *ControlPlaneConfigOptions) *controlplane.Config { controlPlaneConfig := NewControlPlaneConfigWithOptions(opts) - controlPlaneConfig.GenericConfig.PublicAddress = net.ParseIP("192.168.10.4") + controlPlaneConfig.GenericConfig.PublicAddress = netutils.ParseIPSloppy("192.168.10.4") controlPlaneConfig.ExtraConfig.APIResourceConfigSource = controlplane.DefaultAPIResourceConfigSource() // TODO: get rid of these tests or port them to secure serving diff --git a/test/integration/framework/test_server.go b/test/integration/framework/test_server.go index a5974189f9d..4ff98a3b83a 100644 --- a/test/integration/framework/test_server.go +++ b/test/integration/framework/test_server.go @@ -40,6 +40,7 @@ import ( "k8s.io/kubernetes/cmd/kube-apiserver/app/options" "k8s.io/kubernetes/pkg/controlplane" "k8s.io/kubernetes/test/utils" + netutils "k8s.io/utils/net" ) // This key is for testing purposes only and is not considered secure. @@ -63,7 +64,7 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup os.RemoveAll(certDir) }() - _, defaultServiceClusterIPRange, _ := net.ParseCIDR("10.0.0.0/24") + _, defaultServiceClusterIPRange, _ := netutils.ParseCIDRSloppy("10.0.0.0/24") proxySigningKey, err := utils.NewPrivateKey() if err != nil { t.Fatal(err) @@ -105,7 +106,7 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup kubeAPIServerOptions := options.NewServerRunOptions() kubeAPIServerOptions.SecureServing.Listener = listener - kubeAPIServerOptions.SecureServing.BindAddress = net.ParseIP("127.0.0.1") + kubeAPIServerOptions.SecureServing.BindAddress = netutils.ParseIPSloppy("127.0.0.1") kubeAPIServerOptions.SecureServing.ServerCert.CertDirectory = certDir kubeAPIServerOptions.ServiceAccountSigningKeyFile = saSigningKeyFile.Name() kubeAPIServerOptions.Etcd.StorageConfig.Prefix = path.Join("/", uuid.New().String(), "registry") diff --git a/test/integration/ipamperf/ipam_test.go b/test/integration/ipamperf/ipam_test.go index 93d9d92dc52..636265e8e30 100644 --- a/test/integration/ipamperf/ipam_test.go +++ b/test/integration/ipamperf/ipam_test.go @@ -26,6 +26,7 @@ import ( "time" "k8s.io/klog/v2" + netutils "k8s.io/utils/net" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/informers" @@ -117,8 +118,8 @@ func TestPerformance(t *testing.T) { apiURL, apiserverShutdown := util.StartApiserver() defer apiserverShutdown() - _, clusterCIDR, _ := net.ParseCIDR("10.96.0.0/11") // allows up to 8K nodes - _, serviceCIDR, _ := net.ParseCIDR("10.94.0.0/24") // does not matter for test - pick upto 250 services + _, clusterCIDR, _ := netutils.ParseCIDRSloppy("10.96.0.0/11") // allows up to 8K nodes + _, serviceCIDR, _ := netutils.ParseCIDRSloppy("10.94.0.0/24") // does not matter for test - pick upto 250 services subnetMaskSize := 24 var (