Java Code Examples for org.apache.bookkeeper.common.concurrent.FutureUtils#exception()

The following examples show how to use org.apache.bookkeeper.common.concurrent.FutureUtils#exception() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HDBConnection.java    From herddb with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<List<DMLResult>> executeUpdatesAsync(
        String tableSpace, String query, long tx, boolean returnValues,
        boolean usePreparedStatement, List<List<Object>> batch
) {
    if (batch.isEmpty()) {
        return CompletableFuture.completedFuture(Collections.emptyList());
    }
    if (discoverTablespaceFromSql) {
        tableSpace = discoverTablespace(tableSpace, query);
    }
    if (closed) {
        return FutureUtils.exception(new HDBException("client is closed"));
    }
    CompletableFuture<List<DMLResult>> res = new CompletableFuture<>();

    AtomicInteger count = new AtomicInteger(0);
    executeStatementsAsyncInternal(tableSpace, res, query, tx, returnValues, usePreparedStatement, batch, count);
    return res;
}
 
Example 2
Source File: HDBConnection.java    From herddb with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<DMLResult> executeUpdateAsync(String tableSpace, String query, long tx, boolean returnValues, boolean usePreparedStatement, List<Object> params) {
    if (discoverTablespaceFromSql) {
        tableSpace = discoverTablespace(tableSpace, query);
    }
    if (closed) {
        return FutureUtils.exception(new HDBException("client is closed"));
    }
    CompletableFuture<DMLResult> res = new CompletableFuture<>();

    AtomicInteger count = new AtomicInteger(0);
    executeStatementAsyncInternal(tableSpace, res, query, tx, returnValues, usePreparedStatement, params, count);
    return res;
}
 
