Search in sources :

Example 6 with LogNotFoundException

use of com.twitter.distributedlog.exceptions.LogNotFoundException in project distributedlog by twitter.

the class BKLogHandler method forceGetLedgerList.

/**
 * Get a list of all segments in the journal.
 */
protected List<LogSegmentMetadata> forceGetLedgerList(final Comparator<LogSegmentMetadata> comparator, final LogSegmentFilter segmentFilter, boolean throwOnEmpty) throws IOException {
    final List<LogSegmentMetadata> ledgers = new ArrayList<LogSegmentMetadata>();
    final AtomicInteger result = new AtomicInteger(-1);
    final CountDownLatch latch = new CountDownLatch(1);
    Stopwatch stopwatch = Stopwatch.createStarted();
    asyncGetLedgerListInternal(comparator, segmentFilter, null, new GenericCallback<List<LogSegmentMetadata>>() {

        @Override
        public void operationComplete(int rc, List<LogSegmentMetadata> logSegmentMetadatas) {
            result.set(rc);
            if (KeeperException.Code.OK.intValue() == rc) {
                ledgers.addAll(logSegmentMetadatas);
            } else {
                LOG.error("Failed to get ledger list for {} : with error {}", getFullyQualifiedName(), rc);
            }
            latch.countDown();
        }
    }, new AtomicInteger(conf.getZKNumRetries()), new AtomicLong(conf.getZKRetryBackoffStartMillis()));
    try {
        latch.await();
    } catch (InterruptedException e) {
        forceGetListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        throw new DLInterruptedException("Interrupted on reading ledger list from zkfor " + getFullyQualifiedName(), e);
    }
    long elapsedMicros = stopwatch.stop().elapsed(TimeUnit.MICROSECONDS);
    KeeperException.Code rc = KeeperException.Code.get(result.get());
    if (rc == KeeperException.Code.OK) {
        forceGetListStat.registerSuccessfulEvent(elapsedMicros);
    } else {
        forceGetListStat.registerFailedEvent(elapsedMicros);
        if (KeeperException.Code.NONODE == rc) {
            throw new LogNotFoundException("Log " + getFullyQualifiedName() + " is not found");
        } else {
            throw new IOException("ZK Exception " + rc + " reading ledger list for " + getFullyQualifiedName());
        }
    }
    if (throwOnEmpty && ledgers.isEmpty()) {
        throw new LogEmptyException("Log " + getFullyQualifiedName() + " is empty");
    }
    return ledgers;
}
Also used : ArrayList(java.util.ArrayList) Stopwatch(com.google.common.base.Stopwatch) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException) LogEmptyException(com.twitter.distributedlog.exceptions.LogEmptyException) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List) ArrayList(java.util.ArrayList) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException) LogNotFoundException(com.twitter.distributedlog.exceptions.LogNotFoundException) KeeperException(org.apache.zookeeper.KeeperException)

Example 7 with LogNotFoundException

use of com.twitter.distributedlog.exceptions.LogNotFoundException in project distributedlog by twitter.

the class BKLogHandler method asyncGetLedgerListWithRetries.

protected Future<List<LogSegmentMetadata>> asyncGetLedgerListWithRetries(Comparator<LogSegmentMetadata> comparator, LogSegmentFilter segmentFilter, Watcher watcher) {
    final Promise<List<LogSegmentMetadata>> promise = new Promise<List<LogSegmentMetadata>>();
    asyncGetLedgerListWithRetries(comparator, segmentFilter, watcher, new GenericCallback<List<LogSegmentMetadata>>() {

        @Override
        public void operationComplete(int rc, List<LogSegmentMetadata> segments) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.setValue(segments);
            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                promise.setException(new LogNotFoundException("Log " + getFullyQualifiedName() + " not found"));
            } else {
                String errMsg = "ZK Exception " + rc + " reading ledger list for " + getFullyQualifiedName();
                promise.setException(new ZKException(errMsg, KeeperException.Code.get(rc)));
            }
        }
    });
    return promise;
}
Also used : Promise(com.twitter.util.Promise) ZKException(com.twitter.distributedlog.exceptions.ZKException) List(java.util.List) ArrayList(java.util.ArrayList) LogNotFoundException(com.twitter.distributedlog.exceptions.LogNotFoundException)

Example 8 with LogNotFoundException

use of com.twitter.distributedlog.exceptions.LogNotFoundException in project distributedlog by twitter.

the class BKAsyncLogReaderDLSN method run.

