Search in sources :

Example 6 with IgniteException

use of org.apache.ignite.IgniteException in project ignite by apache.

the class MessagingPingPongListenActorExample method main.

/**
     * Executes example.
     *
     * @param args Command line arguments, none required.
     */
public static void main(String[] args) {
    // Game is played over the default ignite.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        if (!ExamplesUtils.checkMinTopologySize(ignite.cluster(), 2))
            return;
        System.out.println();
        System.out.println(">>> Messaging ping-pong listen actor example started.");
        // Pick first remote node as a partner.
        Collection<ClusterNode> rmtNodes = ignite.cluster().forRemotes().nodes();
        ClusterGroup nodeB = ignite.cluster().forNode(rmtNodes.iterator().next());
        // Note that both nodeA and nodeB will always point to
        // same nodes regardless of whether they were implicitly
        // serialized and deserialized on another node as part of
        // anonymous closure's state during its remote execution.
        // Set up remote player.
        ignite.message(nodeB).remoteListen(null, new MessagingListenActor<String>() {

            @Override
            public void receive(UUID nodeId, String rcvMsg) {
                System.out.println(rcvMsg);
                if ("PING".equals(rcvMsg))
                    respond("PONG");
                else if ("STOP".equals(rcvMsg))
                    stop();
            }
        });
        int MAX_PLAYS = 10;
        final CountDownLatch cnt = new CountDownLatch(MAX_PLAYS);
        // Set up local player.
        ignite.message().localListen(null, new MessagingListenActor<String>() {

            @Override
            protected void receive(UUID nodeId, String rcvMsg) throws IgniteException {
                System.out.println(rcvMsg);
                if (cnt.getCount() == 1)
                    stop("STOP");
                else if ("PONG".equals(rcvMsg))
                    respond("PING");
                cnt.countDown();
            }
        });
        // Serve!
        ignite.message(nodeB).send(null, "PING");
        // Wait til the game is over.
        try {
            cnt.await();
        } catch (InterruptedException e) {
            System.err.println("Hm... let us finish the game!\n" + e);
        }
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteException(org.apache.ignite.IgniteException) ClusterGroup(org.apache.ignite.cluster.ClusterGroup) Ignite(org.apache.ignite.Ignite) UUID(java.util.UUID) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 7 with IgniteException

use of org.apache.ignite.IgniteException in project ignite by apache.

the class CassandraSessionImpl method execute.

/** {@inheritDoc} */
@Override
public void execute(BatchLoaderAssistant assistant) {
    int attempt = 0;
    String errorMsg = "Failed to execute Cassandra " + assistant.operationName() + " operation";
    Throwable error = new IgniteException(errorMsg);
    RandomSleeper sleeper = newSleeper();
    incrementSessionRefs();
    try {
        while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
            if (attempt != 0)
                log.warning("Trying " + (attempt + 1) + " attempt to load Ignite cache");
            Statement statement = tuneStatementExecutionOptions(assistant.getStatement());
            try {
                ResultSetFuture fut = session().executeAsync(statement);
                ResultSet resSet = fut.getUninterruptibly();
                if (resSet == null || !resSet.iterator().hasNext())
                    return;
                for (Row row : resSet) assistant.process(row);
                return;
            } catch (Throwable e) {
                error = e;
                if (CassandraHelper.isTableAbsenceError(e))
                    return;
                else if (CassandraHelper.isHostsAvailabilityError(e))
                    handleHostsAvailabilityError(e, attempt, errorMsg);
                else if (CassandraHelper.isPreparedStatementClusterError(e))
                    handlePreparedStatementClusterError(e);
                else
                    // For an error which we don't know how to handle, we will not try next attempts and terminate.
                    throw new IgniteException(errorMsg, e);
            }
            sleeper.sleep();
            attempt++;
        }
    } catch (Throwable e) {
        error = e;
    } finally {
        decrementSessionRefs();
    }
    log.error(errorMsg, error);
    throw new IgniteException(errorMsg, error);
}
Also used : ResultSetFuture(com.datastax.driver.core.ResultSetFuture) IgniteException(org.apache.ignite.IgniteException) PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) BatchStatement(com.datastax.driver.core.BatchStatement) Statement(com.datastax.driver.core.Statement) ResultSet(com.datastax.driver.core.ResultSet) RandomSleeper(org.apache.ignite.cache.store.cassandra.common.RandomSleeper) Row(com.datastax.driver.core.Row)

