Search in sources :

Example 1 with ValidateConfigurationUpdateEvents

use of software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents in project aws-greengrass-nucleus by aws-greengrass.

the class DynamicComponentConfigurationValidationTest method GIVEN_deployment_changes_component_config_WHEN_component_validates_config_THEN_deployment_is_successful.

@Test
void GIVEN_deployment_changes_component_config_WHEN_component_validates_config_THEN_deployment_is_successful() throws Throwable {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    // Subscribe to config validation on behalf of the running service
    CountDownLatch eventReceivedByClient = new CountDownLatch(1);
    Topics servicePrivateConfig = kernel.getConfig().findTopics(SERVICES_NAMESPACE_TOPIC, "OldService", PRIVATE_STORE_NAMESPACE_TOPIC);
    String authToken = Coerce.toString(servicePrivateConfig.find(SERVICE_UNIQUE_ID_KEY));
    CountDownLatch subscriptionLatch = new CountDownLatch(1);
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel);
        AutoCloseable l = TestUtils.createCloseableLogListener(m -> {
            if (m.getMessage().contains("Config IPC subscribe to config validation request")) {
                subscriptionLatch.countDown();
            }
        })) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        SubscribeToValidateConfigurationUpdatesRequest subscribe = new SubscribeToValidateConfigurationUpdatesRequest();
        greengrassCoreIPCClient.subscribeToValidateConfigurationUpdates(subscribe, Optional.of(new StreamResponseHandler<ValidateConfigurationUpdateEvents>() {

            @Override
            public void onStreamEvent(ValidateConfigurationUpdateEvents events) {
                assertNotNull(events);
                assertNotNull(events.getValidateConfigurationUpdateEvent());
                assertNotNull(events.getValidateConfigurationUpdateEvent().getConfiguration());
                assertThat(events.getValidateConfigurationUpdateEvent().getConfiguration(), IsMapContaining.hasEntry("ConfigKey1", "ConfigValue2"));
                eventReceivedByClient.countDown();
                SendConfigurationValidityReportRequest reportRequest = new SendConfigurationValidityReportRequest();
                ConfigurationValidityReport report = new ConfigurationValidityReport();
                report.setStatus(ConfigurationValidityStatus.ACCEPTED);
                report.setDeploymentId(events.getValidateConfigurationUpdateEvent().getDeploymentId());
                reportRequest.setConfigurationValidityReport(report);
                try {
                    greengrassCoreIPCClient.sendConfigurationValidityReport(reportRequest, Optional.empty()).getResponse().get(10, TimeUnit.SECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException e) {
                    fail("received invalid update validate configuration event", e);
                }
            }

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

            @Override
            public void onStreamClosed() {
            }
        }));
        assertTrue(subscriptionLatch.await(20, TimeUnit.SECONDS));
        // Attempt changing the configuration for the running service
        Map<String, Object> newConfig = new HashMap<String, Object>() {

            {
                put(SERVICES_NAMESPACE_TOPIC, new HashMap<String, Object>() {

                    {
                        put("main", kernel.getMain().getServiceConfig().toPOJO());
                        put("OldService", new HashMap<String, Object>() {

                            {
                                put(CONFIGURATION_CONFIG_KEY, new HashMap<String, Object>() {

                                    {
                                        put("ConfigKey1", "ConfigValue2");
                                    }
                                });
                                put(SERVICE_LIFECYCLE_NAMESPACE_TOPIC, new HashMap<String, Object>() {

                                    {
                                        put(LIFECYCLE_RUN_NAMESPACE_TOPIC, "echo Running OldService");
                                    }
                                });
                                put(VERSION_CONFIG_KEY, DEFAULT_EXISTING_SERVICE_VERSION);
                            }
                        });
                        put(DEFAULT_NUCLEUS_COMPONENT_NAME, getNucleusConfig(kernel));
                    }
                });
            }
        };
        DeploymentResult result = deploymentConfigMerger.mergeInNewConfig(createTestDeployment(), newConfig).get(60, TimeUnit.SECONDS);
        assertEquals(DeploymentResult.DeploymentStatus.SUCCESSFUL, result.getDeploymentStatus());
        assertTrue(eventReceivedByClient.await(20, TimeUnit.SECONDS));
    }
}
Also used : Topics(com.aws.greengrass.config.Topics) ValidateConfigurationUpdateEvents(software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents) SubscribeToValidateConfigurationUpdatesRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesRequest) HashMap(java.util.HashMap) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) StreamResponseHandler(software.amazon.awssdk.eventstreamrpc.StreamResponseHandler) SendConfigurationValidityReportRequest(software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportRequest) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) CountDownLatch(java.util.concurrent.CountDownLatch) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) ExecutionException(java.util.concurrent.ExecutionException) ConfigurationValidityReport(software.amazon.awssdk.aws.greengrass.model.ConfigurationValidityReport) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 2 with ValidateConfigurationUpdateEvents

