Search in sources :

Example 1 with DEPLOYMENT_SERVICE_TOPICS

use of com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS in project aws-greengrass-nucleus by aws-greengrass.

the class MultiGroupDeploymentTest method GIVEN_device_belongs_to_two_groups_WHEN_device_is_removed_from_one_group_THEN_next_deployment_removes_corresponding_component.

@Test
void GIVEN_device_belongs_to_two_groups_WHEN_device_is_removed_from_one_group_THEN_next_deployment_removes_corresponding_component() throws Exception {
    CountDownLatch firstGroupCDL = new CountDownLatch(1);
    CountDownLatch secondGroupCDL = new CountDownLatch(1);
    DeploymentStatusKeeper deploymentStatusKeeper = kernel.getContext().get(DeploymentStatusKeeper.class);
    deploymentStatusKeeper.registerDeploymentStatusConsumer(Deployment.DeploymentType.IOT_JOBS, (status) -> {
        if (status.get(DEPLOYMENT_ID_KEY_NAME).equals("firstGroup") && status.get(DEPLOYMENT_STATUS_KEY_NAME).equals("SUCCEEDED")) {
            firstGroupCDL.countDown();
        }
        if (status.get(DEPLOYMENT_ID_KEY_NAME).equals("secondGroup") && status.get(DEPLOYMENT_STATUS_KEY_NAME).equals("SUCCEEDED")) {
            secondGroupCDL.countDown();
        }
        return true;
    }, "dummyValue");
    when(thingGroupHelper.listThingGroupsForDevice(anyInt())).thenReturn(Optional.of(new HashSet<>(Arrays.asList("firstGroup", "secondGroup"))));
    submitSampleJobDocument(DeploymentServiceIntegrationTest.class.getResource("FleetConfigWithRedSignalService.json").toURI(), "firstGroup", Deployment.DeploymentType.IOT_JOBS);
    assertTrue(firstGroupCDL.await(10, TimeUnit.SECONDS));
    when(thingGroupHelper.listThingGroupsForDevice(anyInt())).thenReturn(Optional.of(new HashSet<>(Arrays.asList("secondGroup"))));
    submitSampleJobDocument(DeploymentServiceIntegrationTest.class.getResource("FleetConfigWithSomeService.json").toURI(), "secondGroup", Deployment.DeploymentType.IOT_JOBS);
    assertTrue(secondGroupCDL.await(10, TimeUnit.SECONDS));
    Topics groupToRootTopic = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS, GROUP_TO_ROOT_COMPONENTS_TOPICS);
    List<String> groupNames = new ArrayList<>();
    groupToRootTopic.forEach(node -> groupNames.add(node.getName()));
    assertTrue(groupNames.containsAll(Arrays.asList("secondGroup")), "Device should belong to firstGroup and secondGroup");
    Map<GreengrassService, DependencyType> dependenciesAfter = kernel.getMain().getDependencies();
    List<String> serviceNames = dependenciesAfter.keySet().stream().map(service -> service.getName()).collect(Collectors.toList());
    assertTrue(serviceNames.containsAll(Arrays.asList("SomeService")));
    Topics componentsToGroupTopic = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS, COMPONENTS_TO_GROUPS_TOPICS);
    assertNotNull(componentsToGroupTopic.find("SomeService", "secondGroup"));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Deployment(com.aws.greengrass.deployment.model.Deployment) GROUP_TO_ROOT_COMPONENTS_TOPICS(com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) State(com.aws.greengrass.dependency.State) BaseITCase(com.aws.greengrass.integrationtests.BaseITCase) FleetStatusService(com.aws.greengrass.status.FleetStatusService) Map(java.util.Map) DeploymentStatusKeeper(com.aws.greengrass.deployment.DeploymentStatusKeeper) URI(java.net.URI) Path(java.nio.file.Path) DEPLOYMENT_SERVICE_TOPICS(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS) FLEET_STATUS_SERVICE_TOPICS(com.aws.greengrass.status.FleetStatusService.FLEET_STATUS_SERVICE_TOPICS) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) LocalOverrideRequest(com.aws.greengrass.deployment.model.LocalOverrideRequest) DEPLOYMENT_STATUS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_KEY_NAME) Utils.copyFolderRecursively(com.aws.greengrass.util.Utils.copyFolderRecursively) UUID(java.util.UUID) COMPONENTS_TO_GROUPS_TOPICS(com.aws.greengrass.deployment.DeploymentService.COMPONENTS_TO_GROUPS_TOPICS) Collectors(java.util.stream.Collectors) ExceptionLogProtector.ignoreExceptionOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionOfType) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) PreloadComponentStoreHelper(com.aws.greengrass.helper.PreloadComponentStoreHelper) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Mock(org.mockito.Mock) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) DeploymentQueue(com.aws.greengrass.deployment.DeploymentQueue) ConfigPlatformResolver(com.aws.greengrass.integrationtests.util.ConfigPlatformResolver) HashMap(java.util.HashMap) DEPLOYMENT_STATUS_DETAILS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_DETAILS_KEY_NAME) Configuration(com.amazon.aws.iot.greengrass.configuration.common.Configuration) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Coerce(com.aws.greengrass.util.Coerce) ThingGroupHelper(com.aws.greengrass.deployment.ThingGroupHelper) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) PackageDownloadException(com.aws.greengrass.componentmanager.exceptions.PackageDownloadException) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) REPLACE_EXISTING(java.nio.file.StandardCopyOption.REPLACE_EXISTING) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) DEPLOYMENT_ID_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_ID_KEY_NAME) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) File(java.io.File) ExceptionLogProtector.ignoreExceptionWithMessage(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionWithMessage) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Topic(com.aws.greengrass.config.Topic) AfterEach(org.junit.jupiter.api.AfterEach) Paths(java.nio.file.Paths) ServiceUpdateException(com.aws.greengrass.deployment.exceptions.ServiceUpdateException) NoOpPathOwnershipHandler(com.aws.greengrass.testcommons.testutilities.NoOpPathOwnershipHandler) DeploymentStatus(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus) Topics(com.aws.greengrass.config.Topics) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) ArrayList(java.util.ArrayList) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) DeploymentStatusKeeper(com.aws.greengrass.deployment.DeploymentStatusKeeper) CountDownLatch(java.util.concurrent.CountDownLatch) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Example 2 with DEPLOYMENT_SERVICE_TOPICS

