Search in sources :

Example 11 with EndOfStreamException

use of org.apache.distributedlog.exceptions.EndOfStreamException in project incubator-heron by apache.

the class DLDownloaderTest method testDownload.

@Test
public void testDownload() throws Exception {
    String logName = "test-download";
    URI uri = URI.create("distributedlog://127.0.0.1/test/distributedlog/" + logName);
    File tempFile = File.createTempFile("test", "download");
    // make sure it is deleted when the test completes
    tempFile.deleteOnExit();
    Path path = Paths.get(tempFile.toURI());
    Namespace ns = mock(Namespace.class);
    DistributedLogManager dlm = mock(DistributedLogManager.class);
    LogReader reader = mock(LogReader.class);
    when(ns.openLog(anyString())).thenReturn(dlm);
    when(dlm.getInputStream(eq(DLSN.InitialDLSN))).thenReturn(reader);
    when(reader.readNext(anyBoolean())).thenThrow(new EndOfStreamException("eos"));
    NamespaceBuilder nsBuilder = mock(NamespaceBuilder.class);
    when(nsBuilder.clientId(anyString())).thenReturn(nsBuilder);
    when(nsBuilder.conf(any(DistributedLogConfiguration.class))).thenReturn(nsBuilder);
    when(nsBuilder.uri(any(URI.class))).thenReturn(nsBuilder);
    when(nsBuilder.build()).thenReturn(ns);
    PowerMockito.mockStatic(Extractor.class);
    PowerMockito.doNothing().when(Extractor.class, "extract", any(InputStream.class), any(Path.class));
    DLDownloader downloader = new DLDownloader(() -> nsBuilder);
    downloader.download(uri, path);
    URI parentUri = URI.create("distributedlog://127.0.0.1/test/distributedlog");
    verify(nsBuilder, times(1)).clientId(eq("heron-downloader"));
    verify(nsBuilder, times(1)).conf(eq(CONF));
    verify(nsBuilder, times(1)).uri(parentUri);
    PowerMockito.verifyStatic(times(1));
    Extractor.extract(any(InputStream.class), eq(path));
    verify(ns, times(1)).openLog(eq(logName));
    verify(ns, times(1)).close();
}
Also used : Path(java.nio.file.Path) DistributedLogConfiguration(org.apache.distributedlog.DistributedLogConfiguration) DistributedLogManager(org.apache.distributedlog.api.DistributedLogManager) EndOfStreamException(org.apache.distributedlog.exceptions.EndOfStreamException) DLInputStream(com.twitter.heron.dlog.DLInputStream) InputStream(java.io.InputStream) LogReader(org.apache.distributedlog.api.LogReader) Matchers.anyString(org.mockito.Matchers.anyString) URI(java.net.URI) File(java.io.File) Namespace(org.apache.distributedlog.api.namespace.Namespace) NamespaceBuilder(org.apache.distributedlog.api.namespace.NamespaceBuilder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 12 with EndOfStreamException

use of org.apache.distributedlog.exceptions.EndOfStreamException in project bookkeeper by apache.

the class BKLogWriteHandler method doStartLogSegment.

protected void doStartLogSegment(final long txId, final boolean bestEffort, final boolean allowMaxTxID, final CompletableFuture<BKLogSegmentWriter> promise) {
    // validate the tx id
    if ((txId < 0) || (!allowMaxTxID && (txId == DistributedLogConstants.MAX_TXID))) {
        FutureUtils.completeExceptionally(promise, new IOException("Invalid Transaction Id " + txId));
        return;
    }
    long highestTxIdWritten = maxTxId.get();
    if (txId < highestTxIdWritten) {
        if (highestTxIdWritten == DistributedLogConstants.MAX_TXID) {
            LOG.error("We've already marked the stream as ended and attempting to start a new log segment");
            FutureUtils.completeExceptionally(promise, new EndOfStreamException("Writing to a stream after it has been marked as completed"));
            return;
        } else {
            LOG.error("We've already seen TxId {} the max TXId is {}", txId, highestTxIdWritten);
            FutureUtils.completeExceptionally(promise, new TransactionIdOutOfOrderException(txId, highestTxIdWritten));
            return;
        }
    }
    try {
        logSegmentAllocator.allocate();
    } catch (IOException e) {
        // failed to issue an allocation request
        failStartLogSegment(promise, bestEffort, e);
        return;
    }
    // start the transaction from zookeeper
    final Transaction<Object> txn = streamMetadataStore.newTransaction();
    // failpoint injected before creating ledger
    try {
        FailpointUtils.checkFailPoint(FailpointUtils.FailPointName.FP_StartLogSegmentBeforeLedgerCreate);
    } catch (IOException ioe) {
        failStartLogSegment(promise, bestEffort, ioe);
        return;
    }
    logSegmentAllocator.tryObtain(txn, NULL_OP_LISTENER).whenComplete(new FutureEventListener<LogSegmentEntryWriter>() {

        @Override
        public void onSuccess(LogSegmentEntryWriter entryWriter) {
            // try-obtain succeed
            createInprogressLogSegment(txn, txId, entryWriter, bestEffort, promise);
        }

        @Override
        public void onFailure(Throwable cause) {
            failStartLogSegment(promise, bestEffort, cause);
        }
    });
}
Also used : LogSegmentEntryWriter(org.apache.distributedlog.logsegment.LogSegmentEntryWriter) EndOfStreamException(org.apache.distributedlog.exceptions.EndOfStreamException) TransactionIdOutOfOrderException(org.apache.distributedlog.exceptions.TransactionIdOutOfOrderException) IOException(java.io.IOException)

Example 13 with EndOfStreamException

use of org.apache.distributedlog.exceptions.EndOfStreamException in project bookkeeper by apache.

the class TestBKLogSegmentWriter method testNondurableWriteAfterEndOfStream.

/**
 * Non durable write should fail if writer is marked as end of stream.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testNondurableWriteAfterEndOfStream() throws Exception {
    DistributedLogConfiguration confLocal = newLocalConf();
    confLocal.setImmediateFlushEnabled(false);
    confLocal.setOutputBufferSize(Integer.MAX_VALUE);
    confLocal.setPeriodicFlushFrequencyMilliSeconds(0);
    confLocal.setDurableWriteEnabled(false);
    ZKDistributedLock lock = createLock("/test/lock-" + runtime.getMethodName(), zkc, true);
    BKLogSegmentWriter writer = createLogSegmentWriter(confLocal, 0L, -1L, lock);
    Utils.ioResult(writer.markEndOfStream());
    try {
        Utils.ioResult(writer.asyncWrite(DLMTestUtil.getLogRecordInstance(1)));
        fail("Should fail the write if the writer is marked as end of stream");
    } catch (EndOfStreamException we) {
    // expected
    }
    closeWriterAndLock(writer, lock);
}
Also used : EndOfStreamException(org.apache.distributedlog.exceptions.EndOfStreamException) ZKDistributedLock(org.apache.distributedlog.lock.ZKDistributedLock) Test(org.junit.Test)

Example 14 with EndOfStreamException

use of org.apache.distributedlog.exceptions.EndOfStreamException in project bookkeeper by apache.

the class TestAsyncReaderWriter method testMarkEndOfStream.

@Test(timeout = 60000)
public void testMarkEndOfStream() throws Exception {
    String name = runtime.getMethodName();
    DistributedLogConfiguration confLocal = new DistributedLogConfiguration();
    confLocal.addConfiguration(testConf);
    confLocal.setOutputBufferSize(0);
    confLocal.setImmediateFlushEnabled(true);
    confLocal.setPeriodicFlushFrequencyMilliSeconds(0);
    DistributedLogManager dlm = createNewDLM(confLocal, name);
    BKAsyncLogWriter writer = (BKAsyncLogWriter) dlm.startAsyncLogSegmentNonPartitioned();
    final int numRecords = 10;
    int i = 1;
    for (; i <= numRecords; i++) {
        Utils.ioResult(writer.write(DLMTestUtil.getLogRecordInstance(i)));
        assertEquals("last tx id should become " + i, i, writer.getLastTxId());
    }
    Utils.ioResult(writer.markEndOfStream());
    // Multiple end of streams are ok.
    Utils.ioResult(writer.markEndOfStream());
    try {
        Utils.ioResult(writer.write(DLMTestUtil.getLogRecordInstance(i)));
        fail("Should have thrown");
    } catch (EndOfStreamException ex) {
    }
    BKAsyncLogReader reader = (BKAsyncLogReader) dlm.getAsyncLogReader(DLSN.InitialDLSN);
    LogRecord record = null;
    for (int j = 0; j < numRecords; j++) {
        record = Utils.ioResult(reader.readNext());
        assertEquals(j + 1, record.getTransactionId());
    }
    try {
        record = Utils.ioResult(reader.readNext());
        fail("Should have thrown");
    } catch (EndOfStreamException ex) {
    }
    Utils.close(reader);
}
Also used : DynamicDistributedLogConfiguration(org.apache.distributedlog.config.DynamicDistributedLogConfiguration) DistributedLogManager(org.apache.distributedlog.api.DistributedLogManager) EndOfStreamException(org.apache.distributedlog.exceptions.EndOfStreamException) Test(org.junit.Test)

Example 15 with EndOfStreamException

use of org.apache.distributedlog.exceptions.EndOfStreamException in project bookkeeper by apache.

the class BKAsyncLogReader method safeRun.

@Override
public void safeRun() {
    synchronized (scheduleLock) {
        if (scheduleDelayStopwatch.isRunning()) {
            scheduleLatency.registerSuccessfulEvent(scheduleDelayStopwatch.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
        }
        Stopwatch runTime = Stopwatch.createStarted();
        int iterations = 0;
        long scheduleCountLocal = scheduleCountUpdater.get(this);
        LOG.debug("{}: Scheduled Background Reader", readHandler.getFullyQualifiedName());
        while (true) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("{}: Executing Iteration: {}", readHandler.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", readHandler.getFullyQualifiedName());
                    scheduleCountUpdater.set(this, 0);
                    backgroundReaderRunTime.registerSuccessfulEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
                    return;
                }
                if (disableProcessingReadRequests) {
                    LOG.info("Reader of {} is forced to stop processing read requests", readHandler.getFullyQualifiedName());
                    return;
                }
            }
            lastProcessTime.reset().start();
            // know the last consumed read
            if (null == lastExceptionUpdater.get(this)) {
                if (nextRequest.getPromise().isCancelled()) {
                    setLastException(new DLInterruptedException("Interrupted on reading " + readHandler.getFullyQualifiedName()));
                }
            }
            if (checkClosedOrInError("readNext")) {
                Throwable lastException = lastExceptionUpdater.get(this);
                if (lastException != null && !(lastException.getCause() instanceof LogNotFoundException)) {
                    LOG.warn("{}: Exception", readHandler.getFullyQualifiedName(), lastException);
                }
                backgroundReaderRunTime.registerFailedEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
                return;
            }
            try {
                // Fail 10% of the requests when asked to simulate errors
                if (bkDistributedLogManager.getFailureInjector().shouldInjectErrors()) {
                    throw new IOException("Reader Simulated Exception");
                }
                LogRecordWithDLSN record;
                while (!nextRequest.hasReadEnoughRecords()) {
                    // read single record
                    do {
                        record = readNextRecord();
                    } 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 " + readHandler.getFullyQualifiedName()));
                            break;
                        }
                        // gap detection
                        if (recordPositionsContainsGap(record, lastPosition)) {
                            bkDistributedLogManager.raiseAlert("Gap detected between records at record = {}", record);
                            if (positionGapDetectionEnabled) {
                                throw new DLIllegalStateException("Gap detected between records at record = " + record);
                            }
                        }
                        lastPosition = record.getLastPositionWithinLogSegment();
                        nextRequest.addRecord(record);
                    }
                }
            } catch (IOException exc) {
                setLastException(exc);
                if (!(exc instanceof LogNotFoundException)) {
                    LOG.warn("{} : read with skip Exception", readHandler.getFullyQualifiedName(), lastExceptionUpdater.get(this));
                }
                continue;
            }
            if (nextRequest.hasReadRecords()) {
                long remainingWaitTime = nextRequest.getRemainingWaitTime();
                if (remainingWaitTime > 0 && !nextRequest.hasReadEnoughRecords()) {
                    backgroundReaderRunTime.registerSuccessfulEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
                    scheduleDelayStopwatch.reset().start();
                    scheduleCountUpdater.set(this, 0);
                    // the request could still wait for more records
                    backgroundScheduleTask = scheduler.scheduleOrdered(streamName, 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.completeExceptionally(ise);
                    if (null != request) {
                        request.completeExceptionally(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", lastExceptionUpdater.get(this));
                    backgroundReaderRunTime.registerSuccessfulEvent(runTime.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
                    return;
                }
                scheduleCountLocal = scheduleCountUpdater.decrementAndGet(this);
            }
        }
    }
}
Also used : EndOfStreamException(org.apache.distributedlog.exceptions.EndOfStreamException) Stopwatch(com.google.common.base.Stopwatch) DLIllegalStateException(org.apache.distributedlog.exceptions.DLIllegalStateException) DLInterruptedException(org.apache.distributedlog.exceptions.DLInterruptedException) LogNotFoundException(org.apache.distributedlog.exceptions.LogNotFoundException) IOException(java.io.IOException)

Aggregations

EndOfStreamException (org.apache.distributedlog.exceptions.EndOfStreamException)15 DistributedLogManager (org.apache.distributedlog.api.DistributedLogManager)11 Test (org.junit.Test)9 LogReader (org.apache.distributedlog.api.LogReader)7 DLSN (org.apache.distributedlog.DLSN)4 LogRecordWithDLSN (org.apache.distributedlog.LogRecordWithDLSN)4 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 AsyncLogReader (org.apache.distributedlog.api.AsyncLogReader)2 DynamicDistributedLogConfiguration (org.apache.distributedlog.config.DynamicDistributedLogConfiguration)2 Test (org.testng.annotations.Test)2 Stopwatch (com.google.common.base.Stopwatch)1 DLInputStream (com.twitter.heron.dlog.DLInputStream)1 File (java.io.File)1 InputStream (java.io.InputStream)1 URI (java.net.URI)1 Path (java.nio.file.Path)1 DistributedLogConfiguration (org.apache.distributedlog.DistributedLogConfiguration)1 AsyncLogWriter (org.apache.distributedlog.api.AsyncLogWriter)1 LogWriter (org.apache.distributedlog.api.LogWriter)1