@Override
public void run() {
    synchronized (scheduleLock) {
        if (scheduleDelayStopwatch.isRunning()) {
            scheduleLatency.registerSuccessfulEvent(scheduleDelayStopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }
        Stopwatch runTime = Stopwatch.createStarted();
        int iterations = 0;
        long scheduleCountLocal = scheduleCount.get();
        LOG.debug("{}: Scheduled Background Reader", bkLedgerManager.getFullyQualifiedName());
        while (true) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("{}: Executing Iteration: {}", bkLedgerManager.getFullyQualifiedName(), iterations++);
            }
            PendingReadRequest nextRequest = null;
            synchronized (this) {
                nextRequest = pendingRequests.peek();
                // Queue is empty, nothing to read, return
                if (null == nextRequest) {
                    LOG.trace("{}: Queue Empty waiting for Input", bkLedgerManager.getFullyQualifiedName());
                    scheduleCount.set(0);
                    backgroundReaderRunTime.registerSuccessfulEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS));
                    return;
                }
                if (disableProcessingReadRequests) {
                    LOG.info("Reader of {} is forced to stop processing read requests", bkLedgerManager.getFullyQualifiedName());
                    return;
                }
            }
            // know the last consumed read
            if (null == lastException.get()) {
                if (nextRequest.getPromise().isInterrupted().isDefined()) {
                    setLastException(new DLInterruptedException("Interrupted on reading " + bkLedgerManager.getFullyQualifiedName() + " : ", nextRequest.getPromise().isInterrupted().get()));
                }
            }
            if (checkClosedOrInError("readNext")) {
                if (!(lastException.get().getCause() instanceof LogNotFoundException)) {
                    LOG.warn("{}: Exception", bkLedgerManager.getFullyQualifiedName(), lastException.get());
                }
                backgroundReaderRunTime.registerFailedEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS));
                return;
            }
            try {
                // Fail 10% of the requests when asked to simulate errors
                if (failureInjector.shouldInjectErrors()) {
                    throw new IOException("Reader Simulated Exception");
                }
                LogRecordWithDLSN record;
                while (!nextRequest.hasReadEnoughRecords()) {
                    // read single record
                    do {
                        record = bkLedgerManager.getNextReadAheadRecord();
                    } while (null != record && (record.isControl() || (record.getDlsn().compareTo(getStartDLSN()) < 0)));
                    if (null == record) {
                        break;
                    } else {
                        if (record.isEndOfStream() && !returnEndOfStreamRecord) {
                            setLastException(new EndOfStreamException("End of Stream Reached for " + bkLedgerManager.getFullyQualifiedName()));
                            break;
                        }
                        // gap detection
                        if (recordPositionsContainsGap(record, lastPosition)) {
                            bkDistributedLogManager.raiseAlert("Gap detected between records at dlsn = {}", record.getDlsn());
                            if (positionGapDetectionEnabled) {
                                throw new DLIllegalStateException("Gap detected between records at dlsn = " + record.getDlsn());
                            }
                        }
                        lastPosition = record.getLastPositionWithinLogSegment();
                        nextRequest.addRecord(record);
                    }
                }
                ;
            } catch (IOException exc) {
                setLastException(exc);
                if (!(exc instanceof LogNotFoundException)) {
                    LOG.warn("{} : read with skip Exception", bkLedgerManager.getFullyQualifiedName(), lastException.get());
                }
                continue;
            }
            if (nextRequest.hasReadRecords()) {
                long remainingWaitTime = nextRequest.getRemainingWaitTime();
                if (remainingWaitTime > 0 && !nextRequest.hasReadEnoughRecords()) {
                    backgroundReaderRunTime.registerSuccessfulEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS));
                    scheduleDelayStopwatch.reset().start();
                    scheduleCount.set(0);
                    // the request could still wait for more records
                    backgroundScheduleTask = executorService.schedule(BACKGROUND_READ_SCHEDULER, remainingWaitTime, nextRequest.deadlineTimeUnit);
                    return;
                }
                PendingReadRequest request = pendingRequests.poll();
                if (null != request && nextRequest == request) {
                    request.complete();
                    if (null != backgroundScheduleTask) {
                        backgroundScheduleTask.cancel(true);
                        backgroundScheduleTask = null;
                    }
                } else {
                    DLIllegalStateException ise = new DLIllegalStateException("Unexpected condition at dlsn = " + nextRequest.records.get(0).getDlsn());
                    nextRequest.setException(ise);
                    if (null != request) {
                        request.setException(ise);
                    }
                    // We should never get here as we should have exited the loop if
                    // pendingRequests were empty
                    bkDistributedLogManager.raiseAlert("Unexpected condition at dlsn = {}", nextRequest.records.get(0).getDlsn());
                    setLastException(ise);
                }
            } else {
                if (0 == scheduleCountLocal) {
                    LOG.trace("Schedule count dropping to zero", lastException.get());
                    backgroundReaderRunTime.registerSuccessfulEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS));
                    return;
                }
                scheduleCountLocal = scheduleCount.decrementAndGet();
            }
        }
    }
}
Also used : EndOfStreamException(com.twitter.distributedlog.exceptions.EndOfStreamException) Stopwatch(com.google.common.base.Stopwatch) DLIllegalStateException(com.twitter.distributedlog.exceptions.DLIllegalStateException) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException) LogNotFoundException(com.twitter.distributedlog.exceptions.LogNotFoundException) IOException(java.io.IOException)

Example 9 with LogNotFoundException

use of com.twitter.distributedlog.exceptions.LogNotFoundException in project distributedlog by twitter.

