Search in sources :

Example 1 with RequestTimedOutException

use of org.opennms.core.rpc.api.RequestTimedOutException in project opennms by OpenNMS.

the class DefaultPollContext method testCriticalPath.

private boolean testCriticalPath(CriticalPath criticalPath) {
    if (!"ICMP".equalsIgnoreCase(criticalPath.getServiceName())) {
        LOG.warn("Critical paths using services other than ICMP are not currently supported." + " ICMP will be used for testing {}.", criticalPath);
    }
    final InetAddress ipAddress = criticalPath.getIpAddress();
    final int retries = OpennmsServerConfigFactory.getInstance().getDefaultCriticalPathRetries();
    final int timeout = OpennmsServerConfigFactory.getInstance().getDefaultCriticalPathTimeout();
    boolean available = false;
    try {
        final PingSummary pingSummary = m_locationAwarePingClient.ping(ipAddress).withLocation(criticalPath.getLocationName()).withTimeout(timeout, TimeUnit.MILLISECONDS).withRetries(retries).execute().get();
        // We consider the path to be available if any of the requests were successful
        available = pingSummary.getSequences().stream().filter(PingSequence::isSuccess).count() > 0;
    } catch (InterruptedException e) {
        LOG.warn("Interrupted while testing {}. Marking the path as available.", criticalPath);
        available = true;
    } catch (Throwable e) {
        final Throwable cause = e.getCause();
        if (cause != null && cause instanceof RequestTimedOutException) {
            LOG.warn("No response was received when remotely testing {}." + " Marking the path as available.", criticalPath);
            available = true;
        } else if (cause != null && cause instanceof RequestRejectedException) {
            LOG.warn("Request was rejected when attemtping to test the remote path {}." + " Marking the path as available.", criticalPath);
            available = true;
        }
        LOG.warn("An unknown error occured while testing the critical path: {}." + " Marking the path as unavailable.", criticalPath, e);
        available = false;
    }
    LOG.debug("testCriticalPath: checking {}@{}, available ? {}", criticalPath.getServiceName(), ipAddress, available);
    return available;
}
Also used : RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) PingSummary(org.opennms.netmgt.icmp.proxy.PingSummary) RequestRejectedException(org.opennms.core.rpc.api.RequestRejectedException) InetAddress(java.net.InetAddress)

Example 2 with RequestTimedOutException

use of org.opennms.core.rpc.api.RequestTimedOutException in project opennms by OpenNMS.

the class PollableServiceConfigTest method returnsUnknownOnRequestTimedOutException.

/**
     * Verifies that <b>PollStatus.unknown()</b> is returned when the
     * {@link LocationAwarePollerClient} fails with a {@link RequestTimedOutException}.
     *
     * This can happen when no Minions at the given location are available to process
     * the request, or the request was not completed in time, in which case we cannot
     * ascertain that the service is UP or DOWN.
     */
@Test
public void returnsUnknownOnRequestTimedOutException() throws Exception {
    // Create a future that fails with a RequestTimedOutException
    CompletableFuture<PollerResponse> future = new CompletableFuture<>();
    future.completeExceptionally(new RequestTimedOutException(new Exception("Test")));
    // Now mock the client to always return the future we created above
    LocationAwarePollerClient client = mock(LocationAwarePollerClient.class, Mockito.RETURNS_DEEP_STUBS);
    Mockito.when(client.poll().withService(any()).withMonitor(any()).withTimeToLive(any()).withAttributes(any()).withAdaptor(any()).withAdaptor(any()).execute()).thenReturn(future);
    // Mock all of the required objects required to successfully initialize the PollableServiceConfig
    PollableService pollableSvc = mock(PollableService.class);
    when(pollableSvc.getSvcName()).thenReturn("SVC");
    Service configuredSvc = new Service();
    configuredSvc.setName("SVC");
    Package pkg = mock(Package.class);
    when(pkg.getServices()).thenReturn(Lists.newArrayList(configuredSvc));
    PollerConfig pollerConfig = mock(PollerConfig.class);
    PollOutagesConfig pollOutagesConfig = mock(PollOutagesConfig.class);
    Timer timer = mock(Timer.class);
    PersisterFactory persisterFactory = mock(PersisterFactory.class);
    ResourceStorageDao resourceStorageDao = mock(ResourceStorageDao.class);
    final PollableServiceConfig psc = new PollableServiceConfig(pollableSvc, pollerConfig, pollOutagesConfig, pkg, timer, persisterFactory, resourceStorageDao, client);
    // Trigger the poll
    PollStatus pollStatus = psc.poll();
    // Verify
    assertThat(pollStatus.isUnknown(), is(true));
}
Also used : RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) LocationAwarePollerClient(org.opennms.netmgt.poller.LocationAwarePollerClient) FilesystemResourceStorageDao(org.opennms.netmgt.dao.support.FilesystemResourceStorageDao) ResourceStorageDao(org.opennms.netmgt.dao.api.ResourceStorageDao) PollStatus(org.opennms.netmgt.poller.PollStatus) MockPersisterFactory(org.opennms.netmgt.mock.MockPersisterFactory) PersisterFactory(org.opennms.netmgt.collection.api.PersisterFactory) PollerConfig(org.opennms.netmgt.config.PollerConfig) Service(org.opennms.netmgt.config.poller.Service) RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) CompletableFuture(java.util.concurrent.CompletableFuture) Timer(org.opennms.netmgt.scheduler.Timer) Package(org.opennms.netmgt.config.poller.Package) PollerResponse(org.opennms.netmgt.poller.PollerResponse) PollOutagesConfig(org.opennms.netmgt.config.PollOutagesConfig) Test(org.junit.Test)

