Search in sources :

Example 46 with Kernel

use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.

the class PluginComponentTest method GIVEN_kernel_WHEN_deploy_updated_plugin_THEN_request_kernel_restart.

@Test
void GIVEN_kernel_WHEN_deploy_updated_plugin_THEN_request_kernel_restart(ExtensionContext context) throws Exception {
    ignoreExceptionOfType(context, PackageDownloadException.class);
    ignoreExceptionOfType(context, IOException.class);
    ignoreExceptionOfType(context, SdkClientException.class);
    Kernel kernelSpy = spy(kernel.parseArgs());
    setupPackageStoreAndConfigWithDigest();
    String deploymentId = "deployment1";
    KernelAlternatives kernelAltsSpy = spy(kernelSpy.getContext().get(KernelAlternatives.class));
    kernelSpy.getContext().put(KernelAlternatives.class, kernelAltsSpy);
    // In actual workflow, DeploymentService will setup deployment artifacts directory per deployment before
    // submitting task. Here in test, it's called explicitly because the directory is required by snapshot file.
    kernelSpy.getContext().get(DeploymentDirectoryManager.class).createNewDeploymentDirectory(deploymentId);
    kernelSpy.getContext().put(KernelUpdateActivator.class, new KernelUpdateActivator(kernelSpy, kernelSpy.getContext().get(BootstrapManager.class)));
    // launch Nucleus
    kernelSpy.launch();
    // Ensure that the dependency isn't somehow in our class loader already
    assertThrows(ClassNotFoundException.class, () -> Class.forName("com.aws.greengrass.integrationtests.lifecyclemanager.resource.PluginDependency"));
    // First deployment to add plugin-1.0.0 to kernel
    submitSampleJobDocument(getPluginDeploymentDocument(System.currentTimeMillis(), "1.0.0", deploymentId, FailureHandlingPolicy.DO_NOTHING, componentName), kernelSpy).get(30, TimeUnit.SECONDS);
    GreengrassService eg = kernelSpy.locate(componentName);
    assertEquals("com.aws.greengrass.integrationtests.lifecyclemanager.resource.APluginService", eg.getClass().getName());
    assertEquals(componentId.getVersion().toString(), Coerce.toString(eg.getServiceConfig().findLeafChild(VERSION_CONFIG_KEY)));
    kernelSpy.getContext().get(EZPlugins.class).forName("com.aws.greengrass.integrationtests.lifecyclemanager.resource.PluginDependency");
    // setup again because local files removed by cleanup in the previous deployment
    setupPackageStoreAndConfigWithDigest();
    String deploymentId2 = "deployment2";
    // No need to actually verify directory setup or make directory changes here.
    doReturn(true).when(kernelAltsSpy).isLaunchDirSetup();
    doNothing().when(kernelAltsSpy).prepareBootstrap(eq(deploymentId2));
    doNothing().when(kernelSpy).shutdown(anyInt(), eq(REQUEST_RESTART));
    // Second deployment to add plugin-1.1.0 to kernel which should enter kernel restart workflow
    assertThrows(TimeoutException.class, () -> submitSampleJobDocument(getPluginDeploymentDocument(System.currentTimeMillis(), "1.1.0", deploymentId2, FailureHandlingPolicy.DO_NOTHING, componentName), kernelSpy).get(10, TimeUnit.SECONDS));
    verify(kernelSpy).shutdown(eq(30), eq(REQUEST_RESTART));
}
Also used : EZPlugins(com.aws.greengrass.dependency.EZPlugins) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) DeploymentDirectoryManager(com.aws.greengrass.deployment.DeploymentDirectoryManager) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) KernelUpdateActivator(com.aws.greengrass.deployment.activator.KernelUpdateActivator) Test(org.junit.jupiter.api.Test)

Example 47 with Kernel

use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.

the class GreengrassSetup method performSetup.