use of com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS in project aws-greengrass-nucleus by aws-greengrass.

the class DeploymentServiceTest method startDeploymentServiceInAnotherThread.

private void startDeploymentServiceInAnotherThread() throws InterruptedException {
    CountDownLatch cdl = new CountDownLatch(1);
    Consumer<GreengrassLogMessage> listener = m -> {
        if (m.getContexts() != null && m.getContexts().containsKey(SERVICE_NAME_KEY) && m.getContexts().get(SERVICE_NAME_KEY).equalsIgnoreCase(DEPLOYMENT_SERVICE_TOPICS)) {
            cdl.countDown();
        }
    };
    Slf4jLogAdapter.addGlobalListener(listener);
    deploymentServiceThread = new Thread(() -> {
        try {
            deploymentService.startup();
        } catch (InterruptedException ignore) {
        }
    });
    deploymentServiceThread.start();
    boolean running = cdl.await(1, TimeUnit.SECONDS);
    Slf4jLogAdapter.removeGlobalListener(listener);
    assertTrue(running, "Deployment service must be running");
}
Also used : IsNull(org.hamcrest.core.IsNull) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) IsIterableContainingInAnyOrder.containsInAnyOrder(org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder) Deployment(com.aws.greengrass.deployment.model.Deployment) GROUP_TO_ROOT_COMPONENTS_TOPICS(com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS) IsEmptyCollection(org.hamcrest.collection.IsEmptyCollection) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) State(com.aws.greengrass.dependency.State) Duration(java.time.Duration) Map(java.util.Map) Is.is(org.hamcrest.core.Is.is) Mockito.doReturn(org.mockito.Mockito.doReturn) DependencyResolver(com.aws.greengrass.componentmanager.DependencyResolver) SERVICE_NAME_KEY(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_NAME_KEY) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) DEPLOYMENT_SERVICE_TOPICS(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS) IsMapContaining.hasEntry(org.hamcrest.collection.IsMapContaining.hasEntry) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) IsMapContaining.hasKey(org.hamcrest.collection.IsMapContaining.hasKey) Node(com.aws.greengrass.config.Node) VerificationWithTimeout(org.mockito.verification.VerificationWithTimeout) LOCAL_DEPLOYMENT_GROUP_NAME(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter.LOCAL_DEPLOYMENT_GROUP_NAME) Set(java.util.Set) Mockito.doNothing(org.mockito.Mockito.doNothing) COMPONENTS_TO_GROUPS_TOPICS(com.aws.greengrass.deployment.DeploymentService.COMPONENTS_TO_GROUPS_TOPICS) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) CountDownLatch(java.util.concurrent.CountDownLatch) DeploymentTaskFailureException(com.aws.greengrass.deployment.exceptions.DeploymentTaskFailureException) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IsNot(org.hamcrest.core.IsNot) Mock(org.mockito.Mock) ExceptionLogProtector.ignoreExceptionUltimateCauseWithMessage(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionUltimateCauseWithMessage) EnumSource(org.junit.jupiter.params.provider.EnumSource) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) Mockito.spy(org.mockito.Mockito.spy) Mockito.lenient(org.mockito.Mockito.lenient) ComponentManager(com.aws.greengrass.componentmanager.ComponentManager) Mockito.timeout(org.mockito.Mockito.timeout) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) ArgumentCaptor(org.mockito.ArgumentCaptor) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) ExecutorService(java.util.concurrent.ExecutorService) Collections.emptyMap(java.util.Collections.emptyMap) GGServiceTestUtil(com.aws.greengrass.testcommons.testutilities.GGServiceTestUtil) ExceptionLogProtector.ignoreExceptionUltimateCauseOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionUltimateCauseOfType) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) InputStreamReader(java.io.InputStreamReader) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Topic(com.aws.greengrass.config.Topic) Slf4jLogAdapter(com.aws.greengrass.logging.impl.Slf4jLogAdapter) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) DeploymentStatus(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus) BufferedReader(java.io.BufferedReader) KernelConfigResolver(com.aws.greengrass.componentmanager.KernelConfigResolver) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) GROUP_MEMBERSHIP_TOPICS(com.aws.greengrass.deployment.DeploymentService.GROUP_MEMBERSHIP_TOPICS) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 3 with DEPLOYMENT_SERVICE_TOPICS

