Search in sources :

Example 36 with IgniteException

use of org.apache.ignite.lang.IgniteException in project ignite-3 by apache.

the class DefaultMessagingService method onMessage.

/**
 * Handles an incoming messages.
 *
 * @param obj Incoming message wrapper.
 */
private void onMessage(InNetworkObject obj) {
    if (isInNetworkThread()) {
        inboundService.submit(() -> onMessage(obj));
        return;
    }
    NetworkMessage msg = obj.message();
    DescriptorRegistry registry = obj.registry();
    String consistentId = obj.consistentId();
    try {
        msg.unmarshal(marshaller, registry);
    } catch (Exception e) {
        throw new IgniteException("Failed to unmarshal message: " + e.getMessage(), e);
    }
    if (msg instanceof InvokeResponse) {
        InvokeResponse response = (InvokeResponse) msg;
        onInvokeResponse(response.message(), response.correlationId());
        return;
    }
    Long correlationId = null;
    NetworkMessage message = msg;
    if (msg instanceof InvokeRequest) {
        // Unwrap invocation request
        InvokeRequest messageWithCorrelation = (InvokeRequest) msg;
        correlationId = messageWithCorrelation.correlationId();
        message = messageWithCorrelation.message();
    }
    ClusterNode sender = topologyService.getByConsistentId(consistentId);
    NetworkAddress senderAddress;
    if (sender != null) {
        senderAddress = sender.address();
    } else {
        // TODO: IGNITE-16373 Use fake address if sender is not in cluster yet. For the response, consistentId from this address will
        // be used
        senderAddress = new NetworkAddress(UNKNOWN_HOST, UNKNOWN_HOST_PORT, consistentId);
    }
    for (NetworkMessageHandler networkMessageHandler : getMessageHandlers(message.groupType())) {
        // TODO: IGNITE-16373 We should pass ClusterNode and not the address
        networkMessageHandler.onReceived(message, senderAddress, correlationId);
    }
}
Also used : InvokeResponse(org.apache.ignite.internal.network.message.InvokeResponse) DescriptorRegistry(org.apache.ignite.internal.network.serialization.DescriptorRegistry) ClassDescriptorRegistry(org.apache.ignite.internal.network.serialization.ClassDescriptorRegistry) IgniteException(org.apache.ignite.lang.IgniteException) AtomicLong(java.util.concurrent.atomic.AtomicLong) InvokeRequest(org.apache.ignite.internal.network.message.InvokeRequest) IgniteException(org.apache.ignite.lang.IgniteException) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException)

Example 37 with IgniteException

use of org.apache.ignite.lang.IgniteException in project ignite-3 by apache.

the class RaftGroupServiceImpl method sendWithRetry.

/**
 * Retries a request until success or timeout.
 *
 * @param peer Target peer.
 * @param req The request.
 * @param stopTime Stop time.
 * @param fut The future.
 * @param <R> Response type.
 */
