Search in sources :

Example 26 with SocketOptions

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();
}
Also used : EchoTestRPCClient(software.amazon.awssdk.awstest.EchoTestRPCClient) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EchoTestRPC(software.amazon.awssdk.awstest.EchoTestRPC) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) HostResolver(software.amazon.awssdk.crt.io.HostResolver) CompletableFuture(java.util.concurrent.CompletableFuture) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) EventStreamRPCConnectionConfig(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig)

Example 27 with SocketOptions

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;
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) CompletableFuture(java.util.concurrent.CompletableFuture) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) EventStreamRPCConnectionConfig(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig)

Example 28 with SocketOptions

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();
}
Also used : EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) Test(org.junit.Test)

Example 29 with SocketOptions

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();
}
Also used : ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) Socket(java.net.Socket) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) SocketAddress(java.net.SocketAddress) ReentrantLock(java.util.concurrent.locks.ReentrantLock) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test) IOException(java.io.IOException) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) StandardCharsets(java.nio.charset.StandardCharsets) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) List(java.util.List) Condition(java.util.concurrent.locks.Condition) Lock(java.util.concurrent.locks.Lock) software.amazon.awssdk.crt.eventstream(software.amazon.awssdk.crt.eventstream) Assert(org.junit.Assert) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) ByteBuffer(java.nio.ByteBuffer) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) Socket(java.net.Socket) Test(org.junit.Test)

Example 30 with SocketOptions

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();
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) InetSocketAddress(java.net.InetSocketAddress) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)43 EventLoopGroup (software.amazon.awssdk.crt.io.EventLoopGroup)30 Test (org.junit.jupiter.api.Test)18 ClientBootstrap (software.amazon.awssdk.crt.io.ClientBootstrap)18 ExecutionException (java.util.concurrent.ExecutionException)13 Test (org.junit.Test)11 HostResolver (software.amazon.awssdk.crt.io.HostResolver)11 EventStreamRPCConnection (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection)11 ServerBootstrap (software.amazon.awssdk.crt.io.ServerBootstrap)10 List (java.util.List)9 IOException (java.io.IOException)8 GreengrassCoreIPCClient (software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient)8 ArrayList (java.util.ArrayList)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 TimeoutException (java.util.concurrent.TimeoutException)6 Condition (java.util.concurrent.locks.Condition)6 Lock (java.util.concurrent.locks.Lock)6 ReentrantLock (java.util.concurrent.locks.ReentrantLock)6 Header (software.amazon.awssdk.crt.eventstream.Header)6 HashSet (java.util.HashSet)5