use of com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS in project aws-greengrass-nucleus by aws-greengrass.

the class MqttReconnectTest method GIVEN_new_deployment_while_device_online_WHEN_mqtt_disconnects_and_reconnects_THEN_job_executes_successfully.

// GG_NEEDS_REVIEW: TODO: Fix flaky test https://sim.amazon.com/issues/P40525318
@Disabled
@Timeout(value = 10, unit = TimeUnit.MINUTES)
@Test
void GIVEN_new_deployment_while_device_online_WHEN_mqtt_disconnects_and_reconnects_THEN_job_executes_successfully(ExtensionContext context) throws Exception {
    ignoreExceptionUltimateCauseOfType(context, MqttException.class);
    ignoreExceptionUltimateCauseOfType(context, TimeoutException.class);
    ignoreExceptionWithMessage(context, "No valid versions were found for this package based on provided requirement");
    CountDownLatch jobInProgress = new CountDownLatch(1);
    CountDownLatch jobCompleted = new CountDownLatch(1);
    CountDownLatch connectionInterrupted = new CountDownLatch(1);
    // Create Job
    CreateDeploymentRequest createDeploymentRequest = CreateDeploymentRequest.builder().components(Utils.immutableMap("CustomerApp", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
    CreateDeploymentResponse result = draftAndCreateDeployment(createDeploymentRequest);
    String jobId = result.iotJobId();
    // Subscribe to persisted deployment status
    Topics deploymentServiceTopics = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS);
    Topics processedDeployments = deploymentServiceTopics.lookupTopics(RUNTIME_STORE_NAMESPACE_TOPIC, PROCESSED_DEPLOYMENTS_TOPICS);
    processedDeployments.subscribe((whatHappened, newValue) -> {
        if (!(newValue instanceof Topic)) {
            return;
        }
        if (newValue.childOf(DEPLOYMENT_STATUS_KEY_NAME)) {
            newValue = newValue.parent;
        } else {
            return;
        }
        Map<String, Object> deploymentDetails = ((Topics) newValue).toPOJO();
        if (!deploymentDetails.get(DEPLOYMENT_ID_KEY_NAME).toString().equals(jobId)) {
            return;
        }
        String status = deploymentDetails.get(DEPLOYMENT_STATUS_KEY_NAME).toString();
        if (JobStatus.IN_PROGRESS.toString().equals(status)) {
            jobInProgress.countDown();
        } else if (jobInProgress.getCount() <= 0 && JobStatus.SUCCEEDED.toString().equals(status)) {
            jobCompleted.countDown();
        }
    });
    kernel.launch();
    assertTrue(jobInProgress.await(2, TimeUnit.MINUTES));
    NetworkUtils networkUtils = NetworkUtils.getByPlatform();
    Consumer<GreengrassLogMessage> logListener = m -> {
        String message = m.getMessage();
        if (UPDATE_DEPLOYMENT_STATUS_MQTT_ERROR_LOG.equals(message) && m.getCause().getCause() instanceof MqttException || UPDATE_DEPLOYMENT_STATUS_TIMEOUT_ERROR_LOG.equals(message)) {
            connectionInterrupted.countDown();
        }
    };
    try {
        Slf4jLogAdapter.addGlobalListener(logListener);
        networkUtils.disconnectMqtt();
        // Wait for the deployment to finish offline
        assertTrue(jobCompleted.await(5, TimeUnit.MINUTES));
        assertTrue(connectionInterrupted.await(2, TimeUnit.MINUTES));
    } finally {
        networkUtils.recoverMqtt();
        Slf4jLogAdapter.removeGlobalListener(logListener);
    }
    // Wait for DNS Cache to expire
    Thread.sleep(DNS_CACHE_TTL.plus(Duration.ofSeconds(1)).toMillis());
    // Wait for the IoT job to be updated and marked as successful
    // The reason for making the timeout as 7 min is because it has been observed that if the update job status was
    // invoked just before the connection recovers it can block the call for total timeout of 5 mins,
    // without successfully updating the status of the job in cloud. After this timeout expires the status will
    // be updated again as part of the onConnectionResumed callback. Additional 2 mins are for this status
    // to get updated
    IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, jobId, thingInfo.getThingName(), Duration.ofMinutes(7), s -> s.equals(JobExecutionStatus.SUCCEEDED));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) UPDATE_DEPLOYMENT_STATUS_TIMEOUT_ERROR_LOG(com.aws.greengrass.deployment.IotJobsHelper.UPDATE_DEPLOYMENT_STATUS_TIMEOUT_ERROR_LOG) ComponentDeploymentSpecification(software.amazon.awssdk.services.greengrassv2.model.ComponentDeploymentSpecification) JobExecutionStatus(software.amazon.awssdk.services.iot.model.JobExecutionStatus) TimeoutException(java.util.concurrent.TimeoutException) Disabled(org.junit.jupiter.api.Disabled) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) BaseE2ETestCase(com.aws.greengrass.integrationtests.e2e.BaseE2ETestCase) PROCESSED_DEPLOYMENTS_TOPICS(com.aws.greengrass.deployment.DeploymentStatusKeeper.PROCESSED_DEPLOYMENTS_TOPICS) CreateDeploymentResponse(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentResponse) RUNTIME_STORE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.RUNTIME_STORE_NAMESPACE_TOPIC) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) Duration(java.time.Duration) Map(java.util.Map) NetworkUtils(com.aws.greengrass.integrationtests.e2e.util.NetworkUtils) Tag(org.junit.jupiter.api.Tag) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) DEPLOYMENT_SERVICE_TOPICS(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS) DEPLOYMENT_ID_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_ID_KEY_NAME) DEPLOYMENT_STATUS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_KEY_NAME) ExceptionLogProtector.ignoreExceptionUltimateCauseOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionUltimateCauseOfType) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) ExceptionLogProtector.ignoreExceptionWithMessage(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionWithMessage) UPDATE_DEPLOYMENT_STATUS_MQTT_ERROR_LOG(com.aws.greengrass.deployment.IotJobsHelper.UPDATE_DEPLOYMENT_STATUS_MQTT_ERROR_LOG) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Topic(com.aws.greengrass.config.Topic) Topics(com.aws.greengrass.config.Topics) Slf4jLogAdapter(com.aws.greengrass.logging.impl.Slf4jLogAdapter) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) Utils(com.aws.greengrass.util.Utils) CreateDeploymentRequest(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentRequest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) IotJobsUtils(com.aws.greengrass.integrationtests.e2e.util.IotJobsUtils) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) Timeout(org.junit.jupiter.api.Timeout) CreateDeploymentResponse(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentResponse) Topics(com.aws.greengrass.config.Topics) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) CreateDeploymentRequest(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentRequest) CountDownLatch(java.util.concurrent.CountDownLatch) NetworkUtils(com.aws.greengrass.integrationtests.e2e.util.NetworkUtils) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) Topic(com.aws.greengrass.config.Topic) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout) Disabled(org.junit.jupiter.api.Disabled)

