Search in sources :

Example 1 with SERVICES_NAMESPACE_TOPIC

use of com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC 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 SERVICES_NAMESPACE_TOPIC

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

the class DeviceConfiguration method initNucleusComponentName.

/**
 * Get the Nucleus component name to lookup the configuration in the right place. If no component of type Nucleus
 * exists, create service config for the default Nucleus component.
 */
private String initNucleusComponentName() {
    Optional<CaseInsensitiveString> nucleusComponent = kernel.getConfig().lookupTopics(SERVICES_NAMESPACE_TOPIC).children.keySet().stream().filter(s -> ComponentType.NUCLEUS.name().equals(getComponentType(s.toString()))).findAny();
    String nucleusComponentName = nucleusComponent.isPresent() ? nucleusComponent.get().toString() : DEFAULT_NUCLEUS_COMPONENT_NAME;
    // Initialize default/inferred required config if it doesn't exist
    initializeNucleusComponentConfig(nucleusComponentName);
    return nucleusComponentName;
}
Also used : PackageLoadingException(com.aws.greengrass.componentmanager.exceptions.PackageLoadingException) SerializerFactory.getRecipeSerializer(com.amazon.aws.iot.greengrass.component.common.SerializerFactory.getRecipeSerializer) Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) LogStore(com.aws.greengrass.logging.impl.config.LogStore) Validator(com.aws.greengrass.config.Validator) ComponentConfigurationValidationException(com.aws.greengrass.deployment.exceptions.ComponentConfigurationValidationException) SERVICE_LIFECYCLE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_LIFECYCLE_NAMESPACE_TOPIC) LogFormat(com.aws.greengrass.logging.impl.config.LogFormat) Level(org.slf4j.event.Level) Map(java.util.Map) SETENV_CONFIG_NAMESPACE(com.aws.greengrass.lifecyclemanager.GreengrassService.SETENV_CONFIG_NAMESPACE) LogManager(com.aws.greengrass.logging.impl.LogManager) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) Node(com.aws.greengrass.config.Node) SERVICE_TYPE_TOPIC_KEY(com.aws.greengrass.lifecyclemanager.Kernel.SERVICE_TYPE_TOPIC_KEY) TLSAuthException(com.aws.greengrass.util.exceptions.TLSAuthException) Collectors(java.util.stream.Collectors) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) StandardCharsets(java.nio.charset.StandardCharsets) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) ChildChanged(com.aws.greengrass.config.ChildChanged) Objects(java.util.Objects) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) NucleusPaths(com.aws.greengrass.util.NucleusPaths) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) Optional(java.util.Optional) SecurityService(com.aws.greengrass.security.SecurityService) DefaultAwsRegionProviderChain(software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) VERSION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.VERSION_CONFIG_KEY) COPY_ATTRIBUTES(java.nio.file.StandardCopyOption.COPY_ATTRIBUTES) CONFIGURATION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.CONFIGURATION_CONFIG_KEY) Coerce(com.aws.greengrass.util.Coerce) AtomicReference(java.util.concurrent.atomic.AtomicReference) LogConfigUpdate(com.aws.greengrass.logging.impl.config.model.LogConfigUpdate) ArrayList(java.util.ArrayList) Platform(com.aws.greengrass.util.platforms.Platform) Inject(javax.inject.Inject) MAIN_SERVICE_NAME(com.aws.greengrass.lifecyclemanager.KernelCommandLine.MAIN_SERVICE_NAME) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) NOFOLLOW_LINKS(java.nio.file.LinkOption.NOFOLLOW_LINKS) Semver(com.vdurmont.semver4j.Semver) ManagementFactory(java.lang.management.ManagementFactory) Region(software.amazon.awssdk.regions.Region) DependencyProperties(com.amazon.aws.iot.greengrass.component.common.DependencyProperties) SERVICE_DEPENDENCIES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_DEPENDENCIES_NAMESPACE_TOPIC) REPLACE_EXISTING(java.nio.file.StandardCopyOption.REPLACE_EXISTING) FileSystemPermission(com.aws.greengrass.util.FileSystemPermission) Files(java.nio.file.Files) Permissions(com.aws.greengrass.util.Permissions) IOException(java.io.IOException) ComponentRecipe(com.aws.greengrass.componentmanager.models.ComponentRecipe) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) KeyManager(javax.net.ssl.KeyManager) Topic(com.aws.greengrass.config.Topic) ComponentType(com.amazon.aws.iot.greengrass.component.common.ComponentType) Utils(com.aws.greengrass.util.Utils) RecipeLoader(com.aws.greengrass.componentmanager.converter.RecipeLoader) WhatHappened(com.aws.greengrass.config.WhatHappened) Paths(java.nio.file.Paths) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) KernelAlternatives.locateCurrentKernelUnpackDir(com.aws.greengrass.lifecyclemanager.KernelAlternatives.locateCurrentKernelUnpackDir) DeviceConfigurationException(com.aws.greengrass.deployment.exceptions.DeviceConfigurationException) KernelConfigResolver(com.aws.greengrass.componentmanager.KernelConfigResolver) Collections(java.util.Collections) Logger(com.aws.greengrass.logging.api.Logger) DEFAULT_VALUE_TIMESTAMP(com.aws.greengrass.config.Topic.DEFAULT_VALUE_TIMESTAMP) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString)

