Search in sources :

Example 1 with UpdateBehaviorTree

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

the class IPCPubSubTest method GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds.

@SuppressWarnings({ "PMD.AvoidCatchingGenericException" })
@Test
void GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds() throws Exception {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    String topicName = "topicName";
    SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
    subscribeToTopicRequest.setTopic(topicName);
    CountDownLatch subscriptionLatch = new CountDownLatch(1);
    Slf4jLogAdapter.addGlobalListener(m -> {
        if (m.getMessage().contains("Subscribed to topic")) {
            subscriptionLatch.countDown();
        }
    });
    String authToken = IPCTestUtils.getAuthTokeForService(kernel, "OnlyPublish");
    SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse();
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> fut.get(3, TimeUnit.SECONDS));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        UnauthorizedError unauthorizedError = (UnauthorizedError) executionException.getCause();
        assertEquals("Principal OnlyPublish is not authorized to perform aws.greengrass.ipc.pubsub:aws.greengrass#SubscribeToTopic on resource topicName", unauthorizedError.getMessage());
    }
    Topics aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
    Map<String, Object> newAcl = OBJECT_MAPPER.readValue(newAclStr, new TypeReference<Map<String, Object>>() {
    });
    aclTopic.updateFromMap(newAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
    // Block until events are completed
    kernel.getContext().waitForPublishQueueToClear();
    assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).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));
    }
    aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
    Map<String, Object> oldAcl = OBJECT_MAPPER.readValue(oldAclStr, new TypeReference<Map<String, Object>>() {
    });
    aclTopic.updateFromMap(oldAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
    // Block until events are completed
    kernel.getContext().runOnPublishQueueAndWait(() -> {
    });
}
Also used : Topics(com.aws.greengrass.config.Topics) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) CountDownLatch(java.util.concurrent.CountDownLatch) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) ExecutionException(java.util.concurrent.ExecutionException) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) Map(java.util.Map) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Example 2 with UpdateBehaviorTree

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

the class IPCPubSubTest method GIVEN_pubsubclient_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds.

@Test
@Order(1)
void GIVEN_pubsubclient_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds() throws Exception {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "OnlyPublish")) {
        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));
        });
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        Topics aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
        Map<String, Object> newAcl = OBJECT_MAPPER.readValue(newAclStr, new TypeReference<Map<String, Object>>() {
        });
        aclTopic.updateFromMap(newAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
        // Block until events are completed
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // now this should succeed
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
        aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
        Map<String, Object> oldAcl = OBJECT_MAPPER.readValue(oldAclStr, new TypeReference<Map<String, Object>>() {
        });
        aclTopic.updateFromMap(oldAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
        // Block until events are completed
        kernel.getContext().runOnPublishQueueAndWait(() -> {
        });
    }
}
Also used : Topics(com.aws.greengrass.config.Topics) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) Order(org.junit.jupiter.api.Order) TestMethodOrder(org.junit.jupiter.api.TestMethodOrder) Test(org.junit.jupiter.api.Test)

Example 3 with UpdateBehaviorTree

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

the class ConfigStoreIPCEventStreamAgentTest method GIVEN_subscribe_to_config_update_request_WHEN_timestamp_changes_but_not_value_THEN_no_event_triggered.

@Test
void GIVEN_subscribe_to_config_update_request_WHEN_timestamp_changes_but_not_value_THEN_no_event_triggered() {
    when(mockAuthenticationData.getIdentityLabel()).thenReturn(TEST_COMPONENT_B);
    Topics componentAConfiguration = configuration.getRoot().lookupTopics(SERVICES_NAMESPACE_TOPIC, TEST_COMPONENT_A);
    when(kernel.findServiceTopic(TEST_COMPONENT_A)).thenReturn(componentAConfiguration);
    SubscribeToConfigurationUpdateRequest subscribe = new SubscribeToConfigurationUpdateRequest();
    subscribe.setComponentName(TEST_COMPONENT_A);
    subscribe.setKeyPath(Collections.singletonList(TEST_CONFIG_KEY_1));
    SubscribeToConfigurationUpdateResponse response = agent.getConfigurationUpdateHandler(mockContext).handleRequest(subscribe);
    assertNotNull(response);
    // Add the same key-value to the parent but with a newer timestamp so timestampUpdated event for the topic
    // will be triggered
    long modTime = System.currentTimeMillis();
    Topics parent = configuration.getRoot().lookupTopics(SERVICES_NAMESPACE_TOPIC, TEST_COMPONENT_A, CONFIGURATION_CONFIG_KEY);
    parent.updateFromMap(Collections.singletonMap(TEST_CONFIG_KEY_1, TEST_CONFIG_KEY_1_INITIAL_VALUE), new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.MERGE, modTime));
    // Wait until config watchers finish processing changes, ipc subscription is a watcher too
    configuration.context.waitForPublishQueueToClear();
    // Mod time should be updated but event shouldn't be sent
    assertEquals(modTime, parent.find(TEST_CONFIG_KEY_1).getModtime());
    verify(mockServerConnectionContinuation, never()).sendMessage(anyList(), any(), any(MessageType.class), anyInt());
}
Also used : Topics(com.aws.greengrass.config.Topics) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) SubscribeToConfigurationUpdateResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateResponse) SubscribeToConfigurationUpdateRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateRequest) MessageType(software.amazon.awssdk.crt.eventstream.MessageType) Test(org.junit.jupiter.api.Test)