Example 4 with DEPLOYMENT_SERVICE_TOPICS

use of com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS in project aws-greengrass-nucleus by aws-greengrass.

the class MultipleGroupsDeploymentE2ETest method GIVEN_deployment_2_multiple_groups_WHEN_device_removed_from_group_THEN_components_removed_on_next_deployment.

@Timeout(value = 10, unit = TimeUnit.MINUTES)
@Test
void GIVEN_deployment_2_multiple_groups_WHEN_device_removed_from_group_THEN_components_removed_on_next_deployment() throws Exception {
    CreateDeploymentRequest deploymentToFirstGroup = CreateDeploymentRequest.builder().targetArn(thingGroupArn).components(Utils.immutableMap("CustomerApp", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
    CreateDeploymentResponse firstDeploymentResult = draftAndCreateDeployment(deploymentToFirstGroup);
    IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, firstDeploymentResult.iotJobId(), thingInfo.getThingName(), Duration.ofMinutes(5), s -> s.equals(JobExecutionStatus.SUCCEEDED));
    CreateDeploymentRequest deviceDeployment = CreateDeploymentRequest.builder().targetArn(thingInfo.getThingArn()).components(Utils.immutableMap("SomeService", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
    CountDownLatch deviceDeploymentSucceeded = listenToShadowDeploymentUpdates();
    draftAndCreateDeployment(deviceDeployment);
    deviceDeploymentSucceeded.await(5, TimeUnit.MINUTES);
    CreateThingGroupResponse thirdThingGroup = IotJobsUtils.createThingGroupAndAddThing(iotClient, thingInfo);
    createdThingGroups.add(thirdThingGroup.thingGroupName());
    CreateDeploymentRequest deploymentToThirdGroup = CreateDeploymentRequest.builder().targetArn(thirdThingGroup.thingGroupArn()).components(Utils.immutableMap("YellowSignal", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
    CreateDeploymentResponse thirdDeploymentResult = draftAndCreateDeployment(deploymentToThirdGroup);
    IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, thirdDeploymentResult.iotJobId(), thingInfo.getThingName(), Duration.ofMinutes(5), s -> s.equals(JobExecutionStatus.SUCCEEDED));
    IotJobsUtils.removeFromThingGroup(iotClient, thingInfo, thirdThingGroup.thingGroupArn());
    CreateThingGroupResponse fourthThingGroup = IotJobsUtils.createThingGroupAndAddThing(iotClient, thingInfo);
    createdThingGroups.add(fourthThingGroup.thingGroupName());
    CreateDeploymentRequest deploymentToFourthGroup = CreateDeploymentRequest.builder().targetArn(fourthThingGroup.thingGroupArn()).components(Utils.immutableMap("RedSignal", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
    CreateDeploymentResponse fourthDeploymentResult = draftAndCreateDeployment(deploymentToFourthGroup);
    IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, fourthDeploymentResult.iotJobId(), thingInfo.getThingName(), Duration.ofMinutes(5), s -> s.equals(JobExecutionStatus.SUCCEEDED));
    Map<GreengrassService, DependencyType> dependenciesAfter = kernel.getMain().getDependencies();
    List<String> serviceNames = dependenciesAfter.keySet().stream().map(service -> service.getName()).collect(Collectors.toList());
    assertTrue(serviceNames.containsAll(Arrays.asList(getTestComponentNameInCloud("CustomerApp"), getTestComponentNameInCloud("SomeService"), getTestComponentNameInCloud("RedSignal"))));
    assertFalse(serviceNames.containsAll(Arrays.asList(getTestComponentNameInCloud("YellowSignal"))));
    Topics groupToRootTopic = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS, GROUP_TO_ROOT_COMPONENTS_TOPICS);
    assertNotNull(groupToRootTopic.findTopics(THING_GROUP_RESOURCE_TYPE_PREFIX + thingGroupName, getTestComponentNameInCloud("CustomerApp")));
    assertNotNull(groupToRootTopic.findTopics("thing/" + thingInfo.getThingName(), getTestComponentNameInCloud("SomeService")));
    assertNotNull(groupToRootTopic.findTopics(THING_GROUP_RESOURCE_TYPE_PREFIX + fourthThingGroup.thingGroupName(), getTestComponentNameInCloud("RedSignal")));
    assertNull(groupToRootTopic.findTopics(THING_GROUP_RESOURCE_TYPE_PREFIX + thirdThingGroup.thingGroupName()));
    Topics componentsToGroupTopic = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS, COMPONENTS_TO_GROUPS_TOPICS);
    assertNotNull(componentsToGroupTopic.findTopics(getTestComponentNameInCloud("CustomerApp")));
    assertNotNull(componentsToGroupTopic.findTopics(getTestComponentNameInCloud("SomeService")));
    assertNotNull(componentsToGroupTopic.findTopics(getTestComponentNameInCloud("RedSignal")));
    assertNull(componentsToGroupTopic.findTopics(getTestComponentNameInCloud("YellowSignal")));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ComponentDeploymentSpecification(software.amazon.awssdk.services.greengrassv2.model.ComponentDeploymentSpecification) NoAvailableComponentVersionException(com.aws.greengrass.componentmanager.exceptions.NoAvailableComponentVersionException) GROUP_TO_ROOT_COMPONENTS_TOPICS(com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) State(com.aws.greengrass.dependency.State) Duration(java.time.Duration) Map(java.util.Map) Tag(org.junit.jupiter.api.Tag) DEPLOYMENT_SERVICE_TOPICS(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS) DEPLOYMENT_SHADOW_NAME(com.aws.greengrass.deployment.ShadowDeploymentListener.DEPLOYMENT_SHADOW_NAME) COMPONENTS_TO_GROUPS_TOPICS(com.aws.greengrass.deployment.DeploymentService.COMPONENTS_TO_GROUPS_TOPICS) EventuallyLambdaMatcher.eventuallyEval(com.github.grantwest.eventually.EventuallyLambdaMatcher.eventuallyEval) Collectors(java.util.stream.Collectors) ExceptionLogProtector.ignoreExceptionOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionOfType) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) WrapperMqttClientConnection(com.aws.greengrass.mqttclient.WrapperMqttClientConnection) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CreateDeploymentRequest(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentRequest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Matchers.is(org.hamcrest.Matchers.is) IotJobsUtils(com.aws.greengrass.integrationtests.e2e.util.IotJobsUtils) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) VERSION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.VERSION_CONFIG_KEY) JobExecutionStatus(software.amazon.awssdk.services.iot.model.JobExecutionStatus) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) STATUS_KEY(com.aws.greengrass.status.DeploymentInformation.STATUS_KEY) BaseE2ETestCase(com.aws.greengrass.integrationtests.e2e.BaseE2ETestCase) CreateDeploymentResponse(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentResponse) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) IotShadowClient(software.amazon.awssdk.iot.iotshadow.IotShadowClient) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) CreateThingGroupResponse(software.amazon.awssdk.services.iot.model.CreateThingGroupResponse) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) ComponentConfigurationUpdate(software.amazon.awssdk.services.greengrassv2.model.ComponentConfigurationUpdate) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AfterEach(org.junit.jupiter.api.AfterEach) Utils(com.aws.greengrass.util.Utils) THING_GROUP_RESOURCE_TYPE_PREFIX(com.aws.greengrass.deployment.ThingGroupHelper.THING_GROUP_RESOURCE_TYPE_PREFIX) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) MqttClient(com.aws.greengrass.mqttclient.MqttClient) Timeout(org.junit.jupiter.api.Timeout) CreateDeploymentResponse(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentResponse) Topics(com.aws.greengrass.config.Topics) CreateThingGroupResponse(software.amazon.awssdk.services.iot.model.CreateThingGroupResponse) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) CreateDeploymentRequest(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentRequest) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 5 with DEPLOYMENT_SERVICE_TOPICS

