Search in sources :

Example 1 with SegmentMock

use of io.pravega.segmentstore.server.SegmentMock in project pravega by pravega.

the class ContainerEventProcessorTests method testInitializationException.

/**
 * Check that if the creation of the EventProcessor fails, the future is completed exceptionally.
 *
 * @throws Exception
 */
@Test(timeout = 10000)
public void testInitializationException() throws Exception {
    AtomicBoolean induceFailure = new AtomicBoolean(true);
    Function<String, CompletableFuture<DirectSegmentAccess>> failingSegmentSupplier = s -> induceFailure.getAndSet(!induceFailure.get()) ? CompletableFuture.failedFuture(new IntentionalException()) : CompletableFuture.completedFuture(new SegmentMock(this.executorService()));
    @Cleanup ContainerEventProcessorImpl eventProcessorService = new ContainerEventProcessorImpl(0, failingSegmentSupplier, ITERATION_DELAY, CONTAINER_OPERATION_TIMEOUT, this.executorService());
    int maxItemsProcessed = 10;
    int maxOutstandingBytes = 4 * 1024 * 1024;
    int truncationDataSize = 500;
    ContainerEventProcessor.EventProcessorConfig config = new ContainerEventProcessor.EventProcessorConfig(maxItemsProcessed, maxOutstandingBytes, truncationDataSize);
    // Verify that if the creation of the EventProcessor takes too long, the future completes exceptionally.
    AssertExtensions.assertFutureThrows("Expected future exceptionally complete with IntentionalException", eventProcessorService.forConsumer("testExceptionForConsumer", l -> null, config), ex -> ex instanceof IntentionalException);
    // If the call has failed, the future for that EventProcessor should have been removed from the map.
    Assert.assertNull(eventProcessorService.getEventProcessorMap().get("testExceptionForConsumer"));
    // The next call is expected to succeed, so the future should be in the map when this call completes.
    Assert.assertNotNull(eventProcessorService.forConsumer("testExceptionForConsumer", l -> null, config).join());
    Assert.assertNotNull(eventProcessorService.getEventProcessorMap().get("testExceptionForConsumer"));
    AssertExtensions.assertFutureThrows("Expected future exceptionally complete with IntentionalException", eventProcessorService.forDurableQueue("testExceptionForDurableQueue"), ex -> ex instanceof IntentionalException);
    Assert.assertNull(eventProcessorService.getEventProcessorMap().get("testExceptionForDurableQueue"));
    Assert.assertNotNull(eventProcessorService.forDurableQueue("testExceptionForDurableQueue").join());
    Assert.assertNotNull(eventProcessorService.getEventProcessorMap().get("testExceptionForDurableQueue"));
}
Also used : IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ContainerEventProcessor(io.pravega.segmentstore.server.ContainerEventProcessor) AssertExtensions(io.pravega.test.common.AssertExtensions) Exceptions(io.pravega.common.Exceptions) Cleanup(lombok.Cleanup) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Mockito.spy(org.mockito.Mockito.spy) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) SegmentMetadata(io.pravega.segmentstore.server.SegmentMetadata) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Timeout(org.junit.rules.Timeout) SerializationException(io.pravega.common.io.SerializationException) Mockito.anyLong(org.mockito.Mockito.anyLong) ReusableLatch(io.pravega.common.util.ReusableLatch) IntentionalException(io.pravega.test.common.IntentionalException) Test(org.junit.Test) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) SegmentMock(io.pravega.segmentstore.server.SegmentMock) AtomicLong(java.util.concurrent.atomic.AtomicLong) DirectSegmentAccess(io.pravega.segmentstore.server.DirectSegmentAccess) List(java.util.List) Rule(org.junit.Rule) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) Mockito.anyInt(org.mockito.Mockito.anyInt) Assert(org.junit.Assert) Mockito.mock(org.mockito.Mockito.mock) SegmentMock(io.pravega.segmentstore.server.SegmentMock) Cleanup(lombok.Cleanup) IntentionalException(io.pravega.test.common.IntentionalException) ContainerEventProcessor(io.pravega.segmentstore.server.ContainerEventProcessor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.junit.Test)

Example 2 with SegmentMock

use of io.pravega.segmentstore.server.SegmentMock in project pravega by pravega.

the class IndexReaderWriterTests method newMock.

private SegmentMock newMock() {
    val mock = new SegmentMock(executorService());
    mock.updateAttributes(TableAttributes.DEFAULT_VALUES);
    return mock;
}
Also used : lombok.val(lombok.val) SegmentMock(io.pravega.segmentstore.server.SegmentMock)

