From fe6b633e2adac4949b5bc3ceee4c34aa35bc110c Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Wed, 5 Aug 2015 15:42:13 -0400 Subject: [PATCH 1/2] Convert for util.IP to just use a net.IP pflag can handle IP addresses so use the pflag code instead of doing it ourselves. This means our code just uses net.IP and we don't have all of the useless casting back and forth! --- cmd/kube-apiserver/app/server.go | 24 ++++++------ .../app/controllermanager.go | 6 +-- cmd/kube-proxy/app/server.go | 16 ++++---- cmd/kubelet/app/server.go | 28 ++++++------- contrib/mesos/pkg/executor/service/service.go | 6 +-- .../mesos/pkg/scheduler/service/service.go | 19 +++++---- pkg/util/net.go | 20 ---------- pkg/util/net_test.go | 39 ------------------- plugin/cmd/kube-scheduler/app/server.go | 6 +-- 9 files changed, 52 insertions(+), 112 deletions(-) diff --git a/cmd/kube-apiserver/app/server.go b/cmd/kube-apiserver/app/server.go index 4e8416b2fe9..563562c25fa 100644 --- a/cmd/kube-apiserver/app/server.go +++ b/cmd/kube-apiserver/app/server.go @@ -62,10 +62,10 @@ const ( // APIServer runs a kubernetes api server. type APIServer struct { - InsecureBindAddress util.IP + InsecureBindAddress net.IP InsecurePort int - BindAddress util.IP - AdvertiseAddress util.IP + BindAddress net.IP + AdvertiseAddress net.IP SecurePort int ExternalHost string APIRate float32 @@ -114,8 +114,8 @@ type APIServer struct { func NewAPIServer() *APIServer { s := APIServer{ InsecurePort: 8080, - InsecureBindAddress: util.IP(net.ParseIP("127.0.0.1")), - BindAddress: util.IP(net.ParseIP("0.0.0.0")), + InsecureBindAddress: net.ParseIP("127.0.0.1"), + BindAddress: net.ParseIP("0.0.0.0"), SecurePort: 6443, APIRate: 10.0, APIBurst: 200, @@ -151,20 +151,20 @@ func (s *APIServer) AddFlags(fs *pflag.FlagSet) { "the cluster and that port 443 on the cluster's public address is proxied to this "+ "port. This is performed by nginx in the default setup.") fs.IntVar(&s.InsecurePort, "port", s.InsecurePort, "DEPRECATED: see --insecure-port instead") - fs.Var(&s.InsecureBindAddress, "insecure-bind-address", ""+ + fs.IPVar(&s.InsecureBindAddress, "insecure-bind-address", s.InsecureBindAddress, ""+ "The IP address on which to serve the --insecure-port (set to 0.0.0.0 for all interfaces). "+ "Defaults to localhost.") - fs.Var(&s.InsecureBindAddress, "address", "DEPRECATED: see --insecure-bind-address instead") - fs.Var(&s.BindAddress, "bind-address", ""+ + fs.IPVar(&s.InsecureBindAddress, "address", s.InsecureBindAddress, "DEPRECATED: see --insecure-bind-address instead") + fs.IPVar(&s.BindAddress, "bind-address", s.BindAddress, ""+ "The IP address on which to serve the --read-only-port and --secure-port ports. The "+ "associated interface(s) must be reachable by the rest of the cluster, and by CLI/web "+ "clients. If blank, all interfaces will be used (0.0.0.0).") - fs.Var(&s.AdvertiseAddress, "advertise-address", ""+ + fs.IPVar(&s.AdvertiseAddress, "advertise-address", s.AdvertiseAddress, ""+ "The IP address on which to advertise the apiserver to members of the cluster. This "+ "address must be reachable by the rest of the cluster. If blank, the --bind-address "+ "will be used. If --bind-address is unspecified, the host's default interface will "+ "be used.") - fs.Var(&s.BindAddress, "public-address-override", "DEPRECATED: see --bind-address instead") + fs.IPVar(&s.BindAddress, "public-address-override", s.BindAddress, "DEPRECATED: see --bind-address instead") fs.IntVar(&s.SecurePort, "secure-port", s.SecurePort, ""+ "The port on which to serve HTTPS with authentication and authorization. If 0, "+ "don't serve HTTPS at all.") @@ -257,7 +257,7 @@ func (s *APIServer) Run(_ []string) error { // If advertise-address is not specified, use bind-address. If bind-address // is also unset (or 0.0.0.0), setDefaults() in pkg/master/master.go will // do the right thing and use the host's default interface. - if s.AdvertiseAddress == nil || net.IP(s.AdvertiseAddress).IsUnspecified() { + if s.AdvertiseAddress == nil || s.AdvertiseAddress.IsUnspecified() { s.AdvertiseAddress = s.BindAddress } @@ -394,7 +394,7 @@ func (s *APIServer) Run(_ []string) error { ExpAPIPrefix: s.ExpAPIPrefix, CorsAllowedOriginList: s.CorsAllowedOriginList, ReadWritePort: s.SecurePort, - PublicAddress: net.IP(s.AdvertiseAddress), + PublicAddress: s.AdvertiseAddress, Authenticator: authenticator, SupportsBasicAuth: len(s.BasicAuthFile) > 0, Authorizer: authorizer, diff --git a/cmd/kube-controller-manager/app/controllermanager.go b/cmd/kube-controller-manager/app/controllermanager.go index f6f190b0d7b..d5ad9c023a1 100644 --- a/cmd/kube-controller-manager/app/controllermanager.go +++ b/cmd/kube-controller-manager/app/controllermanager.go @@ -56,7 +56,7 @@ import ( // CMServer is the main context object for the controller manager. type CMServer struct { Port int - Address util.IP + Address net.IP CloudProvider string CloudConfigFile string ConcurrentEndpointSyncs int @@ -90,7 +90,7 @@ type CMServer struct { func NewCMServer() *CMServer { s := CMServer{ Port: ports.ControllerManagerPort, - Address: util.IP(net.ParseIP("127.0.0.1")), + Address: net.ParseIP("127.0.0.1"), ConcurrentEndpointSyncs: 5, ConcurrentRCSyncs: 5, ServiceSyncPeriod: 5 * time.Minute, @@ -108,7 +108,7 @@ func NewCMServer() *CMServer { // AddFlags adds flags for a specific CMServer to the specified FlagSet func (s *CMServer) AddFlags(fs *pflag.FlagSet) { fs.IntVar(&s.Port, "port", s.Port, "The port that the controller-manager's http service runs on") - fs.Var(&s.Address, "address", "The IP address to serve on (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.Address, "address", s.Address, "The IP address to serve on (set to 0.0.0.0 for all interfaces)") fs.StringVar(&s.CloudProvider, "cloud-provider", s.CloudProvider, "The provider for cloud services. Empty string for no provider.") fs.StringVar(&s.CloudConfigFile, "cloud-config", s.CloudConfigFile, "The path to the cloud provider configuration file. Empty string for no configuration file.") fs.IntVar(&s.ConcurrentEndpointSyncs, "concurrent-endpoint-syncs", s.ConcurrentEndpointSyncs, "The number of endpoint syncing operations that will be done concurrently. Larger number = faster endpoint updating, but more CPU (and network) load") diff --git a/cmd/kube-proxy/app/server.go b/cmd/kube-proxy/app/server.go index 72b5585fd65..2e4357ad691 100644 --- a/cmd/kube-proxy/app/server.go +++ b/cmd/kube-proxy/app/server.go @@ -42,9 +42,9 @@ import ( // ProxyServer contains configures and runs a Kubernetes proxy server type ProxyServer struct { - BindAddress util.IP + BindAddress net.IP HealthzPort int - HealthzBindAddress util.IP + HealthzBindAddress net.IP OOMScoreAdj int ResourceContainer string Master string @@ -55,9 +55,9 @@ type ProxyServer struct { // NewProxyServer creates a new ProxyServer object with default parameters func NewProxyServer() *ProxyServer { return &ProxyServer{ - BindAddress: util.IP(net.ParseIP("0.0.0.0")), + BindAddress: net.ParseIP("0.0.0.0"), HealthzPort: 10249, - HealthzBindAddress: util.IP(net.ParseIP("127.0.0.1")), + HealthzBindAddress: net.ParseIP("127.0.0.1"), OOMScoreAdj: qos.KubeProxyOomScoreAdj, ResourceContainer: "/kube-proxy", } @@ -65,10 +65,10 @@ func NewProxyServer() *ProxyServer { // AddFlags adds flags for a specific ProxyServer to the specified FlagSet func (s *ProxyServer) AddFlags(fs *pflag.FlagSet) { - fs.Var(&s.BindAddress, "bind-address", "The IP address for the proxy server to serve on (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.BindAddress, "bind-address", s.BindAddress, "The IP address for the proxy server to serve on (set to 0.0.0.0 for all interfaces)") fs.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)") fs.IntVar(&s.HealthzPort, "healthz-port", s.HealthzPort, "The port to bind the health check server. Use 0 to disable.") - fs.Var(&s.HealthzBindAddress, "healthz-bind-address", "The IP address for the health check server to serve on, defaulting to 127.0.0.1 (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.HealthzBindAddress, "healthz-bind-address", s.HealthzBindAddress, "The IP address for the health check server to serve on, defaulting to 127.0.0.1 (set to 0.0.0.0 for all interfaces)") fs.IntVar(&s.OOMScoreAdj, "oom-score-adj", s.OOMScoreAdj, "The oom_score_adj value for kube-proxy process. Values must be within the range [-1000, 1000]") fs.StringVar(&s.ResourceContainer, "resource-container", s.ResourceContainer, "Absolute name of the resource-only container to create and run the Kube-proxy in (Default: /kube-proxy).") fs.StringVar(&s.Kubeconfig, "kubeconfig", s.Kubeconfig, "Path to kubeconfig file with authorization information (the master location is set by the master flag).") @@ -94,11 +94,11 @@ func (s *ProxyServer) Run(_ []string) error { endpointsConfig := config.NewEndpointsConfig() protocol := iptables.ProtocolIpv4 - if net.IP(s.BindAddress).To4() == nil { + if s.BindAddress.To4() == nil { protocol = iptables.ProtocolIpv6 } loadBalancer := userspace.NewLoadBalancerRR() - proxier, err := userspace.NewProxier(loadBalancer, net.IP(s.BindAddress), iptables.New(exec.New(), protocol), s.PortRange) + proxier, err := userspace.NewProxier(loadBalancer, s.BindAddress, iptables.New(exec.New(), protocol), s.PortRange) if err != nil { glog.Fatalf("Unable to create proxer: %v", err) } diff --git a/cmd/kubelet/app/server.go b/cmd/kubelet/app/server.go index 6bb9d4a952a..4ea2010a2d1 100644 --- a/cmd/kubelet/app/server.go +++ b/cmd/kubelet/app/server.go @@ -73,7 +73,7 @@ type KubeletServer struct { ManifestURL string ManifestURLHeader string EnableServer bool - Address util.IP + Address net.IP Port uint ReadOnlyPort uint HostnameOverride string @@ -93,14 +93,14 @@ type KubeletServer struct { KubeConfig util.StringFlag CadvisorPort uint HealthzPort int - HealthzBindAddress util.IP + HealthzBindAddress net.IP OOMScoreAdj int APIServerList []string RegisterNode bool StandaloneMode bool ClusterDomain string MasterServiceNamespace string - ClusterDNS util.IP + ClusterDNS net.IP StreamingConnectionIdleTimeout time.Duration ImageGCHighThresholdPercent int ImageGCLowThresholdPercent int @@ -153,7 +153,7 @@ func NewKubeletServer() *KubeletServer { FileCheckFrequency: 20 * time.Second, HTTPCheckFrequency: 20 * time.Second, EnableServer: true, - Address: util.IP(net.ParseIP("0.0.0.0")), + Address: net.ParseIP("0.0.0.0"), Port: ports.KubeletPort, ReadOnlyPort: ports.KubeletReadOnlyPort, PodInfraContainerImage: dockertools.PodInfraContainerImage, @@ -167,7 +167,7 @@ func NewKubeletServer() *KubeletServer { KubeConfig: util.NewStringFlag("/var/lib/kubelet/kubeconfig"), CadvisorPort: 4194, HealthzPort: 10248, - HealthzBindAddress: util.IP(net.ParseIP("127.0.0.1")), + HealthzBindAddress: net.ParseIP("127.0.0.1"), RegisterNode: true, // will be ignored if no apiserver is configured OOMScoreAdj: qos.KubeletOomScoreAdj, MasterServiceNamespace: api.NamespaceDefault, @@ -198,7 +198,7 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.ManifestURL, "manifest-url", s.ManifestURL, "URL for accessing the container manifest") fs.StringVar(&s.ManifestURLHeader, "manifest-url-header", s.ManifestURLHeader, "HTTP header to use when accessing the manifest URL, with the key separated from the value with a ':', as in 'key:value'") fs.BoolVar(&s.EnableServer, "enable-server", s.EnableServer, "Enable the Kubelet's server") - fs.Var(&s.Address, "address", "The IP address for the Kubelet to serve on (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.Address, "address", s.Address, "The IP address for the Kubelet to serve on (set to 0.0.0.0 for all interfaces)") fs.UintVar(&s.Port, "port", s.Port, "The port for the Kubelet to serve on. Note that \"kubectl logs\" will not work if you set this flag.") // see #9325 fs.UintVar(&s.ReadOnlyPort, "read-only-port", s.ReadOnlyPort, "The read-only port for the Kubelet to serve on (set to 0 to disable)") fs.StringVar(&s.TLSCertFile, "tls-cert-file", s.TLSCertFile, ""+ @@ -226,13 +226,13 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.Var(&s.KubeConfig, "kubeconfig", "Path to a kubeconfig file, specifying how to authenticate to API server (the master location is set by the api-servers flag).") fs.UintVar(&s.CadvisorPort, "cadvisor-port", s.CadvisorPort, "The port of the localhost cAdvisor endpoint") fs.IntVar(&s.HealthzPort, "healthz-port", s.HealthzPort, "The port of the localhost healthz endpoint") - fs.Var(&s.HealthzBindAddress, "healthz-bind-address", "The IP address for the healthz server to serve on, defaulting to 127.0.0.1 (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.HealthzBindAddress, "healthz-bind-address", s.HealthzBindAddress, "The IP address for the healthz server to serve on, defaulting to 127.0.0.1 (set to 0.0.0.0 for all interfaces)") fs.IntVar(&s.OOMScoreAdj, "oom-score-adj", s.OOMScoreAdj, "The oom-score-adj value for kubelet process. Values must be within the range [-1000, 1000]") fs.StringSliceVar(&s.APIServerList, "api-servers", []string{}, "List of Kubernetes API servers for publishing events, and reading pods and services. (ip:port), comma separated.") fs.BoolVar(&s.RegisterNode, "register-node", s.RegisterNode, "Register the node with the apiserver (defaults to true if --api-server is set)") fs.StringVar(&s.ClusterDomain, "cluster-domain", s.ClusterDomain, "Domain for this cluster. If set, kubelet will configure all containers to search this domain in addition to the host's search domains") fs.StringVar(&s.MasterServiceNamespace, "master-service-namespace", s.MasterServiceNamespace, "The namespace from which the kubernetes master services should be injected into pods") - fs.Var(&s.ClusterDNS, "cluster-dns", "IP address for a cluster DNS server. If set, kubelet will configure all containers to use this for DNS resolution in addition to the host's DNS servers") + fs.IPVar(&s.ClusterDNS, "cluster-dns", s.ClusterDNS, "IP address for a cluster DNS server. If set, kubelet will configure all containers to use this for DNS resolution in addition to the host's DNS servers") fs.DurationVar(&s.StreamingConnectionIdleTimeout, "streaming-connection-idle-timeout", 0, "Maximum time a streaming connection can be idle before the connection is automatically closed. Example: '5m'") fs.DurationVar(&s.NodeStatusUpdateFrequency, "node-status-update-frequency", s.NodeStatusUpdateFrequency, "Specifies how often kubelet posts node status to master. Note: be cautious when changing the constant, it must work with nodeMonitorGracePeriod in nodecontroller. Default: 10s") fs.IntVar(&s.ImageGCHighThresholdPercent, "image-gc-high-threshold", s.ImageGCHighThresholdPercent, "The percent of disk usage after which image garbage collection is always run. Default: 90%%") @@ -568,7 +568,7 @@ func SimpleKubelet(client *client.Client, ManifestURL: manifestURL, PodInfraContainerImage: dockertools.PodInfraContainerImage, Port: port, - Address: util.IP(net.ParseIP(address)), + Address: net.ParseIP(address), EnableServer: true, EnableDebuggingHandlers: true, HTTPCheckFrequency: 1 * time.Second, @@ -672,12 +672,12 @@ func startKubelet(k KubeletBootstrap, podCfg *config.PodConfig, kc *KubeletConfi // start the kubelet server if kc.EnableServer { go util.Forever(func() { - k.ListenAndServe(net.IP(kc.Address), kc.Port, kc.TLSOptions, kc.EnableDebuggingHandlers) + k.ListenAndServe(kc.Address, kc.Port, kc.TLSOptions, kc.EnableDebuggingHandlers) }, 0) } if kc.ReadOnlyPort > 0 { go util.Forever(func() { - k.ListenAndServeReadOnly(net.IP(kc.Address), kc.ReadOnlyPort) + k.ListenAndServeReadOnly(kc.Address, kc.ReadOnlyPort) }, 0) } } @@ -710,7 +710,7 @@ type KubeletConfig struct { KubeClient *client.Client DockerClient dockertools.DockerInterface CadvisorInterface cadvisor.Interface - Address util.IP + Address net.IP AllowPrivileged bool HostNetworkSources []string HostnameOverride string @@ -732,7 +732,7 @@ type KubeletConfig struct { RegisterNode bool StandaloneMode bool ClusterDomain string - ClusterDNS util.IP + ClusterDNS net.IP EnableServer bool EnableDebuggingHandlers bool Port uint @@ -795,7 +795,7 @@ func createAndInitKubelet(kc *KubeletConfig) (k KubeletBootstrap, pc *config.Pod kc.RegisterNode, kc.StandaloneMode, kc.ClusterDomain, - net.IP(kc.ClusterDNS), + kc.ClusterDNS, kc.MasterServiceNamespace, kc.VolumePlugins, kc.NetworkPlugins, diff --git a/contrib/mesos/pkg/executor/service/service.go b/contrib/mesos/pkg/executor/service/service.go index 0833aad9d1f..4f127864206 100644 --- a/contrib/mesos/pkg/executor/service/service.go +++ b/contrib/mesos/pkg/executor/service/service.go @@ -96,7 +96,7 @@ func NewKubeletExecutorServer() *KubeletExecutorServer { } else { k.RootDirectory = pwd // mesos sandbox dir } - k.Address = util.IP(net.ParseIP(defaultBindingAddress())) + k.Address = net.ParseIP(defaultBindingAddress()) k.ShutdownFD = -1 // indicates unspecified FD return k @@ -404,7 +404,7 @@ func (ks *KubeletExecutorServer) createAndInitKubelet( dconfig := bindings.DriverConfig{ Executor: exec, HostnameOverride: ks.HostnameOverride, - BindingAddress: net.IP(ks.Address), + BindingAddress: ks.Address, } if driver, err := bindings.NewMesosExecutorDriver(dconfig); err != nil { log.Fatalf("failed to create executor driver: %v", err) @@ -427,7 +427,7 @@ type kubeletExecutor struct { *kubelet.Kubelet initialize sync.Once driver bindings.ExecutorDriver - address util.IP + address net.IP dockerClient dockertools.DockerInterface hks hyperkube.Interface kubeletFinished chan struct{} // closed once kubelet.Run() returns diff --git a/contrib/mesos/pkg/scheduler/service/service.go b/contrib/mesos/pkg/scheduler/service/service.go index 4be5ce923ce..e61542cdb1d 100644 --- a/contrib/mesos/pkg/scheduler/service/service.go +++ b/contrib/mesos/pkg/scheduler/service/service.go @@ -66,7 +66,6 @@ import ( "k8s.io/kubernetes/pkg/master/ports" etcdstorage "k8s.io/kubernetes/pkg/storage/etcd" "k8s.io/kubernetes/pkg/tools" - "k8s.io/kubernetes/pkg/util" ) const ( @@ -82,7 +81,7 @@ const ( type SchedulerServer struct { Port int - Address util.IP + Address net.IP EnableProfiling bool AuthPath string APIServerList []string @@ -125,10 +124,10 @@ type SchedulerServer struct { FrameworkWebURI string HA bool AdvertisedAddress string - ServiceAddress util.IP + ServiceAddress net.IP HADomain string KMPath string - ClusterDNS util.IP + ClusterDNS net.IP ClusterDomain string KubeletRootDirectory string KubeletDockerEndpoint string @@ -157,7 +156,7 @@ type schedulerProcessInterface interface { func NewSchedulerServer() *SchedulerServer { s := SchedulerServer{ Port: ports.SchedulerPort, - Address: util.IP(net.ParseIP("127.0.0.1")), + Address: net.ParseIP("127.0.0.1"), FailoverTimeout: time.Duration((1 << 62) - 1).Seconds(), RunProxy: true, @@ -196,7 +195,7 @@ func NewSchedulerServer() *SchedulerServer { func (s *SchedulerServer) addCoreFlags(fs *pflag.FlagSet) { fs.IntVar(&s.Port, "port", s.Port, "The port that the scheduler's http service runs on") - fs.Var(&s.Address, "address", "The IP address to serve on (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.Address, "address", s.Address, "The IP address to serve on (set to 0.0.0.0 for all interfaces)") fs.BoolVar(&s.EnableProfiling, "profiling", s.EnableProfiling, "Enable profiling via web interface host:port/debug/pprof/") fs.StringSliceVar(&s.APIServerList, "api-servers", s.APIServerList, "List of Kubernetes API servers for publishing events, and reading pods and services. (ip:port), comma separated.") fs.StringVar(&s.AuthPath, "auth-path", s.AuthPath, "Path to .kubernetes_auth file, specifying how to authenticate to API server.") @@ -204,7 +203,7 @@ func (s *SchedulerServer) addCoreFlags(fs *pflag.FlagSet) { fs.StringVar(&s.EtcdConfigFile, "etcd-config", s.EtcdConfigFile, "The config file for the etcd client. Mutually exclusive with --etcd-servers.") fs.BoolVar(&s.AllowPrivileged, "allow-privileged", s.AllowPrivileged, "If true, allow privileged containers.") fs.StringVar(&s.ClusterDomain, "cluster-domain", s.ClusterDomain, "Domain for this cluster. If set, kubelet will configure all containers to search this domain in addition to the host's search domains") - fs.Var(&s.ClusterDNS, "cluster-dns", "IP address for a cluster DNS server. If set, kubelet will configure all containers to use this for DNS resolution in addition to the host's DNS servers") + fs.IPVar(&s.ClusterDNS, "cluster-dns", s.ClusterDNS, "IP address for a cluster DNS server. If set, kubelet will configure all containers to use this for DNS resolution in addition to the host's DNS servers") fs.StringVar(&s.StaticPodsConfigPath, "static-pods-config", s.StaticPodsConfigPath, "Path for specification of static pods. Path should point to dir containing the staticPods configuration files. Defaults to none.") fs.StringVar(&s.MesosMaster, "mesos-master", s.MesosMaster, "Location of the Mesos master. The format is a comma-delimited list of of hosts like zk://host1:port,host2:port/mesos. If using ZooKeeper, pay particular attention to the leading zk:// and trailing /mesos! If not using ZooKeeper, standard URLs like http://localhost are also acceptable.") @@ -225,7 +224,7 @@ func (s *SchedulerServer) addCoreFlags(fs *pflag.FlagSet) { fs.StringVar(&s.FrameworkName, "framework-name", s.FrameworkName, "The framework name to register with Mesos.") fs.StringVar(&s.FrameworkWebURI, "framework-weburi", s.FrameworkWebURI, "A URI that points to a web-based interface for interacting with the framework.") fs.StringVar(&s.AdvertisedAddress, "advertised-address", s.AdvertisedAddress, "host:port address that is advertised to clients. May be used to construct artifact download URIs.") - fs.Var(&s.ServiceAddress, "service-address", "The service portal IP address that the scheduler should register with (if unset, chooses randomly)") + fs.IPVar(&s.ServiceAddress, "service-address", s.ServiceAddress, "The service portal IP address that the scheduler should register with (if unset, chooses randomly)") fs.Var(&s.DefaultContainerCPULimit, "default-container-cpu-limit", "Containers without a CPU resource limit are admitted this much CPU shares") fs.Var(&s.DefaultContainerMemLimit, "default-container-mem-limit", "Containers without a memory resource limit are admitted this much amount of memory in MB") @@ -662,12 +661,12 @@ func (s *SchedulerServer) bootstrap(hks hyperkube.Interface, sc *schedcfg.Config Framework: info, Master: masterUri, Credential: cred, - BindingAddress: net.IP(s.Address), + BindingAddress: s.Address, BindingPort: uint16(s.DriverPort), HostnameOverride: s.HostnameOverride, WithAuthContext: func(ctx context.Context) context.Context { ctx = auth.WithLoginProvider(ctx, s.MesosAuthProvider) - ctx = sasl.WithBindingAddress(ctx, net.IP(s.Address)) + ctx = sasl.WithBindingAddress(ctx, s.Address) return ctx }, } diff --git a/pkg/util/net.go b/pkg/util/net.go index 1b5f3855e11..cebe4c61378 100644 --- a/pkg/util/net.go +++ b/pkg/util/net.go @@ -17,30 +17,10 @@ limitations under the License. package util import ( - "fmt" "net" "strings" ) -// IP adapts net.IP for use as a flag. -type IP net.IP - -func (ip IP) String() string { - return net.IP(ip).String() -} - -func (ip *IP) Set(value string) error { - *ip = IP(net.ParseIP(strings.TrimSpace(value))) - if *ip == nil { - return fmt.Errorf("invalid IP address: '%s'", value) - } - return nil -} - -func (*IP) Type() string { - return "ip" -} - // IPNet adapts net.IPNet for use as a flag. type IPNet net.IPNet diff --git a/pkg/util/net_test.go b/pkg/util/net_test.go index 786ebfa5e86..e9202e21b05 100644 --- a/pkg/util/net_test.go +++ b/pkg/util/net_test.go @@ -22,45 +22,6 @@ import ( flag "github.com/spf13/pflag" ) -func TestIP(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0", true, "0.0.0.0"}, - {" 0.0.0.0 ", true, "0.0.0.0"}, - {"1.2.3.4", true, "1.2.3.4"}, - {"127.0.0.1", true, "127.0.0.1"}, - {"255.255.255.255", true, "255.255.255.255"}, - {"", false, ""}, - {"0", false, ""}, - {"localhost", false, ""}, - {"0.0.0", false, ""}, - {"0.0.0.", false, ""}, - {"0.0.0.0.", false, ""}, - {"0.0.0.256", false, ""}, - {"0 . 0 . 0 . 0", false, ""}, - } - - for i := range testCases { - tc := &testCases[i] - var f flag.Value = &IP{} - 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()) - } - } - } -} - func TestIPNet(t *testing.T) { testCases := []struct { input string diff --git a/plugin/cmd/kube-scheduler/app/server.go b/plugin/cmd/kube-scheduler/app/server.go index 0b308c9f074..8fedba4c5d4 100644 --- a/plugin/cmd/kube-scheduler/app/server.go +++ b/plugin/cmd/kube-scheduler/app/server.go @@ -48,7 +48,7 @@ import ( // SchedulerServer has all the context and params needed to run a Scheduler type SchedulerServer struct { Port int - Address util.IP + Address net.IP AlgorithmProvider string PolicyConfigFile string EnableProfiling bool @@ -62,7 +62,7 @@ type SchedulerServer struct { func NewSchedulerServer() *SchedulerServer { s := SchedulerServer{ Port: ports.SchedulerPort, - Address: util.IP(net.ParseIP("127.0.0.1")), + Address: net.ParseIP("127.0.0.1"), AlgorithmProvider: factory.DefaultProvider, } return &s @@ -71,7 +71,7 @@ func NewSchedulerServer() *SchedulerServer { // AddFlags adds flags for a specific SchedulerServer to the specified FlagSet func (s *SchedulerServer) AddFlags(fs *pflag.FlagSet) { fs.IntVar(&s.Port, "port", s.Port, "The port that the scheduler's http service runs on") - fs.Var(&s.Address, "address", "The IP address to serve on (set to 0.0.0.0 for all interfaces)") + fs.IPVar(&s.Address, "address", s.Address, "The IP address to serve on (set to 0.0.0.0 for all interfaces)") fs.StringVar(&s.AlgorithmProvider, "algorithm-provider", s.AlgorithmProvider, "The scheduling algorithm provider to use, one of: "+factory.ListAlgorithmProviders()) fs.StringVar(&s.PolicyConfigFile, "policy-config-file", s.PolicyConfigFile, "File with scheduler policy configuration") fs.BoolVar(&s.EnableProfiling, "profiling", true, "Enable profiling via web interface host:port/debug/pprof/") From f3282ff4d2735f1a1f228bfedd47c24e4a8abbf6 Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Wed, 5 Aug 2015 18:44:51 -0400 Subject: [PATCH 2/2] Use pflag IPNet instead of our own helpers Since pflag can handle net.IPNet arguements use that code. This means that our code no longer has casts back and forth and just natively uses net.IPNet. --- cmd/kube-apiserver/app/server.go | 8 +-- .../app/controllermanager.go | 8 +-- pkg/util/net.go | 43 ------------ pkg/util/net_test.go | 68 ------------------- 4 files changed, 8 insertions(+), 119 deletions(-) delete mode 100644 pkg/util/net.go delete mode 100644 pkg/util/net_test.go diff --git a/cmd/kube-apiserver/app/server.go b/cmd/kube-apiserver/app/server.go index 563562c25fa..f4e84a0cca1 100644 --- a/cmd/kube-apiserver/app/server.go +++ b/cmd/kube-apiserver/app/server.go @@ -94,7 +94,7 @@ type APIServer struct { EtcdPathPrefix string CorsAllowedOriginList []string AllowPrivileged bool - ServiceClusterIPRange util.IPNet // TODO: make this a list + ServiceClusterIPRange net.IPNet // TODO: make this a list ServiceNodePortRange util.PortRange EnableLogsSupport bool MasterServiceNamespace string @@ -197,8 +197,8 @@ func (s *APIServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.EtcdPathPrefix, "etcd-prefix", s.EtcdPathPrefix, "The prefix for all resource paths in etcd.") fs.StringSliceVar(&s.CorsAllowedOriginList, "cors-allowed-origins", s.CorsAllowedOriginList, "List of allowed origins for CORS, comma separated. An allowed origin can be a regular expression to support subdomain matching. If this list is empty CORS will not be enabled.") fs.BoolVar(&s.AllowPrivileged, "allow-privileged", s.AllowPrivileged, "If true, allow privileged containers.") - fs.Var(&s.ServiceClusterIPRange, "service-cluster-ip-range", "A CIDR notation IP range from which to assign service cluster IPs. This must not overlap with any IP ranges assigned to nodes for pods.") - fs.Var(&s.ServiceClusterIPRange, "portal-net", "Deprecated: see --service-cluster-ip-range instead.") + fs.IPNetVar(&s.ServiceClusterIPRange, "service-cluster-ip-range", s.ServiceClusterIPRange, "A CIDR notation IP range from which to assign service cluster IPs. This must not overlap with any IP ranges assigned to nodes for pods.") + fs.IPNetVar(&s.ServiceClusterIPRange, "portal-net", s.ServiceClusterIPRange, "Deprecated: see --service-cluster-ip-range instead.") fs.MarkDeprecated("portal-net", "see --service-cluster-ip-range instead.") fs.Var(&s.ServiceNodePortRange, "service-node-port-range", "A port range to reserve for services with NodePort visibility. Example: '30000-32767'. Inclusive at both ends of the range.") fs.Var(&s.ServiceNodePortRange, "service-node-ports", "Deprecated: see --service-node-port-range instead.") @@ -325,7 +325,7 @@ func (s *APIServer) Run(_ []string) error { glog.Fatalf("Invalid experimental storage version or misconfigured etcd: %v", err) } - n := net.IPNet(s.ServiceClusterIPRange) + n := s.ServiceClusterIPRange // Default to the private server key for service account token signing if s.ServiceAccountKeyFile == "" && s.TLSPrivateKeyFile != "" { diff --git a/cmd/kube-controller-manager/app/controllermanager.go b/cmd/kube-controller-manager/app/controllermanager.go index d5ad9c023a1..f4864dbe1de 100644 --- a/cmd/kube-controller-manager/app/controllermanager.go +++ b/cmd/kube-controller-manager/app/controllermanager.go @@ -78,7 +78,7 @@ type CMServer struct { RootCAFile string ClusterName string - ClusterCIDR util.IPNet + ClusterCIDR net.IPNet AllocateNodeCIDRs bool EnableProfiling bool @@ -137,7 +137,7 @@ func (s *CMServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.ServiceAccountKeyFile, "service-account-private-key-file", s.ServiceAccountKeyFile, "Filename containing a PEM-encoded private RSA key used to sign service account tokens.") fs.BoolVar(&s.EnableProfiling, "profiling", true, "Enable profiling via web interface host:port/debug/pprof/") fs.StringVar(&s.ClusterName, "cluster-name", s.ClusterName, "The instance prefix for the cluster") - fs.Var(&s.ClusterCIDR, "cluster-cidr", "CIDR Range for Pods in cluster.") + fs.IPNetVar(&s.ClusterCIDR, "cluster-cidr", s.ClusterCIDR, "CIDR Range for Pods in cluster.") fs.BoolVar(&s.AllocateNodeCIDRs, "allocate-node-cidrs", false, "Should CIDRs for Pods be allocated and set on the cloud provider.") fs.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)") fs.StringVar(&s.Kubeconfig, "kubeconfig", s.Kubeconfig, "Path to kubeconfig file with authorization and master location information.") @@ -197,7 +197,7 @@ func (s *CMServer) Run(_ []string) error { nodeController := nodecontroller.NewNodeController(cloud, kubeClient, s.PodEvictionTimeout, nodecontroller.NewPodEvictor(util.NewTokenBucketRateLimiter(s.DeletingPodsQps, s.DeletingPodsBurst)), - s.NodeMonitorGracePeriod, s.NodeStartupGracePeriod, s.NodeMonitorPeriod, (*net.IPNet)(&s.ClusterCIDR), s.AllocateNodeCIDRs) + s.NodeMonitorGracePeriod, s.NodeStartupGracePeriod, s.NodeMonitorPeriod, &s.ClusterCIDR, s.AllocateNodeCIDRs) nodeController.Run(s.NodeSyncPeriod) serviceController := servicecontroller.New(cloud, kubeClient, s.ClusterName) @@ -211,7 +211,7 @@ func (s *CMServer) Run(_ []string) error { } else if routes, ok := cloud.Routes(); !ok { glog.Warning("allocate-node-cidrs is set, but cloud provider does not support routes. Will not manage routes.") } else { - routeController := routecontroller.New(routes, kubeClient, s.ClusterName, (*net.IPNet)(&s.ClusterCIDR)) + routeController := routecontroller.New(routes, kubeClient, s.ClusterName, &s.ClusterCIDR) routeController.Run(s.NodeSyncPeriod) } } diff --git a/pkg/util/net.go b/pkg/util/net.go deleted file mode 100644 index cebe4c61378..00000000000 --- a/pkg/util/net.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors All rights reserved. - -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 util - -import ( - "net" - "strings" -) - -// IPNet adapts net.IPNet for use as a flag. -type IPNet net.IPNet - -func (ipnet IPNet) String() string { - n := net.IPNet(ipnet) - return n.String() -} - -func (ipnet *IPNet) Set(value string) error { - _, n, err := net.ParseCIDR(strings.TrimSpace(value)) - if err != nil { - return err - } - *ipnet = IPNet(*n) - return nil -} - -func (*IPNet) Type() string { - return "ipNet" -} diff --git a/pkg/util/net_test.go b/pkg/util/net_test.go deleted file mode 100644 index e9202e21b05..00000000000 --- a/pkg/util/net_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors All rights reserved. - -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 util - -import ( - "testing" - - flag "github.com/spf13/pflag" -) - -func TestIPNet(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0/0", true, "0.0.0.0/0"}, - {" 0.0.0.0/0 ", true, "0.0.0.0/0"}, - {"1.2.3.4/8", true, "1.0.0.0/8"}, - {"127.0.0.1/16", true, "127.0.0.0/16"}, - {"255.255.255.255/19", true, "255.255.224.0/19"}, - {"255.255.255.255/32", true, "255.255.255.255/32"}, - {"", false, ""}, - {"/0", false, ""}, - {"0", false, ""}, - {"0/0", false, ""}, - {"localhost/0", false, ""}, - {"0.0.0/4", false, ""}, - {"0.0.0./8", false, ""}, - {"0.0.0.0./12", false, ""}, - {"0.0.0.256/16", false, ""}, - {"0.0.0.0 /20", false, ""}, - {"0.0.0.0/ 24", false, ""}, - {"0 . 0 . 0 . 0 / 28", false, ""}, - {"0.0.0.0/33", false, ""}, - } - - for i := range testCases { - tc := &testCases[i] - var f flag.Value = &IPNet{} - 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()) - } - } - } -}