Example 3 with RequestTimedOutException

use of org.opennms.core.rpc.api.RequestTimedOutException in project opennms by OpenNMS.

the class CamelRpcClientFactory method getClient.

@Override
public <S extends RpcRequest, T extends RpcResponse> RpcClient<S, T> getClient(RpcModule<S, T> module) {
    return new RpcClient<S, T>() {

        @Override
        public CompletableFuture<T> execute(S request) {
            if (request.getLocation() == null || request.getLocation().equals(location)) {
                // The request is for the current location, invoke it directly
                return module.execute(request);
            }
            // Save the context map and restore it on callback
            final Map<String, String> clientContextMap = Logging.getCopyOfContextMap();
            // Wrap the request in a CamelRpcRequest and forward it to the Camel route
            final CompletableFuture<T> future = new CompletableFuture<>();
            try {
                template.asyncCallbackSendBody(endpoint, new CamelRpcRequest<>(module, request), new Synchronization() {

                    @Override
                    public void onComplete(Exchange exchange) {
                        try (MDCCloseable mdc = Logging.withContextMapCloseable(clientContextMap)) {
                            final T response = module.unmarshalResponse(exchange.getOut().getBody(String.class));
                            if (response.getErrorMessage() != null) {
                                future.completeExceptionally(new RemoteExecutionException(response.getErrorMessage()));
                            } else {
                                future.complete(response);
                            }
                        } catch (Throwable ex) {
                            LOG.error("Unmarshalling a response in RPC module {} failed.", module, ex);
                            future.completeExceptionally(ex);
                        }
                        // Ensure that future log statements on this thread are routed properly
                        Logging.putPrefix(RpcClientFactory.LOG_PREFIX);
                    }

                    @Override
                    public void onFailure(Exchange exchange) {
                        try (MDCCloseable mdc = Logging.withContextMapCloseable(clientContextMap)) {
                            final ExchangeTimedOutException timeoutException = exchange.getException(ExchangeTimedOutException.class);
                            final DirectConsumerNotAvailableException directConsumerNotAvailableException = exchange.getException(DirectConsumerNotAvailableException.class);
                            if (timeoutException != null) {
                                // Wrap timeout exceptions within a RequestTimedOutException
                                future.completeExceptionally(new RequestTimedOutException(exchange.getException()));
                            } else if (directConsumerNotAvailableException != null) {
                                // Wrap consumer not available exceptions with a RequestRejectedException
                                future.completeExceptionally(new RequestRejectedException(exchange.getException()));
                            } else {
                                future.completeExceptionally(exchange.getException());
                            }
                        }
                        // Ensure that future log statements on this thread are routed properly
                        Logging.putPrefix(RpcClientFactory.LOG_PREFIX);
                    }
                });
            } catch (IllegalStateException e) {
                try (MDCCloseable mdc = Logging.withContextMapCloseable(clientContextMap)) {
                    // Wrap ProducerTemplate exceptions with a RequestRejectedException
                    future.completeExceptionally(new RequestRejectedException(e));
                }
                // Ensure that future log statements on this thread are routed properly
                Logging.putPrefix(RpcClientFactory.LOG_PREFIX);
            }
            return future;
        }
    };
}
Also used : DirectConsumerNotAvailableException(org.apache.camel.component.direct.DirectConsumerNotAvailableException) RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) RequestRejectedException(org.opennms.core.rpc.api.RequestRejectedException) Synchronization(org.apache.camel.spi.Synchronization) Exchange(org.apache.camel.Exchange) RemoteExecutionException(org.opennms.core.rpc.api.RemoteExecutionException) CompletableFuture(java.util.concurrent.CompletableFuture) MDCCloseable(org.opennms.core.logging.Logging.MDCCloseable) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) RpcClient(org.opennms.core.rpc.api.RpcClient)

Example 4 with RequestTimedOutException

use of org.opennms.core.rpc.api.RequestTimedOutException in project opennms by OpenNMS.

the class EchoRpcIT method throwsRequestTimedOutExceptionOnTimeout.

