Search in sources :

Example 1 with DeviceConfiguration

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

the class DeviceProvisioningHelper method updateKernelConfigWithIotConfiguration.

/**
 * Update the kernel config with iot thing info, in specific CA, private Key and cert path.
 *
 * @param kernel        Kernel instance
 * @param thing         thing info
 * @param awsRegion     aws region
 * @param roleAliasName role alias for using IoT credentials endpoint
 * @throws IOException                  Exception while reading root CA from file
 * @throws DeviceConfigurationException when the configuration parameters are not valid
 */
public void updateKernelConfigWithIotConfiguration(Kernel kernel, ThingInfo thing, String awsRegion, String roleAliasName) throws IOException, DeviceConfigurationException {
    Path rootDir = kernel.getNucleusPaths().rootPath();
    Path caFilePath = rootDir.resolve("rootCA.pem");
    Path privKeyFilePath = rootDir.resolve("privKey.key");
    Path certFilePath = rootDir.resolve("thingCert.crt");
    downloadRootCAToFile(caFilePath.toFile());
    try (CommitableFile cf = CommitableFile.of(privKeyFilePath, true)) {
        cf.write(thing.keyPair.privateKey().getBytes(StandardCharsets.UTF_8));
    }
    try (CommitableFile cf = CommitableFile.of(certFilePath, true)) {
        cf.write(thing.certificatePem.getBytes(StandardCharsets.UTF_8));
    }
    new DeviceConfiguration(kernel, thing.thingName, thing.dataEndpoint, thing.credEndpoint, privKeyFilePath.toString(), certFilePath.toString(), caFilePath.toString(), awsRegion, roleAliasName);
    // Make sure tlog persists the device configuration
    kernel.getContext().waitForPublishQueueToClear();
    outStream.println("Created device configuration");
}
Also used : Path(java.nio.file.Path) CommitableFile(com.aws.greengrass.util.CommitableFile) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration)

Example 2 with DeviceConfiguration

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

the class LogManagerHelperTest method GIVEN_null_logger_config_WHEN_subscribe_THEN_correctly_reconfigures_all_loggers.

@Test
void GIVEN_null_logger_config_WHEN_subscribe_THEN_correctly_reconfigures_all_loggers() throws IOException {
    Topics rootConfigTopics = mock(Topics.class);
    when(rootConfigTopics.findOrDefault(any(), anyString(), anyString(), anyString())).thenReturn(new ArrayList<>());
    when(configuration.lookup(anyString(), anyString(), anyString())).thenReturn(mock(Topic.class));
    when(configuration.lookup(anyString(), anyString(), anyString(), anyString())).thenReturn(mock(Topic.class));
    when(configuration.getRoot()).thenReturn(rootConfigTopics);
    when(kernel.getConfig()).thenReturn(configuration);
    lenient().when(kernel.getNucleusPaths()).thenReturn(nucleusPaths);
    Topics topic = mock(Topics.class);
    Topics topics = Topics.of(mock(Context.class), SERVICES_NAMESPACE_TOPIC, mock(Topics.class));
    when(topic.subscribe(any())).thenReturn(topic);
    when(configuration.lookupTopics(anyString(), anyString(), anyString(), anyString())).thenReturn(topic);
    when(configuration.lookupTopics(anyString())).thenReturn(topics);
    when(configuration.lookupTopics(SERVICES_NAMESPACE_TOPIC, DEFAULT_NUCLEUS_COMPONENT_NAME, CONFIGURATION_CONFIG_KEY)).thenReturn(topics);
    when(configuration.lookupTopics(SYSTEM_NAMESPACE_KEY)).thenReturn(topics);
    new DeviceConfiguration(kernel);
    assertEquals(Level.INFO, LogManager.getRootLogConfiguration().getLevel());
    assertEquals("greengrass", LogManager.getRootLogConfiguration().getFileName());
    assertEquals(LogStore.CONSOLE, LogManager.getRootLogConfiguration().getStore());
    assertEquals(LogFormat.TEXT, LogManager.getRootLogConfiguration().getFormat());
    assertEquals(1024, LogManager.getRootLogConfiguration().getFileSizeKB());
    assertEquals(10240, LogManager.getRootLogConfiguration().getTotalLogStoreSizeKB());
    assertEquals(Level.TRACE, LogManager.getTelemetryConfig().getLevel());
    assertEquals(LogStore.CONSOLE, LogManager.getTelemetryConfig().getStore());
    assertEquals(LogFormat.JSON, LogManager.getTelemetryConfig().getFormat());
    assertEquals(1024, LogManager.getTelemetryConfig().getFileSizeKB());
    assertEquals(10240, LogManager.getTelemetryConfig().getTotalLogStoreSizeKB());
    verify(nucleusPaths, times(0)).setLoggerPath(any(Path.class));
}
Also used : Context(com.aws.greengrass.dependency.Context) Path(java.nio.file.Path) Topics(com.aws.greengrass.config.Topics) Topic(com.aws.greengrass.config.Topic) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Test(org.junit.jupiter.api.Test)

