Search in sources :

Example 6 with ByteArraySegment

use of io.pravega.common.util.ByteArraySegment in project pravega by pravega.

the class DataFrameOutputStream method write.

@Override
public void write(byte[] data, int offset, int length) throws IOException {
    Exceptions.checkNotClosed(this.closed, this);
    Preconditions.checkState(this.currentFrame != null, "No current frame exists. Most likely no record is started.");
    int totalBytesWritten = 0;
    int attemptsWithNoProgress = 0;
    while (totalBytesWritten < length) {
        int bytesWritten = this.currentFrame.append(new ByteArraySegment(data, offset + totalBytesWritten, length - totalBytesWritten));
        attemptsWithNoProgress = bytesWritten == 0 ? attemptsWithNoProgress + 1 : 0;
        if (attemptsWithNoProgress > 1) {
            // We had two consecutive attempts to write to a frame with no progress made.
            throw new IOException("Unable to make progress in serializing to DataFrame.");
        }
        // Update positions.
        totalBytesWritten += bytesWritten;
        if (totalBytesWritten < length) {
            // We were only able to write this partially because the current frame is full. Seal it and create a new one.
            this.currentFrame.endEntry(false);
            flush();
            createNewFrame();
            startNewRecordInCurrentFrame(false);
        }
    }
}
Also used : ByteArraySegment(io.pravega.common.util.ByteArraySegment) IOException(java.io.IOException)

Example 7 with ByteArraySegment

use of io.pravega.common.util.ByteArraySegment in project pravega by pravega.

the class RevisionDataOutputStreamTests method testImpl.

