Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
replaced check for load time method instead of loading the solr document, an index only for the last loading time was created. This prevents that solr has to fetch from its index while the index is created. Excessive re-loading of documents while indexing has shown to produce deadlocks, so this should now be prevented.
Michael Peter Christen163ba26d90d8
diff --git a/htroot/IndexControlURLs_p.java b/htroot/IndexControlURLs_p.javaindex 42d475ec4..25cf668da 100644--- a/htroot/IndexControlURLs_p.java+++ b/htroot/IndexControlURLs_p.java@@ -58,14 +58,14 @@ public class IndexControlURLs_p {final Switchboard sb = (Switchboard) env;final serverObjects prop = new serverObjects();-+/* Acquire a transaction token for the next possible POST form submissions */final String nextTransactionToken = TransactionManager.getTransactionToken(header);prop.put(TransactionManager.TRANSACTION_TOKEN_PARAM, nextTransactionToken);Segment segment = sb.index;long ucount = segment.fulltext().collectionSize();-+// set default valuesprop.put("urlstring", "");prop.put("urlhash", "");@@ -82,16 +82,16 @@ public class IndexControlURLs_p {List<File> dumpFiles = segment.fulltext().dumpFiles();prop.put("dumprestore_dumpfile", dumpFiles.size() == 0 ? "" : dumpFiles.get(dumpFiles.size() - 1).getAbsolutePath());prop.put("dumprestore_optimizemax", 10);- prop.put("dumprestore_rebootSolrEnabled",- sb.getConfigBool(SwitchboardConstants.CORE_SERVICE_FULLTEXT,- SwitchboardConstants.CORE_SERVICE_FULLTEXT_DEFAULT)- && !sb.getConfigBool(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED,- SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED_DEFAULT));+ prop.put("dumprestore_rebootSolrEnabled",+ sb.getConfigBool(SwitchboardConstants.CORE_SERVICE_FULLTEXT,+ SwitchboardConstants.CORE_SERVICE_FULLTEXT_DEFAULT)+ && !sb.getConfigBool(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED,+ SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED_DEFAULT));prop.put("cleanup", ucount == 0 ? 0 : 1);prop.put("cleanupsolr", segment.fulltext().connectedRemoteSolr() ? 1 : 0);prop.put("cleanuprwi", segment.termIndex() != null && !segment.termIndex().isEmpty() ? 1 : 0);prop.put("cleanupcitation", segment.connectedCitation() && !segment.urlCitation().isEmpty() ? 1 : 0);-+if (post == null || env == null) {prop.putNum("ucount", ucount);return prop; // nothing to do@@ -119,14 +119,20 @@ public class IndexControlURLs_p {// delete everythingif ( post.containsKey("deletecomplete") ) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);+if ( post.get("deleteIndex", "").equals("on") ) {- try {segment.fulltext().clearLocalSolr();} catch (final IOException e) {}+ try {+ segment.fulltext().clearLocalSolr();+ segment.loadTimeIndex().clear();+ } catch (final IOException e) {}}if ( post.get("deleteRemoteSolr", "").equals("on")) {- try {segment.fulltext().clearRemoteSolr();} catch (final IOException e) {}+ try {+ segment.fulltext().clearRemoteSolr();+ segment.loadTimeIndex().clear();+ } catch (final IOException e) {}}if ( post.get("deleteRWI", "").equals("on")) {if (segment.termIndex() != null) try {segment.termIndex().clear();} catch (final IOException e) {}@@ -135,7 +141,10 @@ public class IndexControlURLs_p {if (segment.connectedCitation()) try {segment.urlCitation().clear();} catch (final IOException e) {}}if ( post.get("deleteFirstSeen", "").equals("on")) {- try {segment.firstSeen().clear();} catch (final IOException e) {}+ try {+ segment.firstSeenIndex().clear();+ segment.loadTimeIndex().clear();+ } catch (final IOException e) {}}if ( post.get("deleteCrawlQueues", "").equals("on") ) {sb.crawlQueues.clear();@@ -152,18 +161,18 @@ public class IndexControlURLs_p {}if (post.containsKey("urlhashdeleteall")) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);+ClientIdentification.Agent agent = ClientIdentification.getAgent(post.get("agentName", ClientIdentification.yacyInternetCrawlerAgentName));int i = segment.removeAllUrlReferences(urlhash.getBytes(), sb.loader, agent, CacheStrategy.IFEXIST);prop.put("result", "Deleted URL and " + i + " references from " + i + " word indexes.");}if (post.containsKey("urlhashdelete")) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);+DigestURL url;try {url = segment.fulltext().getURL(urlhash);@@ -181,9 +190,9 @@ public class IndexControlURLs_p {}if (post.containsKey("urldelete")) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);+try {urlhash = ASCII.String((new DigestURL(urlstring)).hash());} catch (final MalformedURLException e) {@@ -227,34 +236,34 @@ public class IndexControlURLs_p {prop.put("statistics", 0);}}-+if (post.containsKey("optimizesolr")) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-- final int size = post.getInt("optimizemax", 10);- segment.fulltext().optimize(size);+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);++ final int size = post.getInt("optimizemax", 10);+ segment.fulltext().optimize(size);sb.tables.recordAPICall(post, "IndexControlURLs_p.html", WorkTables.TABLE_API_TYPE_STEERING, "solr optimize " + size);}if (post.containsKey("rebootsolr")) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-- if (sb.getConfigBool(SwitchboardConstants.CORE_SERVICE_FULLTEXT,- SwitchboardConstants.CORE_SERVICE_FULLTEXT_DEFAULT)- && !sb.getConfigBool(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED,- SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED_DEFAULT)) {- /* This operation is designed only for an embdded local Solr with no mirroring to an external remote Solr server */- segment.fulltext().rebootEmbeddedLocalSolr();- sb.tables.recordAPICall(post, "IndexControlURLs_p.html", WorkTables.TABLE_API_TYPE_STEERING, "solr reboot");- }+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);++ if (sb.getConfigBool(SwitchboardConstants.CORE_SERVICE_FULLTEXT,+ SwitchboardConstants.CORE_SERVICE_FULLTEXT_DEFAULT)+ && !sb.getConfigBool(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED,+ SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED_DEFAULT)) {+ /* This operation is designed only for an embdded local Solr with no mirroring to an external remote Solr server */+ segment.fulltext().rebootEmbeddedLocalSolr();+ sb.tables.recordAPICall(post, "IndexControlURLs_p.html", WorkTables.TABLE_API_TYPE_STEERING, "solr reboot");+ }}if (post.containsKey("deletedomain")) {- /* Check the transaction is valid */- TransactionManager.checkPostTransaction(header, post);-+ /* Check the transaction is valid */+ TransactionManager.checkPostTransaction(header, post);+final String domain = post.get("domain");Set<String> hostnames = new HashSet<String>();hostnames.add(domain);diff --git a/source/net/yacy/cora/federate/solr/connector/AbstractSolrConnector.java b/source/net/yacy/cora/federate/solr/connector/AbstractSolrConnector.javaindex 944db080b..efb0298d2 100644--- a/source/net/yacy/cora/federate/solr/connector/AbstractSolrConnector.java+++ b/source/net/yacy/cora/federate/solr/connector/AbstractSolrConnector.java@@ -69,7 +69,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {SOLR_ID_and_LOAD_DATE_FIELDS.add(CollectionSchema.id.getSolrFieldName());SOLR_ID_and_LOAD_DATE_FIELDS.add(CollectionSchema.load_date_dt.getSolrFieldName());}-+public final static SolrDocument POISON_DOCUMENT = new SolrDocument();public final static String POISON_ID = "POISON_ID";public final static String CATCHALL_TERM = "[* TO *]";@@ -92,10 +92,11 @@ public abstract class AbstractSolrConnector implements SolrConnector {catchSuccessQuery.setRows(0);catchSuccessQuery.setStart(0);}-+protected final static int pagesize_docs = 100;protected final static int pagesize_ids = 1000;-++ @Deprecatedprotected static LoadTimeURL getLoadTimeURL(final Object doc) {if (doc == null) return null;Object d = null;@@ -139,7 +140,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {}return fields;}-+/*** Get results from a solr query as a stream of documents.* The result queue is considered as terminated if AbstractSolrConnector.POISON_DOCUMENT is returned.@@ -170,7 +171,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {querystrings.add(querystring);return concurrentDocumentsByQueries(querystrings, sort, offset, maxcount, maxtime, buffersize, concurrency, prefetchIDs, fields);}-+/*** {@inheritDoc}*/@@ -223,7 +224,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {}return queue;}-+@Overridepublic Runnable newDocumentsByQueriesTask(final BlockingQueue<SolrDocument> queue,@@ -236,7 +237,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {final int concurrency,final String ... fields) {Objects.requireNonNull(queue, "The queue parameter must not be null.");-+if (querystrings == null || querystrings.isEmpty()) {return () -> {for (int i = 0; i < Math.max(1, concurrency); i++) {@@ -315,7 +316,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {}};}-+/*** get a document id result stream from a solr query.* The result queue is considered as terminated if AbstractSolrConnector.POISON_ID is returned.@@ -341,7 +342,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {querystrings.add(querystring);return concurrentIDsByQueries(querystrings, sort, offset, maxcount, maxtime, buffersize, concurrency);}-+/*** get a document id result stream from a set of solr queries.* The result queue is considered as terminated if AbstractSolrConnector.POISON_ID is returned.@@ -420,7 +421,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {};}-+/*** get a query result from solr* to get all results set the query String to "*:*"@@ -436,7 +437,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {final String ... fields) throws IOException {// construct queryfinal SolrQuery params = getSolrQuery(querystring, sort, offset, count, fields);-+// query the serverfinal SolrDocumentList docs = getDocumentListByParams(params);return docs;@@ -471,13 +472,14 @@ public abstract class AbstractSolrConnector implements SolrConnector {}return params;}-+/*** check if a given document, identified by url hash as document id exists* @param id the url hash and document id* @return metadata if any entry in solr exists, null otherwise* @throws IOException*/+ @Deprecated@Overridepublic LoadTimeURL getLoadTimeURL(String id) throws IOException {// construct raw query@@ -499,7 +501,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {LoadTimeURL md = getLoadTimeURL(doc);return md;}-+/*** check if a given document, identified by url hash as document id exists* @param id the url hash and document id@@ -515,7 +517,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {return false;}}-+/*** get the number of results when this query is done.* This should only be called if the actual result is never used, and only the count is interesting@@ -564,7 +566,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {params.clearSorts();params.setIncludeScore(false);for (String field: fields) params.addFacetField(field);-+// query the serverQueryResponse rsp = getResponseByParams(params);LinkedHashMap<String, ReversibleScoreMap<String>> facets = new LinkedHashMap<String, ReversibleScoreMap<String>>(fields.length);@@ -578,7 +580,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {}return facets;}-+@Overridepublic SolrDocument getDocumentById(final String id, final String ... fields) throws IOException {assert id.length() == Word.commonHashLength : "wrong id: " + id;@@ -606,7 +608,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {throw new IOException(e.getMessage(), e);}}-+/*** Update a solr document.* This will write only a partial update for all fields given in the SolrInputDocument@@ -634,7 +636,7 @@ public abstract class AbstractSolrConnector implements SolrConnector {for (SolrInputDocument doc: solrdoc) docs.add(partialUpdatePatch(doc));this.add(docs);}-+private SolrInputDocument partialUpdatePatch(final SolrInputDocument docIn) {SolrInputDocument docOut = new SolrInputDocument();docOut.setField(CollectionSchema.id.name(), docIn.getFieldValue(CollectionSchema.id.name()));@@ -649,6 +651,6 @@ public abstract class AbstractSolrConnector implements SolrConnector {}return docOut;}-+}diff --git a/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.java b/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.javaindex b2abffce5..77de53cf6 100644--- a/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.java+++ b/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.java@@ -425,10 +425,12 @@ public class EmbeddedSolrConnector extends SolrServerConnector implements SolrCo/*** check if a given document, identified by url hash as document id exists+ * @Deprecated use Segment.getLastSeenTime instead* @param id the url hash and document id* @return the load date if any entry in solr exists, null otherwise* @throws IOException*/+ @Deprecated@Overridepublic LoadTimeURL getLoadTimeURL(String id) throws IOException {int responseCount = 0;diff --git a/source/net/yacy/cora/federate/solr/connector/MirrorSolrConnector.java b/source/net/yacy/cora/federate/solr/connector/MirrorSolrConnector.javaindex 57fb4cd5a..6cc670f60 100644--- a/source/net/yacy/cora/federate/solr/connector/MirrorSolrConnector.java+++ b/source/net/yacy/cora/federate/solr/connector/MirrorSolrConnector.java@@ -27,9 +27,6 @@ import java.util.Map;import java.util.concurrent.BlockingQueue;import java.util.concurrent.atomic.AtomicLong;-import net.yacy.cora.sorting.ReversibleScoreMap;-import net.yacy.kelondro.data.word.Word;-import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;@@ -38,6 +35,9 @@ import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.ModifiableSolrParams;+import net.yacy.cora.sorting.ReversibleScoreMap;+import net.yacy.kelondro.data.word.Word;+public class MirrorSolrConnector extends AbstractSolrConnector implements SolrConnector {// the twin solrs@@ -47,7 +47,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCothis.solr0 = null;this.solr1 = null;}-+public MirrorSolrConnector(SolrConnector solr0, SolrConnector solr1) {this.solr0 = solr0;this.solr1 = solr1;@@ -64,8 +64,8 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCo((this.solr0 == null && ((MirrorSolrConnector) o).solr0 == null) || (((this.solr0 != null && ((MirrorSolrConnector) o).solr0 != null)) && this.solr0.equals(((MirrorSolrConnector) o).solr0))) &&((this.solr1 == null && ((MirrorSolrConnector) o).solr1 == null) || (((this.solr1 != null && ((MirrorSolrConnector) o).solr1 != null)) && this.solr1.equals(((MirrorSolrConnector) o).solr1)));}--++@Overridepublic int bufferSize() {int b = 0;@@ -79,7 +79,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCoif (this.solr0 != null) this.solr0.clearCaches();if (this.solr1 != null) this.solr1.clearCaches();}-+public boolean isConnected0() {return this.solr0 != null;}@@ -139,7 +139,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCopublic boolean isClosed() {return (this.solr0 == null || this.solr0.isClosed()) && (this.solr1 == null || this.solr1.isClosed());}-+@Overridepublic synchronized void close() {if (this.solr0 != null) {this.solr0.close(); this.solr0 = null;}@@ -183,12 +183,12 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCoif (this.solr0 != null) this.solr0.deleteByQuery(querystring);if (this.solr1 != null) this.solr1.deleteByQuery(querystring);}-+@Overridepublic SolrDocument getDocumentById(final String key, final String ... fields) throws IOException {assert key.length() == Word.commonHashLength : "wrong id: " + key;SolrDocument doc;- if ((solr0 != null && ((doc = solr0.getDocumentById(key, fields)) != null)) || (solr1 != null && ((doc = solr1.getDocumentById(key, fields)) != null))) {+ if ((this.solr0 != null && ((doc = this.solr0.getDocumentById(key, fields)) != null)) || (this.solr1 != null && ((doc = this.solr1.getDocumentById(key, fields)) != null))) {return doc;}return null;@@ -204,7 +204,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCoif (this.solr0 != null) this.solr0.add(solrdoc);if (this.solr1 != null) this.solr1.add(solrdoc);}-+@Overridepublic void add(final Collection<SolrInputDocument> solrdocs) throws IOException, SolrException {if (this.solr0 != null) this.solr0.add(solrdocs);@@ -346,7 +346,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCo// TODO: combine bothreturn l1;}-+@Overridepublic long getCountByQuery(final String querystring) throws IOException {if (this.solr0 == null && this.solr1 == null) return 0;@@ -409,7 +409,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCoif (this.solr1 != null) s += this.solr1.getSize();return s;}-+@Overridepublic boolean exists(final String id) {boolean result = false;@@ -418,6 +418,7 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCoreturn result;}+ @Deprecated@Overridepublic LoadTimeURL getLoadTimeURL(String id) throws IOException {if (this.solr0 != null && this.solr1 == null) return this.solr0.getLoadTimeURL(id);@@ -438,5 +439,5 @@ public class MirrorSolrConnector extends AbstractSolrConnector implements SolrCoif (this.solr0 == null && this.solr1 != null) return this.solr1.concurrentIDsByQuery(querystring, sort, offset, maxcount, maxtime, buffersize, concurrency);return super.concurrentIDsByQuery(querystring, sort, offset, maxcount, maxtime, buffersize, concurrency);}-+}diff --git a/source/net/yacy/cora/federate/solr/connector/SolrConnector.java b/source/net/yacy/cora/federate/solr/connector/SolrConnector.javaindex 0b4294a64..26a61c86c 100644--- a/source/net/yacy/cora/federate/solr/connector/SolrConnector.java+++ b/source/net/yacy/cora/federate/solr/connector/SolrConnector.java@@ -26,8 +26,6 @@ import java.util.LinkedHashMap;import java.util.List;import java.util.concurrent.BlockingQueue;-import net.yacy.cora.sorting.ReversibleScoreMap;-import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;@@ -35,6 +33,8 @@ import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.ModifiableSolrParams;+import net.yacy.cora.sorting.ReversibleScoreMap;+public interface SolrConnector extends Iterable<String> /* Iterable of document IDs */ {public static class LoadTimeURL {@@ -45,23 +45,23 @@ public interface SolrConnector extends Iterable<String> /* Iterable of documentthis.date = date;}}-+/*** clear all caches: inside solr and ouside solr within the implementations of this interface*/public void clearCaches();-+/*** get the size of a write buffer (if any) of pending write requests*/public int bufferSize();-+/*** get the size of the index* @return number of results if solr is queries with a catch-all pattern*/public long getSize();-+/*** force a commit*/@@ -72,19 +72,19 @@ public interface SolrConnector extends Iterable<String> /* Iterable of document* @param maxSegments the maximum number of segments. Set to 1 for maximum optimization*/public void optimize(int maxSegments);-+/*** ask the solr subsystem about it's segment number* @return the segment count, which corresponds to the number of files for an index*/public int getSegmentCount();-+/*** test if the connector is already closed* @return true if the connector is closed*/public boolean isClosed();-+/*** close the server connection*/@@ -123,8 +123,9 @@ public interface SolrConnector extends Iterable<String> /* Iterable of document* @return the load time metadata (url and load data) if any entry in solr exists, null otherwise* @throws IOException*/+ @Deprecatedpublic LoadTimeURL getLoadTimeURL(final String id) throws IOException;-+/*** check if a given document, identified by url hash as document id exists* @param id the url hash and document id@@ -139,7 +140,7 @@ public interface SolrConnector extends Iterable<String> /* Iterable of document* @throws SolrException*/public void add(final SolrInputDocument solrdoc) throws IOException, SolrException;-+/*** Update a solr document.* This will write only a partial update for all fields given in the SolrInputDocument@@ -167,7 +168,7 @@ public interface SolrConnector extends Iterable<String> /* Iterable of document* @throws SolrException*/public void update(final Collection<SolrInputDocument> solrdoc) throws IOException, SolrException;-+/*** get a document from solr by given key for the id-field* @param key@@ -194,7 +195,7 @@ public interface SolrConnector extends Iterable<String> /* Iterable of document* @throws SolrException*/public SolrDocumentList getDocumentListByParams(ModifiableSolrParams params) throws IOException;-+/*** get a query result from solr* to get all results set the query String to "*:*"@@ -211,7 +212,7 @@ public interface SolrConnector extends Iterable<String> /* Iterable of documentfinal int offset,final int count,final String ... fields) throws IOException;-+/*** get the number of results when this query is done.* This should only be called if the actual result is never used, and only the count is interesting@@ -229,12 +230,12 @@ public interface SolrConnector extends Iterable<String> /* Iterable of document* @throws IOException*/public LinkedHashMap<String, ReversibleScoreMap<String>> getFacets(String query, int maxresults, final String ... fields) throws IOException;-+/*** <p>Get results from solr queries as a stream of documents.* The result queue is considered as terminated if AbstractSolrConnector.POISON_DOCUMENT is returned.* The method returns immediately and feeds the search results into the queue.</p>- * <p><strong>Important</strong> : be careful if the consumer thread(s) terminate before taking the poison document(s) from the queue,+ * <p><strong>Important</strong> : be careful if the consumer thread(s) terminate before taking the poison document(s) from the queue,* as the producer thread(s) may indefinitely block on their last step (adding poison element) because the queue would be full.</p>* @param querystring the solr query string* @param sort the solr sort string, may be null to be not used@@ -257,11 +258,11 @@ public interface SolrConnector extends Iterable<String> /* Iterable of documentfinal int concurrency,final boolean prefetchIDs,final String ... fields);-+/*** Creates a new runnable task to run a given list of Solr queries and fill a* results queue by packets of a limited number of results.- *+ ** @param queue the results queue. Must not be null.* @param querystrings a list of Solr queries* @param sort an eventual Solr sort criteria@@ -278,7 +279,7 @@ public interface SolrConnector extends Iterable<String> /* Iterable of documentpublic Runnable newDocumentsByQueriesTask(final BlockingQueue<SolrDocument> queue, final List<String> querystrings,final String sort, final int offset, final int maxcount, final long maxtime, final int buffersize,final int concurrency, final String... fields);-+/*** Get results from solr queries as a stream of documents.* The result queue is considered as terminated if AbstractSolrConnector.POISON_DOCUMENT is returned.@@ -304,7 +305,7 @@ public interface SolrConnector extends Iterable<String> /* Iterable of documentfinal int concurrency,final boolean prefetchIDs,final String ... fields);-+/*** get a document id result stream from a solr query.* The result queue is considered as terminated if AbstractSolrConnector.POISON_ID is returned.diff --git a/source/net/yacy/crawler/CrawlStacker.java b/source/net/yacy/crawler/CrawlStacker.javaindex f1ecdf283..11192703b 100644--- a/source/net/yacy/crawler/CrawlStacker.java+++ b/source/net/yacy/crawler/CrawlStacker.java@@ -425,23 +425,15 @@ public final class CrawlStacker implements WorkflowTask<Request>{if (dbocc != null) {return CRAWL_REJECT_REASON_DOUBLE_IN_PREFIX + ": " + dbocc.name();}- final String urlhash = ASCII.String(url.hash());- LoadTimeURL oldEntry = null;- try {- oldEntry = this.indexSegment.fulltext().getDefaultConnector().getLoadTimeURL(urlhash);- } 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);- return "exception during double-test: " + e.getMessage();- }+ String urls = url.toNormalform(false);+ LoadTimeURL oldEntry = this.indexSegment.getLoadTimeURL(urls, url.hash());// deny urls that exceed allowed number of occurrencesfinal int maxAllowedPagesPerDomain = profile.domMaxPages();if (maxAllowedPagesPerDomain < Integer.MAX_VALUE && maxAllowedPagesPerDomain > 0) {final AtomicInteger dp = profile.getCount(url.getHost());if (dp != null && dp.get() >= maxAllowedPagesPerDomain) {- if (CrawlStacker.log.isFine()) CrawlStacker.log.fine("URL '" + url.toNormalform(false) + "' appeared too often in crawl stack, a maximum of " + maxAllowedPagesPerDomain + " is allowed.");+ if (CrawlStacker.log.isFine()) CrawlStacker.log.fine("URL '" + urls + "' appeared too often in crawl stack, a maximum of " + maxAllowedPagesPerDomain + " is allowed.");return "crawl stack domain counter exceeded (test by profile)";}diff --git a/source/net/yacy/peers/Protocol.java b/source/net/yacy/peers/Protocol.javaindex 5611b033e..dea2e023e 100644--- a/source/net/yacy/peers/Protocol.java+++ b/source/net/yacy/peers/Protocol.java@@ -140,10 +140,10 @@ public final class Protocol {* wrapper class for multi-post attempts to multiple IPs*/public static class Post {-- /** Contains the result from a successful post or null if no attempt was successful */++ /** Contains the result from a successful post or null if no attempt was successful */private byte[] result;-+/*** @param targetBaseURL the base target URL* @param targetHash the hash of the target peer@@ -162,18 +162,18 @@ public final class Protocol {try (final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent)) {httpClient.setTimout(timeout);MultiProtocolURL targetURL = new MultiProtocolURL(targetBaseURL, path);- this.result = httpClient.POSTbytes(targetURL, Seed.b64Hash2hexHash(targetHash) + ".yacyh", parts, false, true);+ this.result = httpClient.POSTbytes(targetURL, Seed.b64Hash2hexHash(targetHash) + ".yacyh", parts, false, true);}}-+/*** @return the result from a successful post or null if no attempt was successful*/public byte[] getResult() {- return this.result;- }+ return this.result;+ }}-+/*** this is called to enrich the seed information by - own address (if peer is behind a nat/router) - check* peer type (virgin/junior/senior/principal) to do this, we send a 'Hello' to another peer this carries@@ -280,7 +280,7 @@ public final class Protocol {Switchboard.getSwitchboard().index.fulltext().connectedLocalSolr() &&responseTime < 1000 && Domains.isThisHostIP(mySeed.getIPs()));-+// change our seed-typefinal Accessible accessible = new Accessible();if ( mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL) ) {@@ -369,7 +369,7 @@ public final class Protocol {return result;}- public static long[] queryRWICount(final MultiProtocolURL targetBaseURL, final Seed target, int timeout) {+ public static long[] queryRWICount(final MultiProtocolURL targetBaseURL, final Seed target, int timeout) {// prepare requestfinal String salt = crypt.randomSalt();@@ -380,7 +380,7 @@ public final class Protocol {parts.put("env", UTF8.StringBody(""));//ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "posting request to " + targetBaseURL);final Post post = new Post(targetBaseURL, target.hash, "/yacy/query.html", parts, timeout);-+//ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "received CONTENT from requesting " + targetBaseURL + (post.result == null ? "NULL" : (": length = " + post.result.length)));final Map<String, String> result = FileUtils.table(post.result);if (result == null || result.isEmpty()) return new long[] {-1, -1};@@ -433,35 +433,35 @@ public final class Protocol {RSSReader reader = null;try (final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, (int) maxTime)) {for (final String ip: target.getIPs()) {- MultiProtocolURL targetBaseURL = null;+ MultiProtocolURL targetBaseURL = null;try {- targetBaseURL = target.getPublicMultiprotocolURL(ip, preferHttps);- byte[] result;- try {- result = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false, true);- } catch(final IOException e) {- if(targetBaseURL.isHTTPS()) {- /* Failed with https : retry with http */- targetBaseURL = target.getPublicMultiprotocolURL(ip, false);- result = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false, true);- if(result != null) {- /* Got something with http : mark peer SSL as unavailable on target peer */- markSSLUnavailableOnPeer(seedDB, target, ip, "yacyClient.queryRemoteCrawlURLs");- }- } else {- throw e;- }- }+ targetBaseURL = target.getPublicMultiprotocolURL(ip, preferHttps);+ byte[] result;+ try {+ result = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false, true);+ } catch(final IOException e) {+ if(targetBaseURL.isHTTPS()) {+ /* Failed with https : retry with http */+ targetBaseURL = target.getPublicMultiprotocolURL(ip, false);+ result = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false, true);+ if(result != null) {+ /* Got something with http : mark peer SSL as unavailable on target peer */+ markSSLUnavailableOnPeer(seedDB, target, ip, "yacyClient.queryRemoteCrawlURLs");+ }+ } else {+ throw e;+ }+ }reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result);} catch(MalformedURLException e) {- Network.log.warn("yacyClient.queryRemoteCrawlURLs malformed target URL for peer '" + target.getName()- + "' on address : " + ip);+ Network.log.warn("yacyClient.queryRemoteCrawlURLs malformed target URL for peer '" + target.getName()+ + "' on address : " + ip);} catch (final IOException e ) {reader = null;Network.log.warn("yacyClient.queryRemoteCrawlURLs failed asking peer '" + target.getName() + "': probably bad response from remote peer (1), reader == null");}if (reader != null) {- break;+ break;}target.put(Seed.RCOUNT, "0");seedDB.peerActions.interfaceDeparture(target, ip);@@ -469,7 +469,7 @@ public final class Protocol {} catch (IOException e) {Network.log.warn(e);}-+final RSSFeed feed = reader == null ? null : reader.getFeed();if ( feed == null ) {// case where the rss reader does not understand the content@@ -520,13 +520,13 @@ public final class Protocol {SearchResult result = null;for (String ip: target.getIPs()) {//if (ip.indexOf(':') >= 0) System.out.println("Search target: IPv6: " + ip);- final String targetBaseURL;+ final String targetBaseURL;if (target.clash(event.peers.mySeed().getIPs())) {- targetBaseURL = "http://localhost:" + event.peers.mySeed().getPort();+ targetBaseURL = "http://localhost:" + event.peers.mySeed().getPort();} else {- targetBaseURL = target.getPublicURL(ip,- Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,- SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));+ targetBaseURL = target.getPublicURL(ip,+ Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,+ SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));}try {result =@@ -551,17 +551,17 @@ public final class Protocol {} catch (final IOException e ) {Network.log.info("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + ")");if(targetBaseURL.startsWith("https")) {- /* First mark https unavailable on this peer before removing any interface */- target.setFlagSSLAvailable(false);- event.peers.updateConnected(target);+ /* First mark https unavailable on this peer before removing any interface */+ target.setFlagSSLAvailable(false);+ event.peers.updateConnected(target);} else {- event.peers.peerActions.interfaceDeparture(target, ip);+ event.peers.peerActions.interfaceDeparture(target, ip);}return -1;}}if (result == null) return -1;-+// computation timefinal long totalrequesttime = System.currentTimeMillis() - timestamp;@@ -618,9 +618,9 @@ public final class Protocol {event.addExpectedRemoteReferences(count);SearchResult result = null;for (String ip: target.getIPs()) {- final String targetBaseURL = target.getPublicURL(ip,- Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,- SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));+ final String targetBaseURL = target.getPublicURL(ip,+ Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,+ SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));try {result =new SearchResult(@@ -644,17 +644,17 @@ public final class Protocol {} catch (final IOException e ) {Network.log.info("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + ")");if(targetBaseURL.startsWith("https")) {- /* First mark https unavailable on this peer before removing any interface */- target.setFlagSSLAvailable(false);- event.peers.updateConnected(target);+ /* First mark https unavailable on this peer before removing any interface */+ target.setFlagSSLAvailable(false);+ event.peers.updateConnected(target);} else {- event.peers.peerActions.interfaceDeparture(target, ip);+ event.peers.peerActions.interfaceDeparture(target, ip);}return -1;}}if (result == null) return -1;-+// computation timefinal long totalrequesttime = System.currentTimeMillis() - timestamp;@@ -781,24 +781,24 @@ public final class Protocol {// insert one container into the search result buffer// one is enough, only the references are used, not the wordif (event.addResultsToLocalIndex) {- /*- * Current thread might be interrupted by SearchEvent.cleanup()- */- if (Thread.interrupted()) {- throw new InterruptedException("solrQuery interrupted");- }- WriteMetadataNodeToLocalIndexThread writerToLocalIndex = new WriteMetadataNodeToLocalIndexThread(event.query.getSegment(), storeDocs);- writerToLocalIndex.start();- try {- writerToLocalIndex.join();- } catch(InterruptedException e) {- /*- * Current thread interruption might happen while waiting- * for writeToLocalIndexThread.- */- writerToLocalIndex.stopWriting();- throw new InterruptedException("remoteProcess stopped!");- }+ /*+ * Current thread might be interrupted by SearchEvent.cleanup()+ */+ if (Thread.interrupted()) {+ throw new InterruptedException("solrQuery interrupted");+ }+ WriteMetadataNodeToLocalIndexThread writerToLocalIndex = new WriteMetadataNodeToLocalIndexThread(event.query.getSegment(), storeDocs);+ writerToLocalIndex.start();+ try {+ writerToLocalIndex.join();+ } catch(InterruptedException e) {+ /*+ * Current thread interruption might happen while waiting+ * for writeToLocalIndexThread.+ */+ writerToLocalIndex.stopWriting();+ throw new InterruptedException("remoteProcess stopped!");+ }event.addRWIs(container.get(0), false, target.getName() + "/" + target.hash, result.totalCount, time);} else {// feed results as nodes (SolrQuery results) which carry metadata,@@ -828,57 +828,59 @@ public final class Protocol {}Network.log.info("remote search: peer " + target.getName() + " sent " + container.get(0).size() + "/" + result.totalCount + " references");}-+/*** This thread is used to write a collection of URIMetadataNode documents to a segment allowing to be safely stopped.- * Indeed, if one interrupt a thread while commiting to Solr index, the index is closed and will be no more writable+ * Indeed, if one interrupt a thread while commiting to Solr index, the index is closed and will be no more writable* (later calls would throw a org.apache.lucene.store.AlreadyClosedException) because Solr IndexWriter uses an InterruptibleChanel.* This thread allow to safely stop writing operation using an AtomicBoolean.* @author luc**/private static class WriteMetadataNodeToLocalIndexThread extends Thread {-- private AtomicBoolean stop = new AtomicBoolean(false);-- private Segment segment;-- private Collection<URIMetadataNode> storeDocs;-- /**- * Parameters must be not null.- * @param segment solr segment to write- * @param storeDocs solr documents collection to put to segment- */- public WriteMetadataNodeToLocalIndexThread(Segment segment, Collection<URIMetadataNode> storeDocs) {- super("WriteMetadataNodeToLocalIndexThread");- this.segment = segment;- this.storeDocs = storeDocs;- }-- /**- * Use this to stop writing operation. This thread will not stop immediately as Solr might be writing something.- */- public void stopWriting() {- this.stop.set(true);- }-- @Override- public void run() {++ private AtomicBoolean stop = new AtomicBoolean(false);++ private Segment segment;++ private Collection<URIMetadataNode> storeDocs;++ /**+ * Parameters must be not null.+ * @param segment solr segment to write+ * @param storeDocs solr documents collection to put to segment+ */+ public WriteMetadataNodeToLocalIndexThread(Segment segment, Collection<URIMetadataNode> storeDocs) {+ super("WriteMetadataNodeToLocalIndexThread");+ this.segment = segment;+ this.storeDocs = storeDocs;+ }++ /**+ * Use this to stop writing operation. This thread will not stop immediately as Solr might be writing something.+ */+ public void stopWriting() {+ this.stop.set(true);+ }++ @Override+ public void run() {for (URIMetadataNode entry : this.storeDocs) {- if(stop.get()) {- Network.log.info("Writing documents collection to Solr segment was stopped.");- return;- }+ if(this.stop.get()) {+ Network.log.info("Writing documents collection to Solr segment was stopped.");+ return;+ }try {- segment.setFirstSeenTime(entry.hash(), Math.min(entry.moddate().getTime(), System.currentTimeMillis()));- segment.fulltext().putMetadata(entry); // it will be checked inside the putMetadata that poor metadata does not overwrite rich metadata+ long now = System.currentTimeMillis();+ this.segment.setFirstSeenTime(entry.hash(), Math.min(entry.moddate().getTime(), now));+ this.segment.setLoadTime(entry.hash(), now);+ this.segment.fulltext().putMetadata(entry); // it will be checked inside the putMetadata that poor metadata does not overwrite rich metadata} catch (final IOException e) {ConcurrentLog.logException(e);}}- }- }+ }+ }private static class SearchResult {public int availableCount; // number of returned LURL's for this search@@ -934,7 +936,7 @@ public final class Protocol {baos.close();baos = null;}-+parts.put("myseed", UTF8.StringBody((event.peers.mySeed() == null) ? "" : event.peers.mySeed().genSeedStr(key)));parts.put("count", UTF8.StringBody(Integer.toString(Math.max(10, count))));parts.put("time", UTF8.StringBody(Long.toString(Math.max(3000, time))));@@ -951,7 +953,7 @@ public final class Protocol {parts.put("author", UTF8.StringBody(event.query.modifier.author));parts.put("contentdom", UTF8.StringBody(contentdom == null ? ContentDomain.ALL.toString() : contentdom.toString()));if(strictContentDom) {- parts.put("strictContentDom", UTF8.StringBody("true"));+ parts.put("strictContentDom", UTF8.StringBody("true"));}parts.put("maxdist", UTF8.StringBody(Integer.toString(maxDistance)));parts.put("profile", UTF8.StringBody(crypt.simpleEncode(event.query.ranking.toExternalString())));@@ -1029,153 +1031,153 @@ public final class Protocol {* A task dedicated to requesting a Solr instance*/protected static class SolrRequestTask extends Thread {-- /** Maximum length of detailed log error message */- private final static int MAX_ERROR_MESSAGE_LENGTH = 500;-- /** Logger */- private final static ConcurrentLog log = new ConcurrentLog(SolrRequestTask.class.getSimpleName());-- /** The solr to request */- private RemoteInstance instance;-- /** Connector to the Solr instance */- private SolrConnector solrConnector;-- /** The solr query to run */- private final SolrQuery solrQuery;-- /** The instance base URL */- private final String targetBaseURL;-- /** The target seed information */- private final Seed target;-- /** Set to true when the target is this local peer */- private final boolean mySeed;-- /** The request timeout in milliseconds */- private final int timeout;-- /** The query response array to fill */- private final QueryResponse[] rsp;-- /** The result documents list to fill */- private final SolrDocumentList[] docList;-- /** Indicates wether this task has been closed */- private volatile boolean closed;-- /**- * Constructor. All parameters are required to not be null.- * @param solrQuery the Solr query to run- * @param targetBaseURL the instance base URL : http(s) + host name or IP + the eventual port- * @param target the remote target seed information- * @param timeout the request timeout in milliseconds- */- protected SolrRequestTask(final SolrQuery solrQuery, final String targetBaseURL, final Seed target,- final boolean mySeed, final int timeout, final QueryResponse[] rsp, final SolrDocumentList[] docList) {- super("Protocol.solrQuery(" + solrQuery.getQuery() + " to " + target.hash + ")");- this.solrQuery = solrQuery;- this.targetBaseURL = targetBaseURL;- this.target = target;- this.mySeed = mySeed;- this.timeout = timeout;- this.rsp = rsp;- this.docList = docList;- this.closed = false;- }-- /**- * Logs the exception detailed message if any, at fine level because errors on remote solr queries to other peers occurs quite frequently.- * @param messageBegin beginning of the log message- * @param ex exception to log- */- private void logError(final String messageBegin, final Exception ex) {- if(log.isFine()) {- String message = ex.getMessage();- if(message == null) {- message = "no details";- } else if(message.length() > MAX_ERROR_MESSAGE_LENGTH){- /* Strip too large details to avoid polluting this log with complete remote stack traces */- message = message.substring(0, MAX_ERROR_MESSAGE_LENGTH) + "...";- }- log.fine(messageBegin + " at " + this.targetBaseURL + " : " + message);- }- }-++ /** Maximum length of detailed log error message */+ private final static int MAX_ERROR_MESSAGE_LENGTH = 500;++ /** Logger */+ private final static ConcurrentLog log = new ConcurrentLog(SolrRequestTask.class.getSimpleName());++ /** The solr to request */+ private RemoteInstance instance;++ /** Connector to the Solr instance */+ private SolrConnector solrConnector;++ /** The solr query to run */+ private final SolrQuery solrQuery;++ /** The instance base URL */+ private final String targetBaseURL;++ /** The target seed information */+ private final Seed target;++ /** Set to true when the target is this local peer */+ private final boolean mySeed;++ /** The request timeout in milliseconds */+ private final int timeout;++ /** The query response array to fill */+ private final QueryResponse[] rsp;++ /** The result documents list to fill */+ private final SolrDocumentList[] docList;++ /** Indicates wether this task has been closed */+ private volatile boolean closed;++ /**+ * Constructor. All parameters are required to not be null.+ * @param solrQuery the Solr query to run+ * @param targetBaseURL the instance base URL : http(s) + host name or IP + the eventual port+ * @param target the remote target seed information+ * @param timeout the request timeout in milliseconds+ */+ protected SolrRequestTask(final SolrQuery solrQuery, final String targetBaseURL, final Seed target,+ final boolean mySeed, final int timeout, final QueryResponse[] rsp, final SolrDocumentList[] docList) {+ super("Protocol.solrQuery(" + solrQuery.getQuery() + " to " + target.hash + ")");+ this.solrQuery = solrQuery;+ this.targetBaseURL = targetBaseURL;+ this.target = target;+ this.mySeed = mySeed;+ this.timeout = timeout;+ this.rsp = rsp;+ this.docList = docList;+ this.closed = false;+ }++ /**+ * Logs the exception detailed message if any, at fine level because errors on remote solr queries to other peers occurs quite frequently.+ * @param messageBegin beginning of the log message+ * @param ex exception to log+ */+ private void logError(final String messageBegin, final Exception ex) {+ if(log.isFine()) {+ String message = ex.getMessage();+ if(message == null) {+ message = "no details";+ } else if(message.length() > MAX_ERROR_MESSAGE_LENGTH){+ /* Strip too large details to avoid polluting this log with complete remote stack traces */+ message = message.substring(0, MAX_ERROR_MESSAGE_LENGTH) + "...";+ }+ log.fine(messageBegin + " at " + this.targetBaseURL + " : " + message);+ }+ }+@Overridepublic void run() {try {- boolean trustSelfSignedOnAuthenticatedServer = SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_AUTHENTICATED_ALLOW_SELF_SIGNED_DEFAULT;- if (Switchboard.getSwitchboard() != null) {- trustSelfSignedOnAuthenticatedServer = Switchboard.getSwitchboard().getConfigBool(- SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_AUTHENTICATED_ALLOW_SELF_SIGNED,- SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_AUTHENTICATED_ALLOW_SELF_SIGNED_DEFAULT);- }- /* Add a limit to the maximum acceptable size of the remote peer Solr response. This can help prevent out of memory errors when :- * - this peer is overloaded- * - the remote peer has indexed documents with excessively large metadata (too large at least to fit within this peer resources)- * - the remote peer is a malicious one and would like to trigger a deny of service */- final long maxBytesPerResponse = MemoryControl.available() / 4;-+ boolean trustSelfSignedOnAuthenticatedServer = SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_AUTHENTICATED_ALLOW_SELF_SIGNED_DEFAULT;+ if (Switchboard.getSwitchboard() != null) {+ trustSelfSignedOnAuthenticatedServer = Switchboard.getSwitchboard().getConfigBool(+ SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_AUTHENTICATED_ALLOW_SELF_SIGNED,+ SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_AUTHENTICATED_ALLOW_SELF_SIGNED_DEFAULT);+ }+ /* Add a limit to the maximum acceptable size of the remote peer Solr response. This can help prevent out of memory errors when :+ * - this peer is overloaded+ * - the remote peer has indexed documents with excessively large metadata (too large at least to fit within this peer resources)+ * - the remote peer is a malicious one and would like to trigger a deny of service */+ final long maxBytesPerResponse = MemoryControl.available() / 4;+this.instance = new RemoteInstance(this.targetBaseURL, null, "solr", this.timeout, trustSelfSignedOnAuthenticatedServer, maxBytesPerResponse, false); // this is a 'patch configuration' which considers 'solr' as default collectiontry {- boolean useBinaryResponseWriter = SwitchboardConstants.REMOTE_SOLR_BINARY_RESPONSE_ENABLED_DEFAULT;- if (Switchboard.getSwitchboard() != null) {- useBinaryResponseWriter = Switchboard.getSwitchboard().getConfigBool(- SwitchboardConstants.REMOTE_SOLR_BINARY_RESPONSE_ENABLED,- SwitchboardConstants.REMOTE_SOLR_BINARY_RESPONSE_ENABLED_DEFAULT);- }+ boolean useBinaryResponseWriter = SwitchboardConstants.REMOTE_SOLR_BINARY_RESPONSE_ENABLED_DEFAULT;+ if (Switchboard.getSwitchboard() != null) {+ useBinaryResponseWriter = Switchboard.getSwitchboard().getConfigBool(+ SwitchboardConstants.REMOTE_SOLR_BINARY_RESPONSE_ENABLED,+ SwitchboardConstants.REMOTE_SOLR_BINARY_RESPONSE_ENABLED_DEFAULT);+ }this.solrConnector = new RemoteSolrConnector(this.instance, useBinaryResponseWriter && (this.mySeed ? true : this.target.getVersion() >= 1.63), "solr");- if (!solrConnector.isClosed() && !this.closed) {- try {- this.rsp[0] = this.solrConnector.getResponseByParams(solrQuery);- this.docList[0] = this.rsp[0].getResults();- if(log.isFine() && rsp[0] != null && rsp[0].getElapsedTime() >= 0) {- log.fine("Got a response from solr instance at " + this.targetBaseURL + " in " + rsp[0].getElapsedTime() + "ms");- }- } catch (Exception e) {- logError("Could not get result from solr", e);- }- }+ if (!this.solrConnector.isClosed() && !this.closed) {+ try {+ this.rsp[0] = this.solrConnector.getResponseByParams(this.solrQuery);+ this.docList[0] = this.rsp[0].getResults();+ if(log.isFine() && this.rsp[0] != null && this.rsp[0].getElapsedTime() >= 0) {+ log.fine("Got a response from solr instance at " + this.targetBaseURL + " in " + this.rsp[0].getElapsedTime() + "ms");+ }+ } catch (Exception e) {+ logError("Could not get result from solr", e);+ }+ }} catch (Exception ee) {- logError("Could not connect to solr instance", ee);+ logError("Could not connect to solr instance", ee);}} catch (Exception eee) {- logError("Could not set up remote solr instance", eee);+ logError("Could not set up remote solr instance", eee);} finally {- this.close();+ this.close();}}-+/*** Stop the eventually running Solr request, and close the eventually opened connector and instance to the target Solr.*/- protected synchronized void close() {- if (!this.closed) {- try {- if (this.solrConnector != null) {- this.solrConnector.close();- }- } catch (Exception e) {- logError("Could not close solr connector", e);- } finally {- try {- if (this.instance != null) {- this.instance.close();- }- } catch (Exception e) {- logError("Could not close solr instance", e);- } finally {- this.closed = true;- }- }- }- }-+ protected synchronized void close() {+ if (!this.closed) {+ try {+ if (this.solrConnector != null) {+ this.solrConnector.close();+ }+ } catch (Exception e) {+ logError("Could not close solr connector", e);+ } finally {+ try {+ if (this.instance != null) {+ this.instance.close();+ }+ } catch (Exception e) {+ logError("Could not close solr instance", e);+ } finally {+ this.closed = true;+ }+ }+ }+ }+}-+/*** Execute solr query against specified target.* @param event search event ot feed with results@@ -1202,7 +1204,7 @@ public final class Protocol {final boolean incrementNavigators) throws InterruptedException {//try {System.out.println("*** debug-query *** " + URLDecoder.decode(solrQuery.toString(), "UTF-8"));} catch (UnsupportedEncodingException e) {}-+if (event.query.getQueryGoal().getQueryString(false) == null || event.query.getQueryGoal().getQueryString(false).length() == 0) {return -1; // we cannot query solr only with word hashes, there is no clear text string}@@ -1210,7 +1212,7 @@ public final class Protocol {if (partitions > 0) solrQuery.set("partitions", partitions);solrQuery.setStart(offset);solrQuery.setRows(count);-+boolean localsearch = target == null || target.equals(event.peers.mySeed());Map<String, ReversibleScoreMap<String>> facets = new HashMap<String, ReversibleScoreMap<String>>(event.query.facetfields.size());Map<String, LinkedHashSet<String>> snippets = new HashMap<String, LinkedHashSet<String>>(); // this will be a list of urlhash-snippet entries@@ -1234,20 +1236,20 @@ public final class Protocol {try {final boolean myseed = target == event.peers.mySeed();if(myseed) {- targetBaseURL = "http://localhost:" + target.getPort();+ targetBaseURL = "http://localhost:" + target.getPort();} else {final Set<String> ips = target.getIPs();if(ips.isEmpty()) {- /* This should not happen : seeds db maintains only seeds with at least one IP */- Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + " has no known IP address");- target.setFlagSolrAvailable(false);- return -1;+ /* This should not happen : seeds db maintains only seeds with at least one IP */+ Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + " has no known IP address");+ target.setFlagSolrAvailable(false);+ return -1;}final String ip = ips.iterator().next();-- targetBaseURL = target.getPublicURL(ip,- Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,- SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));++ targetBaseURL = target.getPublicURL(ip,+ Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,+ SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));}if (!myseed && !target.getFlagSolrAvailable()) { // skip if peer.dna has flag that last try resulted in errorNetwork.log.info("SEARCH skip (solr), remote Solr interface not accessible, peer=" + target.getName());@@ -1258,38 +1260,38 @@ public final class Protocol {remoteRequest.start();remoteRequest.join(solrtimeout); // just wait until timeout appearsif (remoteRequest.isAlive()) {- /* Try to free the request thread resources properly */- remoteRequest.close();- if(remoteRequest.isAlive()) {- /* Thread still running : try also with interrupt*/- remoteRequest.interrupt();- }+ /* Try to free the request thread resources properly */+ remoteRequest.close();+ if(remoteRequest.isAlive()) {+ /* Thread still running : try also with interrupt*/+ remoteRequest.interrupt();+ }Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + "/" + targetBaseURL + " does not answer (time-out)");target.setFlagSolrAvailable(false || myseed);return -1; // give up, leave remoteRequest abandoned.}-+if (rsp[0] == null || docList[0] == null) {Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + "/" + targetBaseURL + " returned null");if(!myseed) {- if(targetBaseURL.startsWith("https")) {- /* First mark https unavailable on this peer before removing anything else */- target.setFlagSSLAvailable(false);- event.peers.updateConnected(target);- } else {- target.setFlagSolrAvailable(false);- }+ if(targetBaseURL.startsWith("https")) {+ /* First mark https unavailable on this peer before removing anything else */+ target.setFlagSSLAvailable(false);+ event.peers.updateConnected(target);+ } else {+ target.setFlagSolrAvailable(false);+ }}return -1;}} catch(InterruptedException e) {- /* Current thread might be interrupted by SearchEvent.cleanup() :- * we must not in that case mark the target as not available but rather transmit the exception to the caller (likely RemoteSearch.solrRemoteSearch) */+ /* Current thread might be interrupted by SearchEvent.cleanup() :+ * we must not in that case mark the target as not available but rather transmit the exception to the caller (likely RemoteSearch.solrRemoteSearch) */throw e;} catch (final Throwable e) {- if(Network.log.isInfo()) {- Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + (targetBaseURL != null ? "/" + targetBaseURL : "") + " (" + e.getMessage() + ")");- }+ if(Network.log.isInfo()) {+ Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + (targetBaseURL != null ? "/" + targetBaseURL : "") + " (" + e.getMessage() + ")");+ }target.setFlagSolrAvailable(false || localsearch);return -1;}@@ -1297,29 +1299,29 @@ public final class Protocol {// evaluate facetsif(useSolrFacets) {- for (String field: event.query.facetfields.keySet()) {- FacetField facet = rsp[0].getFacetField(field);- ReversibleScoreMap<String> result = new ClusteredScoreMap<String>(UTF8.insensitiveUTF8Comparator);- List<Count> values = facet == null ? null : facet.getValues();- if (values == null) {- continue;- }- for (Count ff: values) {- int c = (int) ff.getCount();- if (c == 0) {- continue;- }- if (ff.getName().length() == 0) {- continue; // facet entry without text is not useful- }- result.set(ff.getName(), c);- }- if (result.size() > 0) {- facets.put(field, result);- }- }- }-+ for (String field: event.query.facetfields.keySet()) {+ FacetField facet = rsp[0].getFacetField(field);+ ReversibleScoreMap<String> result = new ClusteredScoreMap<String>(UTF8.insensitiveUTF8Comparator);+ List<Count> values = facet == null ? null : facet.getValues();+ if (values == null) {+ continue;+ }+ for (Count ff: values) {+ int c = (int) ff.getCount();+ if (c == 0) {+ continue;+ }+ if (ff.getName().length() == 0) {+ continue; // facet entry without text is not useful+ }+ result.set(ff.getName(), c);+ }+ if (result.size() > 0) {+ facets.put(field, result);+ }+ }+ }+// evaluate snippetsfinal Map<String, Map<String, List<String>>> rawsnippets = rsp[0].getHighlighting(); // a map from the urlhash to a map with key=field and value = list of snippetsif (rawsnippets != null) {@@ -1341,19 +1343,19 @@ public final class Protocol {}rsp[0] = null;}-+// evaluate resultfinal int numFound = (int) docList[0].getNumFound();if (docList == null || docList[0].isEmpty()) {Network.log.info("SEARCH (solr), returned 0 out of 0 documents from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())) + " query = " + solrQuery.toString()) ;if(localsearch && offset > 0) {- /* No documents were returned from Solr because the offset is too high, but we have to keep the total number of matching documents for accurate pagination.- * This case can notably happen on latest results pages, when mixing results from local RWI and local Solr ("Stealth Mode") */- event.local_solr_stored.set(numFound);+ /* No documents were returned from Solr because the offset is too high, but we have to keep the total number of matching documents for accurate pagination.+ * This case can notably happen on latest results pages, when mixing results from local RWI and local Solr ("Stealth Mode") */+ event.local_solr_stored.set(numFound);}return 0;}-+List<URIMetadataNode> resultContainer = new ArrayList<URIMetadataNode>();Network.log.info("SEARCH (solr), returned " + docList[0].size() + " out of " + docList[0].getNumFound() + " documents and " + facets.size() + " facets " + facets.keySet().toString() + " from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));int term = count;@@ -1402,7 +1404,7 @@ public final class Protocol {// passed all checks, store urlif (!localsearch) {-+// put the remote documents to the local index. We must convert the solr document to a solr input document:if (event.addResultsToLocalIndex) {/* Check document size, only if a limit is set on remote documents size allowed to be stored to local index */@@ -1444,7 +1446,7 @@ public final class Protocol {} else {if (event.addResultsToLocalIndex) {/*- * Current thread might be interrupted by SearchEvent.cleanup()+ * Current thread might be interrupted by SearchEvent.cleanup()*/if (Thread.interrupted()) {throw new InterruptedException("solrQuery interrupted");@@ -1460,101 +1462,101 @@ public final class Protocol {}return resultContainer.size();}-+/*** This thread is used to write a collection of Solr documents to a segment allowing to be safely stopped.- * Indeed, if one interrupt a thread while commiting to Solr index, the index is closed and will be no more writable+ * Indeed, if one interrupt a thread while commiting to Solr index, the index is closed and will be no more writable* (later calls would throw a org.apache.lucene.store.AlreadyClosedException) because Solr IndexWriter uses an InterruptibleChanel.* This thead allow to safely stop writing operation using an AtomicBoolean.* @author luc**/private static class WriteToLocalIndexThread extends Thread {-- private AtomicBoolean stop = new AtomicBoolean(false);-- private Segment segment;-- private Collection<SolrInputDocument> docs;-- /**- * Parameters must be not null.++ private AtomicBoolean stop = new AtomicBoolean(false);++ private Segment segment;++ private Collection<SolrInputDocument> docs;++ /**+ * Parameters must be not null.* After writing the collection is cleared- * @param segment solr segment to write- * @param docs solr documents collection to put to segment- */- public WriteToLocalIndexThread(Segment segment, Collection<SolrInputDocument> docs) {- super("WriteToLocalIndexThread");- this.segment = segment;- this.docs = docs;- }--// /**-// * Use this to stop writing operation. This thread will not stop immediately as Solr might be writing something.-// */-// public void stopWriting() {-// this.stop.set(true);-// }-+ * @param segment solr segment to write+ * @param docs solr documents collection to put to segment+ */+ public WriteToLocalIndexThread(Segment segment, Collection<SolrInputDocument> docs) {+ super("WriteToLocalIndexThread");+ this.segment = segment;+ this.docs = docs;+ }++// /**+// * Use this to stop writing operation. This thread will not stop immediately as Solr might be writing something.+// */+// public void stopWriting() {+// this.stop.set(true);+// }+@Overridepublic void run() {- for (SolrInputDocument doc : docs) {- if (stop.get()) {- docs.clear();+ for (SolrInputDocument doc : this.docs) {+ if (this.stop.get()) {+ this.docs.clear();Network.log.info("Writing documents collection to Solr segment was stopped.");return;}- segment.putDocument(doc);+ this.segment.putDocument(doc);}- docs.clear();+ this.docs.clear();}}-- /**- * Only when maxSize is greater than zero, check that doc size is lower. To- * process in a reasonable amount of time, document size is not evaluated- * summing all fields sizes, but only against text_t field which is quite representative and might weigh- * some MB.- *- * @param doc- * document to verify. Must not be null.- * @param maxSize- * maximum allowed size in bytes- * @return true when document evaluated size is lower or equal than maxSize, or when- * maxSize is lower or equal than zero.- */- protected static boolean checkDocumentSize(SolrDocument doc, long maxSize) {- if (maxSize > 0) {- /* All text field is often the largest */- Object value = doc.getFieldValue(CollectionSchema.text_t.getSolrFieldName());- if(value instanceof String) {- /* Each char uses 2 bytes */- if(((String)value).length() > (maxSize /2)) {- return false;- }- }- }- return true;- }-- /**- * Post a request asking for allowed message size and attachment size to the- * target peer on the selected target ip. All parameters must not be null.- *- * @param targetBaseURL- * the public base URL of the target peer on one of its reported IP- * addresses in {@link Seed#getIPs()}- * @param target- * the target peer- * @param sb- * the switchboard instance- * @return the result of the request- * @throws IOException- * when the peer doesn't answer on this IP or any other error- * occurred- */- public static Map<String, String> permissionMessage(final MultiProtocolURL targetBaseURL, final Seed target,- final Switchboard sb) throws IOException {++ /**+ * Only when maxSize is greater than zero, check that doc size is lower. To+ * process in a reasonable amount of time, document size is not evaluated+ * summing all fields sizes, but only against text_t field which is quite representative and might weigh+ * some MB.+ *+ * @param doc+ * document to verify. Must not be null.+ * @param maxSize+ * maximum allowed size in bytes+ * @return true when document evaluated size is lower or equal than maxSize, or when+ * maxSize is lower or equal than zero.+ */+ protected static boolean checkDocumentSize(SolrDocument doc, long maxSize) {+ if (maxSize > 0) {+ /* All text field is often the largest */+ Object value = doc.getFieldValue(CollectionSchema.text_t.getSolrFieldName());+ if(value instanceof String) {+ /* Each char uses 2 bytes */+ if(((String)value).length() > (maxSize /2)) {+ return false;+ }+ }+ }+ return true;+ }++ /**+ * Post a request asking for allowed message size and attachment size to the+ * target peer on the selected target ip. All parameters must not be null.+ *+ * @param targetBaseURL+ * the public base URL of the target peer on one of its reported IP+ * addresses in {@link Seed#getIPs()}+ * @param target+ * the target peer+ * @param sb+ * the switchboard instance+ * @return the result of the request+ * @throws IOException+ * when the peer doesn't answer on this IP or any other error+ * occurred+ */+ public static Map<String, String> permissionMessage(final MultiProtocolURL targetBaseURL, final Seed target,+ final Switchboard sb) throws IOException {// prepare requestfinal String salt = crypt.randomSalt();@@ -1562,13 +1564,13 @@ public final class Protocol {final Map<String, ContentBody> parts = basicRequestParts(sb, target.hash, salt);parts.put("process", UTF8.StringBody("permission"));final Post post = new Post(targetBaseURL, target.hash, "/yacy/message.html", parts, 6000);-+final Map<String, String> result = FileUtils.table(post.result);return result;}public static Map<String, String> crawlReceipt(- final Switchboard sb,+ final Switchboard sb,final Seed mySeed,final Seed target,final String process,@@ -1602,83 +1604,83 @@ public final class Protocol {// prepare requestfinal String salt = crypt.randomSalt();-- final boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,- SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);-- for (final String ip : target.getIPs()) {- // send request- try {- // prepare request- final Map<String, ContentBody> parts = basicRequestParts(sb, target.hash, salt);- parts.put("process", UTF8.StringBody(process));- parts.put("urlhash", UTF8.StringBody(((entry == null) ? "" : ASCII.String(entry.hash()))));- parts.put("result", UTF8.StringBody(result));- parts.put("reason", UTF8.StringBody(reason));- parts.put("wordh", UTF8.StringBody(wordhashes));- final String lurlstr;- if (entry == null) {- lurlstr = "";- } else {- final ArrayList<String> ldesc = entry.getDescription();- if (ldesc.isEmpty()) {- lurlstr = entry.toString();- } else { // add document abstract/description as snippet (remotely stored in description_txt)- lurlstr = entry.toString(ldesc.get(0));- }- }- parts.put("lurlEntry", UTF8.StringBody(crypt.simpleEncode(lurlstr, salt)));- // send request- byte[] content;- try (final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, 10000)) {- MultiProtocolURL targetBaseURL = target.getPublicMultiprotocolURL(ip, preferHttps);- try {- content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/crawlReceipt.html"),- target.getHexHash() + ".yacyh", parts, false, true);- } catch(final IOException e) {- if(targetBaseURL.isHTTPS()) {- /* Failed using https : retry with http */- targetBaseURL = target.getPublicMultiprotocolURL(ip, false);- content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/crawlReceipt.html"),- target.getHexHash() + ".yacyh", parts, false, true);- if(content != null) {- /* Success with http : mark SSL as unavailable on the target peer */- markSSLUnavailableOnPeer(sb.peers, target, ip, "yacyClient.crawlReceipt");- }- } else {- throw e;- }- }- }- return FileUtils.table(content);- } catch (final Exception e ) {- // most probably a network time-out exception- Network.log.warn("yacyClient.crawlReceipt error:" + e.getMessage());- }- }++ final boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,+ SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);++ for (final String ip : target.getIPs()) {+ // send request+ try {+ // prepare request+ final Map<String, ContentBody> parts = basicRequestParts(sb, target.hash, salt);+ parts.put("process", UTF8.StringBody(process));+ parts.put("urlhash", UTF8.StringBody(((entry == null) ? "" : ASCII.String(entry.hash()))));+ parts.put("result", UTF8.StringBody(result));+ parts.put("reason", UTF8.StringBody(reason));+ parts.put("wordh", UTF8.StringBody(wordhashes));+ final String lurlstr;+ if (entry == null) {+ lurlstr = "";+ } else {+ final ArrayList<String> ldesc = entry.getDescription();+ if (ldesc.isEmpty()) {+ lurlstr = entry.toString();+ } else { // add document abstract/description as snippet (remotely stored in description_txt)+ lurlstr = entry.toString(ldesc.get(0));+ }+ }+ parts.put("lurlEntry", UTF8.StringBody(crypt.simpleEncode(lurlstr, salt)));+ // send request+ byte[] content;+ try (final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, 10000)) {+ MultiProtocolURL targetBaseURL = target.getPublicMultiprotocolURL(ip, preferHttps);+ try {+ content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/crawlReceipt.html"),+ target.getHexHash() + ".yacyh", parts, false, true);+ } catch(final IOException e) {+ if(targetBaseURL.isHTTPS()) {+ /* Failed using https : retry with http */+ targetBaseURL = target.getPublicMultiprotocolURL(ip, false);+ content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/crawlReceipt.html"),+ target.getHexHash() + ".yacyh", parts, false, true);+ if(content != null) {+ /* Success with http : mark SSL as unavailable on the target peer */+ markSSLUnavailableOnPeer(sb.peers, target, ip, "yacyClient.crawlReceipt");+ }+ } else {+ throw e;+ }+ }+ }+ return FileUtils.table(content);+ } catch (final Exception e ) {+ // most probably a network time-out exception+ Network.log.warn("yacyClient.crawlReceipt error:" + e.getMessage());+ }+ }return null;}public static AtomicInteger metadataRetrievalRunning = new AtomicInteger(0);/**- * transfer the index. If the transmission fails, return a string describing the- * cause. If everything is ok, return null.- *- * @param sb- * the Switchboard instance holding server environment- * @param targetSeed- * the target peer- * @param indexes- * the index entries to transfer- * @param urlCache- * @param gzipBody- * when true, the transferred data are compressed using gzip- * @param timeout- * the maximum time in milliseconds to wait for a success of the- * http(s) request to the remote peer- * @return- */+ * transfer the index. If the transmission fails, return a string describing the+ * cause. If everything is ok, return null.+ *+ * @param sb+ * the Switchboard instance holding server environment+ * @param targetSeed+ * the target peer+ * @param indexes+ * the index entries to transfer+ * @param urlCache+ * @param gzipBody+ * when true, the transferred data are compressed using gzip+ * @param timeout+ * the maximum time in milliseconds to wait for a success of the+ * http(s) request to the remote peer+ * @return+ */public static String transferIndex(final Switchboard sb,final Seed targetSeed,@@ -1704,10 +1706,10 @@ public final class Protocol {}}}-- final boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,- SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);-++ final boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,+ SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);+// transfer the RWI without the URLsMap<String, String> in = transferRWI(targetSeed, indexes, gzipBody, timeout, preferHttps);@@ -1777,23 +1779,23 @@ public final class Protocol {}/**- * Transfer Reverse Word Index entries to remote peer. If the used IP is not- * responding, this IP (interface) is removed from targtSeed IP list. Remote- * peer responds with list of unknown url hashes- *- * @param targetSeed- * the target peer- * @param indexes- * the index entries to transfer- * @param gzipBody- * when true, the transferred data are compressed using gzip- * @param timeout- * the maximum time in milliseconds to wait for a success of the- * http(s) request(s) to the remote peer- * @param preferHttps- * when true, use https when available on the target peer- * @return peer response or null if transfer failed- */+ * Transfer Reverse Word Index entries to remote peer. If the used IP is not+ * responding, this IP (interface) is removed from targtSeed IP list. Remote+ * peer responds with list of unknown url hashes+ *+ * @param targetSeed+ * the target peer+ * @param indexes+ * the index entries to transfer+ * @param gzipBody+ * when true, the transferred data are compressed using gzip+ * @param timeout+ * the maximum time in milliseconds to wait for a success of the+ * http(s) request(s) to the remote peer+ * @param preferHttps+ * when true, use https when available on the target peer+ * @return peer response or null if transfer failed+ */private static Map<String, String> transferRWI(final Seed targetSeed,final ReferenceContainerCache<WordReference> indexes,@@ -1807,7 +1809,7 @@ public final class Protocol {}MultiProtocolURL targetBaseURL = null;try {- targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, preferHttps);+ targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, preferHttps);} catch(final MalformedURLException e) {Network.log.info("yacyClient.transferRWI malformed target URL : " + targetBaseURL);// disconnect unavailable peer ip@@ -1854,20 +1856,20 @@ public final class Protocol {byte[] content = null;try (final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, timeout)) {try {- content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferRWI.html"),- targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);+ content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferRWI.html"),+ targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);} catch(final IOException e) {if(targetBaseURL.isHTTPS()) {- targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, false);- /* Failed with https : retry with http on the same address */- content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferRWI.html"),- targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);- if(content != null) {- /* Success with http : mark SSL as unavailable on the target peer */- markSSLUnavailableOnPeer(Switchboard.getSwitchboard().peers, targetSeed, ip, "yacyClient.transferRWI");- }+ targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, false);+ /* Failed with https : retry with http on the same address */+ content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferRWI.html"),+ targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);+ if(content != null) {+ /* Success with http : mark SSL as unavailable on the target peer */+ markSSLUnavailableOnPeer(Switchboard.getSwitchboard().peers, targetSeed, ip, "yacyClient.transferRWI");+ }} else {- throw e;+ throw e;}}}@@ -1891,17 +1893,17 @@ public final class Protocol {/*** Transfer URL entries to remote peer*- * @param targetSeed- * the target peer+ * @param targetSeed+ * the target peer* @param uhs hashes of URLs to transfer (unknown by the target peer)* @param urlRefs list of locally known URLs entries* @param segment- * @param gzipBody- * when true, the transferred data are compressed using gzip- * @param timeout- * the maximum time in milliseconds to wait for a success of the- * http(s) request(s) to the remote peer+ * @param gzipBody+ * when true, the transferred data are compressed using gzip+ * @param timeout+ * the maximum time in milliseconds to wait for a success of the+ * http(s) request(s) to the remote peer* @param preferHttps when true, use https when available on the target peer* @return remote peer response*/@@ -1951,25 +1953,25 @@ public final class Protocol {}}metadataRetrievalRunning.decrementAndGet();-+try {MultiProtocolURL targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, preferHttps);-+parts.put("urlc", UTF8.StringBody(Integer.toString(urlc)));byte[] content = null;try (final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, timeout)) {try {- content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferURL.html"),- targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);+ content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferURL.html"),+ targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);} catch(final IOException e) {- if(targetBaseURL.isHTTPS()) {- targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, false);- /* Failed with https : retry with http on the same address */- content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferURL.html"),- targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);- } else {- throw e;- }+ if(targetBaseURL.isHTTPS()) {+ targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, false);+ /* Failed with https : retry with http on the same address */+ content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/transferURL.html"),+ targetSeed.getHexHash() + ".yacyh", parts, gzipBody, true);+ } else {+ throw e;+ }}}final Iterator<String> v = FileUtils.strings(content);@@ -1997,9 +1999,9 @@ public final class Protocol {// this post a message to the remote message boardfinal String salt = crypt.randomSalt();-- final boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,- SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);++ final boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,+ SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);for (final String ip : targetSeed.getIPs()) {try (final HTTPClient httpclient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, 15000)) {@@ -2007,21 +2009,21 @@ public final class Protocol {MultiProtocolURL targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, preferHttps);byte[] content;try {- content = httpclient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/profile.html"),- targetSeed.getHexHash() + ".yacyh", parts, false, true);+ content = httpclient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/profile.html"),+ targetSeed.getHexHash() + ".yacyh", parts, false, true);} catch(final IOException e) {- if(targetBaseURL.isHTTPS()) {- /* Failed with https : retry using http */- targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, false);- content = httpclient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/profile.html"),- targetSeed.getHexHash() + ".yacyh", parts, false, true);- if(content != null) {- /* Got something with http : mark peer SSL as unavailable on target peer */- markSSLUnavailableOnPeer(sb.peers, targetSeed, ip, "yacyClient.getProfile");- }- } else {- throw e;- }+ if(targetBaseURL.isHTTPS()) {+ /* Failed with https : retry using http */+ targetBaseURL = targetSeed.getPublicMultiprotocolURL(ip, false);+ content = httpclient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/profile.html"),+ targetSeed.getHexHash() + ".yacyh", parts, false, true);+ if(content != null) {+ /* Got something with http : mark peer SSL as unavailable on target peer */+ markSSLUnavailableOnPeer(sb.peers, targetSeed, ip, "yacyClient.getProfile");+ }+ } else {+ throw e;+ }}return FileUtils.table(content);} catch (final Exception e ) {@@ -2054,11 +2056,11 @@ public final class Protocol {final Set<String> targetIps = target.getIPs();if(targetIps.isEmpty()) {Network.log.warn("yacyClient.loadIDXHosts error: no known address on target peer.");- return null;+ return null;}- final String remoteBaseURL = target.getPublicURL(targetIps.iterator().next(),- Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,- SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT));+ final String remoteBaseURL = target.getPublicURL(targetIps.iterator().next(),+ Switchboard.getSwitchboard().getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,+ SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT));final Post post = new Post(new MultiProtocolURL(remoteBaseURL), target.hash, "/yacy/idx.json", parts, 30000);if ( post.result == null || post.result.length == 0 ) {Network.log.warn("yacyClient.loadIDXHosts error: empty result");@@ -2151,25 +2153,25 @@ public final class Protocol {*/public static final LinkedHashMap<String, ContentBody> basicRequestParts(final Switchboard sb, final String targetHash, final String salt) {final LinkedHashMap<String, ContentBody> parts = new LinkedHashMap<String, ContentBody>();-+// just standard identification essentialsif ( sb.peers.mySeed().hash != null ) {parts.put("iam", UTF8.StringBody(sb.peers.mySeed().hash));if ( targetHash != null ) parts.put("youare", UTF8.StringBody(targetHash));-+// time information for synchronizationfinal long myTime = System.currentTimeMillis();String formattedTime;try {- /* Prefer using first the shared and thread-safe DateTimeFormatter instance */- formattedTime = GenericFormatter.FORMAT_SHORT_SECOND.format(Instant.ofEpochMilli(myTime));+ /* Prefer using first the shared and thread-safe DateTimeFormatter instance */+ formattedTime = GenericFormatter.FORMAT_SHORT_SECOND.format(Instant.ofEpochMilli(myTime));} catch(final DateTimeException e) {- /* This should not happen, but rather than failing we fallback to the old formatter wich uses synchronization locks */- formattedTime = GenericFormatter.SHORT_SECOND_FORMATTER.format(new Date(myTime));+ /* This should not happen, but rather than failing we fallback to the old formatter wich uses synchronization locks */+ formattedTime = GenericFormatter.SHORT_SECOND_FORMATTER.format(new Date(myTime));}parts.put("mytime", UTF8.StringBody(formattedTime));parts.put("myUTC", UTF8.StringBody(Long.toString(myTime)));-+// network identificationparts.put(SwitchboardConstants.NETWORK_NAME, UTF8.StringBody(Switchboard.getSwitchboard().getConfig(SwitchboardConstants.NETWORK_NAME,@@ -2203,27 +2205,27 @@ public final class Protocol {}return "?" + sb.toString().substring(1);}-- /**- * Mark a SSL/TLS as unavailable on a connected peer and log an information- * level message. Use when http is successful whereas https is not on the target- * peer. All parameters must not be null.- *- * @param seedDB- * the seeds database to update- * @param peer- * the peer to update- * @param address- * the address on peer where http is successful but https fails.- * @param logPrefix- * a prefix to the log message- */- private static void markSSLUnavailableOnPeer(final SeedDB seedDB, final Seed peer, final String address,- final String logPrefix) {- Network.log.info(logPrefix + " SSL/TLS unavailable on peer '" + peer.getName()- + "' : can be reached using http but not https on address " + address);- peer.setFlagSSLAvailable(false);- seedDB.updateConnected(peer);- }-++ /**+ * Mark a SSL/TLS as unavailable on a connected peer and log an information+ * level message. Use when http is successful whereas https is not on the target+ * peer. All parameters must not be null.+ *+ * @param seedDB+ * the seeds database to update+ * @param peer+ * the peer to update+ * @param address+ * the address on peer where http is successful but https fails.+ * @param logPrefix+ * a prefix to the log message+ */+ private static void markSSLUnavailableOnPeer(final SeedDB seedDB, final Seed peer, final String address,+ final String logPrefix) {+ Network.log.info(logPrefix + " SSL/TLS unavailable on peer '" + peer.getName()+ + "' : can be reached using http but not https on address " + address);+ peer.setFlagSSLAvailable(false);+ seedDB.updateConnected(peer);+ }+}diff --git a/source/net/yacy/search/index/Fulltext.java b/source/net/yacy/search/index/Fulltext.javaindex 8d5449032..5578d5bfa 100644--- a/source/net/yacy/search/index/Fulltext.java+++ b/source/net/yacy/search/index/Fulltext.java@@ -217,7 +217,7 @@ public final class Fulltext {}return null;} finally {- this.solrInstancesLock.unlock();+ this.solrInstancesLock.unlock();}}@@ -226,7 +226,7 @@ public final class Fulltext {try {return this.solrInstances.getDefaultMirrorConnector();} finally {- this.solrInstancesLock.unlock();+ this.solrInstancesLock.unlock();}}@@ -319,8 +319,8 @@ public final class Fulltext {private long lastCommit = 0;public void commit(boolean softCommit) {long t = System.currentTimeMillis();- if (lastCommit + 10000 > t) return;- lastCommit = t;+ if (this.lastCommit + 10000 > t) return;+ this.lastCommit = t;getDefaultConnector().commit(softCommit);if (this.writeWebgraph) getWebgraphConnector().commit(softCommit);}@@ -332,13 +332,13 @@ public final class Fulltext {* are accessible) of the returned document.* If the no document with url.hash = solrdocument.id is found in the embedded* Solr index null is return.- *+ ** @param element rwi wordreference* @return URIMetadataNode (solrdocument) with all fields stored in embedded solr index*/public URIMetadataNode getMetadata(final WeakPriorityBlockingQueue.Element<WordReferenceVars> element) {if (element == null) return null;- WordReferenceVars wre = element.getElement();+ WordReferenceVars wre = element.getElement();if (wre == null) return null; // all time was already wasted in takeRWI to get another elementlong score = element.getWeight();URIMetadataNode node = getMetadata(wre.urlhash(), wre, score);@@ -572,7 +572,7 @@ public final class Fulltext {if (md == null) return null;return new DigestURL(md.url, ASCII.getBytes(urlHash));}-+/*** check if a given document, identified by url hash as document id exists* @param id the url hash and document id@@ -587,6 +587,7 @@ public final class Fulltext {* @param urlHash* @return the time in milliseconds since epoch for the load time or -1 if the document does not exist*/+ @Deprecatedprivate long getLoadTime(final String urlHash) throws IOException {if (urlHash == null) return -1l;SolrConnector.LoadTimeURL md = this.getDefaultConnector().getLoadTimeURL(urlHash);@@ -727,7 +728,7 @@ public final class Fulltext {String nowstr = new Date(now).toInstant().toString();String fromstr = new Date(from).toInstant().toString();String dateq = CollectionSchema.load_date_dt.getSolrFieldName() + ":[" + fromstr + " TO " + nowstr + "]";- query = query == null || AbstractSolrConnector.CATCHALL_QUERY.equals(query) ? dateq : query + " AND " + dateq;+ query = query == null || AbstractSolrConnector.CATCHALL_QUERY.equals(query) ? dateq : query + " AND " + dateq;} else {query = query == null? AbstractSolrConnector.CATCHALL_QUERY : query;}@@ -744,7 +745,7 @@ public final class Fulltext {final Date firstdate, lastdate;if (firstdoclist.size() == 0 || lastdoclist.size() == 0) {/* Now check again the number of documents without sorting, for compatibility with old fields indexed without DocValues fields (prior to YaCy 1.90)- * When the local Solr index contains such old documents, requests with sort query return nothing and trace in logs+ * When the local Solr index contains such old documents, requests with sort query return nothing and trace in logs* "java.lang.IllegalStateException: unexpected docvalues type NONE for field..." */doccount = this.getDefaultConnector().getCountByQuery(query);if(doccount == 0) {@@ -764,8 +765,8 @@ public final class Fulltext {firstdateobject = firstdoc.getFieldValue(CollectionSchema.load_date_dt.getSolrFieldName());lastdateobject = lastdoc.getFieldValue(CollectionSchema.load_date_dt.getSolrFieldName());- /* When firstdate or lastdate is null, we use a default one just to generate a proper dump file path- * This should not happen because load_date_dt field is mandatory in the main Solr schema,+ /* When firstdate or lastdate is null, we use a default one just to generate a proper dump file path+ * This should not happen because load_date_dt field is mandatory in the main Solr schema,* but for some reason some documents might end up here with an empty load_date_dt field value */if(firstdateobject instanceof Date) {firstdate = (Date) firstdateobject;@@ -854,7 +855,7 @@ public final class Fulltext {try (/* Resources automatically closed by this try-with-resources statement */final OutputStream os = new FileOutputStream(this.format == ExportFormat.solr ? new File(this.f.getAbsolutePath() + ".gz") : this.f);- final OutputStream wrappedStream = ((this.format == ExportFormat.solr)) ? new GZIPOutputStream(os, 65536){{def.setLevel(Deflater.BEST_COMPRESSION);}} : os;+ final OutputStream wrappedStream = ((this.format == ExportFormat.solr)) ? new GZIPOutputStream(os, 65536){{this.def.setLevel(Deflater.BEST_COMPRESSION);}} : os;final PrintWriter pw = new PrintWriter(new BufferedOutputStream(wrappedStream));) {if (this.format == ExportFormat.html) {@@ -907,7 +908,7 @@ public final class Fulltext {this.count++;}} else {- BlockingQueue<SolrDocument> docs = Fulltext.this.getDefaultConnector().concurrentDocumentsByQuery(this.query + " AND " + CollectionSchema.httpstatus_i.getSolrFieldName() + ":200", null, 0, 100000000, Long.MAX_VALUE, 100, 1, true,+ BlockingQueue<SolrDocument> docs = Fulltext.this.getDefaultConnector().concurrentDocumentsByQuery(this.query + " AND " + CollectionSchema.httpstatus_i.getSolrFieldName() + ":200", null, 0, 100000000, Long.MAX_VALUE, 100, 1, true,CollectionSchema.id.getSolrFieldName(), CollectionSchema.sku.getSolrFieldName(), CollectionSchema.title.getSolrFieldName(),CollectionSchema.author.getSolrFieldName(), CollectionSchema.description_txt.getSolrFieldName(), CollectionSchema.size_i.getSolrFieldName(), CollectionSchema.last_modified.getSolrFieldName());SolrDocument doc;diff --git a/source/net/yacy/search/index/Segment.java b/source/net/yacy/search/index/Segment.javaindex 486aeee53..953a7379f 100644--- a/source/net/yacy/search/index/Segment.java+++ b/source/net/yacy/search/index/Segment.java@@ -51,6 +51,7 @@ import net.yacy.cora.document.id.DigestURL;import net.yacy.cora.document.id.MultiProtocolURL;import net.yacy.cora.federate.solr.connector.AbstractSolrConnector;import net.yacy.cora.federate.solr.connector.SolrConnector;+import net.yacy.cora.federate.solr.connector.SolrConnector.LoadTimeURL;import net.yacy.cora.federate.yacy.CacheStrategy;import net.yacy.cora.order.Base64Order;import net.yacy.cora.order.ByteOrder;@@ -110,8 +111,9 @@ public class Segment {public static final long targetFileSize = 64 * 1024 * 1024; // 256 MBpublic static final int writeBufferSize = 4 * 1024 * 1024;public static final String termIndexName = "text.index";- public static final String citationIndexName = "citation.index";+ public static final String citationIndexName = "citation.index";public static final String firstseenIndexName = "firstseen.index";+ public static final String loadtimeIndexName = "loadtime.index";// the reference factorypublic static final ReferenceFactory<WordReference> wordReferenceFactory = new WordReferenceFactory();@@ -122,9 +124,10 @@ public class Segment {private final File segmentPath;protected final Fulltext fulltext;protected IndexCell<WordReference> termIndex;- protected IndexCell<CitationReference> urlCitationIndex;- protected IndexTable firstSeenIndex;- protected IODispatcher merger = null; // shared iodispatcher for kelondro indexes+ private IndexCell<CitationReference> urlCitationIndex;+ private IndexTable firstSeenIndex;+ private IndexTable loadTimeIndex;+ private IODispatcher merger = null; // shared iodispatcher for kelondro indexes/*** create a new Segment@@ -138,20 +141,21 @@ public class Segment {this.log = log;this.segmentPath = segmentPath;archivePath.mkdirs();-+this.fulltext = new Fulltext(segmentPath, archivePath, collectionConfiguration, webgraphConfiguration);this.termIndex = null;this.urlCitationIndex = null;this.firstSeenIndex = new IndexTable(new File(segmentPath, firstseenIndexName), 12, 8, false, false);+ this.loadTimeIndex = new IndexTable(new File(segmentPath, loadtimeIndexName), 12, 8, false, false);}-+public boolean connectedRWI() {return this.termIndex != null;}public void connectRWI(final int entityCacheMaxSize, final long maxFileSize) throws IOException {if (this.termIndex != null) return;-+if (this.merger == null) { // init shared iodispatcher if none runningthis.merger = new IODispatcher(2, 2, writeBufferSize);this.merger.start();@@ -166,7 +170,7 @@ public class Segment {targetFileSize,maxFileSize,writeBufferSize,- merger);+ this.merger);}public void disconnectRWI() {@@ -196,7 +200,7 @@ public class Segment {targetFileSize,maxFileSize,writeBufferSize,- merger);+ this.merger);}public void disconnectCitation() {@@ -208,7 +212,7 @@ public class Segment {public int citationCount() {return this.urlCitationIndex == null ? 0 : this.urlCitationIndex.sizesMax();}-+public long citationSegmentCount() {return this.urlCitationIndex == null ? 0 : this.urlCitationIndex.getSegmentCount();}@@ -224,27 +228,31 @@ public class Segment {public IndexCell<CitationReference> urlCitation() {return this.urlCitationIndex;}-- public IndexTable firstSeen() {++ public IndexTable firstSeenIndex() {return this.firstSeenIndex;}-++ public IndexTable loadTimeIndex() {+ return this.loadTimeIndex;+ }+public ReferenceReportCache getReferenceReportCache() {return new ReferenceReportCache();}-+public class ReferenceReportCache {private final Map<String, ReferenceReport> cache;public ReferenceReportCache() {this.cache = new ConcurrentHashMap<String, ReferenceReport>();}public ReferenceReport getReferenceReport(final String id, final boolean acceptSelfReference) throws IOException {- ReferenceReport rr = cache.get(id);- if (MemoryControl.shortStatus()) cache.clear();+ ReferenceReport rr = this.cache.get(id);+ if (MemoryControl.shortStatus()) this.cache.clear();if (rr != null) return rr;try {rr = new ReferenceReport(ASCII.getBytes(id), acceptSelfReference);- cache.put(id, rr);+ this.cache.put(id, rr);return rr;} catch (final SpaceExceededException e) {ConcurrentLog.logException(e);@@ -252,7 +260,7 @@ public class Segment {}}}-+/*** A ReferenceReport object is a container for all references to a specific url.* The class stores the number of links from domain-internal and domain-external backlinks,@@ -278,19 +286,19 @@ public class Segment {CitationReference ref = ri.next();byte[] hh = ref.hosthash(); // host hashif (ByteBuffer.equals(hh, 0, id, 6, 6)) {- internalIDs.put(ref.urlhash());- internal++;+ this.internalIDs.put(ref.urlhash());+ this.internal++;} else {- externalHosts.put(hh);- externalIDs.put(ref.urlhash());- external++;+ this.externalHosts.put(hh);+ this.externalIDs.put(ref.urlhash());+ this.external++;}}} catch (SpaceExceededException e) {// the Citation Index got too large, we ignore the problem and hope that a second solr index is attached which will take over now- if (Segment.this.fulltext.useWebgraph()) internalIDs.clear();+ if (Segment.this.fulltext.useWebgraph()) this.internalIDs.clear();}- if ((internalIDs.size() == 0 || !connectedCitation()) && Segment.this.fulltext.useWebgraph()) {+ if ((this.internalIDs.size() == 0 || !connectedCitation()) && Segment.this.fulltext.useWebgraph()) {// reqd the references from the webgraphSolrConnector webgraph = Segment.this.fulltext.getWebgraphConnector();BlockingQueue<SolrDocument> docs = webgraph.concurrentDocumentsByQuery("{!cache=false raw f=" + WebgraphSchema.target_id_s.getSolrFieldName() + "}" + ASCII.String(id), WebgraphSchema.source_chars_i.getSolrFieldName() + " asc", 0, 10000000, Long.MAX_VALUE, 100, 1, false, WebgraphSchema.source_id_s.getSolrFieldName());@@ -305,13 +313,13 @@ public class Segment {System.arraycopy(refidh, 6, hh, 0, 6);if (ByteBuffer.equals(hh, 0, id, 6, 6)) {if (acceptSelfReference || !Arrays.equals(refidh, id)) {- internalIDs.put(refidh);- internal++;+ this.internalIDs.put(refidh);+ this.internal++;}} else {- externalHosts.put(hh);- externalIDs.put(refidh);- external++;+ this.externalHosts.put(hh);+ this.externalIDs.put(refidh);+ this.external++;}}} catch (final InterruptedException e) {@@ -338,12 +346,12 @@ public class Segment {return this.internalIDs;}}-+public long RWICount() {if (this.termIndex == null) return 0;return this.termIndex.sizesMax();}-+public long RWISegmentCount() {if (this.termIndex == null) return 0;return this.termIndex.getSegmentCount();@@ -377,7 +385,7 @@ public class Segment {return 0;}}-+public void setFirstSeenTime(final byte[] urlhash, long time) {if (urlhash == null || time <= 0) return;try {@@ -387,7 +395,7 @@ public class Segment {ConcurrentLog.logException(e);}}-+public long getFirstSeenTime(final byte[] urlhash) {if (urlhash == null) return -1;try {@@ -397,7 +405,36 @@ public class Segment {return -1;}}-++ public void setLoadTime(final byte[] urlhash, long time) {+ if (urlhash == null || time <= 0) return;+ try {+ this.loadTimeIndex.put(urlhash, time); // ALWAYS overwrite!+ } catch (IOException e) {+ ConcurrentLog.logException(e);+ }+ }++ public long getLoadTime(final byte[] urlhash) {+ if (urlhash == null) return -1;+ try {+ return this.loadTimeIndex.get(urlhash);+ } catch (IOException e) {+ ConcurrentLog.logException(e);+ return -1;+ }+ }++ public LoadTimeURL getLoadTimeURL(String url, byte[] urlhash) {+ long t = getLoadTime(urlhash);+ if (t < 0) return null;+ return new LoadTimeURL(url, t);+ }++ public LoadTimeURL getLoadTimeURL(String url, String id) {+ return getLoadTimeURL(url, id.getBytes());+ }+/*** check if a given document, identified by url hash as document id exists* @param id the url hash and document id@@ -467,7 +504,7 @@ public class Segment {ConcurrentLog.logException(e);}}-+public void clearCaches() {if (this.urlCitationIndex != null) this.urlCitationIndex.clearCache();if (this.termIndex != null) this.termIndex.clearCache();@@ -483,6 +520,7 @@ public class Segment {if (this.fulltext != null) this.fulltext.close();if (this.urlCitationIndex != null) this.urlCitationIndex.close();if (this.firstSeenIndex != null) this.firstSeenIndex.close();+ if (this.loadTimeIndex != null) this.loadTimeIndex.close();if (this.merger != null) {this.merger.terminate();this.merger = null;@@ -575,11 +613,11 @@ public class Segment {) {final CollectionConfiguration collectionConfig = this.fulltext.getDefaultConfiguration();final String language = votedLanguage(url, url.toNormalform(true), document, condenser); // identification of the language-+final CollectionConfiguration.SolrVector vector = collectionConfig.yacy2solr(this, collections, responseHeader,document, condenser, referrerURL, language, crawlProfile.isPushCrawlProfile(),this.fulltext().useWebgraph() ? this.fulltext.getWebgraphConfiguration() : null, sourceName);-+return storeDocument(url, crawlProfile, responseHeader, document, vector, language, condenser,searchEvent, sourceName, storeToRWI, proxy, acceptLanguage);}@@ -599,10 +637,10 @@ public class Segment {final String acceptLanguage) {final long startTime = System.currentTimeMillis();-+final CollectionConfiguration collectionConfig = this.fulltext.getDefaultConfiguration();final String urlNormalform = url.toNormalform(true);-+// CREATE INDEX// load some document metadatafinal Date loadDate = new Date();@@ -619,7 +657,7 @@ public class Segment {// ENRICH DOCUMENT WITH RANKING INFORMATIONthis.fulltext.getDefaultConfiguration().postprocessing_references(this.getReferenceReportCache(), vector, url, null);-+// CREATE SNAPSHOTif ((url.getProtocol().equals("http") || url.getProtocol().equals("https")) &&crawlProfile != null && document.getDepth() <= crawlProfile.snapshotMaxdepth() &&@@ -634,13 +672,13 @@ public class Segment {// STORE IMAGE AND METADATATransactions.store(vector, true, crawlProfile.snapshotLoadImage(), crawlProfile.snapshotReplaceold(), proxy, acceptLanguage);}-+// STORE TO SOLRthis.putDocument(vector);List<SolrInputDocument> webgraph = vector.getWebgraphDocuments();String error = null;if (webgraph != null && webgraph.size() > 0) {-+// write the edges to the webgraph solr indexif (this.fulltext.useWebgraph()) {tryloop: for (int i = 0; i < 20; i++) {@@ -657,16 +695,18 @@ public class Segment {}}}-+}-+// REMEMBER FIRST SEEN- setFirstSeenTime(url.hash(), Math.min(document.getLastModified().getTime(), System.currentTimeMillis())); // should exist already in the index at this time, but just to make sure+ long now = System.currentTimeMillis();+ setFirstSeenTime(url.hash(), Math.min(document.getLastModified().getTime(), now)); // should exist already in the index at this time, but just to make sure+ setLoadTime(url.hash(), now); // always overwrites index entry// write the edges to the citation reference indexif (this.connectedCitation()) try {// we use the subgraph to write the citation index, that shall cause that the webgraph and the citation index is identical-+if (collectionConfig.contains(CollectionSchema.inboundlinks_protocol_sxt) || collectionConfig.contains(CollectionSchema.inboundlinks_urlstub_sxt)) {Collection<Object> inboundlinks_urlstub = vector.getFieldValues(CollectionSchema.inboundlinks_urlstub_sxt.getSolrFieldName());List<String> inboundlinks_protocol = inboundlinks_urlstub == null ? null : CollectionConfiguration.indexedList2protocolList(vector.getFieldValues(CollectionSchema.inboundlinks_protocol_sxt.getSolrFieldName()), inboundlinks_urlstub.size());@@ -676,7 +716,7 @@ public class Segment {String referrerhash = id;String anchorhash = ASCII.String(new DigestURL(targetURL).hash());if (referrerhash != null && anchorhash != null) {- urlCitationIndex.add(ASCII.getBytes(anchorhash), new CitationReference(ASCII.getBytes(referrerhash), loadDate.getTime()));+ this.urlCitationIndex.add(ASCII.getBytes(anchorhash), new CitationReference(ASCII.getBytes(referrerhash), loadDate.getTime()));}} catch (Throwable e) {ConcurrentLog.logException(e);@@ -692,7 +732,7 @@ public class Segment {String referrerhash = id;String anchorhash = ASCII.String(new DigestURL(targetURL).hash());if (referrerhash != null && anchorhash != null) {- urlCitationIndex.add(ASCII.getBytes(anchorhash), new CitationReference(ASCII.getBytes(referrerhash), loadDate.getTime()));+ this.urlCitationIndex.add(ASCII.getBytes(anchorhash), new CitationReference(ASCII.getBytes(referrerhash), loadDate.getTime()));}} catch (Throwable e) {ConcurrentLog.logException(e);@@ -702,7 +742,7 @@ public class Segment {} catch (Throwable e) {ConcurrentLog.logException(e);}-+if (error != null) {ConcurrentLog.severe("SOLR", error + ", PLEASE REPORT TO https://github.com/yacy/yacy_search_server/issues");//Switchboard.getSwitchboard().pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL, error);@@ -728,7 +768,7 @@ public class Segment {UTF8.getBytes(language),docType,outlinksSame, outlinksOther);-+// iterate over all words of content textWord wprop = null;byte[] wordhash;@@ -744,7 +784,7 @@ public class Segment {} catch (final Exception e) {ConcurrentLog.logException(e);}-+// during a search event it is possible that a heuristic is used which aquires index// data during search-time. To transfer indexed data directly to the search process// the following lines push the index data additionally to the search process@@ -762,7 +802,7 @@ public class Segment {}}if (searchEvent != null) searchEvent.addFinalize();-+// assign the catchall wordientry.setWord(wprop == null ? catchallWord : wprop); // we use one of the word properties as template to get the document characteristicsif (this.termIndex != null) try {this.termIndex.add(catchallHash, ientry);} catch (final Throwable e) {ConcurrentLog.logException(e);}