Search in sources :

Example 1 with ServiceLoadException

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

the class IotJobsHelper method evaluateCancellationAndCancelDeploymentIfNeeded.

private void evaluateCancellationAndCancelDeploymentIfNeeded() {
    try {
        GreengrassService deploymentServiceLocateResult = kernel.locate(DeploymentService.DEPLOYMENT_SERVICE_TOPICS);
        if (deploymentServiceLocateResult instanceof DeploymentService) {
            DeploymentService deploymentService = (DeploymentService) deploymentServiceLocateResult;
            DeploymentTaskMetadata currentDeployment = deploymentService.getCurrentDeploymentTaskMetadata();
            // If the queue is not empty then it means deployment(s) from other sources is/are queued in it,
            // in that case don't add a cancellation deployment because it can't be added to the front of the queue
            // we will just have to let current deployment finish
            Deployment deployment = new Deployment(DeploymentType.IOT_JOBS, UUID.randomUUID().toString(), true);
            if (deploymentQueue.isEmpty() && currentDeployment != null && currentDeployment.isCancellable() && DeploymentType.IOT_JOBS.equals(currentDeployment.getDeploymentType()) && deploymentQueue.offer(deployment)) {
                logger.atInfo().log("Added cancellation deployment to the queue");
            }
        }
    } catch (ServiceLoadException e) {
        logger.atError().setCause(e).log("Failed to find deployment service");
    }
}
Also used : GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Deployment(com.aws.greengrass.deployment.model.Deployment) DeploymentTaskMetadata(com.aws.greengrass.deployment.model.DeploymentTaskMetadata) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException)

Example 2 with ServiceLoadException

use of com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException 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 3 with ServiceLoadException

use of com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException 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 4 with ServiceLoadException

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

the class ShadowDeploymentListener method shadowUpdated.

protected void shadowUpdated(Map<String, Object> desired, Map<String, Object> reported, Integer version) {
    if (lastVersion.get() > version) {
        logger.atDebug().kv("SHADOW_VERSION", version).log("Received an older version of shadow. Ignoring...");
        return;
    }
    lastVersion.set(version);
    // the reported section of the shadow was updated
    if (reported != null && !reported.isEmpty()) {
        syncShadowDeploymentStatus(reported);
    }
    if (desired == null || desired.isEmpty()) {
        logger.debug("Empty desired state, no update to desired section or no device deployments created yet");
        return;
    }
    String fleetConfigStr = (String) desired.get(FLEET_CONFIG_KEY);
    Configuration configuration;
    try {
        configuration = SerializerFactory.getFailSafeJsonObjectMapper().readValue(fleetConfigStr, Configuration.class);
    } catch (JsonProcessingException e) {
        logger.atError().log("failed to process shadow update", e);
        return;
    }
    String configurationArn = configuration.getConfigurationArn();
    if (configurationArn == null) {
        logger.atError().log("Desired state has null configuration ARN. Ignoring shadow update");
        return;
    }
    String desiredStatus = (String) desired.get(DESIRED_STATUS_KEY);
    if (desiredStatus == null) {
        logger.atError().log("Desired status is null. Ignoring shadow update");
        return;
    }
    boolean cancelDeployment = DESIRED_STATUS_CANCELED.equals(desiredStatus);
    synchronized (ShadowDeploymentListener.class) {
        // If lastConfigurationArn is null, this is the first shadow update since startup
        if (lastConfigurationArn == null) {
            lastConfigurationArn = configurationArn;
            // Ignore if the latest deployment was canceled
            if (cancelDeployment) {
                logger.atInfo().kv(CONFIGURATION_ARN_LOG_KEY_NAME, configurationArn).log("Deployment was canceled. Ignoring shadow update at startup");
                return;
            }
            // the reported status is terminal (i.e. not in_progress) because it's already fully processed
            if (reported != null && configurationArn.equals(reported.get(ARN_FOR_STATUS_KEY)) && !JobStatus.IN_PROGRESS.toString().equals(reported.get(STATUS_KEY))) {
                logger.atInfo().kv(CONFIGURATION_ARN_LOG_KEY_NAME, configurationArn).log("Deployment result already reported. Ignoring shadow update at startup");
                return;
            }
            // Ignore if it's the ongoing deployment. This can happen if the last shadow deployment caused restart
            try {
                // Using locate instead of injection here because DeploymentService lacks usable injection
                // constructor. Same as in IotJobsHelper.evaluateCancellationAndCancelDeploymentIfNeeded
                GreengrassService deploymentServiceLocateResult = kernel.locate(DeploymentService.DEPLOYMENT_SERVICE_TOPICS);
                if (deploymentServiceLocateResult instanceof DeploymentService) {
                    DeploymentTaskMetadata currentDeployment = ((DeploymentService) deploymentServiceLocateResult).getCurrentDeploymentTaskMetadata();
                    if (currentDeployment != null && configurationArn.equals(currentDeployment.getDeploymentId())) {
                        logger.atInfo().kv(CONFIGURATION_ARN_LOG_KEY_NAME, configurationArn).log("Ongoing deployment. Ignoring shadow update at startup");
                        return;
                    }
                }
            } catch (ServiceLoadException e) {
                logger.atError().setCause(e).log("Failed to find deployment service");
            }
        } else {
            if (lastConfigurationArn.equals(configurationArn) && !cancelDeployment) {
                logger.atInfo().kv(CONFIGURATION_ARN_LOG_KEY_NAME, configurationArn).log("Duplicate deployment notification. Ignoring shadow update");
                return;
            }
            lastConfigurationArn = configurationArn;
        }
    }
    Deployment deployment;
    if (cancelDeployment) {
        deployment = new Deployment(DeploymentType.SHADOW, UUID.randomUUID().toString(), true);
    } else {
        deployment = new Deployment(fleetConfigStr, DeploymentType.SHADOW, configurationArn);
    }
    if (deploymentQueue.offer(deployment)) {
        logger.atInfo().kv("ID", deployment.getId()).log("Added shadow deployment job");
    }
}
Also used : Configuration(com.amazon.aws.iot.greengrass.configuration.common.Configuration) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) Deployment(com.aws.greengrass.deployment.model.Deployment) DeploymentTaskMetadata(com.aws.greengrass.deployment.model.DeploymentTaskMetadata) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException)

