Example #1
0
func shutdownServerAndWait(t *testing.T, s *server.Server) bool {
	listenSpec := s.GetListenEndpoint()
	routeListenSpec := s.GetRouteListenEndpoint()

	s.Shutdown()

	// For now, do this only on Windows. Lots of tests would fail
	// without this because the listen port would linger from one
	// test to another causing failures.
	checkShutdown := func(listen string) bool {
		down := false
		maxTime := time.Now().Add(5 * time.Second)
		for time.Now().Before(maxTime) {
			conn, err := net.Dial("tcp", listen)
			if err != nil {
				down = true
				break
			}
			conn.Close()
			// Retry after 50ms
			time.Sleep(50 * time.Millisecond)
		}
		return down
	}
	if listenSpec != "" {
		if !checkShutdown(listenSpec) {
			return false
		}
	}
	if routeListenSpec != "" {
		if !checkShutdown(routeListenSpec) {
			return false
		}
	}
	return true
}
func runTest(url, user string, count int64) {
	var wg sync.WaitGroup
	var srv *server.Server

	if useLocalServer {
		srv, _ = test.RunServerWithConfig("./gnatsd.conf")
	}

	opts := nats.DefaultOptions
	opts.Timeout = time.Second * 600
	opts.Url = url
	opts.User = user
	opts.Password = "password"

	opts.ReconnectedCB = func(c *nats.Conn) {
		if *doReconnect {
			wg.Done()
		}
	}

	var connStartTime = time.Now()

	connList := make([]*nats.Conn, 0, count)
	wg.Add(int(count))

	// create connections simultaneously to make the test complete faster.
	for i := int64(0); i < count; i++ {
		go func() {
			// randomize connect times to prevent connection read errors
			time.Sleep(time.Millisecond * time.Duration(rand.Intn(2000)))
			nc, err := opts.Connect()
			if err != nil {
				log.Fatalf("Can't connect: %v\n", err)
			}
			connList = append(connList, nc)
			wg.Done()
		}()
	}
	defer func() {
		for _, nc := range connList {
			nc.Close()
		}
	}()

	// wait for all connections to connect
	wg.Wait()
	totalConnectTime := time.Now().Sub(connStartTime)

	var reconnectWaitTime time.Duration

	// Bounce the server
	if *doReconnect {
		wg.Add(int(count))

		srv.Shutdown()
		disconnectTime := time.Now()
		srv, _ = test.RunServerWithConfig("./gnatsd.conf")

		// wait for all connections to reconnect
		wg.Wait()
		reconnectWaitTime = time.Now().Sub(disconnectTime)
	}
	defer srv.Shutdown()

	if *csvOutput {
		log.Printf("%s,%f", user, totalConnectTime.Seconds())
	} else {
		if *doReconnect {
			log.Printf("user=%s, connect time=%v, reconnect time=%v",
				user, totalConnectTime, reconnectWaitTime)
		} else {
			log.Printf("user=%s, connect time=%v",
				user, totalConnectTime)
		}
	}
}