use of software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents in project aws-greengrass-nucleus by aws-greengrass.

the class ConfigStoreIPCEventStreamAgentTest method GIVEN_agent_running_WHEN_subscribe_to_validate_config_request_THEN_validation_event_can_be_triggered.

@Test
void GIVEN_agent_running_WHEN_subscribe_to_validate_config_request_THEN_validation_event_can_be_triggered() throws Exception {
    when(mockAuthenticationData.getIdentityLabel()).thenReturn(TEST_COMPONENT_A);
    when(mockServerConnectionContinuation.sendMessage(anyList(), byteArrayCaptor.capture(), any(MessageType.class), anyInt())).thenReturn(new CompletableFuture<>());
    SubscribeToValidateConfigurationUpdatesRequest request = new SubscribeToValidateConfigurationUpdatesRequest();
    SubscribeToValidateConfigurationUpdatesResponse response = agent.getValidateConfigurationUpdatesHandler(mockContext).handleRequest(request);
    assertNotNull(response);
    Map<String, Object> configToValidate = new HashMap<>();
    configToValidate.put(TEST_CONFIG_KEY_1, 0);
    configToValidate.put(TEST_CONFIG_KEY_2, 100);
    assertTrue(agent.validateConfiguration(TEST_COMPONENT_A, "A", configToValidate, new CompletableFuture<>()));
    verify(mockServerConnectionContinuation, timeout(10000)).sendMessage(anyList(), any(), any(MessageType.class), anyInt());
    ValidateConfigurationUpdateEvents events = agent.getValidateConfigurationUpdatesHandler(mockContext).getOperationModelContext().getServiceModel().fromJson(ValidateConfigurationUpdateEvents.class, byteArrayCaptor.getValue());
    events.selfDesignateSetUnionMember();
    assertNotNull(events.getValidateConfigurationUpdateEvent());
    assertNotNull(events.getValidateConfigurationUpdateEvent().getConfiguration());
    assertFalse(events.getValidateConfigurationUpdateEvent().getConfiguration().isEmpty());
    assertTrue(events.getValidateConfigurationUpdateEvent().getConfiguration().containsKey(TEST_CONFIG_KEY_1));
    assertTrue(events.getValidateConfigurationUpdateEvent().getConfiguration().containsKey(TEST_CONFIG_KEY_2));
    assertEquals(0.0, events.getValidateConfigurationUpdateEvent().getConfiguration().get(TEST_CONFIG_KEY_1));
    assertEquals(100.0, events.getValidateConfigurationUpdateEvent().getConfiguration().get(TEST_CONFIG_KEY_2));
}
Also used : SubscribeToValidateConfigurationUpdatesResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesResponse) CompletableFuture(java.util.concurrent.CompletableFuture) ValidateConfigurationUpdateEvents(software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents) SubscribeToValidateConfigurationUpdatesRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesRequest) HashMap(java.util.HashMap) MessageType(software.amazon.awssdk.crt.eventstream.MessageType) Test(org.junit.jupiter.api.Test)

Example 3 with ValidateConfigurationUpdateEvents

use of software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents in project aws-greengrass-nucleus by aws-greengrass.

the class IPCServicesTest method GIVEN_ConfigStoreEventStreamClient_WHEN_report_config_validation_status_THEN_inform_validation_requester.