void performSetup() throws IOException, DeviceConfigurationException, URISyntaxException, InvalidEnvironmentStageException {
    // Describe usage of the command
    if (showHelp) {
        outStream.println(SHOW_HELP_RESPONSE);
        return;
    }
    if (showVersion) {
        // Use getVersionFromBuildMetadataFile so that we don't need to startup the Nucleus which is slow and will
        // start creating files and directories which may not be desired
        outStream.println(String.format(SHOW_VERSION_RESPONSE, DeviceConfiguration.getVersionFromBuildRecipeFile()));
        return;
    }
    if (kernel == null) {
        kernel = new Kernel();
    }
    kernel.parseArgs(kernelArgs.toArray(new String[] {}));
    try {
        IotSdkClientFactory.EnvironmentStage.fromString(environmentStage);
    } catch (InvalidEnvironmentStageException e) {
        throw new RuntimeException(e);
    }
    if (!Utils.isEmpty(trustedPluginPaths)) {
        copyTrustedPlugins(kernel, trustedPluginPaths);
    }
    DeviceConfiguration deviceConfiguration = kernel.getContext().get(DeviceConfiguration.class);
    if (needProvisioning) {
        if (Utils.isEmpty(awsRegion)) {
            awsRegion = Coerce.toString(deviceConfiguration.getAWSRegion());
        }
        if (Utils.isEmpty(awsRegion)) {
            throw new RuntimeException("Required input aws region not provided for provisioning");
        }
        this.deviceProvisioningHelper = new DeviceProvisioningHelper(awsRegion, environmentStage, this.outStream);
        provision(kernel);
    }
    // Attempt this only after config file and Nucleus args have been parsed
    setComponentDefaultUserAndGroup(deviceConfiguration);
    if (setupSystemService) {
        kernel.getContext().get(KernelLifecycle.class).softShutdown(30);
        boolean ok = kernel.getContext().get(SystemServiceUtilsFactory.class).getInstance().setupSystemService(kernel.getContext().get(KernelAlternatives.class));
        if (ok) {
            outStream.println("Successfully set up Nucleus as a system service");
        // Nucleus will be launched by OS as a service
        } else {
            outStream.println("Unable to set up Nucleus as a system service");
        }
        kernel.shutdown();
        return;
    }
    if (!kernelStart) {
        outStream.println("Nucleus start set to false, exiting...");
        kernel.shutdown();
        return;
    }
    outStream.println("Launching Nucleus...");
    kernel.launch();
    outStream.println("Launched Nucleus successfully.");
}
Also used : InvalidEnvironmentStageException(com.aws.greengrass.util.exceptions.InvalidEnvironmentStageException) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) KernelLifecycle(com.aws.greengrass.lifecyclemanager.KernelLifecycle) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration)

Example 48 with Kernel

use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.

the class MultiGroupDeploymentTest method before.

@BeforeEach
void before(ExtensionContext context) throws Exception {
    ignoreExceptionOfType(context, PackageDownloadException.class);
    ignoreExceptionOfType(context, SdkClientException.class);
    kernel = new Kernel();
    kernel.getContext().put(ThingGroupHelper.class, thingGroupHelper);
    NoOpPathOwnershipHandler.register(kernel);
    ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, DeploymentServiceIntegrationTest.class.getResource("onlyMain.yaml"));
    // ensure deployment service starts
    CountDownLatch deploymentServiceLatch = new CountDownLatch(1);
    kernel.getContext().addGlobalStateChangeListener((service, oldState, newState) -> {
        if (service.getName().equals(DEPLOYMENT_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
            deploymentServiceLatch.countDown();
        }
    });
    setDeviceConfig(kernel, DeviceConfiguration.DEPLOYMENT_POLLING_FREQUENCY_SECONDS, 1L);
    kernel.launch();
    assertTrue(deploymentServiceLatch.await(10, TimeUnit.SECONDS));
    deploymentQueue = kernel.getContext().get(DeploymentQueue.class);
    FleetStatusService fleetStatusService = (FleetStatusService) kernel.locate(FLEET_STATUS_SERVICE_TOPICS);
    fleetStatusService.getIsConnected().set(false);
    localStoreContentPath = Paths.get(DeploymentTaskIntegrationTest.class.getResource("local_store_content").toURI());
}
Also used : FleetStatusService(com.aws.greengrass.status.FleetStatusService) CountDownLatch(java.util.concurrent.CountDownLatch) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) DeploymentQueue(com.aws.greengrass.deployment.DeploymentQueue) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 49 with Kernel