Example 3 with SERVICES_NAMESPACE_TOPIC

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

the class DeviceConfiguration method persistInitialLaunchParams.

/**
 * Persist initial launch parameters of JVM options.
 *
 * @param kernelAlts KernelAlternatives instance
 */
void persistInitialLaunchParams(KernelAlternatives kernelAlts) {
    if (Files.exists(kernelAlts.getLaunchParamsPath())) {
        logger.atDebug().log("Nucleus launch parameters has already been set up");
        return;
    }
    // Persist initial Nucleus launch parameters
    try {
        String jvmOptions = ManagementFactory.getRuntimeMXBean().getInputArguments().stream().sorted().filter(s -> !s.startsWith(JVM_OPTION_ROOT_PATH)).collect(Collectors.joining(" "));
        kernel.getConfig().lookup(SERVICES_NAMESPACE_TOPIC, getNucleusComponentName(), CONFIGURATION_CONFIG_KEY, DEVICE_PARAM_JVM_OPTIONS).withNewerValue(DEFAULT_VALUE_TIMESTAMP + 1, jvmOptions);
        kernelAlts.writeLaunchParamsToFile(jvmOptions);
        logger.atInfo().log("Successfully setup Nucleus launch parameters");
    } catch (IOException e) {
        logger.atError().log("Unable to setup Nucleus launch parameters", e);
    }
}
Also used : PackageLoadingException(com.aws.greengrass.componentmanager.exceptions.PackageLoadingException) SerializerFactory.getRecipeSerializer(com.amazon.aws.iot.greengrass.component.common.SerializerFactory.getRecipeSerializer) Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) LogStore(com.aws.greengrass.logging.impl.config.LogStore) Validator(com.aws.greengrass.config.Validator) ComponentConfigurationValidationException(com.aws.greengrass.deployment.exceptions.ComponentConfigurationValidationException) SERVICE_LIFECYCLE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_LIFECYCLE_NAMESPACE_TOPIC) LogFormat(com.aws.greengrass.logging.impl.config.LogFormat) Level(org.slf4j.event.Level) Map(java.util.Map) SETENV_CONFIG_NAMESPACE(com.aws.greengrass.lifecyclemanager.GreengrassService.SETENV_CONFIG_NAMESPACE) LogManager(com.aws.greengrass.logging.impl.LogManager) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) Node(com.aws.greengrass.config.Node) SERVICE_TYPE_TOPIC_KEY(com.aws.greengrass.lifecyclemanager.Kernel.SERVICE_TYPE_TOPIC_KEY) TLSAuthException(com.aws.greengrass.util.exceptions.TLSAuthException) Collectors(java.util.stream.Collectors) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) StandardCharsets(java.nio.charset.StandardCharsets) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) ChildChanged(com.aws.greengrass.config.ChildChanged) Objects(java.util.Objects) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) NucleusPaths(com.aws.greengrass.util.NucleusPaths) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) Optional(java.util.Optional) SecurityService(com.aws.greengrass.security.SecurityService) DefaultAwsRegionProviderChain(software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) VERSION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.VERSION_CONFIG_KEY) COPY_ATTRIBUTES(java.nio.file.StandardCopyOption.COPY_ATTRIBUTES) CONFIGURATION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.CONFIGURATION_CONFIG_KEY) Coerce(com.aws.greengrass.util.Coerce) AtomicReference(java.util.concurrent.atomic.AtomicReference) LogConfigUpdate(com.aws.greengrass.logging.impl.config.model.LogConfigUpdate) ArrayList(java.util.ArrayList) Platform(com.aws.greengrass.util.platforms.Platform) Inject(javax.inject.Inject) MAIN_SERVICE_NAME(com.aws.greengrass.lifecyclemanager.KernelCommandLine.MAIN_SERVICE_NAME) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) NOFOLLOW_LINKS(java.nio.file.LinkOption.NOFOLLOW_LINKS) Semver(com.vdurmont.semver4j.Semver) ManagementFactory(java.lang.management.ManagementFactory) Region(software.amazon.awssdk.regions.Region) DependencyProperties(com.amazon.aws.iot.greengrass.component.common.DependencyProperties) SERVICE_DEPENDENCIES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_DEPENDENCIES_NAMESPACE_TOPIC) REPLACE_EXISTING(java.nio.file.StandardCopyOption.REPLACE_EXISTING) FileSystemPermission(com.aws.greengrass.util.FileSystemPermission) Files(java.nio.file.Files) Permissions(com.aws.greengrass.util.Permissions) IOException(java.io.IOException) ComponentRecipe(com.aws.greengrass.componentmanager.models.ComponentRecipe) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) KeyManager(javax.net.ssl.KeyManager) Topic(com.aws.greengrass.config.Topic) ComponentType(com.amazon.aws.iot.greengrass.component.common.ComponentType) Utils(com.aws.greengrass.util.Utils) RecipeLoader(com.aws.greengrass.componentmanager.converter.RecipeLoader) WhatHappened(com.aws.greengrass.config.WhatHappened) Paths(java.nio.file.Paths) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) KernelAlternatives.locateCurrentKernelUnpackDir(com.aws.greengrass.lifecyclemanager.KernelAlternatives.locateCurrentKernelUnpackDir) DeviceConfigurationException(com.aws.greengrass.deployment.exceptions.DeviceConfigurationException) KernelConfigResolver(com.aws.greengrass.componentmanager.KernelConfigResolver) Collections(java.util.Collections) Logger(com.aws.greengrass.logging.api.Logger) DEFAULT_VALUE_TIMESTAMP(com.aws.greengrass.config.Topic.DEFAULT_VALUE_TIMESTAMP) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) IOException(java.io.IOException)

