Search in sources :

Example 11 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class BTreeIndex method get.

/**
 * Looks up the value of a single key.
 *
 * @param key     A ByteArraySegment representing the key to look up.
 * @param timeout Timeout for the operation.
 * @return A CompletableFuture that, when completed normally, will contain the value associated with the given key.
 * If no value is associated with this key, the Future will complete with null. If the operation failed, the Future
 * will be completed with the appropriate exception.
 */
public CompletableFuture<ByteArraySegment> get(@NonNull ByteArraySegment key, @NonNull Duration timeout) {
    ensureInitialized();
    TimeoutTimer timer = new TimeoutTimer(timeout);
    // Lookup the page where the Key should exist (if at all).
    PageCollection pageCollection = new PageCollection(this.state.length);
    return locatePage(key, pageCollection, timer).thenApplyAsync(page -> page.getPage().searchExact(key), this.executor);
}
Also used : TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 12 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class BTreeIndex method update.

/**
 * Inserts, updates or removes the given Page Entries into the index. If {@link PageEntry#getValue()} is null, then
 * the page entry is removed, otherwise it is added.
 *
 * @param entries A Collection of Page Entries to insert. The collection need not be sorted.
 * @param timeout Timeout for the operation.
 * @return A CompletableFuture that, when completed normally, will indicate that the index updates have been applied
 * successfully and will contain the current version of the index (any modifications to the index will result in a
 * larger version value). If the operation failed, the Future will be completed with the appropriate exception.
 */
