Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
Limit the synchronization blocking time on some Cache operations.
lucciomana7394b479b4a
diff --git a/source/net/yacy/crawler/data/Cache.java b/source/net/yacy/crawler/data/Cache.javaindex 1ed2927e0..96a97872f 100644--- a/source/net/yacy/crawler/data/Cache.java+++ b/source/net/yacy/crawler/data/Cache.java@@ -57,6 +57,16 @@ import net.yacy.kelondro.index.RowHandleSet;public final class Cache {+ /** Default size in bytes of the backend buffer (buffered bytes before writing to the the file system) */+ protected static final int DEFAULT_BACKEND_BUFFER_SIZE = 1024 * 1024 * 2;++ /** Default size in bytes of the compressor buffer (buffered bytes before compressing and sending to the backend ) */+ protected static final int DEFAULT_COMPRESSOR_BUFFER_SIZE = 6 * 1024 * 1024;++ /** Default size in bytes of the response header data base buffer (buffered bytes before writing to the file system) */+ protected static final int DEFAULT_RESPONSE_HEADER_BUFFER_SIZE = 2048;++private static final String RESPONSE_HEADER_DB_NAME = "responseHeader.heap";private static final String FILE_DB_NAME = "file.array";@@ -69,10 +79,16 @@ public final class Cache {private static String prefix;public static final ConcurrentLog log = new ConcurrentLog("HTCACHE");- public static void init(final File htCachePath, final String peerSalt, final long CacheSizeMax) {+ /**+ * @param htCachePath folder path for the cache+ * @param peerSalt peer identifier+ * @param cacheSizeMax maximum cache size in bytes+ * @param lockTimeout maximum time (in milliseconds) to acquire a synchronization lock on store() and getContent()+ */+ public static void init(final File htCachePath, final String peerSalt, final long cacheSizeMax, final long lockTimeout) {cachePath = htCachePath;- maxCacheSize = CacheSizeMax;+ maxCacheSize = cacheSizeMax;prefix = peerSalt;// set/make cache path@@ -83,14 +99,14 @@ public final class Cache {// open the response header databasefinal File dbfile = new File(cachePath, RESPONSE_HEADER_DB_NAME);try {- responseHeaderDB = new MapHeap(dbfile, Word.commonHashLength, Base64Order.enhancedCoder, 2048, 100, ' ');+ responseHeaderDB = new MapHeap(dbfile, Word.commonHashLength, Base64Order.enhancedCoder, DEFAULT_RESPONSE_HEADER_BUFFER_SIZE, 100, ' ');} catch (final IOException e) {ConcurrentLog.logException(e);// try a healingif (dbfile.exists()) {dbfile.delete();try {- responseHeaderDB = new MapHeap(dbfile, Word.commonHashLength, Base64Order.enhancedCoder, 2048, 100, ' ');+ responseHeaderDB = new MapHeap(dbfile, Word.commonHashLength, Base64Order.enhancedCoder, DEFAULT_RESPONSE_HEADER_BUFFER_SIZE, 100, ' ');} catch (final IOException ee) {ConcurrentLog.logException(e);}@@ -98,18 +114,18 @@ public final class Cache {}// open the cache filetry {- fileDBunbuffered = new ArrayStack(new File(cachePath, FILE_DB_NAME), prefix, Base64Order.enhancedCoder, 12, 1024 * 1024 * 2, false, true);+ fileDBunbuffered = new ArrayStack(new File(cachePath, FILE_DB_NAME), prefix, Base64Order.enhancedCoder, 12, DEFAULT_BACKEND_BUFFER_SIZE, false, true);fileDBunbuffered.setMaxSize(maxCacheSize);- fileDB = new Compressor(fileDBunbuffered, 6 * 1024 * 1024);+ fileDB = new Compressor(fileDBunbuffered, DEFAULT_COMPRESSOR_BUFFER_SIZE, lockTimeout);} catch (final IOException e) {ConcurrentLog.logException(e);// try a healingif (cachePath.exists()) {cachePath.delete();try {- fileDBunbuffered = new ArrayStack(new File(cachePath, FILE_DB_NAME), prefix, Base64Order.enhancedCoder, 12, 1024 * 1024 * 2, false, true);+ fileDBunbuffered = new ArrayStack(new File(cachePath, FILE_DB_NAME), prefix, Base64Order.enhancedCoder, 12, DEFAULT_BACKEND_BUFFER_SIZE, false, true);fileDBunbuffered.setMaxSize(maxCacheSize);- fileDB = new Compressor(fileDBunbuffered, 6 * 1024 * 1024);+ fileDB = new Compressor(fileDBunbuffered, DEFAULT_COMPRESSOR_BUFFER_SIZE, lockTimeout);} catch (final IOException ee) {ConcurrentLog.logException(e);}@@ -196,16 +212,16 @@ public final class Cache {}/**- * get the current actual cache size- * @return+ * Warning : even when the cache is empty,+ * the actual cache size may not be zero because heap files still containing zeros after deletions+ * @return the current actual cache size stored on disk*/public static long getActualCacheSize() {return fileDBunbuffered.length();}/**- * get the current actual cache size- * @return+ * @return the current actual number of cached documents stored on disk*/public static long getActualCacheDocCount() {return fileDBunbuffered.size();diff --git a/source/net/yacy/kelondro/blob/ArrayStack.java b/source/net/yacy/kelondro/blob/ArrayStack.javaindex bcc2817e7..46da81835 100644--- a/source/net/yacy/kelondro/blob/ArrayStack.java+++ b/source/net/yacy/kelondro/blob/ArrayStack.java@@ -99,7 +99,7 @@ public class ArrayStack implements BLOB {private final int buffersize;private final boolean trimall;- // the thread pool for the keeperOf executor service+ /** the thread pool for the keeperOf executor service */private final ExecutorService executor;// use our own formatter to prevent concurrency locks with other processes@@ -881,6 +881,22 @@ public class ArrayStack implements BLOB {private static final ExecutorService DELETE_EXECUTOR = Executors.newCachedThreadPool(new NamePrefixThreadFactory(ArrayStack.class.getSimpleName() + ".DELETE_EXECUTOR"));++ /**+ * Shutdown the delete executor service used to run asynchronously deletions on any ArrayStack instance+ */+ public static void shutdownDeleteService() {+ DELETE_EXECUTOR.shutdown();+ final long timeout = 1;+ try {+ final boolean terminated = DELETE_EXECUTOR.awaitTermination(timeout, TimeUnit.SECONDS);+ if(!terminated) {+ ConcurrentLog.warn("ArrayStack", "Delete executor service could not terminated within " + timeout + " second");+ }+ } catch (InterruptedException e) {+ ConcurrentLog.warn("ArrayStack", "Interrupted before termination of the delete executor service");+ }+ }/*** close the BLOB@@ -890,6 +906,7 @@ public class ArrayStack implements BLOB {for (final blobItem bi: this.blobs) bi.blob.close(writeIDX);this.blobs.clear();this.blobs = null;+ this.executor.shutdown();}/**diff --git a/source/net/yacy/kelondro/blob/Compressor.java b/source/net/yacy/kelondro/blob/Compressor.javaindex 73fc52b05..1bbb2c233 100644--- a/source/net/yacy/kelondro/blob/Compressor.java+++ b/source/net/yacy/kelondro/blob/Compressor.java@@ -35,6 +35,8 @@ import java.io.OutputStream;import java.util.Iterator;import java.util.Map;import java.util.TreeMap;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.locks.ReentrantLock;import java.util.zip.Deflater;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;@@ -53,13 +55,25 @@ public class Compressor implements BLOB, Iterable<byte[]> {private static byte[] plainMagic = {(byte) 'p', (byte) '|'}; // magic for plain content (no encoding)private final BLOB backend;- private TreeMap<byte[], byte[]> buffer; // entries which are not yet compressed, format is RAW (without magic)++ /** entries which are not yet compressed, format is RAW (without magic) */+ private TreeMap<byte[], byte[]> buffer;++ /** Total size (in bytes) of uncompressed entries in buffer */private long bufferlength;private final long maxbufferlength;-- public Compressor(final BLOB backend, final long buffersize) {++ /** Maximum time (in milliseconds) to acquire a synchronization lock on get() and insert() */+ private final long lockTimeout;++ /** Synchronization lock */+ private final ReentrantLock lock;++ public Compressor(final BLOB backend, final long buffersize, final long lockTimeout) {this.backend = backend;this.maxbufferlength = buffersize;+ this.lockTimeout = lockTimeout;+ this.lock = new ReentrantLock();initBuffer();}@@ -79,9 +93,14 @@ public class Compressor implements BLOB, Iterable<byte[]> {}@Override- public synchronized void clear() throws IOException {- initBuffer();- this.backend.clear();+ public void clear() throws IOException {+ this.lock.lock();+ try {+ initBuffer();+ this.backend.clear();+ } finally {+ this.lock.unlock();+ }}private void initBuffer() {@@ -95,10 +114,15 @@ public class Compressor implements BLOB, Iterable<byte[]> {}@Override- public synchronized void close(final boolean writeIDX) {- // no more thread is running, flush all queues- flushAll();- this.backend.close(writeIDX);+ public void close(final boolean writeIDX) {+ this.lock.lock();+ try {+ // no more thread is running, flush all queues+ flushAll();+ this.backend.close(writeIDX);+ } finally {+ this.lock.unlock();+ }}private static byte[] compress(final byte[] b) {@@ -177,22 +201,35 @@ public class Compressor implements BLOB, Iterable<byte[]> {// depending on the source of the result, we additionally do entry compression// because if a document was read once, we think that it will not be retrieved another time again soonbyte[] b = null;- synchronized (this) {- b = this.buffer.remove(key);- if (b != null) {- this.backend.insert(key, compress(b));- this.bufferlength = this.bufferlength - b.length;- return b;+ boolean locked = false;+ try {+ locked = this.lock.tryLock(this.lockTimeout, TimeUnit.MILLISECONDS);+ } catch (InterruptedException ignored) {+ /* When interrupted, simply return null */+ ConcurrentLog.fine("Compressor", "Interrupted while acquiring a synchronzation lock on get()");+ }+ if(locked) {+ try {+ b = this.buffer.remove(key);+ if (b != null) {+ this.bufferlength = this.bufferlength - b.length;+ this.backend.insert(key, compress(b));+ return b;+ }+ } finally {+ this.lock.unlock();+ }++ // return from the backend+ b = this.backend.get(key);+ if (b == null) return null;+ if (!MemoryControl.request(b.length * 2, true)) {+ throw new SpaceExceededException(b.length * 2, "decompress needs 2 * " + b.length + " bytes");}+ return decompress(b);}-- // return from the backend- b = this.backend.get(key);- if (b == null) return null;- if (!MemoryControl.request(b.length * 2, true)) {- throw new SpaceExceededException(b.length * 2, "decompress needs 2 * " + b.length + " bytes");- }- return decompress(b);+ ConcurrentLog.fine("Compressor", "Could not acquire a synchronization lock for retrieval within " + this.lockTimeout + " milliseconds");+ return b;}@Override@@ -210,8 +247,11 @@ public class Compressor implements BLOB, Iterable<byte[]> {@Overridepublic boolean containsKey(final byte[] key) {- synchronized (this) {+ this.lock.lock();+ try {return this.buffer.containsKey(key) || this.backend.containsKey(key);+ } finally {+ this.lock.unlock();}}@@ -221,18 +261,22 @@ public class Compressor implements BLOB, Iterable<byte[]> {}@Override- public synchronized long length() {+ public long length() {+ this.lock.lock();try {return this.backend.length() + this.bufferlength;} catch (final IOException e) {ConcurrentLog.logException(e);return 0;+ } finally {+ this.lock.unlock();}}@Overridepublic long length(final byte[] key) throws IOException {- synchronized (this) {+ this.lock.lock();+ try {byte[] b = this.buffer.get(key);if (b != null) return b.length;try {@@ -243,6 +287,8 @@ public class Compressor implements BLOB, Iterable<byte[]> {} catch (final SpaceExceededException e) {throw new IOException(e.getMessage());}+ } finally {+ this.lock.unlock();}}@@ -254,61 +300,100 @@ public class Compressor implements BLOB, Iterable<byte[]> {@Overridepublic void insert(final byte[] key, final byte[] b) throws IOException {-- // first ensure that the files do not exist anywhere- delete(key);-- // check if the buffer is full or could be full after this write- if (this.bufferlength + b.length * 2 > this.maxbufferlength) synchronized (this) {- // in case that we compress, just compress as much as is necessary to get enough room- while (this.bufferlength + b.length * 2 > this.maxbufferlength) {- if (this.buffer.isEmpty()) break;- flushOne();- }- // in case that this was not enough, just flush all- if (this.bufferlength + b.length * 2 > this.maxbufferlength) flushAll();- }-- // files are written uncompressed to the uncompressed-queue- // they are either written uncompressed to the database- // or compressed later- synchronized (this) {- this.buffer.put(key, b);- this.bufferlength += b.length;- }-- if (MemoryControl.shortStatus()) flushAll();+ boolean locked = false;+ try {+ locked = this.lock.tryLock(this.lockTimeout, TimeUnit.MILLISECONDS);+ } catch (InterruptedException ignored) {+ /* When interrupted, simply nothing is inserted */+ ConcurrentLog.fine("Compressor", "Interrupted while acquiring a synchronzation lock on insert()");+ }+ if(locked) {+ try {+ // first ensure that the files do not exist anywhere+ delete(key);++ // check if the buffer is full or could be full after this write+ if (this.bufferlength + b.length * 2 > this.maxbufferlength) {+ // in case that we compress, just compress as much as is necessary to get enough room+ while (this.bufferlength + b.length * 2 > this.maxbufferlength) {+ if (this.buffer.isEmpty()) break;+ flushOne();+ }+ // in case that this was not enough, just flush all+ if (this.bufferlength + b.length * 2 > this.maxbufferlength) flushAll();+ }++ // files are written uncompressed to the uncompressed-queue+ // they are either written uncompressed to the database+ // or compressed later+ this.buffer.put(key, b);+ this.bufferlength += b.length;+ } finally {+ this.lock.unlock();+ }++ if (MemoryControl.shortStatus()) {+ flushAll();+ }+ } else {+ ConcurrentLog.fine("Compressor", "Could not acquire a synchronization lock for insertion within " + this.lockTimeout + " milliseconds");+ }}@Override- public synchronized void delete(final byte[] key) throws IOException {- this.backend.delete(key);- final long rx = removeFromQueues(key);- if (rx > 0) this.bufferlength -= rx;+ public void delete(final byte[] key) throws IOException {+ this.lock.lock();+ try {+ this.backend.delete(key);+ final long rx = removeFromQueues(key);+ if (rx > 0) this.bufferlength -= rx;+ } finally {+ this.lock.unlock();+ }}@Override- public synchronized int size() {- return this.backend.size() + this.buffer.size();+ public int size() {+ this.lock.lock();+ try {+ return this.backend.size() + this.buffer.size();+ } finally {+ this.lock.unlock();+ }}@Override- public synchronized boolean isEmpty() {- if (!this.backend.isEmpty()) return false;- if (!this.buffer.isEmpty()) return false;- return true;+ public boolean isEmpty() {+ this.lock.lock();+ try {+ if (!this.backend.isEmpty()) return false;+ if (!this.buffer.isEmpty()) return false;+ return true;+ } finally {+ this.lock.unlock();+ }}@Override- public synchronized CloneableIterator<byte[]> keys(final boolean up, final boolean rotating) throws IOException {- flushAll();- return this.backend.keys(up, rotating);+ public CloneableIterator<byte[]> keys(final boolean up, final boolean rotating) throws IOException {+ this.lock.lock();+ try {+ flushAll();+ return this.backend.keys(up, rotating);+ } finally {+ this.lock.unlock();+ }}@Override- public synchronized CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {- flushAll();- return this.backend.keys(up, firstKey);+ public CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {+ this.lock.lock();+ try {+ flushAll();+ return this.backend.keys(up, firstKey);+ } finally {+ this.lock.unlock();+ }}@Override@@ -337,9 +422,16 @@ public class Compressor implements BLOB, Iterable<byte[]> {}public void flushAll() {- while (!this.buffer.isEmpty()) {- if (!flushOne()) break;- }+ this.lock.lock();+ try {+ while (!this.buffer.isEmpty()) {+ if (!flushOne()) {+ break;+ }+ }+ } finally {+ this.lock.unlock();+ }}@Overridediff --git a/source/net/yacy/search/Switchboard.java b/source/net/yacy/search/Switchboard.javaindex 0637bef3e..1ae05c993 100644--- a/source/net/yacy/search/Switchboard.java+++ b/source/net/yacy/search/Switchboard.java@@ -180,6 +180,7 @@ import net.yacy.document.parser.html.Evaluation;import net.yacy.gui.Audio;import net.yacy.gui.Tray;import net.yacy.http.YaCyHttpServer;+import net.yacy.kelondro.blob.ArrayStack;import net.yacy.kelondro.blob.BEncodedHeap;import net.yacy.kelondro.blob.Tables;import net.yacy.kelondro.data.meta.URIMetadataNode;@@ -722,7 +723,7 @@ public final class Switchboard extends serverSwitch {this.log.info("HTCACHE Path = " + this.htCachePath.getAbsolutePath());final long maxCacheSize =1024L * 1024L * Long.parseLong(getConfig(SwitchboardConstants.PROXY_CACHE_SIZE, "2")); // this is megabyte- Cache.init(this.htCachePath, this.peers.mySeed().hash, maxCacheSize);+ Cache.init(this.htCachePath, this.peers.mySeed().hash, maxCacheSize, 2000);final File transactiondir = new File(this.htCachePath, "snapshots");Transactions.init(transactiondir);@@ -1894,6 +1895,7 @@ public final class Switchboard extends serverSwitch {Domains.close();AccessTracker.dumpLog();Switchboard.urlBlacklist.close();+ ArrayStack.shutdownDeleteService();UPnP.deletePortMappings();this.tray.remove();try {diff --git a/test/java/net/yacy/crawler/data/CacheTest.java b/test/java/net/yacy/crawler/data/CacheTest.javanew file mode 100644index 000000000..bb71b5e84--- /dev/null+++ b/test/java/net/yacy/crawler/data/CacheTest.java@@ -0,0 +1,597 @@+// CacheTest.java+// ---------------------------+// Copyright 2017 by luccioman; https://github.com/luccioman+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package net.yacy.crawler.data;++import static org.junit.Assert.*;++import java.io.ByteArrayInputStream;+import java.io.File;+import java.io.IOException;+import java.net.MalformedURLException;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.List;+import java.util.Random;+import java.util.concurrent.TimeUnit;+import java.util.logging.LogManager;++import org.apache.http.HttpStatus;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import net.yacy.cora.document.id.DigestURL;+import net.yacy.cora.protocol.Domains;+import net.yacy.cora.protocol.ResponseHeader;+import net.yacy.cora.util.ConcurrentLog;+import net.yacy.kelondro.blob.ArrayStack;++/**+ * Unit tests for the {@link Cache} class, and stress test as main function.+ *+ * @author luc+ *+ */+public class CacheTest {++ /**+ * Simple test content. Given its reduced size, it is likely to stay in+ * cache buffers and not written on disk+ */+ private static final String TEXT_CONTENT = "Simple text content";++ /**+ * Run before each unit test+ */+ @Before+ public void setUp() {+ Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "testCache"), "peerSalt",+ Math.max(Math.max(TEXT_CONTENT.getBytes(StandardCharsets.UTF_8).length * 10,+ Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE * 2), Cache.DEFAULT_BACKEND_BUFFER_SIZE * 2),+ 2000);+ Cache.clear();+ }++ /**+ * Run after each unit test+ */+ @After+ public void tearDown() {+ Cache.clear();+ Cache.close();+ }++ /**+ * @return random bytes likely to be flushed to the file system when+ * inserted into cache+ */+ private static byte[] generateFlushableContent() {+ /* Set the size higher than the cache backend buffers */+ final byte[] content = new byte[Math.max(Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE + 1,+ Cache.DEFAULT_BACKEND_BUFFER_SIZE + 1)];+ /* Fill the content with random bytes so they can not be compressed */+ new Random().nextBytes(content);+ return content;+ }++ @Test+ public void testGetContent() throws MalformedURLException, IOException {+ final ResponseHeader okResponse = new ResponseHeader(HttpStatus.SC_OK);+ DigestURL url = new DigestURL("http://yacy.net");+ byte[] urlHash = url.hash();+ byte[] fileContent = TEXT_CONTENT.getBytes(StandardCharsets.UTF_8);++ /* content not in cache */+ assertNull(Cache.getContent(urlHash));++ /* Store without committing */+ Cache.store(url, okResponse, fileContent);++ /* content now in cache */+ assertArrayEquals(fileContent, Cache.getContent(urlHash));++ /* Commit */+ Cache.commit();++ /* content is still in cache */+ assertArrayEquals(fileContent, Cache.getContent(urlHash));++ /* update the existing entry */+ fileContent = "abcdef".getBytes(StandardCharsets.UTF_8);+ Cache.store(url, okResponse, fileContent);++ /* content has been updated */+ assertArrayEquals(fileContent, Cache.getContent(urlHash));++ /*+ * Store an entry larger than backend buffer sizes, likely to be flushed+ * to the file system+ */+ url = new DigestURL("http://json.org");+ urlHash = url.hash();+ fileContent = generateFlushableContent();+ Cache.store(new DigestURL("http://json.org"), okResponse, fileContent);+ Cache.commit();+ /* content is in cache */+ assertArrayEquals(fileContent, Cache.getContent(urlHash));+ }++ @Test+ public void testDelete() throws MalformedURLException, IOException {+ final ResponseHeader okResponse = new ResponseHeader(HttpStatus.SC_OK);+ final DigestURL url = new DigestURL("http://yacy.net");+ final byte[] urlHash = url.hash();+ final byte[] fileContent = TEXT_CONTENT.getBytes(StandardCharsets.UTF_8);++ /* try deleting an entry not in cache */+ Cache.delete(urlHash);+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));++ /* Store without committing */+ Cache.store(url, okResponse, fileContent);+ assertTrue(Cache.has(urlHash));+ assertTrue(Cache.hasContent(urlHash));++ /* delete entry in cache */+ Cache.delete(urlHash);+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));++ /* Store and commit */+ Cache.store(url, okResponse, fileContent);+ Cache.commit();+ assertTrue(Cache.has(urlHash));+ assertTrue(Cache.hasContent(urlHash));++ /* delete entry in cache */+ Cache.delete(urlHash);+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));++ /*+ * Store an entry larger than backend buffer sizes, likely to be flushed+ * to the file system+ */+ Cache.store(url, okResponse, generateFlushableContent());+ Cache.commit();+ assertTrue(Cache.has(urlHash));+ assertTrue(Cache.hasContent(urlHash));++ /* delete entry in cache */+ Cache.delete(urlHash);+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));+ }++ @Test+ public void testClear() throws MalformedURLException, IOException {+ final ResponseHeader okResponse = new ResponseHeader(HttpStatus.SC_OK);+ final DigestURL url = new DigestURL("http://yacy.net");+ final byte[] urlHash = url.hash();+ byte[] fileContent = TEXT_CONTENT.getBytes(StandardCharsets.UTF_8);++ /* Store without committing */+ Cache.store(url, okResponse, fileContent);+ assertTrue(Cache.has(urlHash));+ assertTrue(Cache.hasContent(urlHash));++ /* Clear the cache */+ Cache.clear();+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));+ assertEquals(0, Cache.getActualCacheDocCount());+ assertEquals(0, Cache.getActualCacheSize());++ /* Clear the cache even if already empty */+ Cache.clear();+ assertEquals(0, Cache.getActualCacheDocCount());+ assertEquals(0, Cache.getActualCacheSize());++ /* Store and commit */+ Cache.store(url, okResponse, fileContent);+ Cache.commit();+ assertTrue(Cache.has(urlHash));+ assertTrue(Cache.hasContent(urlHash));++ /* Clear the cache */+ Cache.clear();+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));+ assertEquals(0, Cache.getActualCacheDocCount());+ assertEquals(0, Cache.getActualCacheSize());++ /*+ * Store an entry larger than backend buffer sizes, likely to be flushed+ * to the file system+ */+ fileContent = generateFlushableContent();+ Cache.store(url, okResponse, fileContent);+ Cache.commit();+ assertTrue(Cache.has(urlHash));+ assertTrue(Cache.hasContent(urlHash));+ assertNotEquals(0, Cache.getActualCacheDocCount());+ assertNotEquals(0, Cache.getActualCacheSize());++ /* Clear the cache */+ Cache.clear();+ assertFalse(Cache.has(urlHash));+ assertFalse(Cache.hasContent(urlHash));+ assertEquals(0, Cache.getActualCacheDocCount());+ assertEquals(0, Cache.getActualCacheSize());+ }++ /**+ * A test task performing some accesses to the cache. To be run+ * concurrently.+ *+ * @author luc+ *+ */+ private static class CacheAccessTask extends Thread {++ /** The test URLs for this task */+ private final List<DigestURL> urls;++ /** Number of steps to run */+ private final int maxSteps;++ /** Number of steps effectively run */+ private int steps;++ /** Test content size in bytes */+ private final int contentSize;++ /** Sleep time (in milliseconds) between each cache operations */+ private final long sleepTime;++ /** Number of Cache.getContent() successes (not null returned) */+ private int getContentSuccesses;++ /** Number of Cache.getContent() misses (null returned) */+ private int getContentMisses;++ /** Number of Cache.store() failures */+ private int storeFailures;++ /** Total time spent (in nanoseconds) on the Cache.store operation */+ private long storeTime;++ /** Maximum time spent (in nanoseconds)on the Cache.store operation */+ private long maxStoreTime;++ /**+ * Total time spent (in nanoseconds) on the Cache.getContent operation+ */+ private long getContentTime;++ /**+ * Maximum time spent (in nanoseconds) on the Cache.getContent operation+ */+ private long maxGetContentTime;++ /** Total time spent (in nanoseconds) on the Cache.store operation */+ private long deleteTime;++ /** Maximum time spent (in nanoseconds) on the Cache.store operation */+ private long maxDeleteTime;++ /**+ * @param urls+ * the test URLs+ * @param steps+ * number of loops+ * @param contentSize+ * size (in bytes) of the test content to generate and use+ * @param sleepTime+ * sleep time (in milliseconds) between each cache operations+ */+ public CacheAccessTask(final List<DigestURL> urls, final int steps, final int contentSize,+ final long sleepTime) {+ this.urls = urls;+ this.maxSteps = steps;+ this.contentSize = contentSize;+ this.sleepTime = sleepTime;+ }++ private void sleep() {+ if (this.sleepTime > 0) {+ try {+ Thread.sleep(this.sleepTime);+ } catch (InterruptedException ignored) {+ }+ }+ }++ @Override+ public void run() {+ try {+ final ResponseHeader okResponse = new ResponseHeader(HttpStatus.SC_OK);+ final byte[] fileContent = new byte[contentSize];+ new Random().nextBytes(fileContent);++ this.storeTime = 0;+ this.maxStoreTime = 0;+ this.getContentMisses = 0;+ this.getContentSuccesses = 0;+ this.storeFailures = 0;+ this.getContentTime = 0;+ this.maxGetContentTime = 0;+ this.maxDeleteTime = 0;+ this.deleteTime = 0;+ this.steps = 0;+ long time;+ while (this.steps < this.maxSteps) {+ int processedURLs = 0;+ /* Run the same steps for each test URL */+ for (DigestURL url : urls) {+ if (this.steps >= this.maxSteps) {+ break;+ }+ byte[] urlHash = url.hash();++ /* measure store */+ time = System.nanoTime();+ try {+ Cache.store(url, okResponse, fileContent);+ } catch (final IOException e) {+ this.storeFailures++;+ }+ time = (System.nanoTime() - time);+ this.storeTime += time;+ this.maxStoreTime = Math.max(time, this.maxStoreTime);++ sleep();++ /* Measure content retrieval */+ time = System.nanoTime();+ if (Cache.getContent(urlHash) == null) {+ this.getContentMisses++;+ } else {+ this.getContentSuccesses++;+ }+ time = (System.nanoTime() - time);+ this.getContentTime += time;+ this.maxGetContentTime = Math.max(time, this.maxGetContentTime);++ sleep();++ /*+ * Run some cache functions without measurement, to+ * produce some concurrent accesses+ */+ Cache.has(urlHash);++ sleep();++ Cache.hasContent(urlHash);++ sleep();++ Cache.getResponseHeader(urlHash);++ sleep();++ this.steps++;+ processedURLs++;+ }++ Cache.commit();++ /* Now delete each previously inserted URL */+ for (int i = 0; i < processedURLs; i++) {+ DigestURL url = urls.get(i);+ byte[] urlHash = url.hash();++ /* Measure delete operation */+ time = System.nanoTime();+ Cache.delete(urlHash);+ time = (System.nanoTime() - time);+ this.deleteTime += time;+ this.maxDeleteTime = Math.max(time, this.maxDeleteTime);++ sleep();+ }+ }+ } catch (MalformedURLException e) {+ e.printStackTrace();+ } catch (IOException e) {+ e.printStackTrace();+ }+ }++ public int getSteps() {+ return this.steps;+ }++ public long getStoreTime() {+ return this.storeTime;+ }++ public long getMaxStoreTime() {+ return this.maxStoreTime;+ }++ public long getGetContentTime() {+ return this.getContentTime;+ }++ public long getMaxGetContentTime() {+ return this.maxGetContentTime;+ }++ public long getDeleteTime() {+ return this.deleteTime;+ }++ public long getMaxDeleteTime() {+ return this.maxDeleteTime;+ }++ public int getGetContentMisses() {+ return this.getContentMisses;+ }++ public int getGetContentSuccesses() {+ return this.getContentSuccesses;+ }++ public int getStoreFailures() {+ return this.storeFailures;+ }++ }++ /**+ * Run a stress test on the Cache+ *+ * @param args+ * main arguments+ * @throws IOException+ * when a error occurred+ */+ public static void main(final String args[]) throws IOException {+ System.out.println("Stress test on Cache");++ /*+ * Set the root log level to WARNING to prevent filling the console with+ * too many information log messages+ */+ LogManager.getLogManager()+ .readConfiguration(new ByteArrayInputStream(".level=WARNING".getBytes(StandardCharsets.ISO_8859_1)));++ /* Main control parameters. Modify values for different scenarios. */++ /* Number of concurrent test tasks */+ final int threads = 50;+ /* Number of steps in each task */+ final int steps = 10;+ /* Number of test URLs in each task */+ final int urlsPerThread = 5;+ /* Size of the generated test content */+ final int contentSize = Math.max(Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE + 1,+ Cache.DEFAULT_BACKEND_BUFFER_SIZE + 1) / urlsPerThread;+ /* Cache maximum size */+ final long cacheMaxSize = Math.min(1024 * 1024 * 1024, ((long) contentSize) * 10 * urlsPerThread);+ /* Sleep time between each cache operation */+ final long sleepTime = 0;+ /* Maximum waiting time (in ms) for acquiring a synchronization lock */+ final long lockTimeout = 2000;++ Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "yacyTestCache"), "peerSalt",+ cacheMaxSize, lockTimeout);+ Cache.clear();+ System.out.println("Cache initialized with a maximum size of " + cacheMaxSize + " bytes.");++ try {+ System.out.println("Starting " + threads + " threads ...");+ long time = System.nanoTime();+ List<CacheAccessTask> tasks = new ArrayList<>();+ for (int count = 0; count < threads; count++) {+ List<DigestURL> urls = new ArrayList<>();+ for (int i = 0; i < urlsPerThread; i++) {+ urls.add(new DigestURL("http://yacy.net/" + i + "/" + count));+ }+ CacheAccessTask thread = new CacheAccessTask(urls, steps, contentSize, sleepTime);+ thread.start();+ tasks.add(thread);+ }+ /* Wait for tasks termination */+ for (CacheAccessTask task : tasks) {+ try {+ task.join();+ } catch (InterruptedException e) {+ e.printStackTrace();+ }+ }+ /*+ * Check consistency : cache should be empty when all tasks have+ * terminated without error+ */+ Cache.commit();+ long docCount = Cache.getActualCacheDocCount();+ if (docCount > 0) {+ System.out.println("Cache is not empty!!! Actual documents count : " + docCount);+ }++ System.out.println("All threads terminated in " + TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - time)+ + "s. Computing statistics...");+ long storeTime = 0;+ long maxStoreTime = 0;+ long getContentTime = 0;+ long maxGetContentTime = 0;+ int getContentMisses = 0;+ int getContentSuccesses = 0;+ int storeFailures = 0;+ long deleteTime = 0;+ long maxDeleteTime = 0;+ long totalSteps = 0;+ for (CacheAccessTask task : tasks) {+ storeTime += task.getStoreTime();+ maxStoreTime = Math.max(task.getMaxStoreTime(), maxStoreTime);+ getContentTime += task.getGetContentTime();+ maxGetContentTime = Math.max(task.getMaxGetContentTime(), maxGetContentTime);+ getContentMisses += task.getGetContentMisses();+ getContentSuccesses += task.getGetContentSuccesses();+ storeFailures += task.getStoreFailures();+ deleteTime += task.getDeleteTime();+ maxDeleteTime = Math.max(task.getMaxDeleteTime(), maxDeleteTime);+ totalSteps += task.getSteps();+ }+ System.out.println("Cache.store() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime));+ System.out.println("Cache.store() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxStoreTime));+ System.out+ .println("Cache.store() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime / totalSteps));+ System.out+ .println("Cache.store() failures : " + storeFailures);+ System.out.println("");+ System.out.println("Cache.getContent() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(getContentTime));+ System.out.println(+ "Cache.getContent() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxGetContentTime));+ System.out.println("Cache.getContent() mean time (ms) : "+ + TimeUnit.NANOSECONDS.toMillis(getContentTime / totalSteps));+ System.out.println("Cache.getContent() : misses " + getContentMisses + " successes : "+ + getContentSuccesses + " ( miss rate : "+ + ((getContentMisses / ((double) getContentSuccesses + (double) getContentMisses)) * 100) + "% )");+ System.out.println("");+ System.out.println("Cache.delete() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime));+ System.out.println("Cache.delete() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxDeleteTime));+ System.out.println(+ "Cache.delete() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime / totalSteps));+ } finally {+ try {+ Cache.close();+ } finally {+ /* Shutdown running threads */+ ArrayStack.shutdownDeleteService();+ try {+ Domains.close();+ } finally {+ ConcurrentLog.shutdown();+ }+ }+ }++ }++}