Example 4 with SERVICES_NAMESPACE_TOPIC

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

the class Kernel method locateExternalPlugin.

@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.CloseResource" })
private Class<?> locateExternalPlugin(String name, Topics serviceRootTopics) throws ServiceLoadException {
    ComponentIdentifier componentId = ComponentIdentifier.fromServiceTopics(serviceRootTopics);
    Path pluginJar;
    try {
        pluginJar = nucleusPaths.artifactPath(componentId).resolve(componentId.getName() + JAR_FILE_EXTENSION);
    } catch (IOException e) {
        throw new ServiceLoadException(e);
    }
    if (!pluginJar.toFile().exists() || !pluginJar.toFile().isFile()) {
        throw new ServiceLoadException(String.format("Unable to find %s because %s does not exist", name, pluginJar));
    }
    Topic storedDigest = config.find(SERVICES_NAMESPACE_TOPIC, MAIN_SERVICE_NAME, GreengrassService.RUNTIME_STORE_NAMESPACE_TOPIC, SERVICE_DIGEST_TOPIC_KEY, componentId.toString());
    if (storedDigest == null || storedDigest.getOnce() == null) {
        logger.atError("plugin-load-error").kv(GreengrassService.SERVICE_NAME_KEY, name).log("Local external plugin is not supported by this greengrass version");
        throw new ServiceLoadException("Custom plugins is not supported by this greengrass version");
    }
    ComponentStore componentStore = context.get(ComponentStore.class);
    if (!componentStore.validateComponentRecipeDigest(componentId, Coerce.toString(storedDigest))) {
        logger.atError("plugin-load-error").kv(GreengrassService.SERVICE_NAME_KEY, name).log("Local plugin does not match the version in cloud!!");
        throw new ServiceLoadException("Plugin has been modified after it was downloaded");
    }
    Class<?> clazz;
    try {
        AtomicReference<Class<?>> classReference = new AtomicReference<>();
        EZPlugins ezPlugins = context.get(EZPlugins.class);
        ezPlugins.loadPlugin(pluginJar, (sc) -> sc.matchClassesWithAnnotation(ImplementsService.class, (c) -> {
            // Only use the class whose name matches what we want
            ImplementsService serviceImplementation = c.getAnnotation(ImplementsService.class);
            if (serviceImplementation.name().equals(name)) {
                if (classReference.get() != null) {
                    logger.atWarn().log("Multiple classes implementing service found in {} " + "for component {}. Using the first one found: {}", pluginJar, name, classReference.get());
                    return;
                }
                classReference.set(c);
            }
        }));
        clazz = classReference.get();
    } catch (Throwable e) {
        throw new ServiceLoadException(String.format("Unable to load %s as a plugin", name), e);
    }
    if (clazz == null) {
        throw new ServiceLoadException(String.format("Unable to find %s. Could not find any ImplementsService annotation with the same name.", name));
    }
    return clazz;
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) Deployment(com.aws.greengrass.deployment.model.Deployment) SERVICE_LIFECYCLE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_LIFECYCLE_NAMESPACE_TOPIC) BootstrapManager(com.aws.greengrass.deployment.bootstrap.BootstrapManager) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) Map(java.util.Map) LogManager(com.aws.greengrass.logging.impl.LogManager) DeploymentCapability(com.amazon.aws.iot.greengrass.configuration.common.DeploymentCapability) Path(java.nio.file.Path) Configuration(com.aws.greengrass.config.Configuration) Node(com.aws.greengrass.config.Node) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Pair(com.aws.greengrass.util.Pair) Executors(java.util.concurrent.Executors) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) Topics(com.aws.greengrass.config.Topics) CrashableFunction(com.aws.greengrass.util.CrashableFunction) NucleusPaths(com.aws.greengrass.util.NucleusPaths) List(java.util.List) Writer(java.io.Writer) ImplementsService(com.aws.greengrass.dependency.ImplementsService) CommitableWriter(com.aws.greengrass.util.CommitableWriter) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) ProxyUtils(com.aws.greengrass.util.ProxyUtils) DependencyOrder(com.aws.greengrass.util.DependencyOrder) Setter(lombok.Setter) DeploymentDirectoryManager(com.aws.greengrass.deployment.DeploymentDirectoryManager) VERSION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.VERSION_CONFIG_KEY) Getter(lombok.Getter) InputValidationException(com.aws.greengrass.lifecyclemanager.exceptions.InputValidationException) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) EZPlugins(com.aws.greengrass.dependency.EZPlugins) DeploymentQueue(com.aws.greengrass.deployment.DeploymentQueue) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Coerce(com.aws.greengrass.util.Coerce) Constructor(java.lang.reflect.Constructor) AtomicReference(java.util.concurrent.atomic.AtomicReference) Platform(com.aws.greengrass.util.platforms.Platform) HashSet(java.util.HashSet) MAIN_SERVICE_NAME(com.aws.greengrass.lifecyclemanager.KernelCommandLine.MAIN_SERVICE_NAME) AccessLevel(lombok.AccessLevel) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) JAR_FILE_EXTENSION(com.aws.greengrass.dependency.EZPlugins.JAR_FILE_EXTENSION) Context(com.aws.greengrass.dependency.Context) REQUEST_REBOOT(com.aws.greengrass.deployment.bootstrap.BootstrapSuccessCode.REQUEST_REBOOT) REQUEST_RESTART(com.aws.greengrass.deployment.bootstrap.BootstrapSuccessCode.REQUEST_RESTART) SERVICE_DEPENDENCIES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_DEPENDENCIES_NAMESPACE_TOPIC) LinkedHashSet(java.util.LinkedHashSet) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) DeploymentStage(com.aws.greengrass.deployment.model.Deployment.DeploymentStage) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) Files(java.nio.file.Files) Executor(java.util.concurrent.Executor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConfigurationWriter(com.aws.greengrass.config.ConfigurationWriter) IOException(java.io.IOException) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) Topic(com.aws.greengrass.config.Topic) Utils(com.aws.greengrass.util.Utils) DeploymentActivatorFactory(com.aws.greengrass.deployment.activator.DeploymentActivatorFactory) ServiceUpdateException(com.aws.greengrass.deployment.exceptions.ServiceUpdateException) DeviceConfigurationException(com.aws.greengrass.deployment.exceptions.DeviceConfigurationException) Clock(java.time.Clock) Collections(java.util.Collections) Logger(com.aws.greengrass.logging.api.Logger) DEFAULT_VALUE_TIMESTAMP(com.aws.greengrass.config.Topic.DEFAULT_VALUE_TIMESTAMP) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) EZPlugins(com.aws.greengrass.dependency.EZPlugins) ImplementsService(com.aws.greengrass.dependency.ImplementsService) Topic(com.aws.greengrass.config.Topic) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException)

