Search in sources :

Example 1 with Topic

use of com.aws.greengrass.config.Topic in project aws-greengrass-nucleus by aws-greengrass.

the class IPCPubSubRemovalTest method GIVEN_pubsubclient_WHEN_authorized_THEN_ACL_child_removed_THEN_updates.

@Test
void GIVEN_pubsubclient_WHEN_authorized_THEN_ACL_child_removed_THEN_updates() throws Exception {
    try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "DoAll1")) {
        GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(connection);
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        Pair<CompletableFuture<Void>, Consumer<byte[]>> cb = asyncAssertOnConsumer((m) -> {
            assertEquals("some message", new String(m, StandardCharsets.UTF_8));
        });
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
        Topics serviceTopic = kernel.findServiceTopic("DoAll1");
        Topics parameters = serviceTopic.findTopics(CONFIGURATION_CONFIG_KEY);
        Topic acl = parameters.find(ACCESS_CONTROL_NAMESPACE_TOPIC, "aws.greengrass.ipc.pubsub", "policyId5", "operations");
        if (acl != null) {
            acl.withValue(Collections.emptyList());
        }
        // Block until events are completed
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // Now the authorization policies should have been removed and these should fail
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        ExecutionException executionException1 = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
        assertTrue(executionException1.getCause() instanceof UnauthorizedError);
        serviceTopic = kernel.findServiceTopic("DoAll1");
        parameters = serviceTopic.findTopics(CONFIGURATION_CONFIG_KEY);
        Topics aclTopics = parameters.findTopics(ACCESS_CONTROL_NAMESPACE_TOPIC);
        if (aclTopics != null) {
            aclTopics.remove();
        }
        // Block until events are completed
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // Now the authorization policies should have been removed and these should fail
        executionException = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        executionException1 = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
        assertTrue(executionException1.getCause() instanceof UnauthorizedError);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Topics(com.aws.greengrass.config.Topics) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) Topic(com.aws.greengrass.config.Topic) ExecutionException(java.util.concurrent.ExecutionException) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) Test(org.junit.jupiter.api.Test)

Example 2 with Topic

use of com.aws.greengrass.config.Topic in project aws-greengrass-nucleus by aws-greengrass.

the class IPCServicesTest method GIVEN_ConfigStoreEventStreamClient_WHEN_update_config_request_THEN_config_is_updated.

