Search in sources :

Example 1 with Pair

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);
}
Also used : Exec(com.aws.greengrass.util.Exec) LogEventBuilder(com.aws.greengrass.logging.api.LogEventBuilder) IOException(java.io.IOException) Pair(com.aws.greengrass.util.Pair)

Example 2 with Pair

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);
}
Also used : DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) InputValidationException(com.aws.greengrass.lifecyclemanager.exceptions.InputValidationException) Pair(com.aws.greengrass.util.Pair)

Example 3 with Pair

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;
}
Also used : ValidateEventRegistrationException(com.aws.greengrass.builtin.services.configstore.exceptions.ValidateEventRegistrationException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) BiConsumer(java.util.function.BiConsumer) ValidateEventRegistrationException(com.aws.greengrass.builtin.services.configstore.exceptions.ValidateEventRegistrationException) Pair(com.aws.greengrass.util.Pair)

Example 4 with Pair

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")));
}
Also used : SubscribeToComponentUpdatesResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse) CompletableFuture(java.util.concurrent.CompletableFuture) DeferComponentUpdateResponse(software.amazon.awssdk.aws.greengrass.model.DeferComponentUpdateResponse) SubscribeToComponentUpdatesRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesRequest) DeferComponentUpdateRequest(software.amazon.awssdk.aws.greengrass.model.DeferComponentUpdateRequest) Pair(com.aws.greengrass.util.Pair) Test(org.junit.jupiter.api.Test)

Example 5 with Pair

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);
}
Also used : SpoolerStoreException(com.aws.greengrass.mqttclient.spool.SpoolerStoreException) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Matchers.either(org.hamcrest.Matchers.either) DEVICE_PARAM_ROOT_CA_PATH(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_ROOT_CA_PATH) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) TimeoutException(java.util.concurrent.TimeoutException) SpoolMessage(com.aws.greengrass.mqttclient.spool.SpoolMessage) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) DEVICE_PARAM_PRIVATE_KEY_PATH(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_PRIVATE_KEY_PATH) Configuration(com.aws.greengrass.config.Configuration) SpoolerStorageType(com.aws.greengrass.mqttclient.spool.SpoolerStorageType) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) DEFAULT_MQTT_MAX_OF_PUBLISH_RETRY_COUNT(com.aws.greengrass.mqttclient.MqttClient.DEFAULT_MQTT_MAX_OF_PUBLISH_RETRY_COUNT) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) TestUtils(com.aws.greengrass.testcommons.testutilities.TestUtils) Mockito.doNothing(org.mockito.Mockito.doNothing) ExceptionLogProtector.ignoreExceptionOfType(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionOfType) Pair(com.aws.greengrass.util.Pair) StandardCharsets(java.nio.charset.StandardCharsets) ChildChanged(com.aws.greengrass.config.ChildChanged) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) List(java.util.List) DEVICE_PARAM_CERTIFICATE_FILE_PATH(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_CERTIFICATE_FILE_PATH) MAX_NUMBER_OF_FORWARD_SLASHES(com.aws.greengrass.mqttclient.MqttClient.MAX_NUMBER_OF_FORWARD_SLASHES) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) DEVICE_PARAM_AWS_REGION(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_AWS_REGION) Matchers.is(org.hamcrest.Matchers.is) Mockito.mock(org.mockito.Mockito.mock) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Mock(org.mockito.Mock) CompletableFuture(java.util.concurrent.CompletableFuture) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Mockito.spy(org.mockito.Mockito.spy) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) Mockito.lenient(org.mockito.Mockito.lenient) SpoolerConfig(com.aws.greengrass.mqttclient.spool.SpoolerConfig) MQTT_MAX_LIMIT_OF_MESSAGE_SIZE_IN_BYTES(com.aws.greengrass.mqttclient.MqttClient.MQTT_MAX_LIMIT_OF_MESSAGE_SIZE_IN_BYTES) Mockito.timeout(org.mockito.Mockito.timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Context(com.aws.greengrass.dependency.Context) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ExecutorService(java.util.concurrent.ExecutorService) DEVICE_PARAM_IOT_DATA_ENDPOINT(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_IOT_DATA_ENDPOINT) DEVICE_MQTT_NAMESPACE(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_MQTT_NAMESPACE) Spool(com.aws.greengrass.mqttclient.spool.Spool) DEVICE_PARAM_THING_NAME(com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_THING_NAME) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) ExceptionLogProtector.ignoreExceptionWithMessage(com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionWithMessage) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AfterEach(org.junit.jupiter.api.AfterEach) Mockito.never(org.mockito.Mockito.never) WhatHappened(com.aws.greengrass.config.WhatHappened) Collections(java.util.Collections) MAX_LENGTH_OF_TOPIC(com.aws.greengrass.mqttclient.MqttClient.MAX_LENGTH_OF_TOPIC) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test)

Aggregations

Pair (com.aws.greengrass.util.Pair)13 CompletableFuture (java.util.concurrent.CompletableFuture)7 IOException (java.io.IOException)5 List (java.util.List)4 ChildChanged (com.aws.greengrass.config.ChildChanged)3 Configuration (com.aws.greengrass.config.Configuration)3 Topics (com.aws.greengrass.config.Topics)3 WhatHappened (com.aws.greengrass.config.WhatHappened)3 Context (com.aws.greengrass.dependency.Context)3 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)3 DEVICE_MQTT_NAMESPACE (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_MQTT_NAMESPACE)3 DEVICE_PARAM_AWS_REGION (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_AWS_REGION)3 DEVICE_PARAM_CERTIFICATE_FILE_PATH (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_CERTIFICATE_FILE_PATH)3 DEVICE_PARAM_IOT_DATA_ENDPOINT (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_IOT_DATA_ENDPOINT)3 DEVICE_PARAM_PRIVATE_KEY_PATH (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_PRIVATE_KEY_PATH)3 DEVICE_PARAM_ROOT_CA_PATH (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_ROOT_CA_PATH)3 DEVICE_PARAM_THING_NAME (com.aws.greengrass.deployment.DeviceConfiguration.DEVICE_PARAM_THING_NAME)3 DEFAULT_MQTT_MAX_OF_PUBLISH_RETRY_COUNT (com.aws.greengrass.mqttclient.MqttClient.DEFAULT_MQTT_MAX_OF_PUBLISH_RETRY_COUNT)3 MAX_LENGTH_OF_TOPIC (com.aws.greengrass.mqttclient.MqttClient.MAX_LENGTH_OF_TOPIC)3 MAX_NUMBER_OF_FORWARD_SLASHES (com.aws.greengrass.mqttclient.MqttClient.MAX_NUMBER_OF_FORWARD_SLASHES)3