use of com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS in project aws-greengrass-nucleus by aws-greengrass.

the class MultiGroupDeploymentTest method GIVEN_device_belongs_to_two_groups_WHEN_device_receives_deployments_to_both_groups_THEN_no_components_removed.

@Test
void GIVEN_device_belongs_to_two_groups_WHEN_device_receives_deployments_to_both_groups_THEN_no_components_removed() throws Exception {
    CountDownLatch firstGroupCDL = new CountDownLatch(1);
    CountDownLatch secondGroupCDL = new CountDownLatch(1);
    DeploymentStatusKeeper deploymentStatusKeeper = kernel.getContext().get(DeploymentStatusKeeper.class);
    deploymentStatusKeeper.registerDeploymentStatusConsumer(Deployment.DeploymentType.IOT_JOBS, (status) -> {
        if (status.get(DEPLOYMENT_ID_KEY_NAME).equals("firstGroup") && status.get(DEPLOYMENT_STATUS_KEY_NAME).equals("SUCCEEDED")) {
            firstGroupCDL.countDown();
        }
        if (status.get(DEPLOYMENT_ID_KEY_NAME).equals("secondGroup") && status.get(DEPLOYMENT_STATUS_KEY_NAME).equals("SUCCEEDED")) {
            secondGroupCDL.countDown();
        }
        return true;
    }, "dummyValue");
    when(thingGroupHelper.listThingGroupsForDevice(anyInt())).thenReturn(Optional.of(new HashSet<>(Arrays.asList("firstGroup", "secondGroup"))));
    submitSampleJobDocument(DeploymentServiceIntegrationTest.class.getResource("FleetConfigWithRedSignalService.json").toURI(), "firstGroup", Deployment.DeploymentType.IOT_JOBS);
    assertTrue(firstGroupCDL.await(10, TimeUnit.SECONDS));
    submitSampleJobDocument(DeploymentServiceIntegrationTest.class.getResource("FleetConfigWithSomeService.json").toURI(), "secondGroup", Deployment.DeploymentType.IOT_JOBS);
    assertTrue(secondGroupCDL.await(10, TimeUnit.SECONDS));
    Topics groupToRootTopic = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS, GROUP_TO_ROOT_COMPONENTS_TOPICS);
    List<String> groupNames = new ArrayList<>();
    groupToRootTopic.forEach(node -> groupNames.add(node.getName()));
    assertTrue(groupNames.containsAll(Arrays.asList("firstGroup", "secondGroup")), "Device should belong to firstGroup and secondGroup");
    Map<GreengrassService, DependencyType> dependenciesAfter = kernel.getMain().getDependencies();
    List<String> serviceNames = dependenciesAfter.keySet().stream().map(service -> service.getName()).collect(Collectors.toList());
    assertTrue(serviceNames.containsAll(Arrays.asList("SomeService", "RedSignal")));
    Topics componentsToGroupTopic = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC, DEPLOYMENT_SERVICE_TOPICS, COMPONENTS_TO_GROUPS_TOPICS);
    assertNotNull(componentsToGroupTopic.find("SomeService", "secondGroup"));
    assertNotNull(componentsToGroupTopic.find("RedSignal", "firstGroup"));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Deployment(com.aws.greengrass.deployment.model.Deployment) GROUP_TO_ROOT_COMPONENTS_TOPICS(com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) State(com.aws.greengrass.dependency.State) BaseITCase(com.aws.greengrass.integrationtests.BaseITCase) FleetStatusService(com.aws.greengrass.status.FleetStatusService) Map(java.util.Map) DeploymentStatusKeeper(com.aws.greengrass.deployment.DeploymentStatusKeeper) URI(java.net.URI) Path(java.nio.file.Path) DEPLOYMENT_SERVICE_TOPICS(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS) FLEET_STATUS_SERVICE_TOPICS(com.aws.greengrass.status.FleetStatusService.FLEET_STATUS_SERVICE_TOPICS) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) LocalOverrideRequest(com.aws.greengrass.deployment.model.LocalOverrideRequest) DEPLOYMENT_STATUS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_KEY_NAME) Utils.copyFolderRecursively(com.aws.greengrass.util.Utils.copyFolderRecursively) UUID(java.util.UUID) COMPONENTS_TO_GROUPS_TOPICS(com.aws.greengrass.deployment.DeploymentService.COMPONENTS_TO_GROUPS_TOPICS) Collectors(java.util.stream.Collectors) ExceptionLogProtector.ignoreExceptionOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionOfType) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) PreloadComponentStoreHelper(com.aws.greengrass.helper.PreloadComponentStoreHelper) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Mock(org.mockito.Mock) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) DeploymentQueue(com.aws.greengrass.deployment.DeploymentQueue) ConfigPlatformResolver(com.aws.greengrass.integrationtests.util.ConfigPlatformResolver) HashMap(java.util.HashMap) DEPLOYMENT_STATUS_DETAILS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_DETAILS_KEY_NAME) Configuration(com.amazon.aws.iot.greengrass.configuration.common.Configuration) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Coerce(com.aws.greengrass.util.Coerce) ThingGroupHelper(com.aws.greengrass.deployment.ThingGroupHelper) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) PackageDownloadException(com.aws.greengrass.componentmanager.exceptions.PackageDownloadException) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) REPLACE_EXISTING(java.nio.file.StandardCopyOption.REPLACE_EXISTING) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) DEPLOYMENT_ID_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_ID_KEY_NAME) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) File(java.io.File) ExceptionLogProtector.ignoreExceptionWithMessage(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionWithMessage) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Topic(com.aws.greengrass.config.Topic) AfterEach(org.junit.jupiter.api.AfterEach) Paths(java.nio.file.Paths) ServiceUpdateException(com.aws.greengrass.deployment.exceptions.ServiceUpdateException) NoOpPathOwnershipHandler(com.aws.greengrass.testcommons.testutilities.NoOpPathOwnershipHandler) DeploymentStatus(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus) Topics(com.aws.greengrass.config.Topics) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) ArrayList(java.util.ArrayList) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) DeploymentStatusKeeper(com.aws.greengrass.deployment.DeploymentStatusKeeper) CountDownLatch(java.util.concurrent.CountDownLatch) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

Topics (com.aws.greengrass.config.Topics)6 DEPLOYMENT_SERVICE_TOPICS (com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS)6 Map (java.util.Map)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 TimeUnit (java.util.concurrent.TimeUnit)6 AfterEach (org.junit.jupiter.api.AfterEach)6 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)6 BeforeEach (org.junit.jupiter.api.BeforeEach)6 Test (org.junit.jupiter.api.Test)6 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)6 ExtensionContext (org.junit.jupiter.api.extension.ExtensionContext)6 DependencyType (com.amazon.aws.iot.greengrass.component.common.DependencyType)5 Topic (com.aws.greengrass.config.Topic)5 State (com.aws.greengrass.dependency.State)5 COMPONENTS_TO_GROUPS_TOPICS (com.aws.greengrass.deployment.DeploymentService.COMPONENTS_TO_GROUPS_TOPICS)5 GROUP_TO_ROOT_COMPONENTS_TOPICS (com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS)5 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)5 Collectors (java.util.stream.Collectors)5 Assertions.assertFalse (org.junit.jupiter.api.Assertions.assertFalse)5 DEPLOYMENT_ID_KEY_NAME (com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_ID_KEY_NAME)4