@SuppressWarnings({ "PMD.CloseResource", "PMD.AvoidCatchingGenericException" })
@Test
void GIVEN_ConfigStoreEventStreamClient_WHEN_report_config_validation_status_THEN_inform_validation_requester() throws Exception {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    CountDownLatch cdl = new CountDownLatch(1);
    String authToken = IPCTestUtils.getAuthTokeForService(kernel, TEST_SERVICE_NAME);
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        CountDownLatch subscriptionLatch = new CountDownLatch(1);
        Slf4jLogAdapter.addGlobalListener(m -> {
            if (m.getMessage().contains("Config IPC subscribe to config validation request")) {
                subscriptionLatch.countDown();
            }
        });
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        SubscribeToValidateConfigurationUpdatesRequest subscribe = new SubscribeToValidateConfigurationUpdatesRequest();
        CompletableFuture<SubscribeToValidateConfigurationUpdatesResponse> fut = greengrassCoreIPCClient.subscribeToValidateConfigurationUpdates(subscribe, Optional.of(new StreamResponseHandler<ValidateConfigurationUpdateEvents>() {

            @Override
            public void onStreamEvent(ValidateConfigurationUpdateEvents events) {
                assertNotNull(events);
                assertNotNull(events.getValidateConfigurationUpdateEvent());
                assertNotNull(events.getValidateConfigurationUpdateEvent().getConfiguration());
                assertThat(events.getValidateConfigurationUpdateEvent().getConfiguration(), IsMapContaining.hasEntry("keyToValidate", "valueToValidate"));
                cdl.countDown();
                SendConfigurationValidityReportRequest reportRequest = new SendConfigurationValidityReportRequest();
                ConfigurationValidityReport report = new ConfigurationValidityReport();
                report.setStatus(ConfigurationValidityStatus.ACCEPTED);
                report.setDeploymentId(events.getValidateConfigurationUpdateEvent().getDeploymentId());
                reportRequest.setConfigurationValidityReport(report);
                greengrassCoreIPCClient.sendConfigurationValidityReport(reportRequest, Optional.empty());
            }

            @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));
        CompletableFuture<ConfigurationValidityReport> responseTracker = new CompletableFuture<>();
        ConfigStoreIPCEventStreamAgent agent = kernel.getContext().get(ConfigStoreIPCEventStreamAgent.class);
        agent.validateConfiguration("ServiceName", "A", Collections.singletonMap("keyToValidate", "valueToValidate"), responseTracker);
        assertTrue(cdl.await(20, TimeUnit.SECONDS));
        assertEquals(ConfigurationValidityStatus.ACCEPTED, responseTracker.get(20, TimeUnit.SECONDS).getStatus());
        SendConfigurationValidityReportRequest reportRequest = new SendConfigurationValidityReportRequest();
        ConfigurationValidityReport report = new ConfigurationValidityReport();
        report.setStatus(ConfigurationValidityStatus.ACCEPTED);
        reportRequest.setConfigurationValidityReport(report);
        ExecutionException ex = assertThrows(ExecutionException.class, () -> greengrassCoreIPCClient.sendConfigurationValidityReport(reportRequest, Optional.empty()).getResponse().get(5, TimeUnit.SECONDS));
        assertThat(ex.getCause().getMessage(), containsString("was null"));
    }
}
Also used : ValidateConfigurationUpdateEvents(software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents) SubscribeToValidateConfigurationUpdatesRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesRequest) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) SendConfigurationValidityReportRequest(software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) SubscribeToValidateConfigurationUpdatesResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesResponse) CompletableFuture(java.util.concurrent.CompletableFuture) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) ConfigStoreIPCEventStreamAgent(com.aws.greengrass.builtin.services.configstore.ConfigStoreIPCEventStreamAgent) ExecutionException(java.util.concurrent.ExecutionException) ConfigurationValidityReport(software.amazon.awssdk.aws.greengrass.model.ConfigurationValidityReport) Test(org.junit.jupiter.api.Test)

Example 4 with ValidateConfigurationUpdateEvents

use of software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents in project aws-greengrass-nucleus by aws-greengrass.

the class DynamicComponentConfigurationValidationTest method GIVEN_deployment_changes_component_config_WHEN_component_invalidates_config_THEN_deployment_fails.

