Search in sources :

Example 6 with Channel

use of herddb.network.Channel in project herddb by diennea.

the class RoutedClientSideConnection method ensureOpen.

@Override
public Channel ensureOpen() throws HDBException {
    connectionLock.readLock().lock();
    try {
        Channel channel = this.channel;
        if (channel != null && channel.isValid()) {
            return channel;
        }
        connectionLock.readLock().unlock();
        connectionLock.writeLock().lock();
        try {
            channel = this.channel;
            if (this.channel != null) {
                if (channel.isValid()) {
                    return channel;
                }
                // channel is not valid, force close
                channel.close();
            }
            // clean up local cache, if the server restarted we would use old ids
            preparedStatements.clear();
            LOGGER.log(Level.FINE, "{0} - connect to {1}:{2} ssh:{3}", new Object[] { this, server.getHost(), server.getPort(), server.isSsl() });
            channel = this.connection.getClient().createChannelTo(server, this);
            try {
                performAuthentication(channel, server.getHost());
                this.channel = channel;
                return channel;
            } catch (TimeoutException err) {
                LOGGER.log(Level.SEVERE, "Error", err);
                if (channel != null) {
                    channel.close();
                }
                throw new HDBOperationTimeoutException(err);
            } catch (Exception err) {
                LOGGER.log(Level.SEVERE, "Error", err);
                if (channel != null) {
                    channel.close();
                }
                throw err;
            }
        } finally {
            connectionLock.writeLock().unlock();
            connectionLock.readLock().lock();
        }
    } catch (java.net.ConnectException err) {
        // this error will be retryed by the client
        throw new UnreachableServerException("Cannot connect to " + nodeId, err, nodeId);
    } catch (HDBException err) {
        throw err;
    } catch (Exception err) {
        throw new HDBException(err);
    } finally {
        connectionLock.readLock().unlock();
    }
}
Also used : UnreachableServerException(herddb.client.impl.UnreachableServerException) HDBOperationTimeoutException(herddb.client.impl.HDBOperationTimeoutException) Channel(herddb.network.Channel) HDBOperationTimeoutException(herddb.client.impl.HDBOperationTimeoutException) LeaderChangedException(herddb.client.impl.LeaderChangedException) RetryRequestException(herddb.client.impl.RetryRequestException) TimeoutException(java.util.concurrent.TimeoutException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) UnreachableServerException(herddb.client.impl.UnreachableServerException) DataStorageManagerException(herddb.storage.DataStorageManagerException) HDBOperationTimeoutException(herddb.client.impl.HDBOperationTimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 7 with Channel

use of herddb.network.Channel in project herddb by diennea.

the class RoutedClientSideConnection method executeUpdates.

public List<DMLResult> executeUpdates(String tableSpace, String query, long tx, boolean returnValues, boolean usePreparedStatement, List<List<Object>> batch) throws HDBException, ClientSideMetadataProviderException {
    try {
        Channel channel = ensureOpen();
        long requestId = channel.generateRequestId();
        long statementId = usePreparedStatement ? prepareQuery(tableSpace, query) : 0;
        query = statementId > 0 ? "" : query;
        ByteBuf message = PduCodec.ExecuteStatements.write(requestId, tableSpace, query, tx, returnValues, statementId, batch);
        try (Pdu reply = channel.sendMessageWithPduReply(requestId, message, timeout)) {
            if (reply.type == Pdu.TYPE_ERROR) {
                handleGenericError(reply, statementId);
                // not possible, handleGenericError always throws an error
                return Collections.emptyList();
            } else if (reply.type != Pdu.TYPE_EXECUTE_STATEMENTS_RESULT) {
                throw new HDBException(reply);
            }
            long transactionId = PduCodec.ExecuteStatementsResult.readTx(reply);
            List<Long> updateCounts = PduCodec.ExecuteStatementsResult.readUpdateCounts(reply);
            int numResults = updateCounts.size();
            List<DMLResult> results = new ArrayList<>(numResults);
            PduCodec.ListOfListsReader resultRecords = PduCodec.ExecuteStatementsResult.startResultRecords(reply);
            int numResultRecords = resultRecords.getNumLists();
            for (int i = 0; i < numResults; i++) {
                Map<RawString, Object> newvalue = null;
                Object key = null;
                if (numResultRecords > 0) {
                    PduCodec.ObjectListReader list = resultRecords.nextList();
                    newvalue = readParametersListAsMap(list);
                    if (newvalue != null) {
                        key = newvalue.get(RAWSTRING_KEY);
                    }
                }
                long updateCount = updateCounts.get(i);
                DMLResult res = new DMLResult(updateCount, key, newvalue, transactionId);
                results.add(res);
            }
            return results;
        }
    } catch (InterruptedException err) {
        Thread.currentThread().interrupt();
        throw new HDBException(err);
    } catch (TimeoutException err) {
        throw new HDBException(err);
    }
}
Also used : Pdu(herddb.proto.Pdu) RawString(herddb.utils.RawString) Channel(herddb.network.Channel) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) PduCodec(herddb.proto.PduCodec) AtomicLong(java.util.concurrent.atomic.AtomicLong) HDBOperationTimeoutException(herddb.client.impl.HDBOperationTimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with Channel

use of herddb.network.Channel in project herddb by diennea.

the class RoutedClientSideConnection method beginTransaction.

@Override
public long beginTransaction(String tableSpace) throws HDBException, ClientSideMetadataProviderException {
    Channel channel = ensureOpen();
    try {
        long requestId = channel.generateRequestId();
        ByteBuf message = PduCodec.TxCommand.write(requestId, PduCodec.TxCommand.TX_COMMAND_BEGIN_TRANSACTION, 0, tableSpace);
        try (Pdu reply = channel.sendMessageWithPduReply(requestId, message, timeout)) {
            if (reply.type == Pdu.TYPE_ERROR) {
                handleGenericError(reply, 0);
                // not possible
                return -1;
            } else if (reply.type == Pdu.TYPE_TX_COMMAND_RESULT) {
                long tx = PduCodec.TxCommandResult.readTx(reply);
                if (tx <= 0) {
                    throw new HDBException("Server did not create a new transaction");
                }
                return tx;
            } else {
                throw new HDBException(reply);
            }
        }
    } catch (InterruptedException err) {
        Thread.currentThread().interrupt();
        throw new HDBException(err);
    } catch (TimeoutException err) {
        throw new HDBException(err);
    }
}
Also used : Pdu(herddb.proto.Pdu) Channel(herddb.network.Channel) ByteBuf(io.netty.buffer.ByteBuf) HDBOperationTimeoutException(herddb.client.impl.HDBOperationTimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 9 with Channel

use of herddb.network.Channel in project herddb by diennea.

the class RoutedClientSideConnection method executeUpdatesAsync.

@Override
public CompletableFuture<List<DMLResult>> executeUpdatesAsync(String tableSpace, String query, long tx, boolean returnValues, boolean usePreparedStatement, List<List<Object>> batch) {
    CompletableFuture<List<DMLResult>> res = new CompletableFuture<>();
    try {
        Channel channel = ensureOpen();
        long requestId = channel.generateRequestId();
        long statementId = usePreparedStatement ? prepareQuery(tableSpace, query) : 0;
        query = statementId > 0 ? "" : query;
        ByteBuf message = PduCodec.ExecuteStatements.write(requestId, tableSpace, query, tx, returnValues, statementId, batch);
        channel.sendRequestWithAsyncReply(requestId, message, timeout, (msg, error) -> {
            if (error != null) {
                res.completeExceptionally(error);
                return;
            }
            try (Pdu reply = msg) {
                if (reply.type == Pdu.TYPE_ERROR) {
                    handleGenericError(reply, statementId);
                    return;
                } else if (reply.type != Pdu.TYPE_EXECUTE_STATEMENTS_RESULT) {
                    throw new HDBException(reply);
                }
                long transactionId = PduCodec.ExecuteStatementsResult.readTx(reply);
                List<Long> updateCounts = PduCodec.ExecuteStatementsResult.readUpdateCounts(reply);
                int numResults = updateCounts.size();
                List<DMLResult> results = new ArrayList<>(numResults);
                PduCodec.ListOfListsReader resultRecords = PduCodec.ExecuteStatementsResult.startResultRecords(reply);
                int numResultRecords = resultRecords.getNumLists();
                for (int i = 0; i < numResults; i++) {
                    Map<RawString, Object> newvalue = null;
                    Object key = null;
                    if (numResultRecords > 0) {
                        PduCodec.ObjectListReader list = resultRecords.nextList();
                        newvalue = readParametersListAsMap(list);
                        if (newvalue != null) {
                            key = newvalue.get(RAWSTRING_KEY);
                        }
                    }
                    long updateCount = updateCounts.get(i);
                    DMLResult _res = new DMLResult(updateCount, key, newvalue, transactionId);
                    results.add(_res);
                }
                res.complete(results);
            } catch (HDBException | ClientSideMetadataProviderException err) {
                res.completeExceptionally(err);
            }
        });
    } catch (HDBException | ClientSideMetadataProviderException err) {
        res.completeExceptionally(err);
    }
    return res;
}
Also used : Pdu(herddb.proto.Pdu) RawString(herddb.utils.RawString) Channel(herddb.network.Channel) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) PduCodec(herddb.proto.PduCodec) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicLong(java.util.concurrent.atomic.AtomicLong) ArrayList(java.util.ArrayList) List(java.util.List)

Example 10 with Channel

use of herddb.network.Channel in project herddb by diennea.

the class RoutedClientSideConnection method executeUpdate.

@Override
public DMLResult executeUpdate(String tableSpace, String query, long tx, boolean returnValues, boolean usePreparedStatement, List<Object> params) throws HDBException, ClientSideMetadataProviderException {
    Channel channel = ensureOpen();
    try {
        long requestId = channel.generateRequestId();
        long statementId = usePreparedStatement ? prepareQuery(tableSpace, query) : 0;
        query = statementId > 0 ? "" : query;
        ByteBuf message = PduCodec.ExecuteStatement.write(requestId, tableSpace, query, tx, returnValues, statementId, params);
        try (Pdu reply = channel.sendMessageWithPduReply(requestId, message, timeout)) {
            if (reply.type == Pdu.TYPE_ERROR) {
                handleGenericError(reply, statementId);
            } else if (reply.type != Pdu.TYPE_EXECUTE_STATEMENT_RESULT) {
                throw new HDBException(reply);
            }
            long updateCount = PduCodec.ExecuteStatementResult.readUpdateCount(reply);
            long transactionId = PduCodec.ExecuteStatementResult.readTx(reply);
            boolean hasData = PduCodec.ExecuteStatementResult.hasRecord(reply);
            Object key = null;
            Map<RawString, Object> newvalue = null;
            if (hasData) {
                PduCodec.ObjectListReader parametersReader = PduCodec.ExecuteStatementResult.readRecord(reply);
                newvalue = readParametersListAsMap(parametersReader);
                key = newvalue.get(RAWSTRING_KEY);
            }
            return new DMLResult(updateCount, key, newvalue, transactionId);
        }
    } catch (InterruptedException err) {
        Thread.currentThread().interrupt();
        throw new HDBException(err);
    } catch (TimeoutException err) {
        throw new HDBException(err);
    }
}
Also used : Pdu(herddb.proto.Pdu) RawString(herddb.utils.RawString) Channel(herddb.network.Channel) ByteBuf(io.netty.buffer.ByteBuf) PduCodec(herddb.proto.PduCodec) HDBOperationTimeoutException(herddb.client.impl.HDBOperationTimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Channel (herddb.network.Channel)27 Pdu (herddb.proto.Pdu)19 TimeoutException (java.util.concurrent.TimeoutException)18 ByteBuf (io.netty.buffer.ByteBuf)17 HDBOperationTimeoutException (herddb.client.impl.HDBOperationTimeoutException)12 Test (org.junit.Test)9 ChannelEventListener (herddb.network.ChannelEventListener)8 ExecutorService (java.util.concurrent.ExecutorService)8 ServerSideConnection (herddb.network.ServerSideConnection)7 RawString (herddb.utils.RawString)7 Random (java.util.Random)7 AtomicLong (java.util.concurrent.atomic.AtomicLong)7 PduCodec (herddb.proto.PduCodec)6 ArrayList (java.util.ArrayList)6 List (java.util.List)5 Message (herddb.network.Message)4 ServerConfiguration (herddb.server.ServerConfiguration)4 DataStorageManagerException (herddb.storage.DataStorageManagerException)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 CompletableFuture (java.util.concurrent.CompletableFuture)4