diff --git a/server/monitor.go b/server/monitor.go index 6c82a42ad73..00614c506c0 100644 --- a/server/monitor.go +++ b/server/monitor.go @@ -320,13 +320,13 @@ func (s *Server) HandleRoutez(w http.ResponseWriter, r *http.Request) { } ri.Subs = castToSliceString(sublist) } - r.mu.Unlock() - - if ip, ok := r.nc.(*net.TCPConn); ok { - addr := ip.RemoteAddr().(*net.TCPAddr) + switch conn := r.nc.(type) { + case *net.TCPConn, *tls.Conn: + addr := conn.RemoteAddr().(*net.TCPAddr) ri.Port = addr.Port ri.IP = addr.IP.String() } + r.mu.Unlock() rs.Routes = append(rs.Routes, ri) } s.mu.Unlock() diff --git a/server/monitor_test.go b/server/monitor_test.go index a0df3113fd0..a94e0e67793 100644 --- a/server/monitor_test.go +++ b/server/monitor_test.go @@ -1397,3 +1397,41 @@ func TestMonitorHandler(t *testing.T) { t.Fatal("HTTP Handler should be nil") } } + +func TestMonitorRoutezRace(t *testing.T) { + resetPreviousHTTPConnections() + srvAOpts := DefaultMonitorOptions() + srvAOpts.Cluster.Port = -1 + srvA := RunServer(srvAOpts) + defer srvA.Shutdown() + + srvBOpts := nextServerOpts(srvAOpts) + srvBOpts.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) + + url := fmt.Sprintf("http://127.0.0.1:%d/", srvA.MonitorAddr().Port) + doneCh := make(chan struct{}) + go func() { + defer func() { + doneCh <- struct{}{} + }() + for i := 0; i < 10; i++ { + time.Sleep(10 * time.Millisecond) + srvB := RunServer(srvBOpts) + time.Sleep(20 * time.Millisecond) + srvB.Shutdown() + } + }() + done := false + for !done { + if resp, err := http.Get(url + "routez"); err != nil { + time.Sleep(10 * time.Millisecond) + } else { + resp.Body.Close() + } + select { + case <-doneCh: + done = true + default: + } + } +}