use of software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse in project aws-greengrass-nucleus by aws-greengrass.
the class LifecycleIPCEventStreamAgentTest method testUpdateStateHandler_subscribe_then_defer_when_future_no_longer_waiting.
@Test
@SuppressWarnings("PMD.CloseResource")
void testUpdateStateHandler_subscribe_then_defer_when_future_no_longer_waiting() {
SubscribeToComponentUpdatesRequest subsRequest = new SubscribeToComponentUpdatesRequest();
LifecycleIPCEventStreamAgent.SubscribeToComponentUpdateOperationHandler handler = lifecycleIPCEventStreamAgent.getSubscribeToComponentUpdateHandler(mockContext);
SubscribeToComponentUpdatesResponse response = handler.handleRequest(subsRequest);
assertNotNull(response);
DeferComponentUpdateRequest deferComponentUpdateRequest = new DeferComponentUpdateRequest();
deferComponentUpdateRequest.setMessage("Test defer");
deferComponentUpdateRequest.setDeploymentId("abc");
deferComponentUpdateRequest.setRecheckAfterMs(1000L);
assertThrows(ServiceError.class, () -> lifecycleIPCEventStreamAgent.getDeferComponentHandler(mockContext).handleRequest(deferComponentUpdateRequest));
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse in project aws-greengrass-nucleus by aws-greengrass.
the class LifecycleIPCEventStreamAgentTest method testUpdateStateHandler_subscribe_then_defer.
@Test
@SuppressWarnings("PMD.CloseResource")
void testUpdateStateHandler_subscribe_then_defer() throws ExecutionException, InterruptedException {
SubscribeToComponentUpdatesRequest subsRequest = new SubscribeToComponentUpdatesRequest();
LifecycleIPCEventStreamAgent.SubscribeToComponentUpdateOperationHandler handler = lifecycleIPCEventStreamAgent.getSubscribeToComponentUpdateHandler(mockContext);
SubscribeToComponentUpdatesResponse response = handler.handleRequest(subsRequest);
assertNotNull(response);
CompletableFuture<DeferComponentUpdateRequest> deferFuture = new CompletableFuture<>();
lifecycleIPCEventStreamAgent.getDeferUpdateFuturesMap().put(new Pair<>(TEST_SERVICE, "A"), deferFuture);
DeferComponentUpdateRequest deferComponentUpdateRequest = new DeferComponentUpdateRequest();
deferComponentUpdateRequest.setMessage("Test defer");
deferComponentUpdateRequest.setDeploymentId("A");
deferComponentUpdateRequest.setRecheckAfterMs(1000L);
DeferComponentUpdateResponse response1 = lifecycleIPCEventStreamAgent.getDeferComponentHandler(mockContext).handleRequest(deferComponentUpdateRequest);
assertNotNull(response1);
DeferComponentUpdateRequest request = deferFuture.get();
assertEquals("A", request.getDeploymentId());
assertEquals("Test defer", request.getMessage());
assertEquals(1000L, request.getRecheckAfterMs());
assertFalse(lifecycleIPCEventStreamAgent.getDeferUpdateFuturesMap().containsKey(new Pair<>(TEST_SERVICE, "A")));
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentTaskIntegrationTest method GIVEN_deployment_in_progress_WHEN_deployment_task_is_cancelled_THEN_stop_processing.
@Test
@Order(99)
@SuppressWarnings({ "PMD.CloseResource", "PMD.AvoidCatchingGenericException" })
void GIVEN_deployment_in_progress_WHEN_deployment_task_is_cancelled_THEN_stop_processing() throws Exception {
Future<DeploymentResult> resultFuture = submitSampleJobDocument(DeploymentTaskIntegrationTest.class.getResource("AddNewServiceWithSafetyCheck.json").toURI(), System.currentTimeMillis());
resultFuture.get(DEPLOYMENT_TIMEOUT, TimeUnit.SECONDS);
String authToken = IPCTestUtils.getAuthTokeForService(kernel, "NonDisruptableService");
final EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel);
SubscribeToComponentUpdatesRequest subscribeToComponentUpdatesRequest = new SubscribeToComponentUpdatesRequest();
GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
CompletableFuture<SubscribeToComponentUpdatesResponse> fut = greengrassCoreIPCClient.subscribeToComponentUpdates(subscribeToComponentUpdatesRequest, Optional.of(new StreamResponseHandler<ComponentUpdatePolicyEvents>() {
@Override
public void onStreamEvent(ComponentUpdatePolicyEvents streamEvent) {
if (streamEvent.getPreUpdateEvent() != null) {
DeferComponentUpdateRequest deferComponentUpdateRequest = new DeferComponentUpdateRequest();
deferComponentUpdateRequest.setRecheckAfterMs(Duration.ofSeconds(60).toMillis());
deferComponentUpdateRequest.setMessage("Test");
deferComponentUpdateRequest.setDeploymentId(streamEvent.getPreUpdateEvent().getDeploymentId());
greengrassCoreIPCClient.deferComponentUpdate(deferComponentUpdateRequest, Optional.empty());
}
}
@Override
public boolean onStreamError(Throwable error) {
logger.atError().setCause(error).log("Stream closed due to error");
return false;
}
@Override
public void onStreamClosed() {
}
})).getResponse();
try {
fut.get(DEPLOYMENT_TIMEOUT, TimeUnit.SECONDS);
} catch (Exception e) {
logger.atError().setCause(e).log("Error when subscribing to component updates");
fail("Caught exception when subscribing to component updates");
}
List<String> services = kernel.orderedDependencies().stream().filter(greengrassService -> greengrassService instanceof GenericExternalService).map(GreengrassService::getName).collect(Collectors.toList());
// should contain main, Nucleus, NonDisruptableService 1.0.0
assertEquals(3, services.size(), "Actual services: " + services);
assertThat(services, containsInAnyOrder("main", DEFAULT_NUCLEUS_COMPONENT_NAME, "NonDisruptableService"));
CountDownLatch cdlUpdateStarted = new CountDownLatch(1);
CountDownLatch cdlMergeCancelled = new CountDownLatch(1);
Consumer<GreengrassLogMessage> listener = m -> {
if (m.getMessage() != null && m.getMessage().contains("deferred for 60000 millis with message Test")) {
cdlUpdateStarted.countDown();
}
if (m.getMessage() != null && m.getMessage().contains("Cancelled deployment merge future due to interrupt")) {
cdlMergeCancelled.countDown();
}
};
Slf4jLogAdapter.addGlobalListener(listener);
try {
resultFuture = submitSampleJobDocument(DeploymentTaskIntegrationTest.class.getResource("UpdateServiceWithSafetyCheck.json").toURI(), System.currentTimeMillis());
assertTrue(cdlUpdateStarted.await(40, TimeUnit.SECONDS));
resultFuture.cancel(true);
assertTrue(cdlMergeCancelled.await(DEPLOYMENT_TIMEOUT, TimeUnit.SECONDS));
services = kernel.orderedDependencies().stream().filter(greengrassService -> greengrassService instanceof GenericExternalService).map(GreengrassService::getName).collect(Collectors.toList());
// should contain main, Nucleus, NonDisruptableService 1.0.0
assertEquals(3, services.size());
assertThat(services, containsInAnyOrder("main", DEFAULT_NUCLEUS_COMPONENT_NAME, "NonDisruptableService"));
assertEquals("1.0.0", kernel.findServiceTopic("NonDisruptableService").find("version").getOnce());
} finally {
Slf4jLogAdapter.removeGlobalListener(listener);
clientConnection.close();
}
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse in project aws-greengrass-nucleus by aws-greengrass.
the class IPCServicesTest method GIVEN_LifeCycleEventStreamClient_WHEN_subscribe_to_component_update_THEN_service_receives_update_and_close_stream.
@SuppressWarnings({ "PMD.CloseResource", "PMD.AvoidCatchingGenericException" })
@Test
void GIVEN_LifeCycleEventStreamClient_WHEN_subscribe_to_component_update_THEN_service_receives_update_and_close_stream() throws Exception {
// debug log required for assertion
LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
SubscribeToComponentUpdatesRequest subscribeToComponentUpdatesRequest = new SubscribeToComponentUpdatesRequest();
CountDownLatch cdl = new CountDownLatch(2);
CountDownLatch subscriptionLatch = new CountDownLatch(1);
Slf4jLogAdapter.addGlobalListener(m -> {
m.getMessage().contains("subscribed to component update");
subscriptionLatch.countDown();
});
CompletableFuture<Future> futureFuture = new CompletableFuture<>();
GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
StreamResponseHandler<ComponentUpdatePolicyEvents> responseHandler = new StreamResponseHandler<ComponentUpdatePolicyEvents>() {
@Override
public void onStreamEvent(ComponentUpdatePolicyEvents streamEvent) {
if (streamEvent.getPreUpdateEvent() != null) {
cdl.countDown();
DeferComponentUpdateRequest deferComponentUpdateRequest = new DeferComponentUpdateRequest();
deferComponentUpdateRequest.setRecheckAfterMs(Duration.ofSeconds(1).toMillis());
deferComponentUpdateRequest.setDeploymentId(streamEvent.getPreUpdateEvent().getDeploymentId());
deferComponentUpdateRequest.setMessage("Test");
futureFuture.complete(greengrassCoreIPCClient.deferComponentUpdate(deferComponentUpdateRequest, Optional.empty()).getResponse());
}
if (streamEvent.getPostUpdateEvent() != null) {
cdl.countDown();
}
}
@Override
public boolean onStreamError(Throwable error) {
logger.atError().setCause(error).log("Caught stream error");
return false;
}
@Override
public void onStreamClosed() {
}
};
SubscribeToComponentUpdatesResponseHandler streamHandler = greengrassCoreIPCClient.subscribeToComponentUpdates(subscribeToComponentUpdatesRequest, Optional.of(responseHandler));
CompletableFuture<SubscribeToComponentUpdatesResponse> fut = streamHandler.getResponse();
fut.get(3, TimeUnit.SECONDS);
assertTrue(subscriptionLatch.await(5, TimeUnit.SECONDS));
// GG_NEEDS_REVIEW: TODO: When Cli support safe update setting in local deployment, then create a local deployment here to
// trigger update
LifecycleIPCEventStreamAgent lifecycleIPCEventStreamAgent = kernel.getContext().get(LifecycleIPCEventStreamAgent.class);
PreComponentUpdateEvent event = new PreComponentUpdateEvent();
event.setDeploymentId("abc");
List<Future<DeferComponentUpdateRequest>> futureList = lifecycleIPCEventStreamAgent.sendPreComponentUpdateEvent(event);
assertEquals(1, futureList.size());
futureFuture.get(5, TimeUnit.SECONDS).get(5, TimeUnit.SECONDS);
futureList.get(0).get(5, TimeUnit.SECONDS);
lifecycleIPCEventStreamAgent.sendPostComponentUpdateEvent(new PostComponentUpdateEvent());
assertTrue(cdl.await(TIMEOUT_FOR_LIFECYCLE_SECONDS, TimeUnit.SECONDS));
streamHandler.closeStream();
// Checking if a request can be made on teh same connection after closing the stream
UpdateStateRequest updateStateRequest = new UpdateStateRequest();
updateStateRequest.setState(ReportedLifecycleState.RUNNING);
greengrassCoreIPCClient.updateState(updateStateRequest, Optional.empty()).getResponse().get(3, TimeUnit.SECONDS);
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse in project aws-greengrass-nucleus by aws-greengrass.
the class DeploymentConfigMergingTest method GIVEN_a_running_service_is_not_disruptable_WHEN_deployed_THEN_deployment_waits.
@Test
@SuppressWarnings({ "PMD.CloseResource", "PMD.AvoidCatchingGenericException" })
void GIVEN_a_running_service_is_not_disruptable_WHEN_deployed_THEN_deployment_waits() throws Throwable {
// GIVEN
ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, getClass().getResource("non_disruptable_service.yaml"));
kernel.launch();
CountDownLatch mainFinished = new CountDownLatch(1);
kernel.getMain().addStateSubscriber((WhatHappened what, Topic t) -> {
if (Coerce.toEnum(State.class, t).equals(State.FINISHED)) {
mainFinished.countDown();
}
});
// wait for main to finish
assertTrue(mainFinished.await(10, TimeUnit.SECONDS));
AtomicInteger deferCount = new AtomicInteger(0);
AtomicInteger preComponentUpdateCount = new AtomicInteger(0);
CountDownLatch postComponentUpdateRecieved = new CountDownLatch(1);
String authToken = IPCTestUtils.getAuthTokeForService(kernel, "nondisruptable");
final EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel);
GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
SubscribeToComponentUpdatesRequest subscribeToComponentUpdatesRequest = new SubscribeToComponentUpdatesRequest();
CompletableFuture<SubscribeToComponentUpdatesResponse> fut = greengrassCoreIPCClient.subscribeToComponentUpdates(subscribeToComponentUpdatesRequest, Optional.of(new StreamResponseHandler<ComponentUpdatePolicyEvents>() {
@Override
public void onStreamEvent(ComponentUpdatePolicyEvents streamEvent) {
if (streamEvent.getPreUpdateEvent() != null) {
preComponentUpdateCount.getAndIncrement();
if (deferCount.get() < 1) {
DeferComponentUpdateRequest deferComponentUpdateRequest = new DeferComponentUpdateRequest();
deferComponentUpdateRequest.setRecheckAfterMs(Duration.ofSeconds(7).toMillis());
deferComponentUpdateRequest.setMessage("Test");
deferComponentUpdateRequest.setDeploymentId(streamEvent.getPreUpdateEvent().getDeploymentId());
greengrassCoreIPCClient.deferComponentUpdate(deferComponentUpdateRequest, Optional.empty());
deferCount.getAndIncrement();
}
}
if (streamEvent.getPostUpdateEvent() != null) {
postComponentUpdateRecieved.countDown();
clientConnection.disconnect();
}
}
@Override
public boolean onStreamError(Throwable error) {
logger.atError().setCause(error).log("Caught an error on the stream");
return false;
}
@Override
public void onStreamClosed() {
logger.atWarn().log("Stream closed by the server");
}
})).getResponse();
try {
fut.get(30, TimeUnit.SECONDS);
} catch (Exception e) {
logger.atError().setCause(e).log("Error when subscribing to component updates");
fail("Caught exception when subscribing to component updates");
}
Map<String, Object> currentConfig = new HashMap<>(kernel.getConfig().toPOJO());
Future<DeploymentResult> future = deploymentConfigMerger.mergeInNewConfig(testDeployment(), currentConfig);
// update should be deferred for 5 seconds
assertThrows(TimeoutException.class, () -> future.get(5, TimeUnit.SECONDS), "Merge should not happen within 5 seconds");
assertTrue(postComponentUpdateRecieved.await(15, TimeUnit.SECONDS));
assertEquals(2, preComponentUpdateCount.get());
}
Aggregations