when i use springcloud zuul, there is a large number of TCP CLOSE_WAIT status occurs,can anyone knows why its happens?
here is my zuul configuration
parent pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath />
</parent>
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
application.properties
server.port=8081
spring.application.name=zuul-server-test
eureka.instance.preferIpAddress=true
eureka.instance.instance-id=${spring.cloud.client.ipAddress}:${server.port}
eureka.instance.leaseRenewalIntervalInSeconds=5
eureka.instance.leaseExpirationDurationInSeconds=10
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8080/eureka/
zuul.add-host-header=true
zuul.sensitive-headers=
hystrix.command.default.execution.timeout.enable=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=60000
zuul.host.connect-timeout-millis=60000
zuul.host.socket-timeout-milllis=60000
ribbon.eureka.enabled=true
ribbon.ReadTimeout=60000
ribbon.ConnectTimeout=30000
ribbon.MaxAutoRetries=0
ribbon.MaxAutoRetriesNextServer=1
ribbon.OkToRetryOnAllOperations=false
ribbon.httpclient.enabled=false
ribbon.okhttp.enabled=true
zuul.routes.hello.path=/hello/**
zuul.routes.hello.sensitiveHeaders=
zuul.routes.hello.service-id=hello-server
java
#SpringBootApplication
#EnableDiscoveryClient
#EnableZuulProxy
public class DevcloudZuulApplication {
public static void main(String[] args) {
SpringApplication.run(DevcloudZuulApplication.class, args);
}
}
when i visit http://localhost:8081/hello/index.html, tcp links created, port 8082 is the hello-server
tcp 0 0 ::ffff:192.168.120.20:8082 ::ffff:192.168.120.20:21505 ESTABLISHED 47968/java
tcp 0 0 ::ffff:192.168.120.20:21505 ::ffff:192.168.120.20:8082 ESTABLISHED 132689/java
tcp 0 0 ::ffff:192.168.120.20:8082 ::ffff:192.168.120.20:21510 ESTABLISHED 47968/java
tcp 0 0 ::ffff:192.168.120.20:21510 ::ffff:192.168.120.20:8082 ESTABLISHED 132689/java
tcp 0 0 ::ffff:192.168.120.20:8082 ::ffff:192.168.120.20:21504 ESTABLISHED 47968/java
tcp 0 0 ::ffff:192.168.120.20:21504 ::ffff:192.168.120.20:8082 ESTABLISHED 132689/java
then it changes
tcp 0 0 ::ffff:192.168.120.20:8082 ::ffff:192.168.120.20:21505 FIN_WAIT2 -
tcp 1 0 ::ffff:192.168.120.20:21505 ::ffff:192.168.120.20:8082 CLOSE_WAIT 132689/java
tcp 0 0 ::ffff:192.168.120.20:8082 ::ffff:192.168.120.20:21510 FIN_WAIT2 -
tcp 0 0 ::ffff:192.168.120.20:21510 ::ffff:192.168.120.20:8082 CLOSE_WAIT 132689/java
tcp 0 0 ::ffff:192.168.120.20:8082 ::ffff:192.168.120.20:21504 FIN_WAIT2 -
tcp 1 0 ::ffff:192.168.120.20:21504 ::ffff:192.168.120.20:8082 CLOSE_WAIT 132689/java
at last,
tcp 1 0 ::ffff:192.168.120.20:21505 ::ffff:192.168.120.20:8082 CLOSE_WAIT 132689/java
tcp 1 0 ::ffff:192.168.120.20:21504 ::ffff:192.168.120.20:8082 CLOSE_WAIT 132689/java
tcp 1 0 ::ffff:192.168.120.20:21510 ::ffff:192.168.120.20:8082 CLOSE_WAIT 132689/java
and this status will continue through hours.
CLOSE_WAIT described here: TCP connection status
This endpoint has received a close request from the remote endpoint and this TCP is now waiting for a connection termination request from the local application.
Ribbon uses a connection pool to send request to upstream. Every time, it releases connection instead of close it to avoid overhead of establishing new connection.
The connections in pool has alive time by configuring ribbon.PoolKeepAliveTime which default value is 15 * 60 seconds.
public class DefaultClientConfigImpl implements IClientConfig {
public static final long DEFAULT_POOL_KEEP_ALIVE_TIME = 15 * 60L;
public static final TimeUnit DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS = TimeUnit.SECONDS;
}
public class OkHttpRibbonConfiguration {
#Value("${ribbon.client.name}")
private String name = "client";
#Configuration
protected static class OkHttpClientConfiguration {
private OkHttpClient httpClient;
#Bean
#ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(IClientConfig config, OkHttpClientConnectionPoolFactory connectionPoolFactory) {
Integer maxTotalConnections = config.getPropertyAsInteger(
CommonClientConfigKey.MaxTotalConnections,
DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS);
Object timeToLiveObj = config
.getProperty(CommonClientConfigKey.PoolKeepAliveTime);
Long timeToLive = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME;
Object ttlUnitObj = config
.getProperty(CommonClientConfigKey.PoolKeepAliveTimeUnits);
TimeUnit ttlUnit = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS;
if (timeToLiveObj instanceof Long) {
timeToLive = (Long) timeToLiveObj;
}
if (ttlUnitObj instanceof TimeUnit) {
ttlUnit = (TimeUnit) ttlUnitObj;
}
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
}
}
Related
I want so send a message to the localhost on port number 80 but I was able to open a connection What did i do wrong and how can I fix it?
Here is the code to connect to the localhost server
class client:NSObject {
var inputstream = InputStream!
var outputstream = OutputStream!
func setupNetworkCom() {
var readstream = Unmanaged<CFReadStream>?
var writestream = Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, "localhost" as CFString, 80, &readstream, &writestream)
inputstream = readstream!.takeRetainedValue()
outputstream = writestream!.takeReatainedValue()
inputstream.schedule(in: .current, forMode: .common)
outputstream.schedule(in: .current, forMode: .common)
inputstream.open()
outputstream.open()
}
}
It gives me this error
2020-02-25 17:32:49.388120+0530 Test[3800:171412] dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
2020-02-25 17:32:50.389186+0530 Test[3800:171412] dnssd_clientstub ConnectToServer: connect()-> No of tries: 2
2020-02-25 17:32:51.389589+0530 Test[3800:171412] dnssd_clientstub ConnectToServer: connect()-> No of tries: 3
2020-02-25 17:32:52.392031+0530 Test[3800:171412] dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:5 Err:-1 Errno:1 Operation not permitted
2020-02-25 17:32:52.392319+0530 Test[3800:171412] [] nw_resolver_create_dns_service_locked DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2020-02-25 17:32:52.392724+0530 Test[3800:171411] [] nw_connection_get_connected_socket 1 Connection has no connected handler
2020-02-25 17:32:52.392754+0530 Test[3800:171411] TCP Conn 0x600000163a80 Failed : error 0:-65563 [-65563]
I downloaded the server from this tutorial https://www.raywenderlich.com/3437391-real-time-communication-with-streams-tutorial-for-ios#toc-anchor-010
This question and your Other question have the same answer you're missing the entitlement in the capabilities tab.
click on your project settings and go to capabilities there you'll see the app sandbox. make sure it's turned on and then enable incoming connections and outgoing connections.
I have a Spring Authorization/Resource server managing the authorization of a Webflux Oauth2 client. On it's own this is working OK. When I add Spring Cloud Gateway and access the Webflux via the Gateway I see that the Authorization Server validates the user and the Webflux returns 302, but on the Gateway I get 400 "Invalid client registration id".
The Authorization/Resource server is;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
The starter;
#SpringBootApplication
#EnableAuthorizationServer
#EnableResourceServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Properties;
server:
port: 8889
Server configuration;
#Configuration
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private BCryptPasswordEncoder passwordEncoder;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore());
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("myClientId2")
.secret(passwordEncoder.encode("mySecret2"))
.authorizedGrantTypes("authorization_code")
.scopes("all")
.autoApprove(true)
.redirectUris("http://localhost:8083/login/oauth2/code/myAppTwo")
.and()
.withClient("myGatewayId")
.secret(passwordEncoder.encode("myGatewaySecret"))
.authorizedGrantTypes("authorization_code")
.scopes("all")
.autoApprove(true)
.redirectUris("http://localhost:8888/login/oauth2/code/gateway")
;
}
}
Security;
#Configuration
#Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and().authorizeRequests().anyRequest().authenticated()
.and().formLogin().permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("x").password(passwordEncoder().encode("123"))
.roles("USER");
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
User response;
#RestController
public class UserController {
#GetMapping("/user")
public Principal user(Principal principal) {
System.err.println(principal);
return principal;
}
The Webflux is;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
</dependencies>
Properties;
server:
port: 8083
spring:
security:
oauth2:
client:
registration:
myAppTwo:
client-name: Test8082
client-id: myClientId2
client-secret: mySecret2
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
myAppTwo:
authorization-uri: http://localhost:8889/oauth/authorize
token-uri: http://localhost:8889/oauth/token
user-info-uri: http://localhost:8889/user
user-name-attribute: name
Webflux end point;
#RestController
public class Controller {
#GetMapping(value = "/test3")
Mono<OAuth2User> getTest3(#AuthenticationPrincipal Mono<OAuth2User> ouser) {
System.err.println("o =" + ouser);
return ouser;
}
}
Running http://localhost:8083/test3 via Chrome take me to the log-in page on the Authorization server, after which I enter the credentials and then then URL above returns the expected Response.
When I add a Gateway;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
With properties;
server:
port: 8888
spring:
autoconfigure:
# TODO: remove when fixed https://github.com/spring-projects/spring-security/issues/17949
# Without this line, Gateway tries to log in using it's own security, rather than deferring to OAuth2
exclude: org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration
cloud:
gateway:
routes:
- id: oauth
predicates:
- Path=/oauth2/**
uri: http://localhost:8889
filters:
- TokenRelay=
- RemoveRequestHeader=Cookie
- id: route2
predicates:
- Path=/2/**
uri: http://localhost:8083
filters:
- RewritePath=/2/(?<myPath>.*), /$\{myPath}
- TokenRelay=
- RemoveRequestHeader=Cookie
security:
oauth2:
client:
registration:
gateway:
client-id: myGatewayId
client-secret: myGatewaySecret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider: gateway
provider:
gateway:
authorization-uri: http://localhost:8889/oauth/authorize
token-uri: http://localhost:8889/oauth/token
user-info-uri: http://localhost:8889/user
user-name-attribute: name
jwk-set-uri: http://localhost:8889/oauth/token_key
Now if I try http://localhost:8888/2/test3 I am still re-directed to the log-in. The toString on the Authorization server logs the credentials, the Webflux still gives 302, but the Gateway does the following;
Route matched: route2
Mapping [Exchange: GET http://localhost:8888/2/test3] to Route{id='route2', uri=http://localhost:8083, order=0, predicate=Paths: [/2/**], match trailing slash: true, gatewayFilters=[[[RewritePath /2/(?<myPath>.*) = '/${myPath}'], order = 1], [org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$666/1724736027#4b96b22, order = 2], [[RemoveRequestHeader name = 'Cookie'], order = 3]]}
[98bb6dad] Mapped to org.springframework.cloud.gateway.handler.FilteringWebHandler#6fa90b79
Sorted gatewayFilterFactories: [[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter#1894593a}, order = -2147483648], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter#b835727}, order = -2147482648], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyWriteResponseFilter#7fd26ad8}, order = -1], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardPathFilter#7cea0110}, order = 0], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.GatewayMetricsFilter#5527b211}, order = 0], [[RewritePath /2/(?<myPath>.*) = '/${myPath}'], order = 1], [org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$666/1724736027#4b96b22, order = 2], [[RemoveRequestHeader name = 'Cookie'], order = 3], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter#14b0e127}, order = 10000], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.config.GatewayNoLoadBalancerClientAutoConfiguration$NoLoadBalancerClientFilter#54cf7c6a}, order = 10100], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.WebsocketRoutingFilter#468dda3e}, order = 2147483646], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyRoutingFilter#3d37203b}, order = 2147483647], [GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardRoutingFilter#10823d72}, order = 2147483647]]
"GET /2/test3 HTTP/1.1" 302 0 8888 8 ms
Resolved [ResponseStatusException: 400 BAD_REQUEST "Invalid client registration id"] for HTTP GET /oauth2/authorization/myAppTwo
Writing "<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you (truncated)...
"GET /oauth2/authorization/myAppTwo HTTP/1.1" 400 312 8888 2 ms
"GET /favicon.ico HTTP/1.1" 302 0 8888 2 ms
"GET /oauth2/authorization/gateway HTTP/1.1" 302 0 8888 2 ms
Writing form fields [grant_type, code, redirect_uri] (content masked)
Decoded [{access_token=2c14f1e7-5d95-4fed-be95-2d8518d1fb48, token_type=bearer, expires_in=40912, scope=all}]
Decoded [{authorities=[{authority=ROLE_USER}], details={remoteAddress=127.0.0.1, sessionId=null, tokenValue=2 (truncated)...]
"GET /login/oauth2/code/gateway?code=fGdiyz&state=ZynriL0UtU37b4rMfDHM7JheNYYo0UnZQvgu4U2kWwQ%3D HTTP/1.1" 302 0 8888 82 ms
"GET / HTTP/1.1" 200 3348 8888 5 ms
Via the same browser session, if I try the direct URL http://localhost:8083/test, it response correctly (i.e. I am logged in and 8083 has my credentials).
I see via debug that DefaultServerOAuth2AuthorizationRequestResolver.findByRegistrationId first checks the redirect for gateway and passes. However, it tries and fails on a second pass for the redirect of myAppTwo, which was not defined the Gateway's YML and I assume shouldn't be. Removing the route oauth seems to have no affect. I never see that route being hit.
So how do I get the Gateway to redirect to myAppTwo on port 8083?
Update When I use KeyCloak instead of my own AuthorizationServer/ResourceServer I get the same issue.
I'm no more able to connect to api.softlayer.com
I'm calling the rest API from a WebSphere application portal 8.5 (java7) using Apache (HTTP-client-4.5.3.jar)
The coding is
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
The error is
17:44:00.997 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection request: [route: {s}->https://api.softlayer.com:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
17:44:01.044 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {s}->https://api.softlayer.com:443][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
17:44:01.044 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Opening connection {s}->https://api.softlayer.com:443
17:44:01.060 [main] DEBUG o.a.h.i.c.DefaultHttpClientConnectionOperator - Connecting to api.softlayer.com/66.228.119.120:443
17:44:01.060 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Connecting socket to api.softlayer.com/66.228.119.120:443 with timeout 0
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Enabled protocols: [TLSv1]
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Enabled cipher suites:[TLS_EMPTY_RENEGOTIATION_INFO_SCSV, SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_RSA_WITH_AES_128_CBC_SHA256, SSL_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ECDH_RSA_WITH_AES_128_CBC_SHA256, SSL_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_AES_128_CBC_SHA, SSL_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ECDH_RSA_WITH_RC4_128_SHA, SSL_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_MD5]
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Starting handshake
17:44:01.747 [main] DEBUG o.a.h.i.c.DefaultManagedHttpClientConnection - http-outgoing-0: Shutdown connection
17:44:01.747 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Connection discarded
17:44:01.747 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {s}->https://api.softlayer.com:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
17:44:01.747 [main] INFO o.a.http.impl.execchain.RetryExec - I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.softlayer.com:443: Connection reset
17:44:01.747 [main] DEBUG o.a.http.impl.execchain.RetryExec - Connection reset
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:207) ~[na:1.7.0]
at java.net.SocketInputStream.read(SocketInputStream.java:133) ~[na:1.7.0]
at com.ibm.jsse2.a.a(a.java:110) ~[na:7.0 build_20131216]
at com.ibm.jsse2.a.a(a.java:141) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.a(qc.java:691) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.h(qc.java:266) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.a(qc.java:770) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.startHandshake(qc.java:476) ~[na:7.0 build_20131216]
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:396) ~[httpclient-4.5.3.jar:4.5.3]
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:355) ~[httpclient-4.5.3.jar:4.5.3]
The solution is to enable the enable TLSv1.2
import javax.net.ssl.SSLContext;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
public class HttpClientFactory {
private static CloseableHttpClient client;
public static HttpClient getHttpsClient() throws Exception {
if (client != null) {
return client;
}
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2"}, null, new NoopHostnameVerifier());
client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return client;
}
}
Softlayer's servers only accept TLSv1.2 connections you must make sure that your code is only performing connections with that protocol which it seems your code is not doing
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -
Enabled protocols: [TLSv1]
I'm trying to create a Spring cloud microservice application using Zuul and Consul.
I have 2 components in my project:
api-gateway microservice using Zuul
Hello world microservice (a simple hello world Rest Webservice)
Here is the code of The api-gateway:
#SpringBootApplication
#EnableZuulProxy
#EnableDiscoveryClient
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
The pom.xml
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.M3</version>
</parent>
<properties>
<java.version>1.8</java.version>
<spring.cloud.consul.version>1.0.0.BUILD-SNAPSHOT</spring.cloud.consul.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<!-- Setup Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<!-- Setup Spring MVC & REST, use Embedded Tomcat -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<!-- Spring Cloud starter -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
<version>${spring.cloud.consul.version}</version>
</dependency>
</dependencies>
application.yml
zuul:
routes:
hello1:
path: /hello1/**
serviceId: microservice-example
logging:
level:
org.springframework: INFO
com.netflix: DEBUG
bootstrap.yml
spring:
application:
name: edge-server
cloud:
consul:
config:
enabled: true
host: localhost
port: 8500
Here is the code of hello microservice:
#SpringBootApplication
#EnableConfigServer
#EnableDiscoveryClient
#RestController
public class Application {
#RequestMapping(value="/hello1",method = RequestMethod.GET)
public String hello() {
System.out.print("hello1");
return "Hello1";
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
bootstrap.yml:
spring:
application:
name: microservice-example
profiles:
active: native
cloud:
consul:
config:
enabled: true
host: localhost
port: 8500
But, when I test my service the browser shows this message:
Here is the stacktrace of edge-server application:
2015-11-25 16:49:31.780 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Path = null
2015-11-25 16:49:31.781 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Transfer-Encoding = null
2015-11-25 16:49:31.781 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Content-Encoding = null
2015-11-25 16:49:31.781 DEBUG 9876 --- [nio-8080-exec-7] c.n.zuul.http.HttpServletRequestWrapper : Content-Length header = -1
2015-11-25 16:49:31.782 DEBUG 9876 --- [nio-8080-exec-7] c.n.loadbalancer.ZoneAwareLoadBalancer : Zone aware logic disabled or there is only one zone
2015-11-25 16:49:31.782 DEBUG 9876 --- [nio-8080-exec-7] c.n.loadbalancer.LoadBalancerContext : microservice-example using LB returned Server: FR09248851D:1234 for request
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.niws.client.http.RestClient : RestClient sending new Request(GET: ) http://FR09248851D:1234
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] c.n.http4.MonitoredConnectionManager : Get connection: {}->http://FR09248851D:1234, timeout = 2000
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : [{}->http://FR09248851D:1234] total kept alive: 1, total issued: 0, total allocated: 1 out of 200
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Getting free connection [{}->http://FR09248851D:1234][null]
2015-11-25 16:49:31.783 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NFHttpClient : Stale connection check
2015-11-25 16:49:31.784 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NFHttpClient : Attempt 1 to execute request
2015-11-25 16:49:31.791 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NFHttpClient : Connection can be kept alive indefinitely
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] c.n.http4.MonitoredConnectionManager : Released connection is reusable.
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Releasing connection [{}->http://FR09248851D:1234][null]
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Pooling connection [{}->http://FR09248851D:1234][null]; keep alive indefinitely
2015-11-25 16:49:31.796 DEBUG 9876 --- [nio-8080-exec-7] com.netflix.http4.NamedConnectionPool : Notifying no-one, there are no waiting threads
2015-11-25 16:49:35.721 DEBUG 9876 --- [service-example] c.netflix.loadbalancer.BaseLoadBalancer : LoadBalancer: PingTask executing [1] servers configured
2015-11-25 16:49:35.885 DEBUG 9876 --- [clean up thread] com.netflix.http4.ConnectionPoolCleaner : Connection pool clean up started for client microservice-example
2015-11-25 16:49:35.885 DEBUG 9876 --- [clean up thread] c.n.http4.MonitoredConnectionManager : Closing expired connections
I want to send a request over TCP transport to a proxy service, when use this code to send my soap xml
Socket clientSocket = new Socket("host", port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("soap xml instance");
clientSocket.close();
it works fine and my business is continues.
But when i send two xml without closing the socket like this:
Socket clientSocket = new Socket("host", port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("soap xml instance");
outToServer.writeBytes("another soap instance");
clientSocket.close();
it always throws this exception:
TID: [0] [ESB] [2013-06-28 13:36:10,838] ERROR
{org.apache.axis2.transport.tcp.TCPWorker} - Error while processing
TCP request through the Axis2 engine
{org.apache.axis2.transport.tcp.TCPWorker}
org.apache.axiom.om.OMException:
com.ctc.wstx.exc.WstxParsingException: Illegal processing instruction
target ("xml"); xml (case insensitive) is reserved by the specs. at
[row,col {unknown-source}]: [2,5]
at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:296)
at org.apache.axiom.om.impl.llom.OMDocumentImpl.buildNext(OMDocumentImpl.java:135)
at org.apache.axiom.om.impl.llom.OMNodeImpl.getNextOMSibling(OMNodeImpl.java:122)
at org.apache.axiom.om.impl.llom.OMElementImpl.getNextOMSibling(OMElementImpl.java:343)
at org.apache.axiom.om.impl.traverse.OMChildrenIterator.getNextNode(OMChildrenIterator.java:36)
at org.apache.axiom.om.impl.traverse.OMAbstractIterator.hasNext(OMAbstractIterator.java:58)
at org.jaxen.util.DescendantAxisIterator.hasNext(DescendantAxisIterator.java:101)
at org.jaxen.expr.DefaultStep.evaluate(DefaultStep.java:152)
at org.jaxen.expr.DefaultLocationPath.evaluate(DefaultLocationPath.java:140)
at org.jaxen.expr.DefaultAbsoluteLocationPath.evaluate(DefaultAbsoluteLocationPath.java:113)
at org.jaxen.expr.DefaultXPathExpr.asList(DefaultXPathExpr.java:102)
at org.jaxen.BaseXPath.selectNodesForContext(BaseXPath.java:674)
at org.jaxen.BaseXPath.selectNodes(BaseXPath.java:213)
at org.jaxen.BaseXPath.evaluate(BaseXPath.java:172)
at org.apache.synapse.util.xpath.SynapseXPath.stringValueOf(SynapseXPath.java:297)
at org.apache.synapse.mediators.builtin.PropertyMediator.getResultValue(PropertyMediator.java:299)
at org.apache.synapse.mediators.builtin.PropertyMediator.mediate(PropertyMediator.java:95)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:71)
at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:114)
at org.apache.synapse.core.axis2.ProxyServiceMessageReceiver.receive(ProxyServiceMessageReceiver.java:154)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
at org.apache.axis2.transport.tcp.TCPWorker.run(TCPWorker.java:68)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662) Caused by: com.ctc.wstx.exc.WstxParsingException: Illegal processing instruction
target ("xml"); xml (case insensitive) is reserved by the specs. at
[row,col {unknown-source}]: [2,5]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:606)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:479)
at com.ctc.wstx.sr.BasicStreamReader.readPIPrimary(BasicStreamReader.java:3903)
at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2037)
at com.ctc.wstx.sr.BasicStreamReader.closeContentTree(BasicStreamReader.java:2886)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2629)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1062)
at org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.next(XMLStreamReaderWrapper.java:225)
at org.apache.axiom.util.stax.dialect.DisallowDoctypeDeclStreamReaderWrapper.next(DisallowDoctypeDeclStreamReaderWrapper.java:34)
at org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.next(XMLStreamReaderWrapper.java:225)
at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:681)
at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214)
... 25 more
I used appending '\n', "\r\n" to my message but non of them make that work.
Also i tried that used the method that explined in this link.How to Send SOAP Messages Using TCP Transport and it worked fine.
But i could not use that kind of api in my project. How can i get rid of this problem.
I was able to send TCP messages to ESB using a sample client but you have to make sure you send an XML element.
First make sure you have enabled transport reciver for tcp in axis2.xml (repository/conf/axis2/axis2.xml)
<transportReceiver name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportListener" >
========================My Proxy Service which recives TCP messages ===========
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="TCPProxy"
transports="https,http"
statistics="disable"
trace="disable"
startOnLoad="true">
<target>
<inSequence>
<log level="full"/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
<parameter name="transport.tcp.port">6789</parameter>
<parameter name="transport.tcp.contentType">application/xml</parameter>
<description/>
</proxy>
==Client that send messages to TCP server ====
import java.io.*;
import java.net.*;
class TCPClient {
String host = "localhost";
int port = 6789;
Socket socket = null;
public static void main(String args[]) throws Exception{
String name ="Amani";
TCPClient client = new TCPClient();
String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
"<soapenv:Header/>\n" +
"<soapenv:Body>\n" +
" <p:greet xmlns:p=\"http://greet.service.amani.org\">\n" +
" <in>" + name + "</in>\n" +
" </p:greet>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>";
client.SendToServer("<test></test>");
client.close();
}
TCPClient(String _host, int _port) throws Exception{
host = _host;
port = _port;
socket = new Socket(host, port);
}
TCPClient() throws Exception{
socket = new Socket(host, port);
}
void SendToServer(String msg) throws Exception{
//create output stream attached to socket
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//send msg to server
outToServer.print(msg + '\n');
outToServer.flush();
}
String RecieveFromServer() throws Exception{
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
//read line from server
String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
return res;
}
void close() throws IOException{
socket.close();
}
}