Search in sources :

Example 1 with PublishRequest

use of com.aws.greengrass.mqttclient.PublishRequest in project aws-greengrass-nucleus by aws-greengrass.

the class FleetStatusServiceSetupTest method setupKernel.

@BeforeEach
void setupKernel() throws Exception {
    fleetStatusDetails = new AtomicReference<>();
    kernel = new Kernel();
    ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, FleetStatusServiceSetupTest.class.getResource("onlyMain.yaml"));
    kernel.getContext().put(MqttClient.class, mqttClient);
    when(mqttClient.publish(any(PublishRequest.class))).thenAnswer(i -> {
        Object argument = i.getArgument(0);
        PublishRequest publishRequest = (PublishRequest) argument;
        try {
            fleetStatusDetails.set(OBJECT_MAPPER.readValue(publishRequest.getPayload(), FleetStatusDetails.class));
        } catch (JsonMappingException ignored) {
        }
        return CompletableFuture.completedFuture(0);
    });
}
Also used : FleetStatusDetails(com.aws.greengrass.status.FleetStatusDetails) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) PublishRequest(com.aws.greengrass.mqttclient.PublishRequest) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with PublishRequest

use of com.aws.greengrass.mqttclient.PublishRequest in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsFleetStatusServiceTest method WHEN_deployment_bumps_up_component_version_THEN_status_of_new_version_is_updated_to_cloud.

@Test
void WHEN_deployment_bumps_up_component_version_THEN_status_of_new_version_is_updated_to_cloud() throws Exception {
    ((Map) kernel.getContext().getvIfExists(Kernel.SERVICE_TYPE_TO_CLASS_MAP_KEY).get()).put("plugin", GreengrassService.class.getName());
    assertNotNull(deviceConfiguration.getThingName());
    CountDownLatch jobsDeploymentLatch = new CountDownLatch(1);
    CountDownLatch fssPublishLatch = new CountDownLatch(1);
    logListener = eslm -> {
        if (eslm.getMessage() != null && eslm.getMessage().equals(UPDATE_DEPLOYMENT_STATUS_ACCEPTED) && eslm.getContexts().get("JobId").equals("simpleApp2")) {
            jobsDeploymentLatch.countDown();
        }
        if (jobsDeploymentLatch.getCount() == 0 && eslm.getEventType() != null && eslm.getEventType().equals("fss-status-update-published") && eslm.getMessage().equals("Status update published to FSS")) {
            fssPublishLatch.countDown();
        }
    };
    Slf4jLogAdapter.addGlobalListener(logListener);
    // First local deployment adds SimpleApp v1
    Map<String, String> componentsToMerge = new HashMap<>();
    componentsToMerge.put("SimpleApp", "1.0.0");
    LocalOverrideRequest request = LocalOverrideRequest.builder().requestId("SimpleApp1").componentsToMerge(componentsToMerge).requestTimestamp(System.currentTimeMillis()).build();
    submitLocalDocument(request);
    // Second local deployment removes SimpleApp v1
    request = LocalOverrideRequest.builder().requestId("removeSimpleApp").componentsToRemove(Arrays.asList("SimpleApp")).requestTimestamp(System.currentTimeMillis()).build();
    submitLocalDocument(request);
    // Cloud deployment adds SimpleApp v2. First two deployments are local because this edge case is hit when device is
    // offline after receiving the deployment and cannot emit FSS update. Since local deployment do not emit FSS update,
    // this test simulates the device being offline by using local deployments.
    offerSampleIoTJobsDeployment("FleetConfigSimpleApp2.json", "simpleApp2");
    assertTrue(fssPublishLatch.await(180, TimeUnit.SECONDS));
    verify(mqttClient, atLeastOnce()).publish(captor.capture());
    List<PublishRequest> prs = captor.getAllValues();
    // Get the last FSS publish request which should have component info of simpleApp v2 and other built in services
    PublishRequest pr = prs.get(prs.size() - 1);
    try {
        FleetStatusDetails fleetStatusDetails = OBJECT_MAPPER.readValue(pr.getPayload(), FleetStatusDetails.class);
        assertEquals("ThingName", fleetStatusDetails.getThing());
        assertEquals(OverallStatus.HEALTHY, fleetStatusDetails.getOverallStatus());
        assertNotNull(fleetStatusDetails.getComponentStatusDetails());
        assertEquals(componentNamesToCheck.size(), fleetStatusDetails.getComponentStatusDetails().size());
        fleetStatusDetails.getComponentStatusDetails().forEach(componentStatusDetails -> {
            componentNamesToCheck.remove(componentStatusDetails.getComponentName());
            if (componentStatusDetails.getComponentName().equals("SimpleApp")) {
                assertEquals("2.0.0", componentStatusDetails.getVersion());
                assertEquals(1, componentStatusDetails.getFleetConfigArns().size());
                assertEquals(MOCK_FLEET_CONFIG_ARN, componentStatusDetails.getFleetConfigArns().get(0));
                assertEquals(State.FINISHED, componentStatusDetails.getState());
                assertTrue(componentStatusDetails.isRoot());
            } else {
                assertFalse(componentStatusDetails.isRoot());
            }
        });
    } catch (UnrecognizedPropertyException ignored) {
    }
    assertEquals(0, componentNamesToCheck.size());
    Slf4jLogAdapter.removeGlobalListener(logListener);
}
Also used : FleetStatusDetails(com.aws.greengrass.status.FleetStatusDetails) LocalOverrideRequest(com.aws.greengrass.deployment.model.LocalOverrideRequest) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) HashMap(java.util.HashMap) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) CountDownLatch(java.util.concurrent.CountDownLatch) PublishRequest(com.aws.greengrass.mqttclient.PublishRequest) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.jupiter.api.Test)