public CompletableFuture<Long> update(@NonNull Collection<PageEntry> entries, @NonNull Duration timeout) {
    ensureInitialized();
    TimeoutTimer timer = new TimeoutTimer(timeout);
    // Process the Entries in sorted order (by key); this makes the operation more efficient as we can batch-update
    // entries belonging to the same page.
    val toUpdate = entries.stream().sorted((e1, e2) -> KEY_COMPARATOR.compare(e1.getKey(), e2.getKey())).iterator();
    return applyUpdates(toUpdate, timer).thenComposeAsync(pageCollection -> loadSmallestOffsetPage(pageCollection, timer).thenRun(() -> processModifiedPages(pageCollection)).thenComposeAsync(v -> writePages(pageCollection, timer.getRemaining()), this.executor), this.executor);
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Setter(lombok.Setter) BufferViewComparator(io.pravega.common.util.BufferViewComparator) Getter(lombok.Getter) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Duration(java.time.Duration) Iterator(java.util.Iterator) TimeoutTimer(io.pravega.common.TimeoutTimer) Executor(java.util.concurrent.Executor) Predicate(java.util.function.Predicate) NonNull(lombok.NonNull) Collection(java.util.Collection) lombok.val(lombok.val) AsyncIterator(io.pravega.common.util.AsyncIterator) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ByteArraySegment(io.pravega.common.util.ByteArraySegment) Builder(lombok.Builder) Data(lombok.Data) Preconditions(com.google.common.base.Preconditions) IllegalDataFormatException(io.pravega.common.util.IllegalDataFormatException) Collections(java.util.Collections) Futures(io.pravega.common.concurrent.Futures) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 13 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class BTreeIndex method get.

/**
 * Looks up the value of multiple keys.
 *
 * @param keys    A list of ByteArraySegments representing the keys to look up.
 * @param timeout Timeout for the operation.
 * @return A CompletableFuture that, when completed normally, will contain a List with ByteArraySegments representing
 * the values associated with the given keys. The values in this list will be in the same order as the given Keys, so
 * they can be matched to their sought keys by their index. If the operation failed, the Future
 * will be completed with the appropriate exception.
 */
public CompletableFuture<List<ByteArraySegment>> get(@NonNull List<ByteArraySegment> keys, @NonNull Duration timeout) {
    if (keys.size() == 1) {
        // Shortcut for single key.
        return get(keys.get(0), timeout).thenApply(Collections::singletonList);
    }
    // Lookup all the keys in parallel, and make sure to apply their resulting values in the same order that their keys
    // where provided to us.
    ensureInitialized();
    TimeoutTimer timer = new TimeoutTimer(timeout);
    PageCollection pageCollection = new PageCollection(this.state.length);
    val gets = keys.stream().map(key -> locatePage(key, pageCollection, timer).thenApplyAsync(page -> page.getPage().searchExact(key), this.executor)).collect(Collectors.toList());
    return Futures.allOfWithResults(gets);
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Setter(lombok.Setter) BufferViewComparator(io.pravega.common.util.BufferViewComparator) Getter(lombok.Getter) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Duration(java.time.Duration) Iterator(java.util.Iterator) TimeoutTimer(io.pravega.common.TimeoutTimer) Executor(java.util.concurrent.Executor) Predicate(java.util.function.Predicate) NonNull(lombok.NonNull) Collection(java.util.Collection) lombok.val(lombok.val) AsyncIterator(io.pravega.common.util.AsyncIterator) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ByteArraySegment(io.pravega.common.util.ByteArraySegment) Builder(lombok.Builder) Data(lombok.Data) Preconditions(com.google.common.base.Preconditions) IllegalDataFormatException(io.pravega.common.util.IllegalDataFormatException) Collections(java.util.Collections) Futures(io.pravega.common.concurrent.Futures) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) Collections(java.util.Collections) TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 14 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class BTreeIndex method applyUpdates.

// endregion
// region Helpers
/**
 * Executes the given updates on the index. Loads up any necessary BTreePage instances in memory but does not persist
 * the changes to the external data source, nor does it reassign offsets to the modified pages, perform splits, etc.
 *
 * @param updates An Iterator of the PageEntry instances to insert, update or remove. The Iterator must return the
 *                updates in sorted order (by key).
 * @param timer   Timer for the operation.
 * @return A CompletableFuture that will contain a PageCollection with all touched pages.
 */
private CompletableFuture<UpdateablePageCollection> applyUpdates(Iterator<PageEntry> updates, TimeoutTimer timer) {
    UpdateablePageCollection pageCollection = new UpdateablePageCollection(this.state.length);
    AtomicReference<PageWrapper> lastPage = new AtomicReference<>(null);
    val lastPageUpdates = new ArrayList<PageEntry>();
    return Futures.loop(updates::hasNext, () -> {
        // Locate the page where the update is to be executed. Do not apply it yet as it is more efficient
        // to bulk-apply multiple at once. Collect all updates for each Page, and only apply them once we have
        // "moved on" to another page.
        PageEntry next = updates.next();
        return locatePage(next.getKey(), pageCollection, timer).thenAccept(page -> {
            PageWrapper last = lastPage.get();
            if (page != last) {
                // This key goes to a different page than the one we were looking at.
                if (last != null) {
                    // Commit the outstanding updates.
                    last.setEntryCountDelta(last.getPage().update(lastPageUpdates));
                }
                // Update the pointers.
                lastPage.set(page);
                lastPageUpdates.clear();
            }
            // Record the current update.
            lastPageUpdates.add(next);
        });
    }, this.executor).thenApplyAsync(v -> {
        // We need not forget to apply the last batch of updates from the last page.
        PageWrapper last = lastPage.get();
        if (last != null) {
            last.setEntryCountDelta(last.getPage().update(lastPageUpdates));
        }
        return pageCollection;
    }, this.executor);
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Setter(lombok.Setter) BufferViewComparator(io.pravega.common.util.BufferViewComparator) Getter(lombok.Getter) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Duration(java.time.Duration) Iterator(java.util.Iterator) TimeoutTimer(io.pravega.common.TimeoutTimer) Executor(java.util.concurrent.Executor) Predicate(java.util.function.Predicate) NonNull(lombok.NonNull) Collection(java.util.Collection) lombok.val(lombok.val) AsyncIterator(io.pravega.common.util.AsyncIterator) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ByteArraySegment(io.pravega.common.util.ByteArraySegment) Builder(lombok.Builder) Data(lombok.Data) Preconditions(com.google.common.base.Preconditions) IllegalDataFormatException(io.pravega.common.util.IllegalDataFormatException) Collections(java.util.Collections) Futures(io.pravega.common.concurrent.Futures) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 15 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class StreamSegmentContainerTests method tryActivate.

/**
 * Attempts to activate the targetSegment in the given Container. Since we do not have access to the internals of the
 * Container, we need to trigger this somehow, hence the need for this complex code. We need to trigger a truncation,
 * so we need an 'appendSegment' to which we continuously append so that the DurableDataLog is truncated. After truncation,
 * the Metadata should have enough leeway in making room for new activation.
 *
 * @return A Future that will complete either with an exception (failure) or SegmentProperties for the targetSegment.
 */
private CompletableFuture<SegmentProperties> tryActivate(MetadataCleanupContainer localContainer, String targetSegment, String appendSegment) {
    CompletableFuture<SegmentProperties> successfulMap = new CompletableFuture<>();
    // Append continuously to an existing segment in order to trigger truncations (these are necessary for forced evictions).
    val appendFuture = localContainer.appendRandomly(appendSegment, false, () -> !successfulMap.isDone());
    Futures.exceptionListener(appendFuture, successfulMap::completeExceptionally);
    // Repeatedly try to get info on 'segment1' (activate it), until we succeed or time out.
    TimeoutTimer remaining = new TimeoutTimer(TIMEOUT);
    Futures.loop(() -> !successfulMap.isDone(), () -> Futures.delayedFuture(Duration.ofMillis(EVICTION_SEGMENT_EXPIRATION_MILLIS_SHORT), executorService()).thenCompose(v -> localContainer.getStreamSegmentInfo(targetSegment, TIMEOUT)).thenAccept(successfulMap::complete).exceptionally(ex -> {
        if (!(Exceptions.unwrap(ex) instanceof TooManyActiveSegmentsException)) {
            // Some other error.
            successfulMap.completeExceptionally(ex);
        } else if (!remaining.hasRemaining()) {
            // Waited too long.
            successfulMap.completeExceptionally(new TimeoutException("No successful activation could be done in the allotted time."));
        }
        // Try again.
        return null;
    }), executorService());
    return successfulMap;
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Storage(io.pravega.segmentstore.storage.Storage) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) ContainerEventProcessor(io.pravega.segmentstore.server.ContainerEventProcessor) Cleanup(lombok.Cleanup) StorageWriterFactory(io.pravega.segmentstore.server.writer.StorageWriterFactory) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) Future(java.util.concurrent.Future) ContainerTableExtensionImpl(io.pravega.segmentstore.server.tables.ContainerTableExtensionImpl) InMemoryStorageFactory(io.pravega.segmentstore.storage.mocks.InMemoryStorageFactory) Duration(java.time.Duration) Map(java.util.Map) CachePolicy(io.pravega.segmentstore.server.CachePolicy) Operation(io.pravega.segmentstore.server.logs.operations.Operation) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) AsyncReadResultProcessor(io.pravega.segmentstore.server.reading.AsyncReadResultProcessor) ContainerReadIndexFactory(io.pravega.segmentstore.server.reading.ContainerReadIndexFactory) InMemoryDurableDataLogFactory(io.pravega.segmentstore.storage.mocks.InMemoryDurableDataLogFactory) DurableLogFactory(io.pravega.segmentstore.server.logs.DurableLogFactory) Attributes(io.pravega.segmentstore.contracts.Attributes) DurableLogConfig(io.pravega.segmentstore.server.logs.DurableLogConfig) Writer(io.pravega.segmentstore.server.Writer) StandardCharsets(java.nio.charset.StandardCharsets) Stream(java.util.stream.Stream) SegmentContainerFactory(io.pravega.segmentstore.server.SegmentContainerFactory) ContainerTableExtension(io.pravega.segmentstore.server.tables.ContainerTableExtension) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) SyncStorage(io.pravega.segmentstore.storage.SyncStorage) DirectMemoryCache(io.pravega.segmentstore.storage.cache.DirectMemoryCache) TestUtils(io.pravega.test.common.TestUtils) Futures(io.pravega.common.concurrent.Futures) CacheManager(io.pravega.segmentstore.server.CacheManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IllegalContainerStateException(io.pravega.segmentstore.server.IllegalContainerStateException) TooManyActiveSegmentsException(io.pravega.segmentstore.contracts.TooManyActiveSegmentsException) EntrySerializerTests(io.pravega.segmentstore.server.tables.EntrySerializerTests) Exceptions(io.pravega.common.Exceptions) StorageFactory(io.pravega.segmentstore.storage.StorageFactory) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) UpdateableContainerMetadata(io.pravega.segmentstore.server.UpdateableContainerMetadata) SegmentType(io.pravega.segmentstore.contracts.SegmentType) Runnables(com.google.common.util.concurrent.Runnables) AttributeIndexConfig(io.pravega.segmentstore.server.attributes.AttributeIndexConfig) ReadIndexConfig(io.pravega.segmentstore.server.reading.ReadIndexConfig) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BiConsumer(java.util.function.BiConsumer) Timeout(org.junit.rules.Timeout) WriterTableProcessor(io.pravega.segmentstore.server.tables.WriterTableProcessor) ConfigurationException(io.pravega.common.util.ConfigurationException) SegmentContainerExtension(io.pravega.segmentstore.server.SegmentContainerExtension) WriterFactory(io.pravega.segmentstore.server.WriterFactory) Properties(java.util.Properties) DurableDataLog(io.pravega.segmentstore.storage.DurableDataLog) Executor(java.util.concurrent.Executor) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) Assert.assertTrue(org.junit.Assert.assertTrue) OperationLog(io.pravega.segmentstore.server.OperationLog) TableExtensionConfig(io.pravega.segmentstore.server.tables.TableExtensionConfig) IOException(java.io.IOException) Test(org.junit.Test) SystemJournal(io.pravega.segmentstore.storage.chunklayer.SystemJournal) Service(com.google.common.util.concurrent.Service) AtomicLong(java.util.concurrent.atomic.AtomicLong) DirectSegmentAccess(io.pravega.segmentstore.server.DirectSegmentAccess) ContainerAttributeIndex(io.pravega.segmentstore.server.attributes.ContainerAttributeIndex) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) OperationLogFactory(io.pravega.segmentstore.server.OperationLogFactory) SegmentContainer(io.pravega.segmentstore.server.SegmentContainer) Assert(org.junit.Assert) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) Assert.assertEquals(org.junit.Assert.assertEquals) DynamicAttributeValue(io.pravega.segmentstore.contracts.DynamicAttributeValue) OperationPriority(io.pravega.segmentstore.server.logs.operations.OperationPriority) WriterConfig(io.pravega.segmentstore.server.writer.WriterConfig) SneakyThrows(lombok.SneakyThrows) AssertExtensions(io.pravega.test.common.AssertExtensions) BiFunction(java.util.function.BiFunction) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TimeoutException(java.util.concurrent.TimeoutException) ByteBuffer(java.nio.ByteBuffer) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) ReadIndexFactory(io.pravega.segmentstore.server.ReadIndexFactory) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) ContainerAttributeIndexFactoryImpl(io.pravega.segmentstore.server.attributes.ContainerAttributeIndexFactoryImpl) AttributeIndexFactory(io.pravega.segmentstore.server.attributes.AttributeIndexFactory) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) AbstractService(com.google.common.util.concurrent.AbstractService) AttributeIdLengthMismatchException(io.pravega.segmentstore.server.logs.AttributeIdLengthMismatchException) ServiceListeners(io.pravega.segmentstore.server.ServiceListeners) ContainerOfflineException(io.pravega.segmentstore.server.ContainerOfflineException) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletionException(java.util.concurrent.CompletionException) ReadResultEntryType(io.pravega.segmentstore.contracts.ReadResultEntryType) UUID(java.util.UUID) DataLogWriterNotPrimaryException(io.pravega.segmentstore.storage.DataLogWriterNotPrimaryException) DynamicAttributeUpdate(io.pravega.segmentstore.contracts.DynamicAttributeUpdate) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) SegmentMetadataComparer(io.pravega.segmentstore.server.SegmentMetadataComparer) List(java.util.List) ByteArraySegment(io.pravega.common.util.ByteArraySegment) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) WriterSegmentProcessor(io.pravega.segmentstore.server.WriterSegmentProcessor) DurableDataLogFactory(io.pravega.segmentstore.storage.DurableDataLogFactory) ReadResult(io.pravega.segmentstore.contracts.ReadResult) IntStream(java.util.stream.IntStream) ObjectClosedException(io.pravega.common.ObjectClosedException) Setter(lombok.Setter) Getter(lombok.Getter) AsyncStorageWrapper(io.pravega.segmentstore.storage.AsyncStorageWrapper) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) CacheStorage(io.pravega.segmentstore.storage.cache.CacheStorage) HashSet(java.util.HashSet) SegmentMetadata(io.pravega.segmentstore.server.SegmentMetadata) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) ExecutorService(java.util.concurrent.ExecutorService) NameUtils(io.pravega.shared.NameUtils) ExecutorServiceHelpers.newScheduledThreadPool(io.pravega.common.concurrent.ExecutorServiceHelpers.newScheduledThreadPool) TimeoutTimer(io.pravega.common.TimeoutTimer) RollingStorage(io.pravega.segmentstore.storage.rolling.RollingStorage) IntentionalException(io.pravega.test.common.IntentionalException) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) TestReadResultHandler(io.pravega.segmentstore.server.reading.TestReadResultHandler) SnapshotInfo(io.pravega.segmentstore.storage.chunklayer.SnapshotInfo) TestDurableDataLogFactory(io.pravega.segmentstore.server.TestDurableDataLogFactory) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Rule(org.junit.Rule) SegmentOperation(io.pravega.segmentstore.server.SegmentOperation) CachedStreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.CachedStreamSegmentAppendOperation) TypedProperties(io.pravega.common.util.TypedProperties) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) ReadIndex(io.pravega.segmentstore.server.ReadIndex) Comparator(java.util.Comparator) Collections(java.util.Collections) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) InputStream(java.io.InputStream) CompletableFuture(java.util.concurrent.CompletableFuture) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) TooManyActiveSegmentsException(io.pravega.segmentstore.contracts.TooManyActiveSegmentsException) TimeoutTimer(io.pravega.common.TimeoutTimer) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

TimeoutTimer (io.pravega.common.TimeoutTimer)97 lombok.val (lombok.val)55 CompletableFuture (java.util.concurrent.CompletableFuture)52 Duration (java.time.Duration)51 Futures (io.pravega.common.concurrent.Futures)47 Preconditions (com.google.common.base.Preconditions)41 CompletionException (java.util.concurrent.CompletionException)41 Slf4j (lombok.extern.slf4j.Slf4j)41 Collectors (java.util.stream.Collectors)40 SneakyThrows (lombok.SneakyThrows)40 Exceptions (io.pravega.common.Exceptions)39 BufferView (io.pravega.common.util.BufferView)37 Getter (lombok.Getter)37 SegmentProperties (io.pravega.segmentstore.contracts.SegmentProperties)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)36 StreamSegmentNotExistsException (io.pravega.segmentstore.contracts.StreamSegmentNotExistsException)34 SegmentMetadata (io.pravega.segmentstore.server.SegmentMetadata)34 RequiredArgsConstructor (lombok.RequiredArgsConstructor)34 ArrayList (java.util.ArrayList)33 List (java.util.List)31