Search in sources :

Example 1 with EventStreamRPCConnectionConfig

use of software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig in project aws-greengrass-nucleus by aws-greengrass.

the class IPCEventStreamServiceTest method testClientConnection.

@Test
@SuppressWarnings("PMD.CloseResource")
void testClientConnection() throws Exception {
    CountDownLatch connectionLatch = new CountDownLatch(1);
    EventStreamRPCConnection connection = null;
    try (EventLoopGroup elg = new EventLoopGroup(1);
        ClientBootstrap clientBootstrap = new ClientBootstrap(elg, new HostResolver(elg));
        SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC()) {
        String ipcServerSocketPath = Platform.getInstance().prepareIpcFilepathForComponent(mockRootPath);
        final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elg, socketOptions, null, ipcServerSocketPath, DEFAULT_PORT_NUMBER, GreengrassConnectMessageSupplier.connectMessageSupplier("authToken"));
        connection = new EventStreamRPCConnection(config);
        final boolean[] disconnected = { false };
        final int[] disconnectedCode = { -1 };
        // this is a bit cumbersome but does not prevent a convenience wrapper from exposing a sync
        // connect() or a connect() that returns a CompletableFuture that errors
        // this could be wrapped by utility methods to provide a more
        connection.connect(new EventStreamRPCConnection.LifecycleHandler() {

            @Override
            public void onConnect() {
                connectionLatch.countDown();
            }

            @Override
            public void onDisconnect(int errorCode) {
                disconnected[0] = true;
                disconnectedCode[0] = errorCode;
            }

            // This on error is for any errors that is connection level, including problems during connect()
            @Override
            public boolean onError(Throwable t) {
                // hints at handler to disconnect due to this error
                return true;
            }
        });
        assertTrue(connectionLatch.await(2, TimeUnit.SECONDS));
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) HostResolver(software.amazon.awssdk.crt.io.HostResolver) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) EventStreamRPCConnectionConfig(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig) Test(org.junit.jupiter.api.Test)

Example 2 with EventStreamRPCConnectionConfig

use of software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig in project aws-greengrass-cli by aws-greengrass.

the class NucleusAdapterIpcClientImpl method connectToGGCOverEventStreamIPC.

private EventStreamRPCConnection connectToGGCOverEventStreamIPC(SocketOptions socketOptions, String authToken, String ipcServerSocketPath) {
    elGroup = new EventLoopGroup(1);
    clientBootstrap = new ClientBootstrap(elGroup, null);
    final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, ipcServerSocketPath, 8033, GreengrassConnectMessageSupplier.connectMessageSupplier(authToken));
    final CompletableFuture<Void> connected = new CompletableFuture<>();
    final EventStreamRPCConnection connection = new EventStreamRPCConnection(config);
    connection.connect(new EventStreamRPCConnection.LifecycleHandler() {

        // only called on successful connection. That is full on Connect -> ConnectAck(ConnectionAccepted=true)
        @Override
        public void onConnect() {
            connected.complete(null);
        }

        @Override
        public void onDisconnect(int errorCode) {
        }

        // This on error is for any errors that is connection level, including problems during connect()
        @Override
        public boolean onError(Throwable t) {
            connected.completeExceptionally(t);
            // hints at handler to disconnect due to this error
            return true;
        }
    });
    try {
        connected.get(DEFAULT_TIMEOUT_IN_SEC, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new RuntimeException(e);
    }
    return connection;
}
Also used : 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) ExecutionException(java.util.concurrent.ExecutionException) EventStreamRPCConnectionConfig(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with EventStreamRPCConnectionConfig

use of software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig in project aws-iot-device-sdk-java-v2 by aws.

the class EchoTestServiceRunner method runLocalEchoTestServer.

/**
 * Executes testClientLogic in a runnable.
 *  * If the connection encountered an error before the clientTestLogic completes this method will throw that error.
 *  * If the client completes normally first, this will complete normally.
 *  * If the client throws an exception first, this method will throw that exception
 *
 * Note: Use the returned CompletableFuture to check if any errors are occurring AFTER the testClientLogic runs. This
 * may be needed/worth checking
 *
 * @param testClientLogic return
 * @return A CompletableFuture of any connection level error that may have occurred after the testClientLogic completes
 * @throws Exception throws an exception either from the test client logic having thrown, or the connection itself
 *                   encountering an error before test client logic completes
 */
public static CompletableFuture<Void> runLocalEchoTestServer(final BiConsumer<EventStreamRPCConnection, EchoTestRPC> testClientLogic) throws Exception {
    final int port = randomPort();
    final String hostname = "127.0.0.1";
    try (final EventLoopGroup elGroup = new EventLoopGroup(1);
        final EchoTestServiceRunner runner = new EchoTestServiceRunner(elGroup, hostname, port);
        final HostResolver resolver = new HostResolver(elGroup, 64);
        final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, resolver);
        final SocketOptions socketOptions = new SocketOptions()) {
        socketOptions.connectTimeoutMs = 3000;
        socketOptions.domain = SocketOptions.SocketDomain.IPv4;
        socketOptions.type = SocketOptions.SocketType.STREAM;
        runner.runService();
        final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, hostname, 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(480, 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);
            return clientErrorFuture;
        }
    }
}
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 4 with EventStreamRPCConnectionConfig

use of software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig 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 5 with EventStreamRPCConnectionConfig

use of software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig 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)

Aggregations

ClientBootstrap (software.amazon.awssdk.crt.io.ClientBootstrap)6 EventLoopGroup (software.amazon.awssdk.crt.io.EventLoopGroup)6 EventStreamRPCConnection (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection)6 EventStreamRPCConnectionConfig (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig)6 CompletableFuture (java.util.concurrent.CompletableFuture)5 SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)4 HostResolver (software.amazon.awssdk.crt.io.HostResolver)3 EchoTestRPC (software.amazon.awssdk.awstest.EchoTestRPC)2 EchoTestRPCClient (software.amazon.awssdk.awstest.EchoTestRPCClient)2 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 Test (org.junit.jupiter.api.Test)1 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)1