use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.

the class TestUtils method createServiceStateChangeWaiter.

/**
 * Create a runnable that when run, will wait for a latch to countdown ensuring that a state change for the
 * service has occurred. The listener is added immediately. The latch waits when the runnable runs.
 *
 * @param kernel a kernel to monitor
 * @param serviceName the service to watch
 * @param timeoutSeconds the time to wait for the state change
 * @param state the state to watch for
 * @param prevState the previous state to transition from
 * @return a runnable that can be used for asserting that a state has been entered.
 */
public static Runnable createServiceStateChangeWaiter(Kernel kernel, String serviceName, long timeoutSeconds, State state, State prevState) {
    CountDownLatch latch = new CountDownLatch(1);
    GlobalStateChangeListener l = (service, oldState, newState) -> {
        if (service.getName().equals(serviceName) && newState.equals(state) && prevState == null || oldState.equals(prevState)) {
            latch.countDown();
        }
    };
    kernel.getContext().addGlobalStateChangeListener(l);
    return () -> {
        try {
            assertThat(String.format("%s in state %s", serviceName, state.getName()), latch.await(timeoutSeconds, TimeUnit.SECONDS), is(true));
        } catch (InterruptedException e) {
            fail(e);
        } finally {
            kernel.getContext().removeGlobalStateChangeListener(l);
        }
    };
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) AbstractExecutorService(java.util.concurrent.AbstractExecutorService) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) CompletableFuture(java.util.concurrent.CompletableFuture) Pair(com.aws.greengrass.util.Pair) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DEFAULT_NUCLEUS_COMPONENT_NAME(com.aws.greengrass.deployment.DeviceConfiguration.DEFAULT_NUCLEUS_COMPONENT_NAME) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) Slf4jLogAdapter(com.aws.greengrass.logging.impl.Slf4jLogAdapter) CountDownLatch(java.util.concurrent.CountDownLatch) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) List(java.util.List) GlobalStateChangeListener(com.aws.greengrass.lifecyclemanager.GlobalStateChangeListener) State(com.aws.greengrass.dependency.State) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) BiConsumer(java.util.function.BiConsumer) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) ExecutorService(java.util.concurrent.ExecutorService) GlobalStateChangeListener(com.aws.greengrass.lifecyclemanager.GlobalStateChangeListener) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

Kernel (com.aws.greengrass.lifecyclemanager.Kernel)49 CountDownLatch (java.util.concurrent.CountDownLatch)22 BeforeEach (org.junit.jupiter.api.BeforeEach)22 Test (org.junit.jupiter.api.Test)22 HashMap (java.util.HashMap)13 IOException (java.io.IOException)12 DeploymentConfigMerger (com.aws.greengrass.deployment.DeploymentConfigMerger)11 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)11 Map (java.util.Map)11 List (java.util.List)10 TimeUnit (java.util.concurrent.TimeUnit)10 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)10 State (com.aws.greengrass.dependency.State)9 DeploymentDocument (com.aws.greengrass.deployment.model.DeploymentDocument)9 BaseITCase (com.aws.greengrass.integrationtests.BaseITCase)9 ConfigPlatformResolver (com.aws.greengrass.integrationtests.util.ConfigPlatformResolver)9 TestUtils (com.aws.greengrass.testcommons.testutilities.TestUtils)9 Coerce (com.aws.greengrass.util.Coerce)9 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)9 LogManager (com.aws.greengrass.logging.impl.LogManager)8