private void testImpl(RevisionDataOutputStream impl, Supplier<ByteArraySegment> getWrittenData) throws Exception {
    final byte b = 123;
    final short sn = 1234;
    final int n = 123456;
    final long l = (long) Integer.MAX_VALUE + 1;
    final String s = getUTFString();
    final byte[] array = s.getBytes();
    int expectedLength = Byte.BYTES + Short.BYTES + Integer.BYTES + Long.BYTES + impl.getUTFLength(s) + array.length;
    if (impl.requiresExplicitLength()) {
        // Verify a few methods that shouldn't be allowed to run without setting length beforehand.
        Arrays.<AssertExtensions.RunnableWithException>asList(() -> impl.write(1), () -> impl.write(new byte[1], 0, 1), () -> impl.writeInt(1), () -> impl.writeShort(1), () -> impl.writeLong(1), () -> impl.writeUTF("test")).forEach(r -> AssertExtensions.assertThrows("write was allowed without setting length first.", r, ex -> ex instanceof IllegalStateException));
    }
    impl.length(expectedLength);
    impl.writeByte(b);
    impl.writeShort(sn);
    impl.writeInt(n);
    impl.writeLong(l);
    impl.writeUTF(s);
    impl.write(array);
    // Need to close so we flush any remaining stuff to the underlying stream.
    impl.close();
    // Verify the written data can be read back.
    @Cleanup val inputStream = RevisionDataInputStream.wrap(getWrittenData.get().getReader());
    Assert.assertEquals("Unexpected length read back.", expectedLength, inputStream.getLength());
    Assert.assertEquals("Unexpected byte read back.", b, inputStream.read());
    Assert.assertEquals("Unexpected short read back.", sn, inputStream.readShort());
    Assert.assertEquals("Unexpected int read back.", n, inputStream.readInt());
    Assert.assertEquals("Unexpected long read back.", l, inputStream.readLong());
    Assert.assertEquals("Unexpected string read back.", s, inputStream.readUTF());
    byte[] readArray = new byte[array.length];
    int readBytes = inputStream.read(readArray);
    Assert.assertEquals("Unexpected number of bytes read for array.", readArray.length, readBytes);
    Assert.assertArrayEquals("Unexpected array read back.", array, readArray);
    Assert.assertEquals("Not expecting any more data. ", -1, inputStream.read());
    AssertExtensions.assertThrows("Expecting EOF.", () -> inputStream.readFully(new byte[1]), ex -> ex instanceof EOFException);
}
Also used : OutputStream(java.io.OutputStream) Arrays(java.util.Arrays) EnhancedByteArrayOutputStream(io.pravega.common.io.EnhancedByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AssertExtensions(io.pravega.test.common.AssertExtensions) FixedByteArrayOutputStream(io.pravega.common.io.FixedByteArrayOutputStream) lombok.val(lombok.val) Cleanup(lombok.Cleanup) Test(org.junit.Test) EOFException(java.io.EOFException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ByteArrayInputStream(java.io.ByteArrayInputStream) SerializationException(io.pravega.common.io.SerializationException) Assert(org.junit.Assert) lombok.val(lombok.val) AssertExtensions(io.pravega.test.common.AssertExtensions) EOFException(java.io.EOFException) Cleanup(lombok.Cleanup)

Example 8 with ByteArraySegment

use of io.pravega.common.util.ByteArraySegment in project pravega by pravega.

the class CheckpointOperationTests method configurePreSerialization.

@Override
protected void configurePreSerialization(CheckpointOperationBase operation, Random random) {
    if (operation.getContents() == null) {
        byte[] data = new byte[10245];
        random.nextBytes(data);
        operation.setContents(new ByteArraySegment(data));
    } else if (isPreSerializationConfigRequired(operation)) {
        Assert.fail("isPreSerializationConfigRequired returned true but there is nothing to be done.");
    }
}
Also used : ByteArraySegment(io.pravega.common.util.ByteArraySegment)

Example 9 with ByteArraySegment

use of io.pravega.common.util.ByteArraySegment in project pravega by pravega.

the class SegmentStoreReader method readExact.

@Override
public CompletableFuture<ReadItem> readExact(String segmentName, Object address) {
    Exceptions.checkNotNullOrEmpty(segmentName, "segmentName");
    Preconditions.checkArgument(address instanceof Address, "Unexpected address type.");
    Address a = (Address) address;
    return this.store.read(segmentName, a.offset, a.length, this.testConfig.getTimeout()).thenApplyAsync(readResult -> {
        byte[] data = new byte[a.length];
        readResult.readRemaining(data, this.testConfig.getTimeout());
        return new SegmentStoreReadItem(new Event(new ByteArraySegment(data), 0), address);
    }, this.executor);
}
Also used : ByteArraySegment(io.pravega.common.util.ByteArraySegment) Event(io.pravega.test.integration.selftest.Event)

Example 10 with ByteArraySegment

use of io.pravega.common.util.ByteArraySegment in project pravega by pravega.

the class BookKeeperLogTests method testRemoveEmptyLedgers.

/**
 * Tests the ability of BookKeeperLog to automatically remove empty ledgers during initialization.
 */
@Test
public void testRemoveEmptyLedgers() throws Exception {
    final int count = 100;
    final int writeEvery = count / 10;
    final Predicate<Integer> shouldAppendAnything = i -> i % writeEvery == 0;
    val allLedgers = new ArrayList<Map.Entry<Long, LedgerMetadata.Status>>();
    final Predicate<Integer> shouldExist = index -> (index >= allLedgers.size() - Ledgers.MIN_FENCE_LEDGER_COUNT) || (allLedgers.get(index).getValue() != LedgerMetadata.Status.Empty);
    for (int i = 0; i < count; i++) {
        try (BookKeeperLog log = (BookKeeperLog) createDurableDataLog()) {
            log.initialize(TIMEOUT);
            boolean shouldAppend = shouldAppendAnything.test(i);
            val currentMetadata = log.loadMetadata();
            val lastLedger = currentMetadata.getLedgers().get(currentMetadata.getLedgers().size() - 1);
            allLedgers.add(new AbstractMap.SimpleImmutableEntry<>(lastLedger.getLedgerId(), shouldAppend ? LedgerMetadata.Status.NotEmpty : LedgerMetadata.Status.Empty));
            val metadataLedgers = currentMetadata.getLedgers().stream().map(LedgerMetadata::getLedgerId).collect(Collectors.toSet());
            // Verify Log Metadata does not contain old empty ledgers.
            for (int j = 0; j < allLedgers.size(); j++) {
                val e = allLedgers.get(j);
                val expectedExist = shouldExist.test(j);
                Assert.assertEquals("Unexpected state for metadata. AllLedgerCount=" + allLedgers.size() + ", LedgerIndex=" + j + ", LedgerStatus=" + e.getValue(), expectedExist, metadataLedgers.contains(e.getKey()));
            }
            // Append some data to this Ledger, if needed.
            if (shouldAppend) {
                log.append(new ByteArraySegment(getWriteData()), TIMEOUT).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
            }
        }
    }
    // Verify that these ledgers have also been deleted from BookKeeper.
    for (int i = 0; i < allLedgers.size(); i++) {
        val e = allLedgers.get(i);
        if (shouldExist.test(i)) {
            // This should not throw any exceptions.
            Ledgers.openFence(e.getKey(), this.factory.get().getBookKeeperClient(), this.config.get());
        } else {
            AssertExtensions.assertThrows("Ledger not deleted from BookKeeper.", () -> Ledgers.openFence(e.getKey(), this.factory.get().getBookKeeperClient(), this.config.get()), ex -> true);
        }
    }
}
Also used : ObjectClosedException(io.pravega.common.ObjectClosedException) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) BeforeClass(org.junit.BeforeClass) SneakyThrows(lombok.SneakyThrows) AssertExtensions(io.pravega.test.common.AssertExtensions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cleanup(lombok.Cleanup) CompletableFuture(java.util.concurrent.CompletableFuture) LogAddress(io.pravega.segmentstore.storage.LogAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) DataLogNotAvailableException(io.pravega.segmentstore.storage.DataLogNotAvailableException) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) Map(java.util.Map) After(org.junit.After) Timeout(org.junit.rules.Timeout) DurableDataLogException(io.pravega.segmentstore.storage.DurableDataLogException) Before(org.junit.Before) AfterClass(org.junit.AfterClass) DurableDataLog(io.pravega.segmentstore.storage.DurableDataLog) KeeperException(org.apache.zookeeper.KeeperException) CancellationException(java.util.concurrent.CancellationException) Predicate(java.util.function.Predicate) lombok.val(lombok.val) Test(org.junit.Test) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) BKException(org.apache.bookkeeper.client.BKException) TimeUnit(java.util.concurrent.TimeUnit) AbstractMap(java.util.AbstractMap) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Rule(org.junit.Rule) ByteArraySegment(io.pravega.common.util.ByteArraySegment) DurableDataLogTestBase(io.pravega.segmentstore.storage.DurableDataLogTestBase) TreeMap(java.util.TreeMap) WriteFailureException(io.pravega.segmentstore.storage.WriteFailureException) TestUtils(io.pravega.test.common.TestUtils) Comparator(java.util.Comparator) Assert(org.junit.Assert) Futures(io.pravega.common.concurrent.Futures) lombok.val(lombok.val) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractMap(java.util.AbstractMap) Map(java.util.Map) AbstractMap(java.util.AbstractMap) TreeMap(java.util.TreeMap) Test(org.junit.Test)

Aggregations

ByteArraySegment (io.pravega.common.util.ByteArraySegment)28 lombok.val (lombok.val)20 Test (org.junit.Test)20 ArrayList (java.util.ArrayList)14 Cleanup (lombok.Cleanup)7 ObjectClosedException (io.pravega.common.ObjectClosedException)6 AssertExtensions (io.pravega.test.common.AssertExtensions)6 Assert (org.junit.Assert)6 IntentionalException (io.pravega.test.common.IntentionalException)5 IOException (java.io.IOException)5 TreeMap (java.util.TreeMap)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 Collectors (java.util.stream.Collectors)5 Rule (org.junit.Rule)5 Timeout (org.junit.rules.Timeout)5 Exceptions (io.pravega.common.Exceptions)4 DurableDataLog (io.pravega.segmentstore.storage.DurableDataLog)4 Duration (java.time.Duration)4 Comparator (java.util.Comparator)4