From f431ef4c9d6c80ed397322c6d6e7b9e5dc7e237f Mon Sep 17 00:00:00 2001 From: Jonathan Mercier-Ganady Date: Fri, 9 Oct 2020 10:34:15 +0100 Subject: [PATCH 1/2] Simplify GetListenPort --- server/server.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/server/server.go b/server/server.go index b66993a4..25e8d20c 100644 --- a/server/server.go +++ b/server/server.go @@ -264,12 +264,7 @@ func (s *Server) IsRunning() bool { func (s *Server) GetListenPort() int { s.mu.RLock() defer s.mu.RUnlock() - - if s.listener == nil { - return 0 - } - - return s.listener.Addr().(*net.TCPAddr).Port + return s.port } // recoverAndPersistState recovers any existing server metadata state from disk From 2d5d2a8f0cf4c70413149421803a98dc36f8f440 Mon Sep 17 00:00:00 2001 From: Jonathan Mercier-Ganady Date: Fri, 9 Oct 2020 10:52:48 +0100 Subject: [PATCH 2/2] Use the listen port in case the connection port is 0 Note that this is using the server's listen port, not the listen host/port set in the configuration. --- server/metadata.go | 2 +- server/server.go | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/server/metadata.go b/server/metadata.go index 605ec1f7..0b1b1654 100644 --- a/server/metadata.go +++ b/server/metadata.go @@ -209,7 +209,7 @@ func (m *metadataAPI) brokerCache(serverIDs map[string]struct{}) ([]*client.Brok // argument is the expected number of peers to get a response from. func (m *metadataAPI) fetchBrokerInfo(ctx context.Context, numPeers int) ([]*client.Broker, *status.Status) { // Add ourselves. - connectionAddress := m.config.GetConnectionAddress() + connectionAddress := m.getConnectionAddress() brokers := []*client.Broker{{ Id: m.config.Clustering.ServerID, Host: connectionAddress.Host, diff --git a/server/server.go b/server/server.go index 25e8d20c..71cee0ba 100644 --- a/server/server.go +++ b/server/server.go @@ -267,6 +267,22 @@ func (s *Server) GetListenPort() int { return s.port } +// getConnectionAddress returns the connection address that should be used by +// the server. It uses the port the server is currently listening to if the +// connection port is 0, so that an OS-assigned port can be used as a connection +// port. +func (s *Server) getConnectionAddress() HostPort { + s.mu.RLock() + defer s.mu.RUnlock() + + address := s.config.GetConnectionAddress() + if address.Port == 0 { + address.Port = s.port + } + + return address +} + // recoverAndPersistState recovers any existing server metadata state from disk // to initialize the server then writes the metadata back to disk. func (s *Server) recoverAndPersistState() error { @@ -814,7 +830,7 @@ func (s *Server) handleServerInfoRequest(m *nats.Msg) { return } - connectionAddress := s.config.GetConnectionAddress() + connectionAddress := s.getConnectionAddress() data, err := proto.MarshalServerInfoResponse(&proto.ServerInfoResponse{ Id: s.config.Clustering.ServerID, Host: connectionAddress.Host,