Example 8 with IgniteException

use of org.apache.ignite.IgniteException in project ignite by apache.

the class CassandraSessionImpl method createTableIndexes.

/**
     * Creates Cassandra table indexes.
     *
     * @param settings Persistence settings.
     */
private void createTableIndexes(String table, KeyValuePersistenceSettings settings) {
    List<String> indexDDLStatements = settings.getIndexDDLStatements(table);
    if (indexDDLStatements == null || indexDDLStatements.isEmpty())
        return;
    int attempt = 0;
    Throwable error = null;
    String tableFullName = settings.getKeyspace() + "." + table;
    String errorMsg = "Failed to create indexes for Cassandra table " + tableFullName;
    while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
        try {
            log.info("-----------------------------------------------------------------------");
            log.info("Creating indexes for Cassandra table '" + tableFullName + "'");
            log.info("-----------------------------------------------------------------------");
            for (String statement : indexDDLStatements) {
                try {
                    log.info(statement);
                    log.info("-----------------------------------------------------------------------");
                    session().execute(statement);
                } catch (AlreadyExistsException ignored) {
                } catch (Throwable e) {
                    if (!(e instanceof InvalidQueryException) || !"Index already exists".equals(e.getMessage()))
                        throw new IgniteException(errorMsg, e);
                }
            }
            log.info("Indexes for Cassandra table '" + tableFullName + "' were successfully created");
            return;
        } catch (Throwable e) {
            if (CassandraHelper.isHostsAvailabilityError(e))
                handleHostsAvailabilityError(e, attempt, errorMsg);
            else if (CassandraHelper.isTableAbsenceError(e))
                createTable(table, settings);
            else
                throw new IgniteException(errorMsg, e);
            error = e;
        }
        attempt++;
    }
    throw new IgniteException(errorMsg, error);
}
Also used : AlreadyExistsException(com.datastax.driver.core.exceptions.AlreadyExistsException) IgniteException(org.apache.ignite.IgniteException) InvalidQueryException(com.datastax.driver.core.exceptions.InvalidQueryException)

Example 9 with IgniteException

use of org.apache.ignite.IgniteException in project ignite by apache.

the class CassandraSessionImpl method handleHostsAvailabilityError.

/**
     * Handles situation when Cassandra host which is responsible for CQL query execution became unavailable.
     *
     * @param e Exception to handle.
     * @param attempt Number of attempts.
     * @param msg Error message.
     * @return {@code true} if host unavailability was successfully handled.
     */
private boolean handleHostsAvailabilityError(Throwable e, int attempt, String msg) {
    if (attempt >= CQL_EXECUTION_ATTEMPTS_COUNT) {
        log.error("Host availability problem detected. " + "Number of CQL execution attempts reached maximum " + CQL_EXECUTION_ATTEMPTS_COUNT + ", exception will be thrown to upper execution layer.", e);
        throw msg == null ? new IgniteException(e) : new IgniteException(msg, e);
    }
    if (attempt == CQL_EXECUTION_ATTEMPTS_COUNT / 4 || attempt == CQL_EXECUTION_ATTEMPTS_COUNT / 2 || attempt == CQL_EXECUTION_ATTEMPTS_COUNT / 2 + CQL_EXECUTION_ATTEMPTS_COUNT / 4 || attempt == CQL_EXECUTION_ATTEMPTS_COUNT - 1) {
        log.warning("Host availability problem detected, CQL execution attempt  " + (attempt + 1) + ", " + "refreshing Cassandra session", e);
        refresh();
        log.warning("Cassandra session refreshed");
        return true;
    }
    log.warning("Host availability problem detected, CQL execution attempt " + (attempt + 1) + ", " + "sleeping extra " + CQL_EXECUTION_ATTEMPT_MAX_TIMEOUT + " milliseconds", e);
    try {
        Thread.sleep(CQL_EXECUTION_ATTEMPT_MAX_TIMEOUT);
    } catch (InterruptedException ignored) {
    }
    log.warning("Sleep completed");
    return false;
}
Also used : IgniteException(org.apache.ignite.IgniteException)

Example 10 with IgniteException

use of org.apache.ignite.IgniteException in project ignite by apache.

the class CassandraSessionImpl method execute.

