Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

cleaned, small change, Properties

borg-030000ab4d8723b8
diff --git a/source/de/anomic/plasma/plasmaCrawlLoader.java b/source/de/anomic/plasma/plasmaCrawlLoader.java
index fe112c527..201d8b78f 100644
--- a/source/de/anomic/plasma/plasmaCrawlLoader.java
+++ b/source/de/anomic/plasma/plasmaCrawlLoader.java
@@ -4,7 +4,10 @@
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
-// last major change: 25.02.2004
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
//
// 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
@@ -45,87 +48,85 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
-
import de.anomic.server.serverSemaphore;
import de.anomic.server.logging.serverLog;
-
import org.apache.commons.pool.impl.GenericObjectPool;
public final class plasmaCrawlLoader extends Thread {
static plasmaSwitchboard switchboard;
-
+
private final plasmaHTCache cacheManager;
private final serverLog log;
-
+
private final CrawlerMessageQueue theQueue;
private final CrawlerPool crawlwerPool;
private GenericObjectPool.Config cralwerPoolConfig = null;
private final ThreadGroup theThreadGroup = new ThreadGroup("CrawlerThreads");
private boolean stopped = false;
-
+
public plasmaCrawlLoader(
plasmaHTCache theCacheManager,
serverLog theLog) {
this.setName("plasmaCrawlLoader");
-
- this.cacheManager = theCacheManager;
- this.log = theLog;
-
+
+ this.cacheManager = theCacheManager;
+ this.log = theLog;
+
// configuring the crawler messagequeue
this.theQueue = new CrawlerMessageQueue();
-
+
// configuring the crawler thread pool
// implementation of session thread pool
this.cralwerPoolConfig = new GenericObjectPool.Config();
-
+
// The maximum number of active connections that can be allocated from pool at the same time,
// 0 for no limit
this.cralwerPoolConfig.maxActive = Integer.parseInt(switchboard.getConfig("crawler.MaxActiveThreads","10"));
-
+
// The maximum number of idle connections connections in the pool
// 0 = no limit.
this.cralwerPoolConfig.maxIdle = Integer.parseInt(switchboard.getConfig("crawler.MaxIdleThreads","7"));
this.cralwerPoolConfig.minIdle = Integer.parseInt(switchboard.getConfig("crawler.MinIdleThreads","5"));
-
+
// block undefinitely
this.cralwerPoolConfig.maxWait = -1;
-
+
// Action to take in case of an exhausted DBCP statement pool
// 0 = fail, 1 = block, 2= grow
this.cralwerPoolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
this.cralwerPoolConfig.minEvictableIdleTimeMillis = 30000;
// config.testOnReturn = true;
-
+
CrawlerFactory theFactory = new CrawlerFactory(
this.theThreadGroup,
switchboard,
cacheManager,
log);
-
+
this.crawlwerPool = new CrawlerPool(theFactory,this.cralwerPoolConfig,this.theThreadGroup);
// start the crawl loader
this.start();
}
-
+
public GenericObjectPool.Config getPoolConfig() {
return this.cralwerPoolConfig;
}
-
+
public void setPoolConfig(GenericObjectPool.Config newConfig) {
this.crawlwerPool.setConfig(newConfig);
}
-
+
public void close() {
try {
// setting the stop flag to true
this.stopped = true;
-
+
// interrupting the plasmaCrawlLoader
this.interrupt();
-
+
// waiting for the thread to finish ...
this.log.logInfo("Waiting for plasmaCrawlLoader shutdown ...");
this.join(5000);
@@ -139,16 +140,16 @@ public final class plasmaCrawlLoader extends Thread {
}
public void run() {
-
+
while (!this.stopped && !Thread.interrupted()) {
try {
// getting a new message from the crawler queue
plasmaCrawlLoaderMessage theMsg = this.theQueue.waitForMessage();
-
+
// getting a new crawler from the crawler pool
plasmaCrawlWorker theWorker = (plasmaCrawlWorker) this.crawlwerPool.borrowObject();
theWorker.execute(theMsg);
-
+
} catch (InterruptedException e) {
Thread.interrupted();
this.stopped = true;
@@ -157,10 +158,10 @@ public final class plasmaCrawlLoader extends Thread {
this.log.logSevere("plasmaCrawlLoader.run/loop", e);
}
}
-
+
// consuming the is interrupted flag
this.isInterrupted();
-
+
// closing the pool
try {
this.crawlwerPool.close();
@@ -171,7 +172,7 @@ public final class plasmaCrawlLoader extends Thread {
}
}
-
+
public void loadParallel(
URL url,
String name,
@@ -201,7 +202,6 @@ public final class plasmaCrawlLoader extends Thread {
}
}
-
class CrawlerMessageQueue {
private final serverSemaphore readSync;
private final serverSemaphore writeSync;
@@ -213,7 +213,7 @@ class CrawlerMessageQueue {
this.messageList = new ArrayList(10);
}
-
+
/**
*
* @param newMessage
@@ -224,14 +224,14 @@ class CrawlerMessageQueue {
throws InterruptedException, NullPointerException
{
if (newMessage == null) throw new NullPointerException();
-
+
this.writeSync.P();
-
+
boolean insertionDoneSuccessfully = false;
synchronized(this.messageList) {
insertionDoneSuccessfully = this.messageList.add(newMessage);
}
-
+
if (insertionDoneSuccessfully) {
this.sortMessages();
this.readSync.V();
@@ -239,11 +239,11 @@ class CrawlerMessageQueue {
this.writeSync.V();
}
-
+
public plasmaCrawlLoaderMessage waitForMessage() throws InterruptedException {
this.readSync.P();
this.writeSync.P();
-
+
plasmaCrawlLoaderMessage newMessage = null;
synchronized(this.messageList) {
newMessage = (plasmaCrawlLoaderMessage) this.messageList.remove(0);
@@ -252,7 +252,7 @@ class CrawlerMessageQueue {
this.writeSync.V();
return newMessage;
}
-
+
protected void sortMessages() {
Collections.sort(this.messageList, new Comparator() {
public int compare(Object o1, Object o2)
@@ -275,12 +275,10 @@ class CrawlerMessageQueue {
}
}
-
final class CrawlerPool extends GenericObjectPool {
private final ThreadGroup theThreadGroup;
public boolean isClosed = false;
-
-
+
public CrawlerPool(CrawlerFactory objFactory,
GenericObjectPool.Config config,
ThreadGroup threadGroup) {
@@ -303,21 +301,21 @@ final class CrawlerPool extends GenericObjectPool {
* shutdown all still running session threads ...
*/
this.isClosed = true;
-
+
/* waiting for all threads to finish */
int threadCount = this.theThreadGroup.activeCount();
Thread[] threadList = new Thread[threadCount];
threadCount = this.theThreadGroup.enumerate(threadList);
-
+
// signaling shutdown to all still running or pooled threads ...
serverLog.logInfo("CRAWLER","Signaling shutdown to " + threadCount + " remaining crawler threads ...");
for ( int currentThreadIdx = 0; currentThreadIdx < threadCount; currentThreadIdx++ ) {
((plasmaCrawlWorker)threadList[currentThreadIdx]).setStopped(true);
}
-
+
// giving the crawlers some time to finish shutdown
try { Thread.sleep(500); } catch(Exception e) {}
-
+
// sending interrupted signal to all remaining threads
serverLog.logInfo("CRAWLER","Sending interruption signal to " + this.theThreadGroup.activeCount() + " remaining crawler threads ...");
this.theThreadGroup.interrupt();
@@ -331,7 +329,7 @@ final class CrawlerPool extends GenericObjectPool {
((plasmaCrawlWorker)currentThread).close();
}
}
-
+
serverLog.logInfo("CRAWLER","Waiting for " + this.theThreadGroup.activeCount() + " remaining crawler threads to finish shutdown ...");
for ( int currentThreadIdx = 0; currentThreadIdx < threadCount; currentThreadIdx++ ) {
Thread currentThread = threadList[currentThreadIdx];
@@ -347,9 +345,9 @@ final class CrawlerPool extends GenericObjectPool {
}
super.close();
-
+
}
-
+
}
final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFactory {
@@ -359,28 +357,28 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFact
private final plasmaHTCache cacheManager;
private final serverLog theLog;
private final plasmaSwitchboard sb;
-
+
public CrawlerFactory(
ThreadGroup threadGroup,
plasmaSwitchboard theSb,
plasmaHTCache theCacheManager,
serverLog log) {
-
+
super();
-
+
if (threadGroup == null)
throw new IllegalArgumentException("The threadgroup object must not be null.");
-
+
this.theThreadGroup = threadGroup;
this.cacheManager = theCacheManager;
this.sb = theSb;
this.theLog = log;
}
-
+
public void setPool(CrawlerPool pool) {
this.thePool = pool;
}
-
+
/**
* @see org.apache.commons.pool.PoolableObjectFactory#makeObject()
*/
@@ -392,7 +390,7 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFact
this.cacheManager,
this.theLog);
}
-
+
/**
* @see org.apache.commons.pool.PoolableObjectFactory#destroyObject(java.lang.Object)
*/
@@ -402,7 +400,7 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFact
theWorker.setStopped(true);
}
}
-
+
/**
* @see org.apache.commons.pool.PoolableObjectFactory#validateObject(java.lang.Object)
*/
@@ -416,7 +414,7 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFact
}
return true;
}
-
+
/**
* @param obj
*
@@ -434,9 +432,6 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFact
if (obj instanceof plasmaCrawlWorker) {
plasmaCrawlWorker theWorker = (plasmaCrawlWorker) obj;
}
- }
-}
-
-
-
+ }
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaCrawlStacker.java b/source/de/anomic/plasma/plasmaCrawlStacker.java
index 67c761767..a7c23a857 100644
--- a/source/de/anomic/plasma/plasmaCrawlStacker.java
+++ b/source/de/anomic/plasma/plasmaCrawlStacker.java
@@ -7,9 +7,9 @@
//
// This file was contributed by Martin Thelian
//
-// $LastChangedDate: 2005-10-07 15:49:07 +0200 (Fri, 07 Oct 2005) $
-// $LastChangedRevision: 874 $
-// $LastChangedBy: allo $
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
//
// 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
@@ -175,6 +175,7 @@ public final class plasmaCrawlStacker {
public String stackCrawl(String nexturlString, String referrerString, String initiatorHash, String name, Date loadDate, int currentdepth, plasmaCrawlProfile.entry profile) {
// stacks a crawl item. The position can also be remote
// returns null if successful, a reason string if not successful
+ this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
long startTime = System.currentTimeMillis();
String reason = null; // failure reason
@@ -798,29 +799,29 @@ public final class plasmaCrawlStacker {
}
}
- private void execute() {
+ private void execute() {
try {
- String rejectReason = dequeue(this.theMsg);
-
+ String rejectReason = dequeue(this.theMsg);
+
if (rejectReason != null) {
plasmaCrawlStacker.this.sb.urlPool.errorURL.newEntry(
- new URL(this.theMsg.url()),
- this.theMsg.referrerHash(),
- this.theMsg.initiatorHash(),
+ new URL(this.theMsg.url()),
+ this.theMsg.referrerHash(),
+ this.theMsg.initiatorHash(),
yacyCore.seedDB.mySeed.hash,
- this.theMsg.name,
- rejectReason,
- new bitfield(plasmaURL.urlFlagLength),
+ this.theMsg.name,
+ rejectReason,
+ new bitfield(plasmaURL.urlFlagLength),
false
);
- }
+ }
} catch (Exception e) {
- e.printStackTrace();
+ e.printStackTrace();
} finally {
this.done = true;
}
-
- }
+
+ }
}
-}
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaCrawlWorker.java b/source/de/anomic/plasma/plasmaCrawlWorker.java
index fc128aa93..e5886574c 100644
--- a/source/de/anomic/plasma/plasmaCrawlWorker.java
+++ b/source/de/anomic/plasma/plasmaCrawlWorker.java
@@ -5,8 +5,9 @@
//first published on http://www.anomic.de
//Frankfurt, Germany, 2004
//
-//last major change: $LastChangedDate$ by $LastChangedBy$
-//Revision: $LastChangedRevision$
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
//
//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
@@ -52,7 +53,6 @@ import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Date;
-
import de.anomic.http.httpHeader;
import de.anomic.http.httpRemoteProxyConfig;
import de.anomic.http.httpc;
@@ -62,16 +62,16 @@ import de.anomic.tools.bitfield;
import de.anomic.yacy.yacyCore;
public final class plasmaCrawlWorker extends Thread {
-
+
private static final int DEFAULT_CRAWLING_RETRY_COUNT = 5;
private static final String threadBaseName = "CrawlerWorker";
-
+
private final CrawlerPool myPool;
private final plasmaSwitchboard sb;
private final plasmaHTCache cacheManager;
private final serverLog log;
private int socketTimeout;
-
+
public plasmaCrawlLoaderMessage theMsg;
private URL url;
private String name;
@@ -80,12 +80,12 @@ public final class plasmaCrawlWorker extends Thread {
private int depth;
private long startdate;
private plasmaCrawlProfile.entry profile;
- //private String error;
-
+// private String error;
+
private boolean running = false;
private boolean stopped = false;
private boolean done = false;
-
+
private static boolean doCrawlerLogging = false;
/**
* Do logging configuration for special proxy access log file
@@ -104,50 +104,49 @@ public final class plasmaCrawlWorker extends Thread {
// System.err.println("PROXY: Unable to configure proxy access logging.");
// }
// }
-
+
public plasmaCrawlWorker(
- ThreadGroup theTG,
+ ThreadGroup theTG,
CrawlerPool thePool,
plasmaSwitchboard theSb,
plasmaHTCache theCacheManager,
serverLog theLog) {
super(theTG,threadBaseName + "_inPool");
-
+
this.myPool = thePool;
this.sb = theSb;
this.cacheManager = theCacheManager;
this.log = theLog;
-
+
// setting the crawler timeout properly
this.socketTimeout = (int) this.sb.getConfigLong("crawler.clientTimeout", 10000);
}
-
+
public long getDuration() {
- long startDate = this.startdate;
+ final long startDate = this.startdate;
return (startDate != 0) ? System.currentTimeMillis() - startDate : 0;
}
public synchronized void execute(plasmaCrawlLoaderMessage theNewMsg) {
this.theMsg = theNewMsg;
-
+
this.url = theNewMsg.url;
this.name = theNewMsg.name;
this.referer = theNewMsg.referer;
this.initiator = theNewMsg.initiator;
this.depth = theNewMsg.depth;
this.profile = theNewMsg.profile;
-
- this.startdate = System.currentTimeMillis();
- //this.error = null;
-
-
- this.done = false;
- if (!this.running) {
- // this.setDaemon(true);
+
+ this.startdate = System.currentTimeMillis();
+// this.error = null;
+
+ this.done = false;
+ if (!this.running) {
+// this.setDaemon(true);
this.start();
- } else {
+ } else {
this.notifyAll();
- }
+ }
}
public void reset() {
@@ -158,37 +157,35 @@ public final class plasmaCrawlWorker extends Thread {
this.depth = 0;
this.startdate = 0;
this.profile = null;
- //this.error = null;
+// this.error = null;
}
-
- public void run() {
+
+ public void run() {
this.running = true;
-
+
// The thread keeps running.
- while (!this.stopped && !Thread.interrupted()) {
- if (this.done) {
+ while (!this.stopped && !Thread.interrupted()) {
+ if (this.done) {
// We are waiting for a task now.
- synchronized (this) {
- try {
- this.wait(); //Wait until we get a request to process.
- }
- catch (InterruptedException e) {
- this.stopped = true;
- // log.error("", e);
- }
+ synchronized (this) {
+ try {
+ this.wait(); //Wait until we get a request to process.
+ }
+ catch (InterruptedException e) {
+ this.stopped = true;
+ // log.error("", e);
+ }
}
- }
- else
- {
+ } else {
//There is a task....let us execute it.
- try {
- execute();
+ try {
+ execute();
} catch (Exception e) {
// log.error("", e);
- }
- finally {
+ }
+ finally {
reset();
-
+
if (!this.stopped && !this.isInterrupted()) {
try {
this.myPool.returnObject(this);
@@ -199,32 +196,31 @@ public final class plasmaCrawlWorker extends Thread {
}
}
}
- }
- }
+ }
+ }
}
-
+
public void execute() throws IOException {
try {
// setting threadname
this.setName(plasmaCrawlWorker.threadBaseName + "_" + this.url);
-
+
// refreshing timeout value
this.socketTimeout = (int) this.sb.getConfigLong("crawler.clientTimeout", 10000);
-
+
// loading resource
- load(
- this.url,
- this.name,
- this.referer,
- this.initiator,
- this.depth,
- this.profile,
- this.socketTimeout,
- this.sb.remoteProxyConfig,
- this.cacheManager,
- this.log
+ load(this.url,
+ this.name,
+ this.referer,
+ this.initiator,
+ this.depth,
+ this.profile,
+ this.socketTimeout,
+ this.sb.remoteProxyConfig,
+ this.cacheManager,
+ this.log
);
-
+
} catch (IOException e) {
//throw e;
}
@@ -232,7 +228,7 @@ public final class plasmaCrawlWorker extends Thread {
this.done = true;
}
}
-
+
public void setStopped(boolean isStopped) {
this.stopped = isStopped;
}
@@ -240,7 +236,7 @@ public final class plasmaCrawlWorker extends Thread {
public boolean isRunning() {
return this.running;
}
-
+
public void close() {
if (this.isAlive()) {
try {
@@ -250,15 +246,15 @@ public final class plasmaCrawlWorker extends Thread {
this.log.logInfo(closedSockets + " HTTP-client sockets of thread '" + this.getName() + "' closed.");
}
} catch (Exception e) {}
- }
- }
+ }
+ }
public static void load(
- URL url,
+ URL url,
String name,
- String referer,
- String initiator,
- int depth,
+ String referer,
+ String initiator,
+ int depth,
plasmaCrawlProfile.entry profile,
int socketTimeout,
httpRemoteProxyConfig theRemoteProxyConfig,
@@ -269,23 +265,23 @@ public final class plasmaCrawlWorker extends Thread {
name,
referer,
initiator,
- depth,
+ depth,
profile,
- socketTimeout,
+ socketTimeout,
theRemoteProxyConfig,
- cacheManager,
- log,
+ cacheManager,
+ log,
DEFAULT_CRAWLING_RETRY_COUNT,
true
);
}
-
+
private static void load(
URL url,
String name,
- String referer,
- String initiator,
- int depth,
+ String referer,
+ String initiator,
+ int depth,
plasmaCrawlProfile.entry profile,
int socketTimeout,
httpRemoteProxyConfig theRemoteProxyConfig,
@@ -295,44 +291,44 @@ public final class plasmaCrawlWorker extends Thread {
boolean useContentEncodingGzip
) throws IOException {
if (url == null) return;
-
+
// if the recrawling limit was exceeded we stop crawling now
if (crawlingRetryCount <= 0) return;
-
+
// getting a reference to the plasmaSwitchboard
- plasmaSwitchboard sb = plasmaCrawlLoader.switchboard;
-
+ plasmaSwitchboard sb = plasmaCrawlLoader.switchboard;
+
Date requestDate = new Date(); // remember the time...
String host = url.getHost();
String path = url.getPath();
int port = url.getPort();
boolean ssl = url.getProtocol().equals("https");
if (port < 0) port = (ssl) ? 443 : 80;
-
+
// check if url is in blacklist
String hostlow = host.toLowerCase();
if (plasmaSwitchboard.urlBlacklist.isListed(hostlow, path)) {
log.logInfo("CRAWLER Rejecting URL '" + url.toString() + "'. URL is in blacklist.");
sb.urlPool.errorURL.newEntry(
- url,
+ url,
referer,
- initiator,
+ initiator,
yacyCore.seedDB.mySeed.hash,
- name,
- "denied_(url_in_blacklist)",
- new bitfield(plasmaURL.urlFlagLength),
+ name,
+ "denied_(url_in_blacklist)",
+ new bitfield(plasmaURL.urlFlagLength),
true
);
return;
- }
-
+ }
+
// TODO: resolve yacy and yacyh domains
String yAddress = yacyCore.seedDB.resolveYacyAddress(host);
-
+
// set referrer; in some case advertise a little bit:
referer = (referer == null) ? "" : referer.trim();
if (referer.length() == 0) referer = "http://www.yacy.net/yacy/";
-
+
// take a file from the net
httpc remote = null;
try {
@@ -343,36 +339,36 @@ public final class plasmaCrawlWorker extends Thread {
requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5"));
requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"));
if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate");
-
- //System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG
-
+
+// System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG
+
// open the connection
- remote = ((theRemoteProxyConfig != null) && (theRemoteProxyConfig.useProxy()))
+ remote = ((theRemoteProxyConfig != null) && (theRemoteProxyConfig.useProxy()))
? httpc.getInstance(host, port, socketTimeout, ssl, theRemoteProxyConfig,"CRAWLER",null)
: httpc.getInstance(host, port, socketTimeout, ssl, "CRAWLER",null);
-
+
// specifying if content encoding is allowed
remote.setAllowContentEncoding(useContentEncodingGzip);
-
+
// send request
httpc.response res = remote.GET(path, requestHeader);
-
+
if (res.status.startsWith("200") || res.status.startsWith("203")) {
// the transfer is ok
-
+
// TODO: aborting download if content is to long ...
long contentLength = res.responseHeader.contentLength();
-
+
// reserve cache entry
plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile);
-
+
// request has been placed and result has been returned. work off response
File cacheFile = cacheManager.getCachePath(url);
try {
if (plasmaParser.supportedContent(url,res.responseHeader.mime())) {
if (cacheFile.isFile()) {
cacheManager.deleteFile(url);
- }
+ }
// we write the new cache entry to file system directly
cacheFile.getParentFile().mkdirs();
FileOutputStream fos = null;
@@ -388,7 +384,7 @@ public final class plasmaCrawlWorker extends Thread {
} else {
// if the response has not the right file type then reject file
remote.close();
- log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString());
+ log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString());
}
// enQueue new entry with response header
if (profile != null) {
@@ -404,49 +400,49 @@ public final class plasmaCrawlWorker extends Thread {
log.logSevere("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString());
}
} else if (res.status.startsWith("30")) {
- if (crawlingRetryCount > 0) {
+ if (crawlingRetryCount > 0) {
if (res.responseHeader.containsKey(httpHeader.LOCATION)) {
// getting redirection URL
String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);
redirectionUrlString = redirectionUrlString.trim();
-
+
// normalizing URL
redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString);
-
+
// generating the new URL object
URL redirectionUrl = new URL(url, redirectionUrlString);
-
+
// returning the used httpc
- httpc.returnInstance(remote);
+ httpc.returnInstance(remote);
remote = null;
-
+
// restart crawling with new url
log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString());
log.logInfo("CRAWLER ..Redirecting request to: " + redirectionUrl);
-
+
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
- }
-
- // generating url hash
+ }
+
+ // generating url hash
String urlhash = plasmaURL.urlHash(redirectionUrl);
// removing url from loader queue
- plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash);
-
+ plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash);
+
// retry crawling with new url
load(redirectionUrl,
name,
referer,
initiator,
- depth,
+ depth,
profile,
- socketTimeout,
+ socketTimeout,
theRemoteProxyConfig,
- cacheManager,
- log,
+ cacheManager,
+ log,
--crawlingRetryCount,
useContentEncodingGzip
);
@@ -463,39 +459,39 @@ public final class plasmaCrawlWorker extends Thread {
} catch (Exception e) {
boolean retryCrawling = false;
String errorMsg = e.getMessage();
-
+
if (e instanceof MalformedURLException) {
- log.logWarning("CRAWLER Malformed URL '" + url.toString() + "' detected. ");
+ log.logWarning("CRAWLER Malformed URL '" + url.toString() + "' detected. ");
} else if (e instanceof NoRouteToHostException) {
- log.logWarning("CRAWLER No route to host found while trying to crawl URL '" + url.toString() + "'.");
- } else if ((e instanceof UnknownHostException) ||
- ((errorMsg != null) && (errorMsg.indexOf("unknown host") >= 0))) {
+ log.logWarning("CRAWLER No route to host found while trying to crawl URL '" + url.toString() + "'.");
+ } else if ((e instanceof UnknownHostException) ||
+ ((errorMsg != null) && (errorMsg.indexOf("unknown host") >= 0))) {
log.logWarning("CRAWLER Unknown host in URL '" + url.toString() + "'. " +
"Referer URL: " + ((referer == null) ?"Unknown":referer));
} else if (e instanceof java.net.BindException) {
- log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() +
+ log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if ((errorMsg != null) && (errorMsg.indexOf("Corrupt GZIP trailer") >= 0)) {
- log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() +
+ log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() +
"'. Retrying request without using gzip content encoding.");
- retryCrawling = true;
+ retryCrawling = true;
} else if ((errorMsg != null) && (errorMsg.indexOf("Read timed out") >= 0)) {
- log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() +
+ log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if ((errorMsg != null) && (errorMsg.indexOf("connect timed out") >= 0)) {
- log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() +
- "'. Retrying request.");
- retryCrawling = true;
+ log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() +
+ "'. Retrying request.");
+ retryCrawling = true;
} else if ((errorMsg != null) && (errorMsg.indexOf("Connection timed out") >= 0)) {
- log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() +
- "'. Retrying request.");
- retryCrawling = true;
+ log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() +
+ "'. Retrying request.");
+ retryCrawling = true;
} else if ((errorMsg != null) && (errorMsg.indexOf("Connection refused") >= 0)) {
log.logWarning("CRAWLER Connection refused while trying to connect to '" + url.toString() + "'.");
} else if ((errorMsg != null) && (errorMsg.indexOf("There is not enough space on the disk") >= 0)) {
- log.logSevere("CRAWLER Not enough space on the disk detected while crawling '" + url.toString() + "'. " +
+ log.logSevere("CRAWLER Not enough space on the disk detected while crawling '" + url.toString() + "'. " +
"Pausing crawlers. ");
plasmaCrawlLoader.switchboard.pauseCrawling();
} else if ((errorMsg != null) && (errorMsg.indexOf("Network is unreachable") >=0)) {
@@ -505,40 +501,39 @@ public final class plasmaCrawlWorker extends Thread {
} else {
log.logSevere("CRAWLER Unexpected Error with URL '" + url.toString() + "': " + e.toString(),e);
}
-
-
- if (retryCrawling) {
+
+ if (retryCrawling) {
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
-
+
// returning the used httpc
httpc.returnInstance(remote);
- remote = null;
-
- // setting the retry counter to 1
+ remote = null;
+
+ // setting the retry counter to 1
if (crawlingRetryCount > 2) crawlingRetryCount = 2;
-
+
// retry crawling
load(url,
- name,
- referer,
- initiator,
- depth,
- profile,
- socketTimeout,
- theRemoteProxyConfig,
- cacheManager,
- log,
- --crawlingRetryCount,
- false
- );
+ name,
+ referer,
+ initiator,
+ depth,
+ profile,
+ socketTimeout,
+ theRemoteProxyConfig,
+ cacheManager,
+ log,
+ --crawlingRetryCount,
+ false
+ );
}
} finally {
if (remote != null) httpc.returnInstance(remote);
}
}
-
-}
+
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaSwitchboardQueue.java b/source/de/anomic/plasma/plasmaSwitchboardQueue.java
index 516eec959..d4cc48519 100644
--- a/source/de/anomic/plasma/plasmaSwitchboardQueue.java
+++ b/source/de/anomic/plasma/plasmaSwitchboardQueue.java
@@ -1,464 +1,471 @@
-// plasmaSwitchboardQueueEntry.java
-// --------------------------------
-// part of YaCy
-// (C) by Michael Peter Christen; [email protected]
-// first published on http://www.anomic.de
-// Frankfurt, Germany, 2005
-// last major change: 04.07.2005
-//
-// 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
-//
-// Using this software in any meaning (reading, learning, copying, compiling,
-// running) means that you agree that the Author(s) is (are) not responsible
-// for cost, loss of data or any harm that may be caused directly or indirectly
-// by usage of this softare or this documentation. The usage of this software
-// is on your own risk. The installation and usage (starting/running) of this
-// software may allow other people or application to access your computer and
-// any attached devices and is highly dependent on the configuration of the
-// software which must be done by the user of the software; the author(s) is
-// (are) also not responsible for proper configuration and usage of the
-// software, even if provoked by documentation provided together with
-// the software.
-//
-// Any changes to this file according to the GPL as documented in the file
-// gpl.txt aside this file in the shipment you received can be done to the
-// lines that follows this copyright notice here, but changes must not be
-// done inside the copyright notive above. A re-distribution must contain
-// the intact and unchanged copyright notice.
-// Contributions and changes to the program code must be marked as such.
-
-package de.anomic.plasma;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Date;
-
-import de.anomic.htmlFilter.htmlFilterContentScraper;
-import de.anomic.http.httpHeader;
-import de.anomic.kelondro.kelondroStack;
-import de.anomic.server.serverCodings;
-import de.anomic.server.serverDate;
-import de.anomic.server.logging.serverLog;
-import de.anomic.yacy.yacySeedDB;
-
-public class plasmaSwitchboardQueue {
-
- private kelondroStack sbQueueStack;
- private plasmaCrawlProfile profiles;
- private plasmaHTCache htCache;
- private plasmaCrawlLURL lurls;
-
- public plasmaSwitchboardQueue(plasmaHTCache htCache, plasmaCrawlLURL lurls, File sbQueueStackPath, int bufferkb, plasmaCrawlProfile profiles) throws IOException {
- this.profiles = profiles;
- this.htCache = htCache;
- this.lurls = lurls;
-
- if (sbQueueStackPath.exists())
- sbQueueStack = new kelondroStack(sbQueueStackPath, 0);
- else
- sbQueueStack = new kelondroStack(sbQueueStackPath, 0, new int[] {
- plasmaURL.urlStringLength,
- plasmaURL.urlHashLength,
- 11,
- 1,
- yacySeedDB.commonHashLength,
- plasmaURL.urlCrawlDepthLength,
- plasmaURL.urlCrawlProfileHandleLength,
- plasmaURL.urlDescrLength
- });
-
- }
-
- public int size() {
- return sbQueueStack.size();
- }
-
- public void push(Entry entry) throws IOException {
- sbQueueStack.push(new byte[][]{
- entry.url.toString().getBytes(),
- (entry.referrerHash == null) ? plasmaURL.dummyHash.getBytes() : entry.referrerHash.getBytes(),
- serverCodings.enhancedCoder.encodeBase64Long((entry.ifModifiedSince == null) ? 0 : entry.ifModifiedSince.getTime(), 11).getBytes(),
- new byte[entry.flags],
- (entry.initiator == null) ? plasmaURL.dummyHash.getBytes() : entry.initiator.getBytes(),
- serverCodings.enhancedCoder.encodeBase64Long((long) entry.depth, plasmaURL.urlCrawlDepthLength).getBytes(),
- (entry.profileHandle == null) ? plasmaURL.dummyHash.getBytes() : entry.profileHandle.getBytes(),
- (entry.anchorName == null) ? "-".getBytes() : entry.anchorName.getBytes()
- });
- }
-
- public Entry pop() throws IOException {
- if (sbQueueStack.size() == 0) return null;
- return new Entry(sbQueueStack.pot());
- }
-
- public Entry remove(int index) throws IOException {
- if (sbQueueStack.size() == 0) return null;
- return new Entry(sbQueueStack.pot(index));
- }
-
- public Entry get(int index) throws IOException {
- if ((index < 0) || (index >= sbQueueStack.size())) throw new ArrayIndexOutOfBoundsException();
- return new Entry(sbQueueStack.bot(index));
- }
-
- public ArrayList list() throws IOException {
- return list(0);
- }
-
- public ArrayList list(int index) throws IOException {
- if ((index==0) && (sbQueueStack.size()==0)) return new ArrayList(0);
- if ((index < 0) || (index >= sbQueueStack.size())) throw new ArrayIndexOutOfBoundsException();
- ArrayList list = sbQueueStack.botList(index);
- for (int i=0; i < list.size(); i++) {
- list.set(i,new Entry((byte[][])list.get(i)));
- }
- return list;
- }
-
- public void clear() throws IOException {
- sbQueueStack.clear();
- }
-
- public void close() {
- if (sbQueueStack != null) try {
- sbQueueStack.close();
- } catch (IOException e) {
-
- }
- sbQueueStack = null;
- }
-
- public void finalize() {
- close();
- }
-
- public Entry newEntry(URL url, String referrer, Date ifModifiedSince, boolean requestWithCookie,
- String initiator, int depth, String profilehandle, String anchorName) {
- return new Entry(url, referrer, ifModifiedSince, requestWithCookie, initiator, depth, profilehandle, anchorName);
- }
-
- public class Entry {
- private URL url; // plasmaURL.urlStringLength
- private String referrerHash; // plasmaURL.urlHashLength
- private Date ifModifiedSince; // 6
- private byte flags; // 1
- private String initiator; // yacySeedDB.commonHashLength
- private int depth; // plasmaURL.urlCrawlDepthLength
- private String profileHandle; // plasmaURL.urlCrawlProfileHandleLength
- private String anchorName; // plasmaURL.urlDescrLength
-
- // computed values
- private plasmaCrawlProfile.entry profileEntry;
- private httpHeader responseHeader;
- private URL referrerURL;
-
- public Entry(URL url, String referrer, Date ifModifiedSince, boolean requestWithCookie,
- String initiator, int depth, String profileHandle, String anchorName) {
- this.url = url;
- this.referrerHash = referrer;
- this.ifModifiedSince = ifModifiedSince;
- this.flags = (requestWithCookie) ? (byte) 1 : (byte) 0;
- this.initiator = initiator;
- this.depth = depth;
- this.profileHandle = profileHandle;
- this.anchorName = (anchorName==null)?"":anchorName.trim();
-
- this.profileEntry = null;
- this.responseHeader = null;
- this.referrerURL = null;
- }
-
- public Entry(byte[][] row) {
- long ims = (row[2] == null) ? 0 : serverCodings.enhancedCoder.decodeBase64Long(new String(row[2]));
- byte flags = (row[3] == null) ? 0 : row[3][0];
- try {
- this.url = new URL(new String(row[0]));
- } catch (MalformedURLException e) {
- this.url = null;
- }
- this.referrerHash = (row[1] == null) ? null : new String(row[1]);
- this.ifModifiedSince = (ims == 0) ? null : new Date(ims);
- this.flags = ((flags & 1) == 1) ? (byte) 1 : (byte) 0;
- this.initiator = (row[4] == null) ? null : new String(row[4]);
- this.depth = (int) serverCodings.enhancedCoder.decodeBase64Long(new String(row[5]));
- this.profileHandle = new String(row[6]);
- this.anchorName = (row[7] == null) ? null : (new String(row[7])).trim();
-
- this.profileEntry = null;
- this.responseHeader = null;
- this.referrerURL = null;
- }
-
- public String toString() {
- StringBuffer str = new StringBuffer();
- str.append("url: ") .append(this.url==null ? "null" : this.url.toString()).append(" | ")
- .append("referrer: ") .append(this.referrerHash==null?"null":this.referrerHash).append(" | ")
- .append("ifModifiedSince: ").append(this.ifModifiedSince==null?"null":this.ifModifiedSince.toString()).append(" | ")
- .append("flags: ") .append(Byte.toString(this.flags)).append(" | ")
- .append("initiator: ") .append(this.initiator==null ? "null" : this.initiator).append(" | ")
- .append("depth: ") .append(Integer.toString(this.depth)).append(" | ")
- .append("profile: ") .append(this.profileHandle==null?"null":this.profileHandle).append(" | ")
- .append("anchorName: ") .append(this.anchorName==null?"null":this.anchorName);
- return str.toString();
- }
-
- public URL url() {
- return url;
- }
-
- public String normalizedURLString() {
- return htmlFilterContentScraper.urlNormalform(url);
- }
-
- public String urlHash() {
- return plasmaURL.urlHash(url);
- }
-
- public boolean requestedWithCookie() {
- return (flags & 1) == 1;
- }
-
- public File cacheFile() {
- return htCache.getCachePath(url);
- }
-
- public boolean proxy() {
- return (initiator == null) || (initiator.equals(plasmaURL.dummyHash));
- }
-
- public String initiator() {
- return initiator;
- }
-
- public int depth() {
- return depth;
- }
-
- public long size() {
- if (cacheFile().exists()) return cacheFile().length(); else return 0;
- }
-
- public plasmaCrawlProfile.entry profile() {
- if (profileEntry == null) profileEntry = profiles.getEntry(profileHandle);
- return profileEntry;
- }
-
- public httpHeader responseHeader() {
- if (responseHeader == null) try {
- responseHeader = htCache.getCachedResponse(plasmaURL.urlHash(url));
- } catch (IOException e) {
- serverLog.logSevere("PLASMA", "responseHeader: failed to get header", e);
- return null;
- }
- return responseHeader;
- }
-
- public URL referrerURL() {
- if (referrerURL == null) {
- if ((referrerHash == null) || (referrerHash.equals(plasmaURL.dummyHash))) return null;
- referrerURL = lurls.getEntry(referrerHash).url();
- }
- return referrerURL;
- }
-
- public String anchorName() {
- return anchorName;
- }
-
- public String shallIndexCacheForProxy() {
- // decide upon header information if a specific file should be indexed
- // this method returns null if the answer is 'YES'!
- // if the answer is 'NO' (do not index), it returns a string with the reason
- // to reject the crawling demand in clear text
-
- // check profile
- if (!(profile().localIndexing())) return "Indexing_Not_Allowed";
-
- // -CGI access in request
- // CGI access makes the page very individual, and therefore not usable in caches
- if ((plasmaHTCache.isPOST(normalizedURLString())) && (!(profile().crawlingQ()))) return "Dynamic_(POST)";
- if ((plasmaHTCache.isCGI(normalizedURLString())) && (!(profile().crawlingQ()))) return "Dynamic_(CGI)";
-
- // -authorization cases in request
- // we checked that in shallStoreCache
-
- // -ranges in request
- // we checked that in shallStoreCache
-
- // a picture cannot be indexed
- if (plasmaHTCache.noIndexingURL(normalizedURLString())) return "Media_Content_(forbidden)";
-
- // -cookies in request
- // unfortunately, we cannot index pages which have been requested with a cookie
- // because the returned content may be special for the client
- if (requestedWithCookie()) {
- //System.out.println("***not indexed because cookie");
- return "Dynamic_(Requested_With_Cookie)";
- }
-
- // -set-cookie in response
- // the set-cookie from the server does not indicate that the content is special
- // thus we do not care about it here for indexing
-
- if (responseHeader() != null) {
-
- // a picture cannot be indexed
- if (plasmaHTCache.isPicture(responseHeader())) return "Media_Content_(Picture)";
- if (!(plasmaHTCache.isText(responseHeader()))) return "Media_Content_(not_text)";
-
- // -if-modified-since in request
- // if the page is fresh at the very moment we can index it
- if ((ifModifiedSince != null) && (responseHeader().containsKey(httpHeader.LAST_MODIFIED))) {
- // parse date
- Date d = responseHeader().lastModified();
- if (d == null) d = new Date(serverDate.correctedUTCTime());
- // finally, we shall treat the cache as stale if the modification time is after the if-.. time
- if (d.after(ifModifiedSince)) {
- //System.out.println("***not indexed because if-modified-since");
- return "Stale_(Last-Modified>Modified-Since)";
- }
- }
-
- // -pragma in cached response
- if ((responseHeader().containsKey(httpHeader.PRAGMA)) &&
- (((String) responseHeader().get(httpHeader.PRAGMA)).toUpperCase().equals("NO-CACHE"))) return "Denied_(pragma_no_cache)";
-
- // see for documentation also:
- // http://www.web-caching.com/cacheability.html
-
-
- // calculate often needed values for freshness attributes
- Date date = responseHeader().date();
- Date expires = responseHeader().expires();
- Date lastModified = responseHeader().lastModified();
- String cacheControl = (String) responseHeader.get(httpHeader.CACHE_CONTROL);
-
- // look for freshnes information
-
- // -expires in cached response
- // the expires value gives us a very easy hint when the cache is stale
- // sometimes, the expires date is set to the past to prevent that a page is cached
- // we use that information to see if we should index it
- if (expires != null) {
- if (expires.before(new Date(serverDate.correctedUTCTime()))) return "Stale_(Expired)";
- }
-
- // -lastModified in cached response
- // this information is too weak to use it to prevent indexing
- // even if we can apply a TTL heuristic for cache usage
-
- // -cache-control in cached response
- // the cache-control has many value options.
- if (cacheControl != null) {
- cacheControl = cacheControl.trim().toUpperCase();
- /* we have the following cases for cache-control:
- "public" -- can be indexed
- "private", "no-cache", "no-store" -- cannot be indexed
- "max-age=<delta-seconds>" -- stale/fresh dependent on date
- */
- if (cacheControl.startsWith("PUBLIC")) {
- // ok, do nothing
- } else if ((cacheControl.startsWith("PRIVATE")) ||
- (cacheControl.startsWith("NO-CACHE")) ||
- (cacheControl.startsWith("NO-STORE"))) {
- // easy case
- return "Stale_(denied_by_cache-control=" + cacheControl+ ")";
- } else if (cacheControl.startsWith("MAX-AGE=")) {
- // we need also the load date
- if (date == null) return "Stale_(no_date_given_in_response)";
- try {
- long ttl = 1000 * Long.parseLong(cacheControl.substring(8)); // milliseconds to live
- if (serverDate.correctedUTCTime() - date.getTime() > ttl) {
- //System.out.println("***not indexed because cache-control");
- return "Stale_(expired_by_cache-control)";
- }
- } catch (Exception e) {
- return "Error_(" + e.getMessage() + ")";
- }
- }
- }
- }
- return null;
- }
-
-
- public String shallIndexCacheForCrawler() {
- // decide upon header information if a specific file should be indexed
- // this method returns null if the answer is 'YES'!
- // if the answer is 'NO' (do not index), it returns a string with the reason
- // to reject the crawling demand in clear text
-
- // check profile
- if (!(profile().localIndexing())) return "Indexing_Not_Allowed";
-
- // -CGI access in request
- // CGI access makes the page very individual, and therefore not usable in caches
- if ((plasmaHTCache.isPOST(normalizedURLString())) && (!(profile().crawlingQ()))) return "Dynamic_(POST)";
- if ((plasmaHTCache.isCGI(normalizedURLString())) && (!(profile().crawlingQ()))) return "Dynamic_(CGI)";
-
- // -authorization cases in request
- // we checked that in shallStoreCache
-
- // -ranges in request
- // we checked that in shallStoreCache
-
- // a picture cannot be indexed
- if (responseHeader() != null) {
- if (plasmaHTCache.isPicture(responseHeader())) return "Media_Content_(Picture)";
- if (!(plasmaHTCache.isText(responseHeader()))) return "Media_Content_(not_text)";
- }
- if (plasmaHTCache.noIndexingURL(normalizedURLString())) return "Media_Content_(forbidden)";
-
- // -if-modified-since in request
- // if the page is fresh at the very moment we can index it
- // -> this does not apply for the crawler
-
- // -cookies in request
- // unfortunately, we cannot index pages which have been requested with a cookie
- // because the returned content may be special for the client
- // -> this does not apply for a crawler
-
- // -set-cookie in response
- // the set-cookie from the server does not indicate that the content is special
- // thus we do not care about it here for indexing
- // -> this does not apply for a crawler
-
- // -pragma in cached response
- // -> in the crawler we ignore this
-
- // look for freshnes information
-
- // -expires in cached response
- // the expires value gives us a very easy hint when the cache is stale
- // sometimes, the expires date is set to the past to prevent that a page is cached
- // we use that information to see if we should index it
- // -> this does not apply for a crawler
-
- // -lastModified in cached response
- // this information is too weak to use it to prevent indexing
- // even if we can apply a TTL heuristic for cache usage
-
- // -cache-control in cached response
- // the cache-control has many value options.
- // -> in the crawler we ignore this
-
- return null;
- }
-
- }
-}
+// plasmaSwitchboardQueueEntry.java
+// --------------------------------
+// part of YaCy
+// (C) by Michael Peter Christen; [email protected]
+// first published on http://www.anomic.de
+// Frankfurt, Germany, 2005
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
+//
+// 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
+//
+// Using this software in any meaning (reading, learning, copying, compiling,
+// running) means that you agree that the Author(s) is (are) not responsible
+// for cost, loss of data or any harm that may be caused directly or indirectly
+// by usage of this softare or this documentation. The usage of this software
+// is on your own risk. The installation and usage (starting/running) of this
+// software may allow other people or application to access your computer and
+// any attached devices and is highly dependent on the configuration of the
+// software which must be done by the user of the software; the author(s) is
+// (are) also not responsible for proper configuration and usage of the
+// software, even if provoked by documentation provided together with
+// the software.
+//
+// Any changes to this file according to the GPL as documented in the file
+// gpl.txt aside this file in the shipment you received can be done to the
+// lines that follows this copyright notice here, but changes must not be
+// done inside the copyright notive above. A re-distribution must contain
+// the intact and unchanged copyright notice.
+// Contributions and changes to the program code must be marked as such.
+
+package de.anomic.plasma;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import de.anomic.htmlFilter.htmlFilterContentScraper;
+import de.anomic.http.httpHeader;
+import de.anomic.kelondro.kelondroStack;
+import de.anomic.server.serverCodings;
+import de.anomic.server.serverDate;
+import de.anomic.server.logging.serverLog;
+import de.anomic.yacy.yacySeedDB;
+
+public class plasmaSwitchboardQueue {
+
+ private kelondroStack sbQueueStack;
+ private plasmaCrawlProfile profiles;
+ private plasmaHTCache htCache;
+ private plasmaCrawlLURL lurls;
+
+ public plasmaSwitchboardQueue(plasmaHTCache htCache, plasmaCrawlLURL lurls, File sbQueueStackPath, int bufferkb, plasmaCrawlProfile profiles) throws IOException {
+ this.profiles = profiles;
+ this.htCache = htCache;
+ this.lurls = lurls;
+
+ if (sbQueueStackPath.exists())
+ sbQueueStack = new kelondroStack(sbQueueStackPath, 0);
+ else
+ sbQueueStack = new kelondroStack(sbQueueStackPath, 0, new int[] {
+ plasmaURL.urlStringLength,
+ plasmaURL.urlHashLength,
+ 11,
+ 1,
+ yacySeedDB.commonHashLength,
+ plasmaURL.urlCrawlDepthLength,
+ plasmaURL.urlCrawlProfileHandleLength,
+ plasmaURL.urlDescrLength
+ });
+ }
+
+ public int size() {
+ return sbQueueStack.size();
+ }
+
+ public void push(Entry entry) throws IOException {
+ sbQueueStack.push(new byte[][]{
+ entry.url.toString().getBytes(),
+ (entry.referrerHash == null) ? plasmaURL.dummyHash.getBytes() : entry.referrerHash.getBytes(),
+ serverCodings.enhancedCoder.encodeBase64Long((entry.ifModifiedSince == null) ? 0 : entry.ifModifiedSince.getTime(), 11).getBytes(),
+ new byte[entry.flags],
+ (entry.initiator == null) ? plasmaURL.dummyHash.getBytes() : entry.initiator.getBytes(),
+ serverCodings.enhancedCoder.encodeBase64Long((long) entry.depth, plasmaURL.urlCrawlDepthLength).getBytes(),
+ (entry.profileHandle == null) ? plasmaURL.dummyHash.getBytes() : entry.profileHandle.getBytes(),
+ (entry.anchorName == null) ? "-".getBytes() : entry.anchorName.getBytes()
+ });
+ }
+
+ public Entry pop() throws IOException {
+ if (sbQueueStack.size() == 0) return null;
+ return new Entry(sbQueueStack.pot());
+ }
+
+ public Entry remove(int index) throws IOException {
+ if (sbQueueStack.size() == 0) return null;
+ return new Entry(sbQueueStack.pot(index));
+ }
+
+ public Entry get(int index) throws IOException {
+ if ((index < 0) || (index >= sbQueueStack.size())) throw new ArrayIndexOutOfBoundsException();
+ return new Entry(sbQueueStack.bot(index));
+ }
+
+ public ArrayList list() throws IOException {
+ return list(0);
+ }
+
+ public ArrayList list(int index) throws IOException {
+ if ((index==0) && (sbQueueStack.size()==0)) return new ArrayList(0);
+ if ((index < 0) || (index >= sbQueueStack.size())) throw new ArrayIndexOutOfBoundsException();
+ ArrayList list = sbQueueStack.botList(index);
+ for (int i=0; i < list.size(); i++) {
+ list.set(i,new Entry((byte[][])list.get(i)));
+ }
+ return list;
+ }
+
+ public void clear() throws IOException {
+ sbQueueStack.clear();
+ }
+
+ public void close() {
+ if (sbQueueStack != null) try {
+ sbQueueStack.close();
+ } catch (IOException e) {
+ }
+ sbQueueStack = null;
+ }
+
+ protected void finalize() throws Throwable {
+ try {
+ close();
+ } catch (Exception e) {
+ throw new IOException("plasmaSwitchboardQueue.finalize()" + e.getMessage());
+ }
+ super.finalize();
+ }
+
+ public Entry newEntry(URL url, String referrer, Date ifModifiedSince, boolean requestWithCookie,
+ String initiator, int depth, String profilehandle, String anchorName) {
+ return new Entry(url, referrer, ifModifiedSince, requestWithCookie, initiator, depth, profilehandle, anchorName);
+ }
+
+ public class Entry {
+ private URL url; // plasmaURL.urlStringLength
+ private String referrerHash; // plasmaURL.urlHashLength
+ private Date ifModifiedSince; // 6
+ private byte flags; // 1
+ private String initiator; // yacySeedDB.commonHashLength
+ private int depth; // plasmaURL.urlCrawlDepthLength
+ private String profileHandle; // plasmaURL.urlCrawlProfileHandleLength
+ private String anchorName; // plasmaURL.urlDescrLength
+
+ // computed values
+ private plasmaCrawlProfile.entry profileEntry;
+ private httpHeader responseHeader;
+ private URL referrerURL;
+
+ public Entry(URL url, String referrer, Date ifModifiedSince, boolean requestWithCookie,
+ String initiator, int depth, String profileHandle, String anchorName) {
+ this.url = url;
+ this.referrerHash = referrer;
+ this.ifModifiedSince = ifModifiedSince;
+ this.flags = (requestWithCookie) ? (byte) 1 : (byte) 0;
+ this.initiator = initiator;
+ this.depth = depth;
+ this.profileHandle = profileHandle;
+ this.anchorName = (anchorName==null)?"":anchorName.trim();
+
+ this.profileEntry = null;
+ this.responseHeader = null;
+ this.referrerURL = null;
+ }
+
+ public Entry(byte[][] row) {
+ long ims = (row[2] == null) ? 0 : serverCodings.enhancedCoder.decodeBase64Long(new String(row[2]));
+ byte flags = (row[3] == null) ? 0 : row[3][0];
+ try {
+ this.url = new URL(new String(row[0]));
+ } catch (MalformedURLException e) {
+ this.url = null;
+ }
+ this.referrerHash = (row[1] == null) ? null : new String(row[1]);
+ this.ifModifiedSince = (ims == 0) ? null : new Date(ims);
+ this.flags = ((flags & 1) == 1) ? (byte) 1 : (byte) 0;
+ this.initiator = (row[4] == null) ? null : new String(row[4]);
+ this.depth = (int) serverCodings.enhancedCoder.decodeBase64Long(new String(row[5]));
+ this.profileHandle = new String(row[6]);
+ this.anchorName = (row[7] == null) ? null : (new String(row[7])).trim();
+
+ this.profileEntry = null;
+ this.responseHeader = null;
+ this.referrerURL = null;
+ }
+
+ public String toString() {
+ StringBuffer str = new StringBuffer();
+ str.append("url: ") .append(this.url==null ? "null" : this.url.toString()).append(" | ")
+ .append("referrer: ") .append(this.referrerHash==null?"null":this.referrerHash).append(" | ")
+ .append("ifModifiedSince: ").append(this.ifModifiedSince==null?"null":this.ifModifiedSince.toString()).append(" | ")
+ .append("flags: ") .append(Byte.toString(this.flags)).append(" | ")
+ .append("initiator: ") .append(this.initiator==null ? "null" : this.initiator).append(" | ")
+ .append("depth: ") .append(Integer.toString(this.depth)).append(" | ")
+ .append("profile: ") .append(this.profileHandle==null?"null":this.profileHandle).append(" | ")
+ .append("anchorName: ") .append(this.anchorName==null?"null":this.anchorName);
+ return str.toString();
+ }
+
+ public URL url() {
+ return url;
+ }
+
+ public String normalizedURLString() {
+ return htmlFilterContentScraper.urlNormalform(url);
+ }
+
+ public String urlHash() {
+ return plasmaURL.urlHash(url);
+ }
+
+ public boolean requestedWithCookie() {
+ return (flags & 1) == 1;
+ }
+
+ public File cacheFile() {
+ return htCache.getCachePath(url);
+ }
+
+ public boolean proxy() {
+ return (initiator == null) || (initiator.equals(plasmaURL.dummyHash));
+ }
+
+ public String initiator() {
+ return initiator;
+ }
+
+ public int depth() {
+ return depth;
+ }
+
+ public long size() {
+ if (cacheFile().exists()) return cacheFile().length(); else return 0;
+ }
+
+ public plasmaCrawlProfile.entry profile() {
+ if (profileEntry == null) profileEntry = profiles.getEntry(profileHandle);
+ return profileEntry;
+ }
+
+ public httpHeader responseHeader() {
+ if (responseHeader == null) try {
+ responseHeader = htCache.getCachedResponse(plasmaURL.urlHash(url));
+ } catch (IOException e) {
+ serverLog.logSevere("PLASMA", "responseHeader: failed to get header", e);
+ return null;
+ }
+ return responseHeader;
+ }
+
+ public URL referrerURL() {
+ if (referrerURL == null) {
+ if ((referrerHash == null) || (referrerHash.equals(plasmaURL.dummyHash))) return null;
+ referrerURL = lurls.getEntry(referrerHash).url();
+ }
+ return referrerURL;
+ }
+
+ public String anchorName() {
+ return anchorName;
+ }
+
+ /**
+ * decide upon header information if a specific file should be indexed
+ * this method returns null if the answer is 'YES'!
+ * if the answer is 'NO' (do not index), it returns a string with the reason
+ * to reject the crawling demand in clear text
+ */
+ public String shallIndexCacheForProxy() {
+ // check profile
+ if (!profile().localIndexing()) { return "Indexing_Not_Allowed"; }
+
+ String nURL = normalizedURLString();
+ // -CGI access in request
+ // CGI access makes the page very individual, and therefore not usable in caches
+ if (!profile().crawlingQ()) {
+ if (plasmaHTCache.isPOST(nURL)) { return "Dynamic_(POST)"; }
+ if (plasmaHTCache.isCGI(nURL)) { return "Dynamic_(CGI)"; }
+ }
+
+ // -authorization cases in request
+ // we checked that in shallStoreCache
+
+ // -ranges in request
+ // we checked that in shallStoreCache
+
+ // a picture cannot be indexed
+ if (plasmaHTCache.noIndexingURL(nURL)) { return "Media_Content_(forbidden)"; }
+
+ // -cookies in request
+ // unfortunately, we cannot index pages which have been requested with a cookie
+ // because the returned content may be special for the client
+ if (requestedWithCookie()) {
+// System.out.println("***not indexed because cookie");
+ return "Dynamic_(Requested_With_Cookie)";
+ }
+
+ // -set-cookie in response
+ // the set-cookie from the server does not indicate that the content is special
+ // thus we do not care about it here for indexing
+ if (responseHeader() != null) {
+ // a picture cannot be indexed
+ if (plasmaHTCache.isPicture(responseHeader())) return "Media_Content_(Picture)";
+ if (!plasmaHTCache.isText(responseHeader())) return "Media_Content_(not_text)";
+
+ // -if-modified-since in request
+ // if the page is fresh at the very moment we can index it
+ if ((ifModifiedSince != null) && (responseHeader().containsKey(httpHeader.LAST_MODIFIED))) {
+ // parse date
+ Date d = responseHeader().lastModified();
+ if (d == null) d = new Date(serverDate.correctedUTCTime());
+ // finally, we shall treat the cache as stale if the modification time is after the if-.. time
+ if (d.after(ifModifiedSince)) {
+ //System.out.println("***not indexed because if-modified-since");
+ return "Stale_(Last-Modified>Modified-Since)";
+ }
+ }
+
+ // -pragma in cached response
+ if (responseHeader().containsKey(httpHeader.PRAGMA) &&
+ ((String) responseHeader().get(httpHeader.PRAGMA)).toUpperCase().equals("NO-CACHE")) {
+ return "Denied_(pragma_no_cache)";
+ }
+
+ // see for documentation also:
+ // http://www.web-caching.com/cacheability.html
+
+ // look for freshnes information
+
+ // -expires in cached response
+ // the expires value gives us a very easy hint when the cache is stale
+ // sometimes, the expires date is set to the past to prevent that a page is cached
+ // we use that information to see if we should index it
+ Date expires = responseHeader().expires();
+ if (expires != null) {
+ if (expires.before(new Date(serverDate.correctedUTCTime()))) return "Stale_(Expired)";
+ }
+
+ // -lastModified in cached response
+ // this information is too weak to use it to prevent indexing
+ // even if we can apply a TTL heuristic for cache usage
+
+ // -cache-control in cached response
+ // the cache-control has many value options.
+ String cacheControl = (String) responseHeader.get(httpHeader.CACHE_CONTROL);
+ if (cacheControl != null) {
+ cacheControl = cacheControl.trim().toUpperCase();
+ /* we have the following cases for cache-control:
+ "public" -- can be indexed
+ "private", "no-cache", "no-store" -- cannot be indexed
+ "max-age=<delta-seconds>" -- stale/fresh dependent on date
+ */
+ if (cacheControl.startsWith("PRIVATE") ||
+ cacheControl.startsWith("NO-CACHE") ||
+ cacheControl.startsWith("NO-STORE")) {
+ // easy case
+ return "Stale_(denied_by_cache-control=" + cacheControl+ ")";
+// } else if (cacheControl.startsWith("PUBLIC")) {
+// // ok, do nothing
+ } else if (cacheControl.startsWith("MAX-AGE=")) {
+ // we need also the load date
+ Date date = responseHeader().date();
+ if (date == null) return "Stale_(no_date_given_in_response)";
+ try {
+ long ttl = 1000 * Long.parseLong(cacheControl.substring(8)); // milliseconds to live
+ if (serverDate.correctedUTCTime() - date.getTime() > ttl) {
+ //System.out.println("***not indexed because cache-control");
+ return "Stale_(expired_by_cache-control)";
+ }
+ } catch (Exception e) {
+ return "Error_(" + e.getMessage() + ")";
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * decide upon header information if a specific file should be indexed
+ * this method returns null if the answer is 'YES'!
+ * if the answer is 'NO' (do not index), it returns a string with the reason
+ * to reject the crawling demand in clear text
+ */
+ public String shallIndexCacheForCrawler() {
+ // check profile
+ if (!profile().localIndexing()) { return "Indexing_Not_Allowed"; }
+
+ String nURL = normalizedURLString();
+ // -CGI access in request
+ // CGI access makes the page very individual, and therefore not usable in caches
+ if (!profile().crawlingQ()) {
+ if (plasmaHTCache.isPOST(nURL)) { return "Dynamic_(POST)"; }
+ if (plasmaHTCache.isCGI(nURL)) { return "Dynamic_(CGI)"; }
+ }
+
+ // -authorization cases in request
+ // we checked that in shallStoreCache
+
+ // -ranges in request
+ // we checked that in shallStoreCache
+
+ // a picture cannot be indexed
+ if (responseHeader() != null) {
+ if (plasmaHTCache.isPicture(responseHeader())) { return "Media_Content_(Picture)"; }
+ if (!plasmaHTCache.isText(responseHeader())) { return "Media_Content_(not_text)"; }
+ }
+ if (plasmaHTCache.noIndexingURL(nURL)) { return "Media_Content_(forbidden)"; }
+
+ // -if-modified-since in request
+ // if the page is fresh at the very moment we can index it
+ // -> this does not apply for the crawler
+
+ // -cookies in request
+ // unfortunately, we cannot index pages which have been requested with a cookie
+ // because the returned content may be special for the client
+ // -> this does not apply for a crawler
+
+ // -set-cookie in response
+ // the set-cookie from the server does not indicate that the content is special
+ // thus we do not care about it here for indexing
+ // -> this does not apply for a crawler
+
+ // -pragma in cached response
+ // -> in the crawler we ignore this
+
+ // look for freshnes information
+
+ // -expires in cached response
+ // the expires value gives us a very easy hint when the cache is stale
+ // sometimes, the expires date is set to the past to prevent that a page is cached
+ // we use that information to see if we should index it
+ // -> this does not apply for a crawler
+
+ // -lastModified in cached response
+ // this information is too weak to use it to prevent indexing
+ // even if we can apply a TTL heuristic for cache usage
+
+ // -cache-control in cached response
+ // the cache-control has many value options.
+ // -> in the crawler we ignore this
+
+ return null;
+ }
+ } // class Entry
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaWordIndexCache.java b/source/de/anomic/plasma/plasmaWordIndexCache.java
index 16e210d98..8da039703 100644
--- a/source/de/anomic/plasma/plasmaWordIndexCache.java
+++ b/source/de/anomic/plasma/plasmaWordIndexCache.java
@@ -4,7 +4,10 @@
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
-// last major change: 6.5.2005
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
//
// 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
@@ -39,7 +42,6 @@
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
-
package de.anomic.plasma;
import java.io.File;
@@ -47,7 +49,6 @@ import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
-
import de.anomic.kelondro.kelondroArray;
import de.anomic.kelondro.kelondroException;
import de.anomic.kelondro.kelondroMScoreCluster;
@@ -57,7 +58,7 @@ import de.anomic.server.logging.serverLog;
import de.anomic.yacy.yacySeedDB;
public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
-
+
// environment constants
private static final String indexArrayFileName = "indexDump1.array";
private static final String oldSingletonFileName = "indexSingletons0.db";
@@ -65,8 +66,7 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
private static final String indexAssortmentClusterPath = "ACLUSTER";
private static final int assortmentCount = 64;
private static final int ramCacheLimit = 200;
-
-
+
// class variables
private final File databaseRoot;
private final plasmaWordIndexInterface backend;
@@ -83,10 +83,10 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
// calculated constants
private static String minKey, maxKey;
static {
- maxKey = "";
- for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += 'z';
- minKey = "";
- for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += '-';
+ maxKey = "";
+ for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += 'z';
+ minKey = "";
+ for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += '-';
}
public plasmaWordIndexCache(File databaseRoot, plasmaWordIndexInterface backend, int assortmentbufferkb, serverLog log) {
@@ -94,31 +94,31 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
File oldSingletonFile = new File(databaseRoot, oldSingletonFileName);
File newSingletonFile = new File(databaseRoot, newSingletonFileName);
if ((oldSingletonFile.exists()) && (!(newSingletonFile.exists()))) oldSingletonFile.renameTo(newSingletonFile);
-
+
// create new assortment cluster path
File assortmentClusterPath = new File(databaseRoot, indexAssortmentClusterPath);
if (!(assortmentClusterPath.exists())) assortmentClusterPath.mkdirs();
-
+
// migrate#2
File acSingletonFile = new File(assortmentClusterPath, newSingletonFileName);
if ((newSingletonFile.exists()) && (!(acSingletonFile.exists()))) newSingletonFile.renameTo(acSingletonFile);
-
+
// create flushing thread
flushThread = new flush();
-
+
// creates a new index cache
// the cache has a back-end where indexes that do not fit in the cache are flushed
this.databaseRoot = databaseRoot;
this.assortmentBufferSize = assortmentbufferkb;
this.cache = new TreeMap();
- this.hashScore = new kelondroMScoreCluster();
+ this.hashScore = new kelondroMScoreCluster();
this.hashDate = new kelondroMScoreCluster();
this.startTime = System.currentTimeMillis();
- this.maxWordsLow = 8000;
+ this.maxWordsLow = 8000;
this.maxWordsHigh = 10000;
this.backend = backend;
this.log = log;
- this.assortmentCluster = new plasmaWordIndexAssortmentCluster(assortmentClusterPath, assortmentCount, assortmentBufferSize, log);
+ this.assortmentCluster = new plasmaWordIndexAssortmentCluster(assortmentClusterPath, assortmentCount, assortmentBufferSize, log);
// read in dump of last session
try {
@@ -126,70 +126,69 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
} catch (IOException e){
log.logSevere("unable to restore cache dump: " + e.getMessage(), e);
}
-
+
// start permanent flushing
flushThread.start();
}
-
private void dump(int waitingSeconds) throws IOException {
log.logConfig("creating dump for index cache, " + cache.size() + " words (and much more urls)");
File indexDumpFile = new File(databaseRoot, indexArrayFileName);
if (indexDumpFile.exists()) indexDumpFile.delete();
kelondroArray dumpArray = null;
try {
- dumpArray = new kelondroArray(indexDumpFile, plasmaWordIndexAssortment.bufferStructureBasis, 0);
- long startTime = System.currentTimeMillis();
- long messageTime = System.currentTimeMillis() + 5000;
- long wordsPerSecond = 0, wordcount = 0, urlcount = 0;
- synchronized (cache) {
- Iterator i = cache.entrySet().iterator();
- Map.Entry entry;
- String wordHash;
- plasmaWordIndexEntryContainer container;
- long updateTime;
- plasmaWordIndexEntry wordEntry;
- byte[][] row = new byte[5][];
- while (i.hasNext()) {
- // get entries
- entry = (Map.Entry) i.next();
- wordHash = (String) entry.getKey();
- updateTime = getUpdateTime(wordHash);
- container = (plasmaWordIndexEntryContainer) entry.getValue();
-
- // put entries on stack
- if (container != null) {
- Iterator ci = container.entries();
- while (ci.hasNext()) {
- wordEntry = (plasmaWordIndexEntry) ci.next();
- row[0] = wordHash.getBytes();
- row[1] = kelondroRecords.long2bytes(container.size(), 4);
- row[2] = kelondroRecords.long2bytes(updateTime, 8);
- row[3] = wordEntry.getUrlHash().getBytes();
- row[4] = wordEntry.toEncodedForm(true).getBytes();
- dumpArray.set((int) urlcount++, row);
+ dumpArray = new kelondroArray(indexDumpFile, plasmaWordIndexAssortment.bufferStructureBasis, 0);
+ long startTime = System.currentTimeMillis();
+ long messageTime = System.currentTimeMillis() + 5000;
+ long wordsPerSecond = 0, wordcount = 0, urlcount = 0;
+ synchronized (cache) {
+ Iterator i = cache.entrySet().iterator();
+ Map.Entry entry;
+ String wordHash;
+ plasmaWordIndexEntryContainer container;
+ long updateTime;
+ plasmaWordIndexEntry wordEntry;
+ byte[][] row = new byte[5][];
+ while (i.hasNext()) {
+ // get entries
+ entry = (Map.Entry) i.next();
+ wordHash = (String) entry.getKey();
+ updateTime = getUpdateTime(wordHash);
+ container = (plasmaWordIndexEntryContainer) entry.getValue();
+
+ // put entries on stack
+ if (container != null) {
+ Iterator ci = container.entries();
+ while (ci.hasNext()) {
+ wordEntry = (plasmaWordIndexEntry) ci.next();
+ row[0] = wordHash.getBytes();
+ row[1] = kelondroRecords.long2bytes(container.size(), 4);
+ row[2] = kelondroRecords.long2bytes(updateTime, 8);
+ row[3] = wordEntry.getUrlHash().getBytes();
+ row[4] = wordEntry.toEncodedForm(true).getBytes();
+ dumpArray.set((int) urlcount++, row);
+ }
+ }
+ wordcount++;
+ i.remove(); // free some mem
+
+ // write a log
+ if (System.currentTimeMillis() > messageTime) {
+ // System.gc(); // for better statistic
+ wordsPerSecond = wordcount * 1000 / (1 + System.currentTimeMillis() - startTime);
+ log.logInfo("dumping status: " + wordcount + " words done, " + (cache.size() / (wordsPerSecond + 1)) + " seconds remaining, free mem = " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + "MB");
+ messageTime = System.currentTimeMillis() + 5000;
}
- }
- wordcount++;
- i.remove(); // free some mem
-
- // write a log
- if (System.currentTimeMillis() > messageTime) {
- System.gc(); // for better statistic
- wordsPerSecond = wordcount * 1000 / (1 + System.currentTimeMillis() - startTime);
- log.logInfo("dumping status: " + wordcount + " words done, " + (cache.size() / (wordsPerSecond + 1)) + " seconds remaining, free mem = " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + "MB");
- messageTime = System.currentTimeMillis() + 5000;
}
}
- }
- dumpArray.close();
- dumpArray = null;
- log.logConfig("dumped " + urlcount + " word/URL relations in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");
+ dumpArray.close();
+ dumpArray = null;
+ log.logConfig("dumped " + urlcount + " word/URL relations in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");
} finally {
if (dumpArray != null) try {dumpArray.close();}catch(Exception e){}
}
}
-
+
private long restore() throws IOException {
File indexDumpFile = new File(databaseRoot, indexArrayFileName);
if (!(indexDumpFile.exists())) return 0;
@@ -228,7 +227,7 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
}
}
}
-
+
dumpArray.close();
log.logConfig("restored " + cache.size() + " words in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");
} catch (kelondroException e) {
@@ -239,13 +238,13 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
}
return urlCount;
}
-
+
public void intermission(long pause) {
- flushThread.intermission(pause);
+ flushThread.intermission(pause);
}
// cache settings
-
+
public int maxURLinWordCache() {
return hashScore.getScore(hashScore.getMaxObject());
}
@@ -253,28 +252,28 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
public int wordCacheRAMSize() {
return cache.size();
}
-
+
public void setMaxWords(int maxWordsLow, int maxWordsHigh) {
this.maxWordsLow = maxWordsLow;
this.maxWordsHigh = maxWordsHigh;
}
-
+
public int[] assortmentsSizes() {
return assortmentCluster.sizes();
}
-
+
public int[] assortmentsCacheChunkSizeAvg() {
return assortmentCluster.cacheChunkSizeAvg();
}
-
+
public int[] assortmentsCacheFillStatusCml() {
return assortmentCluster.cacheFillStatusCml();
}
-
+
public int size() {
return java.lang.Math.max(assortmentCluster.sizeTotal(), java.lang.Math.max(backend.size(), cache.size()));
}
-
+
public Iterator wordHashes(String startWordHash, boolean up) {
// here we merge 3 databases into one view:
// - the RAM Cache
@@ -289,32 +288,32 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
backend.wordHashes(startWordHash, true),
true);
}
-
+
private final class flush extends Thread {
boolean terminate, pause;
- long intermission;
-
+ long intermission;
+
public flush() {
terminate = false;
intermission = 0;
this.setName(this.getClass().getName());
}
- public void intermission(long pause) {
- this.intermission = System.currentTimeMillis() + pause;
- }
+ public void intermission(long pause) {
+ this.intermission = System.currentTimeMillis() + pause;
+ }
public void run() {
String nextHash;
Runtime rt = Runtime.getRuntime();
long pausetime;
while (!terminate) {
- if (intermission > 0) {
- if (this.intermission > System.currentTimeMillis()) {
- try {this.sleep(this.intermission - System.currentTimeMillis());} catch (InterruptedException e) {}
- }
- this.intermission = 0;
- }
+ if (intermission > 0) {
+ if (this.intermission > System.currentTimeMillis()) {
+ try {this.sleep(this.intermission - System.currentTimeMillis());} catch (InterruptedException e) {}
+ }
+ this.intermission = 0;
+ }
if (pause) {
try {this.sleep(300);} catch (InterruptedException e) {}
} else {
@@ -327,20 +326,20 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
}
}
}
-
+
public void pause() {
pause = true;
}
-
+
public void proceed() {
pause = false;
}
-
+
public void terminate() {
terminate = true;
}
}
-
+
private void flushFromMem() {
// select appropriate hash
// we have 2 different methods to find a good hash:
@@ -370,13 +369,12 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
}
flushThread.proceed();
}
-
+
private int flushFromMem(String key) {
// this method flushes indexes out from the ram to the disc.
-
plasmaWordIndexEntryContainer container = null;
long time;
- synchronized (cache) {
+ synchronized (cache) {
// get the container
container = (plasmaWordIndexEntryContainer) cache.get(key);
if (container == null) return 0; // flushing of nonexisting key
@@ -384,9 +382,9 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
// remove it from the cache
cache.remove(key);
- hashScore.deleteScore(key);
+ hashScore.deleteScore(key);
hashDate.deleteScore(key);
- }
+ }
// now decide where to flush that container
//if (container.size() <= assortmentCluster.clusterCapacity) {
@@ -406,17 +404,17 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
**/
}
-
+
private int intTime(long longTime) {
return (int) ((longTime - startTime) / 1000);
}
-
+
private long longTime(int intTime) {
return ((long) intTime) * ((long) 1000) + startTime;
}
-
+
private boolean flushFromAssortmentCluster(String key, long maxTime) {
- // this should only be called if the assortment shall be deleted or returned in an index entity
+ // this should only be called if the assortment shall be deleted or returned in an index entity
maxTime = 8 * maxTime / 10; // reserve time for later adding to backend
plasmaWordIndexEntryContainer container = assortmentCluster.removeFromAll(key, maxTime);
if (container == null) {
@@ -440,9 +438,9 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
}
flushThread.proceed();
long r = maxTime - (System.currentTimeMillis() - start);
- return backend.getIndex(wordHash, deleteIfEmpty, (r < 0) ? 0 : r);
+ return backend.getIndex(wordHash, deleteIfEmpty, (r < 0) ? 0 : r);
}
-
+
public long getUpdateTime(String wordHash) {
plasmaWordIndexEntryContainer entries = (plasmaWordIndexEntryContainer) cache.get(wordHash);
if (entries == null) return 0;
@@ -453,7 +451,7 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
return time.longValue();
*/
}
-
+
public void deleteIndex(String wordHash) {
flushThread.pause();
synchronized (cache) {
@@ -462,7 +460,7 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
hashDate.deleteScore(wordHash);
}
assortmentCluster.removeFromAll(wordHash, -1);
- backend.deleteIndex(wordHash);
+ backend.deleteIndex(wordHash);
flushThread.proceed();
}
@@ -474,10 +472,10 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
flushThread.proceed();
return removed;
}
-
+
public int addEntries(plasmaWordIndexEntryContainer container, long updateTime, boolean highPriority) {
// this puts the entries into the cache, not into the assortment directly
-
+
int added = 0;
// check cache space
if (cache.size() > 0) try {
@@ -490,21 +488,20 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
if (cache.size() + 1000 >= this.maxWordsLow) Thread.sleep(java.lang.Math.min(1000, cache.size() - this.maxWordsLow + 1000));
pausetime = java.lang.Math.min(10, 2 * cache.size() / (maxWordsLow + 1));
}
-
+
// slow down if we reach cache limit
Thread.sleep(pausetime);
} catch (InterruptedException e) {}
-
+
//serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size());
-
+
// put new words into cache
String wordHash = container.wordHash();
-
+
synchronized (cache) {
-
// stop flushing now for one moment
flushThread.pause();
-
+
// put container into cache
plasmaWordIndexEntryContainer entries = (plasmaWordIndexEntryContainer) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null
if (entries == null) entries = new plasmaWordIndexEntryContainer(wordHash);
@@ -515,18 +512,18 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
hashDate.setScore(wordHash, intTime(updateTime));
}
entries = null;
-
+
// resume flushing
flushThread.proceed();
}
//System.out.println("DEBUG: cache = " + cache.toString());
-
+
return added;
}
private void addEntry(String wordHash, plasmaWordIndexEntry newEntry, long updateTime) {
flushThread.pause();
- plasmaWordIndexEntryContainer container = (plasmaWordIndexEntryContainer) cache.get(wordHash);
+ plasmaWordIndexEntryContainer container = (plasmaWordIndexEntryContainer) cache.get(wordHash);
if (container == null) container = new plasmaWordIndexEntryContainer(wordHash);
plasmaWordIndexEntry[] entries = new plasmaWordIndexEntry[]{newEntry};
if (container.add(entries, updateTime) > 0) {
@@ -543,7 +540,7 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
// stop permanent flushing
flushThread.terminate();
try {flushThread.join(5000);} catch (InterruptedException e) {}
-
+
// close cluster
assortmentCluster.close();
try {
@@ -596,4 +593,4 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
}
}
-}
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaWordIndexDistribution.java b/source/de/anomic/plasma/plasmaWordIndexDistribution.java
index 3ad53e287..ea4841c4a 100644
--- a/source/de/anomic/plasma/plasmaWordIndexDistribution.java
+++ b/source/de/anomic/plasma/plasmaWordIndexDistribution.java
@@ -1,908 +1,907 @@
-//plasmaWordIndexDistribution.java
-//-------------------------------------------
-//(C) by Michael Peter Christen; [email protected]
-//first published on http://www.anomic.de
-//Frankfurt, Germany, 2005
-//
-//last major change: $LastChangedDate$ by $LastChangedBy$
-//Revision: $LastChangedRevision$
-//
-//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
-//
-//Using this software in any meaning (reading, learning, copying, compiling,
-//running) means that you agree that the Author(s) is (are) not responsible
-//for cost, loss of data or any harm that may be caused directly or indirectly
-//by usage of this softare or this documentation. The usage of this software
-//is on your own risk. The installation and usage (starting/running) of this
-//software may allow other people or application to access your computer and
-//any attached devices and is highly dependent on the configuration of the
-//software which must be done by the user of the software; the author(s) is
-//(are) also not responsible for proper configuration and usage of the
-//software, even if provoked by documentation provided together with
-//the software.
-//
-//Any changes to this file according to the GPL as documented in the file
-//gpl.txt aside this file in the shipment you received can be done to the
-//lines that follows this copyright notice here, but changes must not be
-//done inside the copyright notive above. A re-distribution must contain
-//the intact and unchanged copyright notice.
-//Contributions and changes to the program code must be marked as such.
-
-package de.anomic.plasma;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.HashSet;
-import java.util.HashMap;
-
-import de.anomic.yacy.yacyCore;
-import de.anomic.yacy.yacySeed;
-import de.anomic.yacy.yacySeedDB;
-import de.anomic.yacy.yacyClient;
-import de.anomic.yacy.yacyDHTAction;
-import de.anomic.server.serverCodings;
-import de.anomic.server.logging.serverLog;
-import de.anomic.kelondro.kelondroException;
-
-public final class plasmaWordIndexDistribution {
-
- // distributes parts of the index to other peers
- // stops as soon as an error occurrs
-
- private int indexCount;
- private int juniorPeerCount, seniorPeerCount;
- private long maxTime;
-
- private final plasmaURLPool urlPool;
- private final plasmaWordIndex wordIndex;
- final serverLog log;
- boolean paused = false;
- private boolean enabled;
- private boolean enabledWhileCrawling;
- private boolean closed;
- private boolean gzipBody;
- private int timeout;
- private int maxOpenFiles;
-
- public transferIndexThread transferIdxThread = null;
-
- public plasmaWordIndexDistribution(
- plasmaURLPool urlPool,
- plasmaWordIndex wordIndex,
- serverLog log,
- boolean enable,
- boolean enabledWhileCrawling,
- boolean gzipBody,
- int timeout,
- int maxOpenFiles
- ) {
- this.urlPool = urlPool;
- this.wordIndex = wordIndex;
- this.enabled = enable;
- this.enabledWhileCrawling = enabledWhileCrawling;
- this.log = log;
- this.closed = false;
- setCounts(100 /*indexCount*/, 1 /*juniorPeerCount*/, 3 /*seniorPeerCount*/, 8000);
- this.gzipBody = gzipBody;
- this.timeout = timeout;
- this.maxOpenFiles = maxOpenFiles;
- }
-
- public void enable() {
- enabled = true;
- }
-
- public void disable() {
- enabled = false;
- }
-
- public void enableWhileCrawling() {
- this.enabledWhileCrawling = true;
- }
-
- public void disableWhileCrawling() {
- this.enabledWhileCrawling = false;
- }
-
- public void close() {
- closed = true;
- if (transferIdxThread != null) {
- stopTransferWholeIndex(false);
- }
- }
-
- public boolean job() {
-
- if (this.closed) {
- log.logFine("no word distribution: closed");
- return false;
- }
- if (yacyCore.seedDB == null) {
- log.logFine("no word distribution: seedDB == null");
- return false;
- }
- if (yacyCore.seedDB.mySeed == null) {
- log.logFine("no word distribution: mySeed == null");
- return false;
- }
- if (yacyCore.seedDB.mySeed.isVirgin()) {
- log.logFine("no word distribution: status is virgin");
- return false;
- }
- if (!(enabled)) {
- log.logFine("no word distribution: not enabled");
- return false;
- }
- if (paused) {
- log.logFine("no word distribution: paused");
- return false;
- }
- if (urlPool.loadedURL.size() < 10) {
- log.logFine("no word distribution: loadedURL.size() = " + urlPool.loadedURL.size());
- return false;
- }
- if (wordIndex.size() < 100) {
- log.logFine("no word distribution: not enough words - wordIndex.size() = " + wordIndex.size());
- return false;
- }
- if ((!enabledWhileCrawling) && (urlPool.noticeURL.stackSize() > 0)) {
- log.logFine("no word distribution: crawl in progress - noticeURL.stackSize() = " + urlPool.noticeURL.stackSize());
- return false;
- }
-
- // do the transfer
- int peerCount = (yacyCore.seedDB.mySeed.isJunior()) ? juniorPeerCount : seniorPeerCount;
- long starttime = System.currentTimeMillis();
- int transferred = performTransferIndex(indexCount, peerCount, true);
-
- if (transferred <= 0) {
- log.logFine("no word distribution: transfer failed");
- return false;
- }
-
- // adopt transfer count
- if ((System.currentTimeMillis() - starttime) > (maxTime * peerCount))
- indexCount--;
- else
- indexCount++;
- if (indexCount < 50) indexCount = 50;
-
- // show success
- return true;
-
- }
-
- public void setCounts(int indexCount, int juniorPeerCount, int seniorPeerCount, long maxTimePerTransfer) {
- this.maxTime = maxTimePerTransfer;
- this.indexCount = indexCount;
- if (indexCount < 30) indexCount = 30;
- this.juniorPeerCount = juniorPeerCount;
- this.seniorPeerCount = seniorPeerCount;
- }
-
- public int performTransferIndex(int indexCount, int peerCount, boolean delete) {
- if ((yacyCore.seedDB == null) || (yacyCore.seedDB.sizeConnected() == 0)) return -1;
-
- // collect index
- String startPointHash = selectTransferStart();
- log.logFine("Selected hash " + startPointHash + " as start point for index distribution, distance = " + yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, startPointHash));
- Object[] selectResult = selectTransferIndexes(startPointHash, indexCount, this.maxOpenFiles);
- plasmaWordIndexEntity[] indexEntities = (plasmaWordIndexEntity[]) selectResult[0];
- Integer openedFiles = (Integer) selectResult[2];
- HashMap urlCache = (HashMap) selectResult[1]; // String (url-hash) / plasmaCrawlLURL.Entry
- if ((indexEntities == null) || (indexEntities.length == 0)) {
- log.logFine("No index available for index transfer, hash start-point " + startPointHash);
- return -1;
- }
- // count the indexes again, can be smaller as expected
- indexCount = 0;
- for (int i = 0; i < indexEntities.length; i++) {
- indexCount += indexEntities[i].size();
- }
-
- // find start point for DHT-selection
- String keyhash = indexEntities[indexEntities.length - 1].wordHash(); // DHT targets must have greater hashes
-
- // iterate over DHT-peers and send away the indexes
- yacySeed seed;
- int hc = 0;
- Enumeration e = yacyCore.dhtAgent.getAcceptRemoteIndexSeeds(keyhash);
- String error;
- String peerNames = "";
- double avdist;
- long start;
- while ((e.hasMoreElements()) && (hc < peerCount)) {
- if (closed) {
- log.logSevere("Index distribution interrupted by close, nothing deleted locally.");
- return -1; // interrupted
- }
- seed = (yacySeed) e.nextElement();
- if ((seed != null) &&
- ((avdist = (yacyDHTAction.dhtDistance(seed.hash, indexEntities[0].wordHash()) +
- yacyDHTAction.dhtDistance(seed.hash, indexEntities[indexEntities.length-1].wordHash())) / 2.0) < 0.3)) {
- start = System.currentTimeMillis();
- error = yacyClient.transferIndex(seed, indexEntities, urlCache, this.gzipBody, this.timeout);
- if (error == null) {
- log.logInfo("Index transfer of " + indexCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]/" +
- avdist + " to peer " + seed.getName() + ":" + seed.hash + " in " +
- ((System.currentTimeMillis() - start) / 1000) + " seconds successfull (" +
- (1000 * indexCount / (System.currentTimeMillis() - start + 1)) + " words/s)");
- peerNames += ", " + seed.getName();
- hc++;
- } else {
- log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + error + "', disconnecting peer");
- yacyCore.peerActions.peerDeparture(seed);
- }
- }
- }
- if (peerNames.length() > 0) peerNames = peerNames.substring(2); // remove comma
-
- // clean up and finish with deletion of indexes
- if (hc >= peerCount) {
- // success
- if (delete) {
- try {
- if (deleteTransferIndexes(indexEntities)) {
- log.logFine("Deleted all " + indexEntities.length + " transferred whole-word indexes locally");
- return indexCount;
- } else {
- log.logSevere("Deleted not all transferred whole-word indexes");
- return -1;
- }
- } catch (IOException ee) {
- log.logSevere("Deletion of indexes not possible:" + ee.getMessage(), ee);
- return -1;
- }
- } else {
- // simply close the indexEntities
- for (int i = 0; i < indexEntities.length; i++) try {
- indexEntities[i].close();
- } catch (IOException ee) {}
- }
- return indexCount;
- } else {
- log.logSevere("Index distribution failed. Too few peers (" + hc + ") received the index, not deleted locally.");
- return -1;
- }
- }
-
- private String selectTransferStart() {
- String startPointHash;
- // first try to select with increasing probality a good start point
- if (Math.round(Math.random() * 6) != 4) for (int i = 9; i > 0; i--) {
- startPointHash = serverCodings.encodeMD5B64(Long.toString(i + System.currentTimeMillis()), true).substring(2, 2 + yacySeedDB.commonHashLength);
- if (yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, startPointHash) > ((double) i / (double) 10)) return startPointHash;
- }
- // if that fails, take simply the best start point (this is usually avoided, since that leads to always the same target peers)
- startPointHash = yacyCore.seedDB.mySeed.hash.substring(0, 11) + "z";
- return startPointHash;
- }
-
- Object[] /* of {plasmaWordIndexEntity[], HashMap(String, plasmaCrawlLURL.Entry)}*/
- selectTransferIndexes(String hash, int count, int maxOpenFiles) {
- // the hash is a start hash from where the indexes are picked
- ArrayList tmpEntities = new ArrayList(count);
- String nexthash = "";
- try {
- int currOpenFiles = 0;
- Iterator wordHashIterator = this.wordIndex.wordHashes(hash, true, true);
- plasmaWordIndexEntity indexEntity, tmpEntity;
- Iterator urlIter;
- Iterator hashIter;
- plasmaWordIndexEntry indexEntry;
- plasmaCrawlLURL.Entry lurl;
- final HashSet unknownURLEntries = new HashSet();
- final HashMap knownURLs = new HashMap();
- while (
- (count > 0) &&
- (currOpenFiles < maxOpenFiles) &&
- (wordHashIterator.hasNext()) &&
- ((nexthash = (String) wordHashIterator.next()) != null) &&
- (nexthash.trim().length() > 0)
- ) {
- indexEntity = this.wordIndex.getEntity(nexthash, true, -1);
- if (indexEntity.size() == 0) {
- indexEntity.deleteComplete();
- } else if ((indexEntity.size() <= count)|| // if we havn't exceeded the limit
- (Math.abs(indexEntity.size() - count) <= 10)){ // or there are only at most 10 entries left
- // take the whole entity
- try {
- // fist check if we know all urls
- urlIter = indexEntity.elements(true);
- unknownURLEntries.clear();
- while (urlIter.hasNext()) {
- indexEntry = (plasmaWordIndexEntry) urlIter.next();
- lurl = this.urlPool.loadedURL.getEntry(indexEntry.getUrlHash());
- if ((lurl == null) || (lurl.toString() == null)) {
- unknownURLEntries.add(indexEntry.getUrlHash());
- } else {
- if (lurl.toString() == null) {
- this.urlPool.loadedURL.remove(indexEntry.getUrlHash());
- unknownURLEntries.add(indexEntry.getUrlHash());
- } else {
- knownURLs.put(indexEntry.getUrlHash(), lurl);
- }
- }
- }
- // now delete all entries that have no url entry
- hashIter = unknownURLEntries.iterator();
- while (hashIter.hasNext()) {
- indexEntity.removeEntry((String) hashIter.next(), false);
- }
-
- if (indexEntity.size() == 0) {
- indexEntity.deleteComplete();
- } else {
- // use whats remaining
- tmpEntities.add(indexEntity);
- this.log.logFine("Selected whole index (" + indexEntity.size() + " URLs, " + unknownURLEntries.size() + " not bound) for word " + indexEntity.wordHash());
- count -= indexEntity.size();
- currOpenFiles++;
- }
- } catch (kelondroException e) {
- this.log.logSevere("plasmaWordIndexDistribution/1: deleted DB for word " + indexEntity.wordHash(), e);
- indexEntity.deleteComplete();
- }
- } else {
- // make an on-the-fly entity and insert values
- tmpEntity = new plasmaWordIndexEntity(indexEntity.wordHash());
- try {
- urlIter = indexEntity.elements(true);
- unknownURLEntries.clear();
- while ((urlIter.hasNext()) && (count > 0)) {
- indexEntry = (plasmaWordIndexEntry) urlIter.next();
- lurl = this.urlPool.loadedURL.getEntry(indexEntry.getUrlHash());
- if (lurl == null) {
- unknownURLEntries.add(indexEntry.getUrlHash());
- } else {
- if (lurl.toString() == null) {
- this.urlPool.loadedURL.remove(indexEntry.getUrlHash());
- unknownURLEntries.add(indexEntry.getUrlHash());
- } else {
- knownURLs.put(indexEntry.getUrlHash(), lurl);
- tmpEntity.addEntry(indexEntry);
- count--;
- }
- }
- }
- // now delete all entries that have no url entry
- hashIter = unknownURLEntries.iterator();
- while (hashIter.hasNext()) {
- indexEntity.removeEntry((String) hashIter.next(), true);
- }
- // use whats remaining
- this.log.logFine("Selected partial index (" + tmpEntity.size() + " from " + indexEntity.size() +" URLs, " + unknownURLEntries.size() + " not bound) for word " + tmpEntity.wordHash());
- tmpEntities.add(tmpEntity);
- } catch (kelondroException e) {
- this.log.logSevere("plasmaWordIndexDistribution/2: deleted DB for word " + indexEntity.wordHash(), e);
- indexEntity.deleteComplete();
- }
- indexEntity.close(); // important: is not closed elswhere and cannot be deleted afterwards
- indexEntity = null;
- }
-
- }
- // transfer to array
- plasmaWordIndexEntity[] indexEntities = (plasmaWordIndexEntity[]) tmpEntities.toArray(new plasmaWordIndexEntity[tmpEntities.size()]);
- return new Object[]{indexEntities, knownURLs, new Integer(currOpenFiles)};
- } catch (IOException e) {
- this.log.logSevere("selectTransferIndexes IO-Error (hash=" + nexthash + "): " + e.getMessage(), e);
- return new Object[]{new plasmaWordIndexEntity[0], new HashMap(0)};
- } catch (kelondroException e) {
- this.log.logSevere("selectTransferIndexes database corrupted: " + e.getMessage(), e);
- return new Object[]{new plasmaWordIndexEntity[0], new HashMap(0)};
- }
- }
-
- boolean deleteTransferIndexes(plasmaWordIndexEntity[] indexEntities) throws IOException {
- String wordhash;
- Iterator urlIter;
- plasmaWordIndexEntry indexEntry;
- plasmaWordIndexEntity indexEntity;
- String[] urlHashes;
- int sz;
- boolean success = true;
- for (int i = 0; i < indexEntities.length; i++) {
- if (indexEntities[i].isTMPEntity()) {
- // delete entries separately
- int c = 0;
- urlHashes = new String[indexEntities[i].size()];
- urlIter = indexEntities[i].elements(true);
- while (urlIter.hasNext()) {
- indexEntry = (plasmaWordIndexEntry) urlIter.next();
- urlHashes[c++] = indexEntry.getUrlHash();
- }
- wordIndex.removeEntries(indexEntities[i].wordHash(), urlHashes, true);
- indexEntity = wordIndex.getEntity(indexEntities[i].wordHash(), true, -1);
- sz = indexEntity.size();
- indexEntity.close();
- log.logFine("Deleted partial index (" + c + " URLs) for word " + indexEntities[i].wordHash() + "; " + sz + " entries left");
- // DEBUG: now try to delete the remaining index. If this works, this routine is fine
- /*
- if (wordIndex.getEntity(indexEntities[i].wordHash()).deleteComplete())
- System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " SUCCESSFULL");
- else
- System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " FAILED");
- */
- // end debug
- indexEntities[i].close();
- } else {
- // delete complete file
- if (indexEntities[i].deleteComplete()) {
- indexEntities[i].close();
- } else {
- indexEntities[i].close();
- // have another try...
- if (!(plasmaWordIndexEntity.wordHash2path(wordIndex.getRoot() /*PLASMADB*/, indexEntities[i].wordHash()).delete())) {
- success = false;
- log.logSevere("Could not delete whole index for word " + indexEntities[i].wordHash());
- }
- }
- }
- indexEntities[i] = null;
- }
- return success;
- }
-
-
- public void startTransferWholeIndex(yacySeed seed, boolean delete) {
- if (transferIdxThread == null) {
- this.transferIdxThread = new transferIndexThread(seed,delete);
- this.transferIdxThread.start();
- }
- }
-
- public void stopTransferWholeIndex(boolean wait) {
- if ((transferIdxThread != null) && (transferIdxThread.isAlive()) && (!transferIdxThread.isFinished())) {
- try {
- this.transferIdxThread.stopIt(wait);
- } catch (InterruptedException e) { }
- }
- }
-
- public void abortTransferWholeIndex(boolean wait) {
- if (transferIdxThread != null) {
- if (!transferIdxThread.isFinished())
- try {
- this.transferIdxThread.stopIt(wait);
- } catch (InterruptedException e) { }
- transferIdxThread = null;
- }
- }
-
-
- private class transferIndexWorkerThread extends Thread{
- // connection properties
- private boolean gzipBody = false;
- private int timeout = 60000;
-
- // status fields
- private boolean finished = false;
- boolean success = false;
- private String status = "running";
- private long iteration = 0;
- private long transferTime = 0;
- private int idxCount = 0;
- private int chunkSize = 0;
-
- // delivery destination
- yacySeed seed = null;
-
- // word chunk
- private String endPointHash;
- private String startPointHash;
- plasmaWordIndexEntity[] indexEntities;
-
- // other fields
- HashMap urlCache;
-
- public transferIndexWorkerThread(
- yacySeed seed,
- plasmaWordIndexEntity[] indexEntities,
- HashMap urlCache,
- boolean gzipBody,
- int timeout,
- long iteration,
- int idxCount,
- int chunkSize,
- String endPointHash,
- String startPointHash) {
- super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndexWorker_" + seed.getName());
- this.gzipBody = gzipBody;
- this.timeout = timeout;
- this.iteration = iteration;
- this.seed = seed;
- this.indexEntities = indexEntities;
- this.urlCache = urlCache;
- this.idxCount = idxCount;
- this.chunkSize = chunkSize;
- this.startPointHash = startPointHash;
- this.endPointHash = endPointHash;
- }
-
- public void run() {
- try {
- uploadIndex();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
-
- }
- }
-
- public boolean success() {
- return this.success;
- }
-
- public int getChunkSize() {
- return this.chunkSize;
- }
-
- public String getStatus() {
- return this.status;
- }
-
- private boolean isAborted() {
- if (finished || Thread.currentThread().isInterrupted()) {
- return true;
- }
- return false;
- }
-
- public void stopIt() {
- this.finished = true;
- }
-
- public String getRange() {
- return "[" + startPointHash + ".." + endPointHash + "]";
- }
-
- public long getTransferTime() {
- return this.transferTime;
- }
-
- private void uploadIndex() throws InterruptedException {
-
- /* loop until we
- * - have successfully transfered the words list or
- * - the retry counter limit was exceeded
- */
- long retryCount = 0, start = System.currentTimeMillis();
- while (true) {
- // testing if we wer aborted
- if (isAborted()) return;
-
- // transfering seleted words to remote peer
- this.status = "Running: Transfering chunk " + iteration;
- String error = yacyClient.transferIndex(seed, indexEntities, urlCache, this.gzipBody, this.timeout);
- if (error == null) {
- // words successfully transfered
- transferTime = System.currentTimeMillis() - start;
- plasmaWordIndexDistribution.this.log.logInfo("Index transfer of " + idxCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]" +
- " to peer " + seed.getName() + ":" + seed.hash + " in " + (transferTime/1000) + " seconds successfull (" +
- (1000 * idxCount / (transferTime + 1)) + " words/s)");
- retryCount = 0;
-
-// if (transferTime > 30000) {
-// if (chunkSize>100) chunkSize-=50;
-// } else {
-// chunkSize+=50;
-// }
- this.success = true;
- this.status = "Finished: Transfer of chunk " + iteration;
- break;
- } else {
- // worts transfer failed
-
- // inc retry counter
- retryCount++;
-
- // testing if we were aborted ...
- if (isAborted()) return;
-
- // we have lost the connection to the remote peer. Adding peer to disconnected list
- plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + error + "', disconnecting peer");
- yacyCore.peerActions.peerDeparture(seed);
-
- // if the retry counter limit was not exceeded we'll retry it in a few seconds
- this.status = "Disconnected peer: " + ((retryCount > 5)? error + ". Transfer aborted":"Retry " + retryCount);
- if (retryCount > 5) return;
- Thread.sleep(retryCount*5000);
-
- /* loop until
- * - we have successfully done a peer ping or
- * - the retry counter limit was exceeded
- */
- while (true) {
- // testing if we were aborted ...
- if (isAborted()) return;
-
- // doing a peer ping to the remote seed
- int added = yacyClient.publishMySeed(seed.getAddress(), seed.hash);
- if (added < 0) {
- // inc. retry counter
- retryCount++;
- this.status = "Disconnected peer: Peer ping failed. " + ((retryCount > 5)?"Transfer aborted.":"Retry " + retryCount);
- if (retryCount > 5) return;
- Thread.sleep(retryCount*5000);
- continue;
- } else {
- yacyCore.seedDB.getConnected(seed.hash);
- this.status = "running";
- break;
- }
- }
- }
- }
- }
-
- }
-
- public class transferIndexThread extends Thread {
- private yacySeed seed = null;
- private boolean delete = false;
- private boolean finished = false;
- private boolean gzipBody = false;
- private int timeout = 60000;
- private int maxOpenFiles = 800;
- private int transferedIndexCount = 0;
- private String status = "Running";
- private String oldStartingPointHash = "------------", startPointHash = "------------";
- private int wordsDBSize = 0;
- private int chunkSize = 500;
- private final long startingTime = System.currentTimeMillis();
- private final plasmaSwitchboard sb;
- private final Runtime rt = Runtime.getRuntime();
- transferIndexWorkerThread worker = null;
-
- public transferIndexThread(yacySeed seed, boolean delete) {
- super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndex_" + seed.getName());
- this.seed = seed;
- this.delete = delete;
- this.sb = plasmaSwitchboard.getSwitchboard();
- this.wordsDBSize = sb.wordIndex.size();
- this.gzipBody = "true".equalsIgnoreCase(sb.getConfig("indexTransfer.gzipBody","false"));
- this.timeout = (int) sb.getConfigLong("indexTransfer.timeout",60000);
- this.maxOpenFiles = (int) sb.getConfigLong("indexTransfer.maxOpenFiles",800);
- }
-
- public void run() {
- performTransferWholeIndex();
- }
-
- public void stopIt(boolean wait) throws InterruptedException {
- this.finished = true;
- this.join();
- }
-
- public boolean isFinished() {
- return this.finished;
- }
-
- public boolean deleteIndex() {
- return this.delete;
- }
-
- public int[] getChunkSize() {
- transferIndexWorkerThread workerThread = this.worker;
- if (workerThread != null) {
- return new int[]{this.chunkSize,workerThread.getChunkSize()};
- }
- return new int[]{this.chunkSize,500};
- }
-
- public int getTransferedIndexCount() {
- return this.transferedIndexCount;
- }
-
- public float getTransferedIndexPercent() {
- if (wordsDBSize == 0) return 100;
- else return (float)(this.transferedIndexCount*100/wordsDBSize);
- }
-
- public int getTransferedIndexSpeed() {
- return (int) ((1000 * transferedIndexCount) / (System.currentTimeMillis()-startingTime));
- }
-
- public yacySeed getSeed() {
- return this.seed;
- }
-
- public String[] getStatus() {
- transferIndexWorkerThread workerThread = this.worker;
- if (workerThread != null) {
- return new String[]{this.status,workerThread.getStatus()};
- }
- return new String[]{this.status,"Not running"};
- }
-
- public String[] getRange() {
- transferIndexWorkerThread workerThread = this.worker;
- if (workerThread != null) {
- return new String[]{"[" + oldStartingPointHash + ".." + startPointHash + "]",workerThread.getRange()};
- }
- return new String[]{"[" + oldStartingPointHash + ".." + startPointHash + "]","[------------..------------]"};
- }
-
- public void performTransferWholeIndex() {
- plasmaWordIndexEntity[] newIndexEntities = null, oldIndexEntities = null;
- try {
- // pausing the regular index distribution
- // TODO: adding sync, to wait for a still running index distribution to finish
- plasmaWordIndexDistribution.this.paused = true;
-
- // initial startingpoint of intex transfer is "------------"
- plasmaWordIndexDistribution.this.log.logFine("Selected hash " + startPointHash + " as start point for index distribution of whole index");
-
- /* Loop until we have
- * - finished transfer of whole index
- * - detected a server shutdown or user interruption
- * - detected a failure
- */
- long selectionStart = System.currentTimeMillis(), selectionEnd = 0, selectionTime = 0, iteration = 0;
-
- Integer openedFiles = new Integer(0);
- while (!finished && !Thread.currentThread().isInterrupted()) {
- iteration++;
- int idxCount = 0;
- selectionStart = System.currentTimeMillis();
- oldIndexEntities = newIndexEntities;
-
- // selecting 500 words to transfer
- this.status = "Running: Selecting chunk " + iteration;
- Object[] selectResult = selectTransferIndexes(this.startPointHash, this.chunkSize, this.maxOpenFiles-openedFiles.intValue());
- newIndexEntities = (plasmaWordIndexEntity[]) selectResult[0];
- HashMap urlCache = (HashMap) selectResult[1]; // String (url-hash) / plasmaCrawlLURL.Entry
- openedFiles = (Integer) selectResult[2];
-
- /* If we havn't selected a word chunk this could be because of
- * a) no words are left in the index
- * b) max open file limit was exceeded
- */
- if ((newIndexEntities == null) || (newIndexEntities.length == 0)) {
- if (sb.wordIndex.size() > 0) {
- // if there are still words in the index we try it again now
- startPointHash = "------------";
- } else {
- // otherwise we could end transfer now
- plasmaWordIndexDistribution.this.log.logFine("No index available for index transfer, hash start-point " + startPointHash);
- this.status = "Finished. " + iteration + " chunks transfered.";
- finished = true;
- }
- } else {
- // count the indexes again, can be smaller as expected
- for (int i = 0; i < newIndexEntities.length; i++) idxCount += newIndexEntities[i].size();
-
- // getting start point for next DHT-selection
- oldStartingPointHash = startPointHash;
- startPointHash = newIndexEntities[newIndexEntities.length - 1].wordHash(); // DHT targets must have greater hashes
-
- selectionEnd = System.currentTimeMillis();
- selectionTime = selectionEnd - selectionStart;
- plasmaWordIndexDistribution.this.log.logInfo("Index selection of " + idxCount + " words [" + newIndexEntities[0].wordHash() + " .. " + newIndexEntities[newIndexEntities.length-1].wordHash() + "]" +
- " in " +
- (selectionTime / 1000) + " seconds (" +
- (1000 * idxCount / (selectionTime+1)) + " words/s)");
- }
-
- // query status of old worker thread
- if (worker != null) {
- this.status = "Finished: Selecting chunk " + iteration;
- worker.join();
- if (!worker.success) {
- // if the transfer failed we abort index transfer now
- this.status = "Aborted because of Transfer error:\n" + worker.getStatus();
-
- // cleanup. closing all open files
- closeEntities(oldIndexEntities);
- oldIndexEntities = null;
- closeEntities(newIndexEntities);
- newIndexEntities = null;
-
- // abort index transfer
- return;
- } else {
- /*
- * If index transfer was done successfully we close all remaining open
- * files that belong to the old index chunk and handover a new chunk
- * to the transfer thread.
- * Addintionally we recalculate the chunk size to optimize performance
- */
-
- this.chunkSize = worker.getChunkSize();
- long transferTime = worker.getTransferTime();
- //TODO: only increase chunk Size if there is free memory left on the server
-
- // we need aprox. 73Byte per IndexEntity and an average URL length of 32 char
- //if (ft.freeMemory() < 73*2*100)
- if (transferTime > 60*1000) {
- if (chunkSize>200) chunkSize-=100;
- } else if (selectionTime < transferTime){
- this.chunkSize +=100;
- //chunkSize+=50;
- } else if (selectionTime >= selectionTime){
- if (chunkSize>200) chunkSize-=100;
- }
-
- selectionStart = System.currentTimeMillis();
-
- // deleting transfered words from index
- if (delete) {
- this.status = "Running: Deleting chunk " + iteration;
- try {
- if (deleteTransferIndexes(oldIndexEntities)) {
- plasmaWordIndexDistribution.this.log.logFine("Deleted all " + oldIndexEntities.length + " transferred whole-word indexes locally");
- transferedIndexCount += idxCount;
- } else {
- plasmaWordIndexDistribution.this.log.logSevere("Deleted not all transferred whole-word indexes");
- }
- } catch (IOException ee) {
- plasmaWordIndexDistribution.this.log.logSevere("Deletion of indexes not possible:" + ee.getMessage(), ee);
- }
- } else {
- this.closeEntities(oldIndexEntities);
- transferedIndexCount += idxCount;
- }
- oldIndexEntities = null;
- }
- this.worker = null;
- }
-
- // handover chunk to transfer worker
- if (!((newIndexEntities == null) || (newIndexEntities.length == 0))) {
- worker = new transferIndexWorkerThread(seed,newIndexEntities,urlCache,gzipBody,timeout,iteration,idxCount,idxCount,startPointHash,oldStartingPointHash);
- worker.start();
- }
- }
-
- // if we reach this point we were aborted by the user or by server shutdown
- if (sb.wordIndex.size() > 0) this.status = "aborted";
- } catch (Exception e) {
- this.status = "Error: " + e.getMessage();
- plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + e.getMessage() + "'",e);
-
- } finally {
- if (worker != null) {
- worker.stopIt();
- try {worker.join();}catch(Exception e){}
- // worker = null;
- }
- if (oldIndexEntities != null) closeEntities(oldIndexEntities);
- if (newIndexEntities != null) closeEntities(newIndexEntities);
-
- plasmaWordIndexDistribution.this.paused = false;
- }
- }
-
- private void closeEntities(plasmaWordIndexEntity[] indexEntities) {
- if ((indexEntities == null)||(indexEntities.length ==0)) return;
-
- for (int i = 0; i < indexEntities.length; i++) try {
- indexEntities[i].close();
- } catch (IOException ee) {}
- }
-
- private boolean isAborted() {
- if (finished || Thread.currentThread().isInterrupted()) {
- this.status = "aborted";
- return true;
- }
- return false;
- }
- }
-}
+//plasmaWordIndexDistribution.java
+//-------------------------------------------
+//(C) by Michael Peter Christen; [email protected]
+//first published on http://www.anomic.de
+//Frankfurt, Germany, 2005
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
+//
+//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
+//
+//Using this software in any meaning (reading, learning, copying, compiling,
+//running) means that you agree that the Author(s) is (are) not responsible
+//for cost, loss of data or any harm that may be caused directly or indirectly
+//by usage of this softare or this documentation. The usage of this software
+//is on your own risk. The installation and usage (starting/running) of this
+//software may allow other people or application to access your computer and
+//any attached devices and is highly dependent on the configuration of the
+//software which must be done by the user of the software; the author(s) is
+//(are) also not responsible for proper configuration and usage of the
+//software, even if provoked by documentation provided together with
+//the software.
+//
+//Any changes to this file according to the GPL as documented in the file
+//gpl.txt aside this file in the shipment you received can be done to the
+//lines that follows this copyright notice here, but changes must not be
+//done inside the copyright notive above. A re-distribution must contain
+//the intact and unchanged copyright notice.
+//Contributions and changes to the program code must be marked as such.
+
+package de.anomic.plasma;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.HashSet;
+import java.util.HashMap;
+import de.anomic.yacy.yacyCore;
+import de.anomic.yacy.yacySeed;
+import de.anomic.yacy.yacySeedDB;
+import de.anomic.yacy.yacyClient;
+import de.anomic.yacy.yacyDHTAction;
+import de.anomic.server.serverCodings;
+import de.anomic.server.logging.serverLog;
+import de.anomic.kelondro.kelondroException;
+
+public final class plasmaWordIndexDistribution {
+
+ // distributes parts of the index to other peers
+ // stops as soon as an error occurrs
+
+ private int indexCount;
+ private int juniorPeerCount, seniorPeerCount;
+ private long maxTime;
+
+ private final plasmaURLPool urlPool;
+ private final plasmaWordIndex wordIndex;
+ final serverLog log;
+ boolean paused = false;
+ private boolean enabled;
+ private boolean enabledWhileCrawling;
+ private boolean closed;
+ private boolean gzipBody;
+ private int timeout;
+ private int maxOpenFiles;
+
+ public transferIndexThread transferIdxThread = null;
+
+ public plasmaWordIndexDistribution(
+ plasmaURLPool urlPool,
+ plasmaWordIndex wordIndex,
+ serverLog log,
+ boolean enable,
+ boolean enabledWhileCrawling,
+ boolean gzipBody,
+ int timeout,
+ int maxOpenFiles
+ ) {
+ this.urlPool = urlPool;
+ this.wordIndex = wordIndex;
+ this.enabled = enable;
+ this.enabledWhileCrawling = enabledWhileCrawling;
+ this.log = log;
+ this.closed = false;
+ setCounts(100 /*indexCount*/, 1 /*juniorPeerCount*/, 3 /*seniorPeerCount*/, 8000);
+ this.gzipBody = gzipBody;
+ this.timeout = timeout;
+ this.maxOpenFiles = maxOpenFiles;
+ }
+
+ public void enable() {
+ enabled = true;
+ }
+
+ public void disable() {
+ enabled = false;
+ }
+
+ public void enableWhileCrawling() {
+ this.enabledWhileCrawling = true;
+ }
+
+ public void disableWhileCrawling() {
+ this.enabledWhileCrawling = false;
+ }
+
+ public void close() {
+ closed = true;
+ if (transferIdxThread != null) {
+ stopTransferWholeIndex(false);
+ }
+ }
+
+ public boolean job() {
+
+ if (this.closed) {
+ log.logFine("no word distribution: closed");
+ return false;
+ }
+ if (yacyCore.seedDB == null) {
+ log.logFine("no word distribution: seedDB == null");
+ return false;
+ }
+ if (yacyCore.seedDB.mySeed == null) {
+ log.logFine("no word distribution: mySeed == null");
+ return false;
+ }
+ if (yacyCore.seedDB.mySeed.isVirgin()) {
+ log.logFine("no word distribution: status is virgin");
+ return false;
+ }
+ if (!(enabled)) {
+ log.logFine("no word distribution: not enabled");
+ return false;
+ }
+ if (paused) {
+ log.logFine("no word distribution: paused");
+ return false;
+ }
+ if (urlPool.loadedURL.size() < 10) {
+ log.logFine("no word distribution: loadedURL.size() = " + urlPool.loadedURL.size());
+ return false;
+ }
+ if (wordIndex.size() < 100) {
+ log.logFine("no word distribution: not enough words - wordIndex.size() = " + wordIndex.size());
+ return false;
+ }
+ if ((!enabledWhileCrawling) && (urlPool.noticeURL.stackSize() > 0)) {
+ log.logFine("no word distribution: crawl in progress - noticeURL.stackSize() = " + urlPool.noticeURL.stackSize());
+ return false;
+ }
+
+ // do the transfer
+ int peerCount = (yacyCore.seedDB.mySeed.isJunior()) ? juniorPeerCount : seniorPeerCount;
+ long starttime = System.currentTimeMillis();
+ int transferred = performTransferIndex(indexCount, peerCount, true);
+
+ if (transferred <= 0) {
+ log.logFine("no word distribution: transfer failed");
+ return false;
+ }
+
+ // adopt transfer count
+ if ((System.currentTimeMillis() - starttime) > (maxTime * peerCount))
+ indexCount--;
+ else
+ indexCount++;
+ if (indexCount < 50) indexCount = 50;
+
+ // show success
+ return true;
+
+ }
+
+ public void setCounts(int indexCount, int juniorPeerCount, int seniorPeerCount, long maxTimePerTransfer) {
+ this.maxTime = maxTimePerTransfer;
+ this.indexCount = indexCount;
+ if (indexCount < 30) indexCount = 30;
+ this.juniorPeerCount = juniorPeerCount;
+ this.seniorPeerCount = seniorPeerCount;
+ }
+
+ public int performTransferIndex(int indexCount, int peerCount, boolean delete) {
+ if ((yacyCore.seedDB == null) || (yacyCore.seedDB.sizeConnected() == 0)) return -1;
+
+ // collect index
+ String startPointHash = selectTransferStart();
+ log.logFine("Selected hash " + startPointHash + " as start point for index distribution, distance = " + yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, startPointHash));
+ Object[] selectResult = selectTransferIndexes(startPointHash, indexCount, this.maxOpenFiles);
+ plasmaWordIndexEntity[] indexEntities = (plasmaWordIndexEntity[]) selectResult[0];
+ Integer openedFiles = (Integer) selectResult[2];
+ HashMap urlCache = (HashMap) selectResult[1]; // String (url-hash) / plasmaCrawlLURL.Entry
+ if ((indexEntities == null) || (indexEntities.length == 0)) {
+ log.logFine("No index available for index transfer, hash start-point " + startPointHash);
+ return -1;
+ }
+ // count the indexes again, can be smaller as expected
+ indexCount = 0;
+ for (int i = 0; i < indexEntities.length; i++) {
+ indexCount += indexEntities[i].size();
+ }
+
+ // find start point for DHT-selection
+ String keyhash = indexEntities[indexEntities.length - 1].wordHash(); // DHT targets must have greater hashes
+
+ // iterate over DHT-peers and send away the indexes
+ yacySeed seed;
+ int hc = 0;
+ Enumeration e = yacyCore.dhtAgent.getAcceptRemoteIndexSeeds(keyhash);
+ String error;
+ String peerNames = "";
+ double avdist;
+ long start;
+ while ((e.hasMoreElements()) && (hc < peerCount)) {
+ if (closed) {
+ log.logSevere("Index distribution interrupted by close, nothing deleted locally.");
+ return -1; // interrupted
+ }
+ seed = (yacySeed) e.nextElement();
+ if ((seed != null) &&
+ ((avdist = (yacyDHTAction.dhtDistance(seed.hash, indexEntities[0].wordHash()) +
+ yacyDHTAction.dhtDistance(seed.hash, indexEntities[indexEntities.length-1].wordHash())) / 2.0) < 0.3)) {
+ start = System.currentTimeMillis();
+ error = yacyClient.transferIndex(seed, indexEntities, urlCache, this.gzipBody, this.timeout);
+ if (error == null) {
+ log.logInfo("Index transfer of " + indexCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]/" +
+ avdist + " to peer " + seed.getName() + ":" + seed.hash + " in " +
+ ((System.currentTimeMillis() - start) / 1000) + " seconds successfull (" +
+ (1000 * indexCount / (System.currentTimeMillis() - start + 1)) + " words/s)");
+ peerNames += ", " + seed.getName();
+ hc++;
+ } else {
+ log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + error + "', disconnecting peer");
+ yacyCore.peerActions.peerDeparture(seed);
+ }
+ }
+ }
+ if (peerNames.length() > 0) peerNames = peerNames.substring(2); // remove comma
+
+ // clean up and finish with deletion of indexes
+ if (hc >= peerCount) {
+ // success
+ if (delete) {
+ try {
+ if (deleteTransferIndexes(indexEntities)) {
+ log.logFine("Deleted all " + indexEntities.length + " transferred whole-word indexes locally");
+ return indexCount;
+ } else {
+ log.logSevere("Deleted not all transferred whole-word indexes");
+ return -1;
+ }
+ } catch (IOException ee) {
+ log.logSevere("Deletion of indexes not possible:" + ee.getMessage(), ee);
+ return -1;
+ }
+ } else {
+ // simply close the indexEntities
+ for (int i = 0; i < indexEntities.length; i++) try {
+ indexEntities[i].close();
+ } catch (IOException ee) {}
+ }
+ return indexCount;
+ } else {
+ log.logSevere("Index distribution failed. Too few peers (" + hc + ") received the index, not deleted locally.");
+ return -1;
+ }
+ }
+
+ private String selectTransferStart() {
+ String startPointHash;
+ // first try to select with increasing probality a good start point
+ if (Math.round(Math.random() * 6) != 4) for (int i = 9; i > 0; i--) {
+ startPointHash = serverCodings.encodeMD5B64(Long.toString(i + System.currentTimeMillis()), true).substring(2, 2 + yacySeedDB.commonHashLength);
+ if (yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, startPointHash) > ((double) i / (double) 10)) return startPointHash;
+ }
+ // if that fails, take simply the best start point (this is usually avoided, since that leads to always the same target peers)
+ startPointHash = yacyCore.seedDB.mySeed.hash.substring(0, 11) + "z";
+ return startPointHash;
+ }
+
+ Object[] /* of {plasmaWordIndexEntity[], HashMap(String, plasmaCrawlLURL.Entry)}*/
+ selectTransferIndexes(String hash, int count, int maxOpenFiles) {
+ // the hash is a start hash from where the indexes are picked
+ ArrayList tmpEntities = new ArrayList(count);
+ String nexthash = "";
+ try {
+ int currOpenFiles = 0;
+ Iterator wordHashIterator = this.wordIndex.wordHashes(hash, true, true);
+ plasmaWordIndexEntity indexEntity, tmpEntity;
+ Iterator urlIter;
+ Iterator hashIter;
+ plasmaWordIndexEntry indexEntry;
+ plasmaCrawlLURL.Entry lurl;
+ final HashSet unknownURLEntries = new HashSet();
+ final HashMap knownURLs = new HashMap();
+ while (
+ (count > 0) &&
+ (currOpenFiles < maxOpenFiles) &&
+ (wordHashIterator.hasNext()) &&
+ ((nexthash = (String) wordHashIterator.next()) != null) &&
+ (nexthash.trim().length() > 0)
+ ) {
+ indexEntity = this.wordIndex.getEntity(nexthash, true, -1);
+ if (indexEntity.size() == 0) {
+ indexEntity.deleteComplete();
+ } else if ((indexEntity.size() <= count)|| // if we havn't exceeded the limit
+ (Math.abs(indexEntity.size() - count) <= 10)){ // or there are only at most 10 entries left
+ // take the whole entity
+ try {
+ // fist check if we know all urls
+ urlIter = indexEntity.elements(true);
+ unknownURLEntries.clear();
+ while (urlIter.hasNext()) {
+ indexEntry = (plasmaWordIndexEntry) urlIter.next();
+ lurl = this.urlPool.loadedURL.getEntry(indexEntry.getUrlHash());
+ if ((lurl == null) || (lurl.toString() == null)) {
+ unknownURLEntries.add(indexEntry.getUrlHash());
+ } else {
+ if (lurl.toString() == null) {
+ this.urlPool.loadedURL.remove(indexEntry.getUrlHash());
+ unknownURLEntries.add(indexEntry.getUrlHash());
+ } else {
+ knownURLs.put(indexEntry.getUrlHash(), lurl);
+ }
+ }
+ }
+ // now delete all entries that have no url entry
+ hashIter = unknownURLEntries.iterator();
+ while (hashIter.hasNext()) {
+ indexEntity.removeEntry((String) hashIter.next(), false);
+ }
+
+ if (indexEntity.size() == 0) {
+ indexEntity.deleteComplete();
+ } else {
+ // use whats remaining
+ tmpEntities.add(indexEntity);
+ this.log.logFine("Selected whole index (" + indexEntity.size() + " URLs, " + unknownURLEntries.size() + " not bound) for word " + indexEntity.wordHash());
+ count -= indexEntity.size();
+ currOpenFiles++;
+ }
+ } catch (kelondroException e) {
+ this.log.logSevere("plasmaWordIndexDistribution/1: deleted DB for word " + indexEntity.wordHash(), e);
+ indexEntity.deleteComplete();
+ }
+ } else {
+ // make an on-the-fly entity and insert values
+ tmpEntity = new plasmaWordIndexEntity(indexEntity.wordHash());
+ try {
+ urlIter = indexEntity.elements(true);
+ unknownURLEntries.clear();
+ while ((urlIter.hasNext()) && (count > 0)) {
+ indexEntry = (plasmaWordIndexEntry) urlIter.next();
+ lurl = this.urlPool.loadedURL.getEntry(indexEntry.getUrlHash());
+ if (lurl == null) {
+ unknownURLEntries.add(indexEntry.getUrlHash());
+ } else {
+ if (lurl.toString() == null) {
+ this.urlPool.loadedURL.remove(indexEntry.getUrlHash());
+ unknownURLEntries.add(indexEntry.getUrlHash());
+ } else {
+ knownURLs.put(indexEntry.getUrlHash(), lurl);
+ tmpEntity.addEntry(indexEntry);
+ count--;
+ }
+ }
+ }
+ // now delete all entries that have no url entry
+ hashIter = unknownURLEntries.iterator();
+ while (hashIter.hasNext()) {
+ indexEntity.removeEntry((String) hashIter.next(), true);
+ }
+ // use whats remaining
+ this.log.logFine("Selected partial index (" + tmpEntity.size() + " from " + indexEntity.size() +" URLs, " + unknownURLEntries.size() + " not bound) for word " + tmpEntity.wordHash());
+ tmpEntities.add(tmpEntity);
+ } catch (kelondroException e) {
+ this.log.logSevere("plasmaWordIndexDistribution/2: deleted DB for word " + indexEntity.wordHash(), e);
+ indexEntity.deleteComplete();
+ }
+ indexEntity.close(); // important: is not closed elswhere and cannot be deleted afterwards
+ indexEntity = null;
+ }
+
+ }
+ // transfer to array
+ plasmaWordIndexEntity[] indexEntities = (plasmaWordIndexEntity[]) tmpEntities.toArray(new plasmaWordIndexEntity[tmpEntities.size()]);
+ return new Object[]{indexEntities, knownURLs, new Integer(currOpenFiles)};
+ } catch (IOException e) {
+ this.log.logSevere("selectTransferIndexes IO-Error (hash=" + nexthash + "): " + e.getMessage(), e);
+ return new Object[]{new plasmaWordIndexEntity[0], new HashMap(0)};
+ } catch (kelondroException e) {
+ this.log.logSevere("selectTransferIndexes database corrupted: " + e.getMessage(), e);
+ return new Object[]{new plasmaWordIndexEntity[0], new HashMap(0)};
+ }
+ }
+
+ boolean deleteTransferIndexes(plasmaWordIndexEntity[] indexEntities) throws IOException {
+ String wordhash;
+ Iterator urlIter;
+ plasmaWordIndexEntry indexEntry;
+ plasmaWordIndexEntity indexEntity;
+ String[] urlHashes;
+ int sz;
+ boolean success = true;
+ for (int i = 0; i < indexEntities.length; i++) {
+ if (indexEntities[i].isTMPEntity()) {
+ // delete entries separately
+ int c = 0;
+ urlHashes = new String[indexEntities[i].size()];
+ urlIter = indexEntities[i].elements(true);
+ while (urlIter.hasNext()) {
+ indexEntry = (plasmaWordIndexEntry) urlIter.next();
+ urlHashes[c++] = indexEntry.getUrlHash();
+ }
+ wordIndex.removeEntries(indexEntities[i].wordHash(), urlHashes, true);
+ indexEntity = wordIndex.getEntity(indexEntities[i].wordHash(), true, -1);
+ sz = indexEntity.size();
+ indexEntity.close();
+ log.logFine("Deleted partial index (" + c + " URLs) for word " + indexEntities[i].wordHash() + "; " + sz + " entries left");
+ // DEBUG: now try to delete the remaining index. If this works, this routine is fine
+ /*
+ if (wordIndex.getEntity(indexEntities[i].wordHash()).deleteComplete())
+ System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " SUCCESSFULL");
+ else
+ System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " FAILED");
+ */
+ // end debug
+ indexEntities[i].close();
+ } else {
+ // delete complete file
+ if (indexEntities[i].deleteComplete()) {
+ indexEntities[i].close();
+ } else {
+ indexEntities[i].close();
+ // have another try...
+ if (!(plasmaWordIndexEntity.wordHash2path(wordIndex.getRoot() /*PLASMADB*/, indexEntities[i].wordHash()).delete())) {
+ success = false;
+ log.logSevere("Could not delete whole index for word " + indexEntities[i].wordHash());
+ }
+ }
+ }
+ indexEntities[i] = null;
+ }
+ return success;
+ }
+
+ public void startTransferWholeIndex(yacySeed seed, boolean delete) {
+ if (transferIdxThread == null) {
+ this.transferIdxThread = new transferIndexThread(seed,delete);
+ this.transferIdxThread.start();
+ }
+ }
+
+ public void stopTransferWholeIndex(boolean wait) {
+ if ((transferIdxThread != null) && (transferIdxThread.isAlive()) && (!transferIdxThread.isFinished())) {
+ try {
+ this.transferIdxThread.stopIt(wait);
+ } catch (InterruptedException e) { }
+ }
+ }
+
+ public void abortTransferWholeIndex(boolean wait) {
+ if (transferIdxThread != null) {
+ if (!transferIdxThread.isFinished())
+ try {
+ this.transferIdxThread.stopIt(wait);
+ } catch (InterruptedException e) { }
+ transferIdxThread = null;
+ }
+ }
+
+ private class transferIndexWorkerThread extends Thread{
+ // connection properties
+ private boolean gzipBody = false;
+ private int timeout = 60000;
+
+ // status fields
+ private boolean finished = false;
+ boolean success = false;
+ private String status = "running";
+ private long iteration = 0;
+ private long transferTime = 0;
+ private int idxCount = 0;
+ private int chunkSize = 0;
+
+ // delivery destination
+ yacySeed seed = null;
+
+ // word chunk
+ private String endPointHash;
+ private String startPointHash;
+ plasmaWordIndexEntity[] indexEntities;
+
+ // other fields
+ HashMap urlCache;
+
+ public transferIndexWorkerThread(
+ yacySeed seed,
+ plasmaWordIndexEntity[] indexEntities,
+ HashMap urlCache,
+ boolean gzipBody,
+ int timeout,
+ long iteration,
+ int idxCount,
+ int chunkSize,
+ String endPointHash,
+ String startPointHash) {
+ super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndexWorker_" + seed.getName());
+ this.gzipBody = gzipBody;
+ this.timeout = timeout;
+ this.iteration = iteration;
+ this.seed = seed;
+ this.indexEntities = indexEntities;
+ this.urlCache = urlCache;
+ this.idxCount = idxCount;
+ this.chunkSize = chunkSize;
+ this.startPointHash = startPointHash;
+ this.endPointHash = endPointHash;
+ }
+
+ public void run() {
+ try {
+ uploadIndex();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } finally {
+
+ }
+ }
+
+ public boolean success() {
+ return this.success;
+ }
+
+ public int getChunkSize() {
+ return this.chunkSize;
+ }
+
+ public String getStatus() {
+ return this.status;
+ }
+
+ private boolean isAborted() {
+ if (finished || Thread.currentThread().isInterrupted()) {
+ return true;
+ }
+ return false;
+ }
+
+ public void stopIt() {
+ this.finished = true;
+ }
+
+ public String getRange() {
+ return "[" + startPointHash + ".." + endPointHash + "]";
+ }
+
+ public long getTransferTime() {
+ return this.transferTime;
+ }
+
+ private void uploadIndex() throws InterruptedException {
+
+ /* loop until we
+ * - have successfully transfered the words list or
+ * - the retry counter limit was exceeded
+ */
+ long retryCount = 0, start = System.currentTimeMillis();
+ while (true) {
+ // testing if we wer aborted
+ if (isAborted()) return;
+
+ // transfering seleted words to remote peer
+ this.status = "Running: Transfering chunk " + iteration;
+ String error = yacyClient.transferIndex(seed, indexEntities, urlCache, this.gzipBody, this.timeout);
+ if (error == null) {
+ // words successfully transfered
+ transferTime = System.currentTimeMillis() - start;
+ plasmaWordIndexDistribution.this.log.logInfo("Index transfer of " + idxCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]" +
+ " to peer " + seed.getName() + ":" + seed.hash + " in " + (transferTime/1000) + " seconds successfull (" +
+ (1000 * idxCount / (transferTime + 1)) + " words/s)");
+ retryCount = 0;
+
+// if (transferTime > 30000) {
+// if (chunkSize>100) chunkSize-=50;
+// } else {
+// chunkSize+=50;
+// }
+ this.success = true;
+ this.status = "Finished: Transfer of chunk " + iteration;
+ break;
+ } else {
+ // worts transfer failed
+
+ // inc retry counter
+ retryCount++;
+
+ // testing if we were aborted ...
+ if (isAborted()) return;
+
+ // we have lost the connection to the remote peer. Adding peer to disconnected list
+ plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + error + "', disconnecting peer");
+ yacyCore.peerActions.peerDeparture(seed);
+
+ // if the retry counter limit was not exceeded we'll retry it in a few seconds
+ this.status = "Disconnected peer: " + ((retryCount > 5)? error + ". Transfer aborted":"Retry " + retryCount);
+ if (retryCount > 5) return;
+ Thread.sleep(retryCount*5000);
+
+ /* loop until
+ * - we have successfully done a peer ping or
+ * - the retry counter limit was exceeded
+ */
+ while (true) {
+ // testing if we were aborted ...
+ if (isAborted()) return;
+
+ // doing a peer ping to the remote seed
+ int added = yacyClient.publishMySeed(seed.getAddress(), seed.hash);
+ if (added < 0) {
+ // inc. retry counter
+ retryCount++;
+ this.status = "Disconnected peer: Peer ping failed. " + ((retryCount > 5)?"Transfer aborted.":"Retry " + retryCount);
+ if (retryCount > 5) return;
+ Thread.sleep(retryCount*5000);
+ continue;
+ } else {
+ yacyCore.seedDB.getConnected(seed.hash);
+ this.status = "running";
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ public class transferIndexThread extends Thread {
+ private yacySeed seed = null;
+ private boolean delete = false;
+ private boolean finished = false;
+ private boolean gzipBody = false;
+ private int timeout = 60000;
+ private int maxOpenFiles = 800;
+ private int transferedIndexCount = 0;
+ private String status = "Running";
+ private String oldStartingPointHash = "------------", startPointHash = "------------";
+ private int wordsDBSize = 0;
+ private int chunkSize = 500;
+ private final long startingTime = System.currentTimeMillis();
+ private final plasmaSwitchboard sb;
+ private final Runtime rt = Runtime.getRuntime();
+ transferIndexWorkerThread worker = null;
+
+ public transferIndexThread(yacySeed seed, boolean delete) {
+ super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndex_" + seed.getName());
+ this.seed = seed;
+ this.delete = delete;
+ this.sb = plasmaSwitchboard.getSwitchboard();
+ this.wordsDBSize = sb.wordIndex.size();
+ this.gzipBody = "true".equalsIgnoreCase(sb.getConfig("indexTransfer.gzipBody","false"));
+ this.timeout = (int) sb.getConfigLong("indexTransfer.timeout",60000);
+ this.maxOpenFiles = (int) sb.getConfigLong("indexTransfer.maxOpenFiles",800);
+ }
+
+ public void run() {
+ performTransferWholeIndex();
+ }
+
+ public void stopIt(boolean wait) throws InterruptedException {
+ this.finished = true;
+ this.join();
+ }
+
+ public boolean isFinished() {
+ return this.finished;
+ }
+
+ public boolean deleteIndex() {
+ return this.delete;
+ }
+
+ public int[] getChunkSize() {
+ transferIndexWorkerThread workerThread = this.worker;
+ if (workerThread != null) {
+ return new int[]{this.chunkSize,workerThread.getChunkSize()};
+ }
+ return new int[]{this.chunkSize,500};
+ }
+
+ public int getTransferedIndexCount() {
+ return this.transferedIndexCount;
+ }
+
+ public float getTransferedIndexPercent() {
+ if (wordsDBSize == 0) return 100;
+ else return (float)(this.transferedIndexCount*100/wordsDBSize);
+ }
+
+ public int getTransferedIndexSpeed() {
+ return (int) ((1000 * transferedIndexCount) / (System.currentTimeMillis()-startingTime));
+ }
+
+ public yacySeed getSeed() {
+ return this.seed;
+ }
+
+ public String[] getStatus() {
+ transferIndexWorkerThread workerThread = this.worker;
+ if (workerThread != null) {
+ return new String[]{this.status,workerThread.getStatus()};
+ }
+ return new String[]{this.status,"Not running"};
+ }
+
+ public String[] getRange() {
+ transferIndexWorkerThread workerThread = this.worker;
+ if (workerThread != null) {
+ return new String[]{"[" + oldStartingPointHash + ".." + startPointHash + "]",workerThread.getRange()};
+ }
+ return new String[]{"[" + oldStartingPointHash + ".." + startPointHash + "]","[------------..------------]"};
+ }
+
+ public void performTransferWholeIndex() {
+ plasmaWordIndexEntity[] newIndexEntities = null, oldIndexEntities = null;
+ try {
+ // pausing the regular index distribution
+ // TODO: adding sync, to wait for a still running index distribution to finish
+ plasmaWordIndexDistribution.this.paused = true;
+
+ // initial startingpoint of intex transfer is "------------"
+ plasmaWordIndexDistribution.this.log.logFine("Selected hash " + startPointHash + " as start point for index distribution of whole index");
+
+ /* Loop until we have
+ * - finished transfer of whole index
+ * - detected a server shutdown or user interruption
+ * - detected a failure
+ */
+ long selectionStart = System.currentTimeMillis(), selectionEnd = 0, selectionTime = 0, iteration = 0;
+
+ Integer openedFiles = new Integer(0);
+ while (!finished && !Thread.currentThread().isInterrupted()) {
+ iteration++;
+ int idxCount = 0;
+ selectionStart = System.currentTimeMillis();
+ oldIndexEntities = newIndexEntities;
+
+ // selecting 500 words to transfer
+ this.status = "Running: Selecting chunk " + iteration;
+ Object[] selectResult = selectTransferIndexes(this.startPointHash, this.chunkSize, this.maxOpenFiles-openedFiles.intValue());
+ newIndexEntities = (plasmaWordIndexEntity[]) selectResult[0];
+ HashMap urlCache = (HashMap) selectResult[1]; // String (url-hash) / plasmaCrawlLURL.Entry
+ openedFiles = (Integer) selectResult[2];
+
+ /* If we havn't selected a word chunk this could be because of
+ * a) no words are left in the index
+ * b) max open file limit was exceeded
+ */
+ if ((newIndexEntities == null) || (newIndexEntities.length == 0)) {
+ if (sb.wordIndex.size() > 0) {
+ // if there are still words in the index we try it again now
+ startPointHash = "------------";
+ } else {
+ // otherwise we could end transfer now
+ plasmaWordIndexDistribution.this.log.logFine("No index available for index transfer, hash start-point " + startPointHash);
+ this.status = "Finished. " + iteration + " chunks transfered.";
+ finished = true;
+ }
+ } else {
+ // count the indexes again, can be smaller as expected
+ for (int i = 0; i < newIndexEntities.length; i++) idxCount += newIndexEntities[i].size();
+
+ // getting start point for next DHT-selection
+ oldStartingPointHash = startPointHash;
+ startPointHash = newIndexEntities[newIndexEntities.length - 1].wordHash(); // DHT targets must have greater hashes
+
+ selectionEnd = System.currentTimeMillis();
+ selectionTime = selectionEnd - selectionStart;
+ plasmaWordIndexDistribution.this.log.logInfo("Index selection of " + idxCount + " words [" + newIndexEntities[0].wordHash() + " .. " + newIndexEntities[newIndexEntities.length-1].wordHash() + "]" +
+ " in " +
+ (selectionTime / 1000) + " seconds (" +
+ (1000 * idxCount / (selectionTime+1)) + " words/s)");
+ }
+
+ // query status of old worker thread
+ if (worker != null) {
+ this.status = "Finished: Selecting chunk " + iteration;
+ worker.join();
+ if (!worker.success) {
+ // if the transfer failed we abort index transfer now
+ this.status = "Aborted because of Transfer error:\n" + worker.getStatus();
+
+ // cleanup. closing all open files
+ closeEntities(oldIndexEntities);
+ oldIndexEntities = null;
+ closeEntities(newIndexEntities);
+ newIndexEntities = null;
+
+ // abort index transfer
+ return;
+ } else {
+ /*
+ * If index transfer was done successfully we close all remaining open
+ * files that belong to the old index chunk and handover a new chunk
+ * to the transfer thread.
+ * Addintionally we recalculate the chunk size to optimize performance
+ */
+
+ this.chunkSize = worker.getChunkSize();
+ long transferTime = worker.getTransferTime();
+ //TODO: only increase chunk Size if there is free memory left on the server
+
+ // we need aprox. 73Byte per IndexEntity and an average URL length of 32 char
+ //if (ft.freeMemory() < 73*2*100)
+ if (transferTime > 60*1000) {
+ if (chunkSize>200) chunkSize-=100;
+ } else if (selectionTime < transferTime){
+ this.chunkSize +=100;
+ //chunkSize+=50;
+ } else if (selectionTime >= selectionTime){
+ if (chunkSize>200) chunkSize-=100;
+ }
+
+ selectionStart = System.currentTimeMillis();
+
+ // deleting transfered words from index
+ if (delete) {
+ this.status = "Running: Deleting chunk " + iteration;
+ try {
+ if (deleteTransferIndexes(oldIndexEntities)) {
+ plasmaWordIndexDistribution.this.log.logFine("Deleted all " + oldIndexEntities.length + " transferred whole-word indexes locally");
+ transferedIndexCount += idxCount;
+ } else {
+ plasmaWordIndexDistribution.this.log.logSevere("Deleted not all transferred whole-word indexes");
+ }
+ } catch (IOException ee) {
+ plasmaWordIndexDistribution.this.log.logSevere("Deletion of indexes not possible:" + ee.getMessage(), ee);
+ }
+ } else {
+ this.closeEntities(oldIndexEntities);
+ transferedIndexCount += idxCount;
+ }
+ oldIndexEntities = null;
+ }
+ this.worker = null;
+ }
+
+ // handover chunk to transfer worker
+ if (!((newIndexEntities == null) || (newIndexEntities.length == 0))) {
+ worker = new transferIndexWorkerThread(seed,newIndexEntities,urlCache,gzipBody,timeout,iteration,idxCount,idxCount,startPointHash,oldStartingPointHash);
+ worker.start();
+ }
+ }
+
+ // if we reach this point we were aborted by the user or by server shutdown
+ if (sb.wordIndex.size() > 0) this.status = "aborted";
+ } catch (Exception e) {
+ this.status = "Error: " + e.getMessage();
+ plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + e.getMessage() + "'",e);
+
+ } finally {
+ if (worker != null) {
+ worker.stopIt();
+ try {worker.join();}catch(Exception e){}
+ // worker = null;
+ }
+ if (oldIndexEntities != null) closeEntities(oldIndexEntities);
+ if (newIndexEntities != null) closeEntities(newIndexEntities);
+
+ plasmaWordIndexDistribution.this.paused = false;
+ }
+ }
+
+ private void closeEntities(plasmaWordIndexEntity[] indexEntities) {
+ if ((indexEntities == null)||(indexEntities.length ==0)) return;
+
+ for (int i = 0; i < indexEntities.length; i++) try {
+ indexEntities[i].close();
+ } catch (IOException ee) {}
+ }
+
+ private boolean isAborted() {
+ if (finished || Thread.currentThread().isInterrupted()) {
+ this.status = "aborted";
+ return true;
+ }
+ return false;
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaWordIndexEntity.java b/source/de/anomic/plasma/plasmaWordIndexEntity.java
index a1827969f..c3f614451 100644
--- a/source/de/anomic/plasma/plasmaWordIndexEntity.java
+++ b/source/de/anomic/plasma/plasmaWordIndexEntity.java
@@ -4,7 +4,10 @@
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
-// last major change: 21.01.2004
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
//
// 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
@@ -46,7 +49,6 @@ import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.Set;
-
import de.anomic.kelondro.kelondroRecords;
import de.anomic.kelondro.kelondroTree;
import de.anomic.kelondro.kelondroException;
@@ -61,9 +63,9 @@ public final class plasmaWordIndexEntity {
private boolean delete;
public plasmaWordIndexEntity(File databaseRoot, String wordHash, boolean deleteIfEmpty) throws IOException {
- theWordHash = wordHash;
- theIndex = indexFile(databaseRoot, wordHash);
- theTmpMap = null;
+ theWordHash = wordHash;
+ theIndex = indexFile(databaseRoot, wordHash);
+ theTmpMap = null;
delete = deleteIfEmpty;
}
@@ -79,42 +81,42 @@ public final class plasmaWordIndexEntity {
}
return success;
}
-
+
private kelondroTree indexFile(File databaseRoot, String wordHash) throws IOException {
if (wordHash.length() < 12) throw new IOException("word hash wrong: '" + wordHash + "'");
- theLocation = wordHash2path(databaseRoot, wordHash);
- File fp = theLocation.getParentFile();
- if (fp != null) fp.mkdirs();
- kelondroTree kt;
- long cacheSize = theLocation.length();
- if (cacheSize > 1048576) cacheSize = 1048576;
- if (theLocation.exists()) {
- // open existing index file
- kt = new kelondroTree(theLocation, cacheSize);
- } else {
- // create new index file
- kt = new kelondroTree(theLocation, cacheSize, plasmaURL.urlHashLength, plasmaWordIndexEntry.attrSpaceShort);
- }
- return kt; // everyone who get this should close it when finished!
+ theLocation = wordHash2path(databaseRoot, wordHash);
+ File fp = theLocation.getParentFile();
+ if (fp != null) fp.mkdirs();
+ kelondroTree kt;
+ long cacheSize = theLocation.length();
+ if (cacheSize > 1048576) cacheSize = 1048576;
+ if (theLocation.exists()) {
+ // open existing index file
+ kt = new kelondroTree(theLocation, cacheSize);
+ } else {
+ // create new index file
+ kt = new kelondroTree(theLocation, cacheSize, plasmaURL.urlHashLength, plasmaWordIndexEntry.attrSpaceShort);
+ }
+ return kt; // everyone who get this should close it when finished!
}
public static File wordHash2path(File databaseRoot, String hash) {
- // creates a path that constructs hashing on a file system
+ // creates a path that constructs hashing on a file system
return new File (databaseRoot, "WORDS/" +
- hash.substring(0,1) + "/" + hash.substring(1,2) + "/" + hash.substring(2,4) + "/" +
- hash.substring(4,6) + "/" + hash + ".db");
+ hash.substring(0,1) + "/" + hash.substring(1,2) + "/" + hash.substring(2,4) + "/" +
+ hash.substring(4,6) + "/" + hash + ".db");
}
public plasmaWordIndexEntity(String wordHash) {
- // this creates a nameless temporary index. It is needed for combined search
- // and used to hold the intersection of two indexes
+ // this creates a nameless temporary index. It is needed for combined search
+ // and used to hold the intersection of two indexes
// if the nameless intity is suppose to hold indexes for a specific word,
// it can be given here; othervise set wordhash to null
- theWordHash = wordHash;
- theIndex = null;
+ theWordHash = wordHash;
+ theIndex = null;
theLocation = null;
- theTmpMap = new TreeMap();
+ theTmpMap = new TreeMap();
}
public boolean isTMPEntity() {
@@ -126,7 +128,7 @@ public final class plasmaWordIndexEntity {
}
public int size() {
- if (theTmpMap == null) {
+ if (theTmpMap == null) {
int size = theIndex.size();
if ((size == 0) && (delete)) {
deleteComplete();
@@ -140,16 +142,16 @@ public final class plasmaWordIndexEntity {
}
public void close() throws IOException {
- if (theTmpMap == null) {
+ if (theTmpMap == null) {
if (theIndex != null) theIndex.close();
theIndex = null;
} else theTmpMap = null;
}
public void finalize() {
- try {
- close();
- } catch (IOException e) {}
+ try {
+ close();
+ } catch (IOException e) {}
}
public boolean contains(String urlhash) throws IOException {
@@ -162,16 +164,16 @@ public final class plasmaWordIndexEntity {
public boolean addEntry(plasmaWordIndexEntry entry) throws IOException {
if (entry == null) return false;
- if (theTmpMap == null) {
- return (theIndex.put(entry.getUrlHash().getBytes(), entry.toEncodedForm(false).getBytes()) == null);
- } else {
- return (theTmpMap.put(entry.getUrlHash(), entry) == null);
- }
+ if (theTmpMap == null) {
+ return (theIndex.put(entry.getUrlHash().getBytes(), entry.toEncodedForm(false).getBytes()) == null);
+ } else {
+ return (theTmpMap.put(entry.getUrlHash(), entry) == null);
+ }
}
public int addEntries(plasmaWordIndexEntryContainer container) throws IOException {
- //System.out.println("* adding " + newEntries.size() + " cached word index entries for word " + wordHash); // debug
- // fetch the index cache
+ //System.out.println("* adding " + newEntries.size() + " cached word index entries for word " + wordHash); // debug
+ // fetch the index cache
if ((container == null) || (container.size() == 0)) return 0;
// open file
@@ -212,7 +214,7 @@ public final class plasmaWordIndexEntity {
} else {
theTmpMap = new TreeMap();
return true;
- }
+ }
}
public boolean removeEntry(String urlHash, boolean deleteComplete) throws IOException {
@@ -223,19 +225,19 @@ public final class plasmaWordIndexEntity {
boolean wasEntry = (theIndex.remove(urlHash.getBytes()) != null);
if ((theIndex.size() == 0) && (deleteComplete)) deleteComplete();
return wasEntry;
- } else {
+ } else {
return (theTmpMap.remove(urlHash) != null);
- }
+ }
}
public Iterator elements(boolean up) {
- // returns an enumeration of plasmaWordIndexEntry objects
- if (theTmpMap == null) return new dbenum(up); else return new tmpenum(up);
+ // returns an enumeration of plasmaWordIndexEntry objects
+ if (theTmpMap == null) return new dbenum(up); else return new tmpenum(up);
}
public final class dbenum implements Iterator {
- Iterator i;
- public dbenum(boolean up) {
+ Iterator i;
+ public dbenum(boolean up) {
try {
i = theIndex.nodeIterator(up, false);
} catch (kelondroException e) {
@@ -243,48 +245,48 @@ public final class plasmaWordIndexEntity {
theIndex.file().delete();
i = null;
}
- }
- public boolean hasNext() {
- return (i != null) && (i.hasNext());
- }
- public Object next() {
+ }
+ public boolean hasNext() {
+ return (i != null) && (i.hasNext());
+ }
+ public Object next() {
if (i == null) return null;
- try {
- byte[][] n = ((kelondroRecords.Node) i.next()).getValues();
- return new plasmaWordIndexEntry(new String(n[0]), new String(n[1]));
- } catch (IOException e) {
+ try {
+ byte[][] n = ((kelondroRecords.Node) i.next()).getValues();
+ return new plasmaWordIndexEntry(new String(n[0]), new String(n[1]));
+ } catch (IOException e) {
i = null;
- throw new RuntimeException("dbenum: " + e.getMessage());
- }
- }
+ throw new RuntimeException("dbenum: " + e.getMessage());
+ }
+ }
public void remove() {
throw new UnsupportedOperationException();
}
}
public final class tmpenum implements Iterator {
- final TreeMap searchTree;
+ final TreeMap searchTree;
boolean up;
- public tmpenum(boolean up) {
+ public tmpenum(boolean up) {
this.up = up;
searchTree = (TreeMap) theTmpMap.clone(); // a shallow clone that is destroyed during search
- }
- public boolean hasNext() {
- return searchTree.size() > 0;
- }
- public Object next() {
- Object urlHash = (up) ? searchTree.firstKey() : searchTree.lastKey();
- plasmaWordIndexEntry entry = (plasmaWordIndexEntry) searchTree.remove(urlHash);
- return entry;
- }
+ }
+ public boolean hasNext() {
+ return searchTree.size() > 0;
+ }
+ public Object next() {
+ Object urlHash = (up) ? searchTree.firstKey() : searchTree.lastKey();
+ plasmaWordIndexEntry entry = (plasmaWordIndexEntry) searchTree.remove(urlHash);
+ return entry;
+ }
public void remove() {
throw new UnsupportedOperationException();
}
}
public String toString() {
- if (theTmpMap == null) return "DB:" + theIndex.toString();
- else if (theTmpMap != null) return "MAP:" + theTmpMap.size() + " RECORDS IN " + theTmpMap.toString();
- else return "EMPTY";
+ if (theTmpMap == null) return "DB:" + theIndex.toString();
+ else if (theTmpMap != null) return "MAP:" + theTmpMap.size() + " RECORDS IN " + theTmpMap.toString();
+ else return "EMPTY";
}
// join methods
@@ -341,15 +343,15 @@ public final class plasmaWordIndexEntity {
// take the first element of map which is a result and combine it with result
k = (Long) map.firstKey(); // the next smallest...
time -= (System.currentTimeMillis() - stamp); stamp = System.currentTimeMillis();
- searchA = searchResult;
- searchB = (plasmaWordIndexEntity) map.remove(k);
+ searchA = searchResult;
+ searchB = (plasmaWordIndexEntity) map.remove(k);
searchResult = plasmaWordIndexEntity.joinConstructive(searchA, searchB, 2 * time / (map.size() + 1));
- // close the input files/structures
- if (searchA != searchResult) searchA.close();
- if (searchB != searchResult) searchB.close();
+ // close the input files/structures
+ if (searchA != searchResult) searchA.close();
+ if (searchB != searchResult) searchB.close();
}
searchA = null; // free resources
- searchB = null; // free resources
+ searchB = null; // free resources
// in 'searchResult' is now the combined search result
if (searchResult.size() == 0) return new plasmaWordIndexEntity(null);
@@ -461,5 +463,5 @@ public final class plasmaWordIndexEntity {
}
return conj;
}
-
-}
+
+}
\ No newline at end of file
diff --git a/source/de/anomic/plasma/plasmaWordIndexEntry.java b/source/de/anomic/plasma/plasmaWordIndexEntry.java
index dc5584284..2531b6983 100644
--- a/source/de/anomic/plasma/plasmaWordIndexEntry.java
+++ b/source/de/anomic/plasma/plasmaWordIndexEntry.java
@@ -4,7 +4,10 @@
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
-// last major change: 01.06.2004
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
//
// 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
@@ -47,18 +50,17 @@ package de.anomic.plasma;
import java.net.URL;
import java.util.Properties;
-
import de.anomic.htmlFilter.htmlFilterContentScraper;
import de.anomic.server.serverCodings;
import de.anomic.yacy.yacySeedDB;
// import de.anomic.server.logging.serverLog;
public final class plasmaWordIndexEntry {
-
+
// an wordEntry can be filled in either of two ways:
// by the discrete values of the entry
// or by the encoded entry-string
-
+
// the size of a word hash
public static final int wordHashLength = yacySeedDB.commonHashLength; // 12
public static final int urlHashLength = yacySeedDB.commonHashLength; // 12
@@ -69,7 +71,7 @@ public final class plasmaWordIndexEntry {
// the associated hash
private final String urlHash;
-
+
// discrete values
private int count; // words in file
private int posintext; // first position of the word in text as number of word; 0=unknown or irrelevant position
@@ -100,7 +102,7 @@ public final class plasmaWordIndexEntry {
// create a word hash
public static String word2hash(String word) {
- return serverCodings.encodeMD5B64(word.toLowerCase(), true).substring(0, wordHashLength);
+ return serverCodings.encodeMD5B64(word.toLowerCase(), true).substring(0, wordHashLength);
}
// doctype calculation
@@ -133,7 +135,9 @@ public final class plasmaWordIndexEntry {
char doctype = DT_UNKNOWN;
if (mime == null) doctype = DT_UNKNOWN;
else if (mime.endsWith("/gif")) doctype = DT_IMAGE;
+ else if (mime.endsWith("/jpg")) doctype = DT_IMAGE;
else if (mime.endsWith("/jpeg")) doctype = DT_IMAGE;
+ else if (mime.endsWith("/png")) doctype = DT_IMAGE;
else if (mime.endsWith("/html")) doctype = DT_HTML;
else if (mime.endsWith("/rtf")) doctype = DT_DOC;
else if (mime.endsWith("/pdf")) doctype = DT_PDFPS;
@@ -163,7 +167,7 @@ public final class plasmaWordIndexEntry {
//xhtml = application/xhtml+xml
//xla = application/msexcel
//xls = application/msexcel
- //xsl = application/xml
+ //xsl = application/xml
//xml = application/xml
//Z = application/x-compress
//zip = application/zip
@@ -183,19 +187,19 @@ public final class plasmaWordIndexEntry {
// therefore they are all public
public plasmaWordIndexEntry(String urlHash, int count, int posintext, int posinphrase, int posofphrase, int virtualage, int quality, String language, char doctype, boolean local) {
- // ** hier fehlt noch als Attribut: <Wortposition im Text>, damit 'nearby' getrackt werden kann **
+ // ** hier fehlt noch als Attribut: <Wortposition im Text>, damit 'nearby' getrackt werden kann **
- if ((language == null) || (language.length() != plasmaCrawlLURL.urlLanguageLength)) language = "uk";
- this.urlHash = urlHash;
- this.count = count;
+ if ((language == null) || (language.length() != plasmaCrawlLURL.urlLanguageLength)) language = "uk";
+ this.urlHash = urlHash;
+ this.count = count;
this.posintext = posintext;
this.posinphrase = posinphrase;
this.posofphrase = posofphrase;
- this.age = virtualage;
- this.quality = quality;
- this.language = language.getBytes();
- this.doctype = doctype;
- this.localflag = (local) ? LT_LOCAL : LT_GLOBAL;
+ this.age = virtualage;
+ this.quality = quality;
+ this.language = language.getBytes();
+ this.doctype = doctype;
+ this.localflag = (local) ? LT_LOCAL : LT_GLOBAL;
}
public plasmaWordIndexEntry(String urlHash, String code) {
@@ -233,16 +237,16 @@ public final class plasmaWordIndexEntry {
this.localflag = pr.getProperty("f", ""+LT_LOCAL).charAt(0);
}
- private String b64save(long x, int l) {
- try {
- return serverCodings.enhancedCoder.encodeBase64Long(x, l);
- } catch (Exception e) {
- // if x does not fit into l
- return "________".substring(0, l);
- }
+ private String b64save(long x, int l) {
+ try {
+ return serverCodings.enhancedCoder.encodeBase64Long(x, l);
+ } catch (Exception e) {
+ // if x does not fit into l
+ return "________".substring(0, l);
+ }
}
- public String toEncodedForm(boolean longAttr) {
+ public String toEncodedForm(boolean longAttr) {
// attention: this integrates NOT the URL into the encoding
// if you need a complete dump, use toExternalForm()
StringBuffer buf = new StringBuffer(longAttr?18:12);
@@ -299,19 +303,19 @@ public final class plasmaWordIndexEntry {
}
public String getUrlHash() {
- return urlHash;
+ return urlHash;
}
public int getQuality() {
- return quality;
+ return quality;
}
public int getVirtualAge() {
- return age;
+ return age;
}
public int getCount() {
- return count;
+ return count;
}
public int posintext() {
@@ -327,11 +331,11 @@ public final class plasmaWordIndexEntry {
}
public String getLanguage() {
- return new String(language);
+ return new String(language);
}
public char getType() {
- return doctype;
+ return doctype;
}
public boolean isLocal() {
@@ -339,9 +343,9 @@ public final class plasmaWordIndexEntry {
}
public static void main(String[] args) {
- // outputs the word hash to a given word
- if (args.length != 1) System.exit(0);
- System.out.println("WORDHASH: " + word2hash(args[0]));
+ // outputs the word hash to a given word
+ if (args.length != 1) System.exit(0);
+ System.out.println("WORDHASH: " + word2hash(args[0]));
}
-
-}
+
+}
\ No newline at end of file