Example 4 with UpdateBehaviorTree

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

the class KernelConfigResolverTest method GIVEN_deployment_with_configuration_update_WHEN_config_resolution_requested_THEN_correct_value_applied.

@ParameterizedTest
@MethodSource("multiTimestampDeploymentSource")
void GIVEN_deployment_with_configuration_update_WHEN_config_resolution_requested_THEN_correct_value_applied(long previousDeploymentTimestamp, String expectedValue) throws Exception {
    // GIVEN
    ComponentIdentifier rootComponentIdentifier = new ComponentIdentifier(TEST_INPUT_PACKAGE_A, new Semver("1.2.0"));
    ObjectNode node = OBJECT_MAPPER.createObjectNode();
    node.with("startup").put("paramA", "valueA");
    ComponentRecipe rootComponentRecipe = getComponent(TEST_INPUT_PACKAGE_A, "1.2.0", Collections.emptyMap(), node, "/startup/paramA", null, null);
    ConfigurationUpdateOperation updateOperation = new ConfigurationUpdateOperation();
    updateOperation.setValueToMerge(Collections.singletonMap("startup", Collections.singletonMap("paramA", "valueC")));
    DeploymentPackageConfiguration rootPackageDeploymentConfig = DeploymentPackageConfiguration.builder().packageName(TEST_INPUT_PACKAGE_A).rootComponent(true).resolvedVersion(">=1.2").configurationUpdateOperation(previousDeploymentTimestamp == -1 ? null : updateOperation).build();
    DeploymentDocument document = DeploymentDocument.builder().deploymentPackageConfigurationList(Collections.singletonList(rootPackageDeploymentConfig)).timestamp(10_000L).build();
    when(kernel.findServiceTopic(TEST_INPUT_PACKAGE_A)).thenReturn(config.lookupTopics(SERVICES_NAMESPACE_TOPIC, TEST_INPUT_PACKAGE_A));
    config.lookupTopics(SERVICES_NAMESPACE_TOPIC, TEST_INPUT_PACKAGE_A, CONFIGURATION_CONFIG_KEY).updateFromMap(Collections.singletonMap("startup", Collections.singletonMap("paramA", "valueB")), new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, previousDeploymentTimestamp));
    Map<String, Object> servicesConfig = serviceConfigurationProperlyResolved(document, Collections.singletonMap(rootComponentIdentifier, rootComponentRecipe));
    // parameter interpolation
    Map<String, String> serviceInstallCommand = (Map<String, String>) getServiceInstallCommand(TEST_INPUT_PACKAGE_A, servicesConfig);
    assertThat("has running and has update configuration, the updated value should be used", serviceInstallCommand.get(LIFECYCLE_SCRIPT_KEY), equalTo("echo installing service in Component PackageA with param " + expectedValue + "," + " kernel rootPath as " + DUMMY_ROOT_PATH.toAbsolutePath().toString() + " and unpack dir as " + DUMMY_DECOMPRESSED_PATH_KEY.toAbsolutePath().toString() + ", thing name is " + THE_THINGNAME));
    assertThat("has running and has update configuration, the updated value should be used", getServiceRunCommand(TEST_INPUT_PACKAGE_A, servicesConfig), equalTo("echo running service in Component PackageA with param " + expectedValue));
}
Also used : ConfigurationUpdateOperation(com.aws.greengrass.deployment.model.ConfigurationUpdateOperation) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DeploymentDocument(com.aws.greengrass.deployment.model.DeploymentDocument) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) Semver(com.vdurmont.semver4j.Semver) DeploymentPackageConfiguration(com.aws.greengrass.deployment.model.DeploymentPackageConfiguration) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) ComponentRecipe(com.aws.greengrass.componentmanager.models.ComponentRecipe) Map(java.util.Map) HashMap(java.util.HashMap) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 5 with UpdateBehaviorTree

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