Example 3
Source File: TableSpaceManager.java    From herddb with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<StatementExecutionResult> executeTableAwareStatement(Statement statement, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException {
    long lockStamp = context.getTableSpaceLock();
    boolean lockAcquired = false;
    if (lockStamp == 0) {
        lockStamp = acquireReadLock(statement);
        context.setTableSpaceLock(lockStamp);
        lockAcquired = true;
    }
    TableAwareStatement st = (TableAwareStatement) statement;
    String table = st.getTable();
    AbstractTableManager manager = tables.get(table);
    CompletableFuture<StatementExecutionResult> res;
    if (manager == null) {
        res = FutureUtils.exception(new TableDoesNotExistException("no table " + table + " in tablespace " + tableSpaceName));
    } else if (manager.getCreatedInTransaction() > 0
            && (transaction == null || transaction.transactionId != manager.getCreatedInTransaction())) {
        res = FutureUtils.exception(new TableDoesNotExistException("no table " + table + " in tablespace " + tableSpaceName + ". created temporary in transaction " + manager.getCreatedInTransaction()));
    } else {
        res = manager.executeStatementAsync(statement, transaction, context);
    }
    if (lockAcquired) {
        res = releaseReadLock(res, lockStamp, statement)
                .whenComplete((s, err) -> {
                    context.setTableSpaceLock(0);
                });
    }
    return res;

}
 
Example 4
Source File: PulsarMockBookKeeper.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void shutdown() {
    try {
        super.close();
    } catch (Exception e) {
    }
    synchronized (this) {
        defaultResponse = FutureUtils.exception(new BKException.BKClientClosedException());
    }
    for (PulsarMockLedgerHandle ledger : ledgers.values()) {
        ledger.entries.clear();
    }

    ledgers.clear();
}
 
Example 5
Source File: BookkeeperCommitLog.java    From herddb with Apache License 2.0 4 votes vote down vote up
@Override
public CommitLogResult log(LogEntry edit, boolean sync)  {
    CompletableFuture<LogSequenceNumber> res;
    CommitFileWriter _writer = null;
    try {
        _writer = getValidWriter();
    } catch (LogNotAvailableException errorWhileRollingLedger) {
        LOGGER.log(Level.SEVERE, "Cannot get a valid writer for " + tableSpaceDescription(), errorWhileRollingLedger);
    }
    if (failed) {
        res = FutureUtils.exception(new LogNotAvailableException(new Exception("this commitlog is failed, tablespace "
                + tableSpaceDescription() + ", node " + this.localNodeId))
                .fillInStackTrace());
    } else if (closed || _writer == null) {
        res = FutureUtils.exception(new LogNotAvailableException(new Exception("this commitlog has been closed, tablespace "
                + tableSpaceDescription() + ", node " + this.localNodeId))
                .fillInStackTrace());
    } else {
        res = _writer.writeEntry(edit);

        // publish the lastSequenceNumber
        // we must return a new CompletableFuture that completes only
        // AFTER lastSequenceNumber is updated
        // otherwise while doing a checkpoint we could observe
        // an old value for lastSequenceNumber
        // in case of a slow system
        res = res.thenApply((pos) -> {
            if (lastLedgerId == pos.ledgerId) {
                lastSequenceNumber.accumulateAndGet(pos.offset,
                        EnsureLongIncrementAccumulator.INSTANCE);
            }
            notifyListeners(pos, edit);
            return pos;
        }
        );
    }
    if (!sync) {
        // client is not really interested to the result of the write
        // sending a fake completed result
        return new CommitLogResult(
                CompletableFuture.completedFuture(null), true /*
                 * deferred
                 */, false);
    } else {
        return new CommitLogResult(res, false /*
                 * deferred
                 */, true);
    }
}
 
Example 6
Source File: DBManager.java    From herddb with Apache License 2.0 4 votes vote down vote up
public CompletableFuture<StatementExecutionResult> executeStatementAsync(Statement statement, StatementEvaluationContext context, TransactionContext transactionContext) {
        context.setDefaultTablespace(statement.getTableSpace());
        context.setManager(this);
        context.setTransactionContext(transactionContext);
//        LOGGER.log(Level.SEVERE, "executeStatement {0}", new Object[]{statement});
        String tableSpace = statement.getTableSpace();
        if (tableSpace == null) {
            return FutureUtils.exception(new StatementExecutionException("invalid null tableSpace"));
        }
        if (statement instanceof CreateTableSpaceStatement) {
            if (transactionContext.transactionId > 0) {
                return FutureUtils.exception(new StatementExecutionException("CREATE TABLESPACE cannot be issued inside a transaction"));
            }
            return CompletableFuture.completedFuture(createTableSpace((CreateTableSpaceStatement) statement));
        }

        if (statement instanceof AlterTableSpaceStatement) {
            if (transactionContext.transactionId > 0) {
                return FutureUtils.exception(new StatementExecutionException("ALTER TABLESPACE cannot be issued inside a transaction"));
            }
            return CompletableFuture.completedFuture(alterTableSpace((AlterTableSpaceStatement) statement));
        }
        if (statement instanceof DropTableSpaceStatement) {
            if (transactionContext.transactionId > 0) {
                return FutureUtils.exception(new StatementExecutionException("DROP TABLESPACE cannot be issued inside a transaction"));
            }
            return CompletableFuture.completedFuture(dropTableSpace((DropTableSpaceStatement) statement));
        }
        if (statement instanceof TableSpaceConsistencyCheckStatement) {
            if (transactionContext.transactionId > 0) {
                return FutureUtils.exception(new StatementExecutionException("TABLESPACECONSISTENCYCHECK cannot be issue inside a transaction"));
            }
            return  CompletableFuture.completedFuture(createTableSpaceCheckSum((TableSpaceConsistencyCheckStatement) statement));
        }
        TableSpaceManager manager = tablesSpaces.get(tableSpace);
        if (manager == null) {
            return FutureUtils.exception(new NotLeaderException("No such tableSpace " + tableSpace + " here. "
                    + "Maybe the server is starting "));
        }
        if (errorIfNotLeader && !manager.isLeader()) {
            return FutureUtils.exception(new NotLeaderException("node " + nodeId + " is not leader for tableSpace " + tableSpace));
        }
        CompletableFuture<StatementExecutionResult> res = manager.executeStatementAsync(statement, context, transactionContext);
        if (statement instanceof DDLStatement) {
            res.whenComplete((s, err) -> {
                planner.clearCache();
            });
            planner.clearCache();
        }
//        res.whenComplete((s, err) -> {
//            LOGGER.log(Level.SEVERE, "completed " + statement + ": " + s, err);
//        });
        return res;
    }
 
Example 7
Source File: TableManager.java    From herddb with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<StatementExecutionResult> executeInsertAsync(InsertStatement insert, Transaction transaction, StatementEvaluationContext context) {
    /*
     an insert can succeed only if the row is valid and the "keys" structure  does not contain the requested key
     the insert will add the row in the 'buffer' without assigning a page to it
     locks: the insert uses global 'insert' lock on the table
     the insert will update the 'maxKey' for auto_increment primary keys
     */
    Bytes key;
    byte[] value;
    try {
        key = Bytes.from_array(insert.getKeyFunction().computeNewValue(null, context, tableContext));
        value = insert.getValuesFunction().computeNewValue(new Record(key, null), context, tableContext);
    } catch (StatementExecutionException validationError) {
        return FutureUtils.exception(validationError);
    }
    Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name);
    if (indexes != null) {
        try {
            DataAccessor values = new Record(key, Bytes.from_array(value)).getDataAccessor(table);
            for (AbstractIndexManager index : indexes.values()) {
                RecordSerializer.validatePrimaryKey(values, index.getIndex(), index.getColumnNames());
            }
        } catch (IllegalArgumentException err) {
            return FutureUtils.exception(new StatementExecutionException(err.getMessage(), err));
        }
    }


    final long size = DataPage.estimateEntrySize(key, value);
    if (size > maxLogicalPageSize) {
        return FutureUtils
                .exception(new RecordTooBigException("New record " + key + " is to big to be inserted: size " + size + ", max size " + maxLogicalPageSize));
    }

    LockHandle lock = lockForWrite(key, transaction);
    CompletableFuture<StatementExecutionResult> res = null;
    boolean fallbackToUpsert = false;
    if (transaction != null) {
        if (transaction.recordDeleted(table.name, key)) {
            // OK, INSERT on a DELETED record inside this transaction
        } else if (transaction.recordInserted(table.name, key) != null) {
            // ERROR, INSERT on a INSERTED record inside this transaction
            res = FutureUtils.exception(new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key, table) + ", already exists in table " + table.name + " inside transaction " + transaction.transactionId));
        } else if (keyToPage.containsKey(key)) {
            if (insert.isUpsert()) {
                fallbackToUpsert = true;
            } else {
                res = FutureUtils.exception(new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key, table) + ", already exists in table " + table.name + " during transaction " + transaction.transactionId));
            }
        }
    } else if (keyToPage.containsKey(key)) {
        if (insert.isUpsert()) {
            fallbackToUpsert = true;
        } else {
            res = FutureUtils.exception(new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key, table) + ", already exists in table " + table.name));
        }
    }

    if (res == null) {
        LogEntry entry;
        if (fallbackToUpsert) {
            entry = LogEntryFactory.update(table, key, Bytes.from_array(value), transaction);
        } else {
            entry = LogEntryFactory.insert(table, key, Bytes.from_array(value), transaction);
        }
        CommitLogResult pos = log.log(entry, entry.transactionId <= 0);
        res = pos.logSequenceNumber.thenApplyAsync((lsn) -> {
            apply(pos, entry, false);
            return new DMLStatementExecutionResult(entry.transactionId, 1, key,
                    insert.isReturnValues() ? Bytes.from_array(value) : null);
        }, tableSpaceManager.getCallbacksExecutor());
    }
    if (transaction == null) {
        res = releaseWriteLock(res, lock);
    }
    return res;
}
 
