use of com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentConfigMergerTest method GIVEN_deployment_WHEN_check_safety_selected_THEN_check_safety_before_update.
@Test
void GIVEN_deployment_WHEN_check_safety_selected_THEN_check_safety_before_update() throws Exception {
UpdateSystemPolicyService updateSystemPolicyService = mock(UpdateSystemPolicyService.class);
when(context.get(UpdateSystemPolicyService.class)).thenReturn(updateSystemPolicyService);
DeploymentActivatorFactory deploymentActivatorFactory = mock(DeploymentActivatorFactory.class);
DeploymentActivator deploymentActivator = mock(DeploymentActivator.class);
when(deploymentActivatorFactory.getDeploymentActivator(any())).thenReturn(deploymentActivator);
when(context.get(DeploymentActivatorFactory.class)).thenReturn(deploymentActivatorFactory);
DeploymentConfigMerger merger = new DeploymentConfigMerger(kernel, deviceConfiguration, validator);
DeploymentDocument doc = new DeploymentDocument();
doc.setConfigurationArn("NoSafetyCheckDeploy");
doc.setComponentUpdatePolicy(new ComponentUpdatePolicy(0, SKIP_NOTIFY_COMPONENTS));
merger.mergeInNewConfig(createMockDeployment(doc), new HashMap<>());
verify(updateSystemPolicyService, times(0)).addUpdateAction(any(), any());
doc.setConfigurationArn("DeploymentId");
doc.setComponentUpdatePolicy(new ComponentUpdatePolicy(60, NOTIFY_COMPONENTS));
merger.mergeInNewConfig(createMockDeployment(doc), new HashMap<>());
verify(updateSystemPolicyService).addUpdateAction(any(), any());
}
use of com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentConfigMergerTest method GIVEN_deployment_WHEN_task_cancelled_THEN_update_is_cancelled.
@Test
void GIVEN_deployment_WHEN_task_cancelled_THEN_update_is_cancelled() throws Throwable {
ArgumentCaptor<UpdateAction> cancelledTaskCaptor = ArgumentCaptor.forClass(UpdateAction.class);
UpdateSystemPolicyService updateSystemPolicyService = mock(UpdateSystemPolicyService.class);
DeploymentActivatorFactory factory = mock(DeploymentActivatorFactory.class);
when(factory.getDeploymentActivator(anyMap())).thenReturn(mock(KernelUpdateActivator.class));
when(context.get(any())).thenAnswer(invocationOnMock -> {
Object argument = invocationOnMock.getArgument(0);
if (UpdateSystemPolicyService.class.equals(argument)) {
return updateSystemPolicyService;
} else if (DeploymentActivatorFactory.class.equals(argument)) {
return factory;
}
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", argument));
});
// GIVEN
DeploymentConfigMerger merger = new DeploymentConfigMerger(kernel, deviceConfiguration, validator);
DeploymentDocument doc = mock(DeploymentDocument.class);
when(doc.getDeploymentId()).thenReturn("DeploymentId");
when(doc.getComponentUpdatePolicy()).thenReturn(new ComponentUpdatePolicy(0, NOTIFY_COMPONENTS));
Future<DeploymentResult> fut = merger.mergeInNewConfig(createMockDeployment(doc), new HashMap<>());
verify(updateSystemPolicyService).addUpdateAction(any(), cancelledTaskCaptor.capture());
assertEquals(0, cancelledTaskCaptor.getValue().getTimeout());
assertEquals("DeploymentId", cancelledTaskCaptor.getValue().getDeploymentId());
assertTrue(cancelledTaskCaptor.getValue().isGgcRestart());
// WHEN
fut.cancel(true);
cancelledTaskCaptor.getValue().getAction().run();
// THEN
verify(doc, times(0)).getFailureHandlingPolicy();
}
use of com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentE2ETest method GIVEN_deployment_in_progress_with_more_jobs_queued_in_cloud_WHEN_cancel_event_received_and_kernel_is_waiting_for_safe_time_THEN_deployment_should_be_canceled.
@Timeout(value = 10, unit = TimeUnit.MINUTES)
@Test
void GIVEN_deployment_in_progress_with_more_jobs_queued_in_cloud_WHEN_cancel_event_received_and_kernel_is_waiting_for_safe_time_THEN_deployment_should_be_canceled() throws Exception {
// First Deployment to have a service running in Kernel which has a safety check that always returns
// false, i.e. keeps waiting forever
CreateDeploymentRequest createDeploymentRequest1 = CreateDeploymentRequest.builder().components(Utils.immutableMap("NonDisruptableService", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
CreateDeploymentResponse result1 = draftAndCreateDeployment(createDeploymentRequest1);
IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, result1.iotJobId(), thingInfo.getThingName(), Duration.ofMinutes(3), s -> s.equals(JobExecutionStatus.SUCCEEDED));
Consumer<GreengrassLogMessage> logListener = null;
try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "NonDisruptableService" + testComponentSuffix)) {
GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(connection);
ipcClient.subscribeToComponentUpdates(new SubscribeToComponentUpdatesRequest(), Optional.of(new StreamResponseHandler<ComponentUpdatePolicyEvents>() {
@Override
public void onStreamEvent(ComponentUpdatePolicyEvents streamEvent) {
if (streamEvent.getPreUpdateEvent() != null) {
logger.atInfo().log("Got pre component update event");
DeferComponentUpdateRequest deferComponentUpdateRequest = new DeferComponentUpdateRequest();
deferComponentUpdateRequest.setRecheckAfterMs(TimeUnit.SECONDS.toMillis(60));
deferComponentUpdateRequest.setMessage("NonDisruptableService");
logger.atInfo().log("Sending defer request");
// Cannot wait inside a callback
ipcClient.deferComponentUpdate(deferComponentUpdateRequest, Optional.empty());
}
}
@Override
public boolean onStreamError(Throwable error) {
logger.atError().setCause(error).log("Caught stream error while subscribing for component update");
return false;
}
@Override
public void onStreamClosed() {
}
}));
CountDownLatch updateRegistered = new CountDownLatch(1);
CountDownLatch deploymentCancelled = new CountDownLatch(1);
logListener = m -> {
if ("register-service-update-action".equals(m.getEventType())) {
updateRegistered.countDown();
}
if (m.getMessage() != null && m.getMessage().contains("Deployment was cancelled")) {
deploymentCancelled.countDown();
}
};
Slf4jLogAdapter.addGlobalListener(logListener);
// Second deployment to update the service which is currently running an important task so deployment should
// keep waiting for a safe time to update
CreateDeploymentRequest createDeploymentRequest2 = CreateDeploymentRequest.builder().deploymentPolicies(DeploymentPolicies.builder().configurationValidationPolicy(DeploymentConfigurationValidationPolicy.builder().timeoutInSeconds(120).build()).failureHandlingPolicy(DO_NOTHING).componentUpdatePolicy(DeploymentComponentUpdatePolicy.builder().action(NOTIFY_COMPONENTS).timeoutInSeconds(120).build()).build()).components(Utils.immutableMap("NonDisruptableService", ComponentDeploymentSpecification.builder().componentVersion("1.0.1").build())).build();
CreateDeploymentResponse result2 = draftAndCreateDeployment(createDeploymentRequest2);
IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, result2.iotJobId(), thingInfo.getThingName(), Duration.ofMinutes(3), s -> s.equals(JobExecutionStatus.IN_PROGRESS));
// Create one more deployment so that it's queued in cloud
CreateDeploymentRequest createDeploymentRequest3 = CreateDeploymentRequest.builder().deploymentPolicies(DeploymentPolicies.builder().configurationValidationPolicy(DeploymentConfigurationValidationPolicy.builder().timeoutInSeconds(120).build()).failureHandlingPolicy(DO_NOTHING).componentUpdatePolicy(DeploymentComponentUpdatePolicy.builder().action(NOTIFY_COMPONENTS).timeoutInSeconds(120).build()).build()).components(Utils.immutableMap("NonDisruptableService", ComponentDeploymentSpecification.builder().componentVersion("1.0.1").build())).build();
CreateDeploymentResponse result3 = draftAndCreateDeployment(createDeploymentRequest3);
// Wait for the second deployment to start waiting for safe time to update and
// then cancel it's corresponding job from cloud
assertTrue(updateRegistered.await(60, TimeUnit.SECONDS));
UpdateSystemPolicyService updateSystemPolicyService = kernel.getContext().get(UpdateSystemPolicyService.class);
assertThat("The UpdateSystemService should have one pending action.", updateSystemPolicyService.getPendingActions(), IsCollectionWithSize.hasSize(1));
// Get the value of the pending Action
String pendingAction = updateSystemPolicyService.getPendingActions().iterator().next();
// GG_NEEDS_REVIEW: TODO : Call Fleet configuration service's cancel API when ready instead of calling IoT Jobs API
IotJobsUtils.cancelJob(iotClient, result2.iotJobId());
// Wait for indication that cancellation has gone through
assertTrue(deploymentCancelled.await(240, TimeUnit.SECONDS));
// the third deployment may have reached device.
Set<String> pendingActions = updateSystemPolicyService.getPendingActions();
if (pendingActions.size() == 1) {
String newPendingAction = pendingActions.iterator().next();
assertNotEquals(pendingAction, newPendingAction, "The UpdateSystemService's one pending action should be be replaced.");
} else if (pendingActions.size() > 1) {
fail("Deployment not cancelled, pending actions: " + updateSystemPolicyService.getPendingActions());
}
// Now that we've verified that the job got cancelled, let's verify that the next job was picked up
// and put into IN_PROGRESS state
IotJobsUtils.waitForJobExecutionStatusToSatisfy(iotClient, result3.iotJobId(), thingInfo.getThingName(), Duration.ofMinutes(3), s -> s.equals(JobExecutionStatus.IN_PROGRESS));
// Ensure that main is finished, which is its terminal state, so this means that all updates ought to be done
assertThat(kernel.getMain()::getState, eventuallyEval(is(State.FINISHED)));
assertThat(getCloudDeployedComponent("NonDisruptableService")::getState, eventuallyEval(is(State.RUNNING)));
assertEquals("1.0.0", getCloudDeployedComponent("NonDisruptableService").getConfig().find("version").getOnce());
} finally {
if (logListener != null) {
Slf4jLogAdapter.removeGlobalListener(logListener);
}
}
}
use of com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentConfigMergerTest method GIVEN_deployment_activate_WHEN_deployment_has_some_new_config_THEN_old_config_is_validated.
@Test
void GIVEN_deployment_activate_WHEN_deployment_has_some_new_config_THEN_old_config_is_validated(ExtensionContext extensionContext) throws Throwable {
ArgumentCaptor<UpdateAction> taskCaptor = ArgumentCaptor.forClass(UpdateAction.class);
UpdateSystemPolicyService updateSystemPolicyService = mock(UpdateSystemPolicyService.class);
when(context.get(UpdateSystemPolicyService.class)).thenReturn(updateSystemPolicyService);
DeploymentActivatorFactory deploymentActivatorFactory = new DeploymentActivatorFactory(kernel);
when(context.get(DeploymentActivatorFactory.class)).thenReturn(deploymentActivatorFactory);
BootstrapManager bootstrapManager = mock(BootstrapManager.class);
when(bootstrapManager.isBootstrapRequired(any())).thenReturn(false);
when(context.get(BootstrapManager.class)).thenReturn(bootstrapManager);
DefaultActivator defaultActivator = mock(DefaultActivator.class);
when(context.get(DefaultActivator.class)).thenReturn(defaultActivator);
Topic regionTopic = Topic.of(context, DEVICE_PARAM_AWS_REGION, "us-west-2");
when(deviceConfiguration.getAWSRegion()).thenReturn(regionTopic);
Topic credEndpointTopic = Topic.of(context, DEVICE_PARAM_IOT_CRED_ENDPOINT, "xxxxxx.credentials.iot.us-west-2.amazonaws.com");
when(deviceConfiguration.getIotCredentialEndpoint()).thenReturn(credEndpointTopic);
Topic dataEndpointTopic = Topic.of(context, DEVICE_PARAM_IOT_DATA_ENDPOINT, "xxxxxx-ats.iot.us-west-2.amazonaws.com");
when(deviceConfiguration.getIotDataEndpoint()).thenReturn(dataEndpointTopic);
when(deviceConfiguration.getNucleusComponentName()).thenReturn(DEFAULT_NUCLEUS_COMPONENT_NAME);
ArgumentCaptor<String> regionCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> credEndpointCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> dataEndpointCaptor = ArgumentCaptor.forClass(String.class);
ignoreExceptionOfType(extensionContext, IOException.class);
Map<String, Object> newConfig = new HashMap<>();
Map<String, Object> newConfig2 = new HashMap<>();
Map<String, Object> newConfig3 = new HashMap<>();
Map<String, Object> newConfig4 = new HashMap<>();
newConfig4.put(DEVICE_PARAM_AWS_REGION, "us-east-1");
newConfig3.put(CONFIGURATION_CONFIG_KEY, newConfig4);
newConfig2.put(DEFAULT_NUCLEUS_COMPONENT_NAME, newConfig3);
newConfig.put(SERVICES_NAMESPACE_TOPIC, newConfig2);
// GIVEN
DeploymentConfigMerger merger = new DeploymentConfigMerger(kernel, deviceConfiguration, validator);
DeploymentDocument doc = mock(DeploymentDocument.class);
when(doc.getDeploymentId()).thenReturn("DeploymentId");
when(doc.getComponentUpdatePolicy()).thenReturn(new ComponentUpdatePolicy(0, NOTIFY_COMPONENTS));
merger.mergeInNewConfig(createMockDeployment(doc), newConfig);
verify(updateSystemPolicyService).addUpdateAction(any(), taskCaptor.capture());
assertEquals(0, taskCaptor.getValue().getTimeout());
assertEquals("DeploymentId", taskCaptor.getValue().getDeploymentId());
assertFalse(taskCaptor.getValue().isGgcRestart());
// WHEN
taskCaptor.getValue().getAction().run();
// THEN
verify(defaultActivator, times(1)).activate(any(), any(), any());
verify(deviceConfiguration, times(1)).validateEndpoints(regionCaptor.capture(), credEndpointCaptor.capture(), dataEndpointCaptor.capture());
assertNotNull(regionCaptor.getValue());
assertEquals("us-east-1", regionCaptor.getValue());
assertNotNull(credEndpointCaptor.getValue());
assertEquals("xxxxxx.credentials.iot.us-west-2.amazonaws.com", credEndpointCaptor.getValue());
assertNotNull(dataEndpointCaptor.getValue());
assertEquals("xxxxxx-ats.iot.us-west-2.amazonaws.com", dataEndpointCaptor.getValue());
}
use of com.aws.greengrass.lifecyclemanager.UpdateSystemPolicyService in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentConfigMergerTest method GIVEN_deployment_WHEN_task_not_cancelled_THEN_update_is_continued.
@Test
void GIVEN_deployment_WHEN_task_not_cancelled_THEN_update_is_continued() throws Throwable {
ArgumentCaptor<UpdateAction> taskCaptor = ArgumentCaptor.forClass(UpdateAction.class);
UpdateSystemPolicyService updateSystemPolicyService = mock(UpdateSystemPolicyService.class);
when(context.get(UpdateSystemPolicyService.class)).thenReturn(updateSystemPolicyService);
DeploymentActivatorFactory deploymentActivatorFactory = new DeploymentActivatorFactory(kernel);
when(context.get(DeploymentActivatorFactory.class)).thenReturn(deploymentActivatorFactory);
BootstrapManager bootstrapManager = mock(BootstrapManager.class);
when(bootstrapManager.isBootstrapRequired(any())).thenReturn(false);
when(context.get(BootstrapManager.class)).thenReturn(bootstrapManager);
DefaultActivator defaultActivator = mock(DefaultActivator.class);
when(context.get(DefaultActivator.class)).thenReturn(defaultActivator);
// GIVEN
DeploymentConfigMerger merger = new DeploymentConfigMerger(kernel, deviceConfiguration, validator);
DeploymentDocument doc = mock(DeploymentDocument.class);
when(doc.getDeploymentId()).thenReturn("DeploymentId");
when(doc.getComponentUpdatePolicy()).thenReturn(new ComponentUpdatePolicy(0, NOTIFY_COMPONENTS));
merger.mergeInNewConfig(createMockDeployment(doc), new HashMap<>());
verify(updateSystemPolicyService).addUpdateAction(any(), taskCaptor.capture());
assertEquals(0, taskCaptor.getValue().getTimeout());
assertEquals("DeploymentId", taskCaptor.getValue().getDeploymentId());
assertFalse(taskCaptor.getValue().isGgcRestart());
// WHEN
taskCaptor.getValue().getAction().run();
// THEN
verify(defaultActivator, times(1)).activate(any(), any(), any());
}
Aggregations