Apache Nutch is an extensible and scalable web crawler
Merge mapred branch to trunk & remove it.
Douglass Cutting5943b9f1d6f1
diff --git a/bin/nutch b/bin/nutchindex 2a27e0cbc..5ba8902f9 100755--- a/bin/nutch+++ b/bin/nutch@@ -29,29 +29,25 @@ if [ $# = 0 ]; thenecho "Usage: nutch COMMAND"echo "where COMMAND is one of:"echo " crawl one-step crawler for intranets"+ echo " readdb read / dump crawl db"+ echo " readlinkdb read / dump link db"echo " admin database administration, including creation"echo " inject inject new urls into the database"echo " generate generate new segments to fetch"- echo " fetchlist print the fetchlist of a segment"echo " fetch fetch a segment's pages"echo " parse parse a segment's pages"- echo " index run the indexer on a segment's fetcher output"+ echo " updatedb update crawl db from segments after fetching"+ echo " invertlinks create a linkdb from parsed segments"+ echo " index run the indexer on parsed segments and linkdb"echo " merge merge several segment indexes"echo " dedup remove duplicates from a set of segment indexes"- echo " updatedb update db from segments after fetching"- echo " updatesegs update segments with link data from the db"- echo " mergesegs merge multiple segments into a single segment"- echo " readdb examine arbitrary fields of the database"- echo " analyze adjust database link-analysis scoring"- echo " prune prune segment index(es) of unwanted content"- echo " segread read, fix and dump segment data"- echo " segslice append, join and slice segment data"echo " server run a search server"echo " namenode run the NDFS namenode"echo " datanode run an NDFS datanode"echo " ndfs run an NDFS admin client"echo " jobtracker run the MapReduce job Tracker node"echo " tasktracker run a MapReduce task Tracker node"+ echo " job manipulate MapReduce jobs"echo " or"echo " CLASSNAME run the class named CLASSNAME"echo "Most commands print help when invoked w/o parameters."@@ -68,7 +64,7 @@ NUTCH_HOME=`cd "$THIS_DIR/.." ; pwd`# some Java parametersif [ "$NUTCH_JAVA_HOME" != "" ]; then- echo "run java in $NUTCH_JAVA_HOME"+ #echo "run java in $NUTCH_JAVA_HOME"JAVA_HOME=$NUTCH_JAVA_HOMEfi@@ -82,13 +78,14 @@ JAVA_HEAP_MAX=-Xmx1000m# check envvars which might override default argsif [ "$NUTCH_HEAPSIZE" != "" ]; then- echo "run with heapsize $NUTCH_HEAPSIZE"+ #echo "run with heapsize $NUTCH_HEAPSIZE"JAVA_HEAP_MAX="-Xmx""$NUTCH_HEAPSIZE""m"- echo $JAVA_HEAP_MAX+ #echo $JAVA_HEAP_MAXfi# CLASSPATH initially contains $NUTCH_CONF_DIR, or defaults to $NUTCH_HOME/confCLASSPATH=${NUTCH_CONF_DIR:=$NUTCH_HOME/conf}+CLASSPATH=${CLASSPATH}:$JAVA_HOME/lib/tools.jar# for developers, add Nutch classes to CLASSPATHif [ -d "$NUTCH_HOME/build/classes" ]; then@@ -119,7 +116,7 @@ for f in $NUTCH_HOME/lib/*.jar; doCLASSPATH=${CLASSPATH}:$f;done-for f in $NUTCH_HOME/lib/jettyext/*.jar; do+for f in $NUTCH_HOME/lib/jetty-ext/*.jar; doCLASSPATH=${CLASSPATH}:$f;done@@ -128,53 +125,43 @@ unset IFS# figure out which class to runif [ "$COMMAND" = "crawl" ] ; then- CLASS=org.apache.nutch.tools.CrawlTool-elif [ "$COMMAND" = "admin" ] ; then- CLASS=org.apache.nutch.tools.WebDBAdminTool+ CLASS=org.apache.nutch.crawl.Crawlelif [ "$COMMAND" = "inject" ] ; then- CLASS=org.apache.nutch.db.WebDBInjector+ CLASS=org.apache.nutch.crawl.Injectorelif [ "$COMMAND" = "generate" ] ; then- CLASS=org.apache.nutch.tools.FetchListTool-elif [ "$COMMAND" = "fetchlist" ] ; then- CLASS=org.apache.nutch.pagedb.FetchListEntry+ CLASS=org.apache.nutch.crawl.Generatorelif [ "$COMMAND" = "fetch" ] ; then- CLASS=org.apache.nutch.fetcher.Fetcher+ CLASS=org.apache.nutch.crawl.Fetcherelif [ "$COMMAND" = "parse" ] ; then- CLASS=org.apache.nutch.tools.ParseSegment+ CLASS=org.apache.nutch.crawl.ParseSegment+elif [ "$COMMAND" = "readdb" ] ; then+ CLASS=org.apache.nutch.crawl.CrawlDbReader+elif [ "$COMMAND" = "readlinkdb" ] ; then+ CLASS=org.apache.nutch.crawl.LinkDbReader+elif [ "$COMMAND" = "updatedb" ] ; then+ CLASS=org.apache.nutch.crawl.CrawlDb+elif [ "$COMMAND" = "invertlinks" ] ; then+ CLASS=org.apache.nutch.crawl.LinkDbelif [ "$COMMAND" = "index" ] ; then- CLASS=org.apache.nutch.indexer.IndexSegment+ CLASS=org.apache.nutch.crawl.Indexer+elif [ "$COMMAND" = "dedup" ] ; then+ CLASS=org.apache.nutch.crawl.DeleteDuplicateselif [ "$COMMAND" = "merge" ] ; thenCLASS=org.apache.nutch.indexer.IndexMerger-elif [ "$COMMAND" = "dedup" ] ; then- CLASS=org.apache.nutch.indexer.DeleteDuplicates-elif [ "$COMMAND" = "updatedb" ] ; then- CLASS=org.apache.nutch.tools.UpdateDatabaseTool-elif [ "$COMMAND" = "updatesegs" ] ; then- CLASS=org.apache.nutch.tools.UpdateSegmentsFromDb-elif [ "$COMMAND" = "mergesegs" ] ; then- CLASS=org.apache.nutch.tools.SegmentMergeTool-elif [ "$COMMAND" = "readdb" ] ; then- CLASS=org.apache.nutch.db.WebDBReader-elif [ "$COMMAND" = "prune" ] ; then- CLASS=org.apache.nutch.tools.PruneIndexTool-elif [ "$COMMAND" = "segread" ] ; then- CLASS=org.apache.nutch.segment.SegmentReader-elif [ "$COMMAND" = "segslice" ] ; then- CLASS=org.apache.nutch.segment.SegmentSlicer-elif [ "$COMMAND" = "analyze" ] ; then- CLASS=org.apache.nutch.tools.LinkAnalysisToolelif [ "$COMMAND" = "server" ] ; thenCLASS='org.apache.nutch.searcher.DistributedSearch$Server'elif [ "$COMMAND" = "namenode" ] ; then- CLASS='org.apache.nutch.ndfs.NDFS$NameNode'+ CLASS='org.apache.nutch.ndfs.NameNode'elif [ "$COMMAND" = "datanode" ] ; then- CLASS='org.apache.nutch.ndfs.NDFS$DataNode'+ CLASS='org.apache.nutch.ndfs.DataNode'elif [ "$COMMAND" = "ndfs" ] ; then- CLASS=org.apache.nutch.fs.TestClient+ CLASS=org.apache.nutch.fs.NDFSShellelif [ "$COMMAND" = "jobtracker" ] ; then- CLASS=org.apache.nutch.mapReduce.JobTracker+ CLASS=org.apache.nutch.mapred.JobTrackerelif [ "$COMMAND" = "tasktracker" ] ; then- CLASS=org.apache.nutch.mapReduce.TaskTracker+ CLASS=org.apache.nutch.mapred.TaskTracker+elif [ "$COMMAND" = "job" ] ; then+ CLASS=org.apache.nutch.mapred.JobClientelseCLASS=$COMMANDfidiff --git a/bin/nutch-daemon.sh b/bin/nutch-daemon.shindex 03e4559e6..a3d26e386 100755--- a/bin/nutch-daemon.sh+++ b/bin/nutch-daemon.sh@@ -5,19 +5,10 @@# Environment Variables## NUTCH_LOG_DIR Where log files are stored. PWD by default.-#--# resolve links - $0 may be a softlink-this="$0"-while [ -h "$this" ]; do- ls=`ls -ld "$this"`- link=`expr "$ls" : '.*-> \(.*\)$'`- if expr "$link" : '.*/.*' > /dev/null; then- this="$link"- else- this=`dirname "$this"`/"$link"- fi-done+# NUTCH_MASTER host:path where nutch code should be rsync'd from+# NUTCH_PID_DIR The pid files are stored. /tmp by default.+# NUTCH_IDENT_STRING A string representing this instance of nutch. $USER by default+##usage="Usage: nutch-daemon [start|stop] [nutch-command] [args...]"@@ -33,16 +24,34 @@ shiftcommand=$1shift-# some directories-this_dir=`dirname "$this"`+# resolve links - $0 may be a softlink+this="$0"+while [ -h "$this" ]; do+ ls=`ls -ld "$this"`+ link=`expr "$ls" : '.*-> \(.*\)$'`+ if expr "$link" : '.*/.*' > /dev/null; then+ this="$link"+ else+ this=`dirname "$this"`/"$link"+ fi+done+# get log directoryif [ "$NUTCH_LOG_DIR" = "" ]; then- NUTCH_LOG_DIR=.+ NUTCH_LOG_DIR=$PWD+fi++if [ "$NUTCH_PID_DIR" = "" ]; then+ NUTCH_PID_DIR=/tmp+fi++if [ "$NUTCH_IDENT_STRING" = "" ]; then+ NUTCH_IDENT_STRING=$USERfi# some variables-log=$NUTCH_LOG_DIR/nutch-$command-`hostname`.log-pid=/tmp/nutch-$command.pid+log=$NUTCH_LOG_DIR/nutch-$NUTCH_IDENT_STRING-$command-`hostname`.log+pid=$NUTCH_PID_DIR/nutch-$NUTCH_IDENT_STRING-$command.pidcase $startStop in@@ -55,8 +64,15 @@ case $startStop infifi+ root=`dirname $this`/..+ if [ "$NUTCH_MASTER" != "" ]; then+ echo rsync from $NUTCH_MASTER+ rsync -a --delete --exclude=.svn $NUTCH_MASTER/ $root+ fi++ cd $rootecho starting $command, logging to $log- $this_dir/nutch $command "$@" >& $log < /dev/null &+ nohup bin/nutch $command "$@" >& $log < /dev/null &echo $! > $pidsleep 1; head $log;;diff --git a/bin/nutch-daemons.sh b/bin/nutch-daemons.shnew file mode 100755index 000000000..ddb44eea6--- /dev/null+++ b/bin/nutch-daemons.sh@@ -0,0 +1,16 @@+#!/bin/bash+#+# Run a Nutch command on all slave hosts.++usage="Usage: nutch-daemons.sh [start|stop] command args..."++# if no args specified, show usage+if [ $# -le 1 ]; then+ echo $usage+ exit 1+fi++bin=`dirname $0`+bin=`cd $bin; pwd`++exec $bin/slaves.sh $bin/nutch-daemon.sh "$@"diff --git a/bin/slaves.sh b/bin/slaves.shnew file mode 100755index 000000000..c7dbf3c45--- /dev/null+++ b/bin/slaves.sh@@ -0,0 +1,27 @@+#!/bin/bash+#+# Run a shell command on all slave hosts.+#+# Environment Variables+#+# NUTCH_SLAVES File naming remote hosts. Default is ~/.slaves+##++usage="Usage: slaves.sh command..."++# if no args specified, show usage+if [ $# -le 0 ]; then+ echo $usage+ exit 1+fi++if [ "$NUTCH_SLAVES" = "" ]; then+ export NUTCH_SLAVES=$HOME/.slaves+fi++for slave in `cat $NUTCH_SLAVES`; do+ ssh -o ConnectTimeout=1 $slave "$@" \+ 2>&1 | sed "s/^/$slave: /" &+done++waitdiff --git a/bin/start-all.sh b/bin/start-all.shnew file mode 100755index 000000000..65aa44872--- /dev/null+++ b/bin/start-all.sh@@ -0,0 +1,11 @@+#!/bin/bash++# Start all nutch daemons. Run this on master node.++bin=`dirname $0`+bin=`cd $bin; pwd`++$bin/nutch-daemons.sh start datanode+$bin/nutch-daemon.sh start namenode+$bin/nutch-daemon.sh start jobtracker+$bin/nutch-daemons.sh start tasktrackerdiff --git a/bin/stop-all.sh b/bin/stop-all.shnew file mode 100755index 000000000..0bb51c0dc--- /dev/null+++ b/bin/stop-all.sh@@ -0,0 +1,11 @@+#!/bin/bash++# Stop all nutch daemons. Run this on master node.++bin=`dirname $0`+bin=`cd $bin; pwd`++$bin/nutch-daemon.sh stop jobtracker+$bin/nutch-daemons.sh stop tasktracker+$bin/nutch-daemon.sh stop namenode+$bin/nutch-daemons.sh stop datanodediff --git a/build.xml b/build.xmlindex b2e9d9437..06948bfb2 100644--- a/build.xml+++ b/build.xml@@ -38,6 +38,7 @@<target name="init"><mkdir dir="${build.dir}"/><mkdir dir="${build.classes}"/>+ <mkdir dir="${build.webapps}"/><mkdir dir="${test.build.dir}"/><mkdir dir="${test.build.classes}"/>@@ -46,6 +47,10 @@<fileset dir="${conf.dir}" includes="**/*.template"/></touch>+ <copy todir="${build.webapps}/jobtracker">+ <fileset dir="${src.webapps}/jobtracker"/>+ </copy>+<copy todir="${conf.dir}" verbose="true"><fileset dir="${conf.dir}" includes="**/*.template"/><mapper type="glob" from="*.template" to="*"/>@@ -57,7 +62,7 @@<!-- ====================================================== --><!-- Compile the Java files --><!-- ====================================================== -->- <target name="compile" depends="compile-core, compile-plugins, jar"/>+ <target name="compile" depends="compile-core, compile-plugins"/><target name="compile-core" depends="init"><javac@@ -65,9 +70,11 @@srcdir="${src.dir}"includes="org/apache/nutch/**/*.java"destdir="${build.classes}"- debug="${debug}"- optimize="${optimize}"- deprecation="${deprecation}">+ debug="${javac.debug}"+ optimize="${javac.optimize}"+ target="${javac.version}"+ source="${javac.version}"+ deprecation="${javac.deprecation}"><classpath refid="classpath"/></javac></target>@@ -102,12 +109,11 @@todir="${build.classes}"/><copy file="${conf.dir}/nutch-site.xml"todir="${build.classes}"/>- <jar- jarfile="${build.dir}/${final.name}.jar"- basedir="${build.classes}"- />-- <copy file="${build.dir}/${final.name}.jar" tofile="${basedir}/${name}.jar" />+ <jar jarfile="${build.dir}/${final.name}.jar"+ basedir="${build.classes}">+ <manifest>+ </manifest>+ </jar></target><!-- ================================================================== -->@@ -115,7 +121,7 @@<!-- ================================================================== --><!-- --><!-- ================================================================== -->- <target name="war" depends="compile,generate-docs">+ <target name="war" depends="jar,compile,generate-docs"><war destfile="${build.dir}/${final.name}.war"webxml="${web.src.dir}/web.xml"><fileset dir="${web.src.dir}/jsp"/>@@ -150,8 +156,11 @@srcdir="${test.src.dir}"includes="org/apache/nutch/**/*.java"destdir="${test.build.classes}"- debug="${debug}"- deprecation="${deprecation}">+ debug="${javac.debug}"+ optimize="${javac.optimize}"+ target="${javac.version}"+ source="${javac.version}"+ deprecation="${javac.deprecation}"><classpath refid="test.classpath"/></javac></target>@@ -435,7 +444,6 @@<!-- ================================================================== --><target name="clean"><delete dir="${build.dir}"/>- <delete failonerror="true" file="${name}.jar" /></target></project>diff --git a/conf/crawl-tool.xml b/conf/crawl-tool.xmlindex 8ee93b3dd..58080f981 100644--- a/conf/crawl-tool.xml+++ b/conf/crawl-tool.xml@@ -14,13 +14,6 @@<value>crawl-urlfilter.txt</value></property>-<property>- <name>indexer.boost.by.link.count</name>- <value>true</value>- <description>When true scores for a page are multipled by the log of- the number of incoming links to the page.</description>-</property>-<property><name>db.ignore.internal.links</name><value>false</value>@@ -40,7 +33,7 @@<property><name>http.max.delays</name>- <value>100</value>+ <value>1000</value><description>The number of times a thread will delay when trying tofetch a page. When using the crawl tool there are likely to be veryfew different hosts, so we need to be willing to wait longer fordiff --git a/conf/crawl-urlfilter.txt.template b/conf/crawl-urlfilter.txt.templateindex b4715f6d9..705bdb280 100644--- a/conf/crawl-urlfilter.txt.template+++ b/conf/crawl-urlfilter.txt.template@@ -12,11 +12,14 @@-^(file|ftp|mailto):# skip image and other suffixes we can't yet parse--\.(gif|GIF|jpg|JPG|ico|ICO|css|sit|eps|wmf|zip|ppt|mpg|xls|gz|rpm|tgz|mov|MOV|exe|png|PNG)$+-\.(gif|GIF|jpg|JPG|ico|ICO|css|sit|eps|wmf|zip|ppt|mpg|xls|gz|rpm|tgz|mov|MOV|exe|png)$# skip URLs containing certain characters as probable queries, etc.-[?*!@=]+# skip URLs with slash-delimited segment that repeats 3+ times, to break loops+-.*(/.+?)/.*?\1/.*?\1/+# accept hosts in MY.DOMAIN.NAME+^http://([a-z0-9]*\.)*MY.DOMAIN.NAME/diff --git a/conf/mapred-default.xml.template b/conf/mapred-default.xml.templatenew file mode 100644index 000000000..0606e0dd0--- /dev/null+++ b/conf/mapred-default.xml.template@@ -0,0 +1,8 @@+<?xml version="1.0"?>+<?xml-stylesheet type="text/xsl" href="nutch-conf.xsl"?>++<!-- Put mapred-specific property overrides in this file. -->++<nutch-conf>++</nutch-conf>diff --git a/conf/nutch-default.xml b/conf/nutch-default.xmlindex 79360bfbd..ec4ed122b 100644--- a/conf/nutch-default.xml+++ b/conf/nutch-default.xml@@ -69,7 +69,7 @@<property><name>http.max.delays</name>- <value>3</value>+ <value>100</value><description>The number of times a thread will delay when trying tofetch a page. Each time it finds that a host is busy, it will waitfetcher.server.delay. After http.max.delays attepts, it will give@@ -262,15 +262,13 @@recoverable errors is generated for fetch.</description></property>-<!-- fetchlist tool properties -->+<!-- generate properties --><property>- <name>fetchlist.score.by.link.count</name>- <value>true</value>- <description>If true, set page scores on fetchlist entries based on- log(number of anchors), instead of using original page scores. This- results in prioritization of pages with many incoming links.- </description>+ <name>generate.max.per.host</name>+ <value>-1</value>+ <description>The maximum number of urls per host in a single+ fetchlist. -1 if unlimited.</description></property><!-- fetcher properties -->@@ -303,18 +301,23 @@<description>If true, fetcher will log more verbosely.</description></property>-<!-- parser properties --><property>- <name>parser.threads.parse</name>- <value>10</value>- <description>Number of ParserThreads ParseSegment should use.</description>+ <name>fetcher.parse</name>+ <value>true</value>+ <description>If true, fetcher will parse content.</description>+</property>++<property>+ <name>fetcher.store.content</name>+ <value>true</value>+ <description>If true, fetcher will store content.</description></property><!-- i/o properties --><property><name>io.sort.factor</name>- <value>100</value>+ <value>10</value><description>The number of streams to merge at once while sortingfiles. This determines the number of open file handles.</description></property>@@ -329,13 +332,28 @@<property><name>io.file.buffer.size</name>- <value>131072</value>+ <value>4096</value><description>The size of buffer for use in sequence files.The size of this buffer should probably be a multiple of hardwarepage size (4096 on Intel x86), and it determines how much data isbuffered during read and write operations.</description></property>+<property>+ <name>io.bytes.per.checksum</name>+ <value>512</value>+ <description>The number of bytes per checksum. Must not be larger than+ io.file.buffer.size.</description>+</property>++<property>+ <name>io.skip.checksum.errors</name>+ <value>false</value>+ <description>If true, when a checksum error is encountered while+ reading a sequence file, entries are skipped, instead of throwing an+ exception.</description>+</property>+<!-- file system properties --><property>@@ -345,6 +363,14 @@literal string "local" or a host:port for NDFS.</description></property>+<property>+ <name>ndfs.datanode.port</name>+ <value>50010</value>+ <description>The port number that the ndfs datanode server uses as a starting+ point to look for a free port to listen on.+</description>+</property>+<property><name>ndfs.name.dir</name><value>/tmp/nutch/ndfs/name</value>@@ -356,23 +382,108 @@<name>ndfs.data.dir</name><value>/tmp/nutch/ndfs/data</value><description>Determines where on the local filesystem an NDFS data node- should store its blocks.</description>+ should store its blocks. If this is a comma- or space-delimited+ list of directories, then data will be stored in all named+ directories, typically on different devices.</description></property><!-- map/reduce properties --><property><name>mapred.job.tracker</name>- <value>localhost:8010</value>- <description>The host and port that the MapReduce job tracker runs at.+ <value>local</value>+ <description>The host and port that the MapReduce job tracker runs+ at. If "local", then jobs are run in-process as a single map+ and reduce task.+ </description>+</property>++<property>+ <name>mapred.job.tracker.info.port</name>+ <value>50030</value>+ <description>The port that the MapReduce job tracker info webserver runs at.+ </description>+</property>++<property>+ <name>mapred.task.tracker.output.port</name>+ <value>50040</value>+ <description>The port number that the MapReduce task tracker output server uses as a starting+ point to look for a free port to listen on.+ </description>+</property>++<property>+ <name>mapred.task.tracker.report.port</name>+ <value>50050</value>+ <description>The port number that the MapReduce task tracker report server uses as a starting+ point to look for a free port to listen on.</description></property><property><name>mapred.local.dir</name><value>/tmp/nutch/mapred/local</value>- <description>The local directory where MapReduce stores temprorary files- related to tasks and jobs.+ <description>The local directory where MapReduce stores intermediate+ data files. May be a space- or comma- separated list of+ directories on different devices in order to spread disk i/o.+ </description>+</property>++<property>+ <name>mapred.system.dir</name>+ <value>/tmp/nutch/mapred/system</value>+ <description>The shared directory where MapReduce stores control files.+ </description>+</property>++<property>+ <name>mapred.temp.dir</name>+ <value>/tmp/nutch/mapred/temp</value>+ <description>A shared directory for temporary files.+ </description>+</property>++<property>+ <name>mapred.map.tasks</name>+ <value>2</value>+ <description>The default number of map tasks per job. Typically set+ to a prime several times greater than number of available hosts.+ Ignored when mapred.job.tracker is "local".+ </description>+</property>++<property>+ <name>mapred.reduce.tasks</name>+ <value>1</value>+ <description>The default number of reduce tasks per job. Typically set+ to a prime close to the number of available hosts. Ignored when+ mapred.job.tracker is "local".+ </description>+</property>++<property>+ <name>mapred.task.timeout</name>+ <value>600000</value>+ <description>The number of milliseconds before a task will be+ terminated if it neither reads an input, writes an output, nor+ updates its status string.+ </description>+</property>++<property>+ <name>mapred.tasktracker.tasks.maximum</name>+ <value>2</value>+ <description>The maximum number of tasks that will be run+ simultaneously by a task tracker.+ </description>+</property>++<property>+ <name>mapred.job.tracker.info.port</name>+ <value>7845</value>+ <description>The port number where the jobtracker runs its+ administrative web interface.</description></property>@@ -389,13 +500,6 @@effect.</description></property>-<property>- <name>indexer.boost.by.link.count</name>- <value>true</value>- <description>When true scores for a page are multipled by the log of- the number of incoming links to the page.</description>-</property>-<property><name>indexer.max.title.length</name><value>100</value>@@ -444,12 +548,12 @@<property><name>indexer.maxMergeDocs</name>- <value>50</value>+ <value>2147483647</value><description>This number determines the maximum number of LuceneDocuments to be merged into a new Lucene segment. Larger values- increase indexing speed and reduce the number of Lucene segments,+ increase batch indexing speed and reduce the number of Lucene segments,which reduces the number of open file handles; however, this also- increases RAM usage during indexing.+ decreases incremental indexing performance.</description></property>@@ -477,9 +581,9 @@<property><name>searcher.dir</name>- <value>.</value>+ <value>crawl</value><description>- Path to root of index directories. This directory is searched (in+ Path to root of crawl. This directory is searched (inorder) for either the file search-servers.txt, containing a list ofdistributed search servers, or the directory "index" containingmerged indexes, or the directory "segments" containing segment@@ -571,8 +675,8 @@<property><name>ipc.client.timeout</name>- <value>10000</value>- <description>Defines the timeout for IPC calls in milliseconds. </description>+ <value>60000</value>+ <description>Defines the timeout for IPC calls in milliseconds.</description></property><!-- plugin properties -->diff --git a/conf/regex-urlfilter.txt.template b/conf/regex-urlfilter.txt.templateindex 9060b1d12..877892131 100644--- a/conf/regex-urlfilter.txt.template+++ b/conf/regex-urlfilter.txt.template@@ -15,5 +15,8 @@# skip URLs containing certain characters as probable queries, etc.-[?*!@=]+# skip URLs with slash-delimited segment that repeats 3+ times, to break loops+-.*(/.+?)/.*?\1/.*?\1/+# accept anything else+.diff --git a/default.properties b/default.propertiesindex 4ba0a12d4..631aeaa14 100644--- a/default.properties+++ b/default.properties@@ -15,6 +15,7 @@ xmlcatalog.dir = ${basedir}/src/xmlcatalogbuild.dir = ./buildbuild.classes = ${build.dir}/classes+build.webapps = ${build.dir}/webappsbuild.plugins = ${build.dir}/pluginsbuild.docs = ${build.dir}/docsbuild.javadoc = ${build.docs}/api@@ -29,6 +30,7 @@ test.build.javadoc = ${test.build.dir}/docs/apijavacc.home=/usr/java/javaccweb.src.dir = ./src/web+src.webapps = ./src/webappsjavadoc.link.java=http://java.sun.com/j2se/1.4.2/docs/api/javadoc.link.lucene=http://jakarta.apache.org/lucene/docs/api/@@ -36,9 +38,10 @@ javadoc.packages=org.apache.nutch.*dist.dir=${build.dir}/${final.name}-debug=on-optimize=on-deprecation=off+javac.debug=on+javac.optimize=on+javac.deprecation=off+javac.version= 1.4plugin.http=org.apache.nutch.protocol.http*plugin.httpclient=org.apache.nutch.protocol.httpclient*diff --git a/lib/jetty-5.1.2.jar b/lib/jetty-5.1.2.jardeleted file mode 100644index 712e66d04..000000000Binary files a/lib/jetty-5.1.2.jar and /dev/null differdiff --git a/lib/jetty-5.1.2.LICENSE.txt b/lib/jetty-5.1.4.LICENSE.txtsimilarity index 100%rename from lib/jetty-5.1.2.LICENSE.txtrename to lib/jetty-5.1.4.LICENSE.txtdiff --git a/lib/jetty-5.1.4.jar b/lib/jetty-5.1.4.jarnew file mode 100644index 000000000..dcbd99e5aBinary files /dev/null and b/lib/jetty-5.1.4.jar differdiff --git a/lib/jetty-ext/ant.jar b/lib/jetty-ext/ant.jarnew file mode 100644index 000000000..395544dc9Binary files /dev/null and b/lib/jetty-ext/ant.jar differdiff --git a/lib/jetty-ext/commons-el.jar b/lib/jetty-ext/commons-el.jarnew file mode 100644index 000000000..608ed796cBinary files /dev/null and b/lib/jetty-ext/commons-el.jar differdiff --git a/lib/jetty-ext/jasper-compiler.jar b/lib/jetty-ext/jasper-compiler.jarnew file mode 100644index 000000000..96ec53852Binary files /dev/null and b/lib/jetty-ext/jasper-compiler.jar differdiff --git a/lib/jetty-ext/jasper-runtime.jar b/lib/jetty-ext/jasper-runtime.jarnew file mode 100644index 000000000..5c3b4bfffBinary files /dev/null and b/lib/jetty-ext/jasper-runtime.jar differdiff --git a/lib/jetty-ext/jsp-api.jar b/lib/jetty-ext/jsp-api.jarnew file mode 100644index 000000000..93f89576fBinary files /dev/null and b/lib/jetty-ext/jsp-api.jar differdiff --git a/site/tutorial.html b/site/tutorial.htmlindex 0ca440385..c29087740 100644--- a/site/tutorial.html+++ b/site/tutorial.html@@ -276,11 +276,11 @@ around one million pages on a handful of web servers.</p><ol>-<li>Create a flat file of root urls. For example, to crawl the-<span class="codefrag">nutch</span> site you might start with a file named-<span class="codefrag">urls</span> containing just the Nutch home page. All other-Nutch pages should be reachable from this page. The <span class="codefrag">urls</span>-file would thus look like:+<li>Create a directory with a flat file of root urls. For example, to+crawl the <span class="codefrag">nutch</span> site you might start with a file named+<span class="codefrag">urls/nutch</span> containing the url of just the Nutch home+page. All other Nutch pages should be reachable from this page. The+<span class="codefrag">urls/nutch</span> file would thus contain:<pre class="code">http://lucene.apache.org/nutch/</pre>@@ -310,138 +310,152 @@ crawl command. Its options include:</p><span class="codefrag">-dir</span> <em>dir</em> names the directory to put the crawl in.</li><li>-<span class="codefrag">-depth</span> <em>depth</em> indicates the link depth from the root-page that should be crawled.</li>+<span class="codefrag">-threads</span> <em>threads</em> determines the number of+threads that will fetch in parallel.</li><li>-<span class="codefrag">-delay</span> <em>delay</em> determines the number of seconds-between accesses to each host.</li>+<span class="codefrag">-depth</span> <em>depth</em> indicates the link depth from the root+page that should be crawled.</li><li>-<span class="codefrag">-threads</span> <em>threads</em> determines the number of-threads that will fetch in parallel.</li>+<span class="codefrag">-topN</span> <em>N</em> determines the maximum number of pages that+will be retrieved at each level up to the depth.</li></ul><p>For example, a typical call might be:</p><pre class="code">-bin/nutch crawl urls -dir crawl.test -depth 3 >& crawl.log+bin/nutch crawl urls -dir crawl -depth 3 -topN 50</pre>-<p>Typically one starts testing one's configuration by crawling at low-depths, and watching the output to check that desired pages are found.-Once one is more confident of the configuration, then an appropriate-depth for a full crawl is around 10.</p>+<p>Typically one starts testing one's configuration by crawling at+shallow depths, sharply limiting the number of pages fetched at each+level (<span class="codefrag">-topN</span>), and watching the output to check that+desired pages are fetched and undesirable pages are not. Once one is+confident of the configuration, then an appropriate depth for a full+crawl is around 10. The number of pages per level+(<span class="codefrag">-topN</span>) for a full crawl can be from tens of thousands to+millions, depending on your resources.</p><p>Once crawling has completed, one can skip to the Searching sectionbelow.</p></div>-<a name="N100E4"></a><a name="Whole-web+Crawling"></a>+<a name="N100EA"></a><a name="Whole-web+Crawling"></a><h2 class="h3">Whole-web Crawling</h2><div class="section"><p>Whole-web crawling is designed to handle very large crawls which maytake weeks to complete, running on multiple machines.</p>-<a name="N100ED"></a><a name="Whole-web%3A+Concepts"></a>+<a name="N100F3"></a><a name="Whole-web%3A+Concepts"></a><h3 class="h4">Whole-web: Concepts</h3>-<p>Nutch data is of two types:</p>+<p>Nutch data is composed of:</p><ol>+-<li>The web database. This contains information about every-page known to Nutch, and about links between those pages.</li>+<li>The crawl database, or <em>crawldb</em>. This contains+information about every url known to Nutch, including whether it was+fetched, and, if so, when.</li>+-<li>A set of segments. Each segment is a set of pages that are-fetched and indexed as a unit. Segment data consists of the-following types:</li>+<li>The link database, or <em>linkdb</em>. This contains the list+of known links to each url, including both the source url and anchor+text of the link.</li>+++<li>A set of <em>segments</em>. Each segment is a set of urls that are+fetched as a unit. Segments are directories with the following+subdirectories:</li>+<li><ul>-<li>a <em>fetchlist</em> is a file-that names a set of pages to be fetched</li>+<li>a <em>crawl_generate</em> names a set of urls to be fetched</li>++<li>a <em>crawl_fetch</em> contains the status of fetching each url</li>++<li>a <em>content</em> contains the content of each url</li>-<li>the<em> fetcher output</em> is a-set of files containing the fetched pages</li>+<li>a <em>parse_text</em> contains the parsed text of each url</li>-<li>the <em>index </em>is a-Lucene-format index of the fetcher output.</li>+<li>a <em>parse_data</em> contains outlinks and metadata parsed+ from each url</li>++<li>a <em>crawl_parse</em> contains the outlink urls, used to+ update the crawldb</li></ul></li>++<li>The <em>indexes</em>are Lucene-format indexes.</li>++</ol>-<p>In the following examples we will keep our web database in a directory-named <span class="codefrag">db</span> and our segments-in a directory named <span class="codefrag">segments</span>:</p>-<pre class="code">mkdir db-mkdir segments</pre>-<a name="N10123"></a><a name="Whole-web%3A+Boostrapping+the+Web+Database"></a>+<a name="N10140"></a><a name="Whole-web%3A+Boostrapping+the+Web+Database"></a><h3 class="h4">Whole-web: Boostrapping the Web Database</h3>-<p>The admin tool is used to create a new, empty database:</p>-<pre class="code">bin/nutch admin db -create</pre>-<p>The <em>injector</em> adds urls into the database. Let's inject-URLs from the <a href="http://dmoz.org/">DMOZ</a> Open-Directory. First we must download and uncompress the file listing all-of the DMOZ pages. (This is a 200+Mb file, so this will take a few-minutes.)</p>+<p>The <em>injector</em> adds urls to the crawldb. Let's inject URLs+from the <a href="http://dmoz.org/">DMOZ</a> Open Directory. First we+must download and uncompress the file listing all of the DMOZ pages.+(This is a 200+Mb file, so this will take a few minutes.)</p><pre class="code">wget http://rdf.dmoz.org/rdf/content.rdf.u8.gzgunzip content.rdf.u8.gz</pre>-<p>Next we inject a random subset of these pages into the web database.+<p>Next we select a random subset of these pages.(We use a random subset so that everyone who runs this tutorialdoesn't hammer the same sites.) DMOZ contains around three million-URLs. We inject one out of every 3000, so that we end up with+URLs. We select one out of every 5000, so that we end up witharound 1000 URLs:</p>-<pre class="code">bin/nutch inject db -dmozfile content.rdf.u8 -subset 3000</pre>-<p>This also takes a few minutes, as it must parse the full file.</p>+<pre class="code">mkdir dmoz+bin/nutch org.apache.nutch.crawl.DmozParser content.rdf.u8 -subset 5000 > dmoz/urls</pre>+<p>The parser also takes a few minutes, as it must parse the full+file. Finally, we initialize the crawl db with the selected urls.</p>+<pre class="code">bin/nutch inject crawl/crawldb dmoz</pre><p>Now we have a web database with around 1000 as-yet unfetched URLs in it.</p>-<a name="N1014C"></a><a name="Whole-web%3A+Fetching"></a>+<a name="N10166"></a><a name="Whole-web%3A+Fetching"></a><h3 class="h4">Whole-web: Fetching</h3><p>To fetch, we first generate a fetchlist from the database:</p>-<pre class="code">bin/nutch generate db segments+<pre class="code">bin/nutch generate crawl/crawldb crawl/segments</pre><p>This generates a fetchlist for all of the pages due to be fetched.The fetchlist is placed in a newly created segment directory.The segment directory is named by the time it's created. Wesave the name of this segment in the shell variable <span class="codefrag">s1</span>:</p>-<pre class="code">s1=`ls -d segments/2* | tail -1`+<pre class="code">s1=`ls -d crawl/segments/2* | tail -1`echo $s1</pre><p>Now we run the fetcher on this segment with:</p><pre class="code">bin/nutch fetch $s1</pre><p>When this is complete, we update the database with the results of thefetch:</p>-<pre class="code">bin/nutch updatedb db $s1</pre>+<pre class="code">bin/nutch updatedb crawl/crawldb $s1</pre><p>Now the database has entries for all of the pages referenced by theinitial set.</p><p>Now we fetch a new segment with the top-scoring 1000 pages:</p>-<pre class="code">bin/nutch generate db segments -topN 1000-s2=`ls -d segments/2* | tail -1`+<pre class="code">bin/nutch generate crawl/crawldb crawl/segments -topN 1000+s2=`ls -d crawl/segments/2* | tail -1`echo $s2bin/nutch fetch $s2-bin/nutch updatedb db $s2+bin/nutch updatedb crawl/crawldb $s2</pre><p>Let's fetch one more round:</p><pre class="code">-bin/nutch generate db segments -topN 1000-s3=`ls -d segments/2* | tail -1`+bin/nutch generate crawl/crawldb crawl/segments -topN 1000+s3=`ls -d crawl/segments/2* | tail -1`echo $s3bin/nutch fetch $s3-bin/nutch updatedb db $s3+bin/nutch updatedb crawl/crawldb $s3</pre><p>By this point we've fetched a few thousand pages. Let's indexthem!</p>-<a name="N10186"></a><a name="Whole-web%3A+Indexing"></a>+<a name="N101A0"></a><a name="Whole-web%3A+Indexing"></a><h3 class="h4">Whole-web: Indexing</h3>-<p>To index each segment we use the <span class="codefrag">index</span>-command, as follows:</p>-<pre class="code">bin/nutch index $s1-bin/nutch index $s2-bin/nutch index $s3</pre>-<p>Then, before we can search a set of segments, we need to delete-duplicate pages. This is done with:</p>-<pre class="code">bin/nutch dedup segments dedup.tmp</pre>+<p>Before indexing we first invert all of the links, so that we may+index incoming anchor text with the pages.</p>+<pre class="code">bin/nutch invertlinks crawl/linkdb crawl/segments</pre>+<p>To index the segments we use the <span class="codefrag">index</span> command, as follows:</p>+<pre class="code">bin/nutch index indexes crawl/linkdb crawl/segments/*</pre><p>Now we're ready to search!</p>-<a name="N101A1"></a><a name="Searching"></a>+<a name="N101C1"></a><a name="Searching"></a><h3 class="h4">Searching</h3><p>To search you need to put the nutch war file into your servletcontainer. (If instead of downloading a Nutch release you checked the@@ -452,10 +466,8 @@ file may be installed with the commands:</p><pre class="code">rm -rf ~/local/tomcat/webapps/ROOT*cp nutch*.war ~/local/tomcat/webapps/ROOT.war</pre>-<p>The webapp finds its indexes in <span class="codefrag">./segments</span>, relative-to where you start Tomcat, so, if you've done intranet crawling,-connect to your crawl directory, or, if you've done whole-web-crawling, don't change directories, and give the command:</p>+<p>The webapp finds its indexes in <span class="codefrag">./crawl</span>, relative+to where you start Tomcat, so use a command like:</p><pre class="code">~/local/tomcat/bin/catalina.sh start</pre><p>Then visit <a href="http://localhost:8080/">http://localhost:8080/</a>diff --git a/site/tutorial.pdf b/site/tutorial.pdfindex 24d55bb15..8db92431e 100644--- a/site/tutorial.pdf+++ b/site/tutorial.pdf@@ -146,10 +146,10 @@ endobj>>endobj30 0 obj-<< /Length 2578 /Filter [ /ASCII85Decode /FlateDecode ]+<< /Length 2473 /Filter [ /ASCII85Decode /FlateDecode ]>>stream-Gat%%=`<%a&:XAW+Sl]UYZJJu]K(br"LZ]:8rKDr!_QXQZq2mV>__d`muUe3ZP3oR!<SJAR@Wr=Ds5g=Mq+r-))fmMp&7;0%Msks_`pKrFEm!&(,7@A>Gp2iQNh`7?(4Ufrpik]Xc,87BdS_(g4.iQ,:G<(_e^'e8kb$(:9R$VG"tdO\hB-!?@2T[pc[ss22FtU>kQE"((o[,o:E9fWdhLlpib&"ec's"?'p@B!m_&32DI?HeP+.2Y3gEd&ksafj(XePq;RHnfBZ1t+1.eg]oLsbcXeGA`3D+8>q5;=5$UQDjKDUb8+;?LAOa*Z>s4V[?0taZ,qRgd,SFh^n?VeEnHj\]-c"lBRdHT_1>JMlVq9=#q;M#&Ld*XLO=t\=9iY3FL@14LP;Wp<k]`K"SFVR-VkS0Sosf?P.:-TacbIG%q4iFuMuMn0dllf_mSM_fVW(]C_*e;a5sTO+kP^b?RpWpZ]_UmUl`ZrKhTZb,B`nN@_>8MPd/"!mQpBNpqk'K`M<aWk?['StX:Sg'KHb"G=_\hpLQolG0pc+A542(EDt7idd20bii>@Raa`]tg->m*K7US&)/mk,I35(@Og,2O4Tbsi$^m=io_l+BC67tS;2F\A"%kH$U;X+FsIQ:jY'W6nWF[j=-\1=]WKZ`iR34$i0WS"a>YtQ6mNOiQ`fKfa&DYN.lfH#,,#&KnB<BQ-`\gd=HLN2L><jHF%*&*&.H\Mm5LhMsEa"ksY(T>"g/jH;bN4L_M;4MTDPQd>\%q5tBdc9EN468ni>G$nn]mJU4CaQ(?2]"<E>;=O%`Q4<@Al%@d*NC<P9fO[Cp'SPP>W(ZNm2eRaQa\ghrmD0?@FG>=c_O=e69SOql<?FF)>.fK8)3s(O%0RPdR/Bf2pVO/!i+D>;tQPb>We^Y63ui+W7!(X7+Xk&kmi!_Z4'V68\d+7%R2'F$@F=gbPE(JHps#39HdV!HdM+ihbt]Xm!shH!77^IS.'/-ciuo13q@>2o0Q\VPY.hJN+7=0@Ph+iQ9UE8?`E#];J[R/[A1gJJ$9Ad*6=.;N8DgQCVk\_Hr'=12@uHT/-lB_-I3iI?ln3qK6U:J6(BQn'#9ZN9/DI15HEUG8c)OuJ9\^KWC%9nP1:R:27A9h.s36jFZbYg..An\l_Nt8!<BKe3dqa1`j-U]jK5@"^6ei;;&+ZBfN_HPJJmq]=pWmo-/VV.1<rLjA\lFh/%oOCVj[eLh[0-<k@CsKJNUnZH]g5o-pW+aP'FL$!ad,AK!XNkr&3dWM6QC>43=@YP9%p^Jp,cV-:s:b>TYe*,\Wo[\,h%u*XRujO>SuM-j-KIpYb+PMMIV8*J")9UY_KBM(RuOcP,uWB1]ri"ndBkU_(sU8k_c`)hnU;G!E[,/T8.,/2UNTHQ<[TeMu);D)`I%XcGap$mXYq(qb^3[\K1>ed>*DL7M*Ph>sVn',DER5XVDrhQ^p#0;K&rSmXhTkh6.F2;+;9\JS%n"T[V,-Ju-:=\N1A"a%W;o/N[bGuu?u):l%9@WYLM:PB%!So[r!9JN:ZErTm2A6;+XFU,&C$S92Y`4oRmTkhOScaW?!X'l[5P,>MOc*RHlFC2_Xd5e\EH/=?RS&rXG_6WAjGL,-P/DC/F-dVf5Z%QFbFRp.H85!3,#:L(55@@#-7,hdOoWU@i=G;J!8/_l>D>ObL.o+%9@l*a(*OfH@GXJI2R;6?/9_c@aIXj0!6UBnplT-^t'WKbYlLn/;n*)s_QiL4jOab*)QQol^[email protected])LHD1o2A478l/Cr6XQ%XHI0!\c/:YY8rXL9F"28+Nb*@O^-mJ'2=PUVu!,>ZVF:n5-b$(=RbA(fPU8tXg@3%M6@QD(?X(_8dm:q_$XicJMiYk/Z4a7o]<);:Fu-HsYu7P?0nfo)"fCFo+DHedU3@Z7,S(!7oIp@4j;EdfSceGpr_#MmE:"[a1[G^)W<?KAgU&`YYS6HNqF(1M9h(kG1^2`Q/i(]jQl\au]7`R,CeP7Um.O->D8<rGEfnt\OU^W$3$+(:TcGbpr[deNoUH,.[@>BOP7!SQu%7&YpHs(_=;bJoH*]us01RrJ!5K`QP&hqb)_0FLf?LP^b$OMLTj'm4W]&fb#l)p6Zo/rVT_ar\`8CAf#([>:[CQZ[AEm+u-iaOIs9%.js9Tnlg-[u&B)-_=rFFH/VcDPM07S8;Q2q2.aJfCO[:JU.BDU0P2>D:<]b2j@1'>cD%eW'gh:N1kq^M4a"k_B>W5HB;H'Z`VrUCBJ1/\Zdh[6+G(DS?kBg/Ab.V+mn3(6<BfR3gb6&Ml5jD%H'oae7`Kql=qGJ2>D/#3<K^Uon`At8%'u$5OG-cAL6:L(81&b/Tsi2?pRb6h#0UsI_*/eE)5n?B)`4tkV-%ldV+hNh3t6#_X^r1E"DLI9eLXaY1#MJM.S1Rd"Xrf-)dOrCUsa..sF_$reqA1Zg[2A1t<)G(dN3Ed0_FMhs^-BDL7q2c';96<8[=a#;>5"6NS+N^4-!'qM++X]L1=Pf7W<)8@,H\rR3eoQaVBhl(:2H]r:!-f=netWD*%&TVGVI=7&@rGCc?"6T'n)$j?!J_DC/K~>+Gat%%D/\/u%/ui*+nWrU+?AcdV;K_(Y?9OrFZ0`P:rr@`;BkA4e#@*]r@$pkj4Pg76\-@XO$)tVq2eQ^0!?%/,0TM5D(W4u[^E_f/0"RK<artYd.`@VL"<Q:rk<QsF6hBdqY/UVdsp,Bdumb+H#ERj/O+b0a)]s4OflV3L`IlanoShmg9G.5glKJ8+4BVW]$qleq/N1$BeD0`eao*5;Q>5[]__A;e8"s]f",mmQm>N7b'i8=<b]*N6pa,0?5/]"iZPNflc[gs="fo(/DjTWo99_ri0Um82e),Yhj2F8antBtM#,)"nGkb8VQIq.Q&>mVTo0BGWe.(:L1I#0m[l"j(n^?=%h`]-C&,#,4=C%kr[8f0b4dPR)Z5_KJU"_\hK3%Ile!B&=68AeL46$(X"!KSIr#=%(D!"UL#uC3IfC^tg)oT7Dq+55Vd%;(h4VFX6H)->P*lF[P(_K9c;.f6YMO^)E;.E/[s+H/^-7[,Y*0jH$E!6F6rOVd0nI!jWo'FNMt6DU+!6VX<?oqd84CfREirr)(d]E>`][ZarUEunI93?4N;h>N,`WQ5&F9rrHkQ.0j!;oHipt&7M5,0kCR;,-Vo"Z[M(eP&_l+=l;_Ct2%Rq,OG7-,RdddRAr]FX%,c=&S])XQF*_L33UNHDiY<;Pk%_L(8Sf<<ddhb]=*E5iH:+n6:DQcDFY^Y;K\WKBu=6`kBETN<[E[X$Y(uiUg6ODFVZma:2>M"fA<*o=Nn+CKdeQAUQ-X7U-6`'/T(^%N$Sm6]A]ZG0X1B['oo87!53Ao^Ld"8F>9U.Mj.j<.YdiCL!A[InG=;L64IWKIna_<upPN9'BHSTuGKHRPaNq"LF#O>&IH[Y*J4oPW\m!3s7qHBB96Ci4bn']aM5X8]mgN&2NB9P98#ZZD:hADMiq(B9rC.^G+@ocS@+p\79WAaMPC!c'Bb?Unu;"KR)(j$qYFqn^dZ>Z]RH*p"66icKD<mH:X..i'&UM9LKPOh9!bbRk-q2@&c;.7CXc0?Z4pf\/WC;i6O;B(K5q[;/_`^!94L%0$j<Kf<Ta*VuI)M*]\iW0TE2+7Oc'6jK='#p+b*"kqI8cgNs26A:hri10d+miL$#]Y>Y;MPhZ>4iUof<u4gf()XLW]?$KB^gN$[maZW#6Z_A)T2_5K4Pu=Ok6<\GU<<VUFZJeZ+6s,,;Y]+BHqIZ[!YU@bd]'oSd-hTXGhn2>Zr2Urub0W/rAef"*odGp*aYsMu_lY8E0VP$@Ds:"_Yg%n2l<DJ?U,oSRg:5`<O?h;*/S!ZU9gA_AG+T,T0Et_?@W`C^?1bO>V6IE<>F;pVFt"(JcQ4.ffHBN8D1AM;ut%T4[Y*bDLmo)XG5$:]dFG1e^I"4&,pu:;=K--1?Lp//6e\H^g*VZoGHo,94VfD4;peRSiEE%US8I=OH;fek96b%4@c']E<79*a#'M_&+rjo7jC%IN]_$m$S1D1qO4tTd!_4]GAL@GX+OQAF_,!+cGS\>U,e]o40252,Cgc0uFWi=j0XpeC3AG?It_?.FXe`%'b;%DTM<TOLG>!hOg2k4?<1tX!1M[>2fH=h0X3FKZ?HDBmXnaTEdR0D]*Yg>2,dm+>cRYm*ahfI@Z-0moc7N^i1[Is-^-DhKF#656**9S8^P\%Y6iP81$aaD55Xch@j"HKlKa@_<_!g^quNRH1`jJ]iiC(kRZ(7eBNhc,Z68mS<!'2c1=o];tu(JZkQ7"j<]6Ml,U:*1t/s"=9g%M_3i[`3"\&+9r+mMi5fMQlCu"f*m2T`CsGe\Sdh_GjR[h_S\f_YDQdTZSYK7F8k:e$npJuV5JiXYj.r8lC7_?_dN(s,C1];gQ+bN9\ZLRl(9:gX]"3RgTOn\ilS'U#jE1o)?\<Kg(DqtT[RE+5\QgZWL@Te>dA#lnT_H>%(?Z:M&C)(?SugZ.]9^Y>FXF$s9Ytd)I=0F%AC,pt7g@p@mV<gt^E=],R$MS6c?9sNM+AI1(O$WBJY/,fY6J;iL1ieKcS6t3].HqAeM]'mem85q?H\62`T[iOMZ-/i]"mY#M1e(Km/4X>fL9lZgpGRpnW?Y3A#tD])88a'Yft+N8-tbH?7,Msp_#hL#ck>.-i)4eM!+X2brrXNLI.(`QL&s.RTK+J&6,.Zqp76BCXp6(R'G*;<G1MSP9iA[TFABK'.VK2,&s:UJ;0MO[<R%$l#YlG939*[<elRDd5C6bjN1!/L.T22]t,UI!O0k3jHp]0e6q2*Vc0/SX2nIT^'sG_h.4t"_sN$:HbF^6%^\1hb]Y06]ncetE7%aC4UUU3I]tEt1M6j"5`Wu5?j_#j&,ruP;L)GZ*e>sh45(:'!kDRhrHE%]IQL\^9W8%$"UXtVQbOp:qc/*c*3XFg\^G\hD;E8Dn0T%V,_:CYg\[%cY?:bA-TW)eh7J5j1u!2HSsC8*FSo'iHN(diU6BB9puY<.];Il=m)?tr)'=UF)tZgZhR]?8!P&.0pZn^i~>endstreamendobj31 0 obj@@ -250,10 +250,10 @@ endobj>>endobj40 0 obj-<< /Length 2213 /Filter [ /ASCII85Decode /FlateDecode ]+<< /Length 2366 /Filter [ /ASCII85Decode /FlateDecode ]>>stream-Gau0E9on$e&A@sBkgX4nQn)%kHROsYfci`0Y8HIHRf]rc>Ja",.T18p^V5p\=[SU?]d\iPLmEeV]U=':aF1Bth;8$pK9:"fp++lYX;oELIu`XCOo-s'!u0CZ[4/1Q018ENX>T]gq;Oh7$8>rdnQG`?@0OcqEW!bDEH'-H$LHF?]W9./8)sB9e`21/,t4*J=5tseIUNDKR+KEc+qlcemaf.X5$OKe;a`_aGpc#4`4e%;]oPsNSrDJ]@oAFp8eJ*7-Th@P%Qj+.:-n_kB'4G?Je:d]P6:i#8s6f8\TaOnh^]YbT&YJZnAE^NX56]47Y0[3m=s1eN'_@2eCq'S?bP,@([[';[email protected];-pO]_FnGs4HZ4o?2mooPjDBo_isLq0kfDO;IT8DpjT^nE)aPJo[2:$1OON:ZJ+I[8/I:lYI\`*25D&oNb`;8iMRP/^_Z_[(9'9K=Ka"+*kqgZ230C(_jsd;UhM<ibn\YO/=J7nhB+Z>EIC4*NB8F\Vf^O"b/+J'M^"<#4RfpQ4,;<fqGBZ!`H@2geV9gVkAR>.H+(<eIN)oV:om7h2FEr'VnDFAqEh$=ukEQ*Lp`,aB6R1''nrgSMLA=//DAUC6f*`r?XeoEkA`8L3;*><hCoE",4ZAdOh,CTmS,28!5_dPEr]R>k2Mbh$I,7WdtR[2&GIs`!]k(8hpa&*`UQ3(nm[h8=.-_4bRqsh8B:pjJ"'lFJGp2Z5jO`O@d$3"9>GJL>fjY`Je*I(]^ld#;)\WGW2Jgm1ac5>XmHXOSq;KV1f0$cH4OH[%WIs@Rf+/c\r"/$e`AYi%CL.97[e-\q<pQ5m`<;M'JjIl,dg53S,S_ktNIZO/%qZE=l8*QBh+o>eLuYlWU*$6fq%_##X-/U".Z6+<'TcC@n-[4frDC:q[8*WIQtF:0WjLj>kJIM1WDp(b,63hBQDY:R*J-aS>u,VT97HJ15J8rM[t3fJ*jfY;<d_r[9kc6$=(p-am0'>;chJ^t+=I+%f8Ea-#A2m8G9u8&-d(K'C>Dq"Wln;q%6gW=cODf14,J^Dhl;%bRCf>#LGc^a,"GdsAY(qKq^\&-SfrVB?"LrbeLb*&+R:G+;AZLH/04;EPQuo=<4%A/TPe4F#'gU%^Bg!_MYEnRa-.'?Xme9OMHSkaX?\ZUU-$\u*muL'jkeBBgt?-.p/hREONjjIC2Y<f;`^I"31CT<"u(<Lq822rEY'V1Q;62m<],PTHf.I)`Fm/!DK$'I)Ehb0ol48r8jh/UIatQYNJfT[3NjX3;HTdH*kjl:K";r\MZ<.Pk0?pn"/`h,^@tY&__gH1GUjEk4H_m6na6M_<VhgXc$_6\]m3&VC[0ZhmSE*Lfu1GWA%K$\`m]-hUmd)L,X_1Y<ZS!i75h"I??75>E-)+Xu,[*rI#;]QF(%i@14#A/03_+DjXu^N_0EZL?P15K(c#71Gd0hD1M&PuqeSC>.%#IAT4HrmGJ.1a.I<_kln=&LQjC7JXni$hgD.)t"I]Zm=<c"k.qhj3r!Q$e\S<n!7o"T[D*RP)b2XC2:j@8LDEP?'$Xj'M\7BdtRC'ac<2XCHFANh8=3FK0:0aK6NNe>HPXc087o7<8SY0-m:;T:cQ7OYCI^Ma;Ho2)R@[_CZ+h]aM,JV+Ppg)\,TijSZc.(der`<WOK`F)a\#]R^bIqdBD8.o1#0('@S#MK-RES*l.S2oh-q]R=@?Z@]kejXb5f"a`VlK?#<.rjpo4MY6_9?#XFq.erFeQ@,Yk9P?Ajhp)Ve2f':<OAO@QM0%LJEikNh1fgG&c<oI8g"r-CSPVRu4409isJI>f))?BA6'ZdVp2M50?Sq239\9L(S"Ss[qXe$<ZF'>*K1cqb3*_6r.Tf8.f\)@F%kj!4DR4o!G?t*Z$j6(#E9=e/W5G<UC.af:dUN1I(^mOTR/q+6ehOcm'I"C*K47td8>/B%Ed)aQLU!#oU%!Q].OX1Ao$sr-?lsnl1A@iC-08a;Y-5ILIGFfX*o`3AL*TmCk$+KqgnE/;k0?cCDG[`S:2)_d`.$#EE1mMEVeE':IpRRH*p0?Dp=9itQi7K1[rVj+<Q8*'V$MMA;_+\d'V0$kW`I@,aN*=DY)mts1N?T?g55YYVn"Vl3X[mog/)[n<HE)`.%lMr@p761KC#0q%]m*J.fA41q`plR-(WX78X'b;LF'>Ke&27$OTEa6+*/l>Eop>2t;PNk<d^,VG~>+GatU5D/\/e&H88.Tl3T8Qk?=lHqUefBS!&8C1%nD%\PE-&gE1$7+KD.rM]IcX;;gCJ\lMR8+PV[cQ1@#f2m/<Y_EJ4[IsMkf+(kae)`fqH+Nq![VUV&;d7;r[qgS5[-u`FP;KO*PBK"<h.FC'2tN[>:u#_7@[3Of7DSc95)`V,bWBrZ434j)e_Q65qn$-'O3suK,3_Ct%#J%?ZRNdKO?)r#'>NEq`mT\2k4W9L(n$,\qY9t)qW5o`LQBdFq;LqobRQ2[6=abX$q8Oq%,`Z1gWi[s95"`'Hp<1_cXRk?rV2?grSSOT!O1V_k6b5=O$E-8+0\fbV\-Q.^BsWj.klI#N@9`5ktnKHNejARdNQI4p<s.":5imZG6(&n43UqG_8aj)L@fXuk>@Us;',3N;V4G:qe!C:p!l9.3q>t'*>rJVVdHWrK+],kRVA!*>%%q%7*Ct+^&%]mrOP1e4rSCOLPSt!o]Nsk+k$8"]?U"-])#K8H/ILr2J@1'Y!;g>@L-20K1HsPlQFF1ogTO$6*cCU+.SoLDuDqU.%Ilaf?&prE]9S&X1LFY.Lk,o[HnXPdAj5O#*n+L%Ru1ClIc@c+=KE#,,5GXp\e0C'M/oaLP`o3!`kBLY[4Q(CZ'NT0?K5?B@8_hT4TcfU`+uC,%Eg0Ai@8n-H`nm!Nm<bhnW)R'fcQM,%p(ah!m@il3]6Zq&ld)6Q7q(gI(R3KKR@PLiqT@LF8aY@7"qnAOD82-O;T=V1ma.]CNk@Z`lqF`'^\B!=_N87nUEE<C8JiFZZ3>J!dL3i#.=hW,QIU+I>5tBFu`M7f$[m8IMkW8d(uTj`>Co0!\KXU!\\OlH[btB/6U0;H9Vk98[u;5^H=L@C'GC"U-$KqR'sF(I/Z8oJE=?`1f\*9ogFk,$[i<W_-&QQ?K+?.&rSiLh`]RN6op/O=P)f`@+FXE(@kmW%s@G!+OMPF?jD"T!6Bt(D+"WS&0WA)Ri't1Og9Z7n2'@BY-N8=+[?rF'tK_d,]I1hW5)"hA(Z3qSr.bN/RHn5*peka_$?A`^CTJ+0ZB1L5\IU7rmU6m:G!:V2KG#V,Tl6M1`e^h_]m4/sM\:G^i@4DdeNsnBc0"#R&(RZ.NeLK98eHc)f.7WjZY(@NsQHl9fC*j=Vlr$*eVAQ^a["Jb"7hVjiOBXUqjL"8o-1D*,,sV2E-SQfk_QZE=4e5`Xeq`@>OJ+N7G8PR9b&rX&M9/N[X6ZN9X4Is!TeLT1Gs2uGYn9Ra%daO5+HV^sSc$X)lEWX$Lb[<"W=<LMd>BPE6klPU!aA<l2CY.ACKKLX*bLR]9"DI@_)pZmsaX\XSb$_`juHk]VJ+JW48,-cKGmN<?1b@T)\:Eld&W2Hl:SJOlZN,Bk`T"BX`:g'fpZGPjFaB+u[67'JS#4f<TEEB]0<8&)KeTYC&cNZS2Bu\UQPR2OpWBq$sMRP73^s/,11uebX;^tg4=>*+[#QU0E]G?%64f$I&Oq9%B6;NK>id<0XjO="UBQNc0Z.m)6K%Y0@hD"^=;2\(RjH@AV/O:S>ANDI$0t3q9R\\PGaTNsV0i_f^cYpGra3.R;a#fTJVH&9,?7"*_30iHQ.Y1H/?(jA&PpfQ"b$W#,o)Dc\Z[j+Xnqj-=$7=kAH&%k68W:aj?.5__AccTE)=WHaNbmI"p"5gW4u&3U`7soIio_"1(iQ6S*KmDi<Zm5"L$T%scanpELZ-e!^.JsR*"u9G,,?m-o#TJ,J:FJm+D'?8kA9U4Y"Jbu-S?STVNFc]Q<2cRE3a[SLjWaE<dSJ(m++GnjH3*LVIJtA=M'i=i/jgeo3<])2P1=;IU2'GGn.$9mh\%mfQ@aC)h3+Ch-J=88CoA]I\N2+gsR2!!hX6lOKsWa*@hLs55jl=ElobdB<,'*<Z%W%5sr'M,*b#,P]h/l@0OJHAh.`4Q\6HE)0Rp23@6MGqh2*5WqW9mo,'/11-cI\)u3$#lSu:QRcmu=r)Qs0\VGcR*BEul^P-&7,<SSY_/&pWDI@"EVWtp<3DU**`9IDA%,(m\TV.aH5e4"RI&Y]IP"4O`(aG,iVgIeC[N&=JatE"u3Pe^l(8],*J2N$gY7p(\l'a0P`fP:\Bk*Z!)["1;"&,M#2=,Q06`PZ,<)5M9`3KfC;d8V1Vh]&fG(:c4b)J7g-]6B@I=pjQltn;d,K<e7Oq>>=^31l)]JdeXj1"-k1:mA!ZV*3:>A^VV>Sd!pdUUW6F\`&(%W\YJV4a0ia^e*"[ge#tDKm"D7^L`c:%PGmbCCP^CK%o_>*p*#N>@kKhR9es"4cK08"RG+D-Nh0[36=R7mtt2IamRZ4a<oS=6[b4q-G&1X/Nf/:qeri"G))+?$4bOC@*""=jF;pI</2Yp)g0-'FF~>endstreamendobj41 0 obj@@ -265,10 +265,10 @@ endobj>>endobj42 0 obj-<< /Length 2071 /Filter [ /ASCII85Decode /FlateDecode ]+<< /Length 2365 /Filter [ /ASCII85Decode /FlateDecode ]>>stream-Gau0DD/\/e&H;*)Taq6oC^htRUg=Dp_m1luL,Rjk%gBBM-uIA?<`r>n&hh4Qr(aP.*Gs5Ep4<@F.$;PsH1&4)?dC&`bU/r0/r;QaJ[=&p]p_>AE?3s2i@c#7o+d6Ui&RWSk*)Dbf<`Tk-?<esA[\,=E0`O;r1hR*U^0OWS_;$Ym:,Z9:<H5mb'2Sn(\.FOq;%J;G]81g,S\6#Q!/$(<`f7)ktU)4[_#TWiGh1/D^U/NO+7M>e,A:D3`";V<m>!1n#l8pW_6J/8[]Ppen]u"WVO&K.;Lr1Q.i8^*9rsAE'4i>hY%g&-f[paTr[`H*EPfi4u\aan\4O=;(>^YOlKrK[a3!Zg(a4t\;Ydr?hE'ENk:)MEP5b9Hpg<Y&pVZA&I'Lg_9VUsP"i9[?ED14%e_+i%*r"-@AeN(!_S%EqmPDN+75tj'&V;:,hX8S;<R%tCT*mO!YB)/A/sXnPUTc^)30a^T>BatLp'hW9KV#Z1p2=RpDSHcQMKZ.1^[QeY4M(H1Z;;p+:LPKQ[mr<"p.:$V>gHglF;p]J[9LUmpaqA/m$?Tnkfb"r8jEW^\5.r*9VqJo$Q=+Mfi;A0;d3CPCFa$\XMA\RSmDk2i-G>gHqTuGaXe%J0'fqDN_:l0%qKSD]8O"cF6rF99_Fl6]39qjI;lC<FlKg1.fkC9r_B,#+;3%c'K1haC2[->S&e1?-&;2OGS13AXreq).g>@]&1/glO'DOY;@5.);>;[?HZ,V#$IrXnneH]$X2t.p]tH8J-\A!Vc`/3@4q)%Shmf*<KEZsUT'3=A</-@9G_tT6TlRZLF+:I01LG<0&a1(]5"W)8MNiG8[.fHb6d7Z:>2iHdt5WXF@Ntr!K/q,X(G\;g'Xbc8aXlF(?'(L]eZh<*E4ktb+)H(fVq!-`#IKNBRpXXM8#p8<BfI]<cj<ZQVCN6OBXZZ#)Pb3NH8*2c]Ie,gh]r(nOOrbGa/\nIOncM&/'2k["XE3Y`c<9)pBo,\l>&`+Q&>%nQO-%\/dS\)9ks&@t@26dW*B6f<mAb[%LE5lr[Z,W7OM:p`-<T:_O@E5X>S0i:D7(/ct&'-heOL"2bCkYH`;PWS(tLUh>$!,G;/cPkQh5BBEp:i/Ed@g34taS#9G+J;MNMDk^\T@#=[ZKi]p`Ke.5$lc$$C-)#Gc0npYV'S@jDq::M#[CeFsM33l0JS%P)*Ds,RHGFXOA4m(<a,RC]4lKF'WQAZ!!t.9O8's"RYXbRGS+cEU5<+W+k#9-!fOH)F&I&9^c2Lu5/^I%#WjK24SXd,k3S?@jZT3OB7KhaIbtZ3+ic/k\9k9;.4-.BERqK@Y+Z*c`E.KUMN]i]'!chVBG>ORb#%nj3o3<<kXC;;aD*Bd)L92q'\\N1)!10SDAJD(cn.:P6.B45sGmd40h2X$Ao\u=Np(M':1T8:V_YJi'ZZUk8G+oF>^"PrY@P/na@."9%$+RIl@&ET%HEa[B8%*/b]]PKe_YC[.d([`QEDhdVd*,mbnmLt8oWRHbr%gP_ro&_*;VI%V^]].-T+24FFN=^K^AZ^/_#&_0SA%qjlga(Dj!/YD.6:$bRR.=+9d6dU9eEqoYs7d/8^H`uq]:S^pdiea[aS7r]/2s8OCr4dU+L(l7R@AI`KSEoirSMRPA@)oe(hnj$)8Y^f#h_YIVrf_<7T,h_3uS!$C7q&fbsm.1CWVE>,.RhN8.QbVXHZCh!"":V`kDm]C0rEj'mb8cNsdA%%.F4O#V*<4$ipXRGd)sn&nq7QE!p;i[b.,ZD?&`2X$fnN(nq\pdT>6LN,1PndK`a``0=1R(Tr/(,/nN+*dF,ZZEp-BVGMQd+B\MLd:QQ#+R*c;rU%*PP/MoB&/J?3fY]d[8:f>4dCBo1R1lK6_fX`]mW4l7g[[email protected]<+s#bg](gZfCE<@$iqkuc`.,(%>LR?G`$\_5F"P#2Xs&ad.:On&e3f_bX,74bC"^I]B7k#!rj9m>g*W:NbI9o%#a_G+BZL0h@`t]l6(fu-T[9J#[a9>nbc^4<*QKZRf4#b8BaYSO/mF$BkkjGV#>#hT8+8[I*gu$16#s\~>+GatU5gQ(#H&:O:Skb18)2G8rBWCqaWBUWgh,.An'"DG88BUcH\aHA&NEAm%$GB=q0.G:1ZJ;l!naI0q%1PbVOX4dDK30Y$,\Q[<aB/?<C$id.mh%1Y(_C*(@SZA=Qf>CUYX/4,4=;?me$RT,'iSbs2gL6neC)F%Y,fpO9\euP(jT<]tjH9&CF7gLI5^OTaoqUf#T/.+6mIHe>YD]1->BdVJGj"KP@ff].ZrpT+f)Dq^a,.i'dsd_.6h4Z\;O'nW-Iueu^_b5%:?;u',S:5Q%te[]HnP!n=m0\s]YLHq^"fVfld)^.4dWDM`/j;Tq!7%=J<)f*7I6=SQ>.;8`<\1*/Tk4K6)`Bk32>PTCOfq+SHd$G:[$HFnmA5>.dWh^F8sm/,4'bZ>MNj\l$=Vf:R'L\0CqMYd-AebTO@hdVW!@klZlRqbBek\%pD4MnF$sr@G_4$P$1VDRN>ZS8"Go+M:56[bu5>N:2/B41ks48cZXM%,7*^;isbf3a(r.2i<V!3dj/V30rs&=1c-Y5MI!c"eb.Lb6^>Qi`Mpj#I#eD9it/+-L[b+9]rneY$:bjDh`!.HFJZ]NjaMRp?P&ibVO>Y*A1u(O[$lnqQL?(kQZhX;KE-2D(9nYgO0Yog1,;PnI[_YKih.&_L1a;gXO+N5mu:4\5lG"@L;>\(nNp!VUiD%`,SK`#+=XFD`"m@h:G!'RO;,'>3/3u/XU:8,G&H!CKTLMRoRd3T?[4Gds*4F8(e\2ka85,Pm,(t+X7Q%q1ZNAl7G)o98,s.g*:?7K;SR^E3%bM+i#J82ZeoCkY<(usj7HajZ_4Op]mTck].2BL*+Vu(5C3)#iE#:CPPKU6bJ',jhor8Gh't,'%TWs[7^)P973lQCgC8c$1<p71d/i4</+GR!m#WQ^6qM;2b;*@8]7$i>Z%B9A'/W>@66"F>8Rh-C`ZtgD,A7R:72PT&DX)o@N37`Q0rBY1f.knUiT7pu(_s^#TODY-B^E?sT9OKt[5oFHj0[=oA\X!0lU\rC%=efAVrtB5^6"J-#7dr>05*`Tk2aZf1jkd"7Sj@Bl-'5q3&%\Yjfk_LX7+U\Zu!ldCXP!G#4kmWOQq`Z,b(u<]V-=&W1A-2VI/B^0_<p*UIBrZ.*5f-H`mjcJb`EH`(4NoD%9ghfaR&.;4.oI.L`_+Rk=*V[q0"*bYnn<Cr$QHI9-/<Q7=DdSkjS9`*nSda@ij<A,b_u3fZeM_,[@ioDr-;.sF(?O3)Z,lC_#0n^:)lXFa1&+S2\QV*Js?L!'at8"?F,GaV'((N3<EES$]4q&2Gm<(>AOL%I&5Y3V,1ZQ.qo12>Sc-TsXPhhHZu>%ZZ;EaG>)8)^PqF-%jq4=e`D"];JJa5&+&UCZTkA[`+r0+&!n>+7sNcClH4!k,LhJjAB<1p%tp2l,lNj;CYcV@oD4#rCUsk8/PMZk#QW90<!ll;e`7:0Y1Whrft=QnBO'SEIDU>7Ac:W%SfokFl)6gOZJ3,Pjsd:_7orVV*G?HUB?(gSh]Cd?[_pLc:C^XGkV16c-lNDpN9O;ac:]^skH%b/@bJcXqU(ZOb7XC.H?JK_@[unY'qk,kTFAZc>)"@[rq$ZKhcu"ZGf[(Dc:s1P\9]6s]E+%X,e"o!?"A*3dRlod]iCb(M;uDK$+8e,HMkY$g9(F7A6&K2i4"7GSQn4)r3Klu-pA!Fu50<%i&d&*6jZr<S&-VX,:?l)^9Yo2L<];S1iCKC]F&o0LNGr3#s.4s_B8U\mOM9Ja&$>c>mWlK?8=a1*7#cp;N)J8W?2@Wi/gAe`4*e9<L0&CMjW5L\5TLhfJ&[Q'#:g*^otq2ZCHD<6e'N;+D[WB):q!%`1;NAB)%NZtbKOKQf*3+cUn^Ucj'$SH<dOOZ(O@'O^/D;?PiE8`(X]5S4uACN,>XjiGZk%8,\O(-)dRgii-0Rl8Z:nrqZ\3#M,f^&o>(n?<irsLm(J'SX^J(ru,*3UtE!e0=M'6Bj<G*c#/rUFBG/($qXeQ<I1g%WBcrs^&92(-J:I^Er?NAqNO>uN?@,=$&7h'>1DFV)DE3'>U3i%-T08a9hTFWjE(Ak1D9cJ&jJ\0MW0Y.<'V#kuATDYm)I?/X]CiDGq)>;[<Mr`i`M,YG,"`\r,>GtK.q0B]>`'0YnBbON$3M7j-amHEuj6WrepN\/mB;'.a*UOIuBKcTOfLMlIhTbDqi[*-*`m8>J@lcAtP0#"IB[,JOr:ofT$"lWYh\*ei0^2+Q;,nX+/#laGLp"hs#)j]O:h%goqKIl$_s4Sq*M1"98n4'H^J'%CCH+_hq@BOAWikpS_Xr'WFRqW'kf>k%&r%;4>6[RSC4LqPHUss@d-HN9f_Te`[]0Kj0a.UaG*s(=!#OBYF"9~>endstreamendobj43 0 obj@@ -288,7 +288,7 @@ endobj45 0 obj<< /Type /Annot/Subtype /Link-/Rect [ 415.788 579.967 451.116 567.967 ]+/Rect [ 403.788 525.147 439.116 513.147 ]/C [ 0 0 0 ]/Border [ 0 0 0 ]/A << /URI (http://dmoz.org/)@@ -297,10 +297,10 @@ endobj>>endobj46 0 obj-<< /Length 1777 /Filter [ /ASCII85Decode /FlateDecode ]+<< /Length 1818 /Filter [ /ASCII85Decode /FlateDecode ]>>stream-Gat%$gQ(#H&:O:SW'Go.JmFh@86m"p6W,a,Jn!2@NV9%p&DEjqTsElS<87Y7IX=RDCM6@V#6?`WXLXl^F-5<1Aj7kZJ'TO""_4783F9Cg`KX1P#QjcOA:8mH@M3^bd,&g:lg2l*2LcZmXSue9Sl(S\*ef*fCF*O[6KTkChB+D:Bg0in]@t!kmK-SlqI6Rtj7ajLl2Biu5+F#5&W,SEP%pU;X-;Xa#@A!&kAR3;GjD</hrc8B6u1^nD/W#XkL/n)4.9CbLRfm@WA%>Dgip1Zi5m:=;%I=O'06;qlR*-5lqcWFdCCk0M/aM-^"MZ*QG]7TC\A:VO\n`kd$J`?B\6K?r?&aa=@I7J@*W*g2uamNX\(ApahE]PM^$#"^?F+ui&pk2!^T4BHp,<cPlOI0Bj`S+beHP".6%WcNaQds#0tk<MR^)RBl8^d6/R(?-VW%3E'rUA%To^08sQ/!pM-Hr17V-"T&tn/#KuGhGK5e3O839/6(fCnJL2X."Od;Hen"XFTU5Dj^%\pk1uDP)9#QZRV6jtRB$s2OE)h)2_pAkE<N2PAN\87_/oV\kJ4HaYS`NGXGoW=^XitYf.C_h"_G/![R5pM`2%(#l"=h1T(-Ep!\u&\f0H`Oe-X#7MHDE87.h)N]?c[041>9Qu%#BkW6-I61&qWHlp-dU!*'q9fCSrsu2QTl<H(t_j,DCV6F>E/<Y*HKVqK%Whe05)E3n"j-R8j&7>q(0eZq_E4Hbe6)1PeMNjrk="/;M_mYN-N/ome,E(6^/VMIMYchk*YZU*7V@7Sr[VZ+Kt2FSemFI_SE9QidQm`gO\I,u<P-BX<,lZhZK=_mo/O''8/Yd;VMno7\HK7H\OSP]9Kr\qW<D$F-l#@7Qa.fhW*X5]%jmd$$.fN+9B5DA?M7bkRIF@:$i8JYN2Bir'dr.kP/r(<JQ[I@lY37j9[C4>SI$&0*.1#</"O.RrCbm@XX#E:oP"(riD*pf8;5N2\-2qXM%M>=V9Q(qdsGN+c)Bk7TZS!38':%Y/,UAlBbCV%.\dW8n8iDULX+eO!r7,'#hDc+*,_YVA;_BV.(I:Z]^]QXeG63$beZk&jg-4"&W;Sp704o"B(-\1g#.M;r+;^NjEl.\#2TRE;6bn2sr]+$52Q`cAGunjpPeNV^>]Zms8'o9[pJjilmA]-S-B]Q1Om_Rfs6h4e'=d(3MaLP(NF*&][^hj<q1+$VAaNJ9#piqMd)$8qIQq7In'W0`d5kBYY4&jGjGkW%16UTZQ6liEWT+5,,&<]`73.hLpq4ptWMA3PsQl-`tu\Ki@GF>.9)b]qoq%pN=5FZ85Z@8G&JBeBiUUnb&Yqin>AWRK!_S2XT<%>Drq!Do^^#.8f9.@fRIA]J;#k=HnXN26[`Rc4Wf1W;oc;a&"jo[(?XN(2"m')*!!6ia6)E/\"dDtLT0WQ*\`o-UkbP;uP"<u*cT+ZJCb(G8HkRaS>O:F`L'^YjSF0e6.r/Zb_qo6&(t8Rd1J44I'@VIaM5W#@DZdlVKf"G7.;!-(:k&Doc&M#)0^Ij=P5M;\?ki'"NRFi),;4$#&D5sB+eh;?Q5&@\ODpCWDK]Q41)BAt+O%3f4.B3XK17T]Di!qL=b63*YN+,#Xf,`J1^=#E?EjoVi&e&l>p6J5q8&h`LGY5>$#EGP(#)#Kl/?W9\>es=77G'j9LGpjp>J4YPZOBt>9he@NrqkkXoD!dn]1RDo;ED#>3lM>=DGRYl8T-)>36K:OZhUZ&FTWacR+L-)cC(H<k&tO0Y@HrLSW;R5O^;[V~>+Gau`T>Ar7S'Roe[d!u.2K8(^%;3q90BSNqI0Vho_C_,i^dP>YIPsnKCis$@ogNR`I%rKF3?8`KgF_L;M5CVclGI,E`Sa[IDe=/$;e6>Y78)YQ]&diEJi$>+L2qrS,]Xl_lfA6rQoae7M>$58WNL\0!XfQ)F"]^pF;eTU=9.S(G[t7qHR+TOrekiBC.TMV2KjC04NU4oIb[_>hWK\R0]g'3`:C#kTN!+dlmZG)W1?f_QD]]@pa$s)KL`G[#b^.2pUUN0^WlqJGfgS@Z4\3A*kOf@la^5]RP(9eCC=YV_T<r$GT7gOtm(3i9@A-aPDa*u>E`^jSnJH-/m0:m'ij1Q:GudUs>oRBH)uD-cW)=OF=41"7o4df?0gAq2U9Eq[%0Urp`AY;Y)UOQKU336jhgNeTMT(sN.DN;UrG<X9b]:(_I3(-mP)tKq26#$3[Mur_pu$lT,]PZ0WZE9qP_9XBj8%PKiDcf:`#e$pWlIW_2'j*56&4cuQ+<nadB!]YbDe-:<9dbo\.!p4n-KVO#_iYZr"98B*YOq>mgp1P'"Hgbd/S#,#cRKm@0l]s)hL$pTsu(o_b'pLd<NB4!($W)"G;f!R!0+SF-o!UB\_msThKV%Gf[Obng4:[ktZP+aTB0/cmQ*h_(!H_L&1(roB)P*O<Tb]6Qu8UHCqYi"XH@eIp_MHh<`\ieunsRRqN*,9VuJi7+;gdSQ\'e0RHhUfU9%N1AKs$<?h7E:7Gn8Qg,%F@iE*1c*6GlHlC7A<ht'%3%YNR319l,qJ(`bl6l80k]1[;J+hF+J=?Bq-:#7-2^K``W&si1,<Qn-r&3/$mLG:N]m,F*:;amY"gmAD"Z(Q6Z:D5k2-d1&T%'3WSI<Q%$X<f[M*fgPcLRpk4RnIk!<b<"+q_&T1D/c[hHr8"p`^o6^:]-g3bP?_fHq;jl@mcY?D"?t*tU'Wi/DsCZs+gmQmXaDY:S/q=b?3Y5l?)8$&ChLp!@B^J;nft8Wq$4n8!HVnrqqh5o?pbG($tY,FIl!d:YfjITU3m6\8Db(bW'tj^YHTNDp_@JRNL_d=6K8itADn%-6-=`a^X\0ZHM/-5Lo7jB=0@<jRk]DD7p0Q#f01Z3<BCrSf*H3Qht@MXN_IV\%>P_f,9f*$p;Kn-[YE6)ustfK]L+4XP@ZR.%>.bi>JH+g4Y&GfLAnfI3I>$t@g%faJ;FBl$J(,225Q*.4u_I!RpmXUjLC^[nn6G&@Pco8,u$?*TZ4&SHERibjV;m[n3r;jgEUo?M$sSFkTDHp4',4BI0_EDBUX?$u]\2SdV10@PV[bo(IsnpD0[E/$!V$?-mqemHD>%2tn_V%qcJ:1<(DgMJhHpu0-WH73Tq6uXgD[&.'.W$.dKdO+Y"EcN(2XfZ2EkaBm[+,qUP4\-s[,BGi3.VI_i!=A%O)nNIL40Y>nfRcMHgCPic^8/jlSIZJaS@'ieW""92-d^NihXPRLN$WMKHso]^n)#p,fYR6=\dXf3/gEIc?91>*!PL2TcuX_tHCfZe-&`(l<+r;q12mFJIf1k6@Kgbe@od0\M5o7kI=1KX=MTa]6f!9n@bABq!!Mt#]3iWB\93YLgNsHJCu+5ojZP\5Poq1"`b]RkD2;t5RG4+KFP=9V583T1C(6o^:0#ln\\[Y?41=Y;A42N,eu/>3oqJt4h9P5iq3HdLZKfR>S.UU\W_d,$(NnCIPmpqj(gQ&]A&#f:_V,XTd1-][,rQ)58cTNV,]FEXiJh``r*F<6b&"ID<nA]9q5hL`'isV0TbZEN)o;)t?5aq*[.:C!$j4OI(BeSjH[@8"[OWW(H7Df#F@#a>7aWbU~>endstreamendobj47 0 obj@@ -320,7 +320,7 @@ endobj49 0 obj<< /Type /Annot/Subtype /Link-/Rect [ 141.336 194.134 244.02 182.134 ]+/Rect [ 141.336 145.214 244.02 133.214 ]/C [ 0 0 0 ]/Border [ 0 0 0 ]/A << /URI (http://localhost:8080/)@@ -509,43 +509,43 @@ endobj17 0 obj<</S /GoTo-/D [41 0 R /XYZ 85.0 599.68 null]+/D [41 0 R /XYZ 85.0 586.48 null]>>endobj19 0 obj<</S /GoTo-/D [41 0 R /XYZ 85.0 372.707 null]+/D [41 0 R /XYZ 85.0 306.707 null]>>endobj21 0 obj<</S /GoTo-/D [41 0 R /XYZ 85.0 307.173 null]+/D [41 0 R /XYZ 85.0 241.173 null]>>endobj23 0 obj<</S /GoTo-/D [43 0 R /XYZ 85.0 639.28 null]+/D [43 0 R /XYZ 85.0 553.4 null]>>endobj25 0 obj<</S /GoTo-/D [43 0 R /XYZ 85.0 397.787 null]+/D [43 0 R /XYZ 85.0 313.387 null]>>endobj27 0 obj<</S /GoTo-/D [47 0 R /XYZ 85.0 527.86 null]+/D [47 0 R /XYZ 85.0 446.02 null]>>endobj29 0 obj<</S /GoTo-/D [47 0 R /XYZ 85.0 381.567 null]+/D [47 0 R /XYZ 85.0 319.447 null]>>endobj50 0 obj@@ -556,74 +556,74 @@ endobjxref0 690000000000 65535 f-0000017176 00000 n-0000017262 00000 n-0000017354 00000 n+0000017559 00000 n+0000017645 00000 n+0000017737 00000 n0000000015 00000 n0000000071 00000 n0000000922 00000 n0000001042 00000 n0000001137 00000 n-0000017499 00000 n+0000017882 00000 n0000001271 00000 n-0000017562 00000 n+0000017945 00000 n0000001408 00000 n-0000017628 00000 n+0000018011 00000 n0000001545 00000 n-0000017694 00000 n+0000018077 00000 n0000001682 00000 n-0000017760 00000 n+0000018143 00000 n0000001819 00000 n-0000017825 00000 n+0000018208 00000 n0000001956 00000 n-0000017891 00000 n+0000018274 00000 n0000002092 00000 n-0000017957 00000 n+0000018340 00000 n0000002229 00000 n-0000018022 00000 n+0000018404 00000 n0000002366 00000 n-0000018088 00000 n+0000018470 00000 n0000002503 00000 n-0000018153 00000 n+0000018535 00000 n0000002640 00000 n-0000005311 00000 n-0000005434 00000 n-0000005503 00000 n-0000005696 00000 n-0000005897 00000 n-0000006084 00000 n-0000006260 00000 n-0000006450 00000 n-0000006622 00000 n-0000006796 00000 n-0000009102 00000 n-0000009210 00000 n-0000011374 00000 n-0000011497 00000 n-0000011524 00000 n-0000011694 00000 n-0000013564 00000 n-0000013687 00000 n-0000013714 00000 n-0000018219 00000 n-0000013889 00000 n-0000014052 00000 n-0000014247 00000 n-0000014494 00000 n-0000014732 00000 n-0000014992 00000 n-0000015230 00000 n-0000015443 00000 n-0000015793 00000 n-0000016020 00000 n-0000016247 00000 n+0000005206 00000 n+0000005329 00000 n+0000005398 00000 n+0000005591 00000 n+0000005792 00000 n+0000005979 00000 n+0000006155 00000 n+0000006345 00000 n+0000006517 00000 n+0000006691 00000 n+0000009150 00000 n+0000009258 00000 n+0000011716 00000 n+0000011839 00000 n+0000011866 00000 n+0000012036 00000 n+0000013947 00000 n+0000014070 00000 n+0000014097 00000 n+0000018601 00000 n+0000014272 00000 n+0000014435 00000 n+0000014630 00000 n+0000014877 00000 n+0000015115 00000 n+0000015375 00000 n+0000015613 00000 n+0000015826 00000 n+0000016176 00000 n0000016403 00000 n-0000016516 00000 n-0000016626 00000 n-0000016737 00000 n-0000016845 00000 n-0000016951 00000 n-0000017067 00000 n+0000016630 00000 n+0000016786 00000 n+0000016899 00000 n+0000017009 00000 n+0000017120 00000 n+0000017228 00000 n+0000017334 00000 n+0000017450 00000 ntrailer<</Size 69@@ -631,5 +631,5 @@ trailer/Info 4 0 R>>startxref-18270+18652%%EOFdiff --git a/src/java/org/apache/nutch/crawl/Crawl.java b/src/java/org/apache/nutch/crawl/Crawl.javanew file mode 100644index 000000000..a010b139c--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Crawl.java@@ -0,0 +1,123 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.indexer.IndexMerger;++public class Crawl {+ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.Crawl");++ private static String getDate() {+ return new SimpleDateFormat("yyyyMMddHHmmss").format+ (new Date(System.currentTimeMillis()));+ }++ static {+ NutchConf.get().addConfResource("crawl-tool.xml");+ }++ /* 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;+ }++ JobConf conf = new JobConf(NutchConf.get());+ //conf.addConfResource("crawl-tool.xml");++ File rootUrlDir = null;+ File dir = new File("crawl-" + getDate());+ int threads = conf.getInt("fetcher.threads.fetch", 10);+ int depth = 5;+ int topN = Integer.MAX_VALUE;++ for (int i = 0; i < args.length; i++) {+ if ("-dir".equals(args[i])) {+ dir = new File(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 File(args[i]);+ }+ }++ NutchFileSystem fs = NutchFileSystem.get(conf);+ if (fs.exists(dir)) {+ throw new RuntimeException(dir + " already exists.");+ }++ LOG.info("crawl started in: " + dir);+ LOG.info("rootUrlDir = " + rootUrlDir);+ LOG.info("threads = " + threads);+ LOG.info("depth = " + depth);++ if (topN != Integer.MAX_VALUE)+ LOG.info("topN = " + topN);++ File crawlDb = new File(dir + "/crawldb");+ File linkDb = new File(dir + "/linkdb");+ File segments = new File(dir + "/segments");+ File indexes = new File(dir + "/indexes");+ File index = new File(dir + "/index");++ File tmpDir = conf.getLocalFile("crawl", getDate());++ // initialize crawlDb+ new Injector(conf).inject(crawlDb, rootUrlDir);++ for (int i = 0; i < depth; i++) { // generate new segment+ File segment =+ new Generator(conf).generate(crawlDb, segments, -1,+ topN, System.currentTimeMillis());+ new Fetcher(conf).fetch(segment, threads); // fetch it+ if (!Fetcher.isParsing(conf)) {+ new ParseSegment(conf).parse(segment); // parse it, if needed+ }+ new CrawlDb(conf).update(crawlDb, segment); // update crawldb+ }++ new LinkDb(conf).invert(linkDb, segments); // invert links++ // index, dedup & merge+ new Indexer(conf).index(indexes, crawlDb, linkDb, fs.listFiles(segments));+ new DeleteDuplicates(conf).dedup(new File[] { indexes });+ new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir).merge();++ LOG.info("crawl finished: " + dir);+ }+}diff --git a/src/java/org/apache/nutch/crawl/CrawlDatum.java b/src/java/org/apache/nutch/crawl/CrawlDatum.javanew file mode 100644index 000000000..f4e62e3a2--- /dev/null+++ b/src/java/org/apache/nutch/crawl/CrawlDatum.java@@ -0,0 +1,244 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.io.*;+import org.apache.nutch.util.*;++/* The crawl state of a url. */+public class CrawlDatum implements WritableComparable, Cloneable {+ public static final String DB_DIR_NAME = "current";++ public static final String GENERATE_DIR_NAME = "crawl_generate";+ public static final String FETCH_DIR_NAME = "crawl_fetch";+ public static final String PARSE_DIR_NAME = "crawl_parse";++ private final static byte CUR_VERSION = 2;++ public static final byte STATUS_DB_UNFETCHED = 1;+ public static final byte STATUS_DB_FETCHED = 2;+ public static final byte STATUS_DB_GONE = 3;+ public static final byte STATUS_LINKED = 4;+ public static final byte STATUS_FETCH_SUCCESS = 5;+ public static final byte STATUS_FETCH_RETRY = 6;+ public static final byte STATUS_FETCH_GONE = 7;++ public static final String[] statNames = {+ "INVALID",+ "DB_unfetched",+ "DB_fetched",+ "DB_gone",+ "linked",+ "fetch_success",+ "fetch_retry",+ "fetch_gone"+ };++ private static final float MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;++ private byte status;+ private long fetchTime = System.currentTimeMillis();+ private byte retries;+ private float fetchInterval;+ private float score = 1.0f;++ public CrawlDatum() {}++ public CrawlDatum(int status, float fetchInterval) {+ this.status = (byte)status;+ this.fetchInterval = fetchInterval;+ }++ public CrawlDatum(int status, float fetchInterval, float score) {+ this(status, fetchInterval);+ this.score = score;+ }++ //+ // accessor methods+ //++ public byte getStatus() { return status; }+ public void setStatus(int status) { this.status = (byte)status; }++ public long getFetchTime() { return fetchTime; }+ public void setFetchTime(long fetchTime) { this.fetchTime = fetchTime; }++ public void setNextFetchTime() {+ fetchTime += (long)(MILLISECONDS_PER_DAY*fetchInterval);+ }++ public byte getRetriesSinceFetch() { return retries; }+ public void setRetriesSinceFetch(int retries) {this.retries = (byte)retries;}++ public float getFetchInterval() { return fetchInterval; }+ public void setFetchInterval(float fetchInterval) {+ this.fetchInterval = fetchInterval;+ }++ public float getScore() { return score; }+ public void setScore(float score) { this.score = score; }++ //+ // writable methods+ //++ public static CrawlDatum read(DataInput in) throws IOException {+ CrawlDatum result = new CrawlDatum();+ result.readFields(in);+ return result;+ }+++ public void readFields(DataInput in) throws IOException {+ byte version = in.readByte(); // read version+ if (version != CUR_VERSION) // check version+ throw new VersionMismatchException(CUR_VERSION, version);++ status = in.readByte();+ fetchTime = in.readLong();+ retries = in.readByte();+ fetchInterval = in.readFloat();+ score = in.readFloat();+ }++ /** The number of bytes into a CrawlDatum that the score is stored. */+ private static final int SCORE_OFFSET = 1 + 1 + 8 + 1 + 4;++ public void write(DataOutput out) throws IOException {+ out.writeByte(CUR_VERSION); // store current version+ out.writeByte(status);+ out.writeLong(fetchTime);+ out.writeByte(retries);+ out.writeFloat(fetchInterval);+ out.writeFloat(score);+ }++ /** Copy the contents of another instance into this instance. */+ public void set(CrawlDatum that) {+ this.status = that.status;+ this.fetchTime = that.fetchTime;+ this.retries = that.retries;+ this.fetchInterval = that.fetchInterval;+ this.score = that.score;+ }+++ //+ // compare methods+ //++ /** Sort by decreasing score. */+ public int compareTo(Object o) {+ CrawlDatum that = (CrawlDatum)o;+ if (that.score != this.score)+ return (that.score - this.score) > 0 ? 1 : -1;+ if (that.status != this.status)+ return this.status - that.status;+ if (that.fetchTime != this.fetchTime)+ return (that.fetchTime - this.fetchTime) > 0 ? 1 : -1;+ if (that.retries != this.retries)+ return that.retries - this.retries;+ if (that.fetchInterval != this.fetchInterval)+ return (that.fetchInterval - this.fetchInterval) > 0 ? 1 : -1;+ return 0;+ }++ /** A Comparator optimized for CrawlDatum. */+ public static class Comparator extends WritableComparator {+ public Comparator() { super(CrawlDatum.class); }++ public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {+ float score1 = readFloat(b1,s1+SCORE_OFFSET);+ float score2 = readFloat(b2,s2+SCORE_OFFSET);+ if (score2 != score1) {+ return (score2 - score1) > 0 ? 1 : -1;+ }+ int status1 = b1[s1+1];+ int status2 = b2[s2+1];+ if (status2 != status1)+ return status1 - status2;+ long fetchTime1 = readLong(b1, s1+1+1);+ long fetchTime2 = readLong(b2, s2+1+1);+ if (fetchTime2 != fetchTime1)+ return (fetchTime2 - fetchTime1) > 0 ? 1 : -1;+ int retries1 = b1[s1+1+1+8];+ int retries2 = b2[s2+1+1+8];+ if (retries2 != retries1)+ return retries2 - retries1;+ float fetchInterval1 = readFloat(b1, s1+1+1+8+1);+ float fetchInterval2 = readFloat(b2, s2+1+1+8+1);+ if (fetchInterval2 != fetchInterval1)+ return (fetchInterval2 - fetchInterval1) > 0 ? 1 : -1;+ return 0;+ }+ }++ static { // register this comparator+ WritableComparator.define(CrawlDatum.class, new Comparator());+ }+++ //+ // basic methods+ //++ public String toString() {+ StringBuffer buf = new StringBuffer();+ buf.append("Version: " + CUR_VERSION + "\n");+ buf.append("Status: " + getStatus() + " (" + statNames[getStatus()] + ")\n");+ buf.append("Fetch time: " + new Date(getFetchTime()) + "\n");+ buf.append("Retries since fetch: " + getRetriesSinceFetch() + "\n");+ buf.append("Retry interval: " + getFetchInterval() + " days\n");+ buf.append("Score: " + getScore() + "\n");+ return buf.toString();+ }++ public boolean equals(Object o) {+ if (!(o instanceof CrawlDatum))+ return false;+ CrawlDatum other = (CrawlDatum)o;+ return+ (this.status == other.status) &&+ (this.fetchTime == other.fetchTime) &&+ (this.retries == other.retries) &&+ (this.fetchInterval == other.fetchInterval) &&+ (this.score == other.score);+ }++ public int hashCode() {+ return+ status ^+ ((int)fetchTime) ^+ retries ^+ Float.floatToIntBits(fetchInterval) ^+ Float.floatToIntBits(score);+ }++ public Object clone() {+ try {+ return super.clone();+ } catch (CloneNotSupportedException e) {+ throw new RuntimeException(e);+ }+ }++}diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.javanew file mode 100644index 000000000..d60663832--- /dev/null+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java@@ -0,0 +1,104 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.parse.*;++/** 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 CrawlDb extends NutchConfigured {++ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.CrawlDb");++ /** Construct an CrawlDb. */+ public CrawlDb(NutchConf conf) {+ super(conf);+ }++ public void update(File crawlDb, File segment) throws IOException {+ LOG.info("CrawlDb update: starting");+ LOG.info("CrawlDb update: db: " + crawlDb);+ LOG.info("CrawlDb update: segment: " + segment);++ JobConf job = CrawlDb.createJob(getConf(), crawlDb);+ job.addInputDir(new File(segment, CrawlDatum.FETCH_DIR_NAME));+ job.addInputDir(new File(segment, CrawlDatum.PARSE_DIR_NAME));++ LOG.info("CrawlDb update: Merging segment data into db.");+ JobClient.runJob(job);++ CrawlDb.install(job, crawlDb);+ LOG.info("CrawlDb update: done");+ }++ public static JobConf createJob(NutchConf config, File crawlDb) {+ File newCrawlDb =+ new File(crawlDb,+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));++ JobConf job = new JobConf(config);++ job.addInputDir(new File(crawlDb, CrawlDatum.DB_DIR_NAME));+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(CrawlDatum.class);++ job.setReducerClass(CrawlDbReducer.class);++ job.setOutputDir(newCrawlDb);+ job.setOutputFormat(MapFileOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(CrawlDatum.class);++ return job;+ }++ public static void install(JobConf job, File crawlDb) throws IOException {+ File newCrawlDb = job.getOutputDir();+ NutchFileSystem fs = new JobClient(job).getFs();+ File old = new File(crawlDb, "old");+ File current = new File(crawlDb, CrawlDatum.DB_DIR_NAME);+ fs.delete(old);+ fs.rename(current, old);+ fs.rename(newCrawlDb, current);+ fs.delete(old);+ }++ public static void main(String[] args) throws Exception {+ CrawlDb crawlDb = new CrawlDb(NutchConf.get());++ if (args.length < 2) {+ System.err.println("Usage: <crawldb> <segment>");+ return;+ }++ crawlDb.update(new File(args[0]), new File(args[1]));+ }++++}diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.javanew file mode 100644index 000000000..58a13a62b--- /dev/null+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java@@ -0,0 +1,273 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.File;+import java.io.IOException;+import java.util.HashMap;+import java.util.Iterator;+import java.util.TreeMap;+import java.util.logging.Logger;++import org.apache.nutch.fs.NutchFileSystem;+import org.apache.nutch.io.FloatWritable;+import org.apache.nutch.io.IntWritable;+import org.apache.nutch.io.LongWritable;+import org.apache.nutch.io.MapFile;+import org.apache.nutch.io.SequenceFile;+import org.apache.nutch.io.UTF8;+import org.apache.nutch.io.Writable;+import org.apache.nutch.io.WritableComparable;+import org.apache.nutch.io.MapFile.Reader;+import org.apache.nutch.mapred.JobClient;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.MapFileOutputFormat;+import org.apache.nutch.mapred.Mapper;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.Reducer;+import org.apache.nutch.mapred.Reporter;+import org.apache.nutch.mapred.SequenceFileInputFormat;+import org.apache.nutch.mapred.SequenceFileOutputFormat;+import org.apache.nutch.mapred.TextOutputFormat;+import org.apache.nutch.mapred.lib.HashPartitioner;+import org.apache.nutch.mapred.lib.LongSumReducer;+import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.util.NutchConf;++/**+ * Read utility for the CrawlDB.+ *+ * @author Andrzej Bialecki+ *+ */+public class CrawlDbReader {++ public static final Logger LOG = LogFormatter.getLogger(CrawlDbReader.class.getName());++ public static class CrawlDbStatMapper implements Mapper {+ public void configure(JobConf job) {}+ public void map(WritableComparable key, Writable value, OutputCollector output, Reporter reporter)+ throws IOException {+ CrawlDatum cd = (CrawlDatum) value;+ output.collect(new UTF8("TOTAL urls"), new LongWritable(1));+ output.collect(new UTF8("status"), new LongWritable(cd.getStatus()));+ output.collect(new UTF8("retry"), new LongWritable(cd.getRetriesSinceFetch()));+ output.collect(new UTF8("score"), new LongWritable((long) (cd.getScore() * 1000.0)));+ }+ }++ public static class CrawlDbStatReducer implements Reducer {+ public void configure(JobConf job) {}+ public void reduce(WritableComparable key, Iterator values, OutputCollector output, Reporter reporter)+ throws IOException {++ String k = ((UTF8) key).toString();+ if (k.equals("TOTAL urls")) {+ // 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.equals("status") || k.equals("retry")) {+ TreeMap stats = new TreeMap();+ while (values.hasNext()) {+ long val = ((LongWritable) values.next()).get();+ LongWritable cnt = (LongWritable) stats.get(k + " " + val);+ if (cnt == null) {+ cnt = new LongWritable();+ stats.put(k + " " + val, cnt);+ }+ cnt.set(cnt.get() + 1);+ }+ Iterator it = stats.keySet().iterator();+ while (it.hasNext()) {+ String s = (String) it.next();+ output.collect(new UTF8(s), (LongWritable) stats.get(s));+ }+ } else if (k.equals("score")) {+ long min = 0, max = 0, avg = 0, total = 0;+ int cnt = 0;+ boolean first = true;+ while (values.hasNext()) {+ long val = ((LongWritable) values.next()).get();+ if (first) {+ min = val;+ max = val;+ first = false;+ }+ if (val < min) min = val;+ if (val > max) max = val;+ total += val;+ cnt++;+ }+ output.collect(new UTF8("max score"), new LongWritable(max));+ output.collect(new UTF8("min score"), new LongWritable(min));+ output.collect(new UTF8("avg score"), new LongWritable(total / cnt));+ }+ }+ }++ public static class CrawlDbDumpReducer implements Reducer {++ public void reduce(WritableComparable key, Iterator values, OutputCollector output, Reporter reporter) throws IOException {+ while (values.hasNext()) {+ output.collect(key, (Writable)values.next());+ }+ }++ public void configure(JobConf job) {+ }+ }++ public void processStatJob(String crawlDb, NutchConf config) throws IOException {+ LOG.info("CrawlDb statistics start: " + crawlDb);+ File tmpFolder = new File(crawlDb, "stat_tmp" + System.currentTimeMillis());++ JobConf job = new JobConf(config);++ job.addInputDir(new File(crawlDb, CrawlDatum.DB_DIR_NAME));+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(CrawlDatum.class);++ job.setMapperClass(CrawlDbStatMapper.class);+ job.setReducerClass(CrawlDbStatReducer.class);++ job.setOutputDir(tmpFolder);+ job.setOutputFormat(SequenceFileOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(LongWritable.class);++ JobClient.runJob(job);++ // reading the result+ NutchFileSystem fileSystem = NutchFileSystem.get();+ SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(fileSystem, tmpFolder);++ UTF8 key = new UTF8();+ LongWritable value = new LongWritable();++ TreeMap stats = new TreeMap();+ int avg = 0, min = 0, max = 0;+ for (int i = 0; i < readers.length; i++) {+ SequenceFile.Reader reader = readers[i];+ while (reader.next(key, value)) {+ String k = key.toString();+ LongWritable val = (LongWritable) stats.get(k);+ if (val == null) {+ val = new LongWritable();+ stats.put(k, val);+ }+ val.set(val.get() + value.get());+ if (k.startsWith("max"))+ max++;+ else if (k.startsWith("min"))+ min++;+ else if (k.startsWith("avg")) avg++;+ }+ }+ LOG.info("Statistics for CrawlDb: " + crawlDb);+ Iterator it = stats.keySet().iterator();+ while (it.hasNext()) {+ String k = (String) it.next();+ LongWritable val = (LongWritable) stats.get(k);+ if (k.indexOf("score") != -1) {+ if (k.startsWith("min")) {+ LOG.info(k + ":\t" + (float) ((float) (val.get() / min) / 1000.0f));+ } else if (k.startsWith("max")) {+ LOG.info(k + ":\t" + (float) ((float) (val.get() / max) / 1000.0f));+ } else if (k.startsWith("avg")) {+ LOG.info(k + ":\t" + (float) ((float) (val.get() / avg) / 1000.0f));+ }+ } else if (k.startsWith("status")) {+ int code = Integer.parseInt(k.substring(k.indexOf(' ') + 1));+ LOG.info(k + " (" + CrawlDatum.statNames[code] + "):\t" + val);+ } else LOG.info(k + ":\t" + val);+ }+ // removing the tmp folder+ fileSystem.delete(tmpFolder);+ LOG.info("CrawlDb statistics: done");++ }++ public void readUrl(String crawlDb, String url, NutchConf config) throws IOException {+ NutchFileSystem fs = NutchFileSystem.get(config);+ UTF8 key = new UTF8(url);+ CrawlDatum val = new CrawlDatum();+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new File(crawlDb, CrawlDatum.DB_DIR_NAME));+ Writable res = MapFileOutputFormat.getEntry(readers, new HashPartitioner(), key, val);+ System.out.println("URL: " + url);+ if (res != null) {+ System.out.println(val);+ } else {+ System.out.println("not found");+ }+ }++ public void processDumpJob(String crawlDb, String output, NutchConf config) throws IOException {++ LOG.info("CrawlDb dump: starting");+ LOG.info("CrawlDb db: " + crawlDb);+ File outFolder = new File(output);++ JobConf job = new JobConf(config);++ job.addInputDir(new File(crawlDb, CrawlDatum.DB_DIR_NAME));+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(CrawlDatum.class);++ job.setOutputDir(outFolder);+ job.setOutputFormat(TextOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(CrawlDatum.class);++ JobClient.runJob(job);+ }++ 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> | -url <url>)");+ System.err.println("\t<crawldb>\tdirectory name where crawldb is located");+ System.err.println("\t-stats\tprint overall statistics to System.out");+ System.err.println("\t-dump <out_dir>\tdump the whole db to a text file in <out_dir>");+ System.err.println("\t-url <url>\tprint information on <url> to System.out");+ return;+ }+ String param = null;+ String crawlDb = args[0];+ NutchConf conf = NutchConf.get();+ for (int i = 1; i < args.length; i++) {+ if (args[i].equals("-stats")) {+ dbr.processStatJob(crawlDb, conf);+ } else if (args[i].equals("-dump")) {+ param = args[++i];+ dbr.processDumpJob(crawlDb, param, conf);+ } else if (args[i].equals("-url")) {+ param = args[++i];+ dbr.readUrl(crawlDb, 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.javanew file mode 100644index 000000000..dd3bd2640--- /dev/null+++ b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java@@ -0,0 +1,111 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.Iterator;+import java.io.IOException;++import org.apache.nutch.io.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;++/** Merge new page entries with existing entries. */+public class CrawlDbReducer implements Reducer {+ private int retryMax;++ public void configure(JobConf job) {+ retryMax = job.getInt("db.fetch.retry.max", 3);+ }++ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {++ CrawlDatum highest = null;+ CrawlDatum old = null;+ float scoreIncrement = 0.0f;++ while (values.hasNext()) {+ CrawlDatum datum = (CrawlDatum)values.next();++ if (highest == null || datum.getStatus() > highest.getStatus()) {+ highest = datum; // find highest status+ }++ switch (datum.getStatus()) { // find old entry, if any+ case CrawlDatum.STATUS_DB_UNFETCHED:+ case CrawlDatum.STATUS_DB_FETCHED:+ old = datum;+ break;+ case CrawlDatum.STATUS_LINKED:+ scoreIncrement += datum.getScore();+ break;+ }+ }++ CrawlDatum result = null;++ switch (highest.getStatus()) { // determine new status++ case CrawlDatum.STATUS_DB_UNFETCHED: // no new entry+ case CrawlDatum.STATUS_DB_FETCHED:+ case CrawlDatum.STATUS_DB_GONE:+ result = old; // use old+ break;++ case CrawlDatum.STATUS_LINKED: // highest was link+ if (old != null) { // if old exists+ result = old; // use it+ } else {+ result = highest; // use new entry+ result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);+ result.setScore(1.0f); // initial score is 1.0f+ }+ break;++ case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch+ result = highest; // use new entry+ result.setStatus(CrawlDatum.STATUS_DB_FETCHED);+ result.setNextFetchTime();+ break;++ case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure+ result = highest; // use new entry+ if (highest.getRetriesSinceFetch() < retryMax) {+ result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);+ } else {+ result.setStatus(CrawlDatum.STATUS_DB_GONE);+ }+ break;++ case CrawlDatum.STATUS_FETCH_GONE: // permanent failure+ result = highest; // use new entry+ result.setStatus(CrawlDatum.STATUS_DB_GONE);+ break;++ default:+ throw new RuntimeException("Unknown status: "+highest.getStatus());+ }++ if (result != null) {+ result.setScore(result.getScore() + scoreIncrement);+ output.collect(key, result);+ }+ }++}diff --git a/src/java/org/apache/nutch/crawl/DeleteDuplicates.java b/src/java/org/apache/nutch/crawl/DeleteDuplicates.javanew file mode 100644index 000000000..ac3978f8f--- /dev/null+++ b/src/java/org/apache/nutch/crawl/DeleteDuplicates.java@@ -0,0 +1,352 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.security.*;+import java.text.*;+import java.util.*;+import java.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.indexer.*;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.document.Document;++/******************************************************************+ * Deletes duplicate documents in a set of Lucene indexes.+ * Duplicates have either the same contents (via MD5 hash) or the same URL.+ ******************************************************************/+public class DeleteDuplicates extends NutchConfigured+ implements Mapper, Reducer, OutputFormat {+ private static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.DeleteDuplicates");++// Algorithm:+//+// 1. map indexes -> <<md5, score, urlLen>, <index,doc>>+// partition by md5+// reduce, deleting all but largest score w/ shortest url+//+// 2. map indexes -> <<url, fetchdate>, <index,doc>>+// partition by url+// reduce, deleting all but most recent.+//+// Part 2 is not yet implemented, but the Indexer currently only indexes one+// URL per page, so this is not a critical problem.++ public static class IndexDoc implements WritableComparable {+ private UTF8 index; // the segment index+ private int doc; // within the index++ public void write(DataOutput out) throws IOException {+ index.write(out);+ out.writeInt(doc);+ }++ public void readFields(DataInput in) throws IOException {+ if (index == null) {+ index = new UTF8();+ }+ index.readFields(in);+ this.doc = in.readInt();+ }++ public int compareTo(Object o) {+ IndexDoc that = (IndexDoc)o;+ int indexCompare = this.index.compareTo(that.index);+ if (indexCompare != 0) { // prefer later indexes+ return indexCompare;+ } else {+ return this.doc - that.doc; // prefer later docs+ }+ }++ public boolean equals(Object o) {+ IndexDoc that = (IndexDoc)o;+ return this.index.equals(that.index) && this.doc == that.doc;+ }++ }++ public static class HashScore implements WritableComparable {+ private MD5Hash hash;+ private float score;+ private int urlLen;++ public void write(DataOutput out) throws IOException {+ hash.write(out);+ out.writeFloat(score);+ out.writeInt(urlLen);+ }++ public void readFields(DataInput in) throws IOException {+ if (hash == null) {+ hash = new MD5Hash();+ }+ hash.readFields(in);+ score = in.readFloat();+ urlLen = in.readInt();+ }++ public int compareTo(Object o) {+ HashScore that = (HashScore)o;+ if (!this.hash.equals(that.hash)) { // order first by hash+ return this.hash.compareTo(that.hash);+ } else if (this.score != that.score) { // prefer larger scores+ return this.score < that.score ? 1 : -1 ;+ } else { // prefer shorter urls+ return this.urlLen - that.urlLen;+ }+ }++ public boolean equals(Object o) {+ HashScore that = (HashScore)o;+ return this.hash.equals(that.hash)+ && this.score == that.score+ && this.urlLen == that.urlLen;+ }+ }++ public static class InputFormat extends InputFormatBase {+ private static final long INDEX_LENGTH = Integer.MAX_VALUE;++ /** Return each index as a split. */+ public FileSplit[] getSplits(NutchFileSystem fs, JobConf job,+ int numSplits)+ throws IOException {+ File[] files = listFiles(fs, job);+ FileSplit[] splits = new FileSplit[files.length];+ for (int i = 0; i < files.length; i++) {+ splits[i] = new FileSplit(files[i], 0, INDEX_LENGTH);+ }+ return splits;+ }++ /** Return each index as a split. */+ public RecordReader getRecordReader(final NutchFileSystem fs,+ final FileSplit split,+ final JobConf job,+ Reporter reporter) throws IOException {+ final UTF8 index = new UTF8(split.getFile().toString());+ reporter.setStatus(index.toString());+ return new RecordReader() {++ private IndexReader indexReader =+ IndexReader.open(new NdfsDirectory(fs, split.getFile(), false));++ { indexReader.undeleteAll(); }++ private final int maxDoc = indexReader.maxDoc();+ private int doc;++ public boolean next(Writable key, Writable value)+ throws IOException {++ if (doc >= maxDoc)+ return false;++ Document document = indexReader.document(doc);++ // fill in key+ if (key instanceof UTF8) {+ ((UTF8)key).set(document.get("url"));+ } else {+ HashScore hashScore = (HashScore)key;+ if (hashScore.hash == null) {+ hashScore.hash = new MD5Hash();+ }+ hashScore.hash.setDigest(document.get("digest"));+ hashScore.score = Float.parseFloat(document.get("boost"));+ hashScore.urlLen = document.get("url").length();+ }++ // fill in value+ IndexDoc indexDoc = (IndexDoc)value;+ if (indexDoc.index == null) {+ indexDoc.index = new UTF8();+ }+ indexDoc.index.set(index);+ indexDoc.doc = doc;++ doc++;++ return true;+ }++ public long getPos() throws IOException {+ return (doc*INDEX_LENGTH)/maxDoc;+ }++ public void close() throws IOException {+ indexReader.close();+ }+ };+ }+ }++ public static class HashPartitioner implements Partitioner {+ public void configure(JobConf job) {}+ public int getPartition(WritableComparable key, Writable value,+ int numReduceTasks) {+ int hashCode = ((HashScore)key).hash.hashCode();+ return (hashCode & Integer.MAX_VALUE) % numReduceTasks;+ }+ }++ public static class HashReducer implements Reducer {+ private MD5Hash prevHash = new MD5Hash();+ public void configure(JobConf job) {}+ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ MD5Hash hash = ((HashScore)key).hash;+ while (values.hasNext()) {+ Writable value = (Writable)values.next();+ if (hash.equals(prevHash)) { // collect all but first+ output.collect(key, value);+ } else {+ prevHash.set(hash);+ }+ }+ }+ }++ private NutchFileSystem fs;++ public DeleteDuplicates() { super(null); }++ public DeleteDuplicates(NutchConf conf) { super(conf); }++ public void configure(JobConf job) {+ try {+ fs = NutchFileSystem.get(job);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ /** Map [*,IndexDoc] pairs to [index,doc] pairs. */+ public void map(WritableComparable key, Writable value,+ OutputCollector output, Reporter reporter)+ throws IOException {+ IndexDoc indexDoc = (IndexDoc)value;+ output.collect(indexDoc.index, new IntWritable(indexDoc.doc));+ }++ /** Delete docs named in values from index named in key. */+ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ File index = new File(key.toString());+ IndexReader reader = IndexReader.open(new NdfsDirectory(fs, index, false));+ try {+ while (values.hasNext()) {+ reader.delete(((IntWritable)values.next()).get());+ }+ } finally {+ reader.close();+ }+ }++ /** Write nothing. */+ public RecordWriter getRecordWriter(final NutchFileSystem fs,+ final JobConf job,+ final String name) throws IOException {+ return new RecordWriter() {+ public void write(WritableComparable key, Writable value)+ throws IOException {+ throw new UnsupportedOperationException();+ }+ public void close(Reporter reporter) throws IOException {}+ };+ }++ public void dedup(File[] indexDirs)+ throws IOException {++ LOG.info("Dedup: starting");++ File hashDir =+ new File("dedup-hash-"++ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));++ JobConf job = new JobConf(getConf());++ for (int i = 0; i < indexDirs.length; i++) {+ LOG.info("Dedup: adding indexes in: " + indexDirs[i]);+ job.addInputDir(indexDirs[i]);+ }++ job.setInputKeyClass(HashScore.class);+ job.setInputValueClass(IndexDoc.class);+ job.setInputFormat(InputFormat.class);++ job.setPartitionerClass(HashPartitioner.class);+ job.setReducerClass(HashReducer.class);++ job.setOutputDir(hashDir);++ job.setOutputKeyClass(HashScore.class);+ job.setOutputValueClass(IndexDoc.class);+ job.setOutputFormat(SequenceFileOutputFormat.class);++ JobClient.runJob(job);++ job = new JobConf(getConf());++ job.addInputDir(hashDir);++ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(HashScore.class);+ job.setInputValueClass(IndexDoc.class);++ job.setMapperClass(DeleteDuplicates.class);+ job.setReducerClass(DeleteDuplicates.class);++ job.setOutputFormat(DeleteDuplicates.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(IntWritable.class);++ JobClient.runJob(job);++ new JobClient(getConf()).getFs().delete(hashDir);++ LOG.info("Dedup: done");+ }++ public static void main(String[] args) throws Exception {+ DeleteDuplicates dedup = new DeleteDuplicates(NutchConf.get());++ if (args.length < 1) {+ System.err.println("Usage: <indexes> ...");+ return;+ }++ File[] indexes = new File[args.length];+ for (int i = 0; i < args.length; i++) {+ indexes[i] = new File(args[i]);+ }++ dedup.dedup(indexes);+ }++}diff --git a/src/java/org/apache/nutch/crawl/DmozParser.java b/src/java/org/apache/nutch/crawl/DmozParser.javanew file mode 100644index 000000000..bd804a5c2--- /dev/null+++ b/src/java/org/apache/nutch/crawl/DmozParser.java@@ -0,0 +1,384 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;+import java.net.MalformedURLException;+import java.util.regex.*;++import javax.xml.parsers.*;+import org.xml.sax.*;+import org.xml.sax.helpers.*;+import org.apache.xerces.util.XMLChar;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;+import org.apache.nutch.util.*;+import org.apache.nutch.util.NutchConf;++/** Utility that converts DMOZ RDF into a flat file of URLs to be injected. */+public class DmozParser {+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.crawl.DmozParser");++ long pages = 0;++ /**+ * This filter fixes characters that might offend our parser.+ * This lets us be tolerant of errors that might appear in the input XML.+ */+ private static class XMLCharFilter extends FilterReader {+ private boolean lastBad = false;++ public XMLCharFilter(Reader reader) {+ super(reader);+ }++ public int read() throws IOException {+ int c = in.read();+ int value = c;+ if (c != -1 && !(XMLChar.isValid(c))) // fix invalid characters+ value = 'X';+ else if (lastBad && c == '<') { // fix mis-matched brackets+ in.mark(1);+ if (in.read() != '/')+ value = 'X';+ in.reset();+ }+ lastBad = (c == 65533);++ return value;+ }++ public int read(char[] cbuf, int off, int len)+ throws IOException {+ int n = in.read(cbuf, off, len);+ if (n != -1) {+ for (int i = 0; i < n; i++) {+ char c = cbuf[off+i];+ char value = c;+ if (!(XMLChar.isValid(c))) // fix invalid characters+ value = 'X';+ else if (lastBad && c == '<') { // fix mis-matched brackets+ if (i != n-1 && cbuf[off+i+1] != '/')+ value = 'X';+ }+ lastBad = (c == 65533);+ cbuf[off+i] = value;+ }+ }+ return n;+ }+ }+++ /**+ * The RDFProcessor receives tag messages during a parse+ * of RDF XML data. We build whatever structures we need+ * from these messages.+ */+ private class RDFProcessor extends DefaultHandler {+ String curURL = null, curSection = null;+ boolean titlePending = false, descPending = false, insideAdultSection = false;+ Pattern topicPattern = null;+ StringBuffer title = new StringBuffer(), desc = new StringBuffer();+ XMLReader reader;+ int subsetDenom;+ int hashSkew;+ boolean includeAdult;+ Locator location;++ /**+ * Pass in an XMLReader, plus a flag as to whether we+ * should include adult material.+ */+ public RDFProcessor(XMLReader reader, int subsetDenom, boolean includeAdult, int skew, Pattern topicPattern) throws IOException {+ this.reader = reader;+ this.subsetDenom = subsetDenom;+ this.includeAdult = includeAdult;+ this.topicPattern = topicPattern;++ this.hashSkew = skew != 0 ? skew : new Random().nextInt();+ }++ //+ // Interface ContentHandler+ //++ /**+ * Start of an XML elt+ */+ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {+ if ("Topic".equals(qName)) {+ curSection = atts.getValue("r:id");+ } else if ("ExternalPage".equals(qName)) {+ // Porn filter+ if ((! includeAdult) && curSection.startsWith("Top/Adult")) {+ return;+ }++ if (topicPattern != null && !topicPattern.matcher(curSection).matches()) {+ return;+ }++ // Subset denominator filter.+ // Only emit with a chance of 1/denominator.+ String url = atts.getValue("about");+ int hashValue = MD5Hash.digest(url).hashCode();+ hashValue = Math.abs(hashValue ^ hashSkew);+ if ((hashValue % subsetDenom) != 0) {+ return;+ }++ // We actually claim the URL!+ curURL = url;+ } else if (curURL != null && "d:Title".equals(qName)) {+ titlePending = true;+ } else if (curURL != null && "d:Description".equals(qName)) {+ descPending = true;+ }+ }++ /**+ * The contents of an XML elt+ */+ public void characters(char ch[], int start, int length) {+ if (titlePending) {+ title.append(ch, start, length);+ } else if (descPending) {+ desc.append(ch, start, length);+ }+ }++ /**+ * Termination of XML elt+ */+ public void endElement(String namespaceURI, String localName, String qName)+ throws SAXException {+ if (curURL != null) {+ if ("ExternalPage".equals(qName)) {+ //+ // Inc the number of pages, insert the page, and+ // possibly print status.+ //+ System.out.println(curURL);+ pages++;++ //+ // Clear out the link text. This is what+ // you would use for adding to the linkdb.+ //+ if (title.length() > 0) {+ title.delete(0, title.length());+ }+ if (desc.length() > 0) {+ desc.delete(0, desc.length());+ }++ // Null out the URL.+ curURL = null;+ } else if ("d:Title".equals(qName)) {+ titlePending = false;+ } else if ("d:Description".equals(qName)) {+ descPending = false;+ }+ }+ }++ /**+ * When parsing begins+ */+ public void startDocument() {+ LOG.info("Begin parse");+ }++ /**+ * When parsing ends+ */+ public void endDocument() {+ LOG.info("Completed parse. Found " + pages + " pages.");+ }++ /**+ * From time to time the Parser will set the "current location"+ * by calling this function. It's useful for emitting locations+ * for error messages.+ */+ public void setDocumentLocator(Locator locator) {+ location = locator;+ }+++ //+ // Interface ErrorHandler+ //++ /**+ * Emit the exception message+ */+ public void error(SAXParseException spe) {+ LOG.severe("Error: " + spe.toString() + ": " + spe.getMessage());+ spe.printStackTrace(System.err);+ }++ /**+ * Emit the exception message, with line numbers+ */+ public void fatalError(SAXParseException spe) {+ LOG.severe("Fatal err: " + spe.toString() + ": " + spe.getMessage());+ LOG.severe("Last known line is " + location.getLineNumber() + ", column " + location.getColumnNumber());+ spe.printStackTrace(System.err);+ }++ /**+ * Emit exception warning message+ */+ public void warning(SAXParseException spe) {+ LOG.warning("Warning: " + spe.toString() + ": " + spe.getMessage());+ spe.printStackTrace(System.err);+ }+ }++ /**+ * Iterate through all the items in this structured DMOZ file.+ * Add each URL to the web db.+ */+ public void parseDmozFile(File dmozFile, int subsetDenom,+ boolean includeAdult,+ int skew,+ Pattern topicPattern)++ throws IOException, SAXException, ParserConfigurationException {++ SAXParserFactory parserFactory = SAXParserFactory.newInstance();+ SAXParser parser = parserFactory.newSAXParser();+ XMLReader reader = parser.getXMLReader();++ // Create our own processor to receive SAX events+ RDFProcessor rp =+ new RDFProcessor(reader, subsetDenom, includeAdult,+ skew, topicPattern);+ reader.setContentHandler(rp);+ reader.setErrorHandler(rp);+ LOG.info("skew = " + rp.hashSkew);++ //+ // Open filtered text stream. The UTF8Filter makes sure that+ // only appropriate XML-approved UTF8 characters are received.+ // Any non-conforming characters are silently skipped.+ //+ XMLCharFilter in = new XMLCharFilter(new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(dmozFile)), "UTF-8")));+ try {+ InputSource is = new InputSource(in);+ reader.parse(is);+ } catch (Exception e) {+ LOG.severe(e.toString());+ e.printStackTrace(System.err);+ System.exit(0);+ } finally {+ in.close();+ }+ }++ private static void addTopicsFromFile(String topicFile, Vector topics)+ throws IOException {+ BufferedReader in = null;+ try {+ in = new BufferedReader(new InputStreamReader(new FileInputStream(topicFile), "UTF-8"));+ String line = null;+ while ((line = in.readLine()) != null) {+ topics.addElement(new String(line));+ }+ }+ catch (Exception e) {+ LOG.severe(e.toString());+ e.printStackTrace(System.out);+ System.exit(0);+ } finally {+ in.close();+ }+ }++ /**+ * Command-line access. User may add URLs via a flat text file+ * or the structured DMOZ file. By default, we ignore Adult+ * material (as categorized by DMOZ).+ */+ public static void main(String argv[]) throws Exception {+ if (argv.length < 1) {+ System.err.println("Usage: DmozParser <dmoz_file> [-subset <subsetDenominator>] [-includeAdultMaterial] [-skew skew] [-topicFile <topic list file>] [-topic <topic> [-topic <topic> [...]]]");+ return;+ }++ //+ // Parse the command line, figure out what kind of+ // URL file we need to load+ //+ int subsetDenom = 1;+ int skew = 0;+ String dmozFile = argv[0];+ boolean includeAdult = false;+ Pattern topicPattern = null;+ Vector topics = new Vector();++ NutchFileSystem nfs = NutchFileSystem.get();+ try {+ for (int i = 1; i < argv.length; i++) {+ if ("-includeAdultMaterial".equals(argv[i])) {+ includeAdult = true;+ } else if ("-subset".equals(argv[i])) {+ subsetDenom = Integer.parseInt(argv[i+1]);+ i++;+ } else if ("-topic".equals(argv[i])) {+ topics.addElement(argv[i+1]);+ i++;+ } else if ("-topicFile".equals(argv[i])) {+ addTopicsFromFile(argv[i+1], topics);+ i++;+ } else if ("-skew".equals(argv[i])) {+ skew = Integer.parseInt(argv[i+1]);+ i++;+ }+ }++ DmozParser parser = new DmozParser();++ if (!topics.isEmpty()) {+ String regExp = new String("^(");+ int j = 0;+ for ( ; j < topics.size() - 1; ++j) {+ regExp = regExp.concat((String) topics.get(j));+ regExp = regExp.concat("|");+ }+ regExp = regExp.concat((String) topics.get(j));+ regExp = regExp.concat(").*");+ LOG.info("Topic selection pattern = " + regExp);+ topicPattern = Pattern.compile(regExp);+ }++ parser.parseDmozFile(new File(dmozFile), subsetDenom,+ includeAdult, skew, topicPattern);++ } finally {+ nfs.close();+ }+ }++}diff --git a/src/java/org/apache/nutch/crawl/Fetcher.java b/src/java/org/apache/nutch/crawl/Fetcher.javanew file mode 100644index 000000000..7641427e5--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Fetcher.java@@ -0,0 +1,367 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io.File;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;+import org.apache.nutch.util.*;+import org.apache.nutch.protocol.*;+import org.apache.nutch.parse.*;+import org.apache.nutch.mapred.*;++import java.util.logging.*;++/** The fetcher. Most of the work is done by plugins. */+public class Fetcher extends NutchConfigured implements MapRunnable {++ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.fetcher.Fetcher");++ public static final String DIGEST_KEY = "nutch.content.digest";+ public static final String SEGMENT_NAME_KEY = "nutch.segment.name";+ public static final String SCORE_KEY = "nutch.crawl.score";++ public static class InputFormat extends SequenceFileInputFormat {+ /** Don't split inputs, to keep things polite. */+ public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int nSplits)+ throws IOException {+ File[] files = listFiles(fs, job);+ FileSplit[] splits = new FileSplit[files.length];+ for (int i = 0; i < files.length; i++) {+ splits[i] = new FileSplit(files[i], 0, fs.getLength(files[i]));+ }+ return splits;+ }+ }++ private RecordReader input;+ private OutputCollector 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 {+ public FetcherThread() {+ this.setDaemon(true); // don't hang JVM on exit+ this.setName("FetcherThread"); // use an informative name+ }++ public void run() {+ synchronized (Fetcher.this) {activeThreads++;} // count threads++ try {+ UTF8 key = new UTF8();+ CrawlDatum datum = new CrawlDatum();++ while (true) {+ if (LogFormatter.hasLoggedSevere()) // something bad happened+ break; // exit++ try { // get next entry from input+ if (!input.next(key, datum)) {+ break; // at eof, exit+ }+ } catch (IOException e) {+ LOG.severe("fetcher caught:"+e.toString());+ break;+ }++ synchronized (Fetcher.this) {+ lastRequestStart = System.currentTimeMillis();+ }++ String url = key.toString();+ try {+ LOG.info("fetching " + url); // fetch the page++ boolean redirecting;+ int redirectCount = 0;+ do {+ redirecting = false;+ LOG.fine("redirectCount=" + redirectCount);+ Protocol protocol = ProtocolFactory.getProtocol(url);+ ProtocolOutput output = protocol.getProtocolOutput(url);+ ProtocolStatus status = output.getStatus();+ Content content = output.getContent();++ switch(status.getCode()) {++ case ProtocolStatus.SUCCESS: // got a page+ output(key, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS);+ updateStatus(content.getContent().length);+ break;++ case ProtocolStatus.MOVED: // redirect+ case ProtocolStatus.TEMP_MOVED:+ String newUrl = status.getMessage();+ newUrl = URLFilters.filter(newUrl);+ if (newUrl != null && !newUrl.equals(url)) {+ url = newUrl;+ redirecting = true;+ redirectCount++;+ LOG.fine(" - redirect to " + url);+ } else {+ LOG.fine(" - redirect skipped: " ++ (url.equals(newUrl) ? "to same url" : "filtered"));+ }+ break;++ case ProtocolStatus.EXCEPTION:+ logError(url, status.getMessage());+ case ProtocolStatus.RETRY: // retry+ datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1);+ output(key, datum, null, CrawlDatum.STATUS_FETCH_RETRY);+ break;++ case ProtocolStatus.GONE: // gone+ case ProtocolStatus.NOTFOUND:+ case ProtocolStatus.ACCESS_DENIED:+ case ProtocolStatus.ROBOTS_DENIED:+ case ProtocolStatus.NOTMODIFIED:+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);+ break;++ default:+ LOG.warning("Unknown ProtocolStatus: " + status.getCode());+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);+ }++ if (redirecting && redirectCount >= maxRedirect) {+ LOG.info(" - redirect count exceeded " + url);+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);+ }++ } while (redirecting && (redirectCount < maxRedirect));+++ } catch (Throwable t) { // unexpected exception+ logError(url, t.toString());+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);++ }+ }++ } catch (Throwable e) {+ LOG.severe("fetcher caught:"+e.toString());+ } finally {+ synchronized (Fetcher.this) {activeThreads--;} // count threads+ }+ }++ private void logError(String url, String message) {+ LOG.info("fetch of " + url + " failed with: " + message);+ synchronized (Fetcher.this) { // record failure+ errors++;+ }+ }++ private void output(UTF8 key, CrawlDatum datum,+ Content content, int status) {++ datum.setStatus(status);++ if (content == null) {+ String url = key.toString();+ content = new Content(url,url,new byte[0],"",new ContentProperties());+ }++ content.getMetadata().setProperty // add digest to metadata+ (DIGEST_KEY, MD5Hash.digest(content.getContent()).toString());+ content.getMetadata().setProperty // add segment to metadata+ (SEGMENT_NAME_KEY, segmentName);+ content.getMetadata().setProperty // add score to metadata+ (SCORE_KEY, Float.toString(datum.getScore()));++ Parse parse = null;+ if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {+ ParseStatus parseStatus;+ try {+ parse = ParseUtil.parse(content);+ parseStatus = parse.getData().getStatus();+ } catch (Exception e) {+ parseStatus = new ParseStatus(e);+ }+ if (!parseStatus.isSuccess()) {+ LOG.warning("Error parsing: "+key+": "+parseStatus);+ parse = null;+ }+ }++ try {+ output.collect+ (key,+ new FetcherOutput(datum,+ storingContent ? content : null,+ parse != null ? new ParseImpl(parse) : null));+ } catch (IOException e) {+ LOG.severe("fetcher caught:"+e.toString());+ }+ }++ }++ public Fetcher() { super(null); }++ public Fetcher(NutchConf conf) { super(conf); }++ 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 void configure(JobConf job) {+ setConf(job);++ this.segmentName = job.get(SEGMENT_NAME_KEY);+ this.storingContent = isStoringContent(job);+ this.parsing = isParsing(job);++ if (job.getBoolean("fetcher.verbose", false)) {+ LOG.setLevel(Level.FINE);+ }+ }++ public static boolean isParsing(NutchConf conf) {+ return conf.getBoolean("fetcher.parse", true);+ }++ public static boolean isStoringContent(NutchConf conf) {+ return conf.getBoolean("fetcher.store.content", true);+ }++ public void run(RecordReader input, OutputCollector 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);+ LOG.info("Fetcher: threads: " + threadCount);++ for (int i = 0; i < threadCount; i++) { // spawn threads+ new FetcherThread().start();+ }++ // select a timeout that avoids a task timeout+ long timeout = NutchConf.get().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) {+ LOG.warning("Aborting with "+activeThreads+" hung threads.");+ return;+ }+ }++ } while (activeThreads > 0);++ }++ public void fetch(File segment, int threads)+ throws IOException {++ LOG.info("Fetcher: starting");+ LOG.info("Fetcher: segment: " + segment);++ JobConf job = new JobConf(getConf());++ job.setInt("fetcher.threads.fetch", threads);+ job.set(SEGMENT_NAME_KEY, segment.getName());++ job.setInputDir(new File(segment, CrawlDatum.GENERATE_DIR_NAME));+ job.setInputFormat(InputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(CrawlDatum.class);++ job.setMapRunnerClass(Fetcher.class);++ job.setOutputDir(segment);+ job.setOutputFormat(FetcherOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(FetcherOutput.class);++ JobClient.runJob(job);+ LOG.info("Fetcher: done");+ }+++ /** Run the fetcher. */+ public static void main(String[] args) throws Exception {++ String usage = "Usage: Fetcher <segment> [-threads n]";++ if (args.length < 1) {+ System.err.println(usage);+ System.exit(-1);+ }++ File segment = new File(args[0]);++ NutchConf conf = NutchConf.get();++ int threads = conf.getInt("fetcher.threads.fetch", 10);++ for (int i = 1; i < args.length; i++) { // parse command line+ if (args[i].equals("-threads")) { // found -threads option+ threads = Integer.parseInt(args[++i]);+ }+ }++ Fetcher fetcher = new Fetcher(conf); // make a Fetcher++ fetcher.fetch(segment, threads); // run the Fetcher++ }+}diff --git a/src/java/org/apache/nutch/crawl/FetcherOutput.java b/src/java/org/apache/nutch/crawl/FetcherOutput.javanew file mode 100644index 000000000..295d8c014--- /dev/null+++ b/src/java/org/apache/nutch/crawl/FetcherOutput.java@@ -0,0 +1,81 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.util.*;+import org.apache.nutch.protocol.Content;+import org.apache.nutch.parse.*;++/* 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();+ }++}diff --git a/src/java/org/apache/nutch/crawl/FetcherOutputFormat.java b/src/java/org/apache/nutch/crawl/FetcherOutputFormat.javanew file mode 100644index 000000000..5951dbf5d--- /dev/null+++ b/src/java/org/apache/nutch/crawl/FetcherOutputFormat.java@@ -0,0 +1,97 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io.File;++import org.apache.nutch.fs.NutchFileSystem;++import org.apache.nutch.io.MapFile;+import org.apache.nutch.io.WritableComparable;+import org.apache.nutch.io.Writable;+import org.apache.nutch.io.UTF8;++import org.apache.nutch.mapred.OutputFormat;+import org.apache.nutch.mapred.RecordWriter;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;++import org.apache.nutch.protocol.Content;++/** Splits FetcherOutput entries into multiple map files. */+public class FetcherOutputFormat implements OutputFormat {++ public RecordWriter getRecordWriter(final NutchFileSystem fs,+ final JobConf job,+ final String name) throws IOException {++ final File fetch =+ new File(new File(job.getOutputDir(), CrawlDatum.FETCH_DIR_NAME), name);+ final File content =+ new File(new File(job.getOutputDir(), Content.DIR_NAME), name);++ final MapFile.Writer fetchOut =+ new MapFile.Writer(fs, fetch.toString(), UTF8.class, CrawlDatum.class);++ return new RecordWriter() {+ private MapFile.Writer contentOut;+ private RecordWriter parseOut;++ {+ if (Fetcher.isStoringContent(job)) {+ contentOut = new MapFile.Writer(fs, content.toString(),+ UTF8.class, Content.class);+ }++ if (Fetcher.isParsing(job)) {+ parseOut = new ParseOutputFormat().getRecordWriter(fs, job, name);+ }+ }++ public void write(WritableComparable key, Writable value)+ throws IOException {++ FetcherOutput fo = (FetcherOutput)value;++ fetchOut.append(key, fo.getCrawlDatum());++ if (fo.getContent() != null) {+ contentOut.append(key, fo.getContent());+ }++ if (fo.getParse() != null) {+ parseOut.write(key, fo.getParse());+ }++ }++ 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/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.javanew file mode 100644index 000000000..0a20198db--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Generator.java@@ -0,0 +1,265 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.mapred.lib.*;++/** Generates a subset of a crawl db to fetch. */+public class Generator extends NutchConfigured {++ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.Generator");++ /** Selects entries due for fetch. */+ public static class Selector implements Mapper, Partitioner, Reducer {+ private long curTime;+ private long limit;+ private long count;+ private HashMap hostCounts = new HashMap();+ private int maxPerHost;+ private Partitioner hostPartitioner = new PartitionUrlByHost();++ public void configure(JobConf job) {+ curTime = job.getLong("crawl.gen.curTime", System.currentTimeMillis());+ limit = job.getLong("crawl.topN",Long.MAX_VALUE)/job.getNumReduceTasks();+ maxPerHost = job.getInt("generate.max.per.host", -1);+ }++ /** Select & invert subset due for fetch. */+ public void map(WritableComparable key, Writable value,+ OutputCollector output, Reporter reporter)+ throws IOException {+ CrawlDatum crawlDatum = (CrawlDatum)value;++ if (crawlDatum.getStatus() == CrawlDatum.STATUS_DB_GONE)+ return; // don't retry++ if (crawlDatum.getFetchTime() > curTime)+ return; // not time yet++ output.collect(crawlDatum, key); // invert for sort by score+ }++ /** Partition by host (value). */+ public int getPartition(WritableComparable key, Writable value,+ int numReduceTasks) {+ return hostPartitioner.getPartition((WritableComparable)value, key,+ numReduceTasks);+ }++ /** Collect until limit is reached. */+ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {++ while (values.hasNext() && count < limit) {++ UTF8 url = (UTF8)values.next();++ if (maxPerHost > 0) { // are we counting hosts?+ String host = new URL(url.toString()).getHost();+ Integer hostCount = (Integer)hostCounts.get(host);+ if (hostCount != null) {+ if (hostCount.intValue() >= maxPerHost)+ continue; // too many from host+ hostCounts.put(host, new Integer(hostCount.intValue()+1));+ } else { // update host count+ hostCounts.put(host, new Integer(1));+ }+ }++ output.collect(key, url);++ // Count is incremented only when we keep the URL+ // maxPerHost may cause us to skip it.+ count++;+ }++ }++ }++ /** Sort fetch lists by hash of URL. */+ public static class HashComparator extends WritableComparator {+ public HashComparator() { super(UTF8.class); }++ public int compare(WritableComparable a, WritableComparable b) {+ UTF8 url1 = (UTF8)a;+ UTF8 url2 = (UTF8)b;+ int hash1 = hash(url1.getBytes(), 0, url1.getLength());+ int hash2 = hash(url2.getBytes(), 0, url2.getLength());+ if (hash1 != hash2) {+ return hash1 - hash2;+ }+ return compareBytes(url1.getBytes(), 0, url1.getLength(),+ url2.getBytes(), 0, url2.getLength());+ }+++ public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {+ int n1 = readUnsignedShort(b1, s1);+ int n2 = readUnsignedShort(b2, s2);+ int hash1 = hash(b1, s1+2, n1);+ int hash2 = hash(b2, s2+2, n2);+ if (hash1 != hash2) {+ return hash1 - hash2;+ }+ return compareBytes(b1, s1+2, n1, b2, s2+2, n2);+ }++ 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;+ }+ }++ /** Construct a generator. */+ public Generator(NutchConf conf) {+ super(conf);+ }++ /** Generate fetchlists in a segment. */+ public File generate(File dbDir, File segments)+ throws IOException {+ return generate(dbDir, segments,+ -1, Long.MAX_VALUE, System.currentTimeMillis());+ }++ /** Generate fetchlists in a segment. */+ public File generate(File dbDir, File segments,+ int numLists, long topN, long curTime)+ throws IOException {++ File tempDir =+ new File(NutchConf.get().get("mapred.temp.dir", ".") ++ "/generate-temp-"++ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));++ File segment = new File(segments, getDate());+ File output = new File(segment, CrawlDatum.GENERATE_DIR_NAME);++ LOG.info("Generator: starting");+ LOG.info("Generator: segment: " + segment);++ // map to inverted subset due for fetch, sort by link count+ LOG.info("Generator: Selecting most-linked urls due for fetch.");+ JobConf job = new JobConf(getConf());++ if (numLists == -1) { // for politeness make+ numLists = job.getNumMapTasks(); // a partition per fetch task+ }++ job.setLong("crawl.gen.curTime", curTime);+ job.setLong("crawl.topN", topN);++ job.setInputDir(new File(dbDir, CrawlDatum.DB_DIR_NAME));+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(CrawlDatum.class);++ job.setMapperClass(Selector.class);+ job.setPartitionerClass(Selector.class);+ job.setReducerClass(Selector.class);++ job.setOutputDir(tempDir);+ job.setOutputFormat(SequenceFileOutputFormat.class);+ job.setOutputKeyClass(CrawlDatum.class);+ job.setOutputValueClass(UTF8.class);+ JobClient.runJob(job);++ // invert again, paritition by host, sort by url hash+ LOG.info("Generator: Partitioning selected urls by host, for politeness.");+ job = new JobConf(getConf());++ job.setInt("partition.url.by.host.seed", new Random().nextInt());++ job.setInputDir(tempDir);+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(CrawlDatum.class);+ job.setInputValueClass(UTF8.class);++ job.setMapperClass(InverseMapper.class);+ job.setPartitionerClass(PartitionUrlByHost.class);+ job.setNumReduceTasks(numLists);++ job.setOutputDir(output);+ job.setOutputFormat(SequenceFileOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(CrawlDatum.class);+ job.setOutputKeyComparatorClass(HashComparator.class);+ JobClient.runJob(job);++ new JobClient(getConf()).getFs().delete(tempDir);++ LOG.info("Generator: done.");++ return segment;+ }++ private static String getDate() {+ return new SimpleDateFormat("yyyyMMddHHmmss").format+ (new Date(System.currentTimeMillis()));+ }++ /**+ * Generate a fetchlist from the pagedb and linkdb+ */+ public static void main(String args[]) throws Exception {+ if (args.length < 2) {+ System.out.println("Usage: Generator <crawldb> <segments_dir> [-topN N] [-numFetchers numFetchers] [-adddays numDays]");+ return;+ }++ File dbDir = new File(args[0]);+ File segmentsDir = new File(args[1]);+ long curTime = System.currentTimeMillis();+ long topN = Long.MAX_VALUE;+ int numFetchers = -1;++ for (int i = 2; 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;+ }+ }++ if (topN != Long.MAX_VALUE)+ LOG.info("topN: " + topN);+ Generator gen = new Generator(NutchConf.get());+ gen.generate(dbDir, segmentsDir, numFetchers, topN, curTime);+ }+}diff --git a/src/java/org/apache/nutch/crawl/Indexer.java b/src/java/org/apache/nutch/crawl/Indexer.javanew file mode 100644index 000000000..71191813b--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Indexer.java@@ -0,0 +1,284 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.parse.*;+import org.apache.nutch.protocol.*;+import org.apache.nutch.analysis.*;++import org.apache.nutch.indexer.*;+import org.apache.nutch.pagedb.FetchListEntry;+import org.apache.nutch.fetcher.FetcherOutput;+import org.apache.nutch.db.Page;++import org.apache.lucene.index.*;+import org.apache.lucene.document.*;++/** Create indexes for segments. */+public class Indexer extends NutchConfigured implements Reducer {++ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.Indexer");++ /** Wraps inputs in an {@link ObjectWritable}, to permit merging different+ * types in reduce. */+ public static class InputFormat extends SequenceFileInputFormat {+ public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,+ JobConf job, Reporter reporter)+ throws IOException {++ reporter.setStatus(split.toString());++ return new SequenceFileRecordReader(fs, split) {+ public synchronized boolean next(Writable key, Writable value)+ throws IOException {+ ObjectWritable wrapper = (ObjectWritable)value;+ try {+ wrapper.set(getValueClass().newInstance());+ } catch (Exception e) {+ throw new IOException(e.toString());+ }+ return super.next(key, (Writable)wrapper.get());+ }+ };+ }+ }++ /** Unwrap Lucene Documents created by reduce and add them to an index. */+ public static class OutputFormat+ implements org.apache.nutch.mapred.OutputFormat {+ public RecordWriter getRecordWriter(final NutchFileSystem fs, JobConf job,+ String name) throws IOException {+ final File perm = new File(job.getOutputDir(), name);+ final File temp =+ job.getLocalFile("index","_"+Integer.toString(new Random().nextInt()));++ fs.delete(perm); // delete old, if any++ final IndexWriter writer = // build locally first+ new IndexWriter(fs.startLocalOutput(perm, temp),+ new NutchDocumentAnalyzer(), true);++ writer.mergeFactor = job.getInt("indexer.mergeFactor", 10);+ writer.minMergeDocs = job.getInt("indexer.minMergeDocs", 100);+ writer.maxMergeDocs =+ job.getInt("indexer.maxMergeDocs", Integer.MAX_VALUE);+ writer.setTermIndexInterval+ (job.getInt("indexer.termIndexInterval", 128));+ writer.maxFieldLength = job.getInt("indexer.max.tokens", 10000);+ //writer.infoStream = LogFormatter.getLogStream(LOG, Level.FINE);+ writer.setUseCompoundFile(false);+ writer.setSimilarity(new NutchSimilarity());++ return new RecordWriter() {+ boolean closed;++ public void write(WritableComparable key, Writable value)+ throws IOException { // unwrap & index doc+ writer.addDocument((Document)((ObjectWritable)value).get());+ }++ public void close(final Reporter reporter) throws IOException {+ // spawn a thread to give progress heartbeats+ Thread prog = new Thread() {+ public void run() {+ while (!closed) {+ try {+ reporter.setStatus("closing");+ Thread.sleep(1000);+ } catch (InterruptedException e) { continue; }+ catch (Throwable e) { return; }+ }+ }+ };++ try {+ prog.start();+ LOG.info("Optimizing index."); // optimize & close index+ writer.optimize();+ writer.close();+ fs.completeLocalOutput(perm, temp); // copy to ndfs+ fs.createNewFile(new File(perm, IndexSegment.DONE_NAME));+ } finally {+ closed = true;+ }+ }+ };+ }+ }++ public Indexer() {+ super(null);+ }++ /** Construct an Indexer. */+ public Indexer(NutchConf conf) {+ super(conf);+ }++ private float scorePower;++ public void configure(JobConf job) {+ scorePower = job.getFloat("indexer.score.power", 0.5f);+ }++ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ Inlinks inlinks = null;+ CrawlDatum dbDatum = null;+ CrawlDatum fetchDatum = null;+ ParseData parseData = null;+ ParseText parseText = null;+ while (values.hasNext()) {+ Object value = ((ObjectWritable)values.next()).get(); // unwrap+ if (value instanceof Inlinks) {+ inlinks = (Inlinks)value;+ } else if (value instanceof CrawlDatum) {+ CrawlDatum datum = (CrawlDatum)value;+ switch (datum.getStatus()) {+ case CrawlDatum.STATUS_DB_UNFETCHED:+ case CrawlDatum.STATUS_DB_FETCHED:+ case CrawlDatum.STATUS_DB_GONE:+ dbDatum = datum;+ break;+ case CrawlDatum.STATUS_FETCH_SUCCESS:+ case CrawlDatum.STATUS_FETCH_RETRY:+ case CrawlDatum.STATUS_FETCH_GONE:+ fetchDatum = datum;+ break;+ default:+ throw new RuntimeException("Unexpected status: "+datum.getStatus());+ }+ } else if (value instanceof ParseData) {+ parseData = (ParseData)value;+ } else if (value instanceof ParseText) {+ parseText = (ParseText)value;+ } else {+ LOG.warning("Unrecognized type: "+value.getClass());+ }+ }++ if (fetchDatum == null || dbDatum == null+ || parseText == null || parseData == null) {+ return; // only have inlinks+ }++ Document doc = new Document();+ ContentProperties meta = parseData.getMetadata();+ String[] anchors = inlinks!=null ? inlinks.getAnchors() : new String[0];++ // add segment, used to map from merged index back to segment files+ doc.add(Field.UnIndexed("segment",+ meta.getProperty(Fetcher.SEGMENT_NAME_KEY)));++ // add digest, used by dedup+ doc.add(Field.UnIndexed("digest", meta.getProperty(Fetcher.DIGEST_KEY)));++ // boost is opic+ float boost = (float)Math.pow(dbDatum.getScore(), scorePower);+ // apply boost to all indexed fields.+ doc.setBoost(boost);+ // store boost for use by explain and dedup+ doc.add(Field.UnIndexed("boost", Float.toString(boost)));++// LOG.info("Url: "+key.toString());+// LOG.info("Title: "+parseData.getTitle());+// LOG.info(crawlDatum.toString());+// if (inlinks != null) {+// LOG.info(inlinks.toString());+// }++ try {+ // dummy up a FetcherOutput so that we can use existing indexing filters+ // TODO: modify IndexingFilter interface to use Inlinks, etc.+ FetcherOutput fo =+ new FetcherOutput(new FetchListEntry(true,new Page((UTF8)key),anchors),+ null, null);+ fo.setFetchDate(fetchDatum.getFetchTime());++ // run indexing filters+ doc = IndexingFilters.filter(doc,new ParseImpl(parseText, parseData),fo);+ } catch (IndexingException e) {+ LOG.warning("Error indexing "+key+": "+e);+ return;+ }++ output.collect(key, new ObjectWritable(doc));+ }++ public void index(File indexDir, File crawlDb, File linkDb, File[] segments)+ throws IOException {++ LOG.info("Indexer: starting");+ LOG.info("Indexer: linkdb: " + linkDb);++ JobConf job = new JobConf(getConf());++ for (int i = 0; i < segments.length; i++) {+ LOG.info("Indexer: adding segment: " + segments[i]);+ job.addInputDir(new File(segments[i], CrawlDatum.FETCH_DIR_NAME));+ job.addInputDir(new File(segments[i], ParseData.DIR_NAME));+ job.addInputDir(new File(segments[i], ParseText.DIR_NAME));+ }++ job.addInputDir(new File(crawlDb, CrawlDatum.DB_DIR_NAME));+ job.addInputDir(new File(linkDb, LinkDb.CURRENT_NAME));++ job.setInputFormat(InputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(ObjectWritable.class);++ //job.setCombinerClass(Indexer.class);+ job.setReducerClass(Indexer.class);++ job.setOutputDir(indexDir);+ job.setOutputFormat(OutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(ObjectWritable.class);++ JobClient.runJob(job);+ LOG.info("Indexer: done");+ }++ public static void main(String[] args) throws Exception {+ Indexer indexer = new Indexer(NutchConf.get());++ if (args.length < 4) {+ System.err.println("Usage: <index> <crawldb> <linkdb> <segment> ...");+ return;+ }++ File[] segments = new File[args.length-3];+ for (int i = 3; i < args.length; i++) {+ segments[i-3] = new File(args[i]);+ }++ indexer.index(new File(args[0]), new File(args[1]), new File(args[2]),+ segments);+ }++}diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.javanew file mode 100644index 000000000..83dbe1ace--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Injector.java@@ -0,0 +1,129 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;++/** 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 NutchConfigured {+ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.Injector");+++ /** Normalize and filter injected urls. */+ public static class InjectMapper implements Mapper {+ private UrlNormalizer urlNormalizer = UrlNormalizerFactory.getNormalizer();+ private float interval;++ public void configure(JobConf job) {+ interval = job.getFloat("db.default.fetch.interval", 30f);+ }++ public void map(WritableComparable key, Writable val,+ OutputCollector output, Reporter reporter)+ throws IOException {+ UTF8 value = (UTF8)val;+ String url = value.toString(); // value is line of text+ try {+ url = urlNormalizer.normalize(url); // normalize the url+ url = URLFilters.filter(url); // filter the url+ } catch (Exception e) {+ LOG.warning("Skipping " +url+":"+e);+ url = null;+ }+ if (url != null) { // if it passes+ value.set(url); // collect it+ output.collect(value, new CrawlDatum(CrawlDatum.STATUS_DB_UNFETCHED,+ interval));+ }+ }+ }++ /** Combine multiple new entries for a url. */+ public static class InjectReducer implements Reducer {+ public void configure(JobConf job) {}++ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ output.collect(key, (Writable)values.next()); // just collect first value+ }+ }++ /** Construct an Injector. */+ public Injector(NutchConf conf) {+ super(conf);+ }++ public void inject(File crawlDb, File urlDir) throws IOException {+ LOG.info("Injector: starting");+ LOG.info("Injector: crawlDb: " + crawlDb);+ LOG.info("Injector: urlDir: " + urlDir);++ File tempDir =+ new File(NutchConf.get().get("mapred.temp.dir", ".") ++ "/inject-temp-"++ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));++ // map text input file to a <url,CrawlDatum> file+ LOG.info("Injector: Converting injected urls to crawl db entries.");+ JobConf sortJob = new JobConf(getConf());+ sortJob.setInputDir(urlDir);+ sortJob.setMapperClass(InjectMapper.class);+ sortJob.setReducerClass(InjectReducer.class);++ sortJob.setOutputDir(tempDir);+ sortJob.setOutputFormat(SequenceFileOutputFormat.class);+ sortJob.setOutputKeyClass(UTF8.class);+ sortJob.setOutputValueClass(CrawlDatum.class);+ JobClient.runJob(sortJob);++ // merge with existing crawl db+ LOG.info("Injector: Merging injected urls into crawl db.");+ JobConf mergeJob = CrawlDb.createJob(getConf(), crawlDb);+ mergeJob.addInputDir(tempDir);+ JobClient.runJob(mergeJob);+ CrawlDb.install(mergeJob, crawlDb);++ // clean up+ NutchFileSystem fs = new JobClient(getConf()).getFs();+ fs.delete(tempDir);+ LOG.info("Injector: done");++ }++ public static void main(String[] args) throws Exception {+ Injector injector = new Injector(NutchConf.get());++ if (args.length < 2) {+ System.err.println("Usage: Injector <crawldb> <url_dir>");+ return;+ }++ injector.inject(new File(args[0]), new File(args[1]));+ }++}diff --git a/src/java/org/apache/nutch/crawl/Inlink.java b/src/java/org/apache/nutch/crawl/Inlink.javanew file mode 100644index 000000000..020ff2396--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Inlink.java@@ -0,0 +1,77 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.io.*;++/* An incoming link to a page. */+public class Inlink implements Writable {++ private String fromUrl;+ private String anchor;++ public Inlink() {}++ public Inlink(String fromUrl, String anchor) {+ this.fromUrl = fromUrl;+ this.anchor = anchor;+ }++ public void readFields(DataInput in) throws IOException {+ fromUrl = UTF8.readString(in);+ anchor = UTF8.readString(in);+ }++ /** Skips over one Inlink in the input. */+ public static void skip(DataInput in) throws IOException {+ UTF8.skip(in); // skip fromUrl+ UTF8.skip(in); // skip anchor+ }++ public void write(DataOutput out) throws IOException {+ UTF8.writeString(out, fromUrl);+ UTF8.writeString(out, anchor);+ }++ public static Inlink read(DataInput in) throws IOException {+ Inlink inlink = new Inlink();+ inlink.readFields(in);+ return inlink;+ }++ public String getFromUrl() { return fromUrl; }+ public String getAnchor() { return anchor; }++ public boolean equals(Object o) {+ if (!(o instanceof Inlink))+ return false;+ Inlink other = (Inlink)o;+ return+ this.fromUrl.equals(other.fromUrl) &&+ this.anchor.equals(other.anchor);+ }++ public int hashCode() {+ return fromUrl.hashCode() ^ anchor.hashCode();+ }++ public String toString() {+ return "fromUrl: " + fromUrl + " anchor: " + anchor;+ }++}diff --git a/src/java/org/apache/nutch/crawl/Inlinks.java b/src/java/org/apache/nutch/crawl/Inlinks.javanew file mode 100644index 000000000..efb9eaaa3--- /dev/null+++ b/src/java/org/apache/nutch/crawl/Inlinks.java@@ -0,0 +1,95 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.io.*;++/** A list of {@link Inlink}s. */+public class Inlinks implements Writable {+ private ArrayList inlinks = new ArrayList(1);++ public void add(Inlink inlink) { inlinks.add(inlink); }++ public void add(Inlinks inlinks) { this.inlinks.addAll(inlinks.inlinks); }++ public int size() { return inlinks.size(); }++ public Inlink get(int i) { return (Inlink)inlinks.get(i); }++ public void clear() { inlinks.clear(); }++ public void readFields(DataInput in) throws IOException {+ int length = in.readInt();+ inlinks.clear();+ inlinks.ensureCapacity(length);+ for (int i = 0; i < length; i++) {+ add(Inlink.read(in));+ }+ }++ public void write(DataOutput out) throws IOException {+ out.writeInt(inlinks.size());+ for (int i = 0; i < inlinks.size(); i++) {+ ((Writable)inlinks.get(i)).write(out);+ }+ }++ public String toString() {+ StringBuffer buffer = new StringBuffer();+ buffer.append("Inlinks:\n");+ for (int i = 0; i < inlinks.size(); i++) {+ buffer.append(" ");+ buffer.append(inlinks.get(i));+ buffer.append("\n");+ }+ return buffer.toString();+ }++ /** Return the set of anchor texts. Only a single anchor with a given text+ * is permitted from a given domain. */+ public String[] getAnchors() throws IOException {+ HashMap domainToAnchors = new HashMap();+ ArrayList results = new ArrayList();+ for (int i = 0; i < inlinks.size(); i++) {+ Inlink inlink = (Inlink)inlinks.get(i);+ String anchor = inlink.getAnchor();++ if (anchor.length() == 0) // skip empty anchors+ continue;+ String domain = null; // extract domain name+ try {+ domain = new URL(inlink.getFromUrl()).getHost();+ } catch (MalformedURLException e) {}+ Set domainAnchors = (Set)domainToAnchors.get(domain);+ if (domainAnchors == null) {+ domainAnchors = new HashSet();+ domainToAnchors.put(domain, domainAnchors);+ }+ if (domainAnchors.add(anchor)) { // new anchor from domain+ results.add(anchor); // collect it+ }+ }++ return (String[])results.toArray(new String[results.size()]);+ }+++}diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.javanew file mode 100644index 000000000..30ac152de--- /dev/null+++ b/src/java/org/apache/nutch/crawl/LinkDb.java@@ -0,0 +1,197 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.util.logging.*;+import java.net.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;+import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.parse.*;++/** Maintains an inverted link map, listing incoming links for each url. */+public class LinkDb extends NutchConfigured implements Mapper, Reducer {++ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.crawl.LinkDb");++ public static String CURRENT_NAME = "current";++ private int maxAnchorLength;+ private int maxInlinks;+ private boolean ignoreInternalLinks;++ public LinkDb() {+ super(null);+ }++ /** Construct an LinkDb. */+ public LinkDb(NutchConf conf) {+ super(conf);+ }++ public void configure(JobConf job) {+ maxAnchorLength = job.getInt("db.max.anchor.length", 100);+ maxInlinks = job.getInt("db.max.inlinks", 10000);+ ignoreInternalLinks = job.getBoolean("db.ignore.internal.links", true);+ }++ public void map(WritableComparable key, Writable value,+ OutputCollector output, Reporter reporter)+ throws IOException {+ String fromUrl = key.toString();+ String fromHost = getHost(fromUrl);++ ParseData parseData = (ParseData)value;+ 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+ }+ }++ 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 UTF8(toUrl), inlinks);+ }+ }++ private String getHost(String url) {+ try {+ return new URL(url).getHost().toLowerCase();+ } catch (MalformedURLException e) {+ return null;+ }+ }++ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {++ Inlinks result = null;++ while (values.hasNext()) {+ Inlinks inlinks = (Inlinks)values.next();++ if (result == null) { // optimize a common case+ if (inlinks.size() < maxInlinks) {+ result = inlinks;+ continue;+ } else {+ result = new Inlinks();+ }+ }++ int end = Math.min(maxInlinks - result.size(), inlinks.size());+ for (int i = 0; i < end; i++) {+ result.add(inlinks.get(i));+ }+ }+ output.collect(key, result);+ }+++ public void invert(File linkDb, File segmentsDir) throws IOException {+ LOG.info("LinkDb: starting");+ LOG.info("LinkDb: linkdb: " + linkDb);+ LOG.info("LinkDb: segments: " + segmentsDir);++ JobConf job = LinkDb.createJob(getConf(), linkDb);+ job.setInputDir(segmentsDir);+ job.set("mapred.input.subdir", ParseData.DIR_NAME);+ JobClient.runJob(job);+ LinkDb.install(job, linkDb);+ LOG.info("LinkDb: done");+ }++ public void invert(File linkDb, File[] segments) throws IOException {+ LOG.info("LinkDb: starting");+ LOG.info("LinkDb: linkdb: " + linkDb);+ JobConf job = LinkDb.createJob(getConf(), linkDb);+ for (int i = 0; i < segments.length; i++) {+ LOG.info("LinkDb: adding segment: " + segments[i]);+ job.addInputDir(new File(segments[i], ParseData.DIR_NAME));+ }+ JobClient.runJob(job);+ LinkDb.install(job, linkDb);+ LOG.info("LinkDb: done");+ }++ private static JobConf createJob(NutchConf config, File linkDb) {+ File newLinkDb =+ new File(linkDb,+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));++ JobConf job = new JobConf(config);++ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(ParseData.class);++ job.setMapperClass(LinkDb.class);+ //job.setCombinerClass(LinkDb.class);+ job.setReducerClass(LinkDb.class);++ job.setOutputDir(newLinkDb);+ job.setOutputFormat(MapFileOutputFormat.class);+ job.setBoolean("mapred.output.compress", true);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(Inlinks.class);++ return job;+ }++ public static void install(JobConf job, File linkDb) throws IOException {+ File newLinkDb = job.getOutputDir();+ NutchFileSystem fs = new JobClient(job).getFs();+ File old = new File(linkDb, "old");+ File current = new File(linkDb, CURRENT_NAME);+ fs.delete(old);+ fs.rename(current, old);+ fs.rename(newLinkDb, current);+ fs.delete(old);+ }++ public static void main(String[] args) throws Exception {+ LinkDb linkDb = new LinkDb(NutchConf.get());++ if (args.length < 2) {+ System.err.println("Usage: <linkdb> <segments>");+ return;+ }++ linkDb.invert(new File(args[0]), new File(args[1]));+ }++++}diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.javanew file mode 100644index 000000000..2d4cef1d7--- /dev/null+++ b/src/java/org/apache/nutch/crawl/LinkDbReader.java@@ -0,0 +1,111 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io.File;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.mapred.lib.HashPartitioner;+import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.util.NutchConf;++import java.util.logging.Logger;++/** . */+public class LinkDbReader {+ public static final Logger LOG = LogFormatter.getLogger(LinkDbReader.class.getName());++ private static final Partitioner PARTITIONER = new HashPartitioner();++ private NutchFileSystem fs;+ private File directory;+ private MapFile.Reader[] readers;++ public LinkDbReader(NutchFileSystem fs, File directory) {+ this.fs = fs;+ this.directory = directory;+ }++ public String[] getAnchors(UTF8 url) throws IOException {+ Inlinks inlinks = getInlinks(url);+ if (inlinks == null)+ return null;+ return inlinks.getAnchors();+ }++ public Inlinks getInlinks(UTF8 url) throws IOException {++ synchronized (this) {+ if (readers == null) {+ readers = MapFileOutputFormat.getReaders+ (fs, new File(directory, LinkDb.CURRENT_NAME));+ }+ }++ return (Inlinks)MapFileOutputFormat.getEntry+ (readers, PARTITIONER, url, new Inlinks());+ }++ public static void processDumpJob(String linkdb, String output, NutchConf config) throws IOException {+ LOG.info("LinkDb dump: starting");+ LOG.info("LinkDb db: " + linkdb);+ File outFolder = new File(output);++ JobConf job = new JobConf(config);++ job.addInputDir(new File(linkdb, LinkDb.CURRENT_NAME));+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(Inlinks.class);++ job.setOutputDir(outFolder);+ job.setOutputFormat(TextOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(Inlinks.class);++ JobClient.runJob(job);+ }++ public static void main(String[] args) throws Exception {+ if (args.length < 2) {+ System.err.println("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;+ }++ if (args[1].equals("-dump")) {+ LinkDbReader.processDumpJob(args[0], args[2], NutchConf.get());+ } else if (args[1].equals("-url")) {+ LinkDbReader dbr = new LinkDbReader(NutchFileSystem.get(), new File(args[0]));+ Inlinks links = dbr.getInlinks(new UTF8(args[2]));+ if (links == null) {+ System.out.println(" - no link information.");+ } else {+ for (int i = 0; i < links.size(); i++) {+ System.out.println(links.get(i).toString());+ }+ }+ } else {+ System.err.println("Error: wrong argument " + args[1]);+ return;+ }+ }+}diff --git a/src/java/org/apache/nutch/crawl/ParseOutputFormat.java b/src/java/org/apache/nutch/crawl/ParseOutputFormat.javanew file mode 100644index 000000000..f5a7c5d87--- /dev/null+++ b/src/java/org/apache/nutch/crawl/ParseOutputFormat.java@@ -0,0 +1,98 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.parse.*;+import org.apache.nutch.net.*;++import java.io.*;+import java.util.*;++/* Parse content in a segment. */+public class ParseOutputFormat implements OutputFormat {++ private UrlNormalizer urlNormalizer = UrlNormalizerFactory.getNormalizer();++ public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,+ String name) throws IOException {++ final float interval = job.getFloat("db.default.fetch.interval", 30f);++ File text =+ new File(new File(job.getOutputDir(), ParseText.DIR_NAME), name);+ File data =+ new File(new File(job.getOutputDir(), ParseData.DIR_NAME), name);+ File crawl =+ new File(new File(job.getOutputDir(), CrawlDatum.PARSE_DIR_NAME), name);++ final MapFile.Writer textOut =+ new MapFile.Writer(fs, text.toString(), UTF8.class, ParseText.class);++ final MapFile.Writer dataOut =+ new MapFile.Writer(fs, data.toString(), UTF8.class,ParseData.class,true);++ final SequenceFile.Writer crawlOut =+ new SequenceFile.Writer(fs, crawl.toString(),+ UTF8.class, CrawlDatum.class);++ return new RecordWriter() {++ public void write(WritableComparable key, Writable value)+ throws IOException {++ Parse parse = (Parse)value;++ textOut.append(key, new ParseText(parse.getText()));+ dataOut.append(key, parse.getData());++ // collect outlinks for subsequent db update+ Outlink[] links = parse.getData().getOutlinks();++ // compute OPIC score contribution+ float score =+ Float.parseFloat(parse.getData().get(Fetcher.SCORE_KEY));+ score /= links.length;++ for (int i = 0; i < links.length; i++) {+ String toUrl = links[i].getToUrl();+ try {+ toUrl = urlNormalizer.normalize(toUrl); // normalize the url+ toUrl = URLFilters.filter(toUrl); // filter the url+ } catch (Exception e) {+ toUrl = null;+ }+ if (toUrl != null)+ crawlOut.append(new UTF8(toUrl),+ new CrawlDatum(CrawlDatum.STATUS_LINKED,+ interval, score));+ }+ }++ public void close(Reporter reporter) throws IOException {+ textOut.close();+ dataOut.close();+ crawlOut.close();+ }++ };++ }++}diff --git a/src/java/org/apache/nutch/crawl/ParseSegment.java b/src/java/org/apache/nutch/crawl/ParseSegment.javanew file mode 100644index 000000000..8f429c3a1--- /dev/null+++ b/src/java/org/apache/nutch/crawl/ParseSegment.java@@ -0,0 +1,111 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.util.*;+import org.apache.nutch.protocol.*;+import org.apache.nutch.parse.*;+import org.apache.nutch.net.*;++import java.io.*;+import java.util.*;+import java.util.logging.*;++/* Parse content in a segment. */+public class ParseSegment extends NutchConfigured implements Mapper, Reducer {++ public static final Logger LOG =+ LogFormatter.getLogger(Parser.class.getName());++ public ParseSegment() { super(null); }++ public ParseSegment(NutchConf conf) {+ super(conf);+ }++ public void configure(JobConf job) {+ }++ public void map(WritableComparable key, Writable value,+ OutputCollector output, Reporter reporter)+ throws IOException {+ Content content = (Content)value;++ Parse parse = null;+ ParseStatus status;+ try {+ parse = ParseUtil.parse(content);+ status = parse.getData().getStatus();+ } catch (Exception e) {+ status = new ParseStatus(e);+ }++ if (status.isSuccess()) {+ output.collect(key, new ParseImpl(parse.getText(), parse.getData()));+ } else {+ LOG.warning("Error parsing: "+key+": "+status.toString());+ }+ }++ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ output.collect(key, (Writable)values.next()); // collect first value+ }++ public void parse(File segment) throws IOException {+ LOG.info("Parse: starting");+ LOG.info("Parse: segment: " + segment);++ JobConf job = new JobConf(getConf());++ job.setInputDir(new File(segment, Content.DIR_NAME));+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(Content.class);+ job.setMapperClass(ParseSegment.class);+ job.setReducerClass(ParseSegment.class);++ job.setOutputDir(segment);+ job.setOutputFormat(ParseOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(ParseImpl.class);++ JobClient.runJob(job);+ LOG.info("Parse: done");+ }+++ public static void main(String[] args) throws Exception {+ File segment;++ String usage = "Usage: ParseSegment segment";++ if (args.length == 0) {+ System.err.println(usage);+ System.exit(-1);+ }++ segment = new File(args[0]);++ ParseSegment parseSegment = new ParseSegment(NutchConf.get());+ parseSegment.parse(segment);+ }+}diff --git a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.javanew file mode 100644index 000000000..a316d5487--- /dev/null+++ b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java@@ -0,0 +1,52 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.nutch.io.*;+import org.apache.nutch.mapred.*;++/** Partition urls by hostname. */+public class PartitionUrlByHost implements Partitioner {+ private int seed;++ public void configure(JobConf job) {+ seed = job.getInt("partition.url.by.host.seed", 0);+ }++ /** Hash by hostname. */+ public int getPartition(WritableComparable key, Writable value,+ int numReduceTasks) {+ String urlString = ((UTF8)key).toString();+ URL url = null;+ try {+ url = new URL(urlString);+ } catch (MalformedURLException e) {+ }+ 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/package.html b/src/java/org/apache/nutch/crawl/package.htmlnew file mode 100644index 000000000..a5e0a581d--- /dev/null+++ b/src/java/org/apache/nutch/crawl/package.html@@ -0,0 +1,5 @@+<html>+<body>+Crawl control code.+</body>+</html>diff --git a/src/java/org/apache/nutch/db/DistributedWebDBWriter.java b/src/java/org/apache/nutch/db/DistributedWebDBWriter.javaindex d7d7ff753..109dce7a7 100644--- a/src/java/org/apache/nutch/db/DistributedWebDBWriter.java+++ b/src/java/org/apache/nutch/db/DistributedWebDBWriter.java@@ -1656,7 +1656,7 @@ public class DistributedWebDBWriter implements IWebDBWriter {}// Bump number by 1.- DataOutputStream out = new DataOutputStream(nfs.create(openCounter, true));+ DataOutputStream out = nfs.create(openCounter);try {out.write(OPEN_COUNTER_VERSION);out.writeInt(numOpens + 1);@@ -1793,7 +1793,7 @@ public class DistributedWebDBWriter implements IWebDBWriter {// 7. Finally, write out the total num of pages and links//File sectionStats = new File(newSectionDir, STATS_FILE);- DataOutputStream out = new DataOutputStream(nfs.create(sectionStats, true));+ DataOutputStream out = nfs.create(sectionStats);try {//// These counts are guaranteed to be correct; they're@@ -1854,7 +1854,7 @@ public class DistributedWebDBWriter implements IWebDBWriter {}// Bump that number by 1.- out = new DataOutputStream(nfs.create(closeCounter, true));+ out = nfs.create(closeCounter);try {out.write(CLOSE_COUNTER_VERSION);out.writeInt(numCloses + 1);diff --git a/src/java/org/apache/nutch/db/Page.java b/src/java/org/apache/nutch/db/Page.javaindex 08d3b5150..c5f9b93c4 100644--- a/src/java/org/apache/nutch/db/Page.java+++ b/src/java/org/apache/nutch/db/Page.java@@ -64,6 +64,10 @@ public class Page implements WritableComparable, Cloneable {md5 = new MD5Hash(); // initialize for readFields()}+ public Page(UTF8 url) {+ this.url = url;+ }+/** Construct a new, default page, due to be fetched. */public Page(String urlString, MD5Hash md5) throws MalformedURLException {setURL(urlString);diff --git a/src/java/org/apache/nutch/fs/ChecksumException.java b/src/java/org/apache/nutch/fs/ChecksumException.javanew file mode 100644index 000000000..6f409a75a--- /dev/null+++ b/src/java/org/apache/nutch/fs/ChecksumException.java@@ -0,0 +1,26 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.fs;++import java.io.IOException;++/** Thrown for checksum errors. */+public class ChecksumException extends IOException {+ public ChecksumException(String description) {+ super(description);+ }+}diff --git a/src/java/org/apache/nutch/fs/FSError.java b/src/java/org/apache/nutch/fs/FSError.javanew file mode 100644index 000000000..81bd07034--- /dev/null+++ b/src/java/org/apache/nutch/fs/FSError.java@@ -0,0 +1,25 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.fs;++/** Thrown for unexpected filesystem errors, presumed to reflect disk errors+ * in the native filesystem. */+public class FSError extends Error {+ FSError(Throwable cause) {+ super(cause);+ }+}diff --git a/src/java/org/apache/nutch/fs/FileUtil.java b/src/java/org/apache/nutch/fs/FileUtil.javaindex eb095bfc6..baf279657 100644--- a/src/java/org/apache/nutch/fs/FileUtil.java+++ b/src/java/org/apache/nutch/fs/FileUtil.java@@ -18,6 +18,8 @@ package org.apache.nutch.fs;import java.io.*;+import org.apache.nutch.util.NutchConf;+/*** A collection of file-processing util methods*/@@ -52,10 +54,10 @@ public class FileUtil {}if (nfs.isFile(src)) {- DataInputStream in = new DataInputStream(nfs.open(src));+ NFSInputStream in = nfs.openRaw(src);try {- DataOutputStream out = new DataOutputStream(nfs.create(dst));- byte buf[] = new byte[2048];+ NFSOutputStream out = nfs.createRaw(dst, true);+ byte buf[] = new byte[NutchConf.get().getInt("io.file.buffer.size", 4096)];try {int readBytes = in.read(buf);@@ -71,7 +73,7 @@ public class FileUtil {}} else {nfs.mkdirs(dst);- File contents[] = nfs.listFiles(src);+ File contents[] = nfs.listFilesRaw(src);if (contents != null) {for (int i = 0; i < contents.length; i++) {File newDst = new File(dst, contents[i].getName());diff --git a/src/java/org/apache/nutch/fs/LocalFileSystem.java b/src/java/org/apache/nutch/fs/LocalFileSystem.javaindex 76a1cca05..0c562c120 100644--- a/src/java/org/apache/nutch/fs/LocalFileSystem.java+++ b/src/java/org/apache/nutch/fs/LocalFileSystem.java@@ -21,6 +21,7 @@ import java.util.*;import java.nio.channels.*;import org.apache.nutch.ndfs.NDFSFile;+import org.apache.nutch.ndfs.DF;import org.apache.nutch.ndfs.NDFSFileInfo;import org.apache.nutch.io.UTF8;@@ -50,6 +51,20 @@ public class LocalFileSystem extends NutchFileSystem {// useCopyForRename = false;}+ /**+ * Return 1x1 'localhost' cell if the file exists.+ * Return null if otherwise.+ */+ public String[][] getFileCacheHints(File f, long start, long len) throws IOException {+ if (! f.exists()) {+ return null;+ } else {+ String result[][] = new String[1][];+ result[0] = new String[1];+ result[0][0] = "localhost";+ return result;+ }+ }public String getName() { return "local"; }@@ -77,31 +92,36 @@ public class LocalFileSystem extends NutchFileSystem {public int available() throws IOException { return fis.available(); }public void close() throws IOException { fis.close(); }public boolean markSupport() { return false; }- public int read() throws IOException { return fis.read(); }- public int read(byte[] b) throws IOException { return fis.read(b); }++ public int read() throws IOException {+ try {+ return fis.read();+ } catch (IOException e) { // unexpected exception+ throw new FSError(e); // assume native fs error+ }+ }+public int read(byte[] b, int off, int len) throws IOException {+ try {return fis.read(b, off, len);+ } catch (IOException e) { // unexpected exception+ throw new FSError(e); // assume native fs error+ }}+public long skip(long n) throws IOException { return fis.skip(n); }}/*** Open the file at f*/- public NFSInputStream open(File f) throws IOException {+ public NFSInputStream openRaw(File f) throws IOException {if (! f.exists()) {throw new FileNotFoundException(f.toString());}return new LocalNFSFileInputStream(f);}- /**- * Create the file at f.- */- public NFSOutputStream create(File f) throws IOException {- return create(f, false);- }-/********************************************************** For create()'s NFSOutputStream.*********************************************************/@@ -121,16 +141,25 @@ public class LocalFileSystem extends NutchFileSystem {*/public void close() throws IOException { fos.close(); }public void flush() throws IOException { fos.flush(); }- public void write(byte[] b) throws IOException { fos.write(b); }+public void write(byte[] b, int off, int len) throws IOException {- fos.write(b, off, len);+ try {+ fos.write(b, off, len);+ } catch (IOException e) { // unexpected exception+ throw new FSError(e); // assume native fs error+ }+ }+ public void write(int b) throws IOException {+ try {+ fos.write(b);+ } catch (IOException e) { // unexpected exception+ throw new FSError(e); // assume native fs error+ }}- public void write(int b) throws IOException { fos.write(b); }}- /**- */- public NFSOutputStream create(File f, boolean overwrite) throws IOException {+ public NFSOutputStream createRaw(File f, boolean overwrite)+ throws IOException {if (f.exists() && ! overwrite) {throw new IOException("File already exists:"+f);}@@ -144,7 +173,7 @@ public class LocalFileSystem extends NutchFileSystem {/*** Rename files/dirs*/- public boolean rename(File src, File dst) throws IOException {+ public boolean renameRaw(File src, File dst) throws IOException {if (useCopyForRename) {FileUtil.copyContents(this, src, dst, true);return fullyDelete(src);@@ -154,7 +183,7 @@ public class LocalFileSystem extends NutchFileSystem {/*** Get rid of File f, whether a true file or dir.*/- public boolean delete(File f) throws IOException {+ public boolean deleteRaw(File f) throws IOException {if (f.isFile()) {return f.delete();} else return fullyDelete(f);@@ -180,7 +209,7 @@ public class LocalFileSystem extends NutchFileSystem {/***/- public File[] listFiles(File f) throws IOException {+ public File[] listFilesRaw(File f) throws IOException {File[] files = f.listFiles();if (files == null) return null;// 20041022, xing, Watch out here:@@ -346,4 +375,40 @@ public class LocalFileSystem extends NutchFileSystem {}return dir.delete();}++ /** Moves files to a bad file directory on the same device, so that their+ * storage will not be reused. */+ public void reportChecksumFailure(File f, NFSInputStream in,+ long start, long length, int crc) {+ try {+ // canonicalize f+ f = f.getCanonicalFile();++ // find highest writable parent dir of f on the same device+ String device = new DF(f.toString()).getMount();+ File parent = f.getParentFile();+ File dir;+ do {+ dir = parent;+ parent = parent.getParentFile();+ } while (parent.canWrite() && parent.toString().startsWith(device));++ // move the file there+ File badDir = new File(dir, "bad_files");+ badDir.mkdirs();+ String suffix = "." + new Random().nextInt();+ File badFile = new File(badDir,f.getName()+suffix);+ LOG.warning("Moving bad file " + f + " to " + badFile);+ in.close(); // close it first+ f.renameTo(badFile); // rename it++ // move checksum file too+ File checkFile = getChecksumFile(f);+ checkFile.renameTo(new File(badDir, checkFile.getName()+suffix));++ } catch (IOException e) {+ LOG.warning("Error moving bad file " + f + ": " + e);+ }+ }+}diff --git a/src/java/org/apache/nutch/fs/NDFSFileSystem.java b/src/java/org/apache/nutch/fs/NDFSFileSystem.javaindex e9bef1a77..8326f772f 100644--- a/src/java/org/apache/nutch/fs/NDFSFileSystem.java+++ b/src/java/org/apache/nutch/fs/NDFSFileSystem.java@@ -22,10 +22,12 @@ import java.util.*;import org.apache.nutch.io.*;import org.apache.nutch.ndfs.*;+import org.apache.nutch.util.NutchConf;/****************************************************************- * Implement the NutchFileSystem interface for the NDFS system.- *+ * Implementation of the abstract NutchFileSystem for the NDFS system.+ * This is the distributed file system. It can be distributed over+ * 1 or more machines* @author Mike Cafarella*****************************************************************/public class NDFSFileSystem extends NutchFileSystem {@@ -49,44 +51,37 @@ public class NDFSFileSystem extends NutchFileSystem {public String getName() { return name; }private UTF8 getPath(File file) {- File f = file;String path = getNDFSPath(file);if (!path.startsWith(NDFSFile.NDFS_FILE_SEPARATOR)) {- f = new File(HOME_DIR, path);+ path = getNDFSPath(new File(HOME_DIR, path)); // make absolute}- return new UTF8(getNDFSPath(f));+ return new UTF8(path);}- /**- * Open the file at f- */- public NFSInputStream open(File f) throws IOException {- return ndfs.open(getPath(f));+ public String[][] getFileCacheHints(File f, long start, long len) throws IOException {+ return ndfs.getHints(getPath(f), start, len);}- /**- * Create the file at f.- */- public NFSOutputStream create(File f) throws IOException {- return create(f, false);+ public NFSInputStream openRaw(File f) throws IOException {+ return ndfs.open(getPath(f));}- /**- */- public NFSOutputStream create(File f, boolean overwrite) throws IOException {++ public NFSOutputStream createRaw(File f, boolean overwrite)+ throws IOException {return ndfs.create(getPath(f), overwrite);}/*** Rename files/dirs*/- public boolean rename(File src, File dst) throws IOException {+ public boolean renameRaw(File src, File dst) throws IOException {return ndfs.rename(getPath(src), getPath(dst));}/*** Get rid of File f, whether a true file or dir.*/- public boolean delete(File f) throws IOException {+ public boolean deleteRaw(File f) throws IOException {return ndfs.delete(getPath(f));}@@ -111,7 +106,7 @@ public class NDFSFileSystem extends NutchFileSystem {/***/- public File[] listFiles(File f) throws IOException {+ public File[] listFilesRaw(File f) throws IOException {NDFSFileInfo info[] = ndfs.listFiles(getPath(f));if (info == null) {return new File[0];@@ -177,7 +172,7 @@ public class NDFSFileSystem extends NutchFileSystem {doFromLocalFile(contents[i], new File(dst, contents[i].getName()), deleteSource);}} else {- byte buf[] = new byte[4096];+ byte buf[] = new byte[NutchConf.get().getInt("io.file.buffer.size", 4096)];InputStream in = new BufferedInputStream(new FileInputStream(src));try {OutputStream out = create(dst);@@ -213,6 +208,7 @@ public class NDFSFileSystem extends NutchFileSystem {}}}+ dst = dst.getCanonicalFile();if (isDirectory(src)) {dst.mkdirs();@@ -221,10 +217,10 @@ public class NDFSFileSystem extends NutchFileSystem {copyToLocalFile(contents[i], new File(dst, contents[i].getName()));}} else {- byte buf[] = new byte[4096];+ byte buf[] = new byte[NutchConf.get().getInt("io.file.buffer.size", 4096)];InputStream in = open(src);try {- OutputStream out = new BufferedOutputStream(new FileOutputStream(dst));+ OutputStream out = NutchFileSystem.getNamed("local").create(dst);try {int bytesRead = in.read(buf);while (bytesRead >= 0) {@@ -302,18 +298,22 @@ public class NDFSFileSystem extends NutchFileSystem {parent = parent.getParentFile();}StringBuffer path = new StringBuffer();- String fname = (String) l.get(l.size() - 1);- if (!"".equals(fname)) {- path.append(fname); //handle not absolute paths- } else {- if (l.size() == 1)- path.append(NDFSFile.NDFS_FILE_SEPARATOR); //handle root path- }+ path.append(l.get(l.size() - 1));for (int i = l.size() - 2; i >= 0; i--) {- fname = (String) l.get(i);path.append(NDFSFile.NDFS_FILE_SEPARATOR);- path.append(fname);+ path.append(l.get(i));}return path.toString();}++ public void reportChecksumFailure(File f, NFSInputStream in,+ long start, long length, int crc) {++ // ignore for now, causing task to fail, and hope that when task is+ // retried it gets a different copy of the block that is not corrupt.++ // FIXME: we should move the bad block(s) involved to a bad block+ // directory on their datanode, and then re-replicate the blocks, so that+ // no data is lost. a task may fail, but on retry it should succeed.+ }}diff --git a/src/java/org/apache/nutch/fs/TestClient.java b/src/java/org/apache/nutch/fs/NDFSShell.javasimilarity index 95%rename from src/java/org/apache/nutch/fs/TestClient.javarename to src/java/org/apache/nutch/fs/NDFSShell.javaindex 0ea354568..5133a6302 100644--- a/src/java/org/apache/nutch/fs/TestClient.java+++ b/src/java/org/apache/nutch/fs/NDFSShell.java@@ -29,12 +29,12 @@ import java.util.*;** @author Mike Cafarella**************************************************/-public class TestClient {+public class NDFSShell {NutchFileSystem nfs;/***/- public TestClient(NutchFileSystem nfs) {+ public NDFSShell(NutchFileSystem nfs) {this.nfs = nfs;}@@ -216,7 +216,7 @@ public class TestClient {*/public static void main(String argv[]) throws IOException {if (argv.length < 1) {- System.out.println("Usage: java NDFSClient [-local | -ndfs <namenode:port>]" ++ System.out.println("Usage: java NDFSShell [-local | -ndfs <namenode:port>]" +" [-ls <path>] [-du <path>] [-mv <src> <dst>] [-cp <src> <dst>] [-rm <src>]" +" [-put <localsrc> <dst>] [-copyFromLocal <localsrc> <dst>] [-moveFromLocal <localsrc> <dst>]" +" [-get <src> <localdst>] [-copyToLocal <src> <localdst>] [-moveToLocal <src> <localdst>]" +@@ -227,7 +227,7 @@ public class TestClient {int i = 0;NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);try {- TestClient tc = new TestClient(nfs);+ NDFSShell tc = new NDFSShell(nfs);String cmd = argv[i++];if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd)) {@@ -239,17 +239,17 @@ public class TestClient {} else if ("-moveToLocal".equals(cmd)) {tc.moveToLocal(argv[i++], new File(argv[i++]));} else if ("-ls".equals(cmd)) {- tc.ls(argv[i++]);+ String arg = i < argv.length ? argv[i++] : "";+ tc.ls(arg);} else if ("-mv".equals(cmd)) {tc.rename(argv[i++], argv[i++]);} else if ("-cp".equals(cmd)) {tc.copy(argv[i++], argv[i++]);} else if ("-rm".equals(cmd)) {tc.delete(argv[i++]);- } else if ("-ls".equals(cmd)) {- tc.ls(argv[i++]);} else if ("-du".equals(cmd)) {- tc.du(argv[i++]);+ String arg = i < argv.length ? argv[i++] : "";+ tc.du(arg);} else if ("-mkdir".equals(cmd)) {tc.mkdir(argv[i++]);} else if ("-report".equals(cmd)) {diff --git a/src/java/org/apache/nutch/fs/NFSDataInputStream.java b/src/java/org/apache/nutch/fs/NFSDataInputStream.javaindex f253f10e0..81d6f6ad1 100644--- a/src/java/org/apache/nutch/fs/NFSDataInputStream.java+++ b/src/java/org/apache/nutch/fs/NFSDataInputStream.java@@ -16,19 +16,138 @@package org.apache.nutch.fs;import java.io.*;-import org.apache.nutch.util.NutchConf;+import java.util.Arrays;+import java.util.logging.*;+import java.util.zip.*;+import org.apache.nutch.util.*;/** Utility that wraps a {@link NFSInputStream} in a {@link DataInputStream}* and buffers input through a {@link BufferedInputStream}. */public class NFSDataInputStream extends DataInputStream {+ private static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.fs.DataInputStream");++ private static final byte[] VERSION = NFSDataOutputStream.CHECKSUM_VERSION;+ private static final int HEADER_LENGTH = 8;++ private int bytesPerSum = 1;+ /** Verify that data matches checksums. */+ private class Checker extends FilterInputStream implements Seekable {+ private NutchFileSystem fs;+ private File file;+ private NFSDataInputStream sums;+ private Checksum sum = new CRC32();+ private int inSum;++ public Checker(NutchFileSystem fs, File file)+ throws IOException {+ super(fs.openRaw(file));++ this.fs = fs;+ this.file = file;+ File sumFile = fs.getChecksumFile(file);+ try {+ this.sums = new NFSDataInputStream(fs.openRaw(sumFile));+ byte[] version = new byte[VERSION.length];+ sums.readFully(version);+ if (!Arrays.equals(version, VERSION))+ throw new IOException("Not a checksum file: "+sumFile);+ bytesPerSum = sums.readInt();+ } catch (FileNotFoundException e) { // quietly ignore+ stopSumming();+ } catch (IOException e) { // loudly ignore+ LOG.warning("Problem opening checksum file: "+e+". Ignoring.");+ stopSumming();+ }+ }++ public void seek(long desired) throws IOException {+ ((Seekable)in).seek(desired);+ if (sums != null) {+ if (desired % bytesPerSum != 0)+ throw new IOException("Seek to non-checksummed position.");+ try {+ sums.seek(HEADER_LENGTH + 4*(desired/bytesPerSum));+ } catch (IOException e) {+ LOG.warning("Problem seeking checksum file: "+e+". Ignoring.");+ stopSumming();+ }+ sum.reset();+ inSum = 0;+ }+ }++ public int read(byte b[], int off, int len) throws IOException {+ int read = in.read(b, off, len);++ if (sums != null) {+ int summed = 0;+ while (summed < read) {++ int goal = bytesPerSum - inSum;+ int inBuf = read - summed;+ int toSum = inBuf <= goal ? inBuf : goal;++ sum.update(b, off+summed, toSum);+ summed += toSum;++ inSum += toSum;+ if (inSum == bytesPerSum) {+ verifySum(read-(summed-bytesPerSum));+ }+ }+ }++ return read;+ }++ private void verifySum(int delta) throws IOException {+ int crc;+ try {+ crc = sums.readInt();+ } catch (IOException e) {+ LOG.warning("Problem reading checksum file: "+e+". Ignoring.");+ stopSumming();+ return;+ }+ int sumValue = (int)sum.getValue();+ sum.reset();+ inSum = 0;+ if (crc != sumValue) {+ long pos = getPos() - delta;+ fs.reportChecksumFailure(file, (NFSInputStream)in,+ pos, bytesPerSum, crc);+ throw new ChecksumException("Checksum error: "+file+" at "+pos);+ }+ }++ public long getPos() throws IOException {+ return ((NFSInputStream)in).getPos();+ }++ public void close() throws IOException {+ super.close();+ stopSumming();+ }++ private void stopSumming() {+ if (sums != null) {+ try {+ sums.close();+ } catch (IOException f) {}+ sums = null;+ bytesPerSum = 1;+ }+ }+ }+/** Cache the file position. This improves performance significantly.*/private static class PositionCache extends FilterInputStream {long position;- public PositionCache(NFSInputStream in) throws IOException {+ public PositionCache(InputStream in) throws IOException {super(in);- this.position = in.getPos();}// This is the only read() method called by BufferedInputStream, so we trap@@ -40,7 +159,7 @@ public class NFSDataInputStream extends DataInputStream {}public void seek(long desired) throws IOException {- ((NFSInputStream)in).seek(desired); // seek underlying stream+ ((Seekable)in).seek(desired); // seek underlying streamposition = desired; // update position}@@ -51,25 +170,35 @@ public class NFSDataInputStream extends DataInputStream {}/** Buffer input. This improves performance significantly.*/- private static class Buffer extends BufferedInputStream {- public Buffer(PositionCache in, int bufferSize) throws IOException {+ private class Buffer extends BufferedInputStream {+ public Buffer(PositionCache in, int bufferSize)+ throws IOException {super(in, bufferSize);}public void seek(long desired) throws IOException {- long current = getPos();- long start = (current - this.pos);- if (desired >= start && desired < start + this.count) {- this.pos += (desired - current); // can position within buffer+ long end = ((PositionCache)in).getPos();+ long start = end - this.count;+ if (desired >= start && desired < end) {+ this.pos = (int)(desired - start); // can position within buffer} else {this.count = 0; // invalidate bufferthis.pos = 0;- ((PositionCache)in).seek(desired); // seek underlying stream+ long delta = desired % bytesPerSum;++ // seek to last checksummed point, if any+ ((PositionCache)in).seek(desired - delta);++ // scan to desired position+ for (int i = 0; i < delta; i++) {+ read();+ }}+}- public long getPos() throws IOException { // adjust for buffer+ public long getPos() throws IOException { // adjust for bufferreturn ((PositionCache)in).getPos() - (this.count - this.pos);}@@ -82,15 +211,27 @@ public class NFSDataInputStream extends DataInputStream {}+ public NFSDataInputStream(NutchFileSystem fs, File file) throws IOException {+ this(fs, file, NutchConf.get().getInt("io.file.buffer.size", 4096));+ }++ public NFSDataInputStream(NutchFileSystem fs, File file, int bufferSize)+ throws IOException {+ super(null);+ this.in = new Buffer(new PositionCache(new Checker(fs, file)), bufferSize);+ }++ /** Construct without checksums. */public NFSDataInputStream(NFSInputStream in) throws IOException {this(in, NutchConf.get().getInt("io.file.buffer.size", 4096));}-+ /** Construct without checksums. */public NFSDataInputStream(NFSInputStream in, int bufferSize)throws IOException {- super(new Buffer(new PositionCache(in), bufferSize));+ super(null);+ this.in = new Buffer(new PositionCache(in), bufferSize);}-+public void seek(long desired) throws IOException {((Buffer)in).seek(desired);}diff --git a/src/java/org/apache/nutch/fs/NFSDataOutputStream.java b/src/java/org/apache/nutch/fs/NFSDataOutputStream.javaindex 756ad35e5..66b368739 100644--- a/src/java/org/apache/nutch/fs/NFSDataOutputStream.java+++ b/src/java/org/apache/nutch/fs/NFSDataOutputStream.java@@ -16,18 +16,78 @@package org.apache.nutch.fs;import java.io.*;+import java.util.zip.Checksum;+import java.util.zip.CRC32;import org.apache.nutch.util.NutchConf;-/** Utility that wraps a {@link NFSOutputStream} in a {@link DataOutputStream}- * and buffers output through a {@link BufferedOutputStream}. */+/** Utility that wraps a {@link NFSOutputStream} in a {@link DataOutputStream},+ * buffers output through a {@link BufferedOutputStream} and creates a checksum+ * file. */public class NFSDataOutputStream extends DataOutputStream {+ public static final byte[] CHECKSUM_VERSION = new byte[] {'c', 'r', 'c', 0};+ /** Store checksums for data. */+ private static class Summer extends FilterOutputStream {++ private final int bytesPerSum+ = NutchConf.get().getInt("io.bytes.per.checksum", 512);++ private NFSDataOutputStream sums;+ private Checksum sum = new CRC32();+ private int inSum;++ public Summer(NutchFileSystem fs, File file, boolean overwrite)+ throws IOException {+ super(fs.createRaw(file, overwrite));++ this.sums =+ new NFSDataOutputStream(fs.createRaw(fs.getChecksumFile(file), true));++ sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length);+ sums.writeInt(bytesPerSum);+ }++ public void write(byte b[], int off, int len) throws IOException {+ int summed = 0;+ while (summed < len) {++ int goal = bytesPerSum - inSum;+ int inBuf = len - summed;+ int toSum = inBuf <= goal ? inBuf : goal;++ sum.update(b, off+summed, toSum);+ summed += toSum;++ inSum += toSum;+ if (inSum == bytesPerSum) {+ writeSum();+ }+ }++ out.write(b, off, len);+ }++ private void writeSum() throws IOException {+ if (inSum != 0) {+ sums.writeInt((int)sum.getValue());+ sum.reset();+ inSum = 0;+ }+ }++ public void close() throws IOException {+ writeSum();+ sums.close();+ super.close();+ }++ }+private static class PositionCache extends FilterOutputStream {long position;- public PositionCache(NFSOutputStream out) throws IOException {+ public PositionCache(OutputStream out) throws IOException {super(out);- this.position = out.getPos();}// This is the only write() method called by BufferedOutputStream, so we@@ -44,7 +104,7 @@ public class NFSDataOutputStream extends DataOutputStream {}private static class Buffer extends BufferedOutputStream {- public Buffer(PositionCache out, int bufferSize) throws IOException {+ public Buffer(OutputStream out, int bufferSize) throws IOException {super(out, bufferSize);}@@ -63,10 +123,19 @@ public class NFSDataOutputStream extends DataOutputStream {}+ public NFSDataOutputStream(NutchFileSystem fs, File file,+ boolean overwrite, int bufferSize)+ throws IOException {+ super(new Buffer(new PositionCache(new Summer(fs, file, overwrite)),+ bufferSize));+ }++ /** Construct without checksums. */public NFSDataOutputStream(NFSOutputStream out) throws IOException {this(out, NutchConf.get().getInt("io.file.buffer.size", 4096));}+ /** Construct without checksums. */public NFSDataOutputStream(NFSOutputStream out, int bufferSize)throws IOException {super(new Buffer(new PositionCache(out), bufferSize));diff --git a/src/java/org/apache/nutch/fs/NFSInputStream.java b/src/java/org/apache/nutch/fs/NFSInputStream.javaindex 2fc332427..7c1ebab0b 100644--- a/src/java/org/apache/nutch/fs/NFSInputStream.java+++ b/src/java/org/apache/nutch/fs/NFSInputStream.java@@ -23,7 +23,7 @@ import java.io.*;** @author Mike Cafarella*****************************************************************/-public abstract class NFSInputStream extends InputStream {+public abstract class NFSInputStream extends InputStream implements Seekable {/*** Seek to the given offset from the start of the file.* The next read() will be from that location. Can'tdiff --git a/src/java/org/apache/nutch/fs/NutchFileSystem.java b/src/java/org/apache/nutch/fs/NutchFileSystem.javaindex 762cd1d98..3f52b0464 100644--- a/src/java/org/apache/nutch/fs/NutchFileSystem.java+++ b/src/java/org/apache/nutch/fs/NutchFileSystem.java@@ -24,16 +24,21 @@ import org.apache.nutch.ndfs.*;import org.apache.nutch.util.*;/****************************************************************- * NutchFileSystem is an interface for a fairly simple- * distributed file system. A Nutch installation might consist+ * An abstract base class for a fairly simple+ * distributed file system.+ * A Nutch installation might consist* of multiple machines, which should swap files transparently.* This interface allows other Nutch systems to find and place* files into the distributed Nutch-controlled file world.- *+ * <p>+ * A local implementation exists for testing and for small Nutch instances.+ * <p>* The standard job of NutchFileSystem is to take the location-* independent NutchFile objects, and resolve them using local* knowledge and local instances of ShareGroup.- *+ * <p>+ * The local implementation is {@link LocalFileSystem} and distributed+ * implementation is {@link NDFSFileSystem}.* @author Mike Cafarella*****************************************************************/public abstract class NutchFileSystem {@@ -45,6 +50,8 @@ public abstract class NutchFileSystem {* Parse the cmd-line args, starting at i. Remove consumed args* from array. We expect param in the form:* '-local | -ndfs <namenode:port>'+ *+ * @deprecated use fs.default.name config option instead*/public static NutchFileSystem parseArgs(String argv[], int i) throws IOException {/**@@ -57,7 +64,7 @@ public abstract class NutchFileSystem {String cmd = argv[i];if ("-ndfs".equals(cmd)) {i++;- InetSocketAddress addr = NDFS.createSocketAddr(argv[i++]);+ InetSocketAddress addr = DataNode.createSocketAddr(argv[i++]);nfs = new NDFSFileSystem(addr);} else if ("-local".equals(cmd)) {i++;@@ -77,11 +84,16 @@ public abstract class NutchFileSystem {/** Returns the default filesystem implementation.*/public static NutchFileSystem get() throws IOException {- return getNamed(NutchConf.get().get("fs.default.name", "local"));+ return get(NutchConf.get());+ }++ /** Returns the configured filesystem implementation.*/+ public static NutchFileSystem get(NutchConf conf) throws IOException {+ return getNamed(conf.get("fs.default.name", "local"));}- /** Returns a name for this filesystem, suitable to pass to- * {@link NutchFileSystem#getNamed(String)}.*/+ /** Returns a name for this filesystem, suitable to pass to {@link+ * NutchFileSystem#getNamed(String).*/public abstract String getName();/** Returns a named filesystem. Names are either the string "local" or a@@ -92,13 +104,23 @@ public abstract class NutchFileSystem {if ("local".equals(name)) {fs = new LocalFileSystem();} else {- fs = new NDFSFileSystem(NDFS.createSocketAddr(name));+ fs = new NDFSFileSystem(DataNode.createSocketAddr(name));}NAME_TO_FS.put(name, fs);}return fs;}+ /** Return the name of the checksum file associated with a file.*/+ public static File getChecksumFile(File file) {+ return new File(file.getParentFile(), "."+file.getName()+".crc");+ }++ /** Return true iff file is a checksum file name.*/+ public static boolean isChecksumFile(File file) {+ String name = file.getName();+ return name.startsWith(".") && name.endsWith(".crc");+ }///////////////////////////////////////////////////////////////// NutchFileSystem@@ -108,18 +130,70 @@ public abstract class NutchFileSystem {public NutchFileSystem() {}+ /**+ * Return a 2D array of size 1x1 or greater, containing hostnames+ * where portions of the given file can be found. For a nonexistent+ * file or regions, null will be returned.+ *+ * This call is most helpful with NDFS, where it returns+ * hostnames of machines that contain the given file.+ *+ * The NutchFileSystem will simply return an elt containing 'localhost'.+ */+ public abstract String[][] getFileCacheHints(File f, long start, long len) throws IOException;++ /**+ * Opens an NFSDataInputStream for the indicated File.+ */+ public NFSDataInputStream open(File f) throws IOException {+ return open(f, NutchConf.get().getInt("io.file.buffer.size", 4096));+ }++ /**+ * Opens an NFSDataInputStream at the indicated File.+ * @param f the file name to open+ * @param overwrite if a file with this name already exists, then if true,+ * the file will be overwritten, and if false an error will be thrown.+ * @param bufferSize the size of the buffer to be used.+ */+ public NFSDataInputStream open(File f, int bufferSize) throws IOException {+ return new NFSDataInputStream(this, f, bufferSize);+ }+/*** Opens an InputStream for the indicated File, whether local* or via NDFS.*/- public abstract NFSInputStream open(File f) throws IOException;+ public abstract NFSInputStream openRaw(File f) throws IOException;/**- * Opens an OutputStream at the indicated File, whether local- * or via NDFS.+ * Opens an NFSDataOutputStream at the indicated File.+ * Files are overwritten by default.+ */+ public NFSDataOutputStream create(File f) throws IOException {+ return create(f, true,+ NutchConf.get().getInt("io.file.buffer.size", 4096));+ }++ /**+ * Opens an NFSDataOutputStream at the indicated File.+ * @param f the file name to open+ * @param overwrite if a file with this name already exists, then if true,+ * the file will be overwritten, and if false an error will be thrown.+ * @param bufferSize the size of the buffer to be used.+ */+ public NFSDataOutputStream create(File f, boolean overwrite,+ int bufferSize) throws IOException {+ return new NFSDataOutputStream(this, f, overwrite, bufferSize);+ }++ /** Opens an OutputStream at the indicated File.+ * @param f the file name to open+ * @param overwrite if a file with this name already exists, then if true,+ * the file will be overwritten, and if false an error will be thrown.*/- public abstract NFSOutputStream create(File f) throws IOException;- public abstract NFSOutputStream create(File f, boolean overwrite) throws IOException;+ public abstract NFSOutputStream createRaw(File f, boolean overwrite)+ throws IOException;/*** Creates the given File as a brand-new zero-length file. If@@ -129,10 +203,10 @@ public abstract class NutchFileSystem {if (exists(f)) {return false;} else {- OutputStream out = create(f);+ OutputStream out = createRaw(f, false);try {} finally {- out.close();+ out.close();}return true;}@@ -142,24 +216,52 @@ public abstract class NutchFileSystem {* Renames File src to File dst. Can take place on local fs* or remote NDFS.*/- public abstract boolean rename(File src, File dst) throws IOException;+ public boolean rename(File src, File dst) throws IOException {+ if (isDirectory(src)) {+ return renameRaw(src, dst);+ } else {++ boolean value = renameRaw(src, dst);++ File checkFile = getChecksumFile(src);+ if (exists(checkFile))+ renameRaw(checkFile, getChecksumFile(dst)); // try to rename checksum++ return value;+ }++ }/**- * Deletes File+ * Renames File src to File dst. Can take place on local fs+ * or remote NDFS.*/- public abstract boolean delete(File f) throws IOException;+ public abstract boolean renameRaw(File src, File dst) throws IOException;/**- * Check if exists+ * Deletes File*/- public abstract boolean exists(File f) throws IOException;+ public boolean delete(File f) throws IOException {+ if (isDirectory(f)) {+ return deleteRaw(f);+ } else {+ deleteRaw(getChecksumFile(f)); // try to delete checksum+ return deleteRaw(f);+ }+ }/**+ * Deletes File*/- public abstract boolean isDirectory(File f) throws IOException;+ public abstract boolean deleteRaw(File f) throws IOException;/**+ * Check if exists*/+ public abstract boolean exists(File f) throws IOException;++ public abstract boolean isDirectory(File f) throws IOException;+public boolean isFile(File f) throws IOException {if (exists(f) && ! isDirectory(f)) {return true;@@ -168,21 +270,27 @@ public abstract class NutchFileSystem {}}- /**- */public abstract long getLength(File f) throws IOException;- /**- */- public abstract File[] listFiles(File f) throws IOException;+ public File[] listFiles(File f) throws IOException {+ return listFiles(f, new FileFilter() {+ public boolean accept(File file) {+ return !isChecksumFile(file);+ }+ });+ }++ public abstract File[] listFilesRaw(File f) throws IOException;public File[] listFiles(File f, FileFilter filter) throws IOException {Vector results = new Vector();- File listing[] = listFiles(f);- for (int i = 0; i < listing.length; i++) {+ File listing[] = listFilesRaw(f);+ if (listing != null) {+ for (int i = 0; i < listing.length; i++) {if (filter.accept(listing[i])) {- results.add(listing[i]);+ results.add(listing[i]);}+ }}return (File[]) results.toArray(new File[results.size()]);}@@ -266,4 +374,17 @@ public abstract class NutchFileSystem {* release any held locks.*/public abstract void close() throws IOException;++ /**+ * Report a checksum error to the file system.+ * @param f the file name containing the error+ * @param in the stream open on the file+ * @param start the position of the beginning of the bad data in the file+ * @param length the length of the bad data in the file+ * @param crc the expected CRC32 of the data+ */+ public abstract void reportChecksumFailure(File f, NFSInputStream in,+ long start, long length,+ int crc);+}diff --git a/src/java/org/apache/nutch/fs/Seekable.java b/src/java/org/apache/nutch/fs/Seekable.javanew file mode 100644index 000000000..c154971a4--- /dev/null+++ b/src/java/org/apache/nutch/fs/Seekable.java@@ -0,0 +1,28 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.fs;++import java.io.*;++/* Stream which permits seeking. */+public interface Seekable {+ /**+ * Seek to the given offset from the start of the file.+ * The next read() will be from that location. Can't+ * seek past the end of the file.+ */+ void seek(long pos) throws IOException;+}diff --git a/src/java/org/apache/nutch/indexer/IndexMerger.java b/src/java/org/apache/nutch/indexer/IndexMerger.javaindex f50241a91..db3b5e1d8 100644--- a/src/java/org/apache/nutch/indexer/IndexMerger.java+++ b/src/java/org/apache/nutch/indexer/IndexMerger.java@@ -53,39 +53,39 @@ public class IndexMerger {private NutchFileSystem nfs;private File outputIndex;private File localWorkingDir;- private File[] segments;+ private File[] indexes;/**- * Merge all of the segments given+ * Merge all of the indexes given*/- public IndexMerger(NutchFileSystem nfs, File[] segments, File outputIndex, File localWorkingDir) throws IOException {+ public IndexMerger(NutchFileSystem nfs, File[] indexes, File outputIndex, File localWorkingDir) throws IOException {this.nfs = nfs;- this.segments = segments;+ this.indexes = indexes;this.outputIndex = outputIndex;this.localWorkingDir = localWorkingDir;}/**- * Load all input segment indices, then add to the single output index+ * All all input indexes to the single output index*/public void merge() throws IOException {//// Open local copies of NFS indices//- Directory[] dirs = new Directory[segments.length];- File[] localSegments = new File[segments.length];- for (int i = 0; i < segments.length; i++) {- File tmpFile = new File(localWorkingDir, "indexmerge-" + new SimpleDateFormat("yyyMMddHHmmss").format(new Date(System.currentTimeMillis())));- localSegments[i] = nfs.startLocalInput(new File(segments[i], "index"), tmpFile);- dirs[i] = FSDirectory.getDirectory(localSegments[i], false);- }- //// Get local output target//File tmpLocalOutput = new File(localWorkingDir, "merge-output");File localOutput = nfs.startLocalOutput(outputIndex, tmpLocalOutput);+ Directory[] dirs = new Directory[indexes.length];+ for (int i = 0; i < indexes.length; i++) {+ LOG.info("Adding " + indexes[i]);+ dirs[i] = new NdfsDirectory(nfs, indexes[i], false);+ }++ //+//// Merge indices//@@ -105,12 +105,6 @@ public class IndexMerger {//nfs.completeLocalOutput(outputIndex, tmpLocalOutput);- //- // Delete all local inputs, if necessary- //- for (int i = 0; i < localSegments.length; i++) {- nfs.completeLocalInput(localSegments[i]);- }localWorkingDir.delete();}@@ -118,50 +112,46 @@ public class IndexMerger {* Create an index for the input files in the named directory.*/public static void main(String[] args) throws Exception {- String usage = "IndexMerger (-local | -ndfs <nameserver:port>) [-workingdir <workingdir>] outputIndex segments...";+ String usage = "IndexMerger [-workingdir <workingdir>] outputIndex indexesDir...";if (args.length < 2) {System.err.println("Usage: " + usage);return;}//- // Parse args, read all segment directories to be processed+ // Parse args, read all index directories to be processed//- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- try {- File workingDir = new File(new File("").getCanonicalPath());- Vector segments = new Vector();-- int i = 0;- if ("-workingdir".equals(args[i])) {- i++;- workingDir = new File(new File(args[i++]).getCanonicalPath());- }- File outputIndex = new File(args[i++]);-- for (; i < args.length; i++) {- if (args[i] != null) {- segments.add(new File(args[i]));- }- }- workingDir = new File(workingDir, "indexmerger-workingdir");-- //- // Merge the indices- //- File[] segmentFiles = (File[]) segments.toArray(new File[segments.size()]);- LOG.info("merging segment indexes to: " + outputIndex);-- if (workingDir.exists()) {- FileUtil.fullyDelete(workingDir);- }- workingDir.mkdirs();- IndexMerger merger = new IndexMerger(nfs, segmentFiles, outputIndex, workingDir);- merger.merge();- LOG.info("done merging");- FileUtil.fullyDelete(workingDir);- } finally {- nfs.close();+ NutchFileSystem nfs = NutchFileSystem.get();+ File workDir = new File(new File("").getCanonicalPath());+ List indexDirs = new ArrayList();++ int i = 0;+ if ("-workingdir".equals(args[i])) {+ i++;+ workDir = new File(new File(args[i++]).getCanonicalPath());+ }+ workDir = new File(workDir, "indexmerger-workingdir");++ File outputIndex = new File(args[i++]);++ for (; i < args.length; i++) {+ indexDirs.addAll(Arrays.asList(nfs.listFiles(new File(args[i]))));+ }++ //+ // Merge the indices+ //+ LOG.info("merging indexes to: " + outputIndex);++ File[] indexFiles = (File[])indexDirs.toArray(new File[indexDirs.size()]);++ if (workDir.exists()) {+ FileUtil.fullyDelete(workDir);}+ workDir.mkdirs();+ IndexMerger merger = new IndexMerger(nfs,indexFiles,outputIndex,workDir);+ merger.merge();+ LOG.info("done merging");+ FileUtil.fullyDelete(workDir);}}diff --git a/src/java/org/apache/nutch/indexer/IndexOptimizer.java b/src/java/org/apache/nutch/indexer/IndexOptimizer.javadeleted file mode 100644index 3276fa3c8..000000000--- a/src/java/org/apache/nutch/indexer/IndexOptimizer.java+++ /dev/null@@ -1,243 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.File;-import java.io.IOException;-import java.util.BitSet;-import java.util.Date;--import org.apache.lucene.index.FilterIndexReader;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;-import org.apache.lucene.index.TermPositions;-import org.apache.lucene.search.ScoreDoc;-import org.apache.lucene.search.Similarity;-import org.apache.lucene.util.PriorityQueue;--/** */-public class IndexOptimizer {- public static final String DONE_NAME = "optimize.done";-- private static final float IDF_THRESHOLD = 6.0f;- private static final float FRACTION = 0.1f;-- private static class FilterTermDocs implements TermDocs {- protected TermDocs in;-- public FilterTermDocs(TermDocs in) { this.in = in; }-- public void seek(Term term) throws IOException { in.seek(term); }- public void seek(TermEnum e) throws IOException { in.seek(e); }- public int doc() { return in.doc(); }- public int freq() { return in.freq(); }- public boolean next() throws IOException { return in.next(); }- public int read(int[] docs, int[] freqs) throws IOException {- return in.read(docs, freqs);- }- public boolean skipTo(int i) throws IOException { return in.skipTo(i); }- public void close() throws IOException { in.close(); }- }-- private static class FilterTermPositions- extends FilterTermDocs implements TermPositions {-- public FilterTermPositions(TermPositions in) { super(in); }-- public int nextPosition() throws IOException {- return ((TermPositions)in).nextPosition();- }- }-- private static class FilterTermEnum extends TermEnum {- protected TermEnum in;-- public FilterTermEnum(TermEnum in) { this.in = in; }-- public boolean next() throws IOException { return in.next(); }- public Term term() { return in.term(); }- public int docFreq() { return in.docFreq(); }- public void close() throws IOException { in.close(); }- }-- private static class OptimizingTermEnum extends FilterTermEnum {- private IndexReader reader;- private Similarity similarity;-- public OptimizingTermEnum(IndexReader reader, Similarity similarity)- throws IOException {- super(reader.terms());- this.reader = reader;- this.similarity = similarity;- }-- public boolean next() throws IOException {- while (in.next()) {- float idf = similarity.idf(in.docFreq(), reader.maxDoc());-- if (idf <= IDF_THRESHOLD)- return true;- }- return false;- }- }-- private static class ScoreDocQueue extends PriorityQueue {- ScoreDocQueue(int size) {- initialize(size);- }-- protected final boolean lessThan(Object a, Object b) {- ScoreDoc hitA = (ScoreDoc)a;- ScoreDoc hitB = (ScoreDoc)b;- if (hitA.score == hitB.score)- return hitA.doc > hitB.doc;- else- return hitA.score < hitB.score;- }- }-- private static class OptimizingTermPositions extends FilterTermPositions {- private IndexReader reader;- private TermDocs termDocs;- private int docFreq;- private ScoreDocQueue sdq;- private BitSet docs;- private Similarity similarity;-- public OptimizingTermPositions(IndexReader reader, Similarity similarity)- throws IOException {- super(reader.termPositions());- this.reader = reader;- this.termDocs = reader.termDocs();- this.similarity = similarity;- this.sdq = new ScoreDocQueue((int)Math.ceil(reader.maxDoc() * FRACTION));- this.docs = new BitSet(reader.maxDoc());- }-- public void seek(TermEnum e) throws IOException {- super.seek(e);- termDocs.seek(e);-- byte[] norms = reader.norms(e.term().field());-- sdq.clear();- float minScore = 0.0f;- int count = (int)Math.ceil(e.docFreq() * FRACTION);- System.out.println("Optimizing " + e.term()- + " from " + e.docFreq()- + " to " + count);- while (termDocs.next()) {- int doc = termDocs.doc();- float score =- similarity.tf(termDocs.freq()) * similarity.decodeNorm(norms[doc]);-- if (score > minScore) {- sdq.put(new ScoreDoc(doc, score));- if (sdq.size() > count) { // if sdq overfull- sdq.pop(); // remove lowest in sdq- minScore = ((ScoreDoc)sdq.top()).score; // reset minScore- }- }- }-- docs.clear();- while (sdq.size() != 0) {- docs.set(((ScoreDoc)sdq.pop()).doc);- }-- }-- public boolean next() throws IOException {- while (in.next()) {- if (docs.get(in.doc()))- return true;- }- return false;- }-- }-- private static class OptimizingReader extends FilterIndexReader {- private Similarity similarity = new NutchSimilarity();--- public OptimizingReader(IndexReader reader) {- super(reader);- }-- // don't copy any per-document data- public int numDocs() { return 0; }- public int maxDoc() { return 0; }-- // filter out low frequency terms- public TermEnum terms() throws IOException {- return new OptimizingTermEnum(in, similarity);- }-- // filter out low-scoring postings- public TermPositions termPositions() throws IOException {- return new OptimizingTermPositions(in, similarity);- }-- public boolean hasDeletions() { return false; }- }--- private File directory;-- public IndexOptimizer(File directory) {- this.directory = directory;- }-- public void optimize() throws IOException {- IndexReader reader = IndexReader.open(new File(directory, "index"));- OptimizingReader optimizer = new OptimizingReader(reader);- IndexWriter writer = new IndexWriter(new File(directory, "index-opt"),- null, true);- writer.addIndexes(new IndexReader[] { optimizer });- }-- /** */- public static void main(String[] args) throws Exception {- File directory;-- String usage = "IndexOptimizer directory";-- if (args.length < 1) {- System.err.println("Usage: " + usage);- return;- }-- directory = new File(args[0]);-- IndexOptimizer optimizer = new IndexOptimizer(directory);-- Date start = new Date();-- optimizer.optimize();-- Date end = new Date();-- System.out.print(end.getTime() - start.getTime());- System.out.println(" total milliseconds");- }--}diff --git a/src/java/org/apache/nutch/indexer/NdfsDirectory.java b/src/java/org/apache/nutch/indexer/NdfsDirectory.javanew file mode 100644index 000000000..885282254--- /dev/null+++ b/src/java/org/apache/nutch/indexer/NdfsDirectory.java@@ -0,0 +1,241 @@+/**+ * Copyright 2004 The Apache Software Foundation+ *+ * Licensed 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.*;+import org.apache.lucene.store.*;+import org.apache.nutch.fs.*;++/** Reads a Lucene index stored in NDFS. */+public class NdfsDirectory extends Directory {++ private NutchFileSystem fs;+ private File directory;++ public NdfsDirectory(NutchFileSystem fs, File directory, boolean create)+ throws IOException {++ this.fs = fs;+ this.directory = directory;++ if (create) {+ create();+ }++ if (!fs.isDirectory(directory))+ throw new IOException(directory + " not a directory");+ }++ private void create() throws IOException {+ if (!fs.exists(directory)) {+ fs.mkdirs(directory);+ }++ if (!fs.isDirectory(directory))+ throw new IOException(directory + " not a directory");++ // clear old files+ File[] files = fs.listFiles(directory);+ for (int i = 0; i < files.length; i++) {+ if (!files[i].delete())+ throw new IOException("Cannot delete " + files[i]);+ }+ }++ public String[] list() throws IOException {+ File[] files = fs.listFiles(directory);+ if (files == null) return null;++ String[] result = new String[files.length];+ for (int i = 0; i < files.length; i++) {+ result[i] = files[i].getName();+ }+ return result;+ }++ public boolean fileExists(String name) throws IOException {+ return fs.exists(new File(directory, name));+ }++ public long fileModified(String name) {+ throw new UnsupportedOperationException();+ }++ public void touchFile(String name) {+ throw new UnsupportedOperationException();+ }++ public long fileLength(String name) throws IOException {+ return fs.getLength(new File(directory, name));+ }++ public void deleteFile(String name) throws IOException {+ if (!fs.delete(new File(directory, name)))+ throw new IOException("Cannot delete " + name);+ }++ public void renameFile(String from, String to) throws IOException {+ // NDFS is currently broken when target already exists,+ // so we explicitly delete the target first.+ File target = new File(directory, to);+ if (fs.exists(target)) {+ fs.delete(target);+ }+ fs.rename(new File(directory, from), target);+ }++ public IndexOutput createOutput(String name) throws IOException {+ File file = new File(directory, name);+ if (fs.exists(file) && !fs.delete(file)) // delete existing, if any+ throw new IOException("Cannot overwrite: " + file);++ return new NdfsIndexOutput(file);+ }+++ public IndexInput openInput(String name) throws IOException {+ return new NdfsIndexInput(new File(directory, name));+ }++ public Lock makeLock(final String name) {+ return new Lock() {+ public boolean obtain() {+ try {+ fs.lock(new File(directory, name), false);+ return true;+ } catch (IOException e) {+ return false;+ }+ }+ public void release() {+ try {+ fs.release(new File(directory, name));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ public boolean isLocked() {+ throw new UnsupportedOperationException();+ }+ public String toString() {+ return "Lock@" + new File(directory, name);+ }+ };+ }++ public synchronized void close() throws IOException {+ fs.close();+ }++ public String toString() {+ return this.getClass().getName() + "@" + directory;+ }+++ private class NdfsIndexInput extends BufferedIndexInput {++ /** Shared by clones. */+ private class Descriptor {+ public NFSDataInputStream in;+ public long position; // cache of in.getPos()+ public Descriptor(File file) throws IOException {+ this.in = fs.open(file);+ }+ }++ private final Descriptor descriptor;+ private final long length;+ private boolean isClone;++ public NdfsIndexInput(File path) throws IOException {+ descriptor = new Descriptor(path);+ length = fs.getLength(path);+ }++ protected void readInternal(byte[] b, int offset, int len)+ throws IOException {+ synchronized (descriptor) {+ long position = getFilePointer();+ if (position != descriptor.position) {+ descriptor.in.seek(position);+ descriptor.position = position;+ }+ int total = 0;+ do {+ int i = descriptor.in.read(b, offset+total, len-total);+ if (i == -1)+ throw new IOException("read past EOF");+ descriptor.position += i;+ total += i;+ } while (total < len);+ }+ }++ public void close() throws IOException {+ if (!isClone) {+ descriptor.in.close();+ }+ }++ protected void seekInternal(long position) {} // handled in readInternal()++ public long length() {+ return length;+ }++ protected void finalize() throws IOException {+ close(); // close the file+ }++ public Object clone() {+ NdfsIndexInput clone = (NdfsIndexInput)super.clone();+ clone.isClone = true;+ return clone;+ }+ }++ private class NdfsIndexOutput extends BufferedIndexOutput {+ private NFSDataOutputStream out;++ public NdfsIndexOutput(File path) throws IOException {+ out = fs.create(path);+ }++ public void flushBuffer(byte[] b, int size) throws IOException {+ out.write(b, 0, size);+ }++ public void close() throws IOException {+ super.close();+ out.close();+ }++ public void seek(long pos) throws IOException {+ throw new UnsupportedOperationException();+ }++ public long length() throws IOException {+ return out.getPos();+ }++ protected void finalize() throws IOException {+ out.close(); // close the file+ }++ }++}diff --git a/src/java/org/apache/nutch/io/CompressedWritable.java b/src/java/org/apache/nutch/io/CompressedWritable.javanew file mode 100644index 000000000..f90bdfddd--- /dev/null+++ b/src/java/org/apache/nutch/io/CompressedWritable.java@@ -0,0 +1,83 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io;++import java.io.IOException;+import java.io.DataInput;+import java.io.DataOutput;+import java.io.DataOutputStream;+import java.io.DataInputStream;+import java.io.ByteArrayOutputStream;+import java.io.ByteArrayInputStream;+import java.util.zip.Deflater;+import java.util.zip.DeflaterOutputStream;+import java.util.zip.InflaterInputStream;++/** A base-class for Writables which store themselves compressed and lazily+ * inflate on field access. This is useful for large objects whose fields are+ * not be altered during a map or reduce operation: leaving the field data+ * compressed makes copying the instance from one file to another much+ * faster. */+public abstract class CompressedWritable implements Writable {+ // if non-null, the compressed field data of this instance.+ private byte[] compressed;++ public CompressedWritable() {}++ public final void readFields(DataInput in) throws IOException {+ compressed = new byte[in.readInt()];+ in.readFully(compressed, 0, compressed.length);+ }++ /** Must be called by all methods which access fields to ensure that the data+ * has been uncompressed. */+ protected void ensureInflated() {+ if (compressed != null) {+ try {+ ByteArrayInputStream deflated = new ByteArrayInputStream(compressed);+ DataInput inflater =+ new DataInputStream(new InflaterInputStream(deflated));+ readFieldsCompressed(inflater);+ compressed = null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ }++ /** Subclasses implement this instead of {@link #readFields(DataInput)}. */+ protected abstract void readFieldsCompressed(DataInput in)+ throws IOException;++ public final void write(DataOutput out) throws IOException {+ if (compressed == null) {+ ByteArrayOutputStream deflated = new ByteArrayOutputStream();+ Deflater deflater = new Deflater(Deflater.BEST_SPEED);+ DataOutputStream dout =+ new DataOutputStream(new DeflaterOutputStream(deflated, deflater));+ writeCompressed(dout);+ dout.close();+ compressed = deflated.toByteArray();+ }+ out.writeInt(compressed.length);+ out.write(compressed);+ }++ /** Subclasses implement this instead of {@link #write(DataOutput)}. */+ protected abstract void writeCompressed(DataOutput out) throws IOException;++}diff --git a/src/java/org/apache/nutch/io/DataInputBuffer.java b/src/java/org/apache/nutch/io/DataInputBuffer.javaindex 6a83473aa..203ea567f 100644--- a/src/java/org/apache/nutch/io/DataInputBuffer.java+++ b/src/java/org/apache/nutch/io/DataInputBuffer.java@@ -53,6 +53,7 @@ public class DataInputBuffer extends DataInputStream {}public int getPosition() { return pos; }+ public int getLength() { return count; }}private Buffer buffer;@@ -80,4 +81,7 @@ public class DataInputBuffer extends DataInputStream {/** Returns the current position in the input. */public int getPosition() { return buffer.getPosition(); }+ /** Returns the length of the input. */+ public int getLength() { return buffer.getLength(); }+}diff --git a/src/java/org/apache/nutch/io/MapFile.java b/src/java/org/apache/nutch/io/MapFile.javaindex ccaddff57..f05e33884 100644--- a/src/java/org/apache/nutch/io/MapFile.java+++ b/src/java/org/apache/nutch/io/MapFile.java@@ -70,21 +70,35 @@ public class MapFile {/** Create the named map for keys of the named class. */- public Writer(NutchFileSystem nfs, String dirName, Class keyClass, Class valClass)+ public Writer(NutchFileSystem nfs, String dirName,+ Class keyClass, Class valClass)throws IOException {- this(nfs, dirName, WritableComparator.get(keyClass), valClass);+ this(nfs, dirName, WritableComparator.get(keyClass), valClass, false);}+ /** Create the named map for keys of the named class. */+ public Writer(NutchFileSystem nfs, String dirName,+ Class keyClass, Class valClass, boolean compress)+ throws IOException {+ this(nfs, dirName, WritableComparator.get(keyClass), valClass, compress);+ }++ /** Create the named map using the named key comparator. */+ public Writer(NutchFileSystem nfs, String dirName,+ WritableComparator comparator, Class valClass)+ throws IOException {+ this(nfs, dirName, comparator, valClass, false);+ }/** Create the named map using the named key comparator. */- public Writer(NutchFileSystem nfs, String dirName, WritableComparator- comparator, Class valClass) throws IOException {+ public Writer(NutchFileSystem nfs, String dirName,+ WritableComparator comparator, Class valClass,+ boolean compress)+ throws IOException {+this.comparator = comparator;this.lastKey = comparator.newKey();File dir = new File(dirName);- if (nfs.exists(dir)) {- throw new IOException("already exists: " + dir);- }nfs.mkdirs(dir);File dataFile = new File(dir, DATA_FILE_NAME);@@ -92,7 +106,8 @@ public class MapFile {Class keyClass = comparator.getKeyClass();this.data =- new SequenceFile.Writer(nfs, dataFile.getPath(), keyClass, valClass);+ new SequenceFile.Writer(nfs, dataFile.getPath(), keyClass, valClass,+ compress);this.index =new SequenceFile.Writer(nfs, indexFile.getPath(),keyClass, LongWritable.class);@@ -112,8 +127,8 @@ public class MapFile {index.close();}- /** Append a key/value pair to the map. The key must be strictly greater- * than the previous key added to the map. */+ /** Append a key/value pair to the map. The key must be greater or equal+ * to the previous key added to the map. */public synchronized void append(WritableComparable key, Writable val)throws IOException {@@ -130,7 +145,7 @@ public class MapFile {private void checkKey(WritableComparable key) throws IOException {// check that keys are well-ordered- if (size != 0 && comparator.compare(lastKey, key) >= 0)+ if (size != 0 && comparator.compare(lastKey, key) > 0)throw new IOException("key out of order: "+key+" after "+lastKey);// update lastKey with a copy of key by writing and reading@@ -219,7 +234,7 @@ public class MapFile {break;// check order to make sure comparator is compatible- if (lastKey != null && comparator.compare(lastKey, k) >= 0)+ if (lastKey != null && comparator.compare(lastKey, k) > 0)throw new IOException("key out of order: "+k+" after "+lastKey);lastKey = k;diff --git a/src/java/org/apache/nutch/io/ObjectWritable.java b/src/java/org/apache/nutch/io/ObjectWritable.javanew file mode 100644index 000000000..bcf9c06af--- /dev/null+++ b/src/java/org/apache/nutch/io/ObjectWritable.java@@ -0,0 +1,250 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io;++import java.lang.reflect.Proxy;+import java.lang.reflect.Method;+import java.lang.reflect.Array;+import java.lang.reflect.InvocationHandler;+import java.lang.reflect.InvocationTargetException;++import java.io.*;+import java.util.*;++/** A polymorphic Writable that writes an instance with it's class name.+ * Handles arrays, strings and primitive types without a Writable wrapper.+ */+public class ObjectWritable implements Writable {++ private Class declaredClass;+ private Object instance;++ public ObjectWritable() {}++ public ObjectWritable(Object instance) {+ set(instance);+ }++ public ObjectWritable(Class declaredClass, Object instance) {+ this.declaredClass = declaredClass;+ this.instance = instance;+ }++ /** Return the instance, or null if none. */+ public Object get() { return instance; }++ /** Return the class this is meant to be. */+ public Class getDeclaredClass() { return declaredClass; }++ /** Reset the instance. */+ public void set(Object instance) {+ this.declaredClass = instance.getClass();+ this.instance = instance;+ }++ public void readFields(DataInput in) throws IOException {+ readObject(in, this);+ }++ public void write(DataOutput out) throws IOException {+ writeObject(out, instance, declaredClass);+ }++ private static final Map PRIMITIVE_NAMES = new HashMap();+ static {+ PRIMITIVE_NAMES.put("boolean", Boolean.TYPE);+ PRIMITIVE_NAMES.put("byte", Byte.TYPE);+ PRIMITIVE_NAMES.put("char", Character.TYPE);+ PRIMITIVE_NAMES.put("short", Short.TYPE);+ PRIMITIVE_NAMES.put("int", Integer.TYPE);+ PRIMITIVE_NAMES.put("long", Long.TYPE);+ PRIMITIVE_NAMES.put("float", Float.TYPE);+ PRIMITIVE_NAMES.put("double", Double.TYPE);+ PRIMITIVE_NAMES.put("void", Void.TYPE);+ }++ private static class NullInstance implements Writable {+ private Class declaredClass;+ public NullInstance() {}+ public NullInstance(Class declaredClass) {+ this.declaredClass = declaredClass;+ }+ public void readFields(DataInput in) throws IOException {+ String className = UTF8.readString(in);+ declaredClass = (Class)PRIMITIVE_NAMES.get(className);+ if (declaredClass == null) {+ try {+ declaredClass = Class.forName(className);+ } catch (ClassNotFoundException e) {+ throw new RuntimeException(e.toString());+ }+ }+ }+ public void write(DataOutput out) throws IOException {+ UTF8.writeString(out, declaredClass.getName());+ }+ }++ /** Write a {@link Writable}, {@link String}, primitive type, or an array of+ * the preceding. */+ public static void writeObject(DataOutput out, Object instance,+ Class declaredClass) throws IOException {++ if (instance == null) { // null+ instance = new NullInstance(declaredClass);+ declaredClass = NullInstance.class;+ }++ if (instance instanceof Writable) { // Writable++ // write instance's class, to support subclasses of the declared class+ UTF8.writeString(out, instance.getClass().getName());++ ((Writable)instance).write(out);++ return;+ }++ // write declared class for primitives, as they can't be subclassed, and+ // the class of the instance may be a wrapper+ UTF8.writeString(out, declaredClass.getName());++ if (declaredClass.isArray()) { // array+ int length = Array.getLength(instance);+ out.writeInt(length);+ for (int i = 0; i < length; i++) {+ writeObject(out, Array.get(instance, i),+ declaredClass.getComponentType());+ }++ } else if (declaredClass == String.class) { // String+ UTF8.writeString(out, (String)instance);++ } else if (declaredClass.isPrimitive()) { // primitive type++ if (declaredClass == Boolean.TYPE) { // boolean+ out.writeBoolean(((Boolean)instance).booleanValue());+ } else if (declaredClass == Character.TYPE) { // char+ out.writeChar(((Character)instance).charValue());+ } else if (declaredClass == Byte.TYPE) { // byte+ out.writeByte(((Byte)instance).byteValue());+ } else if (declaredClass == Short.TYPE) { // short+ out.writeShort(((Short)instance).shortValue());+ } else if (declaredClass == Integer.TYPE) { // int+ out.writeInt(((Integer)instance).intValue());+ } else if (declaredClass == Long.TYPE) { // long+ out.writeLong(((Long)instance).longValue());+ } else if (declaredClass == Float.TYPE) { // float+ out.writeFloat(((Float)instance).floatValue());+ } else if (declaredClass == Double.TYPE) { // double+ out.writeDouble(((Double)instance).doubleValue());+ } else if (declaredClass == Void.TYPE) { // void+ } else {+ throw new IllegalArgumentException("Not a primitive: "+declaredClass);+ }++ } else {+ throw new IOException("Can't write: "+instance+" as "+declaredClass);+ }+ }+++ /** Read a {@link Writable}, {@link String}, primitive type, or an array of+ * the preceding. */+ public static Object readObject(DataInput in)+ throws IOException {+ return readObject(in, null);+ }++ /** Read a {@link Writable}, {@link String}, primitive type, or an array of+ * the preceding. */+ public static Object readObject(DataInput in, ObjectWritable objectWritable)+ throws IOException {+ String className = UTF8.readString(in);+ Class declaredClass = (Class)PRIMITIVE_NAMES.get(className);+ if (declaredClass == null) {+ try {+ declaredClass = Class.forName(className);+ } catch (ClassNotFoundException e) {+ throw new RuntimeException(e.toString());+ }+ }++ Object instance;++ if (declaredClass == NullInstance.class) { // null+ NullInstance wrapper = new NullInstance();+ wrapper.readFields(in);+ declaredClass = wrapper.declaredClass;+ instance = null;++ } else if (declaredClass.isPrimitive()) { // primitive types++ if (declaredClass == Boolean.TYPE) { // boolean+ instance = Boolean.valueOf(in.readBoolean());+ } else if (declaredClass == Character.TYPE) { // char+ instance = new Character(in.readChar());+ } else if (declaredClass == Byte.TYPE) { // byte+ instance = new Byte(in.readByte());+ } else if (declaredClass == Short.TYPE) { // short+ instance = new Short(in.readShort());+ } else if (declaredClass == Integer.TYPE) { // int+ instance = new Integer(in.readInt());+ } else if (declaredClass == Long.TYPE) { // long+ instance = new Long(in.readLong());+ } else if (declaredClass == Float.TYPE) { // float+ instance = new Float(in.readFloat());+ } else if (declaredClass == Double.TYPE) { // double+ instance = new Double(in.readDouble());+ } else if (declaredClass == Void.TYPE) { // void+ instance = null;+ } else {+ throw new IllegalArgumentException("Not a primitive: "+declaredClass);+ }++ } else if (declaredClass.isArray()) { // array+ int length = in.readInt();+ instance = Array.newInstance(declaredClass.getComponentType(), length);+ for (int i = 0; i < length; i++) {+ Array.set(instance, i, readObject(in));+ }++ } else if (declaredClass == String.class) { // String+ instance = UTF8.readString(in);++ } else { // Writable+ try {+ Writable writable = (Writable)declaredClass.newInstance();+ writable.readFields(in);+ instance = writable;+ } catch (InstantiationException e) {+ throw new RuntimeException(e);+ } catch (IllegalAccessException e) {+ throw new RuntimeException(e);+ }+ }++ if (objectWritable != null) { // store values+ objectWritable.declaredClass = declaredClass;+ objectWritable.instance = instance;+ }++ return instance;++ }++}diff --git a/src/java/org/apache/nutch/io/SequenceFile.java b/src/java/org/apache/nutch/io/SequenceFile.javaindex 8bac31830..22c38dbce 100644--- a/src/java/org/apache/nutch/io/SequenceFile.java+++ b/src/java/org/apache/nutch/io/SequenceFile.java@@ -18,6 +18,7 @@ package org.apache.nutch.io;import java.io.*;import java.util.*;+import java.util.zip.*;import java.util.logging.*;import java.nio.channels.*;import java.net.InetAddress;@@ -35,14 +36,16 @@ public class SequenceFile {private SequenceFile() {} // no public ctorprivate static byte[] VERSION = new byte[] {- (byte)'S', (byte)'E', (byte)'Q', 2+ (byte)'S', (byte)'E', (byte)'Q', 3};private static final int SYNC_ESCAPE = -1; // "length" of sync entries- private static final int SYNC_INTERVAL = 10; // num entries between syncsprivate static final int SYNC_HASH_SIZE = 16; // number of bytes in hashprivate static final int SYNC_SIZE = 4+SYNC_HASH_SIZE; // escape + hash+ /** The number of bytes between sync points.*/+ public static final int SYNC_INTERVAL = 100*SYNC_SIZE;+/** Write key/value pairs to a sequence-format file. */public static class Writer {private NFSDataOutputStream out;@@ -53,11 +56,16 @@ public class SequenceFile {private Class keyClass;private Class valClass;+ private boolean deflateValues;+ private DataOutputBuffer deflateIn = new DataOutputBuffer();+ private byte[] deflateOut = new byte[1024];+ private Deflater deflater = new Deflater(Deflater.BEST_SPEED);+// Insert a globally unique 16-byte value every few entries, so that one// can seek into the middle of a file and then synchronize with record// starts and ends by scanning for this value.- private long count; // number of entries added- private final byte[] sync; // 16 random bytes+ private long lastSyncPos; // position of last sync+ private byte[] sync; // 16 random bytes{try { // use hash of uid + hostMessageDigest digester = MessageDigest.getInstance("MD5");@@ -72,33 +80,44 @@ public class SequenceFile {public Writer(NutchFileSystem nfs, String name,Class keyClass, Class valClass)throws IOException {+ this(nfs, name, keyClass, valClass, false);+ }++ /** Create the named file.+ * @param compress if true, values are compressed.+ */+ public Writer(NutchFileSystem nfs, String name,+ Class keyClass, Class valClass, boolean compress)+ throws IOException {this.nfs = nfs;this.target = new File(name);- if (nfs.exists(target)) {- throw new IOException("already exists: " + target);- }- init(new NFSDataOutputStream(nfs.create(target)),- keyClass, valClass);+ init(nfs.create(target), keyClass, valClass, compress);}/** Write to an arbitrary stream using a specified buffer size. */private Writer(NFSDataOutputStream out,- Class keyClass, Class valClass) throws IOException {- init(out, keyClass, valClass);+ Class keyClass, Class valClass, boolean compress)+ throws IOException {+ init(out, keyClass, valClass, compress);}/** Write and flush the file header. */private void init(NFSDataOutputStream out,- Class keyClass, Class valClass) throws IOException {+ Class keyClass, Class valClass,+ boolean compress) throws IOException {this.out = out;this.out.write(VERSION);this.keyClass = keyClass;this.valClass = valClass;+ this.deflateValues = compress;+new UTF8(WritableName.getName(keyClass)).write(this.out);new UTF8(WritableName.getName(valClass)).write(this.out);+ this.out.writeBoolean(deflateValues);+out.write(sync); // write the sync bytesthis.out.flush(); // flush header@@ -113,7 +132,7 @@ public class SequenceFile {/** Close the file. */- public void close() throws IOException {+ public synchronized void close() throws IOException {if (out != null) {out.close();out = null;@@ -121,7 +140,8 @@ public class SequenceFile {}/** Append a key/value pair. */- public void append(Writable key, Writable val) throws IOException {+ public synchronized void append(Writable key, Writable val)+ throws IOException {if (key.getClass() != keyClass)throw new IOException("wrong key class: "+key+" is not "+keyClass);if (val.getClass() != valClass)@@ -134,17 +154,33 @@ public class SequenceFile {if (keyLength == 0)throw new IOException("zero length keys not allowed: " + key);- val.write(buffer);+ if (deflateValues) {+ deflateIn.reset();+ val.write(deflateIn);+ deflater.reset();+ deflater.setInput(deflateIn.getData(), 0, deflateIn.getLength());+ deflater.finish();+ while (!deflater.finished()) {+ int count = deflater.deflate(deflateOut);+ buffer.write(deflateOut, 0, count);+ }+ } else {+ val.write(buffer);+ }+append(buffer.getData(), 0, buffer.getLength(), keyLength);}/** Append a key/value pair. */- public void append(byte[] data, int start, int length, int keyLength)- throws IOException {+ public synchronized void append(byte[] data, int start, int length,+ int keyLength) throws IOException {if (keyLength == 0)throw new IOException("zero length keys not allowed");- if ((++count % SYNC_INTERVAL) == 0) { // time to emit sync+ if (sync != null &&+ out.getPos() >= lastSyncPos+SYNC_INTERVAL) { // time to emit sync+ lastSyncPos = out.getPos(); // update lastSyncPos+ //LOG.info("sync@"+lastSyncPos);out.writeInt(SYNC_ESCAPE); // escape itout.write(sync); // write sync}@@ -156,7 +192,7 @@ public class SequenceFile {}/** Returns the current length of the output file. */- public long getLength() throws IOException {+ public synchronized long getLength() throws IOException {return out.getPos();}@@ -182,6 +218,11 @@ public class SequenceFile {private long end;private int keyLength;+ private boolean inflateValues;+ private byte[] inflateIn = new byte[1024];+ private DataOutputBuffer inflateOut = new DataOutputBuffer();+ private Inflater inflater = new Inflater();+/** Open the named file. */public Reader(NutchFileSystem nfs, String file) throws IOException {this(nfs, file, NutchConf.get().getInt("io.file.buffer.size", 4096));@@ -191,7 +232,7 @@ public class SequenceFile {this.nfs = nfs;this.file = name;File file = new File(name);- this.in = new NFSDataInputStream(nfs.open(file), bufferSize);+ this.in = nfs.open(file, bufferSize);this.end = nfs.getLength(file);init();}@@ -200,7 +241,7 @@ public class SequenceFile {throws IOException {this.nfs = nfs;this.file = file;- this.in = new NFSDataInputStream(nfs.open(new File(file)), bufferSize);+ this.in = nfs.open(new File(file), bufferSize);seek(start);init();@@ -226,6 +267,10 @@ public class SequenceFile {className.readFields(in); // read val class namethis.valClass = WritableName.getClass(className.toString());+ if (version[3] > 2) { // if version > 2+ this.inflateValues = in.readBoolean(); // is compressed?+ }+if (version[3] > 1) { // if version > 1in.readFully(sync); // read sync bytes}@@ -242,6 +287,9 @@ public class SequenceFile {/** Returns the class of values in this file. */public Class getValueClass() { return valClass; }+ /** Returns true if values are compressed. */+ public boolean isCompressed() { return inflateValues; }+/** Read the next key in the file into <code>key</code>, skipping its* value. True if another entry exists, and false at end of file. */public synchronized boolean next(Writable key) throws IOException {@@ -275,11 +323,29 @@ public class SequenceFile {boolean more = next(key);if (more) {++ if (inflateValues) {+ inflater.reset();+ inflater.setInput(outBuf.getData(), keyLength,+ outBuf.getLength()-keyLength);+ inflateOut.reset();+ while (!inflater.finished()) {+ try {+ int count = inflater.inflate(inflateIn);+ inflateOut.write(inflateIn, 0, count);+ } catch (DataFormatException e) {+ throw new IOException (e.toString());+ }+ }+ inBuf.reset(inflateOut.getData(), inflateOut.getLength());+ }+val.readFields(inBuf);- if (inBuf.getPosition() != outBuf.getLength())++ if (inBuf.getPosition() != inBuf.getLength())throw new IOException(val+" read "+(inBuf.getPosition()-keyLength)+ " bytes, should read " +- (outBuf.getLength()-keyLength));+ (inBuf.getLength()-keyLength));}return more;@@ -293,21 +359,39 @@ public class SequenceFile {if (in.getPos() >= end)return -1;- int length = in.readInt();+ try {+ int length = in.readInt();++ if (version[3] > 1 && sync != null &&+ length == SYNC_ESCAPE) { // process a sync entry+ //LOG.info("sync@"+in.getPos());+ in.readFully(syncCheck); // read syncCheck+ if (!Arrays.equals(sync, syncCheck)) // check it+ throw new IOException("File is corrupt!");+ syncSeen = true;+ length = in.readInt(); // re-read length+ } else {+ syncSeen = false;+ }++ int keyLength = in.readInt();+ buffer.write(in, length);+ return keyLength;- if (version[3] > 1 && length == SYNC_ESCAPE) { // process a sync entry- in.readFully(syncCheck); // read syncCheck- if (!Arrays.equals(sync, syncCheck)) // check it- throw new IOException("File is corrupt!");- syncSeen = true;- length = in.readInt(); // re-read length- } else {- syncSeen = false;+ } catch (ChecksumException e) { // checksum failure+ handleChecksumException(e);+ return next(buffer);}+ }- int keyLength = in.readInt();- buffer.write(in, length);- return keyLength;+ private void handleChecksumException(ChecksumException e)+ throws IOException {+ if (NutchConf.get().getBoolean("io.skip.checksum.errors", false)) {+ LOG.warning("Bad checksum at "+getPosition()+". Skipping entries.");+ sync(getPosition()+NutchConf.get().getInt("io.bytes.per.checksum", 512));+ } else {+ throw e;+ }}/** Set the current byte position in the input file. */@@ -317,23 +401,29 @@ public class SequenceFile {/** Seek to the next sync mark past a given position.*/public synchronized void sync(long position) throws IOException {- if (position+sync.length >= end) {+ if (position+SYNC_SIZE >= end) {seek(end);return;}- seek(position);- in.readFully(syncCheck);- int syncLen = sync.length;- for (int i = 0; in.getPos() < end; i++) {- int j = 0;- for (; j < syncLen; j++) {- if (sync[j] != syncCheck[(i+j)%syncLen])- break;+ try {+ seek(position+4); // skip escape+ in.readFully(syncCheck);+ int syncLen = sync.length;+ for (int i = 0; in.getPos() < end; i++) {+ int j = 0;+ for (; j < syncLen; j++) {+ if (sync[j] != syncCheck[(i+j)%syncLen])+ break;+ }+ if (j == syncLen) {+ in.seek(in.getPos() - SYNC_SIZE); // position before sync+ return;+ }+ syncCheck[i%syncLen] = in.readByte();}- if (j == syncLen)- return;- syncCheck[i%syncLen] = in.readByte();+ } catch (ChecksumException e) { // checksum failure+ handleChecksumException(e);}}@@ -514,20 +604,22 @@ public class SequenceFile {private void flush(int count, boolean done) throws IOException {if (out == null) {outName = done ? outFile : outFile+".0";- out = new NFSDataOutputStream(nfs.create(new File(outName)));+ out = nfs.create(new File(outName));}if (!done) { // an intermediate filelong length = buffer.getLength(); // compute its sizelength += count*8; // allow for length/keyLength- length += (count/SYNC_INTERVAL)*SYNC_SIZE; // allow for syncsout.writeLong(length); // write sizeout.writeLong(count); // write count}- Writer writer = new Writer(out, keyClass, valClass);+ Writer writer = new Writer(out, keyClass, valClass, in.isCompressed());+ if (!done) {+ writer.sync = null; // disable sync on temp files+ }for (int i = 0; i < count; i++) { // write in sorted orderint p = pointers[i];@@ -606,10 +698,11 @@ public class SequenceFile {this.pass = pass;this.last = last;- this.queue = new MergeQueue(factor, last ? outFile : outFile+"."+pass);+ this.queue =+ new MergeQueue(factor, last ? outFile : outFile+"."+pass, last);this.inName = outFile+"."+(pass-1);- this.in = new NFSDataInputStream(nfs.open(new File(inName)));+ this.in = nfs.open(new File(inName));}public void close() throws IOException {@@ -632,21 +725,21 @@ public class SequenceFile {long count = in.readLong();totalLength += length;- totalLength -= (count/SYNC_INTERVAL)*SYNC_SIZE; // remove syncstotalCount+= count;Reader reader = new Reader(nfs, inName, memory/(factor+1),in.getPos(), length);+ reader.sync = null; // disable sync on temp files+MergeStream ms = new MergeStream(reader); // add segment to queueif (ms.next()) {- queue.put(ms);+ queue.add(ms);}in.seek(reader.end);}if (!last) { // intermediate file- totalLength += (totalCount/SYNC_INTERVAL)*SYNC_SIZE; // add syncsqueue.out.writeLong(totalLength); // write sizequeue.out.writeLong(totalCount); // write count}@@ -683,7 +776,7 @@ public class SequenceFile {private MergeQueue queue;public MergeFiles() throws IOException {- this.queue = new MergeQueue(factor, outFile);+ this.queue = new MergeQueue(factor, outFile, true);}public void close() throws IOException {@@ -729,12 +822,23 @@ public class SequenceFile {private class MergeQueue extends PriorityQueue {private NFSDataOutputStream out;+ private boolean done;+ private boolean compress;++ public void add(MergeStream stream) throws IOException {+ if (size() == 0) {+ compress = stream.in.isCompressed();+ } else if (compress != stream.in.isCompressed()) {+ throw new IOException("All merged files must be compressed or not.");+ }+ put(stream);+ }- public MergeQueue(int size, String outName) throws IOException {+ public MergeQueue(int size, String outName, boolean done)+ throws IOException {initialize(size);- this.out =- new NFSDataOutputStream(nfs.create(new File(outName)),- memory/(factor+1));+ this.out = nfs.create(new File(outName), true, memory/(factor+1));+ this.done = done;}protected boolean lessThan(Object a, Object b) {@@ -745,7 +849,10 @@ public class SequenceFile {}public void merge() throws IOException {- Writer writer = new Writer(out, keyClass, valClass);+ Writer writer = new Writer(out, keyClass, valClass, compress);+ if (!done) {+ writer.sync = null; // disable sync on temp files+ }while (size() != 0) {MergeStream ms = (MergeStream)top();diff --git a/src/java/org/apache/nutch/ipc/Client.java b/src/java/org/apache/nutch/ipc/Client.javaindex 34deae789..daabcd803 100644--- a/src/java/org/apache/nutch/ipc/Client.java+++ b/src/java/org/apache/nutch/ipc/Client.java@@ -26,6 +26,8 @@ import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;+import java.io.FilterInputStream;+import java.io.FilterOutputStream;import java.util.Hashtable;import java.util.logging.Logger;@@ -60,12 +62,15 @@ public class Client {Writable param; // parameterWritable value; // value, null if errorString error; // error, null if value+ long lastActivity; // time of last i/o+ boolean done; // true when call is doneprotected Call(Writable param) {this.param = param;synchronized (Client.this) {this.id = counter++;}+ touch();}/** Called by the connection thread when the call is complete and the@@ -73,6 +78,19 @@ public class Client {public synchronized void callComplete() {notify(); // notify caller}++ /** Update lastActivity with the current time. */+ public synchronized void touch() {+ lastActivity = System.currentTimeMillis();+ }++ /** Update lastActivity with the current time. */+ public synchronized void setResult(Writable value, String error) {+ this.value = value;+ this.error = error;+ this.done = true;+ }+}/** Thread that reads responses and notifies callers. Each connection owns a@@ -84,15 +102,34 @@ public class Client {private DataInputStream in;private DataOutputStream out;private Hashtable calls = new Hashtable(); // currently active calls+ private Call readingCall;+ private Call writingCall;public Connection(InetSocketAddress address) throws IOException {this.address = address;this.socket = new Socket(address.getAddress(), address.getPort());socket.setSoTimeout(timeout);this.in = new DataInputStream- (new BufferedInputStream(socket.getInputStream()));+ (new BufferedInputStream+ (new FilterInputStream(socket.getInputStream()) {+ public int read(byte[] buf, int off, int len) throws IOException {+ int value = super.read(buf, off, len);+ if (readingCall != null) {+ readingCall.touch();+ }+ return value;+ }+ }));this.out = new DataOutputStream- (new BufferedOutputStream(socket.getOutputStream()));+ (new BufferedOutputStream+ (new FilterOutputStream(socket.getOutputStream()) {+ public void write(byte[] buf, int o, int len) throws IOException {+ super.write(buf, o, len);+ if (writingCall != null) {+ writingCall.touch();+ }+ }+ }));this.setDaemon(true);this.setName("Client connection to "+ address.getAddress().getHostAddress()@@ -118,13 +155,16 @@ public class Client {if (isError) {UTF8 utf8 = new UTF8();utf8.readFields(in); // read error string- call.error = utf8.toString();- call.value = null;+ call.setResult(null, utf8.toString());} else {Writable value = makeValue();- value.readFields(in); // read value- call.value = value;- call.error = null;+ try {+ readingCall = call;+ value.readFields(in); // read value+ } finally {+ readingCall = null;+ }+ call.setResult(value, null);}call.callComplete(); // deliver result to caller}@@ -148,9 +188,14 @@ public class Client {synchronized (out) {if (LOG.isLoggable(Level.FINE))LOG.fine(getName() + " sending #" + call.id);- out.writeInt(call.id);- call.param.write(out);- out.flush();+ try {+ writingCall = call;+ out.writeInt(call.id);+ call.param.write(out);+ out.flush();+ } finally {+ writingCall = null;+ }}error = false;} finally {@@ -237,13 +282,17 @@ public class Client {Call call = new Call(param);synchronized (call) {connection.sendParam(call); // send the parameter- try {- call.wait(timeout); // wait for the result- } catch (InterruptedException e) {}+ long wait = timeout;+ do {+ try {+ call.wait(wait); // wait for the result+ } catch (InterruptedException e) {}+ wait = timeout - (System.currentTimeMillis() - call.lastActivity);+ } while (!call.done && wait > 0);if (call.error != null) {throw new IOException(call.error);- } else if (call.value == null) {+ } else if (!call.done) {throw new IOException("timed out waiting for response");} else {return call.value;diff --git a/src/java/org/apache/nutch/ipc/RPC.java b/src/java/org/apache/nutch/ipc/RPC.javaindex 31ba6c1c4..ab6dab915 100644--- a/src/java/org/apache/nutch/ipc/RPC.java+++ b/src/java/org/apache/nutch/ipc/RPC.java@@ -54,182 +54,6 @@ public class RPC {private RPC() {} // no public ctor- private static final Map PRIMITIVE_NAMES = new HashMap();- static {- PRIMITIVE_NAMES.put("boolean", Boolean.TYPE);- PRIMITIVE_NAMES.put("byte", Byte.TYPE);- PRIMITIVE_NAMES.put("char", Character.TYPE);- PRIMITIVE_NAMES.put("short", Short.TYPE);- PRIMITIVE_NAMES.put("int", Integer.TYPE);- PRIMITIVE_NAMES.put("long", Long.TYPE);- PRIMITIVE_NAMES.put("float", Float.TYPE);- PRIMITIVE_NAMES.put("double", Double.TYPE);- PRIMITIVE_NAMES.put("void", Void.TYPE);- }-- private static class NullInstance implements Writable {- private Class declaredClass;- public NullInstance() {}- public NullInstance(Class declaredClass) {- this.declaredClass = declaredClass;- }- public void readFields(DataInput in) throws IOException {- String className = UTF8.readString(in);- declaredClass = (Class)PRIMITIVE_NAMES.get(className);- if (declaredClass == null) {- try {- declaredClass = Class.forName(className);- } catch (ClassNotFoundException e) {- throw new RuntimeException(e.toString());- }- }- }- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, declaredClass.getName());- }- }-- private static void writeObject(DataOutput out, Object instance,- Class declaredClass) throws IOException {-- if (instance == null) { // null- instance = new NullInstance(declaredClass);- declaredClass = NullInstance.class;- }-- if (instance instanceof Writable) { // Writable-- // write instance's class, to support subclasses of the declared class- UTF8.writeString(out, instance.getClass().getName());-- ((Writable)instance).write(out);-- return;- }-- // write declared class for primitives, as they can't be subclassed, and- // the class of the instance may be a wrapper- UTF8.writeString(out, declaredClass.getName());-- if (declaredClass.isArray()) { // array- int length = Array.getLength(instance);- out.writeInt(length);- for (int i = 0; i < length; i++) {- writeObject(out, Array.get(instance, i),- declaredClass.getComponentType());- }-- } else if (declaredClass == String.class) { // String- UTF8.writeString(out, (String)instance);-- } else if (declaredClass.isPrimitive()) { // primitive type-- if (declaredClass == Boolean.TYPE) { // boolean- out.writeBoolean(((Boolean)instance).booleanValue());- } else if (declaredClass == Character.TYPE) { // char- out.writeChar(((Character)instance).charValue());- } else if (declaredClass == Byte.TYPE) { // byte- out.writeByte(((Byte)instance).byteValue());- } else if (declaredClass == Short.TYPE) { // short- out.writeShort(((Short)instance).shortValue());- } else if (declaredClass == Integer.TYPE) { // int- out.writeInt(((Integer)instance).intValue());- } else if (declaredClass == Long.TYPE) { // long- out.writeLong(((Long)instance).longValue());- } else if (declaredClass == Float.TYPE) { // float- out.writeFloat(((Float)instance).floatValue());- } else if (declaredClass == Double.TYPE) { // double- out.writeDouble(((Double)instance).doubleValue());- } else if (declaredClass == Void.TYPE) { // void- } else {- throw new IllegalArgumentException("Not a primitive: "+declaredClass);- }-- } else {- throw new IOException("Can't write: "+instance+" as "+declaredClass);- }- }--- private static Object readObject(DataInput in)- throws IOException {- return readObject(in, null);- }-- private static Object readObject(DataInput in, ObjectWritable objectWritable)- throws IOException {- String className = UTF8.readString(in);- Class declaredClass = (Class)PRIMITIVE_NAMES.get(className);- if (declaredClass == null) {- try {- declaredClass = Class.forName(className);- } catch (ClassNotFoundException e) {- throw new RuntimeException(e.toString());- }- }-- Object instance;-- if (declaredClass == NullInstance.class) { // null- NullInstance wrapper = new NullInstance();- wrapper.readFields(in);- declaredClass = wrapper.declaredClass;- instance = null;-- } else if (declaredClass.isPrimitive()) { // primitive types-- if (declaredClass == Boolean.TYPE) { // boolean- instance = Boolean.valueOf(in.readBoolean());- } else if (declaredClass == Character.TYPE) { // char- instance = new Character(in.readChar());- } else if (declaredClass == Byte.TYPE) { // byte- instance = new Byte(in.readByte());- } else if (declaredClass == Short.TYPE) { // short- instance = new Short(in.readShort());- } else if (declaredClass == Integer.TYPE) { // int- instance = new Integer(in.readInt());- } else if (declaredClass == Long.TYPE) { // long- instance = new Long(in.readLong());- } else if (declaredClass == Float.TYPE) { // float- instance = new Float(in.readFloat());- } else if (declaredClass == Double.TYPE) { // double- instance = new Double(in.readDouble());- } else if (declaredClass == Void.TYPE) { // void- instance = null;- } else {- throw new IllegalArgumentException("Not a primitive: "+declaredClass);- }-- } else if (declaredClass.isArray()) { // array- int length = in.readInt();- instance = Array.newInstance(declaredClass.getComponentType(), length);- for (int i = 0; i < length; i++) {- Array.set(instance, i, readObject(in));- }-- } else if (declaredClass == String.class) { // String- instance = UTF8.readString(in);-- } else { // Writable- try {- Writable writable = (Writable)declaredClass.newInstance();- writable.readFields(in);- instance = writable;- } catch (InstantiationException e) {- throw new RuntimeException(e);- } catch (IllegalAccessException e) {- throw new RuntimeException(e);- }- }-- if (objectWritable != null) { // store values- objectWritable.declaredClass = declaredClass;- objectWritable.instance = instance;- }-- return instance;-- }/** A method invocation, including the method name and its parameters.*/private static class Invocation implements Writable {@@ -261,8 +85,8 @@ public class RPC {ObjectWritable objectWritable = new ObjectWritable();for (int i = 0; i < parameters.length; i++) {- parameters[i] = readObject(in, objectWritable);- parameterClasses[i] = objectWritable.declaredClass;+ parameters[i] = ObjectWritable.readObject(in, objectWritable);+ parameterClasses[i] = objectWritable.getDeclaredClass();}}@@ -270,7 +94,7 @@ public class RPC {UTF8.writeString(out, methodName);out.writeInt(parameterClasses.length);for (int i = 0; i < parameterClasses.length; i++) {- writeObject(out, parameters[i], parameterClasses[i]);+ ObjectWritable.writeObject(out, parameters[i], parameterClasses[i]);}}@@ -289,33 +113,6 @@ public class RPC {}- /** A polymorphic Writable that packages a Writable with its class name.- * Also handles arrays and strings w/o a Writable wrapper.- */- private static class ObjectWritable implements Writable {- private Class declaredClass;- private Object instance;-- public ObjectWritable() {}-- public ObjectWritable(Class declaredClass, Object instance) {- this.declaredClass = declaredClass;- this.instance = instance;- }-- /** Return the instance. */- public Object get() { return instance; }-- public void readFields(DataInput in) throws IOException {- readObject(in, this);- }-- public void write(DataOutput out) throws IOException {- writeObject(out, instance, declaredClass);- }-- }-private static Client CLIENT = new Client(ObjectWritable.class);private static class Invoker implements InvocationHandler {diff --git a/src/java/org/apache/nutch/ipc/Server.java b/src/java/org/apache/nutch/ipc/Server.javaindex 41f4df599..3aa990064 100644--- a/src/java/org/apache/nutch/ipc/Server.java+++ b/src/java/org/apache/nutch/ipc/Server.java@@ -25,6 +25,7 @@ import java.io.BufferedOutputStream;import java.net.Socket;import java.net.ServerSocket;+import java.net.SocketException;import java.net.SocketTimeoutException;import java.util.LinkedList;@@ -32,6 +33,7 @@ import java.util.logging.Logger;import java.util.logging.Level;import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.util.NutchConf;import org.apache.nutch.io.Writable;import org.apache.nutch.io.UTF8;@@ -51,7 +53,8 @@ public abstract class Server {private int maxQueuedCalls; // max number of queued callsprivate Class paramClass; // class of call parameters- private int timeout = 10000; // timeout for i/o+ private int timeout = NutchConf.get().getInt("ipc.client.timeout",10000);+private boolean running = true; // true while server runsprivate LinkedList callQueue = new LinkedList(); // queued callsprivate Object callDequeued = new Object(); // used by wait/notify@@ -92,7 +95,9 @@ public abstract class Server {}try {socket.close();- } catch (IOException e) {}+ } catch (IOException e) {+ LOG.info(getName() + ": e=" + e);+ }LOG.info(getName() + ": exiting");}}@@ -146,7 +151,9 @@ public abstract class Server {}}} catch (EOFException eof) {- // This is what happens when the other side shuts things down+ // This is what happens on linux when the other side shuts down+ } catch (SocketException eof) {+ // This is what happens on Win32 when the other side shuts down} catch (Exception e) {LOG.log(Level.INFO, getName() + " caught: " + e, e);} finally {@@ -161,9 +168,9 @@ public abstract class Server {/** Handles queued calls . */private class Handler extends Thread {- public Handler() {+ public Handler(int instanceNumber) {this.setDaemon(true);- this.setName("Server handler on " + port);+ this.setName("Server handler "+ instanceNumber + " on " + port);}public void run() {@@ -237,25 +244,31 @@ public abstract class Server {listener.start();for (int i = 0; i < handlerCount; i++) {- Handler handler = new Handler();+ Handler handler = new Handler(i);handler.start();}}- /** Stops the service. No calls will be handled after this is called. All- * threads will exit. */+ /** Stops the service. No new calls will be handled after this is called. All+ * subthreads will likely be finished after this returns.+ */public synchronized void stop() {LOG.info("Stopping server on " + port);running = false;try {- Thread.sleep(timeout); // let all threads exit+ Thread.sleep(timeout); // inexactly wait for pending requests to finish} catch (InterruptedException e) {}- notify();+ notifyAll();}- /** Wait for the server to be stopped. */+ /** Wait for the server to be stopped.+ * Does not wait for all subthreads to finish.+ * See {@link #stop()}.+ */public synchronized void join() throws InterruptedException {- wait();+ while (running) {+ wait();+ }}/** Called for each call. */diff --git a/src/java/org/apache/nutch/mapReduce/InputFormatBase.java b/src/java/org/apache/nutch/mapReduce/InputFormatBase.javadeleted file mode 100644index 78b4c86e9..000000000--- a/src/java/org/apache/nutch/mapReduce/InputFormatBase.java+++ /dev/null@@ -1,82 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.mapReduce;--import java.io.IOException;-import java.io.File;--import java.util.ArrayList;--import org.apache.nutch.fs.NutchFileSystem;--/** A base class for {@link InputFormat}. */-public abstract class InputFormatBase implements InputFormat {-- private static final double SPLIT_SLOP = 0.1; // 10% slop-- public abstract String getName();-- public abstract RecordReader getRecordReader(NutchFileSystem fs,- FileSplit split,- JobConf job) throws IOException;-- /** Subclasses may override to, e.g., select only files matching a regular- * expression.*/- protected File[] listFiles(NutchFileSystem fs, JobConf job)- throws IOException {- File[] files = fs.listFiles(job.getInputDir());- if (files == null) {- throw new IOException("No input files in: "+job.getInputDir());- }- return files;- }-- /** Splits files returned by {#listFiles(NutchFileSystem,JobConf) when- * they're too big.*/- public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int numSplits)- throws IOException {-- File[] files = listFiles(fs, job);-- long totalSize = 0;- for (int i = 0; i < files.length; i++) {- totalSize += fs.getLength(files[i]);- }-- long bytesPerSplit = totalSize / numSplits;- long maxPerSplit = bytesPerSplit + (long)(bytesPerSplit*SPLIT_SLOP);-- ArrayList splits = new ArrayList(numSplits);- for (int i = 0; i < files.length; i++) {- File file = files[i];- long length = fs.getLength(file);-- long bytesRemaining = length;- while (bytesRemaining >= maxPerSplit) {- splits.add(new FileSplit(file, length-bytesRemaining, bytesPerSplit));- bytesRemaining -= bytesPerSplit;- }-- if (bytesRemaining != 0) {- splits.add(new FileSplit(file, length-bytesRemaining, bytesRemaining));- }- }- return (FileSplit[])splits.toArray(new FileSplit[splits.size()]);- }--}-diff --git a/src/java/org/apache/nutch/mapReduce/InputFormats.java b/src/java/org/apache/nutch/mapReduce/InputFormats.javadeleted file mode 100644index 0b80771fd..000000000--- a/src/java/org/apache/nutch/mapReduce/InputFormats.java+++ /dev/null@@ -1,41 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.mapReduce;--import java.util.HashMap;--/** Repository of named {@link InputFormat}s. */-public class InputFormats {- private static final HashMap NAME_TO_FORMAT = new HashMap();-- static { // register with repository- InputFormats.add(new TextInputFormat());- InputFormats.add(new SequenceFileInputFormat());- }-- private InputFormats() {} // no public ctor-- /** Return the named {@link InputFormat}. */- public static synchronized InputFormat get(String name) {- return (InputFormat)NAME_TO_FORMAT.get(name);- }-- /** Define a named {@link InputFormat}.*/- public static synchronized void add(InputFormat format) {- NAME_TO_FORMAT.put(format.getName(), format);- }-}diff --git a/src/java/org/apache/nutch/mapReduce/OutputFormats.java b/src/java/org/apache/nutch/mapReduce/OutputFormats.javadeleted file mode 100644index 421942df3..000000000--- a/src/java/org/apache/nutch/mapReduce/OutputFormats.java+++ /dev/null@@ -1,41 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.mapReduce;--import java.util.HashMap;--/** Repository of named {@link OutputFormat}s. */-public class OutputFormats {- private static final HashMap NAME_TO_FORMAT = new HashMap();-- static { // register with repository- OutputFormats.add(new TextOutputFormat());- OutputFormats.add(new SequenceFileOutputFormat());- }-- private OutputFormats() {} // no public ctor-- /** Return the named {@link OutputFormat}. */- public static synchronized OutputFormat get(String name) {- return (OutputFormat)NAME_TO_FORMAT.get(name);- }-- /** Define a named {@link OutputFormat}.*/- public static synchronized void add(OutputFormat format) {- NAME_TO_FORMAT.put(format.getName(), format);- }-}diff --git a/src/java/org/apache/nutch/mapReduce/SequenceFileInputFormat.java b/src/java/org/apache/nutch/mapReduce/SequenceFileInputFormat.javadeleted file mode 100644index bd846c658..000000000--- a/src/java/org/apache/nutch/mapReduce/SequenceFileInputFormat.java+++ /dev/null@@ -1,66 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.mapReduce;--import java.io.IOException;-import java.io.File;--import org.apache.nutch.fs.NutchFileSystem;--import org.apache.nutch.io.SequenceFile;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.UTF8;--/** An {@link InputFormat} for plain text files. Files are broken into lines.- * Either linefeed or carriage-return are used to signal end of line. Keys are- * the position in the file, and values are the line of text.. */-public class SequenceFileInputFormat extends InputFormatBase {-- public String getName() { return "seq"; }-- public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,- JobConf job) throws IOException {-- // open the file and seek to the start of the split- final SequenceFile.Reader in =- new SequenceFile.Reader(fs, split.getFile().toString());- final long end = split.getStart() + split.getLength();-- in.sync(split.getStart()); // sync to start-- return new RecordReader() {- public boolean next(Writable key, Writable value) throws IOException {- long pos = in.getPosition();- boolean more = in.next(key, value);- if (pos >= end && in.syncSeen()) {- return false;- } else {- return more;- }- }-- public long getPos() throws IOException { return in.getPosition(); }-- public void close() throws IOException { in.close(); }-- };- }--}-diff --git a/src/java/org/apache/nutch/mapReduce/TaskRunner.java b/src/java/org/apache/nutch/mapReduce/TaskRunner.javadeleted file mode 100644index 37f2be1a2..000000000--- a/src/java/org/apache/nutch/mapReduce/TaskRunner.java+++ /dev/null@@ -1,119 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.mapReduce;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/** Base class that runs a task in a separate process. Tasks are run in a- * separate process in order to isolate the map/reduce system code from bugs in- * user supplied map and reduce functions.- */-abstract class TaskRunner extends Thread {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapReduce.TaskRunner");-- private Process process;- private Task t;- private TaskTracker tracker;-- public TaskRunner(Task t, TaskTracker tracker) {- this.t = t;- this.tracker = tracker;- }-- public Task getTask() { return t; }- public TaskTracker getTracker() { return tracker; }-- /** Called to assemble this task's input. This method is run in the parent- * process before the child is spawned. It should not execute user code,- * only system code. */- public void prepare() throws IOException {}-- /** Called when this task's output is no longer needed.- * This method is run in the parent process after the child exits. It should- * not execute user code, only system code.- */- public void close() throws IOException {}-- public final void run() {- try {-- prepare();-- runChild(new String[] {- "java", // run java- //"-verbose",- "-cp",- new JobConf(t.getJobFile()).getJar(), // classpath is task jar- TaskTracker.Child.class.getName(), // main is Child- tracker.taskReportPort+"", // pass umbilical port- t.getTaskId() // pass task identifier- });- } catch (IOException e) {- LOG.log(Level.WARNING, "Child Error", e);- } finally {- tracker.reportTaskFinished(t.getTaskId());- }- }-- /**- * Run the child process- */- private void runChild(String[] args) throws IOException {- this.process = Runtime.getRuntime().exec(args);- try {- logStream(process.getErrorStream()); // copy log output- logStream(process.getInputStream()); // normally empty-- if (this.process.waitFor() != 0) {- throw new IOException("Child failed!");- }-- } catch (InterruptedException e) {- throw new IOException(e.toString());- }- }-- /**- * Kill the child process- */- public void kill() {- if (process != null) {- process.destroy();- }- }-- /**- */- private void logStream(InputStream output) {- try {- BufferedReader in = new BufferedReader(new InputStreamReader(output));- String line;- while ((line = in.readLine()) != null) {- LOG.info(line);- }- } catch (IOException e) {- LOG.warning(e.toString());- }- }-}diff --git a/src/java/org/apache/nutch/mapReduce/CombiningCollector.java b/src/java/org/apache/nutch/mapred/CombiningCollector.javasimilarity index 83%rename from src/java/org/apache/nutch/mapReduce/CombiningCollector.javarename to src/java/org/apache/nutch/mapred/CombiningCollector.javaindex 443244d2e..634841b94 100644--- a/src/java/org/apache/nutch/mapReduce/CombiningCollector.java+++ b/src/java/org/apache/nutch/mapred/CombiningCollector.java@@ -14,14 +14,14 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.*;import java.net.*;import java.util.*;import org.apache.nutch.io.*;-import org.apache.nutch.util.NutchConf;+import org.apache.nutch.util.*;/** Implements partial value reduction during mapping. This can minimize the* size of intermediate data. Buffers a list of values for each unique key,@@ -37,21 +37,18 @@ class CombiningCollector implements OutputCollector {private JobConf job;private OutputCollector out;private Reducer combiner;+ private Reporter reporter;- public CombiningCollector(JobConf job, OutputCollector out) {+ public CombiningCollector(JobConf job, OutputCollector out,+ Reporter reporter) {this.job = job;this.out = out;+ this.reporter = reporter;this.combiner = (Reducer)job.newInstance(job.getCombinerClass());-- try {- this.keyToValues = new TreeMap- ((Comparator)job.getOutputKeyComparatorClass().newInstance());- } catch (Exception e) {- throw new RuntimeException(e);- }+ this.keyToValues = new TreeMap(job.getOutputKeyComparator());}- public void collect(WritableComparable key, Writable value)+ public synchronized void collect(WritableComparable key, Writable value)throws IOException {// buffer new value in map@@ -71,13 +68,13 @@ class CombiningCollector implements OutputCollector {}}- public void flush() throws IOException {+ public synchronized void flush() throws IOException {Iterator pairs = keyToValues.entrySet().iterator();while (pairs.hasNext()) {Map.Entry pair = (Map.Entry)pairs.next();combiner.reduce((WritableComparable)pair.getKey(),((ArrayList)pair.getValue()).iterator(),- out);+ out, reporter);}keyToValues.clear();count = 0;diff --git a/src/java/org/apache/nutch/mapReduce/FileSplit.java b/src/java/org/apache/nutch/mapred/FileSplit.javasimilarity index 86%rename from src/java/org/apache/nutch/mapReduce/FileSplit.javarename to src/java/org/apache/nutch/mapred/FileSplit.javaindex 4cebe0204..05468d334 100644--- a/src/java/org/apache/nutch/mapReduce/FileSplit.java+++ b/src/java/org/apache/nutch/mapred/FileSplit.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;@@ -25,12 +25,9 @@ import org.apache.nutch.io.Writable;import org.apache.nutch.io.UTF8;import org.apache.nutch.fs.NutchFileSystem;-/**- * A section of an input file.- * Returned by {@link InputFormat#getSplits(NutchFileSystem, JobConf, int)}- * and passed to- * {@link InputFormat#getRecordReader(NutchFileSystem, FileSplit, JobConf)}.- */+/** A section of an input file. Returned by {@link+ * InputFormat#getSplits(NutchFileSystem, JobConf, int)} and passed to+ * InputFormat#getRecordReader(NutchFileSystem,FileSplit,JobConf,Reporter). */public class FileSplit implements Writable {private File file;private long start;@@ -59,6 +56,7 @@ public class FileSplit implements Writable {/** The number of bytes in the file to process. */public long getLength() { return length; }+ public String toString() { return file + ":" + start + "+" + length; }////////////////////////////////////////////// Writable methodsdiff --git a/src/java/org/apache/nutch/mapReduce/InputFormat.java b/src/java/org/apache/nutch/mapred/InputFormat.javasimilarity index 90%rename from src/java/org/apache/nutch/mapReduce/InputFormat.javarename to src/java/org/apache/nutch/mapred/InputFormat.javaindex 35d4b73b4..f66e66b9a 100644--- a/src/java/org/apache/nutch/mapReduce/InputFormat.java+++ b/src/java/org/apache/nutch/mapred/InputFormat.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;@@ -26,11 +26,6 @@ import org.apache.nutch.fs.NutchFileSystem;* Files are processed as sequences of records, implementing {@link* RecordReader}. Files must thus be split on record boundaries. */public interface InputFormat {-- /** The name of this input format.- * @see InputFormats- */- String getName();/** Splits a set of input files. One split is created per map task.*@@ -50,6 +45,7 @@ public interface InputFormat {* @return a {@link RecordReader}*/RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,- JobConf job) throws IOException;+ JobConf job, Reporter reporter)+ throws IOException;}diff --git a/src/java/org/apache/nutch/mapred/InputFormatBase.java b/src/java/org/apache/nutch/mapred/InputFormatBase.javanew file mode 100644index 000000000..557a5a1b8--- /dev/null+++ b/src/java/org/apache/nutch/mapred/InputFormatBase.java@@ -0,0 +1,134 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;+import java.io.File;++import java.util.Arrays;+import java.util.ArrayList;+import java.util.logging.Logger;++import org.apache.nutch.fs.NutchFileSystem;+import org.apache.nutch.util.LogFormatter;++/** A base class for {@link InputFormat}. */+public abstract class InputFormatBase implements InputFormat {++ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.mapred.InputFormatBase");++ private static final double SPLIT_SLOP = 0.1; // 10% slop++ private int minSplitSize = 1;++ protected void setMinSplitSize(int minSplitSize) {+ this.minSplitSize = minSplitSize;+ }++ public abstract RecordReader getRecordReader(NutchFileSystem fs,+ FileSplit split,+ JobConf job,+ Reporter reporter)+ throws IOException;++ /** List input directories.+ * Subclasses may override to, e.g., select only files matching a regular+ * expression.+ * Property mapred.input.subdir, if set, names a subdirectory that+ * is appended to all input dirs specified by job, and if the given fs+ * lists those too, each is added to the returned array of File.+ * @param fs+ * @param job+ * @return array of File objects, never zero length.+ * @throws IOException if zero items.+ */+ protected File[] listFiles(NutchFileSystem fs, JobConf job)+ throws IOException {+ File[] dirs = job.getInputDirs();+ String subdir = job.get("mapred.input.subdir");+ ArrayList result = new ArrayList();+ for (int i = 0; i < dirs.length; i++) {+ File[] dir = fs.listFiles(dirs[i]);+ if (dir != null) {+ for (int j = 0; j < dir.length; j++) {+ File file = dir[j];+ if (subdir != null) {+ File[] subFiles = fs.listFiles(new File(file, subdir));+ if (subFiles != null) {+ for (int k = 0; k < subFiles.length; k++) {+ result.add(subFiles[k]);+ }+ }+ } else {+ result.add(file);+ }+ }+ }+ }++ if (result.size() == 0) {+ throw new IOException("No input directories specified in: "+job);+ }+ return (File[])result.toArray(new File[result.size()]);+ }++ /** Splits files returned by {#listFiles(NutchFileSystem,JobConf) when+ * they're too big.*/+ public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int numSplits)+ throws IOException {++ File[] files = listFiles(fs, job);++ for (int i = 0; i < files.length; i++) { // check we have valid files+ File file = files[i];+ if (fs.isDirectory(file) || !fs.exists(file)) {+ throw new IOException("Not a file: "+files[i]);+ }+ }++ long totalSize = 0; // compute total size+ for (int i = 0; i < files.length; i++) {+ totalSize += fs.getLength(files[i]);+ }++ long bytesPerSplit = Math.max(totalSize / numSplits, minSplitSize);+ long maxPerSplit = bytesPerSplit + (long)(bytesPerSplit*SPLIT_SLOP);++ //LOG.info("bytesPerSplit = " + bytesPerSplit);+ //LOG.info("maxPerSplit = " + maxPerSplit);++ ArrayList splits = new ArrayList(numSplits); // generate splits+ for (int i = 0; i < files.length; i++) {+ File file = files[i];+ long length = fs.getLength(file);++ long bytesRemaining = length;+ while (bytesRemaining >= maxPerSplit) {+ splits.add(new FileSplit(file, length-bytesRemaining, bytesPerSplit));+ bytesRemaining -= bytesPerSplit;+ }++ if (bytesRemaining != 0) {+ splits.add(new FileSplit(file, length-bytesRemaining, bytesRemaining));+ }+ }+ return (FileSplit[])splits.toArray(new FileSplit[splits.size()]);+ }++}+diff --git a/src/java/org/apache/nutch/mapReduce/InterTrackerProtocol.java b/src/java/org/apache/nutch/mapred/InterTrackerProtocol.javasimilarity index 94%rename from src/java/org/apache/nutch/mapReduce/InterTrackerProtocol.javarename to src/java/org/apache/nutch/mapred/InterTrackerProtocol.javaindex 27e8c62e5..288ee4c56 100644--- a/src/java/org/apache/nutch/mapReduce/InterTrackerProtocol.java+++ b/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.*;import org.apache.nutch.io.*;@@ -35,7 +35,7 @@ public interface InterTrackerProtocol {* TaskTracker must also indicate whether this is the first interaction* (since state refresh)*/- IntWritable emitHeartbeat(TaskTrackerStatus status, BooleanWritable initialContact);+ int emitHeartbeat(TaskTrackerStatus status, boolean initialContact);/** Called to get new tasks from from the job tracker for this tracker.*/Task pollForNewTask(String trackerName);diff --git a/src/java/org/apache/nutch/mapReduce/JobClient.java b/src/java/org/apache/nutch/mapred/JobClient.javasimilarity index 86%rename from src/java/org/apache/nutch/mapReduce/JobClient.javarename to src/java/org/apache/nutch/mapred/JobClient.javaindex d9c042df5..4eaf1f6ff 100644--- a/src/java/org/apache/nutch/mapReduce/JobClient.java+++ b/src/java/org/apache/nutch/mapred/JobClient.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;import org.apache.nutch.fs.*;@@ -34,7 +34,7 @@ import java.util.logging.*;* @author Mike Cafarella*******************************************************/public class JobClient implements MRConstants {- private static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapReduce.JobClient");+ private static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobClient");static long MAX_JOBPROFILE_AGE = 1000 * 2;@@ -120,6 +120,14 @@ public class JobClient implements MRConstants {status.getRunState() == JobStatus.FAILED);}+ /**+ * True iff job completed successfully.+ */+ public synchronized boolean isSuccessful() throws IOException {+ ensureFreshStatus();+ return status.getRunState() == JobStatus.SUCCEEDED;+ }+/*** Blocks until the job is finished*/@@ -156,7 +164,6 @@ public class JobClient implements MRConstants {}JobSubmissionProtocol jobSubmitClient;- InetSocketAddress jobTrackAddr;NutchFileSystem fs = null;static Random r = new Random();@@ -164,19 +171,26 @@ public class JobClient implements MRConstants {/*** Build a job client, connect to the default job tracker*/- public JobClient() throws IOException {- this(JobTracker.getDefaultAddress());+ public JobClient(NutchConf conf) throws IOException {+ String tracker = conf.get("mapred.job.tracker", "local");+ if ("local".equals(tracker)) {+ this.jobSubmitClient = new LocalJobRunner();+ } else {+ this.jobSubmitClient = (JobSubmissionProtocol)+ RPC.getProxy(JobSubmissionProtocol.class,+ JobTracker.getAddress(conf));+ }}/*** Build a job client, connect to the indicated job tracker.*/public JobClient(InetSocketAddress jobTrackAddr) throws IOException {- this.jobTrackAddr = jobTrackAddr;this.jobSubmitClient = (JobSubmissionProtocol)RPC.getProxy(JobSubmissionProtocol.class, jobTrackAddr);}+/***/public synchronized void close() throws IOException {@@ -226,17 +240,18 @@ public class JobClient implements MRConstants {String originalJarPath = job.getJar();- // Modify the job file, write to JobTracker's fs- job.setJar(submitJarFile.toString());- NFSDataOutputStream out =- new NFSDataOutputStream(getFs().create(submitJobFile));+ if (originalJarPath != null) { // Copy jar to JobTracker's fs+ job.setJar(submitJarFile.toString());+ getFs().copyFromLocalFile(new File(originalJarPath), submitJarFile);+ }++ // Write job file to JobTracker's fs+ NFSDataOutputStream out = getFs().create(submitJobFile);try {job.write(out);} finally {out.close();}- // Copy jar to JobTracker's fs- getFs().copyFromLocalFile(new File(originalJarPath), submitJarFile);//// Now, actually submit the job (using the submit name)@@ -265,9 +280,10 @@ public class JobClient implements MRConstants {/** Utility that submits a job, then polls for progress until the job is* complete. */public static void runJob(JobConf job) throws IOException {- JobClient jc = new JobClient();+ JobClient jc = new JobClient(job);boolean error = true;RunningJob running = null;+ String lastReport = null;try {running = jc.submitJob(job);String jobId = running.getJobID();@@ -277,14 +293,20 @@ public class JobClient implements MRConstants {Thread.sleep(1000);} catch (InterruptedException e) {}running = jc.getJob(jobId);+ String report = null;if (running.reduceProgress() == 0.0)- LOG.info(" map "+Math.round(running.mapProgress()*100)- +"% complete");+ report=" map "+Math.round(running.mapProgress()*100)+"%";else {- LOG.info(" reduce "+Math.round(running.reduceProgress()*100)- +"% complete");+ report=" reduce "+Math.round(running.reduceProgress()*100)+"%";+ }+ if (!report.equals(lastReport)) {+ LOG.info(report);+ lastReport = report;}}+ if (!running.isSuccessful()) {+ throw new IOException("Job failed!");+ }LOG.info("Job complete: " + jobId);error = false;} finally {@@ -300,7 +322,7 @@ public class JobClient implements MRConstants {*/public static void main(String argv[]) throws IOException {if (argv.length < 2) {- System.out.println("JobClient [-submit <job>] [-status <id>]");+ System.out.println("JobClient -submit <job> | -status <id> | -kill <id>");System.exit(-1);}@@ -327,7 +349,7 @@ public class JobClient implements MRConstants {}// Submit the request- JobClient jc = new JobClient();+ JobClient jc = new JobClient(NutchConf.get());try {if (submitJobFile != null) {RunningJob job = jc.submitJob(submitJobFile);diff --git a/src/java/org/apache/nutch/mapReduce/JobConf.java b/src/java/org/apache/nutch/mapred/JobConf.javasimilarity index 55%rename from src/java/org/apache/nutch/mapReduce/JobConf.javarename to src/java/org/apache/nutch/mapred/JobConf.javaindex 3df294663..b318e91ef 100644--- a/src/java/org/apache/nutch/mapReduce/JobConf.java+++ b/src/java/org/apache/nutch/mapred/JobConf.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;@@ -25,9 +25,13 @@ import java.net.URL;import java.util.Properties;import java.util.jar.JarFile;import java.util.jar.JarEntry;+import java.util.StringTokenizer;+import java.util.ArrayList;import java.util.List;+import java.util.Collections;import org.apache.nutch.fs.NutchFileSystem;+import org.apache.nutch.fs.FileUtil;import org.apache.nutch.util.NutchConf;import org.apache.nutch.io.Writable;@@ -36,9 +40,9 @@ import org.apache.nutch.io.WritableComparator;import org.apache.nutch.io.LongWritable;import org.apache.nutch.io.UTF8;-import org.apache.nutch.mapReduce.lib.IdentityMapper;-import org.apache.nutch.mapReduce.lib.IdentityReducer;-import org.apache.nutch.mapReduce.lib.HashPartitioner;+import org.apache.nutch.mapred.lib.IdentityMapper;+import org.apache.nutch.mapred.lib.IdentityReducer;+import org.apache.nutch.mapred.lib.HashPartitioner;/** A map/reduce job configuration. This names the {@link Mapper}, combiner* (if any), {@link Partitioner}, {@link Reducer}, {@link InputFormat}, and@@ -46,11 +50,16 @@ import org.apache.nutch.mapReduce.lib.HashPartitioner;* of input files, and where the output files should be written. */public class JobConf extends NutchConf {- /** Construct a map/reduce configuration. */- public JobConf() {- super();+ /** Construct a map/reduce job configuration.+ *+ * @param conf a NutchConf whose settings will be inherited.+ */+ public JobConf(NutchConf conf) {+ super(conf);+ addConfResource("mapred-default.xml");}+/** Construct a map/reduce configuration.** @param config a NutchConf-format XML job description file@@ -65,18 +74,11 @@ public class JobConf extends NutchConf {*/public JobConf(File config) {super();+ addConfResource("mapred-default.xml");addConfResource(config);}- public String getJar() {- String defaultValue = "nutch.jar";-- URL jarUrl = get().getResource(defaultValue); // resolve default- if (jarUrl != null && "file".equals(jarUrl.getProtocol()))- defaultValue = jarUrl.getFile();-- return get("mapred.jar", defaultValue);- }+ public String getJar() { return get("mapred.jar"); }public void setJar(String jar) { set("mapred.jar", jar); }public static File getSystemDir() {@@ -84,28 +86,76 @@ public class JobConf extends NutchConf {"/tmp/nutch/mapred/system"));}- public static File getLocalDir() {- return new File(NutchConf.get().get("mapred.local.dir",- "/tmp/nutch/mapred/local"));+ public static String[] getLocalDirs() throws IOException {+ return NutchConf.get().getStrings("mapred.local.dir");+ }++ public static void deleteLocalFiles() throws IOException {+ String[] localDirs = getLocalDirs();+ for (int i = 0; i < localDirs.length; i++) {+ FileUtil.fullyDelete(new File(localDirs[i]));+ }+ }++ public static void deleteLocalFiles(String subdir) throws IOException {+ String[] localDirs = getLocalDirs();+ for (int i = 0; i < localDirs.length; i++) {+ FileUtil.fullyDelete(new File(localDirs[i], subdir));+ }+ }++ /** Constructs a local file name. Files are distributed among configured+ * local directories.*/+ public static File getLocalFile(String subdir, String name)+ throws IOException {+ String[] localDirs = getLocalDirs();+ String path = subdir + File.separator + name;+ int hashCode = path.hashCode();+ for (int i = 0; i < localDirs.length; i++) { // try each local dir+ int index = (hashCode+i & Integer.MAX_VALUE) % localDirs.length;+ File file = new File(localDirs[index], path);+ File dir = file.getParentFile();+ if (dir.exists() || dir.mkdirs()) {+ return file;+ }+ }+ throw new IOException("No valid local directories.");}- public File getInputDir() { return new File(get("mapred.input.dir")); }public void setInputDir(File dir) { set("mapred.input.dir", dir); }+ public void addInputDir(File dir) {+ String dirs = get("mapred.input.dir");+ set("mapred.input.dir", dirs == null ? dir.toString() : dirs + "," + dir);+ }+ public File[] getInputDirs() {+ String dirs = get("mapred.input.dir", "");+ ArrayList list = Collections.list(new StringTokenizer(dirs, ","));+ File[] result = new File[list.size()];+ for (int i = 0; i < list.size(); i++) {+ result[i] = new File((String)list.get(i));+ }+ return result;+ }+public File getOutputDir() { return new File(get("mapred.output.dir")); }public void setOutputDir(File dir) { set("mapred.output.dir", dir); }public InputFormat getInputFormat() {- return InputFormats.get(get("mapred.input.format", "text"));+ return (InputFormat)newInstance(getClass("mapred.input.format.class",+ TextInputFormat.class,+ InputFormat.class));}- public void setInputFormat(InputFormat format) {- set("mapred.input.format", format.getName());+ public void setInputFormat(Class theClass) {+ setClass("mapred.input.format.class", theClass, InputFormat.class);}public OutputFormat getOutputFormat() {- return OutputFormats.get(get("mapred.output.format", "text"));+ return (OutputFormat)newInstance(getClass("mapred.output.format.class",+ TextOutputFormat.class,+ OutputFormat.class));}- public void setOutputFormat(OutputFormat format) {- set("mapred.output.format", format.getName());+ public void setOutputFormat(Class theClass) {+ setClass("mapred.output.format.class", theClass, OutputFormat.class);}public Class getInputKeyClass() {@@ -120,7 +170,7 @@ public class JobConf extends NutchConf {return getClass("mapred.input.value.class", UTF8.class, Writable.class);}public void setInputValueClass(Class theClass) {- setClass("mapred.input.value.class", theClass, WritableComparable.class);+ setClass("mapred.input.value.class", theClass, Writable.class);}public Class getOutputKeyClass() {@@ -131,10 +181,12 @@ public class JobConf extends NutchConf {setClass("mapred.output.key.class", theClass, WritableComparable.class);}- public Class getOutputKeyComparatorClass() {- return getClass("mapred.output.key.comparator.class",- WritableComparator.get(getOutputKeyClass()).getClass(),- WritableComparator.class);+ public WritableComparator getOutputKeyComparator() {+ Class theClass = getClass("mapred.output.key.comparator.class", null,+ WritableComparator.class);+ if (theClass != null)+ return (WritableComparator)newInstance(theClass);+ return WritableComparator.get(getOutputKeyClass());}public void setOutputKeyComparatorClass(Class theClass) {@@ -146,7 +198,7 @@ public class JobConf extends NutchConf {return getClass("mapred.output.value.class", UTF8.class, Writable.class);}public void setOutputValueClass(Class theClass) {- setClass("mapred.output.value.class", theClass, WritableComparable.class);+ setClass("mapred.output.value.class", theClass, Writable.class);}public Class getMapperClass() {@@ -156,6 +208,14 @@ public class JobConf extends NutchConf {setClass("mapred.mapper.class", theClass, Mapper.class);}+ public Class getMapRunnerClass() {+ return getClass("mapred.map.runner.class",+ MapRunner.class, MapRunnable.class);+ }+ public void setMapRunnerClass(Class theClass) {+ setClass("mapred.map.runner.class", theClass, MapRunnable.class);+ }+public Class getPartitionerClass() {return getClass("mapred.partitioner.class",HashPartitioner.class, Partitioner.class);@@ -179,25 +239,23 @@ public class JobConf extends NutchConf {setClass("mapred.combiner.class", theClass, Reducer.class);}- public int getNumMapTasks() { return getInt("mapred.map.tasks", 10); }+ public int getNumMapTasks() { return getInt("mapred.map.tasks", 1); }public void setNumMapTasks(int n) { setInt("mapred.map.tasks", n); }- public int getNumReduceTasks() { return getInt("mapred.reduce.tasks", 10); }+ public int getNumReduceTasks() { return getInt("mapred.reduce.tasks", 1); }public void setNumReduceTasks(int n) { setInt("mapred.reduce.tasks", n); }- public Configurable newInstance(Class theClass) {- Configurable result;+ public Object newInstance(Class theClass) {+ Object result;try {- result = (Configurable)theClass.newInstance();+ result = theClass.newInstance();} catch (Exception e) {throw new RuntimeException(e);}- result.configure(this);+ if (result instanceof JobConfigurable)+ ((JobConfigurable)result).configure(this);return result;}- public static void main(String[] args) {- System.out.println(new JobConf().getJar());- }}diff --git a/src/java/org/apache/nutch/mapReduce/Configurable.java b/src/java/org/apache/nutch/mapred/JobConfigurable.javasimilarity index 81%rename from src/java/org/apache/nutch/mapReduce/Configurable.javarename to src/java/org/apache/nutch/mapred/JobConfigurable.javaindex 64518b667..ba2413294 100644--- a/src/java/org/apache/nutch/mapReduce/Configurable.java+++ b/src/java/org/apache/nutch/mapred/JobConfigurable.java@@ -14,15 +14,10 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;--import java.io.IOException;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;+package org.apache.nutch.mapred;/** That what may be configured. */-public interface Configurable {+public interface JobConfigurable {/** Initializes a new instance from a {@link JobConf}.** @param job the configurationdiff --git a/src/java/org/apache/nutch/mapReduce/JobProfile.java b/src/java/org/apache/nutch/mapred/JobProfile.javasimilarity index 98%rename from src/java/org/apache/nutch/mapReduce/JobProfile.javarename to src/java/org/apache/nutch/mapred/JobProfile.javaindex 4abbf0307..18407671a 100644--- a/src/java/org/apache/nutch/mapReduce/JobProfile.java+++ b/src/java/org/apache/nutch/mapred/JobProfile.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;diff --git a/src/java/org/apache/nutch/mapReduce/JobStatus.java b/src/java/org/apache/nutch/mapred/JobStatus.javasimilarity index 98%rename from src/java/org/apache/nutch/mapReduce/JobStatus.javarename to src/java/org/apache/nutch/mapred/JobStatus.javaindex 669d90a47..d1a2f1497 100644--- a/src/java/org/apache/nutch/mapReduce/JobStatus.java+++ b/src/java/org/apache/nutch/mapred/JobStatus.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;diff --git a/src/java/org/apache/nutch/mapReduce/JobSubmissionProtocol.java b/src/java/org/apache/nutch/mapred/JobSubmissionProtocol.javasimilarity index 88%rename from src/java/org/apache/nutch/mapReduce/JobSubmissionProtocol.javarename to src/java/org/apache/nutch/mapred/JobSubmissionProtocol.javaindex 40740fd41..81810810a 100644--- a/src/java/org/apache/nutch/mapReduce/JobSubmissionProtocol.java+++ b/src/java/org/apache/nutch/mapred/JobSubmissionProtocol.java@@ -14,9 +14,10 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.*;+import java.util.*;import org.apache.nutch.io.*;/**@@ -46,6 +47,12 @@ public interface JobSubmissionProtocol {*/public JobStatus getJobStatus(String jobid);+ /**+ * Grab a bunch of info on the tasks that make up the job+ */+ public Vector[] getMapTaskReport(String jobid);+ public Vector[] getReduceTaskReport(String jobid);+/*** A MapReduce system always operates on a single filesystem. This* function returns the fs name. ('local' if the localfs; 'addr:port'diff --git a/src/java/org/apache/nutch/mapReduce/JobTracker.java b/src/java/org/apache/nutch/mapred/JobTracker.javasimilarity index 77%rename from src/java/org/apache/nutch/mapReduce/JobTracker.javarename to src/java/org/apache/nutch/mapred/JobTracker.javaindex 1ec3e52fb..0458b813b 100644--- a/src/java/org/apache/nutch/mapReduce/JobTracker.java+++ b/src/java/org/apache/nutch/mapred/JobTracker.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;import org.apache.nutch.fs.*;@@ -32,33 +32,32 @@ import java.util.logging.*;* @author Mike Cafarella*******************************************************/public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissionProtocol {- static final int TRACKERINFO_PORT = 7845;+ static final int MAX_TASK_FAILURES = 4;- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapReduce.JobTracker");- public static JobTracker tracker = null;- public static void createTracker() throws IOException {- createTracker(getDefaultAddress());- }- public static void createTracker(InetSocketAddress addr) throws IOException {- tracker = new JobTracker(addr);- }- public static JobTracker getTracker() {- return tracker;- }+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobTracker");- public static InetSocketAddress getDefaultAddress() {- String jobTrackerStr =- NutchConf.get().get("mapred.job.tracker", "localhost:8012");- int colon = jobTrackerStr.indexOf(":");- if (colon < 0) {- throw new RuntimeException("Bad mapred.job.tracker: "+jobTrackerStr);+ private static JobTracker tracker = null;+ public static void startTracker(NutchConf conf) throws IOException {+ if (tracker != null)+ throw new IOException("JobTracker already running.");+ while (true) {+ try {+ tracker = new JobTracker(conf);+ break;+ } catch (IOException e) {+ LOG.log(Level.WARNING, "Starting tracker", e);+ }+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {+ }}- String jobTrackerName = jobTrackerStr.substring(0, colon);- int jobTrackerPort = Integer.parseInt(jobTrackerStr.substring(colon+1));- return new InetSocketAddress(jobTrackerName, jobTrackerPort);+ tracker.offerService();}-+ public static JobTracker getTracker() {+ return tracker;+ }///////////////////////////////////////////////////////// Used to expire TaskTrackers that have gone down@@ -201,18 +200,20 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss// Used to provide an HTML view on Job, Task, and TaskTracker structuresJobTrackerInfoServer infoServer;+ int infoPort;+Server interTrackerServer;// Some jobs are stored in a local system directory. We can delete// the files when we're done with the job.- File localDir;+ static final String SUBDIR = "jobTracker";NutchFileSystem fs;File systemDir;/*** Start the JobTracker process, listen on the indicated port*/- JobTracker(InetSocketAddress addr) throws IOException {+ JobTracker(NutchConf conf) throws IOException {// This is a directory of temporary submission files. We delete it// on startup, and can delete any files that we're done withthis.systemDir = JobConf.getSystemDir();@@ -221,16 +222,23 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissfs.mkdirs(systemDir);// Same with 'localDir' except it's always on the local disk.- this.localDir = JobConf.getLocalDir();- FileUtil.fullyDelete(localDir);- this.localDir.mkdirs();+ JobConf.deleteLocalFiles(SUBDIR);// Set ports, start RPC servers, etc.+ InetSocketAddress addr = getAddress(conf);this.localMachine = addr.getHostName();this.port = addr.getPort();- this.interTrackerServer = RPC.getServer(this, addr.getPort());+ this.interTrackerServer = RPC.getServer(this,addr.getPort(),10,false);this.interTrackerServer.start();- this.infoServer = new JobTrackerInfoServer(this, TRACKERINFO_PORT);+ Properties p = System.getProperties();+ for (Iterator it = p.keySet().iterator(); it.hasNext(); ) {+ String key = (String) it.next();+ String val = (String) p.getProperty(key);+ LOG.info("Property '" + key + "' is " + val);+ }++ this.infoPort = conf.getInt("mapred.job.tracker.info.port", 50030);+ this.infoServer = new JobTrackerInfoServer(this, infoPort);this.infoServer.start();this.startTime = System.currentTimeMillis();@@ -238,6 +246,19 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissnew Thread(this.expireTrackers).start();}+ public static InetSocketAddress getAddress(NutchConf conf) {+ String jobTrackerStr =+ conf.get("mapred.job.tracker", "localhost:8012");+ int colon = jobTrackerStr.indexOf(":");+ if (colon < 0) {+ throw new RuntimeException("Bad mapred.job.tracker: "+jobTrackerStr);+ }+ String jobTrackerName = jobTrackerStr.substring(0, colon);+ int jobTrackerPort = Integer.parseInt(jobTrackerStr.substring(colon+1));+ return new InetSocketAddress(jobTrackerName, jobTrackerPort);+ }++/*** Run forever*/@@ -317,13 +338,13 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss/*** Process incoming heartbeat messages from the task trackers.*/- public IntWritable emitHeartbeat(TaskTrackerStatus trackerStatus, BooleanWritable initialContact) {+ public synchronized int emitHeartbeat(TaskTrackerStatus trackerStatus, boolean initialContact) {String trackerName = trackerStatus.getTrackerName();trackerStatus.setLastSeen(System.currentTimeMillis());synchronized (taskTrackers) {synchronized (trackerExpiryQueue) {- if (initialContact.get()) {+ if (initialContact) {// If it's first contact, then clear out any state hanging aroundif (taskTrackers.get(trackerName) != null) {taskTrackers.remove(trackerName);@@ -332,14 +353,14 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss} else {// If not first contact, there should be some record of the trackerif (taskTrackers.get(trackerName) == null) {- return new IntWritable(InterTrackerProtocol.UNKNOWN_TASKTRACKER);+ return InterTrackerProtocol.UNKNOWN_TASKTRACKER;}}// Store latest state. If first contact, then save current// state in expiry queuetaskTrackers.put(trackerName, trackerStatus);- if (initialContact.get()) {+ if (initialContact) {trackerExpiryQueue.add(trackerStatus);}}@@ -347,13 +368,13 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissupdateTaskStatuses(trackerStatus);//LOG.info("Got heartbeat from "+trackerName);- return new IntWritable(InterTrackerProtocol.TRACKERS_OK);+ return InterTrackerProtocol.TRACKERS_OK;}/*** A tracker wants to know if there's a Task to run*/- public Task pollForNewTask(String trackerName) {+ public synchronized Task pollForNewTask(String trackerName) {//LOG.info("Unassigned tasks: " + unassignedTasks.size());// Allocate a pending task to this TaskTracker@@ -397,30 +418,34 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss* map task outputs.**/- public MapOutputLocation[] locateMapOutputs(String taskId, String[] mapTasksNeeded) {+ public synchronized MapOutputLocation[] locateMapOutputs(String taskId, String[] mapTasksNeeded) {JobInProgress job = (JobInProgress) jobs.get((String) taskToJobMap.get(taskId));MapOutputLocation outputs[] = job.locateTasks(mapTasksNeeded);return outputs;}- public JobTracker.JobInProgress getJob(String jobid) {- return (JobInProgress) jobs.get(jobid);+ /**+ * Grab the local fs name+ */+ public synchronized String getFilesystemName() throws IOException {+ return fs.getName();}+////////////////////////////////////////////////////// JobSubmissionProtocol////////////////////////////////////////////////////- public JobStatus submitJob(String jobFile) throws IOException {+ public synchronized JobStatus submitJob(String jobFile) throws IOException {totalSubmissions++;JobInProgress job = createJob(jobFile);return job.getStatus();}- public void killJob(String jobid) {+ public synchronized void killJob(String jobid) {JobInProgress job = (JobInProgress) jobs.get(jobid);job.kill();}- public JobProfile getJobProfile(String jobid) {+ public synchronized JobProfile getJobProfile(String jobid) {JobInProgress job = (JobInProgress) jobs.get(jobid);if (job != null) {return job.getProfile();@@ -428,7 +453,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissreturn null;}}- public JobStatus getJobStatus(String jobid) {+ public synchronized JobStatus getJobStatus(String jobid) {JobInProgress job = (JobInProgress) jobs.get(jobid);if (job != null) {return job.getStatus();@@ -436,14 +461,66 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissreturn null;}}+ public synchronized Vector[] getMapTaskReport(String jobid) {+ JobInProgress job = (JobInProgress) jobs.get(jobid);+ if (job == null) {+ return new Vector[0];+ } else {+ Vector reports = new Vector();+ TreeMap completeMapTasks = job.getCompleteMapTasks();+ for (Iterator it = completeMapTasks.keySet().iterator(); it.hasNext(); ) {+ String taskid = (String) it.next();+ reports.add(generateSingleReport(taskid, job.getTaskStatus(taskid), job.getTaskDiagnosticInfo(taskid), job.getTaskStateString(taskid)));+ }+ TreeMap incompleteMapTasks = job.getIncompleteMapTasks();+ for (Iterator it = incompleteMapTasks.keySet().iterator(); it.hasNext(); ) {+ String taskid = (String) it.next();+ reports.add(generateSingleReport(taskid, job.getTaskStatus(taskid), job.getTaskDiagnosticInfo(taskid), job.getTaskStateString(taskid)));+ }+ return (Vector[]) reports.toArray(new Vector[reports.size()]);+ }+ }- public String getFilesystemName() throws IOException {- return fs.getName();+ public synchronized Vector[] getReduceTaskReport(String jobid) {+ JobInProgress job = (JobInProgress) jobs.get(jobid);+ if (job == null) {+ return new Vector[0];+ } else {+ Vector reports = new Vector();+ TreeMap completeReduceTasks = job.getCompleteReduceTasks();+ for (Iterator it = completeReduceTasks.keySet().iterator(); it.hasNext(); ) {+ String taskid = (String) it.next();+ reports.add(generateSingleReport(taskid, job.getTaskStatus(taskid), job.getTaskDiagnosticInfo(taskid), job.getTaskStateString(taskid)));+ }+ TreeMap incompleteReduceTasks = job.getIncompleteReduceTasks();+ for (Iterator it = incompleteReduceTasks.keySet().iterator(); it.hasNext(); ) {+ String taskid = (String) it.next();+ reports.add(generateSingleReport(taskid, job.getTaskStatus(taskid), job.getTaskDiagnosticInfo(taskid), job.getTaskStateString(taskid)));+ }+ return (Vector[]) reports.toArray(new Vector[reports.size()]);+ }+ }++ //////////////////////////////////////////////////////////////+ // (See InterTrackerProtocol section for getFilesystemName())+ //////////////////////////////////////////////////////////////++ Vector generateSingleReport(String taskid, TaskStatus status, Vector diagInfo, String stateString) {+ Vector report = new Vector();+ report.add(taskid);+ report.add("" + status.getProgress());+ report.add(stateString);+ report.addAll(diagInfo);+ return report;}///////////////////////////////////////////////////////////////// JobTracker methods///////////////////////////////////////////////////////////////+ public JobTracker.JobInProgress getJob(String jobid) {+ return (JobInProgress) jobs.get(jobid);+ }+/*** JobProfile createJob() kicks off a new job.* This function creates a job profile and also decomposes it into@@ -454,7 +531,17 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissJobInProgress createJob(String jobFile) throws IOException {JobInProgress job = new JobInProgress(jobFile);jobs.put(job.getProfile().getJobId(), job);- job.launch();++ boolean error = true;+ try {+ job.launch();+ error = false;+ } finally {+ if (error) {+ job.kill();+ }+ }+return job;}@@ -475,6 +562,9 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissTreeMap completeMapTasks = new TreeMap();TreeMap incompleteReduceTasks = new TreeMap();TreeMap completeReduceTasks = new TreeMap();+ TreeMap taskFailures = new TreeMap();+ TreeMap taskDiagnosticData = new TreeMap();+ TreeMap taskStateStrings = new TreeMap();// Info for user; useless for JobTrackerint numMapTasks = 0;@@ -495,11 +585,11 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss*/public JobInProgress(String jobFile) throws IOException {String jobid = createJobId();- String url = "http://" + localMachine + ":" + TRACKERINFO_PORT + "/jobdetails.jsp?jobid=" + jobid;+ String url = "http://" + localMachine + ":" + infoPort + "/jobdetails.jsp?jobid=" + jobid;this.profile = new JobProfile(jobid, jobFile, url);this.status = new JobStatus(jobid, 0.0f, 0.0f, JobStatus.RUNNING);- this.localJobFile = new File(localDir, jobid+".xml");+ this.localJobFile = JobConf.getLocalFile(SUBDIR, jobid+".xml");fs.copyToLocalFile(new File(jobFile), localJobFile);JobConf jd = new JobConf(localJobFile);@@ -527,6 +617,15 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissFileSplit[] splits =jd.getInputFormat().getSplits(fs, jd, numMapTasks);+ // sort splits by decreasing length, to reduce job's tail+ Arrays.sort(splits, new Comparator() {+ public int compare(Object a, Object b) {+ long diff =+ ((FileSplit)b).getLength() - ((FileSplit)a).getLength();+ return diff==0 ? 0 : (diff > 0 ? 1 : -1);+ }+ });+// adjust number of map tasks to actual number of splitsnumMapTasks = splits.length;@@ -558,8 +657,24 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss* Kill the job and all its component tasks.*/public synchronized void kill() {- this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.FAILED);- this.finishTime = System.currentTimeMillis();+ if (status.getRunState() != JobStatus.FAILED) {+ this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.FAILED);++ //+ // Kill all the pending tasks+ //+ synchronized (unassignedTasks) {+ for (Iterator it = unassignedTasks.iterator(); it.hasNext(); ) {+ String taskid = (String) it.next();+ if ((incompleteMapTasks.get(taskid) != null) ||+ (incompleteReduceTasks.get(taskid) != null)) {+ it.remove();+ }+ }+ }++ this.finishTime = System.currentTimeMillis();+ }}/**@@ -665,6 +780,16 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmisscompleteReduceTasks.remove(taskid);incompleteReduceTasks.put(taskid, t);}++ // Check if we need to kill the job because of excess failures+ Integer failures = (Integer) taskFailures.get(taskid);+ int numFailures = ((failures == null) ? 0 : failures.intValue()) + 1;+ taskFailures.put(taskid, new Integer(numFailures));+ if (numFailures >= MAX_TASK_FAILURES) {+ LOG.info("Task " + taskid + " has failed " + numFailures + " times. Aborting owning job " + profile.getJobId());+ kill();+ }+if (status.getRunState() == JobStatus.RUNNING) {executeTask(taskid);}@@ -692,6 +817,18 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss//////////////////////////// A number of accessors//////////////////////////+ TreeMap getCompleteMapTasks() {+ return completeMapTasks;+ }+ TreeMap getIncompleteMapTasks() {+ return incompleteMapTasks;+ }+ TreeMap getCompleteReduceTasks() {+ return completeReduceTasks;+ }+ TreeMap getIncompleteReduceTasks() {+ return incompleteReduceTasks;+ }public JobProfile getProfile() {return profile;}@@ -720,6 +857,17 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss}return t;}+ public Vector getTaskDiagnosticInfo(String taskid) {+ Vector v = (Vector) taskDiagnosticData.get(taskid);+ if (v == null) {+ return new Vector();+ } else {+ return v;+ }+ }+ public String getTaskStateString(String taskid) {+ return (String) taskStateStrings.get(taskid);+ }public float completedRatio() {return (0.5f * status.mapProgress()) + (0.5f * status.reduceProgress());}@@ -756,6 +904,18 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss}delta += status.getProgress();+ String diagInfo = status.getDiagnosticInfo();+ if (diagInfo != null && diagInfo.length() > 0) {+ Vector v = (Vector) taskDiagnosticData.get(taskid);+ if (v == null) {+ v = new Vector();+ taskDiagnosticData.put(taskid, v);+ }+ v.add(diagInfo);+ }++ taskStateStrings.put(taskid, status.getStateString());+if (incompleteMapTasks.get(taskid) != null ||completeMapTasks.get(taskid) != null) {totalReportedMapProgress += delta;@@ -789,8 +949,10 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss} else if (incompleteReduceTasks.get(taskid) != null) {attemptedReduceExecutions++;}- updateTaskStatus(taskid, new TaskStatus(taskid, 0.0f, TaskStatus.UNASSIGNED));- unassignedTasks.add(taskid);+ updateTaskStatus(taskid, new TaskStatus(taskid, 0.0f, TaskStatus.UNASSIGNED, "", ""));+ synchronized (unassignedTasks) {+ unassignedTasks.add(taskid);+ }}}@@ -850,28 +1012,30 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss* just grabs a single item out of the pending task list and hands it back.*/Task getTaskAssignment(String taskTracker) {- if (unassignedTasks.size() > 0) {- String taskid = (String) unassignedTasks.elementAt(0);- unassignedTasks.remove(taskid);+ synchronized (unassignedTasks) {+ if (unassignedTasks.size() > 0) {+ String taskid = (String) unassignedTasks.elementAt(0);+ unassignedTasks.remove(taskid);++ // Move task status to RUNNING+ JobInProgress job = (JobInProgress) jobs.get((String) taskToJobMap.get(taskid));+ job.updateTaskStatus(taskid, new TaskStatus(taskid, 0.0f, TaskStatus.RUNNING, "", ""));++ // Remember where we are running it+ TreeSet taskset = (TreeSet) trackerToTaskMap.get(taskTracker);+ if (taskset == null) {+ taskset = new TreeSet();+ trackerToTaskMap.put(taskTracker, taskset);+ }+ LOG.info("Adding task '" + taskid + "' to set for tracker '" + taskTracker + "'");+ taskset.add(taskid);- // Move task status to RUNNING- JobInProgress job = (JobInProgress) jobs.get((String) taskToJobMap.get(taskid));- job.updateTaskStatus(taskid, new TaskStatus(taskid, 0.0f, TaskStatus.RUNNING));+ taskToTrackerMap.put(taskid, taskTracker);- // Remember where we are running it- TreeSet taskset = (TreeSet) trackerToTaskMap.get(taskTracker);- if (taskset == null) {- taskset = new TreeSet();- trackerToTaskMap.put(taskTracker, taskset);+ return job.getTask(taskid);+ } else {+ return null;}- LOG.info("Adding task '" + taskid + "' to set for tracker '" + taskTracker + "'");- taskset.add(taskid);-- taskToTrackerMap.put(taskid, taskTracker);-- return job.getTask(taskid);- } else {- return null;}}@@ -903,8 +1067,6 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissSystem.exit(-1);}- JobTracker.createTracker();- JobTracker jt = JobTracker.getTracker();- jt.offerService();+ startTracker(NutchConf.get());}}diff --git a/src/java/org/apache/nutch/mapReduce/JobTrackerInfoServer.java b/src/java/org/apache/nutch/mapred/JobTrackerInfoServer.javasimilarity index 87%rename from src/java/org/apache/nutch/mapReduce/JobTrackerInfoServer.javarename to src/java/org/apache/nutch/mapred/JobTrackerInfoServer.javaindex 4237fe265..38c816919 100644--- a/src/java/org/apache/nutch/mapReduce/JobTrackerInfoServer.java+++ b/src/java/org/apache/nutch/mapred/JobTrackerInfoServer.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;import org.apache.nutch.ipc.*;@@ -59,10 +59,21 @@ public class JobTrackerInfoServer {* We need the jobTracker to grab stats, and the port to* know where to listen.*/+ private static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException {this.jobTracker = jobTracker;this.server = new org.mortbay.jetty.Server();- WebApplicationContext context = server.addWebApplication(null, "/", "src/webapps/jobtracker");+ URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps");+ String path = url.getPath();+ if (WINDOWS && path.startsWith("/")) {+ path = path.substring(1);+ try {+ path = URLDecoder.decode(path, "UTF-8");+ } catch (UnsupportedEncodingException e) {+ }+ }+ File jobtracker = new File(path, "jobtracker");+ WebApplicationContext context = server.addWebApplication(null, "/", jobtracker.getCanonicalPath());SocketListener socketListener = new SocketListener();socketListener.setPort(port);diff --git a/src/java/org/apache/nutch/mapred/LocalJobRunner.java b/src/java/org/apache/nutch/mapred/LocalJobRunner.javanew file mode 100644index 000000000..98172a677--- /dev/null+++ b/src/java/org/apache/nutch/mapred/LocalJobRunner.java@@ -0,0 +1,175 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.*;+import java.util.*;+import java.util.logging.*;++import org.apache.nutch.io.*;+import org.apache.nutch.fs.*;+import org.apache.nutch.util.*;++/** Implements MapReduce locally, in-process, for debugging. */+public class LocalJobRunner implements JobSubmissionProtocol {+ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.mapred.LocalJobRunner");++ private NutchFileSystem fs;+ private HashMap jobs = new HashMap();++ private class Job extends Thread+ implements TaskUmbilicalProtocol {+ private String file;+ private String id;+ private JobConf job;++ private JobStatus status = new JobStatus();+ private ArrayList mapIds = new ArrayList();++ public Job(String file) throws IOException {+ this.file = file;+ this.id = "job_" + newId();++ File localFile = JobConf.getLocalFile("localRunner", id+".xml");+ fs.copyToLocalFile(new File(file), localFile);+ this.job = new JobConf(localFile);++ this.status.jobid = id;+ this.status.runState = JobStatus.RUNNING;++ jobs.put(id, this);++ this.start();+ }++ public void run() {+ try {+ // split input into minimum number of splits+ FileSplit[] splits = job.getInputFormat().getSplits(fs, job, 1);++ // run a map task for each split+ job.setNumReduceTasks(1); // force a single reduce task+ for (int i = 0; i < splits.length; i++) {+ mapIds.add("map_" + newId());+ MapTask map = new MapTask(file, (String)mapIds.get(i), splits[i]);+ map.run(job, this);+ }++ // move map output to reduce input+ String reduceId = "reduce_" + newId();+ for (int i = 0; i < mapIds.size(); i++) {+ String mapId = (String)mapIds.get(i);+ File mapOut = MapOutputFile.getOutputFile(mapId, 0);+ File reduceIn = MapOutputFile.getInputFile(mapId, reduceId);+ reduceIn.getParentFile().mkdirs();+ if (!NutchFileSystem.getNamed("local").rename(mapOut, reduceIn))+ throw new IOException("Couldn't rename " + mapOut);+ MapOutputFile.removeAll(mapId);+ }++ // run a single reduce task+ ReduceTask reduce =+ new ReduceTask(file, reduceId,+ (String[])mapIds.toArray(new String[0]),+ 0);+ reduce.run(job, this);+ MapOutputFile.removeAll(reduceId);++ this.status.runState = JobStatus.SUCCEEDED;++ } catch (Throwable t) {+ this.status.runState = JobStatus.FAILED;+ t.printStackTrace();+ }+ }++ private String newId() {+ return Integer.toString(Math.abs(new Random().nextInt()),36);+ }++ // TaskUmbilicalProtocol methods++ public Task getTask(String taskid) { return null; }++ public void progress(String taskId, float progress, String state) {+ LOG.info(state);+ float taskIndex = mapIds.indexOf(taskId);+ if (taskIndex >= 0) { // mapping+ float numTasks = mapIds.size();+ status.mapProgress = (taskIndex/numTasks)+(progress/numTasks);+ } else {+ status.reduceProgress = progress;+ }+ }++ public void reportDiagnosticInfo(String taskid, String trace) {+ // Ignore for now+ }++ public void ping(String taskid) throws IOException {}++ public void done(String taskId) throws IOException {+ int taskIndex = mapIds.indexOf(taskId);+ if (taskIndex >= 0) { // mapping+ status.mapProgress = 1.0f;+ } else {+ status.reduceProgress = 1.0f;+ }+ }++ public synchronized void fsError(String message) throws IOException {+ LOG.severe("FSError: "+ message);+ }++ }++ public LocalJobRunner() throws IOException {+ this.fs = NutchFileSystem.get();+ }++ // JobSubmissionProtocol methods++ public JobStatus submitJob(String jobFile) throws IOException {+ return new Job(jobFile).status;+ }++ public void killJob(String id) {+ ((Thread)jobs.get(id)).stop();+ }++ public JobProfile getJobProfile(String id) {+ Job job = (Job)jobs.get(id);+ return new JobProfile(id, job.file, "http://localhost:8080/");+ }++ public Vector[] getMapTaskReport(String id) {+ return new Vector[0];+ }+ public Vector[] getReduceTaskReport(String id) {+ return new Vector[0];+ }++ public JobStatus getJobStatus(String id) {+ Job job = (Job)jobs.get(id);+ return job.status;+ }++ public String getFilesystemName() throws IOException {+ return fs.getName();+ }+}diff --git a/src/java/org/apache/nutch/mapReduce/MRConstants.java b/src/java/org/apache/nutch/mapred/MRConstants.javasimilarity index 90%rename from src/java/org/apache/nutch/mapReduce/MRConstants.javarename to src/java/org/apache/nutch/mapred/MRConstants.javaindex 071eca915..26256e97d 100644--- a/src/java/org/apache/nutch/mapReduce/MRConstants.java+++ b/src/java/org/apache/nutch/mapred/MRConstants.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;/******************************** Some handy constants@@ -25,7 +25,7 @@ public interface MRConstants {// Timeouts, constants//public static final long HEARTBEAT_INTERVAL = 3 * 1000;- public static final long TASKTRACKER_EXPIRY_INTERVAL = 30 * 1000;+ public static final long TASKTRACKER_EXPIRY_INTERVAL = 10 * 60 * 1000;//// Result codesdiff --git a/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java b/src/java/org/apache/nutch/mapred/MapFileOutputFormat.javanew file mode 100644index 000000000..82eb4cab0--- /dev/null+++ b/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java@@ -0,0 +1,79 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;+import java.io.File;+import java.util.Arrays;++import org.apache.nutch.fs.NutchFileSystem;++import org.apache.nutch.io.MapFile;+import org.apache.nutch.io.WritableComparable;+import org.apache.nutch.io.Writable;++public class MapFileOutputFormat implements OutputFormat {++ public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,+ String name) throws IOException {++ File file = new File(job.getOutputDir(), name);++ final MapFile.Writer out =+ new MapFile.Writer(fs, file.toString(),+ job.getOutputKeyClass(),+ job.getOutputValueClass(),+ job.getBoolean("mapred.output.compress", false));++ return new RecordWriter() {++ public void write(WritableComparable key, Writable value)+ throws IOException {++ out.append(key, value);+ }++ public void close(Reporter reporter) throws IOException { out.close();}+ };+ }++ /** Open the output generated by this format. */+ public static MapFile.Reader[] getReaders(NutchFileSystem fs, File dir)+ throws IOException {+ File[] names = fs.listFiles(dir);++ // sort names, so that hash partitioning works+ Arrays.sort(names);++ MapFile.Reader[] parts = new MapFile.Reader[names.length];+ for (int i = 0; i < names.length; i++) {+ parts[i] = new MapFile.Reader(fs, names[i].toString());+ }+ return parts;+ }++ /** Get an entry from output generated by this class. */+ public static Writable getEntry(MapFile.Reader[] readers,+ Partitioner partitioner,+ WritableComparable key,+ Writable value) throws IOException {+ int part = partitioner.getPartition(key, value, readers.length);+ return readers[part].get(key, value);+ }++}+diff --git a/src/java/org/apache/nutch/mapReduce/MapOutputFile.java b/src/java/org/apache/nutch/mapred/MapOutputFile.javasimilarity index 72%rename from src/java/org/apache/nutch/mapReduce/MapOutputFile.javarename to src/java/org/apache/nutch/mapred/MapOutputFile.javaindex 8642f1b1d..91d0d04ab 100644--- a/src/java/org/apache/nutch/mapReduce/MapOutputFile.java+++ b/src/java/org/apache/nutch/mapred/MapOutputFile.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;@@ -25,33 +25,42 @@ import org.apache.nutch.util.*;/** A local file to be transferred via the {@link MapOutputProtocol}. */public class MapOutputFile implements Writable {- private static final String LOCAL_DIR = JobConf.getLocalDir().toString();-private String mapTaskId;private String reduceTaskId;private int partition;+ /** Permits reporting of file copy progress. */+ public static interface ProgressReporter {+ void progress(float progress) throws IOException;+ }++ private static final ThreadLocal REPORTERS = new ThreadLocal();++ public static void setProgressReporter(ProgressReporter reporter) {+ REPORTERS.set(reporter);+ }+/** Create a local map output file name.* @param mapTaskId a map task id* @param partition a reduce partition*/- public static File getOutputFile(String mapTaskId, int partition) {- File taskDir = new File(LOCAL_DIR, mapTaskId);- return new File(taskDir, "part-"+partition+".out");+ public static File getOutputFile(String mapTaskId, int partition)+ throws IOException {+ return JobConf.getLocalFile(mapTaskId, "part-"+partition+".out");}/** Create a local reduce input file name.* @param mapTaskId a map task id* @param reduceTaskId a reduce task id*/- public static File getInputFile(String mapTaskId, String reduceTaskId) {- File taskDir = new File(LOCAL_DIR, reduceTaskId);- return new File(taskDir, mapTaskId+".out");+ public static File getInputFile(String mapTaskId, String reduceTaskId)+ throws IOException {+ return JobConf.getLocalFile(reduceTaskId, mapTaskId+".out");}/** Removes all of the files related to a task. */public static void removeAll(String taskId) throws IOException {- FileUtil.fullyDelete(new File(LOCAL_DIR, taskId));+ JobConf.deleteLocalFiles(taskId);}/**@@ -59,7 +68,7 @@ public class MapOutputFile implements Writable {* startup, to remove any leftovers from previous run.*/public static void cleanupStorage() throws IOException {- FileUtil.fullyDelete(new File(LOCAL_DIR));+ JobConf.deleteLocalFiles();}/** Construct a file for transfer. */@@ -79,7 +88,7 @@ public class MapOutputFile implements Writable {// write the length-prefixed file content to the wireFile file = getOutputFile(mapTaskId, partition);out.writeLong(file.length());- InputStream in = new FileInputStream(file);+ NFSDataInputStream in = NutchFileSystem.getNamed("local").open(file);try {byte[] buffer = new byte[8192];int l;@@ -96,18 +105,24 @@ public class MapOutputFile implements Writable {this.reduceTaskId = UTF8.readString(in);this.partition = in.readInt();+ ProgressReporter reporter = (ProgressReporter)REPORTERS.get();+// read the length-prefixed file content into a local fileFile file = getInputFile(mapTaskId, reduceTaskId);long length = in.readLong();- file.getParentFile().mkdirs(); // make directory- OutputStream out = new FileOutputStream(file);+ float progPerByte = 1.0f / length;+ long unread = length;+ NFSDataOutputStream out = NutchFileSystem.getNamed("local").create(file);try {byte[] buffer = new byte[8192];- while (length > 0) {- int bytesToRead = Math.min((int) length, buffer.length);+ while (unread > 0) {+ int bytesToRead = (int)Math.min(unread, buffer.length);in.readFully(buffer, 0, bytesToRead);out.write(buffer, 0, bytesToRead);- length -= bytesToRead;+ unread -= bytesToRead;+ if (reporter != null) {+ reporter.progress((length-unread)*progPerByte);+ }}} finally {out.close();diff --git a/src/java/org/apache/nutch/mapReduce/MapOutputLocation.java b/src/java/org/apache/nutch/mapred/MapOutputLocation.javasimilarity index 94%rename from src/java/org/apache/nutch/mapReduce/MapOutputLocation.javarename to src/java/org/apache/nutch/mapred/MapOutputLocation.javaindex 57380f632..09a13d8df 100644--- a/src/java/org/apache/nutch/mapReduce/MapOutputLocation.java+++ b/src/java/org/apache/nutch/mapred/MapOutputLocation.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;@@ -61,4 +61,8 @@ public class MapOutputLocation implements Writable {this.port = in.readInt();}+ public String toString() {+ return mapTaskId+"@"+host+":"+port;+ }+}diff --git a/src/java/org/apache/nutch/mapReduce/MapOutputProtocol.java b/src/java/org/apache/nutch/mapred/MapOutputProtocol.javasimilarity index 96%rename from src/java/org/apache/nutch/mapReduce/MapOutputProtocol.javarename to src/java/org/apache/nutch/mapred/MapOutputProtocol.javaindex 8b3877c58..fa42147d2 100644--- a/src/java/org/apache/nutch/mapReduce/MapOutputProtocol.java+++ b/src/java/org/apache/nutch/mapred/MapOutputProtocol.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;diff --git a/src/java/org/apache/nutch/mapred/MapRunnable.java b/src/java/org/apache/nutch/mapred/MapRunnable.javanew file mode 100644index 000000000..796123203--- /dev/null+++ b/src/java/org/apache/nutch/mapred/MapRunnable.java@@ -0,0 +1,33 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;++import org.apache.nutch.io.Writable;+import org.apache.nutch.io.WritableComparable;++/** Expert: Permits greater control of map processing. For example,+ * implementations might perform multi-threaded, asynchronous mappings. */+public interface MapRunnable extends JobConfigurable {+ /** Called to execute mapping. Mapping is complete when this returns.+ * @param input the {@link RecordReader} with input key/value pairs.+ * @param output the {@link OutputCollector} for mapped key/value pairs.+ */+ void run(RecordReader input, OutputCollector output, Reporter reporter)+ throws IOException;+}diff --git a/src/java/org/apache/nutch/mapred/MapRunner.java b/src/java/org/apache/nutch/mapred/MapRunner.javanew file mode 100644index 000000000..6f564fd4a--- /dev/null+++ b/src/java/org/apache/nutch/mapred/MapRunner.java@@ -0,0 +1,56 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;++import org.apache.nutch.io.Writable;+import org.apache.nutch.io.WritableComparable;++/** Default {@link MapRunnable} implementation.*/+public class MapRunner implements MapRunnable {+ private JobConf job;+ private Mapper mapper;+ private Class inputKeyClass;+ private Class inputValueClass;++ public void configure(JobConf job) {+ this.job = job;+ this.mapper = (Mapper)job.newInstance(job.getMapperClass());+ this.inputKeyClass = job.getInputKeyClass();+ this.inputValueClass = job.getInputValueClass();+ }++ public void run(RecordReader input, OutputCollector output,+ Reporter reporter)+ throws IOException {+ while (true) {+ // allocate new key & value instances+ WritableComparable key =+ (WritableComparable)job.newInstance(inputKeyClass);+ Writable value = (Writable)job.newInstance(inputValueClass);++ // read next key & value+ if (!input.next(key, value))+ return;++ // map pair to output+ mapper.map(key, value, output, reporter);+ }+ }++}diff --git a/src/java/org/apache/nutch/mapReduce/MapTask.java b/src/java/org/apache/nutch/mapred/MapTask.javasimilarity index 63%rename from src/java/org/apache/nutch/mapReduce/MapTask.javarename to src/java/org/apache/nutch/mapred/MapTask.javaindex 553b325d5..95cfe6d37 100644--- a/src/java/org/apache/nutch/mapReduce/MapTask.java+++ b/src/java/org/apache/nutch/mapred/MapTask.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.*;import java.net.*;@@ -53,7 +53,7 @@ public class MapTask extends Task {split.readFields(in);}- public void run(final JobConf job, TaskUmbilicalProtocol umbilical)+ public void run(final JobConf job, final TaskUmbilicalProtocol umbilical)throws IOException {// open output files@@ -68,59 +68,52 @@ public class MapTask extends Task {job.getOutputValueClass());}- Mapper mapper = (Mapper)job.newInstance(job.getMapperClass());final Partitioner partitioner =(Partitioner)job.newInstance(job.getPartitionerClass());OutputCollector partCollector = new OutputCollector() { // make collector- public void collect(WritableComparable key, Writable value)+ public synchronized void collect(WritableComparable key,+ Writable value)throws IOException {- outs[partitioner.getPartition(key, partitions)].append(key, value);+ outs[partitioner.getPartition(key, value, partitions)]+ .append(key, value);+ reportProgress(umbilical);}};OutputCollector collector = partCollector;+ Reporter reporter = getReporter(umbilical, getProgress());boolean combining = job.getCombinerClass() != null;if (combining) { // add combining collector- collector = new CombiningCollector(job, partCollector);+ collector = new CombiningCollector(job, partCollector, reporter);}- float end = (float)split.getLength();- float lastProgress = 0.0f;+ final RecordReader rawIn = // open input+ job.getInputFormat().getRecordReader+ (NutchFileSystem.get(), split, job, reporter);- Class inputKeyClass = job.getInputKeyClass();- Class inputValueClass = job.getInputValueClass();- WritableComparable key = null;- Writable value = null;+ RecordReader in = new RecordReader() { // wrap in progress reporter+ private float perByte = 1.0f /(float)split.getLength();- RecordReader in = // open the input- job.getInputFormat().getRecordReader(NutchFileSystem.get(),split,job);+ public synchronized boolean next(Writable key, Writable value)+ throws IOException {- try {+ float progress = // compute progress+ (float)Math.min((rawIn.getPos()-split.getStart())*perByte, 1.0f);+ reportProgress(umbilical, progress);- // always allocate new keys and values when combining- if (combining || key == null) {- try {- key = (WritableComparable)inputKeyClass.newInstance();- value = (Writable)inputValueClass.newInstance();- } catch (Exception e) {- throw new IOException(e.toString());+ return rawIn.next(key, value);}- }-- while (in.next(key, value)) { // map input to collector+ public long getPos() throws IOException { return rawIn.getPos(); }+ public void close() throws IOException { rawIn.close(); }+ };- mapper.map(key, value, collector);+ MapRunnable runner =+ (MapRunnable)job.newInstance(job.getMapRunnerClass());- float progress = // compute progress- (float)Math.min((in.getPos()-split.getStart())/end, 1.0f);-- if ((progress - lastProgress) > 0.01f) { // 100 progress reports- umbilical.progress(getTaskId(), new FloatWritable(progress));- lastProgress = progress;- }- }+ try {+ runner.run(in, collector, reporter); // run the mapif (combining) { // flush combiner((CombiningCollector)collector).flush();@@ -136,6 +129,7 @@ public class MapTask extends Task {}}}+ done(umbilical);}}diff --git a/src/java/org/apache/nutch/mapReduce/MapTaskRunner.java b/src/java/org/apache/nutch/mapred/MapTaskRunner.javasimilarity index 93%rename from src/java/org/apache/nutch/mapReduce/MapTaskRunner.javarename to src/java/org/apache/nutch/mapred/MapTaskRunner.javaindex fc94e2429..48233789e 100644--- a/src/java/org/apache/nutch/mapReduce/MapTaskRunner.java+++ b/src/java/org/apache/nutch/mapred/MapTaskRunner.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;import org.apache.nutch.ipc.*;@@ -36,7 +36,7 @@ class MapTaskRunner extends TaskRunner {/** Delete all of the temporary map output files. */public void close() throws IOException {- LOG.info("Task "+getTask()+" done; removing files.");+ LOG.info(getTask()+" done; removing files.");MapOutputFile.removeAll(getTask().getTaskId());}}diff --git a/src/java/org/apache/nutch/mapReduce/Mapper.java b/src/java/org/apache/nutch/mapred/Mapper.javasimilarity index 88%rename from src/java/org/apache/nutch/mapReduce/Mapper.javarename to src/java/org/apache/nutch/mapred/Mapper.javaindex 08b9bef81..cf3cfbabb 100644--- a/src/java/org/apache/nutch/mapReduce/Mapper.java+++ b/src/java/org/apache/nutch/mapred/Mapper.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;@@ -25,7 +25,7 @@ import org.apache.nutch.io.WritableComparable;* intermediate values associated with a given output key are subsequently* grouped by the map/reduce system, and passed to a {@link Reducer} to* determine the final output.. */-public interface Mapper extends Configurable {+public interface Mapper extends JobConfigurable {/** Maps a single input key/value pair into intermediate key/value pairs.* Output pairs need not be of the same types as input pairs. A given input* pair may map to zero or many output pairs. Output pairs are collected@@ -36,6 +36,7 @@ public interface Mapper extends Configurable {* @param value the values* @param output collects mapped keys and values*/- void map(WritableComparable key, Writable value, OutputCollector output)+ void map(WritableComparable key, Writable value,+ OutputCollector output, Reporter reporter)throws IOException;}diff --git a/src/java/org/apache/nutch/mapReduce/OutputCollector.java b/src/java/org/apache/nutch/mapred/OutputCollector.javasimilarity index 96%rename from src/java/org/apache/nutch/mapReduce/OutputCollector.javarename to src/java/org/apache/nutch/mapred/OutputCollector.javaindex ca1725aa6..135bddfa8 100644--- a/src/java/org/apache/nutch/mapReduce/OutputCollector.java+++ b/src/java/org/apache/nutch/mapred/OutputCollector.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.DataInput;diff --git a/src/java/org/apache/nutch/mapReduce/OutputFormat.java b/src/java/org/apache/nutch/mapred/OutputFormat.javasimilarity index 90%rename from src/java/org/apache/nutch/mapReduce/OutputFormat.javarename to src/java/org/apache/nutch/mapred/OutputFormat.javaindex 654b62a8d..4eb932a33 100644--- a/src/java/org/apache/nutch/mapReduce/OutputFormat.java+++ b/src/java/org/apache/nutch/mapred/OutputFormat.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;@@ -24,11 +24,6 @@ import org.apache.nutch.fs.NutchFileSystem;/** An output data format. Output files are stored in a {@link* NutchFileSystem}. */public interface OutputFormat {-- /** The name of this output format.- * @see OutputFormats- */- String getName();/** Construct a {@link RecordWriter}.*diff --git a/src/java/org/apache/nutch/mapReduce/Partitioner.java b/src/java/org/apache/nutch/mapred/Partitioner.javasimilarity index 75%rename from src/java/org/apache/nutch/mapReduce/Partitioner.javarename to src/java/org/apache/nutch/mapred/Partitioner.javaindex 6c2540f87..6a92f93a6 100644--- a/src/java/org/apache/nutch/mapReduce/Partitioner.java+++ b/src/java/org/apache/nutch/mapred/Partitioner.java@@ -14,19 +14,20 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.Writable;import org.apache.nutch.io.WritableComparable;/** Partitions the key space. A partition is created for each reduce task. */-public interface Partitioner extends Configurable {- /** Returns the paritition number for a given key given the total number of+public interface Partitioner extends JobConfigurable {+ /** Returns the paritition number for a given entry given the total number of* partitions. Typically a hash function on a all or a subset of the key.*- * @param key the key+ * @param key the entry key+ * @param value the entry value* @param numPartitions the number of partitions* @return the partition number*/- int getPartition(WritableComparable key, int numPartitions);+ int getPartition(WritableComparable key, Writable value, int numPartitions);}diff --git a/src/java/org/apache/nutch/mapReduce/RecordReader.java b/src/java/org/apache/nutch/mapred/RecordReader.javasimilarity index 97%rename from src/java/org/apache/nutch/mapReduce/RecordReader.javarename to src/java/org/apache/nutch/mapred/RecordReader.javaindex e3a7394cb..78d443d03 100644--- a/src/java/org/apache/nutch/mapReduce/RecordReader.java+++ b/src/java/org/apache/nutch/mapred/RecordReader.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.DataInput;diff --git a/src/java/org/apache/nutch/mapReduce/RecordWriter.java b/src/java/org/apache/nutch/mapred/RecordWriter.javasimilarity index 93%rename from src/java/org/apache/nutch/mapReduce/RecordWriter.javarename to src/java/org/apache/nutch/mapred/RecordWriter.javaindex d5ade3689..732c5392a 100644--- a/src/java/org/apache/nutch/mapReduce/RecordWriter.java+++ b/src/java/org/apache/nutch/mapred/RecordWriter.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.DataOutput;@@ -35,5 +35,5 @@ public interface RecordWriter {void write(WritableComparable key, Writable value) throws IOException;/** Close this to future operations.*/- void close() throws IOException;+ void close(Reporter reporter) throws IOException;}diff --git a/src/java/org/apache/nutch/mapReduce/ReduceTask.java b/src/java/org/apache/nutch/mapred/ReduceTask.javasimilarity index 55%rename from src/java/org/apache/nutch/mapReduce/ReduceTask.javarename to src/java/org/apache/nutch/mapred/ReduceTask.javaindex f27e1b4c6..361a41c2c 100644--- a/src/java/org/apache/nutch/mapReduce/ReduceTask.java+++ b/src/java/org/apache/nutch/mapred/ReduceTask.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;import org.apache.nutch.util.*;@@ -23,13 +23,20 @@ import org.apache.nutch.fs.*;import java.io.*;import java.net.*;import java.util.*;+import java.text.*;/** A Reduce task. */public class ReduceTask extends Task {- private static final String LOCAL_DIR = JobConf.getLocalDir().toString();-private String[] mapTaskIds;private int partition;+ private boolean sortComplete;++ { getProgress().setStatus("reduce"); }++ private Progress copyPhase = getProgress().addPhase("copy");+ private Progress appendPhase = getProgress().addPhase("append");+ private Progress sortPhase = getProgress().addPhase("sort");+ private Progress reducePhase = getProgress().addPhase("reduce");public ReduceTask() {}@@ -70,15 +77,24 @@ public class ReduceTask extends Task {}/** Iterates values while keys match in sorted input. */- private static class ValuesIterator implements Iterator {+ private class ValuesIterator implements Iterator {private SequenceFile.Reader in; // input fileprivate WritableComparable key; // current keyprivate Writable value; // current valueprivate boolean hasNext; // more w/ this keyprivate boolean more; // more in file-- public ValuesIterator (SequenceFile.Reader in) throws IOException {+ private float progPerByte;+ private TaskUmbilicalProtocol umbilical;+ private WritableComparator comparator;++ public ValuesIterator (SequenceFile.Reader in, long length,+ WritableComparator comparator,+ TaskUmbilicalProtocol umbilical)+ throws IOException {this.in = in;+ this.progPerByte = 1.0f / (float)length;+ this.umbilical = umbilical;+ this.comparator = comparator;getNext();}@@ -101,7 +117,10 @@ public class ReduceTask extends Task {/// Auxiliary methods/** Start processing next unique key. */- public void nextKey() { hasNext = more; }+ public void nextKey() {+ while (hasNext) { next(); } // skip any unread+ hasNext = more;+ }/** True iff more keys remain. */public boolean more() { return more; }@@ -110,6 +129,9 @@ public class ReduceTask extends Task {public WritableComparable getKey() { return key; }private void getNext() throws IOException {+ reducePhase.set(in.getPosition()*progPerByte); // update progress+ reportProgress(umbilical);+Writable lastKey = key; // save previous keytry {key = (WritableComparable)in.getKeyClass().newInstance();@@ -122,7 +144,7 @@ public class ReduceTask extends Task {if (lastKey == null) {hasNext = true;} else {- hasNext = (key.compareTo(lastKey) == 0);+ hasNext = (comparator.compare(key, lastKey) == 0);}} else {hasNext = false;@@ -130,89 +152,136 @@ public class ReduceTask extends Task {}}- public void run(JobConf job, TaskUmbilicalProtocol umbilical)+ public void run(JobConf job, final TaskUmbilicalProtocol umbilical)throws IOException {Class keyClass = job.getOutputKeyClass();Class valueClass = job.getOutputValueClass();Reducer reducer = (Reducer)job.newInstance(job.getReducerClass());-- umbilical.progress(getTaskId(), new FloatWritable(1.0f/3.0f));+ NutchFileSystem lfs = NutchFileSystem.getNamed("local");++ copyPhase.complete(); // copy is already complete// open a file to collect map output- NutchFileSystem lfs = NutchFileSystem.getNamed("local");- File taskDir = new File(LOCAL_DIR, getTaskId());- String file = new File(taskDir, "all.in").toString();+ String file = job.getLocalFile(getTaskId(), "all.1").toString();SequenceFile.Writer writer =new SequenceFile.Writer(lfs, file, keyClass, valueClass);try {// append all input files into a single input file- WritableComparable key;- Writable value;- try {- key = (WritableComparable)keyClass.newInstance();- value = (Writable)valueClass.newInstance();- } catch (Exception e) {- throw new RuntimeException(e);+ for (int i = 0; i < mapTaskIds.length; i++) {+ appendPhase.addPhase(); // one per file}++ DataOutputBuffer buffer = new DataOutputBuffer();+for (int i = 0; i < mapTaskIds.length; i++) {- String partFile =- MapOutputFile.getInputFile(mapTaskIds[i], getTaskId()).toString();- SequenceFile.Reader in = new SequenceFile.Reader(lfs, partFile);+ File partFile =+ MapOutputFile.getInputFile(mapTaskIds[i], getTaskId());+ float progPerByte = 1.0f / lfs.getLength(partFile);+ Progress phase = appendPhase.phase();+ phase.setStatus(partFile.toString());+ SequenceFile.Reader in =+ new SequenceFile.Reader(lfs, partFile.toString());try {- while(in.next(key, value)) {- writer.append(key, value);+ int keyLen;+ while((keyLen = in.next(buffer)) > 0) {+ writer.append(buffer.getData(), 0, buffer.getLength(), keyLen);+ phase.set(in.getPosition()*progPerByte);+ reportProgress(umbilical);+ buffer.reset();}} finally {in.close();}+ phase.complete();}+} finally {writer.close();}- // sort the input file- String sortedFile = file+".sorted";- WritableComparator comparator = null;+ appendPhase.complete(); // append is complete++ // spawn a thread to give sort progress heartbeats+ Thread sortProgress = new Thread() {+ public void run() {+ while (!sortComplete) {+ try {+ reportProgress(umbilical);+ Thread.sleep(PROGRESS_INTERVAL);+ } catch (InterruptedException e) {+ continue;+ } catch (Throwable e) {+ return;+ }+ }+ }+ };+ sortProgress.setName("Sort progress reporter for task "+getTaskId());++ String sortedFile = job.getLocalFile(getTaskId(), "all.2").toString();++ WritableComparator comparator = job.getOutputKeyComparator();+try {- comparator =- (WritableComparator)job.getOutputKeyComparatorClass().newInstance();- } catch (Exception e) {- throw new RuntimeException(e);+ sortProgress.start();++ // sort the input file+ SequenceFile.Sorter sorter =+ new SequenceFile.Sorter(lfs, comparator, valueClass);+ sorter.sort(file, sortedFile); // sort+ lfs.delete(new File(file)); // remove unsorted++ } finally {+ sortComplete = true;}- SequenceFile.Sorter sorter =- new SequenceFile.Sorter(lfs, comparator, valueClass);- sorter.sort(file, sortedFile); // sort- lfs.delete(new File(file)); // remove unsorted- umbilical.progress(getTaskId(), new FloatWritable(2.0f/3.0f));+ sortPhase.complete(); // sort is complete// make output collector- String name = "part-" + getPartition();+ String name = getOutputName(getPartition());final RecordWriter out =job.getOutputFormat().getRecordWriter(NutchFileSystem.get(), job, name);OutputCollector collector = new OutputCollector() {public void collect(WritableComparable key, Writable value)throws IOException {out.write(key, value);+ reportProgress(umbilical);}};// apply reduce functionSequenceFile.Reader in = new SequenceFile.Reader(lfs, sortedFile);+ Reporter reporter = getReporter(umbilical, getProgress());+ long length = lfs.getLength(new File(sortedFile));try {- ValuesIterator values = new ValuesIterator(in);+ ValuesIterator values = new ValuesIterator(in, length, comparator,+ umbilical);while (values.more()) {- reducer.reduce(values.getKey(), values, collector);+ reducer.reduce(values.getKey(), values, collector, reporter);values.nextKey();}} finally {in.close();lfs.delete(new File(sortedFile)); // remove sorted- out.close();+ out.close(reporter);}- umbilical.progress(getTaskId(), new FloatWritable(3.0f/3.0f));+ done(umbilical);+ }++ /** Construct output file names so that, when an output directory listing is+ * sorted lexicographically, positions correspond to output partitions.*/++ private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();++ static {+ NUMBER_FORMAT.setMinimumIntegerDigits(5);+ NUMBER_FORMAT.setGroupingUsed(false);+ }++ private static synchronized String getOutputName(int partition) {+ return "part-" + NUMBER_FORMAT.format(partition);}}diff --git a/src/java/org/apache/nutch/mapReduce/ReduceTaskRunner.java b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.javasimilarity index 63%rename from src/java/org/apache/nutch/mapReduce/ReduceTaskRunner.javarename to src/java/org/apache/nutch/mapred/ReduceTaskRunner.javaindex 16cab2019..c10c69bbc 100644--- a/src/java/org/apache/nutch/mapReduce/ReduceTaskRunner.java+++ b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;import org.apache.nutch.ipc.*;@@ -27,7 +27,7 @@ import java.util.logging.*;/** Runs a reduce task. */class ReduceTaskRunner extends TaskRunner {private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapReduce.ReduceTaskRunner");+ LogFormatter.getLogger("org.apache.nutch.mapred.ReduceTaskRunner");public ReduceTaskRunner(Task task, TaskTracker tracker) {super(task, tracker);@@ -36,26 +36,37 @@ class ReduceTaskRunner extends TaskRunner {/** Assemble all of the map output files. */public void prepare() throws IOException {ReduceTask task = ((ReduceTask)getTask());+ MapOutputFile.removeAll(task.getTaskId()); // cleanup from failuresString[] mapTaskIds = task.getMapTaskIds();-- getTracker().progress(task.getTaskId(), new FloatWritable(0.0f/3.0f));+ final Progress copyPhase = getTask().getProgress().phase();// we need input from every map taskHashSet needed = new HashSet();for (int i = 0; i < mapTaskIds.length; i++) {needed.add(mapTaskIds[i]);+ copyPhase.addPhase(); // add sub-phase per file}InterTrackerProtocol jobClient = getTracker().getJobClient();while (needed.size() > 0) {+ getTask().reportProgress(getTracker());+// get list of available map output locations from job trackerString[] neededStrings =(String[])needed.toArray(new String[needed.size()]);MapOutputLocation[] locs =jobClient.locateMapOutputs(task.getTaskId(), neededStrings);- LOG.info("Got "+locs.length+" map output locations.");+ if (locs.length == 0) {+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {+ }+ continue;+ }++ LOG.info(task.getTaskId()+" Got "+locs.length+" map output locations.");// try each of these locationsfor (int i = 0; i < locs.length; i++) {@@ -65,29 +76,46 @@ class ReduceTaskRunner extends TaskRunner {MapOutputProtocol client =(MapOutputProtocol)RPC.getProxy(MapOutputProtocol.class, addr);-+ MapOutputFile.setProgressReporter(new MapOutputFile.ProgressReporter(){+ public void progress(float progress) {+ copyPhase.phase().set(progress);+ try {+ getTask().reportProgress(getTracker());+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ });++ getTask().reportProgress(getTracker());try {- LOG.info("Copying "+loc.getMapTaskId()+" from "+addr);+ copyPhase.phase().setStatus(loc.toString());+client.getFile(loc.getMapTaskId(), task.getTaskId(),new IntWritable(task.getPartition()));needed.remove(loc.getMapTaskId()); // success: remove from needed- LOG.info("Copy complete: "+loc.getMapTaskId()+" from "+addr);-+ copyPhase.startNextPhase();+} catch (IOException e) { // failed: try again later- LOG.info("Copy failed: "+loc.getMapTaskId()+" from "+addr);+ LOG.log(Level.WARNING,+ task.getTaskId()+" copy failed: "+ +loc.getMapTaskId()+" from "+addr,+ e);+ } finally {+ MapOutputFile.setProgressReporter(null);}}-+}- getTracker().progress(task.getTaskId(), new FloatWritable(1.0f/3.0f));+ getTask().reportProgress(getTracker());}/** Delete all of the temporary map output files. */public void close() throws IOException {- LOG.info("Task "+getTask()+" done; removing files.");+ getTask().getProgress().setStatus("closed");MapOutputFile.removeAll(getTask().getTaskId());}diff --git a/src/java/org/apache/nutch/mapReduce/Reducer.java b/src/java/org/apache/nutch/mapred/Reducer.javasimilarity index 87%rename from src/java/org/apache/nutch/mapReduce/Reducer.javarename to src/java/org/apache/nutch/mapred/Reducer.javaindex 4077778c5..6e6de8887 100644--- a/src/java/org/apache/nutch/mapReduce/Reducer.java+++ b/src/java/org/apache/nutch/mapred/Reducer.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;@@ -25,7 +25,7 @@ import org.apache.nutch.io.WritableComparable;/** Reduces a set of intermediate values which share a key to a smaller set of* values. Input values are the grouped output of a {@link Mapper}. */-public interface Reducer extends Configurable {+public interface Reducer extends JobConfigurable {/** Combines values for a given key. Output values must be of the same type* as input values. Input keys must not be altered. Typically all values* are combined into zero or one value. Output pairs are collected with@@ -35,6 +35,7 @@ public interface Reducer extends Configurable {* @param values the values to combine* @param output to collect combined values*/- void reduce(WritableComparable key, Iterator values, OutputCollector output)+ void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)throws IOException;}diff --git a/src/java/org/apache/nutch/mapred/Reporter.java b/src/java/org/apache/nutch/mapred/Reporter.javanew file mode 100644index 000000000..508b0b0db--- /dev/null+++ b/src/java/org/apache/nutch/mapred/Reporter.java@@ -0,0 +1,28 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;++/** Passed to application code to permit alteration of status. */+public interface Reporter {+ /** Alter the application's status description.+ *+ * @param status a brief description of the current status+ */+ void setStatus(String status) throws IOException;+}diff --git a/src/java/org/apache/nutch/mapReduce/RunningJob.java b/src/java/org/apache/nutch/mapred/RunningJob.javasimilarity index 93%rename from src/java/org/apache/nutch/mapReduce/RunningJob.javarename to src/java/org/apache/nutch/mapred/RunningJob.javaindex cb63220d5..d52f1bf4e 100644--- a/src/java/org/apache/nutch/mapReduce/RunningJob.java+++ b/src/java/org/apache/nutch/mapred/RunningJob.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;@@ -62,6 +62,11 @@ public interface RunningJob {*/public boolean isComplete() throws IOException;+ /**+ * True iff job completed successfully.+ */+ public boolean isSuccessful() throws IOException;+/*** Blocks until the job is complete.*/diff --git a/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java b/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.javanew file mode 100644index 000000000..bfa284bec--- /dev/null+++ b/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java@@ -0,0 +1,61 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;+import java.io.File;++import org.apache.nutch.fs.NutchFileSystem;++import org.apache.nutch.io.SequenceFile;+import org.apache.nutch.io.MapFile;+import org.apache.nutch.io.Writable;+import org.apache.nutch.io.WritableComparable;+import org.apache.nutch.io.LongWritable;+import org.apache.nutch.io.UTF8;++/** An {@link InputFormat} for {@link SequenceFile}s. */+public class SequenceFileInputFormat extends InputFormatBase {++ public SequenceFileInputFormat() {+ setMinSplitSize(SequenceFile.SYNC_INTERVAL);+ }++ protected File[] listFiles(NutchFileSystem fs, JobConf job)+ throws IOException {++ File[] files = super.listFiles(fs, job);+ for (int i = 0; i < files.length; i++) {+ File file = files[i];+ if (file.isDirectory()) { // it's a MapFile+ files[i] = new File(file, MapFile.DATA_FILE_NAME); // use the data file+ }+ }+ return files;+ }++ public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,+ JobConf job, Reporter reporter)+ throws IOException {++ reporter.setStatus(split.toString());++ return new SequenceFileRecordReader(fs, split);+ }++}+diff --git a/src/java/org/apache/nutch/mapReduce/SequenceFileOutputFormat.java b/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.javasimilarity index 63%rename from src/java/org/apache/nutch/mapReduce/SequenceFileOutputFormat.javarename to src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.javaindex ae8329817..dfde84ad7 100644--- a/src/java/org/apache/nutch/mapReduce/SequenceFileOutputFormat.java+++ b/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java@@ -14,20 +14,20 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;+import java.util.Arrays;import org.apache.nutch.fs.NutchFileSystem;+import org.apache.nutch.io.MapFile;import org.apache.nutch.io.SequenceFile;import org.apache.nutch.io.WritableComparable;import org.apache.nutch.io.Writable;public class SequenceFileOutputFormat implements OutputFormat {-- public String getName() { return "seq"; }public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,String name) throws IOException {@@ -37,7 +37,8 @@ public class SequenceFileOutputFormat implements OutputFormat {final SequenceFile.Writer out =new SequenceFile.Writer(fs, file.toString(),job.getOutputKeyClass(),- job.getOutputValueClass());+ job.getOutputValueClass(),+ job.getBoolean("mapred.output.compress", false));return new RecordWriter() {@@ -47,8 +48,23 @@ public class SequenceFileOutputFormat implements OutputFormat {out.append(key, value);}- public void close() throws IOException { out.close(); }+ public void close(Reporter reporter) throws IOException { out.close();}};- }+ }++ /** Open the output generated by this format. */+ public static SequenceFile.Reader[] getReaders(NutchFileSystem fs, File dir)+ throws IOException {+ File[] names = fs.listFiles(dir);++ // sort names, so that hash partitioning works+ Arrays.sort(names);++ SequenceFile.Reader[] parts = new SequenceFile.Reader[names.length];+ for (int i = 0; i < names.length; i++) {+ parts[i] = new SequenceFile.Reader(fs, names[i].toString());+ }+ return parts;+ }}diff --git a/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java b/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.javanew file mode 100644index 000000000..24982709f--- /dev/null+++ b/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java@@ -0,0 +1,76 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.IOException;+import java.io.File;++import org.apache.nutch.fs.NutchFileSystem;++import org.apache.nutch.io.SequenceFile;+import org.apache.nutch.io.Writable;+import org.apache.nutch.io.WritableComparable;+import org.apache.nutch.io.LongWritable;+import org.apache.nutch.io.UTF8;++/** An {@link RecordReader} for {@link SequenceFile}s. */+public class SequenceFileRecordReader implements RecordReader {+ private SequenceFile.Reader in;+ private long end;+ private boolean more = true;++ public SequenceFileRecordReader(NutchFileSystem fs, FileSplit split)+ throws IOException {+ this.in = new SequenceFile.Reader(fs, split.getFile().toString());+ this.end = split.getStart() + split.getLength();++ if (split.getStart() > in.getPosition())+ in.sync(split.getStart()); // sync to start++ more = in.getPosition() < end;+ }+++ /** The class of key that must be passed to {@link+ * #next(Writable,Writable)}.. */+ public Class getKeyClass() { return in.getKeyClass(); }++ /** The class of value that must be passed to {@link+ * #next(Writable,Writable)}.. */+ public Class getValueClass() { return in.getValueClass(); }++ public synchronized boolean next(Writable key, Writable value)+ throws IOException {+ if (!more) return false;+ long pos = in.getPosition();+ boolean eof = in.next(key, value);+ if (pos >= end && in.syncSeen()) {+ more = false;+ } else {+ more = eof;+ }+ return more;+ }++ public synchronized long getPos() throws IOException {+ return in.getPosition();+ }++ public synchronized void close() throws IOException { in.close(); }++}+diff --git a/src/java/org/apache/nutch/mapReduce/Task.java b/src/java/org/apache/nutch/mapred/Task.javasimilarity index 60%rename from src/java/org/apache/nutch/mapReduce/Task.javarename to src/java/org/apache/nutch/mapred/Task.javaindex 43b43dc71..5619b3374 100644--- a/src/java/org/apache/nutch/mapReduce/Task.java+++ b/src/java/org/apache/nutch/mapred/Task.java@@ -14,9 +14,10 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;+import org.apache.nutch.util.*;import java.io.*;import java.net.*;@@ -24,7 +25,6 @@ import java.util.*;/** Base class for tasks. */public abstract class Task implements Writable {-////////////////////////////////////////////// Fields////////////////////////////////////////////@@ -76,4 +76,48 @@ public abstract class Task implements Writable {/** Return an approprate thread runner for this task. */public abstract TaskRunner createRunner(TaskTracker tracker);+ /** The number of milliseconds between progress reports. */+ public static final int PROGRESS_INTERVAL = 1000;++ private transient Progress taskProgress = new Progress();+ private transient long nextProgressTime =+ System.currentTimeMillis() + PROGRESS_INTERVAL;++ public Progress getProgress() { return taskProgress; }++ public Reporter getReporter(final TaskUmbilicalProtocol umbilical,+ final Progress progress) throws IOException {+ return new Reporter() {+ public void setStatus(String status) throws IOException {+ progress.setStatus(status);+ reportProgress(umbilical);+ }+ };+ }++ public void reportProgress(TaskUmbilicalProtocol umbilical, float progress)+ throws IOException {+ taskProgress.set(progress);+ reportProgress(umbilical);+ }++ public void reportProgress(TaskUmbilicalProtocol umbilical)+ throws IOException {+ long now = System.currentTimeMillis();+ if (now > nextProgressTime) {+ synchronized (this) {+ nextProgressTime = now + PROGRESS_INTERVAL;+ float progress = taskProgress.get();+ String status = taskProgress.toString();+ umbilical.progress(getTaskId(), progress, status);+ }+ }+ }++ public void done(TaskUmbilicalProtocol umbilical)+ throws IOException {+ umbilical.progress(getTaskId(), // send a final status report+ taskProgress.get(), taskProgress.toString());+ umbilical.done(getTaskId());+ }}diff --git a/src/java/org/apache/nutch/mapred/TaskRunner.java b/src/java/org/apache/nutch/mapred/TaskRunner.javanew file mode 100644index 000000000..79f601545--- /dev/null+++ b/src/java/org/apache/nutch/mapred/TaskRunner.java@@ -0,0 +1,177 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import org.apache.nutch.io.*;+import org.apache.nutch.ipc.*;+import org.apache.nutch.util.*;+import org.apache.nutch.fs.*;++import java.io.*;+import java.net.*;+import java.util.*;+import java.util.logging.*;++/** Base class that runs a task in a separate process. Tasks are run in a+ * separate process in order to isolate the map/reduce system code from bugs in+ * user supplied map and reduce functions.+ */+abstract class TaskRunner extends Thread {+ public static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.mapred.TaskRunner");++ private Process process;+ private Task t;+ private TaskTracker tracker;++ public TaskRunner(Task t, TaskTracker tracker) {+ this.t = t;+ this.tracker = tracker;+ }++ public Task getTask() { return t; }+ public TaskTracker getTracker() { return tracker; }++ /** Called to assemble this task's input. This method is run in the parent+ * process before the child is spawned. It should not execute user code,+ * only system code. */+ public void prepare() throws IOException {}++ /** Called when this task's output is no longer needed.+ * This method is run in the parent process after the child exits. It should+ * not execute user code, only system code.+ */+ public void close() throws IOException {}++ public final void run() {+ try {++ prepare();++ String sep = System.getProperty("path.separator");+ File workDir = new File(new File(t.getJobFile()).getParent(), "work");+ workDir.mkdirs();++ StringBuffer classPath = new StringBuffer();+ // start with same classpath as parent process+ classPath.append(System.getProperty("java.class.path"));+ classPath.append(sep);++ JobConf job = new JobConf(t.getJobFile());+ String jar = job.getJar();+ if (jar != null) { // if jar exists, it into workDir+ runChild(new String[] { "unzip", jar}, workDir);+ File[] libs = new File(workDir, "lib").listFiles();+ for (int i = 0; i < libs.length; i++) {+ classPath.append(sep); // add libs from jar to classpath+ classPath.append(libs[i]);+ }+ classPath.append(sep);+ classPath.append(new File(workDir, "classes"));+ classPath.append(sep);+ classPath.append(workDir);+ }++ File jvm = // use same jvm as parent+ new File(new File(System.getProperty("java.home"), "bin"), "java");++ // run java+ runChild(new String[] {+ jvm.toString(),+ //"-Xrunhprof:cpu=samples,file="+t.getTaskId()+".prof",+ "-Xmx"+job.get("mapred.child.heap.size", "200m"),+ "-cp", classPath.toString(),+ TaskTracker.Child.class.getName(), // main is Child+ tracker.taskReportPort+"", // pass umbilical port+ t.getTaskId() // pass task identifier+ }, workDir);++ } catch (FSError e) {+ LOG.log(Level.SEVERE, "FSError", e);+ try {+ tracker.fsError(e.getMessage());+ } catch (IOException ie) {+ LOG.log(Level.SEVERE, t.getTaskId()+" reporting FSError", ie);+ }+ } catch (Throwable throwable) {+ LOG.log(Level.WARNING, t.getTaskId()+" Child Error", throwable);+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ throwable.printStackTrace(new PrintStream(baos));+ try {+ tracker.reportDiagnosticInfo(t.getTaskId(), baos.toString());+ } catch (IOException e) {+ LOG.log(Level.WARNING, t.getTaskId()+" Reporting Diagnostics", e);+ }+ } finally {+ tracker.reportTaskFinished(t.getTaskId());+ }+ }++ /**+ * Run the child process+ */+ private void runChild(String[] args, File dir) throws IOException {+ this.process = Runtime.getRuntime().exec(args, null, dir);+ try {+ StringBuffer errorBuf = new StringBuffer();+ new Thread() {+ public void run() {+ logStream(process.getErrorStream()); // copy log output+ }+ }.start();++ logStream(process.getInputStream()); // normally empty++ if (this.process.waitFor() != 0) {+ throw new IOException("Task process exit with nonzero status.");+ }++ } catch (InterruptedException e) {+ throw new IOException(e.toString());+ } finally {+ kill();+ }+ }++ /**+ * Kill the child process+ */+ public void kill() {+ if (process != null) {+ process.destroy();+ }+ }++ /**+ */+ private void logStream(InputStream output) {+ try {+ BufferedReader in = new BufferedReader(new InputStreamReader(output));+ String line;+ while ((line = in.readLine()) != null) {+ LOG.info(t.getTaskId()+" "+line);+ }+ } catch (IOException e) {+ LOG.log(Level.WARNING, t.getTaskId()+" Error reading child output", e);+ } finally {+ try {+ output.close();+ } catch (IOException e) {+ LOG.log(Level.WARNING, t.getTaskId()+" Error closing child output", e);+ }+ }+ }+}diff --git a/src/java/org/apache/nutch/mapReduce/TaskStatus.java b/src/java/org/apache/nutch/mapred/TaskStatus.javasimilarity index 75%rename from src/java/org/apache/nutch/mapReduce/TaskStatus.javarename to src/java/org/apache/nutch/mapred/TaskStatus.javaindex 09c1a99d0..ae6adc888 100644--- a/src/java/org/apache/nutch/mapReduce/TaskStatus.java+++ b/src/java/org/apache/nutch/mapred/TaskStatus.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;@@ -36,13 +36,17 @@ public class TaskStatus implements Writable {private String taskid;private float progress;private int runState;+ private String diagnosticInfo;+ private String stateString;public TaskStatus() {}- public TaskStatus(String taskid, float progress, int runState) {+ public TaskStatus(String taskid, float progress, int runState, String diagnosticInfo, String stateString) {this.taskid = taskid;this.progress = progress;this.runState = runState;+ this.diagnosticInfo = diagnosticInfo;+ this.stateString = stateString;}public String getTaskId() { return taskid; }@@ -50,6 +54,10 @@ public class TaskStatus implements Writable {public void setProgress(float progress) { this.progress = progress; }public int getRunState() { return runState; }public void setRunState(int runState) { this.runState = runState; }+ public String getDiagnosticInfo() { return diagnosticInfo; }+ public void setDiagnosticInfo(String info) { this.diagnosticInfo = info; }+ public String getStateString() { return stateString; }+ public void setStateString(String stateString) { this.stateString = stateString; }//////////////////////////////////////////////// Writable@@ -58,11 +66,15 @@ public class TaskStatus implements Writable {UTF8.writeString(out, taskid);out.writeFloat(progress);out.writeInt(runState);+ UTF8.writeString(out, diagnosticInfo);+ UTF8.writeString(out, stateString);}public void readFields(DataInput in) throws IOException {this.taskid = UTF8.readString(in);this.progress = in.readFloat();this.runState = in.readInt();+ this.diagnosticInfo = UTF8.readString(in);+ this.stateString = UTF8.readString(in);}}diff --git a/src/java/org/apache/nutch/mapReduce/TaskTracker.java b/src/java/org/apache/nutch/mapred/TaskTracker.javasimilarity index 55%rename from src/java/org/apache/nutch/mapReduce/TaskTracker.javarename to src/java/org/apache/nutch/mapred/TaskTracker.javaindex c1be2fc76..01e626bd7 100644--- a/src/java/org/apache/nutch/mapReduce/TaskTracker.java+++ b/src/java/org/apache/nutch/mapred/TaskTracker.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.fs.*;import org.apache.nutch.io.*;@@ -35,11 +35,18 @@ import java.util.logging.*;public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutputProtocol, Runnable {private static final int MAX_CURRENT_TASKS =NutchConf.get().getInt("mapred.tasktracker.tasks.maximum", 2);+static final long WAIT_FOR_DONE = 3 * 1000;++ static final long TASK_TIMEOUT =+ NutchConf.get().getInt("mapred.task.timeout", 10* 60 * 1000);+static final int STALE_STATE = 1;public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapReduce.TaskTracker");+ LogFormatter.getLogger("org.apache.nutch.mapred.TaskTracker");++ private boolean running = true;String taskTrackerName;String localHostname;@@ -58,21 +65,23 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpustatic Random r = new Random();NutchFileSystem fs = null;- File localDir = null;+ static final String SUBDIR = "taskTracker";++ private NutchConf fConf;/*** Start with the local machine name, and the default JobTracker*/- public TaskTracker() throws IOException {- this(JobTracker.getDefaultAddress());+ public TaskTracker(NutchConf conf) throws IOException {+ this(JobTracker.getAddress(conf), conf);}/*** Start with the local machine name, and the addr of the target JobTracker*/- public TaskTracker(InetSocketAddress jobTrackAddr) throws IOException {+ public TaskTracker(InetSocketAddress jobTrackAddr, NutchConf conf) throws IOException {+ this.fConf = conf;this.jobTrackAddr = jobTrackAddr;- this.localDir = new File(JobConf.getLocalDir(), "tracker");initialize();}@@ -85,24 +94,38 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutputhis.taskTrackerName = "tracker_" + (Math.abs(r.nextInt()) % 100000);this.localHostname = InetAddress.getLocalHost().getHostName();- if (localDir.exists()) {- FileUtil.fullyDelete(localDir);- }- localDir.mkdirs();+ JobConf.deleteLocalFiles(SUBDIR);// Clear out state tablesthis.tasks = new TreeMap();this.runningTasks = new TreeMap();- // generate port numbers- this.taskReportPort = 32768+r.nextInt(32768);- this.mapOutputPort = 32768+r.nextInt(32768);+ // port numbers+ this.taskReportPort = this.fConf.getInt("mapred.task.tracker.report.port", 50050);+ this.mapOutputPort = this.fConf.getInt("mapred.task.tracker.output.port", 50040);// RPC initialization- this.taskReportServer = RPC.getServer(this, taskReportPort);- this.taskReportServer.start();- this.mapOutputServer = RPC.getServer(this, mapOutputPort);- this.mapOutputServer.start();+ while (true) {+ try {+ this.taskReportServer = RPC.getServer(this, this.taskReportPort, MAX_CURRENT_TASKS, false);+ this.taskReportServer.start();+ break;+ } catch (BindException e) {+ LOG.info("Could not open report server at " + this.taskReportPort + ", trying new port");+ this.taskReportPort++;+ }++ }+ while (true) {+ try {+ this.mapOutputServer = RPC.getServer(this, this.mapOutputPort, MAX_CURRENT_TASKS, false);+ this.mapOutputServer.start();+ break;+ } catch (BindException e) {+ LOG.info("Could not open mapoutput server at " + this.mapOutputPort + ", trying new port");+ this.mapOutputPort++;+ }+ }// Clear out temporary files that might be lying aroundMapOutputFile.cleanupStorage();@@ -117,16 +140,11 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu* within the same process space might be restarted, so everything must be* clean.*/- public void close() throws IOException {+ public synchronized void close() throws IOException {// Kill running tasks- Vector v = new Vector();- for (Iterator it = tasks.values().iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- v.add(tip);- }- for (Iterator it = v.iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- tip.cleanup();+ while (tasks.size() > 0) {+ TaskInProgress tip = (TaskInProgress)tasks.get(tasks.firstKey());+ tip.jobHasFinished();}// Wait for them to die and report in@@ -163,7 +181,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpuint offerService() throws Exception {long lastHeartbeat = 0;- while (true) {+ while (running) {long now = System.currentTimeMillis();long waitTime = HEARTBEAT_INTERVAL - (now - lastHeartbeat);@@ -179,12 +197,13 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu// Emit standard hearbeat message to check in with JobTracker//Vector taskReports = new Vector();- synchronized (runningTasks) {+ synchronized (this) {for (Iterator it = runningTasks.keySet().iterator(); it.hasNext(); ) {String taskid = (String) it.next();TaskInProgress tip = (TaskInProgress) runningTasks.get(taskid);- taskReports.add(tip.getStatus());- if (tip.getStatus().getRunState() != TaskStatus.RUNNING) {+ TaskStatus status = tip.createStatus();+ taskReports.add(status);+ if (status.getRunState() != TaskStatus.RUNNING) {it.remove();}}@@ -196,11 +215,11 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpuif (justStarted) {this.fs = NutchFileSystem.getNamed(jobClient.getFilesystemName());}-- IntWritable resultCode = jobClient.emitHeartbeat(new TaskTrackerStatus(taskTrackerName, localHostname, mapOutputPort, taskReports), new BooleanWritable(justStarted));++ int resultCode = jobClient.emitHeartbeat(new TaskTrackerStatus(taskTrackerName, localHostname, mapOutputPort, taskReports), justStarted);justStarted = false;-- if (resultCode.get() == InterTrackerProtocol.UNKNOWN_TASKTRACKER) {++ if (resultCode == InterTrackerProtocol.UNKNOWN_TASKTRACKER) {return STALE_STATE;}@@ -211,22 +230,43 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpuTask t = jobClient.pollForNewTask(taskTrackerName);if (t != null) {TaskInProgress tip = new TaskInProgress(t);- tasks.put(t.getTaskId(), tip);- runningTasks.put(t.getTaskId(), tip);+ synchronized (this) {+ tasks.put(t.getTaskId(), tip);+ runningTasks.put(t.getTaskId(), tip);+ }tip.launchTask();}}+ //+ // Kill any tasks that have not reported progress in the last X seconds.+ //+ synchronized (this) {+ for (Iterator it = runningTasks.values().iterator(); it.hasNext(); ) {+ TaskInProgress tip = (TaskInProgress) it.next();+ if ((tip.getRunState() == TaskStatus.RUNNING) &&+ (System.currentTimeMillis() - tip.getLastProgressReport() > TASK_TIMEOUT)) {+ LOG.info("Task " + tip.getTask().getTaskId() + " timed out. Killing.");+ tip.reportDiagnosticInfo("Timed out.");+ tip.killAndCleanup();+ }+ }+ }+//// Check for any Tasks whose job may have ended//String toCloseId = jobClient.pollForClosedTask(taskTrackerName);if (toCloseId != null) {+ synchronized (this) {TaskInProgress tip = (TaskInProgress) tasks.get(toCloseId);- tip.cleanup();+ tip.jobHasFinished();+ }}lastHeartbeat = now;}++ return 0;}/**@@ -237,11 +277,11 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu*/public void run() {try {- while (true) {+ while (running) {boolean staleState = false;try {// This while-loop attempts reconnects if we get network errors- while (! staleState) {+ while (running && ! staleState) {try {if (offerService() == STALE_STATE) {staleState = true;@@ -274,21 +314,21 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu///////////////////////////////////////////////////////class TaskInProgress {Task task;- File localTaskDir;- TaskStatus status;+ float progress;+ int runstate;+ String stateString = "";+ long lastProgressReport;+ StringBuffer diagnosticInfo = new StringBuffer();TaskRunner runner;boolean done = false;- boolean closeRunnerUponEnd = false;+ boolean wasKilled = false;/***/public TaskInProgress(Task task) throws IOException {this.task = task;- this.localTaskDir = new File(localDir, task.getTaskId());- if (localTaskDir.exists()) {- FileUtil.fullyDelete(localTaskDir);- }- this.localTaskDir.mkdirs();+ this.lastProgressReport = System.currentTimeMillis();+ JobConf.deleteLocalFiles(SUBDIR+File.separator+task.getTaskId());localizeTask(task);}@@ -297,8 +337,10 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu* So here, edit the Task's fields appropriately.*/void localizeTask(Task t) throws IOException {- File localJobFile = new File(localTaskDir, "job.xml");- File localJarFile = new File(localTaskDir, "job.jar");+ File localJobFile =+ JobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.xml");+ File localJarFile =+ JobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.jar");String jobFile = t.getJobFile();fs.copyToLocalFile(new File(jobFile), localJobFile);@@ -306,15 +348,17 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpuJobConf jc = new JobConf(localJobFile);String jarFile = jc.getJar();- fs.copyToLocalFile(new File(jarFile), localJarFile);- jc.setJar(localJarFile.getCanonicalPath());+ if (jarFile != null) {+ fs.copyToLocalFile(new File(jarFile), localJarFile);+ jc.setJar(localJarFile.getCanonicalPath());- BufferedOutputStream out =- new BufferedOutputStream(new FileOutputStream(localJobFile));- try {+ BufferedOutputStream out =+ new BufferedOutputStream(new FileOutputStream(localJobFile));+ try {jc.write(out);- } finally {+ } finally {out.close();+ }}}@@ -324,7 +368,13 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpureturn task;}- public TaskStatus getStatus() {+ /**+ */+ public TaskStatus createStatus() {+ TaskStatus status = new TaskStatus(task.getTaskId(), progress, runstate, diagnosticInfo.toString(), (stateString == null) ? "" : stateString);+ if (diagnosticInfo.length() > 0) {+ diagnosticInfo = new StringBuffer();+ }return status;}@@ -332,7 +382,9 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu* Kick off the task execution*/public synchronized void launchTask() throws IOException {- this.status = new TaskStatus(task.getTaskId(), 0.0f, TaskStatus.RUNNING);+ this.progress = 0.0f;+ this.runstate = TaskStatus.RUNNING;+ this.diagnosticInfo = new StringBuffer();this.runner = task.createRunner(TaskTracker.this);this.runner.start();}@@ -340,9 +392,31 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu/*** The task is reporting its progress*/- public synchronized void reportProgress(float p) {- LOG.info("Progress for task " + task.getTaskId() + " is " + p);- this.status = new TaskStatus(task.getTaskId(), p, TaskStatus.RUNNING);+ public synchronized void reportProgress(float p, String state) {+ LOG.info(task.getTaskId()+" "+p+"% "+state);+ this.progress = p;+ this.runstate = TaskStatus.RUNNING;+ this.lastProgressReport = System.currentTimeMillis();+ this.stateString = state;+ }++ /**+ */+ public long getLastProgressReport() {+ return lastProgressReport;+ }++ /**+ */+ public int getRunState() {+ return runstate;+ }++ /**+ * The task has reported some diagnostic info about its status+ */+ public synchronized void reportDiagnosticInfo(String info) {+ this.diagnosticInfo.append(info);}/**@@ -350,6 +424,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu*/public synchronized void reportDone() {LOG.info("Task " + task.getTaskId() + " is done.");+ this.progress = 1.0f;this.done = true;}@@ -375,46 +450,59 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu// task was 'done' before terminating//if (done) {- status.setRunState(TaskStatus.SUCCEEDED);+ runstate = TaskStatus.SUCCEEDED;} else {- status.setRunState(TaskStatus.FAILED);+ runstate = TaskStatus.FAILED;}//- // We've already tried to 'cleanup' this task. So once- // the process actually finishes, finish the cleanup work.+ // If the task has failed, or if the task was killAndCleanup()'ed,+ // we should clean up right away. We only wait to cleanup+ // if the task succeeded, and its results might be useful+ // later on to downstream job processing.//- if (closeRunnerUponEnd) {- runningTasks.remove(task.getTaskId());- tasks.remove(task.getTaskId());+ if (wasKilled || runstate == TaskStatus.FAILED) {try {- runner.close();+ cleanup();} catch (IOException ie) {}- try {- FileUtil.fullyDelete(localTaskDir);- } catch (IOException ie) {- }}}/**- * The owning job is done, and this task is no longer needed.- * This method cleans up the task, first killing it if necessary.+ * We no longer need anything from this task, as the job has+ * finished. If the task is still running, kill it (and clean up*/- public synchronized void cleanup() throws IOException {- if (status.getRunState() == TaskStatus.RUNNING) {- closeRunnerUponEnd = true;- runner.kill();+ public synchronized void jobHasFinished() throws IOException {+ if (getRunState() == TaskStatus.RUNNING) {+ killAndCleanup();} else {- runningTasks.remove(task.getTaskId());- tasks.remove(task.getTaskId());- try {- runner.close();- } catch (IOException ie) {- }- FileUtil.fullyDelete(localTaskDir);+ cleanup();+ }+ }++ /**+ * This task has run on too long, and should be killed.+ */+ public synchronized void killAndCleanup() throws IOException {+ if (runstate == TaskStatus.RUNNING) {+ wasKilled = true;+ runner.kill();+ }+ }++ /**+ * We no longer need anything from this task. Either the+ * controlling job is all done and the files have been copied+ * away, or the task failed and we don't need the remains.+ */+ synchronized void cleanup() throws IOException {+ tasks.remove(task.getTaskId());+ try {+ runner.close();+ } catch (IOException ie) {}+ JobConf.deleteLocalFiles(SUBDIR+File.separator+task.getTaskId());}}@@ -432,7 +520,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu/*** Called upon startup by the child process, to fetch Task data.*/- public Task getTask(String taskid) throws IOException {+ public synchronized Task getTask(String taskid) throws IOException {TaskInProgress tip = (TaskInProgress) tasks.get(taskid);if (tip != null) {return (Task) tip.getTask();@@ -444,26 +532,49 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu/*** Called periodically to report Task progress, from 0.0 to 1.0.*/- public void progress(String taskid, FloatWritable progress) throws IOException {+ public synchronized void progress(String taskid, float progress, String state) throws IOException {TaskInProgress tip = (TaskInProgress) tasks.get(taskid);- tip.reportProgress(progress.get());+ tip.reportProgress(progress, state);+ }++ /**+ * Called when the task dies before completion, and we want to report back+ * diagnostic info+ */+ public synchronized void reportDiagnosticInfo(String taskid, String info) throws IOException {+ TaskInProgress tip = (TaskInProgress) tasks.get(taskid);+ tip.reportDiagnosticInfo(info);+ }++ /** Child checking to see if we're alive. Normally does nothing.*/+ public synchronized void ping(String taskid) throws IOException {+ if (tasks.get(taskid) == null) {+ throw new IOException("No such task id."); // force child exit+ }}/*** The task is done.*/- public void done(String taskid) throws IOException {+ public synchronized void done(String taskid) throws IOException {TaskInProgress tip = (TaskInProgress) tasks.get(taskid);tip.reportDone();}+ /** A child task had a local filesystem error. Exit, so that no future+ * jobs are accepted. */+ public synchronized void fsError(String message) throws IOException {+ LOG.severe("FSError, exiting: "+ message);+ running = false;+ }+/////////////////////////////////////////////////////// Called by TaskTracker thread after task process ends//////////////////////////////////////////////////////*** The task is no longer running. It may not have completed successfully*/- void reportTaskFinished(String taskid) {+ synchronized void reportTaskFinished(String taskid) {TaskInProgress tip = (TaskInProgress) tasks.get(taskid);tip.taskFinished();}@@ -472,7 +583,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu* The main() for child processes.*/public static class Child {- public static void main(String[] args) throws IOException {+ public static void main(String[] args) throws Throwable {LogFormatter.showTime(false);LOG.info("Child starting");@@ -484,8 +595,46 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpuTask task = umbilical.getTask(taskid);JobConf job = new JobConf(task.getJobFile());- task.run(job, umbilical); // run the task- umbilical.done(taskid);++ NutchConf.get().addConfResource(new File(task.getJobFile()));++ startPinging(umbilical, taskid); // start pinging parent++ try {+ task.run(job, umbilical); // run the task+ } catch (FSError e) {+ LOG.log(Level.SEVERE, "FSError from child", e);+ umbilical.fsError(e.getMessage());+ } catch (Throwable throwable) {+ LOG.log(Level.WARNING, "Error running child", throwable);+ // Report back any failures, for diagnostic purposes+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ throwable.printStackTrace(new PrintStream(baos));+ umbilical.reportDiagnosticInfo(taskid, baos.toString());+ }+ }++ /** Periodically ping parent and exit when this fails.*/+ private static void startPinging(final TaskUmbilicalProtocol umbilical,+ final String taskid) {+ Thread thread = new Thread(new Runnable() {+ public void run() {+ while (true) {+ try {+ umbilical.ping(taskid);+ } catch (Throwable t) {+ LOG.warning("Parent died. Exiting "+taskid);+ System.exit(1);+ }+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {+ }+ }+ }+ }, "Pinger for "+taskid);+ thread.setDaemon(true);+ thread.start();}}@@ -498,7 +647,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpuSystem.exit(-1);}- TaskTracker tt = new TaskTracker();+ TaskTracker tt = new TaskTracker(NutchConf.get());tt.run();}}diff --git a/src/java/org/apache/nutch/mapReduce/TaskTrackerStatus.java b/src/java/org/apache/nutch/mapred/TaskTrackerStatus.javasimilarity index 98%rename from src/java/org/apache/nutch/mapReduce/TaskTrackerStatus.javarename to src/java/org/apache/nutch/mapred/TaskTrackerStatus.javaindex 1b435443e..5fc6c4541 100644--- a/src/java/org/apache/nutch/mapReduce/TaskTrackerStatus.java+++ b/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import org.apache.nutch.io.*;diff --git a/src/java/org/apache/nutch/mapReduce/TaskUmbilicalProtocol.java b/src/java/org/apache/nutch/mapred/TaskUmbilicalProtocol.javasimilarity index 66%rename from src/java/org/apache/nutch/mapReduce/TaskUmbilicalProtocol.javarename to src/java/org/apache/nutch/mapred/TaskUmbilicalProtocol.javaindex 14b01e56b..f7e6cd520 100644--- a/src/java/org/apache/nutch/mapReduce/TaskUmbilicalProtocol.java+++ b/src/java/org/apache/nutch/mapred/TaskUmbilicalProtocol.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;@@ -30,12 +30,27 @@ public interface TaskUmbilicalProtocol {Task getTask(String taskid) throws IOException;/** Report child's progress to parent.+ * @param taskid the id of the task* @param progress value between zero and one+ * @param state description of task's current state*/- void progress(String taskid, FloatWritable progress) throws IOException;+ void progress(String taskid, float progress, String state)+ throws IOException;++ /** Report error messages back to parent. Calls should be sparing, since all+ * such messages are held in the job tracker.+ * @param trace, the stack trace text+ */+ void reportDiagnosticInfo(String taskid, String trace) throws IOException;++ /** Periodically called by child to check if parent is still alive. */+ void ping(String taskid) throws IOException;/** Report that the task is successfully completed. Failure is assumed if* the task process exits without calling this. */void done(String taskid) throws IOException;+ /** Report that the task encounted a local filesystem error.*/+ void fsError(String message) throws IOException;+}diff --git a/src/java/org/apache/nutch/mapReduce/TextInputFormat.java b/src/java/org/apache/nutch/mapred/TextInputFormat.javasimilarity index 81%rename from src/java/org/apache/nutch/mapReduce/TextInputFormat.javarename to src/java/org/apache/nutch/mapred/TextInputFormat.javaindex 6d397beb6..a86eb8eda 100644--- a/src/java/org/apache/nutch/mapReduce/TextInputFormat.java+++ b/src/java/org/apache/nutch/mapred/TextInputFormat.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;@@ -32,20 +32,20 @@ import org.apache.nutch.io.UTF8;* the position in the file, and values are the line of text.. */public class TextInputFormat extends InputFormatBase {- public String getName() { return "text"; }-public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,- JobConf job) throws IOException {+ JobConf job, Reporter reporter)+ throws IOException {++ reporter.setStatus(split.toString());final long start = split.getStart();final long end = start + split.getLength();// open the file and seek to the start of the split- final NFSDataInputStream in =- new NFSDataInputStream(fs.open(split.getFile()));- in.seek(start);+ final NFSDataInputStream in = fs.open(split.getFile());if (start != 0) {+ in.seek(start-1);while (in.getPos() < end) { // scan to the next newline in the filechar c = (char)in.read();if (c == '\r' || c == '\n') {@@ -56,7 +56,8 @@ public class TextInputFormat extends InputFormatBase {return new RecordReader() {/** Read a line. */- public boolean next(Writable key, Writable value) throws IOException {+ public synchronized boolean next(Writable key, Writable value)+ throws IOException {long pos = in.getPos();if (pos >= end)return false;@@ -66,9 +67,11 @@ public class TextInputFormat extends InputFormatBase {return true;}- public long getPos() throws IOException { return in.getPos(); }+ public synchronized long getPos() throws IOException {+ return in.getPos();+ }- public void close() throws IOException { in.close(); }+ public synchronized void close() throws IOException { in.close(); }};}diff --git a/src/java/org/apache/nutch/mapReduce/TextOutputFormat.java b/src/java/org/apache/nutch/mapred/TextOutputFormat.javasimilarity index 74%rename from src/java/org/apache/nutch/mapReduce/TextOutputFormat.javarename to src/java/org/apache/nutch/mapred/TextOutputFormat.javaindex 80d19aded..547e66225 100644--- a/src/java/org/apache/nutch/mapReduce/TextOutputFormat.java+++ b/src/java/org/apache/nutch/mapred/TextOutputFormat.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.mapReduce;+package org.apache.nutch.mapred;import java.io.IOException;import java.io.File;@@ -26,26 +26,23 @@ import org.apache.nutch.io.WritableComparable;import org.apache.nutch.io.Writable;public class TextOutputFormat implements OutputFormat {-- public String getName() { return "text"; }public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,String name) throws IOException {File file = new File(job.getOutputDir(), name);- final NFSDataOutputStream out =- new NFSDataOutputStream(fs.create(file, true));+ final NFSDataOutputStream out = fs.create(file);return new RecordWriter() {- public void write(WritableComparable key, Writable value)+ public synchronized void write(WritableComparable key, Writable value)throws IOException {- out.writeBytes(key.toString()); // BUG: assume 8-bit chars+ out.write(key.toString().getBytes("UTF-8"));out.writeByte('\t');- out.writeBytes(value.toString()); // BUG: assume 8-bit chars+ out.write(value.toString().getBytes("UTF-8"));out.writeByte('\n');}- public void close() throws IOException {+ public synchronized void close(Reporter reporter) throws IOException {out.close();}};diff --git a/src/java/org/apache/nutch/mapReduce/demo/Grep.java b/src/java/org/apache/nutch/mapred/demo/Grep.javasimilarity index 72%rename from src/java/org/apache/nutch/mapReduce/demo/Grep.javarename to src/java/org/apache/nutch/mapred/demo/Grep.javaindex f4be84bd9..927088515 100644--- a/src/java/org/apache/nutch/mapReduce/demo/Grep.java+++ b/src/java/org/apache/nutch/mapred/demo/Grep.java@@ -13,23 +13,25 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.mapReduce.demo;+package org.apache.nutch.mapred.demo;-import org.apache.nutch.mapReduce.JobConf;-import org.apache.nutch.mapReduce.JobClient;-import org.apache.nutch.mapReduce.RunningJob;-import org.apache.nutch.mapReduce.InputFormats;-import org.apache.nutch.mapReduce.OutputFormats;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.JobClient;+import org.apache.nutch.mapred.RunningJob;+import org.apache.nutch.mapred.SequenceFileOutputFormat;+import org.apache.nutch.mapred.SequenceFileInputFormat;-import org.apache.nutch.mapReduce.lib.RegexMapper;-import org.apache.nutch.mapReduce.lib.InverseMapper;-import org.apache.nutch.mapReduce.lib.LongSumReducer;-import org.apache.nutch.mapReduce.lib.IdentityReducer;+import org.apache.nutch.mapred.lib.RegexMapper;+import org.apache.nutch.mapred.lib.InverseMapper;+import org.apache.nutch.mapred.lib.LongSumReducer;+import org.apache.nutch.mapred.lib.IdentityReducer;import org.apache.nutch.io.UTF8;import org.apache.nutch.io.LongWritable;import org.apache.nutch.io.WritableComparator;+import org.apache.nutch.util.NutchConf;+import java.io.File;import java.util.Random;@@ -43,13 +45,14 @@ public class Grep {System.exit(-1);}+ NutchConf defaults = NutchConf.get();+File tempDir =new File("grep-temp-"+Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));- JobConf grepJob = new JobConf();+ JobConf grepJob = new JobConf(defaults);- grepJob.setNumMapTasks(18);grepJob.setInputDir(new File(args[0]));grepJob.setMapperClass(RegexMapper.class);@@ -60,20 +63,17 @@ public class Grep {grepJob.setCombinerClass(LongSumReducer.class);grepJob.setReducerClass(LongSumReducer.class);- grepJob.setNumReduceTasks(6);grepJob.setOutputDir(tempDir);- grepJob.setOutputFormat(OutputFormats.get("seq"));+ grepJob.setOutputFormat(SequenceFileOutputFormat.class);grepJob.setOutputKeyClass(UTF8.class);grepJob.setOutputValueClass(LongWritable.class);JobClient.runJob(grepJob);- JobConf sortJob = new JobConf();-- sortJob.setNumMapTasks(6);+ JobConf sortJob = new JobConf(defaults);sortJob.setInputDir(tempDir);- sortJob.setInputFormat(InputFormats.get("seq"));+ sortJob.setInputFormat(SequenceFileInputFormat.class);sortJob.setInputKeyClass(UTF8.class);sortJob.setInputValueClass(LongWritable.class);@@ -86,7 +86,7 @@ public class Grep {JobClient.runJob(sortJob);- new JobClient().getFs().delete(tempDir);+ new JobClient(defaults).getFs().delete(tempDir);}}diff --git a/src/java/org/apache/nutch/mapReduce/lib/HashPartitioner.java b/src/java/org/apache/nutch/mapred/lib/HashPartitioner.javasimilarity index 77%rename from src/java/org/apache/nutch/mapReduce/lib/HashPartitioner.javarename to src/java/org/apache/nutch/mapred/lib/HashPartitioner.javaindex 9c576e24a..477b69927 100644--- a/src/java/org/apache/nutch/mapReduce/lib/HashPartitioner.java+++ b/src/java/org/apache/nutch/mapred/lib/HashPartitioner.java@@ -14,12 +14,13 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;-import org.apache.nutch.mapReduce.Partitioner;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Partitioner;+import org.apache.nutch.mapred.JobConf;import org.apache.nutch.io.WritableComparable;+import org.apache.nutch.io.Writable;/** Partition keys by their {@link Object#hashCode()}. */public class HashPartitioner implements Partitioner {@@ -27,7 +28,8 @@ public class HashPartitioner implements Partitioner {public void configure(JobConf job) {}/** Use {@link Object#hashCode()} to partition. */- public int getPartition(WritableComparable key, int numReduceTasks) {+ public int getPartition(WritableComparable key, Writable value,+ int numReduceTasks) {return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks;}diff --git a/src/java/org/apache/nutch/mapReduce/lib/IdentityMapper.java b/src/java/org/apache/nutch/mapred/lib/IdentityMapper.javasimilarity index 78%rename from src/java/org/apache/nutch/mapReduce/lib/IdentityMapper.javarename to src/java/org/apache/nutch/mapred/lib/IdentityMapper.javaindex 0c0e80359..54f05bea2 100644--- a/src/java/org/apache/nutch/mapReduce/lib/IdentityMapper.java+++ b/src/java/org/apache/nutch/mapred/lib/IdentityMapper.java@@ -14,13 +14,14 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;import java.io.IOException;-import org.apache.nutch.mapReduce.Mapper;-import org.apache.nutch.mapReduce.OutputCollector;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Mapper;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;import org.apache.nutch.io.Writable;import org.apache.nutch.io.WritableComparable;@@ -33,7 +34,8 @@ public class IdentityMapper implements Mapper {/** The identify function. Input key/value pair is written directly to* output.*/public void map(WritableComparable key, Writable val,- OutputCollector output) throws IOException {+ OutputCollector output, Reporter reporter)+ throws IOException {output.collect(key, val);}diff --git a/src/java/org/apache/nutch/mapReduce/lib/IdentityReducer.java b/src/java/org/apache/nutch/mapred/lib/IdentityReducer.javasimilarity index 75%rename from src/java/org/apache/nutch/mapReduce/lib/IdentityReducer.javarename to src/java/org/apache/nutch/mapred/lib/IdentityReducer.javaindex a416a97a7..d3e6b4fe1 100644--- a/src/java/org/apache/nutch/mapReduce/lib/IdentityReducer.java+++ b/src/java/org/apache/nutch/mapred/lib/IdentityReducer.java@@ -14,15 +14,16 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;import java.io.IOException;import java.util.Iterator;-import org.apache.nutch.mapReduce.Reducer;-import org.apache.nutch.mapReduce.OutputCollector;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Reducer;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;import org.apache.nutch.io.Writable;import org.apache.nutch.io.WritableComparable;@@ -33,8 +34,9 @@ public class IdentityReducer implements Reducer {public void configure(JobConf job) {}/** Writes all keys and values directly to output. */- public void reduce (WritableComparable key, Iterator values,- OutputCollector output) throws IOException {+ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {while (values.hasNext()) {output.collect(key, (Writable)values.next());}diff --git a/src/java/org/apache/nutch/mapReduce/lib/InverseMapper.java b/src/java/org/apache/nutch/mapred/lib/InverseMapper.javasimilarity index 78%rename from src/java/org/apache/nutch/mapReduce/lib/InverseMapper.javarename to src/java/org/apache/nutch/mapred/lib/InverseMapper.javaindex 5b5b83ac7..08fe1163d 100644--- a/src/java/org/apache/nutch/mapReduce/lib/InverseMapper.java+++ b/src/java/org/apache/nutch/mapred/lib/InverseMapper.java@@ -14,17 +14,19 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;import java.io.IOException;-import org.apache.nutch.mapReduce.Mapper;-import org.apache.nutch.mapReduce.OutputCollector;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Mapper;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;import org.apache.nutch.io.WritableComparable;import org.apache.nutch.io.Writable;+/** A {@link Mapper} that swaps keys and values. */public class InverseMapper implements Mapper {@@ -32,7 +34,8 @@ public class InverseMapper implements Mapper {/** The inverse function. Input keys and values are swapped.*/public void map(WritableComparable key, Writable value,- OutputCollector output) throws IOException {+ OutputCollector output, Reporter reporter)+ throws IOException {output.collect((WritableComparable)value, key);}}diff --git a/src/java/org/apache/nutch/mapReduce/lib/LongSumReducer.java b/src/java/org/apache/nutch/mapred/lib/LongSumReducer.javasimilarity index 80%rename from src/java/org/apache/nutch/mapReduce/lib/LongSumReducer.javarename to src/java/org/apache/nutch/mapred/lib/LongSumReducer.javaindex 8277580a0..a2b866c4f 100644--- a/src/java/org/apache/nutch/mapReduce/lib/LongSumReducer.java+++ b/src/java/org/apache/nutch/mapred/lib/LongSumReducer.java@@ -14,27 +14,29 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;import java.io.IOException;import java.util.Iterator;-import org.apache.nutch.mapReduce.Reducer;-import org.apache.nutch.mapReduce.OutputCollector;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Reducer;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;+import org.apache.nutch.io.Writable;import org.apache.nutch.io.WritableComparable;import org.apache.nutch.io.LongWritable;-/** A {@link Reducer} that sums long values. */public class LongSumReducer implements Reducer {public void configure(JobConf job) {}public void reduce(WritableComparable key, Iterator values,- OutputCollector output) throws IOException {+ OutputCollector output, Reporter reporter)+ throws IOException {// sum all values for this keylong sum = 0;diff --git a/src/java/org/apache/nutch/mapReduce/lib/RegexMapper.java b/src/java/org/apache/nutch/mapred/lib/RegexMapper.javasimilarity index 83%rename from src/java/org/apache/nutch/mapReduce/lib/RegexMapper.javarename to src/java/org/apache/nutch/mapred/lib/RegexMapper.javaindex db0cf1fc0..525f06460 100644--- a/src/java/org/apache/nutch/mapReduce/lib/RegexMapper.java+++ b/src/java/org/apache/nutch/mapred/lib/RegexMapper.java@@ -14,19 +14,21 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;import java.io.IOException;-import org.apache.nutch.mapReduce.Mapper;-import org.apache.nutch.mapReduce.OutputCollector;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Mapper;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;import org.apache.nutch.io.WritableComparable;import org.apache.nutch.io.Writable;import org.apache.nutch.io.LongWritable;import org.apache.nutch.io.UTF8;+import java.util.regex.Pattern;import java.util.regex.Matcher;@@ -43,7 +45,8 @@ public class RegexMapper implements Mapper {}public void map(WritableComparable key, Writable value,- OutputCollector output) throws IOException {+ OutputCollector output, Reporter reporter)+ throws IOException {String text = ((UTF8)value).toString();Matcher matcher = pattern.matcher(text);while (matcher.find()) {diff --git a/src/java/org/apache/nutch/mapReduce/lib/TokenCountMapper.java b/src/java/org/apache/nutch/mapred/lib/TokenCountMapper.javasimilarity index 83%rename from src/java/org/apache/nutch/mapReduce/lib/TokenCountMapper.javarename to src/java/org/apache/nutch/mapred/lib/TokenCountMapper.javaindex 815e64123..677dd4445 100644--- a/src/java/org/apache/nutch/mapReduce/lib/TokenCountMapper.java+++ b/src/java/org/apache/nutch/mapred/lib/TokenCountMapper.java@@ -14,20 +14,22 @@* limitations under the License.*/-package org.apache.nutch.mapReduce.lib;+package org.apache.nutch.mapred.lib;import java.io.IOException;import java.util.StringTokenizer;-import org.apache.nutch.mapReduce.Mapper;-import org.apache.nutch.mapReduce.OutputCollector;-import org.apache.nutch.mapReduce.JobConf;+import org.apache.nutch.mapred.Mapper;+import org.apache.nutch.mapred.OutputCollector;+import org.apache.nutch.mapred.JobConf;+import org.apache.nutch.mapred.Reporter;import org.apache.nutch.io.WritableComparable;import org.apache.nutch.io.Writable;import org.apache.nutch.io.LongWritable;import org.apache.nutch.io.UTF8;+/** A {@link Mapper} that maps text values into <token,freq> pairs. Uses* {@link StringTokenizer} to break text into tokens. */public class TokenCountMapper implements Mapper {@@ -35,7 +37,8 @@ public class TokenCountMapper implements Mapper {public void configure(JobConf job) {}public void map(WritableComparable key, Writable value,- OutputCollector output) throws IOException {+ OutputCollector output, Reporter reporter)+ throws IOException {// get input textlong position = ((LongWritable)key).get(); // key is position in fileString text = ((UTF8)value).toString(); // value is line of textdiff --git a/src/java/org/apache/nutch/mapReduce/lib/package.html b/src/java/org/apache/nutch/mapred/lib/package.htmlsimilarity index 100%rename from src/java/org/apache/nutch/mapReduce/lib/package.htmlrename to src/java/org/apache/nutch/mapred/lib/package.htmldiff --git a/src/java/org/apache/nutch/mapReduce/package.html b/src/java/org/apache/nutch/mapred/package.htmlsimilarity index 87%rename from src/java/org/apache/nutch/mapReduce/package.htmlrename to src/java/org/apache/nutch/mapred/package.htmlindex a5e9f412b..6eca80bbe 100644--- a/src/java/org/apache/nutch/mapReduce/package.html+++ b/src/java/org/apache/nutch/mapred/package.html@@ -6,7 +6,7 @@ large data collections.</p><p>Applications implement {@link org.apache.nutch.mapReduce.Mapper} and{@link org.apache.nutch.mapReduce.Reducer} interfaces. These are submitted-as a MapReduceJob and are applied to data+as a {@link org.apache.nutch.mapred.JobConf} and are applied to datastored in a {@link org.apache.nutch.fs.NutchFileSystem}.</p><p>See <a href="http://labs.google.com/papers/mapreduce.html">Google'sdiff --git a/src/java/org/apache/nutch/ndfs/Block.java b/src/java/org/apache/nutch/ndfs/Block.javaindex 907ba2857..cb7b45eb9 100644--- a/src/java/org/apache/nutch/ndfs/Block.java+++ b/src/java/org/apache/nutch/ndfs/Block.java@@ -119,4 +119,8 @@ public class Block implements Writable, Comparable {return 1;}}+ public boolean equals(Object o) {+ Block b = (Block) o;+ return (this.compareTo(b) == 0);+ }}diff --git a/src/java/org/apache/nutch/ndfs/BlockCommand.java b/src/java/org/apache/nutch/ndfs/BlockCommand.javanew file mode 100644index 000000000..71a74c718--- /dev/null+++ b/src/java/org/apache/nutch/ndfs/BlockCommand.java@@ -0,0 +1,108 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import org.apache.nutch.io.*;++import java.io.*;++/****************************************************+ * A BlockCommand is an instruction to a datanode regarding+ * some blocks under its control+ *+ * @author Michael Cafarella+ ****************************************************/+public class BlockCommand implements Writable {+ boolean transferBlocks = false;+ boolean invalidateBlocks = false;+ Block blocks[];+ DatanodeInfo targets[][];++ public BlockCommand() {+ this.transferBlocks = false;+ this.invalidateBlocks = false;+ this.blocks = new Block[0];+ this.targets = new DatanodeInfo[0][];+ }++ public BlockCommand(Block blocks[], DatanodeInfo targets[][]) {+ this.transferBlocks = true;+ this.invalidateBlocks = false;+ this.blocks = blocks;+ this.targets = targets;+ }++ public BlockCommand(Block blocks[]) {+ this.transferBlocks = false;+ this.invalidateBlocks = true;+ this.blocks = blocks;+ this.targets = new DatanodeInfo[0][];+ }++ public boolean transferBlocks() {+ return transferBlocks;+ }++ public boolean invalidateBlocks() {+ return invalidateBlocks;+ }++ public Block[] getBlocks() {+ return blocks;+ }++ public DatanodeInfo[][] getTargets() {+ return targets;+ }++ ///////////////////////////////////////////+ // Writable+ ///////////////////////////////////////////+ public void write(DataOutput out) throws IOException {+ out.writeBoolean(transferBlocks);+ out.writeBoolean(invalidateBlocks);+ out.writeInt(blocks.length);+ for (int i = 0; i < blocks.length; i++) {+ blocks[i].write(out);+ }+ out.writeInt(targets.length);+ for (int i = 0; i < targets.length; i++) {+ out.writeInt(targets[i].length);+ for (int j = 0; j < targets[i].length; j++) {+ targets[i][j].write(out);+ }+ }+ }++ public void readFields(DataInput in) throws IOException {+ this.transferBlocks = in.readBoolean();+ this.invalidateBlocks = in.readBoolean();+ this.blocks = new Block[in.readInt()];+ for (int i = 0; i < blocks.length; i++) {+ blocks[i] = new Block();+ blocks[i].readFields(in);+ }++ this.targets = new DatanodeInfo[in.readInt()][];+ for (int i = 0; i < targets.length; i++) {+ this.targets[i] = new DatanodeInfo[in.readInt()];+ for (int j = 0; j < targets[i].length; j++) {+ targets[i][j] = new DatanodeInfo();+ targets[i][j].readFields(in);+ }+ }+ }+}diff --git a/src/java/org/apache/nutch/ndfs/ClientProtocol.java b/src/java/org/apache/nutch/ndfs/ClientProtocol.javanew file mode 100644index 000000000..57981f00b--- /dev/null+++ b/src/java/org/apache/nutch/ndfs/ClientProtocol.java@@ -0,0 +1,140 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import java.io.*;+import org.apache.nutch.io.*;++/**********************************************************************+ * Protocol that an NDFS client uses to communicate with the NameNode.+ * It's used to manipulate the namespace, and obtain datanode info.+ *+ * @author Mike Cafarella+ **********************************************************************/+public interface ClientProtocol {++ /**+ * Open an existing file. Get back block and datanode info+ */+ public LocatedBlock[] open(String src) throws IOException;++ /**+ * Create a new file. Get back block and datanode info+ */+ public LocatedBlock create(String src, String clientName, boolean overwrite) throws IOException;++ /**+ * The client wants to write an additional block to the indicated+ * filename (which must currently be open for writing). Return+ * block and datanode info. A null response means the caller+ * should attempt the call again.+ */+ public LocatedBlock addBlock(String src) throws IOException;++ /**+ * The client wants to report a block it has just successfully+ * written to one or more datanodes. Client-written blocks are+ * always reported by the client, not by the datanode.+ */+ public void reportWrittenBlock(LocatedBlock b) throws IOException;++ /**+ * The client wants to abandon writing to the indicated block,+ * part of the indicated (currently-open) filename.+ */+ public void abandonBlock(Block b, String src) throws IOException;++ /**+ * The client wants to abandon writing to the current file, and+ * let anyone else grab it.+ */+ public void abandonFileInProgress(String src) throws IOException;++ /**+ * The client is done writing data to the given filename, and would+ * like to complete it. Returns whether the file has been closed+ * correctly (true) or whether caller should try again (false).+ * (Because the namenode is waiting for a block to complete).+ */+ public boolean complete(String src, String clientName) throws IOException;++ /**+ * The client wants to read the indicated filename at a certain offset.+ * Return a list of hostnames where the data can be found. (Return+ * a set of hostnames for every block.)+ */+ public String[][] getHints(String src, long start, long len) throws IOException;++ /**+ * Rename an item in the fs namespace+ */+ public boolean rename(String src, String dst) throws IOException;++ /**+ * Remove the given filename from the filesystem+ */+ public boolean delete(String src) throws IOException;++ /**+ * Check whether the given file exists+ */+ public boolean exists(String src) throws IOException;++ /**+ * Check whether the given filename is a directory or not.+ */+ public boolean isDir(String src) throws IOException;++ /**+ * Create a directory (or hierarchy of directories) with the given+ * name.+ */+ public boolean mkdirs(String src) throws IOException;++ /**+ * The client is trying to obtain a lock. Return whether the lock has+ * been seized correctly (true), or whether the client should try again+ * (false).+ */+ public boolean obtainLock(String src, String clientName, boolean exclusive) throws IOException;++ /**+ * The client wants to release a held lock. Return whether the lock was+ * correctly released (true), or whether the client should wait and try the+ * call again (false).+ */+ public boolean releaseLock(String src, String clientName) throws IOException;++ /**+ * The client machine wants to obtain a lease+ */+ public void renewLease(String clientName) throws IOException;++ /**+ * Get a listing of the indicated directory+ */+ public NDFSFileInfo[] getListing(String src) throws IOException;++ /**+ * Get a set of statistics about the filesystem.+ */+ public long[] getStats() throws IOException;++ /**+ * Get a full report on the system's current datanodes.+ */+ public DatanodeInfo[] getDatanodeReport() throws IOException;+}diff --git a/src/java/org/apache/nutch/ndfs/DF.java b/src/java/org/apache/nutch/ndfs/DF.javaindex 98c0ff73c..407ec755a 100644--- a/src/java/org/apache/nutch/ndfs/DF.java+++ b/src/java/org/apache/nutch/ndfs/DF.java@@ -25,7 +25,7 @@ import java.util.Iterator;/** Filesystem disk space usage statistics. Uses the unix 'df' program.* Tested on Linux, FreeBSD and Cygwin. */-class DF {+public class DF {private String filesystem;private long capacity;private long used;@@ -48,6 +48,9 @@ class DF {new StringTokenizer(lines.readLine(), " \t\n\r\f%");this.filesystem = tokens.nextToken();+ if (!tokens.hasMoreTokens()) { // for long filesystem name+ tokens = new StringTokenizer(lines.readLine(), " \t\n\r\f%");+ }this.capacity = Long.parseLong(tokens.nextToken()) * 1024;this.used = Long.parseLong(tokens.nextToken()) * 1024;this.available = Long.parseLong(tokens.nextToken()) * 1024;@@ -61,6 +64,8 @@ class DF {}} catch (InterruptedException e) {throw new IOException(e.toString());+ } finally {+ process.destroy();}}diff --git a/src/java/org/apache/nutch/ndfs/DataNode.java b/src/java/org/apache/nutch/ndfs/DataNode.javanew file mode 100644index 000000000..a4cdffddd--- /dev/null+++ b/src/java/org/apache/nutch/ndfs/DataNode.java@@ -0,0 +1,753 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import org.apache.nutch.io.*;+import org.apache.nutch.ipc.*;+import org.apache.nutch.util.*;++import java.io.*;+import java.net.*;+import java.util.*;+import java.util.logging.*;++/**********************************************************+ * DataNode controls just one critical table:+ * block-> BLOCK_SIZE stream of bytes+ *+ * This info is stored on disk (the NameNode is responsible for+ * asking other machines to replicate the data). The DataNode+ * reports the table's contents to the NameNode upon startup+ * and every so often afterwards.+ *+ * @author Mike Cafarella+ **********************************************************/+public class DataNode implements FSConstants, Runnable {+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.ndfs.DataNode");+ //+ // REMIND - mjc - I might bring "maxgigs" back so user can place+ // artificial limit on space+ //private static final long GIGABYTE = 1024 * 1024 * 1024;+ //private static long numGigs = NutchConf.get().getLong("ndfs.datanode.maxgigs", 100);+ //++ /**+ * Util method to build socket addr from string+ */+ public static InetSocketAddress createSocketAddr(String s) throws IOException {+ String target = s;+ int colonIndex = target.indexOf(':');+ if (colonIndex < 0) {+ throw new RuntimeException("Not a host:port pair: " + s);+ }+ String host = target.substring(0, colonIndex);+ int port = Integer.parseInt(target.substring(colonIndex + 1));++ return new InetSocketAddress(host, port);+ }+++ private static Vector subThreadList = null;+ DatanodeProtocol namenode;+ FSDataset data;+ String localName;+ boolean shouldRun = true;+ Vector receivedBlockList = new Vector();+ int xmitsInProgress = 0;+ Daemon dataXceiveServer = null;+ long blockReportInterval;+ private long datanodeStartupPeriod;+ private NutchConf fConf;++ /**+ * Create given a configuration and a dataDir.+ */+ public DataNode(NutchConf conf, String datadir) throws IOException {+ this(InetAddress.getLocalHost().getHostName(),+ new File(datadir),+ createSocketAddr(conf.get("fs.default.name", "local")), conf);+ }++ /**+ * Needs a directory to find its data (and config info)+ */+ public DataNode(String machineName, File datadir, InetSocketAddress nameNodeAddr, NutchConf conf) throws IOException {+ this.namenode = (DatanodeProtocol) RPC.getProxy(DatanodeProtocol.class, nameNodeAddr);+ this.data = new FSDataset(datadir);++ ServerSocket ss = null;+ int tmpPort = conf.getInt("ndfs.datanode.port", 50010);+ while (ss == null) {+ try {+ ss = new ServerSocket(tmpPort);+ LOG.info("Opened server at " + tmpPort);+ } catch (IOException ie) {+ LOG.info("Could not open server at " + tmpPort + ", trying new port");+ tmpPort++;+ }+ }+ this.localName = machineName + ":" + tmpPort;+ this.dataXceiveServer = new Daemon(new DataXceiveServer(ss));+ this.dataXceiveServer.start();++ long blockReportIntervalBasis =+ conf.getLong("ndfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);+ this.blockReportInterval =+ blockReportIntervalBasis - new Random().nextInt((int)(blockReportIntervalBasis/10));+ this.datanodeStartupPeriod =+ conf.getLong("ndfs.datanode.startupMsec", DATANODE_STARTUP_PERIOD);+ }++ /**+ */+ public String getNamenode() {+ //return namenode.toString();+ return "<namenode>";+ }++ /**+ * Shut down this instance of the datanode.+ * Returns only after shutdown is complete.+ */+ void shutdown() {+ this.shouldRun = false;+ ((DataXceiveServer) this.dataXceiveServer.getRunnable()).kill();+ try {+ this.dataXceiveServer.join();+ } catch (InterruptedException ie) {+ }+ }++ /**+ * Main loop for the DataNode. Runs until shutdown.+ */+ public void offerService() throws Exception {+ long wakeups = 0;+ long lastHeartbeat = 0, lastBlockReport = 0;+ long sendStart = System.currentTimeMillis();+ int heartbeatsSent = 0;+ LOG.info("using BLOCKREPORT_INTERVAL of " + blockReportInterval + "msec");++ //+ // Now loop for a long time....+ //+ while (shouldRun) {+ long now = System.currentTimeMillis();++ //+ // Every so often, send heartbeat or block-report+ //+ synchronized (receivedBlockList) {+ if (now - lastHeartbeat > HEARTBEAT_INTERVAL) {+ //+ // All heartbeat messages include following info:+ // -- Datanode name+ // -- data transfer port+ // -- Total capacity+ // -- Bytes remaining+ //+ namenode.sendHeartbeat(localName, data.getCapacity(), data.getRemaining());+ //LOG.info("Just sent heartbeat, with name " + localName);+ lastHeartbeat = now;+ }+ if (now - lastBlockReport > blockReportInterval) {+ //+ // Send latest blockinfo report if timer has expired.+ // Get back a list of local block(s) that are obsolete+ // and can be safely GC'ed.+ //+ Block toDelete[] = namenode.blockReport(localName, data.getBlockReport());+ data.invalidate(toDelete);+ lastBlockReport = now;+ continue;+ }+ if (receivedBlockList.size() > 0) {+ //+ // Send newly-received blockids to namenode+ //+ Block blockArray[] = (Block[]) receivedBlockList.toArray(new Block[receivedBlockList.size()]);+ receivedBlockList.removeAllElements();+ namenode.blockReceived(localName, blockArray);+ }++ //+ // Only perform block operations (transfer, delete) after+ // a startup quiet period. The assumption is that all the+ // datanodes will be started together, but the namenode may+ // have been started some time before. (This is esp. true in+ // the case of network interruptions.) So, wait for some time+ // to pass from the time of connection to the first block-transfer.+ // Otherwise we transfer a lot of blocks unnecessarily.+ //+ if (now - sendStart > datanodeStartupPeriod) {+ //+ // Check to see if there are any block-instructions from the+ // namenode that this datanode should perform.+ //+ BlockCommand cmd = namenode.getBlockwork(localName, xmitsInProgress);+ if (cmd != null && cmd.transferBlocks()) {+ //+ // Send a copy of a block to another datanode+ //+ Block blocks[] = cmd.getBlocks();+ DatanodeInfo xferTargets[][] = cmd.getTargets();++ for (int i = 0; i < blocks.length; i++) {+ if (!data.isValidBlock(blocks[i])) {+ String errStr = "Can't send invalid block " + blocks[i];+ LOG.info(errStr);+ namenode.errorReport(localName, errStr);+ break;+ } else {+ if (xferTargets[i].length > 0) {+ LOG.info("Starting thread to transfer block " + blocks[i] + " to " + xferTargets[i]);+ new Daemon(new DataTransfer(xferTargets[i], blocks[i])).start();+ }+ }+ }+ } else if (cmd != null && cmd.invalidateBlocks()) {+ //+ // Some local block(s) are obsolete and can be+ // safely garbage-collected.+ //+ data.invalidate(cmd.getBlocks());+ }+ }++ //+ // There is no work to do; sleep until hearbeat timer elapses,+ // or work arrives, and then iterate again.+ //+ long waitTime = HEARTBEAT_INTERVAL - (now - lastHeartbeat);+ if (waitTime > 0 && receivedBlockList.size() == 0) {+ try {+ receivedBlockList.wait(waitTime);+ } catch (InterruptedException ie) {+ }+ }+ }+ }+ }++ /**+ * Server used for receiving/sending a block of data+ */+ class DataXceiveServer implements Runnable {+ boolean shouldListen = true;+ ServerSocket ss;+ public DataXceiveServer(ServerSocket ss) {+ this.ss = ss;+ }++ /**+ */+ public void run() {+ try {+ while (shouldListen) {+ Socket s = ss.accept();+ s.setSoTimeout(READ_TIMEOUT);+ new Daemon(new DataXceiver(s)).start();+ }+ ss.close();+ } catch (IOException ie) {+ LOG.info("Exiting DataXceiveServer due to " + ie.toString());+ }+ }+ public void kill() {+ this.shouldListen = false;+ try {+ this.ss.close();+ } catch (IOException iex) {+ }+ }+ }++ /**+ * Thread for processing incoming/outgoing data stream+ */+ class DataXceiver implements Runnable {+ Socket s;+ public DataXceiver(Socket s) {+ this.s = s;+ }++ /**+ */+ public void run() {+ try {+ DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));+ try {+ byte op = (byte) in.read();+ if (op == OP_WRITE_BLOCK) {+ //+ // Read in the header+ //+ DataOutputStream reply = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));+ try {+ boolean shouldReportBlock = in.readBoolean();+ Block b = new Block();+ b.readFields(in);+ int numTargets = in.readInt();+ if (numTargets <= 0) {+ throw new IOException("Mislabelled incoming datastream.");+ }+ DatanodeInfo targets[] = new DatanodeInfo[numTargets];+ for (int i = 0; i < targets.length; i++) {+ DatanodeInfo tmp = new DatanodeInfo();+ tmp.readFields(in);+ targets[i] = tmp;+ }+ byte encodingType = (byte) in.read();+ long len = in.readLong();++ //+ // Make sure curTarget is equal to this machine+ //+ DatanodeInfo curTarget = targets[0];++ //+ // Track all the places we've successfully written the block+ //+ Vector mirrors = new Vector();++ //+ // Open local disk out+ //+ DataOutputStream out = new DataOutputStream(new BufferedOutputStream(data.writeToBlock(b)));+ InetSocketAddress mirrorTarget = null;+ try {+ //+ // Open network conn to backup machine, if+ // appropriate+ //+ DataInputStream in2 = null;+ DataOutputStream out2 = null;+ if (targets.length > 1) {+ // Connect to backup machine+ mirrorTarget = createSocketAddr(targets[1].getName().toString());+ try {+ Socket s = new Socket(mirrorTarget.getAddress(), mirrorTarget.getPort());+ s.setSoTimeout(READ_TIMEOUT);+ out2 = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));+ in2 = new DataInputStream(new BufferedInputStream(s.getInputStream()));++ // Write connection header+ out2.write(OP_WRITE_BLOCK);+ out2.writeBoolean(shouldReportBlock);+ b.write(out2);+ out2.writeInt(targets.length - 1);+ for (int i = 1; i < targets.length; i++) {+ targets[i].write(out2);+ }+ out2.write(encodingType);+ out2.writeLong(len);+ } catch (IOException ie) {+ if (out2 != null) {+ try {+ out2.close();+ in2.close();+ } catch (IOException out2close) {+ } finally {+ out2 = null;+ in2 = null;+ }+ }+ }+ }++ //+ // Process incoming data, copy to disk and+ // maybe to network.+ //+ try {+ boolean anotherChunk = true;+ byte buf[] = new byte[BUFFER_SIZE];++ while (anotherChunk) {+ while (len > 0) {+ int bytesRead = in.read(buf, 0, (int)Math.min(buf.length, len));+ if (bytesRead < 0) {+ throw new EOFException("EOF reading from "+s.toString());+ }+ if (bytesRead > 0) {+ try {+ out.write(buf, 0, bytesRead);+ } catch (IOException iex) {+ shutdown();+ throw iex;+ }+ if (out2 != null) {+ try {+ out2.write(buf, 0, bytesRead);+ } catch (IOException out2e) {+ //+ // If stream-copy fails, continue+ // writing to disk. We shouldn't+ // interrupt client write.+ //+ try {+ out2.close();+ in2.close();+ } catch (IOException out2close) {+ } finally {+ out2 = null;+ in2 = null;+ }+ }+ }+ len -= bytesRead;+ }+ }++ if (encodingType == RUNLENGTH_ENCODING) {+ anotherChunk = false;+ } else if (encodingType == CHUNKED_ENCODING) {+ len = in.readLong();+ if (out2 != null) {+ out2.writeLong(len);+ }+ if (len == 0) {+ anotherChunk = false;+ }+ }+ }++ if (out2 == null) {+ LOG.info("Received block " + b + " from " + s.getInetAddress());+ } else {+ out2.flush();+ long complete = in2.readLong();+ if (complete != WRITE_COMPLETE) {+ LOG.info("Conflicting value for WRITE_COMPLETE: " + complete);+ }+ LocatedBlock newLB = new LocatedBlock();+ newLB.readFields(in2);+ DatanodeInfo mirrorsSoFar[] = newLB.getLocations();+ for (int k = 0; k < mirrorsSoFar.length; k++) {+ mirrors.add(mirrorsSoFar[k]);+ }+ LOG.info("Received block " + b + " from " + s.getInetAddress() + " and mirrored to " + mirrorTarget);+ }+ } finally {+ if (out2 != null) {+ out2.close();+ in2.close();+ }+ }+ } finally {+ try {+ out.close();+ } catch (IOException iex) {+ shutdown();+ throw iex;+ }+ }+ data.finalizeBlock(b);++ //+ // Tell the namenode that we've received this block+ // in full, if we've been asked to. This is done+ // during NameNode-directed block transfers, but not+ // client writes.+ //+ if (shouldReportBlock) {+ synchronized (receivedBlockList) {+ receivedBlockList.add(b);+ receivedBlockList.notifyAll();+ }+ }++ //+ // Tell client job is done, and reply with+ // the new LocatedBlock.+ //+ reply.writeLong(WRITE_COMPLETE);+ mirrors.add(curTarget);+ LocatedBlock newLB = new LocatedBlock(b, (DatanodeInfo[]) mirrors.toArray(new DatanodeInfo[mirrors.size()]));+ newLB.write(reply);+ } finally {+ reply.close();+ }+ } else if (op == OP_READ_BLOCK || op == OP_READSKIP_BLOCK) {+ //+ // Read in the header+ //+ Block b = new Block();+ b.readFields(in);++ long toSkip = 0;+ if (op == OP_READSKIP_BLOCK) {+ toSkip = in.readLong();+ }++ //+ // Open reply stream+ //+ DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));+ try {+ //+ // Write filelen of -1 if error+ //+ if (! data.isValidBlock(b)) {+ out.writeLong(-1);+ } else {+ //+ // Get blockdata from disk+ //+ long len = data.getLength(b);+ DataInputStream in2 = new DataInputStream(data.getBlockData(b));+ out.writeLong(len);++ if (op == OP_READSKIP_BLOCK) {+ if (toSkip > len) {+ toSkip = len;+ }+ long amtSkipped = 0;+ try {+ amtSkipped = in2.skip(toSkip);+ } catch (IOException iex) {+ shutdown();+ throw iex;+ }+ out.writeLong(amtSkipped);+ }++ byte buf[] = new byte[BUFFER_SIZE];+ try {+ int bytesRead = 0;+ try {+ bytesRead = in2.read(buf);+ } catch (IOException iex) {+ shutdown();+ throw iex;+ }+ while (bytesRead >= 0) {+ out.write(buf, 0, bytesRead);+ len -= bytesRead;+ try {+ bytesRead = in2.read(buf);+ } catch (IOException iex) {+ shutdown();+ throw iex;+ }+ }+ } catch (SocketException se) {+ // This might be because the reader+ // closed the stream early+ } finally {+ try {+ in2.close();+ } catch (IOException iex) {+ shutdown();+ throw iex;+ }+ }+ }+ LOG.info("Served block " + b + " to " + s.getInetAddress());+ } finally {+ out.close();+ }+ } else {+ while (op >= 0) {+ System.out.println("Faulty op: " + op);+ op = (byte) in.read();+ }+ throw new IOException("Unknown opcode for incoming data stream");+ }+ } finally {+ in.close();+ }+ } catch (IOException ie) {+ LOG.log(Level.WARNING, "DataXCeiver", ie);+ } finally {+ try {+ s.close();+ } catch (IOException ie2) {+ }+ }+ }+ }++ /**+ * Used for transferring a block of data+ */+ class DataTransfer implements Runnable {+ InetSocketAddress curTarget;+ DatanodeInfo targets[];+ Block b;+ byte buf[];++ /**+ * Connect to the first item in the target list. Pass along the+ * entire target list, the block, and the data.+ */+ public DataTransfer(DatanodeInfo targets[], Block b) throws IOException {+ this.curTarget = createSocketAddr(targets[0].getName().toString());+ this.targets = targets;+ this.b = b;+ this.buf = new byte[BUFFER_SIZE];+ }++ /**+ * Do the deed, write the bytes+ */+ public void run() {+ xmitsInProgress++;+ try {+ Socket s = new Socket(curTarget.getAddress(), curTarget.getPort());+ DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));+ try {+ long filelen = data.getLength(b);+ DataInputStream in = new DataInputStream(new BufferedInputStream(data.getBlockData(b)));+ try {+ //+ // Header info+ //+ out.write(OP_WRITE_BLOCK);+ out.writeBoolean(true);+ b.write(out);+ out.writeInt(targets.length);+ for (int i = 0; i < targets.length; i++) {+ targets[i].write(out);+ }+ out.write(RUNLENGTH_ENCODING);+ out.writeLong(filelen);++ //+ // Write the data+ //+ while (filelen > 0) {+ int bytesRead = in.read(buf, 0, (int) Math.min(filelen, buf.length));+ out.write(buf, 0, bytesRead);+ filelen -= bytesRead;+ }+ } finally {+ in.close();+ }+ } finally {+ out.close();+ }+ LOG.info("Transmitted block " + b + " to " + curTarget);+ } catch (IOException ie) {+ } finally {+ xmitsInProgress--;+ }+ }+ }++ /**+ * No matter what kind of exception we get, keep retrying to offerService().+ * That's the loop that connects to the NameNode and provides basic DataNode+ * functionality.+ *+ * Only stop when "shouldRun" is turned off (which can only happen at shutdown).+ */+ public void run() {+ LOG.info("Starting DataNode in: "+data.data);+ while (shouldRun) {+ try {+ offerService();+ } catch (Exception ex) {+ LOG.info("Exception: " + ex);+ if (shouldRun) {+ LOG.info("Lost connection to namenode. Retrying...");+ try {+ Thread.sleep(5000);+ } catch (InterruptedException ie) {+ }+ }+ }+ }+ LOG.info("Finishing DataNode in: "+data.data);+ }++ /** Start datanode daemons.+ * Start a datanode daemon for each comma separated data directory+ * specified in property ndfs.data.dir+ */+ public static void run(NutchConf conf) throws IOException {+ String[] dataDirs = conf.getStrings("ndfs.data.dir");+ subThreadList = new Vector(dataDirs.length);+ for (int i = 0; i < dataDirs.length; i++) {+ DataNode dn = makeInstanceForDir(dataDirs[i], conf);+ if (dn != null) {+ Thread t = new Thread(dn, "DataNode: "+dataDirs[i]);+ t.setDaemon(true); // needed for JUnit testing+ t.start();+ subThreadList.add(t);+ }+ }+ }++ /** Start datanode daemons.+ * Start a datanode daemon for each comma separated data directory+ * specified in property ndfs.data.dir and wait for them to finish.+ * If this thread is specifically interrupted, it will stop waiting.+ */+ private static void runAndWait(NutchConf conf) throws IOException {+ run(conf);++ // Wait for sub threads to exit+ for (Iterator iterator = subThreadList.iterator(); iterator.hasNext();) {+ Thread threadDataNode = (Thread) iterator.next();+ try {+ threadDataNode.join();+ } catch (InterruptedException e) {+ if (Thread.currentThread().isInterrupted()) {+ // did someone knock?+ return;+ }+ }+ }+ }++ /**+ * Make an instance of DataNode after ensuring that given data directory+ * (and parent directories, if necessary) can be created.+ * @param dataDir where the new DataNode instance should keep its files.+ * @param conf NutchConf instance to use.+ * @return DataNode instance for given data dir and conf, or null if directory+ * cannot be created.+ * @throws IOException+ */+ static DataNode makeInstanceForDir(String dataDir, NutchConf conf) throws IOException {+ DataNode dn = null;+ File data = new File(dataDir);+ data.mkdirs();+ if (!data.isDirectory()) {+ LOG.warning("Can't start DataNode in non-directory: "+dataDir);+ return null;+ } else {+ dn = new DataNode(conf, dataDir);+ }+ return dn;+ }++ public String toString() {+ return "DataNode{" ++ "data=" + data ++ ", localName='" + localName + "'" ++ ", xmitsInProgress=" + xmitsInProgress ++ "}";+ }++ /**+ */+ public static void main(String args[]) throws IOException {+ LogFormatter.setShowThreadIDs(true);+ runAndWait(NutchConf.get());+ }+}diff --git a/src/java/org/apache/nutch/ndfs/DatanodeInfo.java b/src/java/org/apache/nutch/ndfs/DatanodeInfo.javaindex aee0baf24..d684c184c 100644--- a/src/java/org/apache/nutch/ndfs/DatanodeInfo.java+++ b/src/java/org/apache/nutch/ndfs/DatanodeInfo.java@@ -27,35 +27,36 @@ import java.util.*;* @author Mike Cafarella**************************************************/public class DatanodeInfo implements Writable, Comparable {- UTF8 name;- long capacity, remaining, lastUpdate, lastObsoleteCheck;- volatile TreeSet blocks;+ private UTF8 name;+ private long capacityBytes, remainingBytes, lastUpdate;+ private volatile TreeSet blocks;- /**+ /** Create an empty DatanodeInfo.*/public DatanodeInfo() {this(new UTF8(), 0, 0);}+ /**+ * @param name hostname:portNumber as UTF8 object.+ */public DatanodeInfo(UTF8 name) {this.name = name;- int colon = name.toString().indexOf(":");this.blocks = new TreeSet();- this.lastObsoleteCheck = System.currentTimeMillis();updateHeartbeat(0, 0);}- /**- */+ /**+ * @param name hostname:portNumber as UTF8 object.+ */public DatanodeInfo(UTF8 name, long capacity, long remaining) {this.name = name;this.blocks = new TreeSet();- this.lastObsoleteCheck = System.currentTimeMillis();updateHeartbeat(capacity, remaining);}- /**- */+ /**+ */public void updateBlocks(Block newBlocks[]) {blocks.clear();for (int i = 0; i < newBlocks.length; i++) {@@ -63,8 +64,8 @@ public class DatanodeInfo implements Writable, Comparable {}}- /**- */+ /**+ */public void addBlock(Block b) {blocks.add(b);}@@ -72,13 +73,21 @@ public class DatanodeInfo implements Writable, Comparable {/***/public void updateHeartbeat(long capacity, long remaining) {- this.capacity = capacity;- this.remaining = remaining;+ this.capacityBytes = capacity;+ this.remainingBytes = remaining;this.lastUpdate = System.currentTimeMillis();}++ /**+ * @return hostname:portNumber as UTF8 object.+ */public UTF8 getName() {return name;}++ /**+ * @return hostname and no :portNumber as UTF8 object.+ */public UTF8 getHost() {String nameStr = name.toString();int colon = nameStr.indexOf(":");@@ -98,24 +107,20 @@ public class DatanodeInfo implements Writable, Comparable {return blocks.iterator();}public long getCapacity() {- return capacity;+ return capacityBytes;}public long getRemaining() {- return remaining;+ return remainingBytes;}public long lastUpdate() {return lastUpdate;}- public void updateObsoleteCheck() {- this.lastObsoleteCheck = System.currentTimeMillis();- }- public long lastObsoleteCheck() {- return lastObsoleteCheck;- }- /////////////////////////////////////////////////- // Comparable- /////////////////////////////////////////////////+ /** Comparable.+ * Basis of compare is the UTF8 name (host:portNumber) only.+ * @param o+ * @return as specified by Comparable.+ */public int compareTo(Object o) {DatanodeInfo d = (DatanodeInfo) o;return name.compareTo(d.getName());@@ -128,8 +133,8 @@ public class DatanodeInfo implements Writable, Comparable {*/public void write(DataOutput out) throws IOException {name.write(out);- out.writeLong(capacity);- out.writeLong(remaining);+ out.writeLong(capacityBytes);+ out.writeLong(remainingBytes);out.writeLong(lastUpdate);/**@@ -145,8 +150,8 @@ public class DatanodeInfo implements Writable, Comparable {public void readFields(DataInput in) throws IOException {this.name = new UTF8();this.name.readFields(in);- this.capacity = in.readLong();- this.remaining = in.readLong();+ this.capacityBytes = in.readLong();+ this.remainingBytes = in.readLong();this.lastUpdate = in.readLong();/**diff --git a/src/java/org/apache/nutch/ndfs/DatanodeProtocol.java b/src/java/org/apache/nutch/ndfs/DatanodeProtocol.javanew file mode 100644index 000000000..2abb5f39c--- /dev/null+++ b/src/java/org/apache/nutch/ndfs/DatanodeProtocol.java@@ -0,0 +1,36 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import java.io.*;+import org.apache.nutch.io.*;++/**********************************************************************+ * Protocol that an NDFS datanode uses to communicate with the NameNode.+ * It's used to upload current load information and block records.+ *+ * @author Michael Cafarella+ **********************************************************************/+public interface DatanodeProtocol {++ public void sendHeartbeat(String sender, long capacity, long remaining) throws IOException;+ public Block[] blockReport(String sender, Block blocks[]) throws IOException;+ public void blockReceived(String sender, Block blocks[]) throws IOException;+ public void errorReport(String sender, String msg) throws IOException;++ public BlockCommand getBlockwork(String sender, int xmitsInProgress) throws IOException;+}diff --git a/src/java/org/apache/nutch/ndfs/FSConstants.java b/src/java/org/apache/nutch/ndfs/FSConstants.javaindex e301e56f9..15b186b32 100644--- a/src/java/org/apache/nutch/ndfs/FSConstants.java+++ b/src/java/org/apache/nutch/ndfs/FSConstants.java@@ -15,6 +15,8 @@*/package org.apache.nutch.ndfs;+import org.apache.nutch.util.NutchConf;+/************************************* Some handy constants*@@ -22,7 +24,7 @@ package org.apache.nutch.ndfs;************************************/public interface FSConstants {public static int BLOCK_SIZE = 32 * 1000 * 1000;- //public static int BLOCK_SIZE = 2173;+ //public static int BLOCK_SIZE = 19;public static final long WRITE_COMPLETE = 0xcafae11a;@@ -99,10 +101,14 @@ public interface FSConstants {// Timeouts, constants//public static long HEARTBEAT_INTERVAL = 3 * 1000;- public static long EXPIRE_INTERVAL = 4 * HEARTBEAT_INTERVAL;- public static long BLOCKREPORT_INTERVAL = 9 * 60 * 1000;- public static long OBSOLETE_INTERVAL = 10 * 60 * 1000;- public static long SYSTEM_STARTUP_PERIOD = 15 * 1000;- public static long DATANODE_STARTUP_PERIOD = 30 * 1000;- public static long LEASE_PERIOD = 16 * 1000;+ public static long EXPIRE_INTERVAL = 10 * 60 * 1000;+ public static long BLOCKREPORT_INTERVAL = 60 * 60 * 1000;+ public static long DATANODE_STARTUP_PERIOD = 2 * 60 * 1000;+ public static long LEASE_PERIOD = 60 * 1000;+ public static int READ_TIMEOUT = 60 * 1000;++ public static int BUFFER_SIZE =+ NutchConf.get().getInt("io.file.buffer.size", 4096);+}+diff --git a/src/java/org/apache/nutch/ndfs/FSDataset.java b/src/java/org/apache/nutch/ndfs/FSDataset.javaindex 15fbfc923..6e043e281 100644--- a/src/java/org/apache/nutch/ndfs/FSDataset.java+++ b/src/java/org/apache/nutch/ndfs/FSDataset.java@@ -29,7 +29,8 @@ import org.apache.nutch.util.*;***************************************************/public class FSDataset implements FSConstants {static final double USABLE_DISK_PCT = 0.98;- /**++ /*** A node type that can be built into a tree reflecting the* hierarchy of blocks on the local disk.*/@@ -166,6 +167,13 @@ public class FSDataset implements FSConstants {blkid = blkid >> ((15 - halfByteIndex) * 4);return (int) ((0x000000000000000F) & blkid);}++ public String toString() {+ return "FSDir{" ++ "dir=" + dir ++ ", children=" + (children == null ? null : Arrays.asList(children)) ++ "}";+ }}//////////////////////////////////////////////////////@@ -282,17 +290,23 @@ public class FSDataset implements FSConstants {ongoingCreates.add(b);reserved += BLOCK_SIZE;f = getTmpFile(b);-- if (f.exists()) {- throw new IOException("Unexpected problem in startBlock() for " + b + ". File " + f + " should not be present, but is.");- }- }-- //- // Create the zero-length temp file- //- if (!f.createNewFile()) {- throw new IOException("Unexpected problem in startBlock() for " + b + ". File " + f + " should be creatable, but is already present.");+ try {+ if (f.exists()) {+ throw new IOException("Unexpected problem in startBlock() for " + b + ". File " + f + " should not be present, but is.");+ }++ //+ // Create the zero-length temp file+ //+ if (!f.createNewFile()) {+ throw new IOException("Unexpected problem in startBlock() for " + b + ". File " + f + " should be creatable, but is already present.");+ }+ } catch (IOException ie) {+ System.out.println("Exception! " + ie);+ ongoingCreates.remove(b);+ reserved -= BLOCK_SIZE;+ throw ie;+ }}//@@ -405,4 +419,11 @@ public class FSDataset implements FSConstants {// REMIND - mjc - should cache this result for performancereturn new File(tmp, b.getBlockName());}++ public String toString() {+ return "FSDataset{" ++ "dirpath='" + dirpath + "'" ++ "}";+ }+}diff --git a/src/java/org/apache/nutch/ndfs/FSDirectory.java b/src/java/org/apache/nutch/ndfs/FSDirectory.javaindex 1cce81bda..ee8755153 100644--- a/src/java/org/apache/nutch/ndfs/FSDirectory.java+++ b/src/java/org/apache/nutch/ndfs/FSDirectory.java@@ -47,7 +47,7 @@ public class FSDirectory implements FSConstants {class INode {public String name;public INode parent;- public Vector children = new Vector();+ public TreeMap children = new TreeMap();public Block blocks[];/**@@ -59,61 +59,45 @@ public class FSDirectory implements FSConstants {}/**+ * This is the external interface*/INode getNode(String target) {- if (! target.startsWith("/")) {+ if (! target.startsWith("/") || target.length() == 0) {return null;- }-- if (parent == null) {- if ("/".equals(target)) {- return this;- } else {- // Check with children- for (Iterator it = children.iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- INode result = child.getNode(target);- if (result != null) {- return result;- }- }- }+ } else if (parent == null && "/".equals(target)) {+ return this;} else {- // Strip the leading slash- if (target.length() > 1) {- target = target.substring(1);+ Vector components = new Vector();+ int start = 0;+ int slashid = 0;+ while (start < target.length() && (slashid = target.indexOf('/', start)) >= 0) {+ components.add(target.substring(start, slashid));+ start = slashid + 1;}-- // Check if it's the current node- if (name.equals(target)) {- return this;- }-- // Get the chunk up to the next slash- String curComponent, remainder;- int slash = target.indexOf('/');- if (slash < 0) {- return null;- } else {- curComponent = target.substring(0, slash);- remainder = target.substring(slash);+ if (start < target.length()) {+ components.add(target.substring(start));}+ return getNode(components, 0);+ }+ }- // Make sure we're on the right track- if (! name.equals(curComponent)) {- return null;- }+ /**+ */+ INode getNode(Vector components, int index) {+ if (! name.equals((String) components.elementAt(index))) {+ return null;+ }+ if (index == components.size()-1) {+ return this;+ }- // Check with children- for (Iterator it = children.iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- INode result = child.getNode(remainder);- if (result != null) {- return result;- }- }+ // Check with children+ INode child = (INode) children.get(components.elementAt(index+1));+ if (child == null) {+ return null;+ } else {+ return child.getNode(components, index+1);}- return null;}/**@@ -133,7 +117,7 @@ public class FSDirectory implements FSConstants {} else {String targetName = new File(target).getName();INode newItem = new INode(targetName, parentNode, blks);- parentNode.children.add(newItem);+ parentNode.children.put(targetName, newItem);return newItem;}}@@ -141,13 +125,29 @@ public class FSDirectory implements FSConstants {/***/- INode removeNode(String target) {- INode targetNode = getNode(target);- if (targetNode == null) {- return null;+ boolean removeNode() {+ if (parent == null) {+ return false;} else {- targetNode.parent.children.remove(targetNode);- return targetNode;+ parent.children.remove(name);+ return true;+ }+ }++ /**+ * Collect all the blocks at this INode and all its children.+ * This operation is performed after a node is removed from the tree,+ * and we want to GC all the blocks at this node and below.+ */+ void collectSubtreeBlocks(Vector v) {+ if (blocks != null) {+ for (int i = 0; i < blocks.length; i++) {+ v.add(blocks[i]);+ }+ }+ for (Iterator it = children.values().iterator(); it.hasNext(); ) {+ INode child = (INode) it.next();+ child.collectSubtreeBlocks(v);}}@@ -155,7 +155,7 @@ public class FSDirectory implements FSConstants {*/int numItemsInTree() {int total = 0;- for (Iterator it = children.iterator(); it.hasNext(); ) {+ for (Iterator it = children.values().iterator(); it.hasNext(); ) {INode child = (INode) it.next();total += child.numItemsInTree();}@@ -188,7 +188,7 @@ public class FSDirectory implements FSConstants {*/long computeContentsLength() {long total = computeFileLength();- for (Iterator it = children.iterator(); it.hasNext(); ) {+ for (Iterator it = children.values().iterator(); it.hasNext(); ) {INode child = (INode) it.next();total += child.computeContentsLength();}@@ -202,7 +202,7 @@ public class FSDirectory implements FSConstants {v.add(this);}- for (Iterator it = children.iterator(); it.hasNext(); ) {+ for (Iterator it = children.values().iterator(); it.hasNext(); ) {INode child = (INode) it.next();v.add(child);}@@ -224,7 +224,7 @@ public class FSDirectory implements FSConstants {}}}- for (Iterator it = children.iterator(); it.hasNext(); ) {+ for (Iterator it = children.values().iterator(); it.hasNext(); ) {INode child = (INode) it.next();child.saveImage(fullName, out);}@@ -502,21 +502,24 @@ public class FSDirectory implements FSConstants {*/boolean unprotectedRenameTo(UTF8 src, UTF8 dst) {synchronized(rootDir) {- INode removedNode = rootDir.removeNode(src.toString());+ INode removedNode = rootDir.getNode(src.toString());if (removedNode == null) {return false;}-+ removedNode.removeNode();+ if (isDir(dst)) {+ dst = new UTF8(dst.toString() + "/" + new File(src.toString()).getName());+ }INode newNode = rootDir.addNode(dst.toString(), removedNode.blocks);if (newNode != null) {newNode.children = removedNode.children;- for (Iterator it = newNode.children.iterator(); it.hasNext(); ) {+ for (Iterator it = newNode.children.values().iterator(); it.hasNext(); ) {INode child = (INode) it.next();child.parent = newNode;}return true;} else {- removedNode.parent.children.add(removedNode);+ rootDir.addNode(src.toString(), removedNode.blocks);return false;}}@@ -539,25 +542,21 @@ public class FSDirectory implements FSConstants {if (targetNode == null) {return null;} else {- Vector allBlocks = new Vector();- Vector contents = new Vector();- targetNode.listContents(contents);-- for (Iterator it = contents.iterator(); it.hasNext(); ) {- INode cur = (INode) it.next();- INode removedNode = rootDir.removeNode(cur.computeName());- if (removedNode != null) {- Block blocks[] = removedNode.blocks;- if (blocks != null) {- for (int i = 0; i < blocks.length; i++) {- activeBlocks.remove(blocks[i]);- allBlocks.add(blocks[i]);- }- }+ //+ // Remove the node from the namespace and GC all+ // the blocks underneath the node.+ //+ if (! targetNode.removeNode()) {+ return null;+ } else {+ Vector v = new Vector();+ targetNode.collectSubtreeBlocks(v);+ for (Iterator it = v.iterator(); it.hasNext(); ) {+ Block b = (Block) it.next();+ activeBlocks.remove(b);}+ return (Block[]) v.toArray(new Block[v.size()]);}- rootDir.removeNode(src.toString());- return (Block[]) allBlocks.toArray(new Block[0]);}}}diff --git a/src/java/org/apache/nutch/ndfs/FSNamesystem.java b/src/java/org/apache/nutch/ndfs/FSNamesystem.javaindex 5753148f7..0f233c458 100644--- a/src/java/org/apache/nutch/ndfs/FSNamesystem.java+++ b/src/java/org/apache/nutch/ndfs/FSNamesystem.java@@ -38,12 +38,24 @@ public class FSNamesystem implements FSConstants {final static int DESIRED_REPLICATION =NutchConf.get().getInt("ndfs.replication", 3);+ // The maximum number of replicates we should allow for a single block+ final static int MAX_REPLICATION = DESIRED_REPLICATION;++ // How many outgoing replication streams a given node should have at one time+ final static int MAX_REPLICATION_STREAMS = NutchConf.get().getInt("ndfs.max-repl-streams", 2);+// MIN_REPLICATION is how many copies we need in place or else we disallow the writefinal static int MIN_REPLICATION = 1;// HEARTBEAT_RECHECK is how often a datanode sends its hearbeatfinal static long HEARTBEAT_RECHECK = 1000;+ // Whether we should use disk-availability info when determining target+ final static boolean USE_AVAILABILITY = NutchConf.get().getBoolean("ndfs.availability.allocation", false);++ private boolean allowSameHostTargets =+ NutchConf.get().getBoolean("test.ndfs.same.host.targets.allowed", false);+//// Stores the correct file name hierarchy//@@ -69,6 +81,13 @@ public class FSNamesystem implements FSConstants {//TreeMap recentInvalidateSets = new TreeMap();+ //+ // Keeps a TreeSet for every named node. Each treeset contains+ // a list of the blocks that are "extra" at that location. We'll+ // eventually remove these extras.+ //+ TreeMap excessReplicateMap = new TreeMap();+//// Keeps track of files that are being created, plus the// blocks that make them up.@@ -111,14 +130,14 @@ public class FSNamesystem implements FSConstants {// Store set of Blocks that need to be replicated 1 or more times.// We also store pending replication-orders.//- TreeSet neededReplications = new TreeSet();- TreeSet pendingReplications = new TreeSet();+ private TreeSet neededReplications = new TreeSet();+ private TreeSet pendingReplications = new TreeSet();//// Used for handling lock-leases//- TreeMap leases = new TreeMap();- TreeSet sortedLeases = new TreeSet();+ private TreeMap leases = new TreeMap();+ private TreeSet sortedLeases = new TreeSet();//// Threaded object that checks to see if we have been@@ -143,17 +162,23 @@ public class FSNamesystem implements FSConstants {this.systemStart = System.currentTimeMillis();}- /**+ /** Close down this filesystem manager.+ * Causes heartbeat and lease daemons to stop; waits briefly for+ * them to finish, but a short timeout returns control back to caller.*/public void close() {+ synchronized (this) {fsRunning = false;+ }try {- hbthread.join();- } catch (InterruptedException ie) {- }- try {- lmthread.join();+ hbthread.join(3000);} catch (InterruptedException ie) {+ } finally {+ // using finally to ensure we also wait for lease daemon+ try {+ lmthread.join(3000);+ } catch (InterruptedException ie) {+ }}}@@ -202,6 +227,9 @@ public class FSNamesystem implements FSConstants {* of machines. The first on this list should be where the client* writes data. Subsequent items in the list must be provided in* the connection to the first datanode.+ * @return Return an array that consists of the block, plus a set+ * of machines, or null if src is invalid for creation (based on+ * {@link FSDirectory#isValidToCreate(UTF8)}.*/public synchronized Object[] startFile(UTF8 src, UTF8 holder, boolean overwrite) {Object results[] = null;@@ -218,6 +246,8 @@ public class FSNamesystem implements FSConstants {// Get the array of replication targetsDatanodeInfo targets[] = chooseTargets(DESIRED_REPLICATION, null);if (targets.length < MIN_REPLICATION) {+ LOG.warning("Target-length is " + targets.length ++ ", below MIN_REPLICATION (" + MIN_REPLICATION + ")");return null;}@@ -240,7 +270,11 @@ public class FSNamesystem implements FSConstants {// Create next blockresults[0] = allocateBlock(src);results[1] = targets;+ } else { // ! fileValid+ LOG.warning("Cannot start file because it is invalid. src=" + src);}+ } else {+ LOG.warning("Cannot start file because pendingCreates is non-null. src=" + src);}return results;}@@ -274,16 +308,6 @@ public class FSNamesystem implements FSConstants {// Create next blockresults[0] = allocateBlock(src);results[1] = targets;- } else {- LOG.info("File progress failure for " + src);- Vector v = (Vector) pendingCreates.get(src);- for (Iterator it = v.iterator(); it.hasNext(); ) {- Block b = (Block) it.next();- TreeSet containingNodes = (TreeSet) blocksMap.get(b);- if (containingNodes == null || containingNodes.size() < MIN_REPLICATION) {- LOG.info("Problem with block " + b + ", with " + (containingNodes == null ? "0" : "" + containingNodes.size()) + " nodes reporting in.");- }- }}}return results;@@ -310,6 +334,13 @@ public class FSNamesystem implements FSConstants {return false;}+ /**+ * Abandon the entire file in progress+ */+ public synchronized void abandonFileInProgress(UTF8 src) throws IOException {+ internalReleaseCreate(src);+ }+/*** Finalize the created file and make it world-accessible. The* FSNamesystem will already know the blocks that make up the file.@@ -318,6 +349,7 @@ public class FSNamesystem implements FSConstants {*/public synchronized int completeFile(UTF8 src, UTF8 holder) {if (dir.getFile(src) != null || pendingCreates.get(src) == null) {+ LOG.info("Failed to complete " + src + " because dir.getFile()==" + dir.getFile(src) + " and " + pendingCreates.get(src));return OPERATION_FAILED;} else if (! checkFileProgress(src)) {return STILL_WAITING;@@ -368,18 +400,29 @@ public class FSNamesystem implements FSConstants {}}+ //+ // REMIND - mjc - this should be done only after we wait a few secs.+ // The namenode isn't giving datanodes enough time to report the+ // replicated blocks that are automatically done as part of a client+ // write.+ //+// Now that the file is real, we need to be sure to replicate// the blocks.for (int i = 0; i < pendingBlocks.length; i++) {TreeSet containingNodes = (TreeSet) blocksMap.get(pendingBlocks[i]);if (containingNodes.size() < DESIRED_REPLICATION) {synchronized (neededReplications) {+ LOG.info("Completed file " + src + ", at holder " + holder + ". There is/are only " + containingNodes.size() + " copies of block " + pendingBlocks[i] + ", so replicating up to " + DESIRED_REPLICATION);neededReplications.add(pendingBlocks[i]);}}}return COMPLETE_SUCCESS;+ } else {+ System.out.println("AddFile() for " + src + " failed");}+ LOG.info("Dropped through on file add....");}return OPERATION_FAILED;@@ -486,39 +529,58 @@ public class FSNamesystem implements FSConstants {/*** Figure out a few hosts that are likely to contain the- * block referred to by the given filename, offset pair.+ * block(s) referred to by the given (filename, start, len) tuple.*/- public UTF8[] getDatanodeHints(UTF8 src, long offset) {- Block targetBlock = null;+ public UTF8[][] getDatanodeHints(UTF8 src, long start, long len) {+ if (start < 0 || len < 0) {+ return new UTF8[0][];+ }++ int startBlock = -1;+ int endBlock = -1;Block blocks[] = dir.getFile(src);//- // First, figure out where the offset would fall in+ // First, figure out where the range falls in// the blocklist.//+ long startpos = start;+ long endpos = start + len;for (int i = 0; i < blocks.length; i++) {- offset -= blocks[i].getNumBytes();- if (offset <= 0) {- targetBlock = blocks[i];- break;+ if (startpos >= 0) {+ startpos -= blocks[i].getNumBytes();+ if (startpos <= 0) {+ startBlock = i;+ }+ }+ if (endpos >= 0) {+ endpos -= blocks[i].getNumBytes();+ if (endpos <= 0) {+ endBlock = i;+ break;+ }}}//- // Next, create an array of hosts where that block can+ // Next, create an array of hosts where each block can// be found//- UTF8 hosts[] = null;- if (targetBlock != null) {- TreeSet containingNodes = (TreeSet) blocksMap.get(targetBlock);- Vector v = new Vector();- for (Iterator it = containingNodes.iterator(); it.hasNext(); ) {- DatanodeInfo cur = (DatanodeInfo) it.next();- v.add(cur.getHost());+ if (startBlock < 0 || endBlock < 0) {+ return new UTF8[0][];+ } else {+ UTF8 hosts[][] = new UTF8[endBlock - startBlock + 1][];+ for (int i = startBlock; i <= endBlock; i++) {+ TreeSet containingNodes = (TreeSet) blocksMap.get(blocks[i]);+ Vector v = new Vector();+ for (Iterator it = containingNodes.iterator(); it.hasNext(); ) {+ DatanodeInfo cur = (DatanodeInfo) it.next();+ v.add(cur.getHost());+ }+ hosts[i] = (UTF8[]) v.toArray(new UTF8[v.size()]);}- hosts = (UTF8[]) v.toArray(new UTF8[v.size()]);+ return hosts;}- return hosts;}/************************************************************@@ -535,7 +597,6 @@ public class FSNamesystem implements FSConstants {TreeSet creates = new TreeSet();public Lease(UTF8 holder) {- LOG.info("New lease, holder " + holder);this.holder = holder;renew();}@@ -570,7 +631,10 @@ public class FSNamesystem implements FSConstants {internalReleaseLock(src, holder);}locks.clear();- internalReleaseCreates(creates);+ for (Iterator it = creates.iterator(); it.hasNext(); ) {+ UTF8 src = (UTF8) it.next();+ internalReleaseCreate(src);+ }creates.clear();}@@ -674,14 +738,11 @@ public class FSNamesystem implements FSConstants {private int internalReleaseLock(UTF8 src, UTF8 holder) {return dir.releaseLock(src, holder);}- private void internalReleaseCreates(TreeSet creates) {- for (Iterator it = creates.iterator(); it.hasNext(); ) {- UTF8 src = (UTF8) it.next();- Vector v = (Vector) pendingCreates.remove(src);- for (Iterator it2 = v.iterator(); it2.hasNext(); ) {- Block b = (Block) it2.next();- pendingCreateBlocks.remove(b);- }+ private void internalReleaseCreate(UTF8 src) {+ Vector v = (Vector) pendingCreates.remove(src);+ for (Iterator it2 = v.iterator(); it2.hasNext(); ) {+ Block b = (Block) it2.next();+ pendingCreateBlocks.remove(b);}}@@ -695,7 +756,6 @@ public class FSNamesystem implements FSConstants {sortedLeases.remove(lease);lease.renew();sortedLeases.add(lease);- LOG.info("Renewed lease " + lease);}}}@@ -726,6 +786,7 @@ public class FSNamesystem implements FSConstants {DatanodeInfo nodeinfo = (DatanodeInfo) datanodeMap.get(name);if (nodeinfo == null) {+ LOG.info("Got brand-new heartbeat from " + name);nodeinfo = new DatanodeInfo(name, capacity, remaining);datanodeMap.put(name, nodeinfo);capacityDiff = capacity;@@ -798,7 +859,7 @@ public class FSNamesystem implements FSConstants {* The given node is reporting all its blocks. Use this info to* update the (machine-->blocklist) and (block-->machinelist) tables.*/- public synchronized void processReport(Block newReport[], UTF8 name) {+ public synchronized Block[] processReport(Block newReport[], UTF8 name) {DatanodeInfo node = (DatanodeInfo) datanodeMap.get(name);if (node == null) {throw new IllegalArgumentException("Unexpected exception. Received block report from node " + name + ", but there is no info for " + name);@@ -842,6 +903,29 @@ public class FSNamesystem implements FSConstants {// Modify node so it has the new blockreport//node.updateBlocks(newReport);++ //+ // We've now completely updated the node's block report profile.+ // We now go through all its blocks and find which ones are invalid,+ // no longer pending, or over-replicated.+ //+ // (Note it's not enough to just invalidate blocks at lease expiry+ // time; datanodes can go down before the client's lease on+ // the failed file expires and miss the "expire" event.)+ //+ // This function considers every block on a datanode, and thus+ // should only be invoked infrequently.+ //+ Vector obsolete = new Vector();+ for (Iterator it = node.getBlockIterator(); it.hasNext(); ) {+ Block b = (Block) it.next();++ if (! dir.isValidBlock(b) && ! pendingCreateBlocks.contains(b)) {+ LOG.info("Obsoleting block " + b);+ obsolete.add(b);+ }+ }+ return (Block[]) obsolete.toArray(new Block[obsolete.size()]);}/**@@ -870,7 +954,64 @@ public class FSNamesystem implements FSConstants {neededReplications.add(block);}}++ //+ // Find how many of the containing nodes are "extra", if any.+ // If there are any extras, call chooseExcessReplicates() to+ // mark them in the excessReplicateMap.+ //+ Vector nonExcess = new Vector();+ for (Iterator it = containingNodes.iterator(); it.hasNext(); ) {+ DatanodeInfo cur = (DatanodeInfo) it.next();+ TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(cur.getName());+ if (excessBlocks == null || ! excessBlocks.contains(block)) {+ nonExcess.add(cur);+ }+ }+ if (nonExcess.size() > MAX_REPLICATION) {+ chooseExcessReplicates(nonExcess, block, MAX_REPLICATION);+ }+ }+ }+ }++ /**+ * We want a max of "maxReps" replicates for any block, but we now have too many.+ * In this method, copy enough nodes from 'srcNodes' into 'dstNodes' such that:+ *+ * srcNodes.size() - dstNodes.size() == maxReps+ *+ * For now, we choose nodes randomly. In the future, we might enforce some+ * kind of policy (like making sure replicates are spread across racks).+ */+ void chooseExcessReplicates(Vector nonExcess, Block b, int maxReps) {+ while (nonExcess.size() - maxReps > 0) {+ int chosenNode = r.nextInt(nonExcess.size());+ DatanodeInfo cur = (DatanodeInfo) nonExcess.elementAt(chosenNode);+ nonExcess.removeElementAt(chosenNode);++ TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(cur.getName());+ if (excessBlocks == null) {+ excessBlocks = new TreeSet();+ excessReplicateMap.put(cur.getName(), excessBlocks);+ }+ excessBlocks.add(b);++ //+ // The 'excessblocks' tracks blocks until we get confirmation+ // that the datanode has deleted them; the only way we remove them+ // is when we get a "removeBlock" message.+ //+ // The 'invalidate' list is used to inform the datanode the block+ // should be deleted. Items are removed from the invalidate list+ // upon giving instructions to the namenode.+ //+ Vector invalidateSet = (Vector) recentInvalidateSets.get(cur.getName());+ if (invalidateSet == null) {+ invalidateSet = new Vector();+ recentInvalidateSets.put(cur.getName(), invalidateSet);}+ invalidateSet.add(b);}}@@ -896,6 +1037,18 @@ public class FSNamesystem implements FSConstants {neededReplications.add(block);}}++ //+ // We've removed a block from a node, so it's definitely no longer+ // in "excess" there.+ //+ TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(node.getName());+ if (excessBlocks != null) {+ excessBlocks.remove(block);+ if (excessBlocks.size() == 0) {+ excessReplicateMap.remove(node.getName());+ }+ }}/**@@ -956,49 +1109,14 @@ public class FSNamesystem implements FSConstants {//////////////////////////////////////////////////////////**- * Return with a list of Blocks that should be invalidated- * at the given node. Done in response to a file delete, which- * eliminates a number of blocks from the universe.+ * Check if there are any recently-deleted blocks a datanode should remove.*/- public synchronized Block[] recentlyInvalidBlocks(UTF8 name) {- Vector invalidateSet = (Vector) recentInvalidateSets.remove(name);- if (invalidateSet == null) {- return null;- } else {+ public synchronized Block[] blocksToInvalidate(UTF8 sender) {+ Vector invalidateSet = (Vector) recentInvalidateSets.remove(sender);+ if (invalidateSet != null) {return (Block[]) invalidateSet.toArray(new Block[invalidateSet.size()]);- }- }-- /**- * If the node has not been checked in some time, go through- * its blocks and find which ones are neither valid nor pending.- * It often happens that a client will start writing blocks and- * then exit. The blocks are on-disk, but the file will be- * abandoned.- *- * It's not enough to invalidate blocks at lease expiry time;- * datanodes can go down before the client's lease on- * the failed file expires and miss the "expire" event.- *- * This function considers every block on a datanode, and thus- * should only be invoked infrequently.- */- public synchronized Block[] checkObsoleteBlocks(UTF8 name) {- DatanodeInfo nodeInfo = (DatanodeInfo) datanodeMap.get(name);- if (System.currentTimeMillis() - nodeInfo.lastObsoleteCheck() <= OBSOLETE_INTERVAL) {- return null;} else {- nodeInfo.updateObsoleteCheck();- Vector obsolete = new Vector();- for (Iterator it = nodeInfo.getBlockIterator(); it.hasNext(); ) {- Block b = (Block) it.next();-- if (! dir.isValidBlock(b) && ! pendingCreateBlocks.contains(b)) {- LOG.info("Obsoleting block " + b);- obsolete.add(b);- }- }- return (Block[]) obsolete.toArray(new Block[obsolete.size()]);+ return null;}}@@ -1012,17 +1130,10 @@ public class FSNamesystem implements FSConstants {* target sequence for the Block at the appropriate index.**/- public synchronized Object[] pendingTransfers(DatanodeInfo srcNode, int maxXfers) {- //- // Allow the namenode to come up and hear from all datanodes before- // making transfers.- //- if (System.currentTimeMillis() - systemStart < SYSTEM_STARTUP_PERIOD) {- return null;- }-+ public synchronized Object[] pendingTransfers(DatanodeInfo srcNode, int xmitsInProgress) {synchronized (neededReplications) {Object results[] = null;+ int scheduledXfers = 0;if (neededReplications.size() > 0) {//@@ -1036,7 +1147,7 @@ public class FSNamesystem implements FSConstants {//// We can only reply with 'maxXfers' or fewer blocks//- if (replicateBlocks.size() >= maxXfers) {+ if (scheduledXfers >= MAX_REPLICATION_STREAMS - xmitsInProgress) {break;}@@ -1045,13 +1156,13 @@ public class FSNamesystem implements FSConstants {it.remove();} else {TreeSet containingNodes = (TreeSet) blocksMap.get(block);-if (containingNodes.contains(srcNode)) {- DatanodeInfo targets[] = chooseTargets(DESIRED_REPLICATION - containingNodes.size(), containingNodes);+ DatanodeInfo targets[] = chooseTargets(Math.min(DESIRED_REPLICATION - containingNodes.size(), MAX_REPLICATION_STREAMS - xmitsInProgress), containingNodes);if (targets.length > 0) {// Build items to returnreplicateBlocks.add(block);replicateTargetSets.add(targets);+ scheduledXfers += targets.length;}}}@@ -1059,9 +1170,9 @@ public class FSNamesystem implements FSConstants {//// Move the block-replication into a "pending" state.- // REMIND - mjc - the reason we use 'pending' is so we can retry+ // The reason we use 'pending' is so we can retry// replications that fail after an appropriate amount of time.- // This is not yet implemented+ // (REMIND - mjc - this timer is not yet implemented.)//if (replicateBlocks.size() > 0) {int i = 0;@@ -1074,13 +1185,14 @@ public class FSNamesystem implements FSConstants {neededReplications.remove(block);pendingReplications.add(block);}++ LOG.info("Pending transfer (block " + block.getBlockName() + ") from " + srcNode.getName() + " to " + targets.length + " destinations");}//// Build returned objects from above lists//DatanodeInfo targetMatrix[][] = new DatanodeInfo[replicateTargetSets.size()][];- LOG.info("Pending transfer from " + srcNode.getName() + " to " + targetMatrix.length + " destinations");for (i = 0; i < targetMatrix.length; i++) {targetMatrix[i] = (DatanodeInfo[]) replicateTargetSets.elementAt(i);}@@ -1094,10 +1206,13 @@ public class FSNamesystem implements FSConstants {}}-/**- * Get a certain number of targets, if possible. If not,- * return as many as we can.+ * Get a certain number of targets, if possible.+ * If not, return as many as we can.+ * @param desiredReplicates number of duplicates wanted.+ * @param forbiddenNodes of DatanodeInfo instances that should not be+ * considered targets.+ * @return array of DatanodeInfo instances uses as targets.*/DatanodeInfo[] chooseTargets(int desiredReplicates, TreeSet forbiddenNodes) {TreeSet alreadyChosen = new TreeSet();@@ -1109,7 +1224,7 @@ public class FSNamesystem implements FSConstants {targets.add(target);alreadyChosen.add(target);} else {- break;+ break; // calling chooseTarget again won't help}}return (DatanodeInfo[]) targets.toArray(new DatanodeInfo[targets.size()]);@@ -1122,90 +1237,99 @@ public class FSNamesystem implements FSConstants {* Right now it chooses randomly from available boxes. In future could* choose according to capacity and load-balancing needs (or even* network-topology, to avoid inter-switch traffic).+ * @param forbidden1 DatanodeInfo targets not allowed, null allowed.+ * @param forbidden2 DatanodeInfo targets not allowed, null allowed.+ * @return DatanodeInfo instance to use or null if something went wrong+ * (a log message is emitted if null is returned).*/- DatanodeInfo chooseTarget(TreeSet alreadyHasNode, TreeSet alreadyChosen) {+ DatanodeInfo chooseTarget(TreeSet forbidden1, TreeSet forbidden2) {+ //+ // Check if there are any available targets at all+ //int totalMachines = datanodeMap.size();if (totalMachines == 0) {+ LOG.warning("While choosing target, totalMachines is " + totalMachines);return null;}- int freeMachines = totalMachines;- for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) {- DatanodeInfo node = (DatanodeInfo) it.next();- if ((alreadyHasNode != null && alreadyHasNode.contains(node)) ||- (alreadyChosen != null && alreadyChosen.contains(node))) {- freeMachines--;++ TreeSet forbiddenMachines = new TreeSet();+ //+ // In addition to already-chosen datanode/port pairs, we want to avoid+ // already-chosen machinenames. (There can be multiple datanodes per+ // machine.) We might relax this requirement in the future, though. (Maybe+ // so that at least one replicate is off the machine.)+ //+ UTF8 hostOrHostAndPort = null;+ if (forbidden1 != null) {+ // add name [and host] of all elements in forbidden1 to forbiddenMachines+ for (Iterator it = forbidden1.iterator(); it.hasNext(); ) {+ DatanodeInfo cur = (DatanodeInfo) it.next();+ if (allowSameHostTargets) {+ hostOrHostAndPort = cur.getName(); // forbid same host:port+ } else {+ hostOrHostAndPort = cur.getHost(); // forbid same host+ }+ forbiddenMachines.add(hostOrHostAndPort);+ }+ }+ if (forbidden2 != null) {+ // add name [and host] of all elements in forbidden2 to forbiddenMachines+ for (Iterator it = forbidden2.iterator(); it.hasNext(); ) {+ DatanodeInfo cur = (DatanodeInfo) it.next();+ if (allowSameHostTargets) {+ hostOrHostAndPort = cur.getName(); // forbid same host:port+ } else {+ hostOrHostAndPort = cur.getHost(); // forbid same host+ }+ forbiddenMachines.add(hostOrHostAndPort);}}//- // Now pick one+ // Now build list of machines we can actually choose from//- DatanodeInfo target = null;- if (freeMachines > 0) {- //- // Get all possible targets- //- int i = 0;- DatanodeInfo targetlist[] = new DatanodeInfo[totalMachines];- for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); i++) {- targetlist[i] = (DatanodeInfo) it.next();+ long totalRemaining = 0;+ Vector targetList = new Vector();+ for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) {+ DatanodeInfo node = (DatanodeInfo) it.next();+ if (allowSameHostTargets) {+ hostOrHostAndPort = node.getName(); // match host:port+ } else {+ hostOrHostAndPort = node.getHost(); // match host+ }+ if (! forbiddenMachines.contains(hostOrHostAndPort)) {+ targetList.add(node);+ totalRemaining += node.getRemaining();}-- do {- int index = r.nextInt(totalMachines);- target = targetlist[index];-- if ((alreadyHasNode != null && alreadyHasNode.contains(target)) ||- (alreadyChosen != null && alreadyChosen.contains(target))) {- target = null;- }- } while (target == null);}- return target;- /**- * Choose target weighted by available storage- */- /**- synchronized (datanodeMap) {- if (datanodeMap.size() == 0) {- return;- }+ //+ // Now pick one+ //+ if (targetList.size() == 0) {+ LOG.warning("Zero targets found, forbidden1.size=" ++ ( forbidden1 != null ? forbidden1.size() : 0 ) ++ " allowSameHostTargets=" + allowSameHostTargets ++ " forbidden2.size()=" ++ ( forbidden2 != null ? forbidden2.size() : 0 ));+ return null;+ } else if (! USE_AVAILABILITY) {+ int target = r.nextInt(targetList.size());+ return (DatanodeInfo) targetList.elementAt(target);+ } else {+ // Choose node according to target capacity+ double target = r.nextDouble() * totalRemaining;- long totalRemaining = 0;- Vector okTargets = new Vector();- for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) {+ for (Iterator it = targetList.iterator(); it.hasNext(); ) {DatanodeInfo node = (DatanodeInfo) it.next();- if ((alreadyHasNode == null || ! alreadyHasNode.contains(node)) &&- (alreadyChosen == null || ! alreadyChosen.contains(node))) {- okTargets.add(node);- totalRemaining += node.getRemaining();+ target -= node.getRemaining();+ if (target <= 0) {+ return node;}}- //- // Now pick one- //- DatanodeInfo target = null;- if (okTargets.size() > 0) {- //- // Repeatedly choose random byte of the total bytes free.- // The machine that has that byte will be our target. Thus,- // we select at random with bias toward machines with greater- // available storage.- //- long targetByte = r.nextLong(totalRemaining);- for (Iterator it = okTargets.iterator(); it.hasNext(); ) {- DatanodeInfo node = (DatanodeInfO) it.next();- targetByte -= node.getRemaining();- if (targetByte <= 0) {- target = node;- break;- }- }- }- return target;+ LOG.warning("Impossible state. When trying to choose target node, could not find any. This may indicate that datanode capacities are being updated during datanode selection. Anyway, now returning an arbitrary target to recover...");+ return (DatanodeInfo) targetList.elementAt(r.nextInt(targetList.size()));}- **/}}diff --git a/src/java/org/apache/nutch/ndfs/FSParam.java b/src/java/org/apache/nutch/ndfs/FSParam.javadeleted file mode 100644index 3a30bced7..000000000--- a/src/java/org/apache/nutch/ndfs/FSParam.java+++ /dev/null@@ -1,180 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;--/******************************************************- * IPC param- *- * @author Mike Cafarella- ******************************************************/-public class FSParam implements Writable, FSConstants {- public byte op;- public Writable first;- public Writable second;-- public FSParam() {- this((byte) 0, NullWritable.get(), NullWritable.get());- }-- /**- */- public FSParam(byte op) {- this(op, NullWritable.get(), NullWritable.get());- }-- /**- */- FSParam(byte op, Writable first) {- this(op, first, NullWritable.get());- }-- /**- */- FSParam(byte op, Writable first, Writable second) {- this.op = op;- this.first = first;- this.second = second;- }-- /**- */- public void write(DataOutput out) throws IOException {- out.writeByte(op);- first.write(out);- second.write(out);- }-- /**- * Deserialize the opcode and the args- */- public void readFields(DataInput in) throws IOException {- op = in.readByte();-- switch (op) {- //- // Datanode calls- //- case OP_HEARTBEAT: {- first = new HeartbeatData();- break;- }- case OP_BLOCKREPORT: {- first = new ArrayWritable(Block.class);- second = new UTF8();- break;- }- case OP_BLOCKRECEIVED: {- first = new ArrayWritable(Block.class);- second = new UTF8();- break;- }- case OP_ERROR: {- first = new UTF8();- second = new UTF8();- break;- }-- //- // Client calls- //- case OP_CLIENT_OPEN: {- first = new UTF8();- break;- }- case OP_CLIENT_STARTFILE: {- first = new ArrayWritable(UTF8.class);- second = new BooleanWritable();- break;- }- case OP_CLIENT_ADDBLOCK: {- first = new UTF8();- break;- }- case OP_CLIENT_COMPLETEFILE: {- first = new ArrayWritable(UTF8.class);- break;- }- case OP_CLIENT_DATANODE_HINTS: {- first = new UTF8();- second = new LongWritable();- break;- }- case OP_CLIENT_RENAMETO: {- first = new UTF8();- second = new UTF8();- break;- }- case OP_CLIENT_DELETE: {- first = new UTF8();- break;- }- case OP_CLIENT_EXISTS: {- first = new UTF8();- break;- }- case OP_CLIENT_ISDIR: {- first = new UTF8();- break;- }- case OP_CLIENT_MKDIRS: {- first = new UTF8();- break;- }- case OP_CLIENT_RENEW_LEASE: {- first = new UTF8();- break;- }- case OP_CLIENT_OBTAINLOCK: {- first = new ArrayWritable(UTF8.class);- second = new BooleanWritable();- break;- }- case OP_CLIENT_RELEASELOCK: {- first = new ArrayWritable(UTF8.class);- break;- }- case OP_CLIENT_LISTING: {- first = new UTF8();- break;- }- case OP_CLIENT_ABANDONBLOCK: {- first = new Block();- second = new UTF8();- break;- }- case OP_CLIENT_RAWSTATS: {- break;- }- case OP_CLIENT_DATANODEREPORT: {- break;- }- default: {- throw new IOException("Unknown opcode: " + op);- }- }-- first.readFields(in);- second.readFields(in);- }-}diff --git a/src/java/org/apache/nutch/ndfs/FSResults.java b/src/java/org/apache/nutch/ndfs/FSResults.javadeleted file mode 100644index ed3b0d0d1..000000000--- a/src/java/org/apache/nutch/ndfs/FSResults.java+++ /dev/null@@ -1,190 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;--/*****************************************************- * The result of an NFS IPC call.- *- * @author Mike Cafarella- *****************************************************/-public class FSResults implements Writable, FSConstants {- public byte op;- public Writable first;- public Writable second;- boolean success = false;- boolean tryagain = false;-- /**- */- public FSResults() {- this((byte) 0, NullWritable.get(), NullWritable.get());- }- public FSResults(byte op) {- this(op, NullWritable.get(), NullWritable.get());- }- public FSResults(byte op, Writable first) {- this(op, first, NullWritable.get());- }-- /**- */- public FSResults(byte op, Writable first, Writable second) {- this.op = op;- this.first = first;- this.second = second;- }-- /**- * Whether the call worked.- */- public boolean success() {- return success;- }-- /**- * Whether the client should give it another shot- */- public boolean tryagain() {- return tryagain;- }-- /**- */- public void write(DataOutput out) throws IOException {- out.writeByte(op);- first.write(out);- second.write(out);- }-- /**- */- public void readFields(DataInput in) throws IOException {- op = in.readByte();-- switch (op) {- //- // Issued to DataNodes- //- case OP_INVALIDATE_BLOCKS: {- success = true;- first = new ArrayWritable(Block.class);- break;- }- case OP_TRANSFERBLOCKS: {- success = true;- first = new ArrayWritable(Block.class);- second = new TwoDArrayWritable(DatanodeInfo.class);- break;- }- case OP_ACK: {- success = true;- break;- }-- //- // Client operations- //- case OP_CLIENT_OPEN_ACK: {- success = true;- first = new ArrayWritable(Block.class);- second = new TwoDArrayWritable(DatanodeInfo.class);- break;- }- case OP_CLIENT_STARTFILE_ACK:- case OP_CLIENT_ADDBLOCK_ACK: {- success = true;- first = new Block();- second = new ArrayWritable(DatanodeInfo.class);- break;- }- case OP_CLIENT_COMPLETEFILE_ACK: {- success = true;- break;- }- case OP_CLIENT_DATANODE_HINTS_ACK: {- success = true;- first = new ArrayWritable(UTF8.class);- break;- }- case OP_CLIENT_RENAMETO_ACK:- case OP_CLIENT_DELETE_ACK: {- success = true;- break;- }- case OP_CLIENT_LISTING_ACK: {- success = true;- first = new ArrayWritable(NDFSFileInfo.class);- break;- }- case OP_CLIENT_OBTAINLOCK_ACK: {- success = true;- break;- }- case OP_CLIENT_RELEASELOCK_ACK: {- success = true;- break;- }- case OP_CLIENT_EXISTS_ACK:- case OP_CLIENT_ISDIR_ACK:- case OP_CLIENT_MKDIRS_ACK: {- success = true;- break;- }- case OP_CLIENT_RENEW_LEASE_ACK: {- success = true;- break;- }- case OP_CLIENT_ABANDONBLOCK_ACK: {- success = true;- break;- }- case OP_CLIENT_RAWSTATS_ACK: {- success = true;- first = new ArrayWritable(LongWritable.class);- break;- }- case OP_CLIENT_DATANODEREPORT_ACK: {- success = true;- first = new ArrayWritable(DatanodeInfo.class);- break;- }- case OP_CLIENT_TRYAGAIN: {- success = true;- tryagain = true;- break;- }- case OP_FAILURE: {- success = false;- break;- }- default: {- throw new IOException("Unknown opcode: " + op);- }- }-- first.readFields(in);- second.readFields(in);- }-}-diff --git a/src/java/org/apache/nutch/ndfs/HeartbeatData.java b/src/java/org/apache/nutch/ndfs/HeartbeatData.javadeleted file mode 100644index 8eba66e19..000000000--- a/src/java/org/apache/nutch/ndfs/HeartbeatData.java+++ /dev/null@@ -1,75 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;--/********************************************************- * Heartbeat data- *- * @author Mike Cafarella- ********************************************************/-public class HeartbeatData implements Writable, FSConstants {- UTF8 name;- long capacity, remaining;-- /**- */- public HeartbeatData() {- this.name = new UTF8();- }-- /**- */- public HeartbeatData(String name, long capacity, long remaining) {- this.name = new UTF8(name);- this.capacity = capacity;- this.remaining = remaining;- }-- /**- */- public void write(DataOutput out) throws IOException {- name.write(out);- out.writeLong(capacity);- out.writeLong(remaining);- }-- /**- */- public void readFields(DataInput in) throws IOException {- this.name = new UTF8();- name.readFields(in);- this.capacity = in.readLong();- this.remaining = in.readLong();- }-- public UTF8 getName() {- return name;- }- public long getCapacity() {- return capacity;- }- public long getRemaining() {- return remaining;- }-}diff --git a/src/java/org/apache/nutch/ndfs/LocatedBlock.java b/src/java/org/apache/nutch/ndfs/LocatedBlock.javanew file mode 100644index 000000000..7c16f988c--- /dev/null+++ b/src/java/org/apache/nutch/ndfs/LocatedBlock.java@@ -0,0 +1,79 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import org.apache.nutch.io.*;++import java.io.*;++/****************************************************+ * A LocatedBlock is a pair of Block, DatanodeInfo[]+ * objects. It tells where to find a Block.+ *+ * @author Michael Cafarella+ ****************************************************/+public class LocatedBlock implements Writable {+ Block b;+ DatanodeInfo locs[];++ /**+ */+ public LocatedBlock() {+ this.b = new Block();+ this.locs = new DatanodeInfo[0];+ }++ /**+ */+ public LocatedBlock(Block b, DatanodeInfo[] locs) {+ this.b = b;+ this.locs = locs;+ }++ /**+ */+ public Block getBlock() {+ return b;+ }++ /**+ */+ DatanodeInfo[] getLocations() {+ return locs;+ }++ ///////////////////////////////////////////+ // Writable+ ///////////////////////////////////////////+ public void write(DataOutput out) throws IOException {+ b.write(out);+ out.writeInt(locs.length);+ for (int i = 0; i < locs.length; i++) {+ locs[i].write(out);+ }+ }++ public void readFields(DataInput in) throws IOException {+ this.b = new Block();+ b.readFields(in);+ int count = in.readInt();+ this.locs = new DatanodeInfo[count];+ for (int i = 0; i < locs.length; i++) {+ locs[i] = new DatanodeInfo();+ locs[i].readFields(in);+ }+ }+}diff --git a/src/java/org/apache/nutch/ndfs/NDFS.java b/src/java/org/apache/nutch/ndfs/NDFS.javadeleted file mode 100644index 6ca1e500a..000000000--- a/src/java/org/apache/nutch/ndfs/NDFS.java+++ /dev/null@@ -1,933 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/********************************************************- * The NDFS class holds the NDFS client and server.- *- * @author Mike Cafarella- ********************************************************/-public class NDFS implements FSConstants {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.fs.NDFS");- //- // REMIND - mjc - I might bring "maxgigs" back so user can place- // artificial limit on space- //private static final long GIGABYTE = 1024 * 1024 * 1024;- //private static long numGigs = NutchConf.get().getLong("ndfs.datanode.maxgigs", 100);- //-- //- // Eventually, this constant should be computed dynamically using- // load information- //- private static final int MAX_BLOCKS_PER_ROUNDTRIP = 3;-- /**- * Util method to build socket addr from string- */- public static InetSocketAddress createSocketAddr(String s) throws IOException {- String target = s;- int colonIndex = target.indexOf(':');- if (colonIndex < 0) {- throw new RuntimeException("Not a host:port pair: " + s);- }- String host = target.substring(0, colonIndex);- int port = Integer.parseInt(target.substring(colonIndex + 1));-- return new InetSocketAddress(host, port);- }-- /**- * This class isn't for the outside world- */- private NDFS() {- }-- ////////////////////////////////////////////////////////////////- //- // NameNode- //- ////////////////////////////////////////////////////////////////-- /**********************************************************- * NameNode controls two critical tables:- * 1) filename->blocksequence,version- * 2) block->machinelist- *- * The first table is stored on disk and is very precious.- * The second table is rebuilt every time the NameNode comes- * up.- *- * @author Mike Cafarella- **********************************************************/- public static class NameNode extends org.apache.nutch.ipc.Server {- FSNamesystem namesystem;-- /**- * Create a NameNode at the default location- */- public NameNode() throws IOException {- this(new File(NutchConf.get().get("ndfs.name.dir",- "/tmp/nutch/ndfs/name")),- createSocketAddr- (NutchConf.get().get("fs.default.name", "local")).getPort());- }-- /**- * Create a NameNode at the specified location- */- public NameNode(File dir, int port) throws IOException {- super(port, FSParam.class, 10);- this.namesystem = new FSNamesystem(dir);- }-- /**- * This method implements the call invoked by client.- * Return a Writable as the function return value.- */- public Writable call(Writable param) throws IOException {- FSParam p = (FSParam) param;- FSResults r = null;-- switch (p.op) {- //- // Client methods- //- case OP_CLIENT_OPEN: {- UTF8 src = (UTF8) p.first;- Object results[] = namesystem.open(src);- if (results != null) {- Block blocks[] = (Block[]) results[0];- DatanodeInfo sets[][] = (DatanodeInfo[][]) results[1];- r = new FSResults(OP_CLIENT_OPEN_ACK, new ArrayWritable(Block.class, blocks), new TwoDArrayWritable(DatanodeInfo.class, sets));- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_STARTFILE: {- UTF8 nameParams[] = (UTF8[]) ((ArrayWritable) p.first).toArray();- UTF8 src = nameParams[0];- UTF8 clientName = nameParams[1];- boolean overwrite = ((BooleanWritable) p.second).get();- Object results[] = namesystem.startFile(src, clientName, overwrite);- if (results != null) {- Block b = (Block) results[0];- DatanodeInfo targets[] = (DatanodeInfo[]) results[1];- r = new FSResults(OP_CLIENT_STARTFILE_ACK, b, new ArrayWritable(DatanodeInfo.class, targets));- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_ADDBLOCK: {- UTF8 src = (UTF8) p.first;- Object results[] = namesystem.getAdditionalBlock(src);- if (results != null && results[0] == null) {- try {- Thread.sleep(50);- } catch (InterruptedException ie) {- }- results = namesystem.getAdditionalBlock(src);- }-- if (results != null) {- if (results[0] != null) {- Block b = (Block) results[0];- DatanodeInfo targets[] = (DatanodeInfo[]) results[1];- r = new FSResults(OP_CLIENT_ADDBLOCK_ACK, b, new ArrayWritable(DatanodeInfo.class, targets));- } else {- r = new FSResults(OP_CLIENT_TRYAGAIN);- }- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_ABANDONBLOCK: {- Block b = (Block) p.first;- UTF8 src = (UTF8) p.second;- boolean success = namesystem.abandonBlock(b, src);- if (success) {- r = new FSResults(OP_CLIENT_ABANDONBLOCK_ACK);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_COMPLETEFILE: {- UTF8 nameParams[] = (UTF8[]) ((ArrayWritable) p.first).toArray();- UTF8 src = nameParams[0];- UTF8 clientName = nameParams[1];- int returnCode = namesystem.completeFile(src, clientName);- if (returnCode == COMPLETE_SUCCESS) {- r = new FSResults(OP_CLIENT_COMPLETEFILE_ACK);- } else if (returnCode == STILL_WAITING) {- r = new FSResults(OP_CLIENT_TRYAGAIN);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_DATANODE_HINTS: {- UTF8 src = (UTF8) p.first;- long offset = ((LongWritable) p.second).get();- UTF8 hosts[] = namesystem.getDatanodeHints(src, offset);- if (hosts != null) {- r = new FSResults(OP_CLIENT_DATANODE_HINTS_ACK, new ArrayWritable(UTF8.class, hosts));- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_RENAMETO: {- UTF8 src = (UTF8) p.first;- UTF8 dst = (UTF8) p.second;- boolean success = namesystem.renameTo(src, dst);- if (success) {- r = new FSResults(OP_CLIENT_RENAMETO_ACK);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_DELETE: {- UTF8 src = (UTF8) p.first;- boolean success = namesystem.delete(src);- if (success) {- r = new FSResults(OP_CLIENT_DELETE_ACK);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_EXISTS: {- UTF8 src = (UTF8) p.first;- boolean success = namesystem.exists(src);- if (success) {- r = new FSResults(OP_CLIENT_EXISTS_ACK);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_ISDIR: {- UTF8 src = (UTF8) p.first;- boolean success = namesystem.isDir(src);- if (success) {- r = new FSResults(OP_CLIENT_ISDIR_ACK);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_MKDIRS: {- UTF8 src = (UTF8) p.first;- boolean success = namesystem.mkdirs(src);- if (success) {- r = new FSResults(OP_CLIENT_MKDIRS_ACK);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_OBTAINLOCK: {- UTF8 nameParams[] = (UTF8[]) ((ArrayWritable) p.first).toArray();- UTF8 src = nameParams[0];- UTF8 clientName = nameParams[1];- boolean exclusive = ((BooleanWritable) p.second).get();- int returnCode = namesystem.obtainLock(src, clientName, exclusive);- if (returnCode == COMPLETE_SUCCESS) {- r = new FSResults(OP_CLIENT_OBTAINLOCK_ACK);- } else if (returnCode == STILL_WAITING) {- r = new FSResults(OP_CLIENT_TRYAGAIN);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_RELEASELOCK: {- UTF8 nameParams[] = (UTF8[]) ((ArrayWritable) p.first).toArray();- UTF8 src = nameParams[0];- UTF8 clientName = nameParams[1];- int returnCode = namesystem.releaseLock(src, clientName);- if (returnCode == COMPLETE_SUCCESS) {- r = new FSResults(OP_CLIENT_COMPLETEFILE_ACK);- } else if (returnCode == STILL_WAITING) {- r = new FSResults(OP_CLIENT_TRYAGAIN);- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_RENEW_LEASE: {- UTF8 clientName = (UTF8) p.first;- namesystem.renewLease(clientName);- r = new FSResults(OP_CLIENT_RENEW_LEASE_ACK);- break;- }- case OP_CLIENT_LISTING: {- UTF8 src = (UTF8) p.first;- NDFSFileInfo results[] = namesystem.getListing(src);- if (results != null) {- r = new FSResults(OP_CLIENT_LISTING_ACK, new ArrayWritable(NDFSFileInfo.class, results));- } else {- r = new FSResults(OP_FAILURE);- }- break;- }- case OP_CLIENT_RAWSTATS: {- long totalRaw = namesystem.totalCapacity();- long remainingRaw = namesystem.totalRemaining();- LongWritable results[] = new LongWritable[2];- results[0] = new LongWritable(totalRaw);- results[1] = new LongWritable(totalRaw - remainingRaw);- r = new FSResults(OP_CLIENT_RAWSTATS_ACK, new ArrayWritable(LongWritable.class, results));- break;- }- case OP_CLIENT_DATANODEREPORT: {- DatanodeInfo report[] = namesystem.datanodeReport();- if (report != null) {- r = new FSResults(OP_CLIENT_DATANODEREPORT_ACK, new ArrayWritable(DatanodeInfo.class, report));- } else {- r = new FSResults(OP_FAILURE);- }- break;- }-- //- // Datanode methods- //- case OP_HEARTBEAT:- case OP_BLOCKREPORT:- case OP_BLOCKRECEIVED:- case OP_ERROR: {- UTF8 sender = null;- if (p.op == OP_HEARTBEAT) {- // Receive heartbeat, update last-seen info- HeartbeatData hd = (HeartbeatData) p.first;- sender = hd.getName();- namesystem.gotHeartbeat(sender, hd.getCapacity(), hd.getRemaining());-- } else if (p.op == OP_BLOCKREPORT) {- // Receive report on blocks stored at datanode- Block blocks[] = (Block[]) ((ArrayWritable) p.first).toArray();- sender = (UTF8) p.second;- namesystem.processReport(blocks, sender);-- } else if (p.op == OP_BLOCKRECEIVED) {- // Receive info on block that's just been received by datanode- Writable blocks[] = ((ArrayWritable) p.first).get();- sender = (UTF8) p.second;- for (int i = 0; i < blocks.length; i++) {- namesystem.blockReceived((Block) blocks[i], sender);- }- } else {- // Got an error report from datanode- System.err.println("ERR from datanode! Op = " + p.op);- sender = (UTF8) p.first;- System.err.println("Datanode: " + sender);- System.err.println("Message: " + ((UTF8) p.second));- }-- //- // Compute return message- //- Object xferResults[] = namesystem.pendingTransfers(new DatanodeInfo(sender), MAX_BLOCKS_PER_ROUNDTRIP);- if (xferResults != null) {- r = new FSResults(OP_TRANSFERBLOCKS, new ArrayWritable(Block.class, (Block[]) xferResults[0]), new TwoDArrayWritable(DatanodeInfo.class, (DatanodeInfo[][]) xferResults[1]));- } else {- Block blocks[] = namesystem.recentlyInvalidBlocks(sender);- if (blocks == null) {- blocks = namesystem.checkObsoleteBlocks(sender);- }- if (blocks != null) {- r = new FSResults(OP_INVALIDATE_BLOCKS, new ArrayWritable(Block.class, blocks));- } else {- r = new FSResults(OP_ACK);- }- }- break;- }- default:- throw new RuntimeException("Unknown op code: " + p.op);- }- return r;- }-- /**- */- public static void main(String argv[]) throws IOException, InterruptedException {- NameNode namenode = new NameNode();- namenode.start();- namenode.join();- }- }-- ////////////////////////////////////////////////////////////////- //- // DataNode- //- ////////////////////////////////////////////////////////////////-- /**********************************************************- * DataNode controls just one critical table:- * block-> BLOCK_SIZE stream of bytes- *- * This info is stored on disk (the NameNode is responsible for- * asking other machines to replicate the data). The DataNode- * reports the table's contents to the NameNode upon startup- * and every so often afterwards.- *- * @author Mike Cafarella- **********************************************************/- public static class DataNode extends org.apache.nutch.ipc.Client {- FSDataset data;- String localName;- InetSocketAddress nameNodeAddr;-- Vector receivedBlockList = new Vector();-- /**- * Create using configured defaults and dataDir.- */- public DataNode(String dataDir) throws IOException {- this(InetAddress.getLocalHost().getHostName(), new File(dataDir),- createSocketAddr(NutchConf.get().get("fs.default.name",- "local")));- }-- /**- * Needs a directory to find its data (and config info)- */- public DataNode(String machineName, File dir, InetSocketAddress nameNodeAddr) throws IOException {- super(FSResults.class);- this.data = new FSDataset(dir);- this.nameNodeAddr = nameNodeAddr;-- ServerSocket ss = null;- int tmpPort = 7000;- while (ss == null) {- try {- ss = new ServerSocket(tmpPort);- LOG.info("Opened server at " + tmpPort);- } catch (IOException ie) {- LOG.info("Could not open server at " + tmpPort + ", trying new port");- tmpPort++;- }- }- this.localName = machineName + ":" + tmpPort;- new Daemon(new DataXceiveServer(ss)).start();- }-- /**- * Main loop for the DataNode. Runs until shutdown.- */- public void offerService() throws Exception {- long wakeups = 0;- long lastHeartbeat = 0, lastBlockReport = 0;- long sendStart = System.currentTimeMillis();- int heartbeatsSent = 0;-- //- // Now loop for a long time....- //- boolean shouldRun = true;- while (shouldRun) {- long now = System.currentTimeMillis();-- //- // Every so often, send heartbeat or block-report- //- FSParam p = null;- FSResults r = null;-- synchronized (receivedBlockList) {- if (now - lastHeartbeat > HEARTBEAT_INTERVAL) {- //- // All heartbeat messages include following info:- // -- Datanode name- // -- data transfer port- // -- Total capacity- // -- Bytes remaining- //- p = new FSParam(OP_HEARTBEAT, new HeartbeatData(localName, data.getCapacity(), data.getRemaining()));- lastHeartbeat = now;- } else if (now - lastBlockReport > BLOCKREPORT_INTERVAL) {- //- // Send latest blockinfo report if timer has expired- //- p = new FSParam(OP_BLOCKREPORT, new ArrayWritable(Block.class, data.getBlockReport()), new UTF8(localName));- lastBlockReport = now;- } else if (receivedBlockList.size() > 0) {- //- // Send newly-received blockids to namenode- //- Block blockArray[] = null;- blockArray = (Block[]) receivedBlockList.toArray(new Block[receivedBlockList.size()]);- receivedBlockList.removeAllElements();- p = new FSParam(OP_BLOCKRECEIVED, new ArrayWritable(Block.class, blockArray), new UTF8(localName));- } else {- //- // Nothing to do; sleep (until time elapses, or work arrives)- // and continue work- //- long waitTime = HEARTBEAT_INTERVAL - (now - lastHeartbeat);- if (waitTime > 0) {- try {- receivedBlockList.wait(waitTime);- } catch (InterruptedException ie) {- }- }- continue;- }- }-- //- // Invoke remote call- //- r = (FSResults) call(p, nameNodeAddr);- if (r == null) {- throw new IOException("No response to remote call to " + nameNodeAddr);- }-- //- // Respond to namenode's reply- //- // REMIND - mjc - Right now the Datanode can only get- // requests from the Namenode via a response to HEARTBEAT- // or BLOCKREPORT. That's not so hot, as it means the- // Namenode will have to wait for HEARTBEAT_INTERVAL before- // it can make a request on the Datanode.- //- // The advantage of this system is that it's very simple.- // We'll fix it later on.- //- switch (r.op) {- case OP_ACK: {- //- // The nameserver just acked our call, and didn't- // want anything else.- //- break;- }- case OP_TRANSFERBLOCKS: {- //- // Send a copy of the indicated block to another- // datanode- //- Block blocks[] = (Block[]) ((ArrayWritable) r.first).toArray();- DatanodeInfo xferTargets[][] = (DatanodeInfo[][]) ((TwoDArrayWritable) r.second).toArray();- for (int i = 0; i < blocks.length; i++) {- if (!data.isValidBlock(blocks[i])) {- System.out.println("Invoking error! " + localName);- call(new FSParam(OP_ERROR, new UTF8(localName), new UTF8("Can't send invalid block " + blocks[i])), nameNodeAddr);- break;- } else {- if (xferTargets[i].length > 0) {- LOG.info("Starting thread to transfer block " + blocks[i] + " to " + xferTargets[i]);- new Daemon(new DataTransfer(xferTargets[i], blocks[i])).start();- }- }- }- break;- }- case OP_INVALIDATE_BLOCKS: {- //- // Some local block(s) are obsolete and can be- // safely garbage-collected.- //- ArrayWritable aw = (ArrayWritable) r.first;- Block b[] = (Block[]) aw.toArray();- data.invalidate(b);- break;- }- default:- throw new RuntimeException("Unknown op code: " + r.op);- }- }- }-- /**- * Server used for receiving/sending a block of data- */- class DataXceiveServer implements Runnable {- ServerSocket ss;- public DataXceiveServer(ServerSocket ss) {- this.ss = ss;- }-- /**- */- public void run() {- try {- while (true) {- Socket s = ss.accept();- new Daemon(new DataXceiver(s)).start();- }- } catch (IOException ie) {- LOG.info("Exiting DataXceiveServer due to " + ie.toString());- }- }- }-- /**- * Thread for processing incoming/outgoing data stream- */- class DataXceiver implements Runnable {- Socket s;- public DataXceiver(Socket s) {- this.s = s;- }-- /**- */- public void run() {- try {- DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));- try {- byte op = (byte) in.read();- if (op == OP_WRITE_BLOCK) {- //- // Read in the header- //- DataOutputStream reply = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- try {- Block b = new Block();- b.readFields(in);- int numTargets = in.readInt();- if (numTargets <= 0) {- throw new IOException("Mislabelled incoming datastream.");- }- DatanodeInfo targets[] = new DatanodeInfo[numTargets];- for (int i = 0; i < targets.length; i++) {- DatanodeInfo tmp = new DatanodeInfo();- tmp.readFields(in);- targets[i] = tmp;- }- byte encodingType = (byte) in.read();- long len = in.readLong();-- //- // Make sure curTarget is equal to this machine- // REMIND - mjc- //- DatanodeInfo curTarget = targets[0];-- //- // Open local disk out- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(data.writeToBlock(b)));- InetSocketAddress mirrorTarget = null;- try {- //- // Open network conn to backup machine, if- // appropriate- //- DataInputStream in2 = null;- DataOutputStream out2 = null;- if (targets.length > 1) {- // Connect to backup machine- mirrorTarget = createSocketAddr(targets[1].getName().toString());- try {- Socket s = new Socket(mirrorTarget.getAddress(), mirrorTarget.getPort());- out2 = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- in2 = new DataInputStream(new BufferedInputStream(s.getInputStream()));-- // Write connection header- out2.write(OP_WRITE_BLOCK);- b.write(out2);- out2.writeInt(targets.length - 1);- for (int i = 1; i < targets.length; i++) {- targets[i].write(out2);- }- out2.write(encodingType);- out2.writeLong(len);- } catch (IOException ie) {- if (out2 != null) {- try {- out2.close();- in2.close();- } catch (IOException out2close) {- } finally {- out2 = null;- in2 = null;- }- }- }- }-- //- // Process incoming data, copy to disk and- // maybe to network.- //- try {- boolean anotherChunk = true;- byte buf[] = new byte[2048];-- while (anotherChunk) {- while (len > 0) {- int bytesRead = in.read(buf, 0, Math.min(buf.length, (int) len));- if (bytesRead >= 0) {- out.write(buf, 0, bytesRead);- if (out2 != null) {- try {- out2.write(buf, 0, bytesRead);- } catch (IOException out2e) {- //- // If stream-copy fails, continue- // writing to disk. We shouldn't- // interrupt client write.- //- try {- out2.close();- in2.close();- } catch (IOException out2close) {- } finally {- out2 = null;- in2 = null;- }- }- }- }- len -= bytesRead;- }-- if (encodingType == RUNLENGTH_ENCODING) {- anotherChunk = false;- } else if (encodingType == CHUNKED_ENCODING) {- len = in.readLong();- if (out2 != null) {- out2.writeLong(len);- }- if (len == 0) {- anotherChunk = false;- }- }- }-- if (out2 == null) {- LOG.info("Received block " + b + " from " + s.getInetAddress());- } else {- out2.flush();- long complete = in2.readLong();- if (complete != WRITE_COMPLETE) {- LOG.info("Conflicting value for WRITE_COMPLETE: " + complete);- }- LOG.info("Received block " + b + " from " + s.getInetAddress() + " and mirrored to " + mirrorTarget);- }- } finally {- if (out2 != null) {- out2.close();- in2.close();- }- }- } finally {- out.close();- }- data.finalizeBlock(b);-- //- // Tell the namenode that we've received this block- // in full.- //- synchronized (receivedBlockList) {- receivedBlockList.add(b);- receivedBlockList.notifyAll();- }-- //- // Tell client job is done- //- reply.writeLong(WRITE_COMPLETE);- } finally {- reply.close();- }- } else if (op == OP_READ_BLOCK || op == OP_READSKIP_BLOCK) {- //- // Read in the header- //- Block b = new Block();- b.readFields(in);-- long toSkip = 0;- if (op == OP_READSKIP_BLOCK) {- toSkip = in.readLong();- }-- //- // Open reply stream- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- try {- //- // Write filelen of -1 if error- //- if (! data.isValidBlock(b)) {- out.writeLong(-1);- } else {- //- // Get blockdata from disk- //- long len = data.getLength(b);- DataInputStream in2 = new DataInputStream(data.getBlockData(b));- out.writeLong(len);-- if (op == OP_READSKIP_BLOCK) {- if (toSkip > len) {- toSkip = len;- }- long amtSkipped = in2.skip(toSkip);- out.writeLong(amtSkipped);- }-- byte buf[] = new byte[4096];- try {- int bytesRead = in2.read(buf);- while (bytesRead >= 0) {- out.write(buf, 0, bytesRead);- len -= bytesRead;- bytesRead = in2.read(buf);- }- } catch (SocketException se) {- // This might be because the reader- // closed the stream early- } finally {- in2.close();- }- }- LOG.info("Served block " + b + " to " + s.getInetAddress());- } finally {- out.close();- }- } else {- while (op >= 0) {- System.out.println("Faulty op: " + op);- op = (byte) in.read();- }- throw new IOException("Unknown opcode for incoming data stream");- }- } finally {- in.close();- }- } catch (IOException ie) {- ie.printStackTrace();- } finally {- try {- s.close();- } catch (IOException ie2) {- }- }- }- }-- /**- * Used for transferring a block of data- */- class DataTransfer implements Runnable {- InetSocketAddress curTarget;- DatanodeInfo targets[];- Block b;- byte buf[];-- /**- * Connect to the first item in the target list. Pass along the- * entire target list, the block, and the data.- */- public DataTransfer(DatanodeInfo targets[], Block b) throws IOException {- this.curTarget = createSocketAddr(targets[0].getName().toString());- this.targets = targets;- this.b = b;- this.buf = new byte[2048];- }-- /**- * Do the deed, write the bytes- */- public void run() {- try {- Socket s = new Socket(curTarget.getAddress(), curTarget.getPort());- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- try {- long filelen = data.getLength(b);- DataInputStream in = new DataInputStream(new BufferedInputStream(data.getBlockData(b)));- try {- //- // Header info- //- out.write(OP_WRITE_BLOCK);- b.write(out);- out.writeInt(targets.length);- for (int i = 0; i < targets.length; i++) {- targets[i].write(out);- }- out.write(RUNLENGTH_ENCODING);- out.writeLong(filelen);-- //- // Write the data- //- while (filelen > 0) {- int bytesRead = in.read(buf, 0, (int) Math.min(filelen, buf.length));- out.write(buf, 0, bytesRead);- filelen -= bytesRead;- }- } finally {- in.close();- }- } finally {- out.close();- }- LOG.info("Replicated block " + b + " to " + curTarget);- } catch (IOException ie) {- }- }- }-- /**- */- public static void main(String argv[]) throws IOException {- String dataDir = NutchConf.get().get("ndfs.data.dir",- "/tmp/nutch/data/name");- if (argv.length > 0){- dataDir=argv[0];- }- LOG.info("Using ["+dataDir+"] directory for data storage.");-- DataNode datanode = new DataNode(dataDir);- while (true) {- try {- datanode.offerService();- } catch (Exception ex) {- LOG.info("Lost connection to namenode [" + datanode.nameNodeAddr + "]. Retrying...");- try {- Thread.sleep(5000);- } catch (InterruptedException ie) {- }- }- }- }- }-}diff --git a/src/java/org/apache/nutch/ndfs/NDFSClient.java b/src/java/org/apache/nutch/ndfs/NDFSClient.javaindex a5e9d79a3..670aa13c7 100644--- a/src/java/org/apache/nutch/ndfs/NDFSClient.java+++ b/src/java/org/apache/nutch/ndfs/NDFSClient.java@@ -26,26 +26,25 @@ import java.util.*;import java.util.logging.*;/********************************************************- * NDFSClient does what's necessary to connect to a Nutch Filesystem- * and perform basic file tasks.- *+ * NDFSClient can connect to a Nutch Filesystem and perform basic file tasks.+ * Connects to a namenode daemon.* @author Mike Cafarella, Tessa MacDuff********************************************************/public class NDFSClient implements FSConstants {public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.fs.NDFSClient");- static int BUFFER_SIZE = 4096;- NameNodeCaller nameNodeCaller;+ static int MAX_BLOCK_ACQUIRE_FAILURES = 10;+ ClientProtocol namenode;boolean running = true;Random r = new Random();- UTF8 clientName;+ String clientName;Daemon leaseChecker;- /**+ /** Create a new NDFSClient connected to the given namenode server.*/- public NDFSClient(InetSocketAddress namenode) {- this.nameNodeCaller = new NameNodeCaller(namenode);- this.clientName = new UTF8("NDFSClient_" + r.nextInt());+ public NDFSClient(InetSocketAddress nameNodeAddr) {+ this.namenode = (ClientProtocol) RPC.getProxy(ClientProtocol.class, nameNodeAddr);+ this.clientName = "NDFSClient_" + r.nextInt();this.leaseChecker = new Daemon(new LeaseChecker());this.leaseChecker.start();}@@ -53,7 +52,6 @@ public class NDFSClient implements FSConstants {/***/public void close() throws IOException {- //nameNodeCaller.stop();this.running = false;try {leaseChecker.join();@@ -61,6 +59,15 @@ public class NDFSClient implements FSConstants {}}+ /**+ * Get hints about the location of the indicated block(s). The+ * array returned is as long as there are blocks in the indicated+ * range. Each block may have one or more locations.+ */+ public String[][] getHints(UTF8 src, long start, long len) throws IOException {+ return namenode.getHints(src.toString(), start, len);+ }+/*** Create an input stream that obtains a nodelist from the* namenode, and then reads from all the right places. Creates@@ -69,18 +76,9 @@ public class NDFSClient implements FSConstants {*/public NFSInputStream open(UTF8 src) throws IOException {// Get block info from namenode- Object results[] = nameNodeCaller.getBlocksNodes(src);- return new NDFSInputStream((Block[]) results[0], (DatanodeInfo[][]) results[1]);+ return new NDFSInputStream(src.toString());}- /**- * Create an output stream that writes to all the right places.- * Basically creates instance of inner subclass of OutputStream- * that handles datanode/namenode negotiation.- */- public NFSOutputStream create(UTF8 src) throws IOException {- return create(src, false);- }public NFSOutputStream create(UTF8 src, boolean overwrite) throws IOException {return new NDFSOutputStream(src, overwrite);}@@ -90,7 +88,7 @@ public class NDFSClient implements FSConstants {* there.*/public boolean rename(UTF8 src, UTF8 dst) throws IOException {- return nameNodeCaller.rename(src, dst);+ return namenode.rename(src.toString(), dst.toString());}/**@@ -98,61 +96,86 @@ public class NDFSClient implements FSConstants {* there.*/public boolean delete(UTF8 src) throws IOException {- return nameNodeCaller.delete(src);+ return namenode.delete(src.toString());}/***/public boolean exists(UTF8 src) throws IOException {- return nameNodeCaller.exists(src);+ return namenode.exists(src.toString());}/***/public boolean isDirectory(UTF8 src) throws IOException {- return nameNodeCaller.isDirectory(src);+ return namenode.isDir(src.toString());}/***/public NDFSFileInfo[] listFiles(UTF8 src) throws IOException {- return nameNodeCaller.listing(src);+ return namenode.getListing(src.toString());}/***/public long totalRawCapacity() throws IOException {- long rawNums[] = nameNodeCaller.rawReport();+ long rawNums[] = namenode.getStats();return rawNums[0];}/***/public long totalRawUsed() throws IOException {- long rawNums[] = nameNodeCaller.rawReport();+ long rawNums[] = namenode.getStats();return rawNums[1];}public DatanodeInfo[] datanodeReport() throws IOException {- return nameNodeCaller.datanodeReport();+ return namenode.getDatanodeReport();}/***/public boolean mkdirs(UTF8 src) throws IOException {- return nameNodeCaller.mkdirs(src);+ return namenode.mkdirs(src.toString());}/***/public void lock(UTF8 src, boolean exclusive) throws IOException {- nameNodeCaller.lock(src, exclusive);+ long start = System.currentTimeMillis();+ boolean hasLock = false;+ while (! hasLock) {+ hasLock = namenode.obtainLock(src.toString(), clientName, exclusive);+ if (! hasLock) {+ try {+ Thread.sleep(400);+ if (System.currentTimeMillis() - start > 5000) {+ LOG.info("Waiting to retry lock for " + (System.currentTimeMillis() - start) + " ms.");+ Thread.sleep(2000);+ }+ } catch (InterruptedException ie) {+ }+ }+ }}/**+ **/public void release(UTF8 src) throws IOException {- nameNodeCaller.release(src);+ boolean hasReleased = false;+ while (! hasReleased) {+ hasReleased = namenode.releaseLock(src.toString(), clientName);+ if (! hasReleased) {+ LOG.info("Could not release. Retrying...");+ try {+ Thread.sleep(2000);+ } catch (InterruptedException ie) {+ }+ }+ }}/**@@ -172,8 +195,8 @@ public class NDFSClient implements FSConstants {}/***************************************************************- * If any leases are outstanding, periodically check in with the- * namenode and renew all the leases.+ * Periodically check in with the namenode and renew all the leases+ * when the lease period is half over.***************************************************************/class LeaseChecker implements Runnable {/**@@ -183,8 +206,7 @@ public class NDFSClient implements FSConstants {while (running) {if (System.currentTimeMillis() - lastRenewed > (LEASE_PERIOD / 2)) {try {- FSParam p = new FSParam(OP_CLIENT_RENEW_LEASE, clientName);- FSResults r = nameNodeCaller.call(p);+ namenode.renewLease(clientName);lastRenewed = System.currentTimeMillis();} catch (IOException ie) {}@@ -204,44 +226,64 @@ public class NDFSClient implements FSConstants {class NDFSInputStream extends NFSInputStream {boolean closed = false;+ private String src;private DataInputStream blockStream;private DataOutputStream partnerStream;- private Block blocks[];- private int curBlock = 0;- private DatanodeInfo nodes[][];+ private Block blocks[] = null;+ private DatanodeInfo nodes[][] = null;private long pos = 0;- private long bytesRemainingInBlock = 0, curBlockSize = 0;-- private int memoryBuf[] = new int[32 * 1024];- private long memoryStartPos = 0;- private long openPoint = 0;- private int memoryBytes = 0;- private int memoryBytesStart = 0;+ private long filelen = 0;+ private long blockEnd = -1;/***/- public NDFSInputStream(Block blocks[], DatanodeInfo nodes[][]) throws IOException {- this.blocks = blocks;- this.nodes = nodes;+ public NDFSInputStream(String src) throws IOException {+ this.src = src;+ openInfo();this.blockStream = null;this.partnerStream = null;+ for (int i = 0; i < blocks.length; i++) {+ this.filelen += blocks[i].getNumBytes();+ }}/**- * Open a DataInputStream to a DataNode so that it can be written to.- * This happens when a file is created and each time a new block is allocated.- * Must get block ID and the IDs of the destinations from the namenode.+ * Grab the open-file info from namenode*/- private synchronized void nextBlockInputStream() throws IOException {- nextBlockInputStream(0);+ void openInfo() throws IOException {+ Block oldBlocks[] = this.blocks;++ LocatedBlock results[] = namenode.open(src);+ Vector blockV = new Vector();+ Vector nodeV = new Vector();+ for (int i = 0; i < results.length; i++) {+ blockV.add(results[i].getBlock());+ nodeV.add(results[i].getLocations());+ }+ Block newBlocks[] = (Block[]) blockV.toArray(new Block[blockV.size()]);++ if (oldBlocks != null) {+ for (int i = 0; i < oldBlocks.length; i++) {+ if (! oldBlocks[i].equals(newBlocks[i])) {+ throw new IOException("Blocklist for " + src + " has changed!");+ }+ }+ if (oldBlocks.length != newBlocks.length) {+ throw new IOException("Blocklist for " + src + " now has different length");+ }+ }+ this.blocks = newBlocks;+ this.nodes = (DatanodeInfo[][]) nodeV.toArray(new DatanodeInfo[nodeV.size()][]);}- private synchronized void nextBlockInputStream(long preSkip) throws IOException {- if (curBlock >= blocks.length) {++ /**+ * Open a DataInputStream to a DataNode so that it can be read from.+ * We get block ID and the IDs of the destinations at startup, from the namenode.+ */+ private synchronized void blockSeekTo(long target) throws IOException {+ if (target >= filelen) {throw new IOException("Attempted to read past end of file");}- if (bytesRemainingInBlock > 0) {- throw new IOException("Trying to skip to next block without reading all data");- }if (blockStream != null) {blockStream.close();@@ -249,304 +291,185 @@ public class NDFSClient implements FSConstants {}//- // Connect to best DataNode for current Block+ // Compute desired block+ //+ int targetBlock = -1;+ long targetBlockStart = 0;+ long targetBlockEnd = 0;+ for (int i = 0; i < blocks.length; i++) {+ long blocklen = blocks[i].getNumBytes();+ targetBlockEnd = targetBlockStart + blocklen - 1;++ if (target >= targetBlockStart && target <= targetBlockEnd) {+ targetBlock = i;+ break;+ } else {+ targetBlockStart = targetBlockEnd + 1;+ }+ }+ if (targetBlock < 0) {+ throw new IOException("Impossible situation: could not find target position " + target);+ }+ long offsetIntoBlock = target - targetBlockStart;++ //+ // Connect to best DataNode for desired Block, with potential offset//- InetSocketAddress target = null;+ int failures = 0;+ InetSocketAddress targetAddr = null;Socket s = null;TreeSet deadNodes = new TreeSet();while (s == null) {DatanodeInfo chosenNode;try {- chosenNode = bestNode(nodes[curBlock], deadNodes);- target = NDFS.createSocketAddr(chosenNode.getName().toString());+ chosenNode = bestNode(nodes[targetBlock], deadNodes);+ targetAddr = DataNode.createSocketAddr(chosenNode.getName().toString());} catch (IOException ie) {- LOG.info("Could not obtain block from any node. Retrying...");+ /**+ if (failures >= MAX_BLOCK_ACQUIRE_FAILURES) {+ throw new IOException("Could not obtain block " + blocks[targetBlock]);+ }+ **/+ if (nodes[targetBlock] == null || nodes[targetBlock].length == 0) {+ LOG.info("No node available for block " + blocks[targetBlock]);+ }+ LOG.info("Could not obtain block from any node: " + ie);try {Thread.sleep(10000);} catch (InterruptedException iex) {}deadNodes.clear();+ openInfo();+ failures++;continue;}try {- s = new Socket(target.getAddress(), target.getPort());- //LOG.info("Now downloading from " + target + ", block " + blocks[curBlock] + ", skipahead " + preSkip);+ s = new Socket(targetAddr.getAddress(), targetAddr.getPort());+ s.setSoTimeout(READ_TIMEOUT);//// Xmit header info to datanode//DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));out.write(OP_READSKIP_BLOCK);- blocks[curBlock].write(out);- out.writeLong(preSkip);+ blocks[targetBlock].write(out);+ out.writeLong(offsetIntoBlock);out.flush();//// Get bytes in block, set streams//DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));- curBlockSize = in.readLong();+ long curBlockSize = in.readLong();long amtSkipped = in.readLong();-- pos += amtSkipped;- bytesRemainingInBlock = curBlockSize - amtSkipped;-- if (amtSkipped > 0) {- memoryStartPos = pos;- memoryBytes = 0;- memoryBytesStart = 0;+ if (curBlockSize != blocks[targetBlock].len) {+ throw new IOException("Recorded block size is " + blocks[targetBlock].len + ", but datanode reports size of " + curBlockSize);}- blockStream = in;- partnerStream = out;- curBlock++;- openPoint = pos;+ if (amtSkipped != offsetIntoBlock) {+ throw new IOException("Asked for offset of " + offsetIntoBlock + ", but only received offset of " + amtSkipped);+ }++ this.pos = target;+ this.blockEnd = targetBlockEnd;+ this.blockStream = in;+ this.partnerStream = out;} catch (IOException ex) {// Put chosen node into dead list, continue- LOG.info("Could not connect to " + target);+ LOG.info("Failed to connect to " + targetAddr + ":" + ex);deadNodes.add(chosenNode);- s = null;- }- }- }-- /**- */- public synchronized void seek(long pos) throws IOException {- if (pos < 0) {- throw new IOException("Cannot seek to negative position " + pos);- }- if (pos == this.pos) {- return;- }-- //- // If we have remembered enough bytes to seek backwards to the- // desired pos, we can do so easily- //- if ((pos >= memoryStartPos) && (memoryStartPos + memoryBytes > pos)) {- this.pos = pos;- } else {- //- // If we are seeking backwards (and *don't* have enough memory bytes)- // we need to reset the NDFS streams. They will be reopened upon the- // next call to nextBlockInputStream(). After this operation, all- // seeks will be "forwardSeeks".- //- if (pos < memoryStartPos && blockStream != null) {- blockStream.close();- blockStream = null;- partnerStream.close();- partnerStream = null;- this.curBlock = 0;- this.bytesRemainingInBlock = 0;- this.pos = 0;- this.memoryStartPos = 0;- this.memoryBytes = 0;- this.memoryBytesStart = 0;- //- // REMIND - this could be made more efficient, to just- // skip back block-by-block- //- }-- //- // Now read ahead to the desired position.- //- long diff = pos - this.pos;- while (diff > 0) {- long skipped = skip(diff);- if (skipped > 0) {- diff -= skipped;+ if (s != null) {+ try {+ s.close();+ } catch (IOException iex) {+ }}+ s = null;}- // Pos will be incremented by skip()}}/**- * Skip ahead some number of bytes+ * Close it down!*/- public synchronized long skip(long skip) throws IOException {- long toSkip = 0;- long toFastSkip = 0;- if (skip > memoryBuf.length) {- toSkip = memoryBuf.length;- toFastSkip = skip - toSkip;- } else {- toSkip = skip;- }- long totalSkipped = 0;-- //- // If there's a lot of fast-skipping to do within the current block,- // close it and reopen, so we can fast-skip to the target- //- /**- while (toFastSkip > 0) {- long amtSkipped = super.skip(toFastSkip);- toFastSkip -= amtSkipped;- totalSkipped += amtSkipped;+ public synchronized void close() throws IOException {+ if (closed) {+ throw new IOException("Stream closed");}- **/- long realBytesRemaining = bytesRemainingInBlock + (memoryBytes - (pos - memoryStartPos));- if (toFastSkip > 0 && realBytesRemaining > 0 &&- toFastSkip < realBytesRemaining) {+ if (blockStream != null) {blockStream.close();blockStream = null;partnerStream.close();- partnerStream = null;-- long backwardsDistance = curBlockSize - realBytesRemaining;- pos -= backwardsDistance;- totalSkipped -= backwardsDistance;- toFastSkip += backwardsDistance;- bytesRemainingInBlock = 0;- curBlock--;-- memoryStartPos = pos;- memoryBytes = 0;- memoryBytesStart = 0;- }-- //- // If there's any fast-skipping to do, we do it by opening a- // new block and telling the datanode how many bytes to skip.- //- while (toFastSkip > 0 && curBlock < blocks.length) {-- if (bytesRemainingInBlock > 0) {- blockStream.close();- blockStream = null;- partnerStream.close();- partnerStream = null;-- pos += bytesRemainingInBlock;- totalSkipped += bytesRemainingInBlock;- toFastSkip -= bytesRemainingInBlock;- bytesRemainingInBlock = 0;- }-- long oldPos = pos;- nextBlockInputStream(toFastSkip);- long forwardDistance = (pos - oldPos);- totalSkipped += forwardDistance;- toFastSkip -= (pos - oldPos);-- memoryStartPos = pos;- memoryBytes = 0;- memoryBytesStart = 0;- }-- //- // If there's any remaining toFastSkip, well, there's- // not much we can do about it. We're at the end of- // the stream!- //- if (toFastSkip > 0) {- System.err.println("Trying to skip past end of file....");- toFastSkip = 0;}-- //- // Do a slow skip as we approach, so we can fill the client- // history buffer- //- totalSkipped += super.skip(toSkip);- toSkip = 0;- return totalSkipped;+ super.close();+ closed = true;}/**+ * Basic read()*/- public synchronized long getPos() throws IOException {- return pos;+ public synchronized int read() throws IOException {+ if (closed) {+ throw new IOException("Stream closed");+ }+ int result = -1;+ if (pos < filelen) {+ if (pos > blockEnd) {+ blockSeekTo(pos);+ }+ result = blockStream.read();+ if (result >= 0) {+ pos++;+ }+ }+ return result;}/**+ * Read the entire buffer.*/- public synchronized int available() throws IOException {+ public synchronized int read(byte buf[], int off, int len) throws IOException {if (closed) {throw new IOException("Stream closed");}- return (int) Math.min((long) Integer.MAX_VALUE, bytesRemainingInBlock);+ if (pos < filelen) {+ if (pos > blockEnd) {+ blockSeekTo(pos);+ }+ int result = blockStream.read(buf, off, Math.min(len, (int) (blockEnd - pos + 1)));+ if (result >= 0) {+ pos += result;+ }+ return result;+ }+ return -1;}/**+ * Seek to a new arbitrary location*/- public synchronized void close() throws IOException {- if (closed) {- throw new IOException("Stream closed");+ public synchronized void seek(long targetPos) throws IOException {+ if (targetPos >= filelen) {+ throw new IOException("Cannot seek after EOF");}+ pos = targetPos;+ blockEnd = -1;+ }- if (blockStream != null) {- blockStream.close();- blockStream = null;- partnerStream.close();- }- super.close();- closed = true;+ /**+ */+ public synchronized long getPos() throws IOException {+ return pos;}/**- * Other read() functions are implemented in terms of- * this one.*/- public synchronized int read() throws IOException {+ public synchronized int available() throws IOException {if (closed) {throw new IOException("Stream closed");}-- int b = 0;- if (pos - memoryStartPos < memoryBytes) {- //- // Move the memoryStartPos up to current pos, if necessary.- //- int diff = (int) (pos - memoryStartPos);-- //- // Fetch the byte- //- b = memoryBuf[(memoryBytesStart + diff) % memoryBuf.length];-- //- // Bump the pos- //- pos++;- } else {- if (bytesRemainingInBlock == 0) {- if (curBlock < blocks.length) {- nextBlockInputStream();- } else {- return -1;- }- }- b = blockStream.read();- if (b >= 0) {- //- // Remember byte so we can seek backwards at some later time- //- if (memoryBytes == memoryBuf.length) {- memoryStartPos++;- }-- if (memoryBuf.length > 0) {- int target;- if (memoryBytes == memoryBuf.length) {- target = memoryBytesStart;- memoryBytesStart = (memoryBytesStart + 1) % memoryBuf.length;- } else {- target = (memoryBytesStart + memoryBytes) % memoryBuf.length;- memoryBytes++;- }- memoryBuf[target] = b;- }- bytesRemainingInBlock--;- pos++;- }- }- return b;+ return (int) (filelen - pos);}/**@@ -572,6 +495,7 @@ public class NDFSClient implements FSConstants {private int pos = 0;private UTF8 src;+ boolean closingDown = false;private boolean overwrite;private boolean blockStreamWorking;private DataOutputStream blockStream;@@ -613,18 +537,41 @@ public class NDFSClient implements FSConstants {long start = System.currentTimeMillis();do {retry = false;- Object results[] = nameNodeCaller.getNewOutputBlock(firstTime, overwrite, src);- block = (Block) results[0];- DatanodeInfo nodes[] = (DatanodeInfo[]) results[1];++ long localstart = System.currentTimeMillis();+ boolean blockComplete = false;+ LocatedBlock lb = null;+ while (! blockComplete) {+ if (firstTime) {+ lb = namenode.create(src.toString(), clientName.toString(), overwrite);+ } else {+ lb = namenode.addBlock(src.toString());+ }++ if (lb == null) {+ try {+ Thread.sleep(400);+ if (System.currentTimeMillis() - localstart > 5000) {+ LOG.info("Waiting to find new output block node for " + (System.currentTimeMillis() - start) + "ms");+ }+ } catch (InterruptedException ie) {+ }+ } else {+ blockComplete = true;+ }+ }++ block = lb.getBlock();+ DatanodeInfo nodes[] = lb.getLocations();//// Connect to first DataNode in the list. Abort if this fails.//- InetSocketAddress target = NDFS.createSocketAddr(nodes[0].getName().toString());+ InetSocketAddress target = DataNode.createSocketAddr(nodes[0].getName().toString());Socket s = null;try {- //System.err.println("Trying to connect to " + target);s = new Socket(target.getAddress(), target.getPort());+ s.setSoTimeout(READ_TIMEOUT);} catch (IOException ie) {// Connection failed. Let's wait a little bit and retrytry {@@ -634,7 +581,11 @@ public class NDFSClient implements FSConstants {Thread.sleep(6000);} catch (InterruptedException iex) {}- nameNodeCaller.abandonBlock(block, src);+ if (firstTime) {+ namenode.abandonFileInProgress(src.toString());+ } else {+ namenode.abandonBlock(block, src.toString());+ }retry = true;continue;}@@ -644,6 +595,7 @@ public class NDFSClient implements FSConstants {//DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));out.write(OP_WRITE_BLOCK);+ out.writeBoolean(false);block.write(out);out.writeInt(nodes.length);for (int i = 0; i < nodes.length; i++) {@@ -666,7 +618,6 @@ public class NDFSClient implements FSConstants {/*** Writes the specified byte to this output stream.- * This is the only write method that needs to be implemented.*/public synchronized void write(int b) throws IOException {if (closed) {@@ -681,6 +632,30 @@ public class NDFSClient implements FSConstants {filePos++;}+ /**+ * Writes the specified bytes to this output stream.+ */+ public synchronized void write(byte b[], int off, int len)+ throws IOException {+ if (closed) {+ throw new IOException("Stream closed");+ }+ while (len > 0) {+ int remaining = BUFFER_SIZE - pos;+ int toWrite = Math.min(remaining, len);+ System.arraycopy(b, off, outBuf, pos, toWrite);+ pos += toWrite;+ off += toWrite;+ len -= toWrite;+ filePos += toWrite;++ if ((bytesWrittenToBlock + pos >= BLOCK_SIZE) ||+ (pos == BUFFER_SIZE)) {+ flush();+ }+ }+ }+/*** Flush the buffer, getting a stream to a new block if necessary.*/@@ -706,7 +681,8 @@ public class NDFSClient implements FSConstants {private synchronized void flushData(int maxPos) throws IOException {int workingPos = Math.min(pos, maxPos);- if (workingPos >= 0) {+ if (workingPos > 0 ||+ (workingPos == 0 && closingDown)) {//// To the blockStream, write length, then bytes//@@ -723,7 +699,7 @@ public class NDFSClient implements FSConstants {blockReplyStream.close();} catch (IOException ie2) {}- nameNodeCaller.abandonBlock(block, src);+ namenode.abandonBlock(block, src.toString());blockStreamWorking = false;}}@@ -742,6 +718,7 @@ public class NDFSClient implements FSConstants {}/**+ * We're done writing to the current block.*/private synchronized void endBlock() throws IOException {boolean mustRecover = ! blockStreamWorking;@@ -751,16 +728,7 @@ public class NDFSClient implements FSConstants {//if (blockStreamWorking) {try {- blockStream.writeLong(0);- blockStream.flush();-- long complete = blockReplyStream.readLong();- if (complete != WRITE_COMPLETE) {- LOG.info("Did not receive WRITE_COMPLETE flag: " + complete);- throw new IOException("Did not receive WRITE_COMPLETE_FLAG: " + complete);- }- blockStream.close();- blockReplyStream.close();+ internalClose();} catch (IOException ie) {try {blockStream.close();@@ -770,7 +738,7 @@ public class NDFSClient implements FSConstants {blockReplyStream.close();} catch (IOException ie2) {}- nameNodeCaller.abandonBlock(block, src);+ namenode.abandonBlock(block, src.toString());mustRecover = true;} finally {blockStreamWorking = false;@@ -789,15 +757,14 @@ public class NDFSClient implements FSConstants {nextBlockOutputStream(false);InputStream in = new FileInputStream(backupFile);try {- byte buf[] = new byte[4096];+ byte buf[] = new byte[BUFFER_SIZE];int bytesRead = in.read(buf);while (bytesRead >= 0) {blockStream.writeLong((long) bytesRead);blockStream.write(buf, 0, bytesRead);bytesRead = in.read(buf);}- blockStream.writeLong(0);- blockStream.close();+ internalClose();LOG.info("Recovered from failed datanode connection");mustRecover = false;} catch (IOException ie) {@@ -809,7 +776,7 @@ public class NDFSClient implements FSConstants {blockReplyStream.close();} catch (IOException ie2) {}- nameNodeCaller.abandonBlock(block, src);+ namenode.abandonBlock(block, src.toString());blockStreamWorking = false;}}@@ -822,6 +789,28 @@ public class NDFSClient implements FSConstants {backupStream = new BufferedOutputStream(new FileOutputStream(backupFile));}+ /**+ * Close down stream to remote datanode. Called from two places+ * in endBlock();+ */+ private synchronized void internalClose() throws IOException {+ blockStream.writeLong(0);+ blockStream.flush();++ long complete = blockReplyStream.readLong();+ if (complete != WRITE_COMPLETE) {+ LOG.info("Did not receive WRITE_COMPLETE flag: " + complete);+ throw new IOException("Did not receive WRITE_COMPLETE_FLAG: " + complete);+ }++ LocatedBlock lb = new LocatedBlock();+ lb.readFields(blockReplyStream);+ namenode.reportWrittenBlock(lb);++ blockStream.close();+ blockReplyStream.close();+ }+/*** Closes this output stream and releases any system* resources associated with this stream.@@ -831,6 +820,7 @@ public class NDFSClient implements FSConstants {throw new IOException("Stream closed");}+ closingDown = true;flush();endBlock();@@ -844,304 +834,22 @@ public class NDFSClient implements FSConstants {}super.close();- nameNodeCaller.completeFile(src);- closed = true;- }- }-- /******************************************************************- * Handles the IPC calls to the nameNode.- * This keeps the IPC methods hidden from a the users of FSClient.- *- * I imagine that there will be a NameNodeCaller in the FSClient as- * well as each Stream.- *******************************************************************/- private class NameNodeCaller {- private org.apache.nutch.ipc.Client client;- private InetSocketAddress namenode;-- /**- * Constructor takes the Socket Address of the NameNode.- */- public NameNodeCaller(InetSocketAddress namenode) {- this.client = new org.apache.nutch.ipc.Client(FSResults.class);- this.namenode = namenode;- }-- /**- * General-purpose call- */- public FSResults call(FSParam p) throws IOException {- return (FSResults) call(p, namenode);- }-- private synchronized FSResults call(FSParam p, InetSocketAddress target) throws IOException {- FSResults results = null;- while (results == null) {- try {- results = (FSResults) client.call(p, target);- } catch (IOException ie) {- long start = System.currentTimeMillis();- LOG.info("Problem making IPC call on " + target);- client.stop();- long end = System.currentTimeMillis();- if (end - start < 15000) {- try {- Thread.sleep(15000 - (end - start));- } catch (InterruptedException iex) {- }- }- LOG.info("Restarting client");- client = new org.apache.nutch.ipc.Client(FSResults.class);- }- }- return results;- }-- /**- * Calls the nameNode to get a new block. Returns the blockID- * and resets the given destination nodes.- */- public Object[] getNewOutputBlock(boolean newFile, boolean overwrite, UTF8 src) throws IOException {- long start = System.currentTimeMillis();- FSParam p = null;- FSResults r = null;- boolean blockComplete = false;- while (! blockComplete) {- UTF8 nameParams[] = new UTF8[2];- nameParams[0] = src;- nameParams[1] = clientName;- if (newFile) {- p = new FSParam(OP_CLIENT_STARTFILE, new ArrayWritable(UTF8.class, nameParams), new BooleanWritable(overwrite));- } else {- p = new FSParam(OP_CLIENT_ADDBLOCK, src);- }- r = (FSResults) call(p, namenode);- if (! r.success()) {- throw new IOException("Could not obtain new output block for file " + src);- } else if (r.tryagain()) {- try {- Thread.sleep(400);- if (System.currentTimeMillis() - start > 5000) {- LOG.info("Waiting to find new output block node for " + (System.currentTimeMillis() - start) + "ms");- }- } catch (InterruptedException ie) {- }- } else {- blockComplete = true;- }- }- Block b = (Block) r.first;- DatanodeInfo targets[] = (DatanodeInfo[]) ((ArrayWritable) r.second).toArray();-- Object results[] = new Object[2];- results[0] = b;- results[1] = targets;- return results;- }-- /**- */- public void abandonBlock(Block b, UTF8 src) throws IOException {- FSParam p = null;- FSResults r = null;- p = new FSParam(OP_CLIENT_ABANDONBLOCK, b, src);- r = (FSResults) call(p, namenode);- if (! r.success()) {- throw new IOException("Block " + b + " has already been committed.");- }- }-- /**- * Get the block IDs and Nodes for the given file name (src).- */- public Object[] getBlocksNodes(UTF8 src) throws IOException {- FSParam p = new FSParam(OP_CLIENT_OPEN, src);- FSResults r = (FSResults) call(p, namenode);- if (! r.success()) {- throw new IOException("Could not open file " + src);- } else {- Block blocks[] = (Block[]) ((ArrayWritable) r.first).toArray();- DatanodeInfo nodes[][] = (DatanodeInfo[][]) ((TwoDArrayWritable) r.second).toArray();- Object results[] = new Object[2];- results[0] = blocks;- results[1] = nodes;- return results;- }- }-- /**- * Rename details are kept within the NameNodeCaller.- * This causes an extra level of indirection which might be too costly.- */- public boolean rename(UTF8 src, UTF8 dst) throws IOException{- FSParam p = new FSParam(OP_CLIENT_RENAMETO, src, dst);- FSResults r = (FSResults) call(p, namenode);- return r.success();- }-- /**- * Delete details are kept within the NameNodeCaller.- * This causes an extra level of indirection which might be too costly.- */- public boolean delete(UTF8 src) throws IOException {- FSParam p = new FSParam(OP_CLIENT_DELETE, src);- FSResults r = (FSResults) call(p, namenode);- return r.success();- }-- /**- * Checks to see if the given path exists (as dir or file)- */- public boolean exists(UTF8 src) throws IOException {- FSParam p = new FSParam(OP_CLIENT_EXISTS, src);- FSResults r = (FSResults) call(p, namenode);- return r.success();- }-- /**- * Checks to see if the given path is a dir.- */- public boolean isDirectory(UTF8 src) throws IOException {- FSParam p = new FSParam(OP_CLIENT_ISDIR, src);- FSResults r = (FSResults) call(p, namenode);- return r.success();- }-- /**- */- public boolean mkdirs(UTF8 src) throws IOException {- FSParam p = new FSParam(OP_CLIENT_MKDIRS, src);- FSResults r = (FSResults) call(p, namenode);- return r.success();- }-- /**- * We try to obtain a lock (ex or not, as described). We- * block until successful.- */- public void lock(UTF8 src, boolean exclusive) throws IOException {- long start = System.currentTimeMillis();- boolean complete = false;-- while (! complete) {- UTF8 nameParams[] = new UTF8[2];- nameParams[0] = src;- nameParams[1] = clientName;- FSParam p = new FSParam(OP_CLIENT_OBTAINLOCK, new ArrayWritable(UTF8.class, nameParams), new BooleanWritable(exclusive));- FSResults r = (FSResults) call(p, namenode);- if (! r.success()) {- throw new IOException("Could not obtain lock " + src);- } else if (r.tryagain()) {- try {- Thread.sleep(400);- if (System.currentTimeMillis() - start > 5000) {- LOG.info("Waiting to retry lock for " + (System.currentTimeMillis() - start) + " ms.");- Thread.sleep(2000);- }- } catch (InterruptedException ie) {- }- } else {- complete = true;- }- }- }-- /**- * Release the given lock- */- public void release(UTF8 src) throws IOException {- boolean complete = false;- while (! complete) {- UTF8 nameParams[] = new UTF8[2];- nameParams[0] = src;- nameParams[1] = clientName;- FSParam p = new FSParam(OP_CLIENT_RELEASELOCK, new ArrayWritable(UTF8.class, nameParams));- FSResults r = (FSResults) call(p, namenode);- if (! r.success()) {- throw new IOException("Could not release lock " + src);- } else if (r.tryagain()) {- LOG.info("Could not release. Retrying...");- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- } else {- complete = true;- }- }- }-- /**- * List all the files at the given path- */- public NDFSFileInfo[] listing(UTF8 src) throws IOException {- FSParam p = new FSParam(OP_CLIENT_LISTING, src);- FSResults r = (FSResults) call(p, namenode);- if (r.success()) {- return (NDFSFileInfo[]) ((ArrayWritable) r.first).toArray();- } else {- return null;- }- }-- /**- * Report on raw bytes- */- public long[] rawReport() throws IOException {- long results[] = null;- FSParam p = new FSParam(OP_CLIENT_RAWSTATS);- FSResults r = (FSResults) call(p, namenode);- if (r.success()) {- LongWritable report[] = (LongWritable[]) ((ArrayWritable) r.first).toArray();- results = new long[report.length];- for (int i = 0; i < report.length; i++) {- results[i] = report[i].get();- }- }- return results;- }-- /**- */- public DatanodeInfo[] datanodeReport() throws IOException {- FSParam p = new FSParam(OP_CLIENT_DATANODEREPORT);- FSResults r = (FSResults) call(p, namenode);- if (r.success()) {- return (DatanodeInfo[]) ((ArrayWritable) r.first).toArray();- } else {- return null;- }- }-- /**- * Contacts the namenode repeatedly until file is wholly- * committed. Blocks until that time.- */- public void completeFile(UTF8 src) throws IOException {- long start = System.currentTimeMillis();+ long localstart = System.currentTimeMillis();boolean fileComplete = false;- UTF8 nameParams[] = new UTF8[2];- nameParams[0] = src;- nameParams[1] = clientName;-while (! fileComplete) {- FSParam p = new FSParam(OP_CLIENT_COMPLETEFILE, new ArrayWritable(UTF8.class, nameParams));- FSResults r = (FSResults) call(p, namenode);- if (! r.success()) {- throw new IOException("Could not complete file " + src);- } else if (r.tryagain()) {+ fileComplete = namenode.complete(src.toString(), clientName.toString());+ if (!fileComplete) {try {Thread.sleep(400);- if (System.currentTimeMillis() - start > 5000) {+ if (System.currentTimeMillis() - localstart > 5000) {LOG.info("Could not complete file, retrying...");}} catch (InterruptedException ie) {}- } else {- fileComplete = true;}}+ closed = true;+ closingDown = false;}}}diff --git a/src/java/org/apache/nutch/ndfs/NameNode.java b/src/java/org/apache/nutch/ndfs/NameNode.javanew file mode 100644index 000000000..a687985bf--- /dev/null+++ b/src/java/org/apache/nutch/ndfs/NameNode.java@@ -0,0 +1,352 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import org.apache.nutch.io.*;+import org.apache.nutch.ipc.*;+import org.apache.nutch.util.*;++import java.io.*;+import java.net.*;+import java.util.*;+import java.util.logging.*;++/**********************************************************+ * NameNode controls two critical tables:+ * 1) filename->blocksequence,version+ * 2) block->machinelist+ *+ * The first table is stored on disk and is very precious.+ * The second table is rebuilt every time the NameNode comes+ * up.+ *+ * @author Mike Cafarella+ **********************************************************/+public class NameNode implements ClientProtocol, DatanodeProtocol, FSConstants {+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.ndfs.NameNode");++ private FSNamesystem namesystem;+ private Server server;+ private int handlerCount = 2;++ /** only used for testing purposes */+ private boolean stopRequested = false;++ /**+ * Create a NameNode at the default location+ */+ public NameNode() throws IOException {+ this(new File(NutchConf.get().get("ndfs.name.dir",+ "/tmp/nutch/ndfs/name")),+ DataNode.createSocketAddr+ (NutchConf.get().get("fs.default.name", "local")).getPort());+ }++ /**+ * Create a NameNode at the specified location and start it.+ */+ public NameNode(File dir, int port) throws IOException {+ this.namesystem = new FSNamesystem(dir);+ this.handlerCount =+ NutchConf.get().getInt("ndfs.namenode.handler.count", 10);+ this.server = RPC.getServer(this, port, handlerCount, false);+ this.server.start();+ }++ /**+ * Wait for service to finish.+ * (Normally, it runs forever.)+ */+ public void join() {+ try {+ this.server.join();+ } catch (InterruptedException ie) {+ }+ }++ /**+ * Stop all NameNode threads and wait for all to finish.+ * Package-only access since this is intended for JUnit testing.+ */+ void stop() {+ if (! stopRequested) {+ stopRequested = true;+ namesystem.close();+ server.stop();+ //this.join();+ }+ }++ /////////////////////////////////////////////////////+ // ClientProtocol+ /////////////////////////////////////////////////////+ /**+ */+ public LocatedBlock[] open(String src) throws IOException {+ Object openResults[] = namesystem.open(new UTF8(src));+ if (openResults == null) {+ throw new IOException("Cannot open filename " + src);+ } else {+ Block blocks[] = (Block[]) openResults[0];+ DatanodeInfo sets[][] = (DatanodeInfo[][]) openResults[1];+ LocatedBlock results[] = new LocatedBlock[blocks.length];+ for (int i = 0; i < blocks.length; i++) {+ results[i] = new LocatedBlock(blocks[i], sets[i]);+ }+ return results;+ }+ }++ /**+ */+ public LocatedBlock create(String src, String clientName, boolean overwrite) throws IOException {+ Object results[] = namesystem.startFile(new UTF8(src), new UTF8(clientName), overwrite);+ if (results == null) {+ throw new IOException("Cannot create file " + src + " on client " + clientName);+ } else {+ Block b = (Block) results[0];+ DatanodeInfo targets[] = (DatanodeInfo[]) results[1];+ return new LocatedBlock(b, targets);+ }+ }++ /**+ */+ public LocatedBlock addBlock(String src) throws IOException {+ int retries = 5;+ Object results[] = namesystem.getAdditionalBlock(new UTF8(src));+ while (results != null && results[0] == null && retries > 0) {+ try {+ Thread.sleep(100);+ } catch (InterruptedException ie) {+ }+ results = namesystem.getAdditionalBlock(new UTF8(src));+ retries--;+ }++ if (results == null) {+ throw new IOException("Cannot obtain additional block for file " + src);+ } else if (results[0] == null) {+ return null;+ } else {+ Block b = (Block) results[0];+ DatanodeInfo targets[] = (DatanodeInfo[]) results[1];+ return new LocatedBlock(b, targets);+ }+ }++ /**+ * The client can report in a set written blocks that it wrote.+ * These blocks are reported via the client instead of the datanode+ * to prevent weird heartbeat race conditions.+ */+ public void reportWrittenBlock(LocatedBlock lb) throws IOException {+ Block b = lb.getBlock();+ DatanodeInfo targets[] = lb.getLocations();+ for (int i = 0; i < targets.length; i++) {+ namesystem.blockReceived(b, targets[i].getName());+ }+ }++ /**+ * The client needs to give up on the block.+ */+ public void abandonBlock(Block b, String src) throws IOException {+ if (! namesystem.abandonBlock(b, new UTF8(src))) {+ throw new IOException("Cannot abandon block during write to " + src);+ }+ }+ /**+ */+ public void abandonFileInProgress(String src) throws IOException {+ namesystem.abandonFileInProgress(new UTF8(src));+ }+ /**+ */+ public boolean complete(String src, String clientName) throws IOException {+ int returnCode = namesystem.completeFile(new UTF8(src), new UTF8(clientName));+ if (returnCode == STILL_WAITING) {+ return false;+ } else if (returnCode == COMPLETE_SUCCESS) {+ return true;+ } else {+ throw new IOException("Could not complete write to file " + src + " by " + clientName);+ }+ }+ /**+ */+ public String[][] getHints(String src, long start, long len) throws IOException {+ UTF8 hosts[][] = namesystem.getDatanodeHints(new UTF8(src), start, len);+ if (hosts == null) {+ return new String[0][];+ } else {+ String results[][] = new String[hosts.length][];+ for (int i = 0; i < hosts.length; i++) {+ results[i] = new String[hosts[i].length];+ for (int j = 0; j < results[i].length; j++) {+ results[i][j] = hosts[i][j].toString();+ }+ }+ return results;+ }+ }+ /**+ */+ public boolean rename(String src, String dst) throws IOException {+ return namesystem.renameTo(new UTF8(src), new UTF8(dst));+ }++ /**+ */+ public boolean delete(String src) throws IOException {+ return namesystem.delete(new UTF8(src));+ }++ /**+ */+ public boolean exists(String src) throws IOException {+ return namesystem.exists(new UTF8(src));+ }++ /**+ */+ public boolean isDir(String src) throws IOException {+ return namesystem.isDir(new UTF8(src));+ }++ /**+ */+ public boolean mkdirs(String src) throws IOException {+ return namesystem.mkdirs(new UTF8(src));+ }++ /**+ */+ public boolean obtainLock(String src, String clientName, boolean exclusive) throws IOException {+ int returnCode = namesystem.obtainLock(new UTF8(src), new UTF8(clientName), exclusive);+ if (returnCode == COMPLETE_SUCCESS) {+ return true;+ } else if (returnCode == STILL_WAITING) {+ return false;+ } else {+ throw new IOException("Failure when trying to obtain lock on " + src);+ }+ }++ /**+ */+ public boolean releaseLock(String src, String clientName) throws IOException {+ int returnCode = namesystem.releaseLock(new UTF8(src), new UTF8(clientName));+ if (returnCode == COMPLETE_SUCCESS) {+ return true;+ } else if (returnCode == STILL_WAITING) {+ return false;+ } else {+ throw new IOException("Failure when trying to release lock on " + src);+ }+ }++ /**+ */+ public void renewLease(String clientName) throws IOException {+ namesystem.renewLease(new UTF8(clientName));+ }++ /**+ */+ public NDFSFileInfo[] getListing(String src) throws IOException {+ return namesystem.getListing(new UTF8(src));+ }++ /**+ */+ public long[] getStats() throws IOException {+ long results[] = new long[2];+ results[0] = namesystem.totalCapacity();+ results[1] = namesystem.totalCapacity() - namesystem.totalRemaining();+ return results;+ }++ /**+ */+ public DatanodeInfo[] getDatanodeReport() throws IOException {+ DatanodeInfo results[] = namesystem.datanodeReport();+ if (results == null || results.length == 0) {+ throw new IOException("Cannot find datanode report");+ }+ return results;+ }++ ////////////////////////////////////////////////////////////////+ // DatanodeProtocol+ ////////////////////////////////////////////////////////////////+ /**+ */+ public void sendHeartbeat(String sender, long capacity, long remaining) {+ namesystem.gotHeartbeat(new UTF8(sender), capacity, remaining);+ }++ public Block[] blockReport(String sender, Block blocks[]) {+ LOG.info("Block report from "+sender+": "+blocks.length+" blocks.");+ return namesystem.processReport(blocks, new UTF8(sender));+ }++ public void blockReceived(String sender, Block blocks[]) {+ for (int i = 0; i < blocks.length; i++) {+ namesystem.blockReceived(blocks[i], new UTF8(sender));+ }+ }++ /**+ */+ public void errorReport(String sender, String msg) {+ // Log error message from datanode+ //LOG.info("Report from " + sender + ": " + msg);+ }++ /**+ * Return a block-oriented command for the datanode to execute.+ * This will be either a transfer or a delete operation.+ */+ public BlockCommand getBlockwork(String sender, int xmitsInProgress) {+ //+ // Ask to perform pending transfers, if any+ //+ Object xferResults[] = namesystem.pendingTransfers(new DatanodeInfo(new UTF8(sender)), xmitsInProgress);+ if (xferResults != null) {+ return new BlockCommand((Block[]) xferResults[0], (DatanodeInfo[][]) xferResults[1]);+ }++ //+ // If there are no transfers, check for recently-deleted blocks that+ // should be removed. This is not a full-datanode sweep, as is done during+ // a block report. This is just a small fast removal of blocks that have+ // just been removed.+ //+ Block blocks[] = namesystem.blocksToInvalidate(new UTF8(sender));+ if (blocks != null) {+ return new BlockCommand(blocks);+ }+ return null;+ }++ /**+ */+ public static void main(String argv[]) throws IOException, InterruptedException {+ NameNode namenode = new NameNode();+ namenode.join();+ }+}diff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.javaindex b09bd1695..c12a33000 100644--- a/src/java/org/apache/nutch/parse/ParseData.java+++ b/src/java/org/apache/nutch/parse/ParseData.java@@ -148,9 +148,11 @@ public final class ParseData extends VersionedWritable {buffer.append("Status: " + status + "\n" );buffer.append("Title: " + title + "\n" );- buffer.append("Outlinks: " + outlinks.length + "\n" );- for (int i = 0; i < outlinks.length; i++) {- buffer.append(" outlink: " + outlinks[i] + "\n");+ if (outlinks != null) {+ buffer.append("Outlinks: " + outlinks.length + "\n" );+ for (int i = 0; i < outlinks.length; i++) {+ buffer.append(" outlink: " + outlinks[i] + "\n");+ }}buffer.append("Metadata: " + metadata + "\n" );diff --git a/src/java/org/apache/nutch/parse/ParseImpl.java b/src/java/org/apache/nutch/parse/ParseImpl.javaindex b23bf9333..1c3815ea7 100644--- a/src/java/org/apache/nutch/parse/ParseImpl.java+++ b/src/java/org/apache/nutch/parse/ParseImpl.java@@ -16,19 +16,53 @@package org.apache.nutch.parse;+import java.io.*;+import org.apache.nutch.io.*;++/** The result of parsing a page's raw content.* @see Parser#getParse(Content)*/-public class ParseImpl implements Parse {- private String text;+public class ParseImpl implements Parse, Writable {+ private ParseText text;private ParseData data;+ public ParseImpl() {}++ public ParseImpl(Parse parse) {+ this(parse.getText(), parse.getData());+ }+public ParseImpl(String text, ParseData data) {+ this(new ParseText(text), data);+ }++ public ParseImpl(ParseText text, ParseData data) {this.text = text;this.data = data;}- public String getText() { return text; }+ public String getText() { return text.getText(); }public ParseData getData() { return data; }++ public final void write(DataOutput out) throws IOException {+ text.write(out);+ data.write(out);+ }++ public void readFields(DataInput in) throws IOException {+ 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/protocol/Content.java b/src/java/org/apache/nutch/protocol/Content.javaindex fa1e512fc..0fa383bf3 100755--- a/src/java/org/apache/nutch/protocol/Content.java+++ b/src/java/org/apache/nutch/protocol/Content.java@@ -26,8 +26,7 @@ import org.apache.nutch.util.mime.MimeType;import org.apache.nutch.util.mime.MimeTypes;import org.apache.nutch.util.mime.MimeTypeException;--public final class Content extends VersionedWritable {+public final class Content extends CompressedWritable {public static final String DIR_NAME = "content";@@ -35,12 +34,13 @@ public final class Content extends VersionedWritable {/** A flag that tells if magic resolution must be performed */private final static boolean MAGIC =- NutchConf.get().getBoolean("mime.type.magic", true);-+ NutchConf.get().getBoolean("mime.type.magic", true);+/** Get the MimeTypes resolver instance. */private final static MimeTypes MIME =- MimeTypes.get(NutchConf.get().get("mime.types.file"));+ MimeTypes.get(NutchConf.get().get("mime.types.file"));+ private byte version;private String url;private String base;private byte[] content;@@ -50,7 +50,7 @@ public final class Content extends VersionedWritable {public Content() {}public Content(String url, String base, byte[] content, String contentType,- ContentProperties metadata) {+ ContentProperties metadata){if (url == null) throw new IllegalArgumentException("null url");if (base == null) throw new IllegalArgumentException("null base");@@ -64,15 +64,16 @@ public final class Content extends VersionedWritable {this.metadata = metadata;}- public byte getVersion() { return VERSION; }-- public final void readFields(DataInput in) throws IOException {- super.readFields(in); // check version+ protected final void readFieldsCompressed(DataInput in) throws IOException {+ version = in.readByte();+ if (version > VERSION)+ throw new VersionMismatchException(VERSION, version);url = UTF8.readString(in); // read urlbase = UTF8.readString(in); // read base- content = WritableUtils.readCompressedByteArray(in);+ content = new byte[in.readInt()]; // read content+ in.readFully(content);contentType = UTF8.readString(in); // read contentType@@ -83,13 +84,14 @@ public final class Content extends VersionedWritable {}}- public final void write(DataOutput out) throws IOException {- super.write(out); // write version+ protected final void writeCompressed(DataOutput out) throws IOException {+ out.writeByte(version);UTF8.writeString(out, url); // write urlUTF8.writeString(out, base); // write base- WritableUtils.writeCompressedByteArray(out, content); // write content+ out.writeInt(content.length); // write content+ out.write(content);UTF8.writeString(out, contentType); // write contentType@@ -113,37 +115,61 @@ public final class Content extends VersionedWritable {///** The url fetched. */- public String getUrl() { return url; }+ public String getUrl() {+ ensureInflated();+ return url;+ }/** The base url for relative links contained in the content.* Maybe be different from url if the request redirected.*/- public String getBaseUrl() { return base; }+ public String getBaseUrl() {+ ensureInflated();+ return base;+ }/** The binary content retrieved. */- public byte[] getContent() { return content; }- public void setContent(byte[] content) { this.content = content; }+ public byte[] getContent() {+ ensureInflated();+ return content;+ }+ public void setContent(byte[] content) {+ ensureInflated();+ this.content = content;+ }/** The media type of the retrieved content.* @see <a href="http://www.iana.org/assignments/media-types/">* http://www.iana.org/assignments/media-types/</a>*/- public String getContentType() { return contentType; }+ public String getContentType() {+ ensureInflated();+ return contentType;+ }public void setContentType(String contentType) {+ ensureInflated();this.contentType = contentType;}/** Other protocol-specific data. */- public ContentProperties getMetadata() { return metadata; }+ public ContentProperties getMetadata() {+ ensureInflated();+ return metadata;+ }/** Return the value of a metadata property. */- public String get(String name) { return getMetadata().getProperty(name); }+ public String get(String name) {+ ensureInflated();+ return getMetadata().getProperty(name);+ }public boolean equals(Object o) {+ ensureInflated();if (!(o instanceof Content)){return false;}Content that = (Content)o;+ that.ensureInflated();returnthis.url.equals(that.url) &&this.base.equals(that.base) &&@@ -153,6 +179,7 @@ public final class Content extends VersionedWritable {}public String toString() {+ ensureInflated();StringBuffer buffer = new StringBuffer();buffer.append("url: " + url + "\n" );diff --git a/src/java/org/apache/nutch/searcher/DistributedSearch.java b/src/java/org/apache/nutch/searcher/DistributedSearch.javaindex 1853cc9a2..57ef3e0fa 100644--- a/src/java/org/apache/nutch/searcher/DistributedSearch.java+++ b/src/java/org/apache/nutch/searcher/DistributedSearch.java@@ -24,6 +24,7 @@ import java.lang.reflect.Method;import org.apache.nutch.parse.ParseData;import org.apache.nutch.parse.ParseText;+import org.apache.nutch.crawl.Inlinks;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.io.*;import org.apache.nutch.ipc.RPC;@@ -37,7 +38,7 @@ public class DistributedSearch {/** The distributed search protocol. */public interface Protocol- extends Searcher, HitDetailer, HitSummarizer, HitContent {+ extends Searcher, HitDetailer, HitSummarizer, HitContent, HitInlinks {/** The name of the segments searched by this node. */String[] getSegmentNames();@@ -71,7 +72,8 @@ public class DistributedSearch {/** The search client. */public static class Client extends Thread- implements Searcher, HitDetailer, HitSummarizer, HitContent, Runnable {+ implements Searcher, HitDetailer, HitSummarizer, HitContent, HitInlinks,+ Runnable {private InetSocketAddress[] defaultAddresses;private InetSocketAddress[] liveAddresses;@@ -295,6 +297,10 @@ public class DistributedSearch {return getRemote(hit).getAnchors(hit);}+ public Inlinks getInlinks(HitDetails hit) throws IOException {+ return getRemote(hit).getInlinks(hit);+ }+public long getFetchDate(HitDetails hit) throws IOException {return getRemote(hit).getFetchDate(hit);}diff --git a/src/java/org/apache/nutch/searcher/FetchedSegments.java b/src/java/org/apache/nutch/searcher/FetchedSegments.javaindex 26426d524..915fd6873 100644--- a/src/java/org/apache/nutch/searcher/FetchedSegments.java+++ b/src/java/org/apache/nutch/searcher/FetchedSegments.java@@ -20,6 +20,7 @@ import java.io.IOException;import java.io.File;import java.util.HashMap;+import java.util.Arrays;import org.apache.nutch.io.*;import org.apache.nutch.fs.*;@@ -30,69 +31,71 @@ import org.apache.nutch.protocol.*;import org.apache.nutch.parse.*;import org.apache.nutch.pagedb.*;import org.apache.nutch.indexer.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.mapred.lib.*;+import org.apache.nutch.crawl.*;/** Implements {@link HitSummarizer} and {@link HitContent} for a set of* fetched segments. */public class FetchedSegments implements HitSummarizer, HitContent {private static class Segment {+ private static final Partitioner PARTITIONER = new HashPartitioner();+private NutchFileSystem nfs;private File segmentDir;- private ArrayFile.Reader fetcher;- private ArrayFile.Reader content;- private ArrayFile.Reader text;- private ArrayFile.Reader parsedata;+ private MapFile.Reader[] content;+ private MapFile.Reader[] parseText;+ private MapFile.Reader[] parseData;+ private MapFile.Reader[] crawl;public Segment(NutchFileSystem nfs, File segmentDir) throws IOException {this.nfs = nfs;this.segmentDir = segmentDir;}- public FetcherOutput getFetcherOutput(int docNo) throws IOException {- if (fetcher == null) {- this.fetcher = new ArrayFile.Reader- (nfs, new File(segmentDir, FetcherOutput.DIR_NAME).toString());+ public CrawlDatum getCrawlDatum(UTF8 url) throws IOException {+ synchronized (this) {+ if (crawl == null)+ crawl = getReaders(CrawlDatum.FETCH_DIR_NAME);}-- FetcherOutput entry = new FetcherOutput();- fetcher.get(docNo, entry);- return entry;+ return (CrawlDatum)getEntry(crawl, url, new CrawlDatum());}-- public byte[] getContent(int docNo) throws IOException {- if (content == null) {- this.content = new ArrayFile.Reader- (nfs, new File(segmentDir, Content.DIR_NAME).toString());++ public byte[] getContent(UTF8 url) throws IOException {+ synchronized (this) {+ if (content == null)+ content = getReaders(Content.DIR_NAME);}-- Content entry = new Content();- content.get(docNo, entry);- return entry.getContent();+ return ((Content)getEntry(content, url, new Content())).getContent();}- public ParseData getParseData(int docNo) throws IOException {- if (parsedata == null) {- this.parsedata = new ArrayFile.Reader- (nfs, new File(segmentDir, ParseData.DIR_NAME).toString());+ public ParseData getParseData(UTF8 url) throws IOException {+ synchronized (this) {+ if (parseData == null)+ parseData = getReaders(ParseData.DIR_NAME);}-- ParseData entry = new ParseData();- parsedata.get(docNo, entry);- return entry;+ return (ParseData)getEntry(parseData, url, new ParseData());}- public ParseText getParseText(int docNo) throws IOException {- if (text == null) {- this.text = new ArrayFile.Reader- (nfs, new File(segmentDir, ParseText.DIR_NAME).toString());+ public ParseText getParseText(UTF8 url) throws IOException {+ synchronized (this) {+ if (parseText == null)+ parseText = getReaders(ParseText.DIR_NAME);}-- ParseText entry = new ParseText();- text.get(docNo, entry);- return entry;+ return (ParseText)getEntry(parseText, url, new ParseText());}+ private MapFile.Reader[] getReaders(String subDir) throws IOException {+ return MapFileOutputFormat.getReaders(nfs, new File(segmentDir, subDir));+ }++ private Writable getEntry(MapFile.Reader[] readers, UTF8 url,+ Writable entry) throws IOException {+ return MapFileOutputFormat.getEntry(readers, PARTITIONER, url, entry);+ }+}private HashMap segments = new HashMap();@@ -104,10 +107,12 @@ public class FetchedSegments implements HitSummarizer, HitContent {if (segmentDirs != null) {for (int i = 0; i < segmentDirs.length; i++) {File segmentDir = segmentDirs[i];- File indexdone = new File(segmentDir, IndexSegment.DONE_NAME);- if (nfs.exists(indexdone) && nfs.isFile(indexdone)) {- segments.put(segmentDir.getName(), new Segment(nfs, segmentDir));- }+// File indexdone = new File(segmentDir, IndexSegment.DONE_NAME);+// if (nfs.exists(indexdone) && nfs.isFile(indexdone)) {+// segments.put(segmentDir.getName(), new Segment(nfs, segmentDir));+// }+ segments.put(segmentDir.getName(), new Segment(nfs, segmentDir));+}}}@@ -117,31 +122,26 @@ public class FetchedSegments implements HitSummarizer, HitContent {}public byte[] getContent(HitDetails details) throws IOException {- return getSegment(details).getContent(getDocNo(details));+ return getSegment(details).getContent(getUrl(details));}public ParseData getParseData(HitDetails details) throws IOException {- return getSegment(details).getParseData(getDocNo(details));- }-- public String[] getAnchors(HitDetails details) throws IOException {- return getSegment(details).getFetcherOutput(getDocNo(details))- .getFetchListEntry().getAnchors();+ return getSegment(details).getParseData(getUrl(details));}public long getFetchDate(HitDetails details) throws IOException {- return getSegment(details).getFetcherOutput(getDocNo(details))- .getFetchDate();+ return getSegment(details).getCrawlDatum(getUrl(details))+ .getFetchTime();}public ParseText getParseText(HitDetails details) throws IOException {- return getSegment(details).getParseText(getDocNo(details));+ return getSegment(details).getParseText(getUrl(details));}public String getSummary(HitDetails details, Query query)throws IOException {- String text = getSegment(details).getParseText(getDocNo(details)).getText();+ String text = getSegment(details).getParseText(getUrl(details)).getText();return new Summarizer().getSummary(text, query).toString();}@@ -199,8 +199,8 @@ public class FetchedSegments implements HitSummarizer, HitContent {return (Segment)segments.get(details.getValue("segment"));}- private int getDocNo(HitDetails details) {- return Integer.parseInt(details.getValue("docNo"), 16);+ private UTF8 getUrl(HitDetails details) {+ return new UTF8(details.getValue("url"));}diff --git a/src/java/org/apache/nutch/searcher/HitContent.java b/src/java/org/apache/nutch/searcher/HitContent.javaindex dd588e13d..b98399482 100644--- a/src/java/org/apache/nutch/searcher/HitContent.java+++ b/src/java/org/apache/nutch/searcher/HitContent.java@@ -32,10 +32,7 @@ public interface HitContent {/** Returns the ParseText of a hit document. */ParseText getParseText(HitDetails details) throws IOException;- /** Returns the anchors of a hit document. */- String[] getAnchors(HitDetails details) throws IOException;-- /** Returns the anchors of a hit document. */+ /** Returns the fetch date of a hit document. */long getFetchDate(HitDetails details) throws IOException;}diff --git a/src/java/org/apache/nutch/searcher/HitDetails.java b/src/java/org/apache/nutch/searcher/HitDetails.javaindex 677a2e81b..2ced9b04f 100644--- a/src/java/org/apache/nutch/searcher/HitDetails.java+++ b/src/java/org/apache/nutch/searcher/HitDetails.java@@ -47,12 +47,12 @@ public final class HitDetails implements Writable {}/** Construct minimal details from a segment name and document number. */- public HitDetails(String segment, String docNo) {+ public HitDetails(String segment, String url) {this(new String[2], new String[2]);this.fields[0] = "segment";this.values[0] = segment;- this.fields[1] = "docNo";- this.values[1] = docNo;+ this.fields[1] = "url";+ this.values[1] = url;}/** Returns the number of fields contained in this. */@@ -102,7 +102,7 @@ public final class HitDetails implements Writable {/** Display as a string. */public String toString() {- return getValue("segment") + "/" + getValue("docNo");+ return getValue("segment") + "/" + getValue("url");}/** Display as HTML. */diff --git a/src/java/org/apache/nutch/searcher/HitInlinks.java b/src/java/org/apache/nutch/searcher/HitInlinks.javanew file mode 100644index 000000000..6d1eb2573--- /dev/null+++ b/src/java/org/apache/nutch/searcher/HitInlinks.java@@ -0,0 +1,30 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 org.apache.nutch.crawl.Inlinks;++/** Service that returns information about incoming links to a hit. */+public interface HitInlinks {+ /** Returns the anchors of a hit document. */+ String[] getAnchors(HitDetails details) throws IOException;++ /** Return the inlinks of a hit document. */+ Inlinks getInlinks(HitDetails details) throws IOException;+}diff --git a/src/java/org/apache/nutch/searcher/IndexSearcher.java b/src/java/org/apache/nutch/searcher/IndexSearcher.javaindex b0f7e6e7d..5a5614074 100644--- a/src/java/org/apache/nutch/searcher/IndexSearcher.java+++ b/src/java/org/apache/nutch/searcher/IndexSearcher.java@@ -22,6 +22,9 @@ import java.io.File;import java.util.ArrayList;import java.util.Enumeration;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FSDirectory;+import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.MultiReader;@@ -34,6 +37,7 @@ import org.apache.lucene.search.FieldCache;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;+import org.apache.nutch.fs.*;import org.apache.nutch.io.*;import org.apache.nutch.util.*;import org.apache.nutch.db.*;@@ -43,7 +47,7 @@ import org.apache.nutch.indexer.*;import org.apache.nutch.analysis.NutchDocumentAnalyzer;/** Implements {@link Searcher} and {@link HitDetailer} for either a single- * merged index, or for a set of individual segment indexes. */+ * merged index, or a set of indexes. */public class IndexSearcher implements Searcher, HitDetailer {private org.apache.lucene.search.Searcher luceneSearcher;@@ -53,20 +57,19 @@ public class IndexSearcher implements Searcher, HitDetailer {(NutchConf.get().getInt("searcher.filter.cache.size", 16),NutchConf.get().getFloat("searcher.filter.cache.threshold", 0.05f));- /** Construct given a number of indexed segments. */- public IndexSearcher(File[] segmentDirs) throws IOException {- IndexReader[] readers = new IndexReader[segmentDirs.length];- for (int i = 0; i < segmentDirs.length; i++) {- readers[i] = IndexReader.open(new File(segmentDirs[i], "index"));+ /** Construct given a number of indexes. */+ public IndexSearcher(File[] indexDirs) throws IOException {+ IndexReader[] readers = new IndexReader[indexDirs.length];+ for (int i = 0; i < indexDirs.length; i++) {+ readers[i] = IndexReader.open(getDirectory(indexDirs[i]));}init(new MultiReader(readers));}- /** Construct given a directory containing fetched segments, and a separate- * directory naming their merged index. */- public IndexSearcher(String index)+ /** Construct given a single merged index. */+ public IndexSearcher(File index)throws IOException {- init(IndexReader.open(index));+ init(IndexReader.open(getDirectory(index)));}private void init(IndexReader reader) throws IOException {@@ -75,6 +78,15 @@ public class IndexSearcher implements Searcher, HitDetailer {this.luceneSearcher.setSimilarity(new NutchSimilarity());}+ private Directory getDirectory(File file) throws IOException {+ NutchFileSystem fs = NutchFileSystem.get();+ if ("local".equals(fs.getName())) {+ return FSDirectory.getDirectory(file, false);+ } else {+ return new NdfsDirectory(fs, file, false);+ }+ }+public Hits search(Query query, int numHits,String dedupField, String sortField, boolean reverse)diff --git a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java b/src/java/org/apache/nutch/searcher/LinkDbInlinks.javanew file mode 100644index 000000000..d76d3b582--- /dev/null+++ b/src/java/org/apache/nutch/searcher/LinkDbInlinks.java@@ -0,0 +1,32 @@+/*+ * Created on Nov 23, 2005+ * Author: Andrzej Bialecki <[email protected]>+ *+ */+package org.apache.nutch.searcher;++import java.io.IOException;++import org.apache.nutch.crawl.Inlinks;+import org.apache.nutch.crawl.LinkDbReader;+import org.apache.nutch.fs.NutchFileSystem;+import org.apache.nutch.io.UTF8;++import java.io.File;++public class LinkDbInlinks implements HitInlinks {++ private LinkDbReader linkdb = null;++ public LinkDbInlinks(NutchFileSystem fs, File dir) {+ linkdb = new LinkDbReader(fs, dir);+ }++ public String[] getAnchors(HitDetails details) throws IOException {+ return linkdb.getAnchors(new UTF8(details.getValue("url")));+ }++ public Inlinks getInlinks(HitDetails details) throws IOException {+ return linkdb.getInlinks(new UTF8(details.getValue("url")));+ }+}diff --git a/src/java/org/apache/nutch/searcher/NutchBean.java b/src/java/org/apache/nutch/searcher/NutchBean.javaindex 984780a10..4d74997f2 100644--- a/src/java/org/apache/nutch/searcher/NutchBean.java+++ b/src/java/org/apache/nutch/searcher/NutchBean.java@@ -25,13 +25,15 @@ import org.apache.nutch.fs.*;import org.apache.nutch.util.*;import org.apache.nutch.parse.*;import org.apache.nutch.indexer.*;+import org.apache.nutch.crawl.Inlinks;+import org.apache.nutch.crawl.LinkDbReader;/*** One stop shopping for search-related functionality.* @version $Id: NutchBean.java,v 1.19 2005/02/07 19:10:08 cutting Exp $*/public class NutchBean- implements Searcher, HitDetailer, HitSummarizer, HitContent,+ implements Searcher, HitDetailer, HitSummarizer, HitContent, HitInlinks,DistributedSearch.Protocol {public static final Logger LOG =@@ -41,12 +43,15 @@ public class NutchBeanLogFormatter.setShowThreadIDs(true);}+ private NutchFileSystem fs = NutchFileSystem.get();+private String[] segmentNames;private Searcher searcher;private HitDetailer detailer;private HitSummarizer summarizer;private HitContent content;+ private HitInlinks linkDb;private float RAW_HITS_FACTOR =NutchConf.get().getFloat("searcher.hostgrouping.rawhits.factor", 2.0f);@@ -68,33 +73,38 @@ public class NutchBean/** Construct reading from connected directory. */public NutchBean() throws IOException {- this(new File(NutchConf.get().get("searcher.dir", ".")));+ this(new File(NutchConf.get().get("searcher.dir", "crawl")));}/** Construct in a named directory. */public NutchBean(File dir) throws IOException {File servers = new File(dir, "search-servers.txt");- if (servers.exists()) {+ if (fs.exists(servers)) {LOG.info("searching servers in " + servers.getCanonicalPath());init(new DistributedSearch.Client(servers));} else {- init(new File(dir, "index"), new File(dir, "segments"));+ init(new File(dir, "index"),+ new File(dir, "indexes"),+ new File(dir, "segments"),+ new File(dir, "linkdb"));}}- private void init(File indexDir, File segmentsDir) throws IOException {+ private void init(File indexDir, File indexesDir, File segmentsDir,+ File linkDb)+ throws IOException {IndexSearcher indexSearcher;- if (indexDir.exists()) {- LOG.info("opening merged index in " + indexDir.getCanonicalPath());- indexSearcher = new IndexSearcher(indexDir.getCanonicalPath());+ if (fs.exists(indexDir)) {+ LOG.info("opening merged index in " + indexDir);+ indexSearcher = new IndexSearcher(indexDir);} else {- LOG.info("opening segment indexes in " + segmentsDir.getCanonicalPath());+ LOG.info("opening indexes in " + indexesDir);Vector vDirs=new Vector();- File [] directories = segmentsDir.listFiles();- for(int i = 0; i < directories.length; i++) {+ File [] directories = fs.listFiles(indexesDir);+ for(int i = 0; i < fs.listFiles(indexesDir).length; i++) {File indexdone = new File(directories[i], IndexSegment.DONE_NAME);- if(indexdone.exists() && indexdone.isFile()) {+ if(fs.isFile(indexdone)) {vDirs.add(directories[i]);}}@@ -107,14 +117,18 @@ public class NutchBeanindexSearcher = new IndexSearcher(directories);}- FetchedSegments segments = new FetchedSegments(new LocalFileSystem(), segmentsDir.toString());+ LOG.info("opening segments in " + segmentsDir);+ FetchedSegments segments = new FetchedSegments(fs, segmentsDir.toString());this.segmentNames = segments.getSegmentNames();-+this.searcher = indexSearcher;this.detailer = indexSearcher;this.summarizer = segments;this.content = segments;++ LOG.info("opening linkdb in " + linkDb);+ this.linkDb = new LinkDbInlinks(fs, linkDb);}private void init(DistributedSearch.Client client) {@@ -123,6 +137,7 @@ public class NutchBeanthis.detailer = client;this.summarizer = client;this.content = client;+ this.linkDb = client;}@@ -310,7 +325,11 @@ public class NutchBean}public String[] getAnchors(HitDetails hit) throws IOException {- return content.getAnchors(hit);+ return linkDb.getAnchors(hit);+ }++ public Inlinks getInlinks(HitDetails hit) throws IOException {+ return linkDb.getInlinks(hit);}public long getFetchDate(HitDetails hit) throws IOException {@@ -337,7 +356,7 @@ public class NutchBeanString[] summaries = bean.getSummary(details, query);for (int i = 0; i < hits.getLength(); i++) {- System.out.println(" "+i+" "+ details[i]);// + "\n" + summaries[i]);+ System.out.println(" "+i+" "+ details[i] + "\n" + summaries[i]);}}diff --git a/src/java/org/apache/nutch/util/Daemon.java b/src/java/org/apache/nutch/util/Daemon.javaindex 6a2d97398..e05e4bc8b 100644--- a/src/java/org/apache/nutch/util/Daemon.java+++ b/src/java/org/apache/nutch/util/Daemon.java@@ -23,6 +23,7 @@ public class Daemon extends Thread {setDaemon(true); // always a daemon}+ Runnable runnable = null;/** Construct a daemon thread. */public Daemon() {super();@@ -31,6 +32,11 @@ public class Daemon extends Thread {/** Construct a daemon thread. */public Daemon(Runnable runnable) {super(runnable);+ this.runnable = runnable;+ this.setName(((Object)runnable).toString());}+ public Runnable getRunnable() {+ return runnable;+ }}diff --git a/src/java/org/apache/nutch/util/LogFormatter.java b/src/java/org/apache/nutch/util/LogFormatter.javaindex d5d7de657..84e595347 100644--- a/src/java/org/apache/nutch/util/LogFormatter.java+++ b/src/java/org/apache/nutch/util/LogFormatter.java@@ -70,8 +70,10 @@ public class LogFormatter extends Formatter {StringBuffer buffer = new StringBuffer();// the date- date.setTime(record.getMillis());- formatter.format(date, buffer, new FieldPosition(0));+ if (showTime) {+ date.setTime(record.getMillis());+ formatter.format(date, buffer, new FieldPosition(0));+ }// the thread idif (showThreadIDs) {diff --git a/src/java/org/apache/nutch/util/NutchConf.java b/src/java/org/apache/nutch/util/NutchConf.javaindex 89e3eb860..d856e0838 100644--- a/src/java/org/apache/nutch/util/NutchConf.java+++ b/src/java/org/apache/nutch/util/NutchConf.java@@ -30,14 +30,17 @@ import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;/** Provides access to Nutch configuration parameters.- *+ * <p>An ordered list of configuration parameter files with+ * default and always-overrides site parameters.* <p>Default values for all parameters are specified in a file named* <tt>nutch-default.xml</tt> located on the classpath. Overrides for these* defaults should be in an optional file named <tt>nutch-site.xml</tt>, also* located on the classpath. Typically these files reside in the* <tt>conf/</tt> subdirectory at the top-level of a Nutch installation.+ * <p>The resource files are read upon first access of values (set, get,+ * or write) after {@link #addConfResource(String)} or+ * {@link #addConfResource(File)}.*/-public class NutchConf {private static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.util.NutchConf");@@ -47,7 +50,7 @@ public class NutchConf {/** Return the default configuration. */public static NutchConf get() { return DEFAULT; }- private List resourceNames = new ArrayList();+ private ArrayList resourceNames = new ArrayList();private Properties properties;private ClassLoader classLoader = NutchConf.class.getClassLoader();@@ -57,6 +60,13 @@ public class NutchConf {resourceNames.add("nutch-site.xml");}+ /** A new configuration with the same settings cloned from another. */+ public NutchConf(NutchConf other) {+ this.resourceNames = (ArrayList)other.resourceNames.clone();+ if (other.properties != null)+ this.properties = (Properties)other.properties.clone();+ }+/** Adds a resource name to the chain of resources read. Such resources are* located on the CLASSPATH. The first resource is always* <tt>nutch-default.xml</tt>, and the last is always@@ -131,6 +141,11 @@ public class NutchConf {}}+ /** Sets the value of the <code>name</code> property to a long. */+ public void setLong(String name, long value) {+ set(name, Long.toString(value));+ }+/** Returns the value of the <code>name</code> property as a float. If no* such property is specified, or if the specified value is not a valid* float, then <code>defaultValue</code> is returned.@@ -160,6 +175,11 @@ public class NutchConf {else return defaultValue;}+ /** Sets the value of the <code>name</code> property to an integer. */+ public void setBoolean(String name, boolean value) {+ set(name, Boolean.toString(value));+ }+/** Returns the value of the <code>name</code> property as an array of* strings. If no such property is specified, then <code>null</code>* is returned. Values are whitespace or comma delimted.@@ -377,6 +397,25 @@ public class NutchConf {}}++ public String toString() {+ StringBuffer sb = new StringBuffer(resourceNames.size()*30);+ sb.append("NutchConf: ");+ ListIterator i = resourceNames.listIterator();+ while (i.hasNext()) {+ if (i.nextIndex() != 0) {+ sb.append(" , ");+ }+ Object obj = i.next();+ if (obj instanceof File) {+ sb.append((File)obj);+ } else {+ sb.append((String)obj);+ }+ }+ return sb.toString();+ }+/** For debugging. List non-default properties to the terminal and exit. */public static void main(String[] args) throws Exception {get().write(System.out);diff --git a/src/java/org/apache/nutch/util/NutchConfigurable.java b/src/java/org/apache/nutch/util/NutchConfigurable.javanew file mode 100644index 000000000..6f1a3547c--- /dev/null+++ b/src/java/org/apache/nutch/util/NutchConfigurable.java@@ -0,0 +1,27 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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;++/** Something that may be configured with a {@link NutchConf}. */+public interface NutchConfigurable {++ /** Set the configuration to be used by this object. */+ void setConf(NutchConf conf);++ /** Return the configuration used by this object. */+ NutchConf getConf();+}diff --git a/src/java/org/apache/nutch/util/NutchConfigured.java b/src/java/org/apache/nutch/util/NutchConfigured.javanew file mode 100644index 000000000..0ada1abf0--- /dev/null+++ b/src/java/org/apache/nutch/util/NutchConfigured.java@@ -0,0 +1,39 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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;++/** Base class for things that may be configured with a {@link NutchConf}. */+public class NutchConfigured implements NutchConfigurable {++ private NutchConf conf;++ /** Construct a NutchConfigured. */+ public NutchConfigured(NutchConf conf) {+ setConf(conf);+ }++ // inherit javadoc+ public void setConf(NutchConf conf) {+ this.conf = conf;+ }++ // inherit javadoc+ public NutchConf getConf() {+ return conf;+ }++}diff --git a/src/java/org/apache/nutch/util/Progress.java b/src/java/org/apache/nutch/util/Progress.javanew file mode 100644index 000000000..d9f1794a5--- /dev/null+++ b/src/java/org/apache/nutch/util/Progress.java@@ -0,0 +1,116 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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 java.util.ArrayList;++/** Utility to assist with generation of progress reports. Applications build+ * a hierarchy of {@link Progress} instances, each modelling a phase of+ * execution. The root is constructed with {@link #Progress()}. Nodes for+ * sub-phases are created by calling {@link #addPhase()}.+ */+public class Progress {+ private String status = "";+ private float progress;+ private int currentPhase;+ private ArrayList phases = new ArrayList();+ private Progress parent;+ private float progressPerPhase;++ /** Creates a new root node. */+ public Progress() {}++ /** Adds a named node to the tree. */+ public Progress addPhase(String status) {+ Progress phase = addPhase();+ phase.setStatus(status);+ return phase;+ }++ /** Adds a node to the tree. */+ public Progress addPhase() {+ Progress phase = new Progress();+ phases.add(phase);+ phase.parent = this;+ progressPerPhase = 1.0f / (float)phases.size();+ return phase;+ }++ /** Called during execution to move to the next phase at this level in the+ * tree. */+ public void startNextPhase() {+ currentPhase++;+ }++ /** Returns the current sub-node executing. */+ public Progress phase() {+ return (Progress)phases.get(currentPhase);+ }++ /** Completes this node, moving the parent node to its next child. */+ public void complete() {+ progress = 1.0f;+ if (parent != null) {+ parent.startNextPhase();+ }+ }++ /** Called during execution on a leaf node to set its progress. */+ public void set(float progress) {+ this.progress = progress;+ }++ /** Returns the overall progress of the root. */+ public float get() {+ Progress node = this;+ while (node.parent != null) { // find the root+ node = parent;+ }+ return node.getInternal();+ }++ /** Computes progress in this node. */+ private float getInternal() {+ int phaseCount = phases.size();+ if (phaseCount != 0) {+ float subProgress =+ currentPhase < phaseCount ? phase().getInternal() : 0.0f;+ return progressPerPhase*(currentPhase + subProgress);+ } else {+ return progress;+ }+ }++ public void setStatus(String status) {+ this.status = status;+ }++ public String toString() {+ StringBuffer result = new StringBuffer();+ toString(result);+ return result.toString();+ }++ private void toString(StringBuffer buffer) {+ buffer.append(status);+ if (phases.size() != 0 && currentPhase < phases.size()) {+ buffer.append(" > ");+ phase().toString(buffer);+ }+ }++}diff --git a/src/mapred/README.txt b/src/mapred/README.txtdeleted file mode 100644index 022e5cdc8..000000000--- a/src/mapred/README.txt+++ /dev/null@@ -1 +0,0 @@-This directory contains some demonstration map/reduce jobs.diff --git a/src/mapred/unknown-content.xml b/src/mapred/unknown-content.xmldeleted file mode 100644index 1eb69e60d..000000000--- a/src/mapred/unknown-content.xml+++ /dev/null@@ -1,57 +0,0 @@-<?xml version="1.0"?>--<!-- extract unknown parse content types from a nutch log -->--<nutch-conf>--<property>- <name>mapred.input.dir</name>- <value>sample</value>-</property>--<property>- <name>mapred.output.dir</name>- <value>freqs</value>-</property>--<property>- <name>mapred.mapper.class</name>- <value>org.apache.nutch.mapReduce.lib.RegexMapper</value>-</property>--<property>- <name>mapred.mapper.regex</name>- <value>Content-Type not .*: (.*)</value>-</property>--<property>- <name>mapred.mapper.regex.group</name>- <value>1</value>-</property>--<property>- <name>mapred.reduce.tasks</name>- <value>1</value>-</property>--<property>- <name>mapred.combiner.class</name>- <value>org.apache.nutch.mapReduce.lib.LongSumReducer</value>-</property>--<property>- <name>mapred.reducer.class</name>- <value>org.apache.nutch.mapReduce.lib.LongSumReducer</value>-</property>--<property>- <name>mapred.output.key.class</name>- <value>org.apache.nutch.io.UTF8</value>-</property>--<property>- <name>mapred.output.value.class</name>- <value>org.apache.nutch.io.LongWritable</value>-</property>--</nutch-conf>diff --git a/src/mapred/word-count.xml b/src/mapred/word-count.xmldeleted file mode 100644index 65dceb513..000000000--- a/src/mapred/word-count.xml+++ /dev/null@@ -1,37 +0,0 @@-<?xml version="1.0"?>--<!-- map/reduce configuration file -->--<nutch-conf>--<property>- <name>mapred.input.dir</name>- <value>sample</value>-</property>--<property>- <name>mapred.output.dir</name>- <value>freqs</value>-</property>--<property>- <name>mapred.mapper.class</name>- <value>org.apache.nutch.mapReduce.lib.TokenCountMapper</value>-</property>--<property>- <name>mapred.reducer.class</name>- <value>org.apache.nutch.mapReduce.lib.LongSumReducer</value>-</property>--<property>- <name>mapred.output.key.class</name>- <value>org.apache.nutch.io.UTF8</value>-</property>--<property>- <name>mapred.output.value.class</name>- <value>org.apache.nutch.io.LongWritable</value>-</property>--</nutch-conf>diff --git a/src/plugin/build-plugin.xml b/src/plugin/build-plugin.xmlindex a86a49ac6..8123be8ff 100755--- a/src/plugin/build-plugin.xml+++ b/src/plugin/build-plugin.xml@@ -7,8 +7,7 @@<property name="name" value="${ant.project.name}"/><property name="root" value="${basedir}"/>- <!-- Load all the default properties, and any the user wants -->- <!-- to contribute (without having to type -D or edit this file -->+ <!-- load plugin-specific properties first --><property file="${user.home}/${name}.build.properties" /><property file="${root}/build.properties" />@@ -27,13 +26,8 @@<property name="deploy.dir" location="${nutch.root}/build/plugins/${name}"/>- <property name="javac.deprecation" value="off"/>- <property name="javac.debug" value="on"/>-- <property name="javadoc.link"- value="http://java.sun.com/j2se/1.4/docs/api/"/>-- <property name="build.encoding" value="ISO-8859-1"/>+ <!-- load nutch defaults last so that they can be overridden above -->+ <property file="${nutch.root}/default.properties" /><path id="plugin.deps"/>@@ -85,6 +79,9 @@includes="**/*.java"destdir="${build.classes}"debug="${javac.debug}"+ optimize="${javac.optimize}"+ target="${javac.version}"+ source="${javac.version}"deprecation="${javac.deprecation}"><classpath refid="classpath"/></javac>@@ -126,7 +123,11 @@srcdir="${src.test}"includes="**/*.java"destdir="${build.test}"- debug="${debug}">+ debug="${javac.debug}"+ optimize="${javac.optimize}"+ target="${javac.version}"+ source="${javac.version}"+ deprecation="${javac.deprecation}"><classpath refid="test.classpath"/></javac></target>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.javaindex b138755c9..3bce99e2f 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@@ -296,23 +296,29 @@ public class DOMContentUtils {if (node.getNodeType() == Node.ELEMENT_NODE) {LinkParams params = (LinkParams)linkParams.get(node.getNodeName().toLowerCase());if (params != null) {- if (shouldThrowAwayLink(node, children, childLen, params)) {- // this has no inner structure or just a single nested- // anchor-- toss it!- } else {+ if (!shouldThrowAwayLink(node, children, childLen, params)) {StringBuffer linkText = new StringBuffer();getText(linkText, node, true);NamedNodeMap attrs = node.getAttributes();String target = null;+ boolean noFollow = false;+ boolean post = false;for (int i= 0; i < attrs.getLength(); i++ ) {- if (params.attrName.equalsIgnoreCase(attrs.item(i).getNodeName())) {- target = attrs.item(i).getNodeValue();- break;+ Node attr = attrs.item(i);+ String attrName = attr.getNodeName();+ if (params.attrName.equalsIgnoreCase(attrName)) {+ target = attr.getNodeValue();+ } else if ("rel".equalsIgnoreCase(attrName) &&+ "nofollow".equalsIgnoreCase(attr.getNodeValue())) {+ noFollow = true;+ } else if ("method".equalsIgnoreCase(attrName) &&+ "post".equalsIgnoreCase(attr.getNodeValue())) {+ post = true;}}- if (target != null)+ if (target != null && !noFollow && !post)try {URL url = new URL(base, target);outlinks.add(new Outlink(url.toString(),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.javaindex f12fb3f88..3ed211a31 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@@ -113,6 +113,12 @@ public class TestDOMContentUtils extends TestCase {+ "<h2>End\tthis\rmadness\n!</h2>\r\n"+ " . . . ."+ "</body> </html>"),++ // test that <a rel=nofollow> links are not returned+ new String("<html><head></head><body>"+ + "<a href=\"http://www.nutch.org\" rel=\"nofollow\"> ignore </a>"+ + "<a rel=\"nofollow\" href=\"http://www.nutch.org\"> ignore </a>"+ + "</body></html>"),};private static String[] testBaseHrefs= {@@ -123,6 +129,7 @@ public class TestDOMContentUtils extends TestCase {"http://www.nutch.org/frames/","http://www.nutch.org/maps/","http://www.nutch.org/whitespace/",+ "http://www.nutch.org//",};private static final DocumentFragment testDOMs[]=@@ -145,6 +152,7 @@ public class TestDOMContentUtils extends TestCase {+ "one two three space here space there no space "+ "one two two three three four put some text here and there. "+ "End this madness ! . . . .",+ "ignore ignore",};private static final String[] answerTitle= {@@ -155,6 +163,7 @@ public class TestDOMContentUtils extends TestCase {"my title","my title","my title",+ "",};// note: should be in page-order@@ -214,6 +223,8 @@ public class TestDOMContentUtils extends TestCase {{new Outlink("http://www.nutch.org/index.html", "whitespace test"),},+ {+ }};} catch (MalformedURLException e) {diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.javaindex 824d1c3c4..f9e94e88b 100644--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java@@ -53,6 +53,9 @@ public class RobotRulesParser {private static final boolean ALLOW_FORBIDDEN =NutchConf.get().getBoolean("http.robots.403.allow", false);+ private static final int MAX_REDIRECTS =+ NutchConf.get().getInt("http.redirect.max", 3);+private static final String[] AGENTS = getAgents();private static final Hashtable CACHE = new Hashtable();@@ -377,16 +380,30 @@ public class RobotRulesParser {RobotRuleSet robotRules = (RobotRuleSet)CACHE.get(host);if (robotRules == null) { // cache miss- HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"));-- if (response.getCode() == 200) // found rules: parse them- robotRules = new RobotRulesParser().parseRules(response.getContent());- else if ( (response.getCode() == 403) && (!ALLOW_FORBIDDEN) )- robotRules = FORBID_ALL_RULES; // use forbid all- else- robotRules = EMPTY_RULES; // use default rules+ int redirects = 0;+ do {+ HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"));++ int code = response.getCode();++ if (code == 200) { // found rules: parse them+ robotRules = new RobotRulesParser().parseRules(response.getContent());+ } else if ( (code == 403) && (!ALLOW_FORBIDDEN) ) {+ robotRules = FORBID_ALL_RULES; // use forbid all+ } else if (code >= 300 && code < 400) { // handle redirect+ if (redirects == MAX_REDIRECTS) {+ robotRules = EMPTY_RULES;+ } else {+ url = new URL(url, response.getHeader("Location"));+ LOG.fine("redirect to " + url);+ redirects++;+ }+ } else {+ robotRules = EMPTY_RULES; // use default rules+ }+ } while (robotRules == null);- CACHE.put(host, robotRules); // cache rules for host+ CACHE.put(host, robotRules); // cache rules for host}String path = url.getPath(); // check rulesdiff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.javaindex 8d9eb7dc8..20d0b3ac8 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java@@ -60,10 +60,14 @@ public class HttpResponse {}public HttpResponse(URL url) throws IOException {+ this(url, false);+ }++ HttpResponse(URL url, boolean followRedirects) throws IOException {this.base = url.toString();this.orig = url.toString();GetMethod get = new GetMethod(this.orig);- get.setFollowRedirects(false);+ get.setFollowRedirects(followRedirects);get.setRequestHeader("User-Agent", Http.AGENT_STRING);HttpMethodParams params = get.getParams();// some servers cannot digest the new protocoldiff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.javaindex 98bd8b09e..3e4400eaf 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java@@ -379,7 +379,8 @@ public class RobotRulesParser {if (robotRules == null) { // cache missLOG.fine("cache miss " + url);try {- HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"));+ HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"),+ true);if (response.getCode() == 200) // found rules: parse themrobotRules = new RobotRulesParser().parseRules(response.getContent());diff --git a/src/site/src/documentation/content/xdocs/tutorial.xml b/src/site/src/documentation/content/xdocs/tutorial.xmlindex 5deabf40c..4d7a0ce22 100644--- a/src/site/src/documentation/content/xdocs/tutorial.xml+++ b/src/site/src/documentation/content/xdocs/tutorial.xml@@ -66,11 +66,11 @@ around one million pages on a handful of web servers.</p><ol>-<li>Create a flat file of root urls. For example, to crawl the-<code>nutch</code> site you might start with a file named-<code>urls</code> containing just the Nutch home page. All other-Nutch pages should be reachable from this page. The <code>urls</code>-file would thus look like:+<li>Create a directory with a flat file of root urls. For example, to+crawl the <code>nutch</code> site you might start with a file named+<code>urls/nutch</code> containing the url of just the Nutch home+page. All other Nutch pages should be reachable from this page. The+<code>urls/nutch</code> file would thus contain:<source>http://lucene.apache.org/nutch/</source>@@ -97,24 +97,28 @@ crawl command. Its options include:</p><ul><li><code>-dir</code> <em>dir</em> names the directory to put the crawl in.</li>-<li><code>-depth</code> <em>depth</em> indicates the link depth from the root-page that should be crawled.</li>-<li><code>-delay</code> <em>delay</em> determines the number of seconds-between accesses to each host.</li><li><code>-threads</code> <em>threads</em> determines the number ofthreads that will fetch in parallel.</li>+<li><code>-depth</code> <em>depth</em> indicates the link depth from the root+page that should be crawled.</li>+<li><code>-topN</code> <em>N</em> determines the maximum number of pages that+will be retrieved at each level up to the depth.</li></ul><p>For example, a typical call might be:</p><source>-bin/nutch crawl urls -dir crawl.test -depth 3 >& crawl.log+bin/nutch crawl urls -dir crawl -depth 3 -topN 50</source>-<p>Typically one starts testing one's configuration by crawling at low-depths, and watching the output to check that desired pages are found.-Once one is more confident of the configuration, then an appropriate-depth for a full crawl is around 10.</p>+<p>Typically one starts testing one's configuration by crawling at+shallow depths, sharply limiting the number of pages fetched at each+level (<code>-topN</code>), and watching the output to check that+desired pages are fetched and undesirable pages are not. Once one is+confident of the configuration, then an appropriate depth for a full+crawl is around 10. The number of pages per level+(<code>-topN</code>) for a full crawl can be from tens of thousands to+millions, depending on your resources.</p><p>Once crawling has completed, one can skip to the Searching sectionbelow.</p>@@ -131,54 +135,62 @@ take weeks to complete, running on multiple machines.</p><section><title>Whole-web: Concepts</title>-<p>Nutch data is of two types:</p>+<p>Nutch data is composed of:</p><ol>- <li>The web database. This contains information about every-page known to Nutch, and about links between those pages.</li>- <li>A set of segments. Each segment is a set of pages that are-fetched and indexed as a unit. Segment data consists of the-following types:</li>++ <li>The crawl database, or <em>crawldb</em>. This contains+information about every url known to Nutch, including whether it was+fetched, and, if so, when.</li>++ <li>The link database, or <em>linkdb</em>. This contains the list+of known links to each url, including both the source url and anchor+text of the link.</li>++ <li>A set of <em>segments</em>. Each segment is a set of urls that are+fetched as a unit. Segments are directories with the following+subdirectories:</li>+<li><ul>- <li>a <em>fetchlist</em> is a file-that names a set of pages to be fetched</li>- <li>the<em> fetcher output</em> is a-set of files containing the fetched pages</li>- <li>the <em>index </em>is a-Lucene-format index of the fetcher output.</li>+ <li>a <em>crawl_generate</em> names a set of urls to be fetched</li>+ <li>a <em>crawl_fetch</em> contains the status of fetching each url</li>+ <li>a <em>content</em> contains the content of each url</li>+ <li>a <em>parse_text</em> contains the parsed text of each url</li>+ <li>a <em>parse_data</em> contains outlinks and metadata parsed+ from each url</li>+ <li>a <em>crawl_parse</em> contains the outlink urls, used to+ update the crawldb</li></ul></li>++<li>The <em>indexes</em>are Lucene-format indexes.</li>+</ol>-<p>In the following examples we will keep our web database in a directory-named <code>db</code> and our segments-in a directory named <code>segments</code>:</p>-<source>mkdir db-mkdir segments</source></section><section><title>Whole-web: Boostrapping the Web Database</title>-<p>The admin tool is used to create a new, empty database:</p>-<source>bin/nutch admin db -create</source>--<p>The <em>injector</em> adds urls into the database. Let's inject-URLs from the <a href="http://dmoz.org/">DMOZ</a> Open-Directory. First we must download and uncompress the file listing all-of the DMOZ pages. (This is a 200+Mb file, so this will take a few-minutes.)</p>+<p>The <em>injector</em> adds urls to the crawldb. Let's inject URLs+from the <a href="http://dmoz.org/">DMOZ</a> Open Directory. First we+must download and uncompress the file listing all of the DMOZ pages.+(This is a 200+Mb file, so this will take a few minutes.)</p><source>wget http://rdf.dmoz.org/rdf/content.rdf.u8.gzgunzip content.rdf.u8.gz</source>-<p>Next we inject a random subset of these pages into the web database.+<p>Next we select a random subset of these pages.(We use a random subset so that everyone who runs this tutorialdoesn't hammer the same sites.) DMOZ contains around three million-URLs. We inject one out of every 3000, so that we end up with+URLs. We select one out of every 5000, so that we end up witharound 1000 URLs:</p>-<source>bin/nutch inject db -dmozfile content.rdf.u8 -subset 3000</source>+<source>mkdir dmoz+bin/nutch org.apache.nutch.crawl.DmozParser content.rdf.u8 -subset 5000 > dmoz/urls</source>++<p>The parser also takes a few minutes, as it must parse the full+file. Finally, we initialize the crawl db with the selected urls.</p>-<p>This also takes a few minutes, as it must parse the full file.</p>+<source>bin/nutch inject crawl/crawldb dmoz</source><p>Now we have a web database with around 1000 as-yet unfetched URLs in it.</p>@@ -186,39 +198,39 @@ around 1000 URLs:</p><section><title>Whole-web: Fetching</title><p>To fetch, we first generate a fetchlist from the database:</p>-<source>bin/nutch generate db segments+<source>bin/nutch generate crawl/crawldb crawl/segments</source><p>This generates a fetchlist for all of the pages due to be fetched.The fetchlist is placed in a newly created segment directory.The segment directory is named by the time it's created. Wesave the name of this segment in the shell variable <code>s1</code>:</p>-<source>s1=`ls -d segments/2* | tail -1`+<source>s1=`ls -d crawl/segments/2* | tail -1`echo $s1</source><p>Now we run the fetcher on this segment with:</p><source>bin/nutch fetch $s1</source><p>When this is complete, we update the database with the results of thefetch:</p>-<source>bin/nutch updatedb db $s1</source>+<source>bin/nutch updatedb crawl/crawldb $s1</source><p>Now the database has entries for all of the pages referenced by theinitial set.</p><p>Now we fetch a new segment with the top-scoring 1000 pages:</p>-<source>bin/nutch generate db segments -topN 1000-s2=`ls -d segments/2* | tail -1`+<source>bin/nutch generate crawl/crawldb crawl/segments -topN 1000+s2=`ls -d crawl/segments/2* | tail -1`echo $s2bin/nutch fetch $s2-bin/nutch updatedb db $s2+bin/nutch updatedb crawl/crawldb $s2</source><p>Let's fetch one more round:</p><source>-bin/nutch generate db segments -topN 1000-s3=`ls -d segments/2* | tail -1`+bin/nutch generate crawl/crawldb crawl/segments -topN 1000+s3=`ls -d crawl/segments/2* | tail -1`echo $s3bin/nutch fetch $s3-bin/nutch updatedb db $s3+bin/nutch updatedb crawl/crawldb $s3</source><p>By this point we've fetched a few thousand pages. Let's index@@ -227,16 +239,20 @@ them!</p></section><section><title>Whole-web: Indexing</title>-<p>To index each segment we use the <code>index</code>-command, as follows:</p>-<source>bin/nutch index $s1-bin/nutch index $s2-bin/nutch index $s3</source>-<p>Then, before we can search a set of segments, we need to delete-duplicate pages. This is done with:</p>+<p>Before indexing we first invert all of the links, so that we may+index incoming anchor text with the pages.</p>++<source>bin/nutch invertlinks crawl/linkdb crawl/segments</source>++<p>To index the segments we use the <code>index</code> command, as follows:</p>++<source>bin/nutch index indexes crawl/linkdb crawl/segments/*</source>++<!-- <p>Then, before we can search a set of segments, we need to delete -->+<!-- duplicate pages. This is done with:</p> -->-<source>bin/nutch dedup segments dedup.tmp</source>+<!-- <source>bin/nutch dedup indexes</source> --><p>Now we're ready to search!</p>@@ -256,10 +272,8 @@ file may be installed with the commands:</p>cp nutch*.war ~/local/tomcat/webapps/ROOT.war</source>-<p>The webapp finds its indexes in <code>./segments</code>, relative-to where you start Tomcat, so, if you've done intranet crawling,-connect to your crawl directory, or, if you've done whole-web-crawling, don't change directories, and give the command:</p>+<p>The webapp finds its indexes in <code>./crawl</code>, relative+to where you start Tomcat, so use a command like:</p><source>~/local/tomcat/bin/catalina.sh start</source>diff --git a/src/test/org/apache/nutch/fs/TestNutchFileSystem.java b/src/test/org/apache/nutch/fs/TestNutchFileSystem.javanew file mode 100644index 000000000..3f415ded5--- /dev/null+++ b/src/test/org/apache/nutch/fs/TestNutchFileSystem.java@@ -0,0 +1,418 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.fs;++import java.io.*;+import java.util.*;+import junit.framework.TestCase;+import java.util.logging.*;++import org.apache.nutch.fs.*;+import org.apache.nutch.mapred.*;+import org.apache.nutch.mapred.lib.*;+import org.apache.nutch.io.*;+import org.apache.nutch.util.*;++public class TestNutchFileSystem extends TestCase {+ private static final Logger LOG = InputFormatBase.LOG;++ private static int BUFFER_SIZE =+ NutchConf.get().getInt("io.file.buffer.size", 4096);++ private static final long MEGA = 1024 * 1024;+ private static final int SEEKS_PER_FILE = 4;++ private static String ROOT = System.getProperty("test.build.data","fs_test");+ private static File CONTROL_DIR = new File(ROOT, "fs_control");+ private static File WRITE_DIR = new File(ROOT, "fs_write");+ private static File READ_DIR = new File(ROOT, "fs_read");+ private static File DATA_DIR = new File(ROOT, "fs_data");++ public void testFs() throws Exception {+ testFs(10 * MEGA, 100, 0);+ }++ public static void testFs(long megaBytes, int numFiles, long seed)+ throws Exception {++ NutchFileSystem fs = NutchFileSystem.get();++ if (seed == 0)+ seed = new Random().nextLong();++ LOG.info("seed = "+seed);++ createControlFile(fs, megaBytes, numFiles, seed);+ writeTest(fs, false);+ readTest(fs, false);+ seekTest(fs, false);+ }++ public static void createControlFile(NutchFileSystem fs,+ long megaBytes, int numFiles,+ long seed) throws Exception {++ LOG.info("creating control file: "+megaBytes+" bytes, "+numFiles+" files");++ File controlFile = new File(CONTROL_DIR, "files");+ fs.delete(controlFile);+ Random random = new Random(seed);++ SequenceFile.Writer writer =+ new SequenceFile.Writer(fs, controlFile.toString(),+ UTF8.class, LongWritable.class);++ long totalSize = 0;+ long maxSize = ((megaBytes / numFiles) * 2) + 1;+ try {+ while (totalSize < megaBytes) {+ UTF8 name = new UTF8(Long.toString(random.nextLong()));++ long size = random.nextLong();+ if (size < 0)+ size = -size;+ size = size % maxSize;++ //LOG.info(" adding: name="+name+" size="+size);++ writer.append(name, new LongWritable(size));++ totalSize += size;+ }+ } finally {+ writer.close();+ }+ LOG.info("created control file for: "+totalSize+" bytes");+ }++ public static class WriteMapper extends NutchConfigured implements Mapper {+ private Random random = new Random();+ private byte[] buffer = new byte[BUFFER_SIZE];+ private NutchFileSystem fs;+ private boolean fastCheck;++ {+ try {+ fs = NutchFileSystem.get();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ public WriteMapper() { super(null); }++ public WriteMapper(NutchConf conf) { super(conf); }++ public void configure(JobConf job) {+ setConf(job);+ fastCheck = job.getBoolean("fs.test.fastCheck", false);+ }++ public void map(WritableComparable key, Writable value,+ OutputCollector collector, Reporter reporter)+ throws IOException {+ String name = ((UTF8)key).toString();+ long size = ((LongWritable)value).get();+ long seed = Long.parseLong(name);++ random.setSeed(seed);+ reporter.setStatus("creating " + name);++ OutputStream out = fs.create(new File(DATA_DIR, name));++ long written = 0;+ try {+ while (written < size) {+ if (fastCheck) {+ Arrays.fill(buffer, (byte)random.nextInt(Byte.MAX_VALUE));+ } else {+ random.nextBytes(buffer);+ }+ long remains = size - written;+ int length = (remains<=buffer.length) ? (int)remains : buffer.length;+ out.write(buffer, 0, length);+ written += length;+ reporter.setStatus("writing "+name+"@"+written+"/"+size);+ }+ } finally {+ out.close();+ }++ collector.collect(new UTF8("bytes"), new LongWritable(written));++ reporter.setStatus("wrote " + name);+ }+ }++ public static void writeTest(NutchFileSystem fs, boolean fastCheck)+ throws Exception {++ fs.delete(DATA_DIR);+ fs.delete(WRITE_DIR);++ JobConf job = new JobConf(NutchConf.get());+ job.setBoolean("fs.test.fastCheck", fastCheck);++ job.setInputDir(CONTROL_DIR);+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(LongWritable.class);++ job.setMapperClass(WriteMapper.class);+ job.setReducerClass(LongSumReducer.class);++ job.setOutputDir(WRITE_DIR);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(LongWritable.class);+ job.setNumReduceTasks(1);+ JobClient.runJob(job);+ }++ public static class ReadMapper extends NutchConfigured implements Mapper {+ private Random random = new Random();+ private byte[] buffer = new byte[BUFFER_SIZE];+ private byte[] check = new byte[BUFFER_SIZE];+ private NutchFileSystem fs;+ private boolean fastCheck;++ {+ try {+ fs = NutchFileSystem.get();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ public ReadMapper() { super(null); }++ public ReadMapper(NutchConf conf) { super(conf); }++ public void configure(JobConf job) {+ setConf(job);+ fastCheck = job.getBoolean("fs.test.fastCheck", false);+ }++ public void map(WritableComparable key, Writable value,+ OutputCollector collector, Reporter reporter)+ throws IOException {+ String name = ((UTF8)key).toString();+ long size = ((LongWritable)value).get();+ long seed = Long.parseLong(name);++ random.setSeed(seed);+ reporter.setStatus("opening " + name);++ DataInputStream in =+ new DataInputStream(fs.open(new File(DATA_DIR, name)));++ long read = 0;+ try {+ while (read < size) {+ long remains = size - read;+ int n = (remains<=buffer.length) ? (int)remains : buffer.length;+ in.readFully(buffer, 0, n);+ read += n;+ if (fastCheck) {+ Arrays.fill(check, (byte)random.nextInt(Byte.MAX_VALUE));+ } else {+ random.nextBytes(check);+ }+ if (n != buffer.length) {+ Arrays.fill(buffer, n, buffer.length, (byte)0);+ Arrays.fill(check, n, check.length, (byte)0);+ }+ assertTrue(Arrays.equals(buffer, check));++ reporter.setStatus("reading "+name+"@"+read+"/"+size);++ }+ } finally {+ in.close();+ }++ collector.collect(new UTF8("bytes"), new LongWritable(read));++ reporter.setStatus("read " + name);+ }+ }++ public static void readTest(NutchFileSystem fs, boolean fastCheck)+ throws Exception {++ fs.delete(READ_DIR);++ JobConf job = new JobConf(NutchConf.get());+ job.setBoolean("fs.test.fastCheck", fastCheck);+++ job.setInputDir(CONTROL_DIR);+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(LongWritable.class);++ job.setMapperClass(ReadMapper.class);+ job.setReducerClass(LongSumReducer.class);++ job.setOutputDir(READ_DIR);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(LongWritable.class);+ job.setNumReduceTasks(1);+ JobClient.runJob(job);+ }+++ public static class SeekMapper extends NutchConfigured implements Mapper {+ private Random random = new Random();+ private byte[] check = new byte[BUFFER_SIZE];+ private NutchFileSystem fs;+ private boolean fastCheck;++ {+ try {+ fs = NutchFileSystem.get();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ public SeekMapper() { super(null); }++ public SeekMapper(NutchConf conf) { super(conf); }++ public void configure(JobConf job) {+ setConf(job);+ fastCheck = job.getBoolean("fs.test.fastCheck", false);+ }++ public void map(WritableComparable key, Writable value,+ OutputCollector collector, Reporter reporter)+ throws IOException {+ String name = ((UTF8)key).toString();+ long size = ((LongWritable)value).get();+ long seed = Long.parseLong(name);++ if (size == 0) return;++ reporter.setStatus("opening " + name);++ NFSDataInputStream in = fs.open(new File(DATA_DIR, name));++ try {+ for (int i = 0; i < SEEKS_PER_FILE; i++) {+ // generate a random position+ long position = Math.abs(random.nextLong()) % size;++ // seek file to that position+ reporter.setStatus("seeking " + name);+ in.seek(position);+ byte b = in.readByte();++ // check that byte matches+ byte checkByte = 0;+ // advance random state to that position+ random.setSeed(seed);+ for (int p = 0; p <= position; p+= check.length) {+ reporter.setStatus("generating data for " + name);+ if (fastCheck) {+ checkByte = (byte)random.nextInt(Byte.MAX_VALUE);+ } else {+ random.nextBytes(check);+ checkByte = check[(int)(position % check.length)];+ }+ }+ assertEquals(b, checkByte);+ }+ } finally {+ in.close();+ }+ }+ }++ public static void seekTest(NutchFileSystem fs, boolean fastCheck)+ throws Exception {++ fs.delete(READ_DIR);++ JobConf job = new JobConf(NutchConf.get());+ job.setBoolean("fs.test.fastCheck", fastCheck);++ job.setInputDir(CONTROL_DIR);+ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(LongWritable.class);++ job.setMapperClass(SeekMapper.class);+ job.setReducerClass(LongSumReducer.class);++ job.setOutputDir(READ_DIR);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(LongWritable.class);+ job.setNumReduceTasks(1);+ JobClient.runJob(job);+ }+++ public static void main(String[] args) throws Exception {+ int megaBytes = 10;+ int files = 100;+ boolean noRead = false;+ boolean noWrite = false;+ boolean noSeek = false;+ boolean fastCheck = false;+ long seed = new Random().nextLong();++ String usage = "Usage: TestNutchFileSystem -files N -megaBytes M [-noread] [-nowrite] [-noseek] [-fastcheck]";++ if (args.length == 0) {+ System.err.println(usage);+ System.exit(-1);+ }+ for (int i = 0; i < args.length; i++) { // parse command line+ if (args[i].equals("-files")) {+ files = Integer.parseInt(args[++i]);+ } else if (args[i].equals("-megaBytes")) {+ megaBytes = Integer.parseInt(args[++i]);+ } else if (args[i].equals("-noread")) {+ noRead = true;+ } else if (args[i].equals("-nowrite")) {+ noWrite = true;+ } else if (args[i].equals("-noseek")) {+ noSeek = true;+ } else if (args[i].equals("-fastcheck")) {+ fastCheck = true;+ }+ }++ LOG.info("seed = "+seed);+ LOG.info("files = " + files);+ LOG.info("megaBytes = " + megaBytes);++ NutchFileSystem fs = NutchFileSystem.get();++ if (!noWrite) {+ createControlFile(fs, megaBytes*MEGA, files, seed);+ writeTest(fs, fastCheck);+ }+ if (!noRead) {+ readTest(fs, fastCheck);+ }+ if (!noSeek) {+ seekTest(fs, fastCheck);+ }+ }++}diff --git a/src/test/org/apache/nutch/io/TestSequenceFile.java b/src/test/org/apache/nutch/io/TestSequenceFile.javaindex b3e3c9c82..6678c2db5 100644--- a/src/test/org/apache/nutch/io/TestSequenceFile.java+++ b/src/test/org/apache/nutch/io/TestSequenceFile.java@@ -42,7 +42,7 @@ public class TestSequenceFile extends TestCase {NutchFileSystem nfs = new LocalFileSystem();try {//LOG.setLevel(Level.FINE);- writeTest(nfs, count, seed, file);+ writeTest(nfs, count, seed, file, false);readTest(nfs, count, seed, file);sortTest(nfs, count, megabytes, factor, false, file);@@ -61,12 +61,14 @@ public class TestSequenceFile extends TestCase {}}- private static void writeTest(NutchFileSystem nfs, int count, int seed, String file)+ private static void writeTest(NutchFileSystem nfs, int count, int seed,+ String file, boolean compress)throws IOException {new File(file).delete();LOG.fine("creating with " + count + " records");SequenceFile.Writer writer =- new SequenceFile.Writer(nfs, file, RandomDatum.class, RandomDatum.class);+ new SequenceFile.Writer(nfs, file, RandomDatum.class, RandomDatum.class,+ compress);RandomDatum.Generator generator = new RandomDatum.Generator(seed);for (int i = 0; i < count; i++) {generator.next();@@ -210,8 +212,9 @@ public class TestSequenceFile extends TestCase {boolean check = false;boolean fast = false;boolean merge = false;+ boolean compress = false;String file = null;- String usage = "Usage: SequenceFile (-local | -ndfs <namenode:port>) [-count N] [-megabytes M] [-factor F] [-nocreate] [-check] [-fast] [-merge] file";+ String usage = "Usage: SequenceFile (-local | -ndfs <namenode:port>) [-count N] [-megabytes M] [-factor F] [-nocreate] [-check] [-fast] [-merge] [-compress] file";if (args.length == 0) {System.err.println(usage);@@ -237,6 +240,8 @@ public class TestSequenceFile extends TestCase {fast = true;} else if (args[i].equals("-merge")) {merge = true;+ } else if (args[i].equals("-compress")) {+ compress = true;} else {// file is required parameterfile = args[i];@@ -249,6 +254,7 @@ public class TestSequenceFile extends TestCase {LOG.info("check = " + check);LOG.info("fast = " + fast);LOG.info("merge = " + merge);+ LOG.info("compress = " + compress);LOG.info("file = " + file);int seed = 0;@@ -256,7 +262,7 @@ public class TestSequenceFile extends TestCase {LOG.setLevel(Level.FINE);if (create && !merge) {- writeTest(nfs, count, seed, file);+ writeTest(nfs, count, seed, file, compress);readTest(nfs, count, seed, file);}diff --git a/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java b/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.javanew file mode 100644index 000000000..f0242209c--- /dev/null+++ b/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java@@ -0,0 +1,114 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.*;+import java.util.*;+import junit.framework.TestCase;+import java.util.logging.*;++import org.apache.nutch.fs.*;+import org.apache.nutch.io.*;+import org.apache.nutch.util.*;++public class TestSequenceFileInputFormat extends TestCase {+ private static final Logger LOG = InputFormatBase.LOG;++ private static int MAX_LENGTH = 10000;++ public void testFormat() throws Exception {+ JobConf job = new JobConf(NutchConf.get());+ NutchFileSystem fs = NutchFileSystem.getNamed("local");+ File dir = new File(System.getProperty("test.build.data",".") + "/mapred");+ File file = new File(dir, "test.seq");++ Reporter reporter = new Reporter() {+ public void setStatus(String status) throws IOException {}+ };++ int seed = new Random().nextInt();+ //LOG.info("seed = "+seed);+ Random random = new Random(seed);++ fs.delete(dir);++ job.setInputDir(dir);++ // for a variety of lengths+ for (int length = 0; length < MAX_LENGTH;+ length+= random.nextInt(MAX_LENGTH/10)+1) {++ //LOG.info("creating; entries = " + length);++ // create a file with length entries+ SequenceFile.Writer writer =+ new SequenceFile.Writer(fs, file.toString(),+ IntWritable.class, BytesWritable.class);+ try {+ for (int i = 0; i < length; i++) {+ IntWritable key = new IntWritable(i);+ byte[] data = new byte[random.nextInt(10)];+ random.nextBytes(data);+ BytesWritable value = new BytesWritable(data);+ writer.append(key, value);+ }+ } finally {+ writer.close();+ }++ // try splitting the file in a variety of sizes+ InputFormat format = new SequenceFileInputFormat();+ IntWritable key = new IntWritable();+ BytesWritable value = new BytesWritable();+ for (int i = 0; i < 3; i++) {+ int numSplits =+ random.nextInt(MAX_LENGTH/(SequenceFile.SYNC_INTERVAL/20))+1;+ //LOG.info("splitting: requesting = " + numSplits);+ FileSplit[] splits = format.getSplits(fs, job, numSplits);+ //LOG.info("splitting: got = " + splits.length);++ // check each split+ BitSet bits = new BitSet(length);+ for (int j = 0; j < splits.length; j++) {+ RecordReader reader =+ format.getRecordReader(fs, splits[j], job, reporter);+ try {+ int count = 0;+ while (reader.next(key, value)) {+ // if (bits.get(key.get())) {+ // LOG.info("splits["+j+"]="+splits[j]+" : " + key.get());+ // LOG.info("@"+reader.getPos());+ // }+ assertFalse("Key in multiple partitions.", bits.get(key.get()));+ bits.set(key.get());+ count++;+ }+ //LOG.info("splits["+j+"]="+splits[j]+" count=" + count);+ } finally {+ reader.close();+ }+ }+ assertEquals("Some keys in no partition.", length, bits.cardinality());+ }++ }+ }++ public static void main(String[] args) throws Exception {+ new TestSequenceFileInputFormat().testFormat();+ }+}diff --git a/src/test/org/apache/nutch/mapred/TestTextInputFormat.java b/src/test/org/apache/nutch/mapred/TestTextInputFormat.javanew file mode 100644index 000000000..0b60eedc7--- /dev/null+++ b/src/test/org/apache/nutch/mapred/TestTextInputFormat.java@@ -0,0 +1,108 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.mapred;++import java.io.*;+import java.util.*;+import junit.framework.TestCase;+import java.util.logging.*;++import org.apache.nutch.fs.*;+import org.apache.nutch.io.*;+import org.apache.nutch.util.*;++public class TestTextInputFormat extends TestCase {+ private static final Logger LOG = InputFormatBase.LOG;++ private static int MAX_LENGTH = 10000;++ public void testFormat() throws Exception {+ JobConf job = new JobConf(NutchConf.get());+ NutchFileSystem fs = NutchFileSystem.getNamed("local");+ File dir = new File(System.getProperty("test.build.data",".") + "/mapred");+ File file = new File(dir, "test.txt");++ Reporter reporter = new Reporter() {+ public void setStatus(String status) throws IOException {}+ };++ int seed = new Random().nextInt();+ //LOG.info("seed = "+seed);+ Random random = new Random(seed);++ fs.delete(dir);+ job.setInputDir(dir);++ // for a variety of lengths+ for (int length = 0; length < MAX_LENGTH;+ length+= random.nextInt(MAX_LENGTH/10)+1) {++ //LOG.info("creating; entries = " + length);++ // create a file with length entries+ Writer writer = new OutputStreamWriter(fs.create(file));+ try {+ for (int i = 0; i < length; i++) {+ writer.write(Integer.toString(i));+ writer.write("\n");+ }+ } finally {+ writer.close();+ }++ // try splitting the file in a variety of sizes+ InputFormat format = new TextInputFormat();+ LongWritable key = new LongWritable();+ UTF8 value = new UTF8();+ for (int i = 0; i < 3; i++) {+ int numSplits = random.nextInt(MAX_LENGTH/20)+1;+ //LOG.info("splitting: requesting = " + numSplits);+ FileSplit[] splits = format.getSplits(fs, job, numSplits);+ //LOG.info("splitting: got = " + splits.length);++ // check each split+ BitSet bits = new BitSet(length);+ for (int j = 0; j < splits.length; j++) {+ RecordReader reader =+ format.getRecordReader(fs, splits[j], job, reporter);+ try {+ int count = 0;+ while (reader.next(key, value)) {+ int v = Integer.parseInt(value.toString());+ // if (bits.get(v)) {+ // LOG.info("splits["+j+"]="+splits[j]+" : " + v);+ // LOG.info("@"+reader.getPos());+ // }+ assertFalse("Key in multiple partitions.", bits.get(v));+ bits.set(v);+ count++;+ }+ //LOG.info("splits["+j+"]="+splits[j]+" count=" + count);+ } finally {+ reader.close();+ }+ }+ assertEquals("Some keys in no partition.", length, bits.cardinality());+ }++ }+ }++ public static void main(String[] args) throws Exception {+ new TestTextInputFormat().testFormat();+ }+}diff --git a/src/test/org/apache/nutch/ndfs/TestNDFS.java b/src/test/org/apache/nutch/ndfs/TestNDFS.javanew file mode 100644index 000000000..5cce29859--- /dev/null+++ b/src/test/org/apache/nutch/ndfs/TestNDFS.java@@ -0,0 +1,530 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.ndfs;++import junit.framework.TestCase;+import junit.framework.AssertionFailedError;+import org.apache.nutch.fs.NFSInputStream;+import org.apache.nutch.fs.NFSOutputStream;+import org.apache.nutch.fs.FileUtil;+import org.apache.nutch.io.UTF8;+import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.util.NutchConf;++import java.io.File;+import java.io.FilenameFilter;+import java.net.InetSocketAddress;+import java.util.ArrayList;+import java.util.ListIterator;+import java.util.logging.Logger;+import java.util.Random;+import java.lang.reflect.Constructor;+import java.lang.reflect.InvocationTargetException;++/**+ * Test NDFS.+ * TestNDFS is a JUnit test for NDFS using "pseudo multiprocessing" (or+ more strictly, pseudo distributed) meaning all daemons run in one process+ and sockets are used to communicate between daemons. The test permutes+ * various block sizes, number of files, file sizes, and number of+ * datanodes. After creating 1 or more files and filling them with random+ * data, one datanode is shutdown, and then the files are verfified.+ * Next, all the random test files are deleted and we test for leakage+ * (non-deletion) by directly checking the real directories corresponding+ * to the datanodes still running.+ * <p>+ * Usage notes: TEST_PERMUTATION_MAX can be adjusted to perform more or+ * less testing of permutations. The ceiling of useful permutation is+ * TEST_PERMUTATION_MAX_CEILING.+ * <p>+ * NDFSClient emits many messages that can be ignored like:+ * "Failed to connect to *:7000:java.net.ConnectException: Connection refused: connect"+ * because a datanode is forced to close during testing.+ * <p>+ * Warnings about "Zero targets found" can be ignored (these are naggingly+ * emitted even though it is not possible to achieve the desired replication+ * level with the number of active datanodes.)+ * <p>+ * Possible Extensions:+ * <p>Bring a datanode down and restart it to verify reconnection to namenode.+ * <p>Simulate running out of disk space on one datanode only.+ * <p>Bring the namenode down and restart it to verify that datanodes reconnect.+ * <p>+ * <p>For a another approach to filesystem testing, see the high level+ * (NutchFS level) test {@link org.apache.nutch.fs.TestNutchFileSystem}.+ * @author Paul Baclace+ */+public class TestNDFS extends TestCase implements FSConstants {+ private static final Logger LOG =+ LogFormatter.getLogger("org.apache.nutch.ndfs.TestNDFS");++ private static int BUFFER_SIZE =+ NutchConf.get().getInt("io.file.buffer.size", 4096);++ private static int testCycleNumber = 0;++ /**+ * all NDFS test files go under this base directory+ */+ private static String baseDirSpecified;++ /**+ * base dir as File+ */+ private static File baseDir;++ /** NDFS block sizes to permute over in multiple test cycles+ * (array length should be prime).+ */+ private static final int[] BLOCK_SIZES = {100000, 4096};++ /** NDFS file sizes to permute over in multiple test cycles+ * (array length should be prime).+ */+ private static final int[] FILE_SIZES =+ {100000, 100001, 4095, 4096, 4097, 1000000, 1000001};++ /** NDFS file counts to permute over in multiple test cycles+ * (array length should be prime).+ */+ private static final int[] FILE_COUNTS = {1, 10, 100};++ /** Number of useful permutations or test cycles.+ * (The 2 factor represents the alternating 2 or 3 number of datanodes+ * started.)+ */+ private static final int TEST_PERMUTATION_MAX_CEILING =+ BLOCK_SIZES.length * FILE_SIZES.length * FILE_COUNTS.length * 2;++ /** Number of permutations of NDFS test parameters to perform.+ * If this is greater than ceiling TEST_PERMUTATION_MAX_CEILING, then the+ * ceiling value is used.+ */+ private static final int TEST_PERMUTATION_MAX = 3;+ private Constructor randomDataGeneratorCtor = null;++ static {+ baseDirSpecified = System.getProperty("test.ndfs.data", "/tmp/ndfs_test");+ baseDir = new File(baseDirSpecified);+ }++ protected void setUp() throws Exception {+ super.setUp();+ NutchConf.get().setBoolean("test.ndfs.same.host.targets.allowed", true);+ }++ /**+ * Remove old files from temp area used by this test case and be sure+ * base temp directory can be created.+ */+ protected void prepareTempFileSpace() {+ if (baseDir.exists()) {+ try { // start from a blank slate+ FileUtil.fullyDelete(baseDir);+ } catch (Exception ignored) {+ }+ }+ baseDir.mkdirs();+ if (!baseDir.isDirectory()) {+ throw new RuntimeException("Value of root directory property test.ndfs.data for ndfs test is not a directory: "+ + baseDirSpecified);+ }+ }++ /**+ * Pseudo Distributed FS Test.+ * Test NDFS by running all the necessary daemons in one process.+ * Test various block sizes, number of files, disk space consumption,+ * and leakage.+ *+ * @throws Exception+ */+ public void testFsPseudoDistributed()+ throws Exception {+ while (testCycleNumber < TEST_PERMUTATION_MAX &&+ testCycleNumber < TEST_PERMUTATION_MAX_CEILING) {+ int blockSize = BLOCK_SIZES[testCycleNumber % BLOCK_SIZES.length];+ int numFiles = FILE_COUNTS[testCycleNumber % FILE_COUNTS.length];+ int fileSize = FILE_SIZES[testCycleNumber % FILE_SIZES.length];+ prepareTempFileSpace();+ testFsPseudoDistributed(fileSize, numFiles, blockSize,+ (testCycleNumber % 2) + 2);+ }+ }++ /**+ * Pseudo Distributed FS Testing.+ * Do one test cycle with given parameters.+ *+ * @param nBytes number of bytes to write to each file.+ * @param numFiles number of files to create.+ * @param blockSize block size to use for this test cycle.+ * @param initialDNcount number of datanodes to create+ * @throws Exception+ */+ public void testFsPseudoDistributed(long nBytes, int numFiles,+ int blockSize, int initialDNcount)+ throws Exception {+ long startTime = System.currentTimeMillis();+ int bufferSize = Math.min(BUFFER_SIZE, blockSize);+ boolean checkDataDirsEmpty = false;+ int iDatanodeClosed = 0;+ Random randomDataGenerator = makeRandomDataGenerator();+ final int currentTestCycleNumber = testCycleNumber;+ msg("using randomDataGenerator=" + randomDataGenerator.getClass().getName());++ //+ // modify config for test++ //+ // set given config param to override other config settings+ NutchConf.get().setInt("test.ndfs.block_size", blockSize);+ // verify that config changed+ assertTrue(blockSize == NutchConf.get().getInt("test.ndfs.block_size", 2)); // 2 is an intentional obviously-wrong block size+ // downsize for testing (just to save resources)+ NutchConf.get().setInt("ndfs.namenode.handler.count", 3);+ if (false) { // use MersenneTwister, if present+ NutchConf.get().set("nutch.random.class",+ "org.apache.nutch.util.MersenneTwister");+ }+ NutchConf.get().setLong("ndfs.blockreport.intervalMsec", 50*1000L);+ NutchConf.get().setLong("ndfs.datanode.startupMsec", 15*1000L);++ String nameFSDir = baseDirSpecified + "/name";+ msg("----Start Test Cycle=" + currentTestCycleNumber ++ " test.ndfs.block_size=" + blockSize ++ " nBytes=" + nBytes ++ " numFiles=" + numFiles ++ " initialDNcount=" + initialDNcount);++ //+ // start a NameNode++ int nameNodePort = 9000 + testCycleNumber++; // ToDo: settable base port+ String nameNodeSocketAddr = "localhost:" + nameNodePort;+ NameNode nameNodeDaemon = new NameNode(new File(nameFSDir), nameNodePort);+ NDFSClient ndfsClient = null;+ try {+ //+ // start some DataNodes+ //+ ArrayList listOfDataNodeDaemons = new ArrayList();+ NutchConf conf = NutchConf.get();+ conf.set("fs.default.name", nameNodeSocketAddr);+ for (int i = 0; i < initialDNcount; i++) {+ // uniquely config real fs path for data storage for this datanode+ String dataDir = baseDirSpecified + "/datanode" + i;+ conf.set("ndfs.data.dir", dataDir);+ DataNode dn = DataNode.makeInstanceForDir(dataDir, conf);+ if (dn != null) {+ listOfDataNodeDaemons.add(dn);+ (new Thread(dn, "DataNode" + i + ": " + dataDir)).start();+ }+ }+ try {+ assertTrue("insufficient datanodes for test to continue",+ (listOfDataNodeDaemons.size() >= 2));++ //+ // wait for datanodes to report in+ awaitQuiescence();++ // act as if namenode is a remote process+ ndfsClient = new NDFSClient(new InetSocketAddress("localhost", nameNodePort));++ //+ // write nBytes of data using randomDataGenerator to numFiles+ //+ ArrayList testfilesList = new ArrayList();+ byte[] buffer = new byte[bufferSize];+ UTF8 testFileName = null;+ for (int iFileNumber = 0; iFileNumber < numFiles; iFileNumber++) {+ testFileName = new UTF8("/f" + iFileNumber);+ testfilesList.add(testFileName);+ NFSOutputStream nos = ndfsClient.create(testFileName, false);+ try {+ for (long nBytesWritten = 0L;+ nBytesWritten < nBytes;+ nBytesWritten += buffer.length) {+ if ((nBytesWritten + buffer.length) > nBytes) {+ // calculate byte count needed to exactly hit nBytes in length+ // to keep randomDataGenerator in sync during the verify step+ int pb = (int) (nBytes - nBytesWritten);+ byte[] bufferPartial = new byte[pb];+ randomDataGenerator.nextBytes(bufferPartial);+ nos.write(bufferPartial);+ } else {+ randomDataGenerator.nextBytes(buffer);+ nos.write(buffer);+ }+ }+ } finally {+ nos.flush();+ nos.close();+ }+ }++ //+ // No need to wait for blocks to be replicated because replication+ // is supposed to be complete when the file is closed.+ //++ //+ // take one datanode down+ iDatanodeClosed =+ currentTestCycleNumber % listOfDataNodeDaemons.size();+ DataNode dn = (DataNode) listOfDataNodeDaemons.get(iDatanodeClosed);+ msg("shutdown datanode daemon " + iDatanodeClosed ++ " dn=" + dn.data);+ try {+ dn.shutdown();+ } catch (Exception e) {+ msg("ignoring datanode shutdown exception=" + e);+ }++ //+ // verify data against a "rewound" randomDataGenerator+ // that all of the data is intact+ long lastLong = randomDataGenerator.nextLong();+ randomDataGenerator = makeRandomDataGenerator(); // restart (make new) PRNG+ ListIterator li = testfilesList.listIterator();+ while (li.hasNext()) {+ testFileName = (UTF8) li.next();+ NFSInputStream nis = ndfsClient.open(testFileName);+ byte[] bufferGolden = new byte[bufferSize];+ int m = 42;+ try {+ while (m != -1) {+ m = nis.read(buffer);+ if (m == buffer.length) {+ randomDataGenerator.nextBytes(bufferGolden);+ assertBytesEqual(buffer, bufferGolden, buffer.length);+ } else if (m > 0) {+ byte[] bufferGoldenPartial = new byte[m];+ randomDataGenerator.nextBytes(bufferGoldenPartial);+ assertBytesEqual(buffer, bufferGoldenPartial, bufferGoldenPartial.length);+ }+ }+ } finally {+ nis.close();+ }+ }+ // verify last randomDataGenerator rand val to ensure last file length was checked+ long lastLongAgain = randomDataGenerator.nextLong();+ assertEquals(lastLong, lastLongAgain);+ msg("Finished validating all file contents");++ //+ // now delete all the created files+ msg("Delete all random test files under NDFS via remaining datanodes");+ li = testfilesList.listIterator();+ while (li.hasNext()) {+ testFileName = (UTF8) li.next();+ assertTrue(ndfsClient.delete(testFileName));+ }++ //+ // wait for delete to be propagated+ // (unlike writing files, delete is lazy)+ msg("Test thread sleeping while datanodes propagate delete...");+ awaitQuiescence();+ msg("Test thread awakens to verify file contents");++ //+ // check that the datanode's block directory is empty+ // (except for datanode that had forced shutdown)+ checkDataDirsEmpty = true; // do it during finally clause++ } catch (AssertionFailedError afe) {+ throw afe;+ } catch (Throwable t) {+ msg("Unexpected exception_b: " + t);+ t.printStackTrace();+ } finally {+ //+ // shut down datanode daemons (this takes advantage of being same-process)+ msg("begin shutdown of all datanode daemons for test cycle " ++ currentTestCycleNumber);++ for (int i = 0; i < listOfDataNodeDaemons.size(); i++) {+ DataNode dataNode = (DataNode) listOfDataNodeDaemons.get(i);+ if (i != iDatanodeClosed) {+ try {+ if (checkDataDirsEmpty) {+ File dataDir = new File(dataNode.data.dirpath);+ assertNoBlocks(dataDir);++ }+ dataNode.shutdown();+ } catch (Exception e) {+ msg("ignoring exception during (all) datanode shutdown, e=" + e);+ }+ }+ }+ }+ msg("finished shutdown of all datanode daemons for test cycle " ++ currentTestCycleNumber);+ if (ndfsClient != null) {+ try {+ msg("close down subthreads of NDFSClient");+ ndfsClient.close();+ } catch (Exception ignored) { }+ msg("finished close down of NDFSClient");+ }+ } catch (AssertionFailedError afe) {+ throw afe;+ } catch (Throwable t) {+ msg("Unexpected exception_a: " + t);+ t.printStackTrace();+ } finally {+ // shut down namenode daemon (this takes advantage of being same-process)+ msg("begin shutdown of namenode daemon for test cycle " ++ currentTestCycleNumber);+ try {+ nameNodeDaemon.stop();+ } catch (Exception e) {+ msg("ignoring namenode shutdown exception=" + e);+ }+ msg("finished shutdown of namenode daemon for test cycle " ++ currentTestCycleNumber);+ }+ msg("test cycle " + currentTestCycleNumber + " elapsed time=" ++ (System.currentTimeMillis() - startTime) / 1000. + "sec");+ msg("threads still running (look for stragglers): ");+ msg(summarizeThreadGroup());+ }++ private void assertNoBlocks(File datanodeDir) {+ File datanodeDataDir = new File(datanodeDir, "data");+ String[] blockFilenames =+ datanodeDataDir.list(+ new FilenameFilter() {+ public boolean accept(File dir, String name){+ return Block.isBlockFilename(new File(dir, name));}});+ // if this fails, the delete did not propagate because either+ // awaitQuiescence() returned before the disk images were removed+ // or a real failure was detected.+ assertTrue(" data dir not empty: " + datanodeDataDir,+ blockFilenames.length==0);+ }++ /**+ * Make a data generator.+ * Allows optional use of high quality PRNG by setting property+ * nutch.random.class to the full class path of a subclass of+ * java.util.Random such as "...util.MersenneTwister".+ * The property test.ndfs.random.seed can supply a seed for reproducible+ * testing (a default is set here if property is not set.)+ */+ private Random makeRandomDataGenerator() {+ long seed = NutchConf.get().getLong("test.ndfs.random.seed", 0xB437EF);+ try {+ if (randomDataGeneratorCtor == null) {+ // lazy init+ String rndDataGenClassname =+ NutchConf.get().get("nutch.random.class", "java.util.Random");+ Class clazz = Class.forName(rndDataGenClassname);+ randomDataGeneratorCtor = clazz.getConstructor(new Class[]{Long.TYPE});+ }++ if (randomDataGeneratorCtor != null) {+ Object arg[] = {new Long(seed)};+ return (Random) randomDataGeneratorCtor.newInstance(arg);+ }+ } catch (ClassNotFoundException absorb) {+ } catch (NoSuchMethodException absorb) {+ } catch (SecurityException absorb) {+ } catch (InstantiationException absorb) {+ } catch (IllegalAccessException absorb) {+ } catch (IllegalArgumentException absorb) {+ } catch (InvocationTargetException absorb) {+ }++ // last resort+ return new java.util.Random(seed);+ }++ /** Wait for the NDFS datanodes to become quiescent.+ * The initial implementation is to sleep for some fixed amount of time,+ * but a better implementation would be to really detect when distributed+ * operations are completed.+ * @throws InterruptedException+ */+ private void awaitQuiescence() throws InterruptedException {+ // ToDo: Need observer pattern, not static sleep+ // Doug suggested that the block report interval could be made shorter+ // and then observing that would be a good way to know when an operation+ // was complete (quiescence detect).+ sleepAtLeast(60000);+ }++ private void assertBytesEqual(byte[] buffer, byte[] bufferGolden, int len) {+ for (int i = 0; i < len; i++) {+ assertEquals(buffer[i], bufferGolden[i]);+ }+ }++ private void msg(String s) {+ //System.out.println(s);+ LOG.info(s);+ }++ public static void sleepAtLeast(int tmsec) {+ long t0 = System.currentTimeMillis();+ long t1 = t0;+ long tslept = t1 - t0;+ while (tmsec > tslept) {+ try {+ long tsleep = tmsec - tslept;+ Thread.sleep(tsleep);+ t1 = System.currentTimeMillis();+ } catch (InterruptedException ie) {+ t1 = System.currentTimeMillis();+ }+ tslept = t1 - t0;+ }+ }++ public static String summarizeThreadGroup() {+ int n = 10;+ int k = 0;+ Thread[] tarray = null;+ StringBuffer sb = new StringBuffer(500);+ do {+ n = n * 10;+ tarray = new Thread[n];+ k = Thread.enumerate(tarray);+ } while (k == n); // while array is too small...+ for (int i = 0; i < k; i++) {+ Thread thread = tarray[i];+ sb.append(thread.toString());+ sb.append("\n");+ }+ return sb.toString();+ }++ public static void main(String[] args) throws Exception {+ String usage = "Usage: TestNDFS (no args)";+ if (args.length != 0) {+ System.err.println(usage);+ System.exit(-1);+ }+ String[] testargs = {"org.apache.nutch.ndfs.TestNDFS"};+ junit.textui.TestRunner.main(testargs);+ }++}diff --git a/src/web/jsp/anchors.jsp b/src/web/jsp/anchors.jspindex 870ca0ba1..84f5aebed 100644--- a/src/web/jsp/anchors.jsp+++ b/src/web/jsp/anchors.jsp@@ -55,8 +55,10 @@<ul><%String[] anchors = bean.getAnchors(details);- for (int i = 0; i < anchors.length; i++) {+ if (anchors != null) {+ for (int i = 0; i < anchors.length; i++) {%><li><%=Entities.encode(anchors[i])%>+<% } %><% } %></ul>diff --git a/src/webapps/jobtracker/jobdetails.jsp b/src/webapps/jobtracker/jobdetails.jspindex adcd79cae..745b39898 100644--- a/src/webapps/jobtracker/jobdetails.jsp+++ b/src/webapps/jobtracker/jobdetails.jsp@@ -4,7 +4,7 @@import="javax.servlet.http.*"import="java.io.*"import="java.util.*"- import="org.apache.nutch.mapReduce.*"+ import="org.apache.nutch.mapred.*"%><%String jobid = request.getParameter("jobid");@@ -12,6 +12,9 @@JobTracker.JobInProgress job = (JobTracker.JobInProgress) tracker.getJob(jobid);JobProfile profile = (job != null) ? (job.getProfile()) : null;JobStatus status = (job != null) ? (job.getStatus()) : null;++ Vector mapTaskReports[] = tracker.getMapTaskReport(jobid);+ Vector reduceTaskReports[] = tracker.getReduceTaskReport(jobid);%><html>@@ -35,10 +38,21 @@<h2>Map Tasks</h2><center><table border=2 cellpadding="5" cellspacing="2">- <tr><td align="center" colspan="4">Map Tasks</td></tr>+ <tr><td align="center">Map Task Id</td><td>Pct Complete</td><td>State</td><td>Diagnostic Text</td></tr><%-+ for (int i = 0; i < mapTaskReports.length; i++) {+ Vector v = mapTaskReports[i];+ out.print("<tr><td>" + v.elementAt(0) + "</td><td>" + v.elementAt(1) + "</td><td>" + v.elementAt(2) + "</td>");+ if (v.size() == 3) {+ out.print("<td></td>");+ } else {+ for (int j = 3; j < v.size(); j++) {+ out.print("<td>" + v.elementAt(j) + "</td>");+ }+ }+ out.print("</tr>\n");+ }%></table></center>@@ -46,6 +60,26 @@<h2>Reduce Tasks</h2>+ <center>+ <table border=2 cellpadding="5" cellspacing="2">+ <tr><td align="center">Reduce Task Id</td><td>Pct Complete</td><td>State</td><td>Diagnostic Text</td></tr>++ <%+ for (int i = 0; i < reduceTaskReports.length; i++) {+ Vector v = reduceTaskReports[i];+ out.print("<tr><td>" + v.elementAt(0) + "</td><td>" + v.elementAt(1) + "</td><td>" + v.elementAt(2) + "</td>");+ if (v.size() == 3) {+ out.print("<td></td>");+ } else {+ for (int j = 3; j < v.size(); j++) {+ out.print("<td>" + v.elementAt(j) + "</td>");+ }+ }+ out.print("</tr>\n");+ }+ %>+ </table>+ </center><hr>diff --git a/src/webapps/jobtracker/jobtracker.jsp b/src/webapps/jobtracker/jobtracker.jspindex bbe0ec9fc..5604bda8e 100644--- a/src/webapps/jobtracker/jobtracker.jsp+++ b/src/webapps/jobtracker/jobtracker.jsp@@ -4,7 +4,7 @@import="javax.servlet.http.*"import="java.io.*"import="java.util.*"- import="org.apache.nutch.mapReduce.*"+ import="org.apache.nutch.mapred.*"%><%!JobTracker tracker = JobTracker.getTracker();