@@ -38,6 +38,7 @@ ServiceDiscovery::ServiceDiscovery(const std::string& url, const std::string& na
3838 : curlHandle(initCurl(), &ServiceDiscovery::deleteCurl), mConsulUrl (url), mName (name), mId (id), mHealthUrl (healthEndUrl)
3939{
4040 mHealthUrl = mHealthUrl .empty () ? boost::asio::ip::host_name () : mHealthUrl ;
41+ mHealthPortAssigned = false ;
4142
4243 mHealthThread = std::thread ([=] {
4344#ifdef __linux__
@@ -96,6 +97,11 @@ bool ServiceDiscovery::_register(const std::string& objects)
9697 check.put (" Name" , " Health check " + mId );
9798 check.put (" Interval" , " 5s" );
9899 check.put (" DeregisterCriticalServiceAfter" , " 1m" );
100+ // Wait until port is set by the thread
101+ {
102+ std::unique_lock<std::mutex> lk (mHealthPortMutex );
103+ mHealthPortCV .wait (lk, [this ] { return mHealthPortAssigned == true ; });
104+ }
99105 check.put (" TCP" , mHealthUrl + " :" + std::to_string (mHealthPort ));
100106 checks.push_back (std::make_pair (" " , check));
101107
@@ -151,12 +157,18 @@ void ServiceDiscovery::runHealthServer()
151157 ILOG (Debug, Trace) << " ServiceDiscovery::runHealthServer - cound not bind to " << port << ENDM ;
152158 continue ; // try the next one
153159 }
154- // if we reach this point it means that we could bind
155- mHealthPort = port;
156- ILOG (Debug, Devel) << " ServiceDiscovery selected port: " << mHealthPort << ENDM ;
157160 break ;
158161 }
159162
163+ // assign the port and unblock the main thread (we got a port or we failed)
164+ {
165+ ILOG (Debug, Devel) << " ServiceDiscovery selected port: " << mHealthPort << ENDM ;
166+ std::lock_guard<std::mutex> lk (mHealthPortMutex );
167+ mHealthPort = port;
168+ mHealthPortAssigned = true ;
169+ }
170+ mHealthPortCV .notify_one ();
171+
160172 if (cycle == rangeLength) {
161173 ILOG (Error, Support) << " Could not find a free port for the ServiceDiscovery, aborting the ServiceDiscovery health check" << ENDM ;
162174 return ;
0 commit comments