Skip to content

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

enhanced crawler a main problem when crawling is long waiting time cuased by crawl-delay values from robots.txt entries. that attribute is not supported by google and interpreted by yandex and bing in different ways. In large crawls there is always one host which blocks the whole crawl with extreme large values. YaCy now still obeys crawl-delay but limits them to 10 seconds. Additionally the blocking logic when loading new robots.txt was analyzed and a deadlock was removed. Furthermore the construction of new queue lists was redesigned and it was ensured that always a large list of different hosts for host-balancing is provided for the loader.

Michael Peter Christene6a87e0426a6
diff --git a/.classpath b/.classpath
index 3f4b3e9bc..36153ff3e 100644
--- a/.classpath
+++ b/.classpath
@@ -9,7 +9,6 @@
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
- <classpathentry kind="lib" path="lib/J7Zip-modified.jar"/>
<classpathentry kind="lib" path="lib/apache-mime4j-0.6.jar"/>
<classpathentry kind="lib" path="lib/avatica-core-1.13.0.jar"/>
<classpathentry kind="lib" path="lib/bcmail-jdk15on-1.60.jar"/>
@@ -128,5 +127,6 @@
<classpathentry kind="src" path="htroot/yacy"/>
<classpathentry kind="src" path="source"/>
<classpathentry kind="src" path="test/java"/>
+ <classpathentry kind="lib" path="lib/J7Zip-modified.jar"/>
<classpathentry kind="output" path="gen"/>
</classpath>
diff --git a/defaults/yacy.init b/defaults/yacy.init
index d35d6de8c..bc1992310 100644
--- a/defaults/yacy.init
+++ b/defaults/yacy.init
@@ -699,12 +699,12 @@ collection=user
50_localcrawl_idlesleep=2000
50_localcrawl_busysleep=10
50_localcrawl_memprereq=25165824
-50_localcrawl_loadprereq=6.0
+50_localcrawl_loadprereq=8.0
50_localcrawl_isPaused=false
55_autocrawl_idlesleep=10000
55_autocrawl_busysleep=10000
55_autocrawl_memprereq=25165824
-55_autocrawl_loadprereq=6.0
+55_autocrawl_loadprereq=8.0
60_remotecrawlloader_idlesleep=4000
60_remotecrawlloader_busysleep=800
60_remotecrawlloader_memprereq=12582912
@@ -740,7 +740,7 @@ collection=user
reindexSolr_idlesleep=1000
reindexSolr_busysleep=1
reindexSolr_memprereq=10485760
-reindexSolr_loadprereq=9.0
+reindexSolr_loadprereq=16.0
# additional attributes:
# performanceIO is a percent-value. a value of 10 means, that 10% of the busysleep time
diff --git a/htroot/Crawler_p.java b/htroot/Crawler_p.java
index 55c417784..27e6b02ef 100644
--- a/htroot/Crawler_p.java
+++ b/htroot/Crawler_p.java
@@ -108,9 +108,9 @@ public class Crawler_p {
prop.put("jsonp-end", "");
}
- Segment segment = sb.index;
- Fulltext fulltext = segment.fulltext();
- String localSolr = "solr/select?core=collection1&q=*:*&start=0&rows=3";
+ final Segment segment = sb.index;
+ final Fulltext fulltext = segment.fulltext();
+ final String localSolr = "solr/select?core=collection1&q=*:*&start=0&rows=3";
String remoteSolr = env.getConfig(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_URL, localSolr);
if (!remoteSolr.endsWith("/")) remoteSolr = remoteSolr + "/";
prop.put("urlpublictextSolrURL", fulltext.connectedLocalSolr() ? localSolr : remoteSolr + "collection1/select?&q=*:*&start=0&rows=3");
@@ -129,11 +129,11 @@ public class Crawler_p {
prop.put("loaderMax", 0);
prop.put("list-loader", 0);
- int coreCrawlJobSize = sb.crawlQueues.coreCrawlJobSize();
- int limitCrawlJobSize = sb.crawlQueues.limitCrawlJobSize();
- int remoteTriggeredCrawlJobSize = sb.crawlQueues.remoteTriggeredCrawlJobSize();
- int noloadCrawlJobSize = sb.crawlQueues.noloadCrawlJobSize();
- int allsize = coreCrawlJobSize + limitCrawlJobSize + remoteTriggeredCrawlJobSize + noloadCrawlJobSize;
+ final int coreCrawlJobSize = sb.crawlQueues.coreCrawlJobSize();
+ final int limitCrawlJobSize = sb.crawlQueues.limitCrawlJobSize();
+ final int remoteTriggeredCrawlJobSize = sb.crawlQueues.remoteTriggeredCrawlJobSize();
+ final int noloadCrawlJobSize = sb.crawlQueues.noloadCrawlJobSize();
+ final int allsize = coreCrawlJobSize + limitCrawlJobSize + remoteTriggeredCrawlJobSize + noloadCrawlJobSize;
prop.put("localCrawlSize", coreCrawlJobSize);
prop.put("localCrawlState", "");
@@ -148,10 +148,10 @@ public class Crawler_p {
prop.put("forwardToCrawlStart", "0");
prop.put("info", "0");
- boolean debug = (post != null && post.containsKey("debug"));
+ final boolean debug = (post != null && post.containsKey("debug"));
if (post != null) {
- String c = post.toString();
+ final String c = post.toString();
if (c.length() < 1000) ConcurrentLog.info("Crawl Start", c);
}
@@ -159,16 +159,16 @@ public class Crawler_p {
// terminate crawls individually
sb.crawlQueues.noticeURL.clear();
for (final byte[] h: sb.crawler.getActive()) {
- CrawlProfile p = sb.crawler.getActive(h);
+ final CrawlProfile p = sb.crawler.getActive(h);
if (CrawlSwitchboard.DEFAULT_PROFILES.contains(p.name())) continue;
if (p != null) sb.crawler.putPassive(h, p);
sb.crawler.removeActive(h);
sb.crawler.removePassive(h);
- try {sb.crawlQueues.noticeURL.removeByProfileHandle(p.handle(), 10000);} catch (SpaceExceededException e) {}
+ try {sb.crawlQueues.noticeURL.removeByProfileHandle(p.handle(), 10000);} catch (final SpaceExceededException e) {}
}
// clear stacks
- for (StackType stackType: StackType.values()) sb.crawlQueues.noticeURL.clear(stackType);
+ for (final StackType stackType: StackType.values()) sb.crawlQueues.noticeURL.clear(stackType);
try { sb.cleanProfiles(); } catch (final InterruptedException e) {/* ignore this */}
// remove pause
@@ -200,7 +200,7 @@ public class Crawler_p {
sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL, "user request in Crawler_p from " + header.refererHost());
}
}
- String queuemessage = sb.getConfig(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL + "_isPaused_cause", "");
+ final String queuemessage = sb.getConfig(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL + "_isPaused_cause", "");
if (queuemessage.length() == 0) {
prop.put("info-queue", 0);
} else {
@@ -263,21 +263,21 @@ public class Crawler_p {
final boolean deleteold = (deleteage && deleteageDate != null) || (restrictedcrawl && post.getBoolean("deleteold"));
final String sitemapURLStr = post.get("sitemapURL","");
- String crawlingStart0 = post.get("crawlingURL","").trim(); // the crawljob start url
- String[] rootURLs0 = crawlingStart0.indexOf('\n') > 0 || crawlingStart0.indexOf('\r') > 0 ? crawlingStart0.split("[\\r\\n]+") : crawlingStart0.split(Pattern.quote("|"));
- Set<DigestURL> rootURLs = new HashSet<DigestURL>();
+ final String crawlingStart0 = post.get("crawlingURL","").trim(); // the crawljob start url
+ final String[] rootURLs0 = crawlingStart0.indexOf('\n') > 0 || crawlingStart0.indexOf('\r') > 0 ? crawlingStart0.split("[\\r\\n]+") : crawlingStart0.split(Pattern.quote("|"));
+ Set<DigestURL> rootURLs = new HashSet<>();
String crawlName = "";
if (crawlingFile == null) {
- StringBuilder crawlNameBuilder = new StringBuilder(); // for large crawl queues this can be pretty large
+ final StringBuilder crawlNameBuilder = new StringBuilder(); // for large crawl queues this can be pretty large
for (String crawlingStart: rootURLs0) {
if (crawlingStart == null || crawlingStart.length() == 0) continue;
// add the prefix http:// if necessary
- int pos = crawlingStart.indexOf("://",0);
+ final int pos = crawlingStart.indexOf("://",0);
if (pos == -1) {
if (crawlingStart.startsWith("ftp")) crawlingStart = "ftp://" + crawlingStart; else crawlingStart = "https://" + crawlingStart; // we default to https instead of http becuase those outnumber http by far
}
try {
- DigestURL crawlingStartURL = new DigestURL(crawlingStart);
+ final DigestURL crawlingStartURL = new DigestURL(crawlingStart);
rootURLs.add(crawlingStartURL);
crawlNameBuilder.append((crawlingStartURL.getHost() == null) ? crawlingStartURL.toNormalform(true) : crawlingStartURL.getHost()).append(',');
if (crawlingStartURL != null && (crawlingStartURL.isFile() || crawlingStartURL.isSMB())) storeHTCache = false;
@@ -292,25 +292,25 @@ public class Crawler_p {
if (crawlName.endsWith(",")) crawlName = crawlName.substring(0, crawlName.length() - 1);
if (crawlName.length() > 64) {
crawlName = "crawl_for_" + rootURLs.size() + "_start_points_" + Integer.toHexString(crawlName.hashCode());
- int p = crawlName.lastIndexOf(',');
+ final int p = crawlName.lastIndexOf(',');
if (p >= 8) crawlName = crawlName.substring(0, p);
}
if (crawlName.length() == 0 && sitemapURLStr.length() > 0) crawlName = "sitemap loader for " + sitemapURLStr;
// in case that a root url has a file protocol, then the site filter does not work, patch that:
if (fullDomain) {
- for (DigestURL u: rootURLs) if (u.isFile()) {fullDomain = false; subPath = true; break;}
+ for (final DigestURL u: rootURLs) if (u.isFile()) {fullDomain = false; subPath = true; break;}
}
// delete old robots entries
- for (DigestURL ru : rootURLs) {
+ for (final DigestURL ru : rootURLs) {
sb.robots.delete(ru);
try {
if (ru.getHost() != null) { // might be null for file://
Cache.delete(RobotsTxt.robotsURL(RobotsTxt.getHostPort(ru)).hash());
}
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
- try {sb.robots.clear();} catch (IOException e) {} // to be safe: clear all.
+ try {sb.robots.clear();} catch (final IOException e) {} // to be safe: clear all.
// set the crawl filter
String ipMustMatch = post.get("ipMustmatch", CrawlProfile.MATCH_ALL_STRING);
@@ -357,13 +357,13 @@ public class Crawler_p {
final int crawlingDomMaxPages = (crawlingDomMaxCheck) ? post.getInt("crawlingDomMaxPages", -1) : -1;
env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages));
- boolean followFrames = "on".equals(post.get("followFrames", "false"));
+ final boolean followFrames = "on".equals(post.get("followFrames", "false"));
env.setConfig("followFrames", followFrames);
- boolean obeyHtmlRobotsNoindex = "on".equals(post.get("obeyHtmlRobotsNoindex", "false"));
+ final boolean obeyHtmlRobotsNoindex = "on".equals(post.get("obeyHtmlRobotsNoindex", "false"));
env.setConfig("obeyHtmlRobotsNoindex", obeyHtmlRobotsNoindex);
- boolean obeyHtmlRobotsNofollow = "on".equals(post.get("obeyHtmlRobotsNofollow", "false"));
+ final boolean obeyHtmlRobotsNofollow = "on".equals(post.get("obeyHtmlRobotsNofollow", "false"));
env.setConfig("obeyHtmlRobotsNofollow", obeyHtmlRobotsNofollow);
final boolean indexText = "on".equals(post.get("indexText", "on"));
@@ -374,8 +374,8 @@ public class Crawler_p {
env.setConfig("storeHTCache", storeHTCache);
- String defaultAgentName = sb.isIntranetMode() ? ClientIdentification.yacyIntranetCrawlerAgentName : ClientIdentification.yacyInternetCrawlerAgentName;
- String agentName = post.get("agentName", defaultAgentName);
+ final String defaultAgentName = sb.isIntranetMode() ? ClientIdentification.yacyIntranetCrawlerAgentName : ClientIdentification.yacyInternetCrawlerAgentName;
+ final String agentName = post.get("agentName", defaultAgentName);
ClientIdentification.Agent agent = ClientIdentification.getAgent(agentName);
if (agent == null) agent = ClientIdentification.getAgent(defaultAgentName);
@@ -398,14 +398,14 @@ public class Crawler_p {
if ("sitelist".equals(crawlingMode)) {
newcrawlingMustNotMatch = CrawlProfile.MATCH_NEVER_STRING;
- Set<DigestURL> newRootURLs = new HashSet<DigestURL>();
- for (DigestURL sitelistURL: rootURLs) {
+ final Set<DigestURL> newRootURLs = new HashSet<>();
+ for (final DigestURL sitelistURL: rootURLs) {
// download document
Document scraper;
try {
scraper = sb.loader.loadDocument(sitelistURL, CacheStrategy.IFFRESH, BlacklistType.CRAWLER, agent);
// get links and generate filter
- for (DigestURL u: scraper.getHyperlinks().keySet()) {
+ for (final DigestURL u: scraper.getHyperlinks().keySet()) {
newRootURLs.add(u);
}
} catch (final IOException e) {
@@ -419,10 +419,10 @@ public class Crawler_p {
// delete all error urls for that domain
// and all urls for that host from the crawl queue
- List<String> deleteIDs = new ArrayList<>();
- Set<String> hosthashes = new HashSet<String>();
+ final List<String> deleteIDs = new ArrayList<>();
+ final Set<String> hosthashes = new HashSet<>();
boolean anysmbftporpdf = false;
- for (DigestURL u : rootURLs) {
+ for (final DigestURL u : rootURLs) {
deleteIDs.add(new String(u.hash()));
hosthashes.add(u.hosthash());
if ("smb.ftp".indexOf(u.getProtocol()) >= 0 || "pdf".equals(MultiProtocolURL.getFileExtension(u.getFileName()))) anysmbftporpdf = true;
@@ -431,7 +431,7 @@ public class Crawler_p {
sb.crawlQueues.removeHosts(hosthashes);
sb.index.fulltext().commit(true);
- boolean crawlingQ = anysmbftporpdf || "on".equals(post.get("crawlingQ", "off")) || "sitemap".equals(crawlingMode);
+ final boolean crawlingQ = anysmbftporpdf || "on".equals(post.get("crawlingQ", "off")) || "sitemap".equals(crawlingMode);
env.setConfig("crawlingQ", crawlingQ);
// compute mustmatch filter according to rootURLs
@@ -445,10 +445,10 @@ public class Crawler_p {
} else if (subPath) {
siteFilter = CrawlProfile.subpathFilter(rootURLs);
if (deleteold) {
- for (DigestURL u: rootURLs) {
+ for (final DigestURL u: rootURLs) {
String basepath = u.toNormalform(true);
- if (!basepath.endsWith("/")) {int p = basepath.lastIndexOf("/"); if (p > 0) basepath = basepath.substring(0, p + 1);}
- int count = sb.index.fulltext().remove(basepath, deleteageDate);
+ if (!basepath.endsWith("/")) {final int p = basepath.lastIndexOf("/"); if (p > 0) basepath = basepath.substring(0, p + 1);}
+ final int count = sb.index.fulltext().remove(basepath, deleteageDate);
if (count > 0) ConcurrentLog.info("Crawler_p", "deleted " + count + " documents for host " + u.getHost());
}
}
@@ -463,9 +463,9 @@ public class Crawler_p {
// check if the crawl filter works correctly
try {
- Pattern mmp = Pattern.compile(newcrawlingMustMatch);
+ final Pattern mmp = Pattern.compile(newcrawlingMustMatch);
int maxcheck = 100;
- for (DigestURL u: rootURLs) {
+ for (final DigestURL u: rootURLs) {
assert mmp.matcher(u.toNormalform(true)).matches() : "pattern " + mmp.toString() + " does not match url " + u.toNormalform(true);
if (maxcheck-- <= 0) break;
}
@@ -486,48 +486,48 @@ public class Crawler_p {
}
}
- String snapshotsMaxDepthString = post.get("snapshotsMaxDepth", "-1");
- int snapshotsMaxDepth = Integer.parseInt(snapshotsMaxDepthString);
- boolean snapshotsLoadImage = post.getBoolean("snapshotsLoadImage");
- boolean snapshotsReplaceOld = post.getBoolean("snapshotsReplaceOld");
- String snapshotsMustnotmatch = post.get("snapshotsMustnotmatch", "");
+ final String snapshotsMaxDepthString = post.get("snapshotsMaxDepth", "-1");
+ final int snapshotsMaxDepth = Integer.parseInt(snapshotsMaxDepthString);
+ final boolean snapshotsLoadImage = post.getBoolean("snapshotsLoadImage");
+ final boolean snapshotsReplaceOld = post.getBoolean("snapshotsReplaceOld");
+ final String snapshotsMustnotmatch = post.get("snapshotsMustnotmatch", "");
- String ignoreclassname_s = post.get("ignoreclassname");
- Set<String> ignoreclassname = new HashSet<>();
+ final String ignoreclassname_s = post.get("ignoreclassname");
+ final Set<String> ignoreclassname = new HashSet<>();
if (ignoreclassname_s != null) {
- String[] ignoreclassname_a = ignoreclassname_s.trim().split(",");
+ final String[] ignoreclassname_a = ignoreclassname_s.trim().split(",");
for (int i = 0; i < ignoreclassname_a.length; i++) {
ignoreclassname.add(ignoreclassname_a[i].trim());
}
}
// get vocabulary scraper info
- JSONObject vocabulary_scraper = new JSONObject(); // key = vocabulary_name, value = properties with key = type (i.e. 'class') and value = keyword in context
- for (String key: post.keySet()) {
+ final JSONObject vocabulary_scraper = new JSONObject(); // key = vocabulary_name, value = properties with key = type (i.e. 'class') and value = keyword in context
+ for (final String key: post.keySet()) {
if (key.startsWith("vocabulary_")) {
if (key.endsWith("_class")) {
- String vocabulary = key.substring(11, key.length() - 6);
- String value = post.get(key);
+ final String vocabulary = key.substring(11, key.length() - 6);
+ final String value = post.get(key);
if (value != null && value.length() > 0) {
JSONObject props;
try {
props = vocabulary_scraper.getJSONObject(vocabulary);
- } catch (JSONException e) {
+ } catch (final JSONException e) {
props = new JSONObject();
try {
vocabulary_scraper.put(vocabulary, props);
- } catch (JSONException ee) {}
+ } catch (final JSONException ee) {}
}
try {
props.put("class", value);
- } catch (JSONException e) {
+ } catch (final JSONException e) {
}
}
}
}
}
- int timezoneOffset = post.getInt("timezoneOffset", 0);
+ final int timezoneOffset = post.getInt("timezoneOffset", 0);
// in case that we crawl from a file, load that file and re-compute mustmatch pattern
List<AnchorURL> hyperlinks_from_file = null;
@@ -670,8 +670,8 @@ public class Crawler_p {
if ("url".equals(crawlingMode)) {
// stack requests
sb.crawler.putActive(handle, profile);
- final Set<DigestURL> successurls = new HashSet<DigestURL>();
- final Map<DigestURL,String> failurls = new HashMap<DigestURL, String>();
+ final Set<DigestURL> successurls = new HashSet<>();
+ final Map<DigestURL,String> failurls = new HashMap<>();
sb.stackURLs(rootURLs, profile, successurls, failurls);
if (failurls.size() == 0) {
@@ -681,7 +681,7 @@ public class Crawler_p {
// generate a YaCyNews if the global flag was set
if (!sb.isRobinsonMode() && crawlOrder) {
- final Map<String, String> m = new HashMap<String, String>(profile); // must be cloned
+ final Map<String, String> m = new HashMap<>(profile); // must be cloned
m.remove("specificDepth");
m.remove("indexText");
m.remove("indexMedia");
@@ -700,8 +700,8 @@ public class Crawler_p {
sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), NewsPool.CATEGORY_CRAWL_START, m);
}
} else {
- StringBuilder fr = new StringBuilder();
- for (Map.Entry<DigestURL, String> failure: failurls.entrySet()) {
+ final StringBuilder fr = new StringBuilder();
+ for (final Map.Entry<DigestURL, String> failure: failurls.entrySet()) {
sb.crawlQueues.errorURL.push(failure.getKey(), 0, null, FailCategory.FINAL_LOAD_CONTEXT, failure.getValue(), -1);
fr.append(failure.getValue()).append('/');
}
@@ -743,7 +743,7 @@ public class Crawler_p {
final String crawlingFileContent = post.get("crawlingFile$file", "");
final ContentScraper scraper = new ContentScraper(new DigestURL(crawlingFile), 10000000,
new HashSet<String>(), new VocabularyScraper(), profile.timezoneOffset());
- FileCrawlStarterTask crawlStarterTask = new FileCrawlStarterTask(crawlingFile, crawlingFileContent, scraper, profile,
+ final FileCrawlStarterTask crawlStarterTask = new FileCrawlStarterTask(crawlingFile, crawlingFileContent, scraper, profile,
sb.crawlStacker, sb.peers.mySeed().hash.getBytes());
sb.crawler.putActive(handle, profile);
crawlStarterTask.start();
@@ -805,8 +805,8 @@ public class Crawler_p {
thread.setIdleSleep(2000);
}
- float latencyFactor = post.getFloat("latencyFactor", 0.5f);
- int MaxSameHostInQueue = post.getInt("MaxSameHostInQueue", 20);
+ final float latencyFactor = post.getFloat("latencyFactor", 0.5f);
+ final int MaxSameHostInQueue = post.getInt("MaxSameHostInQueue", 20);
env.setConfig(SwitchboardConstants.CRAWLER_LATENCY_FACTOR, latencyFactor);
env.setConfig(SwitchboardConstants.CRAWLER_MAX_SAME_HOST_IN_QUEUE, MaxSameHostInQueue);
}
@@ -831,7 +831,7 @@ public class Crawler_p {
profile.putProfileEntry("crawlProfilesShow_list_", prop, true, dark, count, domlistlength);
prop.put("crawlProfilesShow_list_" + count + "_debug", debug ? 1 : 0);
if (debug) {
- RowHandleSet urlhashes = sb.crawler.getURLHashes(h);
+ final RowHandleSet urlhashes = sb.crawler.getURLHashes(h);
prop.put("crawlProfilesShow_list_" + count + "_debug_count", urlhashes == null ? "unknown" : Integer.toString(urlhashes.size()));
}
hosts = hosts + "," + profile.name();
@@ -851,15 +851,15 @@ public class Crawler_p {
}
if (count > 0 && sb.getConfigBool(SwitchboardConstants.DECORATION_GRAFICS_LINKSTRUCTURE, true)) {
// collect the host names for 'wide' crawls which can be visualized
- boolean showLinkstructure = hosts.length() > 0 && !hosts.contains("file:");
+ final boolean showLinkstructure = hosts.length() > 0 && !hosts.contains("file:");
if (showLinkstructure) {
- StringBuilder q = new StringBuilder();
+ final StringBuilder q = new StringBuilder();
hosts = hosts.substring(1);
q.append(CollectionSchema.host_s.getSolrFieldName()).append(':').append(hosts).append(" OR ").append(CollectionSchema.host_s.getSolrFieldName()).append(':').append("www.").append(hosts);
try {
prop.put("crawlProfilesShow_linkstructure", count == 1 && sb.index.fulltext().getDefaultConnector().getCountByQuery(q.toString()) > 0 ? 1 : 2);
prop.put("crawlProfilesShow_linkstructure_hosts", hosts);
- } catch (IOException e) {
+ } catch (final IOException e) {
}
}
}
@@ -905,7 +905,7 @@ public class Crawler_p {
if(inStream != null) {
try {
inStream.close();
- } catch(IOException ignoredException) {
+ } catch(final IOException ignoredException) {
ConcurrentLog.info("Crawler_p", "Could not close crawlingFile : " + crawlingFile.getAbsolutePath());
}
}
diff --git a/source/net/yacy/cora/federate/FederateSearchManager.java b/source/net/yacy/cora/federate/FederateSearchManager.java
index 3bca68f02..7a0557d04 100644
--- a/source/net/yacy/cora/federate/FederateSearchManager.java
+++ b/source/net/yacy/cora/federate/FederateSearchManager.java
@@ -59,24 +59,24 @@ import net.yacy.search.schema.WebgraphSchema;
* Handling of queries to configured remote OpenSearch systems.
*/
public class FederateSearchManager {
-
- /** Logger for this class */
- private static final ConcurrentLog LOG = new ConcurrentLog(FederateSearchManager.class.getName());
- /** Delay between connects (in ms) */
+ /** Logger for this class */
+ private static final ConcurrentLog LOG = new ConcurrentLog(FederateSearchManager.class.getName());
+
+ /** Delay between connects (in ms) */
private final int accessDelay = 15000;
private File confFile = null; // later initialized to DATA/SETTINGS/heuristicopensearch.conf
-
+
/** Connectors list */
private HashSet<AbstractFederateSearchConnector> conlist;
-
+
/** PropertiesConfiguration cfg */
protected Configuration cfg;
-
+
/** Switchboard instance */
private Switchboard switchboard;
-
+
/** Self reference for static .getManager() */
private static FederateSearchManager manager = null;
@@ -85,7 +85,7 @@ public class FederateSearchManager {
*/
public FederateSearchManager(Switchboard sb) {
super();
- this.conlist = new HashSet<AbstractFederateSearchConnector>();
+ this.conlist = new HashSet<>();
// from here we need Switchboard settings
if (sb == null) {
@@ -93,49 +93,49 @@ public class FederateSearchManager {
}
this.switchboard = sb;
// Data needed active name, url(template), desc, rule-when-to-use, specifics
- confFile = new File(sb.getDataPath(), "DATA/SETTINGS/heuristicopensearch.conf");
- if (!confFile.exists()) {
+ this.confFile = new File(sb.getDataPath(), "DATA/SETTINGS/heuristicopensearch.conf");
+ if (!this.confFile.exists()) {
try {
- Files.copy(new File(sb.appPath, "defaults/heuristicopensearch.conf"), confFile);
- File defdir = new File(sb.dataPath, "DATA/SETTINGS/federatecfg");
+ Files.copy(new File(sb.appPath, "defaults/heuristicopensearch.conf"), this.confFile);
+ final File defdir = new File(sb.dataPath, "DATA/SETTINGS/federatecfg");
if (!defdir.exists()) {
Files.copy(new File(sb.appPath, "defaults/federatecfg"), defdir);
}
- } catch (IOException ex) {
+ } catch (final IOException ex) {
}
}
// read settings config file
- if (confFile.exists()) {
+ if (this.confFile.exists()) {
try {
- cfg = new Configuration(confFile);
- Iterator<Entry> it = cfg.entryIterator();
+ this.cfg = new Configuration(this.confFile);
+ final Iterator<Entry> it = this.cfg.entryIterator();
while (it.hasNext()) {
- Entry cfgentry = it.next();
- String url = cfgentry.getValue();
+ final Entry cfgentry = it.next();
+ final String url = cfgentry.getValue();
if (cfgentry.enabled() && url != null && !url.isEmpty()) {
- String name = cfgentry.key();
+ final String name = cfgentry.key();
if (url.startsWith("cfgfile:")) { // is cfgfile with field mappings (no opensearch url)
// format prefix:connectortype:configfilename
// example cfgfile:solrconnector:testsys.solr.schema
- String[] parts = url.split(":");
+ final String[] parts = url.split(":");
if (parts[1].equalsIgnoreCase("solrconnector")) {
- SolrFederateSearchConnector sfc = new SolrFederateSearchConnector();
+ final SolrFederateSearchConnector sfc = new SolrFederateSearchConnector();
if (sfc.init(name, sb.getDataPath()+ "/DATA/SETTINGS/federatecfg/" + parts[2])) {
- conlist.add(sfc);
+ this.conlist.add(sfc);
}
} else {
LOG.config("Error in configuration of: " + url);
}
} else { // handle opensearch url template
- OpenSearchConnector osc = new OpenSearchConnector(url);
+ final OpenSearchConnector osc = new OpenSearchConnector(url);
if (osc.init(name, sb.getDataPath()+ "/DATA/SETTINGS/federatecfg/" + OpenSearchConnector.htmlMappingFileName(name))) {
- conlist.add(osc);
+ this.conlist.add(osc);
}
}
}
}
} catch (final IOException ex) {
- LOG.config("Unexpected error when reading configuration file : " + this.confFile, ex);
+ LOG.config("Unexpected error when reading configuration file : " + this.confFile, ex);
}
}
manager = this; // reference for static access via .getManager()
@@ -155,7 +155,7 @@ public class FederateSearchManager {
}
/**
- * Sends a query request to remote systems configured.
+ * Sends a query request to remote systems configured.
* If search query domain is LOCAL procedure does nothing.
*
* @param theSearch
@@ -163,8 +163,8 @@ public class FederateSearchManager {
public void search(SearchEvent theSearch) {
if (theSearch != null) {
if (!theSearch.query.isLocal() && !MemoryControl.shortStatus()) {
- Set<AbstractFederateSearchConnector> picklist = getBest();
- for (AbstractFederateSearchConnector fsc : picklist) {
+ final Set<AbstractFederateSearchConnector> picklist = this.getBest();
+ for (final AbstractFederateSearchConnector fsc : picklist) {
fsc.search(theSearch);
}
}
@@ -179,9 +179,9 @@ public class FederateSearchManager {
*/
public List<URIMetadataNode> query(QueryParams query) {
if (!query.isLocal() && !MemoryControl.shortStatus()) {
- List<URIMetadataNode> sdl = new ArrayList<URIMetadataNode>();
- Set<AbstractFederateSearchConnector> picklist = getBest();
- for (AbstractFederateSearchConnector fsc : picklist) {
+ final List<URIMetadataNode> sdl = new ArrayList<>();
+ final Set<AbstractFederateSearchConnector> picklist = this.getBest();
+ for (final AbstractFederateSearchConnector fsc : picklist) {
sdl.addAll(fsc.query(query));
}
return sdl;
@@ -199,7 +199,7 @@ public class FederateSearchManager {
public List<URIMetadataNode> query(String querystr) {
final QueryGoal qg = new QueryGoal(querystr);
- Bitfield filter = new Bitfield();
+ final Bitfield filter = new Bitfield();
final QueryParams query = new QueryParams(
qg,
new QueryModifier(0),
@@ -227,7 +227,7 @@ public class FederateSearchManager {
0.0d, 0.0d, 0.0d,
new HashSet<>());
- return query(query);
+ return this.query(query);
}
/**
@@ -237,15 +237,15 @@ public class FederateSearchManager {
* @return successful added
*/
public boolean addOpenSearchTarget(String name, String urlTemplate, boolean active, String comment) {
- if (confFile == null) {
+ if (this.confFile == null) {
return false;
}
try {
- Configuration conf = new Configuration(confFile);
+ final Configuration conf = new Configuration(this.confFile);
if (name != null && !name.isEmpty()) {
conf.add(name, null, active);
- Configuration.Entry e = conf.get(name);
+ final Configuration.Entry e = conf.get(name);
e.setValue(urlTemplate);
e.setEnable(active);
e.setComment(comment);
@@ -253,10 +253,10 @@ public class FederateSearchManager {
try {
conf.commit();
if (active) {
- OpenSearchConnector osd = new OpenSearchConnector(urlTemplate);
- String htmlMappingFile = this.switchboard.getDataPath()+ "/DATA/SETTINGS/federatecfg/" + OpenSearchConnector.htmlMappingFileName(name);
+ final OpenSearchConnector osd = new OpenSearchConnector(urlTemplate);
+ final String htmlMappingFile = this.switchboard.getDataPath()+ "/DATA/SETTINGS/federatecfg/" + OpenSearchConnector.htmlMappingFileName(name);
if (osd.init(name, htmlMappingFile)) {
- conlist.add(osd);
+ this.conlist.add(osd);
}
}
} catch (final IOException ex) {
@@ -265,7 +265,7 @@ public class FederateSearchManager {
return true;
}
} catch (final IOException e1) {
- LOG.severe("Unexpected error when writing configuration file : " + confFile, e1);
+ LOG.severe("Unexpected error when writing configuration file : " + this.confFile, e1);
return false;
}
return false;
@@ -275,47 +275,22 @@ public class FederateSearchManager {
* Get the number of active remote query target systems
*/
public int getSize() {
- return conlist.size();
+ return this.conlist.size();
}
/**
* Get best systems from configured targets
- *
+ *
* @return list of searchtargetconnectors
*/
protected Set<AbstractFederateSearchConnector> getBest() {
- HashSet<AbstractFederateSearchConnector> retset = new HashSet<AbstractFederateSearchConnector>();
- MultiProtocolURL connectorURL;
- for (AbstractFederateSearchConnector fsc : conlist) {
- try {
- connectorURL = new MultiProtocolURL(fsc.baseurl);
- } catch (MalformedURLException e) {
- LOG.warn("Malformed connector URL : " + fsc.baseurl);
- continue;
- }
- RobotsTxtEntry robotsEntry = null;
- int robotsDelay = 0;
- if (this.switchboard != null && this.switchboard.robots != null) {
- robotsEntry = this.switchboard.robots.getEntry(connectorURL,
- ClientIdentification.yacyInternetCrawlerAgent);
- if(robotsEntry != null) {
- robotsDelay = robotsEntry.getCrawlDelayMillis();
- }
- }
-
+ final HashSet<AbstractFederateSearchConnector> retset = new HashSet<>();
+ final long currentTime = System.currentTimeMillis();
+ for (final AbstractFederateSearchConnector fsc : this.conlist) {
// check access time
- long currentTime = System.currentTimeMillis();
- if ((fsc.lastaccesstime + accessDelay < currentTime)
- && (fsc.lastaccesstime + robotsDelay < currentTime) ) {
- // enforce 15 sec delay between searches to same system, and also check any eventual robots.txt Crawl-delay directive
- if (robotsEntry == null || !robotsEntry.isDisallowed(connectorURL)) {
- // also check robots.txt exclusion
- retset.add(fsc);
- } else {
- LOG.warn("Connector URL is disallowed by robots.txt : " + fsc.baseurl);
- }
+ if (fsc.lastaccesstime + this.accessDelay < currentTime && fsc.lastaccesstime < currentTime) {
+ retset.add(fsc);
}
-
}
return retset;
}
@@ -352,7 +327,7 @@ public class FederateSearchManager {
final long numfound;
try {
- SolrDocumentList docList = connector.getDocumentListByQuery(webgraphquerystr, null, 0, 1, webgraphqueryfields);
+ final SolrDocumentList docList = connector.getDocumentListByQuery(webgraphquerystr, null, 0, 1, webgraphqueryfields);
numfound = docList.getNumFound();
if (numfound == 0) {
LOG.info("no results found, abort discover job");
@@ -360,7 +335,7 @@ public class FederateSearchManager {
}
LOG.info("start checking " + Long.toString(numfound) + " found index results");
} catch (final IOException ex) {
- LOG.severe("Error on Solr webgraph core query", ex);
+ LOG.severe("Error on Solr webgraph core query", ex);
return false;
}
@@ -374,54 +349,54 @@ public class FederateSearchManager {
try {
boolean doloop = true;
int loopnr = 0;
- Set<String> dblmem = new HashSet<String>(); // temp memory for already checked url
+ final Set<String> dblmem = new HashSet<>(); // temp memory for already checked url
while (doloop) {
LOG.info("start Solr query loop at " + Integer.toString(loopnr * 20) + " of " + Long.toString(numfound));
- SolrDocumentList docList = connector.getDocumentListByQuery(webgraphquerystr, null, loopnr * 20, 20, webgraphqueryfields); // check chunk of 20 result documents
+ final SolrDocumentList docList = connector.getDocumentListByQuery(webgraphquerystr, null, loopnr * 20, 20, webgraphqueryfields); // check chunk of 20 result documents
loopnr++;
if (stoptime < System.currentTimeMillis()) {// stop after max 1h
doloop = false;
LOG.info("long running discover task aborted");
}
if (docList != null && docList.size() > 0) {
- Iterator<SolrDocument> docidx = docList.iterator();
+ final Iterator<SolrDocument> docidx = docList.iterator();
while (docidx.hasNext()) {
- SolrDocument sdoc = docidx.next();
+ final SolrDocument sdoc = docidx.next();
- String hrefurltxt = sdoc.getFieldValue(WebgraphSchema.target_protocol_s.getSolrFieldName()) + "://" + sdoc.getFieldValue(WebgraphSchema.target_urlstub_s.getSolrFieldName());
+ final String hrefurltxt = sdoc.getFieldValue(WebgraphSchema.target_protocol_s.getSolrFieldName()) + "://" + sdoc.getFieldValue(WebgraphSchema.target_urlstub_s.getSolrFieldName());
URL url;
try {
url = new URL(hrefurltxt);
} catch (final MalformedURLException ex) {
- LOG.warn("OpenSearch description URL is malformed : " + hrefurltxt);
- continue;
+ LOG.warn("OpenSearch description URL is malformed : " + hrefurltxt);
+ continue;
}
//TODO: check Blacklist
if (dblmem.add(url.getAuthority())) { // use only main path to detect double entries
- opensearchdescriptionReader os = new opensearchdescriptionReader(hrefurltxt);
+ final opensearchdescriptionReader os = new opensearchdescriptionReader(hrefurltxt);
if (os.getRSSorAtomUrl() != null) {
- /* Check eventual robots.txt policy */
- RobotsTxtEntry robotsEntry = null;
- MultiProtocolURL templateURL;
- try {
- templateURL = new MultiProtocolURL(os.getRSSorAtomUrl());
- } catch (final MalformedURLException ex) {
- LOG.warn("OpenSearch description URL is malformed : " + hrefurltxt);
- continue;
+ /* Check eventual robots.txt policy */
+ RobotsTxtEntry robotsEntry = null;
+ MultiProtocolURL templateURL;
+ try {
+ templateURL = new MultiProtocolURL(os.getRSSorAtomUrl());
+ } catch (final MalformedURLException ex) {
+ LOG.warn("OpenSearch description URL is malformed : " + hrefurltxt);
+ continue;
}
- if(sb.robots != null) {
- robotsEntry = sb.robots.getEntry(templateURL, ClientIdentification.yacyInternetCrawlerAgent);
- }
+ if(sb.robots != null) {
+ robotsEntry = sb.robots.getEntry(templateURL, ClientIdentification.yacyInternetCrawlerAgent);
+ }
- if(robotsEntry != null && robotsEntry.isDisallowed(templateURL)) {
- LOG.info("OpenSearch description template URL is disallowed by robots.xt");
- } else {
- // add found system to config file
- addOpenSearchTarget(os.getShortName(), os.getRSSorAtomUrl(), false, os.getItem("LongName"));
+ if(robotsEntry != null && robotsEntry.isDisallowed(templateURL)) {
+ LOG.info("OpenSearch description template URL is disallowed by robots.xt");
+ } else {
+ // add found system to config file
+ FederateSearchManager.this.addOpenSearchTarget(os.getShortName(), os.getRSSorAtomUrl(), false, os.getItem("LongName"));
LOG.info("added " + os.getShortName() + " " + hrefurltxt);
- }
+ }
} else {
- LOG.info("osd.xml check failed (no RSS or Atom support) for " + hrefurltxt);
+ LOG.info("osd.xml check failed (no RSS or Atom support) for " + hrefurltxt);
}
}
}
@@ -431,7 +406,7 @@ public class FederateSearchManager {
}
LOG.info("finisched Solr query (checked " + Integer.toString(dblmem.size()) + " unique opensearchdescription links found in " + Long.toString(numfound) + " results)");
} catch (final IOException ex) {
- LOG.severe("Unexpected error", ex);
+ LOG.severe("Unexpected error", ex);
}
}
};
@@ -446,41 +421,41 @@ public class FederateSearchManager {
* @return true if successful
*/
public boolean init(String cfgFileName) {
- confFile = new File(cfgFileName);
- if (confFile.exists()) {
+ this.confFile = new File(cfgFileName);
+ if (this.confFile.exists()) {
try {
- cfg = new Configuration(confFile);
+ this.cfg = new Configuration(this.confFile);
if (!this.conlist.isEmpty()) this.conlist.clear(); // prevent double entries
- Iterator<Entry> it = cfg.entryIterator();
+ final Iterator<Entry> it = this.cfg.entryIterator();
while (it.hasNext()) {
- Entry cfgentry = it.next();
+ final Entry cfgentry = it.next();
if (cfgentry.enabled()) { // hold only enabled in memory
- String name = cfgentry.key();
- String url = cfgentry.getValue();
+ final String name = cfgentry.key();
+ final String url = cfgentry.getValue();
if (url != null && !url.isEmpty()) {
if (url.startsWith("cfgfile:")) { // is cfgfile with field mappings (no opensearch url)
// config entry has 3 parts separated by : 1=cfgfile 2=connectortype 3=relative path to connector-cfg-file
// example cfgfile:solrconnector:testsys.solr.schema
- String[] parts = url.split(":");
+ final String[] parts = url.split(":");
if (parts[1].equalsIgnoreCase("solrconnector")) {
- SolrFederateSearchConnector sfc = new SolrFederateSearchConnector();
- if (sfc.init(name, confFile.getParent()+"/federatecfg/"+parts[2])) {
- conlist.add(sfc);
+ final SolrFederateSearchConnector sfc = new SolrFederateSearchConnector();
+ if (sfc.init(name, this.confFile.getParent()+"/federatecfg/"+parts[2])) {
+ this.conlist.add(sfc);
}
} else {
LOG.config("Init error in configuration of: " + url);
}
} else { // handle opensearch url template
- OpenSearchConnector osd = new OpenSearchConnector(url);
- if (osd.init(name, confFile.getParent()+"/federatecfg/" + OpenSearchConnector.htmlMappingFileName(name))) {
- conlist.add(osd);
+ final OpenSearchConnector osd = new OpenSearchConnector(url);
+ if (osd.init(name, this.confFile.getParent()+"/federatecfg/" + OpenSearchConnector.htmlMappingFileName(name))) {
+ this.conlist.add(osd);
}
}
}
}
}
} catch (final IOException ex) {
- LOG.config("Unexpected error when reading configuration file : " + cfgFileName);
+ LOG.config("Unexpected error when reading configuration file : " + cfgFileName);
}
}
return true;
diff --git a/source/net/yacy/crawler/Balancer.java b/source/net/yacy/crawler/Balancer.java
index 5b39e6f46..4e89947cd 100644
--- a/source/net/yacy/crawler/Balancer.java
+++ b/source/net/yacy/crawler/Balancer.java
@@ -1,7 +1,7 @@
/**
- * Balancer
- * SPDX-FileCopyrightText: 2014 Michael Peter Christen <[email protected])>
- * SPDX-License-Identifier: GPL-2.0-or-later
+ * Balancer
+ * SPDX-FileCopyrightText: 2014 Michael Peter Christen <[email protected])>
+ * SPDX-License-Identifier: GPL-2.0-or-later
* Frankfurt am Main, Germany
* First released 14.04.2014 at http://yacy.net
*
@@ -9,12 +9,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library 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
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -71,7 +71,7 @@ public interface Balancer {
* @return number of deleted urls
*/
public int removeAllByHostHashes(final Set<String> hosthashes);
-
+
/**
* @param urlHashes, a list of hashes that shall be removed
* @return number of entries that had been removed
@@ -112,11 +112,11 @@ public interface Balancer {
/**
* get a list of domains that are currently maintained as domain stacks
- * @return a map of clear text strings of host names (each host name eventually concatenated with a port, depending on the implementation)
+ * @return a map of clear text strings of host names (each host name eventually concatenated with a port, depending on the implementation)
* to an integer array: {the size of the domain stack, guessed delta waiting time}
*/
public Map<String, Integer[]> getDomainStackHosts(RobotsTxt robots);
-
+
/**
* get lists of crawl request entries for a specific host
* @param host
@@ -128,8 +128,7 @@ public interface Balancer {
/**
* get the next entry in this crawl queue in such a way that the domain access time delta is maximized
- * and always above the given minimum delay time. An additional delay time is computed using the robots.txt
- * crawl-delay time which is always respected. In case the minimum time cannot ensured, this method pauses
+ * and always above the given minimum delay time. In case the minimum time cannot ensured, this method pauses
* the necessary time until the url is released and returned as CrawlEntry object. In case that a profile
* for the computed Entry does not exist, null is returned
* @param delay true if the requester demands forced delays using explicit thread sleep
diff --git a/source/net/yacy/crawler/CrawlStacker.java b/source/net/yacy/crawler/CrawlStacker.java
index c75e1e964..f1ecdf283 100644
--- a/source/net/yacy/crawler/CrawlStacker.java
+++ b/source/net/yacy/crawler/CrawlStacker.java
@@ -1,7 +1,7 @@
// plasmaCrawlStacker.java
// -----------------------
// part of YaCy
-// SPDX-FileCopyrightText: 2005 Michael Peter Christen <[email protected])>
+// SPDX-FileCopyrightText: 2005 Michael Peter Christen <[email protected])>
// SPDX-License-Identifier: GPL-2.0-or-later
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
@@ -64,15 +64,15 @@ import net.yacy.search.Switchboard;
import net.yacy.search.index.Segment;
public final class CrawlStacker implements WorkflowTask<Request>{
-
+
public static String ERROR_NO_MATCH_MUST_MATCH_FILTER = "url does not match must-match filter ";
public static String ERROR_MATCH_WITH_MUST_NOT_MATCH_FILTER = "url matches must-not-match filter ";
-
+
/** Crawl reject reason prefix having specific processing */
public static final String CRAWL_REJECT_REASON_DOUBLE_IN_PREFIX = "double in";
-
+
private final static ConcurrentLog log = new ConcurrentLog("STACKCRAWL");
-
+
private final RobotsTxt robots;
private final WorkflowProcessor<Request> requestQueue;
public final CrawlQueues nextQueue;
@@ -101,14 +101,14 @@ public final class CrawlStacker implements WorkflowTask<Request>{
this.acceptLocalURLs = acceptLocalURLs;
this.acceptGlobalURLs = acceptGlobalURLs;
this.domainList = domainList;
- this.requestQueue = new WorkflowProcessor<Request>("CrawlStacker", "This process checks new urls before they are enqueued into the balancer (proper, double-check, correct domain, filter)", new String[]{"Balancer"}, this, 10000, null, WorkflowProcessor.availableCPU);
+ this.requestQueue = new WorkflowProcessor<>("CrawlStacker", "This process checks new urls before they are enqueued into the balancer (proper, double-check, correct domain, filter)", new String[]{"Balancer"}, this, 10000, null, WorkflowProcessor.availableCPU);
CrawlStacker.log.info("STACKCRAWL thread initialized.");
}
public int size() {
return this.requestQueue.getQueueSize();
}
-
+
public boolean isEmpty() {
if (!this.requestQueue.queueIsEmpty()) return false;
return true;
@@ -119,26 +119,26 @@ public final class CrawlStacker implements WorkflowTask<Request>{
}
public void announceClose() {
- CrawlStacker.log.info("Flushing remaining " + size() + " crawl stacker job entries.");
+ CrawlStacker.log.info("Flushing remaining " + this.size() + " crawl stacker job entries.");
this.requestQueue.shutdown();
}
public synchronized void close() {
- CrawlStacker.log.info("Shutdown. waiting for remaining " + size() + " crawl stacker job entries. please wait.");
+ CrawlStacker.log.info("Shutdown. waiting for remaining " + this.size() + " crawl stacker job entries. please wait.");
this.requestQueue.shutdown();
CrawlStacker.log.info("Shutdown. Closing stackCrawl queue.");
- clear();
+ this.clear();
}
@Override
public Request process(final Request entry) {
// this is the method that is called by the busy thread from outside
if (entry == null) return null;
-
+
try {
- final String rejectReason = stackCrawl(entry);
+ final String rejectReason = this.stackCrawl(entry);
// if the url was rejected we store it into the error URL db
if (rejectReason != null && !rejectReason.startsWith(CRAWL_REJECT_REASON_DOUBLE_IN_PREFIX)) {
@@ -158,7 +158,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
if (CrawlStacker.log.isFinest()) CrawlStacker.log.finest("ENQUEUE " + entry.url() + ", referer=" + entry.referrerhash() + ", initiator=" + ((entry.initiator() == null) ? "" : ASCII.String(entry.initiator())) + ", name=" + entry.name() + ", appdate=" + entry.appdate() + ", depth=" + entry.depth());
this.requestQueue.enQueue(entry);
}
-
+
public void enqueueEntriesAsynchronous(
final byte[] initiator,
final String profileHandle,
@@ -167,11 +167,11 @@ public final class CrawlStacker implements WorkflowTask<Request>{
new Thread("enqueueEntriesAsynchronous") {
@Override
public void run() {
- enqueueEntries(initiator, profileHandle, hyperlinks, true, timezoneOffset);
+ CrawlStacker.this.enqueueEntries(initiator, profileHandle, hyperlinks, true, timezoneOffset);
}
}.start();
}
-
+
/**
* Enqueue crawl start entries
* @param initiator Hash of the peer initiating the crawl
@@ -187,15 +187,15 @@ public final class CrawlStacker implements WorkflowTask<Request>{
final List<AnchorURL> hyperlinks,
final boolean replace,
final int timezoneOffset) {
- /* Let's check if the profile is still active before removing any existing entry */
- byte[] handle = UTF8.getBytes(profileHandle);
+ /* Let's check if the profile is still active before removing any existing entry */
+ final byte[] handle = UTF8.getBytes(profileHandle);
final CrawlProfile profile = this.crawler.get(handle);
if (profile == null) {
String error;
if(hyperlinks.size() == 1) {
- error = "Rejected URL : " + hyperlinks.get(0).toNormalform(false) + ". Reason : LOST STACKER PROFILE HANDLE '" + profileHandle + "'";
+ error = "Rejected URL : " + hyperlinks.get(0).toNormalform(false) + ". Reason : LOST STACKER PROFILE HANDLE '" + profileHandle + "'";
} else {
- error = "Rejected " + hyperlinks.size() + " crawl entries. Reason : LOST STACKER PROFILE HANDLE '" + profileHandle + "'";
+ error = "Rejected " + hyperlinks.size() + " crawl entries. Reason : LOST STACKER PROFILE HANDLE '" + profileHandle + "'";
}
CrawlStacker.log.info(error); // this is NOT an error but a normal behavior when terminating a crawl queue
/* Throw an exception to signal caller it can stop stacking URLs using this crawl profile */
@@ -203,7 +203,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
}
if (replace) {
// delete old entries, if exists to force a re-load of the url (thats wanted here)
- Set<String> hosthashes = new HashSet<String>();
+ final Set<String> hosthashes = new HashSet<>();
for (final AnchorURL url: hyperlinks) {
if (url == null) continue;
hosthashes.add(url.hosthash());
@@ -231,12 +231,12 @@ public final class CrawlStacker implements WorkflowTask<Request>{
}
if (url.getProtocol().equals("ftp")) {
- /* put ftp site entries on the crawl stack,
+ /* put ftp site entries on the crawl stack,
* using the crawl profile depth to control how many children folders of the url are stacked */
- enqueueEntriesFTP(initiator, profile, url, replace, timezoneOffset);
+ this.enqueueEntriesFTP(initiator, profile, url, replace, timezoneOffset);
} else {
// put entry on crawl stack
- enqueueEntry(new Request(
+ this.enqueueEntry(new Request(
initiator,
url,
null,
@@ -249,7 +249,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
}
}
}
-
+
/**
* Asynchronously enqueue crawl start entries for a ftp url.
* @param initiator Hash of the peer initiating the crawl
@@ -293,13 +293,13 @@ public final class CrawlStacker implements WorkflowTask<Request>{
CrawlStacker.this.indexSegment.fulltext().remove(urlhash);
cq.noticeURL.removeByURLHash(urlhash);
}
-
- /* Each entry is a children resource of the starting ftp URL :
+
+ /* Each entry is a children resource of the starting ftp URL :
* take into account the sub folder depth in the crawl depth control */
- int nextDepth = Math.max(0, url.getPaths().length - pathParts);
+ final int nextDepth = Math.max(0, url.getPaths().length - pathParts);
// put entry on crawl stack
- enqueueEntry(new Request(
+ CrawlStacker.this.enqueueEntry(new Request(
initiator,
url,
null,
@@ -323,8 +323,8 @@ public final class CrawlStacker implements WorkflowTask<Request>{
* @return null if successfull, a reason string if not successful
*/
public String stackSimpleCrawl(final DigestURL url) {
- final CrawlProfile pe = this.crawler.defaultSurrogateProfile;
- return stackCrawl(new Request(
+ final CrawlProfile pe = this.crawler.defaultSurrogateProfile;
+ return this.stackCrawl(new Request(
this.peers.mySeed().hash.getBytes(),
url,
null,
@@ -342,7 +342,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
public String stackCrawl(final Request entry) {
//this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
- byte[] handle = UTF8.getBytes(entry.profileHandle());
+ final byte[] handle = UTF8.getBytes(entry.profileHandle());
final CrawlProfile profile = this.crawler.get(handle);
String error;
if (profile == null) {
@@ -351,9 +351,9 @@ public final class CrawlStacker implements WorkflowTask<Request>{
return error;
}
- error = checkAcceptanceChangeable(entry.url(), profile, entry.depth());
+ error = this.checkAcceptanceChangeable(entry.url(), profile, entry.depth());
if (error != null) return error;
- error = checkAcceptanceInitially(entry.url(), profile);
+ error = this.checkAcceptanceInitially(entry.url(), profile);
if (error != null) return error;
// store information
@@ -377,15 +377,15 @@ public final class CrawlStacker implements WorkflowTask<Request>{
String warning = null;
if (!profile.isCrawlerAlwaysCheckMediaType() && TextParser.supportsExtension(entry.url()) != null) {
- if(profile.isIndexNonParseableUrls()) {
- /* Unsupported file extension and no cross-checking of Media Type : add immediately to the noload stack to index only URL metadata */
- warning = this.nextQueue.noticeURL.push(NoticedURL.StackType.NOLOAD, entry, profile, this.robots);
- if (warning != null && CrawlStacker.log.isFine()) {
- CrawlStacker.log.fine("CrawlStacker.stackCrawl of URL " + entry.url().toNormalform(true) + " - not pushed to " + NoticedURL.StackType.NOLOAD + " stack : " + warning);
- }
- return null;
- }
-
+ if(profile.isIndexNonParseableUrls()) {
+ /* Unsupported file extension and no cross-checking of Media Type : add immediately to the noload stack to index only URL metadata */
+ warning = this.nextQueue.noticeURL.push(NoticedURL.StackType.NOLOAD, entry, profile, this.robots);
+ if (warning != null && CrawlStacker.log.isFine()) {
+ CrawlStacker.log.fine("CrawlStacker.stackCrawl of URL " + entry.url().toNormalform(true) + " - not pushed to " + NoticedURL.StackType.NOLOAD + " stack : " + warning);
+ }
+ return null;
+ }
+
error = "URL '" + entry.url().toString() + "' file extension is not supported and indexing of linked non-parsable documents is disabled.";
CrawlStacker.log.info(error);
return error;
@@ -425,11 +425,11 @@ public final class CrawlStacker implements WorkflowTask<Request>{
if (dbocc != null) {
return CRAWL_REJECT_REASON_DOUBLE_IN_PREFIX + ": " + dbocc.name();
}
- String urlhash = ASCII.String(url.hash());
+ final String urlhash = ASCII.String(url.hash());
LoadTimeURL oldEntry = null;
try {
oldEntry = this.indexSegment.fulltext().getDefaultConnector().getLoadTimeURL(urlhash);
- } catch (IOException e) {
+ } catch (final IOException e) {
// if an exception here occurs then there is the danger that urls which had been in the crawler are overwritten a second time
// to prevent that, we reject urls in these events
ConcurrentLog.logException(e);
@@ -444,7 +444,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
if (CrawlStacker.log.isFine()) CrawlStacker.log.fine("URL '" + url.toNormalform(false) + "' appeared too often in crawl stack, a maximum of " + maxAllowedPagesPerDomain + " is allowed.");
return "crawl stack domain counter exceeded (test by profile)";
}
-
+
/*
if (ResultURLs.domainCount(EventOrigin.LOCAL_CRAWLING, url.getHost()) >= maxAllowedPagesPerDomain) {
if (this.log.isFine()) this.log.fine("URL '" + urlstring + "' appeared too often in result stack, a maximum of " + maxAllowedPagesPerDomain + " is allowed.");
@@ -452,7 +452,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
}
*/
}
-
+
final Long oldDate = oldEntry == null ? null : oldEntry.date;
if (oldDate == null) {
return null; // no evidence that we know that url
@@ -464,9 +464,9 @@ public final class CrawlStacker implements WorkflowTask<Request>{
CrawlStacker.log.fine("RE-CRAWL of URL '" + urlstring + "': this url was crawled " +
((System.currentTimeMillis() - oldDate.longValue()) / 60000 / 60 / 24) + " days ago.");
} else {
- return CRAWL_REJECT_REASON_DOUBLE_IN_PREFIX + ": local index, recrawl rejected. Document date = "
- + ISO8601Formatter.FORMATTER.format(new Date(oldDate)) + " is not older than crawl profile recrawl minimum date = "
- + ISO8601Formatter.FORMATTER.format(new Date(profile.recrawlIfOlder()));
+ return CRAWL_REJECT_REASON_DOUBLE_IN_PREFIX + ": local index, recrawl rejected. Document date = "
+ + ISO8601Formatter.FORMATTER.format(new Date(oldDate)) + " is not older than crawl profile recrawl minimum date = "
+ + ISO8601Formatter.FORMATTER.format(new Date(profile.recrawlIfOlder()));
}
return null;
@@ -490,7 +490,7 @@ public final class CrawlStacker implements WorkflowTask<Request>{
}
// check if ip is local ip address
- final String urlRejectReason = urlInAcceptedDomain(url);
+ final String urlRejectReason = this.urlInAcceptedDomain(url);
if (urlRejectReason != null) {
if (CrawlStacker.log.isFine()) CrawlStacker.log.fine("denied_(" + urlRejectReason + ")");
return "denied_(" + urlRejectReason + ")";
@@ -504,9 +504,9 @@ public final class CrawlStacker implements WorkflowTask<Request>{
// filter with must-match for URLs
if ((depth > 0) && !profile.urlMustMatchPattern().matcher(urlstring).matches()) {
- final String patternStr = profile.formattedUrlMustMatchPattern();
+ final String patternStr = profile.formattedUrlMustMatchPattern();
if (CrawlStacker.log.isFine()) {
- CrawlStacker.log.fine("URL '" + urlstring + "' does not match must-match crawling filter '" + patternStr + "'.");
+ CrawlStacker.log.fine("URL '" + urlstring + "' does not match must-match crawling filter '" + patternStr + "'.");
}
return ERROR_NO_MATCH_MUST_MATCH_FILTER + patternStr;
}
@@ -578,31 +578,31 @@ public final class CrawlStacker implements WorkflowTask<Request>{
if (url == null) return "url is null";
// check domainList from network-definition
if(this.domainList != null) {
- if(!this.domainList.isListed(url, null)) {
- return "the url '" + url + "' is not in domainList of this network";
- }
+ if(!this.domainList.isListed(url, null)) {
+ return "the url '" + url + "' is not in domainList of this network";
+ }
}
-
+
if (Switchboard.getSwitchboard().getConfigBool(
- "contentcontrol.enabled", false) == true) {
+ "contentcontrol.enabled", false) == true) {
- if (!Switchboard.getSwitchboard()
- .getConfig("contentcontrol.mandatoryfilterlist", "")
- .equals("")) {
- FilterEngine f = ContentControlFilterUpdateThread.getNetworkFilter();
- if (f != null) {
- if (!f.isListed(url, null)) {
+ if (!Switchboard.getSwitchboard()
+ .getConfig("contentcontrol.mandatoryfilterlist", "")
+ .equals("")) {
+ final FilterEngine f = ContentControlFilterUpdateThread.getNetworkFilter();
+ if (f != null) {
+ if (!f.isListed(url, null)) {
- return "the url '"
- + url
- + "' does not belong to the network mandatory filter list";
+ return "the url '"
+ + url
+ + "' does not belong to the network mandatory filter list";
- }
- }
- }
+ }
+ }
+ }
+
+ }
- }
-
final boolean local = url.isLocal();
if (this.acceptLocalURLs && local) return null;
if (this.acceptGlobalURLs && !local) return null;
diff --git a/source/net/yacy/crawler/HostBalancer.java b/source/net/yacy/crawler/HostBalancer.java
index 5d6a569a6..cd0bcca87 100644
--- a/source/net/yacy/crawler/HostBalancer.java
+++ b/source/net/yacy/crawler/HostBalancer.java
@@ -1,6 +1,6 @@
/**
* HostQueues
- * SPDX-FileCopyrightText: 2013 Michael Peter Christen <[email protected])>
+ * SPDX-FileCopyrightText: 2013 Michael Peter Christen <[email protected])>
* SPDX-License-Identifier: GPL-2.0-or-later
* First released 24.09.2013 at http://yacy.net
*
@@ -8,12 +8,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library 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
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -32,6 +32,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
@@ -56,7 +57,7 @@ import net.yacy.kelondro.util.FileUtils;
/**
* wrapper for single HostQueue queues; this is a collection of such queues.
* All these queues are stored in a common directory for the queue stacks.
- *
+ *
* ATTENTION: the order of urls returned by this balancer must strictly follow the clickdepth order.
* That means that all links from a given host must be returned from the lowest crawldepth only.
* The crawldepth is interpreted as clickdepth and the crawler is producing that semantic using a
@@ -104,50 +105,50 @@ public class HostBalancer implements Balancer {
// create a stack for newly entered entries
if (!(hostsPath.exists())) hostsPath.mkdirs(); // make the path
- this.queues = new ConcurrentHashMap<String, HostQueue>();
- this.roundRobinHostHashes = new HashSet<String>();
- init(asyncInit); // return without wait but starts a thread to fill the queues
+ this.queues = new ConcurrentHashMap<>();
+ this.roundRobinHostHashes = new HashSet<>();
+ this.init(asyncInit); // return without wait but starts a thread to fill the queues
}
/**
- * Fills the queue by scanning the hostsPath directory.
+ * Fills the queue by scanning the hostsPath directory.
* @param async when true, launch in a dedicated thread to
* return immediately (as large unfinished crawls may take longer to load)
*/
private void init(final boolean async) {
if(async) {
- Thread t = new Thread("HostBalancer.init") {
+ final Thread t = new Thread("HostBalancer.init") {
@Override
public void run() {
- runInit();
+ HostBalancer.this.runInit();
}
};
- t.start();
+ t.start();
} else {
- runInit();
+ this.runInit();
}
}
/**
- * Fills the queue by scanning the hostsPath directory.
+ * Fills the queue by scanning the hostsPath directory.
*/
private void runInit() {
- final String[] hostlist = hostsPath.list();
- for (String hoststr : hostlist) {
+ final String[] hostlist = this.hostsPath.list();
+ for (final String hoststr : hostlist) {
try {
- File queuePath = new File(hostsPath, hoststr);
- HostQueue queue = new HostQueue(queuePath, queues.size() > onDemandLimit, exceed134217727);
+ final File queuePath = new File(this.hostsPath, hoststr);
+ final HostQueue queue = new HostQueue(queuePath, this.queues.size() > this.onDemandLimit, this.exceed134217727);
if (queue.isEmpty()) {
queue.close();
FileUtils.deletedelete(queuePath);
} else {
- queues.put(queue.getHostHash(), queue);
+ this.queues.put(queue.getHostHash(), queue);
}
} catch (MalformedURLException | RuntimeException e) {
- log.warn("delete queue due to init error for " + hostsPath.getName() + " host=" + hoststr + " " + e.getLocalizedMessage());
+ log.warn("delete queue due to init error for " + this.hostsPath.getName() + " host=" + hoststr + " " + e.getLocalizedMessage());
// if exception thrown we can't init the queue, maybe due to name violation. That won't get better, delete it.
- FileUtils.deletedelete(new File(hostsPath, hoststr));
+ FileUtils.deletedelete(new File(this.hostsPath, hoststr));
}
}
}
@@ -157,7 +158,7 @@ public class HostBalancer implements Balancer {
if (depthCache != null) {
depthCache.clear();
}
- for (HostQueue queue: this.queues.values()) queue.close();
+ for (final HostQueue queue: this.queues.values()) queue.close();
this.queues.clear();
}
@@ -166,14 +167,14 @@ public class HostBalancer implements Balancer {
if (depthCache != null) {
depthCache.clear();
}
- for (HostQueue queue: this.queues.values()) queue.clear();
+ for (final HostQueue queue: this.queues.values()) queue.clear();
this.queues.clear();
}
@Override
public Request get(final byte[] urlhash) throws IOException {
- String hosthash = ASCII.String(urlhash, 6, 6);
- HostQueue queue = this.queues.get(hosthash);
+ final String hosthash = ASCII.String(urlhash, 6, 6);
+ final HostQueue queue = this.queues.get(hosthash);
if (queue == null) return null;
return queue.get(urlhash);
}
@@ -181,7 +182,7 @@ public class HostBalancer implements Balancer {
@Override
public int removeAllByProfileHandle(final String profileHandle, final long timeout) throws IOException, SpaceExceededException {
int c = 0;
- for (HostQueue queue: this.queues.values()) {
+ for (final HostQueue queue: this.queues.values()) {
c += queue.removeAllByProfileHandle(profileHandle, timeout);
}
return c;
@@ -195,37 +196,37 @@ public class HostBalancer implements Balancer {
@Override
public int removeAllByHostHashes(final Set<String> hosthashes) {
int c = 0;
- for (String h: hosthashes) {
- HostQueue hq = this.queues.get(h);
+ for (final String h: hosthashes) {
+ final HostQueue hq = this.queues.get(h);
if (hq != null) c += hq.removeAllByHostHashes(hosthashes);
}
// remove from cache
- Iterator<Map.Entry<byte[], Long>> i = depthCache.iterator();
- ArrayList<String> deleteHashes = new ArrayList<String>();
+ final Iterator<Map.Entry<byte[], Long>> i = depthCache.iterator();
+ final ArrayList<String> deleteHashes = new ArrayList<>();
while (i.hasNext()) {
- String h = ASCII.String(i.next().getKey());
+ final String h = ASCII.String(i.next().getKey());
if (hosthashes.contains(h.substring(6))) deleteHashes.add(h);
}
- for (String h: deleteHashes) depthCache.remove(ASCII.getBytes(h));
+ for (final String h: deleteHashes) depthCache.remove(ASCII.getBytes(h));
return c;
}
@Override
public synchronized int remove(final HandleSet urlHashes) throws IOException {
- Map<String, HandleSet> removeLists = new ConcurrentHashMap<String, HandleSet>();
- for (byte[] urlhash: urlHashes) {
+ final Map<String, HandleSet> removeLists = new ConcurrentHashMap<>();
+ for (final byte[] urlhash: urlHashes) {
depthCache.remove(urlhash);
- String hosthash = ASCII.String(urlhash, 6, 6);
+ final String hosthash = ASCII.String(urlhash, 6, 6);
HandleSet removeList = removeLists.get(hosthash);
if (removeList == null) {
removeList = new RowHandleSet(Word.commonHashLength, Base64Order.enhancedCoder, 100);
removeLists.put(hosthash, removeList);
}
- try {removeList.put(urlhash);} catch (SpaceExceededException e) {}
+ try {removeList.put(urlhash);} catch (final SpaceExceededException e) {}
}
int c = 0;
- for (Map.Entry<String, HandleSet> entry: removeLists.entrySet()) {
- HostQueue queue = this.queues.get(entry.getKey());
+ for (final Map.Entry<String, HandleSet> entry: removeLists.entrySet()) {
+ final HostQueue queue = this.queues.get(entry.getKey());
if (queue != null) c += queue.remove(entry.getValue());
}
return c;
@@ -239,8 +240,8 @@ public class HostBalancer implements Balancer {
@Override
public boolean has(final byte[] urlhashb) {
if (depthCache.has(urlhashb)) return true;
- String hosthash = ASCII.String(urlhashb, 6, 6);
- HostQueue queue = this.queues.get(hosthash);
+ final String hosthash = ASCII.String(urlhashb, 6, 6);
+ final HostQueue queue = this.queues.get(hosthash);
if (queue == null) return false;
return queue.has(urlhashb);
}
@@ -248,7 +249,7 @@ public class HostBalancer implements Balancer {
@Override
public int size() {
int c = 0;
- for (HostQueue queue: this.queues.values()) {
+ for (final HostQueue queue: this.queues.values()) {
c += queue.size();
}
return c;
@@ -256,7 +257,7 @@ public class HostBalancer implements Balancer {
@Override
public boolean isEmpty() {
- for (HostQueue queue: this.queues.values()) {
+ for (final HostQueue queue: this.queues.values()) {
if (!queue.isEmpty()) return false;
}
return true;
@@ -284,7 +285,7 @@ public class HostBalancer implements Balancer {
public String push(final Request entry, CrawlProfile profile, final RobotsTxt robots) throws IOException, SpaceExceededException {
if (this.has(entry.url().hash())) return "double occurrence";
depthCache.put(entry.url().hash(), entry.depth());
- String hosthash = entry.url().hosthash();
+ final String hosthash = entry.url().hosthash();
synchronized (this) {
HostQueue queue = this.queues.get(hosthash);
if (queue == null) {
@@ -299,8 +300,7 @@ public class HostBalancer implements Balancer {
/**
* get the next entry in this crawl queue in such a way that the domain access time delta is maximized
- * and always above the given minimum delay time. An additional delay time is computed using the robots.txt
- * crawl-delay time which is always respected. In case the minimum time cannot ensured, this method pauses
+ * and always above the given minimum delay time. In case the minimum time cannot ensured, this method pauses
* the necessary time until the url is released and returned as CrawlEntry object. In case that a profile
* for the computed Entry does not exist, null is returned
* @param delay true if the requester demands forced delays using explicit thread sleep
@@ -324,22 +324,23 @@ public class HostBalancer implements Balancer {
// this shall kick out small stacks to prevent that too many files are opened for very wide crawls
boolean smallStacksExist = false;
boolean singletonStacksExist = false;
- smallsearch: for (String s: this.roundRobinHostHashes) {
- HostQueue hq = this.queues.get(s);
+ smallsearch: for (final String s: this.roundRobinHostHashes) {
+ final HostQueue hq = this.queues.get(s);
if (hq != null) {
- int size = hq.size();
+ final int size = hq.size();
if (size == 1) {singletonStacksExist = true; break smallsearch;}
if (size <= 10) {smallStacksExist = true; break smallsearch;}
}
}
- Set<String> freshhosts = new HashSet<>();
- Iterator<String> i = this.roundRobinHostHashes.iterator();
+ final ArrayList<String> freshhosts = new ArrayList<>();
+ final ArrayList<String> removehosts = new ArrayList<>();
+ final Iterator<String> i = this.roundRobinHostHashes.iterator();
smallstacks: while (i.hasNext()) {
if (this.roundRobinHostHashes.size() <= 10) break smallstacks; // don't shrink the hosts until nothing is left
- String hosthash = i.next();
- HostQueue hq = this.queues.get(hosthash);
- if (hq == null) {i.remove(); continue smallstacks;}
- int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), hosthash, robots, ClientIdentification.yacyInternetCrawlerAgent);
+ final String hosthash = i.next();
+ final HostQueue hq = this.queues.get(hosthash);
+ if (hq == null) {removehosts.add(hosthash); i.remove(); continue smallstacks;}
+ final int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), hosthash, robots, ClientIdentification.yacyInternetCrawlerAgent);
if (delta == Integer.MIN_VALUE) {
// never-crawled hosts; we do not want to have too many of them in here. Loading new hosts means: waiting for robots.txt to load
freshhosts.add(hosthash);
@@ -349,17 +350,28 @@ public class HostBalancer implements Balancer {
if (singletonStacksExist || smallStacksExist) {
if (delta < 0) continue; // keep all non-waiting stacks; they are useful to speed up things
// to protect all small stacks which have a fast throughput, remove all with long waiting time
- if (delta >= 1000) {i.remove(); continue smallstacks;}
- int size = hq.size();
+ if (delta >= 1000) {removehosts.add(hosthash); i.remove(); continue smallstacks;}
+ final int size = hq.size();
if (singletonStacksExist) {
- if (size != 1) {i.remove(); continue smallstacks;} // remove all non-singletons
+ if (size != 1) {removehosts.add(hosthash); i.remove(); continue smallstacks;} // remove all non-singletons
} else /*smallStacksExist*/ {
- if (size > 10) {i.remove(); continue smallstacks;} // remove all large stacks
+ if (size > 10) {removehosts.add(hosthash); i.remove(); continue smallstacks;} // remove all large stacks
}
}
}
+
+ // shuffle the lists
+ final Random r = new Random();
+
// put at least one of the fresh hosts back
- if (freshhosts.size() > 0) this.roundRobinHostHashes.add(freshhosts.iterator().next());
+ if (freshhosts.size() > 0) this.roundRobinHostHashes.add(freshhosts.remove(r.nextInt(freshhosts.size())));
+ // fill up so we can have at least 100 domains in the queue
+ while (this.roundRobinHostHashes.size() < 100 && removehosts.size() > 0) {
+ this.roundRobinHostHashes.add(removehosts.remove(r.nextInt(removehosts.size())));
+ }
+ while (this.roundRobinHostHashes.size() < 100 && freshhosts.size() > 0) {
+ this.roundRobinHostHashes.add(freshhosts.remove(r.nextInt(freshhosts.size())));
+ }
// result
if (this.roundRobinHostHashes.size() == 1) {
@@ -381,9 +393,9 @@ public class HostBalancer implements Balancer {
// create a map of sleep time / queue relations with a fuzzy sleep time (ms / 500).
// if the entry with the smallest sleep time contains at least two entries,
// then the larger one from these queues are selected.
- TreeMap<Integer, List<String>> fastTree = new TreeMap<>();
- mixedstrategy: for (String h: this.roundRobinHostHashes) {
- HostQueue hq = this.queues.get(h);
+ final TreeMap<Integer, List<String>> fastTree = new TreeMap<>();
+ mixedstrategy: for (final String h: this.roundRobinHostHashes) {
+ final HostQueue hq = this.queues.get(h);
if (hq != null) {
int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), h, robots, ClientIdentification.yacyInternetCrawlerAgent) / 200;
if (delta < 0) delta = 0;
@@ -394,14 +406,14 @@ public class HostBalancer implements Balancer {
}
queueHashes.add(h);
// check stop criteria
- List<String> firstEntries = fastTree.firstEntry().getValue();
+ final List<String> firstEntries = fastTree.firstEntry().getValue();
if (firstEntries.size() > 1) {
// select larger queue from that list
int largest = Integer.MIN_VALUE;
- for (String hh: firstEntries) {
- HostQueue hhq = this.queues.get(hh);
+ for (final String hh: firstEntries) {
+ final HostQueue hhq = this.queues.get(hh);
if (hhq != null) {
- int s = hhq.size();
+ final int s = hhq.size();
if (s > largest) {
largest = s;
rhh = hh;
@@ -416,15 +428,15 @@ public class HostBalancer implements Balancer {
if (rhq == null && fastTree.size() > 0) {
// it may be possible that the lowest entry never has more than one queues assigned
// in this case just take the smallest entry
- List<String> firstEntries = fastTree.firstEntry().getValue();
+ final List<String> firstEntries = fastTree.firstEntry().getValue();
assert firstEntries.size() == 1;
rhh = firstEntries.get(0);
rhq = this.queues.get(rhh);
}
// to prevent that the complete roundrobinhosthashes are taken for each round, we remove the entries from the top of the fast queue
- List<String> lastEntries = fastTree.size() > 0 ? fastTree.lastEntry().getValue() : null;
+ final List<String> lastEntries = fastTree.size() > 0 ? fastTree.lastEntry().getValue() : null;
if (lastEntries != null) {
- for (String h: lastEntries) this.roundRobinHostHashes.remove(h);
+ for (final String h: lastEntries) this.roundRobinHostHashes.remove(h);
}
}
@@ -467,20 +479,20 @@ public class HostBalancer implements Balancer {
continue tryagain;
}
this.roundRobinHostHashes.remove(rhh); // prevent that the queue is used again
- long timestamp = System.currentTimeMillis();
- Request request = rhq.pop(delay, cs, robots); // this pop is outside of synchronization to prevent blocking of pushes
- long actualwaiting = System.currentTimeMillis() - timestamp;
+ final long timestamp = System.currentTimeMillis();
+ final Request request = rhq.pop(delay, cs, robots); // this pop is outside of synchronization to prevent blocking of pushes
+ final long actualwaiting = System.currentTimeMillis() - timestamp;
if (actualwaiting > 1000) {
synchronized (this) {
// to prevent that this occurs again, remove all stacks with positive delay times (which may be less after that waiting)
- Iterator<String> i = this.roundRobinHostHashes.iterator();
+ final Iterator<String> i = this.roundRobinHostHashes.iterator();
protectcheck: while (i.hasNext()) {
if (this.roundRobinHostHashes.size() <= 3) break protectcheck; // don't shrink the hosts until nothing is left
- String s = i.next();
- HostQueue hq = this.queues.get(s);
+ final String s = i.next();
+ final HostQueue hq = this.queues.get(s);
if (hq == null) {i.remove(); continue protectcheck;}
- int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), s, robots, ClientIdentification.yacyInternetCrawlerAgent);
+ final int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), s, robots, ClientIdentification.yacyInternetCrawlerAgent);
if (delta >= 0) {i.remove();}
}
}
@@ -494,11 +506,11 @@ public class HostBalancer implements Balancer {
}
if (request == null) continue tryagain;
return request;
- } catch (ConcurrentModificationException e) {
+ } catch (final ConcurrentModificationException e) {
continue tryagain;
- } catch (IOException e) {
+ } catch (final IOException e) {
throw e;
- } catch (Throwable e) {
+ } catch (final Throwable e) {
ConcurrentLog.logException(e);
throw new IOException(e.getMessage());
}
@@ -519,9 +531,9 @@ public class HostBalancer implements Balancer {
public Request next() {
synchronized (HostBalancer.this) {
while (hostIterator[0] == null || !hostIterator[0].hasNext()) try {
- HostQueue entry = hostsIterator.next();
+ final HostQueue entry = hostsIterator.next();
hostIterator[0] = entry.iterator();
- } catch (IOException e) {}
+ } catch (final IOException e) {}
if (!hostIterator[0].hasNext()) return null;
return hostIterator[0].next();
}
@@ -539,9 +551,9 @@ public class HostBalancer implements Balancer {
*/
@Override
public Map<String, Integer[]> getDomainStackHosts(RobotsTxt robots) {
- Map<String, Integer[]> map = new TreeMap<String, Integer[]>(); // we use a tree map to get a stable ordering
- for (HostQueue hq: this.queues.values()) {
- int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), hq.getHostHash(), robots, ClientIdentification.yacyInternetCrawlerAgent);
+ final Map<String, Integer[]> map = new TreeMap<>(); // we use a tree map to get a stable ordering
+ for (final HostQueue hq: this.queues.values()) {
+ final int delta = Latency.waitingRemainingGuessed(hq.getHost(), hq.getPort(), hq.getHostHash(), robots, ClientIdentification.yacyInternetCrawlerAgent);
map.put(hq.getHost() + ":" + hq.getPort(), new Integer[]{hq.size(), delta});
}
return map;
@@ -562,7 +574,7 @@ public class HostBalancer implements Balancer {
try {
HostQueue hq = this.queues.get(DigestURL.hosthash(host, host.startsWith("ftp.") ? 21 : 80));
if (hq == null) hq = this.queues.get(DigestURL.hosthash(host, 443));
- return hq == null ? new ArrayList<Request>(0) : hq.getDomainStackReferences(host, maxcount, maxtime);
+ return hq == null ? new ArrayList<>(0) : hq.getDomainStackReferences(host, maxcount, maxtime);
} catch (final MalformedURLException e) {
ConcurrentLog.logException(e);
return Collections.emptyList();
diff --git a/source/net/yacy/crawler/HostQueue.java b/source/net/yacy/crawler/HostQueue.java
index ea492dda9..dec1a420c 100644
--- a/source/net/yacy/crawler/HostQueue.java
+++ b/source/net/yacy/crawler/HostQueue.java
@@ -1,6 +1,6 @@
/**
* HostQueue
- * SPDX-FileCopyrightText: 2013 Michael Peter Christen <[email protected])>
+ * SPDX-FileCopyrightText: 2013 Michael Peter Christen <[email protected])>
* SPDX-License-Identifier: GPL-2.0-or-later
* First released 24.09.2013 at http://yacy.net
*
@@ -8,12 +8,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library 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
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -65,7 +65,7 @@ import net.yacy.search.Switchboard;
public class HostQueue implements Balancer {
private final static ConcurrentLog log = new ConcurrentLog("HostQueue");
-
+
public static final String indexSuffix = ".stack";
private static final int EcoFSBufferSize = 1000;
private static final int objectIndexBufferSize = 1000;
@@ -100,19 +100,19 @@ public class HostQueue implements Balancer {
this.hostHash = hostUrl.hosthash(); // hosthash is calculated by protocol + hostname + port
// hostName/port included just for human readability (& historically), "-#" marker used to define begin of hosthash in directoryname
if(this.hostName.startsWith("[") && this.hostName.endsWith("]") && this.hostName.contains(":")) {
- /* Percent-encode the host name when it is an IPV6 address, as the ':' character is illegal in a file name on MS Windows FAT32 and NTFS file systems */
- File path;
- try {
- path = new File(hostsPath, URLEncoder.encode(this.hostName, StandardCharsets.UTF_8.name()) + "-#"+ this.hostHash + "." + this.port);
- } catch (final UnsupportedEncodingException e) {
- /* This should not happen has UTF-8 encoding support is required for any JVM implementation */
- path = new File(hostsPath, this.hostName + "-#"+ this.hostHash + "." + this.port);
- }
- this.hostPath = path;
+ /* Percent-encode the host name when it is an IPV6 address, as the ':' character is illegal in a file name on MS Windows FAT32 and NTFS file systems */
+ File path;
+ try {
+ path = new File(hostsPath, URLEncoder.encode(this.hostName, StandardCharsets.UTF_8.name()) + "-#"+ this.hostHash + "." + this.port);
+ } catch (final UnsupportedEncodingException e) {
+ /* This should not happen has UTF-8 encoding support is required for any JVM implementation */
+ path = new File(hostsPath, this.hostName + "-#"+ this.hostHash + "." + this.port);
+ }
+ this.hostPath = path;
} else {
this.hostPath = new File(hostsPath, this.hostName + "-#"+ this.hostHash + "." + this.port);
}
- init();
+ this.init();
}
/**
@@ -132,27 +132,27 @@ public class HostQueue implements Balancer {
this.exceed134217727 = exceed134217727;
this.hostPath = hostPath;
// parse the hostName and port from the file name
- String filename = hostPath.getName();
- int pdot = filename.lastIndexOf('.');
+ final String filename = hostPath.getName();
+ final int pdot = filename.lastIndexOf('.');
if (pdot < 0) throw new RuntimeException("hostPath name must contain a dot: " + filename);
this.port = Integer.parseInt(filename.substring(pdot + 1)); // consider "host.com" contains dot but no required port -> will throw exception
- int p1 = filename.lastIndexOf("-#");
+ final int p1 = filename.lastIndexOf("-#");
if (p1 >= 0) {
String hostNameInFile = filename.substring(0,p1);
if(hostNameInFile.startsWith("%5B") && hostNameInFile.endsWith("%5D") && hostNameInFile.contains("%3A")) {
- /* Host name is a percent-encoded IPV6 address */
- try {
- hostNameInFile = URLDecoder.decode(hostNameInFile, StandardCharsets.UTF_8.name());
- } catch (final UnsupportedEncodingException | RuntimeException ignored) {
- /* This should not happen has UTF-8 encoding support is required for any JVM implementation */
- }
- this.hostName = hostNameInFile;
+ /* Host name is a percent-encoded IPV6 address */
+ try {
+ hostNameInFile = URLDecoder.decode(hostNameInFile, StandardCharsets.UTF_8.name());
+ } catch (final UnsupportedEncodingException | RuntimeException ignored) {
+ /* This should not happen has UTF-8 encoding support is required for any JVM implementation */
+ }
+ this.hostName = hostNameInFile;
} else {
- this.hostName = hostNameInFile;
+ this.hostName = hostNameInFile;
}
this.hostHash = filename.substring(p1+2,pdot);
} else throw new RuntimeException("hostPath name must contain -# followd by hosthash: " + filename);
- init();
+ this.init();
}
/**
@@ -166,38 +166,38 @@ public class HostQueue implements Balancer {
throw new MalformedURLException("hostPath could not be created: " + this.hostPath.toString());
}
}
- this.depthStacks = new TreeMap<Integer, Index>();
- int size = openAllStacks();
+ this.depthStacks = new TreeMap<>();
+ final int size = this.openAllStacks();
if (log.isInfo()) log.info("opened HostQueue " + this.hostPath.getAbsolutePath() + " with " + size + " urls.");
}
-
+
public String getHost() {
return this.hostName;
}
-
+
public int getPort() {
return this.port;
}
-
+
/**
* Get the hosthash of this queue determined during init.
- *
- * @return
+ *
+ * @return
*/
public String getHostHash() {
return this.hostHash;
}
private int openAllStacks() {
- String[] l = this.hostPath.list();
+ final String[] l = this.hostPath.list();
int c = 0;
- if (l != null) for (String s: l) {
+ if (l != null) for (final String s: l) {
if (s.endsWith(indexSuffix)) try {
- int depth = Integer.parseInt(s.substring(0, s.length() - indexSuffix.length()));
- File stackFile = new File(this.hostPath, s);
- Index depthStack = openStack(stackFile);
+ final int depth = Integer.parseInt(s.substring(0, s.length() - indexSuffix.length()));
+ final File stackFile = new File(this.hostPath, s);
+ final Index depthStack = this.openStack(stackFile);
if (depthStack != null) {
- int sz = depthStack.size();
+ final int sz = depthStack.size();
if (sz == 0) {
depthStack.close();
deletedelete(stackFile);
@@ -206,7 +206,7 @@ public class HostQueue implements Balancer {
c += sz;
}
}
- } catch (NumberFormatException e) {}
+ } catch (final NumberFormatException e) {}
}
return c;
}
@@ -220,7 +220,7 @@ public class HostQueue implements Balancer {
if (entry == null) return null; // happens only if map is empty
if (entry.getValue().size() == 0) {
entry.getValue().close();
- deletedelete(getFile(entry.getKey()));
+ deletedelete(this.getFile(entry.getKey()));
this.depthStacks.remove(entry.getKey());
continue;
}
@@ -237,47 +237,47 @@ public class HostQueue implements Balancer {
* @param depth
* @return existing or new/empty stack
*/
- private Index getStack(int depth) {
+ private Index getStack(final int depth) {
Index depthStack;
// create a new stack
synchronized (this) {
depthStack = this.depthStacks.get(depth);
if (depthStack != null) return depthStack;
// now actually create a new stack
- final File f = getFile(depth);
- depthStack = openStack(f);
+ final File f = this.getFile(depth);
+ depthStack = this.openStack(f);
if (depthStack != null) this.depthStacks.put(depth, depthStack);
}
return depthStack;
}
-
- private File getFile(int depth) {
+
+ private File getFile(final int depth) {
String name = Integer.toString(depth);
while (name.length() < 4) name = "0" + name;
final File f = new File(this.hostPath, name + indexSuffix);
return f;
}
-
+
private Index openStack(File f) {
for (int i = 0; i < 10; i++) {
// we try that again if it fails because it shall not fail
if (this.onDemand && (!f.exists() || f.length() < 10000)) {
try {
- return new BufferedObjectIndex(new OnDemandOpenFileIndex(f, Request.rowdef, exceed134217727), objectIndexBufferSize);
- } catch (kelondroException e) {
+ return new BufferedObjectIndex(new OnDemandOpenFileIndex(f, Request.rowdef, this.exceed134217727), objectIndexBufferSize);
+ } catch (final kelondroException e) {
// possibly the file was closed meanwhile
ConcurrentLog.logException(e);
}
} else {
try {
- return new BufferedObjectIndex(new Table(f, Request.rowdef, EcoFSBufferSize, 0, false, exceed134217727, true), objectIndexBufferSize);
+ return new BufferedObjectIndex(new Table(f, Request.rowdef, EcoFSBufferSize, 0, false, this.exceed134217727, true), objectIndexBufferSize);
} catch (final SpaceExceededException e) {
try {
- return new BufferedObjectIndex(new Table(f, Request.rowdef, 0, 0, false, exceed134217727, true), objectIndexBufferSize);
+ return new BufferedObjectIndex(new Table(f, Request.rowdef, 0, 0, false, this.exceed134217727, true), objectIndexBufferSize);
} catch (final SpaceExceededException e1) {
ConcurrentLog.logException(e1);
}
- } catch (kelondroException e) {
+ } catch (final kelondroException e) {
// possibly the file was closed meanwhile
ConcurrentLog.logException(e);
}
@@ -288,25 +288,25 @@ public class HostQueue implements Balancer {
@Override
public synchronized void close() {
- for (Map.Entry<Integer, Index> entry: this.depthStacks.entrySet()) {
- int size = entry.getValue().size();
+ for (final Map.Entry<Integer, Index> entry: this.depthStacks.entrySet()) {
+ final int size = entry.getValue().size();
entry.getValue().close();
- if (size == 0) deletedelete(getFile(entry.getKey()));
+ if (size == 0) deletedelete(this.getFile(entry.getKey()));
}
this.depthStacks.clear();
- String[] l = this.hostPath.list();
+ final String[] l = this.hostPath.list();
if ((l == null || l.length == 0) && this.hostPath != null) deletedelete(this.hostPath);
}
@Override
public synchronized void clear() {
- for (Map.Entry<Integer, Index> entry: this.depthStacks.entrySet()) {
+ for (final Map.Entry<Integer, Index> entry: this.depthStacks.entrySet()) {
entry.getValue().close();
- deletedelete(getFile(entry.getKey()));
+ deletedelete(this.getFile(entry.getKey()));
}
this.depthStacks.clear();
- String[] l = this.hostPath.list();
- if (l != null) for (String s: l) {
+ final String[] l = this.hostPath.list();
+ if (l != null) for (final String s: l) {
deletedelete(new File(this.hostPath, s));
}
deletedelete(this.hostPath);
@@ -316,7 +316,7 @@ public class HostQueue implements Balancer {
public Request get(final byte[] urlhash) throws IOException {
assert urlhash != null;
if (this.depthStacks == null) return null; // case occurs during shutdown
- for (Index depthStack: this.depthStacks.values()) {
+ for (final Index depthStack: this.depthStacks.values()) {
final Row.Entry entry = depthStack.get(urlhash, false);
if (entry == null) return null;
return new Request(entry);
@@ -330,7 +330,7 @@ public class HostQueue implements Balancer {
final long terminate = timeout == Long.MAX_VALUE ? Long.MAX_VALUE : (timeout > 0) ? System.currentTimeMillis() + timeout : Long.MAX_VALUE;
int count = 0;
synchronized (this) {
- for (Index depthStack: this.depthStacks.values()) {
+ for (final Index depthStack: this.depthStacks.values()) {
final HandleSet urlHashes = new RowHandleSet(Word.commonHashLength, Base64Order.enhancedCoder, 100);
final Iterator<Row.Entry> i = depthStack.rows();
Row.Entry rowEntry;
@@ -351,7 +351,7 @@ public class HostQueue implements Balancer {
}
return count;
}
-
+
/**
* delete all urls which are stored for given host hashes
* @param hosthashes
@@ -359,9 +359,9 @@ public class HostQueue implements Balancer {
*/
@Override
public int removeAllByHostHashes(final Set<String> hosthashes) {
- for (String h: hosthashes) {
+ for (final String h: hosthashes) {
if (this.hostHash.equals(h)) {
- int s = this.size();
+ final int s = this.size();
this.clear();
return s;
}
@@ -378,7 +378,7 @@ public class HostQueue implements Balancer {
@Override
public synchronized int remove(final HandleSet urlHashes) throws IOException {
int removedCounter = 0;
- for (Index depthStack: this.depthStacks.values()) {
+ for (final Index depthStack: this.depthStacks.values()) {
final int s = depthStack.size();
for (final byte[] urlhash: urlHashes) {
final Row.Entry entry = depthStack.remove(urlhash);
@@ -394,11 +394,11 @@ public class HostQueue implements Balancer {
public boolean has(final byte[] urlhashb) {
for (int retry = 0; retry < 3; retry++) {
try {
- for (Index depthStack: this.depthStacks.values()) {
+ for (final Index depthStack: this.depthStacks.values()) {
if (depthStack.has(urlhashb)) return true;
}
return false;
- } catch (ConcurrentModificationException e) {}
+ } catch (final ConcurrentModificationException e) {}
}
return false;
}
@@ -406,7 +406,7 @@ public class HostQueue implements Balancer {
@Override
public int size() {
int size = 0;
- for (Index depthStack: this.depthStacks.values()) {
+ for (final Index depthStack: this.depthStacks.values()) {
size += depthStack.size();
}
return size;
@@ -414,7 +414,7 @@ public class HostQueue implements Balancer {
@Override
public boolean isEmpty() {
- for (Index depthStack: this.depthStacks.values()) {
+ for (final Index depthStack: this.depthStacks.values()) {
if (!depthStack.isEmpty()) return false;
}
return true;
@@ -430,15 +430,15 @@ public class HostQueue implements Balancer {
// increase dom counter
if (profile != null) {
- int maxPages = profile.domMaxPages();
+ final int maxPages = profile.domMaxPages();
if (maxPages != Integer.MAX_VALUE && maxPages > 0) {
- String host = entry.url().getHost();
+ final String host = entry.url().getHost();
profile.domInc(host);
}
}
-
+
// add to index
- Index depthStack = getStack(entry.depth());
+ final Index depthStack = this.getStack(entry.depth());
final int s = depthStack.size();
depthStack.put(entry.toRow());
assert s < depthStack.size() : "hash = " + ASCII.String(hash) + ", s = " + s + ", size = " + depthStack.size();
@@ -456,12 +456,12 @@ public class HostQueue implements Balancer {
CrawlProfile profileEntry = null;
synchronized (this) {
mainloop: while (true) {
- Index depthStack = getLowestStack();
+ final Index depthStack = this.getLowestStack();
if (depthStack == null) return null;
Row.Entry rowEntry = null;
- while (depthStack.size() > 0) {
+ depthstack: while (depthStack.size() > 0) {
rowEntry = depthStack.removeOne();
- if (rowEntry != null) break;
+ if (rowEntry != null) break depthstack;
}
if (rowEntry == null) continue mainloop;
crawlEntry = new Request(rowEntry);
@@ -479,16 +479,18 @@ public class HostQueue implements Balancer {
if (log.isFine()) log.fine("no profile entry for handle " + crawlEntry.profileHandle());
continue mainloop;
}
-
+
// depending on the caching policy we need sleep time to avoid DoS-like situations
sleeptime = Latency.getDomainSleepTime(robots, profileEntry, crawlEntry.url());
- break;
+ break mainloop;
}
}
if (crawlEntry == null) return null;
- ClientIdentification.Agent agent = profileEntry == null ? ClientIdentification.yacyInternetCrawlerAgent : profileEntry.getAgent();
- long robotsTime = Latency.getRobotsTime(robots, crawlEntry.url(), agent);
+ final ClientIdentification.Agent agent = profileEntry == null ? ClientIdentification.yacyInternetCrawlerAgent : profileEntry.getAgent();
+ final long robotsTime = Latency.getRobotsTime(robots, crawlEntry.url(), agent);
Latency.updateAfterSelection(crawlEntry.url(), profileEntry == null ? 0 : robotsTime);
+
+ // the following case should be avoided by selection previously
if (delay && sleeptime > 0) {
// force a busy waiting here
// in best case, this should never happen if the balancer works properly
@@ -502,13 +504,10 @@ public class HostQueue implements Balancer {
loops = 0;
}
Thread.currentThread().setName("Balancer waiting for " + crawlEntry.url().getHost() + ": " + sleeptime + " milliseconds");
- synchronized(this) {
- // must be synchronized here to avoid 'takeover' moves from other threads which then idle the same time which would not be enough
- if (rest > 0) {try {this.wait(rest);} catch (final InterruptedException e) {}}
- for (int i = 0; i < loops; i++) {
- if (log.isInfo()) log.info("waiting for " + crawlEntry.url().getHost() + ": " + (loops - i) + " seconds remaining...");
- try {this.wait(1000); } catch (final InterruptedException e) {}
- }
+ if (rest > 0) {try {Thread.sleep(rest);} catch (final InterruptedException e) {}}
+ for (int i = 0; i < loops; i++) {
+ if (log.isInfo()) log.info("waiting for " + crawlEntry.url().getHost() + ": " + (loops - i) + " seconds remaining...");
+ try {Thread.sleep(1000); } catch (final InterruptedException e) {}
}
Latency.updateAfterSelection(crawlEntry.url(), robotsTime);
}
@@ -531,14 +530,14 @@ public class HostQueue implements Balancer {
synchronized (HostQueue.this) {
try {
while (rowIterator[0] == null || !rowIterator[0].hasNext()) {
- Map.Entry<Integer, Index> entry = depthIterator.next();
+ final Map.Entry<Integer, Index> entry = depthIterator.next();
rowIterator[0] = entry.getValue().iterator();
}
if (!rowIterator[0].hasNext()) return null;
- Row.Entry rowEntry = rowIterator[0].next();
+ final Row.Entry rowEntry = rowIterator[0].next();
if (rowEntry == null) return null;
return new Request(rowEntry);
- } catch (Throwable e) {
+ } catch (final Throwable e) {
return null;
}
}
@@ -556,8 +555,8 @@ public class HostQueue implements Balancer {
*/
@Override
public Map<String, Integer[]> getDomainStackHosts(RobotsTxt robots) {
- Map<String, Integer[]> map = new TreeMap<String, Integer[]>();
- int delta = Latency.waitingRemainingGuessed(this.hostName, this.port, this.hostHash, robots, ClientIdentification.yacyInternetCrawlerAgent);
+ final Map<String, Integer[]> map = new TreeMap<>();
+ final int delta = Latency.waitingRemainingGuessed(this.hostName, this.port, this.hostHash, robots, ClientIdentification.yacyInternetCrawlerAgent);
map.put(this.hostName, new Integer[]{this.size(), delta});
return map;
}
@@ -571,19 +570,19 @@ public class HostQueue implements Balancer {
*/
@Override
public List<Request> getDomainStackReferences(String host, int maxcount, long maxtime) {
- if (host == null) return new ArrayList<Request>(0);
- if (!this.hostName.equals(host)) return new ArrayList<Request>(0);
- final ArrayList<Request> cel = new ArrayList<Request>(maxcount);
- long timeout = maxtime == Long.MAX_VALUE ? Long.MAX_VALUE : System.currentTimeMillis() + maxtime;
+ if (host == null) return new ArrayList<>(0);
+ if (!this.hostName.equals(host)) return new ArrayList<>(0);
+ final ArrayList<Request> cel = new ArrayList<>(maxcount);
+ final long timeout = maxtime == Long.MAX_VALUE ? Long.MAX_VALUE : System.currentTimeMillis() + maxtime;
Iterator<Request> i;
try {
i = this.iterator();
while (i.hasNext()) {
- Request r = i.next();
+ final Request r = i.next();
if (r != null) cel.add(r);
if (System.currentTimeMillis() > timeout || cel.size() >= maxcount) break;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
}
return cel;
}
diff --git a/source/net/yacy/crawler/LegacyBalancer.java b/source/net/yacy/crawler/LegacyBalancer.java
index 6355327ef..c3a91e956 100644
--- a/source/net/yacy/crawler/LegacyBalancer.java
+++ b/source/net/yacy/crawler/LegacyBalancer.java
@@ -1,8 +1,8 @@
// LegacyBalancer.java
// -----------------------
// part of YaCy
-// SPDX-FileCopyrightText: 2005 Michael Peter Christen <[email protected])>
-// SPDX-License-Identifier: GPL-2.0-or-later
+// SPDX-FileCopyrightText: 2005 Michael Peter Christen <[email protected])>
+// SPDX-License-Identifier: GPL-2.0-or-later
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
// created: 24.09.2005
@@ -95,19 +95,19 @@ public class LegacyBalancer implements Balancer {
this.handleSet = handleSet;
}
}
-
+
public LegacyBalancer(
final File cachePath,
final String stackname,
final boolean useTailCache,
final boolean exceed134217727) {
this.cacheStacksPath = cachePath;
- this.domainStacks = new ConcurrentHashMap<String, HostHandles>();
+ this.domainStacks = new ConcurrentHashMap<>();
this.domStackInitSize = Integer.MAX_VALUE;
this.double_push_check = new RowHandleSet(Word.commonHashLength, Word.commonHashOrder, 0);
- this.zeroWaitingCandidates = new ArrayList<Map.Entry<String, byte[]>>();
+ this.zeroWaitingCandidates = new ArrayList<>();
this.random = new Random(System.currentTimeMillis());
-
+
// create a stack for newly entered entries
if (!(cachePath.exists())) cachePath.mkdir(); // make the path
this.cacheStacksPath.mkdirs();
@@ -122,7 +122,7 @@ public class LegacyBalancer implements Balancer {
}
}
this.lastDomainStackFill = 0;
- ConcurrentLog.info("Balancer", "opened balancer file with " + this.urlFileIndex.size() + " entries from " + f.toString());
+ ConcurrentLog.info("LEGACY BALANCER", "opened balancer file with " + this.urlFileIndex.size() + " entries from " + f.toString());
}
@Override
@@ -135,7 +135,7 @@ public class LegacyBalancer implements Balancer {
@Override
public void clear() {
- ConcurrentLog.info("Balancer", "cleaning balancer with " + this.urlFileIndex.size() + " entries from " + this.urlFileIndex.filename());
+ ConcurrentLog.info("LEGACY BALANCER", "cleaning balancer with " + this.urlFileIndex.size() + " entries from " + this.urlFileIndex.filename());
try {
this.urlFileIndex.clear();
} catch (final IOException e) {
@@ -177,7 +177,7 @@ public class LegacyBalancer implements Balancer {
}
// then delete all these urls from the queues and the file index
- return remove(urlHashes);
+ return this.remove(urlHashes);
}
/**
@@ -210,7 +210,7 @@ public class LegacyBalancer implements Balancer {
for (final byte[] handle: urlHashes) stack.remove(handle);
if (stack.isEmpty()) q.remove();
}
-
+
// iterate through zero-waiting map
final Iterator<Map.Entry<String, byte[]>> i = this.zeroWaitingCandidates.iterator();
while (i.hasNext()) {
@@ -258,7 +258,7 @@ public class LegacyBalancer implements Balancer {
if (profile != null && profile.domMaxPages() != Integer.MAX_VALUE && profile.domMaxPages() > 0) {
profile.domInc(entry.url().getHost());
}
-
+
// add to index
final int s = this.urlFileIndex.size();
this.urlFileIndex.put(entry.toRow());
@@ -279,12 +279,12 @@ public class LegacyBalancer implements Balancer {
*/
@Override
public Map<String, Integer[]> getDomainStackHosts(RobotsTxt robots) {
- Map<String, Integer[]> map = new TreeMap<String, Integer[]>(); // we use a tree map to get a stable ordering
- for (Map.Entry<String, HostHandles> entry: this.domainStacks.entrySet()) {
+ final Map<String, Integer[]> map = new TreeMap<>(); // we use a tree map to get a stable ordering
+ for (final Map.Entry<String, HostHandles> entry: this.domainStacks.entrySet()) {
final String hostname = entry.getKey();
final HostHandles hosthandles = entry.getValue();
- int size = hosthandles.handleSet.size();
- int delta = Latency.waitingRemainingGuessed(hostname, 80, hosthandles.hosthash, robots, ClientIdentification.yacyInternetCrawlerAgent);
+ final int size = hosthandles.handleSet.size();
+ final int delta = Latency.waitingRemainingGuessed(hostname, 80, hosthandles.hosthash, robots, ClientIdentification.yacyInternetCrawlerAgent);
map.put(hostname, new Integer[]{size, delta});
}
return map;
@@ -300,12 +300,12 @@ public class LegacyBalancer implements Balancer {
@Override
public List<Request> getDomainStackReferences(final String host, int maxcount, final long maxtime) {
final HostHandles hh = this.domainStacks.get(host);
- if (hh == null) return new ArrayList<Request>(0);
+ if (hh == null) return new ArrayList<>(0);
final HandleSet domainList = hh.handleSet;
- if (domainList.isEmpty()) return new ArrayList<Request>(0);
+ if (domainList.isEmpty()) return new ArrayList<>(0);
maxcount = Math.min(maxcount, domainList.size());
- final ArrayList<Request> cel = new ArrayList<Request>(maxcount);
- long timeout = maxtime == Long.MAX_VALUE ? Long.MAX_VALUE : System.currentTimeMillis() + maxtime;
+ final ArrayList<Request> cel = new ArrayList<>(maxcount);
+ final long timeout = maxtime == Long.MAX_VALUE ? Long.MAX_VALUE : System.currentTimeMillis() + maxtime;
for (int i = 0; i < maxcount; i++) {
final byte[] urlhash = domainList.getOne(i);
if (urlhash == null) continue;
@@ -331,14 +331,14 @@ public class LegacyBalancer implements Balancer {
private void pushHashToDomainStacks(String host, String hosthash, final byte[] urlhash) throws SpaceExceededException {
// extend domain stack
if (host == null) host = Domains.LOCALHOST;
- HostHandles hh = this.domainStacks.get(host);
+ final HostHandles hh = this.domainStacks.get(host);
if (hh == null) {
// create new list
- HandleSet domainList = new RowHandleSet(Word.commonHashLength, Base64Order.enhancedCoder, 1);
+ final HandleSet domainList = new RowHandleSet(Word.commonHashLength, Base64Order.enhancedCoder, 1);
domainList.put(urlhash);
this.domainStacks.put(host, new HostHandles(hosthash, domainList));
} else {
- HandleSet domainList = hh.handleSet;
+ final HandleSet domainList = hh.handleSet;
// extend existent domain list
domainList.put(urlhash);
}
@@ -347,20 +347,19 @@ public class LegacyBalancer implements Balancer {
private void removeHashFromDomainStacks(String host, final byte[] urlhash) {
// reduce domain stack
if (host == null) host = Domains.LOCALHOST;
- HostHandles hh = this.domainStacks.get(host);
+ final HostHandles hh = this.domainStacks.get(host);
if (hh == null) {
this.domainStacks.remove(host);
return;
}
- HandleSet domainList = hh.handleSet;
+ final HandleSet domainList = hh.handleSet;
domainList.remove(urlhash);
if (domainList.isEmpty()) this.domainStacks.remove(host);
}
/**
* get the next entry in this crawl queue in such a way that the domain access time delta is maximized
- * and always above the given minimum delay time. An additional delay time is computed using the robots.txt
- * crawl-delay time which is always respected. In case the minimum time cannot ensured, this method pauses
+ * and always above the given minimum delay time. In case the minimum time cannot ensured, this method pauses
* the necessary time until the url is released and returned as CrawlEntry object. In case that a profile
* for the computed Entry does not exist, null is returned
* @param delay true if the requester demands forced delays using explicit thread sleep
@@ -376,51 +375,51 @@ public class LegacyBalancer implements Balancer {
long sleeptime = 0;
Request crawlEntry = null;
CrawlProfile profileEntry = null;
- byte[] failhash = null;
+ final byte[] failhash = null;
while (!this.urlFileIndex.isEmpty()) {
- byte[] nexthash = getbest(robots, cs);
+ final byte[] nexthash = this.getbest(robots, cs);
if (nexthash == null) return null;
-
+
synchronized (this) {
- Row.Entry rowEntry = (nexthash == null) ? null : this.urlFileIndex.remove(nexthash);
+ final Row.Entry rowEntry = (nexthash == null) ? null : this.urlFileIndex.remove(nexthash);
if (rowEntry == null) continue;
-
+
crawlEntry = new Request(rowEntry);
- //Log.logInfo("Balancer", "fetched next url: " + crawlEntry.url().toNormalform(true, false));
-
+ //Log.logInfo("LEGACY BALANCER", "fetched next url: " + crawlEntry.url().toNormalform(true, false));
+
// check blacklist (again) because the user may have created blacklist entries after the queue has been filled
if (Switchboard.urlBlacklist.isListed(BlacklistType.CRAWLER, crawlEntry.url())) {
ConcurrentLog.fine("CRAWLER", "URL '" + crawlEntry.url() + "' is in blacklist.");
continue;
}
-
+
// at this point we must check if the crawlEntry has relevance because the crawl profile still exists
// if not: return null. A calling method must handle the null value and try again
profileEntry = cs.get(UTF8.getBytes(crawlEntry.profileHandle()));
if (profileEntry == null) {
- ConcurrentLog.fine("Balancer", "no profile entry for handle " + crawlEntry.profileHandle());
+ ConcurrentLog.fine("LEGACY BALANCER", "no profile entry for handle " + crawlEntry.profileHandle());
continue;
}
// depending on the caching policy we need sleep time to avoid DoS-like situations
sleeptime = Latency.getDomainSleepTime(robots, profileEntry, crawlEntry.url());
-
+
assert Base64Order.enhancedCoder.equal(nexthash, rowEntry.getPrimaryKeyBytes()) : "result = " + ASCII.String(nexthash) + ", rowEntry.getPrimaryKeyBytes() = " + ASCII.String(rowEntry.getPrimaryKeyBytes());
assert Base64Order.enhancedCoder.equal(nexthash, crawlEntry.url().hash()) : "result = " + ASCII.String(nexthash) + ", crawlEntry.url().hash() = " + ASCII.String(crawlEntry.url().hash());
-
+
if (failhash != null && Base64Order.enhancedCoder.equal(failhash, nexthash)) break; // prevent endless loops
break;
}
}
if (crawlEntry == null) return null;
- ClientIdentification.Agent agent = profileEntry == null ? ClientIdentification.yacyInternetCrawlerAgent : profileEntry.getAgent();
- long robotsTime = Latency.getRobotsTime(robots, crawlEntry.url(), agent);
+ final ClientIdentification.Agent agent = profileEntry == null ? ClientIdentification.yacyInternetCrawlerAgent : profileEntry.getAgent();
+ final long robotsTime = Latency.getRobotsTime(robots, crawlEntry.url(), agent);
Latency.updateAfterSelection(crawlEntry.url(), profileEntry == null ? 0 : robotsTime);
if (delay && sleeptime > 0) {
// force a busy waiting here
// in best case, this should never happen if the balancer works properly
// this is only to protection against the worst case, where the crawler could
// behave in a DoS-manner
- ConcurrentLog.info("BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ": " + Latency.waitingRemainingExplain(crawlEntry.url(), robots, agent) + ", domainStacks.size() = " + this.domainStacks.size() + ", domainStacksInitSize = " + this.domStackInitSize);
+ ConcurrentLog.info("LEGACY BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ": " + Latency.waitingRemainingExplain(crawlEntry.url(), robots, agent) + ", domainStacks.size() = " + this.domainStacks.size() + ", domainStacksInitSize = " + this.domStackInitSize);
long loops = sleeptime / 1000;
long rest = sleeptime % 1000;
if (loops < 3) {
@@ -430,10 +429,10 @@ public class LegacyBalancer implements Balancer {
Thread.currentThread().setName("Balancer waiting for " +crawlEntry.url().getHost() + ": " + sleeptime + " milliseconds");
synchronized(this) {
// must be synchronized here to avoid 'takeover' moves from other threads which then idle the same time which would not be enough
- if (rest > 0) {try {this.wait(rest);} catch (final InterruptedException e) {}}
+ if (rest > 0) {try {Thread.sleep(rest);} catch (final InterruptedException e) {}}
for (int i = 0; i < loops; i++) {
- ConcurrentLog.info("BALANCER", "waiting for " + crawlEntry.url().getHost() + ": " + (loops - i) + " seconds remaining...");
- try {this.wait(1000); } catch (final InterruptedException e) {}
+ ConcurrentLog.info("LEGACY BALANCER", "waiting for " + crawlEntry.url().getHost() + ": " + (loops - i) + " seconds remaining...");
+ try {Thread.sleep(1000); } catch (final InterruptedException e) {}
}
}
Latency.updateAfterSelection(crawlEntry.url(), robotsTime);
@@ -445,86 +444,86 @@ public class LegacyBalancer implements Balancer {
synchronized (this.zeroWaitingCandidates) {
if (this.zeroWaitingCandidates.size() > 0) {
- byte[] urlhash = pickFromZeroWaiting();
+ final byte[] urlhash = this.pickFromZeroWaiting();
if (urlhash != null) return urlhash;
}
this.zeroWaitingCandidates.clear();
-
+
// check if we need to get entries from the file index
try {
- fillDomainStacks();
+ this.fillDomainStacks();
} catch (final IOException e) {
ConcurrentLog.logException(e);
}
-
+
// iterate over the domain stacks
final Iterator<Map.Entry<String, HostHandles>> i = this.domainStacks.entrySet().iterator();
Map.Entry<String, HostHandles> entry;
- OrderedScoreMap<Map.Entry<String, byte[]>> nextZeroCandidates = new OrderedScoreMap<Map.Entry<String, byte[]>>(null);
- OrderedScoreMap<Map.Entry<String, byte[]>> failoverCandidates = new OrderedScoreMap<Map.Entry<String, byte[]>>(null);
+ final OrderedScoreMap<Map.Entry<String, byte[]>> nextZeroCandidates = new OrderedScoreMap<>(null);
+ final OrderedScoreMap<Map.Entry<String, byte[]>> failoverCandidates = new OrderedScoreMap<>(null);
int newCandidatesForward = 1;
while (i.hasNext() && nextZeroCandidates.size() < 1000) {
entry = i.next();
final String hostname = entry.getKey();
final HostHandles hosthandles = entry.getValue();
-
+
// clean up empty entries
if (hosthandles.handleSet.isEmpty()) {
i.remove();
continue;
}
-
+
final byte[] urlhash = hosthandles.handleSet.getOne(0);
if (urlhash == null) continue;
-
+
int w;
Row.Entry rowEntry;
try {
rowEntry = this.urlFileIndex.get(urlhash, false);
if (rowEntry == null) continue; // may have been deleted there manwhile
- Request crawlEntry = new Request(rowEntry);
- CrawlProfile profileEntry = cs.get(UTF8.getBytes(crawlEntry.profileHandle()));
+ final Request crawlEntry = new Request(rowEntry);
+ final CrawlProfile profileEntry = cs.get(UTF8.getBytes(crawlEntry.profileHandle()));
if (profileEntry == null) {
- ConcurrentLog.warn("Balancer", "no profile entry for handle " + crawlEntry.profileHandle());
+ ConcurrentLog.warn("LEGACY BALANCER", "no profile entry for handle " + crawlEntry.profileHandle());
continue;
}
w = Latency.waitingRemaining(crawlEntry.url(), robots, profileEntry.getAgent());
} catch (final IOException e1) {
- ConcurrentLog.warn("Balancer", e1.getMessage(), e1);
+ ConcurrentLog.warn("LEGACY BALANCER", e1.getMessage(), e1);
continue;
}
if (w <= 0) {
if (w == Integer.MIN_VALUE) {
if (newCandidatesForward-- > 0) {
- nextZeroCandidates.set(new AbstractMap.SimpleEntry<String, byte[]>(hostname, urlhash), 10000);
+ nextZeroCandidates.set(new AbstractMap.SimpleEntry<>(hostname, urlhash), 10000);
} else {
- failoverCandidates.set(new AbstractMap.SimpleEntry<String, byte[]>(hostname, urlhash), 0);
+ failoverCandidates.set(new AbstractMap.SimpleEntry<>(hostname, urlhash), 0);
}
} else {
- nextZeroCandidates.set(new AbstractMap.SimpleEntry<String, byte[]>(hostname, urlhash), hosthandles.handleSet.size());
+ nextZeroCandidates.set(new AbstractMap.SimpleEntry<>(hostname, urlhash), hosthandles.handleSet.size());
}
} else {
- failoverCandidates.set(new AbstractMap.SimpleEntry<String, byte[]>(hostname, urlhash), w);
+ failoverCandidates.set(new AbstractMap.SimpleEntry<>(hostname, urlhash), w);
}
}
- //Log.logInfo("Balancer", "*** getbest: created new nextZeroCandidates-list, size = " + nextZeroCandidates.size() + ", domainStacks.size = " + this.domainStacks.size());
-
+ //Log.logInfo("LEGACY BALANCER", "*** getbest: created new nextZeroCandidates-list, size = " + nextZeroCandidates.size() + ", domainStacks.size = " + this.domainStacks.size());
+
if (!nextZeroCandidates.isEmpty()) {
// take some of the nextZeroCandidates and put the best into the zeroWaitingCandidates
int pick = nextZeroCandidates.size() <= 10 ? nextZeroCandidates.size() : Math.max(1, nextZeroCandidates.size() / 3);
- Iterator<Map.Entry<String, byte[]>> k = nextZeroCandidates.keys(false);
+ final Iterator<Map.Entry<String, byte[]>> k = nextZeroCandidates.keys(false);
while (k.hasNext() && pick-- > 0) {
this.zeroWaitingCandidates.add(k.next());
}
- //Log.logInfo("Balancer", "*** getbest: created new zeroWaitingCandidates-list, size = " + zeroWaitingCandidates.size() + ", domainStacks.size = " + this.domainStacks.size());
-
- return pickFromZeroWaiting();
+ //Log.logInfo("LEGACY BALANCER", "*** getbest: created new zeroWaitingCandidates-list, size = " + zeroWaitingCandidates.size() + ", domainStacks.size = " + this.domainStacks.size());
+
+ return this.pickFromZeroWaiting();
}
if (!failoverCandidates.isEmpty()) {
// bad luck: just take that one with least waiting
- Iterator<Map.Entry<String, byte[]>> k = failoverCandidates.keys(true);
+ final Iterator<Map.Entry<String, byte[]>> k = failoverCandidates.keys(true);
String besthost;
byte[] besturlhash;
Map.Entry<String, byte[]> hosthash;
@@ -533,13 +532,13 @@ public class LegacyBalancer implements Balancer {
//if (failoverCandidates.get(hosthash) > 2000) break; // thats too long; we want a second chance for this!
besthost = hosthash.getKey();
besturlhash = hosthash.getValue();
- removeHashFromDomainStacks(besthost, besturlhash);
- //Log.logInfo("Balancer", "*** getbest: no zero waiting candidates, besthost = " + besthost);
+ this.removeHashFromDomainStacks(besthost, besturlhash);
+ //Log.logInfo("LEGACY BALANCER", "*** getbest: no zero waiting candidates, besthost = " + besthost);
return besturlhash;
}
}
-
- //Log.logInfo("Balancer", "*** getbest: besturlhash == null");
+
+ //Log.logInfo("LEGACY BALANCER", "*** getbest: besturlhash == null");
return null; // this should never happen
}
}
@@ -549,21 +548,21 @@ public class LegacyBalancer implements Balancer {
String host = null;
byte[] hash = null;
while (this.zeroWaitingCandidates.size() > 0) {
- Map.Entry<String, byte[]> z = this.zeroWaitingCandidates.remove(this.random.nextInt(this.zeroWaitingCandidates.size()));
- HostHandles hh = this.domainStacks.get(z.getKey());
+ final Map.Entry<String, byte[]> z = this.zeroWaitingCandidates.remove(this.random.nextInt(this.zeroWaitingCandidates.size()));
+ final HostHandles hh = this.domainStacks.get(z.getKey());
if (hh == null) continue;
host = z.getKey(); if (host == null) continue;
hash = z.getValue(); if (hash == null) continue;
- removeHashFromDomainStacks(host, hash);
- ConcurrentLog.info("Balancer", "// getbest: picked a random from the zero-waiting stack: " + host + ", zeroWaitingCandidates.size = " + this.zeroWaitingCandidates.size());
+ this.removeHashFromDomainStacks(host, hash);
+ ConcurrentLog.info("LEGACY BALANCER", "// getbest: picked a random from the zero-waiting stack: " + host + ", zeroWaitingCandidates.size = " + this.zeroWaitingCandidates.size());
return hash;
}
- //Log.logInfo("Balancer", "*** getbest: picking from zero-waiting stack failed!" + " zeroWaitingCandidates.size = " + this.zeroWaitingCandidates.size());
+ //Log.logInfo("LEGACY BALANCER", "*** getbest: picking from zero-waiting stack failed!" + " zeroWaitingCandidates.size = " + this.zeroWaitingCandidates.size());
this.zeroWaitingCandidates.clear();
return null;
}
-
+
private void fillDomainStacks() throws IOException {
if (!this.domainStacks.isEmpty() && System.currentTimeMillis() - this.lastDomainStackFill < 60000L) return;
this.domainStacks.clear();
@@ -572,32 +571,32 @@ public class LegacyBalancer implements Balancer {
String host;
Request request;
int count = 0;
- long timeout = System.currentTimeMillis() + 5000;
- for (Row.Entry entry: this.urlFileIndex.random(10000)) {
+ final long timeout = System.currentTimeMillis() + 5000;
+ for (final Row.Entry entry: this.urlFileIndex.random(10000)) {
if (entry == null) continue;
request = new Request(entry);
-
+
// check blacklist (again) because the user may have created blacklist entries after the queue has been filled
if (Switchboard.urlBlacklist.isListed(BlacklistType.CRAWLER, request.url())) {
ConcurrentLog.fine("CRAWLER", "URL '" + request.url() + "' is in blacklist.");
try {blackhandles.put(entry.getPrimaryKeyBytes());} catch (final SpaceExceededException e) {}
continue;
}
-
+
host = request.url().getHost();
try {
- pushHashToDomainStacks(host, request.url().hosthash(), entry.getPrimaryKeyBytes());
+ this.pushHashToDomainStacks(host, request.url().hosthash(), entry.getPrimaryKeyBytes());
} catch (final SpaceExceededException e) {
break;
}
count++;
if (this.domainStacks.size() >= 1000 || count >= 100000 || System.currentTimeMillis() > timeout) break;
}
-
+
// if we collected blacklist entries then delete them now
- for (byte[] blackhandle: blackhandles) this.urlFileIndex.remove(blackhandle);
-
- ConcurrentLog.info("BALANCER", "re-fill of domain stacks; fileIndex.size() = " + this.urlFileIndex.size() + ", domainStacks.size = " + this.domainStacks.size() + ", blackhandles = " + blackhandles.size() + ", collection time = " + (System.currentTimeMillis() - this.lastDomainStackFill) + " ms");
+ for (final byte[] blackhandle: blackhandles) this.urlFileIndex.remove(blackhandle);
+
+ ConcurrentLog.info("LEGACY BALANCER", "re-fill of domain stacks; fileIndex.size() = " + this.urlFileIndex.size() + ", domainStacks.size = " + this.domainStacks.size() + ", blackhandles = " + blackhandles.size() + ", collection time = " + (System.currentTimeMillis() - this.lastDomainStackFill) + " ms");
this.domStackInitSize = this.domainStacks.size();
}
diff --git a/source/net/yacy/crawler/RecrawlBusyThread.java b/source/net/yacy/crawler/RecrawlBusyThread.java
index f8e9667e1..7c3571705 100644
--- a/source/net/yacy/crawler/RecrawlBusyThread.java
+++ b/source/net/yacy/crawler/RecrawlBusyThread.java
@@ -56,75 +56,75 @@ import net.yacy.search.schema.CollectionSchema;
*/
public class RecrawlBusyThread extends AbstractBusyThread {
- /** The thread name */
+ /** The thread name */
public final static String THREAD_NAME = "recrawlindex";
-
+
/** The default selection query */
public static final String DEFAULT_QUERY = CollectionSchema.fresh_date_dt.getSolrFieldName()+":[* TO NOW/DAY-1DAY]";
-
+
/** Default value for inclusion or not of documents with a https status different from 200 (success) */
public static final boolean DEFAULT_INCLUDE_FAILED = false;
-
+
/** The default value whether to delete on Recrawl */
public static final boolean DEFAULT_DELETE_ON_RECRAWL = false;
/** The current query selecting documents to recrawl */
private String currentQuery;
-
+
/** flag if docs with httpstatus_i <> 200 shall be recrawled */
private boolean includefailed;
-
+
/** flag whether to delete on Recrawl */
private boolean deleteOnRecrawl;
-
+
private int chunkstart = 0;
private final int chunksize = 100;
private final Switchboard sb;
-
+
/** buffer of urls to recrawl */
private final Set<DigestURL> urlstack;
-
+
/** The total number of candidate URLs found for recrawl */
private long urlsToRecrawl = 0;
-
+
/** Total number of URLs added to the crawler queue for recrawl */
private long recrawledUrlsCount = 0;
-
+
/** Total number of URLs rejected for some reason by the crawl stacker or the crawler queue */
private long rejectedUrlsCount = 0;
-
+
/** Total number of malformed URLs found */
private long malformedUrlsCount = 0;
-
+
/** Total number of malformed URLs deleted from index */
private long malformedUrlsDeletedCount = 0;
-
- private String solrSortBy;
-
+
+ private final String solrSortBy;
+
/** Set to true when more URLs are still to be processed */
private boolean moreToRecrawl = true;
-
+
/** True when the job terminated early because an error occurred when requesting the Solr index, or the Solr index was closed */
private boolean terminatedBySolrFailure = false;
-
+
/** The recrawl job start time */
private LocalDateTime startTime;
-
+
/** The recrawl job end time */
private LocalDateTime endTime;
- /**
- * @param xsb
- * the Switchboard instance holding server environment
- * @param query
- * the Solr selection query
- * @param includeFailed
- * set to true when documents with a https status different from 200
- * (success) must be included
- */
+ /**
+ * @param xsb
+ * the Switchboard instance holding server environment
+ * @param query
+ * the Solr selection query
+ * @param includeFailed
+ * set to true when documents with a https status different from 200
+ * (success) must be included
+ */
public RecrawlBusyThread(final Switchboard xsb, final String query, final boolean includeFailed, final boolean deleteOnRecrawl) {
super(3000, 1000); // set lower limits of cycle delay
- setName(THREAD_NAME);
+ this.setName(THREAD_NAME);
this.setIdleSleep(10*60000); // set actual cycle delays
this.setBusySleep(2*60000);
this.setPriority(Thread.MIN_PRIORITY);
@@ -133,15 +133,15 @@ public class RecrawlBusyThread extends AbstractBusyThread {
this.currentQuery = query;
this.includefailed = includeFailed;
this.deleteOnRecrawl = deleteOnRecrawl;
- this.urlstack = new HashSet<DigestURL>();
+ this.urlstack = new HashSet<>();
// workaround to prevent solr exception on existing index (not fully reindexed) since intro of schema with docvalues
// org.apache.solr.core.SolrCore java.lang.IllegalStateException: unexpected docvalues type NONE for field 'load_date_dt' (expected=NUMERIC). Use UninvertingReader or index with docvalues.
- solrSortBy = CollectionSchema.load_date_dt.getSolrFieldName() + " asc";
-
+ this.solrSortBy = CollectionSchema.load_date_dt.getSolrFieldName() + " asc";
+
final SolrConnector solrConnector = this.sb.index.fulltext().getDefaultConnector();
if (solrConnector != null && !solrConnector.isClosed()) {
- /* Ensure indexed data is up-to-date before running the main job */
- solrConnector.commit(true);
+ /* Ensure indexed data is up-to-date before running the main job */
+ solrConnector.commit(true);
}
}
@@ -162,19 +162,19 @@ public class RecrawlBusyThread extends AbstractBusyThread {
public String getQuery() {
return this.currentQuery;
}
-
- /**
- *
- * @param queryBase
- * the base query
- * @param includeFailed
- * set to true when documents with a https status different from 200
- * (success) must be included
- * @return the Solr selection query for candidate URLs to recrawl
- */
- public static final String buildSelectionQuery(final String queryBase, final boolean includeFailed) {
- return includeFailed ? queryBase : queryBase + " AND (" + CollectionSchema.httpstatus_i.name() + ":200)";
- }
+
+ /**
+ *
+ * @param queryBase
+ * the base query
+ * @param includeFailed
+ * set to true when documents with a https status different from 200
+ * (success) must be included
+ * @return the Solr selection query for candidate URLs to recrawl
+ */
+ public static final String buildSelectionQuery(final String queryBase, final boolean includeFailed) {
+ return includeFailed ? queryBase : queryBase + " AND (" + CollectionSchema.httpstatus_i.name() + ":200)";
+ }
/**
* Flag to include failed urls (httpstatus_i <> 200)
@@ -189,18 +189,18 @@ public class RecrawlBusyThread extends AbstractBusyThread {
public boolean getIncludeFailed () {
return this.includefailed;
}
-
+
public void setDeleteOnRecrawl(final boolean deleteOnRecrawl) {
this.deleteOnRecrawl = deleteOnRecrawl;
}
-
+
public boolean getDeleteOnRecrawl() {
return this.deleteOnRecrawl;
}
/**
* feed urls to the local crawler
- * (Switchboard.addToCrawler() is not used here, as there existing urls are always skiped)
+ * (Switchboard.addToCrawler() is not used here, as there existing urls are always skipped)
*
* @return true if urls were added/accepted to the crawler
*/
@@ -209,25 +209,25 @@ public class RecrawlBusyThread extends AbstractBusyThread {
int added = 0;
if (!this.urlstack.isEmpty()) {
- final CrawlProfile profile = sb.crawler.defaultRecrawlJobProfile;
+ final CrawlProfile profile = this.sb.crawler.defaultRecrawlJobProfile;
for (final DigestURL url : this.urlstack) {
- final Request request = new Request(ASCII.getBytes(this.sb.peers.mySeed().hash), url, null, "",
- new Date(), profile.handle(), 0, profile.timezoneOffset());
- String acceptedError = sb.crawlStacker.checkAcceptanceChangeable(url, profile, 0);
- if (!includefailed && acceptedError == null) { // skip check if failed docs to be included
- acceptedError = sb.crawlStacker.checkAcceptanceInitially(url, profile);
+ final Request request = new Request(ASCII.getBytes(this.sb.peers.mySeed().hash), url, null, "",
+ new Date(), profile.handle(), 0, profile.timezoneOffset());
+ String acceptedError = this.sb.crawlStacker.checkAcceptanceChangeable(url, profile, 0);
+ if (!this.includefailed && acceptedError == null) { // skip check if failed docs to be included
+ acceptedError = this.sb.crawlStacker.checkAcceptanceInitially(url, profile);
}
if (acceptedError != null) {
- this.rejectedUrlsCount++;
+ this.rejectedUrlsCount++;
ConcurrentLog.info(THREAD_NAME, "addToCrawler: cannot load " + url.toNormalform(true) + ": " + acceptedError);
continue;
}
final String s;
- s = sb.crawlQueues.noticeURL.push(NoticedURL.StackType.LOCAL, request, profile, sb.robots);
+ s = this.sb.crawlQueues.noticeURL.push(NoticedURL.StackType.LOCAL, request, profile, this.sb.robots);
if (s != null) {
- this.rejectedUrlsCount++;
+ this.rejectedUrlsCount++;
ConcurrentLog.info(THREAD_NAME, "addToCrawler: failed to add " + url.toNormalform(true) + ": " + s);
} else {
added++;
@@ -247,37 +247,37 @@ public class RecrawlBusyThread extends AbstractBusyThread {
@Override
public boolean job() {
// more than chunksize crawls are running, do nothing
- if (sb.crawlQueues.coreCrawlJobSize() > this.chunksize) {
+ if (this.sb.crawlQueues.coreCrawlJobSize() > this.chunksize) {
return false;
}
boolean didSomething = false;
if (this.urlstack.isEmpty()) {
- if(!this.moreToRecrawl) {
- /* We do not remove the thread from the Switchboard worker threads using serverSwitch.terminateThread(String,boolean),
- * because we want to be able to provide a report after its termination */
- terminate(false);
- } else {
- this.moreToRecrawl = processSingleQuery();
- /* Even if no more URLs are to recrawl, the job has done something by searching the Solr index */
- didSomething = true;
- }
+ if(!this.moreToRecrawl) {
+ /* We do not remove the thread from the Switchboard worker threads using serverSwitch.terminateThread(String,boolean),
+ * because we want to be able to provide a report after its termination */
+ this.terminate(false);
+ } else {
+ this.moreToRecrawl = this.processSingleQuery();
+ /* Even if no more URLs are to recrawl, the job has done something by searching the Solr index */
+ didSomething = true;
+ }
} else {
- didSomething = feedToCrawler();
+ didSomething = this.feedToCrawler();
}
return didSomething;
}
-
+
@Override
public synchronized void start() {
- this.startTime = LocalDateTime.now();
- super.start();
+ this.startTime = LocalDateTime.now();
+ super.start();
}
-
+
@Override
public void terminate(boolean waitFor) {
- super.terminate(waitFor);
- this.endTime = LocalDateTime.now();
+ super.terminate(waitFor);
+ this.endTime = LocalDateTime.now();
}
/**
@@ -289,134 +289,134 @@ public class RecrawlBusyThread extends AbstractBusyThread {
return true;
}
SolrDocumentList docList = null;
- final SolrConnector solrConnector = sb.index.fulltext().getDefaultConnector();
+ final SolrConnector solrConnector = this.sb.index.fulltext().getDefaultConnector();
if (solrConnector == null || solrConnector.isClosed()) {
- this.urlsToRecrawl = 0;
- this.terminatedBySolrFailure = true;
- return false;
+ this.urlsToRecrawl = 0;
+ this.terminatedBySolrFailure = true;
+ return false;
}
-
+
try {
// query all or only httpstatus=200 depending on includefailed flag
docList = solrConnector.getDocumentListByQuery(RecrawlBusyThread.buildSelectionQuery(this.currentQuery, this.includefailed),
this.solrSortBy, this.chunkstart, this.chunksize, CollectionSchema.id.getSolrFieldName(), CollectionSchema.sku.getSolrFieldName());
this.urlsToRecrawl = docList.getNumFound();
} catch (final Throwable e) {
- this.urlsToRecrawl = 0;
- this.terminatedBySolrFailure = true;
+ this.urlsToRecrawl = 0;
+ this.terminatedBySolrFailure = true;
}
if (docList != null) {
- Set<String> tobedeletedIDs = new HashSet<>();
+ final Set<String> tobedeletedIDs = new HashSet<>();
for (final SolrDocument doc : docList) {
try {
this.urlstack.add(new DigestURL((String) doc.getFieldValue(CollectionSchema.sku.getSolrFieldName())));
- if (deleteOnRecrawl) tobedeletedIDs.add((String) doc.getFieldValue(CollectionSchema.id.getSolrFieldName()));
+ if (this.deleteOnRecrawl) tobedeletedIDs.add((String) doc.getFieldValue(CollectionSchema.id.getSolrFieldName()));
} catch (final MalformedURLException ex) {
- this.malformedUrlsCount++;
+ this.malformedUrlsCount++;
// if index entry hasn't a valid url (useless), delete it
tobedeletedIDs.add((String) doc.getFieldValue(CollectionSchema.id.getSolrFieldName()));
this.malformedUrlsDeletedCount++;
ConcurrentLog.severe(THREAD_NAME, "deleted index document with invalid url " + (String) doc.getFieldValue(CollectionSchema.sku.getSolrFieldName()));
}
}
-
+
if (!tobedeletedIDs.isEmpty()) try {
solrConnector.deleteByIds(tobedeletedIDs);
solrConnector.commit(false);
- } catch (IOException e) {
+ } catch (final IOException e) {
ConcurrentLog.severe(THREAD_NAME, "error deleting IDs ", e);
}
-
- this.chunkstart = deleteOnRecrawl? 0 : this.chunkstart + this.chunksize;
+
+ this.chunkstart = this.deleteOnRecrawl? 0 : this.chunkstart + this.chunksize;
}
-
+
if (docList == null || docList.size() < this.chunksize) {
return false;
}
return true;
}
-
- /**
- * @return a new default CrawlProfile instance to be used for recrawl jobs.
- */
- public static CrawlProfile buildDefaultCrawlProfile() {
- CrawlProfile profile = new CrawlProfile(CrawlSwitchboard.CRAWL_PROFILE_RECRAWL_JOB, CrawlProfile.MATCH_ALL_STRING, // crawlerUrlMustMatch
- CrawlProfile.MATCH_NEVER_STRING, // crawlerUrlMustNotMatch
- CrawlProfile.MATCH_ALL_STRING, // crawlerIpMustMatch
- CrawlProfile.MATCH_NEVER_STRING, // crawlerIpMustNotMatch
- CrawlProfile.MATCH_NEVER_STRING, // crawlerCountryMustMatch
- CrawlProfile.MATCH_NEVER_STRING, // crawlerNoDepthLimitMatch
- CrawlProfile.MATCH_ALL_STRING, // indexUrlMustMatch
- CrawlProfile.MATCH_NEVER_STRING, // indexUrlMustNotMatch
- CrawlProfile.MATCH_ALL_STRING, // indexContentMustMatch
- CrawlProfile.MATCH_NEVER_STRING, // indexContentMustNotMatch
- 0, false, CrawlProfile.getRecrawlDate(CrawlSwitchboard.CRAWL_PROFILE_RECRAWL_JOB_RECRAWL_CYCLE), -1,
- true, true, true, false, // crawlingQ, followFrames, obeyHtmlRobotsNoindex, obeyHtmlRobotsNofollow,
- true, true, true, false, -1, false, true, CrawlProfile.MATCH_NEVER_STRING, CacheStrategy.IFFRESH,
- "robot_" + CrawlSwitchboard.CRAWL_PROFILE_RECRAWL_JOB,
- ClientIdentification.yacyInternetCrawlerAgentName, null, null, 0);
- return profile;
- }
+
+ /**
+ * @return a new default CrawlProfile instance to be used for recrawl jobs.
+ */
+ public static CrawlProfile buildDefaultCrawlProfile() {
+ final CrawlProfile profile = new CrawlProfile(CrawlSwitchboard.CRAWL_PROFILE_RECRAWL_JOB, CrawlProfile.MATCH_ALL_STRING, // crawlerUrlMustMatch
+ CrawlProfile.MATCH_NEVER_STRING, // crawlerUrlMustNotMatch
+ CrawlProfile.MATCH_ALL_STRING, // crawlerIpMustMatch
+ CrawlProfile.MATCH_NEVER_STRING, // crawlerIpMustNotMatch
+ CrawlProfile.MATCH_NEVER_STRING, // crawlerCountryMustMatch
+ CrawlProfile.MATCH_NEVER_STRING, // crawlerNoDepthLimitMatch
+ CrawlProfile.MATCH_ALL_STRING, // indexUrlMustMatch
+ CrawlProfile.MATCH_NEVER_STRING, // indexUrlMustNotMatch
+ CrawlProfile.MATCH_ALL_STRING, // indexContentMustMatch
+ CrawlProfile.MATCH_NEVER_STRING, // indexContentMustNotMatch
+ 0, false, CrawlProfile.getRecrawlDate(CrawlSwitchboard.CRAWL_PROFILE_RECRAWL_JOB_RECRAWL_CYCLE), -1,
+ true, true, true, false, // crawlingQ, followFrames, obeyHtmlRobotsNoindex, obeyHtmlRobotsNofollow,
+ true, true, true, false, -1, false, true, CrawlProfile.MATCH_NEVER_STRING, CacheStrategy.IFFRESH,
+ "robot_" + CrawlSwitchboard.CRAWL_PROFILE_RECRAWL_JOB,
+ ClientIdentification.yacyInternetCrawlerAgentName, null, null, 0);
+ return profile;
+ }
@Override
public int getJobCount() {
return this.urlstack.size();
}
-
+
/**
* @return The total number of candidate URLs found for recrawl
*/
public long getUrlsToRecrawl() {
- return this.urlsToRecrawl;
- }
+ return this.urlsToRecrawl;
+ }
- /**
- * @return The total number of URLs added to the crawler queue for recrawl
- */
+ /**
+ * @return The total number of URLs added to the crawler queue for recrawl
+ */
public long getRecrawledUrlsCount() {
- return this.recrawledUrlsCount;
- }
-
- /**
- * @return The total number of URLs rejected for some reason by the crawl
- * stacker or the crawler queue
- */
+ return this.recrawledUrlsCount;
+ }
+
+ /**
+ * @return The total number of URLs rejected for some reason by the crawl
+ * stacker or the crawler queue
+ */
public long getRejectedUrlsCount() {
- return this.rejectedUrlsCount;
- }
+ return this.rejectedUrlsCount;
+ }
- /**
- * @return The total number of malformed URLs found
- */
+ /**
+ * @return The total number of malformed URLs found
+ */
public long getMalformedUrlsCount() {
- return this.malformedUrlsCount;
- }
-
- /**
- * @return The total number of malformed URLs deleted from index
- */
+ return this.malformedUrlsCount;
+ }
+
+ /**
+ * @return The total number of malformed URLs deleted from index
+ */
public long getMalformedUrlsDeletedCount() {
- return this.malformedUrlsDeletedCount;
- }
-
- /**
- * @return true when the job terminated early because an error occurred when
- * requesting the Solr index, or the Solr index was closed
- */
+ return this.malformedUrlsDeletedCount;
+ }
+
+ /**
+ * @return true when the job terminated early because an error occurred when
+ * requesting the Solr index, or the Solr index was closed
+ */
public boolean isTerminatedBySolrFailure() {
- return this.terminatedBySolrFailure;
- }
+ return this.terminatedBySolrFailure;
+ }
/** @return The recrawl job start time */
public LocalDateTime getStartTime() {
- return this.startTime;
- }
-
+ return this.startTime;
+ }
+
/** @return The recrawl job end time */
public LocalDateTime getEndTime() {
- return this.endTime;
- }
+ return this.endTime;
+ }
@Override
public void freemem() {
diff --git a/source/net/yacy/crawler/data/Latency.java b/source/net/yacy/crawler/data/Latency.java
index db7400e74..07c3faba2 100644
--- a/source/net/yacy/crawler/data/Latency.java
+++ b/source/net/yacy/crawler/data/Latency.java
@@ -45,7 +45,7 @@ public class Latency {
// the map is a mapping from host names to host configurations
private static final int mapMaxSize = 1000;
- private static final ConcurrentHashMap<String, Host> map = new ConcurrentHashMap<String, Host>();
+ private static final ConcurrentHashMap<String, Host> map = new ConcurrentHashMap<>();
/**
* update the latency entry after a host was selected for queueing into the loader
@@ -55,7 +55,7 @@ public class Latency {
public static void updateAfterSelection(final DigestURL url, final long robotsCrawlDelay) {
final String host = url.getHost();
if (host == null) return;
- String hosthash = url.hosthash();
+ final String hosthash = url.hosthash();
Host h = map.get(hosthash);
if (h == null) {
h = new Host(host, Switchboard.getSwitchboard().getConfigInt("crawler.defaultAverageLatency", 500), robotsCrawlDelay);
@@ -72,7 +72,7 @@ public class Latency {
public static void updateBeforeLoad(final DigestURL url) {
final String host = url.getHost();
if (host == null) return;
- String hosthash = url.hosthash();
+ final String hosthash = url.hosthash();
Host h = map.get(hosthash);
if (h == null) {
h = new Host(host, 500, 0);
@@ -91,7 +91,7 @@ public class Latency {
public static void updateAfterLoad(final DigestURL url, final long time) {
final String host = url.getHost();
if (host == null) return;
- String hosthash = url.hosthash();
+ final String hosthash = url.hosthash();
Host h = map.get(hosthash);
if (h == null) {
h = new Host(host, time, 0);
@@ -122,16 +122,16 @@ public class Latency {
* @return the waiting time in milliseconds; 0 if not known; -1 if host gives us special rights
*/
public static int waitingRobots(final MultiProtocolURL url, final RobotsTxt robots, final ClientIdentification.Agent agent) {
- int robotsDelay = 0;
- RobotsTxtEntry robotsEntry = robots.getEntry(url, agent);
+ int robotsDelay;
+ final RobotsTxtEntry robotsEntry = robots.getEntry(url, agent);
robotsDelay = (robotsEntry == null) ? 0 : robotsEntry.getCrawlDelayMillis();
if (robotsEntry != null && robotsDelay == 0 && robotsEntry.getAgentName() != null) return -1; // no limits if granted exclusively for this peer
return robotsDelay;
}
-
+
private static int waitingRobots(final String hostport, final RobotsTxt robots, final ClientIdentification.Agent agent, final boolean fetchOnlineIfNotAvailableOrNotFresh) {
- int robotsDelay = 0;
- RobotsTxtEntry robotsEntry = robots.getEntry(hostport, agent, fetchOnlineIfNotAvailableOrNotFresh);
+ int robotsDelay;
+ final RobotsTxtEntry robotsEntry = robots.getEntry(hostport, agent, fetchOnlineIfNotAvailableOrNotFresh);
robotsDelay = (robotsEntry == null) ? 0 : robotsEntry.getCrawlDelayMillis();
if (robotsEntry != null && robotsDelay == 0 && robotsEntry.getAgentName() != null) return -1; // no limits if granted exclusively for this peer
return robotsDelay;
@@ -166,20 +166,20 @@ public class Latency {
// if the number of same hosts as in the url in the loading queue is greater than MaxSameHostInQueue, then increase waiting
if (Switchboard.getSwitchboard().crawlQueues.hostcount(hostname) > Switchboard.getSwitchboard().getConfigInt(SwitchboardConstants.CRAWLER_MAX_SAME_HOST_IN_QUEUE, 20)) waiting += 3000;
-
+
// the time since last access to the domain is the basis of the remaining calculation
final int timeSinceLastAccess = (int) (System.currentTimeMillis() - host.lastacc());
-
+
// find the delay as given by robots.txt on target site
if (robots != null) {
- int robotsDelay = waitingRobots(hostname + ":" + port, robots, agent, false);
+ final int robotsDelay = waitingRobots(hostname + ":" + port, robots, agent, false);
if (robotsDelay < 0) return -timeSinceLastAccess; // no limits if granted exclusively for this peer
waiting = Math.max(waiting, robotsDelay);
}
- return Math.min(60000, waiting) - timeSinceLastAccess;
+ return waiting - timeSinceLastAccess;
}
-
+
/**
* calculates how long should be waited until the domain can be accessed again
* this follows from:
@@ -198,7 +198,7 @@ public class Latency {
if (host == null) return Integer.MIN_VALUE; // no delay if host is new; use Integer because there is a cast to int somewhere
// find the minimum waiting time based on the network domain (local or global)
- boolean local = url.isLocal();
+ final boolean local = url.isLocal();
int waiting = agent.minimumDelta;
// if we have accessed the domain many times, get slower (the flux factor)
@@ -206,21 +206,21 @@ public class Latency {
// use the access latency as rule how fast we can access the server
waiting = Math.max(waiting, (int) (host.average() * Switchboard.getSwitchboard().getConfigFloat(SwitchboardConstants.CRAWLER_LATENCY_FACTOR, 0.5f)));
-
+
// if the number of same hosts as in the url in the loading queue is greater than MaxSameHostInQueue, then increase waiting
if (Switchboard.getSwitchboard().crawlQueues.hostcount(url.getHost()) > Switchboard.getSwitchboard().getConfigInt(SwitchboardConstants.CRAWLER_MAX_SAME_HOST_IN_QUEUE, 20)) waiting += 3000;
// the time since last access to the domain is the basis of the remaining calculation
final int timeSinceLastAccess = (int) (System.currentTimeMillis() - host.lastacc());
-
+
// find the delay as given by robots.txt on target site
- int robotsDelay = waitingRobots(url, robots, agent);
+ final int robotsDelay = waitingRobots(url, robots, agent);
if (robotsDelay < 0) return -timeSinceLastAccess; // no limits if granted exclusively for this peer
waiting = Math.max(waiting, robotsDelay);
- return Math.min(60000, waiting) - timeSinceLastAccess;
+ return waiting - timeSinceLastAccess;
}
-
+
public static String waitingRemainingExplain(final DigestURL url, final RobotsTxt robots, final ClientIdentification.Agent agent) {
// first check if the domain was _ever_ accessed before
@@ -228,7 +228,7 @@ public class Latency {
if (host == null) return "host " + host + " never accessed before -> Integer.MIN_VALUE"; // no delay if host is new
// find the minimum waiting time based on the network domain (local or global)
- boolean local = url.isLocal();
+ final boolean local = url.isLocal();
final StringBuilder s = new StringBuilder(50);
// find the minimum waiting time based on the network domain (local or global)
@@ -237,26 +237,26 @@ public class Latency {
// if we have accessed the domain many times, get slower (the flux factor)
if (!local) {
- int flux = host.flux(waiting);
+ final int flux = host.flux(waiting);
waiting += flux;
s.append(", flux = ").append(flux);
}
-
+
// use the access latency as rule how fast we can access the server
// this applies also to localhost, but differently, because it is not necessary to
// consider so many external accesses
s.append(", host.average = ").append(host.average());
waiting = Math.max(waiting, (int) (host.average() * Switchboard.getSwitchboard().getConfigFloat(SwitchboardConstants.CRAWLER_LATENCY_FACTOR, 0.5f)));
-
+
// if the number of same hosts as in the url in the loading queue is greater than MaxSameHostInQueue, then increase waiting
- int hostcount = Switchboard.getSwitchboard().crawlQueues.hostcount(url.getHost());
+ final int hostcount = Switchboard.getSwitchboard().crawlQueues.hostcount(url.getHost());
if (hostcount > Switchboard.getSwitchboard().getConfigInt(SwitchboardConstants.CRAWLER_MAX_SAME_HOST_IN_QUEUE, 20)) {
s.append(", hostcount = ").append(hostcount);
- waiting += 5000;
+ waiting += 3000;
}
// find the delay as given by robots.txt on target site
- int robotsDelay = waitingRobots(url, robots, agent);
+ final int robotsDelay = waitingRobots(url, robots, agent);
if (robotsDelay < 0) return "no waiting for exclusive granted peer"; // no limits if granted exclusively for this peer
waiting = Math.max(waiting, robotsDelay);
@@ -280,13 +280,13 @@ public class Latency {
*/
public static long getDomainSleepTime(final RobotsTxt robots, final CrawlProfile profileEntry, final DigestURL crawlURL) {
if (profileEntry == null) return 0;
- long sleeptime = (
+ final long sleeptime = (
profileEntry.cacheStrategy() == CacheStrategy.CACHEONLY ||
(profileEntry.cacheStrategy() == CacheStrategy.IFEXIST && Cache.has(crawlURL.hash()))
) ? Integer.MIN_VALUE : waitingRemaining(crawlURL, robots, profileEntry.getAgent()); // this uses the robots.txt database and may cause a loading of robots.txt from the server
return sleeptime;
}
-
+
/**
* load a robots.txt to get the robots time.
* ATTENTION: this method causes that a robots.txt is loaded from the web which may cause a longer delay in execution.
@@ -297,16 +297,16 @@ public class Latency {
* @return
*/
public static long getRobotsTime(final RobotsTxt robots, final DigestURL crawlURL, ClientIdentification.Agent agent) {
- long sleeptime = waitingRobots(crawlURL, robots, agent); // this uses the robots.txt database and may cause a loading of robots.txt from the server
+ final long sleeptime = waitingRobots(crawlURL, robots, agent); // this uses the robots.txt database and may cause a loading of robots.txt from the server
return sleeptime < 0 ? 0 : sleeptime;
}
-
+
public static final class Host {
- private AtomicLong timeacc;
- private AtomicLong lastacc;
- private AtomicInteger count;
+ private final AtomicLong timeacc;
+ private final AtomicLong lastacc;
+ private final AtomicInteger count;
private final String host;
- private long robotsMinDelay;
+ private final long robotsMinDelay;
private Host(final String host, final long time, long robotsMinDelay) {
this.host = host;
this.timeacc = new AtomicLong(time);
@@ -354,5 +354,5 @@ public class Latency {
return this.count.get() >= 10000 ? range >> 1 : (range * this.count.get() / 10000) >> 1;
}
}
-
+
}
diff --git a/source/net/yacy/crawler/robots/RobotsTxt.java b/source/net/yacy/crawler/robots/RobotsTxt.java
index 48fc6a97a..16b9cf08b 100644
--- a/source/net/yacy/crawler/robots/RobotsTxt.java
+++ b/source/net/yacy/crawler/robots/RobotsTxt.java
@@ -1,7 +1,7 @@
//plasmaCrawlRobotsTxt.java
//-------------------------------------
//part of YACY
-// SPDX-FileCopyrightText: 2004 Michael Peter Christen <[email protected])>
+// SPDX-FileCopyrightText: 2004 Michael Peter Christen <[email protected])>
// SPDX-License-Identifier: GPL-2.0-or-later
//first published on http://www.anomic.de
//Frankfurt, Germany, 2004
@@ -72,24 +72,24 @@ public class RobotsTxt {
private final WorkTables tables;
private final LoaderDispatcher loader;
/** Thread pool used to launch concurrent tasks */
- private ThreadPoolExecutor threadPool;
+ private final ThreadPoolExecutor threadPool;
private static class DomSync {
- private DomSync() {}
+ private DomSync() {}
}
/**
- *
+ *
* @param worktables
* @param loader
* @param maxConcurrentTheads maximum active threads this instance is allowed to run for its concurrent tasks
*/
public RobotsTxt(final WorkTables worktables, LoaderDispatcher loader, final int maxActiveTheads) {
- this.threadPool = new ThreadPoolExecutor(maxActiveTheads, maxActiveTheads,
+ this.threadPool = new ThreadPoolExecutor(maxActiveTheads, maxActiveTheads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
new NamePrefixThreadFactory(RobotsTxt.class.getSimpleName()));
- this.syncObjects = new ConcurrentHashMap<String, DomSync>();
+ this.syncObjects = new ConcurrentHashMap<>();
this.tables = worktables;
this.loader = loader;
try {
@@ -108,12 +108,12 @@ public class RobotsTxt {
this.tables.getHeap(WorkTables.TABLE_ROBOTS_NAME).clear();
this.syncObjects.clear();
}
-
+
public void close() {
- /* Shutdown all active robots.txt loading threads */
- if(this.threadPool != null) {
- this.threadPool.shutdownNow();
- }
+ /* Shutdown all active robots.txt loading threads */
+ if(this.threadPool != null) {
+ this.threadPool.shutdownNow();
+ }
}
public int size() throws IOException {
@@ -123,7 +123,7 @@ public class RobotsTxt {
public RobotsTxtEntry getEntry(final MultiProtocolURL theURL, final ClientIdentification.Agent agent) {
if (theURL == null) throw new IllegalArgumentException();
if (!theURL.getProtocol().startsWith("http")) return null;
- return getEntry(getHostPort(theURL), agent, true);
+ return this.getEntry(getHostPort(theURL), agent, true);
}
public RobotsTxtEntry getEntry(final String urlHostPort, final ClientIdentification.Agent agent, final boolean fetchOnlineIfNotAvailableOrNotFresh) {
@@ -148,13 +148,13 @@ public class RobotsTxt {
if (record != null) robotsTxt4Host = new RobotsTxtEntry(urlHostPort, record);
if (fetchOnlineIfNotAvailableOrNotFresh && (
- robotsTxt4Host == null ||
+ robotsTxt4Host == null /*||
robotsTxt4Host.getLoadedDate() == null ||
- System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000
+ System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000 */
)) {
// make or get a synchronization object
- DomSync syncObj = this.syncObjects.get(urlHostPort);
+ DomSync syncObj = this.syncObjects.get(urlHostPort);
if (syncObj == null) {
syncObj = new DomSync();
this.syncObjects.put(urlHostPort, syncObj);
@@ -175,19 +175,19 @@ public class RobotsTxt {
record = null;
}
if (record != null) robotsTxt4Host = new RobotsTxtEntry(urlHostPort, record);
- if (robotsTxt4Host != null &&
+ if (robotsTxt4Host != null /*&&
robotsTxt4Host.getLoadedDate() != null &&
- System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() <= 1*24*60*60*1000) {
+ System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() <= 1*24*60*60*1000 */) {
return robotsTxt4Host;
}
// generating the proper url to download the robots txt
- DigestURL robotsURL = robotsURL(urlHostPort);
+ final DigestURL robotsURL = robotsURL(urlHostPort);
Response response = null;
if (robotsURL != null) {
if (log.isFine()) log.fine("Trying to download the robots.txt file from URL '" + robotsURL + "'.");
- Request request = new Request(robotsURL, null);
+ final Request request = new Request(robotsURL, null);
try {
response = RobotsTxt.this.loader.load(request, CacheStrategy.NOCACHE, null, agent);
} catch (final Throwable e) {
@@ -197,16 +197,16 @@ public class RobotsTxt {
}
if (response == null) {
- processOldEntry(robotsTxt4Host, robotsURL, robotsTable);
+ this.processOldEntry(robotsTxt4Host, robotsURL, robotsTable);
} else {
- robotsTxt4Host = processNewEntry(robotsURL, response, agent.robotIDs);
+ robotsTxt4Host = this.processNewEntry(robotsURL, response, agent.robotIDs);
}
}
}
return robotsTxt4Host;
}
-
+
public void delete(final MultiProtocolURL theURL) {
final String urlHostPort = getHostPort(theURL);
if (urlHostPort == null) return;
@@ -220,10 +220,10 @@ public class RobotsTxt {
if (robotsTable == null) return;
try {
robotsTable.delete(robotsTable.encodedKey(urlHostPort));
- } catch (IOException e) {
+ } catch (final IOException e) {
}
}
-
+
public void ensureExist(final MultiProtocolURL theURL, final ClientIdentification.Agent agent, boolean concurrent) {
if (theURL.isLocal()) return;
final String urlHostPort = getHostPort(theURL);
@@ -236,7 +236,7 @@ public class RobotsTxt {
return;
}
if (robotsTable != null && robotsTable.containsKey(robotsTable.encodedKey(urlHostPort))) return;
- Thread t = new Thread("Robots.txt:ensureExist(" + theURL.toNormalform(true) + ")") {
+ final Thread t = new Thread("Robots.txt:ensureExist(" + theURL.toNormalform(true) + ")") {
@Override
public void run(){
// make or get a synchronization object
@@ -250,12 +250,12 @@ public class RobotsTxt {
if (robotsTable.containsKey(robotsTable.encodedKey(urlHostPort))) return;
// generating the proper url to download the robots txt
- DigestURL robotsURL = robotsURL(urlHostPort);
-
+ final DigestURL robotsURL = robotsURL(urlHostPort);
+
Response response = null;
if (robotsURL != null) {
if (log.isFine()) log.fine("Trying to download the robots.txt file from URL '" + robotsURL + "'.");
- Request request = new Request(robotsURL, null);
+ final Request request = new Request(robotsURL, null);
try {
response = RobotsTxt.this.loader.load(request, CacheStrategy.NOCACHE, null, agent);
} catch (final IOException e) {
@@ -264,26 +264,26 @@ public class RobotsTxt {
}
if (response == null) {
- processOldEntry(null, robotsURL, robotsTable);
+ RobotsTxt.this.processOldEntry(null, robotsURL, robotsTable);
} else {
- processNewEntry(robotsURL, response, agent.robotIDs);
+ RobotsTxt.this.processNewEntry(robotsURL, response, agent.robotIDs);
}
}
}
};
if (concurrent) {
- this.threadPool.execute(t);
+ this.threadPool.execute(t);
} else {
- t.run();
+ t.run();
}
}
-
+
/**
* @return the approximate number of threads that are actively
* executing robots.txt loading tasks
*/
public int getActiveThreads() {
- return this.threadPool != null ? this.threadPool.getActiveCount() : 0;
+ return this.threadPool != null ? this.threadPool.getActiveCount() : 0;
}
private void processOldEntry(RobotsTxtEntry robotsTxt4Host, DigestURL robotsURL, BEncodedHeap robotsTable) {
@@ -306,14 +306,14 @@ public class RobotsTxt {
// store the data into the robots DB
final int sz = robotsTable.size();
- addEntry(robotsTxt4Host);
+ this.addEntry(robotsTxt4Host);
if (robotsTable.size() <= sz) {
log.severe("new entry in robots.txt table failed, resetting database");
- try {clear();} catch (final IOException e) {}
- addEntry(robotsTxt4Host);
+ try {this.clear();} catch (final IOException e) {}
+ this.addEntry(robotsTxt4Host);
}
}
-
+
/**
* Process a response to a robots.txt request, create a new robots entry, add it to the robots table then return it.
* @param robotsURL the initial robots.txt URL (before any eventual redirection). Must not be null.
@@ -329,7 +329,7 @@ public class RobotsTxt {
if (response.getResponseHeader().getStatusCode() == 401 || response.getResponseHeader().getStatusCode() == 403) {
parserResult = new RobotsTxtParser(thisAgents);
// create virtual deny path
- denyPath = new ArrayList<String>();
+ denyPath = new ArrayList<>();
denyPath.add("/");
} else {
parserResult = new RobotsTxtParser(thisAgents, robotsTxt);
@@ -337,12 +337,12 @@ public class RobotsTxt {
}
// store the data into the robots DB
- String etag = response.getResponseHeader().containsKey(HeaderFramework.ETAG) ? (response.getResponseHeader().get(HeaderFramework.ETAG)).trim() : null;
- boolean isBrowserAgent = thisAgents.length == 1 && thisAgents[0].equals("Mozilla");
+ final String etag = response.getResponseHeader().containsKey(HeaderFramework.ETAG) ? (response.getResponseHeader().get(HeaderFramework.ETAG)).trim() : null;
+ final boolean isBrowserAgent = thisAgents.length == 1 && thisAgents[0].equals("Mozilla");
if (isBrowserAgent) {
- denyPath.clear();
+ denyPath.clear();
}
- /* The robotsURL may eventually be redirected (from http to https is common),
+ /* The robotsURL may eventually be redirected (from http to https is common),
* but we store here the url before any redirection. If would not process this way, the unredirected URL would later
* never found in the robots table thus needing each time a http load.*/
final RobotsTxtEntry robotsTxt4Host = new RobotsTxtEntry(
@@ -355,10 +355,10 @@ public class RobotsTxt {
parserResult.sitemap(),
parserResult.crawlDelayMillis(),
parserResult.agentName());
- addEntry(robotsTxt4Host);
+ this.addEntry(robotsTxt4Host);
return robotsTxt4Host;
}
-
+
private String addEntry(final RobotsTxtEntry entry) {
// writes a new page and returns key
try {
@@ -382,18 +382,18 @@ public class RobotsTxt {
port = 80;
}
}
- String host = theURL.getHost();
+ final String host = theURL.getHost();
if (host == null) return null;
- StringBuilder sb = new StringBuilder(host.length() + 6);
+ final StringBuilder sb = new StringBuilder(host.length() + 6);
if (host.indexOf(':') >= 0) {sb.append('[').append(host).append(']');} else sb.append(host);
sb.append(':').append(Integer.toString(port));
return sb.toString();
}
-
+
public static boolean isRobotsURL(MultiProtocolURL url) {
return url.getPath().equals(ROBOTS_TXT_PATH);
}
-
+
/**
* generate a robots.txt url.
* @param urlHostPort a string of the form <host>':'<port> or just <host>
@@ -410,7 +410,7 @@ public class RobotsTxt {
}
return robotsURL;
}
-
+
public static class CheckEntry {
public final DigestURL digestURL;
public final RobotsTxtEntry robotsTxtEntry;
@@ -423,59 +423,59 @@ public class RobotsTxt {
this.error = error;
}
}
-
+
/**
* A unit task to load a robots.txt entry
*/
private class CrawlCheckTask implements Callable<CheckEntry> {
-
- private final DigestURL url;
- private final ClientIdentification.Agent userAgent;
-
- public CrawlCheckTask(final DigestURL url, final ClientIdentification.Agent userAgent) {
- this.url = url;
- this.userAgent = userAgent;
- }
-
- @Override
- public CheckEntry call() throws Exception {
+
+ private final DigestURL url;
+ private final ClientIdentification.Agent userAgent;
+
+ public CrawlCheckTask(final DigestURL url, final ClientIdentification.Agent userAgent) {
+ this.url = url;
+ this.userAgent = userAgent;
+ }
+
+ @Override
+ public CheckEntry call() throws Exception {
// try to load the robots
- RobotsTxtEntry robotsEntry = getEntry(this.url, this.userAgent);
- boolean robotsAllowed = robotsEntry == null ? true : !robotsEntry.isDisallowed(this.url);
- if (robotsAllowed) {
- try {
- Request request = loader.request(this.url, true, false);
- Response response = loader.load(request, CacheStrategy.NOCACHE,
- BlacklistType.CRAWLER, userAgent);
- return new CheckEntry(this.url, robotsEntry, response, null);
- } catch (final IOException e) {
- return new CheckEntry(this.url, robotsEntry, null, "error response: " + e.getMessage());
- }
- }
- return new CheckEntry(this.url, robotsEntry, null, null);
- }
-
-
+ final RobotsTxtEntry robotsEntry = RobotsTxt.this.getEntry(this.url, this.userAgent);
+ final boolean robotsAllowed = robotsEntry == null ? true : !robotsEntry.isDisallowed(this.url);
+ if (robotsAllowed) {
+ try {
+ final Request request = RobotsTxt.this.loader.request(this.url, true, false);
+ final Response response = RobotsTxt.this.loader.load(request, CacheStrategy.NOCACHE,
+ BlacklistType.CRAWLER, this.userAgent);
+ return new CheckEntry(this.url, robotsEntry, response, null);
+ } catch (final IOException e) {
+ return new CheckEntry(this.url, robotsEntry, null, "error response: " + e.getMessage());
+ }
+ }
+ return new CheckEntry(this.url, robotsEntry, null, null);
+ }
+
+
}
-
+
public Collection<CheckEntry> massCrawlCheck(final Collection<DigestURL> rootURLs, final ClientIdentification.Agent userAgent) {
final List<Future<CheckEntry>> futures = new ArrayList<>();
- for (DigestURL u: rootURLs) {
- futures.add(this.threadPool.submit(new CrawlCheckTask(u, userAgent)));
- }
+ for (final DigestURL u: rootURLs) {
+ futures.add(this.threadPool.submit(new CrawlCheckTask(u, userAgent)));
+ }
final Collection<CheckEntry> results = new ArrayList<>();
/* Now collect the results concurrently loaded */
- for(Future<CheckEntry> future: futures) {
- try {
- results.add(future.get());
- } catch (InterruptedException e) {
- log.warn("massCrawlCheck was interrupted before retrieving all results.");
- break;
- } catch (ExecutionException e) {
- /* A robots.txt loading failed : let's continue and try to get the next result
- * (most of time this should not happen, as Exceptions are caught inside the concurrent task) */
- continue;
- }
+ for(final Future<CheckEntry> future: futures) {
+ try {
+ results.add(future.get());
+ } catch (final InterruptedException e) {
+ log.warn("massCrawlCheck was interrupted before retrieving all results.");
+ break;
+ } catch (final ExecutionException e) {
+ /* A robots.txt loading failed : let's continue and try to get the next result
+ * (most of time this should not happen, as Exceptions are caught inside the concurrent task) */
+ continue;
+ }
}
return results;
}
diff --git a/source/net/yacy/crawler/robots/RobotsTxtParser.java b/source/net/yacy/crawler/robots/RobotsTxtParser.java
index ee2d81a88..6ec2a961c 100644
--- a/source/net/yacy/crawler/robots/RobotsTxtParser.java
+++ b/source/net/yacy/crawler/robots/RobotsTxtParser.java
@@ -64,7 +64,7 @@ public final class RobotsTxtParser {
private static final Pattern patternTab = Pattern.compile("\t");
- private static final String ROBOTS_USER_AGENT = "User-agent:".toUpperCase();
+ private static final String ROBOTS_USER_AGENT = "User-agent:".toUpperCase();
private static final String ROBOTS_DISALLOW = "Disallow:".toUpperCase();
private static final String ROBOTS_ALLOW = "Allow:".toUpperCase();
private static final String ROBOTS_COMMENT = "#";
@@ -73,15 +73,15 @@ public final class RobotsTxtParser {
private final ArrayList<String> allowList;
private final ArrayList<String> denyList;
- private ArrayList<String> sitemaps;
+ private final ArrayList<String> sitemaps;
private long crawlDelayMillis;
private final String[] myNames; // a list of own name lists
private String agentName; // the name of the agent that was used to return the result
protected RobotsTxtParser(final String[] myNames) {
- this.allowList = new ArrayList<String>(0);
- this.denyList = new ArrayList<String>(0);
- this.sitemaps = new ArrayList<String>(0);
+ this.allowList = new ArrayList<>(0);
+ this.denyList = new ArrayList<>(0);
+ this.sitemaps = new ArrayList<>(0);
this.crawlDelayMillis = 0;
this.myNames = myNames;
this.agentName = null;
@@ -92,15 +92,15 @@ public final class RobotsTxtParser {
if (robotsTxt != null && robotsTxt.length != 0) {
final ByteArrayInputStream bin = new ByteArrayInputStream(robotsTxt);
final BufferedReader reader = new BufferedReader(new InputStreamReader(bin));
- parse(reader);
+ this.parse(reader);
}
}
private void parse(final BufferedReader reader) {
- final ArrayList<String> deny4AllAgents = new ArrayList<String>();
- final ArrayList<String> deny4ThisAgents = new ArrayList<String>();
- final ArrayList<String> allow4AllAgents = new ArrayList<String>();
- final ArrayList<String> allow4ThisAgents = new ArrayList<String>();
+ final ArrayList<String> deny4AllAgents = new ArrayList<>();
+ final ArrayList<String> deny4ThisAgents = new ArrayList<>();
+ final ArrayList<String> allow4AllAgents = new ArrayList<>();
+ final ArrayList<String> allow4ThisAgents = new ArrayList<>();
int pos;
String line = null, lineUpper = null;
@@ -169,21 +169,36 @@ public final class RobotsTxtParser {
continue lineparser;
}
- // parse crawl delay
+ // Parse crawl delay:
+ // The crawl-delay directive is a non-standard value and not supported by google
+ // see: https://en.wikipedia.org/wiki/Robots_exclusion_standard#Crawl-delay_directive
+ // The interpretation of other crawlers vary:
+ // - Yandex interprets the value as the number of seconds to wait between subsequent visits.
+ // - Bing defines crawl-delay as the size of a time window (from 1 to 30 seconds) during which BingBot will access a web site only once.
+ // - Google provides an interface in its search console for webmasters, to control the Googlebot's subsequent visits.
if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
inBlock = true;
- if (isRule4ThisAgents || isRule4AllAgents) {
- pos = line.indexOf(' ');
- if (pos != -1) {
- try {
- // the crawl delay can be a float number and means number of seconds
- this.crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
- } catch (final NumberFormatException e) {
- // invalid crawling delay
- }
- }
- }
- continue lineparser;
+ if (isRule4ThisAgents || isRule4AllAgents) {
+ pos = line.indexOf(' ');
+ if (pos != -1) {
+ try {
+ // the crawl delay can be a float number
+ this.crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
+ // Because different crawlers apply different interpretations, we should do the same here for YaCy
+ // Many robots.txt entries have crawl-delay entries which makes it impossible to crawl the page at all,
+ // i.e. for values like "900" (would be 900 seconds which would be 15 minutes). To be able to operate,
+ // we must do a "good-for-everyone" interpetation. This is done already with the "flux"-compensation delay
+ // factor, which is applied additionally (its the 2-fold of the loading time from last visit), so we would be good
+ // even if we ignore the craw-delay at all.
+ this.crawlDelayMillis = Math.min(10000, this.crawlDelayMillis);
+ // In this case we limit the delay to 10 seconds most. If a host wants not to be indexed at all, there is
+ // an option for this in the robots.txt as well.
+ } catch (final NumberFormatException e) {
+ // invalid crawling delay
+ }
+ }
+ }
+ continue lineparser;
}
// parse disallow