use of software.amazon.awssdk.crt.io.SocketOptions in project aws-iot-device-sdk-java-v2 by aws.
the class EchoTestServiceRunner method runLocalEchoTestServerClientLoopUnixDomain.
/**
* Enables a bit of a performance/load test by reconnecting the client to the same running server multiple times
* and each time the client connects, it runs the test logic for the number of times.
*
* !!! WARNING SocketOptions.SocketDomain is LOCAL for this server. Test client must match
*/
public static void runLocalEchoTestServerClientLoopUnixDomain(final String domainSocket, final BiConsumer<EventStreamRPCConnection, EchoTestRPC> testClientLogic, int nCount) throws Exception {
final int port = randomPort();
Files.deleteIfExists(Paths.get(domainSocket));
try (final EventLoopGroup elGroup = new EventLoopGroup(1);
final EchoTestServiceRunner runner = new EchoTestServiceRunner(elGroup, SocketOptions.SocketDomain.LOCAL, domainSocket, port);
final SocketOptions socketOptions = new SocketOptions();
final HostResolver hostResolver = new HostResolver(elGroup, 64);
final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver)) {
socketOptions.connectTimeoutMs = 3000;
socketOptions.domain = SocketOptions.SocketDomain.LOCAL;
socketOptions.type = SocketOptions.SocketType.STREAM;
runner.runService();
for (int i = 0; i < nCount; ++i) {
final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, domainSocket, port, () -> TestAuthNZHandlers.getClientAuth("accepted.foo"));
try (EventStreamRPCConnection connection = new EventStreamRPCConnection(config)) {
final CompletableFuture<Void> connectFuture = new CompletableFuture<>();
// only completes exceptionally if there's an error
final CompletableFuture<Void> clientErrorFuture = new CompletableFuture<>();
connection.connect(new EventStreamRPCConnection.LifecycleHandler() {
@Override
public void onConnect() {
connectFuture.complete(null);
}
@Override
public void onDisconnect(int errorCode) {
if (!connectFuture.isDone()) {
connectFuture.completeExceptionally(new RuntimeException("Client initial connection failed due to: " + CRT.awsErrorName(errorCode)));
} else if (errorCode != CRT.AWS_CRT_SUCCESS) {
clientErrorFuture.completeExceptionally(new RuntimeException("Client disconnected due to: " + CRT.awsErrorName(errorCode)));
} else {
}
// don't care if it normal closure/disconnect
}
@Override
public boolean onError(Throwable t) {
if (!connectFuture.isDone()) {
connectFuture.completeExceptionally(t);
} else {
clientErrorFuture.completeExceptionally(t);
}
return false;
}
});
// wait for connection to move forward
connectFuture.get(30, TimeUnit.SECONDS);
final EchoTestRPC client = new EchoTestRPCClient(connection);
final CompletableFuture<Object> runClientOrError = CompletableFuture.anyOf(clientErrorFuture, CompletableFuture.runAsync(() -> testClientLogic.accept(connection, client), Executors.newSingleThreadExecutor()));
runClientOrError.get(240, TimeUnit.SECONDS);
}
}
}
// given this method is rather explicitly meant to be used in JUnit tests and intends to check per iteration
// calling waitForNoResources() is necessary to call here, and appropriate
CrtResource.waitForNoResources();
}
use of software.amazon.awssdk.crt.io.SocketOptions in project aws-iot-greengrass-edge-connector-for-kinesis-video-stream by awslabs.
the class IPCUtils method connectToGGCOverEventStreamIPC.
private static EventStreamRPCConnection connectToGGCOverEventStreamIPC(String authToken, String ipcServerSocketPath) throws ExecutionException, InterruptedException {
try (EventLoopGroup elGroup = new EventLoopGroup(1);
ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, null)) {
SocketOptions socketOptions = getSocketOptionsForIPC();
final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, ipcServerSocketPath, DEFAULT_PORT_NUMBER, GreengrassConnectMessageSupplier.connectMessageSupplier(authToken));
final CompletableFuture<Void> connected = new CompletableFuture<>();
final EventStreamRPCConnection connection = getConnectionInstance(config);
final boolean[] disconnected = { false };
final int[] disconnectedCode = { -1 };
connection.connect(new EventStreamRPCConnection.LifecycleHandler() {
@Override
public void onConnect() {
connected.complete(null);
}
@Override
public void onDisconnect(int errorCode) {
disconnected[0] = true;
disconnectedCode[0] = errorCode;
clientConnection = null;
}
@Override
public boolean onError(Throwable t) {
connected.completeExceptionally(t);
clientConnection = null;
return true;
}
});
// waits for future to complete
connected.get();
return connection;
}
}
use of software.amazon.awssdk.crt.io.SocketOptions in project aws-crt-java by awslabs.
the class ServerListenerTest method testSetupAndTearDown.
@Test
public void testSetupAndTearDown() throws ExecutionException, InterruptedException, TimeoutException {
SocketOptions socketOptions = new SocketOptions();
socketOptions.connectTimeoutMs = 3000;
socketOptions.domain = SocketOptions.SocketDomain.IPv4;
socketOptions.type = SocketOptions.SocketType.STREAM;
EventLoopGroup elGroup = new EventLoopGroup(1);
ServerBootstrap bootstrap = new ServerBootstrap(elGroup);
ServerListener listener = new ServerListener("127.0.0.1", (short) 8038, socketOptions, null, bootstrap, new ServerListenerHandler() {
public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
return null;
}
public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
}
});
listener.close();
listener.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
bootstrap.close();
elGroup.close();
elGroup.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
socketOptions.close();
}
use of software.amazon.awssdk.crt.io.SocketOptions in project aws-crt-java by awslabs.
the class ServerListenerTest method testContinuationMessageHandling.
@Test
public void testContinuationMessageHandling() throws ExecutionException, InterruptedException, IOException, TimeoutException {
SocketOptions socketOptions = new SocketOptions();
socketOptions.connectTimeoutMs = 3000;
socketOptions.domain = SocketOptions.SocketDomain.IPv4;
socketOptions.type = SocketOptions.SocketType.STREAM;
EventLoopGroup elGroup = new EventLoopGroup(1);
ServerBootstrap bootstrap = new ServerBootstrap(elGroup);
final boolean[] connectionReceived = { false };
final boolean[] connectionShutdown = { false };
final boolean[] continuationClosed = { false };
final String[] receivedOperationName = new String[] { null };
final String[] receivedContinuationPayload = new String[] { null };
final ServerConnection[] serverConnections = { null };
final Lock lock = new ReentrantLock();
final Condition testSynchronizationCVar = lock.newCondition();
ServerListener listener = new ServerListener("127.0.0.1", (short) 8042, socketOptions, null, bootstrap, new ServerListenerHandler() {
public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
lock.lock();
serverConnections[0] = serverConnection;
connectionReceived[0] = true;
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(serverConnection) {
@Override
protected void onProtocolMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
int responseMessageFlag = MessageFlags.ConnectionAccepted.getByteValue();
MessageType acceptResponseType = MessageType.ConnectAck;
connection.sendProtocolMessage(null, null, acceptResponseType, responseMessageFlag).whenComplete((res, err) -> {
lock.lock();
testSynchronizationCVar.signal();
lock.unlock();
});
}
@Override
protected ServerConnectionContinuationHandler onIncomingStream(ServerConnectionContinuation continuation, String operationName) {
lock.lock();
receivedOperationName[0] = operationName;
lock.unlock();
return new ServerConnectionContinuationHandler(continuation) {
@Override
protected void onContinuationClosed() {
lock.lock();
continuationClosed[0] = true;
testSynchronizationCVar.signal();
lock.unlock();
this.close();
}
@Override
protected void onContinuationMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
lock.lock();
receivedContinuationPayload[0] = new String(payload, StandardCharsets.UTF_8);
lock.unlock();
String responsePayload = "{ \"message\": \"this is a response message\" }";
continuation.sendMessage(null, responsePayload.getBytes(StandardCharsets.UTF_8), MessageType.ApplicationMessage, MessageFlags.TerminateStream.getByteValue()).whenComplete((res, ex) -> {
connection.closeConnection(0);
});
}
};
}
};
testSynchronizationCVar.signal();
lock.unlock();
return connectionHandler;
}
public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
connectionShutdown[0] = true;
}
});
Socket clientSocket = new Socket();
SocketAddress address = new InetSocketAddress("127.0.0.1", 8042);
lock.lock();
clientSocket.connect(address, 3000);
testSynchronizationCVar.await(1, TimeUnit.SECONDS);
assertNotNull(serverConnections[0]);
assertTrue(connectionReceived[0]);
Header messageType = Header.createHeader(":message-type", (int) MessageType.Connect.getEnumValue());
Header messageFlags = Header.createHeader(":message-flags", 0);
Header streamId = Header.createHeader(":stream-id", 0);
List<Header> messageHeaders = new ArrayList<>(3);
messageHeaders.add(messageType);
messageHeaders.add(messageFlags);
messageHeaders.add(streamId);
Message connectMessage = new Message(messageHeaders, null);
ByteBuffer connectMessageBuf = connectMessage.getMessageBuffer();
byte[] toSend = new byte[connectMessageBuf.remaining()];
connectMessageBuf.get(toSend);
clientSocket.getOutputStream().write(toSend);
connectMessage.close();
testSynchronizationCVar.await(1, TimeUnit.SECONDS);
String operationName = "testOperation";
messageHeaders = new ArrayList<>(3);
messageHeaders.add(Header.createHeader(":message-type", (int) MessageType.ApplicationMessage.getEnumValue()));
messageHeaders.add(Header.createHeader(":message-flags", 0));
messageHeaders.add(Header.createHeader(":stream-id", 1));
messageHeaders.add(Header.createHeader("operation", operationName));
String payload = "{\"message\": \"message payload\"}";
Message continuationMessage = new Message(messageHeaders, payload.getBytes(StandardCharsets.UTF_8));
ByteBuffer continuationMessageBuf = continuationMessage.getMessageBuffer();
toSend = new byte[continuationMessageBuf.remaining()];
continuationMessageBuf.get(toSend);
clientSocket.getOutputStream().write(toSend);
continuationMessage.close();
testSynchronizationCVar.await(1, TimeUnit.SECONDS);
lock.unlock();
clientSocket.close();
serverConnections[0].getClosedFuture().get(1, TimeUnit.SECONDS);
assertTrue(connectionShutdown[0]);
assertNotNull(receivedOperationName[0]);
assertEquals(operationName, receivedOperationName[0]);
assertEquals(payload, receivedContinuationPayload[0]);
listener.close();
listener.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
bootstrap.close();
elGroup.close();
elGroup.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
socketOptions.close();
}
use of software.amazon.awssdk.crt.io.SocketOptions in project aws-crt-java by awslabs.
the class ServerListenerTest method testConnectionHandling.
@Test
public void testConnectionHandling() throws ExecutionException, InterruptedException, IOException, TimeoutException {
SocketOptions socketOptions = new SocketOptions();
socketOptions.connectTimeoutMs = 3000;
socketOptions.domain = SocketOptions.SocketDomain.IPv4;
socketOptions.type = SocketOptions.SocketType.STREAM;
EventLoopGroup elGroup = new EventLoopGroup(1);
ServerBootstrap bootstrap = new ServerBootstrap(elGroup);
final boolean[] connectionReceived = { false };
final boolean[] connectionShutdown = { false };
final ServerConnection[] serverConnections = { null };
final Lock lock = new ReentrantLock();
final Condition testSynchronizationCVar = lock.newCondition();
ServerListener listener = new ServerListener("127.0.0.1", (short) 8040, socketOptions, null, bootstrap, new ServerListenerHandler() {
public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
lock.lock();
connectionReceived[0] = true;
serverConnections[0] = serverConnection;
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(serverConnection) {
@Override
protected void onProtocolMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
}
@Override
protected ServerConnectionContinuationHandler onIncomingStream(ServerConnectionContinuation continuation, String operationName) {
return null;
}
};
testSynchronizationCVar.signal();
lock.unlock();
return connectionHandler;
}
public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
connectionShutdown[0] = true;
}
});
Socket clientSocket = new Socket();
SocketAddress address = new InetSocketAddress("127.0.0.1", 8040);
lock.lock();
clientSocket.connect(address, 3000);
testSynchronizationCVar.await(1, TimeUnit.SECONDS);
lock.unlock();
assertNotNull(serverConnections[0]);
clientSocket.close();
serverConnections[0].getClosedFuture().get(1, TimeUnit.SECONDS);
assertTrue(connectionReceived[0]);
assertTrue(connectionShutdown[0]);
listener.close();
listener.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
bootstrap.close();
elGroup.close();
elGroup.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
socketOptions.close();
}
Aggregations