Java Code Examples for com.twitter.util.Promise#addEventListener()

The following examples show how to use com.twitter.util.Promise#addEventListener() . 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: BKLogSegmentWriter.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
synchronized public Future<DLSN> writeInternal(LogRecord record)
        throws LogRecordTooLongException, LockingException, BKTransmitException,
               WriteException, InvalidEnvelopedEntryException {
    int logRecordSize = record.getPersistentSize();

    if (logRecordSize > MAX_LOGRECORD_SIZE) {
        throw new LogRecordTooLongException(String.format(
                "Log Record of size %d written when only %d is allowed",
                logRecordSize, MAX_LOGRECORD_SIZE));
    }

    // If we will exceed the max number of bytes allowed per entry
    // initiate a transmit before accepting the new log record
    if ((recordSetWriter.getNumBytes() + logRecordSize) > MAX_LOGRECORDSET_SIZE) {
        checkStateAndTransmit();
    }

    checkWriteLock();

    if (enableRecordCounts) {
        // Set the count here. The caller would appropriately increment it
        // if this log record is to be counted
        record.setPositionWithinLogSegment(positionWithinLogSegment);
    }

    Promise<DLSN> writePromise = new Promise<DLSN>();
    writePromise.addEventListener(new OpStatsListener<DLSN>(writeTime));
    recordSetWriter.writeRecord(record, writePromise);

    if (record.getTransactionId() < lastTxId) {
        LOG.info("Log Segment {} TxId decreased Last: {} Record: {}",
                new Object[] {fullyQualifiedLogSegment, lastTxId, record.getTransactionId()});
    }
    if (!record.isControl()) {
        // only update last tx id for user records
        lastTxId = record.getTransactionId();
        outstandingBytes += (20 + record.getPayload().length);
    }
    return writePromise;
}
 
Example 2
Source File: ZKDistributedLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> asyncClose() {
    final Promise<Void> closePromise;
    synchronized (this) {
        if (closed) {
            return closeFuture;
        }
        closed = true;
        closeFuture = closePromise = new Promise<Void>();
    }
    final Promise<Void> closeWaiterFuture = new Promise<Void>();
    closeWaiterFuture.addEventListener(OrderedFutureEventListener.of(new FutureEventListener<Void>() {
        @Override
        public void onSuccess(Void value) {
            complete();
        }
        @Override
        public void onFailure(Throwable cause) {
            complete();
        }

        private void complete() {
            FutureUtils.setValue(closePromise, null);
        }
    }, lockStateExecutor, lockPath));
    lockStateExecutor.submit(lockPath, new Runnable() {
        @Override
        public void run() {
            closeWaiter(lockWaiter, closeWaiterFuture);
        }
    });
    return closePromise;
}
 
Example 3
Source File: ZKDistributedLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
void doInternalReacquireLock(final AtomicInteger numRetries,
                             final long lockTimeout,
                             final Promise<ZKDistributedLock> reacquirePromise) {
    internalTryRetries.inc();
    Promise<ZKDistributedLock> tryPromise = new Promise<ZKDistributedLock>();
    tryPromise.addEventListener(new FutureEventListener<ZKDistributedLock>() {
        @Override
        public void onSuccess(ZKDistributedLock lock) {
            FutureUtils.setValue(reacquirePromise, lock);
        }

        @Override
        public void onFailure(Throwable cause) {
            if (cause instanceof OwnershipAcquireFailedException) {
                // the lock has been acquired by others
                FutureUtils.setException(reacquirePromise, cause);
            } else {
                if (numRetries.getAndDecrement() > 0 && !closed) {
                    internalReacquireLock(numRetries, lockTimeout, reacquirePromise);
                } else {
                    FutureUtils.setException(reacquirePromise, cause);
                }
            }
        }
    });
    doAsyncAcquireWithSemaphore(tryPromise, 0);
}
 
Example 4
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Try lock. If it failed, it would cleanup its attempt.
 *
 * @param wait
 *          whether to wait for ownership.
 * @param result
 *          promise to satisfy with current lock owner
 */
private void asyncTryLock(boolean wait, final Promise<String> result) {
    final Promise<String> lockResult = new Promise<String>();
    lockResult.addEventListener(new FutureEventListener<String>() {
        @Override
        public void onSuccess(String currentOwner) {
            result.setValue(currentOwner);
        }

        @Override
        public void onFailure(final Throwable lockCause) {
            // If tryLock failed due to state changed, we don't need to cleanup
            if (lockCause instanceof LockStateChangedException) {
                LOG.info("skipping cleanup for {} at {} after encountering lock " +
                        "state change exception : ", new Object[] { lockId, lockPath, lockCause });
                result.setException(lockCause);
                return;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} is cleaning up its lock state for {} due to : ",
                        new Object[] { lockId, lockPath, lockCause });
            }

            // If we encountered any exception we should cleanup
            Future<BoxedUnit> unlockResult = asyncUnlock();
            unlockResult.addEventListener(new FutureEventListener<BoxedUnit>() {
                @Override
                public void onSuccess(BoxedUnit value) {
                    result.setException(lockCause);
                }
                @Override
                public void onFailure(Throwable cause) {
                    result.setException(lockCause);
                }
            });
        }
    });
    asyncTryLockWithoutCleanup(wait, lockResult);
}
 
