Switch to github.com/golang/dep for vendoring
Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
This commit is contained in:
parent
d6ab91be27
commit
8e5b17cf13
15431 changed files with 3971413 additions and 8881 deletions
269
vendor/k8s.io/apimachinery/pkg/util/net/http.go
generated
vendored
Normal file
269
vendor/k8s.io/apimachinery/pkg/util/net/http.go
generated
vendored
Normal file
|
@ -0,0 +1,269 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/golang/glog"
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
// IsProbableEOF returns true if the given error resembles a connection termination
|
||||
// scenario that would justify assuming that the watch is empty.
|
||||
// These errors are what the Go http stack returns back to us which are general
|
||||
// connection closure errors (strongly correlated) and callers that need to
|
||||
// differentiate probable errors in connection behavior between normal "this is
|
||||
// disconnected" should use the method.
|
||||
func IsProbableEOF(err error) bool {
|
||||
if uerr, ok := err.(*url.Error); ok {
|
||||
err = uerr.Err
|
||||
}
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
return true
|
||||
case err.Error() == "http: can't write HTTP request on broken connection":
|
||||
return true
|
||||
case strings.Contains(err.Error(), "connection reset by peer"):
|
||||
return true
|
||||
case strings.Contains(strings.ToLower(err.Error()), "use of closed network connection"):
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var defaultTransport = http.DefaultTransport.(*http.Transport)
|
||||
|
||||
// SetOldTransportDefaults applies the defaults from http.DefaultTransport
|
||||
// for the Proxy, Dial, and TLSHandshakeTimeout fields if unset
|
||||
func SetOldTransportDefaults(t *http.Transport) *http.Transport {
|
||||
if t.Proxy == nil || isDefault(t.Proxy) {
|
||||
// http.ProxyFromEnvironment doesn't respect CIDRs and that makes it impossible to exclude things like pod and service IPs from proxy settings
|
||||
// ProxierWithNoProxyCIDR allows CIDR rules in NO_PROXY
|
||||
t.Proxy = NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment)
|
||||
}
|
||||
if t.Dial == nil {
|
||||
t.Dial = defaultTransport.Dial
|
||||
}
|
||||
if t.TLSHandshakeTimeout == 0 {
|
||||
t.TLSHandshakeTimeout = defaultTransport.TLSHandshakeTimeout
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// SetTransportDefaults applies the defaults from http.DefaultTransport
|
||||
// for the Proxy, Dial, and TLSHandshakeTimeout fields if unset
|
||||
func SetTransportDefaults(t *http.Transport) *http.Transport {
|
||||
t = SetOldTransportDefaults(t)
|
||||
// Allow clients to disable http2 if needed.
|
||||
if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 {
|
||||
glog.Infof("HTTP2 has been explicitly disabled")
|
||||
} else {
|
||||
if err := http2.ConfigureTransport(t); err != nil {
|
||||
glog.Warningf("Transport failed http2 configuration: %v", err)
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
type RoundTripperWrapper interface {
|
||||
http.RoundTripper
|
||||
WrappedRoundTripper() http.RoundTripper
|
||||
}
|
||||
|
||||
type DialFunc func(net, addr string) (net.Conn, error)
|
||||
|
||||
func Dialer(transport http.RoundTripper) (DialFunc, error) {
|
||||
if transport == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
switch transport := transport.(type) {
|
||||
case *http.Transport:
|
||||
return transport.Dial, nil
|
||||
case RoundTripperWrapper:
|
||||
return Dialer(transport.WrappedRoundTripper())
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown transport type: %v", transport)
|
||||
}
|
||||
}
|
||||
|
||||
// CloneTLSConfig returns a tls.Config with all exported fields except SessionTicketsDisabled and SessionTicketKey copied.
|
||||
// This makes it safe to call CloneTLSConfig on a config in active use by a server.
|
||||
// TODO: replace with tls.Config#Clone when we move to go1.8
|
||||
func CloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||
if cfg == nil {
|
||||
return &tls.Config{}
|
||||
}
|
||||
return &tls.Config{
|
||||
Rand: cfg.Rand,
|
||||
Time: cfg.Time,
|
||||
Certificates: cfg.Certificates,
|
||||
NameToCertificate: cfg.NameToCertificate,
|
||||
GetCertificate: cfg.GetCertificate,
|
||||
RootCAs: cfg.RootCAs,
|
||||
NextProtos: cfg.NextProtos,
|
||||
ServerName: cfg.ServerName,
|
||||
ClientAuth: cfg.ClientAuth,
|
||||
ClientCAs: cfg.ClientCAs,
|
||||
InsecureSkipVerify: cfg.InsecureSkipVerify,
|
||||
CipherSuites: cfg.CipherSuites,
|
||||
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
|
||||
ClientSessionCache: cfg.ClientSessionCache,
|
||||
MinVersion: cfg.MinVersion,
|
||||
MaxVersion: cfg.MaxVersion,
|
||||
CurvePreferences: cfg.CurvePreferences,
|
||||
}
|
||||
}
|
||||
|
||||
type TLSClientConfigHolder interface {
|
||||
TLSClientConfig() *tls.Config
|
||||
}
|
||||
|
||||
func TLSClientConfig(transport http.RoundTripper) (*tls.Config, error) {
|
||||
if transport == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
switch transport := transport.(type) {
|
||||
case *http.Transport:
|
||||
return transport.TLSClientConfig, nil
|
||||
case TLSClientConfigHolder:
|
||||
return transport.TLSClientConfig(), nil
|
||||
case RoundTripperWrapper:
|
||||
return TLSClientConfig(transport.WrappedRoundTripper())
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown transport type: %v", transport)
|
||||
}
|
||||
}
|
||||
|
||||
func FormatURL(scheme string, host string, port int, path string) *url.URL {
|
||||
return &url.URL{
|
||||
Scheme: scheme,
|
||||
Host: net.JoinHostPort(host, strconv.Itoa(port)),
|
||||
Path: path,
|
||||
}
|
||||
}
|
||||
|
||||
func GetHTTPClient(req *http.Request) string {
|
||||
if userAgent, ok := req.Header["User-Agent"]; ok {
|
||||
if len(userAgent) > 0 {
|
||||
return userAgent[0]
|
||||
}
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// Extracts and returns the clients IP from the given request.
|
||||
// Looks at X-Forwarded-For header, X-Real-Ip header and request.RemoteAddr in that order.
|
||||
// Returns nil if none of them are set or is set to an invalid value.
|
||||
func GetClientIP(req *http.Request) net.IP {
|
||||
hdr := req.Header
|
||||
// First check the X-Forwarded-For header for requests via proxy.
|
||||
hdrForwardedFor := hdr.Get("X-Forwarded-For")
|
||||
if hdrForwardedFor != "" {
|
||||
// X-Forwarded-For can be a csv of IPs in case of multiple proxies.
|
||||
// Use the first valid one.
|
||||
parts := strings.Split(hdrForwardedFor, ",")
|
||||
for _, part := range parts {
|
||||
ip := net.ParseIP(strings.TrimSpace(part))
|
||||
if ip != nil {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try the X-Real-Ip header.
|
||||
hdrRealIp := hdr.Get("X-Real-Ip")
|
||||
if hdrRealIp != "" {
|
||||
ip := net.ParseIP(hdrRealIp)
|
||||
if ip != nil {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to Remote Address in request, which will give the correct client IP when there is no proxy.
|
||||
// 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 {
|
||||
return net.ParseIP(host)
|
||||
}
|
||||
|
||||
// Fallback if Remote Address was just IP.
|
||||
return net.ParseIP(req.RemoteAddr)
|
||||
}
|
||||
|
||||
var defaultProxyFuncPointer = fmt.Sprintf("%p", http.ProxyFromEnvironment)
|
||||
|
||||
// isDefault checks to see if the transportProxierFunc is pointing to the default one
|
||||
func isDefault(transportProxier func(*http.Request) (*url.URL, error)) bool {
|
||||
transportProxierPointer := fmt.Sprintf("%p", transportProxier)
|
||||
return transportProxierPointer == defaultProxyFuncPointer
|
||||
}
|
||||
|
||||
// NewProxierWithNoProxyCIDR constructs a Proxier function that respects CIDRs in NO_PROXY and delegates if
|
||||
// no matching CIDRs are found
|
||||
func NewProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error)) func(req *http.Request) (*url.URL, error) {
|
||||
// we wrap the default method, so we only need to perform our check if the NO_PROXY envvar has a CIDR in it
|
||||
noProxyEnv := os.Getenv("NO_PROXY")
|
||||
noProxyRules := strings.Split(noProxyEnv, ",")
|
||||
|
||||
cidrs := []*net.IPNet{}
|
||||
for _, noProxyRule := range noProxyRules {
|
||||
_, cidr, _ := net.ParseCIDR(noProxyRule)
|
||||
if cidr != nil {
|
||||
cidrs = append(cidrs, cidr)
|
||||
}
|
||||
}
|
||||
|
||||
if len(cidrs) == 0 {
|
||||
return delegate
|
||||
}
|
||||
|
||||
return func(req *http.Request) (*url.URL, error) {
|
||||
host := req.URL.Host
|
||||
// for some urls, the Host is already the host, not the host:port
|
||||
if net.ParseIP(host) == nil {
|
||||
var err error
|
||||
host, _, err = net.SplitHostPort(req.URL.Host)
|
||||
if err != nil {
|
||||
return delegate(req)
|
||||
}
|
||||
}
|
||||
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil {
|
||||
return delegate(req)
|
||||
}
|
||||
|
||||
for _, cidr := range cidrs {
|
||||
if cidr.Contains(ip) {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
return delegate(req)
|
||||
}
|
||||
}
|
246
vendor/k8s.io/apimachinery/pkg/util/net/http_test.go
generated
vendored
Normal file
246
vendor/k8s.io/apimachinery/pkg/util/net/http_test.go
generated
vendored
Normal file
|
@ -0,0 +1,246 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
|
||||
func TestCloneTLSConfig(t *testing.T) {
|
||||
expected := sets.NewString(
|
||||
// These fields are copied in CloneTLSConfig
|
||||
"Rand",
|
||||
"Time",
|
||||
"Certificates",
|
||||
"RootCAs",
|
||||
"NextProtos",
|
||||
"ServerName",
|
||||
"InsecureSkipVerify",
|
||||
"CipherSuites",
|
||||
"PreferServerCipherSuites",
|
||||
"MinVersion",
|
||||
"MaxVersion",
|
||||
"CurvePreferences",
|
||||
"NameToCertificate",
|
||||
"GetCertificate",
|
||||
"ClientAuth",
|
||||
"ClientCAs",
|
||||
"ClientSessionCache",
|
||||
|
||||
// These fields are not copied
|
||||
"SessionTicketsDisabled",
|
||||
"SessionTicketKey",
|
||||
|
||||
// These fields are unexported
|
||||
"serverInitOnce",
|
||||
"mutex",
|
||||
"sessionTicketKeys",
|
||||
)
|
||||
|
||||
// See #33936.
|
||||
if strings.HasPrefix(runtime.Version(), "go1.7") {
|
||||
expected.Insert("DynamicRecordSizingDisabled", "Renegotiation")
|
||||
}
|
||||
|
||||
fields := sets.NewString()
|
||||
structType := reflect.TypeOf(tls.Config{})
|
||||
for i := 0; i < structType.NumField(); i++ {
|
||||
fields.Insert(structType.Field(i).Name)
|
||||
}
|
||||
|
||||
if missing := expected.Difference(fields); len(missing) > 0 {
|
||||
t.Errorf("Expected fields that were not seen in http.Transport: %v", missing.List())
|
||||
}
|
||||
if extra := fields.Difference(expected); len(extra) > 0 {
|
||||
t.Errorf("New fields seen in http.Transport: %v\nAdd to CopyClientTLSConfig if client-relevant, then add to expected list in TestCopyClientTLSConfig", extra.List())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetClientIP(t *testing.T) {
|
||||
ipString := "10.0.0.1"
|
||||
ip := net.ParseIP(ipString)
|
||||
invalidIPString := "invalidIPString"
|
||||
testCases := []struct {
|
||||
Request http.Request
|
||||
ExpectedIP net.IP
|
||||
}{
|
||||
{
|
||||
Request: http.Request{},
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
Header: map[string][]string{
|
||||
"X-Real-Ip": {ipString},
|
||||
},
|
||||
},
|
||||
ExpectedIP: ip,
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
Header: map[string][]string{
|
||||
"X-Real-Ip": {invalidIPString},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
Header: map[string][]string{
|
||||
"X-Forwarded-For": {ipString},
|
||||
},
|
||||
},
|
||||
ExpectedIP: ip,
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
Header: map[string][]string{
|
||||
"X-Forwarded-For": {invalidIPString},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
Header: map[string][]string{
|
||||
"X-Forwarded-For": {invalidIPString + "," + ipString},
|
||||
},
|
||||
},
|
||||
ExpectedIP: ip,
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
// RemoteAddr is in the form host:port
|
||||
RemoteAddr: ipString + ":1234",
|
||||
},
|
||||
ExpectedIP: ip,
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
RemoteAddr: invalidIPString,
|
||||
},
|
||||
},
|
||||
{
|
||||
Request: http.Request{
|
||||
Header: map[string][]string{
|
||||
"X-Forwarded-For": {invalidIPString},
|
||||
},
|
||||
// RemoteAddr is in the form host:port
|
||||
RemoteAddr: ipString,
|
||||
},
|
||||
ExpectedIP: ip,
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range testCases {
|
||||
if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true {
|
||||
t.Fatalf("test case %d failed. expected: %v, actual: %v", i, e, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxierWithNoProxyCIDR(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
noProxy string
|
||||
url string
|
||||
|
||||
expectedDelegated bool
|
||||
}{
|
||||
{
|
||||
name: "no env",
|
||||
url: "https://192.168.143.1/api",
|
||||
expectedDelegated: true,
|
||||
},
|
||||
{
|
||||
name: "no cidr",
|
||||
noProxy: "192.168.63.1",
|
||||
url: "https://192.168.143.1/api",
|
||||
expectedDelegated: true,
|
||||
},
|
||||
{
|
||||
name: "hostname",
|
||||
noProxy: "192.168.63.0/24,192.168.143.0/24",
|
||||
url: "https://my-hostname/api",
|
||||
expectedDelegated: true,
|
||||
},
|
||||
{
|
||||
name: "match second cidr",
|
||||
noProxy: "192.168.63.0/24,192.168.143.0/24",
|
||||
url: "https://192.168.143.1/api",
|
||||
expectedDelegated: false,
|
||||
},
|
||||
{
|
||||
name: "match second cidr with host:port",
|
||||
noProxy: "192.168.63.0/24,192.168.143.0/24",
|
||||
url: "https://192.168.143.1:8443/api",
|
||||
expectedDelegated: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
os.Setenv("NO_PROXY", test.noProxy)
|
||||
actualDelegated := false
|
||||
proxyFunc := NewProxierWithNoProxyCIDR(func(req *http.Request) (*url.URL, error) {
|
||||
actualDelegated = true
|
||||
return nil, nil
|
||||
})
|
||||
|
||||
req, err := http.NewRequest("GET", test.url, nil)
|
||||
if err != nil {
|
||||
t.Errorf("%s: unexpected err: %v", test.name, err)
|
||||
continue
|
||||
}
|
||||
if _, err := proxyFunc(req); err != nil {
|
||||
t.Errorf("%s: unexpected err: %v", test.name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if test.expectedDelegated != actualDelegated {
|
||||
t.Errorf("%s: expected %v, got %v", test.name, test.expectedDelegated, actualDelegated)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type fakeTLSClientConfigHolder struct {
|
||||
called bool
|
||||
}
|
||||
|
||||
func (f *fakeTLSClientConfigHolder) TLSClientConfig() *tls.Config {
|
||||
f.called = true
|
||||
return nil
|
||||
}
|
||||
func (f *fakeTLSClientConfigHolder) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestTLSClientConfigHolder(t *testing.T) {
|
||||
rt := &fakeTLSClientConfigHolder{}
|
||||
TLSClientConfig(rt)
|
||||
|
||||
if !rt.called {
|
||||
t.Errorf("didn't find tls config")
|
||||
}
|
||||
}
|
278
vendor/k8s.io/apimachinery/pkg/util/net/interface.go
generated
vendored
Normal file
278
vendor/k8s.io/apimachinery/pkg/util/net/interface.go
generated
vendored
Normal file
|
@ -0,0 +1,278 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
|
||||
"strings"
|
||||
|
||||
"github.com/golang/glog"
|
||||
)
|
||||
|
||||
type Route struct {
|
||||
Interface string
|
||||
Destination net.IP
|
||||
Gateway net.IP
|
||||
// TODO: add more fields here if needed
|
||||
}
|
||||
|
||||
func getRoutes(input io.Reader) ([]Route, error) {
|
||||
routes := []Route{}
|
||||
if input == nil {
|
||||
return nil, fmt.Errorf("input is nil")
|
||||
}
|
||||
scanner := bufio.NewReader(input)
|
||||
for {
|
||||
line, err := scanner.ReadString('\n')
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
//ignore the headers in the route info
|
||||
if strings.HasPrefix(line, "Iface") {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
routes = append(routes, Route{})
|
||||
route := &routes[len(routes)-1]
|
||||
route.Interface = fields[0]
|
||||
ip, err := parseIP(fields[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
route.Destination = ip
|
||||
ip, err = parseIP(fields[2])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
route.Gateway = ip
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
|
||||
func parseIP(str string) (net.IP, error) {
|
||||
if str == "" {
|
||||
return nil, fmt.Errorf("input is nil")
|
||||
}
|
||||
bytes, err := hex.DecodeString(str)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//TODO add ipv6 support
|
||||
if len(bytes) != net.IPv4len {
|
||||
return nil, fmt.Errorf("only IPv4 is supported")
|
||||
}
|
||||
bytes[0], bytes[1], bytes[2], bytes[3] = bytes[3], bytes[2], bytes[1], bytes[0]
|
||||
return net.IP(bytes), nil
|
||||
}
|
||||
|
||||
func isInterfaceUp(intf *net.Interface) bool {
|
||||
if intf == nil {
|
||||
return false
|
||||
}
|
||||
if intf.Flags&net.FlagUp != 0 {
|
||||
glog.V(4).Infof("Interface %v is up", intf.Name)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//getFinalIP method receives all the IP addrs of a Interface
|
||||
//and returns a nil if the address is Loopback, Ipv6, link-local or nil.
|
||||
//It returns a valid IPv4 if an Ipv4 address is found in the array.
|
||||
func getFinalIP(addrs []net.Addr) (net.IP, error) {
|
||||
if len(addrs) > 0 {
|
||||
for i := range addrs {
|
||||
glog.V(4).Infof("Checking addr %s.", addrs[i].String())
|
||||
ip, _, err := net.ParseCIDR(addrs[i].String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//Only IPv4
|
||||
//TODO : add IPv6 support
|
||||
if ip.To4() != nil {
|
||||
if !ip.IsLoopback() && !ip.IsLinkLocalMulticast() && !ip.IsLinkLocalUnicast() {
|
||||
glog.V(4).Infof("IP found %v", ip)
|
||||
return ip, nil
|
||||
} else {
|
||||
glog.V(4).Infof("Loopback/link-local found %v", ip)
|
||||
}
|
||||
} else {
|
||||
glog.V(4).Infof("%v is not a valid IPv4 address", ip)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func getIPFromInterface(intfName string, nw networkInterfacer) (net.IP, error) {
|
||||
intf, err := nw.InterfaceByName(intfName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isInterfaceUp(intf) {
|
||||
addrs, err := nw.Addrs(intf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
glog.V(4).Infof("Interface %q has %d addresses :%v.", intfName, len(addrs), addrs)
|
||||
finalIP, err := getFinalIP(addrs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if finalIP != nil {
|
||||
glog.V(4).Infof("valid IPv4 address for interface %q found as %v.", intfName, finalIP)
|
||||
return finalIP, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func flagsSet(flags net.Flags, test net.Flags) bool {
|
||||
return flags&test != 0
|
||||
}
|
||||
|
||||
func flagsClear(flags net.Flags, test net.Flags) bool {
|
||||
return flags&test == 0
|
||||
}
|
||||
|
||||
func chooseHostInterfaceNativeGo() (net.IP, error) {
|
||||
intfs, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i := 0
|
||||
var ip net.IP
|
||||
for i = range intfs {
|
||||
if flagsSet(intfs[i].Flags, net.FlagUp) && flagsClear(intfs[i].Flags, net.FlagLoopback|net.FlagPointToPoint) {
|
||||
addrs, err := intfs[i].Addrs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(addrs) > 0 {
|
||||
for _, addr := range addrs {
|
||||
if addrIP, _, err := net.ParseCIDR(addr.String()); err == nil {
|
||||
if addrIP.To4() != nil {
|
||||
ip = addrIP.To4()
|
||||
if !ip.IsLinkLocalMulticast() && !ip.IsLinkLocalUnicast() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ip != nil {
|
||||
// This interface should suffice.
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("no acceptable interface from host")
|
||||
}
|
||||
glog.V(4).Infof("Choosing interface %s (IP %v) as default", intfs[i].Name, ip)
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
//ChooseHostInterface is a method used fetch an IP for a daemon.
|
||||
//It uses data from /proc/net/route file.
|
||||
//For a node with no internet connection ,it returns error
|
||||
//For a multi n/w interface node it returns the IP of the interface with gateway on it.
|
||||
func ChooseHostInterface() (net.IP, error) {
|
||||
inFile, err := os.Open("/proc/net/route")
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return chooseHostInterfaceNativeGo()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer inFile.Close()
|
||||
var nw networkInterfacer = networkInterface{}
|
||||
return chooseHostInterfaceFromRoute(inFile, nw)
|
||||
}
|
||||
|
||||
type networkInterfacer interface {
|
||||
InterfaceByName(intfName string) (*net.Interface, error)
|
||||
Addrs(intf *net.Interface) ([]net.Addr, error)
|
||||
}
|
||||
|
||||
type networkInterface struct{}
|
||||
|
||||
func (_ networkInterface) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
intf, err := net.InterfaceByName(intfName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return intf, nil
|
||||
}
|
||||
|
||||
func (_ networkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
addrs, err := intf.Addrs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return addrs, nil
|
||||
}
|
||||
|
||||
func chooseHostInterfaceFromRoute(inFile io.Reader, nw networkInterfacer) (net.IP, error) {
|
||||
routes, err := getRoutes(inFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
zero := net.IP{0, 0, 0, 0}
|
||||
var finalIP net.IP
|
||||
for i := range routes {
|
||||
//find interface with gateway
|
||||
if routes[i].Destination.Equal(zero) {
|
||||
glog.V(4).Infof("Default route transits interface %q", routes[i].Interface)
|
||||
finalIP, err := getIPFromInterface(routes[i].Interface, nw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if finalIP != nil {
|
||||
glog.V(4).Infof("Choosing IP %v ", finalIP)
|
||||
return finalIP, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
glog.V(4).Infof("No valid IP found")
|
||||
if finalIP == nil {
|
||||
return nil, fmt.Errorf("Unable to select an IP.")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// If bind-address is usable, return it directly
|
||||
// If bind-address is not usable (unset, 0.0.0.0, or loopback), we will use the host's default
|
||||
// interface.
|
||||
func ChooseBindAddress(bindAddress net.IP) (net.IP, error) {
|
||||
if bindAddress == nil || bindAddress.IsUnspecified() || bindAddress.IsLoopback() {
|
||||
hostIP, err := ChooseHostInterface()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bindAddress = hostIP
|
||||
}
|
||||
return bindAddress, nil
|
||||
}
|
300
vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go
generated
vendored
Normal file
300
vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go
generated
vendored
Normal file
|
@ -0,0 +1,300 @@
|
|||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const gatewayfirst = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0
|
||||
eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
`
|
||||
const gatewaylast = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0
|
||||
eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0
|
||||
`
|
||||
const gatewaymiddle = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
`
|
||||
const noInternetConnection = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
`
|
||||
const nothing = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
`
|
||||
const gatewayfirstIpv6_1 = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0
|
||||
eth3 0000FE0AA1 00000000 0001 0 0 0 0080FFFF 0 0 0
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
`
|
||||
const gatewayfirstIpv6_2 = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
eth3 00000000 0100FE0AA1 0003 0 0 1024 00000000 0 0 0
|
||||
eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
`
|
||||
const route_Invalidhex = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
eth3 00000000 0100FE0AA 0003 0 0 1024 00000000 0 0 0
|
||||
eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0
|
||||
docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0
|
||||
virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
|
||||
`
|
||||
|
||||
// Based on DigitalOcean COREOS
|
||||
const gatewayfirstLinkLocal = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
|
||||
eth0 00000000 0120372D 0001 0 0 0 00000000 0 0 0
|
||||
eth0 00000000 00000000 0001 0 0 2048 00000000 0 0 0
|
||||
`
|
||||
|
||||
func TestGetRoutes(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcase string
|
||||
route string
|
||||
expected int
|
||||
}{
|
||||
{"gatewayfirst", gatewayfirst, 4},
|
||||
{"gatewaymiddle", gatewaymiddle, 4},
|
||||
{"gatewaylast", gatewaylast, 4},
|
||||
{"nothing", nothing, 0},
|
||||
{"gatewayfirstIpv6_1", gatewayfirstIpv6_1, 0},
|
||||
{"gatewayfirstIpv6_2", gatewayfirstIpv6_2, 0},
|
||||
{"route_Invalidhex", route_Invalidhex, 0},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
r := strings.NewReader(tc.route)
|
||||
routes, err := getRoutes(r)
|
||||
if len(routes) != tc.expected {
|
||||
t.Errorf("case[%v]: expected %v, got %v .err : %v", tc.tcase, tc.expected, len(routes), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseIP(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcase string
|
||||
ip string
|
||||
success bool
|
||||
expected net.IP
|
||||
}{
|
||||
{"empty", "", false, nil},
|
||||
{"too short", "AA", false, nil},
|
||||
{"too long", "0011223344", false, nil},
|
||||
{"invalid", "invalid!", false, nil},
|
||||
{"zero", "00000000", true, net.IP{0, 0, 0, 0}},
|
||||
{"ffff", "FFFFFFFF", true, net.IP{0xff, 0xff, 0xff, 0xff}},
|
||||
{"valid", "12345678", true, net.IP{120, 86, 52, 18}},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
ip, err := parseIP(tc.ip)
|
||||
if !ip.Equal(tc.expected) {
|
||||
t.Errorf("case[%v]: expected %q, got %q . err : %v", tc.tcase, tc.expected, ip, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsInterfaceUp(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcase string
|
||||
intf net.Interface
|
||||
expected bool
|
||||
}{
|
||||
{"up", net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}, true},
|
||||
{"down", net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: 0}, false},
|
||||
{"nothing", net.Interface{}, false},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
it := isInterfaceUp(&tc.intf)
|
||||
if it != tc.expected {
|
||||
t.Errorf("case[%v]: expected %v, got %v .", tc.tcase, tc.expected, it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type addrStruct struct{ val string }
|
||||
|
||||
func (a addrStruct) Network() string {
|
||||
return a.val
|
||||
}
|
||||
func (a addrStruct) String() string {
|
||||
return a.val
|
||||
}
|
||||
|
||||
func TestFinalIP(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcase string
|
||||
addr []net.Addr
|
||||
expected net.IP
|
||||
}{
|
||||
{"ipv6", []net.Addr{addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}}, nil},
|
||||
{"invalidCIDR", []net.Addr{addrStruct{val: "fe80::2f7:67fff:fe6e:2956/64"}}, nil},
|
||||
{"loopback", []net.Addr{addrStruct{val: "127.0.0.1/24"}}, nil},
|
||||
{"ip4", []net.Addr{addrStruct{val: "10.254.12.132/17"}}, net.ParseIP("10.254.12.132")},
|
||||
|
||||
{"nothing", []net.Addr{}, nil},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
ip, err := getFinalIP(tc.addr)
|
||||
if !ip.Equal(tc.expected) {
|
||||
t.Errorf("case[%v]: expected %v, got %v .err : %v", tc.tcase, tc.expected, ip, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddrs(t *testing.T) {
|
||||
var nw networkInterfacer = validNetworkInterface{}
|
||||
intf := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: 0}
|
||||
addrs, err := nw.Addrs(&intf)
|
||||
if err != nil {
|
||||
t.Errorf("expected no error got : %v", err)
|
||||
}
|
||||
if len(addrs) != 2 {
|
||||
t.Errorf("expected addrs: 2 got null")
|
||||
}
|
||||
}
|
||||
|
||||
type validNetworkInterface struct {
|
||||
}
|
||||
|
||||
func (_ validNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}
|
||||
return &c, nil
|
||||
}
|
||||
func (_ validNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
var ifat []net.Addr
|
||||
ifat = []net.Addr{
|
||||
addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}}
|
||||
return ifat, nil
|
||||
}
|
||||
|
||||
type validNetworkInterfaceWithLinkLocal struct {
|
||||
}
|
||||
|
||||
func (_ validNetworkInterfaceWithLinkLocal) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
c := net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: net.FlagUp}
|
||||
return &c, nil
|
||||
}
|
||||
func (_ validNetworkInterfaceWithLinkLocal) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
var ifat []net.Addr
|
||||
ifat = []net.Addr{addrStruct{val: "169.254.162.166/16"}, addrStruct{val: "45.55.47.146/19"}}
|
||||
return ifat, nil
|
||||
}
|
||||
|
||||
type validNetworkInterfacewithIpv6Only struct {
|
||||
}
|
||||
|
||||
func (_ validNetworkInterfacewithIpv6Only) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}
|
||||
return &c, nil
|
||||
}
|
||||
func (_ validNetworkInterfacewithIpv6Only) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
var ifat []net.Addr
|
||||
ifat = []net.Addr{addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}}
|
||||
return ifat, nil
|
||||
}
|
||||
|
||||
type noNetworkInterface struct {
|
||||
}
|
||||
|
||||
func (_ noNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
return nil, fmt.Errorf("unable get Interface")
|
||||
}
|
||||
func (_ noNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type networkInterfacewithNoAddrs struct {
|
||||
}
|
||||
|
||||
func (_ networkInterfacewithNoAddrs) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}
|
||||
return &c, nil
|
||||
}
|
||||
func (_ networkInterfacewithNoAddrs) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
return nil, fmt.Errorf("unable get Addrs")
|
||||
}
|
||||
|
||||
type networkInterfacewithIpv6addrs struct {
|
||||
}
|
||||
|
||||
func (_ networkInterfacewithIpv6addrs) InterfaceByName(intfName string) (*net.Interface, error) {
|
||||
c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}
|
||||
return &c, nil
|
||||
}
|
||||
func (_ networkInterfacewithIpv6addrs) Addrs(intf *net.Interface) ([]net.Addr, error) {
|
||||
var ifat []net.Addr
|
||||
ifat = []net.Addr{addrStruct{val: "fe80::2f7:6ffff:fe6e:2956/64"}}
|
||||
return ifat, nil
|
||||
}
|
||||
|
||||
func TestGetIPFromInterface(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcase string
|
||||
nwname string
|
||||
nw networkInterfacer
|
||||
expected net.IP
|
||||
}{
|
||||
{"valid", "eth3", validNetworkInterface{}, net.ParseIP("10.254.71.145")},
|
||||
{"ipv6", "eth3", validNetworkInterfacewithIpv6Only{}, nil},
|
||||
{"nothing", "eth3", noNetworkInterface{}, nil},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
ip, err := getIPFromInterface(tc.nwname, tc.nw)
|
||||
if !ip.Equal(tc.expected) {
|
||||
t.Errorf("case[%v]: expected %v, got %+v .err : %v", tc.tcase, tc.expected, ip, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChooseHostInterfaceFromRoute(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcase string
|
||||
inFile io.Reader
|
||||
nw networkInterfacer
|
||||
expected net.IP
|
||||
}{
|
||||
{"valid_routefirst", strings.NewReader(gatewayfirst), validNetworkInterface{}, net.ParseIP("10.254.71.145")},
|
||||
{"valid_routelast", strings.NewReader(gatewaylast), validNetworkInterface{}, net.ParseIP("10.254.71.145")},
|
||||
{"valid_routemiddle", strings.NewReader(gatewaymiddle), validNetworkInterface{}, net.ParseIP("10.254.71.145")},
|
||||
{"valid_routemiddle_ipv6", strings.NewReader(gatewaymiddle), validNetworkInterfacewithIpv6Only{}, nil},
|
||||
{"no internet connection", strings.NewReader(noInternetConnection), validNetworkInterface{}, nil},
|
||||
{"no non-link-local ip", strings.NewReader(gatewayfirstLinkLocal), validNetworkInterfaceWithLinkLocal{}, net.ParseIP("45.55.47.146")},
|
||||
{"no route", strings.NewReader(nothing), validNetworkInterface{}, nil},
|
||||
{"no route file", nil, validNetworkInterface{}, nil},
|
||||
{"no interfaces", nil, noNetworkInterface{}, nil},
|
||||
{"no interface Addrs", strings.NewReader(gatewaymiddle), networkInterfacewithNoAddrs{}, nil},
|
||||
{"Invalid Addrs", strings.NewReader(gatewaymiddle), networkInterfacewithIpv6addrs{}, nil},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
ip, err := chooseHostInterfaceFromRoute(tc.inFile, tc.nw)
|
||||
if !ip.Equal(tc.expected) {
|
||||
t.Errorf("case[%v]: expected %v, got %+v .err : %v", tc.tcase, tc.expected, ip, err)
|
||||
}
|
||||
}
|
||||
}
|
113
vendor/k8s.io/apimachinery/pkg/util/net/port_range.go
generated
vendored
Normal file
113
vendor/k8s.io/apimachinery/pkg/util/net/port_range.go
generated
vendored
Normal file
|
@ -0,0 +1,113 @@
|
|||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PortRange represents a range of TCP/UDP ports. To represent a single port,
|
||||
// set Size to 1.
|
||||
type PortRange struct {
|
||||
Base int
|
||||
Size int
|
||||
}
|
||||
|
||||
// Contains tests whether a given port falls within the PortRange.
|
||||
func (pr *PortRange) Contains(p int) bool {
|
||||
return (p >= pr.Base) && ((p - pr.Base) < pr.Size)
|
||||
}
|
||||
|
||||
// String converts the PortRange to a string representation, which can be
|
||||
// parsed by PortRange.Set or ParsePortRange.
|
||||
func (pr PortRange) String() string {
|
||||
if pr.Size == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d-%d", pr.Base, pr.Base+pr.Size-1)
|
||||
}
|
||||
|
||||
// Set parses a string of the form "min-max", inclusive at both ends, and
|
||||
// sets the PortRange from it. This is part of the flag.Value and pflag.Value
|
||||
// interfaces.
|
||||
func (pr *PortRange) Set(value string) error {
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
// TODO: Accept "80" syntax
|
||||
// TODO: Accept "80+8" syntax
|
||||
|
||||
if value == "" {
|
||||
pr.Base = 0
|
||||
pr.Size = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
hyphenIndex := strings.Index(value, "-")
|
||||
if hyphenIndex == -1 {
|
||||
return fmt.Errorf("expected hyphen in port range")
|
||||
}
|
||||
|
||||
var err error
|
||||
var low int
|
||||
var high int
|
||||
low, err = strconv.Atoi(value[:hyphenIndex])
|
||||
if err == nil {
|
||||
high, err = strconv.Atoi(value[hyphenIndex+1:])
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to parse port range: %s: %v", value, err)
|
||||
}
|
||||
|
||||
if low > 65535 || high > 65535 {
|
||||
return fmt.Errorf("the port range cannot be greater than 65535: %s", value)
|
||||
}
|
||||
|
||||
if high < low {
|
||||
return fmt.Errorf("end port cannot be less than start port: %s", value)
|
||||
}
|
||||
|
||||
pr.Base = low
|
||||
pr.Size = 1 + high - low
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type returns a descriptive string about this type. This is part of the
|
||||
// pflag.Value interface.
|
||||
func (*PortRange) Type() string {
|
||||
return "portRange"
|
||||
}
|
||||
|
||||
// ParsePortRange parses a string of the form "min-max", inclusive at both
|
||||
// ends, and initializs a new PortRange from it.
|
||||
func ParsePortRange(value string) (*PortRange, error) {
|
||||
pr := &PortRange{}
|
||||
err := pr.Set(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pr, nil
|
||||
}
|
||||
|
||||
func ParsePortRangeOrDie(value string) *PortRange {
|
||||
pr, err := ParsePortRange(value)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("couldn't parse port range %q: %v", value, err))
|
||||
}
|
||||
return pr
|
||||
}
|
69
vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go
generated
vendored
Normal file
69
vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go
generated
vendored
Normal file
|
@ -0,0 +1,69 @@
|
|||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func TestPortRange(t *testing.T) {
|
||||
testCases := []struct {
|
||||
input string
|
||||
success bool
|
||||
expected string
|
||||
included int
|
||||
excluded int
|
||||
}{
|
||||
{"100-200", true, "100-200", 200, 201},
|
||||
{" 100-200 ", true, "100-200", 200, 201},
|
||||
{"0-0", true, "0-0", 0, 1},
|
||||
{"", true, "", -1, 0},
|
||||
{"100", false, "", -1, -1},
|
||||
{"100 - 200", false, "", -1, -1},
|
||||
{"-100", false, "", -1, -1},
|
||||
{"100-", false, "", -1, -1},
|
||||
{"200-100", false, "", -1, -1},
|
||||
{"60000-70000", false, "", -1, -1},
|
||||
{"70000-80000", false, "", -1, -1},
|
||||
}
|
||||
|
||||
for i := range testCases {
|
||||
tc := &testCases[i]
|
||||
pr := &PortRange{}
|
||||
var f flag.Value = pr
|
||||
err := f.Set(tc.input)
|
||||
if err != nil && tc.success == true {
|
||||
t.Errorf("expected success, got %q", err)
|
||||
continue
|
||||
} else if err == nil && tc.success == false {
|
||||
t.Errorf("expected failure")
|
||||
continue
|
||||
} else if tc.success {
|
||||
if f.String() != tc.expected {
|
||||
t.Errorf("expected %q, got %q", tc.expected, f.String())
|
||||
}
|
||||
if tc.included >= 0 && !pr.Contains(tc.included) {
|
||||
t.Errorf("expected %q to include %d", f.String(), tc.included)
|
||||
}
|
||||
if tc.excluded >= 0 && pr.Contains(tc.excluded) {
|
||||
t.Errorf("expected %q to exclude %d", f.String(), tc.excluded)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
77
vendor/k8s.io/apimachinery/pkg/util/net/port_split.go
generated
vendored
Normal file
77
vendor/k8s.io/apimachinery/pkg/util/net/port_split.go
generated
vendored
Normal file
|
@ -0,0 +1,77 @@
|
|||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
|
||||
var validSchemes = sets.NewString("http", "https", "")
|
||||
|
||||
// SplitSchemeNamePort takes a string of the following forms:
|
||||
// * "<name>", returns "", "<name>","", true
|
||||
// * "<name>:<port>", returns "", "<name>","<port>",true
|
||||
// * "<scheme>:<name>:<port>", returns "<scheme>","<name>","<port>",true
|
||||
//
|
||||
// Name must be non-empty or valid will be returned false.
|
||||
// Scheme must be "http" or "https" if specified
|
||||
// Port is returned as a string, and it is not required to be numeric (could be
|
||||
// used for a named port, for example).
|
||||
func SplitSchemeNamePort(id string) (scheme, name, port string, valid bool) {
|
||||
parts := strings.Split(id, ":")
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
name = parts[0]
|
||||
case 2:
|
||||
name = parts[0]
|
||||
port = parts[1]
|
||||
case 3:
|
||||
scheme = parts[0]
|
||||
name = parts[1]
|
||||
port = parts[2]
|
||||
default:
|
||||
return "", "", "", false
|
||||
}
|
||||
|
||||
if len(name) > 0 && validSchemes.Has(scheme) {
|
||||
return scheme, name, port, true
|
||||
} else {
|
||||
return "", "", "", false
|
||||
}
|
||||
}
|
||||
|
||||
// JoinSchemeNamePort returns a string that specifies the scheme, name, and port:
|
||||
// * "<name>"
|
||||
// * "<name>:<port>"
|
||||
// * "<scheme>:<name>:<port>"
|
||||
// None of the parameters may contain a ':' character
|
||||
// Name is required
|
||||
// Scheme must be "", "http", or "https"
|
||||
func JoinSchemeNamePort(scheme, name, port string) string {
|
||||
if len(scheme) > 0 {
|
||||
// Must include three segments to specify scheme
|
||||
return scheme + ":" + name + ":" + port
|
||||
}
|
||||
if len(port) > 0 {
|
||||
// Must include two segments to specify port
|
||||
return name + ":" + port
|
||||
}
|
||||
// Return name alone
|
||||
return name
|
||||
}
|
121
vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go
generated
vendored
Normal file
121
vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go
generated
vendored
Normal file
|
@ -0,0 +1,121 @@
|
|||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSplitSchemeNamePort(t *testing.T) {
|
||||
table := []struct {
|
||||
in string
|
||||
name, port, scheme string
|
||||
valid bool
|
||||
normalized bool
|
||||
}{
|
||||
{
|
||||
in: "aoeu:asdf",
|
||||
name: "aoeu",
|
||||
port: "asdf",
|
||||
valid: true,
|
||||
normalized: true,
|
||||
}, {
|
||||
in: "http:aoeu:asdf",
|
||||
scheme: "http",
|
||||
name: "aoeu",
|
||||
port: "asdf",
|
||||
valid: true,
|
||||
normalized: true,
|
||||
}, {
|
||||
in: "https:aoeu:",
|
||||
scheme: "https",
|
||||
name: "aoeu",
|
||||
port: "",
|
||||
valid: true,
|
||||
normalized: false,
|
||||
}, {
|
||||
in: "https:aoeu:asdf",
|
||||
scheme: "https",
|
||||
name: "aoeu",
|
||||
port: "asdf",
|
||||
valid: true,
|
||||
normalized: true,
|
||||
}, {
|
||||
in: "aoeu:",
|
||||
name: "aoeu",
|
||||
valid: true,
|
||||
normalized: false,
|
||||
}, {
|
||||
in: "aoeu",
|
||||
name: "aoeu",
|
||||
valid: true,
|
||||
normalized: true,
|
||||
}, {
|
||||
in: ":asdf",
|
||||
valid: false,
|
||||
}, {
|
||||
in: "aoeu:asdf:htns",
|
||||
valid: false,
|
||||
}, {
|
||||
in: "http::asdf",
|
||||
valid: false,
|
||||
}, {
|
||||
in: "http::",
|
||||
valid: false,
|
||||
}, {
|
||||
in: "",
|
||||
valid: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, item := range table {
|
||||
scheme, name, port, valid := SplitSchemeNamePort(item.in)
|
||||
if e, a := item.scheme, scheme; e != a {
|
||||
t.Errorf("%q: Wanted %q, got %q", item.in, e, a)
|
||||
}
|
||||
if e, a := item.name, name; e != a {
|
||||
t.Errorf("%q: Wanted %q, got %q", item.in, e, a)
|
||||
}
|
||||
if e, a := item.port, port; e != a {
|
||||
t.Errorf("%q: Wanted %q, got %q", item.in, e, a)
|
||||
}
|
||||
if e, a := item.valid, valid; e != a {
|
||||
t.Errorf("%q: Wanted %t, got %t", item.in, e, a)
|
||||
}
|
||||
|
||||
// Make sure valid items round trip through JoinSchemeNamePort
|
||||
if item.valid {
|
||||
out := JoinSchemeNamePort(scheme, name, port)
|
||||
if item.normalized && out != item.in {
|
||||
t.Errorf("%q: Wanted %s, got %s", item.in, item.in, out)
|
||||
}
|
||||
scheme, name, port, valid := SplitSchemeNamePort(out)
|
||||
if e, a := item.scheme, scheme; e != a {
|
||||
t.Errorf("%q: Wanted %q, got %q", item.in, e, a)
|
||||
}
|
||||
if e, a := item.name, name; e != a {
|
||||
t.Errorf("%q: Wanted %q, got %q", item.in, e, a)
|
||||
}
|
||||
if e, a := item.port, port; e != a {
|
||||
t.Errorf("%q: Wanted %q, got %q", item.in, e, a)
|
||||
}
|
||||
if e, a := item.valid, valid; e != a {
|
||||
t.Errorf("%q: Wanted %t, got %t", item.in, e, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
46
vendor/k8s.io/apimachinery/pkg/util/net/util.go
generated
vendored
Normal file
46
vendor/k8s.io/apimachinery/pkg/util/net/util.go
generated
vendored
Normal file
|
@ -0,0 +1,46 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"net"
|
||||
"reflect"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// IPNetEqual checks if the two input IPNets are representing the same subnet.
|
||||
// For example,
|
||||
// 10.0.0.1/24 and 10.0.0.0/24 are the same subnet.
|
||||
// 10.0.0.1/24 and 10.0.0.0/25 are not the same subnet.
|
||||
func IPNetEqual(ipnet1, ipnet2 *net.IPNet) bool {
|
||||
if ipnet1 == nil || ipnet2 == nil {
|
||||
return false
|
||||
}
|
||||
if reflect.DeepEqual(ipnet1.Mask, ipnet2.Mask) && ipnet1.Contains(ipnet2.IP) && ipnet2.Contains(ipnet1.IP) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Returns if the given err is "connection reset by peer" error.
|
||||
func IsConnectionReset(err error) bool {
|
||||
opErr, ok := err.(*net.OpError)
|
||||
if ok && opErr.Err.Error() == syscall.ECONNRESET.Error() {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
68
vendor/k8s.io/apimachinery/pkg/util/net/util_test.go
generated
vendored
Normal file
68
vendor/k8s.io/apimachinery/pkg/util/net/util_test.go
generated
vendored
Normal file
|
@ -0,0 +1,68 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func getIPNet(cidr string) *net.IPNet {
|
||||
_, ipnet, _ := net.ParseCIDR(cidr)
|
||||
return ipnet
|
||||
}
|
||||
|
||||
func TestIPNetEqual(t *testing.T) {
|
||||
testCases := []struct {
|
||||
ipnet1 *net.IPNet
|
||||
ipnet2 *net.IPNet
|
||||
expect bool
|
||||
}{
|
||||
//null case
|
||||
{
|
||||
getIPNet("10.0.0.1/24"),
|
||||
getIPNet(""),
|
||||
false,
|
||||
},
|
||||
{
|
||||
getIPNet("10.0.0.0/24"),
|
||||
getIPNet("10.0.0.0/24"),
|
||||
true,
|
||||
},
|
||||
{
|
||||
getIPNet("10.0.0.0/24"),
|
||||
getIPNet("10.0.0.1/24"),
|
||||
true,
|
||||
},
|
||||
{
|
||||
getIPNet("10.0.0.0/25"),
|
||||
getIPNet("10.0.0.0/24"),
|
||||
false,
|
||||
},
|
||||
{
|
||||
getIPNet("10.0.1.0/24"),
|
||||
getIPNet("10.0.0.0/24"),
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
if tc.expect != IPNetEqual(tc.ipnet1, tc.ipnet2) {
|
||||
t.Errorf("Expect equality of %s and %s be to %v", tc.ipnet1.String(), tc.ipnet2.String(), tc.expect)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue