Search in sources :

Example 16 with Topics

use of com.aws.greengrass.config.Topics in project aws-greengrass-nucleus by aws-greengrass.

the class IPCAuthorizationTest method GIVEN_authorizationClient_WHEN_valid_ondemand_lambda_token_provided_THEN_succeeds.

@Test
void GIVEN_authorizationClient_WHEN_valid_ondemand_lambda_token_provided_THEN_succeeds() {
    GreengrassService mockService = mock(GreengrassService.class);
    when(mockService.getServiceName()).thenReturn("ABCService");
    // Pretend to be instance #1 of a lambda
    lenient().when(mockService.getName()).thenReturn("ABCService#1");
    when(mockService.getServiceConfig()).thenReturn(kernel.findServiceTopic("ServiceName"));
    when(mockService.getPrivateConfig()).thenReturn(kernel.findServiceTopic("ServiceName").lookupTopics(PRIVATE_STORE_NAMESPACE_TOPIC));
    registerAuthenticationToken(mockService);
    Topics authTokensArray = kernel.findServiceTopic(AUTHENTICATION_TOKEN_LOOKUP_KEY);
    boolean found = false;
    for (Node node : authTokensArray) {
        if ("ABCService".equals(Coerce.toString(node))) {
            if (found) {
                fail("Duplicate entry!");
            }
            found = true;
        }
    }
    assertTrue(found);
}
Also used : Topics(com.aws.greengrass.config.Topics) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Node(com.aws.greengrass.config.Node) Test(org.junit.jupiter.api.Test)

Example 17 with Topics

use of com.aws.greengrass.config.Topics in project aws-greengrass-nucleus by aws-greengrass.

the class DeploymentService method getAllGroupNames.

/**
 * Gets the list of all the groups that the thing is a part of. This method is used by log manager.
 *
 * @return All the group configs.
 */
public Set<String> getAllGroupNames() {
    Topics componentsToGroupsTopics = config.lookupTopics(COMPONENTS_TO_GROUPS_TOPICS);
    Set<String> allGroupNames = new HashSet<>();
    if (componentsToGroupsTopics != null) {
        componentsToGroupsTopics.iterator().forEachRemaining(node -> {
            Topics groupsTopics = (Topics) node;
            groupsTopics.children.values().stream().map(n -> (Topic) n).forEach(topic -> {
                String groupName = Coerce.toString(topic);
                if (!Utils.isEmpty(groupName)) {
                    allGroupNames.add(groupName);
                }
            });
        });
    }
    return allGroupNames;
}
Also used : PackageLoadingException(com.aws.greengrass.componentmanager.exceptions.PackageLoadingException) SerializerFactory.getRecipeSerializer(com.amazon.aws.iot.greengrass.component.common.SerializerFactory.getRecipeSerializer) SerializerFactory.getRecipeSerializerJson(com.amazon.aws.iot.greengrass.component.common.SerializerFactory.getRecipeSerializerJson) DeploymentDocumentConverter(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter) InvalidRequestException(com.aws.greengrass.deployment.exceptions.InvalidRequestException) THING_GROUP_RESOURCE_NAME_PREFIX(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter.THING_GROUP_RESOURCE_NAME_PREFIX) Deployment(com.aws.greengrass.deployment.model.Deployment) DeploymentTask(com.aws.greengrass.deployment.model.DeploymentTask) Future(java.util.concurrent.Future) DEVICE_DEPLOYMENT_GROUP_NAME_PREFIX(com.aws.greengrass.deployment.DefaultDeploymentTask.DEVICE_DEPLOYMENT_GROUP_NAME_PREFIX) State(com.aws.greengrass.dependency.State) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT(com.aws.greengrass.deployment.model.Deployment.DeploymentStage.DEFAULT) Duration(java.time.Duration) Map(java.util.Map) DeploymentDocument(com.aws.greengrass.deployment.model.DeploymentDocument) Path(java.nio.file.Path) DependencyResolver(com.aws.greengrass.componentmanager.DependencyResolver) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) Node(com.aws.greengrass.config.Node) CancellationException(java.util.concurrent.CancellationException) LocalOverrideRequest(com.aws.greengrass.deployment.model.LocalOverrideRequest) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LOCAL_DEPLOYMENT_GROUP_NAME(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter.LOCAL_DEPLOYMENT_GROUP_NAME) Set(java.util.Set) Collectors(java.util.stream.Collectors) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) List(java.util.List) Stream(java.util.stream.Stream) DeploymentTaskFailureException(com.aws.greengrass.deployment.exceptions.DeploymentTaskFailureException) DEPLOYMENT_ID_LOG_KEY(com.aws.greengrass.deployment.DeploymentConfigMerger.DEPLOYMENT_ID_LOG_KEY) ImplementsService(com.aws.greengrass.dependency.ImplementsService) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) SerializerFactory(com.aws.greengrass.util.SerializerFactory) Setter(lombok.Setter) VERSION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.VERSION_CONFIG_KEY) Getter(lombok.Getter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Configuration(com.amazon.aws.iot.greengrass.configuration.common.Configuration) UpdateSystemPolicyService(com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService) Coerce(com.aws.greengrass.util.Coerce) StandardCopyOption(java.nio.file.StandardCopyOption) HashSet(java.util.HashSet) Inject(javax.inject.Inject) ComponentManager(com.aws.greengrass.componentmanager.ComponentManager) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Context(com.aws.greengrass.dependency.Context) ComponentRecipe(com.amazon.aws.iot.greengrass.component.common.ComponentRecipe) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) PlatformResolver(com.aws.greengrass.config.PlatformResolver) ExecutorService(java.util.concurrent.ExecutorService) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) DeploymentType(com.aws.greengrass.deployment.model.Deployment.DeploymentType) Files(java.nio.file.Files) MissingRequiredCapabilitiesException(com.aws.greengrass.deployment.exceptions.MissingRequiredCapabilitiesException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Topic(com.aws.greengrass.config.Topic) AtomicLong(java.util.concurrent.atomic.AtomicLong) Utils(com.aws.greengrass.util.Utils) DeploymentTaskMetadata(com.aws.greengrass.deployment.model.DeploymentTaskMetadata) Paths(java.nio.file.Paths) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) FAILED_ROLLBACK_NOT_REQUESTED(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus.FAILED_ROLLBACK_NOT_REQUESTED) DeploymentStatus(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus) KernelConfigResolver(com.aws.greengrass.componentmanager.KernelConfigResolver) Logger(com.aws.greengrass.logging.api.Logger) Topics(com.aws.greengrass.config.Topics) Topic(com.aws.greengrass.config.Topic) HashSet(java.util.HashSet)

Example 18 with Topics

use of com.aws.greengrass.config.Topics in project aws-greengrass-nucleus by aws-greengrass.

the class DeploymentService method setComponentsToGroupsMapping.

void setComponentsToGroupsMapping(Topics groupsToRootComponents) {
    Set<String> pendingComponents = new HashSet<>();
    Map<String, Object> componentsToGroupsMappingCache = new ConcurrentHashMap<>();
    Topics componentsToGroupsTopics = getConfig().lookupTopics(COMPONENTS_TO_GROUPS_TOPICS);
    /*
         * Structure of COMPONENTS_TO_GROUPS_TOPICS is:
         * COMPONENTS_TO_GROUPS_TOPICS :
         * |_ <componentName> :
         *     |_ <deploymentID> : <GroupName>
         * This stores all the components with the list of deployment IDs associated to it along with the thing group
         * (if available) to be associated to the deployment.
         */
    // Get all the groups associated to the root components.
    groupsToRootComponents.forEach(groupNode -> ((Topics) groupNode).forEach(componentNode -> {
        Topics componentTopics = (Topics) componentNode;
        Topic groupConfigTopic = componentTopics.lookup(GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN);
        String groupConfig = Coerce.toString(groupConfigTopic);
        Topic groupNameTopic = componentTopics.lookup(GROUP_TO_ROOT_COMPONENTS_GROUP_NAME);
        String groupName = Coerce.toString(groupNameTopic);
        Map<String, Object> groupDeploymentIdSet = (Map<String, Object>) componentsToGroupsMappingCache.getOrDefault(componentTopics.getName(), new HashMap<>());
        groupDeploymentIdSet.putIfAbsent(groupConfig, groupName);
        componentsToGroupsMappingCache.put(componentTopics.getName(), groupDeploymentIdSet);
        pendingComponents.add(componentTopics.getName());
    }));
    // Associate the groups to the dependant services based on the services it is depending on.
    while (!pendingComponents.isEmpty()) {
        String componentName = pendingComponents.iterator().next();
        try {
            GreengrassService greengrassService = kernel.locate(componentName);
            Map<String, Object> groupNamesForComponent = (Map<String, Object>) componentsToGroupsMappingCache.getOrDefault(greengrassService.getName(), new HashMap<>());
            greengrassService.getDependencies().forEach((greengrassService1, dependencyType) -> {
                pendingComponents.add(greengrassService1.getName());
                Map<String, Object> groupNamesForDependentComponent = (Map<String, Object>) componentsToGroupsMappingCache.getOrDefault(greengrassService1.getName(), new HashMap<>());
                groupNamesForDependentComponent.putAll(groupNamesForComponent);
                componentsToGroupsMappingCache.put(greengrassService1.getName(), groupNamesForDependentComponent);
            });
        } catch (ServiceLoadException ex) {
            logger.atError().cause(ex).log("Unable to get status for {}.", componentName);
        }
        pendingComponents.remove(componentName);
    }
    if (componentsToGroupsTopics != null) {
        componentsToGroupsTopics.replaceAndWait(componentsToGroupsMappingCache);
    }
}
Also used : PackageLoadingException(com.aws.greengrass.componentmanager.exceptions.PackageLoadingException) SerializerFactory.getRecipeSerializer(com.amazon.aws.iot.greengrass.component.common.SerializerFactory.getRecipeSerializer) SerializerFactory.getRecipeSerializerJson(com.amazon.aws.iot.greengrass.component.common.SerializerFactory.getRecipeSerializerJson) DeploymentDocumentConverter(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter) InvalidRequestException(com.aws.greengrass.deployment.exceptions.InvalidRequestException) THING_GROUP_RESOURCE_NAME_PREFIX(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter.THING_GROUP_RESOURCE_NAME_PREFIX) Deployment(com.aws.greengrass.deployment.model.Deployment) DeploymentTask(com.aws.greengrass.deployment.model.DeploymentTask) Future(java.util.concurrent.Future) DEVICE_DEPLOYMENT_GROUP_NAME_PREFIX(com.aws.greengrass.deployment.DefaultDeploymentTask.DEVICE_DEPLOYMENT_GROUP_NAME_PREFIX) State(com.aws.greengrass.dependency.State) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT(com.aws.greengrass.deployment.model.Deployment.DeploymentStage.DEFAULT) Duration(java.time.Duration) Map(java.util.Map) DeploymentDocument(com.aws.greengrass.deployment.model.DeploymentDocument) Path(java.nio.file.Path) DependencyResolver(com.aws.greengrass.componentmanager.DependencyResolver) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) Node(com.aws.greengrass.config.Node) CancellationException(java.util.concurrent.CancellationException) LocalOverrideRequest(com.aws.greengrass.deployment.model.LocalOverrideRequest) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LOCAL_DEPLOYMENT_GROUP_NAME(com.aws.greengrass.deployment.converter.DeploymentDocumentConverter.LOCAL_DEPLOYMENT_GROUP_NAME) Set(java.util.Set) Collectors(java.util.stream.Collectors) Topics(com.aws.greengrass.config.Topics) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) List(java.util.List) Stream(java.util.stream.Stream) DeploymentTaskFailureException(com.aws.greengrass.deployment.exceptions.DeploymentTaskFailureException) DEPLOYMENT_ID_LOG_KEY(com.aws.greengrass.deployment.DeploymentConfigMerger.DEPLOYMENT_ID_LOG_KEY) ImplementsService(com.aws.greengrass.dependency.ImplementsService) ComponentStore(com.aws.greengrass.componentmanager.ComponentStore) ComponentIdentifier(com.aws.greengrass.componentmanager.models.ComponentIdentifier) SerializerFactory(com.aws.greengrass.util.SerializerFactory) Setter(lombok.Setter) VERSION_CONFIG_KEY(com.aws.greengrass.componentmanager.KernelConfigResolver.VERSION_CONFIG_KEY) Getter(lombok.Getter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Configuration(com.amazon.aws.iot.greengrass.configuration.common.Configuration) UpdateSystemPolicyService(com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService) Coerce(com.aws.greengrass.util.Coerce) StandardCopyOption(java.nio.file.StandardCopyOption) HashSet(java.util.HashSet) Inject(javax.inject.Inject) ComponentManager(com.aws.greengrass.componentmanager.ComponentManager) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Context(com.aws.greengrass.dependency.Context) ComponentRecipe(com.amazon.aws.iot.greengrass.component.common.ComponentRecipe) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) PlatformResolver(com.aws.greengrass.config.PlatformResolver) ExecutorService(java.util.concurrent.ExecutorService) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) DeploymentType(com.aws.greengrass.deployment.model.Deployment.DeploymentType) Files(java.nio.file.Files) MissingRequiredCapabilitiesException(com.aws.greengrass.deployment.exceptions.MissingRequiredCapabilitiesException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Topic(com.aws.greengrass.config.Topic) AtomicLong(java.util.concurrent.atomic.AtomicLong) Utils(com.aws.greengrass.util.Utils) DeploymentTaskMetadata(com.aws.greengrass.deployment.model.DeploymentTaskMetadata) Paths(java.nio.file.Paths) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) FAILED_ROLLBACK_NOT_REQUESTED(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus.FAILED_ROLLBACK_NOT_REQUESTED) DeploymentStatus(com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus) KernelConfigResolver(com.aws.greengrass.componentmanager.KernelConfigResolver) Logger(com.aws.greengrass.logging.api.Logger) Topics(com.aws.greengrass.config.Topics) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Topic(com.aws.greengrass.config.Topic) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) HashSet(java.util.HashSet)

Example 19 with Topics

use of com.aws.greengrass.config.Topics in project aws-greengrass-nucleus by aws-greengrass.

the class DeploymentStatusKeeper method persistAndPublishDeploymentStatus.

/**
 * Persist deployment status in kernel config.
 *
 * @param deploymentId   id for the deployment.
 * @param deploymentType type of deployment.
 * @param status         status of deployment.
 * @param statusDetails  other details of deployment status.
 * @throws IllegalArgumentException for invalid deployment type
 */
public void persistAndPublishDeploymentStatus(String deploymentId, DeploymentType deploymentType, String status, Map<String, String> statusDetails) {
    // method which consumes the data in config from the same topics. These two thread needs to be synchronized
    synchronized (deploymentType) {
        logger.atDebug().kv(DEPLOYMENT_ID_KEY_NAME, deploymentId).kv(DEPLOYMENT_STATUS_KEY_NAME, status).log("Storing deployment status");
        Map<String, Object> deploymentDetails = new HashMap<>();
        deploymentDetails.put(DEPLOYMENT_ID_KEY_NAME, deploymentId);
        deploymentDetails.put(DEPLOYMENT_TYPE_KEY_NAME, deploymentType.toString());
        deploymentDetails.put(DEPLOYMENT_STATUS_KEY_NAME, status);
        deploymentDetails.put(DEPLOYMENT_STATUS_DETAILS_KEY_NAME, statusDetails);
        // Each status update is uniquely stored
        Topics processedDeployments = getProcessedDeployments();
        Topics thisJob = processedDeployments.createInteriorChild(String.valueOf(System.currentTimeMillis()));
        thisJob.replaceAndWait(deploymentDetails);
        logger.atInfo().kv(DEPLOYMENT_ID_KEY_NAME, deploymentId).kv(DEPLOYMENT_STATUS_KEY_NAME, status).log("Stored deployment status");
    }
    publishPersistedStatusUpdates(deploymentType);
}
Also used : Topics(com.aws.greengrass.config.Topics) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 20 with Topics