@Test
@SuppressWarnings("PMD.AvoidCatchingGenericException")
void GIVEN_deployment_changes_component_config_WHEN_component_invalidates_config_THEN_deployment_fails() throws Throwable {
    // Subscribe to config validation on behalf of the running service
    CountDownLatch eventReceivedByClient = new CountDownLatch(1);
    Topics servicePrivateConfig = kernel.getConfig().findTopics(SERVICES_NAMESPACE_TOPIC, "OldService", PRIVATE_STORE_NAMESPACE_TOPIC);
    String authToken = Coerce.toString(servicePrivateConfig.find(SERVICE_UNIQUE_ID_KEY));
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        SubscribeToValidateConfigurationUpdatesRequest subscribe = new SubscribeToValidateConfigurationUpdatesRequest();
        CompletableFuture<SubscribeToValidateConfigurationUpdatesResponse> fut = greengrassCoreIPCClient.subscribeToValidateConfigurationUpdates(subscribe, Optional.of(new StreamResponseHandler<ValidateConfigurationUpdateEvents>() {

            @Override
            public void onStreamEvent(ValidateConfigurationUpdateEvents events) {
                assertNotNull(events);
                assertNotNull(events.getValidateConfigurationUpdateEvent());
                assertNotNull(events.getValidateConfigurationUpdateEvent().getConfiguration());
                assertThat(events.getValidateConfigurationUpdateEvent().getConfiguration(), IsMapContaining.hasEntry("ConfigKey1", "ConfigValue2"));
                eventReceivedByClient.countDown();
                SendConfigurationValidityReportRequest reportRequest = new SendConfigurationValidityReportRequest();
                ConfigurationValidityReport report = new ConfigurationValidityReport();
                report.setStatus(ConfigurationValidityStatus.REJECTED);
                report.setMessage("I don't like this configuration");
                report.setDeploymentId(events.getValidateConfigurationUpdateEvent().getDeploymentId());
                reportRequest.setConfigurationValidityReport(report);
                try {
                    greengrassCoreIPCClient.sendConfigurationValidityReport(reportRequest, Optional.empty()).getResponse().get(10, TimeUnit.SECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException e) {
                    fail("received invalid update validate configuration event", e);
                }
            }

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

            @Override
            public void onStreamClosed() {
            }
        })).getResponse();
        try {
            fut.get(30, TimeUnit.SECONDS);
        } catch (Exception e) {
            fail("Caught exception when subscribing to configuration validation updates.");
        }
        // Attempt changing the configuration for the running service
        Map<String, Object> newConfig = new HashMap<String, Object>() {

            {
                put(SERVICES_NAMESPACE_TOPIC, new HashMap<String, Object>() {

                    {
                        put("main", kernel.getMain().getServiceConfig().toPOJO());
                        put("OldService", new HashMap<String, Object>() {

                            {
                                put(CONFIGURATION_CONFIG_KEY, new HashMap<String, Object>() {

                                    {
                                        put("ConfigKey1", "ConfigValue2");
                                    }
                                });
                                put(SERVICE_LIFECYCLE_NAMESPACE_TOPIC, new HashMap<String, Object>() {

                                    {
                                        put(LIFECYCLE_RUN_NAMESPACE_TOPIC, "echo Running OldService");
                                    }
                                });
                                put(VERSION_CONFIG_KEY, DEFAULT_EXISTING_SERVICE_VERSION);
                            }
                        });
                        put(DEFAULT_NUCLEUS_COMPONENT_NAME, getNucleusConfig(kernel));
                    }
                });
            }
        };
        DeploymentResult result = deploymentConfigMerger.mergeInNewConfig(createTestDeployment(), newConfig).get(60, TimeUnit.SECONDS);
        assertEquals(DeploymentResult.DeploymentStatus.FAILED_NO_STATE_CHANGE, result.getDeploymentStatus());
        assertTrue(result.getFailureCause() instanceof ComponentConfigurationValidationException);
        assertTrue(result.getFailureCause().getMessage() != null && result.getFailureCause().getMessage().contains("Components reported that their to-be-deployed configuration is invalid { name = " + "OldService, message = I don't like this configuration }"));
        assertTrue(eventReceivedByClient.await(500, TimeUnit.MILLISECONDS));
    }
}
Also used : Topics(com.aws.greengrass.config.Topics) ValidateConfigurationUpdateEvents(software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents) SubscribeToValidateConfigurationUpdatesRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesRequest) HashMap(java.util.HashMap) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) SendConfigurationValidityReportRequest(software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportRequest) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) CountDownLatch(java.util.concurrent.CountDownLatch) ComponentConfigurationValidationException(com.aws.greengrass.deployment.exceptions.ComponentConfigurationValidationException) TimeoutException(java.util.concurrent.TimeoutException) ComponentConfigurationValidationException(com.aws.greengrass.deployment.exceptions.ComponentConfigurationValidationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) SubscribeToValidateConfigurationUpdatesResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesResponse) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) ConfigurationValidityReport(software.amazon.awssdk.aws.greengrass.model.ConfigurationValidityReport) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)4 SubscribeToValidateConfigurationUpdatesRequest (software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesRequest)4 ValidateConfigurationUpdateEvents (software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents)4 HashMap (java.util.HashMap)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ExecutionException (java.util.concurrent.ExecutionException)3 GreengrassCoreIPCClient (software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient)3 ConfigurationValidityReport (software.amazon.awssdk.aws.greengrass.model.ConfigurationValidityReport)3 SendConfigurationValidityReportRequest (software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportRequest)3 SubscribeToValidateConfigurationUpdatesResponse (software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesResponse)3 EventStreamRPCConnection (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection)3 Topics (com.aws.greengrass.config.Topics)2 DeploymentResult (com.aws.greengrass.deployment.model.DeploymentResult)2 IOException (java.io.IOException)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 TimeoutException (java.util.concurrent.TimeoutException)2 ConfigStoreIPCEventStreamAgent (com.aws.greengrass.builtin.services.configstore.ConfigStoreIPCEventStreamAgent)1 ComponentConfigurationValidationException (com.aws.greengrass.deployment.exceptions.ComponentConfigurationValidationException)1 Matchers.containsString (org.hamcrest.Matchers.containsString)1 MessageType (software.amazon.awssdk.crt.eventstream.MessageType)1