Search in sources :

Example 1 with WINDOWS_USER_KEY

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

the class DeploymentTaskIntegrationTest method GIVEN_a_deployment_with_runwith_config_WHEN_submitted_THEN_runwith_updated.

/**
 * Start a service running with a user, then deploy an update to change the user and ensure the correct user stops
 * the process and starts the new one.
 */
@Test
// deploy before tests that break services
@Order(9)
void GIVEN_a_deployment_with_runwith_config_WHEN_submitted_THEN_runwith_updated() throws Exception {
    ((Map) kernel.getContext().getvIfExists(Kernel.SERVICE_TYPE_TO_CLASS_MAP_KEY).get()).put("plugin", GreengrassService.class.getName());
    countDownLatch = new CountDownLatch(2);
    // Set up stdout listener to capture stdout for verifying users
    List<String> stdouts = new CopyOnWriteArrayList<>();
    Consumer<GreengrassLogMessage> listener = m -> {
        String messageOnStdout = m.getMessage();
        if (messageOnStdout != null && messageOnStdout.contains("with user")) {
            stdouts.add(messageOnStdout);
            countDownLatch.countDown();
        }
    };
    final boolean isWindows = PlatformResolver.isWindows;
    final String currentUser = System.getProperty("user.name");
    final String posixDefaultUser = "nobody";
    final String posixPrivilegedUser = "root";
    final String testServiceName = "CustomerAppStartupShutdown";
    try (AutoCloseable ignored = TestUtils.createCloseableLogListener(listener)) {
        /*
             * 1st deployment. Default Config.
             */
        Future<DeploymentResult> resultFuture = submitSampleJobDocument(DeploymentTaskIntegrationTest.class.getResource("SampleJobDocumentWithUser_1.json").toURI(), System.currentTimeMillis());
        resultFuture.get(10, TimeUnit.SECONDS);
        // verify configs
        String posixUser = Coerce.toString(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, POSIX_USER_KEY));
        String windowsUser = Coerce.toString(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, WINDOWS_USER_KEY));
        assertEquals("nobody", posixUser);
        assertEquals(WINDOWS_TEST_UESRNAME, windowsUser);
        long memory = Coerce.toLong(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, SYSTEM_RESOURCE_LIMITS_TOPICS, "memory"));
        assertEquals(1024000, memory);
        double cpus = Coerce.toDouble(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, SYSTEM_RESOURCE_LIMITS_TOPICS, "cpus"));
        assertEquals(1.5, cpus);
        // verify user
        countDownLatch.await(10, TimeUnit.SECONDS);
        // Install has RequiresPrivilege. On Windows, expect current user is the privileged user
        if (isWindows) {
            assertThat(stdouts, hasItem(containsString("installing app with user " + currentUser)));
            assertThat(stdouts, hasItem(containsString("starting app with user " + WINDOWS_TEST_UESRNAME)));
        } else {
            assertThat(stdouts, hasItem(containsString("installing app with user " + posixPrivilegedUser)));
            assertThat(stdouts, hasItem(containsString("starting app with user " + posixDefaultUser)));
        }
        stdouts.clear();
    }
    /*
         * 2nd deployment. Change user
         */
    countDownLatch = new CountDownLatch(3);
    // update component to runas the user running the test
    String doc = Utils.inputStreamToString(DeploymentTaskIntegrationTest.class.getResource("SampleJobDocumentWithUser_2.json").openStream());
    // Set posixUser to currentUser. Set windowsUser to alternative test user
    doc = String.format(doc, currentUser, WINDOWS_TEST_UESRNAME_2);
    File f = File.createTempFile("user-deployment", ".json");
    f.deleteOnExit();
    Files.write(f.toPath(), doc.getBytes(StandardCharsets.UTF_8));
    try (AutoCloseable ignored = TestUtils.createCloseableLogListener(listener)) {
        Future<DeploymentResult> resultFuture = submitSampleJobDocument(f.toURI(), System.currentTimeMillis());
        resultFuture.get(DEPLOYMENT_TIMEOUT, TimeUnit.SECONDS);
        String posixUser = Coerce.toString(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, POSIX_USER_KEY));
        String windowsUser = Coerce.toString(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, WINDOWS_USER_KEY));
        assertEquals(currentUser, posixUser);
        assertEquals(WINDOWS_TEST_UESRNAME_2, windowsUser);
        countDownLatch.await(10, TimeUnit.SECONDS);
        if (isWindows) {
            assertThat(stdouts, hasItem(containsString("stopping app with user " + WINDOWS_TEST_UESRNAME)));
            assertThat(stdouts, hasItem(containsString("installing app with user " + currentUser)));
            assertThat(stdouts, hasItem(containsString("starting app with user " + WINDOWS_TEST_UESRNAME_2)));
        } else {
            assertThat(stdouts, hasItem(containsString("stopping app with user " + posixDefaultUser)));
            assertThat(stdouts, hasItem(containsString("installing app with user " + posixPrivilegedUser)));
            assertThat(stdouts, hasItem(containsString("starting app with user " + currentUser)));
        }
        stdouts.clear();
    }
    /*
         * 3rd deployment. Set runWith user to null and use default
         */
    countDownLatch = new CountDownLatch(3);
    // update component to runas the user running the test
    try (AutoCloseable ignored = TestUtils.createCloseableLogListener(listener)) {
        Future<DeploymentResult> resultFuture = submitSampleJobDocument(DeploymentTaskIntegrationTest.class.getResource("SampleJobDocumentRemovingUser.json").toURI(), System.currentTimeMillis());
        resultFuture.get(10, TimeUnit.SECONDS);
        String posixUser = Coerce.toString(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, POSIX_USER_KEY));
        String windowsUser = Coerce.toString(kernel.findServiceTopic(testServiceName).find(RUN_WITH_NAMESPACE_TOPIC, WINDOWS_USER_KEY));
        assertThat(posixUser, is(nullValue()));
        assertThat(windowsUser, is(nullValue()));
        // Assert fall back to runWithDefault
        countDownLatch.await(10, TimeUnit.SECONDS);
        if (isWindows) {
            assertThat(stdouts, hasItem(containsString("stopping app with user " + WINDOWS_TEST_UESRNAME_2)));
            assertThat(stdouts, hasItem(containsString("installing app with user " + currentUser)));
            assertThat(stdouts, hasItem(containsString("starting app with user " + WINDOWS_TEST_UESRNAME)));
        } else {
            assertThat(stdouts, hasItem(containsString("stopping app with user " + currentUser)));
            assertThat(stdouts, hasItem(containsString("installing app with user " + posixPrivilegedUser)));
            assertThat(stdouts, hasItem(containsString("starting app with user " + posixDefaultUser)));
        }
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Matchers.not(org.hamcrest.Matchers.not) GROUP_TO_ROOT_COMPONENTS_TOPICS(com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS) ComponentUpdatePolicyEvents(software.amazon.awssdk.aws.greengrass.model.ComponentUpdatePolicyEvents) SubscribeToComponentUpdatesResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse) AfterAll(org.junit.jupiter.api.AfterAll) IPCTestUtils(com.aws.greengrass.integrationtests.ipc.IPCTestUtils) Future(java.util.concurrent.Future) BeforeAll(org.junit.jupiter.api.BeforeAll) GenericExternalService(com.aws.greengrass.lifecyclemanager.GenericExternalService) Duration(java.time.Duration) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) LogManager(com.aws.greengrass.logging.impl.LogManager) StreamResponseHandler(software.amazon.awssdk.eventstreamrpc.StreamResponseHandler) Path(java.nio.file.Path) DependencyResolver(com.aws.greengrass.componentmanager.DependencyResolver) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) Set(java.util.Set) Utils.copyFolderRecursively(com.aws.greengrass.util.Utils.copyFolderRecursively) ExceptionLogProtector.ignoreExceptionOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionOfType) DeferComponentUpdateRequest(software.amazon.awssdk.aws.greengrass.model.DeferComponentUpdateRequest) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) CountDownLatch(java.util.concurrent.CountDownLatch) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Matchers.is(org.hamcrest.Matchers.is) DeploymentService(com.aws.greengrass.deployment.DeploymentService) Matchers.containsString(org.hamcrest.Matchers.containsString) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) PreloadComponentStoreHelper(com.aws.greengrass.helper.PreloadComponentStoreHelper) POSIX_USER_KEY(com.aws.greengrass.lifecyclemanager.GreengrassService.POSIX_USER_KEY) DeploymentDirectoryManager(com.aws.greengrass.deployment.DeploymentDirectoryManager) SYSTEM_RESOURCE_LIMITS_TOPICS(com.aws.greengrass.lifecyclemanager.GreengrassService.SYSTEM_RESOURCE_LIMITS_TOPICS) GROUP_TO_ROOT_COMPONENTS_VERSION_KEY(com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY) FileMatchers.anExistingDirectory(org.hamcrest.io.FileMatchers.anExistingDirectory) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) Coerce(com.aws.greengrass.util.Coerce) WINDOWS_USER_KEY(com.aws.greengrass.lifecyclemanager.GreengrassService.WINDOWS_USER_KEY) ComponentManager(com.aws.greengrass.componentmanager.ComponentManager) SudoUtil.assumeCanSudoShell(com.aws.greengrass.testcommons.testutilities.SudoUtil.assumeCanSudoShell) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) REPLACE_EXISTING(java.nio.file.StandardCopyOption.REPLACE_EXISTING) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) TestMethodOrder(org.junit.jupiter.api.TestMethodOrder) Files(java.nio.file.Files) IOException(java.io.IOException) File(java.io.File) AfterEach(org.junit.jupiter.api.AfterEach) Matchers.hasItem(org.hamcrest.Matchers.hasItem) Paths(java.nio.file.Paths) ServiceUpdateException(com.aws.greengrass.deployment.exceptions.ServiceUpdateException) KernelConfigResolver(com.aws.greengrass.componentmanager.KernelConfigResolver) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) IsMapWithSize(org.hamcrest.collection.IsMapWithSize) Logger(com.aws.greengrass.logging.api.Logger) PackageLoadingException(com.aws.greengrass.componentmanager.exceptions.PackageLoadingException) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) URISyntaxException(java.net.URISyntaxException) Deployment(com.aws.greengrass.deployment.model.Deployment) Order(org.junit.jupiter.api.Order) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) DEFAULT_NUCLEUS_COMPONENT_NAME(com.aws.greengrass.deployment.DeviceConfiguration.DEFAULT_NUCLEUS_COMPONENT_NAME) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) State(com.aws.greengrass.dependency.State) BaseITCase(com.aws.greengrass.integrationtests.BaseITCase) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT(com.aws.greengrass.deployment.model.Deployment.DeploymentStage.DEFAULT) DeploymentDocument(com.aws.greengrass.deployment.model.DeploymentDocument) URI(java.net.URI) TestUtils(com.aws.greengrass.testcommons.testutilities.TestUtils) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) DeploymentDocumentDownloader(com.aws.greengrass.deployment.DeploymentDocumentDownloader) Optional(java.util.Optional) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) DeploymentConfigMerger(com.aws.greengrass.deployment.DeploymentConfigMerger) ConfigPlatformResolver(com.aws.greengrass.integrationtests.util.ConfigPlatformResolver) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ThingGroupHelper(com.aws.greengrass.deployment.ThingGroupHelper) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Semver(com.vdurmont.semver4j.Semver) PackageDownloadException(com.aws.greengrass.componentmanager.exceptions.PackageDownloadException) PlatformResolver(com.aws.greengrass.config.PlatformResolver) ExecutorService(java.util.concurrent.ExecutorService) RUN_WITH_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.RUN_WITH_NAMESPACE_TOPIC) ImmutableMap(software.amazon.awssdk.utils.ImmutableMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Matchers(org.hamcrest.Matchers) ExceptionLogProtector.ignoreExceptionUltimateCauseOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionUltimateCauseOfType) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) SubscribeToComponentUpdatesRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesRequest) FileMatchers.anExistingFile(org.hamcrest.io.FileMatchers.anExistingFile) MethodOrderer(org.junit.jupiter.api.MethodOrderer) IsMapContaining(org.hamcrest.collection.IsMapContaining) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Slf4jLogAdapter(com.aws.greengrass.logging.impl.Slf4jLogAdapter) Utils(com.aws.greengrass.util.Utils) NoOpPathOwnershipHandler(com.aws.greengrass.testcommons.testutilities.NoOpPathOwnershipHandler) DefaultDeploymentTask(com.aws.greengrass.deployment.DefaultDeploymentTask) Collections(java.util.Collections) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) Matchers.containsString(org.hamcrest.Matchers.containsString) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) CountDownLatch(java.util.concurrent.CountDownLatch) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Map(java.util.Map) HashMap(java.util.HashMap) ImmutableMap(software.amazon.awssdk.utils.ImmutableMap) File(java.io.File) FileMatchers.anExistingFile(org.hamcrest.io.FileMatchers.anExistingFile) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TestMethodOrder(org.junit.jupiter.api.TestMethodOrder) Order(org.junit.jupiter.api.Order) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Test(org.junit.jupiter.api.Test)

