Search in sources :

Example 41 with SocketOptions

use of software.amazon.awssdk.crt.io.SocketOptions in project aws-greengrass-nucleus by aws-greengrass.

the class IPCPubSubTest method GIVEN_PubSubEventStreamClient_WHEN_subscribe_to_wildcard_THEN_publishes_to_subtopic_only_once.

@Test
@SuppressWarnings({ "PMD.AvoidCatchingGenericException" })
void GIVEN_PubSubEventStreamClient_WHEN_subscribe_to_wildcard_THEN_publishes_to_subtopic_only_once() throws Exception {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    String topicName = "/topic/1/+";
    SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
    subscribeToTopicRequest.setTopic(topicName);
    CountDownLatch cdl = new CountDownLatch(1);
    AtomicInteger atomicInteger = new AtomicInteger();
    CountDownLatch subscriptionLatch = new CountDownLatch(1);
    // Allowed resource /to*/#
    String authToken = IPCTestUtils.getAuthTokeForService(kernel, "SubscribeAndPublishWildcard");
    SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel);
        AutoCloseable l = TestUtils.createCloseableLogListener(m -> {
            if (m.getMessage().contains("Subscribed to topic")) {
                subscriptionLatch.countDown();
            }
        })) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, Optional.of(new StreamResponseHandler<SubscriptionResponseMessage>() {

            @Override
            public void onStreamEvent(SubscriptionResponseMessage message) {
                assertNotNull(message.getBinaryMessage());
                assertNull(message.getJsonMessage());
                assertEquals("ABCDEFG", new String(message.getBinaryMessage().getMessage()));
                atomicInteger.incrementAndGet();
                cdl.countDown();
            }

            @Override
            public boolean onStreamError(Throwable error) {
                logger.atError().log("Received a stream error", error);
                return false;
            }

            @Override
            public void onStreamClosed() {
            }
        })).getResponse();
        try {
            fut.get(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.atError().setCause(e).log("Error when subscribing to component updates");
            fail("Caught exception when subscribing to component updates");
        }
        assertTrue(subscriptionLatch.await(10, TimeUnit.SECONDS));
        publishToTopicOverIpcAsBinaryMessage(greengrassCoreIPCClient, "/topic/1/2", "ABCDEFG");
        assertTrue(cdl.await(20, TimeUnit.SECONDS));
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Example 42 with SocketOptions

use of software.amazon.awssdk.crt.io.SocketOptions in project aws-greengrass-nucleus by aws-greengrass.

the class IPCEventStreamService method startup.

@SuppressWarnings({ "PMD.AvoidCatchingGenericException", "PMD.ExceptionAsFlowControl" })
@Override
public void startup() {
    Path rootPath = kernel.getNucleusPaths().rootPath();
    try {
        greengrassCoreIPCService.getAllOperations().forEach(operation -> greengrassCoreIPCService.setOperationHandler(operation, (context) -> new DefaultOperationHandler(GreengrassCoreIPCServiceModel.getInstance().getOperationModelContext(operation), context)));
        greengrassCoreIPCService.setAuthenticationHandler((List<Header> headers, byte[] bytes) -> ipcAuthenticationHandler(bytes));
        greengrassCoreIPCService.setAuthorizationHandler(this::ipcAuthorizationHandler);
        socketOptions = new SocketOptions();
        socketOptions.connectTimeoutMs = 3000;
        socketOptions.domain = SocketOptions.SocketDomain.LOCAL;
        socketOptions.type = SocketOptions.SocketType.STREAM;
        eventLoopGroup = new EventLoopGroup(1);
        Topic kernelUri = config.getRoot().lookup(SETENV_CONFIG_NAMESPACE, NUCLEUS_DOMAIN_SOCKET_FILEPATH);
        kernelUri.withValue(Platform.getInstance().prepareIpcFilepath(rootPath));
        Topic kernelRelativeUri = config.getRoot().lookup(SETENV_CONFIG_NAMESPACE, NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT);
        kernelRelativeUri.withValue(Platform.getInstance().prepareIpcFilepathForComponent(rootPath));
        // For domain sockets:
        // 1. Port number is ignored. RpcServer does not accept a null value so we are using a default value.
        // 2. The hostname parameter expects the socket filepath
        rpcServer = new RpcServer(eventLoopGroup, socketOptions, null, Platform.getInstance().prepareIpcFilepathForRpcServer(rootPath), DEFAULT_PORT_NUMBER, greengrassCoreIPCService);
        rpcServer.runServer();
    } catch (RuntimeException e) {
        // Make sure to cleanup anything we created since we don't know where exactly we failed
        close();
        throw e;
    }
    logger.debug("Set IPC permissions");
    Platform.getInstance().setIpcFilePermissions(rootPath);
}
Also used : Path(java.nio.file.Path) UnauthenticatedException(com.aws.greengrass.ipc.exceptions.UnauthenticatedException) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) AuthenticationData(software.amazon.awssdk.eventstreamrpc.AuthenticationData) DefaultOperationHandler(com.aws.greengrass.ipc.common.DefaultOperationHandler) GreengrassCoreIPCService(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCService) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) Platform(com.aws.greengrass.util.platforms.Platform) Inject(javax.inject.Inject) SETENV_CONFIG_NAMESPACE(com.aws.greengrass.lifecyclemanager.GreengrassService.SETENV_CONFIG_NAMESPACE) LogManager(com.aws.greengrass.logging.impl.LogManager) Header(software.amazon.awssdk.crt.eventstream.Header) Authorization(software.amazon.awssdk.eventstreamrpc.Authorization) Path(java.nio.file.Path) Configuration(com.aws.greengrass.config.Configuration) RpcServer(software.amazon.awssdk.eventstreamrpc.RpcServer) GreengrassCoreIPCServiceModel(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCServiceModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) Topic(com.aws.greengrass.config.Topic) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) List(java.util.List) Utils(com.aws.greengrass.util.Utils) Closeable(java.io.Closeable) GreengrassEventStreamConnectMessage(software.amazon.awssdk.eventstreamrpc.GreengrassEventStreamConnectMessage) Logger(com.aws.greengrass.logging.api.Logger) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) DefaultOperationHandler(com.aws.greengrass.ipc.common.DefaultOperationHandler) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) RpcServer(software.amazon.awssdk.eventstreamrpc.RpcServer) List(java.util.List) Topic(com.aws.greengrass.config.Topic)

Example 43 with SocketOptions

use of software.amazon.awssdk.crt.io.SocketOptions in project aws-greengrass-nucleus by aws-greengrass.

the class TestUtils method getSocketOptionsForIPC.

public static SocketOptions getSocketOptionsForIPC() {
    SocketOptions socketOptions = new SocketOptions();
    socketOptions.connectTimeoutMs = 3000;
    socketOptions.domain = SocketOptions.SocketDomain.LOCAL;
    socketOptions.type = SocketOptions.SocketType.STREAM;
    return socketOptions;
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions)

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