private <R> void sendWithRetry(Peer peer, Object req, long stopTime, CompletableFuture<R> fut) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("sendWithRetry peers={} req={} from={} to={}", peers, S.toString(req), cluster.topologyService().localMember().address(), peer.address());
    }
    if (currentTimeMillis() >= stopTime) {
        fut.completeExceptionally(new TimeoutException());
        return;
    }
    CompletableFuture<?> fut0 = cluster.messagingService().invoke(peer.address(), (NetworkMessage) req, rpcTimeout);
    // TODO: IGNITE-15389 org.apache.ignite.internal.metastorage.client.CursorImpl has potential deadlock inside
    fut0.whenCompleteAsync(new BiConsumer<Object, Throwable>() {

        @Override
        public void accept(Object resp, Throwable err) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("sendWithRetry resp={} from={} to={} err={}", S.toString(resp), cluster.topologyService().localMember().address(), peer.address(), err == null ? null : err.getMessage());
            }
            if (err != null) {
                if (recoverable(err)) {
                    executor.schedule(() -> {
                        sendWithRetry(randomNode(), req, stopTime, fut);
                        return null;
                    }, retryDelay, TimeUnit.MILLISECONDS);
                } else {
                    fut.completeExceptionally(err);
                }
            } else if (resp instanceof RpcRequests.ErrorResponse) {
                RpcRequests.ErrorResponse resp0 = (RpcRequests.ErrorResponse) resp;
                if (resp0.errorCode() == RaftError.SUCCESS.getNumber()) {
                    // Handle OK response.
                    // The OK response was received from a leader.
                    leader = peer;
                    // Void response.
                    fut.complete(null);
                } else if (resp0.errorCode() == RaftError.EBUSY.getNumber() || resp0.errorCode() == (RaftError.EAGAIN.getNumber()) || resp0.errorCode() == (RaftError.ENOENT.getNumber())) {
                    // Possibly a node has not been started.
                    executor.schedule(() -> {
                        sendWithRetry(peer, req, stopTime, fut);
                        return null;
                    }, retryDelay, TimeUnit.MILLISECONDS);
                } else if (resp0.errorCode() == RaftError.EPERM.getNumber() || // TODO: IGNITE-15706
                resp0.errorCode() == RaftError.UNKNOWN.getNumber() || resp0.errorCode() == RaftError.EINTERNAL.getNumber()) {
                    if (resp0.leaderId() == null) {
                        executor.schedule(() -> {
                            sendWithRetry(randomNode(), req, stopTime, fut);
                            return null;
                        }, retryDelay, TimeUnit.MILLISECONDS);
                    } else {
                        // Update a leader.
                        leader = parsePeer(resp0.leaderId());
                        executor.schedule(() -> {
                            sendWithRetry(leader, req, stopTime, fut);
                            return null;
                        }, retryDelay, TimeUnit.MILLISECONDS);
                    }
                } else {
                    fut.completeExceptionally(new RaftException(RaftError.forNumber(resp0.errorCode()), resp0.errorMsg()));
                }
            } else if (resp instanceof RpcRequests.SMErrorResponse) {
                SMThrowable th = ((RpcRequests.SMErrorResponse) resp).error();
                if (th instanceof SMCompactedThrowable) {
                    SMCompactedThrowable compactedThrowable = (SMCompactedThrowable) th;
                    try {
                        Throwable restoredTh = (Throwable) Class.forName(compactedThrowable.throwableClassName()).getConstructor(String.class).newInstance(compactedThrowable.throwableMessage());
                        fut.completeExceptionally(restoredTh);
                    } catch (Exception e) {
                        LOG.warn("Cannot restore throwable from user's state machine. " + "Check if throwable " + compactedThrowable.throwableClassName() + " is presented in the classpath.");
                        fut.completeExceptionally(new IgniteException(compactedThrowable.throwableMessage()));
                    }
                } else if (th instanceof SMFullThrowable)
                    fut.completeExceptionally(((SMFullThrowable) th).throwable());
            } else {
                // The OK response was received from a leader.
                leader = peer;
                fut.complete((R) resp);
            }
        }
    });
}
Also used : RpcRequests(org.apache.ignite.raft.jraft.rpc.RpcRequests) IgniteException(org.apache.ignite.lang.IgniteException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) IgniteException(org.apache.ignite.lang.IgniteException) TimeoutException(java.util.concurrent.TimeoutException)

Example 38 with IgniteException

use of org.apache.ignite.lang.IgniteException in project ignite-3 by apache.

the class QueryCancel method cancel.

/**
 * Executes cancel closure.
 */
public synchronized void cancel() {
    if (canceled) {
        return;
    }
    canceled = true;
    IgniteException ex = null;
    // Run actions in the reverse order.
    for (int i = cancelActions.size() - 1; i >= 0; i--) {
        try {
            Cancellable act = cancelActions.get(i);
            act.cancel();
        } catch (Exception e) {
            if (ex == null) {
                ex = new IgniteException(e);
            } else {
                ex.addSuppressed(e);
            }
        }
    }
    if (ex != null) {
        throw ex;
    }
}
Also used : IgniteException(org.apache.ignite.lang.IgniteException) Cancellable(org.apache.ignite.internal.util.Cancellable) IgniteException(org.apache.ignite.lang.IgniteException)