Example 5 with SERVICES_NAMESPACE_TOPIC

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

the class AuthorizationPolicyParser method parseAllAuthorizationPolicies.

/**
 * Given a kernel object, construct and return a map of AuthorizationPolicy objects that may exist,
 * grouped into lists of the same destination component.
 * This is used only upon kernel startup, to initialize all policies.
 * Never returns null.
 *
 * @param kernel Kernel
 * @return {@Map} of {@String} keys and {@List} of {@AuthorizationPolicy}'s as values"
 */
public Map<String, List<AuthorizationPolicy>> parseAllAuthorizationPolicies(Kernel kernel) {
    Map<String, List<AuthorizationPolicy>> primaryAuthorizationPolicyMap = new HashMap<>();
    Topics allServices = kernel.getConfig().findTopics(SERVICES_NAMESPACE_TOPIC);
    if (allServices == null) {
        logger.atWarn("load-authorization-all-services-component-config-retrieval-error").log("Unable to retrieve services config");
        return primaryAuthorizationPolicyMap;
    }
    // For each component
    for (Node service : allServices) {
        if (service == null) {
            continue;
        }
        if (!(service instanceof Topics)) {
            continue;
        }
        Topics serviceConfig = (Topics) service;
        String componentName = Kernel.findServiceForNode(serviceConfig);
        Node accessControlMapTopic = serviceConfig.findNode(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
        if (accessControlMapTopic == null) {
            continue;
        }
        // Retrieve all policies, mapped to each policy type
        Map<String, List<AuthorizationPolicy>> componentAuthorizationPolicyMap = parseAllPoliciesForComponent(accessControlMapTopic, componentName);
        // For each policy type (e.g. aws.greengrass.ipc.pubsub)
        for (Map.Entry<String, List<AuthorizationPolicy>> policyTypeList : componentAuthorizationPolicyMap.entrySet()) {
            String policyType = policyTypeList.getKey();
            List<AuthorizationPolicy> policyList = policyTypeList.getValue();
            // If multiple components have policies for the same policy type
            primaryAuthorizationPolicyMap.computeIfAbsent(policyType, k -> new ArrayList<>()).addAll(policyList);
        }
    }
    return primaryAuthorizationPolicyMap;
}
Also used : Node(com.aws.greengrass.config.Node) CONFIGURATION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.CONFIGURATION_CONFIG_KEY) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) HashMap(java.util.HashMap) Coerce(com.aws.greengrass.util.Coerce) JsonMapper(com.fasterxml.jackson.databind.json.JsonMapper) SERVICES_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC) ArrayList(java.util.ArrayList) Topic(com.aws.greengrass.config.Topic) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) List(java.util.List) Utils(com.aws.greengrass.util.Utils) ACCESS_CONTROL_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.ACCESS_CONTROL_NAMESPACE_TOPIC) Map(java.util.Map) LogManager(com.aws.greengrass.logging.impl.LogManager) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Logger(com.aws.greengrass.logging.api.Logger) Topics(com.aws.greengrass.config.Topics) HashMap(java.util.HashMap) Node(com.aws.greengrass.config.Node) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

SERVICES_NAMESPACE_TOPIC (com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICES_NAMESPACE_TOPIC)10 Map (java.util.Map)10 Topics (com.aws.greengrass.config.Topics)9 Topic (com.aws.greengrass.config.Topic)8 IOException (java.io.IOException)8 List (java.util.List)8 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)7 Kernel (com.aws.greengrass.lifecyclemanager.Kernel)7 Arrays (java.util.Arrays)7 Collectors (java.util.stream.Collectors)6 DependencyType (com.amazon.aws.iot.greengrass.component.common.DependencyType)5 Coerce (com.aws.greengrass.util.Coerce)5 Node (com.aws.greengrass.config.Node)4 DEPLOYMENT_SERVICE_TOPICS (com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS)4 Logger (com.aws.greengrass.logging.api.Logger)4 LogManager (com.aws.greengrass.logging.impl.LogManager)4 Utils (com.aws.greengrass.util.Utils)4 Path (java.nio.file.Path)4 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4