@SuppressWarnings({ "PMD.CloseResource", "PMD.AvoidCatchingGenericException" })
@Test
void GIVEN_ConfigStoreEventStreamClient_WHEN_update_config_request_THEN_config_is_updated() throws Exception {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    Topics configuration = kernel.findServiceTopic("ServiceName").createInteriorChild(CONFIGURATION_CONFIG_KEY);
    Topic configToUpdate = configuration.lookup("SomeKeyToUpdate").withNewerValue(0, "InitialValue");
    CountDownLatch cdl = new CountDownLatch(1);
    CountDownLatch subscriptionLatch = new CountDownLatch(1);
    Slf4jLogAdapter.addGlobalListener(m -> {
        if (m.getMessage().contains("subscribed to configuration update")) {
            subscriptionLatch.countDown();
        }
    });
    SubscribeToConfigurationUpdateRequest subscribe = new SubscribeToConfigurationUpdateRequest();
    subscribe.setComponentName("ServiceName");
    subscribe.setKeyPath(Collections.singletonList("SomeKeyToUpdate"));
    CompletableFuture<SubscribeToConfigurationUpdateResponse> fut = greengrassCoreIPCClient.subscribeToConfigurationUpdate(subscribe, Optional.of(new StreamResponseHandler<ConfigurationUpdateEvents>() {

        @Override
        public void onStreamEvent(ConfigurationUpdateEvents event) {
            assertNotNull(event.getConfigurationUpdateEvent());
            assertEquals("ServiceName", event.getConfigurationUpdateEvent().getComponentName());
            assertNotNull(event.getConfigurationUpdateEvent().getKeyPath());
            cdl.countDown();
        }

        @Override
        public boolean onStreamError(Throwable error) {
            logger.atError().log("Received 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(20, TimeUnit.SECONDS));
    CountDownLatch configUpdated = new CountDownLatch(1);
    configToUpdate.subscribe((what, node) -> configUpdated.countDown());
    Map<String, Object> map = new HashMap<>();
    map.put("SomeKeyToUpdate", "SomeValueToUpdate");
    UpdateConfigurationRequest updateConfigurationRequest = new UpdateConfigurationRequest();
    updateConfigurationRequest.setKeyPath(Collections.EMPTY_LIST);
    updateConfigurationRequest.setValueToMerge(map);
    updateConfigurationRequest.setTimestamp(Instant.now());
    greengrassCoreIPCClient.updateConfiguration(updateConfigurationRequest, Optional.empty()).getResponse().get(50, TimeUnit.SECONDS);
    assertTrue(configUpdated.await(TIMEOUT_FOR_CONFIG_STORE_SECONDS, TimeUnit.SECONDS));
    assertTrue(cdl.await(TIMEOUT_FOR_CONFIG_STORE_SECONDS, TimeUnit.SECONDS));
    assertEquals("SomeValueToUpdate", configToUpdate.getOnce());
}
Also used : Topics(com.aws.greengrass.config.Topics) HashMap(java.util.HashMap) SubscribeToConfigurationUpdateResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) ValidateConfigurationUpdateEvents(software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents) ConfigurationUpdateEvents(software.amazon.awssdk.aws.greengrass.model.ConfigurationUpdateEvents) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UpdateConfigurationRequest(software.amazon.awssdk.aws.greengrass.model.UpdateConfigurationRequest) SubscribeToConfigurationUpdateRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateRequest) Topic(com.aws.greengrass.config.Topic) Test(org.junit.jupiter.api.Test)

Example 3 with Topic

use of com.aws.greengrass.config.Topic in project aws-greengrass-nucleus by aws-greengrass.

the class GenericExternalServiceIntegTest method GIVEN_running_service_WHEN_pause_resume_requested_THEN_pause_resume_Service_and_freeze_thaw_cgroup.

void GIVEN_running_service_WHEN_pause_resume_requested_THEN_pause_resume_Service_and_freeze_thaw_cgroup(ExtensionContext context) throws Exception {
    ignoreExceptionOfType(context, FileSystemException.class);
    ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, getClass().getResource("long_running_services.yaml"));
    kernel.launch();
    CountDownLatch mainRunningLatch = new CountDownLatch(1);
    kernel.getMain().addStateSubscriber((WhatHappened what, Topic t) -> {
        if (Coerce.toEnum(State.class, t).isRunning()) {
            mainRunningLatch.countDown();
        }
    });
    // wait for main to run
    assertTrue(mainRunningLatch.await(60, TimeUnit.SECONDS), "main running");
    GenericExternalService component = (GenericExternalService) kernel.locate("sleeperA");
    assertThat(component.getState(), is(State.RUNNING));
    component.pause();
    assertTrue(component.isPaused());
    assertThat(getCgroupFreezerState(component.getServiceName()), anyOf(is(LinuxSystemResourceController.CgroupFreezerState.FROZEN), is(LinuxSystemResourceController.CgroupFreezerState.FREEZING)));
    component.resume();
    assertFalse(component.isPaused());
    assertThat(getCgroupFreezerState(component.getServiceName()), is(LinuxSystemResourceController.CgroupFreezerState.THAWED));
}
Also used : WhatHappened(com.aws.greengrass.config.WhatHappened) State(com.aws.greengrass.dependency.State) CountDownLatch(java.util.concurrent.CountDownLatch) Topic(com.aws.greengrass.config.Topic) GenericExternalService(com.aws.greengrass.lifecyclemanager.GenericExternalService)

Example 4 with Topic

use of com.aws.greengrass.config.Topic in project aws-greengrass-nucleus by aws-greengrass.

the class KernelShutdownTest method WHEN_kernel_shutdown_THEN_services_are_shutdown_in_reverse_dependency_order.

@Test
void WHEN_kernel_shutdown_THEN_services_are_shutdown_in_reverse_dependency_order() throws InterruptedException {
    AtomicBoolean mainClosed = new AtomicBoolean(false);
    AtomicBoolean sleeperAClosed = new AtomicBoolean(false);
    AtomicBoolean sleeperBClosed = new AtomicBoolean(false);
    kernel.getContext().addGlobalStateChangeListener((service, oldState, newState) -> {
        if ("main".equals(service.getName()) && newState.isClosable()) {
            mainClosed.set(true);
        }
        // Only count main as started if its dependency (new_service) has already been started
        if (mainClosed.get() && "sleeperA".equals(service.getName()) && newState.isClosable()) {
            sleeperAClosed.set(true);
        }
        if (sleeperAClosed.get() && "sleeperB".equals(service.getName()) && newState.isClosable()) {
            sleeperBClosed.set(true);
        }
    });
    CountDownLatch mainRunningLatch = new CountDownLatch(1);
    kernel.getMain().addStateSubscriber((WhatHappened what, Topic t) -> {
        if (Coerce.toEnum(State.class, t).isRunning()) {
            mainRunningLatch.countDown();
        }
    });
    // wait for main to run
    assertTrue(mainRunningLatch.await(60, TimeUnit.SECONDS));
    kernel.shutdown(60);
    assertTrue(sleeperBClosed.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WhatHappened(com.aws.greengrass.config.WhatHappened) State(com.aws.greengrass.dependency.State) CountDownLatch(java.util.concurrent.CountDownLatch) Topic(com.aws.greengrass.config.Topic) Test(org.junit.jupiter.api.Test)

Example 5 with Topic

use of com.aws.greengrass.config.Topic in project aws-greengrass-nucleus by aws-greengrass.

the class DeviceConfiguration method getThingName.

/**
 * Get thing name configuration. Also adds the thing name to the env vars if it has changed.
 *
 * @return Thing name config topic.
 */
public Topic getThingName() {
    Topic thingNameTopic = kernel.getConfig().lookup(SYSTEM_NAMESPACE_KEY, DEVICE_PARAM_THING_NAME).dflt("");
    kernel.getConfig().lookup(SETENV_CONFIG_NAMESPACE, AWS_IOT_THING_NAME_ENV).withValue(Coerce.toString(thingNameTopic));
    return thingNameTopic;
}
Also used : Topic(com.aws.greengrass.config.Topic)

Aggregations

Topic (com.aws.greengrass.config.Topic)102 Topics (com.aws.greengrass.config.Topics)58 Test (org.junit.jupiter.api.Test)58 HashMap (java.util.HashMap)23 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)18 ComponentIdentifier (com.aws.greengrass.componentmanager.models.ComponentIdentifier)15 CaseInsensitiveString (com.aws.greengrass.config.CaseInsensitiveString)15 IOException (java.io.IOException)15 CountDownLatch (java.util.concurrent.CountDownLatch)13 Path (java.nio.file.Path)12 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)12 State (com.aws.greengrass.dependency.State)11 Context (com.aws.greengrass.dependency.Context)10 Semver (com.vdurmont.semver4j.Semver)10 HashSet (java.util.HashSet)10 Map (java.util.Map)10 ComponentRecipe (com.aws.greengrass.componentmanager.models.ComponentRecipe)9 Node (com.aws.greengrass.config.Node)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)9 ExecutionException (java.util.concurrent.ExecutionException)8