Example #1
0
func (s *Stream) Connect() error {
	var conn io.WriteCloser
	var err error
	path := s.Url.Host + s.Url.Path

	switch {

	case s.Url.Scheme == "tls" || s.Url.Scheme == "ssl":
		tcpConn, dialErr := net.DialTimeout("tcp", path, DIAL_TIMEOUT)
		if dialErr != nil {
			config := &tls.Config{InsecureSkipVerify: s.Conf.AllowSSCert}
			conn = tls.Client(tcpConn, config)
		} else {
			err = dialErr
		}

	case s.Url.Scheme == "file":
		conn, err = os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)

	default:
		conn, err = net.DialTimeout(s.Url.Scheme, path, DIAL_TIMEOUT)

	}
	s.Conn = conn
	return err
}
Example #2
0
func init() {
	t := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: func(n, a string) (net.Conn, error) {
			return net.DialTimeout(n, a, defaultDialTimeout)
		},
	}
	Client = &http.Client{
		Transport: t,
	}
	httpDo = Client

	// copy for InsecureTLS
	tInsecureTLS := http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: func(n, a string) (net.Conn, error) {
			return net.DialTimeout(n, a, defaultDialTimeout)
		},
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	ClientInsecureTLS = &http.Client{
		Transport: &tInsecureTLS,
	}
	httpDoInsecureTLS = ClientInsecureTLS
}
Example #3
0
func (m *Memcached) gatherServer(
	address string,
	unix bool,
	acc plugins.Accumulator,
) error {
	var conn net.Conn
	if unix {
		conn, err := net.DialTimeout("unix", address, defaultTimeout)
		if err != nil {
			return err
		}
		defer conn.Close()
	} else {
		_, _, err := net.SplitHostPort(address)
		if err != nil {
			address = address + ":11211"
		}

		conn, err = net.DialTimeout("tcp", address, defaultTimeout)
		if err != nil {
			return err
		}
		defer conn.Close()
	}

	// Extend connection
	conn.SetDeadline(time.Now().Add(defaultTimeout))

	// Read and write buffer
	rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))

	// Send command
	if _, err := fmt.Fprint(rw, "stats\r\n"); err != nil {
		return err
	}
	if err := rw.Flush(); err != nil {
		return err
	}

	values, err := parseResponse(rw.Reader)
	if err != nil {
		return err
	}

	// Add server address as a tag
	tags := map[string]string{"server": address}

	// Process values
	for _, key := range sendMetrics {
		if value, ok := values[key]; ok {
			// Mostly it is the number
			if iValue, errParse := strconv.ParseInt(value, 10, 64); errParse != nil {
				acc.Add(key, value, tags)
			} else {
				acc.Add(key, iValue, tags)
			}
		}
	}
	return nil
}
Example #4
0
func rpcConnect(addr string) (net.Conn, error) {
	req, err := http.NewRequest("GET", pdRPCPrefix, nil)
	if err != nil {
		return nil, errors.Trace(err)
	}

	urls, err := parseUrls(addr)
	if err != nil {
		return nil, errors.Trace(err)
	}

	for _, url := range urls {
		var conn net.Conn
		switch url.Scheme {
		// used in tests
		case "unix", "unixs":
			conn, err = net.DialTimeout("unix", url.Host, connectPDTimeout)
		default:
			conn, err = net.DialTimeout("tcp", url.Host, connectPDTimeout)
		}

		if err != nil {
			continue
		}
		err = req.Write(conn)
		if err != nil {
			conn.Close()
			continue
		}
		return conn, nil
	}

	return nil, errors.Errorf("connect to %s failed", addr)
}
Example #5
0
func isNodeNated(ip string) bool {
	for {
		_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", "localhost", DockerHostPort), DialTimeOut*time.Second)
		if err == nil {
			break
		} else {
			time.Sleep(2 * time.Second)
		}
	}

	address := ip
	if address == "" {
		Logger.Printf("Node public IP address return from server is empty, use FQDN instead.")
		address = Conf.CertCommonName
	}
	Logger.Printf("Testing if node %s(%s:%s) is publicly reachable...", Conf.CertCommonName, address, DockerHostPort)
	_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", address, DockerHostPort), DialTimeOut*time.Second)
	if err == nil {
		Logger.Printf("Node %s(%s:%s) is publicly reachable", Conf.CertCommonName, address, DockerHostPort)
		return false
	} else {
		Logger.Printf("Node %s(%s:%s) is not publicly reachable: %s", Conf.CertCommonName, address, DockerHostPort, err)
		return true
	}
}
Example #6
0
func (s *srvLauncherSuite) TestAll() {
	sl := NewServiceLauncher()

	var err error
	var ports = make([]int, 5)

	ports[0], _, err = sl.Start(ZooKeeper)
	s.NoError(err)

	ports[1], _, err = sl.Start(Redis)
	s.NoError(err)

	ports[2], _, err = sl.Start(Etcd)
	s.NoError(err)

	ports[3], _, err = sl.Start(HBase)
	s.NoError(err)

	ports[4], _, err = sl.Start(Gnatsd)
	s.NoError(err)

	for _, port := range ports {
		_, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), time.Second)
		s.NoError(err)
	}

	s.NoError(sl.StopAll())

	time.Sleep(5 * time.Second)

	for _, port := range ports {
		_, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), time.Second)
		s.Error(err)
	}
}
Example #7
0
File: rpc.go Project: jyzhe/beehive
func newRPCClient(addr string) (client *rpcClient, err error) {
	client = &rpcClient{
		addr: addr,
	}

	cmdConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		return nil, err
	}
	client.cmd = rpc.NewClient(cmdConn)

	raftConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		client.raft = client.cmd
	} else {
		client.raft = rpc.NewClient(raftConn)
	}

	prioConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		client.prio = client.raft
	} else {
		client.prio = rpc.NewClient(prioConn)
	}

	msgConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		client.msg = client.cmd
	} else {
		client.msg = rpc.NewClient(msgConn)
	}

	return client, nil
}
Example #8
0
func newHTTPClient(u *url.URL, tlsConfig *tls.Config, timeout time.Duration) *http.Client {

	httpTransport := &http.Transport{
		TLSClientConfig: tlsConfig,
	}

	switch u.Scheme {
	default:
		httpTransport.Dial = func(proto, addr string) (net.Conn, error) {
			return net.DialTimeout(proto, addr, timeout)
		}
	case "unix":
		socketPath := u.Path
		unixDial := func(proto, addr string) (net.Conn, error) {
			ret, err := net.DialTimeout("unix", socketPath, timeout)
			return ret, err
		}
		httpTransport.Dial = unixDial
		// Override the main URL object so the HTTP lib won't complain
		u.Scheme = "http"
		u.Host = "unix.sock"
		u.Path = ""
	}
	return &http.Client{Transport: httpTransport}
}
Example #9
0
// getconn is the unexported function used to connect to Graphite.
// If there is a problem with the connection it retries with an incremental
// sleep time.
// Returns a pointer to the GraphiteServer struct.
func (g *GraphiteServer) getconn() GraphiteServer {
	var (
		err      error
		waitTime time.Duration
	)

	connectAddr := fmt.Sprintf("%s:%d", g.Host, g.Port)

	if g.Timeout == 0 {
		g.Timeout = defaultTimeout * time.Second
	}

	waitTime = initialWaitTime
	g.conn, err = net.DialTimeout("tcp", connectAddr, g.Timeout)
	for err != nil {
		log.Printf(err.Error())
		log.Printf(fmt.Sprintf("error connecting, retrying in %d seconds", waitTime))
		time.Sleep(waitTime * time.Second)

		waitTime += 5
		g.conn, err = net.DialTimeout("tcp", connectAddr, g.Timeout)
	}

	return *g
}
Example #10
0
func (u *Uwsgi) gatherServer(acc telegraf.Accumulator, url *url.URL) error {
	var err error
	var r io.ReadCloser

	switch url.Scheme {
	case "unix":
		r, err = net.DialTimeout(url.Scheme, url.Path, timeout)
	case "tcp":
		r, err = net.DialTimeout(url.Scheme, url.Host, timeout)
	case "http":
		resp, err := http.Get(url.String())
		if err != nil {
			return fmt.Errorf("Could not connect to uWSGI Stats Server '%s': %s", url.String(), err)
		}
		r = resp.Body
	default:
		return fmt.Errorf("'%s' is not a valid URL", url.String())
	}

	if err != nil {
		return fmt.Errorf("Could not connect to uWSGI Stats Server '%s': %s", url.String(), err)
	}
	defer r.Close()

	var s StatsServer
	s.Url = url.String()

	dec := json.NewDecoder(r)
	dec.Decode(&s)

	u.gatherStatServer(acc, &s)

	return nil
}
Example #11
0
func processData(dataCh chan []byte, destinations []Destination) {
	var destConns []net.Conn
	for _, destination := range destinations {
		conn, err := net.DialTimeout("udp", destination.Address, time.Second)
		if err != nil {
			log.Fatalf("ERROR: UDP connection failed - %s", err)
		}
		destConns = append(destConns, conn)
	}

	for data := range dataCh {
		for _, p := range parseMessage(data) {
			for i, destination := range destinations {
				key := destination.Regex.ReplaceAll(p.Key, destination.Replace)
				packet := fmt.Sprintf("%s:%s", key, p.Body)
				conn := destConns[i]
				_, err := conn.Write([]byte(packet))
				if err != nil {
					log.Printf("ERROR: writing to UDP socket - %s", err)
					conn.Close()

					// reconnect
					conn, err := net.DialTimeout("udp", destination.Address, time.Second)
					if err != nil {
						log.Fatalf("ERROR: UDP connection failed - %s", err)
					}
					destConns[i] = conn
				}
			}
		}
	}
}
Example #12
0
func newHTTPClient(u *url.URL, tlsConfig *tls.Config, timeout time.Duration, setUserTimeout tcpFunc) *http.Client {
	httpTransport := &http.Transport{
		TLSClientConfig: tlsConfig,
	}

	switch u.Scheme {
	default:
		httpTransport.Dial = func(proto, addr string) (net.Conn, error) {
			conn, err := net.DialTimeout(proto, addr, timeout)
			if tcpConn, ok := conn.(*net.TCPConn); ok && setUserTimeout != nil {
				// Sender can break TCP connection if the remote side doesn't
				// acknowledge packets within timeout
				setUserTimeout(tcpConn, timeout)
			}
			return conn, err
		}
	case "unix":
		socketPath := u.Path
		unixDial := func(proto, addr string) (net.Conn, error) {
			return net.DialTimeout("unix", socketPath, timeout)
		}
		httpTransport.Dial = unixDial
		// Override the main URL object so the HTTP lib won't complain
		u.Scheme = "http"
		u.Host = "unix.sock"
		u.Path = ""
	}
	return &http.Client{Transport: httpTransport}
}
Example #13
0
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	req1, req2 := DuplicateRequest(req)
	go func() {
		defer func() {
			if r := recover(); r != nil && *debug {
				fmt.Println("Recovered in f", r)
			}
		}()
		client_tcp_conn, _ := net.DialTimeout("tcp", h.Alternative, time.Duration(1*time.Second)) // Open new TCP connection to the server
		client_http_conn := httputil.NewClientConn(client_tcp_conn, nil)                          // Start a new HTTP connection on it
		client_http_conn.Write(req1)                                                              // Pass on the request
		client_http_conn.Read(req1)                                                               // Read back the reply
		client_http_conn.Close()                                                                  // Close the connection to the server
	}()
	defer func() {
		if r := recover(); r != nil && *debug {
			fmt.Println("Recovered in f", r)
		}
	}()

	client_tcp_conn, _ := net.DialTimeout("tcp", h.Target, time.Duration(3*time.Second)) // Open new TCP connection to the server
	client_http_conn := httputil.NewClientConn(client_tcp_conn, nil)                     // Start a new HTTP connection on it
	client_http_conn.Write(req2)                                                         // Pass on the request
	resp, _ := client_http_conn.Read(req2)                                               // Read back the reply
	resp.Write(w)                                                                        // Write the reply to the original connection
	client_http_conn.Close()                                                             // Close the connection to the server
}
Example #14
0
func sockConn(timeout time.Duration) (net.Conn, error) {
	daemon := daemonHost()
	daemonURL, err := url.Parse(daemon)
	if err != nil {
		return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
	}

	var c net.Conn
	switch daemonURL.Scheme {
	case "unix":
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
	case "tcp":
		if os.Getenv("DOCKER_TLS_VERIFY") != "" {
			// Setup the socket TLS configuration.
			tlsConfig, err := getTLSConfig()
			if err != nil {
				return nil, err
			}
			dialer := &net.Dialer{Timeout: timeout}
			return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
		}
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
	default:
		return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
	}
}
Example #15
0
func (conn *ForwardConnection) dialRemote(addr string, lookup_trusted_dns bool) (net.Conn, error) {
	timeout := 10 * time.Second
	//	if !lookup_trusted_dns {
	//		if exist := getDomainCRLFAttr(addr); exist {
	//			conn.try_inject_crlf = true
	//			lookup_trusted_dns = true
	//		}
	//	}
	if lookup_trusted_dns {
		if newaddr, success := lookupAvailableAddress(addr, !conn.prefer_hosts); !success {
			return nil, fmt.Errorf("No available IP found for %s", addr)
		} else {
			log.Printf("Found %s for %s\n", newaddr, addr)
			addr = newaddr
		}
	}
	c, err := net.DialTimeout("tcp", addr, timeout)
	if nil != err && !lookup_trusted_dns {
		if tmp, success := lookupAvailableAddress(addr, !conn.prefer_hosts); success {
			//conn.try_inject_crlf = true
			c, err = net.DialTimeout("tcp", tmp, timeout)
		}
	}
	return c, err
}
Example #16
0
func (c *Client) Connect() (err error) {
	log.Debug("connecting to %s", c.url)

	url, err := url.Parse(c.url)
	if err != nil {
		return err
	}

	switch url.Scheme {
	case "rtmp":
		c.conn, err = net.DialTimeout("tcp", url.Host, 5*time.Second)
		if err != nil {
			return err
		}
	case "rtmps":
		var nc net.Conn
		nc, err = net.DialTimeout("tcp", url.Host, 5*time.Second)
		if err != nil {
			return err
		}

		config := &tls.Config{InsecureSkipVerify: true}
		tc := tls.Client(nc, config)
		err = tc.Handshake()
		if err != nil {
			return err
		}

		c.conn = tc
	default:
		return Error("Unsupported scheme: %s", url.Scheme)
	}

	log.Debug("handshaking with %s", c.url)

	err = c.handshake()
	if err != nil {
		return Error("client connect: could not complete handshake: %s", err)
	}

	log.Debug("sending connect command to %s", c.url)

	go c.receiveLoop()
	go c.sendLoop()
	go c.routeLoop()

	var id string
	id, err = c.connect()
	if err != nil {
		return Error("client connect: could not complete connect: %s", err)
	}

	c.connected = true
	c.connectionId = id

	log.Debug("connected to %s (%s)", c.url, c.connectionId)

	return
}
Example #17
0
// ServeHTTP duplicates the incoming request (req) and does the request to the Target and the Alternate target discading the Alternate response
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	req1, req2 := DuplicateRequest(req)
	go func() {
		defer func() {
			if r := recover(); r != nil && *debug {
				fmt.Println("Recovered in f", r)
			}
		}()
		// Open new TCP connection to the server
		clientTcpConn, err := net.DialTimeout("tcp", h.Alternative, time.Duration(time.Duration(*alternateTimeout)*time.Second))
		if err != nil {
			if *debug {
				fmt.Printf("Failed to connect to %s\n", h.Alternative)
			}
			return
		}
		clientHttpConn := httputil.NewClientConn(clientTcpConn, nil) // Start a new HTTP connection on it
		defer clientHttpConn.Close()                                 // Close the connection to the server
		err = clientHttpConn.Write(req1)                             // Pass on the request
		if err != nil {
			if *debug {
				fmt.Printf("Failed to send to %s: %v\n", h.Alternative, err)
			}
			return
		}
		_, err = clientHttpConn.Read(req1) // Read back the reply
		if err != nil {
			if *debug {
				fmt.Printf("Failed to receive from %s: %v\n", h.Alternative, err)
			}
			return
		}
	}()
	defer func() {
		if r := recover(); r != nil && *debug {
			fmt.Println("Recovered in f", r)
		}
	}()

	// Open new TCP connection to the server
	clientTcpConn, err := net.DialTimeout("tcp", h.Target, time.Duration(time.Duration(*productionTimeout)*time.Second))
	if err != nil {
		fmt.Printf("Failed to connect to %s\n", h.Target)
		return
	}
	clientHttpConn := httputil.NewClientConn(clientTcpConn, nil) // Start a new HTTP connection on it
	defer clientHttpConn.Close()                                 // Close the connection to the server
	err = clientHttpConn.Write(req2)                             // Pass on the request
	if err != nil {
		fmt.Printf("Failed to send to %s: %v\n", h.Target, err)
		return
	}
	resp, err := clientHttpConn.Read(req2) // Read back the reply
	if err != nil {
		fmt.Printf("Failed to receive from %s: %v\n", h.Target, err)
		return
	}
	resp.Write(w) // Write the reply to the original connection
}
Example #18
0
func (w Work) PostPingStats(result *WorkResult) {
	if result == nil {
		fmt.Println("Result is nil")
		return
	}

	if w.HTTP != "" {
		transport := http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				return net.DialTimeout(network, addr, 2e9)
			},
			ResponseHeaderTimeout: 2e9,
		}
		client := http.Client{
			Transport: &transport,
		}
		resp, err := client.PostForm(
			w.HTTP, url.Values{
				"Min":      {result.Min.String()},
				"Max":      {result.Max.String()},
				"Avg":      {result.Avg.String()},
				"Success":  {fmt.Sprintf("%d", result.Success)},
				"Timeouts": {fmt.Sprintf("%d", result.Timeouts)},
				"Data":     {w.Data},
			},
		)
		if err != nil {
			fmt.Println(err)
			return
		}
		if resp.StatusCode >= 400 {
			fmt.Println("Worker: HTTP not ok:", resp.Status)
			return
		}
		fmt.Println("Worker: Posted data over HTTP.")
	}

	if w.UDP != "" {
		conn, err := net.DialTimeout("udp", w.UDP, 1e9)
		if err != nil {
			fmt.Println("Error establishing connection to host: %s\n", err)
			return
		}

		result.Data = w.Data

		bytes, err := json.Marshal(result)
		if err != nil {
			fmt.Println("Error marshalling:", err)
			return
		}
		_, err = conn.Write(bytes)
		if err != nil {
			fmt.Println("Error marshalling:", err)
		}
		fmt.Println("Worker: Posted data over UDP.")
	}
}
Example #19
0
// get a new connection using the specified transport.
func (f *Fluent) getConnection() (net.Conn, error) {
	switch f.Config.FluentNetwork {
	case "tcp":
		return net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort), f.Config.Timeout)
	case "unix":
		return net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentSocketPath, f.Config.Timeout)
	default:
		return nil, net.UnknownNetworkError(f.Config.FluentNetwork)
	}
}
Example #20
0
// connect establishes a new connection using the specified transport.
func (f *Fluent) connect() (err error) {
	switch f.Config.FluentNetwork {
	case "tcp":
		f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort), f.Config.Timeout)
	case "unix":
		f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentSocketPath, f.Config.Timeout)
	default:
		err = net.UnknownNetworkError(f.Config.FluentNetwork)
	}
	return
}
Example #21
0
func (sc *Client) connect() (err error) {
	if sc.conn != nil {
		return
	}

	// set connerror to false.
	sc.connerror = false

	timeout := time.Duration(sc.Timeout) * time.Millisecond

	// Try unix socket first.
	if sc.Socket != "" {
		if sc.conn, err = net.DialTimeout("unix", sc.Socket, timeout); err != nil {
			sc.connerror = true
			return fmt.Errorf("connect() net.DialTimeout(%d ms) > %v", sc.Timeout, err)
		}
	} else if sc.Port > 0 {
		if sc.conn, err = net.DialTimeout("tcp", fmt.Sprintf("%s:%d", sc.Host, sc.Port), timeout); err != nil {
			sc.connerror = true
			return fmt.Errorf("connect() net.DialTimeout(%d ms) > %v", sc.Timeout, err)
		}
	} else {
		return fmt.Errorf("connect() > No valid socket or port!\n%Client: #v", sc)
	}

	// Set deadline
	if err = sc.conn.SetDeadline(time.Now().Add(timeout)); err != nil {
		sc.connerror = true
		return fmt.Errorf("connect() conn.SetDeadline() > %v", err)
	}

	header := make([]byte, 4)
	if _, err = io.ReadFull(sc.conn, header); err != nil {
		sc.connerror = true
		return fmt.Errorf("connect() io.ReadFull() > %v", err)
	}

	version := binary.BigEndian.Uint32(header)
	if version < 1 {
		return fmt.Errorf("connect() > expected searchd protocol version 1+, got version %d", version)
	}

	// send my version
	var i int
	i, err = sc.conn.Write(writeInt32ToBytes([]byte{}, VER_MAJOR_PROTO))
	if err != nil {
		sc.connerror = true
		return fmt.Errorf("connect() conn.Write() > %d bytes, %v", i, err)
	}

	sc.conn.SetDeadline(time.Time{})

	return
}
Example #22
0
// Is the broker valid (active, supports check type, and reachable)
func (cm *CheckManager) isValidBroker(broker *api.Broker) bool {
	brokerPort := 0
	valid := false
	for _, detail := range broker.Details {
		brokerPort = 43191

		// broker must be active
		if detail.Status != statusActive {
			if cm.Debug {
				cm.Log.Printf("[DEBUG] Broker '%s' is not active.\n", broker.Name)
			}
			continue
		}

		// broker must have module loaded for the check type to be used
		if !cm.brokerSupportsCheckType(cm.checkType, &detail) {
			if cm.Debug {
				cm.Log.Printf("[DEBUG] Broker '%s' does not support '%s' checks.\n", broker.Name, cm.checkType)
			}
			continue
		}

		// broker must be reachable and respond within designated time
		conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", detail.IP, brokerPort), cm.brokerMaxResponseTime)
		if err != nil {
			if detail.CN != "trap.noit.circonus.net" {
				if cm.Debug {
					cm.Log.Printf("[DEBUG] Broker '%s' unable to connect, %v\n", broker.Name, err)
				}
				continue // not able to reach the broker (or respone slow enough for it to be considered not usable)
			}
			// if circonus trap broker, try port 443
			brokerPort = 443
			conn, err = net.DialTimeout("tcp", fmt.Sprintf("%s:%d", detail.CN, brokerPort), cm.brokerMaxResponseTime)
			if err != nil {
				if cm.Debug {
					cm.Log.Printf("[DEBUG] Broker '%s' unable to connect %v\n", broker.Name, err)
				}
				continue // not able to reach the broker on 443 either (or respone slow enough for it to be considered not usable)
			}
		}
		conn.Close()

		if cm.Debug {
			cm.Log.Printf("[DEBUG] Broker '%s' is valid\n", broker.Name)
		}

		valid = true
		break

	}
	return valid
}
Example #23
0
func (s *Server) processDown() {
	if len(s.downAddrs) <= 0 {
		return
	}

	downChan := make(chan string, 5000)
	s.downChan = downChan
	//downAddNum := len(s.downAddrs)

	for _, addr := range s.downAddrs {
		conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
		if err != nil {
			s.logf("Connect to down server failed: %s - %s", addr, err)
			continue
		}

		s.downConn[addr] = conn
	}

	ticker := time.NewTicker(5 * time.Second)
	for {
		select {
		case data := <-downChan:
			for addr, conn := range s.downConn {
				_, err := conn.Write([]byte(data))
				if err != nil {
					s.logf("Send data to down server failed: %s - %s", conn.RemoteAddr(), err)
					conn.Close()
					delete(s.downConn, addr)
					continue
				} else {
					break
				}
			}
		case <-ticker.C:
			for _, addr := range s.downAddrs {
				if _, ok := s.downConn[addr]; !ok {
					conn, err := net.DialTimeout("tcp", addr, 1*time.Second)
					if err != nil {
						s.logf("Connect to down server failed: %s - %s", addr, err)
					} else {
						s.downConn[addr] = conn
					}
				}
			}
		case <-s.exitChan:
			goto exit
		}
	}
exit:
	return
}
Example #24
0
func NewHostCert(uri string, cert, key []byte) (*Client, error) {
	var host = GetHost(uri)
	var proto, addr = SplitProtoAddr(host)

	var cli = new(Client)
	cli.proto = proto
	cli.addr = addr
	cli.scheme = "http"
	cli.Images = &ImageService{cli}
	cli.Containers = &ContainerService{cli}

	// if no certificate is provided returns the
	// client with no TLS configured.
	if cert == nil || key == nil || len(cert) == 0 || len(key) == 0 {
		cli.trans = &http.Transport{
			Dial: func(dial_network, dial_addr string) (net.Conn, error) {
				return net.DialTimeout(cli.proto, cli.addr, 32*time.Second)
			},
		}
		return cli, nil
	}

	// loads the key value pair in pem format
	pem, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return nil, err
	}

	// setup the client TLS and store the certificate.
	// also skip verification since we are (typically)
	// going to be using certs for IP addresses.
	cli.scheme = "https"
	cli.tls = new(tls.Config)
	cli.tls.InsecureSkipVerify = true
	cli.tls.Certificates = []tls.Certificate{pem}

	// disable compression for local socket communication.
	if cli.proto == DEFAULTPROTOCOL {
		cli.trans.DisableCompression = true
	}

	// creates a transport that uses the custom tls configuration
	// to securely connect to remote Docker clients.
	cli.trans = &http.Transport{
		TLSClientConfig: cli.tls,
		Dial: func(dial_network, dial_addr string) (net.Conn, error) {
			return net.DialTimeout(cli.proto, cli.addr, 32*time.Second)
		},
	}

	return cli, nil
}
Example #25
0
// dial connects to the address addr for the network set in c.Net
func (w *reply) dial() (err error) {
	var conn net.Conn
	if w.client.Net == "" {
		conn, err = net.DialTimeout("udp", w.addr, 5*1e9)
	} else {
		conn, err = net.DialTimeout(w.client.Net, w.addr, 5*1e9)
	}
	if err != nil {
		return err
	}
	w.conn = conn
	return
}
Example #26
0
// Connect creates a UDP and TCP connection to a Riemann server
func (c *GorymanClient) Connect() error {
	udp, err := net.DialTimeout("udp", c.addr, time.Second*5)
	if err != nil {
		return err
	}
	tcp, err := net.DialTimeout("tcp", c.addr, time.Second*5)
	if err != nil {
		return err
	}
	c.udp = NewUdpTransport(udp)
	c.tcp = NewTcpTransport(tcp)
	return nil
}
Example #27
0
func NewWire(uri string) (*Wire, error) {
	u, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}

	wire := &Wire{URL: u}

	path := u.Host + u.Path

	if u.Scheme == "" && path != "" {
		u.Scheme = "file"
	}

	switch u.Scheme {
	case "":
		wire.Input = os.Stdin //use standard input, output
		wire.Output = os.Stdout
	case "file":
		f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
		if err != nil {
			return nil, err
		}
		wire.Output = f
		wire.Input = os.Stdin

	case "ssl":
		fallthrough
	case "tls":
		tcpConn, err := net.DialTimeout("tcp", path, DIAL_TIMEOUT)
		if err != nil {
			return nil, err
		}
		config := &tls.Config{InsecureSkipVerify: true}
		conn := tls.Client(tcpConn, config)
		wire.Input = conn
		wire.Output = conn

	default:
		conn, err := net.DialTimeout(u.Scheme, path, DIAL_TIMEOUT)
		if err != nil {
			return nil, err
		}
		wire.Input = conn
		wire.Output = conn
	}

	wire.CloseCh = make(chan bool, 10)

	return wire, nil
}
Example #28
0
// Connect establishes a new connection to the server. This should
// generally be done through server.AcquireSocket().
func (server *mongoServer) Connect(timeout time.Duration) (*mongoSocket, error) {
	server.RLock()
	master := server.info.Master
	dial := server.dial
	server.RUnlock()

	logf("Establishing new connection to %s (timeout=%s)...", server.Addr, timeout)
	var conn net.Conn
	var err error
	switch {
	case !dial.isSet():
		// Cannot do this because it lacks timeout support. :-(
		//conn, err = net.DialTCP("tcp", nil, server.tcpaddr)
		conn, err = net.DialTimeout("tcp", server.ResolvedAddr, timeout)
	case dial.old != nil:
		conn, err = dial.old(server.tcpaddr)
	case dial.new != nil:
		conn, err = dial.new(&ServerAddr{server.Addr, server.tcpaddr})
	default:
		panic("dialer is set, but both dial.old and dial.new are nil")
	}
	if err != nil {
		logf("Connection to %s failed: %v", server.Addr, err.Error())
		return nil, err
	}
	logf("Connection to %s established.", server.Addr)

	stats.conn(+1, master)
	return newSocket(server, conn, timeout), nil
}
Example #29
0
func NewProxy(args ProxyArgs) Proxy {
	routeServiceConfig := route_service.NewRouteServiceConfig(args.RouteServiceEnabled, args.RouteServiceTimeout, args.Crypto, args.CryptoPrev)

	p := &proxy{
		accessLogger: args.AccessLogger,
		traceKey:     args.TraceKey,
		ip:           args.Ip,
		logger:       steno.NewLogger("router.proxy"),
		registry:     args.Registry,
		reporter:     args.Reporter,
		transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(network, addr, 5*time.Second)
				if err != nil {
					return conn, err
				}
				if args.EndpointTimeout > 0 {
					err = conn.SetDeadline(time.Now().Add(args.EndpointTimeout))
				}
				return conn, err
			},
			DisableKeepAlives:  true,
			DisableCompression: true,
			TLSClientConfig:    args.TLSConfig,
		},
		fakedomain:         args.FakeDomain,
		secureCookies:      args.SecureCookies,
		routeServiceConfig: routeServiceConfig,
		ExtraHeadersToLog:  args.ExtraHeadersToLog,
	}

	return p
}
Example #30
0
func (d *sentinelFailover) dial() (net.Conn, error) {
	addr, err := d.MasterAddr()
	if err != nil {
		return nil, err
	}
	return net.DialTimeout("tcp", addr, d.opt.DialTimeout)
}