Example 3 with PublishRequest

use of com.aws.greengrass.mqttclient.PublishRequest in project aws-greengrass-nucleus by aws-greengrass.

the class MqttProxyIPCAgentTest method GIVEN_MqttProxyIPCAgent_WHEN_publish_on_topic_THEN_message_published.

@Test
void GIVEN_MqttProxyIPCAgent_WHEN_publish_on_topic_THEN_message_published() throws Exception {
    PublishToIoTCoreRequest publishToIoTCoreRequest = new PublishToIoTCoreRequest();
    publishToIoTCoreRequest.setPayload(TEST_PAYLOAD);
    publishToIoTCoreRequest.setTopicName(TEST_TOPIC);
    publishToIoTCoreRequest.setQos(QOS.AT_LEAST_ONCE);
    CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
    completableFuture.complete(0);
    when(mqttClient.publish(any())).thenReturn(completableFuture);
    when(authorizationHandler.isAuthorized(any(), any(), any())).thenReturn(true);
    ArgumentCaptor<PublishRequest> publishRequestArgumentCaptor = ArgumentCaptor.forClass(PublishRequest.class);
    try (MqttProxyIPCAgent.PublishToIoTCoreOperationHandler publishToIoTCoreOperationHandler = mqttProxyIPCAgent.getPublishToIoTCoreOperationHandler(mockContext)) {
        PublishToIoTCoreResponse publishToIoTCoreResponse = publishToIoTCoreOperationHandler.handleRequest(publishToIoTCoreRequest);
        assertNotNull(publishToIoTCoreResponse);
        verify(authorizationHandler).isAuthorized(MQTT_PROXY_SERVICE_NAME, Permission.builder().principal(TEST_SERVICE).operation(GreengrassCoreIPCService.PUBLISH_TO_IOT_CORE).resource(TEST_TOPIC).build(), ResourceLookupPolicy.MQTT_STYLE);
        verify(mqttClient).publish(publishRequestArgumentCaptor.capture());
        PublishRequest capturedPublishRequest = publishRequestArgumentCaptor.getValue();
        assertThat(capturedPublishRequest.getPayload(), is(TEST_PAYLOAD));
        assertThat(capturedPublishRequest.getTopic(), is(TEST_TOPIC));
        assertThat(capturedPublishRequest.getQos(), is(QualityOfService.AT_LEAST_ONCE));
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) PublishToIoTCoreResponse(software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreResponse) PublishRequest(com.aws.greengrass.mqttclient.PublishRequest) PublishToIoTCoreRequest(software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreRequest) Test(org.junit.jupiter.api.Test)

Example 4 with PublishRequest

use of com.aws.greengrass.mqttclient.PublishRequest in project aws-greengrass-nucleus by aws-greengrass.

the class Spool method removeMessagesWithQosZero.

private void removeMessagesWithQosZero(boolean needToCheckCurSpoolerSize) {
    Iterator<Long> messageIdIterator = queueOfMessageId.iterator();
    while (messageIdIterator.hasNext() && addJudgementWithCurrentSpoolerSize(needToCheckCurSpoolerSize)) {
        long id = messageIdIterator.next();
        PublishRequest request = getMessageById(id).getRequest();
        int qos = request.getQos().getValue();
        if (qos == 0) {
            removeMessageById(id);
            logger.atDebug().kv("id", id).kv("topic", request.getTopic()).kv("Qos", qos).log("The spooler is configured to drop QoS 0 when offline. " + "Dropping message now.");
        }
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) PublishRequest(com.aws.greengrass.mqttclient.PublishRequest)

Example 5 with PublishRequest

use of com.aws.greengrass.mqttclient.PublishRequest in project aws-greengrass-nucleus by aws-greengrass.

the class FleetStatusServiceTest method GIVEN_MQTT_connection_interrupted_WHEN_connection_resumes_THEN_MQTT_Sent_with_event_triggered_fss_data.

@Test
void GIVEN_MQTT_connection_interrupted_WHEN_connection_resumes_THEN_MQTT_Sent_with_event_triggered_fss_data() throws ServiceLoadException, IOException, InterruptedException {
    // Set up all the topics
    Topics statusConfigTopics = Topics.of(context, FLEET_STATUS_CONFIG_TOPICS, null);
    statusConfigTopics.createLeafChild(FLEET_STATUS_PERIODIC_PUBLISH_INTERVAL_SEC).withValue("10000");
    Topics allComponentToGroupsTopics = Topics.of(context, GROUP_TO_ROOT_COMPONENTS_TOPICS, null);
    Topics groupsTopics = Topics.of(context, "MockService", allComponentToGroupsTopics);
    Topics groupsTopics2 = Topics.of(context, "MockService2", allComponentToGroupsTopics);
    Topic groupTopic1 = Topic.of(context, "arn:aws:greengrass:testRegion:12345:configuration:testGroup:12", true);
    groupsTopics.children.put(new CaseInsensitiveString("MockService"), groupTopic1);
    groupsTopics2.children.put(new CaseInsensitiveString("MockService2"), groupTopic1);
    allComponentToGroupsTopics.children.put(new CaseInsensitiveString("MockService"), groupsTopics);
    allComponentToGroupsTopics.children.put(new CaseInsensitiveString("MockService2"), groupsTopics2);
    lenient().when(config.lookupTopics(COMPONENTS_TO_GROUPS_TOPICS)).thenReturn(allComponentToGroupsTopics);
    // Set up all the mocks
    when(mockDeploymentStatusKeeper.registerDeploymentStatusConsumer(any(), consumerArgumentCaptor.capture(), anyString())).thenReturn(true);
    when(mockGreengrassService1.getName()).thenReturn("MockService");
    when(mockGreengrassService1.getServiceConfig()).thenReturn(config);
    when(mockGreengrassService1.getState()).thenReturn(State.RUNNING);
    when(mockGreengrassService2.getName()).thenReturn("MockService2");
    when(mockGreengrassService2.getServiceConfig()).thenReturn(config);
    when(mockGreengrassService2.getState()).thenReturn(State.RUNNING);
    when(mockKernel.locate("MockService")).thenReturn(mockGreengrassService1);
    when(mockKernel.locate("MockService2")).thenReturn(mockGreengrassService2);
    when(mockKernel.locate(DeploymentService.DEPLOYMENT_SERVICE_TOPICS)).thenReturn(mockDeploymentService);
    when(mockKernel.orderedDependencies()).thenReturn(Arrays.asList(mockGreengrassService1, mockGreengrassService2));
    when(mockDeploymentService.getConfig()).thenReturn(config);
    doNothing().when(context).addGlobalStateChangeListener(addGlobalStateChangeListenerArgumentCaptor.capture());
    when(mockDeviceConfiguration.getStatusConfigurationTopics()).thenReturn(statusConfigTopics);
    when(context.get(ScheduledExecutorService.class)).thenReturn(ses);
    doNothing().when(mockMqttClient).addToCallbackEvents(mqttClientConnectionEventsArgumentCaptor.capture());
    // Create the fleet status service instance
    fleetStatusService = createFSS();
    fleetStatusService.startup();
    // Update the job status for an ongoing deployment to SUCCEEDED.
    Map<String, Object> map = new HashMap<>();
    map.put(DEPLOYMENT_STATUS_KEY_NAME, JobStatus.IN_PROGRESS.toString());
    map.put(DEPLOYMENT_ID_KEY_NAME, "testJob");
    consumerArgumentCaptor.getValue().apply(map);
    mqttClientConnectionEventsArgumentCaptor.getValue().onConnectionInterrupted(500);
    // Update the state of an EG service.
    addGlobalStateChangeListenerArgumentCaptor.getValue().globalServiceStateChanged(mockGreengrassService1, State.INSTALLED, State.RUNNING);
    addGlobalStateChangeListenerArgumentCaptor.getValue().globalServiceStateChanged(mockGreengrassService2, State.INSTALLED, State.RUNNING);
    // Update the job status for an ongoing deployment to SUCCEEDED.
    map.put(DEPLOYMENT_STATUS_KEY_NAME, JobStatus.SUCCEEDED.toString());
    consumerArgumentCaptor.getValue().apply(map);
    mqttClientConnectionEventsArgumentCaptor.getValue().onConnectionResumed(false);
    Thread.sleep(300);
    // Verify that an MQTT message with the components' status is uploaded.
    verify(mockMqttClient, atLeast(1)).publish(publishRequestArgumentCaptor.capture());
    Set<String> serviceNamesToCheck = new HashSet<>();
    serviceNamesToCheck.add("MockService");
    serviceNamesToCheck.add("MockService2");
    List<PublishRequest> publishRequests = publishRequestArgumentCaptor.getAllValues();
    ObjectMapper mapper = new ObjectMapper();
    for (PublishRequest publishRequest : publishRequests) {
        assertEquals(QualityOfService.AT_LEAST_ONCE, publishRequest.getQos());
        assertEquals("$aws/things/testThing/greengrassv2/health/json", publishRequest.getTopic());
        FleetStatusDetails fleetStatusDetails = mapper.readValue(publishRequest.getPayload(), FleetStatusDetails.class);
        assertEquals(VERSION, fleetStatusDetails.getGgcVersion());
        assertEquals("testThing", fleetStatusDetails.getThing());
        assertEquals(OverallStatus.HEALTHY, fleetStatusDetails.getOverallStatus());
        assertEquals(2, fleetStatusDetails.getComponentStatusDetails().size());
        for (ComponentStatusDetails componentStatusDetails : fleetStatusDetails.getComponentStatusDetails()) {
            serviceNamesToCheck.remove(componentStatusDetails.getComponentName());
            assertNull(componentStatusDetails.getStatusDetails());
            assertEquals(State.RUNNING, componentStatusDetails.getState());
            assertEquals(Collections.singletonList("arn:aws:greengrass:testRegion:12345:configuration:testGroup:12"), componentStatusDetails.getFleetConfigArns());
        }
    }
    assertThat(serviceNamesToCheck, is(IsEmptyCollection.empty()));
}
Also used : Topics(com.aws.greengrass.config.Topics) HashMap(java.util.HashMap) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) PublishRequest(com.aws.greengrass.mqttclient.PublishRequest) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) Topic(com.aws.greengrass.config.Topic) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

PublishRequest (com.aws.greengrass.mqttclient.PublishRequest)18 Test (org.junit.jupiter.api.Test)15 Topics (com.aws.greengrass.config.Topics)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)9 CaseInsensitiveString (com.aws.greengrass.config.CaseInsensitiveString)8 HashMap (java.util.HashMap)8 Topic (com.aws.greengrass.config.Topic)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 FleetStatusDetails (com.aws.greengrass.status.FleetStatusDetails)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)3 HashSet (java.util.HashSet)3 PublishToIoTCoreRequest (software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreRequest)3 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)2 Kernel (com.aws.greengrass.lifecyclemanager.Kernel)2 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)2 UnrecognizedPropertyException (com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 CompletableFuture (java.util.concurrent.CompletableFuture)2