Aggregations

ComponentManager (com.aws.greengrass.componentmanager.ComponentManager)1 ComponentStore (com.aws.greengrass.componentmanager.ComponentStore)1 DependencyResolver (com.aws.greengrass.componentmanager.DependencyResolver)1 KernelConfigResolver (com.aws.greengrass.componentmanager.KernelConfigResolver)1 PackageDownloadException (com.aws.greengrass.componentmanager.exceptions.PackageDownloadException)1 PackageLoadingException (com.aws.greengrass.componentmanager.exceptions.PackageLoadingException)1 ComponentIdentifier (com.aws.greengrass.componentmanager.models.ComponentIdentifier)1 PlatformResolver (com.aws.greengrass.config.PlatformResolver)1 Topics (com.aws.greengrass.config.Topics)1 State (com.aws.greengrass.dependency.State)1 DefaultDeploymentTask (com.aws.greengrass.deployment.DefaultDeploymentTask)1 DeploymentConfigMerger (com.aws.greengrass.deployment.DeploymentConfigMerger)1 DeploymentDirectoryManager (com.aws.greengrass.deployment.DeploymentDirectoryManager)1 DeploymentDocumentDownloader (com.aws.greengrass.deployment.DeploymentDocumentDownloader)1 DeploymentService (com.aws.greengrass.deployment.DeploymentService)1 GROUP_TO_ROOT_COMPONENTS_TOPICS (com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS)1 GROUP_TO_ROOT_COMPONENTS_VERSION_KEY (com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY)1 DEFAULT_NUCLEUS_COMPONENT_NAME (com.aws.greengrass.deployment.DeviceConfiguration.DEFAULT_NUCLEUS_COMPONENT_NAME)1 ThingGroupHelper (com.aws.greengrass.deployment.ThingGroupHelper)1 ServiceUpdateException (com.aws.greengrass.deployment.exceptions.ServiceUpdateException)1