Example 5 with ServiceLoadException

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

the class DefaultActivator method activate.

@Override
@SuppressWarnings("PMD.PrematureDeclaration")
public void activate(Map<String, Object> newConfig, Deployment deployment, CompletableFuture<DeploymentResult> totallyCompleteFuture) {
    Map<String, Object> serviceConfig;
    if (newConfig.containsKey(SERVICES_NAMESPACE_TOPIC)) {
        serviceConfig = (Map<String, Object>) newConfig.get(SERVICES_NAMESPACE_TOPIC);
    } else {
        serviceConfig = new HashMap<>();
    }
    DeploymentDocument deploymentDocument = deployment.getDeploymentDocumentObj();
    if (isAutoRollbackRequested(deploymentDocument) && !takeConfigSnapshot(totallyCompleteFuture)) {
        return;
    }
    DeploymentConfigMerger.AggregateServicesChangeManager servicesChangeManager = new DeploymentConfigMerger.AggregateServicesChangeManager(kernel, serviceConfig);
    // Get the timestamp before updateMap(). It will be used to check whether services have started.
    long mergeTime = System.currentTimeMillis();
    updateConfiguration(deploymentDocument.getTimestamp(), newConfig);
    // wait until topic listeners finished processing mergeMap changes.
    Throwable setDesiredStateFailureCause = kernel.getContext().runOnPublishQueueAndWait(() -> {
        // polling to wait for all services to be started.
        servicesChangeManager.startNewServices();
        // Close unloadable service instances and initiate with new config
        servicesChangeManager.replaceUnloadableService();
        // Restart any services that may have been broken before this deployment
        // This is added to allow deployments to fix broken services
        servicesChangeManager.reinstallBrokenServices();
    });
    if (setDesiredStateFailureCause != null) {
        handleFailure(servicesChangeManager, deploymentDocument, totallyCompleteFuture, setDesiredStateFailureCause);
        return;
    }
    try {
        Set<GreengrassService> servicesToTrack = servicesChangeManager.servicesToTrack();
        logger.atDebug(MERGE_CONFIG_EVENT_KEY).kv("serviceToTrack", servicesToTrack).kv("mergeTime", mergeTime).log("Applied new service config. Waiting for services to complete update");
        waitForServicesToStart(servicesToTrack, mergeTime);
        logger.atDebug(MERGE_CONFIG_EVENT_KEY).log("new/updated services are running, will now remove old services");
        servicesChangeManager.removeObsoleteServices();
        logger.atInfo(MERGE_CONFIG_EVENT_KEY).kv(DEPLOYMENT_ID_LOG_KEY, deploymentDocument.getDeploymentId()).log("All services updated");
        totallyCompleteFuture.complete(new DeploymentResult(DeploymentResult.DeploymentStatus.SUCCESSFUL, null));
    } catch (InterruptedException | ExecutionException | ServiceUpdateException | ServiceLoadException e) {
        handleFailure(servicesChangeManager, deploymentDocument, totallyCompleteFuture, e);
    }
}
Also used : DeploymentDocument(com.aws.greengrass.deployment.model.DeploymentDocument) DeploymentResult(com.aws.greengrass.deployment.model.DeploymentResult) ServiceUpdateException(com.aws.greengrass.deployment.exceptions.ServiceUpdateException) DeploymentConfigMerger(com.aws.greengrass.deployment.DeploymentConfigMerger) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) ExecutionException(java.util.concurrent.ExecutionException) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException)

Aggregations

ServiceLoadException (com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException)24 Test (org.junit.jupiter.api.Test)11 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)9 Topics (com.aws.greengrass.config.Topics)5 HashMap (java.util.HashMap)5 Topic (com.aws.greengrass.config.Topic)4 ServiceUpdateException (com.aws.greengrass.deployment.exceptions.ServiceUpdateException)4 Deployment (com.aws.greengrass.deployment.model.Deployment)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 ComponentIdentifier (com.aws.greengrass.componentmanager.models.ComponentIdentifier)3 ImplementsService (com.aws.greengrass.dependency.ImplementsService)3 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)3 DeploymentResult (com.aws.greengrass.deployment.model.DeploymentResult)3 DeploymentTaskMetadata (com.aws.greengrass.deployment.model.DeploymentTaskMetadata)3 InputValidationException (com.aws.greengrass.lifecyclemanager.exceptions.InputValidationException)3 ExecutionException (java.util.concurrent.ExecutionException)3 DependencyType (com.amazon.aws.iot.greengrass.component.common.DependencyType)2 Configuration (com.amazon.aws.iot.greengrass.configuration.common.Configuration)2 ComponentStore (com.aws.greengrass.componentmanager.ComponentStore)2