Esempio n. 1
0
func (s *Server) loop(listener *net.TCPListener) {
	defer s.waitGroup.Done()
	log.Printf("[DEBUG] waiting for connections...")
	for {
		select {
		case <-s.ch:
			log.Printf("[DEBUG] stopping listening on %s", listener.Addr())
			_ = listener.Close()
			return
		default:
		}
		_ = listener.SetDeadline(time.Now().Add(s.Deadline))
		conn, err := listener.AcceptTCP()
		if nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Printf("[ERROR] error on loop: %s", err)
		}
		log.Printf("[DEBUG] connected to %s", conn.RemoteAddr())
		c := &connection{
			conn:          conn,
			protocol:      s.protocolCtor(conn),
			waitGroup:     s.waitGroup,
			deadline:      s.Deadline,
			readBuffSize:  s.ReadBuffSize,
			writeBuffSize: s.WriteBuffSize,
		}
		s.waitGroup.Add(1)
		go c.handle(s.ch)
	}
}
Esempio n. 2
0
func (this *Server) Start(listener *net.TCPListener) {
	log.Printf("Start listen on %v", listener.Addr())
	this.waitGroup.Add(1)
	defer func() {
		listener.Close()
		this.waitGroup.Done()
	}()

	for {
		select {
		case <-this.exitCh:
			log.Printf("Stop listen on %v", listener.Addr())
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(this.acceptTimeout))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				// log.Printf("Accept timeout: %v", opErr)
				continue
			}
			log.Printf("Accept error: %v", err)
			continue
		}

		log.Printf("Accept: %v", conn.RemoteAddr())
		go this.handleClientConn(conn)
	}
}
Esempio n. 3
0
// Start starts service
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	for {
		select {
		case <-s.exitChan:
			return

		default:
		}

		listener.SetDeadline(time.Now().Add(acceptTimeout))

		conn, err := listener.AcceptTCP()
		if err != nil {
			continue
		}

		go newConn(conn, s).Do()
	}
}
// listen starts listening for a video connection on a socket for the given
// player. This video will be streamed to the partner.
func listen(ln *net.TCPListener, p *player, partner *player, pairs *[]playerPair) {
	var err error

	// Wait for a TCP connection
	for {
		p.Lock()
		ln.SetDeadline(time.Now().Add(time.Second * 5))
		p.conn, err = ln.AcceptTCP()
		if err == nil {
			break
		}
		p.Unlock()
	}

	log.Println("connected to player", p.id)
	p.conn.SetKeepAlive(true)
	p.conn.SetKeepAlivePeriod(time.Second / 2)
	p.Unlock()
	streamVideo(p, partner)
	removePlayer(pairs, p)
	p.Lock()
	log.Println("lost connection to player", p.id)
	p.active = false
	p.Unlock()
}
Esempio n. 5
0
// Start starts service
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	var index uint32
	index = 0
	for {
		select {
		case <-s.exitChan:
			return

		default:
		}

		listener.SetDeadline(time.Now().Add(acceptTimeout))

		conn, err := listener.AcceptTCP()
		if err != nil {
			continue
		}

		myconn := newConn(conn, s, index)
		s.mqhub.conns[index] = myconn
		index += 1

		go myconn.Do()
	}
}
Esempio n. 6
0
func (self *Service) Serve(listener *net.TCPListener) {
	defer self.wg.Done()

	log.Println("initializing...")
	var err error
	self.repo, err = repository.Initialize(self.dataDir)
	log.Println("data directory: ", self.dataDir)
	if err != nil {
		log.Fatal(err)
	}

	for {
		select {
		case <-self.ch:
			log.Println("stopping listening on", listener.Addr())
			listener.Close()
			return
		default:
		}
		listener.SetDeadline(time.Now().Add(1e9))
		conn, err := listener.AcceptTCP()
		if nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
		}
		self.wg.Add(1)
		go self.HandleConnection(conn)
	}
}
func accept_workers(listener *net.TCPListener, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		if server_state == STOPPED {
			return
		}
		listener.SetDeadline(time.Now().Add(time.Duration(time.Second)))
		conn, err := listener.Accept()
		if err != nil {
			netErr, ok := err.(net.Error)
			if ok && netErr.Timeout() && netErr.Temporary() {
				continue
			} else {
				logger.Printf("accept worker error: %v\n", err)
				server_state = STOPPED
				return
			}
		}
		worker := &tsp_task_manager.WorkerInfo{new_worker_id, &conn, -1}
		tsp_task_manager.AddNewWorker(worker)
		logger.Println("I'm accept worker #", new_worker_id)
		go listen_worker(worker)
		new_worker_id++
	}
}
func accept_clients(listener *net.TCPListener, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		if server_state == STOPPED {
			return
		}
		listener.SetDeadline(time.Now().Add(time.Duration(time.Second)))
		conn, err := listener.Accept()
		if err != nil {
			netErr, ok := err.(net.Error)
			if ok && netErr.Timeout() && netErr.Temporary() {
				continue
			} else {
				logger.Printf("accept client error: %v\n", err)
				server_state = STOPPED
				return
			}
		}
		client := tsp_task_manager.ClientInfo{new_client_id, &conn}
		new_client_id++
		tsp_task_manager.AddNewClient(client)
		logger.Println("I'm accept client #", client.ID)
		go listen_client(client)
	}
}
Esempio n. 9
0
// Start starts service
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	for {
		select {
		case <-s.exitChan:
			return

		default:
		}

		listener.SetDeadline(time.Now().Add(acceptTimeout))

		conn, err := listener.AcceptTCP()

		if e, ok := err.(net.Error); ok && e.Timeout() {
			continue
			// This was a timeout
		} else if err != nil {
			l4g.Info("listener accepttcp continue and found a error: %v", err)
			return
			// This was an error, but not a timeout
		}

		go newConn(conn, s).Do()
	}
}
Esempio n. 10
0
// Accept connections and spawn a goroutine to serve each one.  Stop listening
// if anything is received on the service's channel.
func (self *Service) Serve(listener *net.TCPListener) {
	defer self.waitGroup.Done()
	for {
		select {
		case <-self.done:
			log.Println("Stopping listening on", listener.Addr())
			listener.Close()
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(1e9))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
		}

		log.Println(conn.RemoteAddr(), "connected")

		connection := NewConnection(conn, make(chan []byte))
		self.dataMap[connection.Id] = connection
		self.waitGroup.Add(1)
		go self.serve(connection)
	}
}
Esempio n. 11
0
File: server.go Progetto: houcy/push
func (this *Server) Run(listener *net.TCPListener) {
	defer func() {
		listener.Close()
	}()

	//go this.dealSpamConn()
	log.Infof("Starting comet server on: %s", listener.Addr().String())
	if err := storage.Instance.AddComet(this.Name); err != nil {
		log.Errorf("failed to add comet to Redis: %s", err.Error())
	}

	// keep the data of this node not expired on redis
	this.startRefreshRoutine()
	this.startWorkers()

	for {
		select {
		case <-this.ctrl:
			log.Infof("ask me to quit")
			this.stopWorkers()
			this.stopRefreshRoutine()
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(this.acceptTimeout * time.Second))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if e, ok := err.(*net.OpError); ok && e.Timeout() {
				continue
			}
			log.Errorf("accept failed: %v\n", err)
			continue
		}
		/*
			// first packet must sent by client in specified seconds
			if err = conn.SetReadDeadline(time.Now().Add(20)); err != nil {
				glog.Errorf("conn.SetReadDeadLine() error(%v)", err)
				conn.Close()
				continue
			}*/
		go this.handleConnection(conn)
	}
}
Esempio n. 12
0
func (this *Server) Start(listener *net.TCPListener) {
	log.Printf("Start listen on %v\r\n", listener.Addr())
	this.waitGroup.Add(1)
	defer func() {
		listener.Close()
		this.waitGroup.Done()
	}()

	// 防止恶意连接
	go this.dealSpamConn()

	// report记录,定时发送邮件
	go report.Work()

	for {
		select {
		case <-this.exitCh:
			log.Printf("Stop listen on %v\r\n", listener.Addr())
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(this.acceptTimeout))
		conn, err := listener.AcceptTCP()

		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				// log.Printf("Accept timeout: %v\r\n", opErr)
				continue
			}
			report.AddCount(report.TryConnect, 1)
			log.Printf("Accept error: %v\r\n", err)
			continue
		}

		report.AddCount(report.SuccessConnect, 1)

		// 连接后等待登陆验证
		handlers.ConnMapLoginStatus.Set(conn, time.Now())
		log.Printf("Accept: %v\r\n", conn.RemoteAddr())

		go this.handleClientConn(conn)
	}
}
Esempio n. 13
0
// Accepts inbound connections till the service is terminated. For each one it
// starts a new handler and hands the socket over.
func (r *Relay) acceptor(listener *net.TCPListener) {
	// Accept connections until termination request
	var errc chan error
	for errc == nil {
		select {
		case errc = <-r.quit:
			break
		case client := <-r.done:
			// A client terminated, remove from active list
			delete(r.clients, client)
			if err := client.report(); err != nil {
				log.Printf("relay: closing client error: %v.", err)
			}
		default:
			// Accept an incoming connection but without blocking for too long
			listener.SetDeadline(time.Now().Add(acceptPollRate))
			if sock, err := listener.Accept(); err == nil {
				if rel, err := r.acceptRelay(sock); err != nil {
					log.Printf("relay: accept failed: %v.", err)
				} else {
					r.clients[rel] = struct{}{}
				}
			} else if !err.(net.Error).Timeout() {
				log.Printf("relay: accept failed: %v, terminating.", err)
			}
		}
	}
	// In case of failure, wait for termination request
	if errc == nil {
		errc = <-r.quit
	}
	// Forcefully close all active client connections
	for rel, _ := range r.clients {
		rel.drop()
		<-r.done
	}
	for rel, _ := range r.clients {
		rel.report()
	}
	// Clean up and report
	errc <- listener.Close()
}
Esempio n. 14
0
func serve(listener *net.TCPListener) (err error) {
	for {
		select {
		default:
			listener.SetDeadline(time.Now().Add(1e9 * time.Nanosecond))
			var c *net.TCPConn
			c, err = listener.AcceptTCP()
			if err != nil {
				if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
					continue
				}
				log.WithField("error", err).Warn("AcceptTCP")
				return
			}
			log.WithField("client", c.RemoteAddr()).Debug("Connected")
			go func(c *net.TCPConn) {
				handleConnection(c)
			}(c)
		}
	}
}
Esempio n. 15
0
// Run opens the server socket and runs the telnet server which spawns go
// routines for every connecting client.
func (s *Server) Run(listener *net.TCPListener) error {
	// we want to close the listener when we'll be quitting
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		// wait that all opened goroutines are closed
		s.waitGroup.Done()
	}()

	for {
		// loop forever...
		select {
		case <-s.quitChan:
			// ...until the server quits
			return nil

		default:
		}

		acceptTimeout := time.Second

		// listening for incoming TCP connections
		listener.SetDeadline(time.Now().Add(acceptTimeout))
		conn, err := listener.AcceptTCP()
		if err != nil {
			// wrong connection, leave it
			continue
		}

		s.waitGroup.Add(1)
		go func() {
			c := newClient(conn, s.prompt, s.cmdHandler, s.userdata)
			c.handle()
			s.waitGroup.Done()
		}()
		// start a new goroutine, one more to wait for when we'll be quitting
	}
}
Esempio n. 16
0
func (this *Server) Run(listener *net.TCPListener) {
	this.waitGroup.Add(1)
	defer func() {
		listener.Close()
		this.waitGroup.Done()
	}()

	//go this.dealSpamConn()
	log.Infof("Starting comet server on: %s\n", listener.Addr().String())
	log.Infof("Comet server settings: readtimeout [%d], accepttimeout [%d], heartbeattimeout [%d]\n",
		this.readTimeout, this.acceptTimeout, this.heartbeatTimeout)
	for {
		select {
		case <-this.exitCh:
			log.Infof("Stopping comet server")
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(this.acceptTimeout))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if e, ok := err.(*net.OpError); ok && e.Timeout() {
				continue
			}
			log.Errorf("accept failed: %v\n", err)
			continue
		}
		/*
			// first packet must sent by client in specified seconds
			if err = conn.SetReadDeadline(time.Now().Add(20)); err != nil {
				glog.Errorf("conn.SetReadDeadLine() error(%v)", err)
				conn.Close()
				continue
			}*/
		go this.handleConnection(conn)
	}
}
Esempio n. 17
0
func (s *Server) serve(l *net.TCPListener) {
	defer s.waitGroup.Done()
	s.waitGroup.Add(1)
	for {
		select {
		case <-s.ch:
			log.Debug("stopping listening on: ", l.Addr())
			l.Close()
			return
		default:
		}

		l.SetDeadline(time.Now().Add(1e9))
		conn, err := l.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Debug(err)
		}

		// handle the connection in a new goroutine. This returns to listener
		// accepting code so that multiple connections may be served concurrently.
		keeper := NewKeeper(conn, s.storeClient)

		go func() {
			defer s.waitGroup.Done()
			s.waitGroup.Add(1)
			log.Debug("client connected: ", conn.RemoteAddr())
			if err := keeper.Handle(); err != nil {
				log.Debug("client disconnected: ", conn.RemoteAddr(), " with error: ", err)
			} else {
				log.Debug("client disconnected: ", conn.RemoteAddr())
			}
		}()
	}
}
Esempio n. 18
0
/*
 * Start runs the server main listening loop
 */
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	// we want to close the listener when we'll be quitting
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	for {
		// loop forever...
		select {
		case <-s.exitChan:
			// ...until the server quits
			return

		default:
		}

		// listening for incoming TCP connections
		listener.SetDeadline(time.Now().Add(acceptTimeout))
		conn, err := listener.AcceptTCP()
		if err != nil {
			// wrong connection, leave it
			continue
		}

		// start a new goroutine, one more to wait for when we'll be quitting
		s.waitGroup.Add(1)
		go func() {
			// disable Nagle algorithm
			conn.SetNoDelay(true)
			newConn(conn, s).StartLoops()
			s.waitGroup.Done()
		}()
	}
}
Esempio n. 19
0
func handleAccept(limiter <-chan uint32, lsn *net.TCPListener) {
	defer func() {
		<-limiter
		g_wg.Done()
	}()

	// 处理连接
	lsn.SetDeadline(time.Now().Add(time.Second * 1))
	for {
		conn, err := lsn.AcceptTCP()
		if err != nil {
			oe := err.(*net.OpError)
			if !oe.Timeout() {
				fmt.Println(err)
			}
			break
		}

		conn.SetDeadline(time.Now().Add(time.Second * 60)) // 长连接保持时间

		// 收发消息
		g_wg.Add(1)
		go func(conn *net.TCPConn) {
			defer func() {
				conn.Close()
				g_wg.Done()
			}()

			for {
				rbuf := make([]byte, 4096)
				sz, err := conn.Read(rbuf)
				if err != nil {
					if err != io.EOF {
						fmt.Println(err)
					}
					break
				}

				var magicno, protover, ent_ofst, ent_len, checksum uint32
				rbuf_rder := bytes.NewReader(rbuf)
				binary.Read(rbuf_rder, binary.BigEndian, &magicno)
				binary.Read(rbuf_rder, binary.BigEndian, &protover)
				binary.Read(rbuf_rder, binary.BigEndian, &ent_ofst)
				binary.Read(rbuf_rder, binary.BigEndian, &ent_len)
				binary.Read(rbuf_rder, binary.BigEndian, &checksum)

				if 0x9F846C27 != magicno {
					break
				}
				if ent_ofst < 20 || ent_ofst >= uint32(sz) {
					break
				}
				if ent_len+20 > uint32(sz) {
					break
				}

				content := rbuf[ent_ofst : ent_ofst+ent_len]
				json_rslt := make(map[string]interface{})
				err = json.Unmarshal(content, &json_rslt)
				if nil != err {
					break
				}

				method, exists := json_rslt["method"]
				if !exists {
					fmt.Println("no method found")
					break
				}
				target, exists := json_rslt["target"]
				if !exists {
					fmt.Println("no target found")
					break
				}
				args, exists := json_rslt["args"]
				if !exists {
					fmt.Println("no args found")
					break
				}

				fmt.Println(string(content)) // 验证码请求日志

				do_http := func(method string, target string, args string) *string {
					rsp, err := http.Post(
						target, "application/x-www-form-urlencoded",
						strings.NewReader(args))
					if nil != err {
						fmt.Println(err)
						return nil
					}

					defer rsp.Body.Close()

					body, err := ioutil.ReadAll(rsp.Body)
					if nil != err {
						fmt.Println(err)
						return nil
					}
					rslt := string(body)

					return &rslt
				}

				argmap, err := url.ParseQuery(args.(string))
				if nil != err {
					fmt.Println("url parse query failed:" + err.Error())
					break
				}
				http_rsp := do_http(method.(string), target.(string), argmap.Encode())

				sbuf := new(bytes.Buffer)
				binary.Write(sbuf, binary.BigEndian, uint32(0x9F846C27))
				binary.Write(sbuf, binary.BigEndian, uint32(1000))
				binary.Write(sbuf, binary.BigEndian, uint32(20))
				binary.Write(sbuf, binary.BigEndian, uint32(len(*http_rsp)))
				binary.Write(sbuf, binary.BigEndian, uint32(0))
				binary.Write(sbuf, binary.BigEndian, []byte(*http_rsp))
				conn.Write(sbuf.Bytes())
			}
		}(conn)
	}
}
Esempio n. 20
0
func TestTCPPing(t *testing.T) {
	var tcp *net.TCPListener
	var tcpAddr *net.TCPAddr
	for port := 60000; port < 61000; port++ {
		tcpAddr = &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: port}
		tcpLn, err := net.ListenTCP("tcp", tcpAddr)
		if err == nil {
			tcp = tcpLn
			break
		}
	}
	if tcp == nil {
		t.Fatalf("no tcp listener")
	}

	// Note that tcp gets closed in the last test, so we avoid a deferred
	// Close() call here.

	m := GetMemberlist(t)
	defer m.Shutdown()
	pingTimeout := m.config.ProbeInterval
	pingTimeMax := m.config.ProbeInterval + 10*time.Millisecond

	// Do a normal round trip.
	pingOut := ping{SeqNo: 23, Node: "mongo"}
	go func() {
		tcp.SetDeadline(time.Now().Add(pingTimeMax))
		conn, err := tcp.AcceptTCP()
		if err != nil {
			t.Fatalf("failed to connect: %s", err)
		}
		defer conn.Close()

		msgType, _, dec, err := m.readTCP(conn)
		if err != nil {
			t.Fatalf("failed to read ping: %s", err)
		}

		if msgType != pingMsg {
			t.Fatalf("expecting ping, got message type (%d)", msgType)
		}

		var pingIn ping
		if err := dec.Decode(&pingIn); err != nil {
			t.Fatalf("failed to decode ping: %s", err)
		}

		if pingIn.SeqNo != pingOut.SeqNo {
			t.Fatalf("sequence number isn't correct (%d) vs (%d)", pingIn.SeqNo, pingOut.SeqNo)
		}

		if pingIn.Node != pingOut.Node {
			t.Fatalf("node name isn't correct (%s) vs (%s)", pingIn.Node, pingOut.Node)
		}

		ack := ackResp{pingIn.SeqNo, nil}
		out, err := encode(ackRespMsg, &ack)
		if err != nil {
			t.Fatalf("failed to encode ack: %s", err)
		}

		err = m.rawSendMsgTCP(conn, out.Bytes())
		if err != nil {
			t.Fatalf("failed to send ack: %s", err)
		}
	}()
	deadline := time.Now().Add(pingTimeout)
	didContact, err := m.sendPingAndWaitForAck(tcpAddr, pingOut, deadline)
	if err != nil {
		t.Fatalf("error trying to ping: %s", err)
	}
	if !didContact {
		t.Fatalf("expected successful ping")
	}

	// Make sure a mis-matched sequence number is caught.
	go func() {
		tcp.SetDeadline(time.Now().Add(pingTimeMax))
		conn, err := tcp.AcceptTCP()
		if err != nil {
			t.Fatalf("failed to connect: %s", err)
		}
		defer conn.Close()

		_, _, dec, err := m.readTCP(conn)
		if err != nil {
			t.Fatalf("failed to read ping: %s", err)
		}

		var pingIn ping
		if err := dec.Decode(&pingIn); err != nil {
			t.Fatalf("failed to decode ping: %s", err)
		}

		ack := ackResp{pingIn.SeqNo + 1, nil}
		out, err := encode(ackRespMsg, &ack)
		if err != nil {
			t.Fatalf("failed to encode ack: %s", err)
		}

		err = m.rawSendMsgTCP(conn, out.Bytes())
		if err != nil {
			t.Fatalf("failed to send ack: %s", err)
		}
	}()
	deadline = time.Now().Add(pingTimeout)
	didContact, err = m.sendPingAndWaitForAck(tcpAddr, pingOut, deadline)
	if err == nil || !strings.Contains(err.Error(), "Sequence number") {
		t.Fatalf("expected an error from mis-matched sequence number")
	}
	if didContact {
		t.Fatalf("expected failed ping")
	}

	// Make sure an unexpected message type is handled gracefully.
	go func() {
		tcp.SetDeadline(time.Now().Add(pingTimeMax))
		conn, err := tcp.AcceptTCP()
		if err != nil {
			t.Fatalf("failed to connect: %s", err)
		}
		defer conn.Close()

		_, _, _, err = m.readTCP(conn)
		if err != nil {
			t.Fatalf("failed to read ping: %s", err)
		}

		bogus := indirectPingReq{}
		out, err := encode(indirectPingMsg, &bogus)
		if err != nil {
			t.Fatalf("failed to encode bogus msg: %s", err)
		}

		err = m.rawSendMsgTCP(conn, out.Bytes())
		if err != nil {
			t.Fatalf("failed to send bogus msg: %s", err)
		}
	}()
	deadline = time.Now().Add(pingTimeout)
	didContact, err = m.sendPingAndWaitForAck(tcpAddr, pingOut, deadline)
	if err == nil || !strings.Contains(err.Error(), "Unexpected msgType") {
		t.Fatalf("expected an error from bogus message")
	}
	if didContact {
		t.Fatalf("expected failed ping")
	}

	// Make sure failed I/O respects the deadline. In this case we try the
	// common case of the receiving node being totally down.
	tcp.Close()
	deadline = time.Now().Add(pingTimeout)
	startPing := time.Now()
	didContact, err = m.sendPingAndWaitForAck(tcpAddr, pingOut, deadline)
	pingTime := time.Now().Sub(startPing)
	if err != nil {
		t.Fatalf("expected no error during ping on closed socket, got: %s", err)
	}
	if didContact {
		t.Fatalf("expected failed ping")
	}
	if pingTime > pingTimeMax {
		t.Fatalf("took too long to fail ping, %9.6f", pingTime.Seconds())
	}
}
Esempio n. 21
0
// Listen on the configured TCP port, accepting new connections and processing
// messages from those connections; this function will not return until
// t.Shutdown() is called.
func (t *TCPMsgRing) Listen() {
	var err error
OuterLoop:
	for {
		if err != nil {
			atomic.AddInt32(&t.listenErrors, 1)
			t.logCritical("listen: %s\n", err)
			time.Sleep(time.Second)
		}
		select {
		case <-t.controlChan:
			break OuterLoop
		default:
		}
		ring := t.Ring()
		if ring == nil {
			time.Sleep(time.Second)
			continue
		}
		node := ring.LocalNode()
		var tcpAddr *net.TCPAddr
		tcpAddr, err = net.ResolveTCPAddr("tcp", node.Address(t.addressIndex))
		if err != nil {
			continue
		}
		var server *net.TCPListener
		server, err = net.ListenTCP("tcp", tcpAddr)
		if err != nil {
			continue
		}
		for {
			select {
			case <-t.controlChan:
				break OuterLoop
			default:
			}
			// Deadline to force checking t.controlChan once a second.
			server.SetDeadline(time.Now().Add(time.Second))
			var netConn net.Conn
			if t.useTLS {
				l := tls.NewListener(server, t.serverTLSConfig)
				netConn, err = l.Accept()
				if err == nil {
					if t.mutualTLS {
						err = verifyClientAddrMatch(netConn.(*tls.Conn))
						if err != nil {
							t.logCritical("Client address != any cert names")
						}
					}
				}
			} else {
				netConn, err = server.AcceptTCP()
			}
			if err != nil {
				if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
					continue
				}
				server.Close()
				continue OuterLoop
			}
			atomic.AddInt32(&t.incomingConnections, 1)
			go func(netConn net.Conn) {
				if addr, err := t.handshake(netConn); err != nil {
					t.logDebug("listen: %s %s\n", addr, err)
					netConn.Close()
					return
				} else {
					t.chaosAddrOffsLock.RLock()
					if t.chaosAddrOffs[addr] {
						t.logDebug("listen: %s chaosAddrOff\n", addr)
						netConn.Close()
						t.chaosAddrOffsLock.RUnlock()
						return
					}
					t.chaosAddrOffsLock.RUnlock()
					msgChan, created := t.msgChanForAddr(addr)
					// NOTE: If created is true, it'll indicate to connection
					// that redialing is okay. If created is false, once the
					// connection has terminated it won't be reestablished
					// since there is already another connection running that
					// will redial.
					go t.connection(addr, netConn, msgChan, created)
				}
			}(netConn)
		}
	}
}