Example 3 with SegmentMock

use of io.pravega.segmentstore.server.SegmentMock in project pravega by pravega.

the class IndexReaderWriterTests method checkIndex.

private void checkIndex(Collection<BufferView> allKeys, Map<Long, BufferView> existingKeysByOffset, IndexWriter w, KeyHasher hasher, SegmentMock segment) {
    val timer = new TimeoutTimer(TIMEOUT);
    // Group all keys by their full hash (each hash should translate to a bucket), and make sure they're ordered by
    // offset (in descending order - so we can verify backpointer ordering).
    val existingKeys = existingKeysByOffset.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    val keysByHash = allKeys.stream().map(key -> new BucketUpdate.KeyInfo(key, existingKeys.getOrDefault(key, NO_OFFSET), existingKeys.getOrDefault(key, NO_OFFSET))).sorted(// Reverse order.
    (k1, k2) -> Long.compare(k2.getOffset(), k1.getOffset())).collect(Collectors.groupingBy(keyInfo -> hasher.hash(keyInfo.getKey())));
    int existentBucketCount = 0;
    val buckets = w.locateBuckets(segment, keysByHash.keySet(), timer).join();
    for (val e : keysByHash.entrySet()) {
        val hash = e.getKey();
        val keys = e.getValue();
        val bucket = buckets.get(hash);
        Assert.assertNotNull("No bucket found for hash " + hash, bucket);
        boolean allDeleted = keys.stream().allMatch(k -> k.getOffset() == NO_OFFSET);
        Assert.assertNotEquals("Only expecting inexistent bucket when all its keys are deleted " + hash, allDeleted, bucket.exists());
        val bucketOffsets = w.getBucketOffsets(segment, bucket, timer).join();
        // Verify that we didn't return too many or too few keys.
        if (allDeleted) {
            Assert.assertEquals("Not expecting any offsets to be returned for bucket: " + hash, 0, bucketOffsets.size());
        } else {
            AssertExtensions.assertGreaterThan("Expected at least one offset to be returned for bucket: " + hash, 0, bucketOffsets.size());
            existentBucketCount++;
        }
        AssertExtensions.assertLessThanOrEqual("Too many offsets returned for bucket: " + hash, keys.size(), bucketOffsets.size());
        // Verify returned keys are as expected.
        for (int i = 0; i < bucketOffsets.size(); i++) {
            long actualOffset = bucketOffsets.get(i);
            long expectedOffset = keys.get(i).getOffset();
            String id = String.format("{%s[%s]}", hash, i);
            // In this loop, we do not expect to have Deleted Keys. If our Expected Offset indicates this key should
            // have been deleted, then getBucketOffsets() should not have returned this.
            Assert.assertNotEquals("Expecting a deleted key but found existing one: " + id, NO_OFFSET, expectedOffset);
            Assert.assertEquals("Unexpected key offset in bucket " + id, expectedOffset, actualOffset);
        }
        if (bucketOffsets.size() < keys.size()) {
            val prevKeyOffset = keys.get(bucketOffsets.size()).getOffset();
            Assert.assertEquals("Missing key from bucket " + hash, NO_OFFSET, prevKeyOffset);
        }
    }
    checkEntryCount(existingKeysByOffset.size(), segment);
    checkBucketCount(existentBucketCount, segment);
}
Also used : lombok.val(lombok.val) TableAttributes(io.pravega.segmentstore.contracts.tables.TableAttributes) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) AssertExtensions(io.pravega.test.common.AssertExtensions) HashMap(java.util.HashMap) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) HashSet(java.util.HashSet) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Timeout(org.junit.rules.Timeout) Attributes(io.pravega.segmentstore.contracts.Attributes) ImmutableMap(com.google.common.collect.ImmutableMap) TimeoutTimer(io.pravega.common.TimeoutTimer) Collection(java.util.Collection) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) Test(org.junit.Test) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) SegmentMock(io.pravega.segmentstore.server.SegmentMock) AtomicLong(java.util.concurrent.atomic.AtomicLong) DirectSegmentAccess(io.pravega.segmentstore.server.DirectSegmentAccess) Rule(org.junit.Rule) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) Comparator(java.util.Comparator) Assert(org.junit.Assert) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 4 with SegmentMock

use of io.pravega.segmentstore.server.SegmentMock in project pravega by pravega.

the class TableBucketReaderTests method testFindKey.

/**
 * Tests the ability to locate Table Keys in a Table Bucket using {@link TableBucketReader#key}.
 */