the class KernelConfigResolverTest method GIVEN_component_has_running_configuration_and_no_update_WHEN_config_resolution_requested_THEN_correct_value_applied.

@Test
void GIVEN_component_has_running_configuration_and_no_update_WHEN_config_resolution_requested_THEN_correct_value_applied() throws Exception {
    // GIVEN
    ComponentIdentifier rootComponentIdentifier = new ComponentIdentifier(TEST_INPUT_PACKAGE_A, new Semver("1.2.0"));
    ObjectNode node = OBJECT_MAPPER.createObjectNode();
    node.with("startup").put("paramA", "valueA");
    ComponentRecipe rootComponentRecipe = getComponent(TEST_INPUT_PACKAGE_A, "1.2.0", Collections.emptyMap(), node, "/startup/paramA", null, null);
    DeploymentPackageConfiguration rootPackageDeploymentConfig = DeploymentPackageConfiguration.builder().packageName(TEST_INPUT_PACKAGE_A).rootComponent(true).resolvedVersion(">=1.2").build();
    DeploymentDocument document = DeploymentDocument.builder().deploymentPackageConfigurationList(Collections.singletonList(rootPackageDeploymentConfig)).timestamp(10_000L).build();
    when(kernel.findServiceTopic(TEST_INPUT_PACKAGE_A)).thenReturn(config.lookupTopics(SERVICES_NAMESPACE_TOPIC, TEST_INPUT_PACKAGE_A));
    config.lookupTopics(SERVICES_NAMESPACE_TOPIC, TEST_INPUT_PACKAGE_A, CONFIGURATION_CONFIG_KEY).updateFromMap(Collections.singletonMap("startup", Collections.singletonMap("paramA", "valueB")), new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, 9_000L));
    Map<String, Object> servicesConfig = serviceConfigurationProperlyResolved(document, Collections.singletonMap(rootComponentIdentifier, rootComponentRecipe));
    // parameter interpolation
    Map<String, String> serviceInstallCommand = (Map<String, String>) getServiceInstallCommand(TEST_INPUT_PACKAGE_A, servicesConfig);
    assertThat("has running and no update configuration, the running value should be used", serviceInstallCommand.get(LIFECYCLE_SCRIPT_KEY), equalTo("echo installing service in Component PackageA with param valueB," + " kernel rootPath as " + DUMMY_ROOT_PATH.toAbsolutePath() + " and unpack dir as " + DUMMY_DECOMPRESSED_PATH_KEY.toAbsolutePath() + ", thing name is " + THE_THINGNAME));
    assertThat("has running and no update configuration, the running value should be used", getServiceRunCommand(TEST_INPUT_PACKAGE_A, servicesConfig), equalTo("echo running service in Component PackageA with param valueB"));
    assertThat("no runwith is present", getServiceConfig(TEST_INPUT_PACKAGE_A, servicesConfig), not(hasKey(RUN_WITH_NAMESPACE_TOPIC)));
}
Also used : DeploymentPackageConfiguration(com.aws.greengrass.deployment.model.DeploymentPackageConfiguration) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DeploymentDocument(com.aws.greengrass.deployment.model.DeploymentDocument) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) ComponentRecipe(com.aws.greengrass.componentmanager.models.ComponentRecipe) Semver(com.vdurmont.semver4j.Semver) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

UpdateBehaviorTree (com.aws.greengrass.config.UpdateBehaviorTree)13 Topics (com.aws.greengrass.config.Topics)8 Test (org.junit.jupiter.api.Test)8 Map (java.util.Map)7 HashMap (java.util.HashMap)6 DeploymentDocument (com.aws.greengrass.deployment.model.DeploymentDocument)5 ComponentIdentifier (com.aws.greengrass.componentmanager.models.ComponentIdentifier)4 ComponentRecipe (com.aws.greengrass.componentmanager.models.ComponentRecipe)4 DeploymentPackageConfiguration (com.aws.greengrass.deployment.model.DeploymentPackageConfiguration)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 Semver (com.vdurmont.semver4j.Semver)4 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)4 Configuration (com.aws.greengrass.config.Configuration)3 ConfigurationUpdateOperation (com.aws.greengrass.deployment.model.ConfigurationUpdateOperation)3 Context (com.aws.greengrass.dependency.Context)2 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)2 Logger (com.aws.greengrass.logging.api.Logger)2 IOException (java.io.IOException)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 CountDownLatch (java.util.concurrent.CountDownLatch)2