func TestUDPProxyUpdateDelete(t *testing.T) {
	lb := NewLoadBalancerRR()
	service := ServicePortName{types.NamespacedName{"testnamespace", "echo"}, "p"}
	lb.OnUpdate([]api.Endpoints{
		{
			ObjectMeta: api.ObjectMeta{Namespace: service.Namespace, Name: service.Name},
			Subsets: []api.EndpointSubset{{
				Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
				Ports:     []api.EndpointPort{{Name: "p", Port: udpServerPort}},
			}},
		},
	})

	p := CreateProxier(lb, net.ParseIP("0.0.0.0"), &fakeIptables{}, net.ParseIP("127.0.0.1"))
	waitForNumProxyLoops(t, p, 0)

	svcInfo, err := p.addServiceOnPort(service, "UDP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("udp", joinHostPort("", svcInfo.proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()
	waitForNumProxyLoops(t, p, 1)

	p.OnUpdate([]api.Service{})
	if err := waitForClosedPortUDP(p, svcInfo.proxyPort); err != nil {
		t.Fatalf(err.Error())
	}
	waitForNumProxyLoops(t, p, 0)
}
Example #2
0
func TestLinuxConnections(t *testing.T) {
	fs_hook.Mock(mockFS)
	defer fs_hook.Restore()
	scanner := NewConnectionScanner(process.NewWalker("/proc"))
	defer scanner.Stop()

	// let the background scanner finish its first pass
	time.Sleep(1 * time.Second)

	iter, err := scanner.Connections(true)
	if err != nil {
		t.Fatal(err)
	}
	have := iter.Next()
	want := &Connection{
		LocalAddress:  net.ParseIP("0.0.0.0").To4(),
		LocalPort:     42688,
		RemoteAddress: net.ParseIP("0.0.0.0").To4(),
		RemotePort:    0,
		inode:         5107,
		Proc: Proc{
			PID:  1,
			Name: "foo",
		},
	}
	if !reflect.DeepEqual(want, have) {
		t.Fatal(test.Diff(want, have))
	}

	if have := iter.Next(); have != nil {
		t.Fatal(have)
	}

}
Example #3
0
// Function to mock a domain object
func newDomain() model.Domain {
	var domain model.Domain
	domain.FQDN = "rafael.net.br"

	domain.Nameservers = []model.Nameserver{
		{
			Host: "ns1.rafael.net.br",
			IPv4: net.ParseIP("127.0.0.1"),
			IPv6: net.ParseIP("::1"),
		},
		{
			Host: "ns2.rafael.net.br",
			IPv4: net.ParseIP("127.0.0.2"),
		},
	}

	domain.DSSet = []model.DS{
		{
			Keytag:    1234,
			Algorithm: model.DSAlgorithmRSASHA1,
			Digest:    "A790A11EA430A85DA77245F091891F73AA740483",
		},
	}

	owner, _ := mail.ParseAddress("*****@*****.**")
	domain.Owners = []model.Owner{
		{
			Email:    owner,
			Language: "pt-BR",
		},
	}

	return domain
}
Example #4
0
// getMyIP should return the IPv6 addresses of the IP provider if the useIPv4 flag is set to false.
func Test_getMyIP_UseIPv4False_IPProviderHasIPv6Addresses_IPv46AddressesAreReturned(t *testing.T) {
	// arrange
	ipProvider := testIPProvider{
		ipv4IPs: []net.IP{
			net.ParseIP("127.0.0.1"),
		},
		ipv4Err: nil,
		ipv6IPs: []net.IP{
			net.ParseIP("::1"),
		},
		ipv6Err: nil,
	}
	selectionOption := "all"
	useIPv4 := false

	// act
	ips, _ := getMyIP(ipProvider, selectionOption, useIPv4)

	// assert
	expectedResult := []net.IP{
		net.ParseIP("::1"),
	}
	if fmt.Sprintf("%s", ips) != fmt.Sprintf("%s", expectedResult) {
		t.Fail()
		t.Logf("getMyIP(ipProvider, %q, %v) returned %q but should have returned %q", selectionOption, useIPv4, ips, expectedResult)
	}

}
Example #5
0
// NewKubeletServer will create a new KubeletServer with default values.
func NewKubeletServer() *KubeletServer {
	return &KubeletServer{
		Address:                     net.ParseIP("0.0.0.0"),
		AuthPath:                    util.NewStringFlag("/var/lib/kubelet/kubernetes_auth"), // deprecated
		CAdvisorPort:                4194,
		CertDirectory:               "/var/run/kubernetes",
		CgroupRoot:                  "",
		ConfigureCBR0:               false,
		ContainerRuntime:            "docker",
		CPUCFSQuota:                 false,
		DockerDaemonContainer:       "/docker-daemon",
		DockerExecHandlerName:       "native",
		EventBurst:                  10,
		EventRecordQPS:              5.0,
		EnableDebuggingHandlers:     true,
		EnableServer:                true,
		FileCheckFrequency:          20 * time.Second,
		HealthzBindAddress:          net.ParseIP("127.0.0.1"),
		HealthzPort:                 10248,
		HostNetworkSources:          kubetypes.AllSource,
		HostPIDSources:              kubetypes.AllSource,
		HostIPCSources:              kubetypes.AllSource,
		HTTPCheckFrequency:          20 * time.Second,
		ImageGCHighThresholdPercent: 90,
		ImageGCLowThresholdPercent:  80,
		KubeConfig:                  util.NewStringFlag("/var/lib/kubelet/kubeconfig"),
		LowDiskSpaceThresholdMB:     256,
		MasterServiceNamespace:      api.NamespaceDefault,
		MaxContainerCount:           100,
		MaxPerPodContainerCount:     2,
		MaxOpenFiles:                1000000,
		MaxPods:                     40,
		MinimumGCAge:                1 * time.Minute,
		NetworkPluginDir:            "/usr/libexec/kubernetes/kubelet-plugins/net/exec/",
		NetworkPluginName:           "",
		NodeLabels:                  []string{},
		NodeLabelsFile:              "",
		NodeStatusUpdateFrequency:   10 * time.Second,
		OOMScoreAdj:                 qos.KubeletOOMScoreAdj,
		PodInfraContainerImage:      dockertools.PodInfraContainerImage,
		Port:                           ports.KubeletPort,
		ReadOnlyPort:                   ports.KubeletReadOnlyPort,
		RegisterNode:                   true, // will be ignored if no apiserver is configured
		RegisterSchedulable:            true,
		RegistryBurst:                  10,
		RegistryPullQPS:                5.0,
		ResourceContainer:              "/kubelet",
		RktPath:                        "",
		RktStage1Image:                 "",
		RootDirectory:                  defaultRootDir,
		SerializeImagePulls:            true,
		StreamingConnectionIdleTimeout: 5 * time.Minute,
		SyncFrequency:                  1 * time.Minute,
		SystemContainer:                "",
		ReconcileCIDR:                  true,
		KubeAPIQPS:                     5.0,
		KubeAPIBurst:                   10,
		ExperimentalFlannelOverlay:     experimentalFlannelOverlay,
	}
}
Example #6
0
func (proxier *Proxier) openPortal(service proxy.ServicePortName, info *serviceInfo) error {
	err := proxier.openOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service)
	if err != nil {
		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)
		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)
			if err != nil {
				return err
			}
		}
	}
	if info.nodePort != 0 {
		err = proxier.openNodePort(info.nodePort, info.protocol, proxier.listenIP, info.proxyPort, service)
		if err != nil {
			return err
		}
	}
	return nil
}
Example #7
0
// getMyIP (useIPv4 = true) should only return an error if the IP provider returns an error.
func Test_getMyIP_UseIPv4True_IPProviderReturnsError_NoIPsAreReturned_ErrorIsReturned(t *testing.T) {
	// arrange
	ipProvider := testIPProvider{
		ipv4IPs: []net.IP{
			net.ParseIP("127.0.0.1"),
		},
		ipv4Err: fmt.Errorf("IPv4 error"),
		ipv6IPs: []net.IP{
			net.ParseIP("::1"),
		},
		ipv6Err: fmt.Errorf("IPv6 error"),
	}
	selectionOption := "all"
	useIPv4 := false

	// act
	ips, err := getMyIP(ipProvider, selectionOption, useIPv4)

	// assert
	if len(ips) > 0 {
		t.Fail()
		t.Logf("getMyIP(ipProvider, %q, %v) returned %q but should not have returned anything because the IP provider returned an error", selectionOption, useIPv4, ips)
	}

	if err == nil {
		t.Fail()
		t.Logf("getMyIP(ipProvider, %q, %v) did not return an error even though the IP Provider responded with one.", selectionOption, useIPv4)
	}

}
Example #8
0
File: dns.go Project: ryansb/cjdcmd
// Resolve a hostname to an IP address using the system DNS settings first, then HypeDNS
func resolveHost(hostname string) (ips []string, err error) {
	var ip string
	// Try the system DNS setup
	result, _ := net.LookupHost(hostname)
	if len(result) > 0 {
		goto end
	}

	// Try with hypedns
	ip, err = lookupHypeDNS(hostname)

	if ip == "" || err != nil {
		err = fmt.Errorf("Unable to resolve hostname. This is usually caused by not having a route to hypedns. Please try again in a few seconds.")
		return
	}

	result = append(result, ip)

end:
	for _, addr := range result {
		tIP := net.ParseIP(addr)
		// Only grab the cjdns IP's
		if tIP[0] == 0xfc {
			ips = append(ips, padIPv6(net.ParseIP(addr)))
		}
	}

	return
}
Example #9
0
func TestStore(t *testing.T) {
	fakeClient, storage, backing := newStorage(t)
	if _, err := fakeClient.Set(key(), runtime.EncodeOrDie(testapi.Default.Codec(), validNewRangeAllocation()), 0); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if err := storage.Allocate(net.ParseIP("192.168.1.2")); err != nil {
		t.Fatal(err)
	}
	ok, err := backing.Allocate(1)
	if err != nil {
		t.Fatal(err)
	}
	if ok {
		t.Fatal("Expected allocation to fail")
	}
	if err := storage.Allocate(net.ParseIP("192.168.1.2")); err != ipallocator.ErrAllocated {
		t.Fatal(err)
	}

	obj := fakeClient.Data[key()]
	if obj.R == nil || obj.R.Node == nil {
		t.Fatalf("%s is empty: %#v", key(), obj)
	}
	t.Logf("data: %#v", obj.R.Node)
}
Example #10
0
func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error {
	var (
		err  error
		nMap map[string]interface{}
	)

	if err = json.Unmarshal(b, &nMap); err != nil {
		return err
	}

	if v, ok := nMap["AddressIPv4"]; ok {
		if ncfg.AddressIPv4, err = types.ParseCIDR(v.(string)); err != nil {
			return types.InternalErrorf("failed to decode bridge network address IPv4 after json unmarshal: %s", v.(string))
		}
	}

	if v, ok := nMap["AddressIPv6"]; ok {
		if ncfg.AddressIPv6, err = types.ParseCIDR(v.(string)); err != nil {
			return types.InternalErrorf("failed to decode bridge network address IPv6 after json unmarshal: %s", v.(string))
		}
	}

	ncfg.DefaultBindingIP = net.ParseIP(nMap["DefaultBindingIP"].(string))
	ncfg.DefaultGatewayIPv4 = net.ParseIP(nMap["DefaultGatewayIPv4"].(string))
	ncfg.DefaultGatewayIPv6 = net.ParseIP(nMap["DefaultGatewayIPv6"].(string))
	ncfg.ID = nMap["ID"].(string)
	ncfg.BridgeName = nMap["BridgeName"].(string)
	ncfg.EnableIPv6 = nMap["EnableIPv6"].(bool)
	ncfg.EnableIPMasquerade = nMap["EnableIPMasquerade"].(bool)
	ncfg.EnableICC = nMap["EnableICC"].(bool)
	ncfg.Mtu = int(nMap["Mtu"].(float64))

	return nil
}
Example #11
0
func applyNetConf(link netlink.Link, netConf config.InterfaceConfig) error {
	if netConf.DHCP {
		log.Infof("Running DHCP on %s", link.Attrs().Name)
		cmd := exec.Command("dhcpcd", "-A4", "-e", "force_hostname=true", link.Attrs().Name)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		if err := cmd.Run(); err != nil {
			log.Error(err)
		}
	} else if netConf.IPV4LL {
		if err := AssignLinkLocalIP(link); err != nil {
			log.Error("IPV4LL set failed")
			return err
		}
	} else if netConf.Address == "" {
		return nil
	} else {
		addr, err := netlink.ParseAddr(netConf.Address)
		if err != nil {
			return err
		}
		if err := netlink.AddrAdd(link, addr); err != nil {
			log.Error("addr add failed")
			return err
		}
		log.Infof("Set %s on %s", netConf.Address, link.Attrs().Name)
	}

	if netConf.MTU > 0 {
		if err := netlink.LinkSetMTU(link, netConf.MTU); err != nil {
			log.Error("set MTU Failed")
			return err
		}
	}

	if err := netlink.LinkSetUp(link); err != nil {
		log.Error("failed to setup link")
		return err
	}

	if netConf.Gateway != "" {
		gatewayIp := net.ParseIP(netConf.Gateway)
		if gatewayIp == nil {
			return errors.New("Invalid gateway address " + netConf.Gateway)
		}

		route := netlink.Route{
			Scope: netlink.SCOPE_UNIVERSE,
			Gw:    net.ParseIP(netConf.Gateway),
		}
		if err := netlink.RouteAdd(&route); err != nil {
			log.Error("gateway set failed")
			return err
		}

		log.Infof("Set default gateway %s", netConf.Gateway)
	}

	return nil
}
Example #12
0
// Check that we can prune an answer
func TestPrune(t *testing.T) {
	InitDefaultLogging(testing.Verbose())
	Info.Println("TestPrune starting")

	questionMsg := new(dns.Msg)
	questionMsg.SetQuestion("name", dns.TypeA)
	questionMsg.RecursionDesired = true
	question := &questionMsg.Question[0]
	records := []ZoneRecord{
		Record{"name", net.ParseIP("10.0.1.1"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.2"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.3"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.4"), 0, 0, 0},
	}

	reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL)
	reply.Answer[0].Header().Ttl = DefaultLocalTTL

	pruned := pruneAnswers(reply.Answer, 1)
	require.Equal(t, 1, len(pruned), "wrong number of answers")

	pruned = pruneAnswers(reply.Answer, 2)
	require.Equal(t, 2, len(pruned), "wrong number of answers")

	pruned = pruneAnswers(reply.Answer, 0)
	require.Equal(t, len(records), len(pruned), "wrong number of answers")
}
Example #13
0
func TestClusterConfig_translateAddressAndPort_Success(t *testing.T) {
	cfg := NewCluster()
	cfg.AddressTranslator = staticAddressTranslator(net.ParseIP("10.10.10.10"), 5432)
	newAddr, newPort := cfg.translateAddressPort(net.ParseIP("10.0.0.1"), 2345)
	assertTrue(t, "translated address", net.ParseIP("10.10.10.10").Equal(newAddr))
	assertEqual(t, "translated port", 5432, newPort)
}
Example #14
0
func TestClusterConfig_translateAddressAndPort_NilTranslator(t *testing.T) {
	cfg := NewCluster()
	assertNil(t, "cluster config address translator", cfg.AddressTranslator)
	newAddr, newPort := cfg.translateAddressPort(net.ParseIP("10.0.0.1"), 1234)
	assertTrue(t, "same address as provided", net.ParseIP("10.0.0.1").Equal(newAddr))
	assertEqual(t, "translated host and port", 1234, newPort)
}
Example #15
0
func TestUDPProxyTimeout(t *testing.T) {
	lb := NewLoadBalancerRR()
	service := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: "testnamespace", Name: "echo"}, Port: "p"}
	lb.OnEndpointsUpdate([]api.Endpoints{
		{
			ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
			Subsets: []api.EndpointSubset{{
				Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
				Ports:     []api.EndpointPort{{Name: "p", Port: udpServerPort}},
			}},
		},
	})

	p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest)
	if err != nil {
		t.Fatal(err)
	}
	waitForNumProxyLoops(t, p, 0)

	svcInfo, err := p.addServiceOnPort(service, "UDP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	waitForNumProxyLoops(t, p, 1)
	testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)
	// When connecting to a UDP service endpoint, there should be a Conn for proxy.
	waitForNumProxyClients(t, svcInfo, 1, time.Second)
	// If conn has no activity for serviceInfo.timeout since last Read/Write, it should be closed because of timeout.
	waitForNumProxyClients(t, svcInfo, 0, 2*time.Second)
}
Example #16
0
func ApiStruct2Peer(p *gobgpapi.Peer) *Peer {
	localCaps := capabilities{}
	remoteCaps := capabilities{}
	for _, buf := range p.Conf.LocalCap {
		c, _ := bgp.DecodeCapability(buf)
		localCaps = append(localCaps, c)
	}
	for _, buf := range p.Conf.RemoteCap {
		c, _ := bgp.DecodeCapability(buf)
		remoteCaps = append(remoteCaps, c)
	}
	conf := PeerConf{
		RemoteIp:     net.ParseIP(p.Conf.NeighborAddress),
		Id:           net.ParseIP(p.Conf.Id),
		RemoteAs:     p.Conf.PeerAs,
		LocalAs:      p.Conf.LocalAs,
		RemoteCap:    remoteCaps,
		LocalCap:     localCaps,
		PrefixLimits: p.Conf.PrefixLimits,
	}
	return &Peer{
		Conf:   conf,
		Info:   p.Info,
		Timers: p.Timers,
	}
}
Example #17
0
func init() {
	Describe("Testing with Ginkgo", func() {
		It("lookup host with a valid host", func() {
			res := createResolver()
			ip, err := res.LookupHost([]string{"8.8.8.8"}, "google.com.")

			assert.NoError(GinkgoT(), err)
			assert.NotNil(GinkgoT(), net.ParseIP(ip))
		})
		It("lookup host with an i p", func() {

			res := createResolver()
			ip, err := res.LookupHost([]string{"8.8.8.8"}, "74.125.239.101")

			assert.NoError(GinkgoT(), err)
			assert.Equal(GinkgoT(), ip, "74.125.239.101")
		})
		It("lookup host with multiple dns servers", func() {

			res := createResolver()
			ip, err := res.LookupHost([]string{"127.0.0.127", "8.8.8.8"}, "google.com.")

			assert.NoError(GinkgoT(), err)
			assert.NotNil(GinkgoT(), net.ParseIP(ip))
		})
		It("lookup host an unknown host", func() {

			res := createResolver()
			_, err := res.LookupHost([]string{"8.8.8.8"}, "google.com.local.")

			assert.Error(GinkgoT(), err)
		})
	})
}
// Take in an interface name ("lo", "eth0", "any") passed from either
// a config setting, by using the -listenInterface flag on client or
// -interface flag on server from the command line and return the IP
// address associated with it.
// If no interface is provided use the default loopback interface (127.0.0.1).
// If "any" is passed then listen on 0.0.0.0 for client (invalid with server)
func GetInterfaceIPAddress(listenInterface string) (string, error) {
	var ip net.IP
	if listenInterface == "" {
		ip = net.ParseIP("127.0.0.1")
		return ip.String(), nil
	} else if listenInterface == "any" {
		ip = net.ParseIP("0.0.0.0")
		return ip.String(), nil
	} else {
		availableInterfaces, err := net.InterfaceByName(listenInterface)
		if err != nil {
			return "", common.ContextError(err)
		}

		addrs, err := availableInterfaces.Addrs()
		if err != nil {
			return "", common.ContextError(err)
		}
		for _, addr := range addrs {
			iptype := addr.(*net.IPNet)
			if iptype == nil {
				continue
			}
			// TODO: IPv6 support
			ip = iptype.IP.To4()
			if ip == nil {
				continue
			}
			return ip.String(), nil
		}
	}

	return "", common.ContextError(errors.New("Could not find IP address of specified interface"))

}
Example #19
0
// Self returns the local node's endpoint information.
func (srv *Server) Self() *discover.Node {
	srv.lock.Lock()
	defer srv.lock.Unlock()

	// If the server's not running, return an empty node
	if !srv.running {
		return &discover.Node{IP: net.ParseIP("0.0.0.0")}
	}
	// If the node is running but discovery is off, manually assemble the node infos
	if srv.ntab == nil {
		// Inbound connections disabled, use zero address
		if srv.listener == nil {
			return &discover.Node{IP: net.ParseIP("0.0.0.0"), ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
		}
		// Otherwise inject the listener address too
		addr := srv.listener.Addr().(*net.TCPAddr)
		return &discover.Node{
			ID:  discover.PubkeyID(&srv.PrivateKey.PublicKey),
			IP:  addr.IP,
			TCP: uint16(addr.Port),
		}
	}
	// Otherwise return the live node infos
	return srv.ntab.Self()
}
Example #20
0
// Checks if the client set configurations for more than one network while creating a container
// Also checks if the IPAMConfig is valid
func (daemon *Daemon) verifyNetworkingConfig(nwConfig *networktypes.NetworkingConfig) error {
	if nwConfig == nil || len(nwConfig.EndpointsConfig) == 0 {
		return nil
	}
	if len(nwConfig.EndpointsConfig) == 1 {
		for _, v := range nwConfig.EndpointsConfig {
			if v != nil && v.IPAMConfig != nil {
				if v.IPAMConfig.IPv4Address != "" && net.ParseIP(v.IPAMConfig.IPv4Address).To4() == nil {
					return errors.NewBadRequestError(fmt.Errorf("invalid IPv4 address: %s", v.IPAMConfig.IPv4Address))
				}
				if v.IPAMConfig.IPv6Address != "" {
					n := net.ParseIP(v.IPAMConfig.IPv6Address)
					// if the address is an invalid network address (ParseIP == nil) or if it is
					// an IPv4 address (To4() != nil), then it is an invalid IPv6 address
					if n == nil || n.To4() != nil {
						return errors.NewBadRequestError(fmt.Errorf("invalid IPv6 address: %s", v.IPAMConfig.IPv6Address))
					}
				}
			}
		}
		return nil
	}
	l := make([]string, 0, len(nwConfig.EndpointsConfig))
	for k := range nwConfig.EndpointsConfig {
		l = append(l, k)
	}
	err := fmt.Errorf("Container cannot be connected to network endpoints: %s", strings.Join(l, ", "))
	return errors.NewBadRequestError(err)
}
Example #21
0
// If the select option "3,1" is used the IPs should be returned in the specified order.
func Test_getSelectedIPs_IPsSupplied_SelectOption31_IPsAreReturnedInCorrectOrder(t *testing.T) {
	// arrange
	ips := []net.IP{
		net.ParseIP("127.0.0.1"),
		net.ParseIP("127.0.0.2"),
		net.ParseIP("127.0.0.3"),
	}
	selectOption := "3,1"

	// act
	selectedIPs, err := getSelectedIPs(ips, selectOption)

	// assert
	expectedResult := []net.IP{
		net.ParseIP("127.0.0.3"),
		net.ParseIP("127.0.0.1"),
	}

	if fmt.Sprintf("%s", expectedResult) != fmt.Sprintf("%s", selectedIPs) {
		t.Fail()
		t.Errorf("getSelectedIPs(%q, %q) returned %q but should have returned %q.", ips, selectOption, selectedIPs, expectedResult)
	}

	if err != nil {
		t.Fail()
		t.Errorf("getSelectedIPs(%q, %q) should not return an error but returned: %s.", ips, selectOption, err.Error())
	}
}
Example #22
0
func setupRoute(config *configs.Config) error {
	for _, config := range config.Routes {
		_, dst, err := net.ParseCIDR(config.Destination)
		if err != nil {
			return err
		}
		src := net.ParseIP(config.Source)
		if src == nil {
			return fmt.Errorf("Invalid source for route: %s", config.Source)
		}
		gw := net.ParseIP(config.Gateway)
		if gw == nil {
			return fmt.Errorf("Invalid gateway for route: %s", config.Gateway)
		}
		l, err := netlink.LinkByName(config.InterfaceName)
		if err != nil {
			return err
		}
		route := &netlink.Route{
			Scope:     netlink.SCOPE_UNIVERSE,
			Dst:       dst,
			Src:       src,
			Gw:        gw,
			LinkIndex: l.Attrs().Index,
		}
		if err := netlink.RouteAdd(route); err != nil {
			return err
		}
	}
	return nil
}
Example #23
0
// 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)
}
Example #24
0
// NewAPIServer creates a new APIServer object with default parameters
func NewAPIServer() *APIServer {
	s := APIServer{
		InsecurePort:           8080,
		InsecureBindAddress:    net.ParseIP("127.0.0.1"),
		BindAddress:            net.ParseIP("0.0.0.0"),
		SecurePort:             6443,
		APIPrefix:              "/api",
		APIGroupPrefix:         "/apis",
		EventTTL:               1 * time.Hour,
		AuthorizationMode:      "AlwaysAllow",
		AdmissionControl:       "AlwaysAdmit",
		EtcdPathPrefix:         master.DefaultEtcdPathPrefix,
		EnableLogsSupport:      true,
		MasterServiceNamespace: api.NamespaceDefault,
		ClusterName:            "kubernetes",
		CertDirectory:          "/var/run/kubernetes",
		StorageVersions:        latest.AllPreferredGroupVersions(),

		RuntimeConfig: make(util.ConfigurationMap),
		KubeletConfig: client.KubeletConfig{
			Port:        ports.KubeletPort,
			EnableHttps: true,
			HTTPTimeout: time.Duration(5) * time.Second,
		},
	}

	return &s
}
Example #25
0
// updateKeys allows to add a new key and/or change the primary key and/or prune an existing key
// The primary key is the key used in transmission and will go in first position in the list.
func (d *driver) updateKeys(newKey, primary, pruneKey *key) error {
	logrus.Debugf("Updating Keys. New: %v, Primary: %v, Pruned: %v", newKey, primary, pruneKey)

	logrus.Debugf("Current: %v", d.keys)

	var (
		newIdx = -1
		priIdx = -1
		delIdx = -1
		lIP    = net.ParseIP(d.bindAddress)
	)

	d.Lock()
	// add new
	if newKey != nil {
		d.keys = append(d.keys, newKey)
		newIdx += len(d.keys)
	}
	for i, k := range d.keys {
		if primary != nil && k.tag == primary.tag {
			priIdx = i
		}
		if pruneKey != nil && k.tag == pruneKey.tag {
			delIdx = i
		}
	}
	d.Unlock()

	if (newKey != nil && newIdx == -1) ||
		(primary != nil && priIdx == -1) ||
		(pruneKey != nil && delIdx == -1) {
		return types.BadRequestErrorf("cannot find proper key indices while processing key update:"+
			"(newIdx,priIdx,delIdx):(%d, %d, %d)", newIdx, priIdx, delIdx)
	}

	d.secMapWalk(func(rIPs string, spis []*spi) ([]*spi, bool) {
		rIP := net.ParseIP(rIPs)
		return updateNodeKey(lIP, rIP, spis, d.keys, newIdx, priIdx, delIdx), false
	})

	d.Lock()
	// swap primary
	if priIdx != -1 {
		swp := d.keys[0]
		d.keys[0] = d.keys[priIdx]
		d.keys[priIdx] = swp
	}
	// prune
	if delIdx != -1 {
		if delIdx == 0 {
			delIdx = priIdx
		}
		d.keys = append(d.keys[:delIdx], d.keys[delIdx+1:]...)
	}
	d.Unlock()

	logrus.Debugf("Updated: %v", d.keys)

	return nil
}
Example #26
0
func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
	qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
	resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err)
	}

	respCh := resp.ResponseCh()
	select {
	case r := <-respCh:
		var macStr, maskStr, vtepStr string
		if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil {
			return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err)
		}

		mac, err := net.ParseMAC(macStr)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err)
		}

		return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil

	case <-time.After(time.Second):
		return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster")
	}
}
func TestAddRegistration(t *testing.T) {
	sa, clk, cleanUp := initSA(t)
	defer cleanUp()

	jwk := satest.GoodJWK()

	contact, err := core.ParseAcmeURL("mailto:[email protected]")
	if err != nil {
		t.Fatalf("unable to parse contact link: %s", err)
	}
	contacts := []*core.AcmeURL{contact}
	reg, err := sa.NewRegistration(core.Registration{
		Key:       jwk,
		Contact:   contacts,
		InitialIP: net.ParseIP("43.34.43.34"),
	})
	if err != nil {
		t.Fatalf("Couldn't create new registration: %s", err)
	}
	test.Assert(t, reg.ID != 0, "ID shouldn't be 0")
	test.AssertDeepEquals(t, reg.Contact, contacts)

	_, err = sa.GetRegistration(0)
	test.AssertError(t, err, "Registration object for ID 0 was returned")

	dbReg, err := sa.GetRegistration(reg.ID)
	test.AssertNotError(t, err, fmt.Sprintf("Couldn't get registration with ID %v", reg.ID))

	expectedReg := core.Registration{
		ID:        reg.ID,
		Key:       jwk,
		InitialIP: net.ParseIP("43.34.43.34"),
		CreatedAt: clk.Now(),
	}
	test.AssertEquals(t, dbReg.ID, expectedReg.ID)
	test.Assert(t, core.KeyDigestEquals(dbReg.Key, expectedReg.Key), "Stored key != expected")

	u, _ := core.ParseAcmeURL("test.com")

	newReg := core.Registration{
		ID:        reg.ID,
		Key:       jwk,
		Contact:   []*core.AcmeURL{u},
		InitialIP: net.ParseIP("72.72.72.72"),
		Agreement: "yes",
	}
	err = sa.UpdateRegistration(newReg)
	test.AssertNotError(t, err, fmt.Sprintf("Couldn't get registration with ID %v", reg.ID))
	dbReg, err = sa.GetRegistrationByKey(jwk)
	test.AssertNotError(t, err, "Couldn't get registration by key")

	test.AssertEquals(t, dbReg.ID, newReg.ID)
	test.AssertEquals(t, dbReg.Agreement, newReg.Agreement)

	var anotherJWK jose.JsonWebKey
	err = json.Unmarshal([]byte(anotherKey), &anotherJWK)
	test.AssertNotError(t, err, "couldn't unmarshal anotherJWK")
	_, err = sa.GetRegistrationByKey(anotherJWK)
	test.AssertError(t, err, "Registration object for invalid key was returned")
}
Example #28
0
func TestUDPProxy(t *testing.T) {
	lb := NewLoadBalancerRR()
	service := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: "testnamespace", Name: "echo"}, Port: "p"}
	lb.OnEndpointsUpdate([]api.Endpoints{
		{
			ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
			Subsets: []api.EndpointSubset{{
				Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
				Ports:     []api.EndpointPort{{Name: "p", Port: udpServerPort}},
			}},
		},
	})

	p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest)
	if err != nil {
		t.Fatal(err)
	}
	waitForNumProxyLoops(t, p, 0)

	svcInfo, err := p.addServiceOnPort(service, "UDP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)
	waitForNumProxyLoops(t, p, 1)
}
Example #29
0
func (r *resolver) SetupFunc(port int) func() {
	return (func() {
		var err error

		// DNS operates primarily on UDP
		addr := &net.UDPAddr{
			IP:   net.ParseIP(r.listenAddress),
			Port: port,
		}

		r.conn, err = net.ListenUDP("udp", addr)
		if err != nil {
			r.err = fmt.Errorf("error in opening name server socket %v", err)
			return
		}

		// Listen on a TCP as well
		tcpaddr := &net.TCPAddr{
			IP:   net.ParseIP(r.listenAddress),
			Port: port,
		}

		r.tcpListen, err = net.ListenTCP("tcp", tcpaddr)
		if err != nil {
			r.err = fmt.Errorf("error in opening name TCP server socket %v", err)
			return
		}
		r.err = nil
	})
}
func TestMultiPortProxy(t *testing.T) {
	lb := NewLoadBalancerRR()
	serviceP := ServicePortName{types.NamespacedName{"testnamespace", "echo-p"}, "p"}
	serviceQ := ServicePortName{types.NamespacedName{"testnamespace", "echo-q"}, "q"}
	lb.OnUpdate([]api.Endpoints{{
		ObjectMeta: api.ObjectMeta{Name: serviceP.Name, Namespace: serviceP.Namespace},
		Subsets: []api.EndpointSubset{{
			Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
			Ports:     []api.EndpointPort{{Name: "p", Protocol: "TCP", Port: tcpServerPort}},
		}},
	}, {
		ObjectMeta: api.ObjectMeta{Name: serviceQ.Name, Namespace: serviceQ.Namespace},
		Subsets: []api.EndpointSubset{{
			Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
			Ports:     []api.EndpointPort{{Name: "q", Protocol: "UDP", Port: udpServerPort}},
		}},
	}})

	p := CreateProxier(lb, net.ParseIP("0.0.0.0"), &fakeIptables{}, net.ParseIP("127.0.0.1"))
	waitForNumProxyLoops(t, p, 0)

	svcInfoP, err := p.addServiceOnPort(serviceP, "TCP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	testEchoTCP(t, "127.0.0.1", svcInfoP.proxyPort)
	waitForNumProxyLoops(t, p, 1)

	svcInfoQ, err := p.addServiceOnPort(serviceQ, "UDP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	testEchoUDP(t, "127.0.0.1", svcInfoQ.proxyPort)
	waitForNumProxyLoops(t, p, 2)
}