Example 8
Source File: TableManager.java    From herddb with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<StatementExecutionResult> executeGetAsync(
        GetStatement get, Transaction transaction,
        StatementEvaluationContext context
) {
    Bytes key;
    try {
        key = Bytes.from_nullable_array(get.getKey().computeNewValue(null, context, tableContext));
    } catch (StatementExecutionException validationError) {
        return FutureUtils.exception(validationError);
    }
    Predicate predicate = get.getPredicate();
    boolean requireLock = get.isRequireLock();
    boolean useWriteLock = requireLock && context.isForceAcquireWriteLock();
    long transactionId = transaction != null ? transaction.transactionId : 0;
    LockHandle lock = (transaction != null || requireLock) ? (useWriteLock ? lockForWrite(key, transaction) : lockForRead(key, transaction)) : null;
    CompletableFuture<StatementExecutionResult> res = null;
    try {
        if (transaction != null) {
            if (transaction.recordDeleted(table.name, key)) {
                res = CompletableFuture.completedFuture(GetResult.NOT_FOUND(transactionId));
            } else {
                Record loadedInTransaction = transaction.recordUpdated(table.name, key);
                if (loadedInTransaction != null) {
                    if (predicate != null && !predicate.evaluate(loadedInTransaction, context)) {
                        res = CompletableFuture.completedFuture(GetResult.NOT_FOUND(transactionId));
                    } else {
                        res = CompletableFuture.completedFuture(new GetResult(transactionId, loadedInTransaction, table));
                    }
                } else {
                    loadedInTransaction = transaction.recordInserted(table.name, key);
                    if (loadedInTransaction != null) {
                        if (predicate != null && !predicate.evaluate(loadedInTransaction, context)) {
                            res = CompletableFuture.completedFuture(GetResult.NOT_FOUND(transactionId));
                        } else {
                            res = CompletableFuture.completedFuture(new GetResult(transactionId, loadedInTransaction, table));
                        }
                    }
                }
            }
        }
        if (res == null) {
            Long pageId = keyToPage.get(key);
            if (pageId == null) {
                res = CompletableFuture.completedFuture(GetResult.NOT_FOUND(transactionId));
            } else {
                Record loaded = fetchRecord(key, pageId, null);
                if (loaded == null || (predicate != null && !predicate.evaluate(loaded, context))) {
                    res = CompletableFuture.completedFuture(GetResult.NOT_FOUND(transactionId));
                } else {
                    res = CompletableFuture.completedFuture(new GetResult(transactionId, loaded, table));
                }
            }
        }
        if (transaction == null && lock != null) {
            res.whenComplete((r, e) -> {
                locksManager.releaseReadLock(lock);
            });
        }
        return res;
    } catch (HerdDBInternalException err) {
        return FutureUtils.exception(err);
    }
}
 
Example 9
Source File: AbstractSystemTableManager.java    From herddb with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<StatementExecutionResult> executeStatementAsync(Statement statement, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException {
    return FutureUtils.exception(new StatementExecutionException("not supported on system tables"));
}