Example 3 with DeviceConfiguration

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

the class PlatformResolverTest method WHEN_platform_override_THEN_override_should_take_place.

@Test
void WHEN_platform_override_THEN_override_should_take_place() throws Exception {
    String platformOverrideConfig = "---\n" + "architecture: fooArch\n" + "key1: val1\n";
    Map<String, Object> platformOverrideMap = MAPPER.readValue(platformOverrideConfig, Map.class);
    try (Context context = new Context()) {
        Topics platformOverrideTopics = new Topics(context, DeviceConfiguration.PLATFORM_OVERRIDE_TOPIC, null);
        platformOverrideTopics.updateFromMap(platformOverrideMap, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.MERGE, 1));
        DeviceConfiguration deviceConfiguration = mock(DeviceConfiguration.class);
        when(deviceConfiguration.getPlatformOverrideTopic()).thenReturn(platformOverrideTopics);
        PlatformResolver platformResolver = new PlatformResolver(deviceConfiguration);
        Map<String, String> currentPlatform = platformResolver.getCurrentPlatform();
        assertThat(currentPlatform.get("key1"), equalTo("val1"));
        assertThat(currentPlatform.get(PlatformResolver.ARCHITECTURE_KEY), equalTo("fooArch"));
        // assert that non-overridden platform attributes exist
        assertThat(currentPlatform.containsKey(PlatformResolver.OS_KEY), equalTo(true));
    }
}
Also used : Context(com.aws.greengrass.dependency.Context) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Test(org.junit.jupiter.api.Test)

Example 4 with DeviceConfiguration

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

the class FleetStatusServiceSetupTest method GIVEN_kernel_deployment_WHEN_device_provisioning_completes_before_kernel_launches_and_is_changed_afterTHEN_thing_details_uploaded_to_cloud_exactly_once.

@Test
void GIVEN_kernel_deployment_WHEN_device_provisioning_completes_before_kernel_launches_and_is_changed_afterTHEN_thing_details_uploaded_to_cloud_exactly_once() throws Exception {
    deviceConfiguration = new DeviceConfiguration(kernel, "ThingName", "xxxxxx-ats.iot.us-east-1.amazonaws.com", "xxxxxx.credentials.iot.us-east-1.amazonaws.com", "privKeyFilePath", "certFilePath", "caFilePath", "us-east-1", "roleAliasName");
    kernel.getContext().put(DeviceConfiguration.class, deviceConfiguration);
    kernel.launch();
    assertThat(kernel.locate(FleetStatusService.FLEET_STATUS_SERVICE_TOPICS)::getState, eventuallyEval(is(State.RUNNING)));
    assertEquals("ThingName", Coerce.toString(deviceConfiguration.getThingName()));
    assertThat(() -> fleetStatusDetails.get(), eventuallyEval(notNullValue(), Duration.ofSeconds(30)));
    assertThat(() -> fleetStatusDetails.get().getThing(), eventuallyEval(is("ThingName"), Duration.ofSeconds(30)));
}
Also used : DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Test(org.junit.jupiter.api.Test)

Example 5 with DeviceConfiguration

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

the class IotJobsFleetStatusServiceTest method setupKernel.