Example 39 with IgniteException

use of org.apache.ignite.lang.IgniteException in project ignite-3 by apache.

the class AbstractLockManagerTest method doTestSingleKeyMultithreaded.

/**
 * Do test single key multithreaded.
 *
 * @param duration The duration.
 * @param readLocks Read lock accumulator.
 * @param writeLocks Write lock accumulator.
 * @param failedLocks Failed lock accumulator.
 * @param mode Mode: 0 - read only, 1 - write only, 2 - mixed random.
 * @throws InterruptedException If interrupted while waiting.
 */
private void doTestSingleKeyMultithreaded(long duration, LongAdder readLocks, LongAdder writeLocks, LongAdder failedLocks, int mode) throws InterruptedException {
    Object key = new String("test");
    Thread[] threads = new Thread[Runtime.getRuntime().availableProcessors() * 2];
    CyclicBarrier startBar = new CyclicBarrier(threads.length, () -> log.info("Before test"));
    AtomicBoolean stop = new AtomicBoolean();
    Random r = new Random();
    AtomicReference<Throwable> firstErr = new AtomicReference<>();
    try {
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                try {
                    startBar.await();
                } catch (Exception e) {
                    fail();
                }
                while (!stop.get() && firstErr.get() == null) {
                    Timestamp timestamp = Timestamp.nextVersion();
                    if (mode == 0 ? false : mode == 1 ? true : r.nextBoolean()) {
                        try {
                            lockManager.tryAcquire(key, timestamp).join();
                            writeLocks.increment();
                        } catch (CompletionException e) {
                            failedLocks.increment();
                            continue;
                        }
                        try {
                            lockManager.tryRelease(key, timestamp);
                        } catch (LockException e) {
                            fail(e.getMessage());
                        }
                    } else {
                        try {
                            lockManager.tryAcquireShared(key, timestamp).join();
                            readLocks.increment();
                        } catch (CompletionException e) {
                            if (mode == 0) {
                                fail("Unexpected exception for read only locking mode");
                            }
                            failedLocks.increment();
                            continue;
                        }
                        try {
                            lockManager.tryReleaseShared(key, timestamp);
                        } catch (LockException e) {
                            fail(e.getMessage());
                        }
                    }
                }
            });
            threads[i].setName("Worker" + i);
            threads[i].setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    firstErr.compareAndExchange(null, e);
                }
            });
            threads[i].start();
        }
        Thread.sleep(duration);
        stop.set(true);
    } finally {
        for (Thread thread : threads) {
            thread.join();
        }
    }
    if (firstErr.get() != null) {
        throw new IgniteException(firstErr.get());
    }
    log.info("After test readLocks={} writeLocks={} failedLocks={}", readLocks.sum(), writeLocks.sum(), failedLocks.sum());
    assertTrue(lockManager.queue(key).isEmpty());
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) IgniteException(org.apache.ignite.lang.IgniteException) CompletionException(java.util.concurrent.CompletionException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) IgniteException(org.apache.ignite.lang.IgniteException) CompletionException(java.util.concurrent.CompletionException)

Aggregations

IgniteException (org.apache.ignite.lang.IgniteException)39 ArrayList (java.util.ArrayList)14 IOException (java.io.IOException)10 BinaryRow (org.apache.ignite.internal.schema.BinaryRow)10 NotNull (org.jetbrains.annotations.NotNull)10 Map (java.util.Map)9 MarshallerException (org.apache.ignite.internal.schema.marshaller.MarshallerException)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 HashMap (java.util.HashMap)7 List (java.util.List)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 NodeStoppingException (org.apache.ignite.lang.NodeStoppingException)7 HashSet (java.util.HashSet)6 CompletionException (java.util.concurrent.CompletionException)6 Row (org.apache.ignite.internal.schema.row.Row)6 NoSuchElementException (java.util.NoSuchElementException)5 Set (java.util.Set)5 UUID (java.util.UUID)5 Consumer (java.util.function.Consumer)5 Collectors (java.util.stream.Collectors)5