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(() -> {
});
}
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(() -> {
});
}
}
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());
}
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));
}
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)));
}
Aggregations