use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.
the class DockerImageArtifactDownloadTest method before.
@BeforeEach
void before() throws Exception {
Instant credentialsExpiry = Instant.now().plusSeconds(10);
AuthorizationData authorizationData = AuthorizationData.builder().authorizationToken(Base64.getEncoder().encodeToString("username:password".getBytes(StandardCharsets.UTF_8))).expiresAt(credentialsExpiry).build();
GetAuthorizationTokenResponse response = GetAuthorizationTokenResponse.builder().authorizationData(authorizationData).build();
lenient().when(ecrClient.getAuthorizationToken(any(GetAuthorizationTokenRequest.class))).thenReturn(response);
lenient().when(dockerClient.dockerInstalled()).thenReturn(true);
AtomicBoolean mqttOnline = new AtomicBoolean(true);
lenient().when(mqttClient.getMqttOnline()).thenReturn(mqttOnline);
kernel = new Kernel();
NucleusPaths nucleusPaths = kernel.getNucleusPaths();
nucleusPaths.setComponentStorePath(tempRootDir);
ComponentStore store = new ComponentStore(nucleusPaths, platformResolver, recipeLoader);
EcrAccessor ecrAccessor = new EcrAccessor(ecrClient);
kernel.getContext().put(ComponentStore.class, store);
kernel.getContext().put(EcrAccessor.class, ecrAccessor);
kernel.getContext().put(DefaultDockerClient.class, dockerClient);
kernel.getContext().put(MqttClient.class, mqttClient);
preloadLocalStoreContent();
componentManager = kernel.getContext().get(ComponentManager.class);
}
use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.
the class KernelUpdateDeploymentTask method call.
@SuppressWarnings({ "PMD.AvoidDuplicateLiterals" })
@Override
public DeploymentResult call() {
Deployment.DeploymentStage stage = deployment.getDeploymentStage();
try {
List<GreengrassService> servicesToTrack = kernel.orderedDependencies().stream().filter(GreengrassService::shouldAutoStart).filter(o -> !kernel.getMain().equals(o)).collect(Collectors.toList());
long mergeTimestamp = kernel.getConfig().lookup("system", "rootpath").getModtime();
logger.atDebug().kv("serviceToTrack", servicesToTrack).kv("mergeTime", mergeTimestamp).log("Nucleus update workflow waiting for services to complete update");
DeploymentConfigMerger.waitForServicesToStart(servicesToTrack, mergeTimestamp);
DeploymentResult result = null;
if (KERNEL_ACTIVATION.equals(stage)) {
result = new DeploymentResult(DeploymentResult.DeploymentStatus.SUCCESSFUL, null);
} else if (KERNEL_ROLLBACK.equals(stage)) {
result = new DeploymentResult(DeploymentResult.DeploymentStatus.FAILED_ROLLBACK_COMPLETE, getDeploymentStatusDetails());
}
componentManager.cleanupStaleVersions();
return result;
} catch (InterruptedException e) {
logger.atError("deployment-interrupted", e).log();
try {
saveDeploymentStatusDetails(e.getMessage());
} catch (IOException ioException) {
logger.atError().log("Failed to persist deployment error information", ioException);
}
// Interrupted workflow. Shutdown kernel and retry this stage.
kernel.shutdown(30, REQUEST_RESTART);
return null;
} catch (ServiceUpdateException e) {
logger.atError("deployment-errored", e).log();
if (KERNEL_ACTIVATION.equals(stage)) {
try {
deployment.setDeploymentStage(KERNEL_ROLLBACK);
saveDeploymentStatusDetails(e.getMessage());
// Rollback workflow. Flip symlinks and restart kernel
kernel.getContext().get(KernelAlternatives.class).prepareRollback();
kernel.shutdown(30, REQUEST_RESTART);
} catch (IOException ioException) {
logger.atError().log("Failed to set up Nucleus rollback directory", ioException);
return new DeploymentResult(DeploymentResult.DeploymentStatus.FAILED_UNABLE_TO_ROLLBACK, e);
}
return null;
} else if (KERNEL_ROLLBACK.equals(stage)) {
logger.atError().log("Nucleus update workflow failed on rollback", e);
return new DeploymentResult(DeploymentResult.DeploymentStatus.FAILED_UNABLE_TO_ROLLBACK, getDeploymentStatusDetails());
}
return null;
}
}
use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.
the class GreengrassSetupTest method GIVEN_invalid_user_WHEN_script_is_used_THEN_error.
@ParameterizedTest
@MethodSource("invalidUsers")
@DisabledOnOs(OS.WINDOWS)
void GIVEN_invalid_user_WHEN_script_is_used_THEN_error(String user, ExtensionContext context) throws Exception {
ignoreExceptionUltimateCauseOfType(context, IOException.class);
Kernel realKernel = new Kernel();
greengrassSetup = new GreengrassSetup(System.out, System.err, deviceProvisioningHelper, platform, realKernel, "--component-default-user", user, "--aws-region", "us-east-1", "-ss", "false");
Exception e = assertThrows(RuntimeException.class, () -> {
greengrassSetup.parseArgs();
greengrassSetup.performSetup();
});
realKernel.shutdown();
assertThat(e.getMessage(), containsString(String.format("Error while looking up primary group for %s. No " + "group specified for the user", user)));
}
use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.
the class FleetStatusServiceSetupTest method setupKernel.
@BeforeEach
void setupKernel() throws Exception {
fleetStatusDetails = new AtomicReference<>();
kernel = new Kernel();
ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, FleetStatusServiceSetupTest.class.getResource("onlyMain.yaml"));
kernel.getContext().put(MqttClient.class, mqttClient);
when(mqttClient.publish(any(PublishRequest.class))).thenAnswer(i -> {
Object argument = i.getArgument(0);
PublishRequest publishRequest = (PublishRequest) argument;
try {
fleetStatusDetails.set(OBJECT_MAPPER.readValue(publishRequest.getPayload(), FleetStatusDetails.class));
} catch (JsonMappingException ignored) {
}
return CompletableFuture.completedFuture(0);
});
}
use of com.aws.greengrass.lifecyclemanager.Kernel in project aws-greengrass-nucleus by aws-greengrass.
the class IotJobsFleetStatusServiceTest method setupKernel.
@SuppressWarnings("PMD.CloseResource")
@BeforeEach
void setupKernel(ExtensionContext context) throws Exception {
ignoreExceptionOfType(context, TLSAuthException.class);
ignoreExceptionOfType(context, PackageDownloadException.class);
ignoreExceptionUltimateCauseOfType(context, EOFException.class);
ignoreExceptionUltimateCauseOfType(context, ResourceNotFoundException.class);
CountDownLatch fssRunning = new CountDownLatch(1);
CountDownLatch deploymentServiceRunning = new CountDownLatch(1);
CompletableFuture<Void> cf = new CompletableFuture<>();
cf.complete(null);
lenient().when(mockIotJobsClientWrapper.PublishUpdateJobExecution(any(UpdateJobExecutionRequest.class), any(QualityOfService.class))).thenAnswer(invocationOnMock -> {
verify(mockIotJobsClientWrapper, atLeastOnce()).SubscribeToUpdateJobExecutionAccepted(any(), eq(QualityOfService.AT_LEAST_ONCE), jobsAcceptedHandlerCaptor.capture());
Consumer<UpdateJobExecutionResponse> jobResponseConsumer = jobsAcceptedHandlerCaptor.getValue();
UpdateJobExecutionResponse mockJobExecutionResponse = mock(UpdateJobExecutionResponse.class);
jobResponseConsumer.accept(mockJobExecutionResponse);
return cf;
});
lenient().when(mqttClient.publish(any())).thenReturn(CompletableFuture.completedFuture(0));
kernel = new Kernel();
NoOpPathOwnershipHandler.register(kernel);
ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, IotJobsFleetStatusServiceTest.class.getResource("onlyMain.yaml"));
kernel.getContext().put(MqttClient.class, mqttClient);
kernel.getContext().put(ThingGroupHelper.class, thingGroupHelper);
// Mock out cloud communication
GreengrassServiceClientFactory mgscf = mock(GreengrassServiceClientFactory.class);
GreengrassV2DataClient mcf = mock(GreengrassV2DataClient.class);
lenient().when(mcf.resolveComponentCandidates(any(ResolveComponentCandidatesRequest.class))).thenThrow(ResourceNotFoundException.class);
lenient().when(mgscf.getGreengrassV2DataClient()).thenReturn(mcf);
kernel.getContext().put(GreengrassServiceClientFactory.class, mgscf);
componentNamesToCheck.clear();
kernel.getContext().addGlobalStateChangeListener((service, oldState, newState) -> {
if (service.getName().equals(FleetStatusService.FLEET_STATUS_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
fssRunning.countDown();
}
if (service.getName().equals(DeploymentService.DEPLOYMENT_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
deploymentServiceRunning.countDown();
deploymentService = (DeploymentService) service;
IotJobsHelper iotJobsHelper = deploymentService.getContext().get(IotJobsHelper.class);
iotJobsHelper.setIotJobsClientWrapper(mockIotJobsClientWrapper);
}
componentNamesToCheck.add(service.getName());
});
// set required instances from context
deviceConfiguration = new DeviceConfiguration(kernel, "ThingName", "xxxxxx-ats.iot.us-east-1.amazonaws.com", "xxxxxx.credentials.iot.us-east-1.amazonaws.com", "privKeyFilePath", "certFilePath", "caFilePath", "us-east-1", "roleAliasName");
kernel.getContext().put(DeviceConfiguration.class, deviceConfiguration);
// pre-load contents to package store
Path localStoreContentPath = Paths.get(IotJobsFleetStatusServiceTest.class.getResource("local_store_content").toURI());
PreloadComponentStoreHelper.preloadRecipesFromTestResourceDir(localStoreContentPath.resolve("recipes"), kernel.getNucleusPaths().recipePath());
copyFolderRecursively(localStoreContentPath.resolve("artifacts"), kernel.getNucleusPaths().artifactPath(), REPLACE_EXISTING);
kernel.launch();
assertTrue(fssRunning.await(10, TimeUnit.SECONDS));
assertTrue(deploymentServiceRunning.await(10, TimeUnit.SECONDS));
}
Aggregations