예제 #1
1
파일: net.go 프로젝트: taysom/va
func Port(networkType, service string) {
	port, err := net.LookupPort(networkType, service)
	if err != nil {
		log.Fatal("Error: ", err.Error())
	}
	fmt.Println("Service port ", port)
}
예제 #2
0
// Like FuzzySplitHostPort, but returns an integer for the port. Supports
// symbolic port names (e.g. "http"). If the port name is unknown, returns error.
//
// "net" must be the port namespace (e.g. "tcp" or "udp"). If "", the port must
// be given as an integer.
//
// If a port was not specified, port is 0.
func FuzzySplitHostPortI(network, hostport string) (host string, port uint16, err error) {
	host, ports, err := FuzzySplitHostPort(hostport)
	if err != nil {
		return
	}

	if ports == "" {
		return
	}

	px, err := strconv.ParseUint(ports, 10, 16)
	p := int(px)
	if err != nil {
		if network == "" {
			err = &net.AddrError{Err: "port must be numeric", Addr: ports}
			return
		}

		p, err = net.LookupPort(network, ports)
		if err != nil {
			return
		}
	}

	if p < 0 || p > 0xFFFF {
		err = &net.AddrError{Err: "invalid port", Addr: ports}
		return
	}

	port = uint16(p)
	return
}
예제 #3
0
func (bv *bindValue) Set(input string) error {
	if input == "" {
		return nil
	}
	if !strings.Contains(input, ":") {
		input = ":" + input
	}
	var err error
	bv.Host, bv.Port, err = net.SplitHostPort(input)
	if err != nil {
		return err
	}
	if bv.Host == "*" {
		bv.Host = ""
	} else if bv.Port == "127" {
		bv.Host = "127.0.0.1"
		bv.Port = bv.defport
	}
	if _, err = net.LookupPort("tcp", bv.Port); err != nil {
		if bv.Host != "" {
			return err
		}
		bv.Host, bv.Port = bv.Port, bv.defport
	}

	bv.string = bv.Host + ":" + bv.Port
	return nil
}
예제 #4
0
파일: bind.go 프로젝트: vadv/ostent
func (b *Bind) Set(input string) error {
	if input == "" {
		b.Port = b.defport
	} else {
		if !strings.Contains(input, ":") {
			input = ":" + input
		}
		var err error
		b.Host, b.Port, err = net.SplitHostPort(input)
		if err != nil {
			return err
		}
		if b.Host == "*" {
			b.Host = ""
		} else if b.Port == "127" {
			b.Host = "127.0.0.1"
			b.Port = b.defport
		}
		if _, err = net.LookupPort("tcp", b.Port); err != nil {
			if b.Host != "" {
				return err
			}
			b.Host, b.Port = b.Port, b.defport
		}
	}
	b.string = b.Host + ":" + b.Port
	return nil
}
예제 #5
0
func parseaddr(bind_spec, defport string) (string, error) {
	if !strings.Contains(bind_spec, ":") {
		bind_spec = ":" + bind_spec
	}
	host, port, err := net.SplitHostPort(bind_spec)
	if err != nil {
		return "", err
	}
	if host == "*" {
		host = ""
	} else if port == "127" {
		host = "127.0.0.1"
		port = defport
	}
	if _, err = net.LookupPort("tcp", port); err != nil {
		if host != "" {
			return "", err
		}
		host = port
		port = defport
	}
	if err = os.Setenv("HOST", host); err != nil {
		return "", err
	}
	if err = os.Setenv("PORT", port); err != nil {
		return "", err
	}

	return host + ":" + port, nil
}
예제 #6
0
파일: options.go 프로젝트: jxaas/jxaas
func GetOptions() *Options {
	flag.Parse()

	self := &Options{}

	self.AgentConf = *flagAgentConf
	self.ApiPasswordPath = *flagApiPasswordPath

	self.CfTenantId = *flagCfTenantId
	self.ListenAddress = *flagListenAddress

	host, port, err := net.SplitHostPort(self.ListenAddress)
	if err != nil {
		log.Warn("Cannot parse listen address: %v", self.ListenAddress)
		return nil
	}
	var portNum int
	if port == "" {
		portNum = 8080
	} else {
		portNum, err = net.LookupPort("tcp", port)
		if err != nil {
			log.Warn("Cannot resolve port: %v", port)
			return nil
		}
	}

	privateUrl := *flagPrivateUrl
	if privateUrl == "" {
		privateHost := host
		if privateHost == "" {
			ip, err := localIP()
			if err != nil {
				log.Warn("Error finding local IP", err)
				return nil
			}
			privateHost = ip.String()
		}

		privateUrl = fmt.Sprintf("http://%v:%v/xaasprivate", privateHost, portNum)
		log.Info("Chose private url: %v", privateUrl)
	}
	self.PrivateUrl = privateUrl

	authMode := *flagAuth
	authMode = strings.TrimSpace(authMode)
	authMode = strings.ToLower(authMode)
	if authMode == "openstack" {
		keystoneUrl := *flagKeystoneUrl
		self.Authenticator = auth.NewOpenstackMultiAuthenticator(keystoneUrl)
	} else if authMode == "development" {
		self.Authenticator = auth.NewDevelopmentAuthenticator()
	} else {
		log.Warn("Unknown authentication mode: %v", authMode)
		return nil
	}

	return self
}
예제 #7
0
func main() {

	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s service [network-type] \n", os.Args[0])
		os.Exit(1)
	}

	service := os.Args[1]

	var networkType string

	if len(os.Args) == 3 {
		networkType = os.Args[2]

		port, err := net.LookupPort(networkType, service)
		if err != nil {
			fmt.Println("Error: ", err.Error())
			os.Exit(2)
		}

		fmt.Printf("Service %s network Type %s port %d\n", service, networkType, port)

	} else {

		networkTypes := []string{"tcp", "udp"}

		var output string

		for _, networkType := range networkTypes {
			port, err := net.LookupPort(networkType, service)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
				continue
			} else {
				output = fmt.Sprintf("%s %s/%d", output, networkType, port)
			}
		}

		if len(output) > 0 {
			fmt.Printf("Service %s port(s): %s\n", service, output)
		}

	}

	os.Exit(0)
}
예제 #8
0
func setWKS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
	rr := new(WKS)
	rr.Hdr = h

	l := <-c
	if l.length == 0 {
		return rr, nil, l.comment
	}
	rr.Address = net.ParseIP(l.token)
	if rr.Address == nil {
		return nil, &ParseError{f, "bad WKS Address", l}, ""
	}

	<-c // zBlank
	l = <-c
	proto := "tcp"
	i, e := strconv.Atoi(l.token)
	if e != nil {
		return nil, &ParseError{f, "bad WKS Protocol", l}, ""
	}
	rr.Protocol = uint8(i)
	switch rr.Protocol {
	case 17:
		proto = "udp"
	case 6:
		proto = "tcp"
	default:
		return nil, &ParseError{f, "bad WKS Protocol", l}, ""
	}

	<-c
	l = <-c
	rr.BitMap = make([]uint16, 0)
	var (
		k   int
		err error
	)
	for l.value != zNewline && l.value != zEOF {
		switch l.value {
		case zBlank:
			// Ok
		case zString:
			if k, err = net.LookupPort(proto, l.token); err != nil {
				if i, e := strconv.Atoi(l.token); e != nil { // If a number use that
					return nil, &ParseError{f, "bad WKS BitMap", l}, ""
				} else {
					rr.BitMap = append(rr.BitMap, uint16(i))
				}
			}
			rr.BitMap = append(rr.BitMap, uint16(k))
		default:
			return nil, &ParseError{f, "bad WKS BitMap", l}, ""
		}
		l = <-c
	}
	return rr, nil, l.comment
}
예제 #9
0
파일: tlsa.go 프로젝트: FlyWings/kubernetes
// TLSAName returns the ownername of a TLSA resource record as per the
// rules specified in RFC 6698, Section 3.
func TLSAName(name, service, network string) (string, error) {
	if !IsFqdn(name) {
		return "", ErrFqdn
	}
	p, e := net.LookupPort(network, service)
	if e != nil {
		return "", e
	}
	return "_" + strconv.Itoa(p) + "._" + network + "." + name, nil
}
예제 #10
0
파일: tlsa.go 프로젝트: ActiveState/dns
// TLSAName returns the ownername of a TLSA resource record as per the
// rules specified in RFC 6698, Section 3. When an error occurs the
// empty string is returned.
func TLSAName(name, service, network string) string {
	if !IsFqdn(name) {
		return ""
	}
	p, e := net.LookupPort(network, service)
	if e != nil {
		return ""
	}
	return "_" + strconv.Itoa(p) + "_" + network + "." + name
}
예제 #11
0
파일: main.go 프로젝트: migdi/delphos-api
func validateFlags(logger lager.Logger) {
	_, portString, err := net.SplitHostPort(*listenAddress)
	if err != nil {
		logger.Fatal("failed-invalid-listen-address", err)
	}
	_, err = net.LookupPort("tcp", portString)
	if err != nil {
		logger.Fatal("failed-invalid-listen-port", err)
	}
}
예제 #12
0
func (p *policyPortValue) Set(value string) error {
	port, err := strconv.Atoi(value)
	if err != nil {
		port, err = net.LookupPort("", value)
		if err != nil {
			return err
		}
	}
	*p = policyPortValue(port)
	return nil
}
예제 #13
0
func setWKS(h RR_Header, c chan lex, f string) (RR, *ParseError) {
	rr := new(RR_WKS)
	rr.Hdr = h

	l := <-c
	rr.Address = net.ParseIP(l.token)
	if rr.Address == nil {
		return nil, &ParseError{f, "bad WKS Adress", l}
	}

	<-c // _BLANK
	l = <-c
	proto := "tcp"
	if i, e := strconv.Atoi(l.token); e != nil {
		return nil, &ParseError{f, "bad WKS Protocol", l}
	} else {
		rr.Protocol = uint8(i)
		switch rr.Protocol {
		case 17:
			proto = "udp"
		case 6:
			proto = "tcp"
		default:
			return nil, &ParseError{f, "bad WKS Protocol", l}
		}
	}

	<-c
	l = <-c
	rr.BitMap = make([]uint16, 0)
	var (
		k   int
		err error
	)
	for l.value != _NEWLINE && l.value != _EOF {
		switch l.value {
		case _BLANK:
			// Ok
		case _STRING:
			if k, err = net.LookupPort(proto, l.token); err != nil {
				if i, e := strconv.Atoi(l.token); e != nil { // If a number use that
					rr.BitMap = append(rr.BitMap, uint16(i))
				} else {
					return nil, &ParseError{f, "bad WKS BitMap", l}
				}
			}
			rr.BitMap = append(rr.BitMap, uint16(k))
		default:
			return nil, &ParseError{f, "bad WKS BitMap", l}
		}
		l = <-c
	}
	return rr, nil
}
예제 #14
0
func main() {
	if len(os.Args) != 3 {
		log.Fatalf("Usage %s network-type service", os.Args[0])
	}
	networkType := os.Args[1]
	service := os.Args[2]
	port, err := net.LookupPort(networkType, service)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Service port %d", port)
}
예제 #15
0
파일: cs.go 프로젝트: joushou/net9p
func (h *csHandle) WriteAt(p []byte, _ int64) (int, error) {
	h.buflock.Lock()
	defer h.buflock.Unlock()

	cmd := strings.Split(strings.TrimSpace(string(p)), "!")

	switch len(cmd) {
	default:
		return len(p), errors.New("invalid query")
	case 2:
		h.buf = append(h.buf, []byte(fmt.Sprintf("/net/%s/clone %s", cmd[0], cmd[1])))
		return len(p), nil
	case 3:
		break
	}

	if cmd[0] == "net" {
		// Whatever
		cmd[0] = "tcp"
	}

	switch cmd[2] {
	case "9fs", "9pfs":
		cmd[2] = "564"
	}

	port, err := net.LookupPort(cmd[0], cmd[2])
	if err != nil {
		return len(p), err
	}

	var addrs []string
	if cmd[1] == "*" {
		addrs = []string{""}
	} else {
		addrs, err = net.LookupHost(cmd[1])
		if err != nil {
			return len(p), err
		}
	}

	for _, addr := range addrs {
		var a string
		if addr == "" {
			a = fmt.Sprintf("%d", port)
		} else {
			a = fmt.Sprintf("%s!%d", addr, port)
		}
		h.buf = append(h.buf, []byte(fmt.Sprintf("/net/%s/clone %s", cmd[0], a)))
	}

	return len(p), err
}
예제 #16
0
func parsePort(addr string) (port int, err error) {
	_, portStr, err := net.SplitHostPort(addr)
	if err != nil {
		return 0, err
	}
	port, err = net.LookupPort("udp", portStr)
	if err != nil {
		return 0, err
	}

	return port, nil
}
예제 #17
0
func main() {
	checkArgs(os.Args)

	networkType := os.Args[1]
	service := os.Args[2]

	port, err := net.LookupPort(networkType, service)

	checkError(err)

	fmt.Println("Service port", port)
}
예제 #18
0
// parsePort parses port as a network service port number for both
// TCP and UDP.
func parsePort(network, port string) (int, error) {
	p, i, ok := dtoi(port, 0)
	if !ok || i != len(port) {
		var err error
		p, err = net.LookupPort(network, port)
		if err != nil {
			return 0, err
		}
	}
	if p < 0 || p > 0xFFFF {
		return 0, &net.AddrError{Err: "invalid port", Addr: port}
	}
	return p, nil
}
예제 #19
0
파일: portSpec.go 프로젝트: grrtrr/clcv2
// ParsePortSpec parses a string satisfying one of the following formats into a Port:
// a) <proto>:<servicename>         - single port referenced via an /etc/services name
// b) <servicename>                 - abbreviation for tcp:<servicename>
//    <number>                      - abbreviation for tcp:<number>
// c) ping or icmp                  - an abbreviation for icmp:0
// c) <proto>/<portNumber>          - single numeric port
// d) <proto>/<startPort>-<endPort> - numeric port range
func ParsePortSpec(ps string) (p Port, err error) {
	var numericPorts = regexp.MustCompile(`^(\d+-)?\d+$`)
	var el = strings.Split(ps, "/")

	if len(el) != 2 {
		if ps == "ping" || ps == "icmp" {
			p.Protocol = "icmp"
			return
		} else if ps == "rdp" {
			/* RDP may not be listed in /etc/services */
			p.Protocol, p.Port = "tcp", 3389
			return
		}
		/* Otherwise assume it's a tcp Service Name */
		return ParsePortSpec("tcp/" + ps)
	}

	switch proto := strings.ToLower(el[0]); proto {
	case "udp", "tcp", "icmp": /* only supported formats */
		p.Protocol = proto
	default:
		return p, errors.Errorf("unsupported protocol type %q", proto)
	}

	if numericPorts.MatchString(el[1]) { /* numeric port or port range */
		if idx := strings.Index(el[1], "-"); idx > 0 {
			/* port range */
			if p.Port, err = strconv.Atoi(el[1][:idx]); err != nil || p.Port < 0 || p.Port > 65535 {
				return p, errors.Errorf("invalid start port %q", el[1][:idx])
			} else if p.PortTo, err = strconv.Atoi(el[1][idx+1:]); err != nil || p.PortTo < 0 || p.PortTo > 65535 {
				return p, errors.Errorf("invalid end port %q", el[1][idx+1:])
			} else if p.PortTo < p.Port {
				return p, errors.Errorf("invalid port range %q", el[1])
			}
		} else if p.Port, err = strconv.Atoi(el[1]); err == nil {
			/* numeric port */
			if p.Port < 0 || p.Port > 65535 {
				return p, errors.Errorf("invalid port %q", el[1])
			}
		}
	} else if p.Protocol != "udp" && p.Protocol != "tcp" {
		/* service name, as defined in /etc/services for UDP and TCP */
		return p, errors.Errorf("invalid service specification %q for %s", el[1], p.Protocol)
	} else {
		/* CLCv2 uses IPv4 addresses exclusively - look up v4 port names only */
		p.Port, err = net.LookupPort(p.Protocol+"4", el[1])
	}
	return
}
예제 #20
0
파일: 7.go 프로젝트: jianyongchen/GoUnix
func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "Usage:%s networkType service\n", os.Args[0])
		os.Exit(1)
	}
	networkType := os.Args[1]
	service := os.Args[2]
	port, err := net.LookupPort(networkType, service)
	if err != nil {
		fmt.Println("LookupPort error:", err.Error())
		os.Exit(1)
	}
	fmt.Println("The service port is:", port)
	os.Exit(0)
}
예제 #21
0
파일: ip.go 프로젝트: jhahn21/go-mdns-sd
// Convert "host:port" into netpkg.IP address and port.
func hostPortToIP(net, hostport string) (ip netpkg.IP, iport int, err error) {
	host, port, err := netpkg.SplitHostPort(hostport)
	if err != nil {
		return nil, 0, err
	}

	var addr netpkg.IP
	if host != "" {
		// Try as an netpkg.IP address.
		addr = netpkg.ParseIP(host)
		if addr == nil {
			var filter func(netpkg.IP) netpkg.IP
			if net != "" && net[len(net)-1] == '4' {
				filter = ipv4only
			}
			if net != "" && net[len(net)-1] == '6' {
				filter = ipv6only
			}
			// Not an netpkg.IP address.  Try as a DNS name.
			addrs, err := LookupHost(host)
			if err != nil {
				return nil, 0, err
			}
			addr = firstFavoriteAddr(filter, addrs)
			if addr == nil {
				// should not happen
				return nil, 0, &netpkg.AddrError{"LookupHost returned no suitable address", addrs[0]}
			}
		}
	}

	p, err := strconv.Atoi(port)
	if err != nil {
		p, err = netpkg.LookupPort(net, port)
		if err != nil {
			return nil, 0, err
		}
	}
	if p < 0 || p > 0xFFFF {
		return nil, 0, &netpkg.AddrError{"invalid port", port}
	}

	return addr, p, nil

}
예제 #22
0
func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "Usage: %s network-type service\n", os.Args[0])
		return
	}

	netType := os.Args[1]
	service := os.Args[2]

	port, err := net.LookupPort(netType, service)

	if err != nil {
		fmt.Println("Error: ", err.Error())
		return
	}

	fmt.Println("Service port ", port)
}
예제 #23
0
func connect(network, service, host string) net.Conn {
	_, addrs, _ := net.LookupSRV(service, network, host)
	for _, srv := range addrs {
		c := tryConnect(network, srv.Target, int(srv.Port))
		if c != nil {
			return c
		}
	}
	port, _ := net.LookupPort(network, service)
	ips, _ := net.LookupHost(host)
	for _, ip := range ips {
		c := tryConnect(network, ip, port)
		if c != nil {
			return c
		}
	}
	return nil
}
예제 #24
0
func SplitHostAndPort(hostAndPort string, defaultPort int) (host string, port int, err error) {
	parts := strings.Split(hostAndPort, ":")
	if len(parts) == 0 || len(parts) > 2 {
		err = fmt.Errorf("%s malformed host and port", hostAndPort)
		return
	}
	port = defaultPort
	if len(parts) > 0 {
		host = parts[0]
	}
	if len(parts) > 1 {
		port, err = strconv.Atoi(parts[1])
		if err != nil {
			port, err = net.LookupPort("tcp", parts[1])
		}
	}
	return
}
예제 #25
0
func initializeRegistrationRunner(logger lager.Logger, consulClient consuladapter.Client, listenAddress string, clock clock.Clock) ifrit.Runner {
	_, portString, err := net.SplitHostPort(listenAddress)
	if err != nil {
		logger.Fatal("failed-invalid-listen-address", err)
	}
	portNum, err := net.LookupPort("tcp", portString)
	if err != nil {
		logger.Fatal("failed-invalid-listen-port", err)
	}

	registration := &api.AgentServiceRegistration{
		Name: "cc-uploader",
		Port: portNum,
		Check: &api.AgentServiceCheck{
			TTL: "3s",
		},
	}

	return locket.NewRegistrationRunner(logger, registration, consulClient, locket.RetryInterval, clock)
}
예제 #26
0
func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "Usage: %s network-type serveice\n", os.Args[0])
		os.Exit(1)
	}

	networkType := os.Args[1]
	service := os.Args[2]

	// looks up the port for the given network and service.
	// on unix system, go interrogate file /etc/services
	port, err := net.LookupPort(networkType, service)
	if err != nil {
		fmt.Println("Error: ", err.Error())
		os.Exit(2)
	}

	fmt.Println("Service port ", port)
	os.Exit(0)
}
예제 #27
0
파일: net.go 프로젝트: chengguozhen/clive
// Return the port for a given network and service
func Port(netw, svc string) string {
	if netw == "*" || netw == "" {
		netw = "tcp"
	}
	lk.Lock()
	p, ok := svcs[svc]
	lk.Unlock()
	if !ok {
		if _, err := strconv.ParseInt(svc, 10, 64); err != nil {
			if nb, err := net.LookupPort(netw, svc); err == nil {
				p = strconv.Itoa(nb)
			}
		}
		if p == "" {
			p = svc
		}
	}
	if netw == "unix" {
		p = "/tmp/clive." + p
	}
	return p
}
예제 #28
0
func TestSyncNow(t *testing.T) {
	cs, testconsul := testConsul(t)
	defer cs.Shutdown()
	defer testconsul.Stop()

	cs.SetAddrFinder(func(h string) (string, int) {
		a, pstr, _ := net.SplitHostPort(h)
		p, _ := net.LookupPort("tcp", pstr)
		return a, p
	})
	cs.syncInterval = 9000 * time.Hour

	service := &structs.Service{Name: "foo1", Tags: []string{"a", "b"}}
	services := map[ServiceKey]*structs.Service{
		GenerateServiceKey(service): service,
	}

	// Run syncs once on startup and then blocks forever
	go cs.Run()

	if err := cs.SetServices(serviceGroupName, services); err != nil {
		t.Fatalf("error setting services: %v", err)
	}

	synced := false
	for i := 0; !synced && i < 10; i++ {
		time.Sleep(250 * time.Millisecond)
		agentServices, err := cs.queryAgentServices()
		if err != nil {
			t.Fatalf("error querying consul services: %v", err)
		}
		synced = len(agentServices) == 1
	}
	if !synced {
		t.Fatalf("initial sync never occurred")
	}

	// SetServices again should cause another sync
	service1 := &structs.Service{Name: "foo1", Tags: []string{"Y", "Z"}}
	service2 := &structs.Service{Name: "bar"}
	services = map[ServiceKey]*structs.Service{
		GenerateServiceKey(service1): service1,
		GenerateServiceKey(service2): service2,
	}

	if err := cs.SetServices(serviceGroupName, services); err != nil {
		t.Fatalf("error setting services: %v", err)
	}

	synced = false
	for i := 0; !synced && i < 10; i++ {
		time.Sleep(250 * time.Millisecond)
		agentServices, err := cs.queryAgentServices()
		if err != nil {
			t.Fatalf("error querying consul services: %v", err)
		}
		synced = len(agentServices) == 2
	}
	if !synced {
		t.Fatalf("SetServices didn't sync immediately")
	}
}
예제 #29
0
func TestConsulServiceUpdateService(t *testing.T) {
	cs, testconsul := testConsul(t)
	defer cs.Shutdown()
	defer testconsul.Stop()

	cs.SetAddrFinder(func(h string) (string, int) {
		a, pstr, _ := net.SplitHostPort(h)
		p, _ := net.LookupPort("tcp", pstr)
		return a, p
	})

	service1 := &structs.Service{Name: "foo1", Tags: []string{"a", "b"}}
	service2 := &structs.Service{Name: "foo2"}
	services := map[ServiceKey]*structs.Service{
		GenerateServiceKey(service1): service1,
		GenerateServiceKey(service2): service2,
	}
	if err := cs.SetServices(serviceGroupName, services); err != nil {
		t.Fatalf("error setting services: %v", err)
	}
	if err := cs.SyncServices(); err != nil {
		t.Fatalf("error syncing services: %v", err)
	}

	// Now update both services
	service1 = &structs.Service{Name: "foo1", Tags: []string{"a", "z"}}
	service2 = &structs.Service{Name: "foo2", PortLabel: ":8899"}
	service3 := &structs.Service{Name: "foo3"}
	services = map[ServiceKey]*structs.Service{
		GenerateServiceKey(service1): service1,
		GenerateServiceKey(service2): service2,
		GenerateServiceKey(service3): service3,
	}
	if err := cs.SetServices(serviceGroupName, services); err != nil {
		t.Fatalf("error setting services: %v", err)
	}
	if err := cs.SyncServices(); err != nil {
		t.Fatalf("error syncing services: %v", err)
	}

	agentServices, err := cs.queryAgentServices()
	if err != nil {
		t.Fatalf("error querying consul services: %v", err)
	}
	if len(agentServices) != 3 {
		t.Fatalf("expected 3 services in consul but found %d:\n%#v", len(agentServices), agentServices)
	}
	consulServices := make(map[string]*api.AgentService, 3)
	for _, as := range agentServices {
		consulServices[as.ID] = as
	}

	found := 0
	for _, s := range cs.flattenedServices() {
		// Assert sure changes were applied to internal state
		switch s.Name {
		case "foo1":
			found++
			if !reflect.DeepEqual(service1.Tags, s.Tags) {
				t.Errorf("incorrect tags on foo1:\n  expected: %v\n  found: %v", service1.Tags, s.Tags)
			}
		case "foo2":
			found++
			if s.Address != "" {
				t.Errorf("expected empty host on foo2 but found %q", s.Address)
			}
			if s.Port != 8899 {
				t.Errorf("expected port 8899 on foo2 but found %d", s.Port)
			}
		case "foo3":
			found++
		default:
			t.Errorf("unexpected service: %s", s.Name)
		}

		// Assert internal state equals consul's state
		cs, ok := consulServices[s.ID]
		if !ok {
			t.Errorf("service not in consul: %s id: %s", s.Name, s.ID)
			continue
		}
		if !reflect.DeepEqual(s.Tags, cs.Tags) {
			t.Errorf("mismatched tags in syncer state and consul for %s:\nsyncer: %v\nconsul: %v", s.Name, s.Tags, cs.Tags)
		}
		if cs.Port != s.Port {
			t.Errorf("mismatched port in syncer state and consul for %s\nsyncer: %v\nconsul: %v", s.Name, s.Port, cs.Port)
		}
		if cs.Address != s.Address {
			t.Errorf("mismatched address in syncer state and consul for %s\nsyncer: %v\nconsul: %v", s.Name, s.Address, cs.Address)
		}
	}
	if found != 3 {
		t.Fatalf("expected 3 services locally but found %d", found)
	}
}
예제 #30
0
파일: main.go 프로젝트: cloudfoundry/bbs
func main() {
	debugserver.AddFlags(flag.CommandLine)
	lagerflags.AddFlags(flag.CommandLine)
	etcdFlags := AddETCDFlags(flag.CommandLine)
	encryptionFlags := encryption.AddEncryptionFlags(flag.CommandLine)

	flag.Parse()

	cfhttp.Initialize(*communicationTimeout)

	logger, reconfigurableSink := lagerflags.New("bbs")
	logger.Info("starting")

	initializeDropsonde(logger)

	clock := clock.NewClock()

	consulClient, err := consuladapter.NewClientFromUrl(*consulCluster)
	if err != nil {
		logger.Fatal("new-consul-client-failed", err)
	}

	serviceClient := bbs.NewServiceClient(consulClient, clock)

	maintainer := initializeLockMaintainer(logger, serviceClient)

	_, portString, err := net.SplitHostPort(*listenAddress)
	if err != nil {
		logger.Fatal("failed-invalid-listen-address", err)
	}
	portNum, err := net.LookupPort("tcp", portString)
	if err != nil {
		logger.Fatal("failed-invalid-listen-port", err)
	}

	_, portString, err = net.SplitHostPort(*healthAddress)
	if err != nil {
		logger.Fatal("failed-invalid-health-address", err)
	}
	_, err = net.LookupPort("tcp", portString)
	if err != nil {
		logger.Fatal("failed-invalid-health-port", err)
	}

	registrationRunner := initializeRegistrationRunner(logger, consulClient, portNum, clock)

	var activeDB db.DB
	var sqlDB *sqldb.SQLDB
	var sqlConn *sql.DB
	var storeClient etcddb.StoreClient
	var etcdDB *etcddb.ETCDDB

	key, keys, err := encryptionFlags.Parse()
	if err != nil {
		logger.Fatal("cannot-setup-encryption", err)
	}
	keyManager, err := encryption.NewKeyManager(key, keys)
	if err != nil {
		logger.Fatal("cannot-setup-encryption", err)
	}
	cryptor := encryption.NewCryptor(keyManager, rand.Reader)

	etcdOptions, err := etcdFlags.Validate()
	if err != nil {
		logger.Fatal("etcd-validation-failed", err)
	}

	if etcdOptions.IsConfigured {
		storeClient = initializeEtcdStoreClient(logger, etcdOptions)
		etcdDB = initializeEtcdDB(logger, cryptor, storeClient, serviceClient, *desiredLRPCreationTimeout)
		activeDB = etcdDB
	}

	// If SQL database info is passed in, use SQL instead of ETCD
	if *databaseDriver != "" && *databaseConnectionString != "" {
		var err error
		connectionString := appendSSLConnectionStringParam(logger, *databaseDriver, *databaseConnectionString, *sqlCACertFile)

		sqlConn, err = sql.Open(*databaseDriver, connectionString)
		if err != nil {
			logger.Fatal("failed-to-open-sql", err)
		}
		defer sqlConn.Close()
		sqlConn.SetMaxOpenConns(*maxDatabaseConnections)
		sqlConn.SetMaxIdleConns(*maxDatabaseConnections)

		err = sqlConn.Ping()
		if err != nil {
			logger.Fatal("sql-failed-to-connect", err)
		}

		sqlDB = sqldb.NewSQLDB(sqlConn, *convergenceWorkers, *updateWorkers, format.ENCRYPTED_PROTO, cryptor, guidprovider.DefaultGuidProvider, clock, *databaseDriver)
		err = sqlDB.SetIsolationLevel(logger, sqldb.IsolationLevelReadCommitted)
		if err != nil {
			logger.Fatal("sql-failed-to-set-isolation-level", err)
		}

		err = sqlDB.CreateConfigurationsTable(logger)
		if err != nil {
			logger.Fatal("sql-failed-create-configurations-table", err)
		}
		activeDB = sqlDB
	}

	if activeDB == nil {
		logger.Fatal("no-database-configured", errors.New("no database configured"))
	}

	encryptor := encryptor.New(logger, activeDB, keyManager, cryptor, clock)

	migrationsDone := make(chan struct{})

	migrationManager := migration.NewManager(
		logger,
		etcdDB,
		storeClient,
		sqlDB,
		sqlConn,
		cryptor,
		migrations.Migrations,
		migrationsDone,
		clock,
		*databaseDriver,
	)

	desiredHub := events.NewHub()
	actualHub := events.NewHub()

	repTLSConfig := &rep.TLSConfig{
		RequireTLS:      *repRequireTLS,
		CaCertFile:      *repCACert,
		CertFile:        *repClientCert,
		KeyFile:         *repClientKey,
		ClientCacheSize: *repClientSessionCacheSize,
	}

	httpClient := cfhttp.NewClient()
	repClientFactory, err := rep.NewClientFactory(httpClient, httpClient, repTLSConfig)
	if err != nil {
		logger.Fatal("new-rep-client-factory-failed", err)
	}

	auctioneerClient := initializeAuctioneerClient(logger)

	exitChan := make(chan struct{})

	var accessLogger lager.Logger
	if *accessLogPath != "" {
		accessLogger = lager.NewLogger("bbs-access")
		file, err := os.OpenFile(*accessLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			logger.Error("invalid-access-log-path", err, lager.Data{"access-log-path": *accessLogPath})
			os.Exit(1)
		}
		accessLogger.RegisterSink(lager.NewWriterSink(file, lager.INFO))
	}

	var tlsConfig *tls.Config
	if *requireSSL {
		tlsConfig, err = cfhttp.NewTLSConfig(*certFile, *keyFile, *caFile)
		if err != nil {
			logger.Fatal("tls-configuration-failed", err)
		}
	}

	cbWorkPool := taskworkpool.New(logger, *taskCallBackWorkers, taskworkpool.HandleCompletedTask, tlsConfig)

	handler := handlers.New(
		logger,
		accessLogger,
		*updateWorkers,
		*convergenceWorkers,
		activeDB,
		desiredHub,
		actualHub,
		cbWorkPool,
		serviceClient,
		auctioneerClient,
		repClientFactory,
		migrationsDone,
		exitChan,
	)

	metricsNotifier := metrics.NewPeriodicMetronNotifier(logger)

	retirer := controllers.NewActualLRPRetirer(activeDB, actualHub, repClientFactory, serviceClient)
	lrpConvergenceController := controllers.NewLRPConvergenceController(logger, activeDB, actualHub, auctioneerClient, serviceClient, retirer, *convergenceWorkers)
	taskController := controllers.NewTaskController(activeDB, cbWorkPool, auctioneerClient, serviceClient, repClientFactory)

	convergerProcess := converger.New(
		logger,
		clock,
		lrpConvergenceController,
		taskController,
		serviceClient,
		*convergeRepeatInterval,
		*kickTaskDuration,
		*expirePendingTaskDuration,
		*expireCompletedTaskDuration)

	var server ifrit.Runner
	if tlsConfig != nil {
		server = http_server.NewTLSServer(*listenAddress, handler, tlsConfig)
	} else {
		server = http_server.New(*listenAddress, handler)
	}

	healthcheckServer := http_server.New(*healthAddress, http.HandlerFunc(healthCheckHandler))

	members := grouper.Members{
		{"healthcheck", healthcheckServer},
		{"lock-maintainer", maintainer},
		{"workpool", cbWorkPool},
		{"server", server},
		{"migration-manager", migrationManager},
		{"encryptor", encryptor},
		{"hub-maintainer", hubMaintainer(logger, desiredHub, actualHub)},
		{"metrics", *metricsNotifier},
		{"converger", convergerProcess},
		{"registration-runner", registrationRunner},
	}

	if dbgAddr := debugserver.DebugAddress(flag.CommandLine); dbgAddr != "" {
		members = append(grouper.Members{
			{"debug-server", debugserver.Runner(dbgAddr, reconfigurableSink)},
		}, members...)
	}

	group := grouper.NewOrdered(os.Interrupt, members)

	monitor := ifrit.Invoke(sigmon.New(group))
	go func() {
		// If a handler writes to this channel, we've hit an unrecoverable error
		// and should shut down (cleanly)
		<-exitChan
		monitor.Signal(os.Interrupt)
	}()

	logger.Info("started")

	err = <-monitor.Wait()
	if sqlConn != nil {
		sqlConn.Close()
	}
	if err != nil {
		logger.Error("exited-with-failure", err)
		os.Exit(1)
	}

	logger.Info("exited")
}