use of com.aws.greengrass.util.Pair in project aws-greengrass-nucleus by aws-greengrass.
the class GenericExternalService method run.
@SuppressWarnings("PMD.CloseResource")
protected Pair<RunStatus, Exec> run(Topic t, String cmd, IntConsumer background, List<Exec> trackingList, boolean requiresPrivilege) throws InterruptedException {
if (runWith == null) {
Optional<RunWith> opt = computeRunWithConfiguration();
if (!opt.isPresent()) {
logger.atError().log("Could not determine user/group to run with. Ensure that {} is set for {}", DeviceConfiguration.RUN_WITH_TOPIC, deviceConfiguration.getNucleusComponentName());
return new Pair<>(RunStatus.Errored, null);
}
runWith = opt.get();
LogEventBuilder logEvent = logger.atDebug().kv("user", runWith.getUser());
if (runWith.getGroup() != null) {
logEvent.kv("group", runWith.getGroup());
}
if (runWith.getShell() != null) {
logEvent.kv("shell", runWith.getShell());
}
logEvent.log("Saving user information for service execution");
if (!updateComponentPathOwner()) {
logger.atError().log("Service artifacts may not be accessible to user");
}
}
final ShellRunner shellRunner = context.get(ShellRunner.class);
Exec exec;
try {
exec = shellRunner.setup(t.getFullName(), cmd, this);
} catch (IOException e) {
logger.atError().log("Error setting up to run {}", t.getFullName(), e);
return new Pair<>(RunStatus.Errored, null);
}
if (exec == null) {
return new Pair<>(RunStatus.NothingDone, null);
}
exec = addUser(exec, requiresPrivilege);
exec = addShell(exec);
addEnv(exec, t.parent);
logger.atDebug().setEventType("generic-service-run").log();
// Track all running processes that we fork
if (exec.isRunning()) {
trackingList.add(exec);
}
RunStatus ret = shellRunner.successful(exec, t.getFullName(), background, this) ? RunStatus.OK : RunStatus.Errored;
return new Pair<>(ret, exec);
}
use of com.aws.greengrass.util.Pair in project aws-greengrass-nucleus by aws-greengrass.
the class GreengrassService method parseSingleDependency.
/**
* Parse a string into a dependency specification.
*
* @param dependency string in the format of one service dependency
* @return a pair of dependency name and type
* @throws InputValidationException if the dependency string has invalid format
*/
public static Pair<String, DependencyType> parseSingleDependency(String dependency) throws InputValidationException {
String[] dependencyInfo = dependency.split(":");
if (dependencyInfo.length == 0 || dependencyInfo.length > 2) {
throw new InputValidationException("Bad dependency syntax");
}
String typeString = dependencyInfo.length > 1 ? dependencyInfo[1] : null;
DependencyType type = null;
if (typeString != null && !typeString.isEmpty()) {
// do "friendly" match
for (DependencyType s : DependencyType.values()) {
if (typeString.regionMatches(true, 0, s.name(), 0, typeString.length())) {
type = s;
break;
}
}
if (type == null) {
throw new InputValidationException(typeString + " does not match any Service dependency type");
}
}
return new Pair<>(dependencyInfo[0], type == null ? DependencyType.HARD : type);
}
use of com.aws.greengrass.util.Pair in project aws-greengrass-nucleus by aws-greengrass.
the class ConfigStoreIPCEventStreamAgent method validateConfiguration.
/**
* Trigger a validate event to service/component, typically used during deployments.
*
* @param componentName service/component to send validate event to
* @param deploymentId deployment id which is being validated
* @param configuration new component configuration to validate
* @param reportFuture future to track validation report in response to the event
* @return true if the service has registered a validator, false if not
* @throws ValidateEventRegistrationException throws when triggering requested validation event failed
*/
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public boolean validateConfiguration(String componentName, String deploymentId, Map<String, Object> configuration, CompletableFuture<ConfigurationValidityReport> reportFuture) throws ValidateEventRegistrationException {
for (Map.Entry<String, BiConsumer<String, Map<String, Object>>> e : configValidationListeners.entrySet()) {
if (e.getKey().equals(componentName)) {
Pair componentToDeploymentId = new Pair<>(componentName, deploymentId);
try {
configValidationReportFutures.put(componentToDeploymentId, reportFuture);
e.getValue().accept(deploymentId, configuration);
return true;
} catch (Exception ex) {
// TODO: [P41211196]: Retries, timeouts & and better exception handling in sending server event to
// components
configValidationReportFutures.remove(componentToDeploymentId);
throw new ValidateEventRegistrationException(ex);
}
}
}
return false;
}
use of com.aws.greengrass.util.Pair 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 com.aws.greengrass.util.Pair in project aws-greengrass-nucleus by aws-greengrass.
the class MqttClientTest method GIVEN_incoming_message_WHEN_received_and_subscriber_throws_THEN_still_calls_remaining_subscriptions.
@Test
void GIVEN_incoming_message_WHEN_received_and_subscriber_throws_THEN_still_calls_remaining_subscriptions(ExtensionContext context) throws ExecutionException, InterruptedException, TimeoutException {
ignoreExceptionWithMessage(context, "Uncaught!");
MqttClient client = spy(new MqttClient(deviceConfiguration, (c) -> builder, ses, executorService));
AwsIotMqttClient mockIndividual = mock(AwsIotMqttClient.class);
when(mockIndividual.subscribe(any(), any())).thenReturn(CompletableFuture.completedFuture(0));
when(client.getNewMqttClient()).thenReturn(mockIndividual);
assertFalse(client.connected());
client.subscribe(SubscribeRequest.builder().topic("A/B/+").callback((m) -> {
throw new RuntimeException("Uncaught!");
}).build());
Pair<CompletableFuture<Void>, Consumer<MqttMessage>> abc = asyncAssertOnConsumer((m) -> {
assertEquals("A/B/C", m.getTopic());
});
client.subscribe(SubscribeRequest.builder().topic("A/B/C").callback(abc.getRight()).build());
Consumer<MqttMessage> handler = client.getMessageHandlerForClient(mockIndividual);
handler.accept(new MqttMessage("A/B/C", new byte[0]));
abc.getLeft().get(0, TimeUnit.SECONDS);
}
Aggregations