/** {@inheritDoc} */
@Override
public void execute(List<Mutation> mutations) {
    if (mutations == null || mutations.isEmpty())
        return;
    Throwable error = null;
    String errorMsg = "Failed to apply " + mutations.size() + " mutations performed withing Ignite " + "transaction into Cassandra";
    int attempt = 0;
    boolean tableExistenceRequired = false;
    Map<String, PreparedStatement> statements = new HashMap<>();
    Map<String, KeyValuePersistenceSettings> tableSettings = new HashMap<>();
    RandomSleeper sleeper = newSleeper();
    incrementSessionRefs();
    try {
        while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
            error = null;
            if (attempt != 0) {
                log.warning("Trying " + (attempt + 1) + " attempt to apply " + mutations.size() + " mutations " + "performed withing Ignite transaction into Cassandra");
            }
            try {
                BatchStatement batch = new BatchStatement();
                // accumulating all the mutations into one Cassandra logged batch
                for (Mutation mutation : mutations) {
                    String key = mutation.getTable() + mutation.getClass().getName();
                    PreparedStatement st = statements.get(key);
                    if (st == null) {
                        st = prepareStatement(mutation.getTable(), mutation.getStatement(), mutation.getPersistenceSettings(), mutation.tableExistenceRequired());
                        if (st != null)
                            statements.put(key, st);
                    }
                    if (st != null)
                        batch.add(mutation.bindStatement(st));
                    if (attempt == 0) {
                        if (mutation.tableExistenceRequired()) {
                            tableExistenceRequired = true;
                            if (!tableSettings.containsKey(mutation.getTable()))
                                tableSettings.put(mutation.getTable(), mutation.getPersistenceSettings());
                        }
                    }
                }
                // committing logged batch into Cassandra
                if (batch.size() > 0)
                    session().execute(tuneStatementExecutionOptions(batch));
                return;
            } catch (Throwable e) {
                error = e;
                if (CassandraHelper.isTableAbsenceError(e)) {
                    if (tableExistenceRequired) {
                        for (Map.Entry<String, KeyValuePersistenceSettings> entry : tableSettings.entrySet()) handleTableAbsenceError(entry.getKey(), entry.getValue());
                    } else
                        return;
                } else if (CassandraHelper.isHostsAvailabilityError(e)) {
                    if (handleHostsAvailabilityError(e, attempt, errorMsg))
                        statements.clear();
                } else if (CassandraHelper.isPreparedStatementClusterError(e)) {
                    handlePreparedStatementClusterError(e);
                    statements.clear();
                } else {
                    // For an error which we don't know how to handle, we will not try next attempts and terminate.
                    throw new IgniteException(errorMsg, e);
                }
            }
            if (!CassandraHelper.isTableAbsenceError(error))
                sleeper.sleep();
            attempt++;
        }
    } catch (Throwable e) {
        error = e;
    } finally {
        decrementSessionRefs();
    }
    log.error(errorMsg, error);
    throw new IgniteException(errorMsg, error);
}
Also used : HashMap(java.util.HashMap) PreparedStatement(com.datastax.driver.core.PreparedStatement) KeyValuePersistenceSettings(org.apache.ignite.cache.store.cassandra.persistence.KeyValuePersistenceSettings) IgniteException(org.apache.ignite.IgniteException) BatchStatement(com.datastax.driver.core.BatchStatement) RandomSleeper(org.apache.ignite.cache.store.cassandra.common.RandomSleeper) Mutation(org.apache.ignite.cache.store.cassandra.session.transaction.Mutation)

Aggregations

IgniteException (org.apache.ignite.IgniteException)414 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)114 Ignite (org.apache.ignite.Ignite)82 ClusterNode (org.apache.ignite.cluster.ClusterNode)47 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)42 ArrayList (java.util.ArrayList)40 UUID (java.util.UUID)40 CountDownLatch (java.util.concurrent.CountDownLatch)40 IOException (java.io.IOException)32 HashMap (java.util.HashMap)32 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)31 CacheException (javax.cache.CacheException)31 Transaction (org.apache.ignite.transactions.Transaction)28 CyclicBarrier (java.util.concurrent.CyclicBarrier)21 Map (java.util.Map)20 IgniteCache (org.apache.ignite.IgniteCache)19 ClusterStartNodeResult (org.apache.ignite.cluster.ClusterStartNodeResult)18 Nullable (org.jetbrains.annotations.Nullable)18 List (java.util.List)17 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)16