@SuppressWarnings("PMD.CloseResource")
@BeforeEach
void setupKernel(ExtensionContext context) throws Exception {
    ignoreExceptionOfType(context, TLSAuthException.class);
    ignoreExceptionOfType(context, PackageDownloadException.class);
    ignoreExceptionUltimateCauseOfType(context, EOFException.class);
    ignoreExceptionUltimateCauseOfType(context, ResourceNotFoundException.class);
    CountDownLatch fssRunning = new CountDownLatch(1);
    CountDownLatch deploymentServiceRunning = new CountDownLatch(1);
    CompletableFuture<Void> cf = new CompletableFuture<>();
    cf.complete(null);
    lenient().when(mockIotJobsClientWrapper.PublishUpdateJobExecution(any(UpdateJobExecutionRequest.class), any(QualityOfService.class))).thenAnswer(invocationOnMock -> {
        verify(mockIotJobsClientWrapper, atLeastOnce()).SubscribeToUpdateJobExecutionAccepted(any(), eq(QualityOfService.AT_LEAST_ONCE), jobsAcceptedHandlerCaptor.capture());
        Consumer<UpdateJobExecutionResponse> jobResponseConsumer = jobsAcceptedHandlerCaptor.getValue();
        UpdateJobExecutionResponse mockJobExecutionResponse = mock(UpdateJobExecutionResponse.class);
        jobResponseConsumer.accept(mockJobExecutionResponse);
        return cf;
    });
    lenient().when(mqttClient.publish(any())).thenReturn(CompletableFuture.completedFuture(0));
    kernel = new Kernel();
    NoOpPathOwnershipHandler.register(kernel);
    ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, IotJobsFleetStatusServiceTest.class.getResource("onlyMain.yaml"));
    kernel.getContext().put(MqttClient.class, mqttClient);
    kernel.getContext().put(ThingGroupHelper.class, thingGroupHelper);
    // Mock out cloud communication
    GreengrassServiceClientFactory mgscf = mock(GreengrassServiceClientFactory.class);
    GreengrassV2DataClient mcf = mock(GreengrassV2DataClient.class);
    lenient().when(mcf.resolveComponentCandidates(any(ResolveComponentCandidatesRequest.class))).thenThrow(ResourceNotFoundException.class);
    lenient().when(mgscf.getGreengrassV2DataClient()).thenReturn(mcf);
    kernel.getContext().put(GreengrassServiceClientFactory.class, mgscf);
    componentNamesToCheck.clear();
    kernel.getContext().addGlobalStateChangeListener((service, oldState, newState) -> {
        if (service.getName().equals(FleetStatusService.FLEET_STATUS_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
            fssRunning.countDown();
        }
        if (service.getName().equals(DeploymentService.DEPLOYMENT_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
            deploymentServiceRunning.countDown();
            deploymentService = (DeploymentService) service;
            IotJobsHelper iotJobsHelper = deploymentService.getContext().get(IotJobsHelper.class);
            iotJobsHelper.setIotJobsClientWrapper(mockIotJobsClientWrapper);
        }
        componentNamesToCheck.add(service.getName());
    });
    // set required instances from context
    deviceConfiguration = new DeviceConfiguration(kernel, "ThingName", "xxxxxx-ats.iot.us-east-1.amazonaws.com", "xxxxxx.credentials.iot.us-east-1.amazonaws.com", "privKeyFilePath", "certFilePath", "caFilePath", "us-east-1", "roleAliasName");
    kernel.getContext().put(DeviceConfiguration.class, deviceConfiguration);
    // pre-load contents to package store
    Path localStoreContentPath = Paths.get(IotJobsFleetStatusServiceTest.class.getResource("local_store_content").toURI());
    PreloadComponentStoreHelper.preloadRecipesFromTestResourceDir(localStoreContentPath.resolve("recipes"), kernel.getNucleusPaths().recipePath());
    copyFolderRecursively(localStoreContentPath.resolve("artifacts"), kernel.getNucleusPaths().artifactPath(), REPLACE_EXISTING);
    kernel.launch();
    assertTrue(fssRunning.await(10, TimeUnit.SECONDS));
    assertTrue(deploymentServiceRunning.await(10, TimeUnit.SECONDS));
}
Also used : Path(java.nio.file.Path) UpdateJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse) GreengrassServiceClientFactory(com.aws.greengrass.util.GreengrassServiceClientFactory) CountDownLatch(java.util.concurrent.CountDownLatch) GreengrassV2DataClient(software.amazon.awssdk.services.greengrassv2data.GreengrassV2DataClient) CompletableFuture(java.util.concurrent.CompletableFuture) IotJobsHelper(com.aws.greengrass.deployment.IotJobsHelper) UpdateJobExecutionRequest(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) ResolveComponentCandidatesRequest(software.amazon.awssdk.services.greengrassv2data.model.ResolveComponentCandidatesRequest) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)39 Test (org.junit.jupiter.api.Test)28 Topics (com.aws.greengrass.config.Topics)25 Context (com.aws.greengrass.dependency.Context)21 IOException (java.io.IOException)20 BeforeEach (org.junit.jupiter.api.BeforeEach)20 CompletableFuture (java.util.concurrent.CompletableFuture)18 Configuration (com.aws.greengrass.config.Configuration)17 WhatHappened (com.aws.greengrass.config.WhatHappened)17 DEVICE_PARAM_AWS_REGION (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_AWS_REGION)17 DEVICE_PARAM_CERTIFICATE_FILE_PATH (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_CERTIFICATE_FILE_PATH)17 DEVICE_PARAM_IOT_DATA_ENDPOINT (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_IOT_DATA_ENDPOINT)17 DEVICE_PARAM_PRIVATE_KEY_PATH (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_PRIVATE_KEY_PATH)17 DEVICE_PARAM_ROOT_CA_PATH (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_ROOT_CA_PATH)17 DEVICE_PARAM_THING_NAME (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_THING_NAME)17 Spool (com.aws.greengrass.mqttclient.spool.Spool)17 GGExtension (com.aws.greengrass.testcommons.testutilities.GGExtension)17 TestUtils (com.aws.greengrass.testcommons.testutilities.TestUtils)17 StandardCharsets (java.nio.charset.StandardCharsets)17 ChildChanged (com.aws.greengrass.config.ChildChanged)16