This is an automated email from the ASF dual-hosted git repository.

sijie pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/bookkeeper.git


The following commit(s) were added to refs/heads/master by this push:
     new e87bf7c  DbLedgerStorage -- ReadCache
e87bf7c is described below

commit e87bf7c10d2cd51453ddeb1c31ad8ce0a5f1544a
Author: Matteo Merli <[email protected]>
AuthorDate: Wed Dec 13 15:59:30 2017 -0800

    DbLedgerStorage -- ReadCache
    
    Adds a `ReadCache` class to be used from LedgerStorage.
    
    The read cache is used when doing read-ahead caching after reading one 
entry.
    
    The idea is that entries for the same ledger as stored in order (for each 
flush cycle, eg: 1min). When reading 1 entry, we expect the client to read all 
subsequent entries. We can then skip the RocksDb `get()` to fetch the index of 
the entries, by just keep reading from the entryLog, and exploiting page cache 
and seqeuential reads. The entries are then added to this ReadCache, where they 
will looked when the request for next entry comes in.
    
    This implementation is based on dividing the memory into multiple segments. 
Whenever the read cache is full, the oldest segment gets recycled and 
overwritten with new entries.
    
    Author: Matteo Merli <[email protected]>
    
    Reviewers: Sijie Guo <[email protected]>
    
    This closes #843 from merlimat/read-cache
---
 .../bookkeeper/bookie/storage/ldb/ReadCache.java   | 197 +++++++++++++++++++++
 .../bookie/storage/ldb/ReadCacheTest.java          | 118 ++++++++++++
 2 files changed, 315 insertions(+)

diff --git 
a/bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/storage/ldb/ReadCache.java
 