@Test
public void testFindKey() throws Exception {
    val segment = new SegmentMock(executorService());
    // Generate our test data and append it to the segment.
    val data = generateData();
    segment.append(new ByteArraySegment(data.serialization), null, TIMEOUT).join();
    val reader = TableBucketReader.key(segment, (s, offset, timeout) -> CompletableFuture.completedFuture(data.getBackpointer(offset)), executorService());
    // Check a valid result.
    val validKey = data.entries.get(1).getKey();
    val validResult = reader.find(validKey.getKey(), data.getBucketOffset(), new TimeoutTimer(TIMEOUT)).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    Assert.assertEquals("Unexpected version from valid key.", data.getEntryOffset(1), validResult.getVersion());
    Assert.assertEquals("Unexpected 'valid' key returned.", validKey.getKey(), validResult.getKey());
    // Check a key that does not exist.
    val invalidKey = data.unlinkedEntry.getKey();
    val invalidResult = reader.find(invalidKey.getKey(), data.getBucketOffset(), new TimeoutTimer(TIMEOUT)).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    Assert.assertNull("Not expecting any result for key that does not exist.", invalidResult);
}
Also used : lombok.val(lombok.val) ByteArraySegment(io.pravega.common.util.ByteArraySegment) SegmentMock(io.pravega.segmentstore.server.SegmentMock) TimeoutTimer(io.pravega.common.TimeoutTimer) Test(org.junit.Test)

Example 5 with SegmentMock

use of io.pravega.segmentstore.server.SegmentMock in project pravega by pravega.

the class TableBucketReaderTests method testFindAll.

@SneakyThrows
private <T> void testFindAll(GetBucketReader<T> createReader, Function<TableEntry, T> getItem, BiPredicate<T, T> areEqual) {
    val segment = new SegmentMock(executorService());
    // Generate our test data and append it to the segment.
    val data = generateData();
    segment.append(new ByteArraySegment(data.serialization), null, TIMEOUT).join();
    // Generate a deleted key and append it to the segment.
    val deletedKey = data.entries.get(0).getKey();
    val es = new EntrySerializer();
    val deletedData = es.serializeRemoval(Collections.singleton(deletedKey));
    long newBucketOffset = segment.append(deletedData, null, TIMEOUT).join();
    data.backpointers.put(newBucketOffset, data.getBucketOffset());
    // Create a new TableBucketReader and get all the requested items for this bucket. We pass the offset of the
    // deleted entry to make sure its data is not included.
    val reader = createReader.apply(segment, (s, offset, timeout) -> CompletableFuture.completedFuture(data.getBackpointer(offset)), executorService());
    val result = reader.findAllExisting(newBucketOffset, new TimeoutTimer(TIMEOUT)).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    // We expect to find all non-deleted Table Items that are linked.
    val expectedResult = data.entries.stream().filter(e -> data.backpointers.containsValue(e.getKey().getVersion())).map(getItem).collect(Collectors.toList());
    AssertExtensions.assertContainsSameElements("Unexpected result from findAll().", expectedResult, result, (i1, i2) -> areEqual.test(i1, i2) ? 0 : 1);
}
Also used : lombok.val(lombok.val) ByteArraySegment(io.pravega.common.util.ByteArraySegment) SegmentMock(io.pravega.segmentstore.server.SegmentMock) TimeoutTimer(io.pravega.common.TimeoutTimer) SneakyThrows(lombok.SneakyThrows)

Aggregations

SegmentMock (io.pravega.segmentstore.server.SegmentMock)9 ByteArraySegment (io.pravega.common.util.ByteArraySegment)7 Test (org.junit.Test)7 lombok.val (lombok.val)6 TimeoutTimer (io.pravega.common.TimeoutTimer)5 BufferView (io.pravega.common.util.BufferView)4 DirectSegmentAccess (io.pravega.segmentstore.server.DirectSegmentAccess)4 AssertExtensions (io.pravega.test.common.AssertExtensions)4 ThreadPooledTestSuite (io.pravega.test.common.ThreadPooledTestSuite)4 Duration (java.time.Duration)4 ArrayList (java.util.ArrayList)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 TimeUnit (java.util.concurrent.TimeUnit)4 AtomicLong (java.util.concurrent.atomic.AtomicLong)4 Assert (org.junit.Assert)4 Rule (org.junit.Rule)4 Timeout (org.junit.rules.Timeout)4 Exceptions (io.pravega.common.Exceptions)3 SerializationException (io.pravega.common.io.SerializationException)3 ReusableLatch (io.pravega.common.util.ReusableLatch)3