Example 5
Source File: BKLogWriteHandler.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
private Future<LogSegmentMetadata> deleteLogSegment(
        final LogSegmentMetadata ledgerMetadata) {
    LOG.info("Deleting ledger {} for {}", ledgerMetadata, getFullyQualifiedName());
    final Promise<LogSegmentMetadata> promise = new Promise<LogSegmentMetadata>();
    final Stopwatch stopwatch = Stopwatch.createStarted();
    promise.addEventListener(new FutureEventListener<LogSegmentMetadata>() {
        @Override
        public void onSuccess(LogSegmentMetadata segment) {
            deleteOpStats.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }

        @Override
        public void onFailure(Throwable cause) {
            deleteOpStats.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }
    });
    try {
        bookKeeperClient.get().asyncDeleteLedger(ledgerMetadata.getLedgerId(), new AsyncCallback.DeleteCallback() {
            @Override
            public void deleteComplete(int rc, Object ctx) {
                if (BKException.Code.NoSuchLedgerExistsException == rc) {
                    LOG.warn("No ledger {} found to delete for {} : {}.",
                            new Object[]{ledgerMetadata.getLedgerId(), getFullyQualifiedName(),
                                    ledgerMetadata});
                } else if (BKException.Code.OK != rc) {
                    BKException bke = BKException.create(rc);
                    LOG.error("Couldn't delete ledger {} from bookkeeper for {} : ",
                            new Object[]{ledgerMetadata.getLedgerId(), getFullyQualifiedName(), bke});
                    promise.setException(bke);
                    return;
                }
                // after the ledger is deleted, we delete the metadata znode
                scheduler.submit(new Runnable() {
                    @Override
                    public void run() {
                        deleteLogSegmentMetadata(ledgerMetadata, promise);
                    }
                });
            }
        }, null);
    } catch (IOException e) {
        promise.setException(BKException.create(BKException.Code.BookieHandleNotAvailableException));
    }
    return promise;
}
 
Example 6
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * NOTE: unlockInternal should only after try lock.
 */
private void unlockInternal(final Promise<BoxedUnit> promise) {

    // already closed or expired, nothing to cleanup
    this.epoch.incrementAndGet();
    if (null != watcher) {
        this.zkClient.unregister(watcher);
    }

    if (lockState.inState(State.CLOSED)) {
        promise.setValue(BoxedUnit.UNIT);
        return;
    }

    LOG.info("Lock {} for {} is closed from state {}.",
            new Object[] { lockId, lockPath, lockState.getState() });

    final boolean skipCleanup = lockState.inState(State.INIT) || lockState.inState(State.EXPIRED);

    lockState.transition(State.CLOSING);

    if (skipCleanup) {
        // Nothing to cleanup if INIT (never tried) or EXPIRED (ephemeral node
        // auto-removed)
        lockState.transition(State.CLOSED);
        promise.setValue(BoxedUnit.UNIT);
        return;
    }

    // In any other state, we should clean up the member node
    Promise<BoxedUnit> deletePromise = new Promise<BoxedUnit>();
    deleteLockNode(deletePromise);

    // Set the state to closed after we've cleaned up
    deletePromise.addEventListener(new FutureEventListener<BoxedUnit>() {
        @Override
        public void onSuccess(BoxedUnit complete) {
            lockStateExecutor.submit(lockPath, new SafeRunnable() {
                @Override
                public void safeRun() {
                    lockState.transition(State.CLOSED);
                    promise.setValue(BoxedUnit.UNIT);
                }
            });
        }
        @Override
        public void onFailure(Throwable cause) {
            // Delete failure is quite serious (causes lock leak) and should be
            // handled better
            LOG.error("lock node delete failed {} {}", lockId, lockPath);
            promise.setValue(BoxedUnit.UNIT);
        }
    });
}
 
Example 7
Source File: LedgerHandleCache.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * Open the log segment.
 *
 * @param metadata
 *          the log segment metadata
 * @param fence
 *          whether to fence the log segment during open
 * @return a future presenting the open result.
 */
public Future<LedgerDescriptor> asyncOpenLedger(LogSegmentMetadata metadata, boolean fence) {
    final Stopwatch stopwatch = Stopwatch.createStarted();
    final OpStatsLogger openStatsLogger = fence ? openStats : openNoRecoveryStats;
    final Promise<LedgerDescriptor> promise = new Promise<LedgerDescriptor>();
    final LedgerDescriptor ledgerDesc = new LedgerDescriptor(metadata.getLedgerId(), metadata.getLogSegmentSequenceNumber(), fence);
    RefCountedLedgerHandle refhandle = handlesMap.get(ledgerDesc);
    if (null == refhandle) {
        asyncOpenLedger(ledgerDesc, new AsyncCallback.OpenCallback() {
            @Override
            public void openComplete(int rc, LedgerHandle lh, Object ctx) {
                if (BKException.Code.OK != rc) {
                    promise.setException(BKException.create(rc));
                    return;
                }
                RefCountedLedgerHandle newRefHandle = new RefCountedLedgerHandle(lh);
                RefCountedLedgerHandle oldRefHandle = handlesMap.putIfAbsent(ledgerDesc, newRefHandle);
                if (null != oldRefHandle) {
                    oldRefHandle.addRef();
                    if (newRefHandle.removeRef()) {
                        newRefHandle.handle.asyncClose(new AsyncCallback.CloseCallback() {
                            @Override
                            public void closeComplete(int i, LedgerHandle ledgerHandle, Object o) {
                                // No action necessary
                            }
                        }, null);
                    }
                }
                promise.setValue(ledgerDesc);
            }
        }, null);
    } else {
        refhandle.addRef();
        promise.setValue(ledgerDesc);
    }
    return promise.addEventListener(new FutureEventListener<LedgerDescriptor>() {
        @Override
        public void onSuccess(LedgerDescriptor value) {
            openStatsLogger.registerSuccessfulEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS));
        }

        @Override
        public void onFailure(Throwable cause) {
            openStatsLogger.registerFailedEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS));
        }
    });
}