b/bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/storage/ldb/ReadCache.java
new file mode 100644
index 0000000..b14478f
--- /dev/null
+++ 
b/bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/storage/ldb/ReadCache.java
@@ -0,0 +1,197 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.bookkeeper.bookie.storage.ldb;
+
+import static org.apache.bookkeeper.bookie.storage.ldb.WriteCache.align64;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufAllocator;
+import io.netty.buffer.Unpooled;
+
+import java.io.Closeable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.apache.bookkeeper.util.collections.ConcurrentLongLongPairHashMap;
+import 
org.apache.bookkeeper.util.collections.ConcurrentLongLongPairHashMap.LongPair;
+
+/**
+ * Read cache implementation.
+ *
+ * <p>Uses the specified amount of memory and pairs it with a hashmap.
+ *
+ * <p>The memory is splitted in multiple segments that are used in a
+ * ring-buffer fashion. When the read cache is full, the oldest segment
+ * is cleared and rotated to make space for new entries to be added to
+ * the read cache.
+ */
+public class ReadCache implements Closeable {
+
+    private static final int DEFAULT_MAX_SEGMENT_SIZE = 1 * 1024 * 1024 * 1024;
+
+    private final List<ByteBuf> cacheSegments;
+    private final List<ConcurrentLongLongPairHashMap> cacheIndexes;
+
+    private int currentSegmentIdx;
+    private final AtomicInteger currentSegmentOffset = new AtomicInteger(0);
+
+    private final int segmentSize;
+
+    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+
+    public ReadCache(long maxCacheSize) {
+        this(maxCacheSize, DEFAULT_MAX_SEGMENT_SIZE);
+    }
+
+    public ReadCache(long maxCacheSize, int maxSegmentSize) {
+        int segmentsCount = Math.max(2, (int) (maxCacheSize / maxSegmentSize));
+        segmentSize = (int) (maxCacheSize / segmentsCount);
+
+        cacheSegments = new ArrayList<>();
+        cacheIndexes = new ArrayList<>();
+
+        for (int i = 0; i < segmentsCount; i++) {
+            cacheSegments.add(Unpooled.directBuffer(segmentSize, segmentSize));
+            cacheIndexes.add(new ConcurrentLongLongPairHashMap(4096, 2 * 
Runtime.getRuntime().availableProcessors()));
+        }
+    }
+
+    @Override
+    public void close() {
+        cacheSegments.forEach(ByteBuf::release);
+    }
+
+    public void put(long ledgerId, long entryId, ByteBuf entry) {
+        int entrySize = entry.readableBytes();
+        int alignedSize = align64(entrySize);
+
+        lock.readLock().lock();
+
+        try {
+            int offset = currentSegmentOffset.getAndAdd(alignedSize);
+            if (offset + entrySize > segmentSize) {
+                // Roll-over the segment (outside the read-lock)
+            } else {
+                // Copy entry into read cache segment
+                cacheSegments.get(currentSegmentIdx).setBytes(offset, entry, 
entry.readerIndex(),
+                        entry.readableBytes());
+                cacheIndexes.get(currentSegmentIdx).put(ledgerId, entryId, 
offset, entrySize);
+                return;
+            }
+        } finally {
+            lock.readLock().unlock();
+        }
+
+        // We could not insert in segment, we to get the write lock and 
roll-over to
+        // next segment
+        lock.writeLock().lock();
+
+        try {
+            int offset = currentSegmentOffset.getAndAdd(entrySize);
+            if (offset + entrySize > segmentSize) {
+                // Rollover to next segment
+                currentSegmentIdx = (currentSegmentIdx + 1) % 
cacheSegments.size();
+                currentSegmentOffset.set(alignedSize);
+                cacheIndexes.get(currentSegmentIdx).clear();
+                offset = 0;
+            }
+
+            // Copy entry into read cache segment
+            cacheSegments.get(currentSegmentIdx).setBytes(offset, entry, 
entry.readerIndex(), entry.readableBytes());
+            cacheIndexes.get(currentSegmentIdx).put(ledgerId, entryId, offset, 
entrySize);
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    public ByteBuf get(long ledgerId, long entryId) {
+        lock.readLock().lock();
+
+        try {
+            // We need to check all the segments, starting from the current 
one and looking
+            // backward to minimize the
+            // checks for recently inserted entries
+            int size = cacheSegments.size();
+            for (int i = 0; i < size; i++) {
+                int segmentIdx = (currentSegmentIdx + (size - i)) % size;
+
+                LongPair res = cacheIndexes.get(segmentIdx).get(ledgerId, 
entryId);
+                if (res != null) {
+                    int entryOffset = (int) res.first;
+                    int entryLen = (int) res.second;
+
+                    ByteBuf entry = 
ByteBufAllocator.DEFAULT.directBuffer(entryLen, entryLen);
+                    entry.writeBytes(cacheSegments.get(segmentIdx), 
entryOffset, entryLen);
+                    return entry;
+                }
+            }
+        } finally {
+            lock.readLock().unlock();
+        }
+
+        // Entry not found in any segment
+        return null;
+    }
+
+    /**
+     * @return the total size of cached entries
+     */
+    public long size() {
+        lock.readLock().lock();
+
+        try {
+            long size = 0;
+            for (int i = 0; i < cacheIndexes.size(); i++) {
+                if (i == currentSegmentIdx) {
+                    size += currentSegmentOffset.get();
+                } else if (!cacheIndexes.get(i).isEmpty()) {
+                    size += segmentSize;
+                } else {
+                    // the segment is empty
+                }
+            }
+
+            return size;
+        } finally {
+            lock.readLock().unlock();
+        }
+    }
+
+    /**
+     * @return the total number of cached entries
+     */
+    public long count() {
+        lock.readLock().lock();
+
+        try {
+            long count = 0;
+            for (int i = 0; i < cacheIndexes.size(); i++) {
+                count += cacheIndexes.get(i).size();
+            }
+
+            return count;
+        } finally {
+            lock.readLock().unlock();
+        }
+    }
+}
diff --git 
a/bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/storage/ldb/ReadCacheTest.java
 
b/bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/storage/ldb/ReadCacheTest.java
new file mode 100644
index 0000000..42e5099
--- /dev/null
+++ 
b/bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/storage/ldb/ReadCacheTest.java
@@ -0,0 +1,118 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.bookkeeper.bookie.storage.ldb;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+
+import org.junit.Test;
+
+/**
+ * Unit test for {@link ReadCache}.
+ */
+public class ReadCacheTest {
+
+    @Test
+    public void simple() {
+        ReadCache cache = new ReadCache(10 * 1024);
+
+        assertEquals(0, cache.count());
+        assertEquals(0, cache.size());
+
+        ByteBuf entry = Unpooled.wrappedBuffer(new byte[1024]);
+        cache.put(1, 0, entry);
+
+        assertEquals(1, cache.count());
+        assertEquals(1024, cache.size());
+
+        assertEquals(entry, cache.get(1, 0));
+        assertNull(cache.get(1, 1));
+
+        for (int i = 1; i < 10; i++) {
+            cache.put(1, i, entry);
+        }
+
+        assertEquals(10, cache.count());
+        assertEquals(10 * 1024, cache.size());
+
+        cache.put(1, 10, entry);
+
+        // First half of entries will have been evicted
+        for (int i = 0; i < 5; i++) {
+            assertNull(cache.get(1, i));
+        }
+
+        for (int i = 5; i < 11; i++) {
+            assertEquals(entry, cache.get(1, i));
+        }
+
+        cache.close();
+    }
+
+    @Test
+    public void emptyCache() {
+        ReadCache cache = new ReadCache(10 * 1024);
+
+        assertEquals(0, cache.count());
+        assertEquals(0, cache.size());
+        assertEquals(null, cache.get(0, 0));
+
+        cache.close();
+    }
+
+    @Test
+    public void multipleSegments() {
+        // Test with multiple smaller segments
+        ReadCache cache = new ReadCache(10 * 1024, 2 * 1024);
+
+        assertEquals(0, cache.count());
+        assertEquals(0, cache.size());
+
+        for (int i = 0; i < 10; i++) {
+            ByteBuf entry = Unpooled.wrappedBuffer(new byte[1024]);
+            entry.setInt(0, i);
+            cache.put(1, i, entry);
+        }
+
+        for (int i = 0; i < 10; i++) {
+            ByteBuf res = cache.get(1, i);
+            assertEquals(1, res.refCnt());
+
+            assertEquals(1024, res.readableBytes());
+            assertEquals(i, res.getInt(0));
+        }
+
+        assertEquals(10, cache.count());
+        assertEquals(10 * 1024, cache.size());
+
+        // Putting one more entry, should trigger the 1st segment rollover
+        ByteBuf entry = Unpooled.wrappedBuffer(new byte[1024]);
+        cache.put(2, 0, entry);
+
+        assertEquals(9, cache.count());
+        assertEquals(9 * 1024, cache.size());
+
+        cache.close();
+    }
+}

-- 
To stop receiving notification emails like this one, please contact
['"[email protected]" <[email protected]>'].

Reply via email to