Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

NUTCH-650 - Hbase integration

Tacettin Guneyea5384453b85
diff --git a/CHANGES.txt b/CHANGES.txt
index 808bc2c4a..178f96240 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -5,6 +5,8 @@ Unreleased Changes
1. NUTCH-735 - crawl-tool.xml must be read before nutch-site.xml when
invoked using crawl command (Susam Pal via dogacan)
+ 2. NUTCH-650 - Hbase Integration (dogacan)
+
Release 1.0 - 2009-03-23
1. NUTCH-474 - Fetcher2 crawlDelay and blocking fix (Dogacan Guney via ab)
diff --git a/bin/nutch b/bin/nutch
index 57fddd568..9f7f1ddf5 100755
--- a/bin/nutch
+++ b/bin/nutch
@@ -32,21 +32,22 @@ done
if [ $# = 0 ]; then
echo "Usage: nutch [-core] COMMAND"
echo "where COMMAND is one of:"
- echo " crawl one-step crawler for intranets"
- echo " readdb read / dump crawl db"
- echo " convdb convert crawl db from pre-0.9 format"
- echo " mergedb merge crawldb-s, with optional filtering"
- echo " readlinkdb read / dump link db"
+# echo " crawl one-step crawler for intranets"
+# echo " readdb read / dump crawl db"
+# echo " convdb convert crawl db from pre-0.9 format"
+# echo " mergedb merge crawldb-s, with optional filtering"
+# echo " readlinkdb read / dump link db"
+ echo " createtable create a new webtable in hbase"
echo " inject inject new urls into the database"
echo " generate generate new segments to fetch from crawl db"
- echo " freegen generate new segments to fetch from text files"
- echo " fetch fetch a segment's pages"
- echo " parse parse a segment's pages"
- echo " readseg read / dump segment data"
- echo " mergesegs merge several segments, with optional filtering and slicing"
- echo " updatedb update crawl db from segments after fetching"
- echo " invertlinks create a linkdb from parsed segments"
- echo " mergelinkdb merge linkdb-s, with optional filtering"
+# echo " freegen generate new segments to fetch from text files"
+ echo " fetch fetch URLs marked during generate"
+ echo " parse parse URLs marked during fetch"
+# echo " readseg read / dump segment data"
+# echo " mergesegs merge several segments, with optional filtering and slicing"
+# echo " updatedb update crawl db from segments after fetching"
+# echo " invertlinks create a linkdb from parsed segments"
+# echo " mergelinkdb merge linkdb-s, with optional filtering"
echo " index run the indexer on parsed segments and linkdb"
echo " solrindex run the solr indexer on parsed segments and linkdb"
echo " merge merge several segment indexes"
@@ -186,7 +187,7 @@ if $cygwin; then
NUTCH_LOG_DIR=`cygpath -p -w "$NUTCH_LOG_DIR"`
fi
-NUTCH_OPTS="$NUTCH_OPTS -Dhadoop.log.dir=$NUTCH_LOG_DIR"
+NUTCH_OPTS="$NUTCH_OPTS -Dhadoop.log.dir=$NUTCH_LOG_DIR -Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
NUTCH_OPTS="$NUTCH_OPTS -Dhadoop.log.file=$NUTCH_LOGFILE"
if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
@@ -196,39 +197,39 @@ fi
# figure out which class to run
if [ "$COMMAND" = "crawl" ] ; then
CLASS=org.apache.nutch.crawl.Crawl
+elif [ "$COMMAND" = "createtable" ] ; then
+ CLASS=org.apache.nutch.util.hbase.WebTableCreator
elif [ "$COMMAND" = "inject" ] ; then
CLASS=org.apache.nutch.crawl.Injector
elif [ "$COMMAND" = "generate" ] ; then
CLASS=org.apache.nutch.crawl.Generator
-elif [ "$COMMAND" = "freegen" ] ; then
- CLASS=org.apache.nutch.tools.FreeGenerator
+#elif [ "$COMMAND" = "freegen" ] ; then
+# CLASS=org.apache.nutch.tools.FreeGenerator
elif [ "$COMMAND" = "fetch" ] ; then
CLASS=org.apache.nutch.fetcher.Fetcher
-elif [ "$COMMAND" = "fetch2" ] ; then
- CLASS=org.apache.nutch.fetcher.Fetcher2
elif [ "$COMMAND" = "parse" ] ; then
- CLASS=org.apache.nutch.parse.ParseSegment
-elif [ "$COMMAND" = "readdb" ] ; then
- CLASS=org.apache.nutch.crawl.CrawlDbReader
-elif [ "$COMMAND" = "convdb" ] ; then
- CLASS=org.apache.nutch.tools.compat.CrawlDbConverter
-elif [ "$COMMAND" = "mergedb" ] ; then
- CLASS=org.apache.nutch.crawl.CrawlDbMerger
-elif [ "$COMMAND" = "readlinkdb" ] ; then
- CLASS=org.apache.nutch.crawl.LinkDbReader
-elif [ "$COMMAND" = "readseg" ] ; then
- CLASS=org.apache.nutch.segment.SegmentReader
-elif [ "$COMMAND" = "segread" ] ; then
- echo "[DEPRECATED] Command 'segread' is deprecated, use 'readseg' instead."
- CLASS=org.apache.nutch.segment.SegmentReader
-elif [ "$COMMAND" = "mergesegs" ] ; then
- CLASS=org.apache.nutch.segment.SegmentMerger
-elif [ "$COMMAND" = "updatedb" ] ; then
- CLASS=org.apache.nutch.crawl.CrawlDb
-elif [ "$COMMAND" = "invertlinks" ] ; then
- CLASS=org.apache.nutch.crawl.LinkDb
-elif [ "$COMMAND" = "mergelinkdb" ] ; then
- CLASS=org.apache.nutch.crawl.LinkDbMerger
+ CLASS=org.apache.nutch.parse.TableParser
+#elif [ "$COMMAND" = "readdb" ] ; then
+# CLASS=org.apache.nutch.crawl.CrawlDbReader
+#elif [ "$COMMAND" = "convdb" ] ; then
+# CLASS=org.apache.nutch.tools.compat.CrawlDbConverter
+#elif [ "$COMMAND" = "mergedb" ] ; then
+# CLASS=org.apache.nutch.crawl.CrawlDbMerger
+#elif [ "$COMMAND" = "readlinkdb" ] ; then
+# CLASS=org.apache.nutch.crawl.LinkDbReader
+#elif [ "$COMMAND" = "readseg" ] ; then
+# CLASS=org.apache.nutch.segment.SegmentReader
+#elif [ "$COMMAND" = "segread" ] ; then
+# echo "[DEPRECATED] Command 'segread' is deprecated, use 'readseg' instead."
+# CLASS=org.apache.nutch.segment.SegmentReader
+#elif [ "$COMMAND" = "mergesegs" ] ; then
+# CLASS=org.apache.nutch.segment.SegmentMerger
+elif [ "$COMMAND" = "updatetable" ] ; then
+ CLASS=org.apache.nutch.crawl.TableUpdater
+#elif [ "$COMMAND" = "invertlinks" ] ; then
+# CLASS=org.apache.nutch.crawl.LinkDb
+#elif [ "$COMMAND" = "mergelinkdb" ] ; then
+# CLASS=org.apache.nutch.crawl.LinkDbMerger
elif [ "$COMMAND" = "index" ] ; then
CLASS=org.apache.nutch.indexer.Indexer
elif [ "$COMMAND" = "solrindex" ] ; then
diff --git a/build.xml b/build.xml
index 3ea76dfc1..69909f559 100644
--- a/build.xml
+++ b/build.xml
@@ -99,6 +99,7 @@
encoding="${build.encoding}"
srcdir="${src.dir}"
includes="org/apache/nutch/**/*.java"
+ excludes="org/apache/nutch/scoring/webgraph/**/*.java,org/apache/nutch/tools/compat/**/*.java,org/apache/nutch/tools/arc/**/*.java,org/apache/nutch/indexer/field/**/*.java"
destdir="${build.classes}"
debug="${javac.debug}"
optimize="${javac.optimize}"
@@ -181,6 +182,8 @@
<include name="lucene*.jar"/>
<include name="taglibs-*.jar"/>
<include name="hadoop-*.jar"/>
+ <include name="hbase-*.jar"/>
+ <include name="zookeeper-*.jar"/>
<include name="dom4j-*.jar"/>
<include name="xerces-*.jar"/>
<include name="tika-*.jar"/>
@@ -215,7 +218,8 @@
<javac
encoding="${build.encoding}"
srcdir="${test.src.dir}"
- includes="org/apache/nutch/**/*.java"
+ includes="org/apache/nutch*/**/*.java"
+ excludes="org/apache/nutch/scoring/webgraph/**/*.java,org/apache/nutch/tools/compat/**/*.java,org/apache/nutch/tools/arc/**/*.java"
destdir="${test.build.classes}"
debug="${javac.debug}"
optimize="${javac.optimize}"
diff --git a/conf/hbase-site.xml.template b/conf/hbase-site.xml.template
new file mode 100644
index 000000000..c39db3e56
--- /dev/null
+++ b/conf/hbase-site.xml.template
@@ -0,0 +1,25 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
+<!--
+/**
+ * Copyright 2009 The Apache Software Foundation
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+-->
+<configuration>
+</configuration>
diff --git a/conf/log4j.properties b/conf/log4j.properties
index bdc804280..f0254bcc9 100644
--- a/conf/log4j.properties
+++ b/conf/log4j.properties
@@ -28,6 +28,7 @@ log4j.logger.org.apache.nutch.indexer.IndexMerger=INFO,cmdstdout
log4j.logger.org.apache.nutch=INFO
log4j.logger.org.apache.hadoop=WARN
+log4j.logger.org.apache.zookeeper=WARN
#
# Daily Rolling File Appender
diff --git a/conf/nutch-default.xml b/conf/nutch-default.xml
index c24f89817..686b11547 100644
--- a/conf/nutch-default.xml
+++ b/conf/nutch-default.xml
@@ -886,8 +886,8 @@
<property>
<name>plugin.includes</name>
- <value>protocol-http|urlfilter-regex|parse-(text|html|js)|index-(basic|anchor)|query-(basic|site|url)|response-(json|xml)|summary-basic|scoring-opic|urlnormalizer-(pass|regex|basic)</value>
- <description>Regular expression naming plugin directory names to
+ <value>protocol-http|urlfilter-regex|parse-(html|js)|index-basic|urlnormalizer-(pass|regex|basic)|scoring-opic|query-(basic|site|url)|summary-basic</value>
+ <description>Regular expression naming plugin directory names to
include. Any plugin not matching this expression is excluded.
In any case you need at least include the nutch-extensionpoints plugin. By
default Nutch includes crawling just HTML and plain text via HTTP,
diff --git a/lib/hadoop-0.19.1-core.jar b/lib/hadoop-0.19.1-core.jar
deleted file mode 100644
index efc47823d..000000000
Binary files a/lib/hadoop-0.19.1-core.jar and /dev/null differ
diff --git a/lib/hadoop-0.20.0-core.jar b/lib/hadoop-0.20.0-core.jar
new file mode 100644
index 000000000..c99ce6d44
Binary files /dev/null and b/lib/hadoop-0.20.0-core.jar differ
diff --git a/lib/hbase-0.20.0-r804408.jar b/lib/hbase-0.20.0-r804408.jar
new file mode 100644
index 000000000..45cf8d32f
Binary files /dev/null and b/lib/hbase-0.20.0-r804408.jar differ
diff --git a/lib/zookeeper-r785019-hbase-1329.jar b/lib/zookeeper-r785019-hbase-1329.jar
new file mode 100644
index 000000000..26923f2c2
Binary files /dev/null and b/lib/zookeeper-r785019-hbase-1329.jar differ
diff --git a/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java b/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java
index 82a033211..67ede76ca 100644
--- a/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java
+++ b/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java
@@ -19,12 +19,14 @@ package org.apache.nutch.analysis;
// JDK imports
import java.io.Reader;
import java.io.IOException;
+import java.util.Collection;
// Lucene imports
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Token;
+import org.apache.nutch.util.hbase.HbaseColumn;
import org.apache.hadoop.conf.Configuration;
/**
diff --git a/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java b/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
index 122df7fa8..900154d8c 100755
--- a/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
@@ -17,12 +17,17 @@
package org.apache.nutch.crawl;
+import java.util.HashSet;
+import java.util.Set;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.crawl.FetchSchedule;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* This class provides common methods for implementations of
@@ -30,12 +35,22 @@ import org.apache.nutch.crawl.CrawlDatum;
*
* @author Andrzej Bialecki
*/
-public abstract class AbstractFetchSchedule extends Configured implements FetchSchedule {
+public abstract class AbstractFetchSchedule
+extends Configured
+implements FetchSchedule {
private static final Log LOG = LogFactory.getLog(AbstractFetchSchedule.class);
protected int defaultInterval;
protected int maxInterval;
+ private static final Set<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.FETCH_TIME));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.RETRIES));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.FETCH_INTERVAL));
+ }
+
public AbstractFetchSchedule() {
super(null);
}
@@ -49,10 +64,14 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
if (conf == null) return;
int oldDefaultInterval = conf.getInt("db.default.fetch.interval", 0);
defaultInterval = conf.getInt("db.fetch.interval.default", 0);
- if (oldDefaultInterval > 0 && defaultInterval == 0) defaultInterval = oldDefaultInterval * SECONDS_PER_DAY;
+ if (oldDefaultInterval > 0 && defaultInterval == 0) {
+ defaultInterval = oldDefaultInterval * FetchSchedule.SECONDS_PER_DAY;
+ }
int oldMaxInterval = conf.getInt("db.max.fetch.interval", 0);
maxInterval = conf.getInt("db.fetch.interval.max", 0 );
- if (oldMaxInterval > 0 && maxInterval == 0) maxInterval = oldMaxInterval * FetchSchedule.SECONDS_PER_DAY;
+ if (oldMaxInterval > 0 && maxInterval == 0) {
+ maxInterval = oldMaxInterval * FetchSchedule.SECONDS_PER_DAY;
+ }
LOG.info("defaultInterval=" + defaultInterval);
LOG.info("maxInterval=" + maxInterval);
}
@@ -64,13 +83,12 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
* default <code>fetchInterval</code>.
*
* @param url URL of the page.
- * @param datum datum instance to be initialized (modified in place).
+ * @param row url's row
*/
- public CrawlDatum initializeSchedule(Text url, CrawlDatum datum) {
- datum.setFetchTime(System.currentTimeMillis());
- datum.setFetchInterval(defaultInterval);
- datum.setRetriesSinceFetch(0);
- return datum;
+ public void initializeSchedule(String url, WebTableRow row) {
+ row.setFetchTime(System.currentTimeMillis());
+ row.setFetchInterval(defaultInterval);
+ row.setRetriesSinceFetch(0);
}
/**
@@ -79,11 +97,10 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
* retry counter - extending classes should call super.setFetchSchedule() to
* preserve this behavior.
*/
- public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
+ public void setFetchSchedule(String url, WebTableRow row,
long prevFetchTime, long prevModifiedTime,
long fetchTime, long modifiedTime, int state) {
- datum.setRetriesSinceFetch(0);
- return datum;
+ row.setRetriesSinceFetch(0);
}
/**
@@ -92,20 +109,20 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
* and if it exceeds the <code>maxInterval</code> it calls
* {@link #forceRefetch(Text, CrawlDatum, boolean)}.
* @param url URL of the page
- * @param datum datum instance to be adjusted
+ * @param row url's row
* @return adjusted page information, including all original information.
* NOTE: this may be a different instance than {@param datum}, but
* implementations should make sure that it contains at least all
* information from {@param datum}.
*/
- public CrawlDatum setPageGoneSchedule(Text url, CrawlDatum datum,
+ public void setPageGoneSchedule(String url, WebTableRow row,
long prevFetchTime, long prevModifiedTime, long fetchTime) {
// no page is truly GONE ... just increase the interval by 50%
// and try much later.
- datum.setFetchInterval(datum.getFetchInterval() * 1.5f);
- datum.setFetchTime(fetchTime + (long)datum.getFetchInterval() * 1000);
- if (maxInterval < datum.getFetchInterval()) forceRefetch(url, datum, false);
- return datum;
+ int newFetchInterval = (int) (row.getFetchInterval() * 1.5f);
+ row.setFetchInterval(newFetchInterval);
+ row.setFetchTime(fetchTime + newFetchInterval * 1000L);
+ if (maxInterval < newFetchInterval) forceRefetch(url, row, false);
}
/**
@@ -114,28 +131,24 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
* sets the next fetch time 1 day in the future and increases
* the retry counter.
* @param url URL of the page
- * @param datum page information
+ * @param row url's row
* @param prevFetchTime previous fetch time
* @param prevModifiedTime previous modified time
* @param fetchTime current fetch time
- * @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than {@param datum}, but
- * implementations should make sure that it contains at least all
- * information from {@param datum}.
*/
- public CrawlDatum setPageRetrySchedule(Text url, CrawlDatum datum,
+ public void setPageRetrySchedule(String url, WebTableRow row,
long prevFetchTime, long prevModifiedTime, long fetchTime) {
- datum.setFetchTime(fetchTime + (long)SECONDS_PER_DAY);
- datum.setRetriesSinceFetch(datum.getRetriesSinceFetch() + 1);
- return datum;
+ row.setFetchTime(fetchTime + (long)FetchSchedule.SECONDS_PER_DAY);
+ int oldRetries = row.getRetriesSinceFetch();
+ row.setRetriesSinceFetch(oldRetries + 1);
}
/**
* This method return the last fetch time of the CrawlDatum
* @return the date as a long.
*/
- public long calculateLastFetchTime(CrawlDatum datum) {
- return datum.getFetchTime() - (long)datum.getFetchInterval() * 1000;
+ public long calculateLastFetchTime(WebTableRow row) {
+ return row.getFetchTime() - row.getFetchInterval() * 1000L;
}
/**
@@ -148,21 +161,22 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
* check that fetchTime is not too remote (more than <code>maxInterval</code),
* in which case it lowers the interval and returns true.
* @param url URL of the page
- * @param datum datum instance
+ * @param row url's row
* @param curTime reference time (usually set to the time when the
* fetchlist generation process was started).
* @return true, if the page should be considered for inclusion in the current
* fetchlist, otherwise false.
*/
- public boolean shouldFetch(Text url, CrawlDatum datum, long curTime) {
+ public boolean shouldFetch(String url, WebTableRow row, long curTime) {
// pages are never truly GONE - we have to check them from time to time.
// pages with too long fetchInterval are adjusted so that they fit within
// maximum fetchInterval (segment retention period).
- if (datum.getFetchTime() - curTime > (long) maxInterval * 1000) {
- datum.setFetchInterval(maxInterval * 0.9f);
- datum.setFetchTime(curTime);
+ long fetchTime = row.getFetchTime();
+ if (fetchTime - curTime > maxInterval * 1000L) {
+ row.setFetchInterval(Math.round(maxInterval * 0.9f));
+ row.setFetchTime(curTime);
}
- if (datum.getFetchTime() > curTime) {
+ if (fetchTime > curTime) {
return false; // not time yet
}
return true;
@@ -172,21 +186,25 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
* This method resets fetchTime, fetchInterval, modifiedTime,
* retriesSinceFetch and page signature, so that it forces refetching.
* @param url URL of the page
- * @param datum datum instance
+ * @param row url's row
* @param asap if true, force refetch as soon as possible - this sets
* the fetchTime to now. If false, force refetch whenever the next fetch
* time is set.
*/
- public CrawlDatum forceRefetch(Text url, CrawlDatum datum, boolean asap) {
+ public void forceRefetch(String url, WebTableRow row, boolean asap) {
// reduce fetchInterval so that it fits within the max value
- if (datum.getFetchInterval() > maxInterval)
- datum.setFetchInterval(maxInterval * 0.9f);
- datum.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
- datum.setRetriesSinceFetch(0);
- datum.setSignature(null);
- datum.setModifiedTime(0L);
- if (asap) datum.setFetchTime(System.currentTimeMillis());
- return datum;
+ if (row.getFetchInterval() > maxInterval)
+ row.setFetchInterval(Math.round(maxInterval * 0.9f));
+ row.setStatus(CrawlDatumHbase.STATUS_UNFETCHED);
+ row.setRetriesSinceFetch(0);
+ // TODO: row.setSignature(null) ??
+ row.setModifiedTime(0L);
+ if (asap) row.setFetchTime(System.currentTimeMillis());
+ }
+
+
+ public Set<HbaseColumn> getColumns() {
+ return COLUMNS;
}
}
diff --git a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
index ccd956c5c..a8105c2ec 100755
--- a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
@@ -18,9 +18,8 @@
package org.apache.nutch.crawl;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.crawl.FetchSchedule;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* This class implements an adaptive re-fetch algorithm. This works as follows:
@@ -63,7 +62,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
private boolean SYNC_DELTA;
- private double SYNC_DELTA_RATE;
+ private float SYNC_DELTA_RATE;
public void setConf(Configuration conf) {
super.setConf(conf);
@@ -71,20 +70,22 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
INC_RATE = conf.getFloat("db.fetch.schedule.adaptive.inc_rate", 0.2f);
DEC_RATE = conf.getFloat("db.fetch.schedule.adaptive.dec_rate", 0.2f);
MIN_INTERVAL = conf.getInt("db.fetch.schedule.adaptive.min_interval", 60);
- MAX_INTERVAL = conf.getInt("db.fetch.schedule.adaptive.max_interval", SECONDS_PER_DAY * 365 ); // 1 year
+ MAX_INTERVAL =
+ conf.getInt("db.fetch.schedule.adaptive.max_interval",
+ FetchSchedule.SECONDS_PER_DAY * 365 ); // 1 year
SYNC_DELTA = conf.getBoolean("db.fetch.schedule.adaptive.sync_delta", true);
SYNC_DELTA_RATE = conf.getFloat("db.fetch.schedule.adaptive.sync_delta_rate", 0.2f);
}
@Override
- public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
+ public void setFetchSchedule(String url, WebTableRow row,
long prevFetchTime, long prevModifiedTime,
long fetchTime, long modifiedTime, int state) {
- super.setFetchSchedule(url, datum, prevFetchTime, prevModifiedTime,
+ super.setFetchSchedule(url, row, prevFetchTime, prevModifiedTime,
fetchTime, modifiedTime, state);
long refTime = fetchTime;
if (modifiedTime <= 0) modifiedTime = fetchTime;
- float interval = datum.getFetchInterval();
+ int interval = row.getFetchInterval();
switch (state) {
case FetchSchedule.STATUS_MODIFIED:
interval *= (1.0f - DEC_RATE);
@@ -95,69 +96,19 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
case FetchSchedule.STATUS_UNKNOWN:
break;
}
+ row.setFetchInterval(interval);
if (SYNC_DELTA) {
// try to synchronize with the time of change
- long delta = (fetchTime - modifiedTime) / 1000L;
+ // TODO: different from normal class (is delta in seconds)?
+ int delta = (int) ((fetchTime - modifiedTime) / 1000L) ;
if (delta > interval) interval = delta;
- refTime = fetchTime - Math.round(delta * SYNC_DELTA_RATE * 1000);
+ refTime = fetchTime - Math.round(delta * SYNC_DELTA_RATE);
}
- if (interval < MIN_INTERVAL) {
- interval = MIN_INTERVAL;
- } else if (interval > MAX_INTERVAL) {
- interval = MAX_INTERVAL;
- }
- datum.setFetchInterval(interval);
- datum.setFetchTime(refTime + Math.round(interval * 1000.0));
- datum.setModifiedTime(modifiedTime);
- return datum;
+ if (interval < MIN_INTERVAL) interval = MIN_INTERVAL;
+ if (interval > MAX_INTERVAL) interval = MAX_INTERVAL;
+ row.setFetchTime(refTime + interval * 1000L);
+ row.setModifiedTime(modifiedTime);
}
- public static void main(String[] args) throws Exception {
- FetchSchedule fs = new AdaptiveFetchSchedule();
- fs.setConf(NutchConfiguration.create());
- // we start the time at 0, for simplicity
- long curTime = 0;
- long delta = 1000L * 3600L * 24L; // 2 hours
- // we trigger the update of the page every 30 days
- long update = 1000L * 3600L * 24L * 30L; // 30 days
- boolean changed = true;
- long lastModified = 0;
- int miss = 0;
- int totalMiss = 0;
- int maxMiss = 0;
- int fetchCnt = 0;
- int changeCnt = 0;
- // initial fetchInterval is 10 days
- CrawlDatum p = new CrawlDatum(1, 3600 * 24 * 30, 1.0f);
- p.setFetchTime(0);
- System.out.println(p);
- // let's move the timeline a couple of deltas
- for (int i = 0; i < 10000; i++) {
- if (lastModified + update < curTime) {
- //System.out.println("i=" + i + ", lastModified=" + lastModified + ", update=" + update + ", curTime=" + curTime);
- changed = true;
- changeCnt++;
- lastModified = curTime;
- }
- System.out.println(i + ". " + changed + "\twill fetch at " + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY ) + " days" + "\t missed " + miss);
- if (p.getFetchTime() <= curTime) {
- fetchCnt++;
- fs.setFetchSchedule(new Text("http://www.example.com"), p,
- p.getFetchTime(), p.getModifiedTime(), curTime, lastModified,
- changed ? FetchSchedule.STATUS_MODIFIED : FetchSchedule.STATUS_NOTMODIFIED);
- System.out.println("\tfetched & adjusted: " + "\twill fetch at " + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY ) + " days");
- if (!changed) miss++;
- if (miss > maxMiss) maxMiss = miss;
- changed = false;
- totalMiss += miss;
- miss = 0;
- }
- if (changed) miss++;
- curTime += delta;
- }
- System.out.println("Total missed: " + totalMiss + ", max miss: " + maxMiss);
- System.out.println("Page changed " + changeCnt + " times, fetched " + fetchCnt + " times.");
- }
+
}
diff --git a/src/java/org/apache/nutch/crawl/Crawl.java b/src/java/org/apache/nutch/crawl/Crawl.java
deleted file mode 100644
index 523b7f29a..000000000
--- a/src/java/org/apache/nutch/crawl/Crawl.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.util.*;
-import java.text.*;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.nutch.parse.ParseSegment;
-import org.apache.nutch.indexer.DeleteDuplicates;
-import org.apache.nutch.indexer.IndexMerger;
-import org.apache.nutch.indexer.Indexer;
-import org.apache.nutch.util.HadoopFSUtil;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-import org.apache.nutch.fetcher.Fetcher;
-
-public class Crawl {
- public static final Log LOG = LogFactory.getLog(Crawl.class);
-
- private static String getDate() {
- return new SimpleDateFormat("yyyyMMddHHmmss").format
- (new Date(System.currentTimeMillis()));
- }
-
-
- /* Perform complete crawling and indexing given a set of root urls. */
- public static void main(String args[]) throws Exception {
- if (args.length < 1) {
- System.out.println
- ("Usage: Crawl <urlDir> [-dir d] [-threads n] [-depth i] [-topN N]");
- return;
- }
-
- Configuration conf = NutchConfiguration.createCrawlConfiguration();
- JobConf job = new NutchJob(conf);
-
- Path rootUrlDir = null;
- Path dir = new Path("crawl-" + getDate());
- int threads = job.getInt("fetcher.threads.fetch", 10);
- int depth = 5;
- long topN = Long.MAX_VALUE;
- for (int i = 0; i < args.length; i++) {
- if ("-dir".equals(args[i])) {
- dir = new Path(args[i+1]);
- i++;
- } else if ("-threads".equals(args[i])) {
- threads = Integer.parseInt(args[i+1]);
- i++;
- } else if ("-depth".equals(args[i])) {
- depth = Integer.parseInt(args[i+1]);
- i++;
- } else if ("-topN".equals(args[i])) {
- topN = Integer.parseInt(args[i+1]);
- i++;
- } else if (args[i] != null) {
- rootUrlDir = new Path(args[i]);
- }
- }
-
- FileSystem fs = FileSystem.get(job);
-
- if (LOG.isInfoEnabled()) {
- LOG.info("crawl started in: " + dir);
- LOG.info("rootUrlDir = " + rootUrlDir);
- LOG.info("threads = " + threads);
- LOG.info("depth = " + depth);
- if (topN != Long.MAX_VALUE)
- LOG.info("topN = " + topN);
- }
-
- Path crawlDb = new Path(dir + "/crawldb");
- Path linkDb = new Path(dir + "/linkdb");
- Path segments = new Path(dir + "/segments");
- Path indexes = new Path(dir + "/indexes");
- Path index = new Path(dir + "/index");
-
- Path tmpDir = job.getLocalPath("crawl"+Path.SEPARATOR+getDate());
- Injector injector = new Injector(conf);
- Generator generator = new Generator(conf);
- Fetcher fetcher = new Fetcher(conf);
- ParseSegment parseSegment = new ParseSegment(conf);
- CrawlDb crawlDbTool = new CrawlDb(conf);
- LinkDb linkDbTool = new LinkDb(conf);
- Indexer indexer = new Indexer(conf);
- DeleteDuplicates dedup = new DeleteDuplicates(conf);
- IndexMerger merger = new IndexMerger(conf);
-
- // initialize crawlDb
- injector.inject(crawlDb, rootUrlDir);
- int i;
- for (i = 0; i < depth; i++) { // generate new segment
- Path segment = generator.generate(crawlDb, segments, -1, topN, System
- .currentTimeMillis());
- if (segment == null) {
- LOG.info("Stopping at depth=" + i + " - no more URLs to fetch.");
- break;
- }
- fetcher.fetch(segment, threads, org.apache.nutch.fetcher.Fetcher.isParsing(conf)); // fetch it
- if (!Fetcher.isParsing(job)) {
- parseSegment.parse(segment); // parse it, if needed
- }
- crawlDbTool.update(crawlDb, new Path[]{segment}, true, true); // update crawldb
- }
- if (i > 0) {
- linkDbTool.invert(linkDb, segments, true, true, false); // invert links
-
- if(indexes != null) {
- // Delete old indexes
- if (fs.exists(indexes)) {
- LOG.info("Deleting old indexes: " + indexes);
- fs.delete(indexes, true);
- }
-
- // Delete old index
- if (fs.exists(index)) {
- LOG.info("Deleting old merged index: " + index);
- fs.delete(index, true);
- }
- }
-
- // index, dedup & merge
- FileStatus[] fstats = fs.listStatus(segments, HadoopFSUtil.getPassDirectoriesFilter(fs));
- indexer.index(indexes, crawlDb, linkDb, Arrays.asList(HadoopFSUtil.getPaths(fstats)));
- if(indexes != null) {
- dedup.dedup(new Path[] { indexes });
- fstats = fs.listStatus(indexes, HadoopFSUtil.getPassDirectoriesFilter(fs));
- merger.merge(HadoopFSUtil.getPaths(fstats), index, tmpDir);
- }
- } else {
- LOG.warn("No URLs to fetch - check your seed list and URL filters.");
- }
- if (LOG.isInfoEnabled()) { LOG.info("crawl finished: " + dir); }
- }
-}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDatum.java b/src/java/org/apache/nutch/crawl/CrawlDatum.java
index b3812736e..64413df5a 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDatum.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDatum.java
@@ -340,7 +340,7 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
return (that.fetchInterval - this.fetchInterval) > 0 ? 1 : -1;
if (that.modifiedTime != this.modifiedTime)
return (that.modifiedTime - this.modifiedTime) > 0 ? 1 : -1;
- return SignatureComparator._compare(this, that);
+ return SignatureComparator.compare(this.signature, that.signature);
}
/** A Comparator optimized for CrawlDatum. */
@@ -427,7 +427,7 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
(this.modifiedTime == other.modifiedTime) &&
(this.retries == other.retries) &&
(this.fetchInterval == other.fetchInterval) &&
- (SignatureComparator._compare(this.signature, other.signature) == 0) &&
+ (SignatureComparator.compare(this.signature, other.signature) == 0) &&
(this.score == other.score);
if (!res) return res;
return metadataEquals(other.metaData);
diff --git a/src/java/org/apache/nutch/crawl/CrawlDatumHbase.java b/src/java/org/apache/nutch/crawl/CrawlDatumHbase.java
new file mode 100644
index 000000000..750a9ae34
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/CrawlDatumHbase.java
@@ -0,0 +1,38 @@
+package org.apache.nutch.crawl;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class CrawlDatumHbase {
+ /** Page was not fetched yet. */
+ public static final byte STATUS_UNFETCHED = 0x01;
+ /** Page was successfully fetched. */
+ public static final byte STATUS_FETCHED = 0x02;
+ /** Page no longer exists. */
+ public static final byte STATUS_GONE = 0x03;
+ /** Page temporarily redirects to other page. */
+ public static final byte STATUS_REDIR_TEMP = 0x04;
+ /** Page permanently redirects to other page. */
+ public static final byte STATUS_REDIR_PERM = 0x05;
+ /** Fetching unsuccessful, needs to be retried (transient errors). */
+ public static final byte STATUS_RETRY = 0x22;
+ /** Fetching successful - page is not modified. */
+ public static final byte STATUS_NOTMODIFIED = 0x26;
+
+ private static final Map<Byte, String> NAMES = new HashMap<Byte, String>();
+
+ static {
+ NAMES.put(STATUS_UNFETCHED, "status_unfetched");
+ NAMES.put(STATUS_FETCHED, "status_fetched");
+ NAMES.put(STATUS_GONE, "status_gone");
+ NAMES.put(STATUS_REDIR_TEMP, "status_redir_temp");
+ NAMES.put(STATUS_REDIR_PERM, "status_redir_perm");
+ NAMES.put(STATUS_RETRY, "status_retry");
+ NAMES.put(STATUS_NOTMODIFIED, "status_notmodified");
+ }
+
+ public static String getName(byte status) {
+ return NAMES.get(status);
+ }
+
+}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.java
index 07cac53d2..fe430f7b8 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDb.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java
@@ -17,180 +17,10 @@
package org.apache.nutch.crawl;
-import java.io.*;
-import java.util.*;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-
-import org.apache.nutch.util.HadoopFSUtil;
-import org.apache.nutch.util.LockUtil;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-/**
- * This class takes the output of the fetcher and updates the
- * crawldb accordingly.
- */
-public class CrawlDb extends Configured implements Tool {
- public static final Log LOG = LogFactory.getLog(CrawlDb.class);
-
+public interface CrawlDb {
public static final String CRAWLDB_ADDITIONS_ALLOWED = "db.update.additions.allowed";
public static final String CURRENT_NAME = "current";
public static final String LOCK_NAME = ".locked";
-
- public CrawlDb() {}
-
- public CrawlDb(Configuration conf) {
- setConf(conf);
- }
-
- public void update(Path crawlDb, Path[] segments, boolean normalize, boolean filter) throws IOException {
- boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED, true);
- update(crawlDb, segments, normalize, filter, additionsAllowed, false);
- }
-
- public void update(Path crawlDb, Path[] segments, boolean normalize, boolean filter, boolean additionsAllowed, boolean force) throws IOException {
- FileSystem fs = FileSystem.get(getConf());
- Path lock = new Path(crawlDb, LOCK_NAME);
- LockUtil.createLockFile(fs, lock, force);
- if (LOG.isInfoEnabled()) {
- LOG.info("CrawlDb update: starting");
- LOG.info("CrawlDb update: db: " + crawlDb);
- LOG.info("CrawlDb update: segments: " + Arrays.asList(segments));
- LOG.info("CrawlDb update: additions allowed: " + additionsAllowed);
- LOG.info("CrawlDb update: URL normalizing: " + normalize);
- LOG.info("CrawlDb update: URL filtering: " + filter);
- }
-
- JobConf job = CrawlDb.createJob(getConf(), crawlDb);
- job.setBoolean(CRAWLDB_ADDITIONS_ALLOWED, additionsAllowed);
- job.setBoolean(CrawlDbFilter.URL_FILTERING, filter);
- job.setBoolean(CrawlDbFilter.URL_NORMALIZING, normalize);
- for (int i = 0; i < segments.length; i++) {
- Path fetch = new Path(segments[i], CrawlDatum.FETCH_DIR_NAME);
- Path parse = new Path(segments[i], CrawlDatum.PARSE_DIR_NAME);
- if (fs.exists(fetch) && fs.exists(parse)) {
- FileInputFormat.addInputPath(job, fetch);
- FileInputFormat.addInputPath(job, parse);
- } else {
- LOG.info(" - skipping invalid segment " + segments[i]);
- }
- }
-
- if (LOG.isInfoEnabled()) {
- LOG.info("CrawlDb update: Merging segment data into db.");
- }
- try {
- JobClient.runJob(job);
- } catch (IOException e) {
- LockUtil.removeLockFile(fs, lock);
- Path outPath = FileOutputFormat.getOutputPath(job);
- if (fs.exists(outPath) ) fs.delete(outPath, true);
- throw e;
- }
-
- CrawlDb.install(job, crawlDb);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb update: done"); }
- }
-
- public static JobConf createJob(Configuration config, Path crawlDb)
- throws IOException {
- Path newCrawlDb =
- new Path(crawlDb,
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
-
- JobConf job = new NutchJob(config);
- job.setJobName("crawldb " + crawlDb);
-
-
- Path current = new Path(crawlDb, CURRENT_NAME);
- if (FileSystem.get(job).exists(current)) {
- FileInputFormat.addInputPath(job, current);
- }
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(CrawlDbFilter.class);
- job.setReducerClass(CrawlDbReducer.class);
-
- FileOutputFormat.setOutputPath(job, newCrawlDb);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
-
- return job;
- }
-
- public static void install(JobConf job, Path crawlDb) throws IOException {
- Path newCrawlDb = FileOutputFormat.getOutputPath(job);
- FileSystem fs = new JobClient(job).getFs();
- Path old = new Path(crawlDb, "old");
- Path current = new Path(crawlDb, CURRENT_NAME);
- if (fs.exists(current)) {
- if (fs.exists(old)) fs.delete(old, true);
- fs.rename(current, old);
- }
- fs.mkdirs(crawlDb);
- fs.rename(newCrawlDb, current);
- if (fs.exists(old)) fs.delete(old, true);
- Path lock = new Path(crawlDb, LOCK_NAME);
- LockUtil.removeLockFile(fs, lock);
- }
-
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new CrawlDb(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Usage: CrawlDb <crawldb> (-dir <segments> | <seg1> <seg2> ...) [-force] [-normalize] [-filter] [-noAdditions]");
- System.err.println("\tcrawldb\tCrawlDb to update");
- System.err.println("\t-dir segments\tparent directory containing all segments to update from");
- System.err.println("\tseg1 seg2 ...\tlist of segment names to update from");
- System.err.println("\t-force\tforce update even if CrawlDb appears to be locked (CAUTION advised)");
- System.err.println("\t-normalize\tuse URLNormalizer on urls in CrawlDb and segment (usually not needed)");
- System.err.println("\t-filter\tuse URLFilters on urls in CrawlDb and segment");
- System.err.println("\t-noAdditions\tonly update already existing URLs, don't add any newly discovered URLs");
- return -1;
- }
- boolean normalize = false;
- boolean filter = false;
- boolean force = false;
- final FileSystem fs = FileSystem.get(getConf());
- boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED, true);
- HashSet<Path> dirs = new HashSet<Path>();
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-normalize")) {
- normalize = true;
- } else if (args[i].equals("-filter")) {
- filter = true;
- } else if (args[i].equals("-force")) {
- force = true;
- } else if (args[i].equals("-noAdditions")) {
- additionsAllowed = false;
- } else if (args[i].equals("-dir")) {
- FileStatus[] paths = fs.listStatus(new Path(args[++i]), HadoopFSUtil.getPassDirectoriesFilter(fs));
- dirs.addAll(Arrays.asList(HadoopFSUtil.getPaths(paths)));
- } else {
- dirs.add(new Path(args[i]));
- }
- }
- try {
- update(new Path(args[0]), dirs.toArray(new Path[dirs.size()]), normalize, filter, additionsAllowed, force);
- return 0;
- } catch (Exception e) {
- LOG.fatal("CrawlDb update: " + StringUtils.stringifyException(e));
- return -1;
- }
- }
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
deleted file mode 100644
index a1db9e8f5..000000000
--- a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.io.IOException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.nutch.net.URLFilters;
-import org.apache.nutch.net.URLNormalizers;
-
-/**
- * This class provides a way to separate the URL normalization
- * and filtering steps from the rest of CrawlDb manipulation code.
- *
- * @author Andrzej Bialecki
- */
-public class CrawlDbFilter implements Mapper<Text, CrawlDatum, Text, CrawlDatum> {
- public static final String URL_FILTERING = "crawldb.url.filters";
-
- public static final String URL_NORMALIZING = "crawldb.url.normalizers";
-
- public static final String URL_NORMALIZING_SCOPE = "crawldb.url.normalizers.scope";
-
- private boolean urlFiltering;
-
- private boolean urlNormalizers;
-
- private URLFilters filters;
-
- private URLNormalizers normalizers;
-
- private String scope;
-
- public static final Log LOG = LogFactory.getLog(CrawlDbFilter.class);
-
- public void configure(JobConf job) {
- urlFiltering = job.getBoolean(URL_FILTERING, false);
- urlNormalizers = job.getBoolean(URL_NORMALIZING, false);
- if (urlFiltering) {
- filters = new URLFilters(job);
- }
- if (urlNormalizers) {
- scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_CRAWLDB);
- normalizers = new URLNormalizers(job, scope);
- }
- }
-
- public void close() {}
-
- private Text newKey = new Text();
-
- public void map(Text key, CrawlDatum value,
- OutputCollector<Text, CrawlDatum> output,
- Reporter reporter) throws IOException {
-
- String url = key.toString();
- if (urlNormalizers) {
- try {
- url = normalizers.normalize(url, scope); // normalize the url
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
- url = null;
- }
- }
- if (url != null && urlFiltering) {
- try {
- url = filters.filter(url); // filter the url
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
- url = null;
- }
- }
- if (url != null) { // if it passes
- newKey.set(url); // collect it
- output.collect(newKey, value);
- }
- }
-}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
deleted file mode 100644
index 35d4a8ff4..000000000
--- a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.io.IOException;
-import java.util.*;
-import java.util.Map.Entry;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-import org.apache.hadoop.conf.*;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-/**
- * This tool merges several CrawlDb-s into one, optionally filtering
- * URLs through the current URLFilters, to skip prohibited
- * pages.
- *
- * <p>It's possible to use this tool just for filtering - in that case
- * only one CrawlDb should be specified in arguments.</p>
- * <p>If more than one CrawlDb contains information about the same URL,
- * only the most recent version is retained, as determined by the
- * value of {@link org.apache.nutch.crawl.CrawlDatum#getFetchTime()}.
- * However, all metadata information from all versions is accumulated,
- * with newer values taking precedence over older values.
- *
- * @author Andrzej Bialecki
- */
-public class CrawlDbMerger extends Configured implements Tool {
- private static final Log LOG = LogFactory.getLog(CrawlDbMerger.class);
-
- public static class Merger extends MapReduceBase implements Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- private org.apache.hadoop.io.MapWritable meta;
- private CrawlDatum res = new CrawlDatum();
- private FetchSchedule schedule;
-
- public void close() throws IOException {}
-
- public void configure(JobConf conf) {
- schedule = FetchScheduleFactory.getFetchSchedule(conf);
- }
-
- public void reduce(Text key, Iterator<CrawlDatum> values, OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- long resTime = 0L;
- boolean resSet = false;
- meta = new org.apache.hadoop.io.MapWritable();
- while (values.hasNext()) {
- CrawlDatum val = values.next();
- if (!resSet) {
- res.set(val);
- resSet = true;
- resTime = schedule.calculateLastFetchTime(res);
- for (Entry<Writable, Writable> e : res.getMetaData().entrySet()) {
- meta.put(e.getKey(), e.getValue());
- }
- continue;
- }
- // compute last fetch time, and pick the latest
- long valTime = schedule.calculateLastFetchTime(val);
- if (valTime > resTime) {
- // collect all metadata, newer values override older values
- for (Entry<Writable, Writable> e : val.getMetaData().entrySet()) {
- meta.put(e.getKey(), e.getValue());
- }
- res.set(val);
- resTime = valTime ;
- } else {
- // insert older metadata before newer
- for (Entry<Writable, Writable> e : meta.entrySet()) {
- val.getMetaData().put(e.getKey(), e.getValue());
- }
- meta = val.getMetaData();
- }
- }
- res.setMetaData(meta);
- output.collect(key, res);
- }
- }
-
- public CrawlDbMerger() {
-
- }
-
- public CrawlDbMerger(Configuration conf) {
- setConf(conf);
- }
-
- public void merge(Path output, Path[] dbs, boolean normalize, boolean filter) throws Exception {
- JobConf job = createMergeJob(getConf(), output, normalize, filter);
- for (int i = 0; i < dbs.length; i++) {
- FileInputFormat.addInputPath(job, new Path(dbs[i], CrawlDb.CURRENT_NAME));
- }
- JobClient.runJob(job);
- FileSystem fs = FileSystem.get(getConf());
- fs.mkdirs(output);
- fs.rename(FileOutputFormat.getOutputPath(job), new Path(output, CrawlDb.CURRENT_NAME));
- }
-
- public static JobConf createMergeJob(Configuration conf, Path output, boolean normalize, boolean filter) {
- Path newCrawlDb = new Path("crawldb-merge-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
-
- JobConf job = new NutchJob(conf);
- job.setJobName("crawldb merge " + output);
-
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(CrawlDbFilter.class);
- job.setBoolean(CrawlDbFilter.URL_FILTERING, filter);
- job.setBoolean(CrawlDbFilter.URL_NORMALIZING, normalize);
- job.setReducerClass(Merger.class);
-
- FileOutputFormat.setOutputPath(job, newCrawlDb);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
-
- return job;
- }
-
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new CrawlDbMerger(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Usage: CrawlDbMerger <output_crawldb> <crawldb1> [<crawldb2> <crawldb3> ...] [-normalize] [-filter]");
- System.err.println("\toutput_crawldb\toutput CrawlDb");
- System.err.println("\tcrawldb1 ...\tinput CrawlDb-s (single input CrawlDb is ok)");
- System.err.println("\t-normalize\tuse URLNormalizer on urls in the crawldb(s) (usually not needed)");
- System.err.println("\t-filter\tuse URLFilters on urls in the crawldb(s)");
- return -1;
- }
- Path output = new Path(args[0]);
- ArrayList<Path> dbs = new ArrayList<Path>();
- boolean filter = false;
- boolean normalize = false;
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-filter")) {
- filter = true;
- continue;
- } else if (args[i].equals("-normalize")) {
- normalize = true;
- continue;
- }
- dbs.add(new Path(args[i]));
- }
- try {
- merge(output, dbs.toArray(new Path[dbs.size()]), normalize, filter);
- return 0;
- } catch (Exception e) {
- LOG.fatal("CrawlDb merge: " + StringUtils.stringifyException(e));
- return -1;
- }
- }
-}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
deleted file mode 100644
index 0ba44afc8..000000000
--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java
+++ /dev/null
@@ -1,527 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Random;
-import java.util.TreeMap;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.Closeable;
-import org.apache.hadoop.io.FloatWritable;
-import org.apache.hadoop.io.LongWritable;
-import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.SequenceFile;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.RecordWriter;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.TextOutputFormat;
-import org.apache.hadoop.mapred.lib.HashPartitioner;
-import org.apache.hadoop.mapred.lib.IdentityMapper;
-import org.apache.hadoop.mapred.lib.IdentityReducer;
-import org.apache.hadoop.util.Progressable;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-import org.apache.nutch.util.StringUtil;
-
-/**
- * Read utility for the CrawlDB.
- *
- * @author Andrzej Bialecki
- *
- */
-public class CrawlDbReader implements Closeable {
-
- public static final Log LOG = LogFactory.getLog(CrawlDbReader.class);
-
- public static final int STD_FORMAT = 0;
- public static final int CSV_FORMAT = 1;
-
- private MapFile.Reader[] readers = null;
-
- private void openReaders(String crawlDb, Configuration config) throws IOException {
- if (readers != null) return;
- FileSystem fs = FileSystem.get(config);
- readers = MapFileOutputFormat.getReaders(fs, new Path(crawlDb,
- CrawlDb.CURRENT_NAME), config);
- }
-
- private void closeReaders() {
- if (readers == null) return;
- for (int i = 0; i < readers.length; i++) {
- try {
- readers[i].close();
- } catch (Exception e) {
-
- }
- }
- }
-
- public static class CrawlDatumCsvOutputFormat extends FileOutputFormat<Text,CrawlDatum> {
- protected static class LineRecordWriter implements RecordWriter<Text,CrawlDatum> {
- private DataOutputStream out;
-
- public LineRecordWriter(DataOutputStream out) {
- this.out = out;
- try {
- out.writeBytes("Url;Status code;Status name;Fetch Time;Modified Time;Retries since fetch;Retry interval;Score;Signature;Metadata\n");
- } catch (IOException e) {}
- }
-
- public synchronized void write(Text key, CrawlDatum value) throws IOException {
- out.writeByte('"');
- out.writeBytes(key.toString());
- out.writeByte('"');
- out.writeByte(';');
- out.writeBytes(Integer.toString(value.getStatus()));
- out.writeByte(';');
- out.writeByte('"');
- out.writeBytes(CrawlDatum.getStatusName(value.getStatus()));
- out.writeByte('"');
- out.writeByte(';');
- out.writeBytes(new Date(value.getFetchTime()).toString());
- out.writeByte(';');
- out.writeBytes(new Date(value.getModifiedTime()).toString());
- out.writeByte(';');
- out.writeBytes(Integer.toString(value.getRetriesSinceFetch()));
- out.writeByte(';');
- out.writeBytes(Float.toString(value.getFetchInterval()));
- out.writeByte(';');
- out.writeBytes(Float.toString((value.getFetchInterval() / FetchSchedule.SECONDS_PER_DAY)));
- out.writeByte(';');
- out.writeBytes(Float.toString(value.getScore()));
- out.writeByte(';');
- out.writeByte('"');
- out.writeBytes(value.getSignature() != null ? StringUtil.toHexString(value.getSignature()): "null");
- out.writeByte('"');
- out.writeByte('\n');
- }
-
- public synchronized void close(Reporter reporter) throws IOException {
- out.close();
- }
- }
-
- public RecordWriter<Text,CrawlDatum> getRecordWriter(FileSystem fs, JobConf job, String name,
- Progressable progress) throws IOException {
- Path dir = FileOutputFormat.getOutputPath(job);
- DataOutputStream fileOut = fs.create(new Path(dir, name), progress);
- return new LineRecordWriter(fileOut);
- }
- }
-
- public static class CrawlDbStatMapper implements Mapper<Text, CrawlDatum, Text, LongWritable> {
- LongWritable COUNT_1 = new LongWritable(1);
- private boolean sort = false;
- public void configure(JobConf job) {
- sort = job.getBoolean("db.reader.stats.sort", false );
- }
- public void close() {}
- public void map(Text key, CrawlDatum value, OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
- output.collect(new Text("T"), COUNT_1);
- output.collect(new Text("status " + value.getStatus()), COUNT_1);
- output.collect(new Text("retry " + value.getRetriesSinceFetch()), COUNT_1);
- output.collect(new Text("s"), new LongWritable((long) (value.getScore() * 1000.0)));
- if(sort){
- URL u = new URL(key.toString());
- String host = u.getHost();
- output.collect(new Text("status " + value.getStatus() + " " + host), COUNT_1);
- }
- }
- }
-
- public static class CrawlDbStatCombiner implements Reducer<Text, LongWritable, Text, LongWritable> {
- LongWritable val = new LongWritable();
-
- public CrawlDbStatCombiner() { }
- public void configure(JobConf job) { }
- public void close() {}
- public void reduce(Text key, Iterator<LongWritable> values, OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
- val.set(0L);
- String k = ((Text)key).toString();
- if (!k.equals("s")) {
- while (values.hasNext()) {
- LongWritable cnt = (LongWritable)values.next();
- val.set(val.get() + cnt.get());
- }
- output.collect(key, val);
- } else {
- long total = 0;
- long min = Long.MAX_VALUE;
- long max = Long.MIN_VALUE;
- while (values.hasNext()) {
- LongWritable cnt = (LongWritable)values.next();
- if (cnt.get() < min) min = cnt.get();
- if (cnt.get() > max) max = cnt.get();
- total += cnt.get();
- }
- output.collect(new Text("scn"), new LongWritable(min));
- output.collect(new Text("scx"), new LongWritable(max));
- output.collect(new Text("sct"), new LongWritable(total));
- }
- }
- }
-
- public static class CrawlDbStatReducer implements Reducer<Text, LongWritable, Text, LongWritable> {
- public void configure(JobConf job) {}
- public void close() {}
- public void reduce(Text key, Iterator<LongWritable> values, OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
-
- String k = ((Text) key).toString();
- if (k.equals("T")) {
- // sum all values for this key
- long sum = 0;
- while (values.hasNext()) {
- sum += ((LongWritable) values.next()).get();
- }
- // output sum
- output.collect(key, new LongWritable(sum));
- } else if (k.startsWith("status") || k.startsWith("retry")) {
- LongWritable cnt = new LongWritable();
- while (values.hasNext()) {
- LongWritable val = (LongWritable)values.next();
- cnt.set(cnt.get() + val.get());
- }
- output.collect(key, cnt);
- } else if (k.equals("scx")) {
- LongWritable cnt = new LongWritable(Long.MIN_VALUE);
- while (values.hasNext()) {
- LongWritable val = (LongWritable)values.next();
- if (cnt.get() < val.get()) cnt.set(val.get());
- }
- output.collect(key, cnt);
- } else if (k.equals("scn")) {
- LongWritable cnt = new LongWritable(Long.MAX_VALUE);
- while (values.hasNext()) {
- LongWritable val = (LongWritable)values.next();
- if (cnt.get() > val.get()) cnt.set(val.get());
- }
- output.collect(key, cnt);
- } else if (k.equals("sct")) {
- LongWritable cnt = new LongWritable();
- while (values.hasNext()) {
- LongWritable val = (LongWritable)values.next();
- cnt.set(cnt.get() + val.get());
- }
- output.collect(key, cnt);
- }
- }
- }
-
- public static class CrawlDbTopNMapper implements Mapper<Text, CrawlDatum, FloatWritable, Text> {
- private static final FloatWritable fw = new FloatWritable();
- private float min = 0.0f;
-
- public void configure(JobConf job) {
- long lmin = job.getLong("db.reader.topn.min", 0);
- if (lmin != 0) {
- min = (float)lmin / 1000000.0f;
- }
- }
- public void close() {}
- public void map(Text key, CrawlDatum value, OutputCollector<FloatWritable, Text> output, Reporter reporter)
- throws IOException {
- if (value.getScore() < min) return; // don't collect low-scoring records
- fw.set(-value.getScore()); // reverse sorting order
- output.collect(fw, key); // invert mapping: score -> url
- }
- }
-
- public static class CrawlDbTopNReducer implements Reducer<FloatWritable, Text, FloatWritable, Text> {
- private long topN;
- private long count = 0L;
-
- public void reduce(FloatWritable key, Iterator<Text> values, OutputCollector<FloatWritable, Text> output, Reporter reporter) throws IOException {
- while (values.hasNext() && count < topN) {
- key.set(-key.get());
- output.collect(key, values.next());
- count++;
- }
- }
-
- public void configure(JobConf job) {
- topN = job.getLong("db.reader.topn", 100) / job.getNumReduceTasks();
- }
-
- public void close() {}
- }
-
- public void close() {
- closeReaders();
- }
-
- public void processStatJob(String crawlDb, Configuration config, boolean sort) throws IOException {
-
- if (LOG.isInfoEnabled()) {
- LOG.info("CrawlDb statistics start: " + crawlDb);
- }
-
- Path tmpFolder = new Path(crawlDb, "stat_tmp" + System.currentTimeMillis());
-
- JobConf job = new NutchJob(config);
- job.setJobName("stats " + crawlDb);
- job.setBoolean("db.reader.stats.sort", sort);
-
- FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(CrawlDbStatMapper.class);
- job.setCombinerClass(CrawlDbStatCombiner.class);
- job.setReducerClass(CrawlDbStatReducer.class);
-
- FileOutputFormat.setOutputPath(job, tmpFolder);
- job.setOutputFormat(SequenceFileOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(LongWritable.class);
-
- JobClient.runJob(job);
-
- // reading the result
- FileSystem fileSystem = FileSystem.get(config);
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config, tmpFolder);
-
- Text key = new Text();
- LongWritable value = new LongWritable();
-
- TreeMap<String, LongWritable> stats = new TreeMap<String, LongWritable>();
- for (int i = 0; i < readers.length; i++) {
- SequenceFile.Reader reader = readers[i];
- while (reader.next(key, value)) {
- String k = key.toString();
- LongWritable val = stats.get(k);
- if (val == null) {
- val = new LongWritable();
- if (k.equals("scx")) val.set(Long.MIN_VALUE);
- if (k.equals("scn")) val.set(Long.MAX_VALUE);
- stats.put(k, val);
- }
- if (k.equals("scx")) {
- if (val.get() < value.get()) val.set(value.get());
- } else if (k.equals("scn")) {
- if (val.get() > value.get()) val.set(value.get());
- } else {
- val.set(val.get() + value.get());
- }
- }
- reader.close();
- }
-
- if (LOG.isInfoEnabled()) {
- LOG.info("Statistics for CrawlDb: " + crawlDb);
- LongWritable totalCnt = stats.get("T");
- stats.remove("T");
- LOG.info("TOTAL urls:\t" + totalCnt.get());
- for (Map.Entry<String, LongWritable> entry : stats.entrySet()) {
- String k = entry.getKey();
- LongWritable val = entry.getValue();
- if (k.equals("scn")) {
- LOG.info("min score:\t" + (float) (val.get() / 1000.0f));
- } else if (k.equals("scx")) {
- LOG.info("max score:\t" + (float) (val.get() / 1000.0f));
- } else if (k.equals("sct")) {
- LOG.info("avg score:\t" + (float) ((((double)val.get()) / totalCnt.get()) / 1000.0));
- } else if (k.startsWith("status")) {
- String[] st = k.split(" ");
- int code = Integer.parseInt(st[1]);
- if(st.length >2 ) LOG.info(" " + st[2] +" :\t" + val);
- else LOG.info(st[0] +" " +code + " (" + CrawlDatum.getStatusName((byte) code) + "):\t" + val);
- } else LOG.info(k + ":\t" + val);
- }
- }
- // removing the tmp folder
- fileSystem.delete(tmpFolder, true);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb statistics: done"); }
-
- }
-
- public CrawlDatum get(String crawlDb, String url, Configuration config) throws IOException {
- Text key = new Text(url);
- CrawlDatum val = new CrawlDatum();
- openReaders(crawlDb, config);
- CrawlDatum res = (CrawlDatum)MapFileOutputFormat.getEntry(readers,
- new HashPartitioner<Text, CrawlDatum>(), key, val);
- return res;
- }
-
- public void readUrl(String crawlDb, String url, Configuration config) throws IOException {
- CrawlDatum res = get(crawlDb, url, config);
- System.out.println("URL: " + url);
- if (res != null) {
- System.out.println(res);
- } else {
- System.out.println("not found");
- }
- }
-
- public void processDumpJob(String crawlDb, String output, Configuration config, int format) throws IOException {
-
- if (LOG.isInfoEnabled()) {
- LOG.info("CrawlDb dump: starting");
- LOG.info("CrawlDb db: " + crawlDb);
- }
-
- Path outFolder = new Path(output);
-
- JobConf job = new NutchJob(config);
- job.setJobName("dump " + crawlDb);
-
- FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
-
- FileOutputFormat.setOutputPath(job, outFolder);
- if(format == CSV_FORMAT) job.setOutputFormat(CrawlDatumCsvOutputFormat.class);
- else job.setOutputFormat(TextOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
-
- JobClient.runJob(job);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb dump: done"); }
- }
-
- public void processTopNJob(String crawlDb, long topN, float min, String output, Configuration config) throws IOException {
-
- if (LOG.isInfoEnabled()) {
- LOG.info("CrawlDb topN: starting (topN=" + topN + ", min=" + min + ")");
- LOG.info("CrawlDb db: " + crawlDb);
- }
-
- Path outFolder = new Path(output);
- Path tempDir =
- new Path(config.get("mapred.temp.dir", ".") +
- "/readdb-topN-temp-"+
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
-
- JobConf job = new NutchJob(config);
- job.setJobName("topN prepare " + crawlDb);
- FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(CrawlDbTopNMapper.class);
- job.setReducerClass(IdentityReducer.class);
-
- FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(SequenceFileOutputFormat.class);
- job.setOutputKeyClass(FloatWritable.class);
- job.setOutputValueClass(Text.class);
-
- // XXX hmmm, no setFloat() in the API ... :(
- job.setLong("db.reader.topn.min", Math.round(1000000.0 * min));
- JobClient.runJob(job);
-
- if (LOG.isInfoEnabled()) {
- LOG.info("CrawlDb topN: collecting topN scores.");
- }
- job = new NutchJob(config);
- job.setJobName("topN collect " + crawlDb);
- job.setLong("db.reader.topn", topN);
-
- FileInputFormat.addInputPath(job, tempDir);
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(IdentityMapper.class);
- job.setReducerClass(CrawlDbTopNReducer.class);
-
- FileOutputFormat.setOutputPath(job, outFolder);
- job.setOutputFormat(TextOutputFormat.class);
- job.setOutputKeyClass(FloatWritable.class);
- job.setOutputValueClass(Text.class);
-
- job.setNumReduceTasks(1); // create a single file.
-
- JobClient.runJob(job);
- FileSystem fs = FileSystem.get(config);
- fs.delete(tempDir, true);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb topN: done"); }
-
- }
-
- public static void main(String[] args) throws IOException {
- CrawlDbReader dbr = new CrawlDbReader();
-
- if (args.length < 1) {
- System.err.println("Usage: CrawlDbReader <crawldb> (-stats | -dump <out_dir> | -topN <nnnn> <out_dir> [<min>] | -url <url>)");
- System.err.println("\t<crawldb>\tdirectory name where crawldb is located");
- System.err.println("\t-stats [-sort] \tprint overall statistics to System.out");
- System.err.println("\t\t[-sort]\tlist status sorted by host");
- System.err.println("\t-dump <out_dir> [-format normal|csv ]\tdump the whole db to a text file in <out_dir>");
- System.err.println("\t\t[-format csv]\tdump in Csv format");
- System.err.println("\t\t[-format normal]\tdump in standard format (default option)");
- System.err.println("\t-url <url>\tprint information on <url> to System.out");
- System.err.println("\t-topN <nnnn> <out_dir> [<min>]\tdump top <nnnn> urls sorted by score to <out_dir>");
- System.err.println("\t\t[<min>]\tskip records with scores below this value.");
- System.err.println("\t\t\tThis can significantly improve performance.");
- return;
- }
- String param = null;
- String crawlDb = args[0];
- Configuration conf = NutchConfiguration.create();
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-stats")) {
- boolean toSort = false;
- if(i < args.length - 1 && "-sort".equals(args[i+1])){
- toSort = true;
- i++;
- }
- dbr.processStatJob(crawlDb, conf, toSort);
- } else if (args[i].equals("-dump")) {
- param = args[++i];
- String format = "normal";
- if(i < args.length - 1 && "-format".equals(args[i+1]))
- format = args[i=i+2];
- dbr.processDumpJob(crawlDb, param, conf, "csv".equals(format)? CSV_FORMAT : STD_FORMAT );
- } else if (args[i].equals("-url")) {
- param = args[++i];
- dbr.readUrl(crawlDb, param, conf);
- } else if (args[i].equals("-topN")) {
- param = args[++i];
- long topN = Long.parseLong(param);
- param = args[++i];
- float min = 0.0f;
- if (i < args.length - 1) {
- min = Float.parseFloat(args[++i]);
- }
- dbr.processTopNJob(crawlDb, topN, min, param, conf);
- } else {
- System.err.println("\nError: wrong argument " + args[i]);
- }
- }
- return;
- }
-}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
deleted file mode 100644
index dc2c0a692..000000000
--- a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.io.IOException;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.scoring.ScoringFilterException;
-import org.apache.nutch.scoring.ScoringFilters;
-
-/** Merge new page entries with existing entries. */
-public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- public static final Log LOG = LogFactory.getLog(CrawlDbReducer.class);
-
- private int retryMax;
- private CrawlDatum result = new CrawlDatum();
- private ArrayList<CrawlDatum> linked = new ArrayList<CrawlDatum>();
- private ScoringFilters scfilters = null;
- private boolean additionsAllowed;
- private int maxInterval;
- private FetchSchedule schedule;
- private CrawlDatum fetch = new CrawlDatum();
- private CrawlDatum old = new CrawlDatum();
-
- public void configure(JobConf job) {
- retryMax = job.getInt("db.fetch.retry.max", 3);
- scfilters = new ScoringFilters(job);
- additionsAllowed = job.getBoolean(CrawlDb.CRAWLDB_ADDITIONS_ALLOWED, true);
- int oldMaxInterval = job.getInt("db.max.fetch.interval", 0);
- maxInterval = job.getInt("db.fetch.interval.max", 0 );
- if (oldMaxInterval > 0 && maxInterval == 0) maxInterval = oldMaxInterval * FetchSchedule.SECONDS_PER_DAY;
- schedule = FetchScheduleFactory.getFetchSchedule(job);
- }
-
- public void close() {}
-
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
-
- boolean fetchSet = false;
- boolean oldSet = false;
- byte[] signature = null;
- linked.clear();
-
- while (values.hasNext()) {
- CrawlDatum datum = (CrawlDatum)values.next();
- if (CrawlDatum.hasDbStatus(datum)) {
- if (!oldSet) {
- old.set(datum);
- oldSet = true;
- } else {
- // always take the latest version
- if (old.getFetchTime() < datum.getFetchTime()) old.set(datum);
- }
- continue;
- }
-
- if (CrawlDatum.hasFetchStatus(datum)) {
- if (!fetchSet) {
- fetch.set(datum);
- fetchSet = true;
- } else {
- // always take the latest version
- if (fetch.getFetchTime() < datum.getFetchTime()) fetch.set(datum);
- }
- continue;
- }
-
- switch (datum.getStatus()) { // collect other info
- case CrawlDatum.STATUS_LINKED:
- CrawlDatum link = new CrawlDatum();
- link.set(datum);
- linked.add(link);
- break;
- case CrawlDatum.STATUS_SIGNATURE:
- signature = datum.getSignature();
- break;
- default:
- LOG.warn("Unknown status, key: " + key + ", datum: " + datum);
- }
- }
-
- // if it doesn't already exist, skip it
- if (!oldSet && !additionsAllowed) return;
-
- // if there is no fetched datum, perhaps there is a link
- if (!fetchSet && linked.size() > 0) {
- fetch = linked.get(0);
- fetchSet = true;
- }
-
- // still no new data - record only unchanged old data, if exists, and return
- if (!fetchSet) {
- if (oldSet) // at this point at least "old" should be present
- output.collect(key, old);
- else
- LOG.warn("Missing fetch and old value, signature=" + signature);
- return;
- }
-
- if (signature == null) signature = fetch.getSignature();
- long prevModifiedTime = oldSet ? old.getModifiedTime() : 0L;
- long prevFetchTime = oldSet ? old.getFetchTime() : 0L;
-
- // initialize with the latest version, be it fetch or link
- result.set(fetch);
- if (oldSet) {
- // copy metadata from old, if exists
- if (old.getMetaData().size() > 0) {
- result.putAllMetaData(old);
- // overlay with new, if any
- if (fetch.getMetaData().size() > 0)
- result.putAllMetaData(fetch);
- }
- // set the most recent valid value of modifiedTime
- if (old.getModifiedTime() > 0 && fetch.getModifiedTime() == 0) {
- result.setModifiedTime(old.getModifiedTime());
- }
- }
-
- switch (fetch.getStatus()) { // determine new status
-
- case CrawlDatum.STATUS_LINKED: // it was link
- if (oldSet) { // if old exists
- result.set(old); // use it
- } else {
- result = schedule.initializeSchedule((Text)key, result);
- result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
- try {
- scfilters.initialScore((Text)key, result);
- } catch (ScoringFilterException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Cannot filter init score for url " + key +
- ", using default: " + e.getMessage());
- }
- result.setScore(0.0f);
- }
- }
- break;
-
- case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch
- case CrawlDatum.STATUS_FETCH_REDIR_TEMP: // successful fetch, redirected
- case CrawlDatum.STATUS_FETCH_REDIR_PERM:
- case CrawlDatum.STATUS_FETCH_NOTMODIFIED: // successful fetch, notmodified
- // determine the modification status
- int modified = FetchSchedule.STATUS_UNKNOWN;
- if (fetch.getStatus() == CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
- modified = FetchSchedule.STATUS_NOTMODIFIED;
- } else {
- if (oldSet && old.getSignature() != null && signature != null) {
- if (SignatureComparator._compare(old.getSignature(), signature) != 0) {
- modified = FetchSchedule.STATUS_MODIFIED;
- } else {
- modified = FetchSchedule.STATUS_NOTMODIFIED;
- }
- }
- }
- // set the schedule
- result = schedule.setFetchSchedule((Text)key, result, prevFetchTime,
- prevModifiedTime, fetch.getFetchTime(), fetch.getModifiedTime(), modified);
- // set the result status and signature
- if (modified == FetchSchedule.STATUS_NOTMODIFIED) {
- result.setStatus(CrawlDatum.STATUS_DB_NOTMODIFIED);
- if (oldSet) result.setSignature(old.getSignature());
- } else {
- switch (fetch.getStatus()) {
- case CrawlDatum.STATUS_FETCH_SUCCESS:
- result.setStatus(CrawlDatum.STATUS_DB_FETCHED);
- break;
- case CrawlDatum.STATUS_FETCH_REDIR_PERM:
- result.setStatus(CrawlDatum.STATUS_DB_REDIR_PERM);
- break;
- case CrawlDatum.STATUS_FETCH_REDIR_TEMP:
- result.setStatus(CrawlDatum.STATUS_DB_REDIR_TEMP);
- break;
- default:
- LOG.warn("Unexpected status: " + fetch.getStatus() + " resetting to old status.");
- if (oldSet) result.setStatus(old.getStatus());
- else result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
- }
- result.setSignature(signature);
- }
- // if fetchInterval is larger than the system-wide maximum, trigger
- // an unconditional recrawl. This prevents the page to be stuck at
- // NOTMODIFIED state, when the old fetched copy was already removed with
- // old segments.
- if (maxInterval < result.getFetchInterval())
- result = schedule.forceRefetch((Text)key, result, false);
- break;
- case CrawlDatum.STATUS_SIGNATURE:
- if (LOG.isWarnEnabled()) {
- LOG.warn("Lone CrawlDatum.STATUS_SIGNATURE: " + key);
- }
- return;
- case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure
- if (oldSet) {
- result.setSignature(old.getSignature()); // use old signature
- }
- result = schedule.setPageRetrySchedule((Text)key, result, prevFetchTime,
- prevModifiedTime, fetch.getFetchTime());
- if (result.getRetriesSinceFetch() < retryMax) {
- result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
- } else {
- result.setStatus(CrawlDatum.STATUS_DB_GONE);
- }
- break;
-
- case CrawlDatum.STATUS_FETCH_GONE: // permanent failure
- if (oldSet)
- result.setSignature(old.getSignature()); // use old signature
- result.setStatus(CrawlDatum.STATUS_DB_GONE);
- result = schedule.setPageGoneSchedule((Text)key, result, prevFetchTime,
- prevModifiedTime, fetch.getFetchTime());
- break;
-
- default:
- throw new RuntimeException("Unknown status: " + fetch.getStatus() + " " + key);
- }
-
- try {
- scfilters.updateDbScore((Text)key, oldSet ? old : null, result, linked);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't update score, key=" + key + ": " + e);
- }
- }
- // remove generation time, if any
- result.getMetaData().remove(Nutch.WRITABLE_GENERATE_TIME_KEY);
- output.collect(key, result);
- }
-
-}
diff --git a/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java b/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java
index 8db9a3230..959a9256c 100755
--- a/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java
@@ -17,7 +17,7 @@
package org.apache.nutch.crawl;
-import org.apache.hadoop.io.Text;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* This class implements the default re-fetch schedule. That is, no matter
@@ -30,13 +30,13 @@ import org.apache.hadoop.io.Text;
public class DefaultFetchSchedule extends AbstractFetchSchedule {
@Override
- public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
+ public void setFetchSchedule(String url, WebTableRow row,
long prevFetchTime, long prevModifiedTime,
long fetchTime, long modifiedTime, int state) {
- datum = super.setFetchSchedule(url, datum, prevFetchTime, prevModifiedTime,
+ super.setFetchSchedule(url, row, prevFetchTime, prevModifiedTime,
fetchTime, modifiedTime, state);
- datum.setFetchTime(fetchTime + (long)datum.getFetchInterval() * 1000);
- datum.setModifiedTime(modifiedTime);
- return datum;
+ row.setFetchTime(fetchTime + row.getFetchInterval() * 1000L);
+ row.setModifiedTime(modifiedTime);
}
+
}
diff --git a/src/java/org/apache/nutch/crawl/FetchSchedule.java b/src/java/org/apache/nutch/crawl/FetchSchedule.java
index dcc9905ca..a14b03c88 100755
--- a/src/java/org/apache/nutch/crawl/FetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/FetchSchedule.java
@@ -17,8 +17,12 @@
package org.apache.nutch.crawl;
+import java.util.Set;
+
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.io.Text;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* This interface defines the contract for implementations that manipulate
@@ -27,15 +31,16 @@ import org.apache.hadoop.io.Text;
* @author Andrzej Bialecki
*/
public interface FetchSchedule extends Configurable {
-
+
/** It is unknown whether page was changed since our last visit. */
public static final int STATUS_UNKNOWN = 0;
/** Page is known to have been modified since our last visit. */
public static final int STATUS_MODIFIED = 1;
/** Page is known to remain unmodified since our last visit. */
public static final int STATUS_NOTMODIFIED = 2;
-
+
public static final int SECONDS_PER_DAY = 3600 * 24;
+
/**
* Initialize fetch schedule related data. Implementations should at least
* set the <code>fetchTime</code> and <code>fetchInterval</code>. The default
@@ -43,14 +48,10 @@ public interface FetchSchedule extends Configurable {
* default <code>fetchInterval</code>.
*
* @param url URL of the page.
- * @param datum datum instance to be initialized.
- * @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than {@param datum}, but
- * implementations should make sure that it contains at least all
- * information from {@param datum}.
+ * @param row url's row
*/
- public CrawlDatum initializeSchedule(Text url, CrawlDatum datum);
-
+ public void initializeSchedule(String url, WebTableRow row);
+
/**
* Sets the <code>fetchInterval</code> and <code>fetchTime</code> on a
* successfully fetched page.
@@ -58,10 +59,9 @@ public interface FetchSchedule extends Configurable {
* schedules.
*
* @param url url of the page
- * @param datum page description to be adjusted. NOTE: this instance, passed by reference,
- * may be modified inside the method.
- * @param prevFetchTime previous value of fetch time, or 0 if not available
- * @param prevModifiedTime previous value of modifiedTime, or 0 if not available
+ * @param row url's row
+ * @param prevFetchTime previous value of fetch time, or -1 if not available
+ * @param prevModifiedTime previous value of modifiedTime, or -1 if not available
* @param fetchTime the latest time, when the page was recently re-fetched. Most FetchSchedule
* implementations should update the value in {@param datum} to something greater than this value.
* @param modifiedTime last time the content was modified. This information comes from
@@ -72,52 +72,41 @@ public interface FetchSchedule extends Configurable {
* This information may be obtained by comparing page signatures before and after fetching. If this
* is set to {@link #STATUS_UNKNOWN}, then it is unknown whether the page was changed; implementations
* are free to follow a sensible default behavior.
- * @return adjusted page information, including all original information. NOTE: this may
- * be a different instance than {@param datum}, but implementations should make sure that
- * it contains at least all information from {@param datum}.
*/
- public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime,
- long fetchTime, long modifiedTime, int state);
-
+ public void setFetchSchedule(String url, WebTableRow row,
+ long prevFetchTime, long prevModifiedTime,
+ long fetchTime, long modifiedTime, int state);
+
/**
* This method specifies how to schedule refetching of pages
* marked as GONE. Default implementation increases fetchInterval by 50%,
* and if it exceeds the <code>maxInterval</code> it calls
* {@link #forceRefetch(Text, CrawlDatum, boolean)}.
* @param url URL of the page
- * @param datum datum instance to be adjusted
- * @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than {@param datum}, but
- * implementations should make sure that it contains at least all
- * information from {@param datum}.
+ * @param row url's row
*/
- public CrawlDatum setPageGoneSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime, long fetchTime);
-
+ public void setPageGoneSchedule(String url, WebTableRow row,
+ long prevFetchTime, long prevModifiedTime, long fetchTime);
+
/**
* This method adjusts the fetch schedule if fetching needs to be
* re-tried due to transient errors. The default implementation
* sets the next fetch time 1 day in the future and increases the
* retry counter.
* @param url URL of the page
- * @param datum page information
+ * @param row url's row
* @param prevFetchTime previous fetch time
* @param prevModifiedTime previous modified time
* @param fetchTime current fetch time
- * @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than {@param datum}, but
- * implementations should make sure that it contains at least all
- * information from {@param datum}.
*/
- public CrawlDatum setPageRetrySchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime, long fetchTime);
-
+ public void setPageRetrySchedule(String url, WebTableRow row,
+ long prevFetchTime, long prevModifiedTime, long fetchTime);
+
/**
* Calculates last fetch time of the given CrawlDatum.
* @return the date as a long.
*/
- public long calculateLastFetchTime(CrawlDatum datum);
+ public long calculateLastFetchTime(WebTableRow row);
/**
* This method provides information whether the page is suitable for
@@ -129,26 +118,24 @@ public interface FetchSchedule extends Configurable {
* check that fetchTime is not too remote (more than <code>maxInterval</code),
* in which case it lowers the interval and returns true.
* @param url URL of the page
- * @param datum datum instance
+ * @param row url's row
* @param curTime reference time (usually set to the time when the
* fetchlist generation process was started).
* @return true, if the page should be considered for inclusion in the current
* fetchlist, otherwise false.
*/
- public boolean shouldFetch(Text url, CrawlDatum datum, long curTime);
-
+ public boolean shouldFetch(String url, WebTableRow row, long curTime);
+
/**
* This method resets fetchTime, fetchInterval, modifiedTime and
* page signature, so that it forces refetching.
* @param url URL of the page
- * @param datum datum instance
+ * @param row url's row
* @param asap if true, force refetch as soon as possible - this sets
* the fetchTime to now. If false, force refetch whenever the next fetch
* time is set.
- * @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than {@param datum}, but
- * implementations should make sure that it contains at least all
- * information from {@param datum}.
*/
- public CrawlDatum forceRefetch(Text url, CrawlDatum datum, boolean asap);
+ public void forceRefetch(String url, WebTableRow row, boolean asap);
+
+ public Set<HbaseColumn> getColumns();
}
diff --git a/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java b/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
index cf54f141b..f4df17d97 100755
--- a/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
+++ b/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
@@ -37,7 +37,7 @@ public class FetchScheduleFactory {
if (impl == null) {
try {
LOG.info("Using FetchSchedule impl: " + clazz);
- Class implClass = Class.forName(clazz);
+ Class<?> implClass = Class.forName(clazz);
impl = (FetchSchedule)implClass.newInstance();
impl.setConf(conf);
objectCache.setObject(clazz, impl);
diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.java
index f43e6301b..12c0be264 100644
--- a/src/java/org/apache/nutch/crawl/Generator.java
+++ b/src/java/org/apache/nutch/crawl/Generator.java
@@ -1,626 +1,185 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.apache.nutch.crawl;
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import java.text.*;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Random;
+import java.util.Set;
-// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.net.URLFilterException;
-import org.apache.nutch.net.URLFilters;
-import org.apache.nutch.net.URLNormalizers;
-import org.apache.nutch.scoring.ScoringFilterException;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.LockUtil;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.WritableComparable;
+import org.apache.hadoop.io.WritableComparator;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
-
-/** Generates a subset of a crawl db to fetch. */
-public class Generator extends Configured implements Tool {
-
+import org.apache.nutch.util.URLUtil;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
+
+public class Generator
+extends Configured
+implements Tool {
public static final String CRAWL_GENERATE_FILTER = "crawl.generate.filter";
- public static final String GENERATE_MAX_PER_HOST_BY_IP = "generate.max.per.host.by.ip";
public static final String GENERATE_MAX_PER_HOST = "generate.max.per.host";
- public static final String GENERATE_UPDATE_CRAWLDB = "generate.update.crawldb";
public static final String CRAWL_TOP_N = "crawl.topN";
public static final String CRAWL_GEN_CUR_TIME = "crawl.gen.curTime";
- public static final String CRAWL_GEN_DELAY = "crawl.gen.delay";
- public static final Log LOG = LogFactory.getLog(Generator.class);
+ public static final String CRAWL_RANDOM_SEED = "generate.partition.seed";
- public static class SelectorEntry implements Writable {
- public Text url;
- public CrawlDatum datum;
-
- public SelectorEntry() {
- url = new Text();
- datum = new CrawlDatum();
- }
-
- public void readFields(DataInput in) throws IOException {
- url.readFields(in);
- datum.readFields(in);
- }
-
- public void write(DataOutput out) throws IOException {
- url.write(out);
- datum.write(out);
- }
-
- public String toString() {
- return "url=" + url.toString() + ", datum=" + datum.toString();
- }
+ private static final Set<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.FETCH_TIME));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.SCORE));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.STATUS));
}
-
- /** Selects entries due for fetch. */
- public static class Selector implements Mapper<Text, CrawlDatum, FloatWritable, SelectorEntry>, Partitioner<FloatWritable, Writable>, Reducer<FloatWritable, SelectorEntry, FloatWritable, SelectorEntry> {
- private LongWritable genTime = new LongWritable(System.currentTimeMillis());
- private long curTime;
- private long limit;
- private long count;
- private HashMap<String, IntWritable> hostCounts =
- new HashMap<String, IntWritable>();
- private int maxPerHost;
- private HashSet<String> maxedHosts = new HashSet<String>();
- private HashSet<String> dnsFailureHosts = new HashSet<String>();
- private Partitioner<Text, Writable> hostPartitioner = new PartitionUrlByHost();
- private URLFilters filters;
- private URLNormalizers normalizers;
- private ScoringFilters scfilters;
- private SelectorEntry entry = new SelectorEntry();
- private FloatWritable sortValue = new FloatWritable();
- private boolean byIP;
- private long dnsFailure = 0L;
- private boolean filter;
- private long genDelay;
- private FetchSchedule schedule;
-
- public void configure(JobConf job) {
- curTime = job.getLong(CRAWL_GEN_CUR_TIME, System.currentTimeMillis());
- limit = job.getLong(CRAWL_TOP_N,Long.MAX_VALUE)/job.getNumReduceTasks();
- maxPerHost = job.getInt(GENERATE_MAX_PER_HOST, -1);
- byIP = job.getBoolean(GENERATE_MAX_PER_HOST_BY_IP, false);
- filters = new URLFilters(job);
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
- scfilters = new ScoringFilters(job);
- hostPartitioner.configure(job);
- filter = job.getBoolean(CRAWL_GENERATE_FILTER, true);
- genDelay = job.getLong(CRAWL_GEN_DELAY, 7L) * 3600L * 24L * 1000L;
- long time = job.getLong(Nutch.GENERATE_TIME_KEY, 0L);
- if (time > 0) genTime.set(time);
- schedule = FetchScheduleFactory.getFetchSchedule(job);
- }
-
- public void close() {}
-
- /** Select & invert subset due for fetch. */
- public void map(Text key, CrawlDatum value,
- OutputCollector<FloatWritable, SelectorEntry> output, Reporter reporter)
- throws IOException {
- Text url = key;
- if (filter) {
- // If filtering is on don't generate URLs that don't pass URLFilters
- try {
- if (filters.filter(url.toString()) == null)
- return;
- } catch (URLFilterException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't filter url: " + url + " (" + e.getMessage()
- + ")");
- }
- }
- }
- CrawlDatum crawlDatum = value;
-
- // check fetch schedule
- if (!schedule.shouldFetch(url, crawlDatum, curTime)) {
- LOG.debug("-shouldFetch rejected '" + url+ "', fetchTime=" + crawlDatum.getFetchTime() + ", curTime=" + curTime);
- return;
- }
-
- LongWritable oldGenTime = (LongWritable)crawlDatum.getMetaData().get(Nutch.WRITABLE_GENERATE_TIME_KEY);
- if (oldGenTime != null) { // awaiting fetch & update
- if (oldGenTime.get() + genDelay > curTime) // still wait for update
- return;
- }
- float sort = 1.0f;
- try {
- sort = scfilters.generatorSortValue((Text)key, crawlDatum, sort);
- } catch (ScoringFilterException sfe) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't filter generatorSortValue for " + key + ": " + sfe);
- }
- }
- // sort by decreasing score, using DecreasingFloatComparator
- sortValue.set(sort);
- // record generation time
- crawlDatum.getMetaData().put(Nutch.WRITABLE_GENERATE_TIME_KEY, genTime);
- entry.datum = crawlDatum;
- entry.url = (Text)key;
- output.collect(sortValue, entry); // invert for sort by score
- }
-
- /** Partition by host. */
- public int getPartition(FloatWritable key, Writable value,
- int numReduceTasks) {
- return hostPartitioner.getPartition(((SelectorEntry)value).url, key,
- numReduceTasks);
- }
-
- /** Collect until limit is reached. */
- public void reduce(FloatWritable key, Iterator<SelectorEntry> values,
- OutputCollector<FloatWritable, SelectorEntry> output,
- Reporter reporter)
- throws IOException {
-
- while (values.hasNext() && count < limit) {
-
- SelectorEntry entry = values.next();
- Text url = entry.url;
- String urlString = url.toString();
- URL u = null;
-
- // skip bad urls, including empty and null urls
- try {
- u = new URL(url.toString());
- } catch (MalformedURLException e) {
- LOG.info("Bad protocol in url: " + url.toString());
- continue;
- }
-
- String host = u.getHost();
- host = host.toLowerCase();
- String hostname = host;
-
- // partitioning by ip will generate lots of DNS requests here, and will
- // be up to double the overall dns load, do not run this way unless you
- // are running a local caching DNS server or a two layer DNS cache
- if (byIP) {
- if (maxedHosts.contains(host)) {
- if (LOG.isDebugEnabled()) { LOG.debug("Host already maxed out: " + host); }
- continue;
- }
- if (dnsFailureHosts.contains(host)) {
- if (LOG.isDebugEnabled()) { LOG.debug("Host name lookup already failed: " + host); }
- continue;
- }
- try {
- InetAddress ia = InetAddress.getByName(host);
- host = ia.getHostAddress();
- urlString = new URL(u.getProtocol(), host, u.getPort(), u.getFile()).toString();
- }
- catch (UnknownHostException uhe) {
- // remember hostnames that could not be looked up
- dnsFailureHosts.add(hostname);
- if (LOG.isDebugEnabled()) {
- LOG.debug("DNS lookup failed: " + host + ", skipping.");
- }
- dnsFailure++;
- if ((dnsFailure % 1000 == 0) && (LOG.isWarnEnabled())) {
- LOG.warn("DNS failures: " + dnsFailure);
- }
- continue;
- }
- }
-
- try {
- urlString = normalizers.normalize(urlString, URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
- host = new URL(urlString).getHost();
- } catch (Exception e) {
- LOG.warn("Malformed URL: '" + urlString + "', skipping (" +
- StringUtils.stringifyException(e) + ")");
- continue;
- }
-
- // only filter if we are counting hosts
- if (maxPerHost > 0) {
-
- IntWritable hostCount = hostCounts.get(host);
- if (hostCount == null) {
- hostCount = new IntWritable();
- hostCounts.put(host, hostCount);
- }
- // increment hostCount
- hostCount.set(hostCount.get() + 1);
+ public static final byte[] GENERATOR_MARK =
+ Bytes.toBytes("__genmrk__");
- // skip URL if above the limit per host.
- if (hostCount.get() > maxPerHost) {
- if (hostCount.get() == maxPerHost + 1) {
- // remember the raw hostname that is maxed out
- maxedHosts.add(hostname);
- if (LOG.isInfoEnabled()) {
- LOG.info("Host " + host + " has more than " + maxPerHost +
- " URLs." + " Skipping additional.");
- }
- }
- continue;
- }
- }
+ public static final Log LOG = LogFactory.getLog(Generator.class);
- output.collect(key, entry);
+ public static class SelectorEntry
+ implements WritableComparable<SelectorEntry> {
- // Count is incremented only when we keep the URL
- // maxPerHost may cause us to skip it.
- count++;
- }
+ String url;
+ String host;
+ float score;
+
+ public SelectorEntry() { }
+
+ public SelectorEntry(String url, float score) {
+ this.url = url;
+ this.host = URLUtil.getHost(url);
+ this.score = score;
}
- }
- public static class DecreasingFloatComparator extends FloatWritable.Comparator {
-
- /** Compares two FloatWritables decreasing. */
- public int compare(byte[] b1, int s1, int l1,
- byte[] b2, int s2, int l2) {
- return super.compare(b2, s2, l2, b1, s1, l1);
+ public void readFields(DataInput in) throws IOException {
+ url = Text.readString(in);
+ host = Text.readString(in);
+ score = in.readFloat();
}
- }
-
- public static class SelectorInverseMapper extends MapReduceBase implements Mapper<FloatWritable, SelectorEntry, Text, SelectorEntry> {
- public void map(FloatWritable key, SelectorEntry value, OutputCollector<Text, SelectorEntry> output, Reporter reporter) throws IOException {
- SelectorEntry entry = (SelectorEntry)value;
- output.collect(entry.url, entry);
+ public void write(DataOutput out) throws IOException {
+ Text.writeString(out, url);
+ Text.writeString(out, host);
+ out.writeFloat(score);
}
- }
-
- public static class PartitionReducer extends MapReduceBase
- implements Reducer<Text, SelectorEntry, Text, CrawlDatum> {
- public void reduce(Text key, Iterator<SelectorEntry> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter) throws IOException {
- // if using HashComparator, we get only one input key in case of hash collision
- // so use only URLs from values
- while (values.hasNext()) {
- SelectorEntry entry = values.next();
- output.collect(entry.url, entry.datum);
- }
+ public int compareTo(SelectorEntry se) {
+ if (se.score > score)
+ return 1;
+ else if (se.score == score)
+ return url.compareTo(se.url);
+ return -1;
}
- }
-
- /** Sort fetch lists by hash of URL. */
- public static class HashComparator extends WritableComparator {
- public HashComparator() {
- super(Text.class);
- }
-
- public int compare(WritableComparable a, WritableComparable b) {
- Text url1 = (Text) a;
- Text url2 = (Text) b;
- int hash1 = hash(url1.getBytes(), 0, url1.getLength());
- int hash2 = hash(url2.getBytes(), 0, url2.getLength());
- return (hash1 < hash2 ? -1 : (hash1 == hash2 ? 0 : 1));
- }
-
- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
- int hash1 = hash(b1, s1, l1);
- int hash2 = hash(b2, s2, l2);
- return (hash1 < hash2 ? -1 : (hash1 == hash2 ? 0 : 1));
- }
-
- private static int hash(byte[] bytes, int start, int length) {
- int hash = 1;
- // make later bytes more significant in hash code, so that sorting by
- // hashcode correlates less with by-host ordering.
- for (int i = length - 1; i >= 0; i--)
- hash = (31 * hash) + (int) bytes[start + i];
- return hash;
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + url.hashCode();
+ result = prime * result + Float.floatToIntBits(score);
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ SelectorEntry other = (SelectorEntry) obj;
+ if (!url.equals(other.url))
+ return false;
+ if (Float.floatToIntBits(score) != Float.floatToIntBits(other.score))
+ return false;
+ return true;
}
}
- /**
- * Update the CrawlDB so that the next generate won't include the same URLs.
- */
- public static class CrawlDbUpdater extends MapReduceBase implements Mapper<WritableComparable, Writable, Text, CrawlDatum>, Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- long generateTime;
-
- public void configure(JobConf job) {
- generateTime = job.getLong(Nutch.GENERATE_TIME_KEY, 0L);
- }
-
- public void map(WritableComparable key, Writable value, OutputCollector<Text, CrawlDatum> output, Reporter reporter) throws IOException {
- if (key instanceof FloatWritable) { // tempDir source
- SelectorEntry se = (SelectorEntry)value;
- output.collect(se.url, se.datum);
- } else {
- output.collect((Text)key, (CrawlDatum)value);
- }
+ public static class SelectorEntryComparator extends WritableComparator {
+ public SelectorEntryComparator() {
+ super(SelectorEntry.class, true);
}
- private CrawlDatum orig = new CrawlDatum();
- private LongWritable genTime = new LongWritable(0L);
-
- public void reduce(Text key, Iterator<CrawlDatum> values, OutputCollector<Text, CrawlDatum> output, Reporter reporter) throws IOException {
- while (values.hasNext()) {
- CrawlDatum val = values.next();
- if (val.getMetaData().containsKey(Nutch.WRITABLE_GENERATE_TIME_KEY)) {
- LongWritable gt = (LongWritable)val.getMetaData().get(Nutch.WRITABLE_GENERATE_TIME_KEY);
- genTime.set(gt.get());
- if (genTime.get() != generateTime) {
- orig.set(val);
- genTime.set(0L);
- continue;
- }
- } else {
- orig.set(val);
- }
- }
- if (genTime.get() != 0L) {
- orig.getMetaData().put(Nutch.WRITABLE_GENERATE_TIME_KEY, genTime);
- }
- output.collect(key, orig);
- }
}
- public Generator() {}
-
- public Generator(Configuration conf) {
- setConf(conf);
+ static {
+ WritableComparator.define(SelectorEntry.class,
+ new SelectorEntryComparator());
}
/**
- * Generate fetchlists in a segment. Whether to filter URLs or not is
- * read from the crawl.generate.filter property in the configuration
- * files. If the property is not found, the URLs are filtered.
- *
- * @param dbDir Crawl database directory
- * @param segments Segments directory
- * @param numLists Number of reduce tasks
- * @param topN Number of top URLs to be selected
- * @param curTime Current time in milliseconds
- *
- * @return Path to generated segment or null if no entries were
- * selected
- *
- * @throws IOException When an I/O error occurs
- */
- public Path generate(Path dbDir, Path segments, int numLists,
- long topN, long curTime) throws IOException {
-
- JobConf job = new NutchJob(getConf());
- boolean filter = job.getBoolean(CRAWL_GENERATE_FILTER, true);
- return generate(dbDir, segments, numLists, topN, curTime, filter, false);
- }
-
- /**
- * Generate fetchlists in a segment.
- * @return Path to generated segment or null if no entries were selected.
+ * Mark URLs ready for fetching.
+ * @throws ClassNotFoundException
+ * @throws InterruptedException
* */
- public Path generate(Path dbDir, Path segments,
- int numLists, long topN, long curTime, boolean filter,
- boolean force)
- throws IOException {
-
- Path tempDir =
- new Path(getConf().get("mapred.temp.dir", ".") +
- "/generate-temp-"+ System.currentTimeMillis());
-
- Path segment = new Path(segments, generateSegmentName());
- Path output = new Path(segment, CrawlDatum.GENERATE_DIR_NAME);
-
- Path lock = new Path(dbDir, CrawlDb.LOCK_NAME);
- FileSystem fs = FileSystem.get(getConf());
- LockUtil.createLockFile(fs, lock, force);
-
- LOG.info("Generator: Selecting best-scoring urls due for fetch.");
- LOG.info("Generator: starting");
- LOG.info("Generator: segment: " + segment);
- LOG.info("Generator: filtering: " + filter);
+ public void generate(String table, long topN, long curTime, boolean filter)
+ throws Exception {
+
+ LOG.info("GeneratorHbase: Selecting best-scoring urls due for fetch.");
+ LOG.info("GeneratorHbase: starting");
+ LOG.info("GeneratorHbase: filtering: " + filter);
if (topN != Long.MAX_VALUE) {
- LOG.info("Generator: topN: " + topN);
+ LOG.info("GeneratorHbase: topN: " + topN);
}
-
+
// map to inverted subset due for fetch, sort by score
- JobConf job = new NutchJob(getConf());
- job.setJobName("generate: select " + segment);
-
- if (numLists == -1) { // for politeness make
- numLists = job.getNumMapTasks(); // a partition per fetch task
- }
- if ("local".equals(job.get("mapred.job.tracker")) && numLists != 1) {
- // override
- LOG.info("Generator: jobtracker is 'local', generating exactly one partition.");
- numLists = 1;
- }
- job.setLong(CRAWL_GEN_CUR_TIME, curTime);
- // record real generation time
- long generateTime = System.currentTimeMillis();
- job.setLong(Nutch.GENERATE_TIME_KEY, generateTime);
- job.setLong(CRAWL_TOP_N, topN);
- job.setBoolean(CRAWL_GENERATE_FILTER, filter);
-
- FileInputFormat.addInputPath(job, new Path(dbDir, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(Selector.class);
- job.setPartitionerClass(Selector.class);
- job.setReducerClass(Selector.class);
-
- FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(SequenceFileOutputFormat.class);
- job.setOutputKeyClass(FloatWritable.class);
- job.setOutputKeyComparatorClass(DecreasingFloatComparator.class);
- job.setOutputValueClass(SelectorEntry.class);
- try {
- JobClient.runJob(job);
- } catch (IOException e) {
- LockUtil.removeLockFile(fs, lock);
- throw e;
- }
-
- // check that we selected at least some entries ...
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(job, tempDir);
- boolean empty = true;
- if (readers != null && readers.length > 0) {
- for (int num = 0; num < readers.length; num++) {
- if (readers[num].next(new FloatWritable())) {
- empty = false;
- break;
- }
- }
- }
-
- for (int i = 0; i < readers.length; i++) readers[i].close();
-
- if (empty) {
- LOG.warn("Generator: 0 records selected for fetching, exiting ...");
- LockUtil.removeLockFile(fs, lock);
- fs.delete(tempDir, true);
- return null;
- }
-
- // invert again, paritition by host, sort by url hash
- if (LOG.isInfoEnabled()) {
- LOG.info("Generator: Partitioning selected urls by host, for politeness.");
- }
- job = new NutchJob(getConf());
- job.setJobName("generate: partition " + segment);
+ getConf().setLong(CRAWL_GEN_CUR_TIME, curTime);
+ getConf().setLong(CRAWL_TOP_N, topN);
+ getConf().setBoolean(CRAWL_GENERATE_FILTER, filter);
+ getConf().setInt(CRAWL_RANDOM_SEED, new Random().nextInt());
+
+ Job job = new NutchJob(getConf(), "generate-hbase: " + table);
+ job.setJobName("generate-hbase: " + table);
+ Scan scan = TableUtil.createScanFromColumns(COLUMNS);
+ TableMapReduceUtil.initTableMapperJob(table, scan,
+ GeneratorMapper.class, SelectorEntry.class,
+ WebTableRow.class, job);
+ TableMapReduceUtil.initTableReducerJob(table, GeneratorReducer.class, job, PartitionSelectorByHost.class);
+
+ job.waitForCompletion(true);
- job.setInt("partition.url.by.host.seed", new Random().nextInt());
-
- FileInputFormat.addInputPath(job, tempDir);
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(SelectorInverseMapper.class);
- job.setMapOutputKeyClass(Text.class);
- job.setMapOutputValueClass(SelectorEntry.class);
- job.setPartitionerClass(PartitionUrlByHost.class);
- job.setReducerClass(PartitionReducer.class);
- job.setNumReduceTasks(numLists);
-
- FileOutputFormat.setOutputPath(job, output);
- job.setOutputFormat(SequenceFileOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
- job.setOutputKeyComparatorClass(HashComparator.class);
- try {
- JobClient.runJob(job);
- } catch (IOException e) {
- LockUtil.removeLockFile(fs, lock);
- fs.delete(tempDir, true);
- throw e;
- }
- if (getConf().getBoolean(GENERATE_UPDATE_CRAWLDB, false)) {
- // update the db from tempDir
- Path tempDir2 =
- new Path(getConf().get("mapred.temp.dir", ".") +
- "/generate-temp-"+ System.currentTimeMillis());
-
- job = new NutchJob(getConf());
- job.setJobName("generate: updatedb " + dbDir);
- job.setLong(Nutch.GENERATE_TIME_KEY, generateTime);
- FileInputFormat.addInputPath(job, tempDir);
- FileInputFormat.addInputPath(job, new Path(dbDir, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(CrawlDbUpdater.class);
- job.setReducerClass(CrawlDbUpdater.class);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
- FileOutputFormat.setOutputPath(job, tempDir2);
- try {
- JobClient.runJob(job);
- CrawlDb.install(job, dbDir);
- } catch (IOException e) {
- LockUtil.removeLockFile(fs, lock);
- fs.delete(tempDir, true);
- fs.delete(tempDir2, true);
- throw e;
- }
- fs.delete(tempDir2, true);
- }
- LockUtil.removeLockFile(fs, lock);
- fs.delete(tempDir, true);
-
- if (LOG.isInfoEnabled()) { LOG.info("Generator: done."); }
-
- return segment;
- }
-
- private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
-
- public static synchronized String generateSegmentName() {
- try {
- Thread.sleep(1000);
- } catch (Throwable t) {};
- return sdf.format
- (new Date(System.currentTimeMillis()));
+ LOG.info("GeneratorHbase: done");
}
- /**
- * Generate a fetchlist from the crawldb.
- */
- public static void main(String args[]) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new Generator(), args);
- System.exit(res);
- }
-
public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.out.println("Usage: Generator <crawldb> <segments_dir> [-force] [-topN N] [-numFetchers numFetchers] [-adddays numDays] [-noFilter]");
+ if (args.length < 1) {
+ System.out.println("Usage: GeneratorHbase <webtable> [-topN N] [-noFilter]");
return -1;
}
-
- Path dbDir = new Path(args[0]);
- Path segmentsDir = new Path(args[1]);
+
+ String table = args[0];
long curTime = System.currentTimeMillis();
long topN = Long.MAX_VALUE;
- int numFetchers = -1;
boolean filter = true;
- boolean force = false;
- for (int i = 2; i < args.length; i++) {
+ for (int i = 1; i < args.length; i++) {
if ("-topN".equals(args[i])) {
- topN = Long.parseLong(args[i+1]);
- i++;
- } else if ("-numFetchers".equals(args[i])) {
- numFetchers = Integer.parseInt(args[i+1]);
- i++;
- } else if ("-adddays".equals(args[i])) {
- long numDays = Integer.parseInt(args[i+1]);
- curTime += numDays * 1000L * 60 * 60 * 24;
+ topN = Long.parseLong(args[++i]);
} else if ("-noFilter".equals(args[i])) {
filter = false;
- } else if ("-force".equals(args[i])) {
- force = true;
}
-
}
-
+
try {
- Path seg = generate(dbDir, segmentsDir, numFetchers, topN, curTime, filter, force);
- if (seg == null) return -2;
- else return 0;
+ generate(table, topN, curTime, filter);
+ return 0;
} catch (Exception e) {
- LOG.fatal("Generator: " + StringUtils.stringifyException(e));
+ LOG.fatal("GeneratorHbase: " + StringUtils.stringifyException(e));
return -1;
}
}
+
+ public static void main(String args[]) throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(), new Generator(), args);
+ System.exit(res);
+ }
}
diff --git a/src/java/org/apache/nutch/crawl/GeneratorMapper.java b/src/java/org/apache/nutch/crawl/GeneratorMapper.java
new file mode 100644
index 000000000..c9ba0d163
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/GeneratorMapper.java
@@ -0,0 +1,78 @@
+package org.apache.nutch.crawl;
+
+import java.io.IOException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.nutch.crawl.Generator.SelectorEntry;
+import org.apache.nutch.net.URLFilterException;
+import org.apache.nutch.net.URLFilters;
+import org.apache.nutch.net.URLNormalizers;
+import org.apache.nutch.scoring.ScoringFilterException;
+import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.TableUtil;
+
+public class GeneratorMapper
+extends TableMapper<SelectorEntry, WebTableRow> {
+
+ private URLFilters filters;
+ private URLNormalizers normalizers;
+ private boolean filter;
+ private FetchSchedule schedule;
+ private ScoringFilters scoringFilters;
+ private long curTime;
+
+ @Override
+ public void map(ImmutableBytesWritable key, Result result,
+ Context context) throws IOException, InterruptedException {
+ String reversedUrl = Bytes.toString(key.get());
+ String url = TableUtil.unreverseUrl(reversedUrl);
+
+ WebTableRow row = new WebTableRow(result);
+
+ // If filtering is on don't generate URLs that don't pass URLFilters
+ try {
+ url = normalizers.normalize(url, URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
+ if (filter && filters.filter(url) == null)
+ return;
+ } catch (URLFilterException e) {
+ Generator.LOG.warn("Couldn't filter url: " + url + " (" + e.getMessage() + ")");
+ return;
+ }
+
+ // check fetch schedule
+ if (!schedule.shouldFetch(url, row, curTime)) {
+ if (Generator.LOG.isDebugEnabled()) {
+ Generator.LOG.debug("-shouldFetch rejected '" + url + "', fetchTime=" +
+ row.getFetchTime() + ", curTime=" + curTime);
+ }
+ return;
+ }
+
+ float score = row.getScore();
+ try {
+ score = scoringFilters.generatorSortValue(url, row, score);
+ } catch (ScoringFilterException e) {
+ // ignore
+ }
+ SelectorEntry entry = new SelectorEntry(url, score);
+ context.write(entry, row);
+
+ }
+
+ @Override
+ public void setup(Context context) {
+ Configuration conf = context.getConfiguration();
+ filters = new URLFilters(conf);
+ curTime = conf.getLong(Generator.CRAWL_GEN_CUR_TIME,
+ System.currentTimeMillis());
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
+ filter = conf.getBoolean(Generator.CRAWL_GENERATE_FILTER, true);
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
+ scoringFilters = new ScoringFilters(conf);
+ }
+}
diff --git a/src/java/org/apache/nutch/crawl/GeneratorReducer.java b/src/java/org/apache/nutch/crawl/GeneratorReducer.java
new file mode 100644
index 000000000..cb94ca928
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/GeneratorReducer.java
@@ -0,0 +1,68 @@
+package org.apache.nutch.crawl;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.mapreduce.TableReducer;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.nutch.crawl.Generator.SelectorEntry;
+import org.apache.nutch.util.hbase.WebTableRow;
+
+/** Reduce class for generate
+ *
+ * The #reduce() method write a random integer to all generated URLs. This random
+ * number is then used by {@link FetcherMapper}.
+ *
+ */
+public class GeneratorReducer
+extends TableReducer<SelectorEntry, WebTableRow, SelectorEntry> {
+
+ private long limit;
+ private long maxPerHost;
+ private long count = 0;
+ private Map<String, Integer> hostCountMap = new HashMap<String, Integer>();
+ private Random random = new Random();
+
+ @Override
+ protected void reduce(SelectorEntry key, Iterable<WebTableRow> values,
+ Context context) throws IOException, InterruptedException {
+ for (WebTableRow row : values) {
+ if (maxPerHost > 0) {
+ String host = key.host;
+ Integer hostCount = hostCountMap.get(host);
+ if (hostCount == null) {
+ hostCountMap.put(host, 0);
+ hostCount = 0;
+ }
+ if (hostCount > maxPerHost) {
+ return;
+ }
+ hostCountMap.put(host, hostCount + 1);
+ }
+ if (count >= limit) {
+ return;
+ }
+
+ row.putMeta(Generator.GENERATOR_MARK, Bytes.toBytes(random.nextInt()));
+ row.makeRowMutation().writeToContext(key, context);
+ count++;
+ }
+ }
+
+ @Override
+ protected void setup(Context context)
+ throws IOException, InterruptedException {
+ Configuration conf = context.getConfiguration();
+ long totalLimit = conf.getLong(Generator.CRAWL_TOP_N, Long.MAX_VALUE);
+ if (totalLimit == Long.MAX_VALUE) {
+ limit = Long.MAX_VALUE;
+ } else {
+ limit = totalLimit / context.getNumReduceTasks();
+ }
+ maxPerHost = conf.getLong(Generator.GENERATE_MAX_PER_HOST, -1);
+ }
+
+}
\ No newline at end of file
diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.java
index c2f0d91f6..0885f86c5 100644
--- a/src/java/org/apache/nutch/crawl/Injector.java
+++ b/src/java/org/apache/nutch/crawl/Injector.java
@@ -1,198 +1,223 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.apache.nutch.crawl;
-import java.io.*;
-import java.util.*;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
-// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-
-import org.apache.nutch.net.*;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.filter.ValueFilter;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.IdentityTableReducer;
+import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.LongWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.net.URLFilters;
+import org.apache.nutch.net.URLNormalizers;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.LogUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
-/** This class takes a flat file of URLs and adds them to the of pages to be
- * crawled. Useful for bootstrapping the system. */
-public class Injector extends Configured implements Tool {
- public static final Log LOG = LogFactory.getLog(Injector.class);
-
+public class Injector
+implements Tool {
- /** Normalize and filter injected urls. */
- public static class InjectMapper implements Mapper<WritableComparable, Text, Text, CrawlDatum> {
+ public static final Log LOG = LogFactory.getLog(Injector.class);
+
+ private static final String INJECT_KEY_STR = "__injkey__";
+ public static final byte[] INJECT_KEY =
+ Bytes.toBytes(INJECT_KEY_STR);
+
+ private static final Set<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA, INJECT_KEY));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.STATUS));
+ }
+
+ private Configuration conf;
+
+ public static class UrlMapper
+ extends Mapper<LongWritable, Text, Text, Text> {
private URLNormalizers urlNormalizers;
- private int interval;
- private float scoreInjected;
- private JobConf jobConf;
private URLFilters filters;
- private ScoringFilters scfilters;
- private long curTime;
-
- public void configure(JobConf job) {
- this.jobConf = job;
- urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_INJECT);
- interval = jobConf.getInt("db.fetch.interval.default", 2592000);
- filters = new URLFilters(jobConf);
- scfilters = new ScoringFilters(jobConf);
- scoreInjected = jobConf.getFloat("db.score.injected", 1.0f);
- curTime = job.getLong("injector.current.time", System.currentTimeMillis());
- }
-
- public void close() {}
-
- public void map(WritableComparable key, Text value,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- String url = value.toString(); // value is line of text
+ private HTable table;
+ private HBaseConfiguration hbaseConf;
+
+ @Override
+ public void map(LongWritable key, Text value, Context context)
+ throws IOException {
+ if (table == null) {
+ throw new IOException("Can not connect to hbase table");
+ }
+ String url = value.toString();
+ String reversedUrl;
try {
url = urlNormalizers.normalize(url, URLNormalizers.SCOPE_INJECT);
- url = filters.filter(url); // filter the url
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) { LOG.warn("Skipping " +url+":"+e); }
- url = null;
- }
- if (url != null) { // if it passes
- value.set(url); // collect it
- CrawlDatum datum = new CrawlDatum(CrawlDatum.STATUS_INJECTED, interval);
- datum.setFetchTime(curTime);
- datum.setScore(scoreInjected);
- try {
- scfilters.injectedScore(value, datum);
- } catch (ScoringFilterException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Cannot filter injected score for url " + url +
- ", using default (" + e.getMessage() + ")");
- }
- datum.setScore(scoreInjected);
+ url = filters.filter(url);
+ if (url == null) {
+ return;
}
- output.collect(value, datum);
+ reversedUrl = TableUtil.reverseUrl(url);
+ } catch (Exception e) {
+ LOG.warn("Skipping " + url + ":" + e);
+ return;
}
+
+ Put put = new Put(Bytes.toBytes(reversedUrl));
+ put.add(WebTableColumns.METADATA, INJECT_KEY, TableUtil.YES_VAL);
+
+ table.put(put);
}
- }
- /** Combine multiple new entries for a url. */
- public static class InjectReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- public void configure(JobConf job) {}
- public void close() {}
+ @Override
+ public void setup(Context context) {
+ Configuration conf = context.getConfiguration();
+ urlNormalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_INJECT);
+ filters = new URLFilters(conf);
+ hbaseConf = new HBaseConfiguration();
+ try {
+ table = new HTable(hbaseConf, conf.get("input.table") );
+ } catch (IOException e) {
+ e.printStackTrace(LogUtil.getFatalStream(LOG));
+ }
- private CrawlDatum old = new CrawlDatum();
- private CrawlDatum injected = new CrawlDatum();
+ }
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- boolean oldSet = false;
- while (values.hasNext()) {
- CrawlDatum val = values.next();
- if (val.getStatus() == CrawlDatum.STATUS_INJECTED) {
- injected.set(val);
- injected.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
- } else {
- old.set(val);
- oldSet = true;
+ @Override
+ public void cleanup(Context context) throws IOException {
+ table.close();
+ }
+
+ }
+
+ public static class InjectorMapper
+ extends TableMapper<Text, Text> {
+ private HTable table;
+ private float scoreInjected;
+ private FetchSchedule schedule;
+ private ScoringFilters scoringFilters;
+
+ @Override
+ public void setup(Context context) throws IOException {
+ Configuration conf = context.getConfiguration();
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
+ table = new HTable(conf.get(TableInputFormat.INPUT_TABLE));
+ scoreInjected = conf.getFloat("db.score.injected", 1.0f);
+ scoringFilters = new ScoringFilters(conf);
+ }
+
+ @Override
+ public void map(ImmutableBytesWritable key, Result result, Context context)
+ throws IOException {
+ WebTableRow row = new WebTableRow(result);
+ row.deleteMeta(INJECT_KEY);
+ if (!row.hasColumn(WebTableColumns.STATUS, null)) {
+ String url = TableUtil.unreverseUrl(Bytes.toString(key.get()));
+ // this is a new column so add necessary fields
+ row.setStatus(CrawlDatumHbase.STATUS_UNFETCHED);
+ schedule.initializeSchedule(url, row);
+ try {
+ scoringFilters.injectedScore(url, row);
+ } catch (ScoringFilterException e) {
+ row.setScore(scoreInjected);
}
}
- CrawlDatum res = null;
- if (oldSet) res = old; // don't overwrite existing value
- else res = injected;
-
- output.collect(key, res);
+ row.makeRowMutation().commit(table);
+ }
+
+ @Override
+ public void cleanup(Context context) throws IOException {
+ table.close();
}
}
- public Injector() {}
-
- public Injector(Configuration conf) {
- setConf(conf);
- }
-
- public void inject(Path crawlDb, Path urlDir) throws IOException {
+ public boolean inject(String table, Path urlDir)
+ throws IOException, InterruptedException, ClassNotFoundException {
- if (LOG.isInfoEnabled()) {
- LOG.info("Injector: starting");
- LOG.info("Injector: crawlDb: " + crawlDb);
- LOG.info("Injector: urlDir: " + urlDir);
- }
+ LOG.info("Injector: starting");
+ LOG.info("Injector: urlDir: " + urlDir);
- Path tempDir =
- new Path(getConf().get("mapred.temp.dir", ".") +
- "/inject-temp-"+
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ getConf().setLong("injector.current.time", System.currentTimeMillis());
+ getConf().set("input.table", table);
+ Job job = new NutchJob(getConf(), "inject-hbase-p1 " + urlDir);
+ FileInputFormat.addInputPath(job, urlDir);
+ job.setMapperClass(UrlMapper.class);
+ TableMapReduceUtil.initTableReducerJob(table,
+ IdentityTableReducer.class, job);
+ job.setOutputFormatClass(NullOutputFormat.class);
- // map text input file to a <url,CrawlDatum> file
- if (LOG.isInfoEnabled()) {
- LOG.info("Injector: Converting injected urls to crawl db entries.");
+ if (!job.waitForCompletion(true)) {
+ LOG.warn("Injecting new users failed!");
+ return false;
}
- JobConf sortJob = new NutchJob(getConf());
- sortJob.setJobName("inject " + urlDir);
- FileInputFormat.addInputPath(sortJob, urlDir);
- sortJob.setMapperClass(InjectMapper.class);
-
- FileOutputFormat.setOutputPath(sortJob, tempDir);
- sortJob.setOutputFormat(SequenceFileOutputFormat.class);
- sortJob.setOutputKeyClass(Text.class);
- sortJob.setOutputValueClass(CrawlDatum.class);
- sortJob.setLong("injector.current.time", System.currentTimeMillis());
- JobClient.runJob(sortJob);
-
- // merge with existing crawl db
- if (LOG.isInfoEnabled()) {
- LOG.info("Injector: Merging injected urls into crawl db.");
+ job = new NutchJob(getConf(), "inject-hbase-p2 " + urlDir);
+
+ Scan scan = TableUtil.createScanFromColumns(COLUMNS);
+ scan.setFilter(new ValueFilter(WebTableColumns.METADATA, INJECT_KEY, ValueFilter.CompareOp.EQUAL, TableUtil.YES_VAL, true));
+ TableMapReduceUtil.initTableMapperJob(table,
+ scan, InjectorMapper.class, Text.class, Text.class, job);
+ TableMapReduceUtil.initTableReducerJob(table,
+ IdentityTableReducer.class, job);
+ if (job.waitForCompletion(true)) {
+ LOG.info("Injector: done");
+ return true;
}
- JobConf mergeJob = CrawlDb.createJob(getConf(), crawlDb);
- FileInputFormat.addInputPath(mergeJob, tempDir);
- mergeJob.setReducerClass(InjectReducer.class);
- JobClient.runJob(mergeJob);
- CrawlDb.install(mergeJob, crawlDb);
-
- // clean up
- FileSystem fs = FileSystem.get(getConf());
- fs.delete(tempDir, true);
- if (LOG.isInfoEnabled()) { LOG.info("Injector: done"); }
+ return false;
+ }
+
+ @Override
+ public Configuration getConf() {
+ return conf;
}
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new Injector(), args);
- System.exit(res);
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
}
-
+
public int run(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("Usage: Injector <crawldb> <url_dir>");
+ System.err.println("Usage: Injector <webtable> <url_dir>");
return -1;
}
try {
- inject(new Path(args[0]), new Path(args[1]));
- return 0;
+ if (inject(args[0], new Path(args[1]))) {
+ return 0;
+ }
+ return -1;
} catch (Exception e) {
LOG.fatal("Injector: " + StringUtils.stringifyException(e));
return -1;
}
}
+ public static void main(String[] args) throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(),
+ new Injector(), args);
+ System.exit(res);
+ }
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.java
deleted file mode 100644
index 7d6ea5046..000000000
--- a/src/java/org/apache/nutch/crawl/LinkDb.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.io.*;
-import java.util.*;
-import java.net.*;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-
-import org.apache.nutch.net.URLFilters;
-import org.apache.nutch.net.URLNormalizers;
-import org.apache.nutch.parse.*;
-import org.apache.nutch.util.HadoopFSUtil;
-import org.apache.nutch.util.LockUtil;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-/** Maintains an inverted link map, listing incoming links for each url. */
-public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData, Text, Inlinks> {
-
- public static final Log LOG = LogFactory.getLog(LinkDb.class);
-
- public static final String CURRENT_NAME = "current";
- public static final String LOCK_NAME = ".locked";
-
- private int maxAnchorLength;
- private boolean ignoreInternalLinks;
- private URLFilters urlFilters;
- private URLNormalizers urlNormalizers;
-
- public LinkDb() {}
-
- public LinkDb(Configuration conf) {
- setConf(conf);
- }
-
- public void configure(JobConf job) {
- maxAnchorLength = job.getInt("db.max.anchor.length", 100);
- ignoreInternalLinks = job.getBoolean("db.ignore.internal.links", true);
- if (job.getBoolean(LinkDbFilter.URL_FILTERING, false)) {
- urlFilters = new URLFilters(job);
- }
- if (job.getBoolean(LinkDbFilter.URL_NORMALIZING, false)) {
- urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_LINKDB);
- }
- }
-
- public void close() {}
-
- public void map(Text key, ParseData parseData,
- OutputCollector<Text, Inlinks> output, Reporter reporter)
- throws IOException {
- String fromUrl = key.toString();
- String fromHost = getHost(fromUrl);
- if (urlNormalizers != null) {
- try {
- fromUrl = urlNormalizers.normalize(fromUrl, URLNormalizers.SCOPE_LINKDB); // normalize the url
- } catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
- fromUrl = null;
- }
- }
- if (fromUrl != null && urlFilters != null) {
- try {
- fromUrl = urlFilters.filter(fromUrl); // filter the url
- } catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
- fromUrl = null;
- }
- }
- if (fromUrl == null) return; // discard all outlinks
- Outlink[] outlinks = parseData.getOutlinks();
- Inlinks inlinks = new Inlinks();
- for (int i = 0; i < outlinks.length; i++) {
- Outlink outlink = outlinks[i];
- String toUrl = outlink.getToUrl();
-
- if (ignoreInternalLinks) {
- String toHost = getHost(toUrl);
- if (toHost == null || toHost.equals(fromHost)) { // internal link
- continue; // skip it
- }
- }
- if (urlNormalizers != null) {
- try {
- toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB); // normalize the url
- } catch (Exception e) {
- LOG.warn("Skipping " + toUrl + ":" + e);
- toUrl = null;
- }
- }
- if (toUrl != null && urlFilters != null) {
- try {
- toUrl = urlFilters.filter(toUrl); // filter the url
- } catch (Exception e) {
- LOG.warn("Skipping " + toUrl + ":" + e);
- toUrl = null;
- }
- }
- if (toUrl == null) continue;
- inlinks.clear();
- String anchor = outlink.getAnchor(); // truncate long anchors
- if (anchor.length() > maxAnchorLength) {
- anchor = anchor.substring(0, maxAnchorLength);
- }
- inlinks.add(new Inlink(fromUrl, anchor)); // collect inverted link
- output.collect(new Text(toUrl), inlinks);
- }
- }
-
- private String getHost(String url) {
- try {
- return new URL(url).getHost().toLowerCase();
- } catch (MalformedURLException e) {
- return null;
- }
- }
-
- public void invert(Path linkDb, final Path segmentsDir, boolean normalize, boolean filter, boolean force) throws IOException {
- final FileSystem fs = FileSystem.get(getConf());
- FileStatus[] files = fs.listStatus(segmentsDir, HadoopFSUtil.getPassDirectoriesFilter(fs));
- invert(linkDb, HadoopFSUtil.getPaths(files), normalize, filter, force);
- }
-
- public void invert(Path linkDb, Path[] segments, boolean normalize, boolean filter, boolean force) throws IOException {
-
- Path lock = new Path(linkDb, LOCK_NAME);
- FileSystem fs = FileSystem.get(getConf());
- LockUtil.createLockFile(fs, lock, force);
- Path currentLinkDb = new Path(linkDb, CURRENT_NAME);
- if (LOG.isInfoEnabled()) {
- LOG.info("LinkDb: starting");
- LOG.info("LinkDb: linkdb: " + linkDb);
- LOG.info("LinkDb: URL normalize: " + normalize);
- LOG.info("LinkDb: URL filter: " + filter);
- }
- JobConf job = LinkDb.createJob(getConf(), linkDb, normalize, filter);
- for (int i = 0; i < segments.length; i++) {
- if (LOG.isInfoEnabled()) {
- LOG.info("LinkDb: adding segment: " + segments[i]);
- }
- FileInputFormat.addInputPath(job, new Path(segments[i], ParseData.DIR_NAME));
- }
- try {
- JobClient.runJob(job);
- } catch (IOException e) {
- LockUtil.removeLockFile(fs, lock);
- throw e;
- }
- if (fs.exists(currentLinkDb)) {
- if (LOG.isInfoEnabled()) {
- LOG.info("LinkDb: merging with existing linkdb: " + linkDb);
- }
- // try to merge
- Path newLinkDb = FileOutputFormat.getOutputPath(job);
- job = LinkDbMerger.createMergeJob(getConf(), linkDb, normalize, filter);
- FileInputFormat.addInputPath(job, currentLinkDb);
- FileInputFormat.addInputPath(job, newLinkDb);
- try {
- JobClient.runJob(job);
- } catch (IOException e) {
- LockUtil.removeLockFile(fs, lock);
- fs.delete(newLinkDb, true);
- throw e;
- }
- fs.delete(newLinkDb, true);
- }
- LinkDb.install(job, linkDb);
- if (LOG.isInfoEnabled()) { LOG.info("LinkDb: done"); }
- }
-
- private static JobConf createJob(Configuration config, Path linkDb, boolean normalize, boolean filter) {
- Path newLinkDb =
- new Path("linkdb-" +
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
-
- JobConf job = new NutchJob(config);
- job.setJobName("linkdb " + linkDb);
-
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(LinkDb.class);
- job.setCombinerClass(LinkDbMerger.class);
- // if we don't run the mergeJob, perform normalization/filtering now
- if (normalize || filter) {
- try {
- FileSystem fs = FileSystem.get(config);
- if (!fs.exists(linkDb)) {
- job.setBoolean(LinkDbFilter.URL_FILTERING, filter);
- job.setBoolean(LinkDbFilter.URL_NORMALIZING, normalize);
- }
- } catch (Exception e) {
- LOG.warn("LinkDb createJob: " + e);
- }
- }
- job.setReducerClass(LinkDbMerger.class);
-
- FileOutputFormat.setOutputPath(job, newLinkDb);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setBoolean("mapred.output.compress", true);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(Inlinks.class);
-
- return job;
- }
-
- public static void install(JobConf job, Path linkDb) throws IOException {
- Path newLinkDb = FileOutputFormat.getOutputPath(job);
- FileSystem fs = new JobClient(job).getFs();
- Path old = new Path(linkDb, "old");
- Path current = new Path(linkDb, CURRENT_NAME);
- if (fs.exists(current)) {
- if (fs.exists(old)) fs.delete(old, true);
- fs.rename(current, old);
- }
- fs.mkdirs(linkDb);
- fs.rename(newLinkDb, current);
- if (fs.exists(old)) fs.delete(old, true);
- LockUtil.removeLockFile(fs, new Path(linkDb, LOCK_NAME));
- }
-
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new LinkDb(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Usage: LinkDb <linkdb> (-dir <segmentsDir> | <seg1> <seg2> ...) [-force] [-noNormalize] [-noFilter]");
- System.err.println("\tlinkdb\toutput LinkDb to create or update");
- System.err.println("\t-dir segmentsDir\tparent directory of several segments, OR");
- System.err.println("\tseg1 seg2 ...\t list of segment directories");
- System.err.println("\t-force\tforce update even if LinkDb appears to be locked (CAUTION advised)");
- System.err.println("\t-noNormalize\tdon't normalize link URLs");
- System.err.println("\t-noFilter\tdon't apply URLFilters to link URLs");
- return -1;
- }
- Path segDir = null;
- final FileSystem fs = FileSystem.get(getConf());
- Path db = new Path(args[0]);
- ArrayList<Path> segs = new ArrayList<Path>();
- boolean filter = true;
- boolean normalize = true;
- boolean force = false;
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-dir")) {
- segDir = new Path(args[++i]);
- FileStatus[] files = fs.listStatus(segDir, HadoopFSUtil.getPassDirectoriesFilter(fs));
- if (files != null) segs.addAll(Arrays.asList(HadoopFSUtil.getPaths(files)));
- break;
- } else if (args[i].equalsIgnoreCase("-noNormalize")) {
- normalize = false;
- } else if (args[i].equalsIgnoreCase("-noFilter")) {
- filter = false;
- } else if (args[i].equalsIgnoreCase("-force")) {
- force = true;
- } else segs.add(new Path(args[i]));
- }
- try {
- invert(db, segs.toArray(new Path[segs.size()]), normalize, filter, force);
- return 0;
- } catch (Exception e) {
- LOG.fatal("LinkDb: " + StringUtils.stringifyException(e));
- return -1;
- }
- }
-
-}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbFilter.java b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
deleted file mode 100644
index 645a3b376..000000000
--- a/src/java/org/apache/nutch/crawl/LinkDbFilter.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.io.IOException;
-import java.util.Iterator;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.nutch.net.URLFilters;
-import org.apache.nutch.net.URLNormalizers;
-
-/**
- * This class provides a way to separate the URL normalization
- * and filtering steps from the rest of LinkDb manipulation code.
- *
- * @author Andrzej Bialecki
- */
-public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
- public static final String URL_FILTERING = "linkdb.url.filters";
-
- public static final String URL_NORMALIZING = "linkdb.url.normalizer";
-
- public static final String URL_NORMALIZING_SCOPE = "linkdb.url.normalizer.scope";
-
- private boolean filter;
-
- private boolean normalize;
-
- private URLFilters filters;
-
- private URLNormalizers normalizers;
-
- private String scope;
-
- public static final Log LOG = LogFactory.getLog(LinkDbFilter.class);
-
- private Text newKey = new Text();
-
- public void configure(JobConf job) {
- filter = job.getBoolean(URL_FILTERING, false);
- normalize = job.getBoolean(URL_NORMALIZING, false);
- if (filter) {
- filters = new URLFilters(job);
- }
- if (normalize) {
- scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_LINKDB);
- normalizers = new URLNormalizers(job, scope);
- }
- }
-
- public void close() {}
-
- public void map(Text key, Inlinks value,
- OutputCollector<Text, Inlinks> output, Reporter reporter) throws IOException {
- String url = key.toString();
- Inlinks result = new Inlinks();
- if (normalize) {
- try {
- url = normalizers.normalize(url, scope); // normalize the url
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
- url = null;
- }
- }
- if (url != null && filter) {
- try {
- url = filters.filter(url); // filter the url
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
- url = null;
- }
- }
- if (url == null) return; // didn't pass the filters
- Iterator<Inlink> it = value.iterator();
- String fromUrl = null;
- while (it.hasNext()) {
- Inlink inlink = it.next();
- fromUrl = inlink.getFromUrl();
- if (normalize) {
- try {
- fromUrl = normalizers.normalize(fromUrl, scope); // normalize the url
- } catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
- fromUrl = null;
- }
- }
- if (fromUrl != null && filter) {
- try {
- fromUrl = filters.filter(fromUrl); // filter the url
- } catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
- fromUrl = null;
- }
- }
- if (fromUrl != null) {
- result.add(new Inlink(fromUrl, inlink.getAnchor()));
- }
- }
- if (result.size() > 0) { // don't collect empty inlinks
- newKey.set(url);
- output.collect(newKey, result);
- }
- }
-}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbMerger.java b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
deleted file mode 100644
index 7e6a83730..000000000
--- a/src/java/org/apache/nutch/crawl/LinkDbMerger.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.nutch.crawl;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Random;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.hadoop.util.StringUtils;
-import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.util.ToolRunner;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-/**
- * This tool merges several LinkDb-s into one, optionally filtering
- * URLs through the current URLFilters, to skip prohibited URLs and
- * links.
- *
- * <p>It's possible to use this tool just for filtering - in that case
- * only one LinkDb should be specified in arguments.</p>
- * <p>If more than one LinkDb contains information about the same URL,
- * all inlinks are accumulated, but only at most <code>db.max.inlinks</code>
- * inlinks will ever be added.</p>
- * <p>If activated, URLFilters will be applied to both the target URLs and
- * to any incoming link URL. If a target URL is prohibited, all
- * inlinks to that target will be removed, including the target URL. If
- * some of incoming links are prohibited, only they will be removed, and they
- * won't count when checking the above-mentioned maximum limit.
- *
- * @author Andrzej Bialecki
- */
-public class LinkDbMerger extends Configured implements Tool, Reducer<Text, Inlinks, Text, Inlinks> {
- private static final Log LOG = LogFactory.getLog(LinkDbMerger.class);
-
- private int maxInlinks;
-
- public LinkDbMerger() {
-
- }
-
- public LinkDbMerger(Configuration conf) {
- setConf(conf);
- }
-
- public void reduce(Text key, Iterator<Inlinks> values, OutputCollector<Text, Inlinks> output, Reporter reporter) throws IOException {
-
- Inlinks result = new Inlinks();
-
- while (values.hasNext()) {
- Inlinks inlinks = values.next();
-
- int end = Math.min(maxInlinks - result.size(), inlinks.size());
- Iterator<Inlink> it = inlinks.iterator();
- int i = 0;
- while(it.hasNext() && i++ < end) {
- result.add(it.next());
- }
- }
- if (result.size() == 0) return;
- output.collect(key, result);
-
- }
-
- public void configure(JobConf job) {
- maxInlinks = job.getInt("db.max.inlinks", 10000);
- }
-
- public void close() throws IOException { }
-
- public void merge(Path output, Path[] dbs, boolean normalize, boolean filter) throws Exception {
- JobConf job = createMergeJob(getConf(), output, normalize, filter);
- for (int i = 0; i < dbs.length; i++) {
- FileInputFormat.addInputPath(job, new Path(dbs[i], LinkDb.CURRENT_NAME));
- }
- JobClient.runJob(job);
- FileSystem fs = FileSystem.get(getConf());
- fs.mkdirs(output);
- fs.rename(FileOutputFormat.getOutputPath(job), new Path(output, LinkDb.CURRENT_NAME));
- }
-
- public static JobConf createMergeJob(Configuration config, Path linkDb, boolean normalize, boolean filter) {
- Path newLinkDb =
- new Path("linkdb-merge-" +
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
-
- JobConf job = new NutchJob(config);
- job.setJobName("linkdb merge " + linkDb);
-
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(LinkDbFilter.class);
- job.setBoolean(LinkDbFilter.URL_NORMALIZING, normalize);
- job.setBoolean(LinkDbFilter.URL_FILTERING, filter);
- job.setReducerClass(LinkDbMerger.class);
-
- FileOutputFormat.setOutputPath(job, newLinkDb);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setBoolean("mapred.output.compress", true);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(Inlinks.class);
-
- return job;
- }
-
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new LinkDbMerger(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Usage: LinkDbMerger <output_linkdb> <linkdb1> [<linkdb2> <linkdb3> ...] [-normalize] [-filter]");
- System.err.println("\toutput_linkdb\toutput LinkDb");
- System.err.println("\tlinkdb1 ...\tinput LinkDb-s (single input LinkDb is ok)");
- System.err.println("\t-normalize\tuse URLNormalizer on both fromUrls and toUrls in linkdb(s) (usually not needed)");
- System.err.println("\t-filter\tuse URLFilters on both fromUrls and toUrls in linkdb(s)");
- return -1;
- }
- Path output = new Path(args[0]);
- ArrayList<Path> dbs = new ArrayList<Path>();
- boolean normalize = false;
- boolean filter = false;
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-filter")) {
- filter = true;
- } else if (args[i].equals("-normalize")) {
- normalize = true;
- } else dbs.add(new Path(args[i]));
- }
- try {
- merge(output, dbs.toArray(new Path[dbs.size()]), normalize, filter);
- return 0;
- } catch (Exception e) {
- LOG.fatal("LinkDbMerger: " + StringUtils.stringifyException(e));
- return -1;
- }
- }
-
-}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.java
deleted file mode 100644
index 0c23f8b3a..000000000
--- a/src/java/org/apache/nutch/crawl/LinkDbReader.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.io.IOException;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.mapred.lib.HashPartitioner;
-import org.apache.hadoop.util.*;
-import org.apache.hadoop.conf.Configuration;
-
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-import java.util.Iterator;
-
-/** . */
-public class LinkDbReader extends Configured implements Tool, Closeable {
- public static final Log LOG = LogFactory.getLog(LinkDbReader.class);
-
- private static final Partitioner<WritableComparable, Writable> PARTITIONER = new HashPartitioner<WritableComparable, Writable>();
-
- private FileSystem fs;
- private Path directory;
- private MapFile.Reader[] readers;
-
- public LinkDbReader() {
-
- }
-
- public LinkDbReader(Configuration conf, Path directory) throws Exception {
- setConf(conf);
- init(directory);
- }
-
- public void init(Path directory) throws Exception {
- this.fs = FileSystem.get(getConf());
- this.directory = directory;
- }
-
- public String[] getAnchors(Text url) throws IOException {
- Inlinks inlinks = getInlinks(url);
- if (inlinks == null)
- return null;
- return inlinks.getAnchors();
- }
-
- public Inlinks getInlinks(Text url) throws IOException {
-
- if (readers == null) {
- synchronized(this) {
- readers = MapFileOutputFormat.getReaders
- (fs, new Path(directory, LinkDb.CURRENT_NAME), getConf());
- }
- }
-
- return (Inlinks)MapFileOutputFormat.getEntry
- (readers, PARTITIONER, url, new Inlinks());
- }
-
- public void close() throws IOException {
- if (readers != null) {
- for (int i = 0; i < readers.length; i++) {
- readers[i].close();
- }
- }
- }
-
- public void processDumpJob(String linkdb, String output) throws IOException {
-
- if (LOG.isInfoEnabled()) {
- LOG.info("LinkDb dump: starting");
- LOG.info("LinkDb db: " + linkdb);
- }
- Path outFolder = new Path(output);
-
- JobConf job = new NutchJob(getConf());
- job.setJobName("read " + linkdb);
-
- FileInputFormat.addInputPath(job, new Path(linkdb, LinkDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
-
- FileOutputFormat.setOutputPath(job, outFolder);
- job.setOutputFormat(TextOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(Inlinks.class);
-
- JobClient.runJob(job);
- }
-
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new LinkDbReader(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Usage: LinkDbReader <linkdb> {-dump <out_dir> | -url <url>)");
- System.err.println("\t-dump <out_dir>\tdump whole link db to a text file in <out_dir>");
- System.err.println("\t-url <url>\tprint information about <url> to System.out");
- return -1;
- }
- try {
- if (args[1].equals("-dump")) {
- processDumpJob(args[0], args[2]);
- return 0;
- } else if (args[1].equals("-url")) {
- init(new Path(args[0]));
- Inlinks links = getInlinks(new Text(args[2]));
- if (links == null) {
- System.out.println(" - no link information.");
- } else {
- Iterator<Inlink> it = links.iterator();
- while (it.hasNext()) {
- System.out.println(it.next().toString());
- }
- }
- return 0;
- } else {
- System.err.println("Error: wrong argument " + args[1]);
- return -1;
- }
- } catch (Exception e) {
- LOG.fatal("LinkDbReader: " + StringUtils.stringifyException(e));
- return -1;
- }
- }
-}
diff --git a/src/java/org/apache/nutch/crawl/MD5Signature.java b/src/java/org/apache/nutch/crawl/MD5Signature.java
index ddcfce429..9f0ab161d 100644
--- a/src/java/org/apache/nutch/crawl/MD5Signature.java
+++ b/src/java/org/apache/nutch/crawl/MD5Signature.java
@@ -17,9 +17,14 @@
package org.apache.nutch.crawl;
+import java.util.Collection;
+import java.util.HashSet;
+
import org.apache.hadoop.io.MD5Hash;
import org.apache.nutch.parse.Parse;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* Default implementation of a page signature. It calculates an MD5 hash
@@ -30,10 +35,20 @@ import org.apache.nutch.protocol.Content;
*/
public class MD5Signature extends Signature {
- public byte[] calculate(Content content, Parse parse) {
- byte[] data = content.getContent();
- if (data == null) data = content.getUrl().getBytes();
- StringBuilder buf = new StringBuilder().append(data).append(parse.getText());
- return MD5Hash.digest(buf.toString().getBytes()).getDigest();
+ private final static Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.CONTENT));
+ }
+
+ @Override
+ public byte[] calculate(WebTableRow row, Parse parse) {
+ byte[] data = row.getContent();
+ return MD5Hash.digest(data).getDigest();
+ }
+
+ @Override
+ public Collection<HbaseColumn> getColumns() {
+ return COLUMNS;
}
}
diff --git a/src/java/org/apache/nutch/crawl/NutchWritable.java b/src/java/org/apache/nutch/crawl/NutchWritable.java
index ef5f00978..e42853c4b 100644
--- a/src/java/org/apache/nutch/crawl/NutchWritable.java
+++ b/src/java/org/apache/nutch/crawl/NutchWritable.java
@@ -41,13 +41,15 @@ public class NutchWritable extends GenericWritableConfigurable {
org.apache.nutch.parse.Outlink.class,
org.apache.nutch.parse.ParseText.class,
org.apache.nutch.parse.ParseData.class,
- org.apache.nutch.parse.ParseImpl.class,
org.apache.nutch.parse.ParseStatus.class,
org.apache.nutch.protocol.Content.class,
org.apache.nutch.protocol.ProtocolStatus.class,
org.apache.nutch.searcher.Hit.class,
org.apache.nutch.searcher.HitDetails.class,
- org.apache.nutch.searcher.Hits.class
+ org.apache.nutch.searcher.Hits.class,
+ org.apache.nutch.scoring.ScoreDatum.class,
+ org.apache.nutch.util.hbase.WebTableRow.class,
+ org.apache.hadoop.hbase.client.Result.class
};
}
diff --git a/src/java/org/apache/nutch/crawl/PartitionSelectorByHost.java b/src/java/org/apache/nutch/crawl/PartitionSelectorByHost.java
new file mode 100644
index 000000000..154fc48c8
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/PartitionSelectorByHost.java
@@ -0,0 +1,16 @@
+package org.apache.nutch.crawl;
+
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.nutch.crawl.Generator.SelectorEntry;
+import org.apache.nutch.util.hbase.WebTableRow;
+
+public class PartitionSelectorByHost extends Partitioner<SelectorEntry, WebTableRow> {
+
+ @Override
+ public int getPartition(SelectorEntry key, WebTableRow value,
+ int numPartitions) {
+ int hashCode = key.host.hashCode();
+
+ return (hashCode & Integer.MAX_VALUE) % numPartitions;
+ }
+}
diff --git a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java
deleted file mode 100644
index f1248e5d5..000000000
--- a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.net.URL;
-import java.net.MalformedURLException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.nutch.net.URLNormalizers;
-
-/** Partition urls by hostname. */
-public class PartitionUrlByHost implements Partitioner<Text, Writable> {
- private static final Log LOG = LogFactory.getLog(PartitionUrlByHost.class);
-
- private int seed;
- private URLNormalizers normalizers;
-
- public void configure(JobConf job) {
- seed = job.getInt("partition.url.by.host.seed", 0);
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_PARTITION);
- }
-
- public void close() {}
-
- /** Hash by hostname. */
- public int getPartition(Text key, Writable value,
- int numReduceTasks) {
- String urlString = key.toString();
- try {
- urlString = normalizers.normalize(urlString, URLNormalizers.SCOPE_PARTITION);
- } catch (Exception e) {
- LOG.warn("Malformed URL: '" + urlString + "'");
- }
- URL url = null;
- try {
- url = new URL(urlString);
- } catch (MalformedURLException e) {
- LOG.warn("Malformed URL: '" + urlString + "'");
- }
- int hashCode = (url==null ? urlString : url.getHost()).hashCode();
-
- // make hosts wind up in different partitions on different runs
- hashCode ^= seed;
-
- return (hashCode & Integer.MAX_VALUE) % numReduceTasks;
- }
-
-}
-
-
diff --git a/src/java/org/apache/nutch/crawl/Signature.java b/src/java/org/apache/nutch/crawl/Signature.java
index d10e0f927..37a04a456 100644
--- a/src/java/org/apache/nutch/crawl/Signature.java
+++ b/src/java/org/apache/nutch/crawl/Signature.java
@@ -17,21 +17,16 @@
package org.apache.nutch.crawl;
+import java.util.Collection;
+
import org.apache.nutch.parse.Parse;
-import org.apache.nutch.protocol.Content;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configurable;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.hadoop.conf.Configured;
-public abstract class Signature implements Configurable {
- protected Configuration conf;
+public abstract class Signature extends Configured {
- public abstract byte[] calculate(Content content, Parse parse);
-
- public Configuration getConf() {
- return conf;
- }
-
- public void setConf(Configuration conf) {
- this.conf = conf;
- }
+ public abstract byte[] calculate(WebTableRow row, Parse parse);
+
+ public abstract Collection<HbaseColumn> getColumns();
}
diff --git a/src/java/org/apache/nutch/crawl/SignatureComparator.java b/src/java/org/apache/nutch/crawl/SignatureComparator.java
index 574c47f4d..fe0589755 100644
--- a/src/java/org/apache/nutch/crawl/SignatureComparator.java
+++ b/src/java/org/apache/nutch/crawl/SignatureComparator.java
@@ -17,23 +17,13 @@
package org.apache.nutch.crawl;
-import java.util.Comparator;
-
-public class SignatureComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return _compare(o1, o2);
- }
+public class SignatureComparator {
+ public static int compare(byte[] data1, byte[] data2) {
+ if (data1 == null && data2 == null) return 0;
+ if (data1 == null) return -1;
+ if (data2 == null) return 1;
+ return _compare(data1, 0, data1.length, data2, 0, data2.length); }
- public static int _compare(Object o1, Object o2) {
- if (o1 == null && o2 == null) return 0;
- if (o1 == null) return -1;
- if (o2 == null) return 1;
- if (!(o1 instanceof byte[])) return -1;
- if (!(o2 instanceof byte[])) return 1;
- byte[] data1 = (byte[])o1;
- byte[] data2 = (byte[])o2;
- return _compare(data1, 0, data1.length, data2, 0, data2.length);
- }
public static int _compare(byte[] data1, int s1, int l1, byte[] data2, int s2, int l2) {
if (l2 > l1) return -1;
diff --git a/src/java/org/apache/nutch/crawl/SignatureFactory.java b/src/java/org/apache/nutch/crawl/SignatureFactory.java
index 65d51690b..83fcbfd5e 100644
--- a/src/java/org/apache/nutch/crawl/SignatureFactory.java
+++ b/src/java/org/apache/nutch/crawl/SignatureFactory.java
@@ -18,12 +18,15 @@
package org.apache.nutch.crawl;
// Commons Logging imports
+import java.util.Collection;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.ObjectCache;
+import org.apache.nutch.util.hbase.HbaseColumn;
/**
* Factory class, which instantiates a Signature implementation according to the
@@ -44,10 +47,8 @@ public class SignatureFactory {
Signature impl = (Signature)objectCache.getObject(clazz);
if (impl == null) {
try {
- if (LOG.isInfoEnabled()) {
- LOG.info("Using Signature impl: " + clazz);
- }
- Class implClass = Class.forName(clazz);
+ LOG.info("Using Signature impl: " + clazz);
+ Class<?> implClass = Class.forName(clazz);
impl = (Signature)implClass.newInstance();
impl.setConf(conf);
objectCache.setObject(clazz, impl);
@@ -57,4 +58,9 @@ public class SignatureFactory {
}
return impl;
}
+
+ public static Collection<HbaseColumn> getColumns(Configuration conf) {
+ Signature impl = getSignature(conf);
+ return impl.getColumns();
+ }
}
diff --git a/src/java/org/apache/nutch/crawl/TableUpdateMapper.java b/src/java/org/apache/nutch/crawl/TableUpdateMapper.java
new file mode 100644
index 000000000..4bd477293
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/TableUpdateMapper.java
@@ -0,0 +1,67 @@
+package org.apache.nutch.crawl;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.scoring.ScoreDatum;
+import org.apache.nutch.scoring.ScoringFilterException;
+import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.TableUtil;
+
+public class TableUpdateMapper
+extends TableMapper<ImmutableBytesWritable, NutchWritable> {
+ public static final Log LOG = TableUpdater.LOG;
+
+ private ScoringFilters scoringFilters;
+
+ private List<ScoreDatum> scoreData = new ArrayList<ScoreDatum>();
+
+ @Override
+ public void map(ImmutableBytesWritable key, Result result, Context context)
+ throws IOException, InterruptedException {
+
+ String url = TableUtil.unreverseUrl(Bytes.toString(key.get()));
+ WebTableRow row = new WebTableRow(result);
+
+ Collection<Outlink> outlinks = row.getOutlinks();
+
+ scoreData.clear();
+ for (Outlink outlink : outlinks) {
+ scoreData.add(new ScoreDatum(0.0f, outlink.getToUrl(), outlink.getAnchor()));
+ }
+
+ // TODO: Outlink filtering (i.e. "only keep the first n outlinks")
+ try {
+ scoringFilters.distributeScoreToOutlinks(url, row, scoreData, outlinks.size());
+ } catch (ScoringFilterException e) {
+ LOG.warn("Distributing score failed for URL: " + key +
+ " exception:" + StringUtils.stringifyException(e));
+ }
+
+ context.write(key, new NutchWritable(row));
+
+ for (ScoreDatum scoreDatum : scoreData) {
+ String reversedOut = TableUtil.reverseUrl(scoreDatum.getUrl());
+ ImmutableBytesWritable outKey =
+ new ImmutableBytesWritable(reversedOut.getBytes());
+ scoreDatum.setUrl(url);
+ context.write(outKey, new NutchWritable(scoreDatum));
+ }
+ }
+
+ @Override
+ public void setup(Context context) {
+ scoringFilters = new ScoringFilters(context.getConfiguration());
+ }
+
+}
diff --git a/src/java/org/apache/nutch/crawl/TableUpdateReducer.java b/src/java/org/apache/nutch/crawl/TableUpdateReducer.java
new file mode 100644
index 000000000..5a7e649fc
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/TableUpdateReducer.java
@@ -0,0 +1,163 @@
+package org.apache.nutch.crawl;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableReducer;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.nutch.crawl.CrawlDb;
+import org.apache.nutch.crawl.FetchSchedule;
+import org.apache.nutch.crawl.Inlink;
+import org.apache.nutch.crawl.NutchWritable;
+import org.apache.nutch.crawl.SignatureComparator;
+import org.apache.nutch.fetcher.Fetcher;
+import org.apache.nutch.parse.TableParser;
+import org.apache.nutch.scoring.ScoreDatum;
+import org.apache.nutch.scoring.ScoringFilterException;
+import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
+import org.apache.nutch.util.hbase.WebTableRow;
+
+public class TableUpdateReducer
+extends TableReducer<ImmutableBytesWritable, NutchWritable, ImmutableBytesWritable> {
+
+ public static final Log LOG = TableUpdater.LOG;
+
+ private int retryMax;
+ private boolean additionsAllowed;
+ private int maxInterval;
+ private FetchSchedule schedule;
+ private ScoringFilters scoringFilters;
+ private List<ScoreDatum> inlinkedScoreData = new ArrayList<ScoreDatum>();
+
+ @Override
+ protected void setup(Context context) throws IOException, InterruptedException {
+ Configuration conf = context.getConfiguration();
+ retryMax = conf.getInt("db.fetch.retry.max", 3);
+ additionsAllowed = conf.getBoolean(CrawlDb.CRAWLDB_ADDITIONS_ALLOWED, true);
+ maxInterval = conf.getInt("db.fetch.interval.max", 0 );
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
+ scoringFilters = new ScoringFilters(conf);
+ }
+
+ @Override
+ protected void reduce(ImmutableBytesWritable key, Iterable<NutchWritable> values,
+ Context context) throws IOException, InterruptedException {
+
+ WebTableRow row = null;
+ inlinkedScoreData.clear();
+
+ for (NutchWritable nutchWritable : values) {
+ Writable val = nutchWritable.get();
+ if (val instanceof WebTableRow) {
+ row = (WebTableRow) val;
+ } else {
+ inlinkedScoreData.add((ScoreDatum) val);
+ }
+ }
+ String url;
+ try {
+ url = TableUtil.unreverseUrl(Bytes.toString(key.get()));
+ } catch (Exception e) {
+ // this can happen because a newly discovered malformed link
+ // may slip by url filters
+ // TODO: Find a better solution
+ return;
+ }
+
+ if (row == null) { // new row
+ if (!additionsAllowed) {
+ return;
+ }
+ row = new WebTableRow(key.get());
+ schedule.initializeSchedule(url, row);
+ row.setStatus(CrawlDatumHbase.STATUS_UNFETCHED);
+ try {
+ scoringFilters.initialScore(url, row);
+ } catch (ScoringFilterException e) {
+ row.setScore(0.0f);
+ }
+ } else {
+ if (row.hasMeta(Fetcher.REDIRECT_DISCOVERED) && !row.hasColumn(WebTableColumns.STATUS, null)) {
+ // this row is marked during fetch as the destination of a redirect
+ // but does not contain anything else, so we initialize it.
+ schedule.initializeSchedule(url, row);
+ row.setStatus(CrawlDatumHbase.STATUS_UNFETCHED);
+ try {
+ scoringFilters.initialScore(url, row);
+ } catch (ScoringFilterException e) {
+ row.setScore(0.0f);
+ }
+ } else { // update row
+ byte status = row.getStatus();
+ switch (status) {
+ case CrawlDatumHbase.STATUS_FETCHED: // succesful fetch
+ case CrawlDatumHbase.STATUS_REDIR_TEMP: // successful fetch, redirected
+ case CrawlDatumHbase.STATUS_REDIR_PERM:
+ case CrawlDatumHbase.STATUS_NOTMODIFIED: // successful fetch, notmodified
+ int modified = FetchSchedule.STATUS_UNKNOWN;
+ if (status == CrawlDatumHbase.STATUS_NOTMODIFIED) {
+ modified = FetchSchedule.STATUS_NOTMODIFIED;
+ }
+ byte[] prevSig = row.getPrevSignature();
+ byte[] signature = row.getSignature();
+ if (prevSig != null && signature != null) {
+ if (SignatureComparator.compare(prevSig, signature) != 0) {
+ modified = FetchSchedule.STATUS_MODIFIED;
+ } else {
+ modified = FetchSchedule.STATUS_NOTMODIFIED;
+ }
+ }
+ long fetchTime = row.getFetchTime();
+ long prevFetchTime = row.getPrevFetchTime();
+ long modifiedTime = row.getModifiedTime();
+
+ schedule.setFetchSchedule(url, row, prevFetchTime, 0L,
+ fetchTime, modifiedTime, modified);
+ if (maxInterval < row.getFetchInterval())
+ schedule.forceRefetch(url, row, false);
+ break;
+ case CrawlDatumHbase.STATUS_RETRY:
+ schedule.setPageRetrySchedule(url, row, 0L, 0L, row.getFetchTime());
+ if (row.getRetriesSinceFetch() < retryMax) {
+ row.setStatus(CrawlDatumHbase.STATUS_UNFETCHED);
+ } else {
+ row.setStatus(CrawlDatumHbase.STATUS_GONE);
+ }
+ break;
+ case CrawlDatumHbase.STATUS_GONE:
+ schedule.setPageGoneSchedule(url, row, 0L, 0L, row.getFetchTime());
+ break;
+ }
+ }
+ }
+
+ row.deleteAllInlinks();
+ for (ScoreDatum inlink : inlinkedScoreData) {
+ row.addInlink(new Inlink(inlink.getUrl(), inlink.getAnchor()));
+ }
+
+ try {
+ scoringFilters.updateScore(url, row, inlinkedScoreData);
+ } catch (ScoringFilterException e) {
+ LOG.warn("Scoring filters failed with exception " +
+ StringUtils.stringifyException(e));
+ }
+
+ // clear markers
+ row.deleteMeta(Fetcher.REDIRECT_DISCOVERED);
+ row.deleteMeta(Generator.GENERATOR_MARK);
+ row.deleteMeta(Fetcher.FETCH_MARK);
+ row.deleteMeta(TableParser.PARSE_MARK);
+
+ row.makeRowMutation(key.get()).writeToContext(key, context);
+ }
+
+}
diff --git a/src/java/org/apache/nutch/crawl/TableUpdater.java b/src/java/org/apache/nutch/crawl/TableUpdater.java
new file mode 100644
index 000000000..e2368b189
--- /dev/null
+++ b/src/java/org/apache/nutch/crawl/TableUpdater.java
@@ -0,0 +1,81 @@
+package org.apache.nutch.crawl;
+
+import java.util.Collection;
+import java.util.HashSet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.crawl.NutchWritable;
+import org.apache.nutch.fetcher.Fetcher;
+import org.apache.nutch.parse.TableParser;
+import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
+
+public class TableUpdater extends Configured
+implements Tool {
+
+ public static final Log LOG = LogFactory.getLog(TableUpdater.class);
+
+
+ private static final Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.OUTLINKS));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.INLINKS));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.STATUS));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA, TableParser.PARSE_MARK));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA, Fetcher.REDIRECT_DISCOVERED));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.RETRIES));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.FETCH_TIME));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.MODIFIED_TIME));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.FETCH_INTERVAL));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.PREV_FETCH_TIME));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.PREV_SIGNATURE));
+ }
+
+ private void updateTable(String table) throws Exception {
+ LOG.info("TableUpdater: starting");
+ LOG.info("TableUpdater: table: " + table);
+ Job job = new NutchJob(getConf(), "update-table " + table);
+ //job.setBoolean(ALL, updateAll);
+ job.setJobName("update-table " + table);
+ ScoringFilters scoringFilters = new ScoringFilters(getConf());
+ HashSet<HbaseColumn> columns = new HashSet<HbaseColumn>(COLUMNS);
+ columns.addAll(scoringFilters.getColumns());
+ TableMapReduceUtil.initTableMapperJob(table, TableUtil.createScanFromColumns(columns),
+ TableUpdateMapper.class, ImmutableBytesWritable.class,
+ NutchWritable.class, job);
+ TableMapReduceUtil.initTableReducerJob(table, TableUpdateReducer.class, job);
+
+ job.waitForCompletion(true);
+ LOG.info("TableUpdater: done");
+ }
+
+ public int run(String[] args) throws Exception {
+ String usage = "Usage: TableUpdater <webtable>";
+
+ if (args.length < 1) {
+ System.err.println(usage);
+ System.exit(-1);
+ }
+
+ updateTable(args[0]);
+ return 0;
+ }
+
+ public static void main(String[] args) throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(), new TableUpdater(), args);
+ System.exit(res);
+ }
+
+}
diff --git a/src/java/org/apache/nutch/crawl/TextProfileSignature.java b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
index e1b28caf5..77d92098f 100644
--- a/src/java/org/apache/nutch/crawl/TextProfileSignature.java
+++ b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
@@ -17,22 +17,20 @@
package org.apache.nutch.crawl;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStreamReader;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import org.apache.hadoop.io.MD5Hash;
+
import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseImpl;
-import org.apache.nutch.protocol.Content;
-import org.apache.nutch.util.StringUtil;
-import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* <p>An implementation of a page signature. It calculates an MD5 hash
@@ -60,16 +58,22 @@ import org.apache.nutch.util.NutchConfiguration;
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class TextProfileSignature extends Signature {
+
+ private final static Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.CONTENT));
+ }
Signature fallback = new MD5Signature();
- public byte[] calculate(Content content, Parse parse) {
+ public byte[] calculate(WebTableRow row, Parse parse) {
int MIN_TOKEN_LEN = getConf().getInt("db.signature.text_profile.min_token_len", 2);
float QUANT_RATE = getConf().getFloat("db.signature.text_profile.quant_rate", 0.01f);
HashMap<String, Token> tokens = new HashMap<String, Token>();
String text = null;
if (parse != null) text = parse.getText();
- if (text == null || text.length() == 0) return fallback.calculate(content, parse);
+ if (text == null || text.length() == 0) return fallback.calculate(row, parse);
StringBuffer curToken = new StringBuffer();
int maxFreq = 0;
for (int i = 0; i < text.length(); i++) {
@@ -133,6 +137,10 @@ public class TextProfileSignature extends Signature {
}
return MD5Hash.digest(newText.toString()).getDigest();
}
+
+ public Collection<HbaseColumn> getColumns() {
+ return COLUMNS;
+ }
private static class Token {
public int cnt;
@@ -153,30 +161,4 @@ public class TextProfileSignature extends Signature {
return t2.cnt - t1.cnt;
}
}
-
- public static void main(String[] args) throws Exception {
- TextProfileSignature sig = new TextProfileSignature();
- sig.setConf(NutchConfiguration.create());
- HashMap<String, byte[]> res = new HashMap<String, byte[]>();
- File[] files = new File(args[0]).listFiles();
- for (int i = 0; i < files.length; i++) {
- FileInputStream fis = new FileInputStream(files[i]);
- BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
- StringBuffer text = new StringBuffer();
- String line = null;
- while ((line = br.readLine()) != null) {
- if (text.length() > 0) text.append("\n");
- text.append(line);
- }
- br.close();
- byte[] signature = sig.calculate(null, new ParseImpl(text.toString(), null));
- res.put(files[i].toString(), signature);
- }
- Iterator<String> it = res.keySet().iterator();
- while (it.hasNext()) {
- String name = it.next();
- byte[] signature = res.get(name);
- System.out.println(name + "\t" + StringUtil.toHexString(signature));
- }
- }
}
diff --git a/src/java/org/apache/nutch/fetcher/FetchEntry.java b/src/java/org/apache/nutch/fetcher/FetchEntry.java
new file mode 100644
index 000000000..5e7b3f158
--- /dev/null
+++ b/src/java/org/apache/nutch/fetcher/FetchEntry.java
@@ -0,0 +1,49 @@
+package org.apache.nutch.fetcher;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.io.Writable;
+
+public class FetchEntry implements Writable {
+
+ private ImmutableBytesWritable key;
+ private Result row;
+
+ public FetchEntry() {
+ key = new ImmutableBytesWritable();
+ row = new Result();
+ }
+
+ public FetchEntry(FetchEntry fe) {
+ this.key = new ImmutableBytesWritable(fe.key.get().clone());
+ }
+
+ public FetchEntry(ImmutableBytesWritable key, Result row) {
+ this.key = key;
+ this.row = row;
+ }
+
+ @Override
+ public void readFields(DataInput in) throws IOException {
+ key.readFields(in);
+ row.readFields(in);
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ key.write(out);
+ row.write(out);
+ }
+
+ public ImmutableBytesWritable getKey() {
+ return key;
+ }
+
+ public Result getRow() {
+ return row;
+ }
+}
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index 4b6c2b6a4..1f5c72cf6 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -1,1042 +1,161 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
package org.apache.nutch.fetcher;
import java.io.IOException;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
-// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.StringUtils;
-
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.NutchWritable;
-import org.apache.nutch.crawl.SignatureFactory;
-import org.apache.nutch.metadata.Metadata;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.net.*;
-import org.apache.nutch.protocol.*;
-import org.apache.nutch.parse.*;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.*;
-
-
-/**
- * A queue-based fetcher.
- *
- * <p>This fetcher uses a well-known model of one producer (a QueueFeeder)
- * and many consumers (FetcherThread-s).
- *
- * <p>QueueFeeder reads input fetchlists and
- * populates a set of FetchItemQueue-s, which hold FetchItem-s that
- * describe the items to be fetched. There are as many queues as there are unique
- * hosts, but at any given time the total number of fetch items in all queues
- * is less than a fixed number (currently set to a multiple of the number of
- * threads).
- *
- * <p>As items are consumed from the queues, the QueueFeeder continues to add new
- * input items, so that their total count stays fixed (FetcherThread-s may also
- * add new items to the queues e.g. as a results of redirection) - until all
- * input items are exhausted, at which point the number of items in the queues
- * begins to decrease. When this number reaches 0 fetcher will finish.
- *
- * <p>This fetcher implementation handles per-host blocking itself, instead
- * of delegating this work to protocol-specific plugins.
- * Each per-host queue handles its own "politeness" settings, such as the
- * maximum number of concurrent requests and crawl delay between consecutive
- * requests - and also a list of requests in progress, and the time the last
- * request was finished. As FetcherThread-s ask for new items to be fetched,
- * queues may return eligible items or null if for "politeness" reasons this
- * host's queue is not yet ready.
- *
- * <p>If there are still unfetched items in the queues, but none of the items
- * are ready, FetcherThread-s will spin-wait until either some items become
- * available, or a timeout is reached (at which point the Fetcher will abort,
- * assuming the task is hung).
- *
- * @author Andrzej Bialecki
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.filter.Filter;
+import org.apache.hadoop.hbase.filter.FilterList;
+import org.apache.hadoop.hbase.filter.ValueFilter;
+import org.apache.hadoop.hbase.filter.FilterList.Operator;
+import org.apache.hadoop.hbase.filter.ValueFilter.CompareOp;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.crawl.Generator;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
+
+/** Multi-threaded fetcher.
+ *
*/
-public class Fetcher extends Configured implements
- MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
-
- public static final int PERM_REFRESH_TIME = 5;
-
- public static final String CONTENT_REDIR = "content";
-
- public static final String PROTOCOL_REDIR = "protocol";
-
- public static final Log LOG = LogFactory.getLog(Fetcher.class);
-
- public static class InputFormat extends SequenceFileInputFormat<Text, CrawlDatum> {
- /** Don't split inputs, to keep things polite. */
- public InputSplit[] getSplits(JobConf job, int nSplits)
- throws IOException {
- FileStatus[] files = listStatus(job);
- FileSplit[] splits = new FileSplit[files.length];
- for (int i = 0; i < files.length; i++) {
- FileStatus cur = files[i];
- splits[i] = new FileSplit(cur.getPath(), 0,
- cur.getLen(), (String[])null);
- }
- return splits;
- }
- }
-
- private OutputCollector<Text, NutchWritable> output;
- private Reporter reporter;
+public class Fetcher
+implements Tool {
- private String segmentName;
- private AtomicInteger activeThreads = new AtomicInteger(0);
- private AtomicInteger spinWaiting = new AtomicInteger(0);
-
- private long start = System.currentTimeMillis(); // start time of fetcher run
- private AtomicLong lastRequestStart = new AtomicLong(start);
-
- private AtomicLong bytes = new AtomicLong(0); // total bytes fetched
- private AtomicInteger pages = new AtomicInteger(0); // total pages fetched
- private AtomicInteger errors = new AtomicInteger(0); // total pages errored
-
- private boolean storingContent;
- private boolean parsing;
- FetchItemQueues fetchQueues;
- QueueFeeder feeder;
+ public static final String PROTOCOL_REDIR = "protocol";
- /**
- * This class described the item to be fetched.
- */
- private static class FetchItem {
- String queueID;
- Text url;
- URL u;
- CrawlDatum datum;
-
- public FetchItem(Text url, URL u, CrawlDatum datum, String queueID) {
- this.url = url;
- this.u = u;
- this.datum = datum;
- this.queueID = queueID;
- }
-
- /** Create an item. Queue id will be created based on <code>byIP</code>
- * argument, either as a protocol + hostname pair, or protocol + IP
- * address pair.
- */
- public static FetchItem create(Text url, CrawlDatum datum, boolean byIP) {
- String queueID;
- URL u = null;
- try {
- u = new URL(url.toString());
- } catch (Exception e) {
- LOG.warn("Cannot parse url: " + url, e);
- return null;
- }
- String proto = u.getProtocol().toLowerCase();
- String host;
- if (byIP) {
- try {
- InetAddress addr = InetAddress.getByName(u.getHost());
- host = addr.getHostAddress();
- } catch (UnknownHostException e) {
- // unable to resolve it, so don't fall back to host name
- LOG.warn("Unable to resolve: " + u.getHost() + ", skipping.");
- return null;
- }
- } else {
- host = u.getHost();
- if (host == null) {
- LOG.warn("Unknown host for url: " + url + ", skipping.");
- return null;
- }
- host = host.toLowerCase();
- }
- queueID = proto + "://" + host;
- return new FetchItem(url, u, datum, queueID);
- }
-
- public CrawlDatum getDatum() {
- return datum;
- }
+ public static final int PERM_REFRESH_TIME = 5;
- public String getQueueID() {
- return queueID;
- }
+ public static final byte[] REDIRECT_DISCOVERED =
+ Bytes.toBytes("___rdrdsc__");
- public Text getUrl() {
- return url;
- }
-
- public URL getURL2() {
- return u;
- }
- }
+ public static final byte[] FETCH_MARK =
+ Bytes.toBytes("__ftchmrk__");
- /**
- * This class handles FetchItems which come from the same host ID (be it
- * a proto/hostname or proto/IP pair). It also keeps track of requests in
- * progress and elapsed time between requests.
- */
- private static class FetchItemQueue {
- List<FetchItem> queue = Collections.synchronizedList(new LinkedList<FetchItem>());
- Set<FetchItem> inProgress = Collections.synchronizedSet(new HashSet<FetchItem>());
- AtomicLong nextFetchTime = new AtomicLong();
- long crawlDelay;
- long minCrawlDelay;
- int maxThreads;
- Configuration conf;
-
- public FetchItemQueue(Configuration conf, int maxThreads, long crawlDelay, long minCrawlDelay) {
- this.conf = conf;
- this.maxThreads = maxThreads;
- this.crawlDelay = crawlDelay;
- this.minCrawlDelay = minCrawlDelay;
- // ready to start
- setEndTime(System.currentTimeMillis() - crawlDelay);
- }
-
- public int getQueueSize() {
- return queue.size();
- }
-
- public int getInProgressSize() {
- return inProgress.size();
- }
-
- public void finishFetchItem(FetchItem it, boolean asap) {
- if (it != null) {
- inProgress.remove(it);
- setEndTime(System.currentTimeMillis(), asap);
- }
- }
-
- public void addFetchItem(FetchItem it) {
- if (it == null) return;
- queue.add(it);
- }
-
- public void addInProgressFetchItem(FetchItem it) {
- if (it == null) return;
- inProgress.add(it);
- }
-
- public FetchItem getFetchItem() {
- if (inProgress.size() >= maxThreads) return null;
- long now = System.currentTimeMillis();
- if (nextFetchTime.get() > now) return null;
- FetchItem it = null;
- if (queue.size() == 0) return null;
- try {
- it = queue.remove(0);
- inProgress.add(it);
- } catch (Exception e) {
- LOG.error("Cannot remove FetchItem from queue or cannot add it to inProgress queue", e);
- }
- return it;
- }
-
- public synchronized void dump() {
- LOG.info(" maxThreads = " + maxThreads);
- LOG.info(" inProgress = " + inProgress.size());
- LOG.info(" crawlDelay = " + crawlDelay);
- LOG.info(" minCrawlDelay = " + minCrawlDelay);
- LOG.info(" nextFetchTime = " + nextFetchTime.get());
- LOG.info(" now = " + System.currentTimeMillis());
- for (int i = 0; i < queue.size(); i++) {
- FetchItem it = queue.get(i);
- LOG.info(" " + i + ". " + it.url);
- }
- }
-
- private void setEndTime(long endTime) {
- setEndTime(endTime, false);
- }
-
- private void setEndTime(long endTime, boolean asap) {
- if (!asap)
- nextFetchTime.set(endTime + (maxThreads > 1 ? minCrawlDelay : crawlDelay));
- else
- nextFetchTime.set(endTime);
- }
- }
-
- /**
- * Convenience class - a collection of queues that keeps track of the total
- * number of items, and provides items eligible for fetching from any queue.
- */
- private static class FetchItemQueues {
- public static final String DEFAULT_ID = "default";
- Map<String, FetchItemQueue> queues = new HashMap<String, FetchItemQueue>();
- AtomicInteger totalSize = new AtomicInteger(0);
- int maxThreads;
- boolean byIP;
- long crawlDelay;
- long minCrawlDelay;
- Configuration conf;
-
- public FetchItemQueues(Configuration conf) {
- this.conf = conf;
- this.maxThreads = conf.getInt("fetcher.threads.per.host", 1);
- // backward-compatible default setting
- this.byIP = conf.getBoolean("fetcher.threads.per.host.by.ip", false);
- this.crawlDelay = (long) (conf.getFloat("fetcher.server.delay", 1.0f) * 1000);
- this.minCrawlDelay = (long) (conf.getFloat("fetcher.server.min.delay", 0.0f) * 1000);
- }
-
- public int getTotalSize() {
- return totalSize.get();
- }
-
- public int getQueueCount() {
- return queues.size();
- }
-
- public void addFetchItem(Text url, CrawlDatum datum) {
- FetchItem it = FetchItem.create(url, datum, byIP);
- if (it != null) addFetchItem(it);
- }
-
- public void addFetchItem(FetchItem it) {
- FetchItemQueue fiq = getFetchItemQueue(it.queueID);
- fiq.addFetchItem(it);
- totalSize.incrementAndGet();
- }
-
- public void finishFetchItem(FetchItem it) {
- finishFetchItem(it, false);
- }
-
- public void finishFetchItem(FetchItem it, boolean asap) {
- FetchItemQueue fiq = queues.get(it.queueID);
- if (fiq == null) {
- LOG.warn("Attempting to finish item from unknown queue: " + it);
- return;
- }
- fiq.finishFetchItem(it, asap);
- }
-
- public synchronized FetchItemQueue getFetchItemQueue(String id) {
- FetchItemQueue fiq = queues.get(id);
- if (fiq == null) {
- // initialize queue
- fiq = new FetchItemQueue(conf, maxThreads, crawlDelay, minCrawlDelay);
- queues.put(id, fiq);
- }
- return fiq;
- }
-
- public synchronized FetchItem getFetchItem() {
- Iterator<Map.Entry<String, FetchItemQueue>> it =
- queues.entrySet().iterator();
- while (it.hasNext()) {
- FetchItemQueue fiq = it.next().getValue();
- // reap empty queues
- if (fiq.getQueueSize() == 0 && fiq.getInProgressSize() == 0) {
- it.remove();
- continue;
- }
- FetchItem fit = fiq.getFetchItem();
- if (fit != null) {
- totalSize.decrementAndGet();
- return fit;
- }
- }
- return null;
- }
-
- public synchronized void dump() {
- for (String id : queues.keySet()) {
- FetchItemQueue fiq = queues.get(id);
- if (fiq.getQueueSize() == 0) continue;
- LOG.info("* queue: " + id);
- fiq.dump();
- }
- }
- }
+ private static final Collection<HbaseColumn> COLUMNS =
+ new HashSet<HbaseColumn>();
- /**
- * This class feeds the queues with input items, and re-fills them as
- * items are consumed by FetcherThread-s.
- */
- private static class QueueFeeder extends Thread {
- private RecordReader<Text, CrawlDatum> reader;
- private FetchItemQueues queues;
- private int size;
-
- public QueueFeeder(RecordReader<Text, CrawlDatum> reader,
- FetchItemQueues queues, int size) {
- this.reader = reader;
- this.queues = queues;
- this.size = size;
- this.setDaemon(true);
- this.setName("QueueFeeder");
- }
-
- public void run() {
- boolean hasMore = true;
- int cnt = 0;
-
- while (hasMore) {
- int feed = size - queues.getTotalSize();
- if (feed <= 0) {
- // queues are full - spin-wait until they have some free space
- try {
- Thread.sleep(1000);
- } catch (Exception e) {};
- continue;
- } else {
- LOG.debug("-feeding " + feed + " input urls ...");
- while (feed > 0 && hasMore) {
- try {
- Text url = new Text();
- CrawlDatum datum = new CrawlDatum();
- hasMore = reader.next(url, datum);
- if (hasMore) {
- queues.addFetchItem(url, datum);
- cnt++;
- feed--;
- }
- } catch (IOException e) {
- LOG.fatal("QueueFeeder error reading input, record " + cnt, e);
- return;
- }
- }
- }
- }
- LOG.info("QueueFeeder finished: total " + cnt + " records.");
- }
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA,
+ Generator.GENERATOR_MARK));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.REPR_URL));
}
/**
- * This class picks items from queues and fetches the pages.
+ * <p>Mapper class for Fetcher.</p>
+ * <p>
+ * This class reads the random integer written by {@link GeneratorHbase} as its key
+ * while outputting the actual key and value arguments through a {@link FetchEntry}
+ * instance.
+ * </p>
+ * <p>
+ * This approach (combined with the use of {@link PartitionUrlByHostHbase})
+ * makes sure that Fetcher is still polite while also randomizing the key order.
+ * If one host has a huge number of URLs in your table while other hosts
+ * have not, {@link FetcherReducer} will not be stuck on one host but process
+ * URLs from other hosts as well.
+ * </p>
*/
- private class FetcherThread extends Thread {
- private Configuration conf;
- private URLFilters urlFilters;
- private ScoringFilters scfilters;
- private ParseUtil parseUtil;
- private URLNormalizers normalizers;
- private ProtocolFactory protocolFactory;
- private long maxCrawlDelay;
- private boolean byIP;
- private int maxRedirect;
- private String reprUrl;
- private boolean redirecting;
- private int redirectCount;
- private boolean ignoreExternalLinks;
-
- public FetcherThread(Configuration conf) {
- this.setDaemon(true); // don't hang JVM on exit
- this.setName("FetcherThread"); // use an informative name
- this.conf = conf;
- this.urlFilters = new URLFilters(conf);
- this.scfilters = new ScoringFilters(conf);
- this.parseUtil = new ParseUtil(conf);
- this.protocolFactory = new ProtocolFactory(conf);
- this.normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_FETCHER);
- this.maxCrawlDelay = conf.getInt("fetcher.max.crawl.delay", 30) * 1000;
- // backward-compatible default setting
- this.byIP = conf.getBoolean("fetcher.threads.per.host.by.ip", true);
- this.maxRedirect = conf.getInt("http.redirect.max", 3);
- this.ignoreExternalLinks =
- conf.getBoolean("db.ignore.external.links", false);
- }
-
- public void run() {
- activeThreads.incrementAndGet(); // count threads
-
- FetchItem fit = null;
- try {
-
- while (true) {
- fit = fetchQueues.getFetchItem();
- if (fit == null) {
- if (feeder.isAlive() || fetchQueues.getTotalSize() > 0) {
- LOG.debug(getName() + " spin-waiting ...");
- // spin-wait.
- spinWaiting.incrementAndGet();
- try {
- Thread.sleep(500);
- } catch (Exception e) {}
- spinWaiting.decrementAndGet();
- continue;
- } else {
- // all done, finish this thread
- return;
- }
- }
- lastRequestStart.set(System.currentTimeMillis());
- Text reprUrlWritable =
- (Text) fit.datum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
- if (reprUrlWritable == null) {
- reprUrl = fit.url.toString();
- } else {
- reprUrl = reprUrlWritable.toString();
- }
- try {
- if (LOG.isInfoEnabled()) { LOG.info("fetching " + fit.url); }
-
- // fetch the page
- redirecting = false;
- redirectCount = 0;
- do {
- if (LOG.isDebugEnabled()) {
- LOG.debug("redirectCount=" + redirectCount);
- }
- redirecting = false;
- Protocol protocol = this.protocolFactory.getProtocol(fit.url.toString());
- RobotRules rules = protocol.getRobotRules(fit.url, fit.datum);
- if (!rules.isAllowed(fit.u)) {
- // unblock
- fetchQueues.finishFetchItem(fit, true);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Denied by robots.txt: " + fit.url);
- }
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_ROBOTS_DENIED, CrawlDatum.STATUS_FETCH_GONE);
- continue;
- }
- if (rules.getCrawlDelay() > 0) {
- if (rules.getCrawlDelay() > maxCrawlDelay) {
- // unblock
- fetchQueues.finishFetchItem(fit, true);
- LOG.debug("Crawl-Delay for " + fit.url + " too long (" + rules.getCrawlDelay() + "), skipping");
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_ROBOTS_DENIED, CrawlDatum.STATUS_FETCH_GONE);
- continue;
- } else {
- FetchItemQueue fiq = fetchQueues.getFetchItemQueue(fit.queueID);
- fiq.crawlDelay = rules.getCrawlDelay();
- }
- }
- ProtocolOutput output = protocol.getProtocolOutput(fit.url, fit.datum);
- ProtocolStatus status = output.getStatus();
- Content content = output.getContent();
- ParseStatus pstatus = null;
- // unblock queue
- fetchQueues.finishFetchItem(fit);
+ public static class FetcherMapper
+ extends TableMapper<ImmutableBytesWritable, FetchEntry> {
- String urlString = fit.url.toString();
-
- switch(status.getCode()) {
-
- case ProtocolStatus.WOULDBLOCK:
- // retry ?
- fetchQueues.addFetchItem(fit);
- break;
-
- case ProtocolStatus.SUCCESS: // got a page
- pstatus = output(fit.url, fit.datum, content, status, CrawlDatum.STATUS_FETCH_SUCCESS);
- updateStatus(content.getContent().length);
- if (pstatus != null && pstatus.isSuccess() &&
- pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
- String newUrl = pstatus.getMessage();
- int refreshTime = Integer.valueOf(pstatus.getArgs()[1]);
- Text redirUrl =
- handleRedirect(fit.url, fit.datum,
- urlString, newUrl,
- refreshTime < Fetcher.PERM_REFRESH_TIME,
- Fetcher.CONTENT_REDIR);
- if (redirUrl != null) {
- CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_DB_UNFETCHED,
- fit.datum.getFetchInterval(), fit.datum.getScore());
- if (reprUrl != null) {
- newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
- fit = FetchItem.create(redirUrl, newDatum, byIP);
- if (fit != null) {
- FetchItemQueue fiq =
- fetchQueues.getFetchItemQueue(fit.queueID);
- fiq.addInProgressFetchItem(fit);
- } else {
- // stop redirecting
- redirecting = false;
- }
- }
- }
- break;
-
- case ProtocolStatus.MOVED: // redirect
- case ProtocolStatus.TEMP_MOVED:
- int code;
- boolean temp;
- if (status.getCode() == ProtocolStatus.MOVED) {
- code = CrawlDatum.STATUS_FETCH_REDIR_PERM;
- temp = false;
- } else {
- code = CrawlDatum.STATUS_FETCH_REDIR_TEMP;
- temp = true;
- }
- output(fit.url, fit.datum, content, status, code);
- String newUrl = status.getMessage();
- Text redirUrl =
- handleRedirect(fit.url, fit.datum,
- urlString, newUrl, temp,
- Fetcher.PROTOCOL_REDIR);
- if (redirUrl != null) {
- CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_DB_UNFETCHED,
- fit.datum.getFetchInterval(), fit.datum.getScore());
- if (reprUrl != null) {
- newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
- fit = FetchItem.create(redirUrl, newDatum, byIP);
- if (fit != null) {
- FetchItemQueue fiq =
- fetchQueues.getFetchItemQueue(fit.queueID);
- fiq.addInProgressFetchItem(fit);
- } else {
- // stop redirecting
- redirecting = false;
- }
- } else {
- // stop redirecting
- redirecting = false;
- }
- break;
-
- case ProtocolStatus.EXCEPTION:
- logError(fit.url, status.getMessage());
- /* FALLTHROUGH */
- case ProtocolStatus.RETRY: // retry
- case ProtocolStatus.BLOCKED:
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_RETRY);
- break;
-
- case ProtocolStatus.GONE: // gone
- case ProtocolStatus.NOTFOUND:
- case ProtocolStatus.ACCESS_DENIED:
- case ProtocolStatus.ROBOTS_DENIED:
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_GONE);
- break;
-
- case ProtocolStatus.NOTMODIFIED:
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_NOTMODIFIED);
- break;
-
- default:
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unknown ProtocolStatus: " + status.getCode());
- }
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_RETRY);
- }
-
- if (redirecting && redirectCount >= maxRedirect) {
- fetchQueues.finishFetchItem(fit);
- if (LOG.isInfoEnabled()) {
- LOG.info(" - redirect count exceeded " + fit.url);
- }
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_REDIR_EXCEEDED, CrawlDatum.STATUS_FETCH_GONE);
- }
-
- } while (redirecting && (redirectCount < maxRedirect));
-
- } catch (Throwable t) { // unexpected exception
- // unblock
- fetchQueues.finishFetchItem(fit);
- logError(fit.url, t.toString());
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_FAILED, CrawlDatum.STATUS_FETCH_RETRY);
- }
- }
-
- } catch (Throwable e) {
- if (LOG.isFatalEnabled()) {
- e.printStackTrace(LogUtil.getFatalStream(LOG));
- LOG.fatal("fetcher caught:"+e.toString());
- }
- } finally {
- if (fit != null) fetchQueues.finishFetchItem(fit);
- activeThreads.decrementAndGet(); // count threads
- LOG.info("-finishing thread " + getName() + ", activeThreads=" + activeThreads);
- }
+ @Override
+ protected void map(ImmutableBytesWritable key, Result value,
+ Context context) throws IOException, InterruptedException {
+ byte[] outKeyRaw =
+ value.getValue(WebTableColumns.METADATA, Generator.GENERATOR_MARK);
+ context.write(new ImmutableBytesWritable(outKeyRaw), new FetchEntry(key, value));
}
-
- private Text handleRedirect(Text url, CrawlDatum datum,
- String urlString, String newUrl,
- boolean temp, String redirType)
- throws MalformedURLException, URLFilterException {
- newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);
- newUrl = urlFilters.filter(newUrl);
-
- if (ignoreExternalLinks) {
- try {
- String origHost = new URL(urlString).getHost().toLowerCase();
- String newHost = new URL(newUrl).getHost().toLowerCase();
- if (!origHost.equals(newHost)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - ignoring redirect " + redirType + " from " +
- urlString + " to " + newUrl +
- " because external links are ignored");
- }
- return null;
- }
- } catch (MalformedURLException e) { }
- }
-
- if (newUrl != null && !newUrl.equals(urlString)) {
- reprUrl = URLUtil.chooseRepr(reprUrl, newUrl, temp);
- url = new Text(newUrl);
- if (maxRedirect > 0) {
- redirecting = true;
- redirectCount++;
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching now)");
- }
- return url;
- } else {
- CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_LINKED,
- datum.getFetchInterval());
- if (reprUrl != null) {
- newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
- output(url, newDatum, null, null, CrawlDatum.STATUS_LINKED);
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching later)");
- }
- return null;
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect skipped: " +
- (newUrl != null ? "to same url" : "filtered"));
- }
- return null;
- }
- }
-
- private void logError(Text url, String message) {
- if (LOG.isInfoEnabled()) {
- LOG.info("fetch of " + url + " failed with: " + message);
- }
- errors.incrementAndGet();
- }
-
- private ParseStatus output(Text key, CrawlDatum datum,
- Content content, ProtocolStatus pstatus, int status) {
-
- datum.setStatus(status);
- datum.setFetchTime(System.currentTimeMillis());
- if (pstatus != null) datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
-
- ParseResult parseResult = null;
- if (content != null) {
- Metadata metadata = content.getMetadata();
- // add segment to metadata
- metadata.set(Nutch.SEGMENT_NAME_KEY, segmentName);
- // add score to content metadata so that ParseSegment can pick it up.
- try {
- scfilters.passScoreBeforeParsing(key, datum, content);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
- }
- }
- /* Note: Fetcher will only follow meta-redirects coming from the
- * original URL. */
- if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {
- try {
- parseResult = this.parseUtil.parse(content);
- } catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": " + StringUtils.stringifyException(e));
- }
-
- if (parseResult == null) {
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content,
- new ParseStatus().getEmptyParse(conf));
- datum.setSignature(signature);
- }
- }
-
- /* Store status code in content So we can read this value during
- * parsing (as a separate job) and decide to parse or not.
- */
- content.getMetadata().add(Nutch.FETCH_STATUS_KEY, Integer.toString(status));
- }
-
- try {
- output.collect(key, new NutchWritable(datum));
- if (content != null && storingContent)
- output.collect(key, new NutchWritable(content));
- if (parseResult != null) {
- for (Entry<Text, Parse> entry : parseResult) {
- Text url = entry.getKey();
- Parse parse = entry.getValue();
- ParseStatus parseStatus = parse.getData().getStatus();
-
- if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
- parse = parseStatus.getEmptyParse(getConf());
- }
-
- // Calculate page signature. For non-parsing fetchers this will
- // be done in ParseSegment
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content, parse);
- // Ensure segment name and score are in parseData metadata
- parse.getData().getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- segmentName);
- parse.getData().getContentMeta().set(Nutch.SIGNATURE_KEY,
- StringUtil.toHexString(signature));
- // Pass fetch time to content meta
- parse.getData().getContentMeta().set(Nutch.FETCH_TIME_KEY,
- Long.toString(datum.getFetchTime()));
- if (url.equals(key))
- datum.setSignature(signature);
- try {
- scfilters.passScoreAfterParsing(url, content, parse);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
- }
- }
- output.collect(url, new NutchWritable(
- new ParseImpl(new ParseText(parse.getText()),
- parse.getData(), parse.isCanonical())));
- }
- }
- } catch (IOException e) {
- if (LOG.isFatalEnabled()) {
- e.printStackTrace(LogUtil.getFatalStream(LOG));
- LOG.fatal("fetcher caught:"+e.toString());
- }
- }
-
- // return parse status if it exits
- if (parseResult != null && !parseResult.isEmpty()) {
- Parse p = parseResult.get(content.getUrl());
- if (p != null) {
- return p.getData().getStatus();
- }
- }
- return null;
- }
-
}
-
- public Fetcher() { super(null); }
-
- public Fetcher(Configuration conf) { super(conf); }
-
- private void updateStatus(int bytesInPage) throws IOException {
- pages.incrementAndGet();
- bytes.addAndGet(bytesInPage);
- }
-
- private void reportStatus() throws IOException {
- String status;
- long elapsed = (System.currentTimeMillis() - start)/1000;
- status = activeThreads + " threads, " +
- pages+" pages, "+errors+" errors, "
- + Math.round(((float)pages.get()*10)/elapsed)/10.0+" pages/s, "
- + Math.round(((((float)bytes.get())*8)/1024)/elapsed)+" kb/s, ";
- reporter.setStatus(status);
- }
-
- public void configure(JobConf job) {
- setConf(job);
-
- this.segmentName = job.get(Nutch.SEGMENT_NAME_KEY);
- this.storingContent = isStoringContent(job);
- this.parsing = isParsing(job);
-
-// if (job.getBoolean("fetcher.verbose", false)) {
-// LOG.setLevel(Level.FINE);
-// }
- }
+ public static final Log LOG = LogFactory.getLog(Fetcher.class);
- public void close() {}
+ private Configuration conf;
- public static boolean isParsing(Configuration conf) {
- return conf.getBoolean("fetcher.parse", true);
+ @Override
+ public Configuration getConf() {
+ return conf;
}
- public static boolean isStoringContent(Configuration conf) {
- return conf.getBoolean("fetcher.store.content", true);
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
}
- public void run(RecordReader<Text, CrawlDatum> input,
- OutputCollector<Text, NutchWritable> output,
- Reporter reporter) throws IOException {
-
- this.output = output;
- this.reporter = reporter;
- this.fetchQueues = new FetchItemQueues(getConf());
-
- int threadCount = getConf().getInt("fetcher.threads.fetch", 10);
- if (LOG.isInfoEnabled()) { LOG.info("Fetcher: threads: " + threadCount); }
-
- feeder = new QueueFeeder(input, fetchQueues, threadCount * 50);
- //feeder.setPriority((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2);
- feeder.start();
-
- // set non-blocking & no-robots mode for HTTP protocol plugins.
- getConf().setBoolean(Protocol.CHECK_BLOCKING, false);
- getConf().setBoolean(Protocol.CHECK_ROBOTS, false);
+ private void fetch(String table, int threads, boolean restart) throws Exception {
+ LOG.info("Fetcher: starting");
+ LOG.info("Fetcher: table: " + table);
- for (int i = 0; i < threadCount; i++) { // spawn threads
- new FetcherThread(getConf()).start();
+ if (threads > 0) {
+ getConf().setInt("fetcher.threads.fetch", threads);
}
-
- // select a timeout that avoids a task timeout
- long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2;
-
- do { // wait for threads to exit
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {}
-
- reportStatus();
- LOG.info("-activeThreads=" + activeThreads + ", spinWaiting=" + spinWaiting.get()
- + ", fetchQueues.totalSize=" + fetchQueues.getTotalSize());
-
- if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) {
- fetchQueues.dump();
- }
- // some requests seem to hang, despite all intentions
- if ((System.currentTimeMillis() - lastRequestStart.get()) > timeout) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Aborting with "+activeThreads+" hung threads.");
- }
- return;
- }
-
- } while (activeThreads.get() > 0);
- LOG.info("-activeThreads=" + activeThreads);
- }
-
- public void fetch(Path segment, int threads, boolean parsing)
- throws IOException {
-
- checkConfiguration();
-
- if (LOG.isInfoEnabled()) {
- LOG.info("Fetcher: starting");
- LOG.info("Fetcher: segment: " + segment);
+ Job job = new NutchJob(getConf(), "fetch " + table);
+ Scan scan = TableUtil.createScanFromColumns(COLUMNS);
+ List<Filter> filters = new ArrayList<Filter>();
+ if (!restart) {
+ filters.add(new ValueFilter(WebTableColumns.METADATA, FETCH_MARK,
+ CompareOp.NOT_EQUAL, TableUtil.YES_VAL, false));
}
-
- JobConf job = new NutchJob(getConf());
- job.setJobName("fetch " + segment);
-
- job.setInt("fetcher.threads.fetch", threads);
- job.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
- job.setBoolean("fetcher.parse", parsing);
-
- // for politeness, don't permit parallel execution of a single task
- job.setSpeculativeExecution(false);
-
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
- job.setInputFormat(InputFormat.class);
-
- job.setMapRunnerClass(Fetcher.class);
-
- FileOutputFormat.setOutputPath(job, segment);
- job.setOutputFormat(FetcherOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(NutchWritable.class);
-
- JobClient.runJob(job);
- if (LOG.isInfoEnabled()) { LOG.info("Fetcher: done"); }
+ filters.add(new ValueFilter(WebTableColumns.METADATA, Generator.GENERATOR_MARK,
+ CompareOp.GREATER_OR_EQUAL, new byte[] { (byte)0 }, true));
+ FilterList filterList = new FilterList(Operator.MUST_PASS_ALL, filters);
+ scan.setFilter(filterList);
+ TableMapReduceUtil.initTableMapperJob(table, scan, FetcherMapper.class,
+ ImmutableBytesWritable.class, FetchEntry.class, job);
+ TableMapReduceUtil.initTableReducerJob(table,
+ FetcherReducer.class, job, PartitionUrlByHost.class);
+
+ job.waitForCompletion(true);
+
+ LOG.info("Fetcher: done");
}
-
-
- /** Run the fetcher. */
- public static void main(String[] args) throws Exception {
-
- String usage = "Usage: Fetcher <segment> [-threads n] [-noParsing]";
+
+ @Override
+ public int run(String[] args) throws Exception {
+ final String usage = "Usage: FetcherHbase <webtable> [-threads n] [-restart]";
if (args.length < 1) {
System.err.println(usage);
System.exit(-1);
}
-
- Path segment = new Path(args[0]);
- Configuration conf = NutchConfiguration.create();
+ final String table = args[0];
- int threads = conf.getInt("fetcher.threads.fetch", 10);
- boolean parsing = true;
+ int threads = -1;
+ boolean restart = false;
- for (int i = 1; i < args.length; i++) { // parse command line
- if (args[i].equals("-threads")) { // found -threads option
+ for (int i = 1; i < args.length; i++) {
+ if ("-threads".equals(args[i])) {
+ // found -threads option
threads = Integer.parseInt(args[++i]);
- } else if (args[i].equals("-noParsing")) parsing = false;
+ } else if ("-restart".equals(args[i])) {
+ restart = true;
+ }
}
- conf.setInt("fetcher.threads.fetch", threads);
- if (!parsing) {
- conf.setBoolean("fetcher.parse", parsing);
- }
- Fetcher fetcher = new Fetcher(conf); // make a Fetcher
-
- fetcher.fetch(segment, threads, parsing); // run the Fetcher
+ fetch(table, threads, restart); // run the Fetcher
+ return 0;
}
- private void checkConfiguration() {
-
- // ensure that a value has been set for the agent name and that that
- // agent name is the first value in the agents we advertise for robot
- // rules parsing
- String agentName = getConf().get("http.agent.name");
- if (agentName == null || agentName.trim().length() == 0) {
- String message = "Fetcher: No agents listed in 'http.agent.name'"
- + " property.";
- if (LOG.isFatalEnabled()) {
- LOG.fatal(message);
- }
- throw new IllegalArgumentException(message);
- } else {
-
- // get all of the agents that we advertise
- String agentNames = getConf().get("http.robots.agents");
- StringTokenizer tok = new StringTokenizer(agentNames, ",");
- ArrayList<String> agents = new ArrayList<String>();
- while (tok.hasMoreTokens()) {
- agents.add(tok.nextToken().trim());
- }
-
- // if the first one is not equal to our agent name, log fatal and throw
- // an exception
- if (!(agents.get(0)).equalsIgnoreCase(agentName)) {
- String message = "Fetcher: Your 'http.agent.name' value should be "
- + "listed first in 'http.robots.agents' property.";
- if (LOG.isWarnEnabled()) {
- LOG.warn(message);
- }
- }
- }
+ public static void main(String[] args) throws Exception {
+ final int res = ToolRunner.run(NutchConfiguration.create(),
+ new Fetcher(), args);
+ System.exit(res);
}
-
}
diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutput.java b/src/java/org/apache/nutch/fetcher/FetcherOutput.java
index c2c92b57e..adafa8f1d 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherOutput.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherOutput.java
@@ -17,65 +17,16 @@
package org.apache.nutch.fetcher;
-import java.io.*;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
-import org.apache.hadoop.io.*;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.protocol.Content;
-import org.apache.nutch.parse.*;
+import org.apache.hadoop.io.Writable;
/* An entry in the fetcher's output. */
public final class FetcherOutput implements Writable {
- private CrawlDatum crawlDatum;
- private Content content;
- private ParseImpl parse;
- public FetcherOutput() {}
-
- public FetcherOutput(CrawlDatum crawlDatum, Content content,
- ParseImpl parse) {
- this.crawlDatum = crawlDatum;
- this.content = content;
- this.parse = parse;
- }
-
- public final void readFields(DataInput in) throws IOException {
- this.crawlDatum = CrawlDatum.read(in);
- this.content = in.readBoolean() ? Content.read(in) : null;
- this.parse = in.readBoolean() ? ParseImpl.read(in) : null;
- }
-
- public final void write(DataOutput out) throws IOException {
- crawlDatum.write(out);
-
- out.writeBoolean(content != null);
- if (content != null) {
- content.write(out);
- }
-
- out.writeBoolean(parse != null);
- if (parse != null) {
- parse.write(out);
- }
- }
-
- public CrawlDatum getCrawlDatum() { return crawlDatum; }
- public Content getContent() { return content; }
- public ParseImpl getParse() { return parse; }
-
- public boolean equals(Object o) {
- if (!(o instanceof FetcherOutput))
- return false;
- FetcherOutput other = (FetcherOutput)o;
- return
- this.crawlDatum.equals(other.crawlDatum) &&
- this.content.equals(other.content);
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("CrawlDatum: " + crawlDatum+"\n" );
- return buffer.toString();
- }
+ public final void readFields(DataInput in) throws IOException { }
+ public final void write(DataOutput out) throws IOException { }
}
diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
deleted file mode 100644
index 70e411ccc..000000000
--- a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.fetcher;
-
-import java.io.IOException;
-
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.NutchWritable;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-
-import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.io.SequenceFile.CompressionType;
-
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.OutputFormat;
-import org.apache.hadoop.mapred.RecordWriter;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
-import org.apache.hadoop.util.Progressable;
-
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseOutputFormat;
-import org.apache.nutch.protocol.Content;
-
-/** Splits FetcherOutput entries into multiple map files. */
-public class FetcherOutputFormat implements OutputFormat<Text, NutchWritable> {
-
- public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
- Path out = FileOutputFormat.getOutputPath(job);
- if (fs.exists(new Path(out, CrawlDatum.FETCH_DIR_NAME)))
- throw new IOException("Segment already fetched!");
- }
-
- public RecordWriter<Text, NutchWritable> getRecordWriter(final FileSystem fs,
- final JobConf job,
- final String name,
- final Progressable progress) throws IOException {
-
- Path out = FileOutputFormat.getOutputPath(job);
- final Path fetch =
- new Path(new Path(out, CrawlDatum.FETCH_DIR_NAME), name);
- final Path content =
- new Path(new Path(out, Content.DIR_NAME), name);
-
- final CompressionType compType = SequenceFileOutputFormat.getOutputCompressionType(job);
-
- final MapFile.Writer fetchOut =
- new MapFile.Writer(job, fs, fetch.toString(), Text.class, CrawlDatum.class,
- compType, progress);
-
- return new RecordWriter<Text, NutchWritable>() {
- private MapFile.Writer contentOut;
- private RecordWriter<Text, Parse> parseOut;
-
- {
- if (Fetcher.isStoringContent(job)) {
- contentOut = new MapFile.Writer(job, fs, content.toString(),
- Text.class, Content.class,
- compType, progress);
- }
-
- if (Fetcher.isParsing(job)) {
- parseOut = new ParseOutputFormat().getRecordWriter(fs, job, name, progress);
- }
- }
-
- public void write(Text key, NutchWritable value)
- throws IOException {
-
- Writable w = value.get();
-
- if (w instanceof CrawlDatum)
- fetchOut.append(key, w);
- else if (w instanceof Content)
- contentOut.append(key, w);
- else if (w instanceof Parse)
- parseOut.write(key, (Parse)w);
- }
-
- public void close(Reporter reporter) throws IOException {
- fetchOut.close();
- if (contentOut != null) {
- contentOut.close();
- }
- if (parseOut != null) {
- parseOut.close(reporter);
- }
- }
-
- };
-
- }
-}
-
diff --git a/src/java/org/apache/nutch/fetcher/FetcherReducer.java b/src/java/org/apache/nutch/fetcher/FetcherReducer.java
new file mode 100644
index 000000000..c313b30f3
--- /dev/null
+++ b/src/java/org/apache/nutch/fetcher/FetcherReducer.java
@@ -0,0 +1,663 @@
+package org.apache.nutch.fetcher;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.commons.logging.Log;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableReducer;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.Writables;
+import org.apache.nutch.crawl.CrawlDatumHbase;
+import org.apache.nutch.fetcher.Fetcher;
+import org.apache.nutch.net.URLFilterException;
+import org.apache.nutch.net.URLFilters;
+import org.apache.nutch.net.URLNormalizers;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.protocol.Protocol;
+import org.apache.nutch.protocol.ProtocolFactory;
+import org.apache.nutch.protocol.ProtocolOutput;
+import org.apache.nutch.protocol.ProtocolStatus;
+import org.apache.nutch.protocol.RobotRules;
+import org.apache.nutch.util.LogUtil;
+import org.apache.nutch.util.URLUtil;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
+import org.apache.nutch.util.hbase.WebTableRow;
+
+public class FetcherReducer
+extends TableReducer<ImmutableBytesWritable, FetchEntry, ImmutableBytesWritable> {
+
+ public static final Log LOG = Fetcher.LOG;
+
+ private final AtomicInteger activeThreads = new AtomicInteger(0);
+ private final AtomicInteger spinWaiting = new AtomicInteger(0);
+
+ private final long start = System.currentTimeMillis(); // start time of fetcher run
+ private final AtomicLong lastRequestStart = new AtomicLong(start);
+
+ private final AtomicLong bytes = new AtomicLong(0); // total bytes fetched
+ private final AtomicInteger pages = new AtomicInteger(0); // total pages fetched
+ private final AtomicInteger errors = new AtomicInteger(0); // total pages errored
+
+ private QueueFeeder feeder;
+
+ private List<FetcherThread> fetcherThreads = new ArrayList<FetcherThread>();
+
+ private FetchItemQueues fetchQueues;
+
+ private static final ImmutableBytesWritable REDUCE_KEY =
+ new ImmutableBytesWritable(TableUtil.YES_VAL);
+
+ /**
+ * This class described the item to be fetched.
+ */
+ private static class FetchItem {
+ WebTableRow row;
+ String queueID;
+ String url;
+ URL u;
+
+ public FetchItem(String url, WebTableRow row, URL u, String queueID) {
+ this.row = row;
+ this.url = url;
+ this.u = u;
+ this.queueID = queueID;
+ }
+
+ /** Create an item. Queue id will be created based on <code>byIP</code>
+ * argument, either as a protocol + hostname pair, or protocol + IP
+ * address pair.
+ */
+ public static FetchItem create(String url, WebTableRow row, boolean byIP) {
+ String queueID;
+ URL u = null;
+ try {
+ u = new URL(url);
+ } catch (final Exception e) {
+ LOG.warn("Cannot parse url: " + url, e);
+ return null;
+ }
+ final String proto = u.getProtocol().toLowerCase();
+ String host;
+ if (byIP) {
+ try {
+ final InetAddress addr = InetAddress.getByName(u.getHost());
+ host = addr.getHostAddress();
+ } catch (final UnknownHostException e) {
+ // unable to resolve it, so don't fall back to host name
+ LOG.warn("Unable to resolve: " + u.getHost() + ", skipping.");
+ return null;
+ }
+ } else {
+ host = u.getHost();
+ if (host == null) {
+ LOG.warn("Unknown host for url: " + url + ", skipping.");
+ return null;
+ }
+ host = host.toLowerCase();
+ }
+ queueID = proto + "://" + host;
+ return new FetchItem(url, row, u, queueID);
+ }
+
+ }
+
+ /**
+ * This class handles FetchItems which come from the same host ID (be it
+ * a proto/hostname or proto/IP pair). It also keeps track of requests in
+ * progress and elapsed time between requests.
+ */
+ private static class FetchItemQueue {
+ List<FetchItem> queue = Collections.synchronizedList(new LinkedList<FetchItem>());
+ Set<FetchItem> inProgress = Collections.synchronizedSet(new HashSet<FetchItem>());
+ AtomicLong nextFetchTime = new AtomicLong();
+ long crawlDelay;
+ long minCrawlDelay;
+ int maxThreads;
+
+ public FetchItemQueue(Configuration conf, int maxThreads, long crawlDelay, long minCrawlDelay) {
+ this.maxThreads = maxThreads;
+ this.crawlDelay = crawlDelay;
+ this.minCrawlDelay = minCrawlDelay;
+ // ready to start
+ setEndTime(System.currentTimeMillis() - crawlDelay);
+ }
+
+ public int getQueueSize() {
+ return queue.size();
+ }
+
+ public int getInProgressSize() {
+ return inProgress.size();
+ }
+
+ public void finishFetchItem(FetchItem it, boolean asap) {
+ if (it != null) {
+ inProgress.remove(it);
+ setEndTime(System.currentTimeMillis(), asap);
+ }
+ }
+
+ public void addFetchItem(FetchItem it) {
+ if (it == null) return;
+ queue.add(it);
+ }
+
+ @SuppressWarnings("unused")
+ public void addInProgressFetchItem(FetchItem it) {
+ if (it == null) return;
+ inProgress.add(it);
+ }
+
+ public FetchItem getFetchItem() {
+ if (inProgress.size() >= maxThreads) return null;
+ final long now = System.currentTimeMillis();
+ if (nextFetchTime.get() > now) return null;
+ FetchItem it = null;
+ if (queue.size() == 0) return null;
+ try {
+ it = queue.remove(0);
+ inProgress.add(it);
+ } catch (final Exception e) {
+ LOG.error("Cannot remove FetchItem from queue or cannot add it to inProgress queue", e);
+ }
+ return it;
+ }
+
+ public synchronized void dump() {
+ LOG.info(" maxThreads = " + maxThreads);
+ LOG.info(" inProgress = " + inProgress.size());
+ LOG.info(" crawlDelay = " + crawlDelay);
+ LOG.info(" minCrawlDelay = " + minCrawlDelay);
+ LOG.info(" nextFetchTime = " + nextFetchTime.get());
+ LOG.info(" now = " + System.currentTimeMillis());
+ for (int i = 0; i < queue.size(); i++) {
+ final FetchItem it = queue.get(i);
+ LOG.info(" " + i + ". " + it.url);
+ }
+ }
+
+ private void setEndTime(long endTime) {
+ setEndTime(endTime, false);
+ }
+
+ private void setEndTime(long endTime, boolean asap) {
+ if (!asap)
+ nextFetchTime.set(endTime + (maxThreads > 1 ? minCrawlDelay : crawlDelay));
+ else
+ nextFetchTime.set(endTime);
+ }
+ }
+
+ /**
+ * Convenience class - a collection of queues that keeps track of the total
+ * number of items, and provides items eligible for fetching from any queue.
+ */
+ private static class FetchItemQueues {
+ @SuppressWarnings("unused")
+ public static final String DEFAULT_ID = "default";
+ Map<String, FetchItemQueue> queues = new HashMap<String, FetchItemQueue>();
+ AtomicInteger totalSize = new AtomicInteger(0);
+ int maxThreads;
+ boolean byIP;
+ long crawlDelay;
+ long minCrawlDelay;
+ Configuration conf;
+
+ public FetchItemQueues(Configuration conf) {
+ this.conf = conf;
+ this.maxThreads = conf.getInt("fetcher.threads.per.host", 1);
+ // backward-compatible default setting
+ this.byIP = conf.getBoolean("fetcher.threads.per.host.by.ip", false);
+ this.crawlDelay = (long) (conf.getFloat("fetcher.server.delay", 1.0f) * 1000);
+ this.minCrawlDelay = (long) (conf.getFloat("fetcher.server.min.delay", 0.0f) * 1000);
+ }
+
+ public int getTotalSize() {
+ return totalSize.get();
+ }
+
+ public int getQueueCount() {
+ return queues.size();
+ }
+
+ public void addFetchItem(String url, WebTableRow row) {
+ final FetchItem it = FetchItem.create(url, row, byIP);
+ if (it != null) addFetchItem(it);
+ }
+
+ public synchronized void addFetchItem(FetchItem it) {
+ final FetchItemQueue fiq = getFetchItemQueue(it.queueID);
+ fiq.addFetchItem(it);
+ totalSize.incrementAndGet();
+ }
+
+ public void finishFetchItem(FetchItem it) {
+ finishFetchItem(it, false);
+ }
+
+ public void finishFetchItem(FetchItem it, boolean asap) {
+ final FetchItemQueue fiq = queues.get(it.queueID);
+ if (fiq == null) {
+ LOG.warn("Attempting to finish item from unknown queue: " + it);
+ return;
+ }
+ fiq.finishFetchItem(it, asap);
+ }
+
+ public synchronized FetchItemQueue getFetchItemQueue(String id) {
+ FetchItemQueue fiq = queues.get(id);
+ if (fiq == null) {
+ // initialize queue
+ fiq = new FetchItemQueue(conf, maxThreads, crawlDelay, minCrawlDelay);
+ queues.put(id, fiq);
+ }
+ return fiq;
+ }
+
+ public synchronized FetchItem getFetchItem() {
+ final Iterator<Map.Entry<String, FetchItemQueue>> it =
+ queues.entrySet().iterator();
+ while (it.hasNext()) {
+ final FetchItemQueue fiq = it.next().getValue();
+ // reap empty queues
+ if (fiq.getQueueSize() == 0 && fiq.getInProgressSize() == 0) {
+ it.remove();
+ continue;
+ }
+ final FetchItem fit = fiq.getFetchItem();
+ if (fit != null) {
+ totalSize.decrementAndGet();
+
+ return fit;
+ }
+ }
+ return null;
+ }
+
+ public synchronized void dump() {
+ for (final String id : queues.keySet()) {
+ final FetchItemQueue fiq = queues.get(id);
+ if (fiq.getQueueSize() == 0) continue;
+ LOG.info("* queue: " + id);
+ fiq.dump();
+ }
+ }
+ }
+
+ /**
+ * This class picks items from queues and fetches the pages.
+ */
+ private class FetcherThread extends Thread {
+ private final URLFilters urlFilters;
+ private final URLNormalizers normalizers;
+ private final ProtocolFactory protocolFactory;
+ private final long maxCrawlDelay;
+ @SuppressWarnings("unused")
+ private final boolean byIP;
+ private final int maxRedirect;
+ private String reprUrl;
+ private boolean redirecting;
+ private int redirectCount;
+ private Context context;
+
+ public FetcherThread(Context context, int num) {
+ this.setDaemon(true); // don't hang JVM on exit
+ this.setName("FetcherThread" + num); // use an informative name
+ this.context = context;
+ Configuration conf = context.getConfiguration();
+ this.urlFilters = new URLFilters(conf);
+ this.protocolFactory = new ProtocolFactory(conf);
+ this.normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_FETCHER);
+ this.maxCrawlDelay = conf.getInt("fetcher.max.crawl.delay", 30) * 1000;
+ // backward-compatible default setting
+ this.byIP = conf.getBoolean("fetcher.threads.per.host.by.ip", true);
+ this.maxRedirect = conf.getInt("http.redirect.max", 3);
+ }
+
+ @Override
+ public void run() {
+ activeThreads.incrementAndGet(); // count threads
+
+ FetchItem fit = null;
+ try {
+
+ while (true) {
+ fit = fetchQueues.getFetchItem();
+ if (fit == null) {
+ if (feeder.isAlive() || fetchQueues.getTotalSize() > 0) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(getName() + " fetchQueues.getFetchItem() was null, spin-waiting ...");
+ }
+ // spin-wait.
+ spinWaiting.incrementAndGet();
+ try {
+ Thread.sleep(500);
+ } catch (final Exception e) {}
+ spinWaiting.decrementAndGet();
+ continue;
+ } else {
+ // all done, finish this thread
+ return;
+ }
+ }
+ lastRequestStart.set(System.currentTimeMillis());
+ if (!fit.row.hasColumn(WebTableColumns.REPR_URL, null)) {
+ reprUrl = fit.url.toString();
+ } else {
+ reprUrl = fit.row.getReprUrl();
+ }
+ try {
+ LOG.info("fetching " + fit.url);
+
+ // fetch the page
+ redirecting = false;
+ redirectCount = 0;
+ do {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("redirectCount=" + redirectCount);
+ }
+ redirecting = false;
+ final Protocol protocol = this.protocolFactory.getProtocol(fit.url);
+ final RobotRules rules = protocol.getRobotRules(fit.url, fit.row);
+ if (!rules.isAllowed(fit.u)) {
+ // unblock
+ fetchQueues.finishFetchItem(fit, true);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Denied by robots.txt: " + fit.url);
+ }
+ output(fit, null, ProtocolStatus.STATUS_ROBOTS_DENIED,
+ CrawlDatumHbase.STATUS_GONE);
+ continue;
+ }
+ if (rules.getCrawlDelay() > 0) {
+ if (rules.getCrawlDelay() > maxCrawlDelay) {
+ // unblock
+ fetchQueues.finishFetchItem(fit, true);
+ LOG.debug("Crawl-Delay for " + fit.url + " too long (" + rules.getCrawlDelay() + "), skipping");
+ output(fit, null, ProtocolStatus.STATUS_ROBOTS_DENIED, CrawlDatumHbase.STATUS_GONE);
+ continue;
+ } else {
+ final FetchItemQueue fiq = fetchQueues.getFetchItemQueue(fit.queueID);
+ fiq.crawlDelay = rules.getCrawlDelay();
+ }
+ }
+ final ProtocolOutput output = protocol.getProtocolOutput(fit.url, fit.row);
+ final ProtocolStatus status = output.getStatus();
+ final Content content = output.getContent();
+ // unblock queue
+ fetchQueues.finishFetchItem(fit);
+
+ switch(status.getCode()) {
+
+ case ProtocolStatus.WOULDBLOCK:
+ // retry ?
+ fetchQueues.addFetchItem(fit);
+ break;
+
+ case ProtocolStatus.SUCCESS: // got a page
+ output(fit, content, status, CrawlDatumHbase.STATUS_FETCHED);
+ updateStatus(content.getContent().length);
+ break;
+
+ case ProtocolStatus.MOVED: // redirect
+ case ProtocolStatus.TEMP_MOVED:
+ byte code;
+ boolean temp;
+ if (status.getCode() == ProtocolStatus.MOVED) {
+ code = CrawlDatumHbase.STATUS_REDIR_PERM;
+ temp = false;
+ } else {
+ code = CrawlDatumHbase.STATUS_REDIR_TEMP;
+ temp = true;
+ }
+ output(fit, content, status, code);
+ final String newUrl = status.getMessage();
+ handleRedirect(fit.url, newUrl, temp, Fetcher.PROTOCOL_REDIR);
+ redirecting = false;
+ break;
+ case ProtocolStatus.EXCEPTION:
+ logError(fit.url, status.getMessage());
+ /* FALLTHROUGH */
+ case ProtocolStatus.RETRY: // retry
+ case ProtocolStatus.BLOCKED:
+ output(fit, null, status, CrawlDatumHbase.STATUS_RETRY);
+ break;
+
+ case ProtocolStatus.GONE: // gone
+ case ProtocolStatus.NOTFOUND:
+ case ProtocolStatus.ACCESS_DENIED:
+ case ProtocolStatus.ROBOTS_DENIED:
+ output(fit, null, status, CrawlDatumHbase.STATUS_GONE);
+ break;
+
+ case ProtocolStatus.NOTMODIFIED:
+ output(fit, null, status, CrawlDatumHbase.STATUS_NOTMODIFIED);
+ break;
+
+ default:
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Unknown ProtocolStatus: " + status.getCode());
+ }
+ output(fit, null, status, CrawlDatumHbase.STATUS_RETRY);
+ }
+
+ if (redirecting && redirectCount >= maxRedirect) {
+ fetchQueues.finishFetchItem(fit);
+ if (LOG.isInfoEnabled()) {
+ LOG.info(" - redirect count exceeded " + fit.url);
+ }
+ output(fit, null, ProtocolStatus.STATUS_REDIR_EXCEEDED, CrawlDatumHbase.STATUS_GONE);
+ }
+
+ } while (redirecting && (redirectCount < maxRedirect));
+
+ } catch (final Throwable t) { // unexpected exception
+ // unblock
+ fetchQueues.finishFetchItem(fit);
+ t.printStackTrace();
+ logError(fit.url, t.toString());
+ output(fit, null, ProtocolStatus.STATUS_FAILED, CrawlDatumHbase.STATUS_RETRY);
+ }
+ }
+
+ } catch (final Throwable e) {
+ if (LOG.isFatalEnabled()) {
+ e.printStackTrace(LogUtil.getFatalStream(LOG));
+ LOG.fatal("fetcher caught:"+e.toString());
+ }
+ } finally {
+ if (fit != null) fetchQueues.finishFetchItem(fit);
+ activeThreads.decrementAndGet(); // count threads
+ LOG.info("-finishing thread " + getName() + ", activeThreads=" + activeThreads);
+ }
+ }
+
+ private void handleRedirect(String url, String newUrl,
+ boolean temp, String redirType)
+ throws URLFilterException, IOException, InterruptedException {
+ newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);
+ newUrl = urlFilters.filter(newUrl);
+ if (newUrl == null || newUrl.equals(url)) {
+ return;
+ }
+ reprUrl = URLUtil.chooseRepr(reprUrl, newUrl, temp);
+ final String reversedNewUrl = TableUtil.reverseUrl(newUrl);
+ // TODO: Find a way to use MutablWebTableRow here
+ Put put = new Put(Bytes.toBytes(reversedNewUrl));
+ if (!reprUrl.equals(url)) {
+ put.add(WebTableColumns.REPR_URL, null, Bytes.toBytes(reprUrl));
+ }
+ put.add(WebTableColumns.METADATA,
+ Fetcher.REDIRECT_DISCOVERED, TableUtil.YES_VAL);
+ context.write(REDUCE_KEY, put);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(" - " + redirType + " redirect to " +
+ reprUrl + " (fetching later)");
+ }
+
+ }
+
+ private void updateStatus(int bytesInPage) throws IOException {
+ pages.incrementAndGet();
+ bytes.addAndGet(bytesInPage);
+ }
+
+ private void output(FetchItem fit, Content content,
+ ProtocolStatus pstatus, byte status)
+ throws IOException, InterruptedException {
+ fit.row.setStatus(status);
+ final long prevFetchTime = fit.row.getFetchTime();
+ fit.row.setPrevFetchTime(prevFetchTime);
+ fit.row.setFetchTime(System.currentTimeMillis());
+ if (pstatus != null) {
+ fit.row.setProtocolStatus(pstatus);
+ }
+
+ if (content != null) {
+ fit.row.setContent(content.getContent());
+ fit.row.setContentType(content.getContentType());
+ fit.row.setBaseUrl(content.getBaseUrl());
+ }
+ fit.row.putMeta(Fetcher.FETCH_MARK, TableUtil.YES_VAL);
+ fit.row.makeRowMutation().writeToContext(REDUCE_KEY, context);
+ }
+
+ private void logError(String url, String message) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("fetch of " + url + " failed with: " + message);
+ }
+ errors.incrementAndGet();
+ }
+ }
+
+ /**
+ * This class feeds the queues with input items, and re-fills them as
+ * items are consumed by FetcherThread-s.
+ */
+ private static class QueueFeeder extends Thread {
+ private final Context context;
+ private final FetchItemQueues queues;
+ private final int size;
+ private Iterator<FetchEntry> currentIter;
+ boolean hasMore;
+
+ public QueueFeeder(Context context,
+ FetchItemQueues queues, int size)
+ throws IOException, InterruptedException {
+ this.context = context;
+ this.queues = queues;
+ this.size = size;
+ this.setDaemon(true);
+ this.setName("QueueFeeder");
+ hasMore = context.nextKey();
+ if (hasMore) {
+ currentIter = context.getValues().iterator();
+ }
+ }
+
+ @Override
+ public void run() {
+ int cnt = 0;
+ try {
+ while (hasMore) {
+ int feed = size - queues.getTotalSize();
+ if (feed <= 0) {
+ // queues are full - spin-wait until they have some free space
+ try {
+ Thread.sleep(1000);
+ } catch (final Exception e) {};
+ continue;
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("-feeding " + feed + " input urls ...");
+ }
+ while (feed > 0 && currentIter.hasNext()) {
+ FetchEntry entry = new FetchEntry();
+ // since currentIter.next() reuses the same
+ // FetchEntry object we need to clone it
+ Writables.copyWritable(currentIter.next(), entry);
+ WebTableRow row = new WebTableRow(entry.getRow());
+ final String url =
+ TableUtil.unreverseUrl(Bytes.toString(entry.getKey().get()));
+ queues.addFetchItem(url, row);
+ feed--;
+ cnt++;
+ }
+ if (currentIter.hasNext()) {
+ continue; // finish items in current list before reading next key
+ }
+ hasMore = context.nextKey();
+ if (hasMore) {
+ currentIter = context.getValues().iterator();
+ }
+ }
+ } catch (Exception e) {
+ LOG.fatal("QueueFeeder error reading input, record " + cnt, e);
+ return;
+ }
+ LOG.info("QueueFeeder finished: total " + cnt + " records.");
+ }
+ }
+
+ @Override
+ public void run(Context context)
+ throws IOException, InterruptedException {
+ Configuration conf = context.getConfiguration();
+ this.fetchQueues = new FetchItemQueues(conf);
+ final int threadCount = conf.getInt("fetcher.threads.fetch", 10);
+ LOG.info("FetcherHbase: threads: " + threadCount);
+
+ // set non-blocking & no-robots mode for HTTP protocol plugins.
+ conf.setBoolean(Protocol.CHECK_BLOCKING, false);
+ conf.setBoolean(Protocol.CHECK_ROBOTS, false);
+
+ feeder = new QueueFeeder(context, fetchQueues, threadCount * 50);
+ feeder.start();
+
+ for (int i = 0; i < threadCount; i++) { // spawn threads
+ FetcherThread ft = new FetcherThread(context, i);
+ fetcherThreads.add(ft);
+ ft.start();
+ }
+ // select a timeout that avoids a task timeout
+ final long timeout = conf.getInt("mapred.task.timeout", 10*60*1000)/2;
+
+ do { // wait for threads to exit
+ try {
+ Thread.sleep(10000);
+ } catch (final InterruptedException e) {}
+
+ context.progress();
+ LOG.info("-activeThreads=" + activeThreads + ", spinWaiting=" + spinWaiting.get()
+ + ", fetchQueues= " + fetchQueues.getQueueCount() +", fetchQueues.totalSize=" + fetchQueues.getTotalSize());
+
+ if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) {
+ fetchQueues.dump();
+ }
+ // some requests seem to hang, despite all intentions
+ if ((System.currentTimeMillis() - lastRequestStart.get()) > timeout) {
+ LOG.warn("Aborting with " + activeThreads + " hung threads.");
+ return;
+ }
+
+ } while (activeThreads.get() > 0);
+ LOG.info("-activeThreads=" + activeThreads);
+ }
+}
diff --git a/src/java/org/apache/nutch/fetcher/OldFetcher.java b/src/java/org/apache/nutch/fetcher/OldFetcher.java
deleted file mode 100644
index 4796a4d37..000000000
--- a/src/java/org/apache/nutch/fetcher/OldFetcher.java
+++ /dev/null
@@ -1,574 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.fetcher;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.util.Map.Entry;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.NutchWritable;
-import org.apache.nutch.crawl.SignatureFactory;
-import org.apache.nutch.metadata.Metadata;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.net.*;
-import org.apache.nutch.protocol.*;
-import org.apache.nutch.parse.*;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.*;
-
-
-/** The fetcher. Most of the work is done by plugins. */
-public class OldFetcher extends Configured implements Tool, MapRunnable<WritableComparable, Writable, Text, NutchWritable> {
-
- public static final Log LOG = LogFactory.getLog(OldFetcher.class);
-
- public static final int PERM_REFRESH_TIME = 5;
-
- public static final String CONTENT_REDIR = "content";
-
- public static final String PROTOCOL_REDIR = "protocol";
-
- public static class InputFormat extends SequenceFileInputFormat<WritableComparable, Writable> {
- /** Don't split inputs, to keep things polite. */
- public InputSplit[] getSplits(JobConf job, int nSplits)
- throws IOException {
- FileStatus[] files = listStatus(job);
- FileSystem fs = FileSystem.get(job);
- InputSplit[] splits = new InputSplit[files.length];
- for (int i = 0; i < files.length; i++) {
- FileStatus cur = files[i];
- splits[i] = new FileSplit(cur.getPath(), 0,
- cur.getLen(), (String[])null);
- }
- return splits;
- }
- }
-
- private RecordReader<WritableComparable, Writable> input;
- private OutputCollector<Text, NutchWritable> output;
- private Reporter reporter;
-
- private String segmentName;
- private int activeThreads;
- private int maxRedirect;
-
- private long start = System.currentTimeMillis(); // start time of fetcher run
- private long lastRequestStart = start;
-
- private long bytes; // total bytes fetched
- private int pages; // total pages fetched
- private int errors; // total pages errored
-
- private boolean storingContent;
- private boolean parsing;
-
- private class FetcherThread extends Thread {
- private Configuration conf;
- private URLFilters urlFilters;
- private ScoringFilters scfilters;
- private ParseUtil parseUtil;
- private URLNormalizers normalizers;
- private ProtocolFactory protocolFactory;
- private boolean redirecting;
- private int redirectCount;
- private String reprUrl;
-
- public FetcherThread(Configuration conf) {
- this.setDaemon(true); // don't hang JVM on exit
- this.setName("FetcherThread"); // use an informative name
- this.conf = conf;
- this.urlFilters = new URLFilters(conf);
- this.scfilters = new ScoringFilters(conf);
- this.parseUtil = new ParseUtil(conf);
- this.protocolFactory = new ProtocolFactory(conf);
- this.normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_FETCHER);
- }
-
- public void run() {
- synchronized (OldFetcher.this) {activeThreads++;} // count threads
-
- try {
- Text key = new Text();
- CrawlDatum datum = new CrawlDatum();
-
- while (true) {
- // TODO : NUTCH-258 ...
- // If something bad happened, then exit
- // if (conf.getBoolean("fetcher.exit", false)) {
- // break;
- // ]
-
- try { // get next entry from input
- if (!input.next(key, datum)) {
- break; // at eof, exit
- }
- } catch (IOException e) {
- if (LOG.isFatalEnabled()) {
- e.printStackTrace(LogUtil.getFatalStream(LOG));
- LOG.fatal("fetcher caught:"+e.toString());
- }
- break;
- }
-
- synchronized (OldFetcher.this) {
- lastRequestStart = System.currentTimeMillis();
- }
-
- // url may be changed through redirects.
- Text url = new Text(key);
-
- Text reprUrlWritable =
- (Text) datum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
- if (reprUrlWritable == null) {
- reprUrl = key.toString();
- } else {
- reprUrl = reprUrlWritable.toString();
- }
-
- try {
- if (LOG.isInfoEnabled()) { LOG.info("fetching " + url); }
-
- // fetch the page
- redirectCount = 0;
- do {
- if (LOG.isDebugEnabled()) {
- LOG.debug("redirectCount=" + redirectCount);
- }
- redirecting = false;
- Protocol protocol = this.protocolFactory.getProtocol(url.toString());
- ProtocolOutput output = protocol.getProtocolOutput(url, datum);
- ProtocolStatus status = output.getStatus();
- Content content = output.getContent();
- ParseStatus pstatus = null;
-
- String urlString = url.toString();
- if (reprUrl != null && !reprUrl.equals(urlString)) {
- datum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
-
- switch(status.getCode()) {
-
- case ProtocolStatus.SUCCESS: // got a page
- pstatus = output(url, datum, content, status, CrawlDatum.STATUS_FETCH_SUCCESS);
- updateStatus(content.getContent().length);
- if (pstatus != null && pstatus.isSuccess() &&
- pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
- String newUrl = pstatus.getMessage();
- int refreshTime = Integer.valueOf(pstatus.getArgs()[1]);
- url = handleRedirect(url, datum, urlString, newUrl,
- refreshTime < PERM_REFRESH_TIME,
- CONTENT_REDIR);
- }
- break;
-
- case ProtocolStatus.MOVED: // redirect
- case ProtocolStatus.TEMP_MOVED:
- int code;
- boolean temp;
- if (status.getCode() == ProtocolStatus.MOVED) {
- code = CrawlDatum.STATUS_FETCH_REDIR_PERM;
- temp = false;
- } else {
- code = CrawlDatum.STATUS_FETCH_REDIR_TEMP;
- temp = true;
- }
- output(url, datum, content, status, code);
- String newUrl = status.getMessage();
- url = handleRedirect(url, datum, urlString, newUrl,
- temp, PROTOCOL_REDIR);
- break;
-
- // failures - increase the retry counter
- case ProtocolStatus.EXCEPTION:
- logError(url, status.getMessage());
- /* FALLTHROUGH */
- case ProtocolStatus.RETRY: // retry
- case ProtocolStatus.WOULDBLOCK:
- case ProtocolStatus.BLOCKED:
- output(url, datum, null, status, CrawlDatum.STATUS_FETCH_RETRY);
- break;
-
- // permanent failures
- case ProtocolStatus.GONE: // gone
- case ProtocolStatus.NOTFOUND:
- case ProtocolStatus.ACCESS_DENIED:
- case ProtocolStatus.ROBOTS_DENIED:
- output(url, datum, null, status, CrawlDatum.STATUS_FETCH_GONE);
- break;
-
- case ProtocolStatus.NOTMODIFIED:
- output(url, datum, null, status, CrawlDatum.STATUS_FETCH_NOTMODIFIED);
- break;
-
- default:
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unknown ProtocolStatus: " + status.getCode());
- }
- output(url, datum, null, status, CrawlDatum.STATUS_FETCH_GONE);
- }
-
- if (redirecting && redirectCount >= maxRedirect) {
- if (LOG.isInfoEnabled()) {
- LOG.info(" - redirect count exceeded " + url);
- }
- output(url, datum, null, status, CrawlDatum.STATUS_FETCH_GONE);
- }
-
- } while (redirecting && (redirectCount < maxRedirect));
-
-
- } catch (Throwable t) { // unexpected exception
- logError(url, t.toString());
- output(url, datum, null, null, CrawlDatum.STATUS_FETCH_RETRY);
-
- }
- }
-
- } catch (Throwable e) {
- if (LOG.isFatalEnabled()) {
- e.printStackTrace(LogUtil.getFatalStream(LOG));
- LOG.fatal("fetcher caught:"+e.toString());
- }
- } finally {
- synchronized (OldFetcher.this) {activeThreads--;} // count threads
- }
- }
-
- private Text handleRedirect(Text url, CrawlDatum datum,
- String urlString, String newUrl,
- boolean temp, String redirType)
- throws MalformedURLException, URLFilterException {
- newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);
- newUrl = urlFilters.filter(newUrl);
- if (newUrl != null && !newUrl.equals(urlString)) {
- reprUrl = URLUtil.chooseRepr(reprUrl, newUrl, temp);
- url = new Text(newUrl);
- if (maxRedirect > 0) {
- redirecting = true;
- redirectCount++;
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching now)");
- }
- return url;
- } else {
- CrawlDatum newDatum = new CrawlDatum();
- if (reprUrl != null) {
- newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
- output(url, newDatum, null, null, CrawlDatum.STATUS_LINKED);
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching later)");
- }
- return null;
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect skipped: " +
- (newUrl != null ? "to same url" : "filtered"));
- }
- return null;
- }
- }
-
- private void logError(Text url, String message) {
- if (LOG.isInfoEnabled()) {
- LOG.info("fetch of " + url + " failed with: " + message);
- }
- synchronized (OldFetcher.this) { // record failure
- errors++;
- }
- }
-
- private ParseStatus output(Text key, CrawlDatum datum,
- Content content, ProtocolStatus pstatus, int status) {
-
- datum.setStatus(status);
- datum.setFetchTime(System.currentTimeMillis());
- if (pstatus != null) datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
-
- ParseResult parseResult = null;
- if (content != null) {
- Metadata metadata = content.getMetadata();
- // add segment to metadata
- metadata.set(Nutch.SEGMENT_NAME_KEY, segmentName);
- // add score to content metadata so that ParseSegment can pick it up.
- try {
- scfilters.passScoreBeforeParsing(key, datum, content);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
- }
- }
- /* Note: Fetcher will only follow meta-redirects coming from the
- * original URL. */
- if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {
- try {
- parseResult = this.parseUtil.parse(content);
- } catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": " + StringUtils.stringifyException(e));
- }
-
- if (parseResult == null) {
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content,
- new ParseStatus().getEmptyParse(conf));
- datum.setSignature(signature);
- }
- }
-
- /* Store status code in content So we can read this value during
- * parsing (as a separate job) and decide to parse or not.
- */
- content.getMetadata().add(Nutch.FETCH_STATUS_KEY, Integer.toString(status));
- }
-
- try {
- output.collect(key, new NutchWritable(datum));
- if (content != null && storingContent)
- output.collect(key, new NutchWritable(content));
- if (parseResult != null) {
- for (Entry<Text, Parse> entry : parseResult) {
- Text url = entry.getKey();
- Parse parse = entry.getValue();
- ParseStatus parseStatus = parse.getData().getStatus();
-
- if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
- parse = parseStatus.getEmptyParse(getConf());
- }
-
- // Calculate page signature. For non-parsing fetchers this will
- // be done in ParseSegment
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content, parse);
- // Ensure segment name and score are in parseData metadata
- parse.getData().getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- segmentName);
- parse.getData().getContentMeta().set(Nutch.SIGNATURE_KEY,
- StringUtil.toHexString(signature));
- // Pass fetch time to content meta
- parse.getData().getContentMeta().set(Nutch.FETCH_TIME_KEY,
- Long.toString(datum.getFetchTime()));
- if (url.equals(key))
- datum.setSignature(signature);
- try {
- scfilters.passScoreAfterParsing(url, content, parse);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
- }
- }
- output.collect(url, new NutchWritable(
- new ParseImpl(new ParseText(parse.getText()),
- parse.getData(), parse.isCanonical())));
- }
- }
- } catch (IOException e) {
- if (LOG.isFatalEnabled()) {
- e.printStackTrace(LogUtil.getFatalStream(LOG));
- LOG.fatal("fetcher caught:"+e.toString());
- }
- }
-
- // return parse status if it exits
- if (parseResult != null && !parseResult.isEmpty()) {
- Parse p = parseResult.get(content.getUrl());
- if (p != null) {
- return p.getData().getStatus();
- }
- }
- return null;
- }
-
- }
-
- private synchronized void updateStatus(int bytesInPage) throws IOException {
- pages++;
- bytes += bytesInPage;
- }
-
- private void reportStatus() throws IOException {
- String status;
- synchronized (this) {
- long elapsed = (System.currentTimeMillis() - start)/1000;
- status =
- pages+" pages, "+errors+" errors, "
- + Math.round(((float)pages*10)/elapsed)/10.0+" pages/s, "
- + Math.round(((((float)bytes)*8)/1024)/elapsed)+" kb/s, ";
- }
- reporter.setStatus(status);
- }
-
- public OldFetcher() {
-
- }
-
- public OldFetcher(Configuration conf) {
- setConf(conf);
- }
-
- public void configure(JobConf job) {
- setConf(job);
-
- this.segmentName = job.get(Nutch.SEGMENT_NAME_KEY);
- this.storingContent = isStoringContent(job);
- this.parsing = isParsing(job);
-
-// if (job.getBoolean("fetcher.verbose", false)) {
-// LOG.setLevel(Level.FINE);
-// }
- }
-
- public void close() {}
-
- public static boolean isParsing(Configuration conf) {
- return conf.getBoolean("fetcher.parse", true);
- }
-
- public static boolean isStoringContent(Configuration conf) {
- return conf.getBoolean("fetcher.store.content", true);
- }
-
- public void run(RecordReader<WritableComparable, Writable> input, OutputCollector<Text, NutchWritable> output,
- Reporter reporter) throws IOException {
-
- this.input = input;
- this.output = output;
- this.reporter = reporter;
-
- this.maxRedirect = getConf().getInt("http.redirect.max", 3);
-
- int threadCount = getConf().getInt("fetcher.threads.fetch", 10);
- if (LOG.isInfoEnabled()) { LOG.info("OldFetcher: threads: " + threadCount); }
-
- for (int i = 0; i < threadCount; i++) { // spawn threads
- new FetcherThread(getConf()).start();
- }
-
- // select a timeout that avoids a task timeout
- long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2;
-
- do { // wait for threads to exit
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {}
-
- reportStatus();
-
- // some requests seem to hang, despite all intentions
- synchronized (this) {
- if ((System.currentTimeMillis() - lastRequestStart) > timeout) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Aborting with "+activeThreads+" hung threads.");
- }
- return;
- }
- }
-
- } while (activeThreads > 0);
-
- }
-
- public void fetch(Path segment, int threads)
- throws IOException {
-
- if (LOG.isInfoEnabled()) {
- LOG.info("OldFetcher: starting");
- LOG.info("OldFetcher: segment: " + segment);
- }
-
- JobConf job = new NutchJob(getConf());
- job.setJobName("fetch " + segment);
-
- job.setInt("fetcher.threads.fetch", threads);
- job.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
-
- // for politeness, don't permit parallel execution of a single task
- job.setSpeculativeExecution(false);
-
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
- job.setInputFormat(InputFormat.class);
-
- job.setMapRunnerClass(OldFetcher.class);
-
- FileOutputFormat.setOutputPath(job, segment);
- job.setOutputFormat(FetcherOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(NutchWritable.class);
-
- JobClient.runJob(job);
- if (LOG.isInfoEnabled()) { LOG.info("OldFetcher: done"); }
- }
-
-
- /** Run the fetcher. */
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new OldFetcher(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
-
- String usage = "Usage: OldFetcher <segment> [-threads n] [-noParsing]";
-
- if (args.length < 1) {
- System.err.println(usage);
- return -1;
- }
-
- Path segment = new Path(args[0]);
- int threads = getConf().getInt("fetcher.threads.fetch", 10);
- boolean parsing = true;
-
- for (int i = 1; i < args.length; i++) { // parse command line
- if (args[i].equals("-threads")) { // found -threads option
- threads = Integer.parseInt(args[++i]);
- } else if (args[i].equals("-noParsing")) parsing = false;
- }
-
- getConf().setInt("fetcher.threads.fetch", threads);
- if (!parsing) {
- getConf().setBoolean("fetcher.parse", parsing);
- }
- try {
- fetch(segment, threads); // run the Fetcher
- return 0;
- } catch (Exception e) {
- LOG.fatal("OldFetcher: " + StringUtils.stringifyException(e));
- return -1;
- }
-
- }
-}
diff --git a/src/java/org/apache/nutch/fetcher/PartitionUrlByHost.java b/src/java/org/apache/nutch/fetcher/PartitionUrlByHost.java
new file mode 100644
index 000000000..13a17c1a9
--- /dev/null
+++ b/src/java/org/apache/nutch/fetcher/PartitionUrlByHost.java
@@ -0,0 +1,23 @@
+package org.apache.nutch.fetcher;
+
+import java.net.URL;
+
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.mapreduce.Partitioner;
+
+public class PartitionUrlByHost
+extends Partitioner<ImmutableBytesWritable, FetchEntry> {
+
+ @Override
+ public int getPartition(ImmutableBytesWritable key,
+ FetchEntry value, int numPartitions) {
+ String urlString = Bytes.toString(value.getKey().get());
+
+ URL url = null;
+
+ int hashCode = (url==null ? urlString : url.getHost()).hashCode();
+
+ return (hashCode & Integer.MAX_VALUE) % numPartitions;
+ }
+}
diff --git a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java b/src/java/org/apache/nutch/indexer/DeleteDuplicates.java
index dedc0864b..507dc347f 100644
--- a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java
+++ b/src/java/org/apache/nutch/indexer/DeleteDuplicates.java
@@ -31,7 +31,7 @@ import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.NutchJobConf;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.document.DateTools;
@@ -424,7 +424,7 @@ public class DeleteDuplicates extends Configured
new Path("dedup-urls-"+
Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(getConf());
+ JobConf job = new NutchJobConf(getConf());
for (int i = 0; i < indexDirs.length; i++) {
if (LOG.isInfoEnabled()) {
@@ -450,7 +450,7 @@ public class DeleteDuplicates extends Configured
Path outDir2 =
new Path("dedup-hash-"+
Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- job = new NutchJob(getConf());
+ job = new NutchJobConf(getConf());
job.setJobName("dedup 2: content by hash");
FileInputFormat.addInputPath(job, outDir1);
@@ -472,7 +472,7 @@ public class DeleteDuplicates extends Configured
// remove outDir1 - no longer needed
fs.delete(outDir1, true);
- job = new NutchJob(getConf());
+ job = new NutchJobConf(getConf());
job.setJobName("dedup 3: delete from index(es)");
FileInputFormat.addInputPath(job, outDir2);
diff --git a/src/java/org/apache/nutch/indexer/Indexer.java b/src/java/org/apache/nutch/indexer/Indexer.java
index 9b92f9e01..be1fcfadc 100644
--- a/src/java/org/apache/nutch/indexer/Indexer.java
+++ b/src/java/org/apache/nutch/indexer/Indexer.java
@@ -1,104 +1,161 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.apache.nutch.indexer;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.filter.Filter;
+import org.apache.hadoop.hbase.filter.FilterList;
+import org.apache.hadoop.hbase.filter.ValueFilter;
+import org.apache.hadoop.hbase.filter.FilterList.Operator;
+import org.apache.hadoop.hbase.filter.ValueFilter.CompareOp;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.indexer.lucene.LuceneWriter;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.scoring.ScoringFilters;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
-/** Create indexes for segments. */
-public class Indexer extends Configured implements Tool {
+public class Indexer
+extends TableMapper<ImmutableBytesWritable, WebTableRow>
+implements Tool {
public static final String DONE_NAME = "index.done";
-
+
public static final Log LOG = LogFactory.getLog(Indexer.class);
- public Indexer() {
- super(null);
+ private static final Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ public static final byte[] INDEX_MARK = Bytes.toBytes("__idxmrk__");
+
+ private Configuration conf;
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.SIGNATURE));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.PARSE_STATUS));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.SCORE));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA, INDEX_MARK));
+ }
+
+ @Override
+ public Configuration getConf() {
+ return conf;
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ @Override
+ public void map(ImmutableBytesWritable key, Result result, Context context)
+ throws IOException, InterruptedException {
+ WebTableRow row = new WebTableRow(result);
+
+ ParseStatus pstatus = row.getParseStatus();
+ if (!pstatus.isSuccess() ||
+ pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
+ return; // filter urls not parsed
+ }
+
+ context.write(key, row);
}
- public Indexer(Configuration conf) {
- super(conf);
+ public static Collection<HbaseColumn> getColumns(Job job) {
+ Configuration conf = job.getConfiguration();
+ Collection<HbaseColumn> columns = new HashSet<HbaseColumn>(COLUMNS);
+ IndexingFilters filters = new IndexingFilters(conf);
+ columns.addAll(filters.getColumns());
+ ScoringFilters scoringFilters = new ScoringFilters(conf);
+ columns.addAll(scoringFilters.getColumns());
+ return columns;
+ }
+
+ public static Job createIndexJob(Configuration conf, String jobName,
+ String table, boolean reindex) throws IOException {
+ Job job = new NutchJob(conf, jobName);
+ Scan scan = TableUtil.createScanFromColumns(getColumns(job));
+ List<Filter> filters = new ArrayList<Filter>();
+ if (!reindex) {
+ filters.add(
+ new ValueFilter(WebTableColumns.METADATA, INDEX_MARK,
+ CompareOp.NOT_EQUAL, TableUtil.YES_VAL, false));
+ }
+ filters.add(
+ new ValueFilter(WebTableColumns.PARSE_STATUS, null,
+ CompareOp.GREATER_OR_EQUAL, new byte[] { (byte)0 }, true));
+ FilterList filterList = new FilterList(Operator.MUST_PASS_ALL, filters);
+ scan.setFilter(filterList);
+ TableMapReduceUtil.initTableMapperJob(table,
+ scan,
+ Indexer.class, ImmutableBytesWritable.class,
+ WebTableRow.class, job);
+
+ job.setReducerClass(IndexerReducer.class);
+ job.setOutputFormatClass(IndexerOutputFormat.class);
+ return job;
}
- public void index(Path luceneDir, Path crawlDb,
- Path linkDb, List<Path> segments)
- throws IOException {
- LOG.info("Indexer: starting");
+ private void index(Path indexDir, String table, boolean reindex) throws Exception {
+ LOG.info("IndexerHbase: starting");
+ LOG.info("IndexerHbase: table: " + table);
- final JobConf job = new NutchJob(getConf());
- job.setJobName("index-lucene " + luceneDir);
+ LuceneWriter.addFieldOptions("segment", LuceneWriter.STORE.YES, LuceneWriter.INDEX.NO, getConf());
+ LuceneWriter.addFieldOptions("digest", LuceneWriter.STORE.YES, LuceneWriter.INDEX.NO, getConf());
+ LuceneWriter.addFieldOptions("boost", LuceneWriter.STORE.YES, LuceneWriter.INDEX.NO, getConf());
- IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
+ NutchIndexWriterFactory.addClassToConf(getConf(), LuceneWriter.class);
- FileOutputFormat.setOutputPath(job, luceneDir);
+ Job job = createIndexJob(getConf(), "index " + table, table, reindex);
- LuceneWriter.addFieldOptions("segment", LuceneWriter.STORE.YES, LuceneWriter.INDEX.NO, job);
- LuceneWriter.addFieldOptions("digest", LuceneWriter.STORE.YES, LuceneWriter.INDEX.NO, job);
- LuceneWriter.addFieldOptions("boost", LuceneWriter.STORE.YES, LuceneWriter.INDEX.NO, job);
+ FileOutputFormat.setOutputPath(job, indexDir);
- NutchIndexWriterFactory.addClassToConf(job, LuceneWriter.class);
+ job.waitForCompletion(true);
+ FileOutputFormat.setOutputPath(job, indexDir);
- JobClient.runJob(job);
- LOG.info("Indexer: done");
+ job.waitForCompletion(true);
+ LOG.info("IndexerHbase: done");
}
public int run(String[] args) throws Exception {
- if (args.length < 4) {
- System.err.println("Usage: Indexer <index> <crawldb> <linkdb> <segment> ...");
- return -1;
- }
+ String usage = "Usage: IndexerHbase <index> <webtable> [-reindex]";
- final Path luceneDir = new Path(args[0]);
- final Path crawlDb = new Path(args[1]);
- final Path linkDb = new Path(args[2]);
-
- final List<Path> segments = new ArrayList<Path>();
- for (int i = 3; i < args.length; i++) {
- segments.add(new Path(args[i]));
+ if (args.length < 2) {
+ System.err.println(usage);
+ System.exit(-1);
}
-
- try {
- index(luceneDir, crawlDb, linkDb, segments);
- return 0;
- } catch (final Exception e) {
- LOG.fatal("Indexer: " + StringUtils.stringifyException(e));
- return -1;
+
+ boolean reindex = false;
+ if (args.length >= 3 && "-reindex".equals(args[2])) {
+ reindex = true;
}
+
+ index(new Path(args[0]), args[1], reindex);
+ return 0;
}
public static void main(String[] args) throws Exception {
- final int res = ToolRunner.run(NutchConfiguration.create(), new Indexer(), args);
+ int res = ToolRunner.run(NutchConfiguration.create(), new Indexer(), args);
System.exit(res);
}
+
}
diff --git a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
deleted file mode 100644
index 8a93d76b7..000000000
--- a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.nutch.indexer;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.CrawlDb;
-import org.apache.nutch.crawl.Inlinks;
-import org.apache.nutch.crawl.LinkDb;
-import org.apache.nutch.crawl.NutchWritable;
-import org.apache.nutch.metadata.Metadata;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.parse.ParseImpl;
-import org.apache.nutch.parse.ParseText;
-import org.apache.nutch.scoring.ScoringFilterException;
-import org.apache.nutch.scoring.ScoringFilters;
-
-public class IndexerMapReduce extends Configured
-implements Mapper<Text, Writable, Text, NutchWritable>,
- Reducer<Text, NutchWritable, Text, NutchDocument> {
-
- public static final Log LOG = LogFactory.getLog(IndexerMapReduce.class);
-
- private IndexingFilters filters;
- private ScoringFilters scfilters;
-
- public void configure(JobConf job) {
- setConf(job);
- this.filters = new IndexingFilters(getConf());
- this.scfilters = new ScoringFilters(getConf());
- }
-
- public void map(Text key, Writable value,
- OutputCollector<Text, NutchWritable> output, Reporter reporter) throws IOException {
- output.collect(key, new NutchWritable(value));
- }
-
- public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text, NutchDocument> output, Reporter reporter)
- throws IOException {
- Inlinks inlinks = null;
- CrawlDatum dbDatum = null;
- CrawlDatum fetchDatum = null;
- ParseData parseData = null;
- ParseText parseText = null;
- while (values.hasNext()) {
- final Writable value = values.next().get(); // unwrap
- if (value instanceof Inlinks) {
- inlinks = (Inlinks)value;
- } else if (value instanceof CrawlDatum) {
- final CrawlDatum datum = (CrawlDatum)value;
- if (CrawlDatum.hasDbStatus(datum))
- dbDatum = datum;
- else if (CrawlDatum.hasFetchStatus(datum)) {
- // don't index unmodified (empty) pages
- if (datum.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED)
- fetchDatum = datum;
- } else if (CrawlDatum.STATUS_LINKED == datum.getStatus() ||
- CrawlDatum.STATUS_SIGNATURE == datum.getStatus()) {
- continue;
- } else {
- throw new RuntimeException("Unexpected status: "+datum.getStatus());
- }
- } else if (value instanceof ParseData) {
- parseData = (ParseData)value;
- } else if (value instanceof ParseText) {
- parseText = (ParseText)value;
- } else if (LOG.isWarnEnabled()) {
- LOG.warn("Unrecognized type: "+value.getClass());
- }
- }
-
- if (fetchDatum == null || dbDatum == null
- || parseText == null || parseData == null) {
- return; // only have inlinks
- }
-
- if (!parseData.getStatus().isSuccess() ||
- fetchDatum.getStatus() != CrawlDatum.STATUS_FETCH_SUCCESS) {
- return;
- }
-
- NutchDocument doc = new NutchDocument();
- final Metadata metadata = parseData.getContentMeta();
-
- // add segment, used to map from merged index back to segment files
- doc.add("segment", metadata.get(Nutch.SEGMENT_NAME_KEY));
-
- // add digest, used by dedup
- doc.add("digest", metadata.get(Nutch.SIGNATURE_KEY));
-
- final Parse parse = new ParseImpl(parseText, parseData);
- try {
- // extract information from dbDatum and pass it to
- // fetchDatum so that indexing filters can use it
- final Text url = (Text) dbDatum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
- if (url != null) {
- fetchDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY, url);
- }
- // run indexing filters
- doc = this.filters.filter(doc, parse, key, fetchDatum, inlinks);
- } catch (final IndexingException e) {
- if (LOG.isWarnEnabled()) { LOG.warn("Error indexing "+key+": "+e); }
- return;
- }
-
- // skip documents discarded by indexing filters
- if (doc == null) return;
-
- float boost = 1.0f;
- // run scoring filters
- try {
- boost = this.scfilters.indexerScore(key, doc, dbDatum,
- fetchDatum, parse, inlinks, boost);
- } catch (final ScoringFilterException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Error calculating score " + key + ": " + e);
- }
- return;
- }
- // apply boost to all indexed fields.
- doc.setScore(boost);
- // store boost for use by explain and dedup
- doc.add("boost", Float.toString(boost));
-
- output.collect(key, doc);
- }
-
- public void close() throws IOException { }
-
- public static void initMRJob(Path crawlDb, Path linkDb,
- Collection<Path> segments,
- JobConf job) {
-
- LOG.info("IndexerMapReduce: crawldb: " + crawlDb);
- LOG.info("IndexerMapReduce: linkdb: " + linkDb);
-
- for (final Path segment : segments) {
- LOG.info("IndexerMapReduces: adding segment: " + segment);
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.FETCH_DIR_NAME));
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.PARSE_DIR_NAME));
- FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME));
- FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
- }
-
- FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- FileInputFormat.addInputPath(job, new Path(linkDb, LinkDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
-
- job.setMapperClass(IndexerMapReduce.class);
- job.setReducerClass(IndexerMapReduce.class);
-
- job.setOutputFormat(IndexerOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setMapOutputValueClass(NutchWritable.class);
- job.setOutputValueClass(NutchWritable.class);
- }
-}
diff --git a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
index 211d4a615..e97f45fe2 100644
--- a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
+++ b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
@@ -18,41 +18,41 @@ package org.apache.nutch.indexer;
import java.io.IOException;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.RecordWriter;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.util.Progressable;
+import org.apache.hadoop.io.WritableComparable;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.nutch.indexer.NutchDocument;
-public class IndexerOutputFormat extends FileOutputFormat<Text, NutchDocument> {
+public class IndexerOutputFormat
+extends FileOutputFormat<WritableComparable<?>, NutchDocument> {
@Override
- public RecordWriter<Text, NutchDocument> getRecordWriter(FileSystem ignored,
- JobConf job, String name, Progressable progress) throws IOException {
-
- // populate JobConf with field indexing options
- IndexingFilters filters = new IndexingFilters(job);
-
+ public RecordWriter<WritableComparable<?>, NutchDocument> getRecordWriter(
+ TaskAttemptContext job) throws IOException, InterruptedException {
+
final NutchIndexWriter[] writers =
- NutchIndexWriterFactory.getNutchIndexWriters(job);
+ NutchIndexWriterFactory.getNutchIndexWriters(job.getConfiguration());
for (final NutchIndexWriter writer : writers) {
- writer.open(job, name);
+ writer.open(job, FileOutputFormat.getUniqueFile(job, "part", ""));
}
- return new RecordWriter<Text, NutchDocument>() {
- public void close(Reporter reporter) throws IOException {
+ return new RecordWriter<WritableComparable<?>, NutchDocument>() {
+
+ @Override
+ public void write(WritableComparable<?> key, NutchDocument doc) throws IOException {
for (final NutchIndexWriter writer : writers) {
- writer.close();
+ writer.write(doc);
}
}
- public void write(Text key, NutchDocument doc) throws IOException {
+ @Override
+ public void close(TaskAttemptContext context) throws IOException,
+ InterruptedException {
for (final NutchIndexWriter writer : writers) {
- writer.write(doc);
- }
+ writer.close();
+ }
}
};
}
diff --git a/src/java/org/apache/nutch/indexer/IndexerReducer.java b/src/java/org/apache/nutch/indexer/IndexerReducer.java
new file mode 100644
index 000000000..8c36a20fb
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/IndexerReducer.java
@@ -0,0 +1,87 @@
+package org.apache.nutch.indexer;
+
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.scoring.ScoringFilterException;
+import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.StringUtil;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.TableUtil;
+
+public class IndexerReducer
+extends Reducer<ImmutableBytesWritable, WebTableRow, ImmutableBytesWritable, NutchDocument> {
+
+ public static final Log LOG = Indexer.LOG;
+
+ private IndexingFilters filters;
+
+ private ScoringFilters scoringFilters;
+
+ private HTable table;
+
+ @Override
+ protected void setup(Context context) throws IOException {
+ Configuration conf = context.getConfiguration();
+ filters = new IndexingFilters(conf);
+ table = new HTable(conf.get(TableInputFormat.INPUT_TABLE));
+ scoringFilters = new ScoringFilters(conf);
+ }
+
+ @Override
+ protected void reduce(ImmutableBytesWritable key, Iterable<WebTableRow> values,
+ Context context) throws IOException, InterruptedException {
+ WebTableRow row = values.iterator().next();
+ NutchDocument doc = new NutchDocument();
+
+ doc.add("id", Bytes.toString(key.get()));
+ doc.add("digest", StringUtil.toHexString(row.getSignature()));
+
+ String url = TableUtil.unreverseUrl(Bytes.toString(key.get()));
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Indexing URL: " + url);
+ }
+
+ try {
+ doc = filters.filter(doc, url, row);
+ } catch (IndexingException e) {
+ LOG.warn("Error indexing "+key+": "+e);
+ return;
+ }
+
+ // skip documents discarded by indexing filters
+ if (doc == null) return;
+
+ float boost = 1.0f;
+ // run scoring filters
+ try {
+ boost = scoringFilters.indexerScore(url, doc, row, boost);
+ } catch (final ScoringFilterException e) {
+ LOG.warn("Error calculating score " + key + ": " + e);
+ return;
+ }
+
+ doc.setScore(boost);
+ // store boost for use by explain and dedup
+ doc.add("boost", Float.toString(boost));
+
+ row.putMeta(Indexer.INDEX_MARK, TableUtil.YES_VAL);
+ row.makeRowMutation().commit(table);
+ context.write(key, doc);
+ }
+
+ @Override
+ public void cleanup(Context context) throws IOException {
+ table.close();
+ }
+
+}
diff --git a/src/java/org/apache/nutch/indexer/IndexingFilter.java b/src/java/org/apache/nutch/indexer/IndexingFilter.java
index c5a5392e3..0e3dd6f03 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFilter.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFilter.java
@@ -20,20 +20,19 @@ package org.apache.nutch.indexer;
// Hadoop imports
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
// Nutch imports
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Inlinks;
-import org.apache.nutch.plugin.Pluggable;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.plugin.TablePluggable;
+import org.apache.nutch.util.hbase.WebTableRow;
/** Extension point for indexing. Permits one to add metadata to the indexed
* fields. All plugins found which implement this extension point are run
* sequentially on the parse.
*/
-public interface IndexingFilter extends Pluggable, Configurable {
+public interface IndexingFilter extends TablePluggable, Configurable {
/** The name of the extension point. */
final static String X_POINT_ID = IndexingFilter.class.getName();
@@ -42,17 +41,15 @@ public interface IndexingFilter extends Pluggable, Configurable {
* parse. Unwanted documents can be removed from indexing by returning a null value.
*
* @param doc document instance for collecting fields
- * @param parse parse data instance
* @param url page url
- * @param datum crawl datum for the page
- * @param inlinks page inlinks
+ * @param url's row
* @return modified (or a new) document instance, or null (meaning the document
* should be discarded)
* @throws IndexingException
*/
- NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException;
-
+ NutchDocument filter(NutchDocument doc, String url, WebTableRow row)
+ throws IndexingException;
+
/** Adds index-level configuraition options.
* Implementations can update given configuration to pass document-independent
* information to indexing backends. As a rule of thumb, prefix meta keys
diff --git a/src/java/org/apache/nutch/indexer/IndexingFilters.java b/src/java/org/apache/nutch/indexer/IndexingFilters.java
index 0fb70484b..41451b72e 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFilters.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFilters.java
@@ -18,24 +18,26 @@
package org.apache.nutch.indexer;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
+import java.util.HashSet;
// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.nutch.plugin.*;
-import org.apache.nutch.parse.Parse;
import org.apache.nutch.util.ObjectCache;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
import org.apache.hadoop.conf.Configuration;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Inlinks;
-import org.apache.hadoop.io.Text;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.NutchDocument;
/** Creates and caches {@link IndexingFilter} implementing plugins.*/
public class IndexingFilters {
- public static final String INDEXINGFILTER_ORDER = "indexingfilter.order";
+ public static final String INDEXINGFILTER_ORDER = "indexingfilterhbase.order";
public final static Log LOG = LogFactory.getLog(IndexingFilters.class);
@@ -86,8 +88,7 @@ public class IndexingFilters {
} else {
ArrayList<IndexingFilter> filters = new ArrayList<IndexingFilter>();
for (int i = 0; i < orderedFilters.length; i++) {
- IndexingFilter filter = filterMap
- .get(orderedFilters[i]);
+ IndexingFilter filter = filterMap.get(orderedFilters[i]);
if (filter != null) {
filter.addIndexBackendOptions(conf);
filters.add(filter);
@@ -102,13 +103,12 @@ public class IndexingFilters {
this.indexingFilters = (IndexingFilter[]) objectCache
.getObject(IndexingFilter.class.getName());
}
- }
-
+ }
/** Run all defined filters. */
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum,
- Inlinks inlinks) throws IndexingException {
- for (int i = 0; i < this.indexingFilters.length; i++) {
- doc = this.indexingFilters[i].filter(doc, parse, url, datum, inlinks);
+ public NutchDocument filter(NutchDocument doc, String url, WebTableRow row)
+ throws IndexingException {
+ for (IndexingFilter indexingFilter : indexingFilters) {
+ doc = indexingFilter.filter(doc, url, row);
// break the loop if an indexing filter discards the doc
if (doc == null) return null;
}
@@ -116,4 +116,12 @@ public class IndexingFilters {
return doc;
}
+ public Collection<HbaseColumn> getColumns() {
+ Collection<HbaseColumn> columns = new HashSet<HbaseColumn>();
+ for (IndexingFilter indexingFilter : indexingFilters) {
+ columns.addAll(indexingFilter.getColumns());
+ }
+ return columns;
+ }
+
}
diff --git a/src/java/org/apache/nutch/indexer/NutchIndexWriter.java b/src/java/org/apache/nutch/indexer/NutchIndexWriter.java
index 24db8db13..7623abd8f 100644
--- a/src/java/org/apache/nutch/indexer/NutchIndexWriter.java
+++ b/src/java/org/apache/nutch/indexer/NutchIndexWriter.java
@@ -18,10 +18,11 @@ package org.apache.nutch.indexer;
import java.io.IOException;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.nutch.indexer.NutchDocument;
public interface NutchIndexWriter {
- public void open(JobConf job, String name) throws IOException;
+ public void open(TaskAttemptContext job, String name) throws IOException;
public void write(NutchDocument doc) throws IOException;
diff --git a/src/java/org/apache/nutch/indexer/lucene/LuceneWriter.java b/src/java/org/apache/nutch/indexer/lucene/LuceneWriter.java
index a28bd3898..608292154 100644
--- a/src/java/org/apache/nutch/indexer/lucene/LuceneWriter.java
+++ b/src/java/org/apache/nutch/indexer/lucene/LuceneWriter.java
@@ -27,11 +27,12 @@ import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.nutch.analysis.AnalyzerFactory;
import org.apache.nutch.analysis.NutchAnalyzer;
import org.apache.nutch.analysis.NutchDocumentAnalyzer;
@@ -39,6 +40,7 @@ import org.apache.nutch.indexer.Indexer;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.NutchIndexWriter;
import org.apache.nutch.indexer.NutchSimilarity;
+import org.apache.nutch.indexer.lucene.LuceneConstants;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.util.LogUtil;
@@ -108,13 +110,13 @@ public class LuceneWriter implements NutchIndexWriter {
} else if (LuceneConstants.STORE_NO.equals(val)) {
store = Field.Store.NO;
} else if (LuceneConstants.INDEX_TOKENIZED.equals(val)) {
- index = Field.Index.TOKENIZED;
+ index = Field.Index.ANALYZED;
} else if (LuceneConstants.INDEX_NO.equals(val)) {
index = Field.Index.NO;
} else if (LuceneConstants.INDEX_UNTOKENIZED.equals(val)) {
- index = Field.Index.UN_TOKENIZED;
+ index = Field.Index.NOT_ANALYZED;
} else if (LuceneConstants.INDEX_NO_NORMS.equals(val)) {
- index = Field.Index.NO_NORMS;
+ index = Field.Index.ANALYZED_NO_NORMS;
} else if (LuceneConstants.VECTOR_NO.equals(val)) {
vector = Field.TermVector.NO;
} else if (LuceneConstants.VECTOR_YES.equals(val)) {
@@ -169,13 +171,13 @@ public class LuceneWriter implements NutchIndexWriter {
fieldIndex.put(field, Field.Index.NO);
break;
case NO_NORMS:
- fieldIndex.put(field, Field.Index.NO_NORMS);
+ fieldIndex.put(field, Field.Index.ANALYZED_NO_NORMS);
break;
case TOKENIZED:
- fieldIndex.put(field, Field.Index.TOKENIZED);
+ fieldIndex.put(field, Field.Index.ANALYZED);
break;
case UNTOKENIZED:
- fieldIndex.put(field, Field.Index.UN_TOKENIZED);
+ fieldIndex.put(field, Field.Index.NOT_ANALYZED);
break;
}
} else if (key.startsWith(LuceneConstants.FIELD_VECTOR_PREFIX)) {
@@ -203,32 +205,35 @@ public class LuceneWriter implements NutchIndexWriter {
}
}
- public void open(JobConf job, String name)
+ public void open(TaskAttemptContext job, String name)
throws IOException {
- this.fs = FileSystem.get(job);
+ Configuration conf = job.getConfiguration();
+ this.fs = FileSystem.get(conf);
perm = new Path(FileOutputFormat.getOutputPath(job), name);
- temp = job.getLocalPath("index/_" +
+ temp = conf.getLocalPath("mapred.local.dir", "index/_" +
Integer.toString(new Random().nextInt()));
fs.delete(perm, true); // delete old, if any
- analyzerFactory = new AnalyzerFactory(job);
+ analyzerFactory = new AnalyzerFactory(conf);
+ MaxFieldLength mfl = new MaxFieldLength(IndexWriter.DEFAULT_MAX_FIELD_LENGTH);
writer = new IndexWriter(fs.startLocalOutput(perm, temp).toString(),
- new NutchDocumentAnalyzer(job), true);
+ new NutchDocumentAnalyzer(conf), true, mfl);
- writer.setMergeFactor(job.getInt("indexer.mergeFactor", 10));
- writer.setMaxBufferedDocs(job.getInt("indexer.minMergeDocs", 100));
- writer.setMaxMergeDocs(job
+ writer.setMergeFactor(conf.getInt("indexer.mergeFactor", 10));
+ writer.setMaxBufferedDocs(conf.getInt("indexer.minMergeDocs", 100));
+ writer.setMaxMergeDocs(conf
.getInt("indexer.maxMergeDocs", Integer.MAX_VALUE));
- writer.setTermIndexInterval(job.getInt("indexer.termIndexInterval", 128));
- writer.setMaxFieldLength(job.getInt("indexer.max.tokens", 10000));
+ writer.setTermIndexInterval(conf.getInt("indexer.termIndexInterval", 128));
+ writer.setMaxFieldLength(conf.getInt("indexer.max.tokens", 10000));
writer.setInfoStream(LogUtil.getDebugStream(Indexer.LOG));
writer.setUseCompoundFile(false);
writer.setSimilarity(new NutchSimilarity());
- processOptions(job);
+ processOptions(conf);
}
public void close() throws IOException {
+ writer.commit();
writer.optimize();
writer.close();
fs.completeLocalOutput(perm, temp); // copy to dfs
diff --git a/src/java/org/apache/nutch/indexer/solr/SolrDeleteDuplicates.java b/src/java/org/apache/nutch/indexer/solr/SolrDeleteDuplicates.java
index df4b2a1d1..3c58dcdb7 100644
--- a/src/java/org/apache/nutch/indexer/solr/SolrDeleteDuplicates.java
+++ b/src/java/org/apache/nutch/indexer/solr/SolrDeleteDuplicates.java
@@ -4,28 +4,28 @@ import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.net.MalformedURLException;
+import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.InputFormat;
-import org.apache.hadoop.mapred.InputSplit;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.RecordReader;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.lib.IdentityMapper;
-import org.apache.hadoop.mapred.lib.NullOutputFormat;
+import org.apache.hadoop.mapreduce.InputFormat;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.JobContext;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.indexer.DeleteDuplicates;
import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
@@ -65,8 +65,8 @@ import org.apache.solr.common.SolrDocumentList;
* documents with <b>different</b> URLs but the same digest.
*/
public class SolrDeleteDuplicates
-implements Reducer<Text, SolrDeleteDuplicates.SolrRecord, Text, SolrDeleteDuplicates.SolrRecord>,
-Tool {
+extends Reducer<Text, SolrDeleteDuplicates.SolrRecord, Text, SolrDeleteDuplicates.SolrRecord>
+implements Tool {
public static final Log LOG = LogFactory.getLog(SolrDeleteDuplicates.class);
@@ -121,7 +121,7 @@ Tool {
}
}
- public static class SolrInputSplit implements InputSplit {
+ public static class SolrInputSplit extends InputSplit {
private int docBegin;
private int numDocs;
@@ -137,10 +137,6 @@ Tool {
return docBegin;
}
- public int getNumDocs() {
- return numDocs;
- }
-
@Override
public long getLength() throws IOException {
return numDocs;
@@ -150,25 +146,72 @@ Tool {
public String[] getLocations() throws IOException {
return new String[] {} ;
}
+ }
+
+ public static class SolrRecordReader extends RecordReader<Text, SolrRecord> {
+ private int currentDoc = 0;
+ private int numDocs;
+ private Text text;
+ private SolrRecord record;
+ private SolrDocumentList solrDocs;
+
+ public SolrRecordReader(SolrDocumentList solrDocs, int numDocs) {
+ this.solrDocs = solrDocs;
+ this.numDocs = numDocs;
+ }
+
@Override
- public void readFields(DataInput in) throws IOException {
- docBegin = in.readInt();
- numDocs = in.readInt();
+ public void initialize(InputSplit split, TaskAttemptContext context)
+ throws IOException, InterruptedException {
+ text = new Text();
+ record = new SolrRecord();
}
@Override
- public void write(DataOutput out) throws IOException {
- out.writeInt(docBegin);
- out.writeInt(numDocs);
+ public void close() throws IOException { }
+
+ @Override
+ public float getProgress() throws IOException {
+ return currentDoc / (float) numDocs;
}
- }
- public static class SolrInputFormat implements InputFormat<Text, SolrRecord> {
+ @Override
+ public Text getCurrentKey() throws IOException, InterruptedException {
+ return text;
+ }
+
+ @Override
+ public SolrRecord getCurrentValue() throws IOException,
+ InterruptedException {
+ return record;
+ }
+
+ @Override
+ public boolean nextKeyValue() throws IOException, InterruptedException {
+ if (currentDoc >= numDocs) {
+ return false;
+ }
+
+ SolrDocument doc = solrDocs.get(currentDoc);
+ String digest = (String) doc.getFieldValue(SolrConstants.DIGEST_FIELD);
+ text.set(digest);
+ record.readSolrDocument(doc);
- /** Return each index as a split. */
- public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
- SolrServer solr = new CommonsHttpSolrServer(job.get(SolrConstants.SERVER_URL));
+ currentDoc++;
+ return true;
+ }
+
+ };
+
+ public static class SolrInputFormat extends InputFormat<Text, SolrRecord> {
+
+ @Override
+ public List<InputSplit> getSplits(JobContext context)
+ throws IOException, InterruptedException {
+ Configuration conf = context.getConfiguration();
+ int numSplits = context.getNumReduceTasks();
+ SolrServer solr = new CommonsHttpSolrServer(conf.get(SolrConstants.SERVER_URL));
final SolrQuery solrQuery = new SolrQuery(SOLR_GET_ALL_QUERY);
solrQuery.setFields(SolrConstants.ID_FIELD);
@@ -184,24 +227,23 @@ Tool {
int numResults = (int)response.getResults().getNumFound();
int numDocsPerSplit = (numResults / numSplits);
int currentDoc = 0;
- SolrInputSplit[] splits = new SolrInputSplit[numSplits];
+ List<InputSplit> splits = new ArrayList<InputSplit>();
for (int i = 0; i < numSplits - 1; i++) {
- splits[i] = new SolrInputSplit(currentDoc, numDocsPerSplit);
+ splits.add(new SolrInputSplit(currentDoc, numDocsPerSplit));
currentDoc += numDocsPerSplit;
}
- splits[splits.length - 1] = new SolrInputSplit(currentDoc, numResults - currentDoc);
+ splits.add(new SolrInputSplit(currentDoc, numResults - currentDoc));
return splits;
}
- public RecordReader<Text, SolrRecord> getRecordReader(final InputSplit split,
- final JobConf job,
- Reporter reporter)
- throws IOException {
-
- SolrServer solr = new CommonsHttpSolrServer(job.get(SolrConstants.SERVER_URL));
+ @Override
+ public RecordReader<Text, SolrRecord> createRecordReader(InputSplit split,
+ TaskAttemptContext context) throws IOException, InterruptedException {
+ Configuration conf = context.getConfiguration();
+ SolrServer solr = new CommonsHttpSolrServer(conf.get(SolrConstants.SERVER_URL));
SolrInputSplit solrSplit = (SolrInputSplit) split;
- final int numDocs = solrSplit.getNumDocs();
+ final int numDocs = (int) solrSplit.getLength();
SolrQuery solrQuery = new SolrQuery(SOLR_GET_ALL_QUERY);
solrQuery.setFields(SolrConstants.ID_FIELD, SolrConstants.BOOST_FIELD,
@@ -218,49 +260,7 @@ Tool {
}
final SolrDocumentList solrDocs = response.getResults();
-
- return new RecordReader<Text, SolrRecord>() {
-
- private int currentDoc = 0;
-
- @Override
- public void close() throws IOException { }
-
- @Override
- public Text createKey() {
- return new Text();
- }
-
- @Override
- public SolrRecord createValue() {
- return new SolrRecord();
- }
-
- @Override
- public long getPos() throws IOException {
- return currentDoc;
- }
-
- @Override
- public float getProgress() throws IOException {
- return currentDoc / (float) numDocs;
- }
-
- @Override
- public boolean next(Text key, SolrRecord value) throws IOException {
- if (currentDoc >= numDocs) {
- return false;
- }
-
- SolrDocument doc = solrDocs.get(currentDoc);
- String digest = (String) doc.getFieldValue(SolrConstants.DIGEST_FIELD);
- key.set(digest);
- value.readSolrDocument(doc);
-
- currentDoc++;
- return true;
- }
- };
+ return new SolrRecordReader(solrDocs, numDocs);
}
}
@@ -283,34 +283,34 @@ Tool {
}
@Override
- public void configure(JobConf job) {
+ public void setup(Context job) throws IOException {
+ Configuration conf = job.getConfiguration();
try {
- solr = new CommonsHttpSolrServer(job.get(SolrConstants.SERVER_URL));
+ solr = new CommonsHttpSolrServer(conf.get(SolrConstants.SERVER_URL));
} catch (MalformedURLException e) {
- throw new RuntimeException(e);
+ throw new IOException(e);
}
}
@Override
- public void close() throws IOException {
+ public void cleanup(Context context) throws IOException {
try {
if (numDeletes > 0) {
updateRequest.process(solr);
}
- solr.optimize();
} catch (SolrServerException e) {
throw new IOException(e);
}
}
@Override
- public void reduce(Text key, Iterator<SolrRecord> values,
- OutputCollector<Text, SolrRecord> output, Reporter reporter)
+ public void reduce(Text key, Iterable<SolrRecord> values, Context context)
throws IOException {
- SolrRecord recordToKeep = values.next();
- while (values.hasNext()) {
- SolrRecord solrRecord = values.next();
+ Iterator<SolrRecord> iterator = values.iterator();
+ SolrRecord recordToKeep = iterator.next();
+ while (iterator.hasNext()) {
+ SolrRecord solrRecord = iterator.next();
if (solrRecord.getBoost() > recordToKeep.getBoost() ||
(solrRecord.getBoost() == recordToKeep.getBoost() &&
solrRecord.getTstamp() > recordToKeep.getTstamp())) {
@@ -332,33 +332,39 @@ Tool {
}
}
- public void dedup(String solrUrl) throws IOException {
+ public boolean dedup(String solrUrl)
+ throws IOException, InterruptedException, ClassNotFoundException {
LOG.info("SolrDeleteDuplicates: starting...");
LOG.info("SolrDeleteDuplicates: Solr url: " + solrUrl);
- JobConf job = new NutchJob(getConf());
+ getConf().set(SolrConstants.SERVER_URL, solrUrl);
+
+ Job job = new Job(getConf(), "solrdedup");
- job.set(SolrConstants.SERVER_URL, solrUrl);
- job.setInputFormat(SolrInputFormat.class);
- job.setOutputFormat(NullOutputFormat.class);
+ job.setInputFormatClass(SolrInputFormat.class);
+ job.setOutputFormatClass(NullOutputFormat.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(SolrRecord.class);
- job.setMapperClass(IdentityMapper.class);
+ job.setMapperClass(Mapper.class);
job.setReducerClass(SolrDeleteDuplicates.class);
- JobClient.runJob(job);
-
- LOG.info("SolrDeleteDuplicates: done.");
+ return job.waitForCompletion(true);
}
- public int run(String[] args) throws IOException {
+ public int run(String[] args)
+ throws IOException, InterruptedException, ClassNotFoundException {
if (args.length != 1) {
System.err.println("Usage: SolrDeleteDuplicates <solr url>");
return 1;
}
- dedup(args[0]);
- return 0;
+ boolean result = dedup(args[0]);
+ if (result) {
+ LOG.info("SolrDeleteDuplicates: done.");
+ return 0;
+ }
+
+ return -1;
}
public static void main(String[] args) throws Exception {
diff --git a/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java b/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java
index ce18e1117..38872355a 100644
--- a/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java
+++ b/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java
@@ -16,9 +16,6 @@
*/
package org.apache.nutch.indexer.solr;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Random;
import org.apache.commons.logging.Log;
@@ -27,16 +24,15 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
-import org.apache.nutch.indexer.IndexerMapReduce;
+import org.apache.nutch.indexer.Indexer;
import org.apache.nutch.indexer.NutchIndexWriterFactory;
+import org.apache.nutch.indexer.solr.SolrConstants;
import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
public class SolrIndexer extends Configured implements Tool {
@@ -50,49 +46,40 @@ public class SolrIndexer extends Configured implements Tool {
super(conf);
}
- private void indexSolr(String solrUrl, Path crawlDb, Path linkDb,
- List<Path> segments) throws IOException {
+ private void indexSolr(String solrUrl, String table, boolean reindex)
+ throws Exception {
LOG.info("SolrIndexer: starting");
- final JobConf job = new NutchJob(getConf());
- job.setJobName("index-solr " + solrUrl);
-
- IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
-
- job.set(SolrConstants.SERVER_URL, solrUrl);
-
- NutchIndexWriterFactory.addClassToConf(job, SolrWriter.class);
-
- job.setReduceSpeculativeExecution(false);
+ NutchIndexWriterFactory.addClassToConf(getConf(), SolrWriter.class);
+ getConf().set(SolrConstants.SERVER_URL, solrUrl);
+ final Job job = Indexer.createIndexJob(getConf(), "solr-index " + table,
+ table, reindex);;
final Path tmp = new Path("tmp_" + System.currentTimeMillis() + "-" +
new Random().nextInt());
FileOutputFormat.setOutputPath(job, tmp);
try {
- JobClient.runJob(job);
+ job.waitForCompletion(true);
} finally {
- FileSystem.get(job).delete(tmp, true);
+ FileSystem.get(getConf()).delete(tmp, true);
}
LOG.info("SolrIndexer: done");
}
public int run(String[] args) throws Exception {
- if (args.length < 4) {
- System.err.println("Usage: SolrIndexer <solr url> <crawldb> <linkdb> <segment> ...");
+ if (args.length < 2) {
+ System.err.println("Usage: SolrIndexer <solr url> <webtable> [-reindex]");
return -1;
}
- final Path crawlDb = new Path(args[1]);
- final Path linkDb = new Path(args[2]);
-
- final List<Path> segments = new ArrayList<Path>();
- for (int i = 3; i < args.length; i++) {
- segments.add(new Path(args[i]));
+ boolean reindex = false;
+ if (args.length > 2 && "-reindex".equals(args[2])) {
+ reindex = true;
}
try {
- indexSolr(args[0], crawlDb, linkDb, segments);
+ indexSolr(args[0], args[1], reindex);
return 0;
} catch (final Exception e) {
LOG.fatal("SolrIndexer: " + StringUtils.stringifyException(e));
diff --git a/src/java/org/apache/nutch/indexer/solr/SolrWriter.java b/src/java/org/apache/nutch/indexer/solr/SolrWriter.java
index 7a9664afb..ceb6e92e2 100644
--- a/src/java/org/apache/nutch/indexer/solr/SolrWriter.java
+++ b/src/java/org/apache/nutch/indexer/solr/SolrWriter.java
@@ -21,7 +21,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.NutchIndexWriter;
import org.apache.solr.client.solrj.SolrServer;
@@ -38,12 +39,15 @@ public class SolrWriter implements NutchIndexWriter {
private int commitSize;
- public void open(JobConf job, String name)
+ @Override
+ public void open(TaskAttemptContext job, String name)
throws IOException {
- solr = new CommonsHttpSolrServer(job.get(SolrConstants.SERVER_URL));
- commitSize = job.getInt(SolrConstants.COMMIT_SIZE, 1000);
+ Configuration conf = job.getConfiguration();
+ solr = new CommonsHttpSolrServer(conf.get(SolrConstants.SERVER_URL));
+ commitSize = conf.getInt(SolrConstants.COMMIT_SIZE, 1000);
}
+ @Override
public void write(NutchDocument doc) throws IOException {
final SolrInputDocument inputDoc = new SolrInputDocument();
for(final Entry<String, List<String>> e : doc) {
@@ -57,12 +61,13 @@ public class SolrWriter implements NutchIndexWriter {
try {
solr.add(inputDocs);
} catch (final SolrServerException e) {
- throw makeIOException(e);
+ throw new IOException(e);
}
inputDocs.clear();
}
}
+ @Override
public void close() throws IOException {
try {
if (!inputDocs.isEmpty()) {
@@ -71,14 +76,8 @@ public class SolrWriter implements NutchIndexWriter {
}
solr.commit();
} catch (final SolrServerException e) {
- throw makeIOException(e);
+ throw new IOException(e);
}
}
- public static IOException makeIOException(SolrServerException e) {
- final IOException ioe = new IOException();
- ioe.initCause(e);
- return ioe;
- }
-
}
diff --git a/src/java/org/apache/nutch/parse/HTMLMetaTags.java b/src/java/org/apache/nutch/parse/HTMLMetaTags.java
index 0148aaabf..9a5d4de86 100644
--- a/src/java/org/apache/nutch/parse/HTMLMetaTags.java
+++ b/src/java/org/apache/nutch/parse/HTMLMetaTags.java
@@ -188,7 +188,7 @@ public class HTMLMetaTags {
+ ", refreshHref=" + refreshHref + "\n"
);
sb.append(" * general tags:\n");
- Iterator it = generalTags.keySet().iterator();
+ Iterator<?> it = generalTags.keySet().iterator();
while (it.hasNext()) {
String key = (String)it.next();
sb.append(" - " + key + "\t=\t" + generalTags.get(key) + "\n");
diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilter.java b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
index 18e81f41d..7b34b8fa7 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilter.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
@@ -1,42 +1,27 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.apache.nutch.parse;
-// JDK imports
import org.w3c.dom.DocumentFragment;
// Hadoop imports
import org.apache.hadoop.conf.Configurable;
// Nutch imports
-import org.apache.nutch.plugin.Pluggable;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.plugin.TablePluggable;
+import org.apache.nutch.util.hbase.WebTableRow;
/** Extension point for DOM-based HTML parsers. Permits one to add additional
* metadata to HTML parses. All plugins found which implement this extension
* point are run sequentially on the parse.
*/
-public interface HtmlParseFilter extends Pluggable, Configurable {
+public interface HtmlParseFilter extends TablePluggable, Configurable {
/** The name of the extension point. */
final static String X_POINT_ID = HtmlParseFilter.class.getName();
/** Adds metadata or otherwise modifies a parse of HTML content, given
* the DOM tree of a page. */
- ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc);
+ Parse filter(String url, WebTableRow row, Parse parseResult,
+ HTMLMetaTags metaTags, DocumentFragment doc);
+
}
diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilters.java b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
index 90acaac6b..93bfdb23f 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilters.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
@@ -17,11 +17,15 @@
package org.apache.nutch.parse;
+import java.util.Collection;
import java.util.HashMap;
+import java.util.HashSet;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.parse.HTMLMetaTags;
import org.apache.nutch.plugin.*;
import org.apache.nutch.util.ObjectCache;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
import org.apache.hadoop.conf.Configuration;
import org.w3c.dom.DocumentFragment;
@@ -33,51 +37,59 @@ public class HtmlParseFilters {
public HtmlParseFilters(Configuration conf) {
ObjectCache objectCache = ObjectCache.get(conf);
- this.htmlParseFilters = (HtmlParseFilter[]) objectCache.getObject(HtmlParseFilter.class.getName());
+ this.htmlParseFilters =
+ (HtmlParseFilter[]) objectCache.getObject(HtmlParseFilter.class.getName());
if (htmlParseFilters == null) {
HashMap<String, HtmlParseFilter> filters =
new HashMap<String, HtmlParseFilter>();
try {
- ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(HtmlParseFilter.X_POINT_ID);
+ ExtensionPoint point =
+ PluginRepository.get(conf).getExtensionPoint(HtmlParseFilter.X_POINT_ID);
if (point == null)
throw new RuntimeException(HtmlParseFilter.X_POINT_ID + " not found.");
Extension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
- HtmlParseFilter parseFilter = (HtmlParseFilter) extension.getExtensionInstance();
+ HtmlParseFilter parseFilter =
+ (HtmlParseFilter) extension.getExtensionInstance();
if (!filters.containsKey(parseFilter.getClass().getName())) {
filters.put(parseFilter.getClass().getName(), parseFilter);
}
}
- HtmlParseFilter[] htmlParseFilters = filters.values().toArray(new HtmlParseFilter[filters.size()]);
+ HtmlParseFilter[] htmlParseFilters =
+ filters.values().toArray(new HtmlParseFilter[filters.size()]);
objectCache.setObject(HtmlParseFilter.class.getName(), htmlParseFilters);
} catch (PluginRuntimeException e) {
throw new RuntimeException(e);
}
- this.htmlParseFilters = (HtmlParseFilter[]) objectCache.getObject(HtmlParseFilter.class.getName());
+ this.htmlParseFilters =
+ (HtmlParseFilter[])objectCache.getObject(HtmlParseFilter.class.getName());
}
}
/** Run all defined filters. */
- public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) {
+ public Parse filter(String url, WebTableRow row, Parse parse,
+ HTMLMetaTags metaTags, DocumentFragment doc) {
// loop on each filter
- for (int i = 0 ; i < this.htmlParseFilters.length; i++) {
+ for (HtmlParseFilter htmlParseFilter : htmlParseFilters) {
// call filter interface
- parseResult =
- htmlParseFilters[i].filter(content, parseResult, metaTags, doc);
+ parse = htmlParseFilter.filter(url, row, parse, metaTags, doc);
// any failure on parse obj, return
- if (!parseResult.isSuccess()) {
- // TODO: What happens when parseResult.isEmpty() ?
- // Maybe clone parseResult and use parseResult as backup...
-
- // remove failed parse before return
- parseResult.filter();
- return parseResult;
+ if (!parse.getParseStatus().isSuccess()) {
+ return parse;
}
}
- return parseResult;
+ return parse;
+ }
+
+ public Collection<HbaseColumn> getColumns() {
+ Collection<HbaseColumn> columns = new HashSet<HbaseColumn>();
+ for (HtmlParseFilter htmlParseFilter : htmlParseFilters) {
+ columns.addAll(htmlParseFilter.getColumns());
+ }
+ return columns;
}
}
diff --git a/src/java/org/apache/nutch/parse/Outlink.java b/src/java/org/apache/nutch/parse/Outlink.java
index 744140c0a..6ae8f5f63 100644
--- a/src/java/org/apache/nutch/parse/Outlink.java
+++ b/src/java/org/apache/nutch/parse/Outlink.java
@@ -18,7 +18,6 @@
package org.apache.nutch.parse;
import java.io.*;
-import java.net.MalformedURLException;
import org.apache.hadoop.io.*;
@@ -30,7 +29,7 @@ public class Outlink implements Writable {
public Outlink() {}
- public Outlink(String toUrl, String anchor) throws MalformedURLException {
+ public Outlink(String toUrl, String anchor) {
this.toUrl = toUrl;
if (anchor == null) anchor = "";
this.anchor = anchor;
diff --git a/src/java/org/apache/nutch/parse/OutlinkExtractor.java b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
index 1e4c93f0d..998f3c599 100644
--- a/src/java/org/apache/nutch/parse/OutlinkExtractor.java
+++ b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
@@ -17,7 +17,6 @@
package org.apache.nutch.parse;
-import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
@@ -110,11 +109,7 @@ public class OutlinkExtractor {
}
result = matcher.getMatch();
url = result.group(0);
- try {
- outlinks.add(new Outlink(url, anchor));
- } catch (MalformedURLException mue) {
- LOG.warn("Invalid url: '" + url + "', skipping.");
- }
+ outlinks.add(new Outlink(url, anchor));
}
} catch (Exception ex) {
// if the matcher fails (perhaps a malformed URL) we just log it and move on
diff --git a/src/java/org/apache/nutch/parse/Parse.java b/src/java/org/apache/nutch/parse/Parse.java
index 9096bf1a8..b6c14cc7b 100644
--- a/src/java/org/apache/nutch/parse/Parse.java
+++ b/src/java/org/apache/nutch/parse/Parse.java
@@ -1,34 +1,82 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.apache.nutch.parse;
-/** The result of parsing a page's raw content.
- * @see Parser#getParse(Content)
- */
-public interface Parse {
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.ParseStatus;
+
+public class Parse implements Writable {
+
+ private String text;
+ private String title;
+ private Outlink[] outlinks;
+ private ParseStatus parseStatus;
+
+ public Parse() {
+ }
- /** The textual content of the page. This is indexed, searched, and used when
- * generating snippets.*/
- String getText();
+ public Parse(String text, String title, Outlink[] outlinks,
+ ParseStatus parseStatus) {
+ this.text = text;
+ this.title = title;
+ this.outlinks = outlinks;
+ this.parseStatus = parseStatus;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public String getTitle() {
+ return title;
+ }
- /** Other data extracted from the page. */
- ParseData getData();
+ public Outlink[] getOutlinks() {
+ return outlinks;
+ }
+
+ public ParseStatus getParseStatus() {
+ return parseStatus;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public void setOutlinks(Outlink[] outlinks) {
+ this.outlinks = outlinks;
+ }
+
+ public void setParseStatus(ParseStatus parseStatus) {
+ this.parseStatus = parseStatus;
+ }
- /** Indicates if the parse is coming from a url or a sub-url */
- boolean isCanonical();
+ public void readFields(DataInput in) throws IOException {
+ text = Text.readString(in);
+ title = Text.readString(in);
+ int numOutlinks = in.readInt();
+ outlinks = new Outlink[numOutlinks];
+ for (int i = 0; i < numOutlinks; i++) {
+ outlinks[i] = Outlink.read(in);
+ }
+ parseStatus = ParseStatus.read(in);
+ }
+
+ public void write(DataOutput out) throws IOException {
+ Text.writeString(out, text);
+ Text.writeString(out, title);
+ out.writeInt(outlinks.length);
+ for (Outlink outlink : outlinks) {
+ outlink.write(out);
+ }
+ parseStatus.write(out);
+ }
}
diff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.java
index c8da2c305..cc0bf9ccc 100644
--- a/src/java/org/apache/nutch/parse/ParseData.java
+++ b/src/java/org/apache/nutch/parse/ParseData.java
@@ -21,6 +21,7 @@ import java.io.*;
import java.util.*;
import org.apache.hadoop.io.*;
+import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
@@ -197,16 +198,20 @@ public final class ParseData extends VersionedWritable {
return buffer.toString();
}
- public static void main(String argv[]) throws Exception {
- String usage = "ParseData (-local | -dfs <namenode:port>) recno segment";
+ public static void main(String args[]) throws Exception {
+ String usage = "ParseData (-fs <local|namenode:port>) recno segment";
- if (argv.length < 3) {
+ if (args.length < 3) {
System.out.println("usage:" + usage);
return;
}
- Configuration conf = NutchConfiguration.create();
- FileSystem fs = FileSystem.parseArgs(argv, 0, conf);
+ GenericOptionsParser optParser =
+ new GenericOptionsParser(NutchConfiguration.create(), args);
+ String[] argv = optParser.getRemainingArgs();
+ Configuration conf = optParser.getConfiguration();
+
+ FileSystem fs = FileSystem.get(conf);
try {
int recno = Integer.parseInt(argv[0]);
String segment = argv[1];
diff --git a/src/java/org/apache/nutch/parse/ParseImpl.java b/src/java/org/apache/nutch/parse/ParseImpl.java
deleted file mode 100644
index 4c9847508..000000000
--- a/src/java/org/apache/nutch/parse/ParseImpl.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.parse;
-
-import java.io.*;
-import org.apache.hadoop.io.*;
-
-
-/** The result of parsing a page's raw content.
- * @see Parser#getParse(Content)
- */
-public class ParseImpl implements Parse, Writable {
- private ParseText text;
- private ParseData data;
- private boolean isCanonical;
-
- public ParseImpl() {}
-
- public ParseImpl(Parse parse) {
- this(new ParseText(parse.getText()), parse.getData(), true);
- }
-
- public ParseImpl(String text, ParseData data) {
- this(new ParseText(text), data, true);
- }
-
- public ParseImpl(ParseText text, ParseData data) {
- this(text, data, true);
- }
-
- public ParseImpl(ParseText text, ParseData data, boolean isCanonical) {
- this.text = text;
- this.data = data;
- this.isCanonical = isCanonical;
- }
-
- public String getText() { return text.getText(); }
-
- public ParseData getData() { return data; }
-
- public boolean isCanonical() { return isCanonical; }
-
- public final void write(DataOutput out) throws IOException {
- out.writeBoolean(isCanonical);
- text.write(out);
- data.write(out);
- }
-
- public void readFields(DataInput in) throws IOException {
- isCanonical = in.readBoolean();
- text = new ParseText();
- text.readFields(in);
-
- data = new ParseData();
- data.readFields(in);
- }
-
- public static ParseImpl read(DataInput in) throws IOException {
- ParseImpl parseImpl = new ParseImpl();
- parseImpl.readFields(in);
- return parseImpl;
- }
-
-}
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
deleted file mode 100644
index 7dd042246..000000000
--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.parse;
-
-// Commons Logging imports
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.io.SequenceFile.CompressionType;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.fetcher.Fetcher;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.nutch.scoring.ScoringFilterException;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.StringUtil;
-import org.apache.nutch.util.URLUtil;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.net.*;
-
-import java.io.*;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.util.Progressable;
-
-/* Parse content in a segment. */
-public class ParseOutputFormat implements OutputFormat<Text, Parse> {
- private static final Log LOG = LogFactory.getLog(ParseOutputFormat.class);
-
- private URLFilters filters;
- private URLNormalizers normalizers;
- private ScoringFilters scfilters;
-
- private static class SimpleEntry implements Entry<Text, CrawlDatum> {
- private Text key;
- private CrawlDatum value;
-
- public SimpleEntry(Text key, CrawlDatum value) {
- this.key = key;
- this.value = value;
- }
-
- public Text getKey() {
- return key;
- }
-
- public CrawlDatum getValue() {
- return value;
- }
-
- public CrawlDatum setValue(CrawlDatum value) {
- this.value = value;
- return this.value;
- }
- }
-
- public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
- Path out = FileOutputFormat.getOutputPath(job);
- if (fs.exists(new Path(out, CrawlDatum.PARSE_DIR_NAME)))
- throw new IOException("Segment already parsed!");
- }
-
- public RecordWriter<Text, Parse> getRecordWriter(FileSystem fs, JobConf job,
- String name, Progressable progress) throws IOException {
-
- this.filters = new URLFilters(job);
- this.normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK);
- this.scfilters = new ScoringFilters(job);
- final int interval = job.getInt("db.fetch.interval.default", 2592000);
- final boolean ignoreExternalLinks = job.getBoolean("db.ignore.external.links", false);
- int maxOutlinksPerPage = job.getInt("db.max.outlinks.per.page", 100);
- final int maxOutlinks = (maxOutlinksPerPage < 0) ? Integer.MAX_VALUE
- : maxOutlinksPerPage;
- final CompressionType compType = SequenceFileOutputFormat.getOutputCompressionType(job);
- Path out = FileOutputFormat.getOutputPath(job);
-
- Path text = new Path(new Path(out, ParseText.DIR_NAME), name);
- Path data = new Path(new Path(out, ParseData.DIR_NAME), name);
- Path crawl = new Path(new Path(out, CrawlDatum.PARSE_DIR_NAME), name);
-
- final MapFile.Writer textOut =
- new MapFile.Writer(job, fs, text.toString(), Text.class, ParseText.class,
- CompressionType.RECORD, progress);
-
- final MapFile.Writer dataOut =
- new MapFile.Writer(job, fs, data.toString(), Text.class, ParseData.class,
- compType, progress);
-
- final SequenceFile.Writer crawlOut =
- SequenceFile.createWriter(fs, job, crawl, Text.class, CrawlDatum.class,
- compType, progress);
-
- return new RecordWriter<Text, Parse>() {
-
-
- public void write(Text key, Parse parse)
- throws IOException {
-
- String fromUrl = key.toString();
- String fromHost = null;
- String toHost = null;
- textOut.append(key, new ParseText(parse.getText()));
-
- ParseData parseData = parse.getData();
- // recover the signature prepared by Fetcher or ParseSegment
- String sig = parseData.getContentMeta().get(Nutch.SIGNATURE_KEY);
- if (sig != null) {
- byte[] signature = StringUtil.fromHexString(sig);
- if (signature != null) {
- // append a CrawlDatum with a signature
- CrawlDatum d = new CrawlDatum(CrawlDatum.STATUS_SIGNATURE, 0);
- d.setSignature(signature);
- crawlOut.append(key, d);
- }
- }
-
- try {
- ParseStatus pstatus = parseData.getStatus();
- if (pstatus != null && pstatus.isSuccess() &&
- pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
- String newUrl = pstatus.getMessage();
- int refreshTime = Integer.valueOf(pstatus.getArgs()[1]);
- newUrl = normalizers.normalize(newUrl,
- URLNormalizers.SCOPE_FETCHER);
- newUrl = filters.filter(newUrl);
- String url = key.toString();
- if (newUrl != null && !newUrl.equals(url)) {
- String reprUrl =
- URLUtil.chooseRepr(url, newUrl,
- refreshTime < Fetcher.PERM_REFRESH_TIME);
- CrawlDatum newDatum = new CrawlDatum();
- newDatum.setStatus(CrawlDatum.STATUS_LINKED);
- if (reprUrl != null && !reprUrl.equals(newUrl)) {
- newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
- crawlOut.append(new Text(newUrl), newDatum);
- }
- }
- } catch (URLFilterException e) {
- // ignore
- }
-
- // collect outlinks for subsequent db update
- Outlink[] links = parseData.getOutlinks();
- int outlinksToStore = Math.min(maxOutlinks, links.length);
- if (ignoreExternalLinks) {
- try {
- fromHost = new URL(fromUrl).getHost().toLowerCase();
- } catch (MalformedURLException e) {
- fromHost = null;
- }
- } else {
- fromHost = null;
- }
-
- int validCount = 0;
- CrawlDatum adjust = null;
- List<Entry<Text, CrawlDatum>> targets = new ArrayList<Entry<Text, CrawlDatum>>(outlinksToStore);
- List<Outlink> outlinkList = new ArrayList<Outlink>(outlinksToStore);
- for (int i = 0; i < links.length && validCount < outlinksToStore; i++) {
- String toUrl = links[i].getToUrl();
- // ignore links to self (or anchors within the page)
- if (fromUrl.equals(toUrl)) {
- continue;
- }
- if (ignoreExternalLinks) {
- try {
- toHost = new URL(toUrl).getHost().toLowerCase();
- } catch (MalformedURLException e) {
- toHost = null;
- }
- if (toHost == null || !toHost.equals(fromHost)) { // external links
- continue; // skip it
- }
- }
- try {
- toUrl = normalizers.normalize(toUrl,
- URLNormalizers.SCOPE_OUTLINK); // normalize the url
- toUrl = filters.filter(toUrl); // filter the url
- if (toUrl == null) {
- continue;
- }
- } catch (Exception e) {
- continue;
- }
- CrawlDatum target = new CrawlDatum(CrawlDatum.STATUS_LINKED, interval);
- Text targetUrl = new Text(toUrl);
- try {
- scfilters.initialScore(targetUrl, target);
- } catch (ScoringFilterException e) {
- LOG.warn("Cannot filter init score for url " + key +
- ", using default: " + e.getMessage());
- target.setScore(0.0f);
- }
-
- targets.add(new SimpleEntry(targetUrl, target));
- outlinkList.add(links[i]);
- validCount++;
- }
- try {
- // compute score contributions and adjustment to the original score
- adjust = scfilters.distributeScoreToOutlinks((Text)key, parseData,
- targets, null, links.length);
- } catch (ScoringFilterException e) {
- LOG.warn("Cannot distribute score from " + key + ": " + e.getMessage());
- }
- for (Entry<Text, CrawlDatum> target : targets) {
- crawlOut.append(target.getKey(), target.getValue());
- }
- if (adjust != null) crawlOut.append(key, adjust);
-
- Outlink[] filteredLinks = outlinkList.toArray(new Outlink[outlinkList.size()]);
- parseData = new ParseData(parseData.getStatus(), parseData.getTitle(),
- filteredLinks, parseData.getContentMeta(),
- parseData.getParseMeta());
- dataOut.append(key, parseData);
- if (!parse.isCanonical()) {
- CrawlDatum datum = new CrawlDatum();
- datum.setStatus(CrawlDatum.STATUS_FETCH_SUCCESS);
- String timeString = parse.getData().getContentMeta().get(Nutch.FETCH_TIME_KEY);
- try {
- datum.setFetchTime(Long.parseLong(timeString));
- } catch (Exception e) {
- LOG.warn("Can't read fetch time for: " + key);
- datum.setFetchTime(System.currentTimeMillis());
- }
- crawlOut.append(key, datum);
- }
- }
-
- public void close(Reporter reporter) throws IOException {
- textOut.close();
- dataOut.close();
- crawlOut.close();
- }
-
- };
-
- }
-
-}
diff --git a/src/java/org/apache/nutch/parse/ParsePluginList.java b/src/java/org/apache/nutch/parse/ParsePluginList.java
index 22fd3cf9a..1160b2948 100644
--- a/src/java/org/apache/nutch/parse/ParsePluginList.java
+++ b/src/java/org/apache/nutch/parse/ParsePluginList.java
@@ -32,7 +32,7 @@ import java.util.Map;
* @author mattmann
* @version 1.0
*/
-class ParsePluginList {
+public class ParsePluginList {
/* a map to link mimeType to an ordered list of parsing plugins */
private Map<String, List<String>> fMimeTypeToPluginMap = null;
@@ -49,7 +49,7 @@ class ParsePluginList {
aliases = new HashMap<String, String>();
}
- List<String> getPluginList(String mimeType) {
+ public List<String> getPluginList(String mimeType) {
return fMimeTypeToPluginMap.get(mimeType);
}
@@ -57,7 +57,7 @@ class ParsePluginList {
this.aliases = aliases;
}
- Map<String, String> getAliases() {
+ public Map<String, String> getAliases() {
return aliases;
}
diff --git a/src/java/org/apache/nutch/parse/ParsePluginsReader.java b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
index 6fc959f56..9962404ba 100644
--- a/src/java/org/apache/nutch/parse/ParsePluginsReader.java
+++ b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
@@ -50,7 +50,7 @@ import org.apache.nutch.util.NutchConfiguration;
* @author mattmann
* @version 1.0
*/
-class ParsePluginsReader {
+public class ParsePluginsReader {
/* our log stream */
public static final Log LOG = LogFactory.getLog(ParsePluginsReader.class);
diff --git a/src/java/org/apache/nutch/parse/ParseResult.java b/src/java/org/apache/nutch/parse/ParseResult.java
deleted file mode 100644
index 82b3efec4..000000000
--- a/src/java/org/apache/nutch/parse/ParseResult.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.parse;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.io.Text;
-
-/**
- * A utility class that stores result of a parse. Internally
- * a ParseResult stores &lt;{@link Text}, {@link Parse}&gt; pairs.
- * <p>Parsers may return multiple results, which correspond to parts
- * or other associated documents related to the original URL.</p>
- * <p>There will be usually one parse result that corresponds directly
- * to the original URL, and possibly many (or none) results that correspond
- * to derived URLs (or sub-URLs).
- */
-public class ParseResult implements Iterable<Map.Entry<Text, Parse>> {
- private Map<Text, Parse> parseMap;
- private String originalUrl;
-
- public static final Log LOG = LogFactory.getLog(ParseResult.class);
-
- /**
- * Create a container for parse results.
- * @param originalUrl the original url from which all parse results
- * have been obtained.
- */
- public ParseResult(String originalUrl) {
- parseMap = new HashMap<Text, Parse>();
- this.originalUrl = originalUrl;
- }
-
- /**
- * Convenience method for obtaining {@link ParseResult} from a single
- * {@link Parse} output.
- * @param url canonical url
- * @param parse single parse output
- * @return result containing the single parse output
- */
- public static ParseResult createParseResult(String url, Parse parse) {
- ParseResult parseResult = new ParseResult(url);
- parseResult.put(new Text(url), new ParseText(parse.getText()), parse.getData());
- return parseResult;
- }
-
- /**
- * Checks whether the result is empty.
- * @return
- */
- public boolean isEmpty() {
- return parseMap.isEmpty();
- }
-
- /**
- * Return the number of parse outputs (both successful and failed)
- */
- public int size() {
- return parseMap.size();
- }
-
- /**
- * Retrieve a single parse output.
- * @param key sub-url under which the parse output is stored.
- * @return parse output corresponding to this sub-url, or null.
- */
- public Parse get(String key) {
- return get(new Text(key));
- }
-
- /**
- * Retrieve a single parse output.
- * @param key sub-url under which the parse output is stored.
- * @return parse output corresponding to this sub-url, or null.
- */
- public Parse get(Text key) {
- return parseMap.get(key);
- }
-
- /**
- * Store a result of parsing.
- * @param key URL or sub-url of this parse result
- * @param text plain text result
- * @param data corresponding parse metadata of this result
- */
- public void put(Text key, ParseText text, ParseData data) {
- put(key.toString(), text, data);
- }
-
- /**
- * Store a result of parsing.
- * @param key URL or sub-url of this parse result
- * @param text plain text result
- * @param data corresponding parse metadata of this result
- */
- public void put(String key, ParseText text, ParseData data) {
- parseMap.put(new Text(key), new ParseImpl(text, data, key.equals(originalUrl)));
- }
-
- /**
- * Iterate over all entries in the &lt;url, Parse&gt; map.
- */
- public Iterator<Entry<Text, Parse>> iterator() {
- return parseMap.entrySet().iterator();
- }
-
- /**
- * Remove all results where status is not successful (as determined
- * by {@link ParseStatus#isSuccess()}). Note that effects of this operation
- * cannot be reversed.
- */
- public void filter() {
- for(Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
- Entry<Text, Parse> entry = i.next();
- if (!entry.getValue().getData().getStatus().isSuccess()) {
- LOG.warn(entry.getKey() + " is not parsed successfully, filtering");
- i.remove();
- }
- }
-
- }
-
- /**
- * A convenience method which returns true only if all parses are successful.
- * Parse success is determined by {@link ParseStatus#isSuccess()}
- */
- public boolean isSuccess() {
- for(Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
- Entry<Text, Parse> entry = i.next();
- if (!entry.getValue().getData().getStatus().isSuccess()) {
- return false;
- }
- }
- return true;
- }
-}
diff --git a/src/java/org/apache/nutch/parse/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.java
deleted file mode 100644
index abdad07b5..000000000
--- a/src/java/org/apache/nutch/parse/ParseSegment.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.parse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.SignatureFactory;
-import org.apache.hadoop.io.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.util.*;
-import org.apache.hadoop.conf.*;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.protocol.*;
-import org.apache.nutch.scoring.ScoringFilterException;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.*;
-import org.apache.hadoop.fs.Path;
-
-import java.io.*;
-import java.util.*;
-import java.util.Map.Entry;
-
-/* Parse content in a segment. */
-public class ParseSegment extends Configured implements Tool,
- Mapper<WritableComparable, Content, Text, ParseImpl>,
- Reducer<Text, Writable, Text, Writable> {
-
- public static final Log LOG = LogFactory.getLog(Parser.class);
-
- private ScoringFilters scfilters;
-
- public ParseSegment() {
- this(null);
- }
-
- public ParseSegment(Configuration conf) {
- super(conf);
- }
-
- public void configure(JobConf job) {
- setConf(job);
- this.scfilters = new ScoringFilters(job);
- }
-
- public void close() {}
-
- private Text newKey = new Text();
-
- public void map(WritableComparable key, Content content,
- OutputCollector<Text, ParseImpl> output, Reporter reporter)
- throws IOException {
- // convert on the fly from old UTF8 keys
- if (key instanceof UTF8) {
- newKey.set(key.toString());
- key = newKey;
- }
-
- int status =
- Integer.parseInt(content.getMetadata().get(Nutch.FETCH_STATUS_KEY));
- if (status != CrawlDatum.STATUS_FETCH_SUCCESS) {
- // content not fetched successfully, skip document
- LOG.debug("Skipping " + key + " as content is not fetched successfully");
- return;
- }
-
- ParseResult parseResult = null;
- try {
- parseResult = new ParseUtil(getConf()).parse(content);
- } catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": " + StringUtils.stringifyException(e));
- return;
- }
-
- for (Entry<Text, Parse> entry : parseResult) {
- Text url = entry.getKey();
- Parse parse = entry.getValue();
- ParseStatus parseStatus = parse.getData().getStatus();
-
- if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
- parse = parseStatus.getEmptyParse(getConf());
- }
-
- // pass segment name to parse data
- parse.getData().getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- getConf().get(Nutch.SEGMENT_NAME_KEY));
-
- // compute the new signature
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content, parse);
- parse.getData().getContentMeta().set(Nutch.SIGNATURE_KEY,
- StringUtil.toHexString(signature));
-
- try {
- scfilters.passScoreAfterParsing(url, content, parse);
- } catch (ScoringFilterException e) {
- if (LOG.isWarnEnabled()) {
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- LOG.warn("Error passing score: "+ url +": "+e.getMessage());
- }
- }
- output.collect(url, new ParseImpl(new ParseText(parse.getText()),
- parse.getData(), parse.isCanonical()));
- }
- }
-
- public void reduce(Text key, Iterator<Writable> values,
- OutputCollector<Text, Writable> output, Reporter reporter)
- throws IOException {
- output.collect(key, (Writable)values.next()); // collect first value
- }
-
- public void parse(Path segment) throws IOException {
-
- if (LOG.isInfoEnabled()) {
- LOG.info("Parse: starting");
- LOG.info("Parse: segment: " + segment);
- }
-
- JobConf job = new NutchJob(getConf());
- job.setJobName("parse " + segment);
-
- FileInputFormat.addInputPath(job, new Path(segment, Content.DIR_NAME));
- job.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(ParseSegment.class);
- job.setReducerClass(ParseSegment.class);
-
- FileOutputFormat.setOutputPath(job, segment);
- job.setOutputFormat(ParseOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(ParseImpl.class);
-
- JobClient.runJob(job);
- if (LOG.isInfoEnabled()) { LOG.info("Parse: done"); }
- }
-
-
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new ParseSegment(), args);
- System.exit(res);
- }
-
- public int run(String[] args) throws Exception {
- Path segment;
-
- String usage = "Usage: ParseSegment segment";
-
- if (args.length == 0) {
- System.err.println(usage);
- System.exit(-1);
- }
- segment = new Path(args[0]);
- parse(segment);
- return 0;
- }
-}
diff --git a/src/java/org/apache/nutch/parse/ParseStatus.java b/src/java/org/apache/nutch/parse/ParseStatus.java
index d86d95846..29b34556e 100644
--- a/src/java/org/apache/nutch/parse/ParseStatus.java
+++ b/src/java/org/apache/nutch/parse/ParseStatus.java
@@ -30,8 +30,6 @@ import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.conf.Configuration;
-import org.apache.nutch.metadata.Metadata;
-
/**
* @author Andrzej Bialecki &lt;[email protected]&gt;
@@ -201,12 +199,19 @@ public class ParseStatus implements Writable {
return new EmptyParseImpl(this, conf);
}
+ /** A convenience method. Creates an empty ParseHbase instance,
+ * which returns this status.
+ */
+ public Parse getEmptyParseHbase(Configuration conf) {
+ return new Parse("", "", new Outlink[0], this);
+ }
+
/** A convenience method. Creates an empty ParseResult,
* which contains this status.
*/
- public ParseResult getEmptyParseResult(String url, Configuration conf) {
- return ParseResult.createParseResult(url, getEmptyParse(conf));
- }
+ //public ParseResult getEmptyParseResult(String url, Configuration conf) {
+ // return ParseResult.createParseResult(url, getEmptyParse(conf));
+ //}
public String toString() {
StringBuffer res = new StringBuffer();
@@ -267,25 +272,10 @@ public class ParseStatus implements Writable {
return true;
}
- private static class EmptyParseImpl implements Parse {
-
- private ParseData data = null;
-
- public EmptyParseImpl(ParseStatus status, Configuration conf) {
- data = new ParseData(status, "", new Outlink[0],
- new Metadata(), new Metadata());
- }
-
- public ParseData getData() {
- return data;
- }
-
- public String getText() {
- return "";
- }
+ private static class EmptyParseImpl extends Parse {
- public boolean isCanonical() {
- return true;
+ public EmptyParseImpl(ParseStatus parseStatus, Configuration conf) {
+ super("", "", new Outlink[0], parseStatus);
}
}
}
diff --git a/src/java/org/apache/nutch/parse/ParseText.java b/src/java/org/apache/nutch/parse/ParseText.java
index b79fb95f7..6189b2a81 100644
--- a/src/java/org/apache/nutch/parse/ParseText.java
+++ b/src/java/org/apache/nutch/parse/ParseText.java
@@ -19,6 +19,7 @@ package org.apache.nutch.parse;
import java.io.*;
import org.apache.hadoop.io.*;
+import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.nutch.util.NutchConfiguration;
@@ -79,16 +80,20 @@ public final class ParseText implements Writable {
return text;
}
- public static void main(String argv[]) throws Exception {
+ public static void main(String args[]) throws Exception {
String usage = "ParseText (-local | -dfs <namenode:port>) recno segment";
- if (argv.length < 3) {
+ if (args.length < 3) {
System.out.println("usage:" + usage);
return;
}
+
+ GenericOptionsParser optParser =
+ new GenericOptionsParser(NutchConfiguration.create(), args);
+ String[] argv = optParser.getRemainingArgs();
+ Configuration conf = optParser.getConfiguration();
- Configuration conf = NutchConfiguration.create();
- FileSystem fs = FileSystem.parseArgs(argv, 0, conf);
+ FileSystem fs = FileSystem.get(conf);
try {
int recno = Integer.parseInt(argv[0]);
String segment = argv[1];
diff --git a/src/java/org/apache/nutch/parse/ParseUtil.java b/src/java/org/apache/nutch/parse/ParseUtil.java
index 40434662a..b7335755e 100644
--- a/src/java/org/apache/nutch/parse/ParseUtil.java
+++ b/src/java/org/apache/nutch/parse/ParseUtil.java
@@ -21,12 +21,13 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// Nutch Imports
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.parse.ParserNotFound;
+import org.apache.nutch.util.hbase.WebTableRow;
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
-
/**
* A Utility class containing methods to simply perform parsing utilities such
* as iterating through a preferred list of {@link Parser}s to obtain
@@ -56,84 +57,37 @@ public class ParseUtil {
* returned. If the parse is unsuccessful, a message is logged to the
* <code>WARNING</code> level, and an empty parse is returned.
*
- * @param content The content to try and parse.
- * @return &lt;key, {@link Parse}&gt; pairs.
* @throws ParseException If no suitable parser is found to perform the parse.
*/
- public ParseResult parse(Content content) throws ParseException {
+ public Parse parse(String url, WebTableRow row) throws ParseException {
Parser[] parsers = null;
+ String contentType = row.getContentType();
+
try {
- parsers = this.parserFactory.getParsers(content.getContentType(),
- content.getUrl() != null ? content.getUrl():"");
+ parsers = this.parserFactory.getParsers(contentType, url);
} catch (ParserNotFound e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("No suitable parser found when trying to parse content " + content.getUrl() +
- " of type " + content.getContentType());
+ LOG.warn("No suitable parser found when trying to parse content " + url +
+ " of type " + contentType);
}
throw new ParseException(e.getMessage());
}
- ParseResult parseResult = null;
+ Parse parse = null;
for (int i=0; i<parsers.length; i++) {
if (LOG.isDebugEnabled()) {
- LOG.debug("Parsing [" + content.getUrl() + "] with [" + parsers[i] + "]");
+ LOG.debug("Parsing [" + url + "] with [" + parsers[i] + "]");
}
- parseResult = parsers[i].getParse(content);
- if (parseResult != null && !parseResult.isEmpty())
- return parseResult;
+ parse = parsers[i].getParse(url, row);
+ if (parse != null)
+ return parse;
}
if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to successfully parse content " + content.getUrl() +
- " of type " + content.getContentType());
+ LOG.warn("Unable to successfully parse content " + url +
+ " of type " + contentType);
}
return null;
}
-
- /**
- * Method parses a {@link Content} object using the {@link Parser} specified
- * by the parameter <code>extId</code>, i.e., the Parser's extension ID.
- * If a suitable {@link Parser} is not found, then a <code>WARNING</code>
- * level message is logged, and a ParseException is thrown. If the parse is
- * uncessful for any other reason, then a <code>WARNING</code> level
- * message is logged, and a <code>ParseStatus.getEmptyParse()</code> is
- * returned.
- *
- * @param extId The extension implementation ID of the {@link Parser} to use
- * to parse the specified content.
- * @param content The content to parse.
- *
- * @return &lt;key, {@link Parse}&gt; pairs if the parse is successful, otherwise,
- * a single &lt;key, <code>ParseStatus.getEmptyParse()</code>&gt; pair.
- *
- * @throws ParseException If there is no suitable {@link Parser} found
- * to perform the parse.
- */
- public ParseResult parseByExtensionId(String extId, Content content)
- throws ParseException {
- Parser p = null;
-
- try {
- p = this.parserFactory.getParserById(extId);
- } catch (ParserNotFound e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("No suitable parser found when trying to parse content " + content.getUrl() +
- " of type " + content.getContentType());
- }
- throw new ParseException(e.getMessage());
- }
-
- ParseResult parseResult = p.getParse(content);
- if (parseResult != null && !parseResult.isEmpty()) {
- return parseResult;
- } else {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to successfully parse content " + content.getUrl() +
- " of type " + content.getContentType());
- }
- return null;
- }
- }
-
}
diff --git a/src/java/org/apache/nutch/parse/Parser.java b/src/java/org/apache/nutch/parse/Parser.java
index 0f8b68084..daf1e9604 100644
--- a/src/java/org/apache/nutch/parse/Parser.java
+++ b/src/java/org/apache/nutch/parse/Parser.java
@@ -21,36 +21,27 @@ package org.apache.nutch.parse;
import org.apache.hadoop.conf.Configurable;
// Nutch imports
-import org.apache.nutch.plugin.Pluggable;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.plugin.TablePluggable;
+import org.apache.nutch.util.hbase.WebTableRow;
/** A parser for content generated by a {@link org.apache.nutch.protocol.Protocol}
* implementation. This interface is implemented by extensions. Nutch's core
* contains no page parsing code.
*/
-public interface Parser extends Pluggable, Configurable {
+public interface Parser extends TablePluggable, Configurable {
/** The name of the extension point. */
public final static String X_POINT_ID = Parser.class.getName();
/**
* <p>
- * This method parses the given content and returns a map of
- * &lt;key, parse&gt; pairs. {@link Parse} instances will be persisted
- * under the given key.
- * </p>
- * <p>
- * Note: Meta-redirects should be followed only when they are coming from
- * the original URL. That is: <br>
- * Assume fetcher is in parsing mode and is currently processing
- * foo.bar.com/redirect.html. If this url contains a meta redirect
- * to another url, fetcher should only follow the redirect if the map
- * contains an entry of the form &lt;"foo.bar.com/redirect.html",
- * {@link Parse} with a {@link ParseStatus} indicating the redirect&gt;.
+ * This method takes a Hbase table row and returns a {@link Parse} instance
* </p>
*
- * @param c Content to be parsed
- * @return a map containing &lt;key, parse&gt; pairs
- * @since NUTCH-443
+ * @param url Page's URL
+ * @param row url's row. Parse plugins can add their updates here. They
+ * will be reflected in hbase. Plugins must not update for items already
+ * in ParseHbase
+ * @return Parse
*/
- ParseResult getParse(Content c);
+ Parse getParse(String url, WebTableRow row);
}
diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.java
deleted file mode 100644
index 01b601c3d..000000000
--- a/src/java/org/apache/nutch/parse/ParserChecker.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.parse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.apache.hadoop.conf.Configuration;
-
-import org.apache.nutch.util.NutchConfiguration;
-
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.parse.ParseUtil;
-
-import org.apache.nutch.protocol.ProtocolFactory;
-import org.apache.nutch.protocol.Protocol;
-import org.apache.nutch.protocol.Content;
-
-/**
- * Parser checker, useful for testing parser.
- *
- * @author John Xing
- */
-
-public class ParserChecker {
-
- public static final Log LOG = LogFactory.getLog(ParserChecker.class);
-
- public ParserChecker() {}
-
- public static void main(String[] args) throws Exception {
- boolean dumpText = false;
- boolean force = false;
- String contentType = null;
- String url = null;
-
- String usage = "Usage: ParserChecker [-dumpText] [-forceAs mimeType] url";
-
- if (args.length == 0) {
- System.err.println(usage);
- System.exit(-1);
- }
-
- for (int i = 0; i < args.length; i++) {
- if (args[i].equals("-forceAs")) {
- force = true;
- contentType = args[++i];
- } else if (args[i].equals("-dumpText")) {
- dumpText = true;
- } else if (i != args.length-1) {
- System.err.println(usage);
- System.exit(-1);
- } else {
- url = args[i];
- }
- }
-
- if (LOG.isInfoEnabled()) { LOG.info("fetching: "+url); }
-
- Configuration conf = NutchConfiguration.create();
- ProtocolFactory factory = new ProtocolFactory(conf);
- Protocol protocol = factory.getProtocol(url);
- Content content = protocol.getProtocolOutput(new Text(url), new CrawlDatum()).getContent();
-
- if (force) {
- content.setContentType(contentType);
- } else {
- contentType = content.getContentType();
- }
-
- if (contentType == null) {
- System.err.println("");
- System.exit(-1);
- }
-
- if (LOG.isInfoEnabled()) {
- LOG.info("parsing: "+url);
- LOG.info("contentType: "+contentType);
- }
-
- ParseResult parseResult = new ParseUtil(conf).parse(content);
-
- for (java.util.Map.Entry<Text, Parse> entry : parseResult) {
- Parse parse = entry.getValue();
- System.out.print("---------\nUrl\n---------------\n");
- System.out.print(entry.getKey());
- System.out.print("---------\nParseData\n---------\n");
- System.out.print(parse.getData().toString());
- if (dumpText) {
- System.out.print("---------\nParseText\n---------\n");
- System.out.print(parse.getText());
- }
- }
-
- System.exit(0);
- }
-}
diff --git a/src/java/org/apache/nutch/parse/ParserFactory.java b/src/java/org/apache/nutch/parse/ParserFactory.java
index ee8975e51..0fa1ef390 100644
--- a/src/java/org/apache/nutch/parse/ParserFactory.java
+++ b/src/java/org/apache/nutch/parse/ParserFactory.java
@@ -18,10 +18,10 @@ package org.apache.nutch.parse;
// JDK imports
import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
+import java.util.Collection;
+import java.util.HashSet;
import java.util.List;
-import java.util.Vector;
+import java.util.Set;
// Commons Logging imports
import org.apache.commons.logging.Log;
@@ -31,6 +31,9 @@ import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
// Nutch imports
+import org.apache.nutch.parse.ParsePluginList;
+import org.apache.nutch.parse.ParsePluginsReader;
+import org.apache.nutch.parse.ParserNotFound;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
import org.apache.nutch.plugin.PluginRuntimeException;
@@ -38,6 +41,7 @@ import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.LogUtil;
import org.apache.nutch.util.MimeUtil;
import org.apache.nutch.util.ObjectCache;
+import org.apache.nutch.util.hbase.HbaseColumn;
/** Creates and caches {@link Parser} plugins.*/
@@ -49,7 +53,8 @@ public final class ParserFactory {
public static final String DEFAULT_PLUGIN = "*";
/** Empty extension list for caching purposes. */
- private final List EMPTY_EXTENSION_LIST = Collections.EMPTY_LIST;
+ private final List<Extension> EMPTY_EXTENSION_LIST =
+ new ArrayList<Extension>();
private Configuration conf;
private ExtensionPoint extensionPoint;
@@ -121,9 +126,8 @@ public final class ParserFactory {
throw new ParserNotFound(url, contentType);
}
- parsers = new Vector<Parser>(parserExts.size());
- for (Iterator i=parserExts.iterator(); i.hasNext(); ){
- Extension ext = (Extension) i.next();
+ parsers = new ArrayList<Parser>(parserExts.size());
+ for (Extension ext : parserExts){
Parser p = null;
try {
//check to see if we've cached this parser instance yet
@@ -207,6 +211,20 @@ public final class ParserFactory {
}
}
+ public Collection<HbaseColumn> getColumns() {
+ Set<HbaseColumn> columns = new HashSet<HbaseColumn>();
+ Extension[] extensions = this.extensionPoint.getExtensions();
+ for (Extension ext : extensions) {
+ try {
+ Parser parser = (Parser) ext.getExtensionInstance();
+ columns.addAll(parser.getColumns());
+ } catch (PluginRuntimeException e) {
+ // ignore
+ }
+ }
+ return columns;
+ }
+
/**
* Finds the best-suited parse plugin for a given contentType.
*
@@ -214,6 +232,7 @@ public final class ParserFactory {
* @return a list of extensions to be used for this contentType.
* If none, returns <code>null</code>.
*/
+ @SuppressWarnings("unchecked")
protected List<Extension> getExtensions(String contentType) {
ObjectCache objectCache = ObjectCache.get(conf);
@@ -221,7 +240,6 @@ public final class ParserFactory {
String type = null;
type = MimeUtil.cleanMimeType(contentType);
-
List<Extension> extensions = (List<Extension>) objectCache.getObject(type);
// Just compare the reference:
diff --git a/src/java/org/apache/nutch/parse/TableParser.java b/src/java/org/apache/nutch/parse/TableParser.java
new file mode 100644
index 000000000..1a230074c
--- /dev/null
+++ b/src/java/org/apache/nutch/parse/TableParser.java
@@ -0,0 +1,276 @@
+package org.apache.nutch.parse;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.filter.Filter;
+import org.apache.hadoop.hbase.filter.FilterList;
+import org.apache.hadoop.hbase.filter.ValueFilter;
+import org.apache.hadoop.hbase.filter.FilterList.Operator;
+import org.apache.hadoop.hbase.filter.ValueFilter.CompareOp;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.IdentityTableReducer;
+import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.crawl.CrawlDatumHbase;
+import org.apache.nutch.crawl.Signature;
+import org.apache.nutch.crawl.SignatureFactory;
+import org.apache.nutch.fetcher.Fetcher;
+import org.apache.nutch.net.URLFilterException;
+import org.apache.nutch.net.URLFilters;
+import org.apache.nutch.net.URLNormalizers;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.URLUtil;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.TableUtil;
+
+public class TableParser
+extends TableMapper<ImmutableBytesWritable, ImmutableBytesWritable>
+implements Tool {
+
+ public static final Log LOG = LogFactory.getLog(TableParser.class);
+
+ public static final String PARSE_MARK_STR = "__prsmrk__";
+
+ public static final byte[] PARSE_MARK = Bytes.toBytes("__prsmrk__");
+
+ private static final Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ private Configuration conf;
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.STATUS));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.CONTENT));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.CONTENT_TYPE));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.SIGNATURE));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA, Fetcher.FETCH_MARK));
+ }
+
+ private ParseUtil parseUtil;
+ private Signature sig;
+ private URLFilters filters;
+ private URLNormalizers normalizers;
+ private int maxOutlinks;
+ private boolean ignoreExternalLinks;
+ private HTable table;
+
+ @Override
+ public void setup(Context context) throws IOException {
+ Configuration conf = context.getConfiguration();
+ parseUtil = new ParseUtil(conf);
+ sig = SignatureFactory.getSignature(conf);
+ filters = new URLFilters(conf);
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_OUTLINK);
+ final int maxOutlinksPerPage = conf.getInt("db.max.outlinks.per.page", 100);
+ maxOutlinks = (maxOutlinksPerPage < 0) ? Integer.MAX_VALUE
+ : maxOutlinksPerPage;
+ ignoreExternalLinks = conf.getBoolean("db.ignore.external.links", false);
+ table = new HTable(conf.get(TableInputFormat.INPUT_TABLE));
+ }
+
+ @Override
+ public void map(ImmutableBytesWritable key, Result result, Context context)
+ throws IOException {
+ final WebTableRow row = new WebTableRow(result);
+ final String url = TableUtil.unreverseUrl(Bytes.toString(key.get()));
+ final byte status = row.getStatus();
+ if (status != CrawlDatumHbase.STATUS_FETCHED) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Skipping " + url + " as status is: " +
+ CrawlDatumHbase.getName(status));
+ }
+ return;
+ }
+
+ Parse parse;
+ try {
+ parse = parseUtil.parse(url, row);
+ } catch (final Exception e) {
+ LOG.warn("Error parsing: " + url + ": " + StringUtils.stringifyException(e));
+ return;
+ }
+
+ final byte[] signature = sig.calculate(row, parse);
+
+ final ParseStatus pstatus = parse.getParseStatus();
+ row.setParseStatus(pstatus);
+ if (pstatus.isSuccess()) {
+ if (pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
+ String newUrl = pstatus.getMessage();
+ final int refreshTime = Integer.parseInt(pstatus.getArgs()[1]);
+ newUrl = normalizers.normalize(newUrl,
+ URLNormalizers.SCOPE_FETCHER);
+ try {
+ newUrl = filters.filter(newUrl);
+ } catch (URLFilterException e) {
+ return; // TODO: is this correct
+ }
+ if (newUrl == null || newUrl.equals(url)) {
+ final String reprUrl = URLUtil.chooseRepr(url, newUrl,
+ refreshTime < Fetcher.PERM_REFRESH_TIME);
+ try {
+ final String reversedUrl = TableUtil.reverseUrl(reprUrl);
+ final ImmutableBytesWritable newKey =
+ new ImmutableBytesWritable(reversedUrl.getBytes());
+ final Put put = new Put(newKey.get());
+ if (!reprUrl.equals(url)) {
+ put.add(WebTableColumns.REPR_URL, null, Bytes.toBytes(reprUrl));
+ }
+ put.add(WebTableColumns.METADATA,
+ Fetcher.REDIRECT_DISCOVERED, TableUtil.YES_VAL);
+ table.put(put);
+ } catch (MalformedURLException e) {
+ // ignore
+ }
+ }
+ } else {
+ row.setText(parse.getText());
+ row.setTitle(parse.getTitle());
+ final byte[] prevSig = row.getSignature();
+ if (prevSig != null) {
+ row.setPrevSignature(prevSig);
+ }
+ row.setSignature(signature);
+ row.deleteAllOutlinks();
+ final Outlink[] outlinks = parse.getOutlinks();
+ final int count = 0;
+ String fromHost;
+ if (ignoreExternalLinks) {
+ try {
+ fromHost = new URL(url).getHost().toLowerCase();
+ } catch (final MalformedURLException e) {
+ fromHost = null;
+ }
+ } else {
+ fromHost = null;
+ }
+ for (int i = 0; count < maxOutlinks && i < outlinks.length; i++) {
+ String toUrl = outlinks[i].getToUrl();
+ toUrl = normalizers.normalize(toUrl, URLNormalizers.SCOPE_OUTLINK);
+ try {
+ toUrl = filters.filter(toUrl);
+ } catch (final URLFilterException e) {
+ continue;
+ }
+ if (toUrl == null) {
+ continue;
+ }
+ String toHost;
+ if (ignoreExternalLinks) {
+ try {
+ toHost = new URL(toUrl).getHost().toLowerCase();
+ } catch (final MalformedURLException e) {
+ toHost = null;
+ }
+ if (toHost == null || !toHost.equals(fromHost)) { // external links
+ continue; // skip it
+ }
+ }
+
+ row.addOutlink(new Outlink(toUrl, outlinks[i].getAnchor()));
+ }
+ row.putMeta(PARSE_MARK, TableUtil.YES_VAL);
+ }
+ }
+
+ row.makeRowMutation().commit(table);
+ }
+
+ @Override
+ public void cleanup(Context context) throws IOException {
+ table.close();
+ }
+
+ private Scan makeScan(Job job, boolean restart) {
+ Configuration conf = job.getConfiguration();
+ final Collection<HbaseColumn> columns = new HashSet<HbaseColumn>(COLUMNS);
+ final ParserFactory parserFactory = new ParserFactory(conf);
+ columns.addAll(parserFactory.getColumns());
+ columns.addAll(SignatureFactory.getColumns(conf));
+ final HtmlParseFilters parseFilters = new HtmlParseFilters(conf);
+ columns.addAll(parseFilters.getColumns());
+ Scan scan = TableUtil.createScanFromColumns(columns);
+ List<Filter> filters = new ArrayList<Filter>();
+ if (!restart) {
+ filters.add(new ValueFilter(WebTableColumns.METADATA, PARSE_MARK,
+ CompareOp.NOT_EQUAL, TableUtil.YES_VAL, false));
+ }
+ filters.add(new ValueFilter(WebTableColumns.METADATA, Fetcher.FETCH_MARK,
+ CompareOp.EQUAL, TableUtil.YES_VAL, true));
+ scan.setFilter(new FilterList(Operator.MUST_PASS_ALL, filters));
+ return scan;
+ }
+
+
+ @Override
+ public Configuration getConf() {
+ return conf;
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ public void parse(String table, boolean restart) throws Exception {
+
+ LOG.info("TableParser: starting");
+ LOG.info("TableParser: segment: " + table);
+
+ final Job job = new NutchJob(getConf(), "parse " + table);
+
+ Scan scan = makeScan(job, restart);
+ TableMapReduceUtil.initTableMapperJob(table, scan,
+ TableParser.class, ImmutableBytesWritable.class,
+ ImmutableBytesWritable.class, job);
+ TableMapReduceUtil.initTableReducerJob(table, IdentityTableReducer.class, job);
+ job.waitForCompletion(true);
+ LOG.info("TableParser: done");
+ }
+
+ public int run(String[] args) throws Exception {
+ final String usage = "Usage: TableParser <webtable> [-restart]";
+
+ if (args.length == 0) {
+ System.err.println(usage);
+ System.exit(-1);
+ }
+
+ boolean restart = false;
+ if (args.length >= 2 && "-restart".equals(args[1])) {
+ restart = true;
+ }
+
+ parse(args[0], restart);
+ return 0;
+ }
+
+ public static void main(String[] args) throws Exception {
+ final int res = ToolRunner.run(NutchConfiguration.create(), new TableParser(), args);
+ System.exit(res);
+ }
+
+}
diff --git a/src/java/org/apache/nutch/plugin/Pluggable.java b/src/java/org/apache/nutch/plugin/Pluggable.java
index 9d99ecb4f..7ef8713e9 100644
--- a/src/java/org/apache/nutch/plugin/Pluggable.java
+++ b/src/java/org/apache/nutch/plugin/Pluggable.java
@@ -1,21 +1,6 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
package org.apache.nutch.plugin;
+
/**
* Defines the capability of a class to be plugged into Nutch.
* This is a common interface that must be implemented by all
@@ -28,5 +13,4 @@ package org.apache.nutch.plugin;
* plugin package description</a>
*/
public interface Pluggable {
-
}
diff --git a/src/java/org/apache/nutch/plugin/TablePluggable.java b/src/java/org/apache/nutch/plugin/TablePluggable.java
new file mode 100644
index 000000000..6e8951814
--- /dev/null
+++ b/src/java/org/apache/nutch/plugin/TablePluggable.java
@@ -0,0 +1,15 @@
+package org.apache.nutch.plugin;
+
+import java.util.Collection;
+import java.util.HashSet;
+
+import org.apache.nutch.util.hbase.HbaseColumn;
+
+public interface TablePluggable extends Pluggable {
+
+ public static final Collection<HbaseColumn> EMPTY_COLUMNS =
+ new HashSet<HbaseColumn>();
+
+ public Collection<HbaseColumn> getColumns();
+
+}
diff --git a/src/java/org/apache/nutch/protocol/Content.java b/src/java/org/apache/nutch/protocol/Content.java
index a9e8e2a56..d39b509e7 100755
--- a/src/java/org/apache/nutch/protocol/Content.java
+++ b/src/java/org/apache/nutch/protocol/Content.java
@@ -35,6 +35,7 @@ import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.UTF8;
import org.apache.hadoop.io.VersionMismatchException;
import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.util.GenericOptionsParser;
//Nutch imports
import org.apache.nutch.metadata.Metadata;
@@ -85,6 +86,27 @@ public final class Content implements Writable{
this.mimeTypes = new MimeUtil(conf);
this.contentType = getContentType(contentType, url, content);
}
+
+ public Content(String url, String base, byte[] content, String contentType,
+ Metadata metadata, MimeUtil mimeTypes) {
+
+ if (url == null)
+ throw new IllegalArgumentException("null url");
+ if (base == null)
+ throw new IllegalArgumentException("null base");
+ if (content == null)
+ throw new IllegalArgumentException("null content");
+ if (metadata == null)
+ throw new IllegalArgumentException("null metadata");
+
+ this.url = url;
+ this.base = base;
+ this.content = content;
+ this.metadata = metadata;
+
+ this.mimeTypes = mimeTypes;
+ this.contentType = getContentType(contentType, url, content);
+ }
private final void readFieldsCompressed(DataInput in) throws IOException {
byte oldVersion = in.readByte();
@@ -247,16 +269,21 @@ public final class Content implements Writable{
}
- public static void main(String argv[]) throws Exception {
+ public static void main(String args[]) throws Exception {
String usage = "Content (-local | -dfs <namenode:port>) recno segment";
- if (argv.length < 3) {
+ if (args.length < 3) {
System.out.println("usage:" + usage);
return;
}
- Configuration conf = NutchConfiguration.create();
- FileSystem fs = FileSystem.parseArgs(argv, 0, conf);
+
+ GenericOptionsParser optParser =
+ new GenericOptionsParser(NutchConfiguration.create(), args);
+ String[] argv = optParser.getRemainingArgs();
+ Configuration conf = optParser.getConfiguration();
+
+ FileSystem fs = FileSystem.get(conf);
try {
int recno = Integer.parseInt(argv[0]);
String segment = argv[1];
diff --git a/src/java/org/apache/nutch/protocol/Protocol.java b/src/java/org/apache/nutch/protocol/Protocol.java
index 911a5f4c0..8a2cff3dc 100755
--- a/src/java/org/apache/nutch/protocol/Protocol.java
+++ b/src/java/org/apache/nutch/protocol/Protocol.java
@@ -18,16 +18,18 @@
package org.apache.nutch.protocol;
// Hadoop imports
+
import org.apache.hadoop.conf.Configurable;
-import org.apache.hadoop.io.Text;
// Nutch imports
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.plugin.Pluggable;
-
+import org.apache.nutch.plugin.TablePluggable;
+import org.apache.nutch.protocol.ProtocolOutput;
+import org.apache.nutch.protocol.RobotRules;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableRow;
/** A retriever of url content. Implemented by protocol extensions. */
-public interface Protocol extends Pluggable, Configurable {
+public interface Protocol extends TablePluggable, Configurable {
/** The name of the extension point. */
public final static String X_POINT_ID = Protocol.class.getName();
@@ -51,13 +53,13 @@ public interface Protocol extends Pluggable, Configurable {
/** Returns the {@link Content} for a fetchlist entry.
*/
- ProtocolOutput getProtocolOutput(Text url, CrawlDatum datum);
+ ProtocolOutput getProtocolOutput(String url, WebTableRow row);
/**
* Retrieve robot rules applicable for this url.
* @param url url to check
- * @param datum page datum
+ * @param row Row
* @return robot rules (specific for this url or default), never null
*/
- RobotRules getRobotRules(Text url, CrawlDatum datum);
+ RobotRules getRobotRules(String url, WebTableRow row);
}
diff --git a/src/java/org/apache/nutch/protocol/ProtocolFactory.java b/src/java/org/apache/nutch/protocol/ProtocolFactory.java
index 44d4ae9f7..e850b9f88 100644
--- a/src/java/org/apache/nutch/protocol/ProtocolFactory.java
+++ b/src/java/org/apache/nutch/protocol/ProtocolFactory.java
@@ -19,13 +19,17 @@ package org.apache.nutch.protocol;
import java.net.URL;
import java.net.MalformedURLException;
+import java.util.Collection;
+import java.util.HashSet;
// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.nutch.plugin.*;
+import org.apache.nutch.protocol.ProtocolNotFound;
import org.apache.nutch.util.ObjectCache;
+import org.apache.nutch.util.hbase.HbaseColumn;
import org.apache.hadoop.conf.Configuration;
@@ -100,7 +104,6 @@ public class ProtocolFactory {
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
-
if (contains(name, extension.getAttribute("protocolName")))
return extension;
}
@@ -115,4 +118,18 @@ public class ProtocolFactory {
return false;
}
+ public Collection<HbaseColumn> getColumnSet() {
+ Collection<HbaseColumn> columns = new HashSet<HbaseColumn>();
+ for (Extension extension : this.extensionPoint.getExtensions()) {
+ Protocol protocol;
+ try {
+ protocol = (Protocol) extension.getExtensionInstance();
+ columns.addAll(protocol.getColumns());
+ } catch (PluginRuntimeException e) {
+ // ignore
+ }
+ }
+ return columns;
+ }
+
}
diff --git a/src/java/org/apache/nutch/scoring/ScoreDatum.java b/src/java/org/apache/nutch/scoring/ScoreDatum.java
new file mode 100644
index 000000000..9b0cfe29b
--- /dev/null
+++ b/src/java/org/apache/nutch/scoring/ScoreDatum.java
@@ -0,0 +1,89 @@
+package org.apache.nutch.scoring;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableUtils;
+
+public class ScoreDatum implements Writable {
+
+ private float score;
+ private String url;
+ private String anchor;
+ private Map<String, byte[]> metaData = new HashMap<String, byte[]>();
+
+ public ScoreDatum() { }
+
+ public ScoreDatum(float score, String url, String anchor) {
+ this.score = score;
+ this.url = url;
+ this.anchor = anchor;
+ }
+
+ @Override
+ public void readFields(DataInput in) throws IOException {
+ score = in.readFloat();
+ url = Text.readString(in);
+ anchor = Text.readString(in);
+ metaData.clear();
+
+ int size = WritableUtils.readVInt(in);
+ for (int i = 0; i < size; i++) {
+ String key = Text.readString(in);
+ byte[] value = Bytes.readByteArray(in);
+ metaData.put(key, value);
+ }
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ out.writeFloat(score);
+ Text.writeString(out, url);
+ Text.writeString(out, anchor);
+
+ WritableUtils.writeVInt(out, metaData.size());
+ for (Entry<String, byte[]> e : metaData.entrySet()) {
+ Text.writeString(out, e.getKey());
+ Bytes.writeByteArray(out, e.getValue());
+ }
+ }
+
+ public byte[] getMeta(String key) {
+ return metaData.get(key);
+ }
+
+ public void setMeta(String key, byte[] value) {
+ metaData.put(key, value);
+ }
+
+ public byte[] deleteMeta(String key) {
+ return metaData.remove(key);
+ }
+
+ public float getScore() {
+ return score;
+ }
+
+ public void setScore(float score) {
+ this.score = score;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getAnchor() {
+ return anchor;
+ }
+}
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilter.java b/src/java/org/apache/nutch/scoring/ScoringFilter.java
index 410521d51..89acc5e15 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilter.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilter.java
@@ -18,17 +18,11 @@ package org.apache.nutch.scoring;
import java.util.Collection;
import java.util.List;
-import java.util.Map.Entry;
import org.apache.hadoop.conf.Configurable;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.NutchDocument;
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.plugin.Pluggable;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.plugin.TablePluggable;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* A contract defining behavior of scoring plugins.
@@ -39,7 +33,7 @@ import org.apache.nutch.protocol.Content;
*
* @author Andrzej Bialecki
*/
-public interface ScoringFilter extends Configurable, Pluggable {
+public interface ScoringFilter extends Configurable, TablePluggable {
/** The name of the extension point. */
public final static String X_POINT_ID = ScoringFilter.class.getName();
@@ -49,10 +43,10 @@ public interface ScoringFilter extends Configurable, Pluggable {
* score to a non-zero value, to give newly injected pages some initial
* credit.
* @param url url of the page
- * @param datum new datum. Filters will modify it in-place.
+ * @param row new row. Filters will modify it in-place.
* @throws ScoringFilterException
*/
- public void injectedScore(Text url, CrawlDatum datum) throws ScoringFilterException;
+ public void injectedScore(String url, WebTableRow row) throws ScoringFilterException;
/**
* Set an initial score for newly discovered pages. Note: newly discovered pages
@@ -60,102 +54,59 @@ public interface ScoringFilter extends Configurable, Pluggable {
* may choose to set initial score to zero (unknown value), and then the inlink
* score contribution will set the "real" value of the new page.
* @param url url of the page
- * @param datum new datum. Filters will modify it in-place.
+ * @param row page row. Modifications will be persisted.
* @throws ScoringFilterException
*/
- public void initialScore(Text url, CrawlDatum datum) throws ScoringFilterException;
+ public void initialScore(String url, WebTableRow row) throws ScoringFilterException;
/**
* This method prepares a sort value for the purpose of sorting and
* selecting top N scoring pages during fetchlist generation.
* @param url url of the page
- * @param datum page's datum, should not be modified
+ * @param datum page row. Modifications will be persisted.
* @param initSort initial sort value, or a value from previous filters in chain
*/
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort) throws ScoringFilterException;
-
- /**
- * This method takes all relevant score information from the current datum
- * (coming from a generated fetchlist) and stores it into
- * {@link org.apache.nutch.protocol.Content} metadata.
- * This is needed in order to pass this value(s) to the mechanism that distributes it
- * to outlinked pages.
- * @param url url of the page
- * @param datum source datum. NOTE: modifications to this value are not persisted.
- * @param content instance of content. Implementations may modify this
- * in-place, primarily by setting some metadata properties.
- */
- public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content) throws ScoringFilterException;
-
- /**
- * Currently a part of score distribution is performed using only data coming
- * from the parsing process. We need this method in order to ensure the
- * presence of score data in these steps.
- * @param url page url
- * @param content original content. NOTE: modifications to this value are not persisted.
- * @param parse target instance to copy the score information to. Implementations
- * may modify this in-place, primarily by setting some metadata properties.
- */
- public void passScoreAfterParsing(Text url, Content content, Parse parse) throws ScoringFilterException;
-
+ public float generatorSortValue(String url, WebTableRow row, float initSort) throws ScoringFilterException;
+
/**
* Distribute score value from the current page to all its outlinked pages.
* @param fromUrl url of the source page
- * @param parseData ParseData instance, which stores relevant score value(s)
- * in its metadata. NOTE: filters may modify this in-place, all changes will
- * be persisted.
- * @param targets &lt;url, CrawlDatum&gt; pairs. NOTE: filters can modify this in-place,
- * all changes will be persisted.
- * @param adjust a CrawlDatum instance, initially null, which implementations
- * may use to pass adjustment values to the original CrawlDatum. When creating
- * this instance, set its status to {@link CrawlDatum#STATUS_LINKED}.
+ * @param row page row
+ * @param scoreData A list of {@link OutlinkedScoreDatum}s for every outlink.
+ * These {@link OutlinkedScoreDatum}s will be passed to
+ * {@link #updateScore(String, WebTableRow, List)}
+ * for every outlinked URL.
* @param allCount number of all collected outlinks from the source page
- * @return if needed, implementations may return an instance of CrawlDatum,
- * with status {@link CrawlDatum#STATUS_LINKED}, which contains adjustments
- * to be applied to the original CrawlDatum score(s) and metadata. This can
- * be null if not needed.
* @throws ScoringFilterException
*/
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData,
- Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust,
- int allCount) throws ScoringFilterException;
+ public void distributeScoreToOutlinks(String fromUrl,
+ WebTableRow row, Collection<ScoreDatum> scoreData,
+ int allCount) throws ScoringFilterException;
/**
- * This method calculates a new score of CrawlDatum during CrawlDb update, based on the
- * initial value of the original CrawlDatum, and also score values contributed by
- * inlinked pages.
+ * This method calculates a new score during table update, based on the values contributed
+ * by inlinked pages.
* @param url url of the page
- * @param old original datum, with original score. May be null if this is a newly
- * discovered page. If not null, filters should use score values from this parameter
- * as the starting values - the <code>datum</code> parameter may contain values that are
- * no longer valid, if other updates occured between generation and this update.
- * @param datum the new datum, with the original score saved at the time when
- * fetchlist was generated. Filters should update this in-place, and it will be saved in
- * the crawldb.
- * @param inlinked (partial) list of CrawlDatum-s (with their scores) from
- * links pointing to this page, found in the current update batch.
+ * @param row page row
+ * @param inlinked list of {@link OutlinkedScoreDatum}s for all inlinks pointing to this URL.
* @throws ScoringFilterException
*/
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum, List<CrawlDatum> inlinked) throws ScoringFilterException;
+ public void updateScore(String url, WebTableRow row, List<ScoreDatum> inlinkedScoreData)
+ throws ScoringFilterException;
/**
* This method calculates a Lucene document boost.
* @param url url of the page
- * @param doc Lucene document. NOTE: this already contains all information collected
+ * @param doc document. NOTE: this already contains all information collected
* by indexing filters. Implementations may modify this instance, in order to store/remove
* some information.
- * @param dbDatum current page from CrawlDb. NOTE: changes made to this instance
- * are not persisted.
- * @param fetchDatum datum from FetcherOutput (containing among others the fetching status)
- * @param parse parsing result. NOTE: changes made to this instance are not persisted.
- * @param inlinks current inlinks from LinkDb. NOTE: changes made to this instance are
- * not persisted.
+ * @param row page row
* @param initScore initial boost value for the Lucene document.
* @return boost value for the Lucene document. This value is passed as an argument
* to the next scoring filter in chain. NOTE: implementations may also express
* other scoring strategies by modifying Lucene document directly.
* @throws ScoringFilterException
*/
- public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
- CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore) throws ScoringFilterException;
+ public float indexerScore(String url, NutchDocument doc, WebTableRow row, float initScore)
+ throws ScoringFilterException;
}
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilters.java b/src/java/org/apache/nutch/scoring/ScoringFilters.java
index 835426660..69dcaedbd 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilters.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilters.java
@@ -19,24 +19,20 @@ package org.apache.nutch.scoring;
import java.util.Collection;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
-import java.util.Map.Entry;
+import java.util.Set;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Inlinks;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
import org.apache.nutch.indexer.NutchDocument;
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseData;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
-import org.apache.nutch.plugin.PluginRuntimeException;
import org.apache.nutch.plugin.PluginRepository;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.plugin.PluginRuntimeException;
import org.apache.nutch.util.ObjectCache;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.io.Text;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
* Creates and caches {@link ScoringFilter} implementing plugins.
@@ -89,58 +85,63 @@ public class ScoringFilters extends Configured implements ScoringFilter {
}
/** Calculate a sort value for Generate. */
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- initSort = this.filters[i].generatorSortValue(url, datum, initSort);
+ @Override
+ public float generatorSortValue(String url, WebTableRow row, float initSort)
+ throws ScoringFilterException {
+ for (ScoringFilter filter : filters) {
+ initSort = filter.generatorSortValue(url, row, initSort);
}
return initSort;
}
/** Calculate a new initial score, used when adding newly discovered pages. */
- public void initialScore(Text url, CrawlDatum datum) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- this.filters[i].initialScore(url, datum);
+ @Override
+ public void initialScore(String url, WebTableRow row) throws ScoringFilterException {
+ for (ScoringFilter filter : filters) {
+ filter.initialScore(url, row);
}
}
/** Calculate a new initial score, used when injecting new pages. */
- public void injectedScore(Text url, CrawlDatum datum) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- this.filters[i].injectedScore(url, datum);
+ @Override
+ public void injectedScore(String url, WebTableRow row) throws ScoringFilterException {
+ for (ScoringFilter filter : filters) {
+ filter.injectedScore(url, row);
}
}
- /** Calculate updated page score during CrawlDb.update(). */
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum, List<CrawlDatum> inlinked) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- this.filters[i].updateDbScore(url, old, datum, inlinked);
+ @Override
+ public void distributeScoreToOutlinks(String fromUrl, WebTableRow row,
+ Collection<ScoreDatum> scoreData, int allCount)
+ throws ScoringFilterException {
+ for (ScoringFilter filter : filters) {
+ filter.distributeScoreToOutlinks(fromUrl, row, scoreData, allCount);
}
}
-
- public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- this.filters[i].passScoreBeforeParsing(url, datum, content);
- }
- }
-
- public void passScoreAfterParsing(Text url, Content content, Parse parse) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- this.filters[i].passScoreAfterParsing(url, content, parse);
- }
- }
-
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust, int allCount) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- adjust = this.filters[i].distributeScoreToOutlinks(fromUrl, parseData, targets, adjust, allCount);
- }
- return adjust;
+
+ @Override
+ public void updateScore(String url, WebTableRow row,
+ List<ScoreDatum> inlinkedScoreData) throws ScoringFilterException {
+ for (ScoringFilter filter : filters) {
+ filter.updateScore(url, row, inlinkedScoreData);
+ }
}
- public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum, CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore) throws ScoringFilterException {
- for (int i = 0; i < this.filters.length; i++) {
- initScore = this.filters[i].indexerScore(url, doc, dbDatum, fetchDatum, parse, inlinks, initScore);
+ @Override
+ public float indexerScore(String url, NutchDocument doc, WebTableRow row,
+ float initScore) throws ScoringFilterException {
+ for (ScoringFilter filter : filters) {
+ initScore = filter.indexerScore(url, doc, row, initScore);
}
return initScore;
}
+ @Override
+ public Collection<HbaseColumn> getColumns() {
+ Set<HbaseColumn> columns = new HashSet<HbaseColumn>();
+ for (ScoringFilter filter : filters) {
+ columns.addAll(filter.getColumns());
+ }
+ return columns;
+ }
}
diff --git a/src/java/org/apache/nutch/searcher/DistributedSegmentBean.java b/src/java/org/apache/nutch/searcher/DistributedSegmentBean.java
deleted file mode 100644
index 3651064f3..000000000
--- a/src/java/org/apache/nutch/searcher/DistributedSegmentBean.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.nutch.searcher;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.ipc.RPC;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.parse.ParseText;
-
-public class DistributedSegmentBean implements SegmentBean {
-
- private static final ExecutorService executor =
- Executors.newCachedThreadPool();
-
- private final ScheduledExecutorService pingService;
-
- private class DistSummmaryTask implements Callable<Summary[]> {
- private int id;
-
- private HitDetails[] details;
- private Query query;
-
- public DistSummmaryTask(int id) {
- this.id = id;
- }
-
- public Summary[] call() throws Exception {
- if (details == null) {
- return null;
- }
- return beans[id].getSummary(details, query);
- }
-
- public void setSummaryArgs(HitDetails[] details, Query query) {
- this.details = details;
- this.query = query;
- }
-
- }
-
- private class SegmentWorker implements Runnable {
- private int id;
-
- public SegmentWorker(int id) {
- this.id = id;
- }
-
- public void run() {
- try {
- String[] segments = beans[id].getSegmentNames();
- for (String segment : segments) {
- segmentMap.put(segment, id);
- }
- } catch (IOException e) {
- // remove all segments this bean was serving
- Iterator<Map.Entry<String, Integer>> i =
- segmentMap.entrySet().iterator();
- while (i.hasNext()) {
- Map.Entry<String, Integer> entry = i.next();
- int curId = entry.getValue();
- if (curId == this.id) {
- i.remove();
- }
- }
- }
- }
- }
-
- private long timeout;
-
- private SegmentBean[] beans;
-
- private ConcurrentMap<String, Integer> segmentMap;
-
- private List<Callable<Summary[]>> summaryTasks;
-
- private List<SegmentWorker> segmentWorkers;
-
- public DistributedSegmentBean(Configuration conf, Path serversConfig)
- throws IOException {
- this.timeout = conf.getLong("ipc.client.timeout", 60000);
-
- List<SegmentBean> beanList = new ArrayList<SegmentBean>();
-
- List<InetSocketAddress> segmentServers =
- NutchBean.readAddresses(serversConfig, conf);
-
- for (InetSocketAddress addr : segmentServers) {
- SegmentBean bean = (RPCSegmentBean) RPC.getProxy(RPCSegmentBean.class,
- FetchedSegments.VERSION, addr, conf);
- beanList.add(bean);
- }
-
- beans = beanList.toArray(new SegmentBean[beanList.size()]);
-
- summaryTasks = new ArrayList<Callable<Summary[]>>(beans.length);
- segmentWorkers = new ArrayList<SegmentWorker>(beans.length);
-
- for (int i = 0; i < beans.length; i++) {
- summaryTasks.add(new DistSummmaryTask(i));
- segmentWorkers.add(new SegmentWorker(i));
- }
-
- segmentMap = new ConcurrentHashMap<String, Integer>();
-
- pingService = Executors.newScheduledThreadPool(beans.length);
- for (SegmentWorker worker : segmentWorkers) {
- pingService.scheduleAtFixedRate(worker, 0, 30, TimeUnit.SECONDS);
- }
- }
-
- private SegmentBean getBean(HitDetails details) {
- return beans[segmentMap.get(details.getValue("segment"))];
- }
-
- public String[] getSegmentNames() {
- return segmentMap.keySet().toArray(new String[segmentMap.size()]);
- }
-
- public byte[] getContent(HitDetails details) throws IOException {
- return getBean(details).getContent(details);
- }
-
- public long getFetchDate(HitDetails details) throws IOException {
- return getBean(details).getFetchDate(details);
- }
-
- public ParseData getParseData(HitDetails details) throws IOException {
- return getBean(details).getParseData(details);
- }
-
- public ParseText getParseText(HitDetails details) throws IOException {
- return getBean(details).getParseText(details);
- }
-
- public void close() throws IOException {
- executor.shutdown();
- pingService.shutdown();
- for (SegmentBean bean : beans) {
- bean.close();
- }
- }
-
- public Summary getSummary(HitDetails details, Query query)
- throws IOException {
- return getBean(details).getSummary(details, query);
- }
-
- @SuppressWarnings("unchecked")
- public Summary[] getSummary(HitDetails[] detailsArr, Query query)
- throws IOException {
- List<HitDetails>[] detailsList = new ArrayList[summaryTasks.size()];
- for (int i = 0; i < detailsList.length; i++) {
- detailsList[i] = new ArrayList<HitDetails>();
- }
- for (HitDetails details : detailsArr) {
- detailsList[segmentMap.get(details.getValue("segment"))].add(details);
- }
- for (int i = 0; i < summaryTasks.size(); i++) {
- DistSummmaryTask task = (DistSummmaryTask)summaryTasks.get(i);
- if (detailsList[i].size() > 0) {
- HitDetails[] taskDetails =
- detailsList[i].toArray(new HitDetails[detailsList[i].size()]);
- task.setSummaryArgs(taskDetails, query);
- } else {
- task.setSummaryArgs(null, null);
- }
- }
-
- List<Future<Summary[]>> summaries;
- try {
- summaries =
- executor.invokeAll(summaryTasks, timeout, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
- List<Summary> summaryList = new ArrayList<Summary>();
- for (Future<Summary[]> f : summaries) {
- Summary[] summaryArray;
- try {
- summaryArray = f.get();
- if (summaryArray == null) {
- continue;
- }
- for (Summary summary : summaryArray) {
- summaryList.add(summary);
- }
- } catch (Exception e) {
- if (e.getCause() instanceof IOException) {
- throw (IOException) e.getCause();
- }
- throw new RuntimeException(e);
- }
- }
-
- return summaryList.toArray(new Summary[summaryList.size()]);
- }
-
-}
diff --git a/src/java/org/apache/nutch/searcher/Hit.java b/src/java/org/apache/nutch/searcher/Hit.java
index cf70a46ef..9462a0897 100644
--- a/src/java/org/apache/nutch/searcher/Hit.java
+++ b/src/java/org/apache/nutch/searcher/Hit.java
@@ -89,6 +89,44 @@ public class Hit implements Writable, Comparable<Hit> {
}
}
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((dedupValue == null) ? 0 : dedupValue.hashCode());
+ result = prime * result + indexNo;
+ result = prime * result + (moreFromDupExcluded ? 1231 : 1237);
+ result = prime * result + ((sortValue == null) ? 0 : sortValue.hashCode());
+ result = prime * result + uniqueKey.hashCode();
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ Hit other = (Hit) obj;
+ if (!uniqueKey.equals(other.uniqueKey))
+ return false;
+ if (dedupValue == null) {
+ if (other.dedupValue != null)
+ return false;
+ } else if (!dedupValue.equals(other.dedupValue))
+ return false;
+ if (indexNo != other.indexNo)
+ return false;
+ if (moreFromDupExcluded != other.moreFromDupExcluded)
+ return false;
+ if (sortValue == null) {
+ if (other.sortValue != null)
+ return false;
+ } else if (!sortValue.equals(other.sortValue))
+ return false;
+ return true;
+ }
+
+
public void write(DataOutput out) throws IOException {
Text.writeString(out, uniqueKey);
}
diff --git a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java b/src/java/org/apache/nutch/searcher/LinkDbInlinks.java
deleted file mode 100644
index 1027818cd..000000000
--- a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-/*
- * Created on Nov 23, 2005
- * Author: Andrzej Bialecki &lt;[email protected]&gt;
- *
- */
-package org.apache.nutch.searcher;
-
-import java.io.IOException;
-
-import org.apache.nutch.crawl.Inlinks;
-import org.apache.nutch.crawl.LinkDbReader;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.Path;
-
-public class LinkDbInlinks implements HitInlinks {
- private static final Log LOG = LogFactory.getLog(LinkDbInlinks.class);
-
- private LinkDbReader linkdb = null;
-
- public LinkDbInlinks(FileSystem fs, Path dir, Configuration conf) {
- try {
- linkdb = new LinkDbReader(conf, dir);
- } catch (Exception e) {
- LOG.warn("Could not create LinkDbReader: " + e);
- }
- }
-
- public String[] getAnchors(HitDetails details) throws IOException {
- return linkdb.getAnchors(new Text(details.getValue("url")));
- }
-
- public Inlinks getInlinks(HitDetails details) throws IOException {
- return linkdb.getInlinks(new Text(details.getValue("url")));
- }
-
- public void close() throws IOException {
- if (linkdb != null) { linkdb.close(); }
- }
-
-}
diff --git a/src/java/org/apache/nutch/searcher/NutchBean.java b/src/java/org/apache/nutch/searcher/NutchBean.java
index 452088bcc..6693dbf97 100644
--- a/src/java/org/apache/nutch/searcher/NutchBean.java
+++ b/src/java/org/apache/nutch/searcher/NutchBean.java
@@ -28,11 +28,15 @@ import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.hbase.client.Get;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.parse.*;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.hbase.WebTableColumns;
/**
* One stop shopping for search-related functionality.
@@ -49,8 +53,10 @@ implements SearchBean, SegmentBean, HitInlinks, Closeable {
// }
private SearchBean searchBean;
- private SegmentBean segmentBean;
- private final HitInlinks linkDb;
+
+ private HTable table;
+
+ private SummarizerFactory summarizerFactory;
/** BooleanQuery won't permit more than 32 required/prohibited clauses. We
* don't want to use too many of those. */
@@ -92,7 +98,6 @@ implements SearchBean, SegmentBean, HitInlinks, Closeable {
}
final Path luceneConfig = new Path(dir, "search-servers.txt");
final Path solrConfig = new Path(dir, "solr-servers.txt");
- final Path segmentConfig = new Path(dir, "segment-servers.txt");
if (fs.exists(luceneConfig) || fs.exists(solrConfig)) {
searchBean = new DistributedSearchBean(conf, luceneConfig, solrConfig);
@@ -101,16 +106,11 @@ implements SearchBean, SegmentBean, HitInlinks, Closeable {
final Path indexesDir = new Path(dir, "indexes");
searchBean = new LuceneSearchBean(conf, indexDir, indexesDir);
}
-
- if (fs.exists(segmentConfig)) {
- segmentBean = new DistributedSegmentBean(conf, segmentConfig);
- } else if (fs.exists(luceneConfig)) {
- segmentBean = new DistributedSegmentBean(conf, luceneConfig);
- } else {
- segmentBean = new FetchedSegments(conf, new Path(dir, "segments"));
- }
-
- linkDb = new LinkDbInlinks(fs, new Path(dir, "linkdb"), conf);
+
+ String tableName = conf.get("table.name", "webtable");
+ table = new HTable(tableName);
+
+ summarizerFactory = new SummarizerFactory(conf);
}
public static List<InetSocketAddress> readAddresses(Path path,
@@ -146,10 +146,6 @@ implements SearchBean, SegmentBean, HitInlinks, Closeable {
}
}
- public String[] getSegmentNames() throws IOException {
- return segmentBean.getSegmentNames();
- }
-
public Hits search(Query query, int numHits) throws IOException {
return search(query, numHits, null, null, false);
}
@@ -317,42 +313,56 @@ implements SearchBean, SegmentBean, HitInlinks, Closeable {
}
public Summary getSummary(HitDetails hit, Query query) throws IOException {
- return segmentBean.getSummary(hit, query);
+ return summarizerFactory.getSummarizer().getSummary(getText(hit), query);
}
public Summary[] getSummary(HitDetails[] hits, Query query)
- throws IOException {
- return segmentBean.getSummary(hits, query);
+ throws IOException {
+ Summary[] summaries = new Summary[hits.length];
+ for (int i = 0; i < hits.length; i++) {
+ summaries[i] = getSummary(hits[i], query);
+ }
+ return summaries;
+ }
+
+ private byte[] getRowId(HitDetails hitDetails) {
+ return Bytes.toBytes(hitDetails.getValue("id"));
}
- public byte[] getContent(HitDetails hit) throws IOException {
- return segmentBean.getContent(hit);
+ public byte[] getContent(HitDetails hitDetails) throws IOException {
+ Get get = new Get(getRowId(hitDetails));
+ get.addColumn(WebTableColumns.CONTENT, null);
+ return table.get(get).getValue(WebTableColumns.CONTENT, null);
}
public ParseData getParseData(HitDetails hit) throws IOException {
- return segmentBean.getParseData(hit);
+ return null; // TODO
}
public ParseText getParseText(HitDetails hit) throws IOException {
- return segmentBean.getParseText(hit);
+ return null; // TODO
+ }
+
+ public String getText(HitDetails hitDetails) throws IOException {
+ Get get = new Get(getRowId(hitDetails));
+ get.addColumn(WebTableColumns.TEXT, null);
+ return Bytes.toString(table.get(get).getValue(WebTableColumns.TEXT, null));
}
public String[] getAnchors(HitDetails hit) throws IOException {
- return linkDb.getAnchors(hit);
+ return null; // TODO
}
public Inlinks getInlinks(HitDetails hit) throws IOException {
- return linkDb.getInlinks(hit);
+ return null; // TODO
}
public long getFetchDate(HitDetails hit) throws IOException {
- return segmentBean.getFetchDate(hit);
+ return -1L; // TODO
}
public void close() throws IOException {
if (searchBean != null) { searchBean.close(); }
- if (segmentBean != null) { segmentBean.close(); }
- if (linkDb != null) { linkDb.close(); }
if (fs != null) { fs.close(); }
}
@@ -397,11 +407,6 @@ implements SearchBean, SegmentBean, HitInlinks, Closeable {
final RPCSearchBean rpcBean = (RPCSearchBean)searchBean;
return rpcBean.getProtocolVersion(className, clientVersion);
- } else if (RPCSegmentBean.class.getName().equals(className) &&
- segmentBean instanceof RPCSegmentBean) {
-
- final RPCSegmentBean rpcBean = (RPCSegmentBean)segmentBean;
- return rpcBean.getProtocolVersion(className, clientVersion);
} else {
throw new IOException("Unknown Protocol classname:" + className);
}
diff --git a/src/java/org/apache/nutch/searcher/SegmentBean.java b/src/java/org/apache/nutch/searcher/SegmentBean.java
index 81422a7c0..9dc313bbb 100644
--- a/src/java/org/apache/nutch/searcher/SegmentBean.java
+++ b/src/java/org/apache/nutch/searcher/SegmentBean.java
@@ -16,9 +16,5 @@
*/
package org.apache.nutch.searcher;
-import java.io.IOException;
-
public interface SegmentBean extends HitContent, HitSummarizer {
-
- public String[] getSegmentNames() throws IOException;
}
diff --git a/src/java/org/apache/nutch/searcher/SolrSearchBean.java b/src/java/org/apache/nutch/searcher/SolrSearchBean.java
index a553b7c51..f33734230 100644
--- a/src/java/org/apache/nutch/searcher/SolrSearchBean.java
+++ b/src/java/org/apache/nutch/searcher/SolrSearchBean.java
@@ -35,7 +35,6 @@ import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.ToStringUtils;
-import org.apache.nutch.indexer.solr.SolrWriter;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
@@ -87,7 +86,7 @@ public class SolrSearchBean implements SearchBean {
try {
response = solr.query(solrQuery);
} catch (final SolrServerException e) {
- throw SolrWriter.makeIOException(e);
+ throw new IOException(e);
}
final SolrDocumentList docList = response.getResults();
@@ -115,7 +114,7 @@ public class SolrSearchBean implements SearchBean {
final String uniqueKey = (String )solrDoc.getFirstValue("id");
- hitArr[i] = new Hit(uniqueKey, sortValue, dedupValue);
+ hitArr[i] = new Hit(0, uniqueKey, sortValue, dedupValue);
}
return new Hits(docList.getNumFound(), hitArr);
@@ -126,7 +125,7 @@ public class SolrSearchBean implements SearchBean {
try {
response = solr.query(new SolrQuery("id:\"" + hit.getUniqueKey() + "\""));
} catch (final SolrServerException e) {
- throw SolrWriter.makeIOException(e);
+ throw new IOException(e);
}
final SolrDocumentList docList = response.getResults();
@@ -146,15 +145,16 @@ public class SolrSearchBean implements SearchBean {
buf.append("\"");
}
buf.append(")");
-
+
QueryResponse response;
try {
response = solr.query(new SolrQuery(buf.toString()));
} catch (final SolrServerException e) {
- throw SolrWriter.makeIOException(e);
+ throw new IOException(e);
}
final SolrDocumentList docList = response.getResults();
+
if (docList.size() < hits.length) {
throw new RuntimeException("Missing hit details! Found: " +
docList.size() + ", expecting: " +
@@ -184,7 +184,7 @@ public class SolrSearchBean implements SearchBean {
try {
return solr.ping().getStatus() == 0;
} catch (final SolrServerException e) {
- throw SolrWriter.makeIOException(e);
+ throw new IOException(e);
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentMerger.java b/src/java/org/apache/nutch/segment/SegmentMerger.java
deleted file mode 100644
index 113cd8586..000000000
--- a/src/java/org/apache/nutch/segment/SegmentMerger.java
+++ /dev/null
@@ -1,668 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.nutch.segment;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.TreeMap;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.SequenceFile;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.io.SequenceFile.CompressionType;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.FileSplit;
-import org.apache.hadoop.mapred.InputSplit;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.RecordReader;
-import org.apache.hadoop.mapred.RecordWriter;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.SequenceFileRecordReader;
-import org.apache.hadoop.util.Progressable;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Generator;
-import org.apache.nutch.metadata.MetaWrapper;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.net.URLFilters;
-import org.apache.nutch.net.URLNormalizers;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.parse.ParseText;
-import org.apache.nutch.protocol.Content;
-import org.apache.nutch.util.HadoopFSUtil;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-/**
- * This tool takes several segments and merges their data together. Only the
- * latest versions of data is retained.
- * <p>
- * Optionally, you can apply current URLFilters to remove prohibited URL-s.
- * </p>
- * <p>
- * Also, it's possible to slice the resulting segment into chunks of fixed size.
- * </p>
- * <h3>Important Notes</h3>
- * <h4>Which parts are merged?</h4>
- * <p>It doesn't make sense to merge data from segments, which are at different stages
- * of processing (e.g. one unfetched segment, one fetched but not parsed, and
- * one fetched and parsed). Therefore, prior to merging, the tool will determine
- * the lowest common set of input data, and only this data will be merged.
- * This may have some unintended consequences:
- * e.g. if majority of input segments are fetched and parsed, but one of them is unfetched,
- * the tool will fall back to just merging fetchlists, and it will skip all other data
- * from all segments.</p>
- * <h4>Merging fetchlists</h4>
- * <p>Merging segments, which contain just fetchlists (i.e. prior to fetching)
- * is not recommended, because this tool (unlike the {@link org.apache.nutch.crawl.Generator}
- * doesn't ensure that fetchlist parts for each map task are disjoint.</p>
- * <p>
- * <h4>Duplicate content</h4>
- * Merging segments removes older content whenever possible (see below). However,
- * this is NOT the same as de-duplication, which in addition removes identical
- * content found at different URL-s. In other words, running DeleteDuplicates is
- * still necessary.
- * </p>
- * <p>For some types of data (especially ParseText) it's not possible to determine
- * which version is really older. Therefore the tool always uses segment names as
- * timestamps, for all types of input data. Segment names are compared in forward lexicographic
- * order (0-9a-zA-Z), and data from segments with "higher" names will prevail.
- * It follows then that it is extremely important that segments be named in an
- * increasing lexicographic order as their creation time increases.</p>
- * <p>
- * <h4>Merging and indexes</h4>
- * Merged segment gets a different name. Since Indexer embeds segment names in
- * indexes, any indexes originally created for the input segments will NOT work with the
- * merged segment. Newly created merged segment(s) need to be indexed afresh.
- * This tool doesn't use existing indexes in any way, so if
- * you plan to merge segments you don't have to index them prior to merging.
- *
- *
- * @author Andrzej Bialecki
- */
-public class SegmentMerger extends Configured implements
- Mapper<Text, MetaWrapper, Text, MetaWrapper>,
- Reducer<Text, MetaWrapper, Text, MetaWrapper> {
- private static final Log LOG = LogFactory.getLog(SegmentMerger.class);
-
- private static final String SEGMENT_PART_KEY = "part";
- private static final String SEGMENT_SLICE_KEY = "slice";
-
- private URLFilters filters = null;
- private URLNormalizers normalizers = null;
- private long sliceSize = -1;
- private long curCount = 0;
-
- /**
- * Wraps inputs in an {@link MetaWrapper}, to permit merging different
- * types in reduce and use additional metadata.
- */
- public static class ObjectInputFormat extends
- SequenceFileInputFormat<Text, MetaWrapper> {
-
- @Override
- public RecordReader<Text, MetaWrapper> getRecordReader(final InputSplit split,
- final JobConf job, Reporter reporter) throws IOException {
-
- reporter.setStatus(split.toString());
-
- // find part name
- SegmentPart segmentPart;
- final String spString;
- final FileSplit fSplit = (FileSplit) split;
- try {
- segmentPart = SegmentPart.get(fSplit);
- spString = segmentPart.toString();
- } catch (IOException e) {
- throw new RuntimeException("Cannot identify segment:", e);
- }
-
- final SequenceFile.Reader reader =
- new SequenceFile.Reader(FileSystem.get(job), fSplit.getPath(), job);
-
- final Writable w;
- try {
- w = (Writable) reader.getValueClass().newInstance();
- } catch (Exception e) {
- throw new IOException(e.toString());
- }
-
- try {
- return new SequenceFileRecordReader<Text, MetaWrapper>(job, fSplit) {
-
- public synchronized boolean next(Text key, MetaWrapper wrapper) throws IOException {
- LOG.debug("Running OIF.next()");
-
- boolean res = reader.next(key, w);
- wrapper.set(w);
- wrapper.setMeta(SEGMENT_PART_KEY, spString);
- return res;
- }
-
- @Override
- public synchronized void close() throws IOException {
- reader.close();
- }
-
- @Override
- public MetaWrapper createValue() {
- return new MetaWrapper();
- }
-
- };
- } catch (IOException e) {
- throw new RuntimeException("Cannot create RecordReader: ", e);
- }
- }
- }
-
- public static class SegmentOutputFormat extends FileOutputFormat<Text, MetaWrapper> {
- private static final String DEFAULT_SLICE = "default";
-
- @Override
- public RecordWriter<Text, MetaWrapper> getRecordWriter(final FileSystem fs, final JobConf job, final String name, final Progressable progress) throws IOException {
- return new RecordWriter<Text, MetaWrapper>() {
- MapFile.Writer c_out = null;
- MapFile.Writer f_out = null;
- MapFile.Writer pd_out = null;
- MapFile.Writer pt_out = null;
- SequenceFile.Writer g_out = null;
- SequenceFile.Writer p_out = null;
- HashMap sliceWriters = new HashMap();
- String segmentName = job.get("segment.merger.segmentName");
-
- public void write(Text key, MetaWrapper wrapper) throws IOException {
- // unwrap
- SegmentPart sp = SegmentPart.parse(wrapper.getMeta(SEGMENT_PART_KEY));
- Writable o = (Writable)wrapper.get();
- String slice = wrapper.getMeta(SEGMENT_SLICE_KEY);
- if (o instanceof CrawlDatum) {
- if (sp.partName.equals(CrawlDatum.GENERATE_DIR_NAME)) {
- g_out = ensureSequenceFile(slice, CrawlDatum.GENERATE_DIR_NAME);
- g_out.append(key, o);
- } else if (sp.partName.equals(CrawlDatum.FETCH_DIR_NAME)) {
- f_out = ensureMapFile(slice, CrawlDatum.FETCH_DIR_NAME, CrawlDatum.class);
- f_out.append(key, o);
- } else if (sp.partName.equals(CrawlDatum.PARSE_DIR_NAME)) {
- p_out = ensureSequenceFile(slice, CrawlDatum.PARSE_DIR_NAME);
- p_out.append(key, o);
- } else {
- throw new IOException("Cannot determine segment part: " + sp.partName);
- }
- } else if (o instanceof Content) {
- c_out = ensureMapFile(slice, Content.DIR_NAME, Content.class);
- c_out.append(key, o);
- } else if (o instanceof ParseData) {
- // update the segment name inside contentMeta - required by Indexer
- if (slice == null) {
- ((ParseData)o).getContentMeta().set(Nutch.SEGMENT_NAME_KEY, segmentName);
- } else {
- ((ParseData)o).getContentMeta().set(Nutch.SEGMENT_NAME_KEY, segmentName + "-" + slice);
- }
- pd_out = ensureMapFile(slice, ParseData.DIR_NAME, ParseData.class);
- pd_out.append(key, o);
- } else if (o instanceof ParseText) {
- pt_out = ensureMapFile(slice, ParseText.DIR_NAME, ParseText.class);
- pt_out.append(key, o);
- }
- }
-
- // lazily create SequenceFile-s.
- private SequenceFile.Writer ensureSequenceFile(String slice, String dirName) throws IOException {
- if (slice == null) slice = DEFAULT_SLICE;
- SequenceFile.Writer res = (SequenceFile.Writer)sliceWriters.get(slice + dirName);
- if (res != null) return res;
- Path wname;
- Path out = FileOutputFormat.getOutputPath(job);
- if (slice == DEFAULT_SLICE) {
- wname = new Path(new Path(new Path(out, segmentName), dirName), name);
- } else {
- wname = new Path(new Path(new Path(out, segmentName + "-" + slice), dirName), name);
- }
- res = SequenceFile.createWriter(fs, job, wname, Text.class,
- CrawlDatum.class,
- SequenceFileOutputFormat.getOutputCompressionType(job), progress);
- sliceWriters.put(slice + dirName, res);
- return res;
- }
-
- // lazily create MapFile-s.
- private MapFile.Writer ensureMapFile(String slice, String dirName, Class<? extends Writable> clazz) throws IOException {
- if (slice == null) slice = DEFAULT_SLICE;
- MapFile.Writer res = (MapFile.Writer)sliceWriters.get(slice + dirName);
- if (res != null) return res;
- Path wname;
- Path out = FileOutputFormat.getOutputPath(job);
- if (slice == DEFAULT_SLICE) {
- wname = new Path(new Path(new Path(out, segmentName), dirName), name);
- } else {
- wname = new Path(new Path(new Path(out, segmentName + "-" + slice), dirName), name);
- }
- CompressionType compType =
- SequenceFileOutputFormat.getOutputCompressionType(job);
- if (clazz.isAssignableFrom(ParseText.class)) {
- compType = CompressionType.RECORD;
- }
- res = new MapFile.Writer(job, fs, wname.toString(), Text.class, clazz, compType, progress);
- sliceWriters.put(slice + dirName, res);
- return res;
- }
-
- public void close(Reporter reporter) throws IOException {
- Iterator<Object> it = sliceWriters.values().iterator();
- while (it.hasNext()) {
- Object o = it.next();
- if (o instanceof SequenceFile.Writer) {
- ((SequenceFile.Writer)o).close();
- } else {
- ((MapFile.Writer)o).close();
- }
- }
- }
- };
- }
- }
-
- public SegmentMerger() {
- super(null);
- }
-
- public SegmentMerger(Configuration conf) {
- super(conf);
- }
-
- public void setConf(Configuration conf) {
- super.setConf(conf);
- if (conf == null) return;
- if (conf.getBoolean("segment.merger.filter", false))
- filters = new URLFilters(conf);
- if (conf.getBoolean("segment.merger.normalizer", false))
- normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
- sliceSize = conf.getLong("segment.merger.slice", -1);
- if ((sliceSize > 0) && (LOG.isInfoEnabled())) {
- LOG.info("Slice size: " + sliceSize + " URLs.");
- }
- }
-
- public void close() throws IOException {
- }
-
- public void configure(JobConf conf) {
- setConf(conf);
- if (sliceSize > 0) {
- sliceSize = sliceSize / conf.getNumReduceTasks();
- }
- }
-
- private Text newKey = new Text();
-
- public void map(Text key, MetaWrapper value,
- OutputCollector<Text, MetaWrapper> output, Reporter reporter) throws IOException {
- String url = key.toString();
- if (normalizers != null) {
- try {
- url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT); // normalize the url
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e.getMessage());
- url = null;
- }
- }
- if (url != null && filters != null) {
- try {
- url = filters.filter(url);
- } catch (Exception e) {
- LOG.warn("Skipping key " + url + ": " + e.getMessage());
- url = null;
- }
- }
- if(url != null) {
- newKey.set(url);
- output.collect(newKey, value);
- }
- }
-
- /**
- * NOTE: in selecting the latest version we rely exclusively on the segment
- * name (not all segment data contain time information). Therefore it is extremely
- * important that segments be named in an increasing lexicographic order as
- * their creation time increases.
- */
- public void reduce(Text key, Iterator<MetaWrapper> values,
- OutputCollector<Text, MetaWrapper> output, Reporter reporter) throws IOException {
- CrawlDatum lastG = null;
- CrawlDatum lastF = null;
- CrawlDatum lastSig = null;
- Content lastC = null;
- ParseData lastPD = null;
- ParseText lastPT = null;
- String lastGname = null;
- String lastFname = null;
- String lastSigname = null;
- String lastCname = null;
- String lastPDname = null;
- String lastPTname = null;
- TreeMap<String, ArrayList<CrawlDatum>> linked =
- new TreeMap<String, ArrayList<CrawlDatum>>();
- while (values.hasNext()) {
- MetaWrapper wrapper = values.next();
- Object o = wrapper.get();
- String spString = wrapper.getMeta(SEGMENT_PART_KEY);
- if (spString == null) {
- throw new IOException("Null segment part, key=" + key);
- }
- SegmentPart sp = SegmentPart.parse(spString);
- if (o instanceof CrawlDatum) {
- CrawlDatum val = (CrawlDatum)o;
- // check which output dir it belongs to
- if (sp.partName.equals(CrawlDatum.GENERATE_DIR_NAME)) {
- if (lastG == null) {
- lastG = val;
- lastGname = sp.segmentName;
- } else {
- // take newer
- if (lastGname.compareTo(sp.segmentName) < 0) {
- lastG = val;
- lastGname = sp.segmentName;
- }
- }
- } else if (sp.partName.equals(CrawlDatum.FETCH_DIR_NAME)) {
- if (lastF == null) {
- lastF = val;
- lastFname = sp.segmentName;
- } else {
- // take newer
- if (lastFname.compareTo(sp.segmentName) < 0) {
- lastF = val;
- lastFname = sp.segmentName;
- }
- }
- } else if (sp.partName.equals(CrawlDatum.PARSE_DIR_NAME)) {
- if (val.getStatus() == CrawlDatum.STATUS_SIGNATURE) {
- if (lastSig == null) {
- lastSig = val;
- lastSigname = sp.segmentName;
- } else {
- // take newer
- if (lastSigname.compareTo(sp.segmentName) < 0) {
- lastSig = val;
- lastSigname = sp.segmentName;
- }
- }
- continue;
- }
- // collect all LINKED values from the latest segment
- ArrayList<CrawlDatum> segLinked = linked.get(sp.segmentName);
- if (segLinked == null) {
- segLinked = new ArrayList<CrawlDatum>();
- linked.put(sp.segmentName, segLinked);
- }
- segLinked.add(val);
- } else {
- throw new IOException("Cannot determine segment part: " + sp.partName);
- }
- } else if (o instanceof Content) {
- if (lastC == null) {
- lastC = (Content)o;
- lastCname = sp.segmentName;
- } else {
- if (lastCname.compareTo(sp.segmentName) < 0) {
- lastC = (Content)o;
- lastCname = sp.segmentName;
- }
- }
- } else if (o instanceof ParseData) {
- if (lastPD == null) {
- lastPD = (ParseData)o;
- lastPDname = sp.segmentName;
- } else {
- if (lastPDname.compareTo(sp.segmentName) < 0) {
- lastPD = (ParseData)o;
- lastPDname = sp.segmentName;
- }
- }
- } else if (o instanceof ParseText) {
- if (lastPT == null) {
- lastPT = (ParseText)o;
- lastPTname = sp.segmentName;
- } else {
- if (lastPTname.compareTo(sp.segmentName) < 0) {
- lastPT = (ParseText)o;
- lastPTname = sp.segmentName;
- }
- }
- }
- }
- curCount++;
- String sliceName = null;
- MetaWrapper wrapper = new MetaWrapper();
- if (sliceSize > 0) {
- sliceName = String.valueOf(curCount / sliceSize);
- wrapper.setMeta(SEGMENT_SLICE_KEY, sliceName);
- }
- SegmentPart sp = new SegmentPart();
- // now output the latest values
- if (lastG != null) {
- wrapper.set(lastG);
- sp.partName = CrawlDatum.GENERATE_DIR_NAME;
- sp.segmentName = lastGname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastF != null) {
- wrapper.set(lastF);
- sp.partName = CrawlDatum.FETCH_DIR_NAME;
- sp.segmentName = lastFname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastSig != null) {
- wrapper.set(lastSig);
- sp.partName = CrawlDatum.PARSE_DIR_NAME;
- sp.segmentName = lastSigname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastC != null) {
- wrapper.set(lastC);
- sp.partName = Content.DIR_NAME;
- sp.segmentName = lastCname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastPD != null) {
- wrapper.set(lastPD);
- sp.partName = ParseData.DIR_NAME;
- sp.segmentName = lastPDname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastPT != null) {
- wrapper.set(lastPT);
- sp.partName = ParseText.DIR_NAME;
- sp.segmentName = lastPTname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (linked.size() > 0) {
- String name = linked.lastKey();
- sp.partName = CrawlDatum.PARSE_DIR_NAME;
- sp.segmentName = name;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- ArrayList<CrawlDatum> segLinked = linked.get(name);
- for (int i = 0; i < segLinked.size(); i++) {
- CrawlDatum link = segLinked.get(i);
- wrapper.set(link);
- output.collect(key, wrapper);
- }
- }
- }
-
- public void merge(Path out, Path[] segs, boolean filter, boolean normalize, long slice) throws Exception {
- String segmentName = Generator.generateSegmentName();
- if (LOG.isInfoEnabled()) {
- LOG.info("Merging " + segs.length + " segments to " + out + "/" + segmentName);
- }
- JobConf job = new NutchJob(getConf());
- job.setJobName("mergesegs " + out + "/" + segmentName);
- job.setBoolean("segment.merger.filter", filter);
- job.setBoolean("segment.merger.normalizer", normalize);
- job.setLong("segment.merger.slice", slice);
- job.set("segment.merger.segmentName", segmentName);
- FileSystem fs = FileSystem.get(getConf());
- // prepare the minimal common set of input dirs
- boolean g = true;
- boolean f = true;
- boolean p = true;
- boolean c = true;
- boolean pd = true;
- boolean pt = true;
- for (int i = 0; i < segs.length; i++) {
- if (!fs.exists(segs[i])) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Input dir " + segs[i] + " doesn't exist, skipping.");
- }
- segs[i] = null;
- continue;
- }
- if (LOG.isInfoEnabled()) {
- LOG.info("SegmentMerger: adding " + segs[i]);
- }
- Path cDir = new Path(segs[i], Content.DIR_NAME);
- Path gDir = new Path(segs[i], CrawlDatum.GENERATE_DIR_NAME);
- Path fDir = new Path(segs[i], CrawlDatum.FETCH_DIR_NAME);
- Path pDir = new Path(segs[i], CrawlDatum.PARSE_DIR_NAME);
- Path pdDir = new Path(segs[i], ParseData.DIR_NAME);
- Path ptDir = new Path(segs[i], ParseText.DIR_NAME);
- c = c && fs.exists(cDir);
- g = g && fs.exists(gDir);
- f = f && fs.exists(fDir);
- p = p && fs.exists(pDir);
- pd = pd && fs.exists(pdDir);
- pt = pt && fs.exists(ptDir);
- }
- StringBuffer sb = new StringBuffer();
- if (c) sb.append(" " + Content.DIR_NAME);
- if (g) sb.append(" " + CrawlDatum.GENERATE_DIR_NAME);
- if (f) sb.append(" " + CrawlDatum.FETCH_DIR_NAME);
- if (p) sb.append(" " + CrawlDatum.PARSE_DIR_NAME);
- if (pd) sb.append(" " + ParseData.DIR_NAME);
- if (pt) sb.append(" " + ParseText.DIR_NAME);
- if (LOG.isInfoEnabled()) {
- LOG.info("SegmentMerger: using segment data from:" + sb.toString());
- }
- for (int i = 0; i < segs.length; i++) {
- if (segs[i] == null) continue;
- if (g) {
- Path gDir = new Path(segs[i], CrawlDatum.GENERATE_DIR_NAME);
- FileInputFormat.addInputPath(job, gDir);
- }
- if (c) {
- Path cDir = new Path(segs[i], Content.DIR_NAME);
- FileInputFormat.addInputPath(job, cDir);
- }
- if (f) {
- Path fDir = new Path(segs[i], CrawlDatum.FETCH_DIR_NAME);
- FileInputFormat.addInputPath(job, fDir);
- }
- if (p) {
- Path pDir = new Path(segs[i], CrawlDatum.PARSE_DIR_NAME);
- FileInputFormat.addInputPath(job, pDir);
- }
- if (pd) {
- Path pdDir = new Path(segs[i], ParseData.DIR_NAME);
- FileInputFormat.addInputPath(job, pdDir);
- }
- if (pt) {
- Path ptDir = new Path(segs[i], ParseText.DIR_NAME);
- FileInputFormat.addInputPath(job, ptDir);
- }
- }
- job.setInputFormat(ObjectInputFormat.class);
- job.setMapperClass(SegmentMerger.class);
- job.setReducerClass(SegmentMerger.class);
- FileOutputFormat.setOutputPath(job, out);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(MetaWrapper.class);
- job.setOutputFormat(SegmentOutputFormat.class);
-
- setConf(job);
-
- JobClient.runJob(job);
- }
-
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("SegmentMerger output_dir (-dir segments | seg1 seg2 ...) [-filter] [-slice NNNN]");
- System.err.println("\toutput_dir\tname of the parent dir for output segment slice(s)");
- System.err.println("\t-dir segments\tparent dir containing several segments");
- System.err.println("\tseg1 seg2 ...\tlist of segment dirs");
- System.err.println("\t-filter\t\tfilter out URL-s prohibited by current URLFilters");
- System.err.println("\t-slice NNNN\tcreate many output segments, each containing NNNN URLs");
- return;
- }
- Configuration conf = NutchConfiguration.create();
- final FileSystem fs = FileSystem.get(conf);
- Path out = new Path(args[0]);
- ArrayList<Path> segs = new ArrayList<Path>();
- long sliceSize = 0;
- boolean filter = false;
- boolean normalize = false;
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-dir")) {
- FileStatus[] fstats = fs.listStatus(new Path(args[++i]),
- HadoopFSUtil.getPassDirectoriesFilter(fs));
- Path[] files = HadoopFSUtil.getPaths(fstats);
- for (int j = 0; j < files.length; j++)
- segs.add(files[j]);
- } else if (args[i].equals("-filter")) {
- filter = true;
- } else if (args[i].equals("-normalize")) {
- normalize = true;
- } else if (args[i].equals("-slice")) {
- sliceSize = Long.parseLong(args[++i]);
- } else {
- segs.add(new Path(args[i]));
- }
- }
- if (segs.size() == 0) {
- System.err.println("ERROR: No input segments.");
- return;
- }
- SegmentMerger merger = new SegmentMerger(conf);
- merger.merge(out, segs.toArray(new Path[segs.size()]), filter, normalize, sliceSize);
- }
-
-}
diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.java
index 9abdd9ec8..59eee817f 100644
--- a/src/java/org/apache/nutch/segment/SegmentReader.java
+++ b/src/java/org/apache/nutch/segment/SegmentReader.java
@@ -68,7 +68,7 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.HadoopFSUtil;
import org.apache.nutch.util.LogUtil;
import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.NutchJobConf;
/** Dump the content of a segment. */
public class SegmentReader extends Configured implements
@@ -158,7 +158,7 @@ public class SegmentReader extends Configured implements
}
private JobConf createJobConf() {
- JobConf job = new NutchJob(getConf());
+ JobConf job = new NutchJobConf(getConf());
job.setBoolean("segment.reader.co", this.co);
job.setBoolean("segment.reader.fe", this.fe);
job.setBoolean("segment.reader.ge", this.ge);
diff --git a/src/java/org/apache/nutch/tools/FreeGenerator.java b/src/java/org/apache/nutch/tools/FreeGenerator.java
deleted file mode 100644
index dfca7564d..000000000
--- a/src/java/org/apache/nutch/tools/FreeGenerator.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.tools;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map.Entry;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.io.WritableComparable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapReduceBase;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.TextInputFormat;
-import org.apache.hadoop.util.StringUtils;
-import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.util.ToolRunner;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Generator;
-import org.apache.nutch.crawl.PartitionUrlByHost;
-import org.apache.nutch.net.URLFilters;
-import org.apache.nutch.net.URLNormalizers;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
-
-/**
- * This tool generates fetchlists (segments to be fetched) from plain text
- * files containing one URL per line. It's useful when arbitrary URL-s need to
- * be fetched without adding them first to the CrawlDb, or during testing.
- *
- * @author Andrzej Bialecki
- */
-public class FreeGenerator extends Configured implements Tool {
- private static final Log LOG = LogFactory.getLog(FreeGenerator.class);
-
- private static final String FILTER_KEY = "free.generator.filter";
- private static final String NORMALIZE_KEY = "free.generator.normalize";
-
- public static class FG extends MapReduceBase
- implements Mapper<WritableComparable, Text, Text, Generator.SelectorEntry>,
- Reducer<Text, Generator.SelectorEntry, Text, CrawlDatum> {
- private URLNormalizers normalizers = null;
- private URLFilters filters = null;
- private ScoringFilters scfilters;
- private CrawlDatum datum = new CrawlDatum();
- private Text url = new Text();
-
- @Override
- public void configure(JobConf job) {
- super.configure(job);
- scfilters = new ScoringFilters(job);
- if (job.getBoolean(FILTER_KEY, false)) {
- filters = new URLFilters(job);
- }
- if (job.getBoolean(NORMALIZE_KEY, false)) {
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_INJECT);
- }
- }
-
- Generator.SelectorEntry entry = new Generator.SelectorEntry();
-
- public void map(WritableComparable key, Text value, OutputCollector<Text,
- Generator.SelectorEntry> output, Reporter reporter) throws IOException {
- // value is a line of text
- String urlString = value.toString();
- try {
- if (normalizers != null) {
- urlString = normalizers.normalize(urlString, URLNormalizers.SCOPE_INJECT);
- }
- if (urlString != null && filters != null) {
- urlString = filters.filter(urlString);
- }
- if (urlString != null) {
- url.set(urlString);
- scfilters.injectedScore(url, datum);
- }
- } catch (Exception e) {
- LOG.warn("Error adding url '" + value.toString() + "', skipping: " + StringUtils.stringifyException(e));
- return;
- }
- if (urlString == null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("- skipping " + value.toString());
- }
- return;
- }
- entry.datum = datum;
- entry.url = url;
- output.collect(url, entry);
- }
-
- public void reduce(Text key, Iterator<Generator.SelectorEntry> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter) throws IOException {
- // pick unique urls from values - discard the reduce key due to hash collisions
- HashMap<Text, CrawlDatum> unique = new HashMap<Text, CrawlDatum>();
- while (values.hasNext()) {
- Generator.SelectorEntry entry = (Generator.SelectorEntry)values.next();
- unique.put(entry.url, entry.datum);
- }
- // output unique urls
- for (Entry<Text, CrawlDatum> e : unique.entrySet()) {
- output.collect(e.getKey(), e.getValue());
- }
- }
- }
-
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Usage: FreeGenerator <inputDir> <segmentsDir> [-filter] [-normalize]");
- System.err.println("\tinputDir\tinput directory containing one or more input files.");
- System.err.println("\t\tEach text file contains a list of URLs, one URL per line");
- System.err.println("\tsegmentsDir\toutput directory, where new segment will be created");
- System.err.println("\t-filter\trun current URLFilters on input URLs");
- System.err.println("\t-normalize\trun current URLNormalizers on input URLs");
- return -1;
- }
- boolean filter = false;
- boolean normalize = false;
- if (args.length > 2) {
- for (int i = 2; i < args.length; i++) {
- if (args[i].equals("-filter")) {
- filter = true;
- } else if (args[i].equals("-normalize")) {
- normalize = true;
- } else {
- LOG.fatal("Unknown argument: " + args[i] + ", exiting ...");
- return -1;
- }
- }
- }
-
- JobConf job = new NutchJob(getConf());
- job.setBoolean(FILTER_KEY, filter);
- job.setBoolean(NORMALIZE_KEY, normalize);
- FileInputFormat.addInputPath(job, new Path(args[0]));
- job.setInputFormat(TextInputFormat.class);
- job.setMapperClass(FG.class);
- job.setMapOutputKeyClass(Text.class);
- job.setMapOutputValueClass(Generator.SelectorEntry.class);
- job.setPartitionerClass(PartitionUrlByHost.class);
- job.setReducerClass(FG.class);
- String segName = Generator.generateSegmentName();
- job.setNumReduceTasks(job.getNumMapTasks());
- job.setOutputFormat(SequenceFileOutputFormat.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
- job.setOutputKeyComparatorClass(Generator.HashComparator.class);
- FileOutputFormat.setOutputPath(job, new Path(args[1],
- new Path(segName, CrawlDatum.GENERATE_DIR_NAME)));
- try {
- JobClient.runJob(job);
- return 0;
- } catch (Exception e) {
- LOG.fatal("FAILED: " + StringUtils.stringifyException(e));
- return -1;
- }
- }
-
- public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new FreeGenerator(), args);
- System.exit(res);
- }
-}
diff --git a/src/java/org/apache/nutch/util/EncodingDetector.java b/src/java/org/apache/nutch/util/EncodingDetector.java
index b0440805c..c57e218ce 100644
--- a/src/java/org/apache/nutch/util/EncodingDetector.java
+++ b/src/java/org/apache/nutch/util/EncodingDetector.java
@@ -34,6 +34,7 @@ import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogUtil;
import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.hbase.WebTableRow;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
@@ -81,10 +82,12 @@ public class EncodingDetector {
this.confidence = confidence;
}
+ @SuppressWarnings("unused")
public String getSource() {
return source;
}
+ @SuppressWarnings("unused")
public String getValue() {
return value;
}
@@ -163,9 +166,20 @@ public class EncodingDetector {
}
public void autoDetectClues(Content content, boolean filter) {
- byte[] data = content.getContent();
+ autoDetectClues(content.getContent(), content.getContentType(),
+ parseCharacterEncoding(content.getMetadata().get(Response.CONTENT_TYPE)),
+ filter);
+ }
+
+ public void autoDetectClues(WebTableRow row, boolean filter) {
+ autoDetectClues(row.getContent(), row.getContentType(),
+ parseCharacterEncoding(row.getHeader(Response.CONTENT_TYPE)), filter);
+ }
+
+ private void autoDetectClues(byte[] data, String type,
+ String encoding, boolean filter) {
- if (minConfidence >= 0 && DETECTABLES.contains(content.getContentType())
+ if (minConfidence >= 0 && DETECTABLES.contains(type)
&& data.length > MIN_LENGTH) {
CharsetMatch[] matches = null;
@@ -190,8 +204,7 @@ public class EncodingDetector {
}
// add character encoding coming from HTTP response header
- addClue(parseCharacterEncoding(
- content.getMetadata().get(Response.CONTENT_TYPE)), "header");
+ addClue(encoding, "header");
}
public void addClue(String value, String source, int confidence) {
@@ -207,7 +220,7 @@ public class EncodingDetector {
public void addClue(String value, String source) {
addClue(value, source, NO_THRESHOLD);
}
-
+
/**
* Guess the encoding with the previously specified list of clues.
*
@@ -219,6 +232,34 @@ public class EncodingDetector {
* @return Guessed encoding or defaultValue
*/
public String guessEncoding(Content content, String defaultValue) {
+ return guessEncoding(content.getBaseUrl(), defaultValue);
+ }
+
+ /**
+ * Guess the encoding with the previously specified list of clues.
+ *
+ * @param row URL's row
+ * @param defaultValue Default encoding to return if no encoding can be
+ * detected with enough confidence. Note that this will <b>not</b> be
+ * normalized with {@link EncodingDetector#resolveEncodingAlias}
+ *
+ * @return Guessed encoding or defaultValue
+ */
+ public String guessEncoding(WebTableRow row, String defaultValue) {
+ return guessEncoding(row.getBaseUrl(), defaultValue);
+ }
+
+ /**
+ * Guess the encoding with the previously specified list of clues.
+ *
+ * @param baseUrl Base URL
+ * @param defaultValue Default encoding to return if no encoding can be
+ * detected with enough confidence. Note that this will <b>not</b> be
+ * normalized with {@link EncodingDetector#resolveEncodingAlias}
+ *
+ * @return Guessed encoding or defaultValue
+ */
+ private String guessEncoding(String baseUrl, String defaultValue) {
/*
* This algorithm could be replaced by something more sophisticated;
* ideally we would gather a bunch of data on where various clues
@@ -227,10 +268,9 @@ public class EncodingDetector {
* to generate a better heuristic.
*/
- String base = content.getBaseUrl();
if (LOG.isTraceEnabled()) {
- findDisagreements(base, clues);
+ findDisagreements(baseUrl, clues);
}
/*
@@ -244,12 +284,12 @@ public class EncodingDetector {
for (EncodingClue clue : clues) {
if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": charset " + clue);
+ LOG.trace(baseUrl + ": charset " + clue);
}
String charset = clue.value;
if (minConfidence >= 0 && clue.confidence >= minConfidence) {
if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": Choosing encoding: " + charset +
+ LOG.trace(baseUrl + ": Choosing encoding: " + charset +
" with confidence " + clue.confidence);
}
return resolveEncodingAlias(charset).toLowerCase();
@@ -259,7 +299,7 @@ public class EncodingDetector {
}
if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": Choosing encoding: " + bestClue);
+ LOG.trace(baseUrl + ": Choosing encoding: " + bestClue);
}
return bestClue.value.toLowerCase();
}
@@ -371,10 +411,11 @@ public class EncodingDetector {
}
byte[] data = ostr.toByteArray();
+ MimeUtil mimeTypes = new MimeUtil(conf);
// make a fake Content
Content content =
- new Content("", "", data, "text/html", new Metadata(), conf);
+ new Content("", "", data, "text/html", new Metadata(), mimeTypes);
detector.autoDetectClues(content, true);
String encoding = detector.guessEncoding(content,
diff --git a/src/java/org/apache/nutch/util/NutchJob.java b/src/java/org/apache/nutch/util/NutchJob.java
index fef433fe8..7e6f06506 100644
--- a/src/java/org/apache/nutch/util/NutchJob.java
+++ b/src/java/org/apache/nutch/util/NutchJob.java
@@ -17,15 +17,21 @@
package org.apache.nutch.util;
+import java.io.IOException;
+
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
-/** A {@link JobConf} for Nutch jobs. */
-public class NutchJob extends JobConf {
+/** A {@link Job} for Nutch jobs. */
+public class NutchJob extends Job {
- public NutchJob(Configuration conf) {
- super(conf, NutchJob.class);
+ public NutchJob(Configuration conf) throws IOException {
+ super(conf);
+ setJarByClass(this.getClass());
}
-
-}
-
+
+ public NutchJob(Configuration conf, String jobName) throws IOException {
+ super(conf, jobName);
+ setJarByClass(this.getClass());
+ }
+}
\ No newline at end of file
diff --git a/src/java/org/apache/nutch/util/NutchJobConf.java b/src/java/org/apache/nutch/util/NutchJobConf.java
new file mode 100644
index 000000000..f7f8076bc
--- /dev/null
+++ b/src/java/org/apache/nutch/util/NutchJobConf.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.nutch.util;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapred.JobConf;
+
+/** A {@link JobConf} for Nutch jobs. */
+public class NutchJobConf extends JobConf {
+
+ public NutchJobConf(Configuration conf) {
+ super(conf, NutchJobConf.class);
+ }
+
+}
+
diff --git a/src/java/org/apache/nutch/util/domain/DomainStatistics.java b/src/java/org/apache/nutch/util/domain/DomainStatistics.java
index 843877a02..ff19fbfd7 100644
--- a/src/java/org/apache/nutch/util/domain/DomainStatistics.java
+++ b/src/java/org/apache/nutch/util/domain/DomainStatistics.java
@@ -42,7 +42,7 @@ import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.NutchJobConf;
import org.apache.nutch.util.URLUtil;
/**
@@ -81,7 +81,7 @@ implements Tool, Mapper<Text, CrawlDatum, Text, LongWritable>,
numOfReducers = Integer.parseInt(args[3]);
}
- JobConf job = new NutchJob(getConf());
+ JobConf job = new NutchJobConf(getConf());
job.setJobName("Domain statistics");
int mode = 0;
diff --git a/src/java/org/apache/nutch/util/hbase/ColumnData.java b/src/java/org/apache/nutch/util/hbase/ColumnData.java
new file mode 100644
index 000000000..8d08661fd
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/ColumnData.java
@@ -0,0 +1,51 @@
+package org.apache.nutch.util.hbase;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.Writable;
+
+public class ColumnData implements Writable {
+
+ private byte[] data;
+ private boolean isModified;
+
+ public ColumnData() { // do not use!
+ }
+
+ public ColumnData(byte[] data) {
+ this(data, false);
+ }
+
+ public ColumnData(byte[] data, boolean isModified) {
+ this.data = data;
+ this.isModified = isModified;
+ }
+
+ public void set(byte[] data) {
+ this.data = data;
+ isModified = true;
+ }
+
+ public byte[] getData() {
+ return data;
+ }
+
+ public boolean isModified() {
+ return isModified;
+ }
+
+ @Override
+ public void readFields(DataInput in) throws IOException {
+ data = Bytes.readByteArray(in);
+ isModified = in.readBoolean();
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ Bytes.writeByteArray(out, data);
+ out.writeBoolean(isModified);
+ }
+}
diff --git a/src/java/org/apache/nutch/util/hbase/ColumnDescriptor.java b/src/java/org/apache/nutch/util/hbase/ColumnDescriptor.java
new file mode 100644
index 000000000..af073fe69
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/ColumnDescriptor.java
@@ -0,0 +1,21 @@
+package org.apache.nutch.util.hbase;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.io.hfile.Compression;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface ColumnDescriptor {
+ int versions() default HColumnDescriptor.DEFAULT_VERSIONS;
+ Compression.Algorithm compression() default Compression.Algorithm.NONE;
+ boolean inMemory() default HColumnDescriptor.DEFAULT_IN_MEMORY;
+ boolean blockCacheEnabled() default HColumnDescriptor.DEFAULT_BLOCKCACHE;
+ int blockSize() default HColumnDescriptor.DEFAULT_BLOCKSIZE;
+ int timeToLive() default HColumnDescriptor.DEFAULT_TTL;
+ boolean bloomFilter() default HColumnDescriptor.DEFAULT_BLOOMFILTER;
+}
diff --git a/src/java/org/apache/nutch/util/hbase/HbaseColumn.java b/src/java/org/apache/nutch/util/hbase/HbaseColumn.java
new file mode 100644
index 000000000..e2ac6f207
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/HbaseColumn.java
@@ -0,0 +1,34 @@
+package org.apache.nutch.util.hbase;
+
+public class HbaseColumn {
+ private byte[] family;
+ private byte[] qualifier;
+ private int versions;
+
+ public HbaseColumn(byte[] family) {
+ this(family, null, 1);
+ }
+
+ public HbaseColumn(byte[] family, byte[] qualifier) {
+ this(family, qualifier, 1);
+ }
+
+ public HbaseColumn(byte[] family, byte[] qualifier, int versions) {
+ this.family = family;
+ this.qualifier = qualifier;
+ this.versions = versions;
+ }
+
+ public byte[] getFamily() {
+ return family;
+ }
+
+ public byte[] getQualifier() {
+ return qualifier;
+ }
+
+ public int getVersions() {
+ return versions;
+ }
+
+}
diff --git a/src/java/org/apache/nutch/util/hbase/RowMutation.java b/src/java/org/apache/nutch/util/hbase/RowMutation.java
new file mode 100644
index 000000000..93a224f33
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/RowMutation.java
@@ -0,0 +1,149 @@
+package org.apache.nutch.util.hbase;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableComparable;
+import org.apache.hadoop.mapreduce.Reducer;
+
+public class RowMutation implements Writable {
+
+ private static class RowOperation implements Writable {
+ private byte[] family, qualifier, value;
+ private long ts;
+
+ RowOperation() { }
+
+ public RowOperation(byte[] family, byte[] qualifier, byte[] value) {
+ this(family, qualifier, value, HConstants.LATEST_TIMESTAMP);
+ }
+
+ public RowOperation(byte[] family, byte[] qualifier, byte[] value, long ts) {
+ this.family = family;
+ this.qualifier = qualifier;
+ this.value = value;
+ this.ts = ts;
+ }
+
+ @Override
+ public void readFields(DataInput in) throws IOException {
+ family = Bytes.readByteArray(in);
+ qualifier = Bytes.readByteArray(in);
+ value = Bytes.readByteArray(in);
+ ts = in.readLong();
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ Bytes.writeByteArray(out, family);
+ Bytes.writeByteArray(out, qualifier);
+ Bytes.writeByteArray(out, value);
+ out.writeLong(ts);
+ }
+ }
+
+ private byte[] row;
+
+ private List<RowOperation> ops = new ArrayList<RowOperation>();
+
+ public RowMutation() { }
+
+ public RowMutation(byte[] row) {
+ this.row = row;
+ }
+
+ @Override
+ public void readFields(DataInput in) throws IOException {
+ row = Bytes.readByteArray(in);
+ int size = in.readInt();
+ for (int i = 0; i < size; i++) {
+ RowOperation rowOp = new RowOperation();
+ rowOp.readFields(in);
+ ops.add(rowOp);
+ }
+ }
+
+ public void add(byte[] family, byte[] qualifier, byte[] value) {
+ ops.add(new RowOperation(family, qualifier, value));
+ }
+
+ public void delete(byte[] family, byte[] qualifier) {
+ ops.add(new RowOperation(family, qualifier, null));
+ }
+
+ public void add(byte[] family, byte[] qualifier, long ts, byte[] value) {
+ ops.add(new RowOperation(family, qualifier, value, ts));
+ }
+
+ public void delete(byte[] family, byte[] qualifier, long ts) {
+ ops.add(new RowOperation(family, qualifier, null, ts));
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ Bytes.writeByteArray(out, row);
+ for (RowOperation rowOp : ops) {
+ rowOp.write(out);
+ }
+ }
+
+ public void commit(HTable table) throws IOException {
+ Put put = new Put(row);
+ Delete delete = new Delete(row); // deletes entire row, so be careful
+ boolean hasPuts = false;
+ boolean hasDeletes = false;
+
+ for (RowOperation rowOp : ops) {
+ byte[] value = rowOp.value;
+ if (value == null) {
+ hasDeletes = true;
+ delete.deleteColumn(rowOp.family, rowOp.qualifier, rowOp.ts);
+ } else {
+ hasPuts = true;
+ put.add(rowOp.family, rowOp.qualifier, rowOp.ts, rowOp.value);
+ }
+ }
+ if (hasPuts) {
+ table.put(put);
+ }
+ if (hasDeletes) {
+ table.delete(delete);
+ }
+ }
+
+ public <K2 extends WritableComparable<? super K2>>
+ void writeToContext(K2 key, Reducer<?, ?, K2, Writable>.Context context)
+ throws IOException, InterruptedException {
+ Put put = new Put(row);
+ Delete delete = new Delete(row); // deletes entire row, be careful
+ boolean hasPuts = false;
+ boolean hasDeletes = false;
+
+ for (RowOperation rowOp : ops) {
+ byte[] value = rowOp.value;
+ if (value == null) {
+ hasDeletes = true;
+ delete.deleteColumn(rowOp.family, rowOp.qualifier);
+ } else {
+ hasPuts = true;
+ put.add(rowOp.family, rowOp.qualifier, rowOp.value);
+ }
+ }
+ if (hasPuts) {
+ context.write(key, put);
+ }
+ if (hasDeletes) {
+ context.write(key, delete);
+ }
+ }
+
+}
diff --git a/src/java/org/apache/nutch/util/hbase/TableRow.java b/src/java/org/apache/nutch/util/hbase/TableRow.java
new file mode 100644
index 000000000..d4c1a089e
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/TableRow.java
@@ -0,0 +1,240 @@
+package org.apache.nutch.util.hbase;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.Comparator;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.io.Writable;
+
+class TableRow implements Writable {
+
+ private static Comparator<Long> TS_COMPARATOR = new Comparator<Long>() {
+ public int compare(Long l1, Long l2) {
+ return l2.compareTo(l1);
+ }
+ };
+
+ protected static byte[] EMPTY = new byte[0];
+
+ protected byte[] row;
+
+ protected long now;
+
+ // used for family:qualifier columns
+ protected final NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, ColumnData>>> map =
+ new TreeMap<byte[], NavigableMap<byte[], NavigableMap<Long, ColumnData>>>(Bytes.BYTES_COMPARATOR);
+
+ public TableRow() { // do not use!
+ now = System.currentTimeMillis();
+ }
+
+ public TableRow(byte[] row) {
+ this();
+ this.row = row;
+ }
+
+ public TableRow(Result result) {
+ this();
+ row = result.getRow();
+ for (Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> e1 : result.getMap().entrySet()) {
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> familyMap = new TreeMap<byte[], NavigableMap<Long,ColumnData>>(Bytes.BYTES_COMPARATOR);
+ for (Entry<byte[], NavigableMap<Long, byte[]>> e2 : e1.getValue().entrySet()) {
+ NavigableMap<Long, ColumnData> qualMap = new TreeMap<Long, ColumnData>(TS_COMPARATOR);
+ for (Entry<Long, byte[]> e3 : e2.getValue().entrySet()) {
+ qualMap.put(e3.getKey(), new ColumnData(e3.getValue()));
+ }
+ familyMap.put(e2.getKey(), qualMap);
+ }
+ map.put(e1.getKey(), familyMap);
+ }
+ }
+
+ public boolean hasColumn(byte[] family, byte[] qualifier) {
+ if (qualifier == null) { qualifier = EMPTY; }
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> qualMap = map.get(family);
+ if (qualMap != null) {
+ NavigableMap<Long, ColumnData> versionMap = qualMap.get(qualifier);
+ if (versionMap != null) {
+ return versionMap.firstEntry().getValue().getData() != null;
+ }
+ }
+ return false;
+ }
+
+ public void delete(byte[] family, byte[] qualifier) {
+ delete(family, qualifier, HConstants.LATEST_TIMESTAMP);
+ }
+
+ public void delete(byte[] family, byte[] qualifier, long ts) {
+ if (qualifier == null) { qualifier = EMPTY; }
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> familyMap = map.get(family);
+ if (familyMap != null) {
+ NavigableMap<Long, ColumnData> versionMap = familyMap.get(qualifier);
+ if (versionMap != null) {
+ Entry<Long, ColumnData> e = versionMap.ceilingEntry(ts);
+ if (e != null) {
+ e.getValue().set(null);
+ } else {
+ // TODO: if family:qualifier doesn't exist, what to do?
+ // we add a delete for now
+ versionMap.put(now, new ColumnData(null, true));
+ }
+ }
+ }
+ }
+
+ public void deleteFamily(byte[] family) {
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> familyMap = map.get(family);
+ if (familyMap == null) {
+ return;
+ }
+
+ for (Entry<byte[], NavigableMap<Long, ColumnData>> e: familyMap.entrySet()) {
+ ColumnData latestColumnData = e.getValue().firstEntry().getValue();
+ latestColumnData.set(null);
+ }
+
+ }
+
+ public byte[] get(byte[] family, byte[] qualifier) {
+ return get(family, qualifier, HConstants.LATEST_TIMESTAMP);
+ }
+
+ public byte[] get(byte[] family, byte[] qualifier, long ts) {
+ if (qualifier == null) { qualifier = EMPTY; }
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> familyMap = map.get(family);
+ if (familyMap != null) {
+ NavigableMap<Long, ColumnData> versionMap = familyMap.get(qualifier);
+ if (versionMap != null) {
+ Entry<Long, ColumnData> e = versionMap.ceilingEntry(ts);
+ if (e != null) {
+ return e.getValue().getData();
+ }
+ }
+ }
+ return null;
+ }
+
+ public void put(byte[] family, byte[] qualifier, byte[] value) {
+ put(family, qualifier, value, now);
+ }
+
+ public void put(byte[] family, byte[] qualifier, byte[] value, long ts) {
+ if (qualifier == null) { qualifier = EMPTY; }
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> familyMap = map.get(family);
+ if (familyMap == null) {
+ familyMap = new TreeMap<byte[], NavigableMap<Long, ColumnData>>(Bytes.BYTES_COMPARATOR);
+ map.put(family, familyMap);
+ }
+ NavigableMap<Long, ColumnData> versionMap = familyMap.get(qualifier);
+ if (versionMap == null) {
+ versionMap = new TreeMap<Long, ColumnData>(TS_COMPARATOR);
+ familyMap.put(qualifier, versionMap);
+ }
+ versionMap.put(ts, new ColumnData(value, true));
+ }
+
+ public void put(byte[] family, byte[] qualifier, float value) {
+ put(family, qualifier, Bytes.toBytes(value));
+ }
+
+ public void put(byte[] family, byte[] qualifier, int value) {
+ put(family, qualifier, Bytes.toBytes(value));
+ }
+
+ public void put(byte[] family, byte[] qualifier, long value) {
+ put(family, qualifier, Bytes.toBytes(value));
+ }
+
+ public void put(byte[] family, byte[] qualifier, String value) {
+ put(family, qualifier, Bytes.toBytes(value));
+ }
+
+ public RowMutation makeRowMutation() {
+ return makeRowMutation(row);
+ }
+
+ private void addEntry(byte[] family, byte[] qualifier, long ts, byte[] value,
+ RowMutation mut) {
+ if (value == null) {
+ mut.delete(family, qualifier, ts);
+ } else {
+ mut.add(family, qualifier, ts, value);
+ }
+ }
+
+ public RowMutation makeRowMutation(byte[] row) {
+ RowMutation mut = new RowMutation(row);
+ for (Entry<byte[], NavigableMap<byte[], NavigableMap<Long, ColumnData>>> e1 : map.entrySet()) {
+ for (Entry<byte[], NavigableMap<Long, ColumnData>> e2 : e1.getValue().entrySet()) {
+ for (Entry<Long, ColumnData> e3 : e2.getValue().entrySet()) {
+ ColumnData rawDatum = e3.getValue();
+ if (rawDatum.isModified()) {
+ addEntry(e1.getKey(), e2.getKey(), e3.getKey(), rawDatum.getData(), mut);
+ }
+ }
+ }
+ }
+
+ return mut;
+ }
+
+ @Override
+ public void readFields(DataInput in) throws IOException {
+ now = in.readLong();
+ row = Bytes.readByteArray(in);
+
+ map.clear();
+ int mapSize = in.readInt();
+ for (int i = 0; i < mapSize; i++) {
+ byte[] family = Bytes.readByteArray(in);
+ int familyMapSize = in.readInt();
+ TreeMap<byte[], NavigableMap<Long, ColumnData>> familyMap =
+ new TreeMap<byte[], NavigableMap<Long,ColumnData>>(Bytes.BYTES_COMPARATOR);
+ for (int j = 0; j < familyMapSize; j++) {
+ byte[] qual = Bytes.readByteArray(in);
+ int versionMapSize = in.readInt();
+ TreeMap<Long, ColumnData> versionMap = new TreeMap<Long, ColumnData>(TS_COMPARATOR);
+ for (int k = 0; k < versionMapSize; k++) {
+ long ts = in.readLong();
+ ColumnData columnData = new ColumnData();
+ columnData.readFields(in);
+ versionMap.put(ts, columnData);
+ }
+ familyMap.put(qual, versionMap);
+ }
+ map.put(family, familyMap);
+ }
+
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ out.writeLong(now);
+ Bytes.writeByteArray(out, row);
+
+ out.writeInt(map.size());
+ for (Entry<byte[], NavigableMap<byte[], NavigableMap<Long, ColumnData>>> e : map.entrySet()) {
+ Bytes.writeByteArray(out, e.getKey());
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> familyMap = e.getValue();
+ out.writeInt(familyMap.size());
+ for (Entry<byte[], NavigableMap<Long, ColumnData>> e2 : familyMap.entrySet()) {
+ Bytes.writeByteArray(out, e2.getKey());
+ NavigableMap<Long, ColumnData> versionMap = e2.getValue();
+ out.writeInt(versionMap.size());
+ for (Entry<Long, ColumnData> e3 : versionMap.entrySet()) {
+ out.writeLong(e3.getKey());
+ e3.getValue().write(out);
+ }
+ }
+ }
+ }
+
+}
diff --git a/src/java/org/apache/nutch/util/hbase/TableUtil.java b/src/java/org/apache/nutch/util/hbase/TableUtil.java
new file mode 100644
index 000000000..206eca49a
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/TableUtil.java
@@ -0,0 +1,152 @@
+package org.apache.nutch.util.hbase;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.util.Set;
+
+import org.apache.hadoop.hbase.client.Scan;
+
+public class TableUtil {
+
+ public static final byte[] YES_VAL = new byte[] { 'y' };
+
+ private static final int SIZEOF_FLOAT = Float.SIZE / Byte.SIZE;
+
+ /**
+ * Convert a float value to a byte array
+ * @param val
+ * @return the byte array
+ */
+ public static byte[] toBytes(final float val) {
+ ByteBuffer bb = ByteBuffer.allocate(SIZEOF_FLOAT);
+ bb.putFloat(val);
+ return bb.array();
+ }
+
+ /**
+ * Converts a byte array to a float value
+ * @param bytes
+ * @return the long value
+ */
+ public static float toFloat(byte[] bytes) {
+ if (bytes == null || bytes.length == 0) {
+ return -1L;
+ }
+ return ByteBuffer.wrap(bytes).getFloat();
+ }
+
+ /** Reverses a url's domain. This form is better for storing in hbase.
+ * Because scans within the same domain are faster. <p>
+ * E.g. "http://bar.foo.com:8983/to/index.html?a=b" becomes
+ * "com.foo.bar:8983:http/to/index.html?a=b".
+ * @param url url to be reversed
+ * @return Reversed url
+ * @throws MalformedURLException
+ */
+ public static String reverseUrl(String urlString)
+ throws MalformedURLException {
+ return reverseUrl(new URL(urlString));
+ }
+
+ /** Reverses a url's domain. This form is better for storing in hbase.
+ * Because scans within the same domain are faster. <p>
+ * E.g. "http://bar.foo.com:8983/to/index.html?a=b" becomes
+ * "com.foo.bar:http:8983/to/index.html?a=b".
+ * @param url url to be reversed
+ * @return Reversed url
+ */
+ public static String reverseUrl(URL url) {
+ String host = url.getHost();
+ String file = url.getFile();
+ String protocol = url.getProtocol();
+ int port = url.getPort();
+
+ StringBuilder buf = new StringBuilder();
+
+ /* reverse host */
+ reverseAppendSplits(host.split("\\."), buf);
+
+ /* add protocol */
+ buf.append(':');
+ buf.append(protocol);
+
+ /* add port if necessary */
+ if (port != -1) {
+ buf.append(':');
+ buf.append(port);
+ }
+
+ /* add path */
+ if (file.length() == 0 || '/' !=file.charAt(0)) {
+ buf.append('/');
+ }
+ buf.append(file);
+
+ return buf.toString();
+ }
+
+ public static String unreverseUrl(String reversedUrl) {
+ StringBuilder buf = new StringBuilder(reversedUrl.length() + 2);
+
+ int pathBegin = reversedUrl.indexOf('/');
+ String sub = reversedUrl.substring(0, pathBegin);
+
+ String[] splits = sub.split(":"); // {<reversed host>, <port>, <protocol>}
+
+ buf.append(splits[1]); // add protocol
+ buf.append("://");
+ reverseAppendSplits(splits[0].split("\\."), buf); // splits[0] is reversed host
+ if (splits.length == 3) { // has a port
+ buf.append(':');
+ buf.append(splits[2]);
+ }
+ buf.append(reversedUrl.substring(pathBegin));
+ return buf.toString();
+ }
+
+ /** Given a reversed url, returns the reversed host
+ * E.g "com.foo.bar:http:8983/to/index.html?a=b" -> "com.foo.bar"
+ * @param reversedUrl Reversed url
+ * @return Reversed host
+ */
+ public static String getReversedHost(String reversedUrl) {
+ return reversedUrl.substring(0, reversedUrl.indexOf(':'));
+ }
+
+ private static void reverseAppendSplits(String[] splits, StringBuilder buf) {
+ for (int i = splits.length - 1; i > 0; i--) {
+ buf.append(splits[i]);
+ buf.append('.');
+ }
+ buf.append(splits[0]);
+ }
+
+ /** Given a set of columns, returns a space-separated string of columns.
+ *
+ * @param columnSet Column set
+ * @return Space-separated string
+ */
+ public static String getColumns(Set<String> columnSet) {
+ StringBuilder buf = new StringBuilder();
+ for (String column : columnSet) {
+ buf.append(column);
+ buf.append(' ');
+ }
+ return buf.toString();
+ }
+
+ public static Scan createScanFromColumns(Iterable<HbaseColumn> columns) {
+ Scan scan = new Scan();
+ int maxVersions = Integer.MIN_VALUE;
+ for (HbaseColumn col : columns) {
+ if (col.getQualifier() != null) {
+ scan.addColumn(col.getFamily(), col.getQualifier());
+ }
+ scan.addColumn(col.getFamily());
+ maxVersions = Math.max(maxVersions, col.getVersions());
+ }
+ scan.setMaxVersions(maxVersions);
+ return scan;
+ }
+}
diff --git a/src/java/org/apache/nutch/util/hbase/WebTableColumns.java b/src/java/org/apache/nutch/util/hbase/WebTableColumns.java
new file mode 100644
index 000000000..c58ab0f57
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/WebTableColumns.java
@@ -0,0 +1,75 @@
+package org.apache.nutch.util.hbase;
+
+import org.apache.hadoop.hbase.util.Bytes;
+
+public interface WebTableColumns {
+ public static final String BASE_URL_STR = "bas";
+ public static final String STATUS_STR = "stt";
+ public static final String FETCH_TIME_STR = "fcht";
+ public static final String RETRIES_STR = "rtrs";
+ public static final String FETCH_INTERVAL_STR = "fchi";
+ public static final String SCORE_STR = "scr";
+ public static final String MODIFIED_TIME_STR = "modt";
+ public static final String SIGNATURE_STR = "sig";
+ public static final String CONTENT_STR = "cnt";
+ public static final String CONTENT_TYPE_STR = "cnttyp:";
+ public static final String TITLE_STR = "ttl:";
+ public static final String OUTLINKS_STR = "olnk:";
+ public static final String INLINKS_STR = "ilnk:";
+ public static final String PARSE_STATUS_STR = "prsstt:";
+ public static final String PROTOCOL_STATUS_STR = "prtstt:";
+ public static final String TEXT_STR = "txt:";
+ public static final String REPR_URL_STR = "repr:";
+ public static final String HEADERS_STR = "hdrs:";
+ public static final String METADATA_STR = "mtdt:";
+
+ // Hackish solution to access previous versions of some columns
+ public static final String PREV_SIGNATURE_STR = "prvsig";
+ public static final String PREV_FETCH_TIME_STR = "prvfch";
+
+ @ColumnDescriptor
+ public static final byte[] BASE_URL = Bytes.toBytes(BASE_URL_STR);
+ @ColumnDescriptor
+ public static final byte[] STATUS = Bytes.toBytes(STATUS_STR);
+ @ColumnDescriptor
+ public static final byte[] FETCH_TIME = Bytes.toBytes(FETCH_TIME_STR);
+ @ColumnDescriptor
+ public static final byte[] RETRIES = Bytes.toBytes(RETRIES_STR);
+ @ColumnDescriptor
+ public static final byte[] FETCH_INTERVAL = Bytes.toBytes(FETCH_INTERVAL_STR);
+ @ColumnDescriptor
+ public static final byte[] SCORE = Bytes.toBytes(SCORE_STR);
+ @ColumnDescriptor
+ public static final byte[] MODIFIED_TIME = Bytes.toBytes(MODIFIED_TIME_STR);
+ @ColumnDescriptor
+ public static final byte[] SIGNATURE = Bytes.toBytes(SIGNATURE_STR);
+ @ColumnDescriptor
+ public static final byte[] CONTENT = Bytes.toBytes(CONTENT_STR);
+ @ColumnDescriptor
+ public static final byte[] CONTENT_TYPE = Bytes.toBytes(CONTENT_TYPE_STR);
+ @ColumnDescriptor
+ public static final byte[] TITLE = Bytes.toBytes(TITLE_STR);
+ @ColumnDescriptor
+ public static final byte[] OUTLINKS = Bytes.toBytes(OUTLINKS_STR);
+ @ColumnDescriptor
+ public static final byte[] INLINKS = Bytes.toBytes(INLINKS_STR);
+ @ColumnDescriptor
+ public static final byte[] PARSE_STATUS = Bytes.toBytes(PARSE_STATUS_STR);
+ @ColumnDescriptor
+ public static final byte[] PROTOCOL_STATUS = Bytes.toBytes(PROTOCOL_STATUS_STR);
+ @ColumnDescriptor
+ public static final byte[] TEXT = Bytes.toBytes(TEXT_STR);
+ @ColumnDescriptor
+ public static final byte[] REPR_URL = Bytes.toBytes(REPR_URL_STR);
+ @ColumnDescriptor
+ public static final byte[] HEADERS = Bytes.toBytes(HEADERS_STR);
+ @ColumnDescriptor
+ public static final byte[] METADATA = Bytes.toBytes(METADATA_STR);
+
+ // Hackish solution to access previous versions of some columns
+ @ColumnDescriptor
+ public static final byte[] PREV_SIGNATURE = Bytes.toBytes(PREV_SIGNATURE_STR);
+ @ColumnDescriptor
+ public static final byte[] PREV_FETCH_TIME = Bytes.toBytes(PREV_FETCH_TIME_STR);
+
+}
diff --git a/src/java/org/apache/nutch/util/hbase/WebTableCreator.java b/src/java/org/apache/nutch/util/hbase/WebTableCreator.java
new file mode 100644
index 000000000..b27bae4de
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/WebTableCreator.java
@@ -0,0 +1,68 @@
+package org.apache.nutch.util.hbase;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.client.HBaseAdmin;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+
+import org.apache.hadoop.conf.*;
+
+import org.apache.nutch.util.NutchConfiguration;
+
+public class WebTableCreator extends Configured implements Tool {
+
+ public static final Log LOG = LogFactory.getLog(WebTableCreator.class);
+
+ public static void main(String[] args) throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(),
+ new WebTableCreator(), args);
+ System.exit(res);
+ }
+
+ public int run(String[] args) throws Exception {
+
+ if (args.length != 1) {
+ System.err.println("Usage: WebTableCreator <webtable>");
+ return -1;
+ }
+
+ try {
+ HBaseConfiguration hbaseConf = new HBaseConfiguration();
+
+ LOG.info("WebTableCreator: Creating table: " + args[0]);
+ HTableDescriptor tableDesc = new HTableDescriptor(args[0]);
+
+ final Field[] fields = WebTableColumns.class.getFields();
+
+ for (final Field field : fields) {
+ final Annotation ann = field.getAnnotation(ColumnDescriptor.class);
+ if (ann == null) {
+ continue;
+ }
+ ColumnDescriptor colDesc = (ColumnDescriptor) ann;
+ HColumnDescriptor family = new HColumnDescriptor((byte[])field.get(null),
+ colDesc.versions(), colDesc.compression().getName(),
+ colDesc.inMemory(), colDesc.blockCacheEnabled(),
+ colDesc.blockSize(), colDesc.timeToLive(), colDesc.bloomFilter());
+ tableDesc.addFamily(family);
+ }
+
+ HBaseAdmin admin = new HBaseAdmin(hbaseConf);
+ admin.createTable(tableDesc);
+ LOG.info("WebTableCreator: Done.");
+ return 0;
+ } catch (Exception e) {
+ LOG.fatal("WebTableCreator: " + StringUtils.stringifyException(e));
+ return -1;
+ }
+
+ }
+}
diff --git a/src/java/org/apache/nutch/util/hbase/WebTableRow.java b/src/java/org/apache/nutch/util/hbase/WebTableRow.java
new file mode 100644
index 000000000..c7d402ab2
--- /dev/null
+++ b/src/java/org/apache/nutch/util/hbase/WebTableRow.java
@@ -0,0 +1,318 @@
+package org.apache.nutch.util.hbase;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.Writables;
+import static org.apache.nutch.util.hbase.WebTableColumns.*;
+
+import org.apache.nutch.crawl.Inlink;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.protocol.ProtocolStatus;
+
+public class WebTableRow extends TableRow {
+ public WebTableRow() { // do not use!
+ super();
+ }
+
+ public WebTableRow(byte[] row) {
+ super(row);
+ }
+
+ public WebTableRow(Result result) {
+ super(result);
+ }
+
+ private String stringify(byte[] val) {
+ if (val == null)
+ return null;
+ return Bytes.toString(val);
+ }
+
+ public String getBaseUrl() {
+ return stringify(get(BASE_URL, null));
+ }
+
+ public byte getStatus() {
+ return get(STATUS, null)[0];
+ }
+
+ public byte[] getSignature() {
+ return get(SIGNATURE, null);
+ }
+
+ public byte[] getPrevSignature() {
+ return get(PREV_SIGNATURE, null);
+ }
+
+ public long getFetchTime() {
+ return Bytes.toLong(get(FETCH_TIME, null));
+ }
+
+ public long getPrevFetchTime() {
+ byte[] val = get(PREV_FETCH_TIME, null);
+ if (val == null)
+ return 0L;
+
+ return Bytes.toLong(val);
+ }
+
+ public long getModifiedTime() {
+ return Bytes.toLong(get(MODIFIED_TIME, null));
+ }
+
+ public int getFetchInterval() {
+ return Bytes.toInt(get(FETCH_INTERVAL, null));
+ }
+
+ public int getRetriesSinceFetch() {
+ return Bytes.toInt(get(RETRIES, null));
+ }
+
+ public ProtocolStatus getProtocolStatus() throws IOException {
+ final ProtocolStatus protocolStatus = new ProtocolStatus();
+ final byte[] val = get(PROTOCOL_STATUS, null);
+ return (ProtocolStatus) Writables.getWritable(val, protocolStatus);
+ }
+
+ public float getScore() {
+ return Bytes.toFloat(get(SCORE, null));
+ }
+
+ public byte[] getContent() {
+ return get(CONTENT, null);
+ }
+
+ public String getContentType() {
+ return stringify(get(CONTENT_TYPE, null));
+ }
+
+ public String getText() {
+ return stringify(get(TEXT, null));
+ }
+
+ public String getTitle() {
+ return stringify(get(TITLE, null));
+ }
+
+ public ParseStatus getParseStatus() {
+ final ParseStatus parseStatus = new ParseStatus();
+ final byte[] val = get(PARSE_STATUS, null);
+ try {
+ return (ParseStatus) Writables.getWritable(val, parseStatus);
+ } catch (final IOException e) {
+ return null;
+ }
+ }
+
+ public String getReprUrl() {
+ return stringify(get(REPR_URL, null));
+ }
+
+ public void setBaseUrl(String baseUrl) {
+ put(BASE_URL, null, baseUrl);
+ }
+
+ public void setContent(byte[] content) {
+ put(CONTENT, null, content);
+ }
+
+ public void setContentType(String contentType) {
+ put(CONTENT_TYPE, null, contentType);
+ }
+
+ public void setFetchInterval(int fetchInterval) {
+ put(FETCH_INTERVAL, null, fetchInterval);
+ }
+
+ public void setFetchTime(long fetchTime) {
+ put(FETCH_TIME, null, fetchTime);
+ }
+
+ public void setModifiedTime(long modifiedTime) {
+ put(MODIFIED_TIME, null, modifiedTime);
+ }
+
+ public void setParseStatus(ParseStatus parseStatus) throws IOException {
+ put(PARSE_STATUS, null, Writables.getBytes(parseStatus));
+ }
+
+ public void setPrevFetchTime(long prevFetchTime) {
+ put(PREV_FETCH_TIME, null, prevFetchTime);
+ }
+
+ public void setPrevSignature(byte[] prevSig) {
+ put(PREV_SIGNATURE, null, prevSig);
+ }
+
+ public void setProtocolStatus(ProtocolStatus protocolStatus)
+ throws IOException {
+ put(PROTOCOL_STATUS, null, Writables.getBytes(protocolStatus));
+ }
+
+ public void setReprUrl(String reprUrl) {
+ put(REPR_URL, null, reprUrl);
+ }
+
+ public void setRetriesSinceFetch(int retries) {
+ put(RETRIES, null, retries);
+ }
+
+ public void setScore(float score) {
+ put(SCORE, null, score);
+ }
+
+ public void setSignature(byte[] signature) {
+ put(SIGNATURE, null, signature);
+ }
+
+ public void setStatus(byte status) {
+ put(STATUS, null, new byte[] { status });
+ }
+
+ public void setText(String text) {
+ put(TEXT, null, text);
+ }
+
+ public void setTitle(String title) {
+ put(TITLE, null, title);
+ }
+
+ public Collection<Outlink> getOutlinks() {
+ final List<Outlink> outlinks = new ArrayList<Outlink>();
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> outlinkMap =
+ map.get(OUTLINKS);
+ if (outlinkMap == null) {
+ return outlinks;
+ }
+ for (final Entry<byte[], NavigableMap<Long, ColumnData>> e : outlinkMap.entrySet()) {
+ final String toUrl = Bytes.toString(e.getKey());
+ ColumnData latestColumnData = e.getValue().firstEntry().getValue();
+ final String anchor = Bytes.toString(latestColumnData.getData());
+ outlinks.add(new Outlink(toUrl, anchor));
+ }
+ return outlinks;
+ }
+
+ public void addOutlink(Outlink outlink) {
+ put(OUTLINKS, Bytes.toBytes(outlink.getToUrl()),
+ Bytes.toBytes(outlink.getAnchor()));
+ }
+
+ public void deleteAllOutlinks() {
+ deleteFamily(OUTLINKS);
+ }
+
+ public Collection<Inlink> getInlinks() {
+ final List<Inlink> inlinks = new ArrayList<Inlink>();
+ NavigableMap<byte[], NavigableMap<Long, ColumnData>> inlinkMap =
+ map.get(INLINKS);
+ if (inlinkMap == null) {
+ return inlinks;
+ }
+ for (final Entry<byte[], NavigableMap<Long, ColumnData>> e : inlinkMap.entrySet()) {
+ final String fromUrl = Bytes.toString(e.getKey());
+ ColumnData latestColumnData = e.getValue().firstEntry().getValue();
+ final String anchor = Bytes.toString(latestColumnData.getData());
+ inlinks.add(new Inlink(fromUrl, anchor));
+ }
+
+ return inlinks;
+ }
+
+ public void addInlink(Inlink inlink) {
+ put(INLINKS, Bytes.toBytes(inlink.getFromUrl()),
+ Bytes.toBytes(inlink.getAnchor()));
+ }
+
+ public void deleteAllInlinks() {
+ deleteFamily(INLINKS);
+ }
+
+
+ /** Returns a header.
+ * @param key Header-key
+ * @return headers if it exists, null otherwise
+ */
+ public String getHeader(String key) {
+ return getHeader(Bytes.toBytes(key));
+ }
+
+ /** Returns a header.
+ * @param key Header-key
+ * @return headers if it exists, null otherwise
+ */
+ public String getHeader(byte[] key) {
+ byte[] val = get(HEADERS, key);
+ return val == null ? null : stringify(val);
+ }
+
+ public void addHeader(String key, String value) {
+ put(HEADERS, Bytes.toBytes(key), Bytes.toBytes(value));
+ }
+
+ public void deleteHeaders() {
+ deleteFamily(HEADERS);
+ }
+
+ /** Checks if a metadata key exists in "metadata" column.
+ * @param metaKey Key to search in metadata column
+ * @return true if key exists
+ */
+ public boolean hasMeta(String metaKey) {
+ return hasMeta(Bytes.toBytes(metaKey));
+ }
+
+
+ /** Checks if a metadata key exists in "metadata" column.
+ * @param metaKey Key to search in metadata column
+ * @return true if key exists
+ */
+ public boolean hasMeta(byte[] metaKey) {
+ return hasColumn(METADATA, metaKey);
+ }
+
+ /** Read a metadata key from "metadata" column.
+ * @param metaKey Key to search in metadata column
+ * @return Value in byte array form or null if metadata doesn't exist
+ */
+ public byte[] getMeta(String metaKey) {
+ return getMeta(Bytes.toBytes(metaKey));
+ }
+
+ /** Read a metadata key from "metadata" column.
+ * @param metaKey Key to search in metadata column
+ * @return Value in byte array form or null if metadata doesn't exist
+ */
+ public byte[] getMeta(byte[] metaKey) {
+ return get(METADATA, metaKey);
+ }
+
+ public String getMetaAsString(String metaKey) {
+ final byte[] val = getMeta(metaKey);
+ return val == null ? null : Bytes.toString(val);
+ }
+
+ public void putMeta(String metaKey, byte[] val) {
+ putMeta(Bytes.toBytes(metaKey), val);
+ }
+
+ public void putMeta(byte[] metaKey, byte[] val) {
+ put(METADATA, metaKey, val);
+ }
+
+ public void deleteMeta(String metaKey) {
+ deleteMeta(Bytes.toBytes(metaKey));
+ }
+
+ public void deleteMeta(byte[] metaKey) {
+ delete(METADATA, metaKey);
+ }
+}
diff --git a/src/plugin/build.xml b/src/plugin/build.xml
index a301d61a0..eb0b0a999 100755
--- a/src/plugin/build.xml
+++ b/src/plugin/build.xml
@@ -26,17 +26,17 @@
<!-- Build & deploy all the plugin jars. -->
<!-- ====================================================== -->
<target name="deploy">
- <ant dir="clustering-carrot2" target="deploy"/>
+ <!--<ant dir="clustering-carrot2" target="deploy"/>
<ant dir="creativecommons" target="deploy"/>
- <ant dir="feed" target="deploy"/>
+ <ant dir="feed" target="deploy"/>-->
<ant dir="index-basic" target="deploy"/>
- <ant dir="index-anchor" target="deploy"/>
+ <!--<ant dir="index-anchor" target="deploy"/>
<ant dir="index-more" target="deploy"/>
<ant dir="field-basic" target="deploy"/>
<ant dir="field-boost" target="deploy"/>
- <ant dir="languageidentifier" target="deploy"/>
+ <ant dir="languageidentifier" target="deploy"/>-->
<ant dir="lib-http" target="deploy"/>
- <ant dir="lib-jakarta-poi" target="deploy"/>
+ <!--<ant dir="lib-jakarta-poi" target="deploy"/>
<ant dir="lib-lucene-analyzers" target="deploy"/>
<ant dir="lib-nekohtml" target="deploy"/>
<ant dir="lib-parsems" target="deploy"/>
@@ -46,36 +46,42 @@
<ant dir="nutch-extensionpoints" target="deploy"/>
<ant dir="ontology" target="deploy"/>
<ant dir="protocol-file" target="deploy"/>
- <ant dir="protocol-ftp" target="deploy"/>
+ <ant dir="protocol-ftp" target="deploy"/>-->
<ant dir="protocol-http" target="deploy"/>
- <ant dir="protocol-httpclient" target="deploy"/>
- <ant dir="parse-ext" target="deploy"/>
+ <!--<ant dir="protocol-httpclient" target="deploy"/>
+ <ant dir="parse-ext" target="deploy"/>-->
<ant dir="parse-html" target="deploy"/>
<ant dir="parse-js" target="deploy"/>
<!-- <ant dir="parse-mp3" target="deploy"/> -->
- <ant dir="parse-msexcel" target="deploy"/>
+ <!--<ant dir="parse-msexcel" target="deploy"/>
<ant dir="parse-mspowerpoint" target="deploy"/>
<ant dir="parse-msword" target="deploy"/>
<ant dir="parse-oo" target="deploy"/>
<ant dir="parse-pdf" target="deploy"/>
- <ant dir="parse-rss" target="deploy"/>
+ <ant dir="parse-rss" target="deploy"/>-->
<!-- <ant dir="parse-rtf" target="deploy"/> -->
- <ant dir="parse-swf" target="deploy"/>
+ <!--<ant dir="parse-swf" target="deploy"/>
<ant dir="parse-text" target="deploy"/>
<ant dir="parse-zip" target="deploy"/>
+ -->
<ant dir="query-basic" target="deploy"/>
<ant dir="query-more" target="deploy"/>
<ant dir="query-site" target="deploy"/>
- <ant dir="query-custom" target="deploy"/>
+ <!--<ant dir="query-custom" target="deploy"/>-->
<ant dir="query-url" target="deploy"/>
+ <!--
<ant dir="response-json" target="deploy"/>
<ant dir="response-xml" target="deploy"/>
+ -->
<ant dir="scoring-opic" target="deploy"/>
+ <!--
<ant dir="scoring-link" target="deploy"/>
+ -->
<ant dir="summary-basic" target="deploy"/>
- <ant dir="subcollection" target="deploy"/>
<ant dir="summary-lucene" target="deploy"/>
- <ant dir="tld" target="deploy"/>
+ <!--
+ <ant dir="subcollection" target="deploy"/>
+ <ant dir="tld" target="deploy"/>-->
<ant dir="urlfilter-automaton" target="deploy"/>
<ant dir="urlfilter-domain" target="deploy" />
<ant dir="urlfilter-prefix" target="deploy"/>
@@ -133,6 +139,7 @@
<ant dir="creativecommons" target="clean"/>
<ant dir="feed" target="clean"/>
<ant dir="index-basic" target="clean"/>
+ <ant dir="index-basichbase" target="clean"/>
<ant dir="index-anchor" target="clean"/>
<ant dir="index-more" target="clean"/>
<ant dir="field-basic" target="clean"/>
@@ -140,6 +147,7 @@
<ant dir="languageidentifier" target="clean"/>
<ant dir="lib-commons-httpclient" target="clean"/>
<ant dir="lib-http" target="clean"/>
+ <ant dir="lib-httphbase" target="clean"/>
<ant dir="lib-jakarta-poi" target="clean"/>
<ant dir="lib-lucene-analyzers" target="clean"/>
<ant dir="lib-nekohtml" target="clean"/>
@@ -152,10 +160,13 @@
<ant dir="protocol-file" target="clean"/>
<ant dir="protocol-ftp" target="clean"/>
<ant dir="protocol-http" target="clean"/>
+ <ant dir="protocol-httphbase" target="clean"/>
<ant dir="protocol-httpclient" target="clean"/>
<ant dir="parse-ext" target="clean"/>
<ant dir="parse-html" target="clean"/>
+ <ant dir="parse-htmlhbase" target="clean"/>
<ant dir="parse-js" target="clean"/>
+ <ant dir="parse-jshbase" target="clean"/>
<ant dir="parse-mp3" target="clean"/>
<ant dir="parse-msexcel" target="clean"/>
<ant dir="parse-mspowerpoint" target="clean"/>
diff --git a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java
index fa5a68a6f..d49a0c5d8 100644
--- a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java
+++ b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java
@@ -22,20 +22,21 @@ import org.apache.commons.logging.LogFactory;
import org.apache.lucene.document.DateTools;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.parse.Parse;
-
-import org.apache.nutch.indexer.IndexingFilter;
+import org.apache.nutch.crawl.Inlink;
import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.lucene.LuceneWriter;
-import org.apache.hadoop.io.Text;
-
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Inlinks;
+import org.apache.nutch.metadata.Nutch;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.WebTableRow;
import java.net.MalformedURLException;
import java.net.URL;
+import java.util.Collection;
+import java.util.HashSet;
+
import org.apache.hadoop.conf.Configuration;
/** Adds basic searchable fields to a document. */
@@ -44,21 +45,30 @@ public class BasicIndexingFilter implements IndexingFilter {
private int MAX_TITLE_LENGTH;
private Configuration conf;
+
+ private static final Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.TITLE));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.TEXT));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.FETCH_TIME));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.INLINKS));
+ }
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
+ public NutchDocument filter(NutchDocument doc, String url, WebTableRow row)
throws IndexingException {
- Text reprUrl = (Text) datum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
- String reprUrlString = reprUrl != null ? reprUrl.toString() : null;
- String urlString = url.toString();
+ String reprUrl = null;
+ if (row.hasColumn(WebTableColumns.REPR_URL, null))
+ reprUrl = row.getReprUrl();
String host = null;
try {
URL u;
- if (reprUrlString != null) {
- u = new URL(reprUrlString);
+ if (reprUrl!= null) {
+ u = new URL(reprUrl);
} else {
- u = new URL(urlString);
+ u = new URL(url);
}
host = u.getHost();
} catch (MalformedURLException e) {
@@ -66,34 +76,48 @@ public class BasicIndexingFilter implements IndexingFilter {
}
if (host != null) {
+ // add host as un-stored, indexed and tokenized
doc.add("host", host);
+ // add site as un-stored, indexed and un-tokenized
doc.add("site", host);
}
- doc.add("url", reprUrlString == null ? urlString : reprUrlString);
- doc.add("content", parse.getText());
+ // url is both stored and indexed, so it's both searchable and returned
+ doc.add("url", reprUrl == null ? url : reprUrl);
+
+ if (reprUrl != null) {
+ // also store original url as both stored and indexes
+ doc.add("orig", url);
+ }
+
+ // content is indexed, so that it's searchable, but not stored in index
+ doc.add("content", row.getText());
// title
- String title = parse.getData().getTitle();
+ String title = row.getTitle();
if (title.length() > MAX_TITLE_LENGTH) { // truncate title if needed
title = title.substring(0, MAX_TITLE_LENGTH);
}
+ // add title indexed and stored so that it can be displayed
doc.add("title", title);
-
// add cached content/summary display policy, if available
- String caching = parse.getData().getMeta(Nutch.CACHING_FORBIDDEN_KEY);
- if (caching != null && !caching.equals(Nutch.CACHING_FORBIDDEN_NONE)) {
+ String caching = row.getMetaAsString(Nutch.CACHING_FORBIDDEN_KEY);
+ if (caching != null && !caching.equals(Nutch.CACHING_FORBIDDEN_NONE)) {
doc.add("cache", caching);
}
// add timestamp when fetched, for deduplication
doc.add("tstamp",
- DateTools.timeToString(datum.getFetchTime(),
- DateTools.Resolution.MILLISECOND));
-
+ DateTools.timeToString(row.getFetchTime(), DateTools.Resolution.MILLISECOND));
+
+ // TODO: move anchors to its own plugin
+ for (Inlink inlink : row.getInlinks()) {
+ doc.add("anchor", inlink.getAnchor());
+ }
+
return doc;
}
-
+
public void addIndexBackendOptions(Configuration conf) {
///////////////////////////
@@ -137,4 +161,8 @@ public class BasicIndexingFilter implements IndexingFilter {
return this.conf;
}
+ public Collection<HbaseColumn> getColumns() {
+ return COLUMNS;
+ }
+
}
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java
index 6ef07254f..e1afbaa9f 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java
@@ -17,6 +17,7 @@
package org.apache.nutch.protocol.http.api;
+@SuppressWarnings("serial")
public class BlockedException extends HttpException {
public BlockedException(String msg) {
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
index 9f513eab5..60c772783 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
@@ -29,7 +29,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// Nutch imports
-import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
@@ -38,12 +37,14 @@ import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.protocol.RobotRules;
import org.apache.nutch.util.GZIPUtils;
-import org.apache.nutch.util.DeflateUtils;
import org.apache.nutch.util.LogUtil;
+import org.apache.nutch.util.MimeUtil;
+import org.apache.nutch.util.hbase.TableUtil;
+import org.apache.nutch.util.hbase.WebTableRow;
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
+import org.apache.hadoop.hbase.util.Bytes;
/**
* @author J&eacute;r&ocirc;me Charron
@@ -100,18 +101,20 @@ public abstract class HttpBase implements Protocol {
* a request finishes. This way only one thread at a time accesses a
* host.
*/
- private static HashMap BLOCKED_ADDR_TO_TIME = new HashMap();
+ private static HashMap<String, Long> BLOCKED_ADDR_TO_TIME =
+ new HashMap<String, Long>();
/**
* Maps a host to the number of threads accessing that host.
*/
- private static HashMap THREADS_PER_HOST_COUNT = new HashMap();
+ private static HashMap<String, Integer> THREADS_PER_HOST_COUNT =
+ new HashMap<String, Integer>();
/**
* Queue of blocked hosts. This contains all of the non-zero entries
* from BLOCKED_ADDR_TO_TIME, ordered by increasing time.
*/
- private static LinkedList BLOCKED_ADDR_QUEUE = new LinkedList();
+ private static LinkedList<String> BLOCKED_ADDR_QUEUE = new LinkedList<String>();
/** The default logger */
private final static Log LOGGER = LogFactory.getLog(HttpBase.class);
@@ -124,6 +127,8 @@ public abstract class HttpBase implements Protocol {
/** Do we block by IP addresses or by hostnames? */
private boolean byIP = true;
+
+ private MimeUtil mimeTypes;
/** Do we use HTTP/1.1? */
protected boolean useHttp11 = false;
@@ -166,6 +171,7 @@ public abstract class HttpBase implements Protocol {
this.maxCrawlDelay = (long)(conf.getInt("fetcher.max.crawl.delay", -1) * 1000);
// backward-compatible default setting
this.byIP = conf.getBoolean("fetcher.threads.per.host.by.ip", true);
+ this.mimeTypes = new MimeUtil(conf);
this.useHttp11 = conf.getBoolean("http.useHttp11", false);
this.robots.setConf(conf);
this.checkBlocking = conf.getBoolean(Protocol.CHECK_BLOCKING, true);
@@ -180,11 +186,10 @@ public abstract class HttpBase implements Protocol {
- public ProtocolOutput getProtocolOutput(Text url, CrawlDatum datum) {
+ public ProtocolOutput getProtocolOutput(String url, WebTableRow row) {
- String urlString = url.toString();
try {
- URL u = new URL(urlString);
+ URL u = new URL(url);
if (checkRobots) {
try {
@@ -217,7 +222,7 @@ public abstract class HttpBase implements Protocol {
}
Response response;
try {
- response = getResponse(u, datum, false); // make a request
+ response = getResponse(u, row, false); // make a request
} finally {
if (checkBlocking) unblockAddr(host, delay);
}
@@ -227,7 +232,7 @@ public abstract class HttpBase implements Protocol {
Content c = new Content(u.toString(), u.toString(),
(content == null ? EMPTY_CONTENT : content),
response.getHeader("Content-Type"),
- response.getHeaders(), this.conf);
+ response.getHeaders(), mimeTypes);
if (code == 200) { // got a good response
return new ProtocolOutput(c); // return it
@@ -269,7 +274,7 @@ public abstract class HttpBase implements Protocol {
} else if (code == 401) { // requires authorization, but no valid auth provided.
if (logger.isTraceEnabled()) { logger.trace("401 Authentication Required"); }
return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.ACCESS_DENIED, "Authentication required: "
- + urlString));
+ + url));
} else if (code == 404) {
return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.NOTFOUND, u));
} else if (code == 410) { // permanently GONE
@@ -353,11 +358,11 @@ public abstract class HttpBase implements Protocol {
Long time;
synchronized (BLOCKED_ADDR_TO_TIME) {
- time = (Long) BLOCKED_ADDR_TO_TIME.get(host);
+ time = BLOCKED_ADDR_TO_TIME.get(host);
if (time == null) { // address is free
// get # of threads already accessing this addr
- Integer counter = (Integer)THREADS_PER_HOST_COUNT.get(host);
+ Integer counter = THREADS_PER_HOST_COUNT.get(host);
int count = (counter == null) ? 0 : counter.intValue();
count++; // increment & store
@@ -392,7 +397,7 @@ public abstract class HttpBase implements Protocol {
private void unblockAddr(String host, long crawlDelay) {
synchronized (BLOCKED_ADDR_TO_TIME) {
- int addrCount = ((Integer)THREADS_PER_HOST_COUNT.get(host)).intValue();
+ int addrCount = THREADS_PER_HOST_COUNT.get(host).intValue();
if (addrCount == 1) {
THREADS_PER_HOST_COUNT.remove(host);
BLOCKED_ADDR_QUEUE.addFirst(host);
@@ -407,8 +412,8 @@ public abstract class HttpBase implements Protocol {
private static void cleanExpiredServerBlocks() {
synchronized (BLOCKED_ADDR_TO_TIME) {
for (int i = BLOCKED_ADDR_QUEUE.size() - 1; i >= 0; i--) {
- String host = (String) BLOCKED_ADDR_QUEUE.get(i);
- long time = ((Long) BLOCKED_ADDR_TO_TIME.get(host)).longValue();
+ String host = BLOCKED_ADDR_QUEUE.get(i);
+ long time = BLOCKED_ADDR_TO_TIME.get(host).longValue();
if (time <= System.currentTimeMillis()) {
BLOCKED_ADDR_TO_TIME.remove(host);
BLOCKED_ADDR_QUEUE.remove(i);
@@ -499,25 +504,9 @@ public abstract class HttpBase implements Protocol {
}
return content;
}
-
- public byte[] processDeflateEncoded(byte[] compressed, URL url) throws IOException {
-
- if (LOGGER.isTraceEnabled()) { LOGGER.trace("inflating...."); }
-
- byte[] content = DeflateUtils.inflateBestEffort(compressed, getMaxContent());
-
- if (content == null)
- throw new IOException("inflateBestEffort returned null");
-
- if (LOGGER.isTraceEnabled()) {
- LOGGER.trace("fetched " + compressed.length
- + " bytes of compressed content (expanded to "
- + content.length + " bytes) from " + url);
- }
- return content;
- }
-
+
protected static void main(HttpBase http, String[] args) throws Exception {
+ @SuppressWarnings("unused")
boolean verbose = false;
String url = null;
@@ -544,7 +533,7 @@ public abstract class HttpBase implements Protocol {
// LOGGER.setLevel(Level.FINE);
// }
- ProtocolOutput out = http.getProtocolOutput(new Text(url), new CrawlDatum());
+ ProtocolOutput out = http.getProtocolOutput(url, new WebTableRow(Bytes.toBytes(TableUtil.reverseUrl(url))));
Content content = out.getContent();
System.out.println("Status: " + out.getStatus());
@@ -561,11 +550,12 @@ public abstract class HttpBase implements Protocol {
protected abstract Response getResponse(URL url,
- CrawlDatum datum,
+ WebTableRow row,
boolean followRedirects)
throws ProtocolException, IOException;
- public RobotRules getRobotRules(Text url, CrawlDatum datum) {
+ @Override
+ public RobotRules getRobotRules(String url, WebTableRow row) {
return robots.getRobotRulesSet(this, url);
}
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
index 8f652f117..626b036a6 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
@@ -19,8 +19,8 @@ package org.apache.nutch.protocol.http.api;
// JDK imports
import java.io.FileInputStream;
import java.io.FileReader;
-import java.io.LineNumberReader;
import java.io.IOException;
+import java.io.LineNumberReader;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
@@ -28,17 +28,14 @@ import java.util.HashMap;
import java.util.Hashtable;
import java.util.StringTokenizer;
-// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-// Nutch imports
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configurable;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.protocol.RobotRules;
+import org.apache.nutch.util.hbase.WebTableRow;
/**
@@ -223,6 +220,9 @@ public class RobotRulesParser implements Configurable {
// Grab the agent names we advertise to robots files.
//
String agentName = conf.get("http.agent.name");
+ if (null == agentName) {
+ throw new RuntimeException("Agent name not configured!");
+ }
String agentNames = conf.get("http.robots.agents");
StringTokenizer tok = new StringTokenizer(agentNames, ",");
ArrayList agents = new ArrayList();
@@ -230,6 +230,23 @@ public class RobotRulesParser implements Configurable {
agents.add(tok.nextToken().trim());
}
+ //
+ // If there are no agents for robots-parsing, use our
+ // default agent-string. If both are present, our agent-string
+ // should be the first one we advertise to robots-parsing.
+ //
+ if (agents.size() == 0) {
+ agents.add(agentName);
+ if (LOG.isFatalEnabled()) {
+ LOG.fatal("No agents listed in 'http.robots.agents' property!");
+ }
+ } else if (!((String)agents.get(0)).equalsIgnoreCase(agentName)) {
+ agents.add(0, agentName);
+ if (LOG.isFatalEnabled()) {
+ LOG.fatal("Agent we advertise (" + agentName
+ + ") not listed first in 'http.robots.agents' property!");
+ }
+ }
setRobotNames((String[]) agents.toArray(new String[agents.size()]));
}
@@ -415,10 +432,10 @@ public class RobotRulesParser implements Configurable {
return rules;
}
- public RobotRuleSet getRobotRulesSet(HttpBase http, Text url) {
+ public RobotRuleSet getRobotRulesSet(HttpBase http, String url) {
URL u = null;
try {
- u = new URL(url.toString());
+ u = new URL(url);
} catch (Exception e) {
return EMPTY_RULES;
}
@@ -437,7 +454,7 @@ public class RobotRulesParser implements Configurable {
if (LOG.isTraceEnabled()) { LOG.trace("cache miss " + url); }
try {
Response response = http.getResponse(new URL(url, "/robots.txt"),
- new CrawlDatum(), true);
+ new WebTableRow(), true);
if (response.getCode() == 200) // found rules: parse them
robotRules = parseRules(response.getContent());
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
index 2778d3926..e5b652759 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
@@ -58,7 +58,7 @@ public class DOMBuilder
public DocumentFragment m_docFrag = null;
/** Vector of element nodes */
- protected Stack m_elemStack = new Stack();
+ protected Stack<Element> m_elemStack = new Stack<Element>();
/**
* DOMBuilder instance constructor... it will add the DOM nodes
@@ -347,7 +347,7 @@ public class DOMBuilder
throws org.xml.sax.SAXException
{
m_elemStack.pop();
- m_currentNode = m_elemStack.isEmpty() ? null : (Node)m_elemStack.peek();
+ m_currentNode = m_elemStack.isEmpty() ? null : m_elemStack.peek();
}
/**
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
index 55870dafa..56ae989bc 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
@@ -22,7 +22,6 @@ import java.net.MalformedURLException;
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Stack;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.util.NodeWalker;
@@ -55,8 +54,7 @@ public class DOMContentUtils {
}
}
- private HashMap linkParams = new HashMap();
- private Configuration conf;
+ private HashMap<String, LinkParams> linkParams = new HashMap<String, LinkParams>();
public DOMContentUtils(Configuration conf) {
setConf(conf);
@@ -66,7 +64,6 @@ public class DOMContentUtils {
// forceTags is used to override configurable tag ignoring, later on
Collection<String> forceTags = new ArrayList<String>(1);
- this.conf = conf;
linkParams.clear();
linkParams.put("a", new LinkParams("a", "href", 1));
linkParams.put("area", new LinkParams("area", "href", 0));
@@ -90,9 +87,9 @@ public class DOMContentUtils {
}
/**
- * This method takes a {@link StringBuffer} and a DOM {@link Node},
+ * This method takes a {@link StringBuilder} and a DOM {@link Node},
* and will append all the content text found beneath the DOM node to
- * the <code>StringBuffer</code>.
+ * the <code>StringBuilder</code>.
*
* <p>
*
@@ -104,7 +101,7 @@ public class DOMContentUtils {
*
* @return true if nested anchors were found
*/
- public boolean getText(StringBuffer sb, Node node,
+ public boolean getText(StringBuilder sb, Node node,
boolean abortOnNestedAnchors) {
if (getTextHelper(sb, node, abortOnNestedAnchors, 0)) {
return true;
@@ -118,13 +115,13 @@ public class DOMContentUtils {
* #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
*
*/
- public void getText(StringBuffer sb, Node node) {
+ public void getText(StringBuilder sb, Node node) {
getText(sb, node, false);
}
// returns true if abortOnNestedAnchors is true and we find nested
// anchors
- private boolean getTextHelper(StringBuffer sb, Node node,
+ private boolean getTextHelper(StringBuilder sb, Node node,
boolean abortOnNestedAnchors,
int anchorDepth) {
boolean abort = false;
@@ -174,7 +171,7 @@ public class DOMContentUtils {
*
* @return true if a title node was found, false otherwise
*/
- public boolean getTitle(StringBuffer sb, Node node) {
+ public boolean getTitle(StringBuilder sb, Node node) {
NodeWalker walker = new NodeWalker(node);
@@ -358,7 +355,7 @@ public class DOMContentUtils {
* nodes (this is a common DOM-fixup artifact, at least with
* nekohtml).
*/
- public void getOutlinks(URL base, ArrayList outlinks,
+ public void getOutlinks(URL base, ArrayList<Outlink> outlinks,
Node node) {
NodeWalker walker = new NodeWalker(node);
@@ -373,11 +370,11 @@ public class DOMContentUtils {
if (nodeType == Node.ELEMENT_NODE) {
nodeName = nodeName.toLowerCase();
- LinkParams params = (LinkParams)linkParams.get(nodeName);
+ LinkParams params = linkParams.get(nodeName);
if (params != null) {
if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {
- StringBuffer linkText = new StringBuffer();
+ StringBuilder linkText = new StringBuilder();
getText(linkText, currentNode, true);
NamedNodeMap attrs = currentNode.getAttributes();
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
index eb841a57e..59d889fa1 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
@@ -17,29 +17,48 @@
package org.apache.nutch.parse.html;
-import java.util.ArrayList;
-import java.util.Map;
-import java.net.URL;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
+import java.net.URL;
import java.nio.charset.Charset;
-import java.io.*;
-import java.util.regex.*;
-
-import org.cyberneko.html.parsers.*;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.w3c.dom.*;
-import org.apache.html.dom.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.html.dom.HTMLDocumentImpl;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.protocol.Content;
-import org.apache.hadoop.conf.*;
-import org.apache.nutch.parse.*;
-import org.apache.nutch.util.*;
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.parse.HtmlParseFilters;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.parse.Parser;
+import org.apache.nutch.util.EncodingDetector;
+import org.apache.nutch.util.LogUtil;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.TableUtil;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.cyberneko.html.parsers.DOMFragmentParser;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.DocumentFragment;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
public class HtmlParser implements Parser {
public static final Log LOG = LogFactory.getLog("org.apache.nutch.parse.html");
@@ -55,6 +74,12 @@ public class HtmlParser implements Parser {
Pattern.compile("charset=\\s*([a-z][_\\-0-9a-z]*)",
Pattern.CASE_INSENSITIVE);
+ private static Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.BASE_URL));
+ }
+
private String parserImpl;
/**
@@ -110,15 +135,16 @@ public class HtmlParser implements Parser {
private HtmlParseFilters htmlParseFilters;
private String cachingPolicy;
-
- public ParseResult getParse(Content content) {
+
+ public Parse getParse(String url, WebTableRow row) {
HTMLMetaTags metaTags = new HTMLMetaTags();
+ String baseUrl = row.getBaseUrl();
URL base;
try {
- base = new URL(content.getBaseUrl());
+ base = new URL(baseUrl);
} catch (MalformedURLException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e).getEmptyParseHbase(getConf());
}
String text = "";
@@ -129,13 +155,13 @@ public class HtmlParser implements Parser {
// parse the content
DocumentFragment root;
try {
- byte[] contentInOctets = content.getContent();
+ byte[] contentInOctets = row.getContent();
InputSource input = new InputSource(new ByteArrayInputStream(contentInOctets));
EncodingDetector detector = new EncodingDetector(conf);
- detector.autoDetectClues(content, true);
+ detector.autoDetectClues(row, true);
detector.addClue(sniffCharacterEncoding(contentInOctets), "sniffed");
- String encoding = detector.guessEncoding(content, defaultCharEncoding);
+ String encoding = detector.guessEncoding(row, defaultCharEncoding);
metadata.set(Metadata.ORIGINAL_CHAR_ENCODING, encoding);
metadata.set(Metadata.CHAR_ENCODING_FOR_CONVERSION, encoding);
@@ -144,14 +170,14 @@ public class HtmlParser implements Parser {
if (LOG.isTraceEnabled()) { LOG.trace("Parsing..."); }
root = parse(input);
} catch (IOException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e).getEmptyParseHbase(getConf());
} catch (DOMException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e).getEmptyParseHbase(getConf());
} catch (SAXException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e).getEmptyParseHbase(getConf());
} catch (Exception e) {
e.printStackTrace(LogUtil.getWarnStream(LOG));
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e).getEmptyParseHbase(getConf());
}
// get meta directives
@@ -161,7 +187,7 @@ public class HtmlParser implements Parser {
}
// check meta directives
if (!metaTags.getNoIndex()) { // okay to index
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
if (LOG.isTraceEnabled()) { LOG.trace("Getting text..."); }
utils.getText(sb, root); // extract text
text = sb.toString();
@@ -178,7 +204,7 @@ public class HtmlParser implements Parser {
utils.getOutlinks(baseTag!=null?baseTag:base, l, root);
outlinks = l.toArray(new Outlink[l.size()]);
if (LOG.isTraceEnabled()) {
- LOG.trace("found "+outlinks.length+" outlinks in "+content.getUrl());
+ LOG.trace("found "+outlinks.length+" outlinks in "+ url);
}
}
@@ -188,20 +214,15 @@ public class HtmlParser implements Parser {
status.setArgs(new String[] {metaTags.getRefreshHref().toString(),
Integer.toString(metaTags.getRefreshTime())});
}
- ParseData parseData = new ParseData(status, title, outlinks,
- content.getMetadata(), metadata);
- ParseResult parseResult = ParseResult.createParseResult(content.getUrl(),
- new ParseImpl(text, parseData));
-
- // run filters on parse
- ParseResult filteredParse = this.htmlParseFilters.filter(content, parseResult,
- metaTags, root);
+
+ Parse parse = new Parse(text, title, outlinks, status);
+ parse = htmlParseFilters.filter(url, row, parse, metaTags, root);
+
if (metaTags.getNoCache()) { // not okay to cache
- for (Map.Entry<org.apache.hadoop.io.Text, Parse> entry : filteredParse)
- entry.getValue().getData().getParseMeta().set(Nutch.CACHING_FORBIDDEN_KEY,
- cachingPolicy);
+ row.putMeta(Nutch.CACHING_FORBIDDEN_KEY, Bytes.toBytes(cachingPolicy));
}
- return filteredParse;
+
+ return parse;
}
private DocumentFragment parse(InputSource input) throws Exception {
@@ -260,6 +281,25 @@ public class HtmlParser implements Parser {
} catch (Exception x) { x.printStackTrace(LogUtil.getWarnStream(LOG));};
return res;
}
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ this.htmlParseFilters = new HtmlParseFilters(getConf());
+ this.parserImpl = getConf().get("parser.html.impl", "neko");
+ this.defaultCharEncoding = getConf().get(
+ "parser.character.encoding.default", "windows-1252");
+ this.utils = new DOMContentUtils(conf);
+ this.cachingPolicy = getConf().get("parser.caching.forbidden.policy",
+ Nutch.CACHING_FORBIDDEN_CONTENT);
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ public Collection<HbaseColumn> getColumns() {
+ return COLUMNS;
+ }
public static void main(String[] args) throws Exception {
//LOG.setLevel(Level.FINE);
@@ -272,26 +312,15 @@ public class HtmlParser implements Parser {
Configuration conf = NutchConfiguration.create();
HtmlParser parser = new HtmlParser();
parser.setConf(conf);
- Parse parse = parser.getParse(
- new Content(url, url, bytes, "text/html", new Metadata(), conf)).get(url);
- System.out.println("data: "+parse.getData());
-
+ WebTableRow row = new WebTableRow(Bytes.toBytes(TableUtil.reverseUrl(url)));
+ row.setBaseUrl(url);
+ row.setContent(bytes);
+ row.setContentType("text/html");
+ Parse parse = parser.getParse(url, row);
+ System.out.println("title: "+parse.getTitle());
System.out.println("text: "+parse.getText());
+ System.out.println("outlinks: " + Arrays.toString(parse.getOutlinks()));
}
- public void setConf(Configuration conf) {
- this.conf = conf;
- this.htmlParseFilters = new HtmlParseFilters(getConf());
- this.parserImpl = getConf().get("parser.html.impl", "neko");
- this.defaultCharEncoding = getConf().get(
- "parser.character.encoding.default", "windows-1252");
- this.utils = new DOMContentUtils(conf);
- this.cachingPolicy = getConf().get("parser.caching.forbidden.policy",
- Nutch.CACHING_FORBIDDEN_CONTENT);
- }
-
- public Configuration getConf() {
- return this.conf;
- }
}
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
index 4ecc5f069..6b16a0bdf 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
@@ -24,7 +24,6 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.NutchConfiguration;
import java.io.ByteArrayInputStream;
-import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
@@ -238,64 +237,60 @@ public class TestDOMContentUtils extends TestCase {
}
testDOMs[i]= node;
}
- try {
- answerOutlinks = new Outlink[][]{
- {
- new Outlink("http://www.nutch.org", "anchor"),
- },
- {
- new Outlink("http://www.nutch.org/", "home"),
- new Outlink("http://www.nutch.org/docs/bot.html", "bots"),
- },
- {
- new Outlink("http://www.nutch.org/", "separate this"),
- new Outlink("http://www.nutch.org/docs/ok", "from this"),
- },
- {
- new Outlink("http://www.nutch.org/", "home"),
- new Outlink("http://www.nutch.org/docs/1", "1"),
- new Outlink("http://www.nutch.org/docs/2", "2"),
- },
- {
- new Outlink("http://www.nutch.org/frames/top.html", ""),
- new Outlink("http://www.nutch.org/frames/left.html", ""),
- new Outlink("http://www.nutch.org/frames/invalid.html", ""),
- new Outlink("http://www.nutch.org/frames/right.html", ""),
- },
- {
- new Outlink("http://www.nutch.org/maps/logo.gif", ""),
- new Outlink("http://www.nutch.org/index.html", ""),
- new Outlink("http://www.nutch.org/maps/#bottom", ""),
- new Outlink("http://www.nutch.org/bot.html", ""),
- new Outlink("http://www.nutch.org/docs/index.html", ""),
- },
- {
- new Outlink("http://www.nutch.org/index.html", "whitespace test"),
- },
- {
- },
- {
- new Outlink("http://www.nutch.org/dummy.jsp", "test2"),
- },
- {
- },
- {
- new Outlink("http://www.nutch.org/;x", "anchor1"),
- new Outlink("http://www.nutch.org/g;x", "anchor2"),
- new Outlink("http://www.nutch.org/g;x?y#s", "anchor3")
- },
- {
- new Outlink("http://www.nutch.org/g;something", "anchor1"),
- new Outlink("http://www.nutch.org/g;something?y#s", "anchor2"),
- new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
- new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
- new Outlink("http://www.nutch.org/?y=1;somethingelse", "anchor5")
- }
- };
-
- } catch (MalformedURLException e) {
-
- }
+ answerOutlinks = new Outlink[][]{
+ {
+ new Outlink("http://www.nutch.org", "anchor"),
+ },
+ {
+ new Outlink("http://www.nutch.org/", "home"),
+ new Outlink("http://www.nutch.org/docs/bot.html", "bots"),
+ },
+ {
+ new Outlink("http://www.nutch.org/", "separate this"),
+ new Outlink("http://www.nutch.org/docs/ok", "from this"),
+ },
+ {
+ new Outlink("http://www.nutch.org/", "home"),
+ new Outlink("http://www.nutch.org/docs/1", "1"),
+ new Outlink("http://www.nutch.org/docs/2", "2"),
+ },
+ {
+ new Outlink("http://www.nutch.org/frames/top.html", ""),
+ new Outlink("http://www.nutch.org/frames/left.html", ""),
+ new Outlink("http://www.nutch.org/frames/invalid.html", ""),
+ new Outlink("http://www.nutch.org/frames/right.html", ""),
+ },
+ {
+ new Outlink("http://www.nutch.org/maps/logo.gif", ""),
+ new Outlink("http://www.nutch.org/index.html", ""),
+ new Outlink("http://www.nutch.org/maps/#bottom", ""),
+ new Outlink("http://www.nutch.org/bot.html", ""),
+ new Outlink("http://www.nutch.org/docs/index.html", ""),
+ },
+ {
+ new Outlink("http://www.nutch.org/index.html", "whitespace test"),
+ },
+ {
+ },
+ {
+ new Outlink("http://www.nutch.org/dummy.jsp", "test2"),
+ },
+ {
+ },
+ {
+ new Outlink("http://www.nutch.org/;x", "anchor1"),
+ new Outlink("http://www.nutch.org/g;x", "anchor2"),
+ new Outlink("http://www.nutch.org/g;x?y#s", "anchor3")
+ },
+ {
+ new Outlink("http://www.nutch.org/g;something", "anchor1"),
+ new Outlink("http://www.nutch.org/g;something?y#s", "anchor2"),
+ new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
+ new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
+ new Outlink("http://www.nutch.org/?y=1;somethingelse", "anchor5")
+ }
+ };
+
}
private static boolean equalsIgnoreWhitespace(String s1, String s2) {
@@ -317,7 +312,7 @@ public class TestDOMContentUtils extends TestCase {
if (testDOMs[0] == null)
setup();
for (int i= 0; i < testPages.length; i++) {
- StringBuffer sb= new StringBuffer();
+ StringBuilder sb= new StringBuilder();
utils.getText(sb, testDOMs[i]);
String text= sb.toString();
assertTrue("expecting text: " + answerText[i]
@@ -332,7 +327,7 @@ public class TestDOMContentUtils extends TestCase {
if (testDOMs[0] == null)
setup();
for (int i= 0; i < testPages.length; i++) {
- StringBuffer sb= new StringBuffer();
+ StringBuilder sb= new StringBuilder();
utils.getTitle(sb, testDOMs[i]);
String text= sb.toString();
assertTrue("expecting text: " + answerText[i]
@@ -347,7 +342,7 @@ public class TestDOMContentUtils extends TestCase {
if (testDOMs[0] == null)
setup();
for (int i= 0; i < testPages.length; i++) {
- ArrayList outlinks= new ArrayList();
+ ArrayList<Outlink> outlinks= new ArrayList<Outlink>();
if (i == SKIP) {
conf.setBoolean("parser.html.form.use_action", false);
utils.setConf(conf);
@@ -357,7 +352,7 @@ public class TestDOMContentUtils extends TestCase {
}
utils.getOutlinks(testBaseHrefURLs[i], outlinks, testDOMs[i]);
Outlink[] outlinkArr= new Outlink[outlinks.size()];
- outlinkArr= (Outlink[]) outlinks.toArray(outlinkArr);
+ outlinkArr= outlinks.toArray(outlinkArr);
compareOutlinks(answerOutlinks[i], outlinkArr);
}
}
diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
index 9df3cefc4..f3bbe4885 100644
--- a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
@@ -24,6 +24,7 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -33,16 +34,14 @@ import org.apache.nutch.parse.HTMLMetaTags;
import org.apache.nutch.parse.HtmlParseFilter;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.parse.ParseImpl;
-import org.apache.nutch.parse.ParseResult;
-import org.apache.nutch.parse.ParseText;
import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.plugin.Pluggable;
import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableRow;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
@@ -71,36 +70,30 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
private Configuration conf;
- public ParseResult filter(Content content, ParseResult parseResult,
+ @Override
+ public Parse filter(String url, WebTableRow row, Parse parse,
HTMLMetaTags metaTags, DocumentFragment doc) {
- Parse parse = parseResult.get(content.getUrl());
-
- String url = content.getBaseUrl();
- ArrayList outlinks = new ArrayList();
+ ArrayList<Outlink> outlinks = new ArrayList<Outlink>();
walk(doc, parse, metaTags, url, outlinks);
if (outlinks.size() > 0) {
- Outlink[] old = parse.getData().getOutlinks();
- String title = parse.getData().getTitle();
- List list = Arrays.asList(old);
+ Outlink[] old = parse.getOutlinks();
+ String title = parse.getTitle();
+ List<Outlink> list = Arrays.asList(old);
outlinks.addAll(list);
- ParseStatus status = parse.getData().getStatus();
+ ParseStatus status = parse.getParseStatus();
String text = parse.getText();
- Outlink[] newlinks = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]);
- ParseData parseData = new ParseData(status, title, newlinks,
- parse.getData().getContentMeta(),
- parse.getData().getParseMeta());
-
- // replace original parse obj with new one
- parseResult.put(content.getUrl(), new ParseText(text), parseData);
+ Outlink[] newlinks = outlinks.toArray(new Outlink[outlinks.size()]);
+ return new Parse(text, title, newlinks, status);
}
- return parseResult;
+ return parse;
}
- private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List outlinks) {
+ private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List<Outlink> outlinks) {
if (n instanceof Element) {
String name = n.getNodeName();
if (name.equalsIgnoreCase("script")) {
+ @SuppressWarnings("unused")
String lang = null;
Node lNode = n.getAttributes().getNamedItem("language");
if (lNode == null) lang = "javascript";
@@ -149,13 +142,14 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
}
}
- public ParseResult getParse(Content c) {
- String type = c.getContentType();
+ @Override
+ public Parse getParse(String url, WebTableRow row) {
+ String type = row.getContentType();
if (type != null && !type.trim().equals("") && !type.toLowerCase().startsWith("application/x-javascript"))
return new ParseStatus(ParseStatus.FAILED_INVALID_FORMAT,
- "Content not JavaScript: '" + type + "'").getEmptyParseResult(c.getUrl(), getConf());
- String script = new String(c.getContent());
- Outlink[] outlinks = getJSLinks(script, "", c.getUrl());
+ "Content not JavaScript: '" + type + "'").getEmptyParseHbase(getConf());
+ String script = new String(row.getContent());
+ Outlink[] outlinks = getJSLinks(script, "", url);
if (outlinks == null) outlinks = new Outlink[0];
// Title? use the first line of the script...
String title;
@@ -167,9 +161,9 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
idx = Math.min(MAX_TITLE_LEN, script.length());
title = script.substring(0, idx);
}
- ParseData pd = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks,
- c.getMetadata());
- return ParseResult.createParseResult(c.getUrl(), new ParseImpl(script, pd));
+ Parse parse =
+ new Parse(script, title, outlinks, ParseStatus.STATUS_SUCCESS);
+ return parse;
}
private static final String STRING_PATTERN = "(\\\\*(?:\"|\'))([^\\s\"\']+?)(?:\\1)";
@@ -183,7 +177,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
*/
private Outlink[] getJSLinks(String plainText, String anchor, String base) {
- final List outlinks = new ArrayList();
+ final List<Outlink> outlinks = new ArrayList<Outlink>();
URL baseURL = null;
try {
@@ -248,7 +242,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
//create array of the Outlinks
if (outlinks != null && outlinks.size() > 0) {
- retval = (Outlink[]) outlinks.toArray(new Outlink[0]);
+ retval = outlinks.toArray(new Outlink[0]);
} else {
retval = new Outlink[0];
}
@@ -281,4 +275,9 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
public Configuration getConf() {
return this.conf;
}
+
+ public Collection<HbaseColumn> getColumns() {
+ return EMPTY_COLUMNS;
+ }
+
}
diff --git a/src/plugin/parse-oo/src/java/org/apache/nutch/parse/oo/OOParser.java b/src/plugin/parse-oo/src/java/org/apache/nutch/parse/oo/OOParser.java
index 25e126bfb..0e5cd5e9b 100644
--- a/src/plugin/parse-oo/src/java/org/apache/nutch/parse/oo/OOParser.java
+++ b/src/plugin/parse-oo/src/java/org/apache/nutch/parse/oo/OOParser.java
@@ -144,12 +144,8 @@ public class OOParser implements Parser {
}
String u = el.getAttributeValue("href", xlink);
if (u == null) u = a; // often anchors are URLs
- try {
- Outlink o = new Outlink(u, a);
- outlinks.add(o);
- } catch (MalformedURLException mue) {
- // skip
- }
+ Outlink o = new Outlink(u, a);
+ outlinks.add(o);
if (a != null && !a.equals("")) {
if (!lastp) res.append(' ');
res.append(a);
diff --git a/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java b/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java
index 39d35f7c6..11e3f2099 100644
--- a/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java
+++ b/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java
@@ -126,23 +126,16 @@ public class RSSParser implements Parser {
indexText.append(" ");
if (r.getLink() != null) {
- try {
// get the outlink
if (r.getDescription()!= null ) {
theOutlinks.add(new Outlink(r.getLink(), r.getDescription()));
} else {
theOutlinks.add(new Outlink(r.getLink(), ""));
}
- } catch (MalformedURLException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("MalformedURL: " + r.getLink());
- LOG.warn("Attempting to continue processing outlinks");
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- }
- continue;
- }
}
+
+
// now get the descriptions of all the underlying RSS Items and
// then index them too
for (int j = 0; j < r.getItems().size(); j++) {
@@ -158,20 +151,12 @@ public class RSSParser implements Parser {
whichLink = theRSSItem.getLink();
if (whichLink != null) {
- try {
if (theRSSItem.getDescription()!=null) {
theOutlinks.add(new Outlink(whichLink, theRSSItem.getDescription()));
} else {
theOutlinks.add(new Outlink(whichLink, ""));
}
- } catch (MalformedURLException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("MalformedURL: " + whichLink);
- LOG.warn("Attempting to continue processing outlinks");
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- }
- continue;
- }
+
}
}
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
index fe7fbfca7..a4b675492 100755
--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
@@ -19,27 +19,31 @@ package org.apache.nutch.protocol.http;
// JDK imports
import java.io.IOException;
import java.net.URL;
+import java.util.Collection;
+import java.util.HashSet;
-// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
-// Hadoop imports
import org.apache.hadoop.conf.Configuration;
-
-// Nutch imports
-import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.protocol.http.api.HttpBase;
import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.WebTableRow;
public class Http extends HttpBase {
public static final Log LOG = LogFactory.getLog(Http.class);
-
+ private static final Collection<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.MODIFIED_TIME));
+ }
+
public Http() {
super(LOG);
}
@@ -59,9 +63,14 @@ public class Http extends HttpBase {
main(http, args);
}
- protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)
+ @Override
+ protected Response getResponse(URL url, WebTableRow row, boolean redirect)
throws ProtocolException, IOException {
- return new HttpResponse(this, url, datum);
+ return new HttpResponse(this, url, row);
+ }
+
+ public Collection<HbaseColumn> getColumns() {
+ return COLUMNS;
}
}
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
index 9e70d4613..1f7854d92 100644
--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
@@ -28,8 +28,6 @@ import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
-// Nutch imports
-import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.metadata.SpellCheckedMetadata;
import org.apache.nutch.net.protocols.HttpDateFormat;
@@ -38,6 +36,8 @@ import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.protocol.http.api.HttpBase;
import org.apache.nutch.protocol.http.api.HttpException;
import org.apache.nutch.util.LogUtil;
+import org.apache.nutch.util.hbase.WebTableColumns;
+import org.apache.nutch.util.hbase.WebTableRow;
/** An HTTP response. */
@@ -45,20 +45,16 @@ public class HttpResponse implements Response {
private HttpBase http;
private URL url;
- private String orig;
- private String base;
private byte[] content;
private int code;
private Metadata headers = new SpellCheckedMetadata();
- public HttpResponse(HttpBase http, URL url, CrawlDatum datum)
+ public HttpResponse(HttpBase http, URL url, WebTableRow row)
throws ProtocolException, IOException {
this.http = http;
this.url = url;
- this.orig = url.toString();
- this.base = url.toString();
if (!"http".equals(url.getProtocol()))
throw new HttpException("Not an HTTP url:" + url);
@@ -113,7 +109,7 @@ public class HttpResponse implements Response {
reqStr.append(portString);
reqStr.append("\r\n");
- reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");
+ reqStr.append("Accept-Encoding: x-gzip, gzip\r\n");
String userAgent = http.getUserAgent();
if ((userAgent == null) || (userAgent.length() == 0)) {
@@ -125,8 +121,9 @@ public class HttpResponse implements Response {
}
reqStr.append("\r\n");
- if (datum.getModifiedTime() > 0) {
- reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(datum.getModifiedTime()));
+ if (row.hasColumn(WebTableColumns.MODIFIED_TIME, null)) {
+ reqStr.append("If-Modified-Since: " +
+ HttpDateFormat.toString(row.getModifiedTime()));
reqStr.append("\r\n");
}
@@ -156,13 +153,17 @@ public class HttpResponse implements Response {
String contentEncoding = getHeader(Response.CONTENT_ENCODING);
if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
content = http.processGzipEncoded(content, url);
- } else if ("deflate".equals(contentEncoding)) {
- content = http.processDeflateEncoded(content, url);
} else {
if (Http.LOG.isTraceEnabled()) {
Http.LOG.trace("fetched " + content.length + " bytes from " + url);
}
}
+
+ // add headers in metadata to row
+ row.deleteHeaders();
+ for (String key : headers.names()) {
+ row.addHeader(key, headers.get(key));
+ }
} finally {
if (socket != null)
@@ -231,84 +232,6 @@ public class HttpResponse implements Response {
content = out.toByteArray();
}
- private void readChunkedContent(PushbackInputStream in,
- StringBuffer line)
- throws HttpException, IOException {
- boolean doneChunks= false;
- int contentBytesRead= 0;
- byte[] bytes = new byte[Http.BUFFER_SIZE];
- ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);
-
- while (!doneChunks) {
- if (Http.LOG.isTraceEnabled()) {
- Http.LOG.trace("Http: starting chunk");
- }
-
- readLine(in, line, false);
-
- String chunkLenStr;
- // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line + "'"); }
-
- int pos= line.indexOf(";");
- if (pos < 0) {
- chunkLenStr= line.toString();
- } else {
- chunkLenStr= line.substring(0, pos);
- // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " + line.substring(pos+1)); }
- }
- chunkLenStr= chunkLenStr.trim();
- int chunkLen;
- try {
- chunkLen= Integer.parseInt(chunkLenStr, 16);
- } catch (NumberFormatException e){
- throw new HttpException("bad chunk length: "+line.toString());
- }
-
- if (chunkLen == 0) {
- doneChunks= true;
- break;
- }
-
- if ( (contentBytesRead + chunkLen) > http.getMaxContent() )
- chunkLen= http.getMaxContent() - contentBytesRead;
-
- // read one chunk
- int chunkBytesRead= 0;
- while (chunkBytesRead < chunkLen) {
-
- int toRead= (chunkLen - chunkBytesRead) < Http.BUFFER_SIZE ?
- (chunkLen - chunkBytesRead) : Http.BUFFER_SIZE;
- int len= in.read(bytes, 0, toRead);
-
- if (len == -1)
- throw new HttpException("chunk eof after " + contentBytesRead
- + " bytes in successful chunks"
- + " and " + chunkBytesRead
- + " in current chunk");
-
- // DANGER!!! Will printed GZIPed stuff right to your
- // terminal!
- // if (LOG.isTraceEnabled()) { LOG.trace("read: " + new String(bytes, 0, len)); }
-
- out.write(bytes, 0, len);
- chunkBytesRead+= len;
- }
-
- readLine(in, line, false);
-
- }
-
- if (!doneChunks) {
- if (contentBytesRead != http.getMaxContent())
- throw new HttpException("chunk eof: !doneChunk && didn't max out");
- return;
- }
-
- content = out.toByteArray();
- parseHeaders(in, line);
-
- }
-
private int parseStatusLine(PushbackInputStream in, StringBuffer line)
throws IOException, HttpException {
readLine(in, line, false);
diff --git a/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java b/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java
index 30d244d29..5f19ef52d 100644
--- a/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java
+++ b/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java
@@ -20,25 +20,23 @@ package org.apache.nutch.scoring.opic;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
+import java.util.HashSet;
import java.util.List;
-import java.util.Map.Entry;
+import java.util.Set;
-// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
+import org.apache.hadoop.hbase.util.Bytes;
import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.NutchDocument;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.protocol.Content;
+import org.apache.nutch.scoring.ScoreDatum;
import org.apache.nutch.scoring.ScoringFilter;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.util.LogUtil;
+import org.apache.nutch.util.hbase.HbaseColumn;
+import org.apache.nutch.util.hbase.WebTableRow;
+import org.apache.nutch.util.hbase.WebTableColumns;
/**
* This plugin implements a variant of an Online Page Importance Computation
@@ -53,12 +51,22 @@ import org.apache.nutch.util.LogUtil;
public class OPICScoringFilter implements ScoringFilter {
private final static Log LOG = LogFactory.getLog(OPICScoringFilter.class);
+
+ private final static byte[] CASH_KEY = Bytes.toBytes("_csh_");
+
+ private final static Set<HbaseColumn> COLUMNS = new HashSet<HbaseColumn>();
+
+ static {
+ COLUMNS.add(new HbaseColumn(WebTableColumns.METADATA, CASH_KEY));
+ COLUMNS.add(new HbaseColumn(WebTableColumns.SCORE, CASH_KEY));
+ }
private Configuration conf;
private float scoreInjected;
private float scorePower;
private float internalScoreFactor;
private float externalScoreFactor;
+ @SuppressWarnings("unused")
private boolean countFiltered;
public Configuration getConf() {
@@ -75,88 +83,79 @@ public class OPICScoringFilter implements ScoringFilter {
}
/** Set to the value defined in config, 1.0f by default. */
- public void injectedScore(Text url, CrawlDatum datum) throws ScoringFilterException {
- datum.setScore(scoreInjected);
+ @Override
+ public void injectedScore(String url, WebTableRow row)
+ throws ScoringFilterException {
+ row.setScore(scoreInjected);
+ row.putMeta(CASH_KEY, Bytes.toBytes(scoreInjected));
}
/** Set to 0.0f (unknown value) - inlink contributions will bring it to
* a correct level. Newly discovered pages have at least one inlink. */
- public void initialScore(Text url, CrawlDatum datum) throws ScoringFilterException {
- datum.setScore(0.0f);
+ @Override
+ public void initialScore(String url, WebTableRow row) throws ScoringFilterException {
+ row.setScore(0.0f);
+ row.putMeta(CASH_KEY, Bytes.toBytes(0.0f));
}
/** Use {@link CrawlDatum#getScore()}. */
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort) throws ScoringFilterException {
- return datum.getScore() * initSort;
+ @Override
+ public float generatorSortValue(String url, WebTableRow row, float initSort) throws ScoringFilterException {
+ return row.getScore() * initSort;
}
/** Increase the score by a sum of inlinked scores. */
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum, List inlinked) throws ScoringFilterException {
+ @Override
+ public void updateScore(String url, WebTableRow row, List<ScoreDatum> inlinkedScoreData) {
float adjust = 0.0f;
- for (int i = 0; i < inlinked.size(); i++) {
- CrawlDatum linked = (CrawlDatum)inlinked.get(i);
- adjust += linked.getScore();
+ for (ScoreDatum scoreDatum : inlinkedScoreData) {
+ adjust += scoreDatum.getScore();
}
- if (old == null) old = datum;
- datum.setScore(old.getScore() + adjust);
- }
-
- /** Store a float value of CrawlDatum.getScore() under Fetcher.SCORE_KEY. */
- public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content) {
- content.getMetadata().set(Nutch.SCORE_KEY, "" + datum.getScore());
+ float oldScore = row.getScore();
+ row.setScore(oldScore + adjust);
+ float cash = Bytes.toFloat(row.getMeta(CASH_KEY));
+ row.putMeta(CASH_KEY, Bytes.toBytes(cash + adjust));
}
- /** Copy the value from Content metadata under Fetcher.SCORE_KEY to parseData. */
- public void passScoreAfterParsing(Text url, Content content, Parse parse) {
- parse.getData().getContentMeta().set(Nutch.SCORE_KEY, content.getMetadata().get(Nutch.SCORE_KEY));
- }
-
- /** Get a float value from Fetcher.SCORE_KEY, divide it by the number of outlinks and apply. */
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust, int allCount) throws ScoringFilterException {
- float score = scoreInjected;
- String scoreString = parseData.getContentMeta().get(Nutch.SCORE_KEY);
- if (scoreString != null) {
- try {
- score = Float.parseFloat(scoreString);
- } catch (Exception e) {
- e.printStackTrace(LogUtil.getWarnStream(LOG));
- }
- }
- int validCount = targets.size();
- if (countFiltered) {
- score /= allCount;
- } else {
- if (validCount == 0) {
- // no outlinks to distribute score, so just return adjust
- return adjust;
- }
- score /= validCount;
+ /** Get cash on hand, divide it by the number of outlinks and apply. */
+ @Override
+ public void distributeScoreToOutlinks(String fromUrl,
+ WebTableRow row, Collection<ScoreDatum> scoreData,
+ int allCount) {
+ float cash = Bytes.toFloat(row.getMeta(CASH_KEY));
+ if (cash == 0) {
+ return;
}
+ // TODO: count filtered vs. all count for outlinks
+ float scoreUnit = cash / allCount;
// internal and external score factor
- float internalScore = score * internalScoreFactor;
- float externalScore = score * externalScoreFactor;
- for (Entry<Text, CrawlDatum> target : targets) {
+ float internalScore = scoreUnit * internalScoreFactor;
+ float externalScore = scoreUnit * externalScoreFactor;
+ for (ScoreDatum scoreDatum : scoreData) {
try {
- String toHost = new URL(target.getKey().toString()).getHost();
+ String toHost = new URL(scoreDatum.getUrl()).getHost();
String fromHost = new URL(fromUrl.toString()).getHost();
if(toHost.equalsIgnoreCase(fromHost)){
- target.getValue().setScore(internalScore);
+ scoreDatum.setScore(internalScore);
} else {
- target.getValue().setScore(externalScore);
+ scoreDatum.setScore(externalScore);
}
} catch (MalformedURLException e) {
e.printStackTrace(LogUtil.getWarnStream(LOG));
- target.getValue().setScore(externalScore);
+ scoreDatum.setScore(externalScore);
}
}
- // XXX (ab) no adjustment? I think this is contrary to the algorithm descr.
- // XXX in the paper, where page "loses" its score if it's distributed to
- // XXX linked pages...
- return adjust;
+ // reset cash to zero
+ row.putMeta(CASH_KEY, Bytes.toBytes(0.0f));
}
/** Dampen the boost value by scorePower.*/
- public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum, CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore) throws ScoringFilterException {
- return (float)Math.pow(dbDatum.getScore(), scorePower) * initScore;
+ public float indexerScore(String url, NutchDocument doc, WebTableRow row, float initScore) {
+ return (float)Math.pow(row.getScore(), scorePower) * initScore;
+ }
+
+ @Override
+ public Collection<HbaseColumn> getColumns() {
+ return COLUMNS;
}
}
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
deleted file mode 100644
index 4c490d012..000000000
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.TreeSet;
-import java.util.logging.Logger;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.util.NutchConfiguration;
-
-import junit.framework.TestCase;
-
-public class TestCrawlDbMerger extends TestCase {
- private static final Logger LOG = Logger.getLogger(CrawlDbMerger.class.getName());
-
- String url10 = "http://example.com/";
- String url11 = "http://example.com/foo";
- String url20 = "http://example.com/";
- String url21 = "http://example.com/bar";
- String[] urls_expected = new String[] {
- url10,
- url11,
- url21
- };
-
- TreeSet init1 = new TreeSet();
- TreeSet init2 = new TreeSet();
- HashMap expected = new HashMap();
- CrawlDatum cd1, cd2, cd3;
- Configuration conf;
- FileSystem fs;
- Path testDir;
- CrawlDbReader reader;
-
- public void setUp() throws Exception {
- init1.add(url10);
- init1.add(url11);
- init2.add(url20);
- init2.add(url21);
- long time = System.currentTimeMillis();
- cd1 = new CrawlDatum();
- cd1.setFetchInterval(1.0f);
- cd1.setFetchTime(time);
- cd1.getMetaData().put(new Text("name"), new Text("cd1"));
- cd1.getMetaData().put(new Text("cd1"), new Text("cd1"));
- cd2 = new CrawlDatum();
- cd2.setFetchInterval(1.0f);
- cd2.setFetchTime(time + 10000);
- cd2.getMetaData().put(new Text("name"), new Text("cd2"));
- cd3 = new CrawlDatum();
- cd3.setFetchInterval(1.0f);
- cd3.setFetchTime(time + 10000);
- cd3.getMetaData().putAll(cd1.getMetaData());
- cd3.getMetaData().putAll(cd2.getMetaData());
- expected.put(url10, cd3);
- expected.put(url11, cd1);
- expected.put(url21, cd2);
- conf = NutchConfiguration.create();
- fs = FileSystem.get(conf);
- testDir = new Path("test-crawldb-" +
- new java.util.Random().nextInt());
- fs.mkdirs(testDir);
- }
-
- public void tearDown() {
- try {
- if (fs.exists(testDir))
- fs.delete(testDir);
- } catch (Exception e) { }
- try {
- reader.close();
- } catch (Exception e) { }
- }
-
- public void testMerge() throws Exception {
- Path crawldb1 = new Path(testDir, "crawldb1");
- Path crawldb2 = new Path(testDir, "crawldb2");
- Path output = new Path(testDir, "output");
- createCrawlDb(conf, fs, crawldb1, init1, cd1);
- createCrawlDb(conf, fs, crawldb2, init2, cd2);
- CrawlDbMerger merger = new CrawlDbMerger(conf);
- LOG.fine("* merging crawldbs to " + output);
- merger.merge(output, new Path[]{crawldb1, crawldb2}, false, false);
- LOG.fine("* reading crawldb: " + output);
- reader = new CrawlDbReader();
- String crawlDb = output.toString();
- Iterator it = expected.keySet().iterator();
- while (it.hasNext()) {
- String url = (String)it.next();
- LOG.fine("url=" + url);
- CrawlDatum cd = (CrawlDatum)expected.get(url);
- CrawlDatum res = reader.get(crawlDb, url, conf);
- LOG.fine(" -> " + res);
- System.out.println("url=" + url);
- System.out.println(" cd " + cd);
- System.out.println(" res " + res);
- // may not be null
- assertNotNull(res);
- assertTrue(cd.equals(res));
- }
- reader.close();
- fs.delete(testDir);
- }
-
- private void createCrawlDb(Configuration config, FileSystem fs, Path crawldb, TreeSet init, CrawlDatum cd) throws Exception {
- LOG.fine("* creating crawldb: " + crawldb);
- Path dir = new Path(crawldb, CrawlDb.CURRENT_NAME);
- MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir, "part-00000").toString(), Text.class, CrawlDatum.class);
- Iterator it = init.iterator();
- while (it.hasNext()) {
- String key = (String)it.next();
- writer.append(new Text(key), cd);
- }
- writer.close();
- }
-}
diff --git a/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java b/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
deleted file mode 100644
index a8e1b49d2..000000000
--- a/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.crawl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.TreeMap;
-import java.util.logging.Logger;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.util.NutchConfiguration;
-
-import junit.framework.TestCase;
-
-public class TestLinkDbMerger extends TestCase {
- private static final Logger LOG = Logger.getLogger(TestLinkDbMerger.class.getName());
-
- String url10 = "http://example.com/foo";
- String[] urls10 = new String[] {
- "http://example.com/100",
- "http://example.com/101"
- };
-
- String url11 = "http://example.com/";
- String[] urls11 = new String[] {
- "http://example.com/110",
- "http://example.com/111"
- };
-
- String url20 = "http://example.com/";
- String[] urls20 = new String[] {
- "http://foo.com/200",
- "http://foo.com/201"
- };
- String url21 = "http://example.com/bar";
- String[] urls21 = new String[] {
- "http://foo.com/210",
- "http://foo.com/211"
- };
-
- String[] urls10_expected = urls10;
- String[] urls11_expected = new String[] {
- urls11[0],
- urls11[1],
- urls20[0],
- urls20[1]
- };
- String[] urls20_expected = urls11_expected;
- String[] urls21_expected = urls21;
-
- TreeMap init1 = new TreeMap();
- TreeMap init2 = new TreeMap();
- HashMap expected = new HashMap();
- Configuration conf;
- Path testDir;
- FileSystem fs;
- LinkDbReader reader;
-
- public void setUp() throws Exception {
- init1.put(url10, urls10);
- init1.put(url11, urls11);
- init2.put(url20, urls20);
- init2.put(url21, urls21);
- expected.put(url10, urls10_expected);
- expected.put(url11, urls11_expected);
- expected.put(url20, urls20_expected);
- expected.put(url21, urls21_expected);
- conf = NutchConfiguration.create();
- fs = FileSystem.get(conf);
- testDir = new Path("build/test/test-linkdb-" +
- new java.util.Random().nextInt());
- fs.mkdirs(testDir);
- }
-
- public void tearDown() {
- try {
- if (fs.exists(testDir))
- fs.delete(testDir, true);
- } catch (Exception e) { }
- try {
- reader.close();
- } catch (Exception e) { }
- }
-
- public void testMerge() throws Exception {
- Configuration conf = NutchConfiguration.create();
- FileSystem fs = FileSystem.get(conf);
- fs.mkdirs(testDir);
- Path linkdb1 = new Path(testDir, "linkdb1");
- Path linkdb2 = new Path(testDir, "linkdb2");
- Path output = new Path(testDir, "output");
- createLinkDb(conf, fs, linkdb1, init1);
- createLinkDb(conf, fs, linkdb2, init2);
- LinkDbMerger merger = new LinkDbMerger(conf);
- LOG.fine("* merging linkdbs to " + output);
- merger.merge(output, new Path[]{linkdb1, linkdb2}, false, false);
- LOG.fine("* reading linkdb: " + output);
- reader = new LinkDbReader(conf, output);
- Iterator it = expected.keySet().iterator();
- while (it.hasNext()) {
- String url = (String)it.next();
- LOG.fine("url=" + url);
- String[] vals = (String[])expected.get(url);
- Inlinks inlinks = reader.getInlinks(new Text(url));
- // may not be null
- assertNotNull(inlinks);
- ArrayList links = new ArrayList();
- Iterator it2 = inlinks.iterator();
- while (it2.hasNext()) {
- Inlink in = (Inlink)it2.next();
- links.add(in.getFromUrl());
- }
- for (int i = 0; i < vals.length; i++) {
- LOG.fine(" -> " + vals[i]);
- assertTrue(links.contains(vals[i]));
- }
- }
- reader.close();
- fs.delete(testDir, true);
- }
-
- private void createLinkDb(Configuration config, FileSystem fs, Path linkdb, TreeMap init) throws Exception {
- LOG.fine("* creating linkdb: " + linkdb);
- Path dir = new Path(linkdb, LinkDb.CURRENT_NAME);
- MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir, "part-00000").toString(), Text.class, Inlinks.class);
- Iterator it = init.keySet().iterator();
- while (it.hasNext()) {
- String key = (String)it.next();
- Inlinks inlinks = new Inlinks();
- String[] vals = (String[])init.get(key);
- for (int i = 0; i < vals.length; i++) {
- Inlink in = new Inlink(vals[i], vals[i]);
- inlinks.add(in);
- }
- writer.append(new Text(key), inlinks);
- }
- writer.close();
- }
-}
diff --git a/src/test/org/apache/nutch/util/TestTableUtil.java b/src/test/org/apache/nutch/util/TestTableUtil.java
new file mode 100644
index 000000000..40271d96a
--- /dev/null
+++ b/src/test/org/apache/nutch/util/TestTableUtil.java
@@ -0,0 +1,51 @@
+package org.apache.nutch.util;
+
+import org.apache.nutch.util.hbase.TableUtil;
+import junit.framework.TestCase;
+
+public class TestTableUtil extends TestCase {
+
+ String urlString1 = "http://foo.com/";
+ String urlString2 = "http://foo.com:8900/";
+ String urlString3 = "ftp://bar.baz.com/";
+ String urlString4 = "http://bar.baz.com:8983/to/index.html?a=b&c=d";
+ String urlString5 = "http://foo.com?a=/a/b&c=0";
+ String urlString5rev = "http://foo.com/?a=/a/b&c=0";
+ String urlString6 = "http://foo.com";
+
+ String reversedUrlString1 = "com.foo:http/";
+ String reversedUrlString2 = "com.foo:http:8900/";
+ String reversedUrlString3 = "com.baz.bar:ftp/";
+ String reversedUrlString4 = "com.baz.bar:http:8983/to/index.html?a=b&c=d";
+ String reversedUrlString5 = "com.foo:http/?a=/a/b&c=0";
+ String reversedUrlString6 = "com.foo:http";
+
+ public void testReverseUrl() throws Exception {
+ assertReverse(urlString1, reversedUrlString1);
+ assertReverse(urlString2, reversedUrlString2);
+ assertReverse(urlString3, reversedUrlString3);
+ assertReverse(urlString4, reversedUrlString4);
+ assertReverse(urlString5, reversedUrlString5);
+ assertReverse(urlString5, reversedUrlString5);
+ assertReverse(urlString6, reversedUrlString6);
+ }
+
+ public void testUnreverseUrl() throws Exception {
+ assertUnreverse(reversedUrlString1, urlString1);
+ assertUnreverse(reversedUrlString2, urlString2);
+ assertUnreverse(reversedUrlString3, urlString3);
+ assertUnreverse(reversedUrlString4, urlString4);
+ assertUnreverse(reversedUrlString5, urlString5rev);
+ assertUnreverse(reversedUrlString6, urlString6);
+ }
+
+ private static void assertReverse(String url, String expectedReversedUrl) throws Exception {
+ String reversed = TableUtil.reverseUrl(url);
+ assertEquals(reversed, expectedReversedUrl);
+ }
+
+ private static void assertUnreverse(String reversedUrl, String expectedUrl) {
+ String unreversed = TableUtil.unreverseUrl(reversedUrl);
+ assertEquals(unreversed, expectedUrl);
+ }
+}