@Test(timeout = CamelRpcClientPreProcessor.CAMEL_JMS_REQUEST_TIMEOUT_DEFAULT * 4)
public void throwsRequestTimedOutExceptionOnTimeout() throws Exception {
    assertNotEquals(REMOTE_LOCATION_NAME, identity.getLocation());
    EchoRpcModule echoRpcModule = new EchoRpcModule();
    CamelContext context = getContext();
    context.getShutdownStrategy().setTimeout(5);
    context.getShutdownStrategy().setTimeUnit(TimeUnit.SECONDS);
    CamelRpcServerRouteManager routeManager = getRouteManager(context);
    routeManager.bind(echoRpcModule);
    EchoRequest request = new EchoRequest("HELLO!!!");
    request.setLocation(REMOTE_LOCATION_NAME);
    request.setDelay(CamelRpcClientPreProcessor.CAMEL_JMS_REQUEST_TIMEOUT_DEFAULT * 2);
    try {
        echoClient.execute(request).get();
        fail("Did not get ExecutionException");
    } catch (ExecutionException e) {
        assertTrue("Cause is not of type RequestTimedOutException: " + ExceptionUtils.getStackTrace(e), e.getCause() instanceof RequestTimedOutException);
        // Verify that the exchange error was logged
        MockLogAppender.assertLogMatched(Level.ERROR, "Message History");
        MockLogAppender.assertLogMatched(Level.ERROR, "direct://executeRpc");
        // Verify that the message body was suppressed
        MockLogAppender.assertNoLogMatched(Level.ERROR, "HELLO!!!");
    }
    routeManager.unbind(echoRpcModule);
    context.stop();
}
Also used : CamelContext(org.apache.camel.CamelContext) EchoRpcModule(org.opennms.core.rpc.echo.EchoRpcModule) RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) EchoRequest(org.opennms.core.rpc.echo.EchoRequest) RemoteExecutionException(org.opennms.core.rpc.api.RemoteExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 5 with RequestTimedOutException

use of org.opennms.core.rpc.api.RequestTimedOutException in project opennms by OpenNMS.

the class EchoRpcIT method failsWithTimeoutWhenSystemIdDoesNotExist.

/**
 * Issues a RPC to a location at which a listener is registered,
 * but specifies a system id that is not equal to the listener's.
 * Since no matching system can process the request, the request
 * should time out.
 */
@Test(timeout = 60000)
public void failsWithTimeoutWhenSystemIdDoesNotExist() throws Exception {
    assertNotEquals(REMOTE_LOCATION_NAME, identity.getLocation());
    EchoRpcModule echoRpcModule = new EchoRpcModule();
    CamelContext context = getContext();
    context.start();
    MinionIdentity minionIdentity = new MockMinionIdentity(REMOTE_LOCATION_NAME);
    CamelRpcServerRouteManager routeManager = getRouteManager(context);
    routeManager.bind(echoRpcModule);
    EchoRequest request = new EchoRequest("HELLO!!!");
    // Use a different system id, other than the one that's actually listening
    request.setSystemId(minionIdentity.getId() + "!");
    request.setLocation(REMOTE_LOCATION_NAME);
    try {
        echoClient.execute(request).get();
        fail("Did not get ExecutionException");
    } catch (ExecutionException e) {
        assertTrue("Cause is not of type RequestTimedOutException: " + ExceptionUtils.getStackTrace(e), e.getCause() instanceof RequestTimedOutException);
    }
    routeManager.unbind(echoRpcModule);
    context.stop();
}
Also used : CamelContext(org.apache.camel.CamelContext) EchoRpcModule(org.opennms.core.rpc.echo.EchoRpcModule) RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) EchoRequest(org.opennms.core.rpc.echo.EchoRequest) MinionIdentity(org.opennms.minion.core.api.MinionIdentity) RemoteExecutionException(org.opennms.core.rpc.api.RemoteExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

RequestTimedOutException (org.opennms.core.rpc.api.RequestTimedOutException)7 Test (org.junit.Test)4 CompletableFuture (java.util.concurrent.CompletableFuture)3 ExecutionException (java.util.concurrent.ExecutionException)3 RemoteExecutionException (org.opennms.core.rpc.api.RemoteExecutionException)3 RequestRejectedException (org.opennms.core.rpc.api.RequestRejectedException)3 CamelContext (org.apache.camel.CamelContext)2 EchoRequest (org.opennms.core.rpc.echo.EchoRequest)2 EchoRpcModule (org.opennms.core.rpc.echo.EchoRpcModule)2 PersisterFactory (org.opennms.netmgt.collection.api.PersisterFactory)2 PollOutagesConfig (org.opennms.netmgt.config.PollOutagesConfig)2 PollerConfig (org.opennms.netmgt.config.PollerConfig)2 Package (org.opennms.netmgt.config.poller.Package)2 Service (org.opennms.netmgt.config.poller.Service)2 ResourceStorageDao (org.opennms.netmgt.dao.api.ResourceStorageDao)2 FilesystemResourceStorageDao (org.opennms.netmgt.dao.support.FilesystemResourceStorageDao)2 MockPersisterFactory (org.opennms.netmgt.mock.MockPersisterFactory)2 LocationAwarePollerClient (org.opennms.netmgt.poller.LocationAwarePollerClient)2 PollStatus (org.opennms.netmgt.poller.PollStatus)2 PollerResponse (org.opennms.netmgt.poller.PollerResponse)2