the class MultiReader method main.

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;
    }
    String dlUriStr = args[0];
    final String streamList = args[1];
    URI uri = URI.create(dlUriStr);
    DistributedLogConfiguration conf = new DistributedLogConfiguration();
    DistributedLogNamespace namespace = DistributedLogNamespaceBuilder.newBuilder().conf(conf).uri(uri).build();
    String[] streamNameList = StringUtils.split(streamList, ',');
    DistributedLogManager[] managers = new DistributedLogManager[streamNameList.length];
    for (int i = 0; i < managers.length; i++) {
        String streamName = streamNameList[i];
        // open the dlm
        System.out.println("Opening log stream " + streamName);
        managers[i] = namespace.openLog(streamName);
    }
    final CountDownLatch keepAliveLatch = new CountDownLatch(1);
    for (DistributedLogManager dlm : managers) {
        final DistributedLogManager manager = dlm;
        dlm.getLastLogRecordAsync().addEventListener(new FutureEventListener<LogRecordWithDLSN>() {

            @Override
            public void onFailure(Throwable cause) {
                if (cause instanceof LogNotFoundException) {
                    System.err.println("Log stream " + manager.getStreamName() + " is not found. Please create it first.");
                    keepAliveLatch.countDown();
                } else if (cause instanceof LogEmptyException) {
                    System.err.println("Log stream " + manager.getStreamName() + " is empty.");
                    readLoop(manager, DLSN.InitialDLSN, keepAliveLatch);
                } else {
                    System.err.println("Encountered exception on process stream " + manager.getStreamName());
                    keepAliveLatch.countDown();
                }
            }

            @Override
            public void onSuccess(LogRecordWithDLSN record) {
                readLoop(manager, record.getDlsn(), keepAliveLatch);
            }
        });
    }
    keepAliveLatch.await();
    for (DistributedLogManager dlm : managers) {
        dlm.close();
    }
    namespace.close();
}
Also used : DistributedLogNamespace(com.twitter.distributedlog.namespace.DistributedLogNamespace) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) LogEmptyException(com.twitter.distributedlog.exceptions.LogEmptyException) LogNotFoundException(com.twitter.distributedlog.exceptions.LogNotFoundException)

Example 10 with LogNotFoundException

use of com.twitter.distributedlog.exceptions.LogNotFoundException in project distributedlog by twitter.

the class TailReader method main.

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;
    }
    String dlUriStr = args[0];
    final String streamName = args[1];
    URI uri = URI.create(dlUriStr);
    DistributedLogConfiguration conf = new DistributedLogConfiguration();
    DistributedLogNamespace namespace = DistributedLogNamespaceBuilder.newBuilder().conf(conf).uri(uri).build();
    // open the dlm
    System.out.println("Opening log stream " + streamName);
    DistributedLogManager dlm = namespace.openLog(streamName);
    // get the last record
    LogRecordWithDLSN lastRecord;
    DLSN dlsn;
    try {
        lastRecord = dlm.getLastLogRecord();
        dlsn = lastRecord.getDlsn();
        readLoop(dlm, dlsn);
    } catch (LogNotFoundException lnfe) {
        System.err.println("Log stream " + streamName + " is not found. Please create it first.");
        return;
    } catch (LogEmptyException lee) {
        System.err.println("Log stream " + streamName + " is empty.");
        dlsn = DLSN.InitialDLSN;
        readLoop(dlm, dlsn);
    } finally {
        dlm.close();
        namespace.close();
    }
}
Also used : LogEmptyException(com.twitter.distributedlog.exceptions.LogEmptyException) DistributedLogNamespace(com.twitter.distributedlog.namespace.DistributedLogNamespace) LogNotFoundException(com.twitter.distributedlog.exceptions.LogNotFoundException) URI(java.net.URI)

Aggregations

LogNotFoundException (com.twitter.distributedlog.exceptions.LogNotFoundException)10 DLInterruptedException (com.twitter.distributedlog.exceptions.DLInterruptedException)4 LogEmptyException (com.twitter.distributedlog.exceptions.LogEmptyException)4 ZKException (com.twitter.distributedlog.exceptions.ZKException)3 DistributedLogNamespace (com.twitter.distributedlog.namespace.DistributedLogNamespace)3 Promise (com.twitter.util.Promise)3 URI (java.net.URI)3 List (java.util.List)3 Stopwatch (com.google.common.base.Stopwatch)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AsyncCallback (org.apache.zookeeper.AsyncCallback)2 AsyncLogReader (com.twitter.distributedlog.AsyncLogReader)1 DLSN (com.twitter.distributedlog.DLSN)1 DistributedLogManager (com.twitter.distributedlog.DistributedLogManager)1 LogReader (com.twitter.distributedlog.LogReader)1 LogRecord (com.twitter.distributedlog.LogRecord)1 LogRecordWithDLSN (com.twitter.distributedlog.LogRecordWithDLSN)1 DLIllegalStateException (com.twitter.distributedlog.exceptions.DLIllegalStateException)1