use of com.aws.greengrass.config.Topics in project aws-greengrass-nucleus by aws-greengrass.

the class DeploymentStatusKeeper method publishPersistedStatusUpdates.

/**
 * Invokes the call-backs with persisted deployment status updates for deployments with specified type.
 * This is called by IotJobsHelper/MqttJobsHelper when connection is re-established to update cloud of all
 * all deployments the device performed when offline
 *
 * @param type deployment type
 */
public void publishPersistedStatusUpdates(DeploymentType type) {
    synchronized (type) {
        Topics processedDeployments = getProcessedDeployments();
        ArrayList<Topics> deployments = new ArrayList<>();
        processedDeployments.forEach(node -> {
            Topics deploymentDetails = (Topics) node;
            DeploymentType deploymentType = Coerce.toEnum(DeploymentType.class, deploymentDetails.find(DEPLOYMENT_TYPE_KEY_NAME));
            if (Objects.equals(deploymentType, type)) {
                deployments.add(deploymentDetails);
            }
        });
        // Topics are stored as ConcurrentHashMaps which do not guarantee ordering of elements
        // We want the statuses to be updated in the cloud in the order in which they were processed on the device.
        // This will be accurate representation of what happened on the device, especially when deployment service
        // processes multiple deployments in the order in which they come. Additionally, a customer workflow can
        // depend on this order. If Group2 gets successfully updated before Group1 then customer workflow may
        // error out.
        List<Topics> sortedByTimestamp = deployments.stream().sorted((o1, o2) -> {
            if (o1.getModtime() > o2.getModtime()) {
                return 1;
            }
            return -1;
        }).collect(Collectors.toList());
        List<Function<Map<String, Object>, Boolean>> consumers = getConsumersForDeploymentType(type);
        logger.atDebug().kv("deploymentType", type).kv("numberOfSubscribers", consumers.size()).log("Updating status of persisted deployments to subscribers");
        for (Topics topics : sortedByTimestamp) {
            boolean allConsumersUpdated = consumers.stream().allMatch(consumer -> consumer.apply(topics.toPOJO()));
            if (!allConsumersUpdated) {
                // If one deployment update fails, exit the loop to ensure the update order.
                logger.atDebug().log("Unable to update status of persisted deployments. Retry later");
                break;
            }
            processedDeployments.remove(topics);
        }
    }
}
Also used : Setter(lombok.Setter) DeploymentType(com.aws.greengrass.deployment.model.Deployment.DeploymentType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Coerce(com.aws.greengrass.util.Coerce) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Objects(java.util.Objects) Topics(com.aws.greengrass.config.Topics) List(java.util.List) Map(java.util.Map) LogManager(com.aws.greengrass.logging.impl.LogManager) Collections(java.util.Collections) Logger(com.aws.greengrass.logging.api.Logger) Function(java.util.function.Function) Topics(com.aws.greengrass.config.Topics) ArrayList(java.util.ArrayList) DeploymentType(com.aws.greengrass.deployment.model.Deployment.DeploymentType)

Aggregations

Topics (com.aws.greengrass.config.Topics)151 Test (org.junit.jupiter.api.Test)104 Topic (com.aws.greengrass.config.Topic)65 HashMap (java.util.HashMap)50 Map (java.util.Map)29 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)28 Context (com.aws.greengrass.dependency.Context)24 CountDownLatch (java.util.concurrent.CountDownLatch)24 IOException (java.io.IOException)23 ExecutionException (java.util.concurrent.ExecutionException)22 CaseInsensitiveString (com.aws.greengrass.config.CaseInsensitiveString)21 HashSet (java.util.HashSet)19 BeforeEach (org.junit.jupiter.api.BeforeEach)18 ComponentIdentifier (com.aws.greengrass.componentmanager.models.ComponentIdentifier)17 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)17 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 ArrayList (java.util.ArrayList)15 Path (java.nio.file.Path)13 ComponentRecipe (com.aws.greengrass.componentmanager.models.ComponentRecipe)12