Skip to content

Commit 78954c7

Browse files
committed
[ISSUE apache#8426] Resolve actually bound server port for client registration when server.port=0
PortUtils.findPort reflected getPort() off the web-server factory config bean, so an embedded server started on server.port=0 reported its configured value 0 as the registration port. Discovery now reads the port the owned WebServer actually bound from the client's application context (walking up the parent chain so classic child contexts resolve to their owning server context), keeps the Boot 1.x/2.x factory and JMX external-container fallbacks for external deployments, and fails loudly instead of silently resolving a non-positive port. The client-wide register config now treats a positive advertised port as authoritative and otherwise resolves the bound port, instead of registering a configured 0 verbatim.
1 parent 71b7f37 commit 78954c7

8 files changed

Lines changed: 320 additions & 15 deletions

File tree

‎shenyu-client/shenyu-client-core/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@
8686
<artifactId>spring-boot-starter-tomcat</artifactId>
8787
<scope>test</scope>
8888
</dependency>
89+
<dependency>
90+
<groupId>io.projectreactor</groupId>
91+
<artifactId>reactor-core</artifactId>
92+
<scope>test</scope>
93+
</dependency>
8994
<dependency>
9095
<groupId>com.google.protobuf</groupId>
9196
<artifactId>protobuf-java</artifactId>

‎shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfigImpl.java‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,15 @@ public List<String> getNamespace() {
8080
public Integer getPort() {
8181

8282
if (Objects.isNull(port)) {
83-
this.port = Optional
83+
final Integer configured = Optional
8484
.ofNullable(props.getProperty(ShenyuClientConstants.PORT))
8585
.map(Integer::parseInt)
86-
.orElseGet(() -> PortUtils
87-
.findPort(applicationContext.getAutowireCapableBeanFactory()));
86+
.orElse(null);
87+
//a positive advertised port is authoritative; an absent or non-positive
88+
//one resolves the port the owned web server actually bound (issue #8426)
89+
this.port = Objects.nonNull(configured) && configured > 0
90+
? configured
91+
: PortUtils.findPort(applicationContext);
8892
}
8993

9094
return this.port;

‎shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/utils/PortUtils.java‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,70 @@
2020
import org.apache.commons.collections4.CollectionUtils;
2121
import org.apache.shenyu.common.exception.ShenyuException;
2222
import org.springframework.beans.factory.BeanFactory;
23+
import org.springframework.context.ApplicationContext;
2324

2425
import javax.management.MBeanServer;
2526
import javax.management.ObjectName;
2627
import java.lang.management.ManagementFactory;
2728
import java.lang.reflect.InvocationTargetException;
2829
import java.lang.reflect.Method;
30+
import java.util.Objects;
2931
import java.util.Set;
3032

3133
/**
3234
* get the port number exposed by the current tomcat.
3335
*/
3436
public class PortUtils {
3537

38+
/**
39+
* Guard against malformed context parent chains when walking up to the
40+
* application context that owns the running web server.
41+
*/
42+
private static final int MAX_CONTEXT_DEPTH = 8;
43+
44+
/**
45+
* Referenced reflectively so this module keeps no compile-time spring-boot dependency.
46+
*/
47+
private static final String WEB_SERVER_APPLICATION_CONTEXT_CLASS_NAME =
48+
"org.springframework.boot.web.context.WebServerApplicationContext";
49+
50+
/**
51+
* Referenced reflectively so this module keeps no compile-time spring-boot dependency.
52+
*/
53+
private static final String WEB_SERVER_CLASS_NAME =
54+
"org.springframework.boot.web.server.WebServer";
55+
56+
/**
57+
* Find the port the application's own embedded web server actually bound.
58+
* Note: preferred over {@link #findPort(BeanFactory)} whenever an
59+
* {@link ApplicationContext} is at hand: the factory-reflective variant
60+
* reports the <em>configured</em> port, which is {@code 0} when the server
61+
* was started on a random port ({@code server.port=0}). This variant asks
62+
* the running {@code WebServer} for its bound port, walking up the context
63+
* parent chain so classic child contexts resolve to their owning server
64+
* context; a management context is never in that chain and is therefore
65+
* never selected. When no bound port can be observed (no embedded server,
66+
* external deployment), discovery falls back to the legacy chain and a
67+
* non-positive resolution fails loudly instead of registering an unusable
68+
* address.
69+
*
70+
* @param applicationContext the application context the client is registering from
71+
* @return the positive port the owned web server bound
72+
* @throws ShenyuException when no usable port can be discovered
73+
*/
74+
public static int findPort(final ApplicationContext applicationContext) {
75+
final Integer bound = findBoundWebServerPort(applicationContext);
76+
if (Objects.nonNull(bound) && bound > 0) {
77+
return bound;
78+
}
79+
final int legacy = findPort(applicationContext.getAutowireCapableBeanFactory());
80+
if (legacy <= 0) {
81+
throw new ShenyuException("can not find port automatically: port discovery resolved the non-positive port "
82+
+ legacy + "; configure the advertised port explicitly, e.g. shenyu.client.http.props.port");
83+
}
84+
return legacy;
85+
}
86+
3687
/**
3788
* Note: springboot 1.x version has been made compatible.
3889
* Note: springmvc with external tomcat had been made compatible.
@@ -108,4 +159,48 @@ public static Integer getPort() throws Exception {
108159
throw new IllegalStateException("failed to get the HTTP port of the current tomcat");
109160
}
110161

162+
/**
163+
* Read the port the running web server bound from the application context
164+
* owning it, walking up the parent chain so classic child contexts resolve
165+
* to their owning server context. Both spring-boot types are resolved
166+
* reflectively because this module has no compile-time spring-boot
167+
* dependency.
168+
*
169+
* @param applicationContext starting context of the walk
170+
* @return the bound port, or {@code null} when it cannot be observed
171+
*/
172+
private static Integer findBoundWebServerPort(final ApplicationContext applicationContext) {
173+
final Class<?> webServerApplicationContextClass;
174+
try {
175+
webServerApplicationContextClass = Class.forName(WEB_SERVER_APPLICATION_CONTEXT_CLASS_NAME);
176+
} catch (ClassNotFoundException e) {
177+
//spring-boot web classes are not on the classpath: nothing to probe
178+
return null;
179+
}
180+
final Class<?> webServerClass;
181+
try {
182+
webServerClass = Class.forName(WEB_SERVER_CLASS_NAME);
183+
} catch (ClassNotFoundException e) {
184+
return null;
185+
}
186+
ApplicationContext current = applicationContext;
187+
int depth = 0;
188+
while (Objects.nonNull(current) && depth++ < MAX_CONTEXT_DEPTH) {
189+
if (webServerApplicationContextClass.isInstance(current)) {
190+
try {
191+
final Object webServer = webServerApplicationContextClass
192+
.getMethod("getWebServer").invoke(current);
193+
if (Objects.nonNull(webServer)) {
194+
return (Integer) webServerClass.getMethod("getPort").invoke(webServer);
195+
}
196+
} catch (ReflectiveOperationException ignored) {
197+
//fall through to legacy discovery in the caller
198+
return null;
199+
}
200+
}
201+
current = current.getParent();
202+
}
203+
return null;
204+
}
205+
111206
}
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.client.core.register;
19+
20+
import org.apache.shenyu.common.enums.RpcTypeEnum;
21+
import org.apache.shenyu.common.exception.ShenyuException;
22+
import org.apache.shenyu.register.common.config.ShenyuClientConfig;
23+
import org.junit.jupiter.api.Assertions;
24+
import org.junit.jupiter.api.Test;
25+
import org.mockito.Mockito;
26+
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
27+
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
28+
import org.springframework.boot.web.context.WebServerApplicationContext;
29+
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
30+
import org.springframework.boot.web.server.WebServer;
31+
import org.springframework.context.ApplicationContext;
32+
import org.springframework.core.env.Environment;
33+
34+
import java.util.Properties;
35+
36+
/**
37+
* Test for {@link ClientRegisterConfigImpl} port resolution (issue #8426).
38+
*/
39+
public class ClientRegisterConfigImplTest {
40+
41+
private static final int DISCOVERED_PORT = 27987;
42+
43+
@Test
44+
public void configuredPositivePortIsAuthoritative() {
45+
final ClientRegisterConfigImpl config = new ClientRegisterConfigImpl(
46+
clientConfig(props("port", "18443")), RpcTypeEnum.HTTP,
47+
Mockito.mock(ApplicationContext.class), Mockito.mock(Environment.class));
48+
Assertions.assertEquals(18443, config.getPort());
49+
}
50+
51+
@Test
52+
public void zeroConfiguredPortResolvesActuallyBoundServerPort() {
53+
//issue #8426: an explicitly configured 0 means random-port binding and
54+
//must not be registered verbatim; the bound port wins instead
55+
final ApplicationContext context = webServerContext(DISCOVERED_PORT);
56+
final ClientRegisterConfigImpl config = new ClientRegisterConfigImpl(
57+
clientConfig(props("port", "0")), RpcTypeEnum.HTTP, context, Mockito.mock(Environment.class));
58+
Assertions.assertEquals(DISCOVERED_PORT, config.getPort());
59+
}
60+
61+
@Test
62+
public void absentPortResolvesActuallyBoundServerPort() {
63+
final ApplicationContext context = webServerContext(DISCOVERED_PORT);
64+
final ClientRegisterConfigImpl config = new ClientRegisterConfigImpl(
65+
clientConfig(new Properties()), RpcTypeEnum.HTTP, context, Mockito.mock(Environment.class));
66+
Assertions.assertEquals(DISCOVERED_PORT, config.getPort());
67+
}
68+
69+
@Test
70+
public void zeroResolutionWithoutRunningServerFailsLoudly() {
71+
//a factory configured for a random port but no owned running server
72+
//(context is not a web-server context): registration must fail loudly
73+
//instead of silently resolving the non-positive configured value
74+
final ApplicationContext context = Mockito.mock(ApplicationContext.class);
75+
final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
76+
beanFactory.registerBeanDefinition("servletWebServerFactory", BeanDefinitionBuilder
77+
.rootBeanDefinition(TomcatServletWebServerFactory.class)
78+
.addConstructorArgValue(0)
79+
.getBeanDefinition());
80+
Mockito.when(context.getAutowireCapableBeanFactory()).thenReturn(beanFactory);
81+
final ClientRegisterConfigImpl config = new ClientRegisterConfigImpl(
82+
clientConfig(props("port", "0")), RpcTypeEnum.HTTP, context, Mockito.mock(Environment.class));
83+
Assertions.assertThrows(ShenyuException.class, config::getPort);
84+
}
85+
86+
private static ApplicationContext webServerContext(final int port) {
87+
final WebServer server = webServer(port);
88+
final WebServerApplicationContext context = Mockito.mock(WebServerApplicationContext.class);
89+
Mockito.when(context.getWebServer()).thenReturn(server);
90+
return context;
91+
}
92+
93+
private static WebServer webServer(final int port) {
94+
final WebServer webServer = Mockito.mock(WebServer.class);
95+
Mockito.when(webServer.getPort()).thenReturn(port);
96+
return webServer;
97+
}
98+
99+
private static Properties props(final String key, final String value) {
100+
final Properties properties = new Properties();
101+
properties.setProperty(key, value);
102+
return properties;
103+
}
104+
105+
private static ShenyuClientConfig clientConfig(final Properties props) {
106+
final ShenyuClientConfig config = new ShenyuClientConfig();
107+
final ShenyuClientConfig.ClientPropertiesConfig clientProperties = new ShenyuClientConfig.ClientPropertiesConfig();
108+
clientProperties.setProps(props);
109+
config.getClient().put(RpcTypeEnum.HTTP.getName(), clientProperties);
110+
return config;
111+
}
112+
}

‎shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/utils/PortUtilsTest.java‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,20 @@
1717

1818
package org.apache.shenyu.client.core.utils;
1919

20+
import org.apache.shenyu.common.exception.ShenyuException;
2021
import org.junit.jupiter.api.Assertions;
2122
import org.junit.jupiter.api.Test;
2223
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
2324
import org.springframework.beans.factory.support.GenericBeanDefinition;
25+
import org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactory;
2426
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
27+
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
28+
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
29+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
30+
import org.springframework.http.server.reactive.HttpHandler;
31+
import reactor.core.publisher.Mono;
32+
33+
import java.net.ServerSocket;
2534

2635
/**
2736
* Test for {@link PortUtils}.
@@ -39,4 +48,91 @@ public void testFindPort() {
3948
Assertions.assertEquals(8080, port);
4049
}
4150

51+
@Test
52+
public void testFindPortReportsActuallyBoundPort() {
53+
//issue #8426: with server.port=0 the configured value stays 0 while the
54+
//embedded server binds a random port; discovery must report the bound one
55+
final ServletWebServerApplicationContext context = new ServletWebServerApplicationContext();
56+
final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
57+
context.registerBean("servletWebServerFactory", TomcatServletWebServerFactory.class, () -> factory);
58+
try {
59+
context.refresh();
60+
final int bound = context.getWebServer().getPort();
61+
final int detected = PortUtils.findPort(context);
62+
Assertions.assertTrue(bound > 0);
63+
Assertions.assertEquals(bound, detected);
64+
} finally {
65+
context.close();
66+
}
67+
}
68+
69+
@Test
70+
public void testFindPortReturnsConfiguredPortOfRunningServer() throws Exception {
71+
final int staticPort;
72+
try (ServerSocket socket = new ServerSocket(0)) {
73+
staticPort = socket.getLocalPort();
74+
}
75+
final ServletWebServerApplicationContext context = new ServletWebServerApplicationContext();
76+
final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(staticPort);
77+
context.registerBean("servletWebServerFactory", TomcatServletWebServerFactory.class, () -> factory);
78+
try {
79+
context.refresh();
80+
Assertions.assertEquals(staticPort, PortUtils.findPort(context));
81+
} finally {
82+
context.close();
83+
}
84+
}
85+
86+
@Test
87+
public void testFindPortWalksToOwningServerContext() {
88+
final ServletWebServerApplicationContext root = new ServletWebServerApplicationContext();
89+
final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
90+
root.registerBean("servletWebServerFactory", TomcatServletWebServerFactory.class, () -> factory);
91+
try {
92+
root.refresh();
93+
final AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
94+
child.setParent(root);
95+
try {
96+
child.refresh();
97+
final int bound = root.getWebServer().getPort();
98+
Assertions.assertTrue(bound > 0);
99+
Assertions.assertEquals(bound, PortUtils.findPort(child));
100+
} finally {
101+
child.close();
102+
}
103+
} finally {
104+
root.close();
105+
}
106+
}
107+
108+
@Test
109+
public void testFindPortFromRunningReactiveServer() {
110+
final ReactiveWebServerApplicationContext context = new ReactiveWebServerApplicationContext();
111+
final TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0);
112+
context.registerBean("reactiveWebServerFactory", TomcatReactiveWebServerFactory.class, () -> factory);
113+
context.registerBean("httpHandler", HttpHandler.class, () -> (request, response) -> Mono.empty());
114+
try {
115+
context.refresh();
116+
final int bound = context.getWebServer().getPort();
117+
final int detected = PortUtils.findPort(context);
118+
Assertions.assertTrue(bound > 0);
119+
Assertions.assertEquals(bound, detected);
120+
} finally {
121+
context.close();
122+
}
123+
}
124+
125+
@Test
126+
public void testFindPortFailsLoudlyInsteadOfRegisteringZero() {
127+
//a factory configured for a random port but no running owned server
128+
//(context is not a web-server context): discovery must not silently
129+
//resolve the non-positive configured value (issue #8426 acceptance)
130+
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
131+
context.registerBean("servletWebServerFactory", TomcatServletWebServerFactory.class,
132+
() -> new TomcatServletWebServerFactory(0));
133+
context.refresh();
134+
Assertions.assertThrows(ShenyuException.class, () -> PortUtils.findPort(context));
135+
}
136+
}
137+
42138
}

‎shenyu-client/shenyu-client-http/shenyu-client-springmvc/src/main/java/org/apache/shenyu/client/springmvc/init/SpringMvcClientEventListener.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ protected ApiDocRegisterDTO.ApiExt customApiDocExt(final ApiDocRegisterDTO.ApiEx
384384
@Override
385385
public String getPort() {
386386
final int port = Integer.parseInt(Optional.ofNullable(super.getPort()).orElse("-1"));
387-
final int mergedPort = port <= 0 ? PortUtils.findPort(getContext().getAutowireCapableBeanFactory()) : port;
387+
final int mergedPort = port <= 0 ? PortUtils.findPort(getContext()) : port;
388388
return String.valueOf(mergedPort);
389389
}
390390
}

0 commit comments

Comments
 (0)