Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Fix Netty IO client threading issue (#2481)

Rich Turner6dc46ea0cc85
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
index 8a5d9c781..69a0a65c7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
@@ -233,12 +233,11 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
try {
// Inject OAuth header
- String authHeaderValue = client.getAuthHeader();
+ String authHeaderValue = client.getAuthHeader().get();
if (authHeaderValue != null) {
if (headers == null) {
headers = new MultivaluedHashMap<>();
}
- headers.remove(HttpHeaders.AUTHORIZATION);
headers.put(HttpHeaders.AUTHORIZATION, Collections.singletonList(authHeaderValue));
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
index bbd541b1c..2a91f8a22 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
@@ -45,6 +45,8 @@ import org.openremote.model.util.TextUtil;
import javax.net.ssl.SSLException;
import java.net.InetSocketAddress;
import java.net.URI;
+import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -160,11 +162,6 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T, InetSocketAdd
this.headers.forEach(hdrs::add);
}
- String authHeaderValue = getAuthHeader();
- if (authHeaderValue != null) {
- hdrs.set(HttpHeaderNames.AUTHORIZATION, authHeaderValue);
- }
-
handler = new WebSocketClientProtocolHandler(
WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, true, hdrs)) {
@@ -174,7 +171,7 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T, InetSocketAdd
super.userEventTriggered(ctx, evt);
if (evt instanceof WebSocketClientProtocolHandler.ClientHandshakeStateEvent handshakeStateEvent) {
if (handshakeStateEvent == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
- onHandshakeDone();
+ executorService.submit(WebsocketIOClient.this::onHandshakeDone);
}
}
}
@@ -268,6 +265,24 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T, InetSocketAdd
}
}
+ /**
+ * We need to get the auth header before we connect so we have it for the handshake
+ */
+ @Override
+ protected CompletableFuture<Void> doConnect() {
+ return getAuthHeader().thenCompose(authHeader -> {
+ // Push auth header into headers
+ if (authHeader != null) {
+ if (headers == null) {
+ headers = new HashMap<>(1);
+ }
+ headers.put(HttpHeaderNames.AUTHORIZATION.toString(), Collections.singletonList(authHeader));
+ }
+
+ return super.doConnect();
+ });
+ }
+
@Override
protected void doDisconnect() {
// Cancel ping task
@@ -278,24 +293,34 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T, InetSocketAdd
super.doDisconnect();
}
- public String getAuthHeader() throws Exception {
- String authHeaderValue = null;
+ /**
+ * Get the auth header asynchronously
+ */
+ public CompletableFuture<String> getAuthHeader() {
+ if (oAuthGrant == null) {
+ return CompletableFuture.completedFuture(null);
+ }
+
+ CompletableFuture<String> future = new CompletableFuture<>();
- if (oAuthGrant != null) {
- LOG.finest("Retrieving OAuth access token: " + getClientUri());
+ executorService.submit(() -> {
+ if (oAuthGrant != null) {
+ LOG.finest("Retrieving OAuth access token: " + getClientUri());
- try {
- OAuthFilter oAuthFilter = new OAuthFilter(getClient(), oAuthGrant);
- authHeaderValue = oAuthFilter.getAuthHeader();
- if (TextUtil.isNullOrEmpty(authHeaderValue)) {
- throw new RuntimeException("Returned access token is null");
+ try {
+ OAuthFilter oAuthFilter = new OAuthFilter(getClient(), oAuthGrant);
+ String authHeaderValue = oAuthFilter.getAuthHeader();
+ if (TextUtil.isNullOrEmpty(authHeaderValue)) {
+ throw new RuntimeException("Returned access token is null");
+ }
+ LOG.fine("Retrieved access token via OAuth: " + getClientUri());
+ future.complete(authHeaderValue);
+ } catch (Exception e) {
+ future.completeExceptionally(new Exception("Error retrieving OAuth access token for '" + getClientUri() + "': " + e.getMessage()));
}
- LOG.fine("Retrieved access token via OAuth: " + getClientUri());
- } catch (Exception e) {
- throw new Exception("Error retrieving OAuth access token for '" + getClientUri() + "': " + e.getMessage());
}
- }
+ });
- return authHeaderValue;
+ return future;
}
}
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
index 40f0ee7e0..5cd2eef3a 100644
--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
@@ -586,19 +586,19 @@ public class GatewayService extends RouteBuilder implements ContainerService {
GatewayConnector connector = gatewayConnectorMap.get(gatewayId);
if (connector == null || !realm.equals(connector.getRealm())) {
- String msg = "Failed to stop tunnel: reason=Gateway disconnected or doesn't exist, id=" + gatewayId;
+ String msg = "Failed to stop tunnel: reason=Gateway disconnected or doesn't exist, id=" + tunnelInfo.getGatewayId();
LOG.info(msg);
throw new IllegalStateException(msg);
}
if (!connector.isTunnellingSupported()) {
- String msg = "Failed to stop tunnel: reason=Not supported by gateway, id=" + gatewayId;
+ String msg = "Failed to stop tunnel: reason=Not supported by gateway, id=" + tunnelInfo.getGatewayId();
LOG.info(msg);
throw new IllegalArgumentException(msg);
}
if (!connector.isConnected()) {
- LOG.info("Just removing tunnel from list: reason=Not connected, id=" + gatewayId);
+ LOG.info("Just removing tunnel from list: reason=Not connected, id=" + tunnelInfo.getGatewayId());
tunnelInfos.remove(tunnelInfo.getId(), tunnelInfo);
return;
}
@@ -608,11 +608,11 @@ public class GatewayService extends RouteBuilder implements ContainerService {
try {
stopFuture.get(20, TimeUnit.SECONDS);
} catch (ExecutionException e) {
- String msg = "Failed to stop tunnel: An error occurred whilst waiting for the tunnel to be stopped: id=" + gatewayId;
+ String msg = "Failed to stop tunnel: An error occurred whilst waiting for the tunnel to be stopped: id=" + tunnelInfo.getGatewayId();
LOG.log(Level.WARNING, msg, e.getCause());
throw new RuntimeException(msg, e.getCause());
} catch (InterruptedException | TimeoutException e) {
- String msg = "Failed to stop tunnel: An error occurred whilst waiting for the tunnel to be stopped: id=" + gatewayId;
+ String msg = "Failed to stop tunnel: An error occurred whilst waiting for the tunnel to be stopped: id=" + tunnelInfo.getGatewayId();
LOG.warning(msg);
throw new RuntimeException(msg);
} finally {
diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
index e073017fb..687087ec4 100644
--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
@@ -131,7 +131,6 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
[new AbstractNettyIOClient.MessageToMessageDecoder<String>(String.class, gatewayClient)].toArray(new ChannelHandler[0])
})
-
and: "we add callback consumers to the client"
def connectionStatus = gatewayClient.getConnectionStatus()
List<String> clientReceivedMessages = []