Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

New MapReduce JobTracker internals. This fixes several bugs, as listed in JIRA NUTCH-183.

Michael John Cafarellab6b05637e212
diff --git a/src/java/org/apache/nutch/fs/NFSDataInputStream.java b/src/java/org/apache/nutch/fs/NFSDataInputStream.java
index da65625a3..0cba855a9 100644
--- a/src/java/org/apache/nutch/fs/NFSDataInputStream.java
+++ b/src/java/org/apache/nutch/fs/NFSDataInputStream.java
@@ -57,7 +57,7 @@ public class NFSDataInputStream extends DataInputStream {
} catch (FileNotFoundException e) { // quietly ignore
stopSumming();
} catch (IOException e) { // loudly ignore
- LOG.warning("Problem opening checksum file: "+e+". Ignoring.");
+ LOG.warning("Problem opening checksum file: "+ file + ". Ignoring with exception " + e + ".");
stopSumming();
}
}
diff --git a/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java b/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java
index 288ee4c56..4096e2c0b 100644
--- a/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java
+++ b/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java
@@ -40,10 +40,11 @@ public interface InterTrackerProtocol {
/** Called to get new tasks from from the job tracker for this tracker.*/
Task pollForNewTask(String trackerName);
- /** Called to find which tasks that have been run by this tracker are now
- * closed, i.e., their job is complete. This is used to, e.g., notify a map
- * task that its output is no longer needed and may be removed. */
- String pollForClosedTask(String trackerName);
+ /** Called to find which tasks that have been run by this tracker should now
+ * be closed because their job is complete. This is used to, e.g.,
+ * notify a map task that its output is no longer needed and may
+ * be removed. */
+ String pollForTaskWithClosedJob(String trackerName);
/** Called by a reduce task to find which map tasks are completed.
*
@@ -51,7 +52,7 @@ public interface InterTrackerProtocol {
* @param mapTasksNeeded an array of UTF8 naming map task ids whose output is needed.
* @return an array of MapOutputLocation
*/
- MapOutputLocation[] locateMapOutputs(String taskId, String[] mapTasksNeeded);
+ MapOutputLocation[] locateMapOutputs(String taskId, String[][] mapTasksNeeded);
/**
* The task tracker calls this once, to discern where it can find
diff --git a/src/java/org/apache/nutch/mapred/JobClient.java b/src/java/org/apache/nutch/mapred/JobClient.java
index 4ff1e855a..72dcefd10 100644
--- a/src/java/org/apache/nutch/mapred/JobClient.java
+++ b/src/java/org/apache/nutch/mapred/JobClient.java
@@ -296,11 +296,7 @@ public class JobClient implements MRConstants {
} catch (InterruptedException e) {}
running = jc.getJob(jobId);
String report = null;
- if (running.reduceProgress() == 0.0)
- report=" map "+Math.round(running.mapProgress()*100)+"%";
- else {
- report=" reduce "+Math.round(running.reduceProgress()*100)+"%";
- }
+ report = " map "+Math.round(running.mapProgress()*100)+"% reduce " + Math.round(running.reduceProgress()*100)+"%";
if (!report.equals(lastReport)) {
LOG.info(report);
lastReport = report;
diff --git a/src/java/org/apache/nutch/mapred/JobConf.java b/src/java/org/apache/nutch/mapred/JobConf.java
index a34bfacc0..728963303 100644
--- a/src/java/org/apache/nutch/mapred/JobConf.java
+++ b/src/java/org/apache/nutch/mapred/JobConf.java
@@ -16,6 +16,7 @@
package org.apache.nutch.mapred;
+
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
@@ -112,18 +113,34 @@ public class JobConf extends NutchConf {
/** Constructs a local file name. Files are distributed among configured
* local directories.*/
- public File getLocalFile(String subdir, String name)
- throws IOException {
+ public File getLocalFile(String subdir, String name) throws IOException {
+ String param[] = new String[1];
+ param[0] = name;
+ return getLocalFile(subdir, param, "", false);
+ }
+ // REMIND - mjc - rename this! getLocalFile() is not quite the same.
+ public File getLocalFile(String subdir, String names[], String ending) throws IOException {
+ return getLocalFile(subdir, names, ending, true);
+ }
+ File getLocalFile(String subdir, String names[], String ending, boolean existingFileTest) 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;
- }
+ for (int k = 0; k < names.length; k++) {
+ String path = subdir + File.separator + names[k] + ending;
+ 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 (existingFileTest) {
+ if (file.exists()) {
+ return file;
+ }
+ } else {
+ if (dir.exists() || dir.mkdirs()) {
+ return file;
+ }
+ }
+ }
}
throw new IOException("No valid local directories.");
}
diff --git a/src/java/org/apache/nutch/mapred/JobInProgress.java b/src/java/org/apache/nutch/mapred/JobInProgress.java
new file mode 100644
index 000000000..bbe8440fc
--- /dev/null
+++ b/src/java/org/apache/nutch/mapred/JobInProgress.java
@@ -0,0 +1,436 @@
+/**
+ * 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.fs.*;
+import org.apache.nutch.ipc.*;
+import org.apache.nutch.util.*;
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import java.util.logging.*;
+
+///////////////////////////////////////////////////////
+// JobInProgress maintains all the info for keeping
+// a Job on the straight and narrow. It keeps its JobProfile
+// and its latest JobStatus, plus a set of tables for
+// doing bookkeeping of its Tasks.
+///////////////////////////////////////////////////////
+public class JobInProgress {
+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobInProgress");
+
+ JobProfile profile;
+ JobStatus status;
+ File localJobFile = null;
+
+ TaskInProgress maps[] = null;
+ TaskInProgress reduces[] = null;
+ int numMapTasks = 0;
+ int numReduceTasks = 0;
+
+ JobTracker jobtracker = null;
+
+ long startTime;
+ long finishTime;
+ String deleteUponCompletion = null;
+
+ NutchConf nutchConf;
+ boolean tasksInited = false;
+
+ /**
+ * Create a JobInProgress with the given job file, plus a handle
+ * to the tracker.
+ */
+ public JobInProgress(String jobFile, JobTracker jobtracker, NutchConf nutchConf) throws IOException {
+ String jobid = "job_" + jobtracker.createUniqueId();
+ String url = "http://" + jobtracker.getJobTrackerMachine() + ":" + jobtracker.getInfoPort() + "/jobdetails.jsp?jobid=" + jobid;
+ this.nutchConf = nutchConf;
+ this.jobtracker = jobtracker;
+ this.profile = new JobProfile(jobid, jobFile, url);
+ this.status = new JobStatus(jobid, 0.0f, 0.0f, JobStatus.RUNNING);
+ this.startTime = System.currentTimeMillis();
+
+ this.localJobFile = new JobConf(nutchConf).getLocalFile(JobTracker.SUBDIR, jobid + ".xml");
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
+ fs.copyToLocalFile(new File(jobFile), localJobFile);
+
+ JobConf jd = new JobConf(localJobFile);
+ this.numMapTasks = jd.getNumMapTasks();
+ this.numReduceTasks = jd.getNumReduceTasks();
+
+ //
+ // If a jobFile is in the systemDir, we can delete it (and
+ // its JAR) upon completion
+ //
+ File systemDir = jd.getSystemDir();
+ if (jobFile.startsWith(systemDir.getPath())) {
+ this.deleteUponCompletion = jobFile;
+ }
+ }
+
+ /**
+ * Construct the splits, etc
+ */
+ void initTasks() throws IOException {
+ if (tasksInited) {
+ return;
+ }
+
+ //
+ // construct input splits
+ //
+ String jobid = profile.getJobId();
+ String jobFile = profile.getJobFile();
+
+ JobConf jd = new JobConf(localJobFile);
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
+ FileSplit[] 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 splits
+ //
+ this.numMapTasks = splits.length;
+ // create a map task for each split
+ this.maps = new TaskInProgress[numMapTasks];
+ for (int i = 0; i < numMapTasks; i++) {
+ maps[i] = new TaskInProgress(jobFile, splits[i], jobtracker, nutchConf, this);
+ }
+
+ //
+ // Create reduce tasks
+ //
+ this.reduces = new TaskInProgress[numReduceTasks];
+ for (int i = 0; i < numReduceTasks; i++) {
+ reduces[i] = new TaskInProgress(jobFile, maps, i, jobtracker, nutchConf, this);
+ }
+
+ tasksInited = true;
+ }
+
+ /////////////////////////////////////////////////////
+ // Accessors for the JobInProgress
+ /////////////////////////////////////////////////////
+ public JobProfile getProfile() {
+ return profile;
+ }
+ public JobStatus getStatus() {
+ return status;
+ }
+ public long getStartTime() {
+ return startTime;
+ }
+ public long getFinishTime() {
+ return finishTime;
+ }
+ public int desiredMaps() {
+ return numMapTasks;
+ }
+ public int finishedMaps() {
+ int finishedCount = 0;
+ for (int i = 0; i < maps.length; i++) {
+ if (maps[i].isComplete()) {
+ finishedCount++;
+ }
+ }
+ return finishedCount;
+ }
+ public int desiredReduces() {
+ return numReduceTasks;
+ }
+ public int finishedReduces() {
+ int finishedCount = 0;
+ for (int i = 0; i < reduces.length; i++) {
+ if (reduces[i].isComplete()) {
+ finishedCount++;
+ }
+ }
+ return finishedCount;
+ }
+
+ /**
+ * Return a treeset of completed TaskInProgress objects
+ */
+ public Vector reportTasksInProgress(boolean shouldBeMap, boolean shouldBeComplete) {
+ Vector results = new Vector();
+ TaskInProgress tips[] = null;
+ if (shouldBeMap) {
+ tips = maps;
+ } else {
+ tips = reduces;
+ }
+ for (int i = 0; i < tips.length; i++) {
+ if (tips[i].isComplete() == shouldBeComplete) {
+ results.add(tips[i]);
+ }
+ }
+ return results;
+ }
+
+ ////////////////////////////////////////////////////
+ // Status update methods
+ ////////////////////////////////////////////////////
+ public void updateTaskStatus(TaskInProgress tip, TaskStatus status) {
+ tip.updateStatus(status);
+
+ //
+ // Update JobInProgress status
+ //
+ if (maps.length == 0) {
+ this.status.setMapProgress(1.0f);
+ } else {
+ double reportedProgress = 0;
+ for (int i = 0; i < maps.length; i++) {
+ reportedProgress += maps[i].getProgress();
+ }
+ this.status.setMapProgress((float) (reportedProgress / maps.length));
+ }
+ if (reduces.length == 0) {
+ this.status.setReduceProgress(1.0f);
+ } else {
+ double reportedProgress = 0;
+ for (int i = 0; i < reduces.length; i++) {
+ reportedProgress += reduces[i].getProgress();
+ }
+ this.status.setReduceProgress((float) (reportedProgress / reduces.length));
+ }
+ }
+
+ /////////////////////////////////////////////////////
+ // Create/manage tasks
+ /////////////////////////////////////////////////////
+ /**
+ * Return a MapTask, if appropriate, to run on the given tasktracker
+ */
+ public Task obtainNewMapTask(String taskTracker, TaskTrackerStatus tts) {
+ if (! tasksInited) {
+ try {
+ initTasks();
+ } catch (IOException ie) {
+ ie.printStackTrace();
+ LOG.info("Cannot create task split for " + profile.getJobId());
+ }
+ }
+
+ Task t = null;
+ int cacheTarget = -1;
+ int stdTarget = -1;
+ int specTarget = -1;
+ double totalProgress = 0;
+
+ //
+ // We end up creating two tasks for the same bucket, because
+ // we call obtainNewMapTask() really fast, twice in a row.
+ // There's not enough time for the "recentTasks"
+ //
+ for (int i = 0; i < maps.length; i++) {
+ if (maps[i].hasTaskWithCacheHit(taskTracker, tts)) {
+ if (cacheTarget < 0) {
+ cacheTarget = i;
+ }
+ } else if (maps[i].hasTask()) {
+ if (stdTarget < 0) {
+ stdTarget = i;
+ }
+ }
+ totalProgress += maps[i].getProgress();
+ }
+ double avgProgress = totalProgress / maps.length;
+
+ for (int i = 0; i < maps.length; i++) {
+ if (maps[i].hasSpeculativeTask(avgProgress)) {
+ if (specTarget < 0) {
+ specTarget = i;
+ }
+ }
+ }
+
+ if (cacheTarget >= 0) {
+ t = maps[cacheTarget].getTaskToRun(taskTracker, tts, avgProgress);
+ } else if (stdTarget >= 0) {
+ t = maps[stdTarget].getTaskToRun(taskTracker, tts, avgProgress);
+ } else if (specTarget >= 0) {
+ t = maps[specTarget].getTaskToRun(taskTracker, tts, avgProgress);
+ }
+ return t;
+ }
+
+ /**
+ * Return a ReduceTask, if appropriate, to run on the given tasktracker.
+ * We don't have cache-sensitivity for reduce tasks, as they
+ * work on temporary MapRed files.
+ */
+ public Task obtainNewReduceTask(String taskTracker, TaskTrackerStatus tts) {
+ if (! tasksInited) {
+ try {
+ initTasks();
+ } catch (IOException ie) {
+ ie.printStackTrace();
+ LOG.info("Cannot create task split for " + profile.getJobId());
+ }
+ }
+
+ Task t = null;
+ int stdTarget = -1;
+ int specTarget = -1;
+ int totalProgress = 0;
+ for (int i = 0; i < reduces.length; i++) {
+ totalProgress += reduces[i].getProgress();
+ }
+ double avgProgress = (1.0 * totalProgress) / reduces.length;
+
+ for (int i = 0; i < reduces.length; i++) {
+ if (reduces[i].hasTask()) {
+ if (stdTarget < 0) {
+ stdTarget = i;
+ }
+ } else if (reduces[i].hasSpeculativeTask(avgProgress)) {
+ if (specTarget < 0) {
+ specTarget = i;
+ }
+ }
+ }
+
+ if (stdTarget >= 0) {
+ t = reduces[stdTarget].getTaskToRun(taskTracker, tts, avgProgress);
+ } else if (specTarget >= 0) {
+ t = reduces[specTarget].getTaskToRun(taskTracker, tts, avgProgress);
+ }
+ return t;
+ }
+
+ /**
+ * A taskid assigned to this JobInProgress has reported in successfully.
+ */
+ public synchronized void completedTask(TaskInProgress tip, String taskid) {
+ LOG.info("Taskid '" + taskid + "' has finished successfully.");
+ tip.completed(taskid);
+
+ //
+ // Figure out whether the Job is done
+ //
+ boolean allDone = true;
+ for (int i = 0; i < maps.length; i++) {
+ if (! maps[i].isComplete()) {
+ allDone = false;
+ break;
+ }
+ }
+ if (allDone) {
+ for (int i = 0; i < reduces.length; i++) {
+ if (! reduces[i].isComplete()) {
+ allDone = false;
+ break;
+ }
+ }
+ }
+
+ //
+ // If all tasks are complete, then the job is done!
+ //
+ if (status.getRunState() == JobStatus.RUNNING && allDone) {
+ this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.SUCCEEDED);
+ this.finishTime = System.currentTimeMillis();
+ }
+ }
+
+ /**
+ * Kill the job and all its component tasks.
+ */
+ public synchronized void kill() {
+ if (status.getRunState() != JobStatus.FAILED) {
+ this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.FAILED);
+ this.finishTime = System.currentTimeMillis();
+
+ //
+ // kill all TIPs.
+ //
+ for (int i = 0; i < maps.length; i++) {
+ maps[i].kill();
+ }
+ for (int i = 0; i < reduces.length; i++) {
+ reduces[i].kill();
+ }
+ }
+ }
+
+ /**
+ * A task assigned to this JobInProgress has reported in as failed.
+ * Most of the time, we'll just reschedule execution. However, after
+ * many repeated failures we may instead decide to allow the entire
+ * job to fail.
+ *
+ * Even if a task has reported as completed in the past, it might later
+ * be reported as failed. That's because the TaskTracker that hosts a map
+ * task might die before the entire job can complete. If that happens,
+ * we need to schedule reexecution so that downstream reduce tasks can
+ * obtain the map task's output.
+ */
+ public void failedTask(TaskInProgress tip, String taskid, String trackerName) {
+ tip.failedSubTask(taskid, trackerName);
+
+ //
+ // Check if we need to kill the job because of too many failures
+ //
+ if (tip.isFailed()) {
+ LOG.info("Aborting job " + profile.getJobId());
+ kill();
+ }
+ }
+
+ /**
+ * The job is dead. We're now GC'ing it, getting rid of the job
+ * from all tables. Be sure to remove all of this job's tasks
+ * from the various tables.
+ */
+ public synchronized void garbageCollect() throws IOException {
+ //
+ // Remove this job from all tables
+ //
+
+ // Definitely remove the local-disk copy of the job file
+ if (localJobFile != null) {
+ localJobFile.delete();
+ localJobFile = null;
+ }
+
+ //
+ // If the job file was in the temporary system directory,
+ // we should delete it upon garbage collect.
+ //
+ if (deleteUponCompletion != null) {
+ JobConf jd = new JobConf(deleteUponCompletion);
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
+ fs.delete(new File(jd.getJar()));
+ fs.delete(new File(deleteUponCompletion));
+ deleteUponCompletion = null;
+ }
+ }
+}
+
diff --git a/src/java/org/apache/nutch/mapred/JobTracker.java b/src/java/org/apache/nutch/mapred/JobTracker.java
index 052ff3516..3c5e76afc 100644
--- a/src/java/org/apache/nutch/mapred/JobTracker.java
+++ b/src/java/org/apache/nutch/mapred/JobTracker.java
@@ -15,6 +15,7 @@
*/
package org.apache.nutch.mapred;
+
import org.apache.nutch.io.*;
import org.apache.nutch.fs.*;
import org.apache.nutch.ipc.*;
@@ -32,7 +33,11 @@ import java.util.logging.*;
* @author Mike Cafarella
*******************************************************/
public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissionProtocol {
- static final int MAX_TASK_FAILURES = 4;
+ static long RETIRE_JOB_INTERVAL;
+ static long RETIRE_JOB_CHECK_INTERVAL;
+ static float TASK_ALLOC_EPSILON;
+ static float PAD_FRACTION;
+ static float MIN_SLOTS_FOR_PADDING;
public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobTracker");
@@ -104,7 +109,12 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
if (newProfile != null) {
if (now - newProfile.getLastSeen() > TASKTRACKER_EXPIRY_INTERVAL) {
// Remove completely
- taskTrackers.remove(leastRecent.getTrackerName());
+
+ TaskTrackerStatus oldStatus = (TaskTrackerStatus) taskTrackers.remove(leastRecent.getTrackerName());
+ if (oldStatus != null) {
+ totalMaps -= oldStatus.countMapTasks();
+ totalReduces -= oldStatus.countReduceTasks();
+ }
lostTaskTracker(leastRecent.getTrackerName());
} else {
// Update time by inserting latest profile
@@ -125,6 +135,45 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
}
}
+ ///////////////////////////////////////////////////////
+ // Used to remove old finished Jobs that have been around for too long
+ ///////////////////////////////////////////////////////
+ class RetireJobs implements Runnable {
+ boolean shouldRun = true;
+ public RetireJobs() {
+ }
+
+ /**
+ * The run method lives for the life of the JobTracker,
+ * and removes Jobs that are not still running, but which
+ * finished a long time ago.
+ */
+ public void run() {
+ while (shouldRun) {
+ try {
+ Thread.sleep(RETIRE_JOB_CHECK_INTERVAL);
+ } catch (InterruptedException ie) {
+ }
+
+ synchronized (jobs) {
+ for (Iterator it = jobs.keySet().iterator(); it.hasNext(); ) {
+ String jobid = (String) it.next();
+ JobInProgress job = (JobInProgress) jobs.get(jobid);
+
+ if (job.getStatus().getRunState() != JobStatus.RUNNING &&
+ (job.getFinishTime() + RETIRE_JOB_INTERVAL < System.currentTimeMillis())) {
+ it.remove();
+ jobsByArrival.remove(job);
+ }
+ }
+ }
+ }
+ }
+ public void stopRetirer() {
+ shouldRun = false;
+ }
+ }
+
/////////////////////////////////////////////////////////////////
// The real JobTracker
////////////////////////////////////////////////////////////////
@@ -134,6 +183,8 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
int totalSubmissions = 0;
Random r = new Random();
+ private int maxCurrentTasks;
+
//
// Properties to maintain while running Jobs and Tasks:
//
@@ -152,28 +203,26 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
// All the known jobs. (jobid->JobInProgress)
TreeMap jobs = new TreeMap();
+ Vector jobsByArrival = new Vector();
- // (taskId->jobid that contains the task)
- TreeMap taskToJobMap = new TreeMap();
+ // All the known TaskInProgress items, mapped to by taskids (taskid->TIP)
+ TreeMap taskidToTIPMap = new TreeMap();
- // (taskId->trackerID) locates a given task
- TreeMap taskToTrackerMap = new TreeMap();
+ // (taskid --> trackerID)
+ TreeMap taskidToTrackerMap = new TreeMap();
// (trackerID->TreeSet of taskids running at that tracker)
TreeMap trackerToTaskMap = new TreeMap();
- // a list of taskIds waiting for a task tracker to run on
- Vector unassignedTasks = new Vector();
-
- // Tasks that we've closed
- TreeSet tasksReportedClosed = new TreeSet();
-
//
// Watch and expire TaskTracker objects using these structures.
// We can map from Name->TaskTrackerStatus, or we can expire by time.
//
+ int totalMaps = 0;
+ int totalReduces = 0;
TreeMap taskTrackers = new TreeMap();
ExpireTrackers expireTrackers = new ExpireTrackers();
+ RetireJobs retireJobs = new RetireJobs();
/**
* It might seem like a bug to maintain a TreeSet of status objects,
@@ -209,18 +258,27 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
static final String SUBDIR = "jobTracker";
NutchFileSystem fs;
File systemDir;
-
private NutchConf nutchConf;
/**
* Start the JobTracker process, listen on the indicated port
*/
JobTracker(NutchConf conf) throws IOException {
+ //
+ // Grab some static constants
+ //
+ maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2);
+ RETIRE_JOB_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.interval", 24 * 60 * 60 * 1000);
+ RETIRE_JOB_CHECK_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.check", 60 * 1000);
+ TASK_ALLOC_EPSILON = conf.getFloat("mapred.jobtracker.taskalloc.loadbalance.epsilon", 0.2f);
+ PAD_FRACTION = conf.getFloat("mapred.jobtracker.taskalloc.capacitypad", 0.1f);
+ MIN_SLOTS_FOR_PADDING = 3 * maxCurrentTasks;
+
// This is a directory of temporary submission files. We delete it
// on startup, and can delete any files that we're done with
+ this.nutchConf = conf;
JobConf jobConf = new JobConf(conf);
this.systemDir = jobConf.getSystemDir();
- this.nutchConf = conf;
this.fs = NutchFileSystem.get(conf);
FileUtil.fullyDelete(fs, systemDir);
fs.mkdirs(systemDir);
@@ -248,6 +306,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
this.startTime = System.currentTimeMillis();
new Thread(this.expireTrackers).start();
+ new Thread(this.retireJobs).start();
}
public static InetSocketAddress getAddress(NutchConf conf) {
@@ -273,6 +332,41 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
}
}
+ ///////////////////////////////////////////////////////
+ // Maintain lookup tables; called by JobInProgress
+ // and TaskInProgress
+ ///////////////////////////////////////////////////////
+ void createTaskEntry(String taskid, String taskTracker, TaskInProgress tip) {
+ LOG.info("Adding task '" + taskid + "' to tip " + tip.getTIPId() + ", for tracker '" + taskTracker + "'");
+
+ // taskid --> tracker
+ taskidToTrackerMap.put(taskid, taskTracker);
+
+ // tracker --> taskid
+ TreeSet taskset = (TreeSet) trackerToTaskMap.get(taskTracker);
+ if (taskset == null) {
+ taskset = new TreeSet();
+ trackerToTaskMap.put(taskTracker, taskset);
+ }
+ taskset.add(taskid);
+
+ // taskid --> TIP
+ taskidToTIPMap.put(taskid, tip);
+ }
+ void removeTaskEntry(String taskid) {
+ // taskid --> tracker
+ String tracker = (String) taskidToTrackerMap.remove(taskid);
+
+ // tracker --> taskid
+ TreeSet trackerSet = (TreeSet) trackerToTaskMap.get(tracker);
+ if (trackerSet != null) {
+ trackerSet.remove(taskid);
+ }
+
+ // taskid --> TIP
+ taskidToTIPMap.remove(taskid);
+ }
+
///////////////////////////////////////////////////////
// Accessors for objects that want info on jobs, tasks,
// trackers, etc.
@@ -286,6 +380,9 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
public int getTrackerPort() {
return port;
}
+ public int getInfoPort() {
+ return infoPort;
+ }
public long getStartTime() {
return startTime;
}
@@ -334,7 +431,10 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
////////////////////////////////////////////////////
public void initialize(String taskTrackerName) {
if (taskTrackers.get(taskTrackerName) != null) {
- taskTrackers.remove(taskTrackerName);
+ TaskTrackerStatus oldStatus = (TaskTrackerStatus) taskTrackers.remove(taskTrackerName);
+ totalMaps -= oldStatus.countMapTasks();
+ totalReduces -= oldStatus.countReduceTasks();
+
lostTaskTracker(taskTrackerName);
}
}
@@ -351,7 +451,9 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
if (initialContact) {
// If it's first contact, then clear out any state hanging around
if (taskTrackers.get(trackerName) != null) {
- taskTrackers.remove(trackerName);
+ TaskTrackerStatus oldStatus = (TaskTrackerStatus) taskTrackers.remove(trackerName);
+ totalMaps -= oldStatus.countMapTasks();
+ totalReduces -= oldStatus.countReduceTasks();
lostTaskTracker(trackerName);
}
} else {
@@ -363,6 +465,8 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
// Store latest state. If first contact, then save current
// state in expiry queue
+ totalMaps += trackerStatus.countMapTasks();
+ totalReduces += trackerStatus.countReduceTasks();
taskTrackers.put(trackerName, trackerStatus);
if (initialContact) {
trackerExpiryQueue.add(trackerStatus);
@@ -376,38 +480,129 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
}
/**
- * A tracker wants to know if there's a Task to run
+ * A tracker wants to know if there's a Task to run. Returns
+ * a task we'd like the TaskTracker to execute right now.
+ *
+ * Eventually this function should compute load on the various TaskTrackers,
+ * and incorporate knowledge of NDFS file placement. But for right now, it
+ * just grabs a single item out of the pending task list and hands it back.
*/
- public synchronized Task pollForNewTask(String trackerName) {
- //LOG.info("Unassigned tasks: " + unassignedTasks.size());
+ public synchronized Task pollForNewTask(String taskTracker) {
+ //
+ // Compute average map and reduce task numbers across pool
+ //
+ int avgMaps = 0;
+ int avgReduces = 0;
+ if (taskTrackers.size() > 0) {
+ avgMaps = totalMaps / taskTrackers.size();
+ avgReduces = totalReduces / taskTrackers.size();
+ }
+ int totalCapacity = taskTrackers.size() * maxCurrentTasks;
+
+ //
+ // Get map + reduce counts for the current tracker.
+ //
+ TaskTrackerStatus tts = (TaskTrackerStatus) taskTrackers.get(taskTracker);
+ int numMaps = tts.countMapTasks();
+ int numReduces = tts.countReduceTasks();
+
+ //
+ // In the below steps, we allocate first a map task (if appropriate),
+ // and then a reduce task if appropriate. We go through all jobs
+ // in order of job arrival; jobs only get serviced if their
+ // predecessors are serviced, too.
+ //
+
+ //
+ // We hand a task to the current taskTracker if the given machine
+ // has a workload that's equal to or less than the averageMaps
+ // +/- TASK_ALLOC_EPSILON. (That epsilon is in place in case
+ // there is an odd machine that is failing for some reason but
+ // has not yet been removed from the pool, making capacity seem
+ // larger than it really is.)
+ //
+ if ((numMaps < maxCurrentTasks) &&
+ (numMaps <= (avgMaps + TASK_ALLOC_EPSILON))) {
+
+ int totalNeededMaps = 0;
+ for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) {
+ JobInProgress job = (JobInProgress) it.next();
+ if (job.getStatus().getRunState() != JobStatus.RUNNING) {
+ continue;
+ }
+
+ Task t = job.obtainNewMapTask(taskTracker, tts);
+ if (t != null) {
+ return t;
+ }
- // Allocate a pending task to this TaskTracker
- return getTaskAssignment(trackerName);
+ //
+ // Beyond the highest-priority task, reserve a little
+ // room for failures and speculative executions; don't
+ // schedule tasks to the hilt.
+ //
+ totalNeededMaps += job.desiredMaps();
+ double padding = 0;
+ if (totalCapacity > MIN_SLOTS_FOR_PADDING) {
+ padding = Math.min(maxCurrentTasks, totalNeededMaps * PAD_FRACTION);
+ }
+ if (totalNeededMaps + padding >= totalCapacity) {
+ break;
+ }
+ }
+ }
+
+ //
+ // Same thing, but for reduce tasks
+ //
+ if ((numReduces < maxCurrentTasks) &&
+ (numReduces <= (avgReduces + TASK_ALLOC_EPSILON))) {
+
+ int totalNeededReduces = 0;
+ for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) {
+ JobInProgress job = (JobInProgress) it.next();
+ if (job.getStatus().getRunState() != JobStatus.RUNNING) {
+ continue;
+ }
+
+ Task t = job.obtainNewReduceTask(taskTracker, tts);
+ if (t != null) {
+ return t;
+ }
+
+ //
+ // Beyond the highest-priority task, reserve a little
+ // room for failures and speculative executions; don't
+ // schedule tasks to the hilt.
+ //
+ totalNeededReduces += job.desiredReduces();
+ double padding = 0;
+ if (totalCapacity > MIN_SLOTS_FOR_PADDING) {
+ padding = Math.min(maxCurrentTasks, totalNeededReduces * PAD_FRACTION);
+ }
+ if (totalNeededReduces + padding >= totalCapacity) {
+ break;
+ }
+ }
+ }
+ return null;
}
/**
* A tracker wants to know if any of its Tasks have been
* closed (because the job completed, whether successfully or not)
*/
- public String pollForClosedTask(String trackerName) {
- TreeSet taskIds = (TreeSet) trackerToTaskMap.get(trackerName);
+ public String pollForTaskWithClosedJob(String taskTracker) {
+ TreeSet taskIds = (TreeSet) trackerToTaskMap.get(taskTracker);
if (taskIds != null) {
for (Iterator it = taskIds.iterator(); it.hasNext(); ) {
String taskId = (String) it.next();
- String jobId = (String) taskToJobMap.get(taskId);
- JobInProgress job = (JobInProgress) jobs.get(jobId);
- int runState = job.getStatus().getRunState();
-
- if (! tasksReportedClosed.contains(taskId) &&
- (runState == JobStatus.SUCCEEDED ||
- runState == JobStatus.FAILED)) {
- tasksReportedClosed.add(taskId);
-
- //
- // REMIND - mjc - what happens when a job dies, but no one
- // arrives to claim the tasks? I suppose when the job is
- // eventually GC'ed, we make sure all its tasks are flushed
- // from lookup tables.
+ TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(taskId);
+ if (tip.shouldCloseForClosedJob(taskId)) {
+ //
+ // This is how the JobTracker ends a task at the TaskTracker.
+ // It may be successfully completed, or may be killed in
+ // mid-execution.
//
return taskId;
}
@@ -417,15 +612,27 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
}
/**
- * A tracker wants to know the physical locations of completed, but not
+ * A TaskTracker wants to know the physical locations of completed, but not
* yet closed, tasks. This exists so the reduce task thread can locate
* map task outputs.
- *
*/
- 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 synchronized MapOutputLocation[] locateMapOutputs(String taskId, String[][] mapTasksNeeded) {
+ ArrayList v = new ArrayList();
+ for (int i = 0; i < mapTasksNeeded.length; i++) {
+ for (int j = 0; j < mapTasksNeeded[i].length; j++) {
+ TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(mapTasksNeeded[i][j]);
+ if (tip != null && tip.isComplete(mapTasksNeeded[i][j])) {
+ String trackerId = (String) taskidToTrackerMap.get(mapTasksNeeded[i][j]);
+ TaskTrackerStatus tracker = (TaskTrackerStatus) taskTrackers.get(trackerId);
+ v.add(new MapOutputLocation(mapTasksNeeded[i][j], tracker.getHost(), tracker.getPort()));
+ break;
+ }
+ }
+ }
+ // randomly shuffle results to load-balance map output requests
+ Collections.shuffle(v);
+
+ return (MapOutputLocation[]) v.toArray(new MapOutputLocation[v.size()]);
}
/**
@@ -471,15 +678,15 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
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)));
+ Vector completeMapTasks = job.reportTasksInProgress(true, true);
+ for (Iterator it = completeMapTasks.iterator(); it.hasNext(); ) {
+ TaskInProgress tip = (TaskInProgress) it.next();
+ reports.add(tip.generateSingleReport());
}
- 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)));
+ Vector incompleteMapTasks = job.reportTasksInProgress(true, false);
+ for (Iterator it = incompleteMapTasks.iterator(); it.hasNext(); ) {
+ TaskInProgress tip = (TaskInProgress) it.next();
+ reports.add(tip.generateSingleReport());
}
return (Vector[]) reports.toArray(new Vector[reports.size()]);
}
@@ -491,39 +698,32 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
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)));
+ Vector completeReduceTasks = job.reportTasksInProgress(false, true);
+ for (Iterator it = completeReduceTasks.iterator(); it.hasNext(); ) {
+ TaskInProgress tip = (TaskInProgress) it.next();
+ reports.add(tip.generateSingleReport());
}
- 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)));
+ Vector incompleteReduceTasks = job.reportTasksInProgress(false, false);
+ for (Iterator it = incompleteReduceTasks.iterator(); it.hasNext(); ) {
+ TaskInProgress tip = (TaskInProgress) it.next();
+ reports.add(tip.generateSingleReport());
}
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) {
+ public JobInProgress getJob(String jobid) {
return (JobInProgress) jobs.get(jobid);
}
+ /**
+ * Grab random num for task id
+ */
+ String createUniqueId() {
+ return "" + Integer.toString(Math.abs(r.nextInt()),36);
+ }
/**
* JobProfile createJob() kicks off a new job.
@@ -531,439 +731,19 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
* tasks. The tasks are added to the unassignedTasks structure.
* (The precise structure will change as we get more sophisticated about
* task allocation.)
+ *
+ * Create a 'JobInProgress' object, which contains both JobProfile
+ * and JobStatus. Those two sub-objects are sometimes shipped outside
+ * of the JobTracker. But JobInProgress adds info that's useful for
+ * the JobTracker alone.
*/
JobInProgress createJob(String jobFile) throws IOException {
- JobInProgress job = new JobInProgress(jobFile, this.nutchConf);
+ JobInProgress job = new JobInProgress(jobFile, this, this.nutchConf);
jobs.put(job.getProfile().getJobId(), job);
-
- boolean error = true;
- try {
- job.launch();
- error = false;
- } finally {
- if (error) {
- job.kill();
- }
- }
-
+ jobsByArrival.add(job);
return job;
}
- ///////////////////////////////////////////////////////
- // JobInProgress maintains all the info for keeping
- // a Job on the straight and narrow. It keeps its JobProfile
- // and its latest JobStatus, plus a set of tables for
- // doing bookkeeping of its Tasks.
- ///////////////////////////////////////////////////////
- public class JobInProgress {
- JobProfile profile;
- JobStatus status;
- Vector reducesToLaunch = new Vector();
- File localJobFile = null;
-
- TreeMap taskStatus = new TreeMap();
- TreeMap incompleteMapTasks = new TreeMap();
- TreeMap 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 JobTracker
- int numMapTasks = 0;
- int numReduceTasks = 0;
- float totalReportedMapProgress = 0.0f;
- float totalReportedReduceProgress = 0.0f;
- int attemptedMapExecutions = 0;
- int attemptedReduceExecutions = 0;
- long startTime;
- long finishTime;
- String deleteUponCompletion = null;
- private NutchConf nutchConf;
-
- /**
- * Create a 'JobInProgress' object, which contains both JobProfile
- * and JobStatus. Those two sub-objects are sometimes shipped outside
- * of the JobTracker. But JobInProgress adds info that's useful for
- * the JobTracker alone.
- */
- public JobInProgress(String jobFile, NutchConf nutchConf) throws IOException {
- String jobid = createJobId();
- 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 JobConf(nutchConf).getLocalFile(SUBDIR, jobid + ".xml");
- fs.copyToLocalFile(new File(jobFile), localJobFile);
-
- JobConf jd = new JobConf(localJobFile);
- this.numMapTasks = jd.getNumMapTasks();
- this.numReduceTasks = jd.getNumReduceTasks();
- this.startTime = System.currentTimeMillis();
-
- // If a jobFile is in the systemDir, we can delete it (and
- // its JAR) upon completion
- if (jobFile.startsWith(systemDir.getPath())) {
- this.deleteUponCompletion = jobFile;
- }
- this.nutchConf = nutchConf;
- }
-
- /**
- * Start up the tasks
- */
- public void launch() throws IOException {
- String jobid = profile.getJobId();
- String jobFile = profile.getJobFile();
-
- // construct input splits
- JobConf jd = new JobConf(localJobFile);
- NutchFileSystem fs = NutchFileSystem.get(nutchConf);
- FileSplit[] 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 splits
- numMapTasks = splits.length;
-
- // create a map task for each split
- String mapIds[] = new String[numMapTasks];
- for (int i = 0; i < numMapTasks; i++) {
- mapIds[i] = createMapTaskId();
- Task t = new MapTask(jobFile, mapIds[i], splits[i]);
- t.setConf(this.nutchConf);
-
- incompleteMapTasks.put(mapIds[i], t);
- taskToJobMap.put(mapIds[i], jobid);
- }
-
- // Create reduce tasks
- for (int i = 0; i < numReduceTasks; i++) {
- String taskid = createReduceTaskId();
- Task t = new ReduceTask(jobFile, taskid, mapIds, i);
- t.setConf(this.nutchConf);
- reducesToLaunch.add(t);
- taskToJobMap.put(taskid, jobid);
- }
-
- // Launch the map tasks
- for (int i = 0; i < mapIds.length; i++) {
- executeTask(mapIds[i]);
- }
- }
-
- /**
- * Kill the job and all its component tasks.
- */
- public synchronized void kill() {
- 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();
- }
- }
-
- /**
- * The job is dead. We're now GC'ing it, getting rid of the job
- * from all tables. Be sure to remove all of this job's tasks
- * from the various tables.
- */
- public synchronized void garbageCollect() throws IOException {
- //
- // Remove this job from all tables
- //
-
-
- // Definitely remove the local-disk copy of the job file
- if (localJobFile != null) {
- localJobFile.delete();
- localJobFile = null;
- }
-
- //
- // If the job file was in the temporary system directory,
- // we should delete it upon garbage collect.
- //
- if (deleteUponCompletion != null) {
- JobConf jd = new JobConf(deleteUponCompletion);
- fs.delete(new File(jd.getJar()));
- fs.delete(new File(deleteUponCompletion));
- deleteUponCompletion = null;
- }
- }
-
- /**
- * A task assigned to this JobInProgress has reported in successfully.
- *
- * This might prompt us to launch more tasks, or it might even indicate
- * the job is now complete.
- */
- public synchronized void completedTask(String taskid) {
- LOG.info("Task '" + taskid + "' has finished successfully.");
-
- Task t = null;
- if ((t = (Task) incompleteMapTasks.get(taskid)) != null) {
- incompleteMapTasks.remove(taskid);
- completeMapTasks.put(taskid, t);
- } else if ((t = (Task) incompleteReduceTasks.get(taskid)) != null) {
- incompleteReduceTasks.remove(taskid);
- completeReduceTasks.put(taskid, t);
- } else {
- // Impossible situation; taskid is not 'incomplete' yet is reported
- // as just finishing
- throw new IllegalArgumentException("Impossible state: task " + taskid + " reported as complete, but was not known as incomplete");
- }
-
- //
- // We may have Reduce tasks that are still waiting to be scheduled for execution;
- // we don't want to launch them all while still waiting for most Map tasks to
- // finish. Nor do we want to wait for all the maps to finish, as the reduce task
- // could be downloading files while other map tasks complete.
- //
- // WELL, maybe we do want to wait. It's not obvious what the right launch rate
- // would be. For the moment, we wait until ALL map tasks have finished
- // before launching even a single reduce task.
- //
- while (status.getRunState() == JobStatus.RUNNING &&
- reducesToLaunch.size() > 0 &&
- completeMapTasks.size() == numMapTasks) {
- t = (Task) reducesToLaunch.elementAt(0);
- reducesToLaunch.removeElement(t);
- incompleteReduceTasks.put(t.getTaskId(), t);
- executeTask(t.getTaskId());
- }
-
- //
- // If all tasks are complete, then the job is done!
- //
- if (status.getRunState() == JobStatus.RUNNING &&
- completeReduceTasks.size() == numReduceTasks) {
- this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.SUCCEEDED);
- this.finishTime = System.currentTimeMillis();
- }
- }
-
- /**
- * A task assigned to this JobInProgress has reported in as failed.
- * Most of the time, we'll just reschedule execution. However, after
- * many repeated failures we may instead decide to allow the entire
- * job to fail.
- *
- * Even if a task has reported as completed in the past, it might later
- * be reported as failed. That's because the TaskTracker that hosts a map
- * task might die before the entire job can complete. If that happens,
- * we need to schedule reexecution so that downstream reduce tasks can
- * obtain the map task's output.
- */
- public void failedTask(String taskid) {
- LOG.info("Task '" + taskid + "' has been lost.");
-
- Task t = null;
- if ((t = (Task) completeMapTasks.get(taskid)) != null) {
- completeMapTasks.remove(taskid);
- incompleteMapTasks.put(taskid, t);
- } else if ((t = (Task) completeReduceTasks.get(taskid)) != null) {
- completeReduceTasks.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);
- }
- }
-
- /**
- * Return locations for all the indicated taskIds. If the task
- * is not complete, don't return anything.
- */
- public MapOutputLocation[] locateTasks(String taskIds[]) {
- ArrayList v = new ArrayList();
- for (int i = 0; i < taskIds.length; i++) {
- if (completeMapTasks.get(taskIds[i]) != null) {
- String trackerId = (String) taskToTrackerMap.get(taskIds[i]);
- TaskTrackerStatus tracker = (TaskTrackerStatus) taskTrackers.get(trackerId);
- v.add(new MapOutputLocation(taskIds[i], tracker.getHost(), tracker.getPort()));
- }
- }
- // randomly shuffle results to load-balance map output requests
- Collections.shuffle(v);
-
- return (MapOutputLocation[]) v.toArray(new MapOutputLocation[v.size()]);
- }
-
- //////////////////////////
- // 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;
- }
- public JobStatus getStatus() {
- return status;
- }
- public Task getTask(String taskid) {
- Task t = null;
- synchronized (incompleteMapTasks) {
- if ((t = (Task) incompleteMapTasks.get(taskid)) != null) {
- return t;
- }
- synchronized (completeMapTasks) {
- if ((t = (Task) completeMapTasks.get(taskid)) != null) {
- return t;
- }
- synchronized (incompleteReduceTasks) {
- if ((t = (Task) incompleteReduceTasks.get(taskid)) != null) {
- return t;
- }
- synchronized (completeReduceTasks) {
- t = (Task) completeReduceTasks.get(taskid);
- }
- }
- }
- }
- 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());
- }
- public long getStartTime() {
- return startTime;
- }
- public long getFinishTime() {
- return finishTime;
- }
- public int desiredMaps() {
- return numMapTasks;
- }
- public int attemptedMaps() {
- return attemptedMapExecutions;
- }
- public int completedMaps() {
- return completeMapTasks.size();
- }
- public int desiredReduces() {
- return numReduceTasks;
- }
- public int attemptedReduces() {
- return attemptedReduceExecutions;
- }
- public int completedReduces() {
- return completeReduceTasks.size();
- }
- public void updateTaskStatus(String taskid, TaskStatus status) {
- TaskStatus oldStatus = (TaskStatus) taskStatus.put(taskid, status);
-
- float delta = 0.0f;
- if (oldStatus != null) {
- delta -= oldStatus.getProgress();
- }
- 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;
- if (numMapTasks == 0) {
- this.status.setMapProgress(1.0f);
- } else {
- this.status.setMapProgress((float) (totalReportedMapProgress / numMapTasks));
- }
- } else if (incompleteReduceTasks.get(taskid) != null ||
- completeReduceTasks.get(taskid) != null) {
- totalReportedReduceProgress += delta;
- if (numReduceTasks == 0) {
- this.status.setReduceProgress(1.0f);
- } else {
- this.status.setReduceProgress((float) (totalReportedReduceProgress / numReduceTasks));
- }
- } else {
- LOG.info("Serious problem. While updating status, cannot find taskid " + taskid);
- }
- }
- public TaskStatus getTaskStatus(String taskid) {
- return (TaskStatus) taskStatus.get(taskid);
- }
-
- /////////////////////////////
- // Some private util methods
- /////////////////////////////
- void executeTask(String taskid) {
- if (incompleteMapTasks.get(taskid) != null) {
- attemptedMapExecutions++;
- } else if (incompleteReduceTasks.get(taskid) != null) {
- attemptedReduceExecutions++;
- }
- updateTaskStatus(taskid, new TaskStatus(taskid, 0.0f, TaskStatus.UNASSIGNED, "", ""));
- synchronized (unassignedTasks) {
- unassignedTasks.add(taskid);
- }
- }
- }
-
////////////////////////////////////////////////////
// Methods to track all the TaskTrackers
////////////////////////////////////////////////////
@@ -977,16 +757,19 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
void updateTaskStatuses(TaskTrackerStatus status) {
for (Iterator it = status.taskReports(); it.hasNext(); ) {
TaskStatus report = (TaskStatus) it.next();
- JobInProgress job = (JobInProgress) jobs.get((String) taskToJobMap.get(report.getTaskId()));
- job.updateTaskStatus(report.getTaskId(), report);
-
- if (report.getRunState() == TaskStatus.SUCCEEDED) {
- job.completedTask(report.getTaskId());
- } else if (report.getRunState() == TaskStatus.FAILED) {
- TreeSet taskset = (TreeSet) trackerToTaskMap.get(status.getTrackerName());
- taskset.remove(report.getTaskId());
- taskToTrackerMap.remove(report.getTaskId());
- job.failedTask(report.getTaskId());
+ TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(report.getTaskId());
+ if (tip == null) {
+ LOG.info("Serious problem. While updating status, cannot find taskid " + report.getTaskId());
+ } else {
+ JobInProgress job = tip.getJob();
+ job.updateTaskStatus(tip, report);
+
+ if (report.getRunState() == TaskStatus.SUCCEEDED) {
+ job.completedTask(tip, report.getTaskId());
+ } else if (report.getRunState() == TaskStatus.FAILED) {
+ // Tell the job to fail the relevant task
+ job.failedTask(tip, report.getTaskId(), status.getTrackerName());
+ }
}
}
}
@@ -1004,63 +787,15 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
if (lostTasks != null) {
for (Iterator it = lostTasks.iterator(); it.hasNext(); ) {
String taskId = (String) it.next();
- taskToTrackerMap.remove(taskId);
- JobInProgress job = (JobInProgress) jobs.get((String) taskToJobMap.get(taskId));
- job.failedTask(taskId);
- }
- }
- }
-
- /**
- * Task getTaskAssignment() returns
- * a task we'd like the taskTracker to execute right now.
- *
- * Eventually this function should compute load on the various TaskTrackers,
- * and incorporate knowledge of NDFS file placement. But for right now, it
- * just grabs a single item out of the pending task list and hands it back.
- */
- Task getTaskAssignment(String taskTracker) {
- 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);
+ TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(taskId);
- taskToTrackerMap.put(taskid, taskTracker);
-
- return job.getTask(taskid);
- } else {
- return null;
+ // Tell the job to fail the relevant task
+ JobInProgress job = tip.getJob();
+ job.failedTask(tip, taskId, trackerName);
}
}
}
- /**
- * Grab random num for task id
- */
- String createMapTaskId() {
- return "task_m_" + Integer.toString(Math.abs(r.nextInt()),36);
- }
- String createReduceTaskId() {
- return "task_r_" + Integer.toString(Math.abs(r.nextInt()),36);
- }
-
- String createJobId() {
- return "job_" + Integer.toString(Math.abs(r.nextInt()),36);
- }
-
////////////////////////////////////////////////////////////
// main()
////////////////////////////////////////////////////////////
diff --git a/src/java/org/apache/nutch/mapred/LocalJobRunner.java b/src/java/org/apache/nutch/mapred/LocalJobRunner.java
index a3d806355..6a4a9e8c2 100644
--- a/src/java/org/apache/nutch/mapred/LocalJobRunner.java
+++ b/src/java/org/apache/nutch/mapred/LocalJobRunner.java
@@ -89,9 +89,13 @@ public class LocalJobRunner implements JobSubmissionProtocol {
}
// run a single reduce task
+ String mapDependencies[][] = new String[mapIds.size()][1];
+ for (int i = 0; i < mapIds.size(); i++) {
+ mapDependencies[i][0] = (String) mapIds.get(i);
+ }
ReduceTask reduce =
new ReduceTask(file, reduceId,
- (String[])mapIds.toArray(new String[0]),
+ mapDependencies,
0);
reduce.setConf(job);
reduce.run(job, this);
diff --git a/src/java/org/apache/nutch/mapred/MRConstants.java b/src/java/org/apache/nutch/mapred/MRConstants.java
index 26256e97d..e4106ce37 100644
--- a/src/java/org/apache/nutch/mapred/MRConstants.java
+++ b/src/java/org/apache/nutch/mapred/MRConstants.java
@@ -25,7 +25,7 @@ public interface MRConstants {
// Timeouts, constants
//
public static final long HEARTBEAT_INTERVAL = 3 * 1000;
- public static final long TASKTRACKER_EXPIRY_INTERVAL = 10 * 60 * 1000;
+ public static final long TASKTRACKER_EXPIRY_INTERVAL = 60 * 1000;
//
// Result codes
diff --git a/src/java/org/apache/nutch/mapred/MapOutputFile.java b/src/java/org/apache/nutch/mapred/MapOutputFile.java
index 4614593e9..0c86dd797 100644
--- a/src/java/org/apache/nutch/mapred/MapOutputFile.java
+++ b/src/java/org/apache/nutch/mapred/MapOutputFile.java
@@ -58,6 +58,10 @@ public class MapOutputFile implements Writable, NutchConfigurable {
throws IOException {
return this.jobConf.getLocalFile(reduceTaskId, mapTaskId+".out");
}
+ public File getInputFile(String mapTaskId[], String reduceTaskId)
+ throws IOException {
+ return this.jobConf.getLocalFile(reduceTaskId, mapTaskId, ".out");
+ }
/** Removes all of the files related to a task. */
public void removeAll(String taskId) throws IOException {
diff --git a/src/java/org/apache/nutch/mapred/MapTask.java b/src/java/org/apache/nutch/mapred/MapTask.java
index 7a32288ac..46380fedd 100644
--- a/src/java/org/apache/nutch/mapred/MapTask.java
+++ b/src/java/org/apache/nutch/mapred/MapTask.java
@@ -37,6 +37,10 @@ public class MapTask extends Task {
this.split = split;
}
+ public boolean isMapTask() {
+ return true;
+ }
+
public TaskRunner createRunner(TaskTracker tracker) {
return new MapTaskRunner(this, tracker, this.nutchConf);
}
diff --git a/src/java/org/apache/nutch/mapred/MapTaskRunner.java b/src/java/org/apache/nutch/mapred/MapTaskRunner.java
index 9fe398f77..2ee37e257 100644
--- a/src/java/org/apache/nutch/mapred/MapTaskRunner.java
+++ b/src/java/org/apache/nutch/mapred/MapTaskRunner.java
@@ -35,8 +35,9 @@ class MapTaskRunner extends TaskRunner {
}
/** Delete any temporary files from previous failed attempts. */
- public void prepare() throws IOException {
+ public boolean prepare() throws IOException {
this.mapOutputFile.removeAll(getTask().getTaskId());
+ return true;
}
/** Delete all of the temporary map output files. */
diff --git a/src/java/org/apache/nutch/mapred/ReduceTask.java b/src/java/org/apache/nutch/mapred/ReduceTask.java
index 75a971a4b..4f5456035 100644
--- a/src/java/org/apache/nutch/mapred/ReduceTask.java
+++ b/src/java/org/apache/nutch/mapred/ReduceTask.java
@@ -27,7 +27,7 @@ import java.text.*;
/** A Reduce task. */
public class ReduceTask extends Task {
- private String[] mapTaskIds;
+ private String[][] mapTaskIds;
private int partition;
private boolean sortComplete;
@@ -43,7 +43,7 @@ public class ReduceTask extends Task {
public ReduceTask() {}
public ReduceTask(String jobFile, String taskId,
- String[] mapTaskIds, int partition) {
+ String[][] mapTaskIds, int partition) {
super(jobFile, taskId);
this.mapTaskIds = mapTaskIds;
this.partition = partition;
@@ -53,7 +53,11 @@ public class ReduceTask extends Task {
return new ReduceTaskRunner(this, tracker, this.nutchConf);
}
- public String[] getMapTaskIds() { return mapTaskIds; }
+ public boolean isMapTask() {
+ return false;
+ }
+
+ public String[][] getMapTaskIds() { return mapTaskIds; }
public int getPartition() { return partition; }
public void write(DataOutput out) throws IOException {
@@ -61,7 +65,10 @@ public class ReduceTask extends Task {
out.writeInt(mapTaskIds.length); // write mapTaskIds
for (int i = 0; i < mapTaskIds.length; i++) {
- UTF8.writeString(out, mapTaskIds[i]);
+ out.writeInt(mapTaskIds[i].length);
+ for (int j = 0; j < mapTaskIds[i].length; j++) {
+ UTF8.writeString(out, mapTaskIds[i][j]);
+ }
}
out.writeInt(partition); // write partition
@@ -70,9 +77,12 @@ public class ReduceTask extends Task {
public void readFields(DataInput in) throws IOException {
super.readFields(in);
- mapTaskIds = new String[in.readInt()]; // read mapTaskIds
+ mapTaskIds = new String[in.readInt()][]; // read mapTaskIds
for (int i = 0; i < mapTaskIds.length; i++) {
- mapTaskIds[i] = UTF8.readString(in);
+ mapTaskIds[i] = new String[in.readInt()];
+ for (int j = 0; j < mapTaskIds[i].length; j++) {
+ mapTaskIds[i][j] = UTF8.readString(in);
+ }
}
this.partition = in.readInt(); // read partition
@@ -182,6 +192,7 @@ public class ReduceTask extends Task {
float progPerByte = 1.0f / lfs.getLength(partFile);
Progress phase = appendPhase.phase();
phase.setStatus(partFile.toString());
+
SequenceFile.Reader in =
new SequenceFile.Reader(lfs, partFile.toString(), job);
try {
diff --git a/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java
index 40cc1fd15..ef8b05bc9 100644
--- a/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java
+++ b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java
@@ -37,14 +37,14 @@ class ReduceTaskRunner extends TaskRunner {
}
/** Assemble all of the map output files. */
- public void prepare() throws IOException {
+ public boolean prepare() throws IOException {
ReduceTask task = ((ReduceTask)getTask());
this.mapOutputFile.removeAll(task.getTaskId()); // cleanup from failures
- String[] mapTaskIds = task.getMapTaskIds();
+ String[][] mapTaskIds = task.getMapTaskIds();
final Progress copyPhase = getTask().getProgress().phase();
// we need input from every map task
- HashSet needed = new HashSet();
+ Vector needed = new Vector();
for (int i = 0; i < mapTaskIds.length; i++) {
needed.add(mapTaskIds[i]);
copyPhase.addPhase(); // add sub-phase per file
@@ -52,17 +52,21 @@ class ReduceTaskRunner extends TaskRunner {
InterTrackerProtocol jobClient = getTracker().getJobClient();
while (needed.size() > 0) {
-
getTask().reportProgress(getTracker());
// get list of available map output locations from job tracker
- String[] neededStrings =
- (String[])needed.toArray(new String[needed.size()]);
+ String[][] neededStrings = new String[needed.size()][];
+ for (int i = 0; i < needed.size(); i++) {
+ neededStrings[i] = (String[]) needed.elementAt(i);
+ }
MapOutputLocation[] locs =
jobClient.locateMapOutputs(task.getTaskId(), neededStrings);
if (locs.length == 0) {
try {
+ if (killed) {
+ return false;
+ }
Thread.sleep(1000);
} catch (InterruptedException e) {
}
@@ -96,9 +100,19 @@ class ReduceTaskRunner extends TaskRunner {
client.getFile(loc.getMapTaskId(), task.getTaskId(),
new IntWritable(task.getPartition()));
-
- needed.remove(loc.getMapTaskId()); // success: remove from needed
-
+
+ // Success: remove from 'needed'
+ boolean foundit = false;
+ for (Iterator it = needed.iterator(); it.hasNext() && !foundit; ) {
+ String idsForSingleMap[] = (String[]) it.next();
+ for (int j = 0; j < idsForSingleMap.length; j++) {
+ if (idsForSingleMap[j].equals(loc.getMapTaskId())) {
+ it.remove();
+ foundit = true;
+ break;
+ }
+ }
+ }
copyPhase.startNextPhase();
} catch (IOException e) { // failed: try again later
@@ -109,11 +123,10 @@ class ReduceTaskRunner extends TaskRunner {
} finally {
this.mapOutputFile.setProgressReporter(null);
}
-
}
-
}
getTask().reportProgress(getTracker());
+ return true;
}
/** Delete all of the temporary map output files. */
diff --git a/src/java/org/apache/nutch/mapred/Task.java b/src/java/org/apache/nutch/mapred/Task.java
index d506a8d40..cbfd61bcb 100644
--- a/src/java/org/apache/nutch/mapred/Task.java
+++ b/src/java/org/apache/nutch/mapred/Task.java
@@ -82,6 +82,8 @@ public abstract class Task implements Writable, NutchConfigurable {
private transient long nextProgressTime =
System.currentTimeMillis() + PROGRESS_INTERVAL;
+ public abstract boolean isMapTask();
+
public Progress getProgress() { return taskProgress; }
public Reporter getReporter(final TaskUmbilicalProtocol umbilical,
diff --git a/src/java/org/apache/nutch/mapred/TaskInProgress.java b/src/java/org/apache/nutch/mapred/TaskInProgress.java
new file mode 100644
index 000000000..a718a1feb
--- /dev/null
+++ b/src/java/org/apache/nutch/mapred/TaskInProgress.java
@@ -0,0 +1,445 @@
+/**
+ * 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.fs.*;
+import org.apache.nutch.ipc.*;
+import org.apache.nutch.util.*;
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import java.util.logging.*;
+
+
+////////////////////////////////////////////////////////
+// TaskInProgress maintains all the info needed for a
+// Task in the lifetime of its owning Job. A given Task
+// might be speculatively executed or reexecuted, so we
+// need a level of indirection above the running-id itself.
+//
+// A given TaskInProgress contains multiple taskids,
+// 0 or more of which might be executing at any one time.
+// (That's what allows speculative execution.) A taskid
+// is now *never* recycled. A TIP allocates enough taskids
+// to account for all the speculation and failures it will
+// ever have to handle. Once those are up, the TIP is dead.
+//
+////////////////////////////////////////////////////////
+class TaskInProgress {
+ static final int MAX_TASK_EXECS = 10;
+ static final int MAX_TASK_FAILURES = 4;
+ static final double SPECULATIVE_GAP = 0.2;
+ static final long SPECULATIVE_LAG = 60 * 1000;
+
+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.TaskInProgress");
+
+ // Defines the TIP
+ String jobFile = null;
+ FileSplit split = null;
+ TaskInProgress predecessors[] = null;
+ int partition;
+ JobTracker jobtracker;
+ String id;
+ String totalTaskIds[];
+ JobInProgress job;
+
+ // Status of the TIP
+ int numTaskFailures = 0;
+ double progress = 0;
+ long startTime = 0;
+ int completes = 0;
+ boolean failed = false;
+ TreeSet usableTaskIds = new TreeSet();
+ TreeSet recentTasks = new TreeSet();
+ NutchConf nutchConf;
+
+ TreeMap taskDiagnosticData = new TreeMap();
+ TreeMap taskStatuses = new TreeMap();
+
+ TreeSet machinesWhereFailed = new TreeSet();
+ TreeSet tasksReportedClosed = new TreeSet();
+
+ /**
+ * Constructor for MapTask
+ */
+ public TaskInProgress(String jobFile, FileSplit split, JobTracker jobtracker, NutchConf nutchConf, JobInProgress job) {
+ this.jobFile = jobFile;
+ this.split = split;
+ this.jobtracker = jobtracker;
+ this.job = job;
+ this.nutchConf = nutchConf;
+ init();
+ }
+
+ /**
+ * Constructor for ReduceTask
+ */
+ public TaskInProgress(String jobFile, TaskInProgress predecessors[], int partition, JobTracker jobtracker, NutchConf nutchConf, JobInProgress job) {
+ this.jobFile = jobFile;
+ this.predecessors = predecessors;
+ this.partition = partition;
+ this.jobtracker = jobtracker;
+ this.job = job;
+ this.nutchConf = nutchConf;
+ init();
+ }
+
+ /**
+ * Initialization common to Map and Reduce
+ */
+ void init() {
+ this.startTime = System.currentTimeMillis();
+ this.id = "tip_" + jobtracker.createUniqueId();
+ this.totalTaskIds = new String[MAX_TASK_EXECS + MAX_TASK_FAILURES];
+ for (int i = 0; i < totalTaskIds.length; i++) {
+ if (isMapTask()) {
+ totalTaskIds[i] = "task_m_" + jobtracker.createUniqueId();
+ } else {
+ totalTaskIds[i] = "task_r_" + jobtracker.createUniqueId();
+ }
+ usableTaskIds.add(totalTaskIds[i]);
+ }
+ }
+
+ ////////////////////////////////////
+ // Accessors, info, profiles, etc.
+ ////////////////////////////////////
+
+ /**
+ * Return the parent job
+ */
+ public JobInProgress getJob() {
+ return job;
+ }
+ /**
+ * Return an ID for this task, not its component taskid-threads
+ */
+ public String getTIPId() {
+ return this.id;
+ }
+ /**
+ * Whether this is a map task
+ */
+ public boolean isMapTask() {
+ return split != null;
+ }
+ /**
+ */
+ public boolean isComplete() {
+ return (completes > 0);
+ }
+ /**
+ */
+ public boolean isComplete(String taskid) {
+ TaskStatus status = (TaskStatus) taskStatuses.get(taskid);
+ if (status == null) {
+ return false;
+ }
+ return ((completes > 0) && (status.getRunState() == TaskStatus.SUCCEEDED));
+ }
+ /**
+ */
+ public boolean isFailed() {
+ return failed;
+ }
+ /**
+ * Number of times the TaskInProgress has failed.
+ */
+ public int numTaskFailures() {
+ return numTaskFailures();
+ }
+ /**
+ * Get the overall progress (from 0 to 1.0) for this TIP
+ */
+ public double getProgress() {
+ return progress;
+ }
+ /**
+ * Returns whether a component task-thread should be
+ * closed because the containing JobInProgress has completed.
+ */
+ public boolean shouldCloseForClosedJob(String taskid) {
+ // If the thing has never been closed,
+ // and it belongs to this TIP,
+ // and this TIP is somehow FINISHED,
+ // then true
+ TaskStatus ts = (TaskStatus) taskStatuses.get(taskid);
+ if ((ts != null) &&
+ (! tasksReportedClosed.contains(taskid)) &&
+ (job.getStatus().getRunState() != JobStatus.RUNNING)) {
+ tasksReportedClosed.add(taskid);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * A TaskInProgress might be speculatively executed, and so
+ * can have many taskids simultaneously. Reduce tasks rely on knowing
+ * their predecessor ids, so they can be sure that all the previous
+ * work has been completed.
+ *
+ * But we don't know ahead of time which task id will actually be
+ * the one that completes for a given Map task. We don't want the
+ * Reduce task to have to be recreated after Map-completion, or check
+ * in with the JobTracker. So instead, each TaskInProgress preallocates
+ * all the task-ids it could ever want to run simultaneously. Then the
+ * Reduce task can be told about all the ids task-ids for a given Map
+ * TaskInProgress. If any of the Map TIP's tasks complete, the Reduce
+ * task will know all is well, and can continue.
+ *
+ * Most of the time, only a small number of the possible task-ids will
+ * ever be used.
+ */
+ public String[] getAllPossibleTaskIds() {
+ return totalTaskIds;
+ }
+
+ /**
+ * Creates a "status report" for this task. Includes the
+ * task ID and overall status, plus reports for all the
+ * component task-threads that have ever been started.
+ */
+ Vector generateSingleReport() {
+ Vector report = new Vector();
+ report.add(getTIPId());
+ report.add("" + progress);
+
+ report.add(new Integer(taskDiagnosticData.size()));
+ for (Iterator it = taskDiagnosticData.keySet().iterator(); it.hasNext(); ) {
+ String taskid = (String) it.next();
+ Vector taskData = (Vector) taskDiagnosticData.get(taskid);
+
+ TaskStatus taskStatus = (TaskStatus) taskStatuses.get(taskid);
+ String taskStateString = taskStatus.getStateString();
+
+ report.add(taskData);
+ report.add(taskStateString);
+ }
+ return report;
+ }
+
+ ////////////////////////////////////////////////
+ // Update methods, usually invoked by the owning
+ // job.
+ ////////////////////////////////////////////////
+ /**
+ * A status message from a client has arrived.
+ * It updates the status of a single component-thread-task,
+ * which might result in an overall TaskInProgress status update.
+ */
+ public void updateStatus(TaskStatus status) {
+ String taskid = status.getTaskId();
+ String diagInfo = status.getDiagnosticInfo();
+ if (diagInfo != null && diagInfo.length() > 0) {
+ Vector diagHistory = (Vector) taskDiagnosticData.get(taskid);
+ if (diagHistory == null) {
+ diagHistory = new Vector();
+ taskDiagnosticData.put(taskid, diagHistory);
+ }
+ diagHistory.add(diagInfo);
+ }
+ taskStatuses.put(taskid, status);
+
+ // Recompute progress
+ recomputeProgress();
+ }
+
+ /**
+ * Indicate that one of the taskids in this TaskInProgress
+ * has failed.
+ */
+ public void failedSubTask(String taskid, String trackerName) {
+ //
+ // Note the failure and its location
+ //
+ LOG.info("Task '" + taskid + "' has been lost.");
+ TaskStatus status = (TaskStatus) taskStatuses.get(taskid);
+ if (status != null) {
+ status.setRunState(TaskStatus.FAILED);
+ }
+ this.recentTasks.remove(taskid);
+ this.completes--;
+
+ numTaskFailures++;
+ if (numTaskFailures >= MAX_TASK_FAILURES) {
+ LOG.info("TaskInProgress " + getTIPId() + " has failed " + numTaskFailures + " times.");
+ kill();
+ }
+ machinesWhereFailed.add(trackerName);
+
+ // Ask JobTracker to forget about this task
+ jobtracker.removeTaskEntry(taskid);
+
+ recomputeProgress();
+ }
+
+ /**
+ * Indicate that one of the taskids in this TaskInProgress
+ * has successfully completed!
+ */
+ public void completed(String taskid) {
+ LOG.info("Task '" + taskid + "' has completed.");
+ TaskStatus status = (TaskStatus) taskStatuses.get(taskid);
+ status.setRunState(TaskStatus.SUCCEEDED);
+ recentTasks.remove(taskid);
+
+ //
+ // Now that the TIP is complete, the other speculative
+ // subtasks will be closed when the owning tasktracker
+ // reports in and calls shouldClose() on this object.
+ //
+
+ this.completes++;
+ recomputeProgress();
+ }
+
+ /**
+ * The TIP's been ordered kill()ed.
+ */
+ public void kill() {
+ if (isComplete() || failed) {
+ return;
+ }
+ this.failed = true;
+ recomputeProgress();
+ }
+
+ /**
+ * This method is called whenever there's a status change
+ * for one of the TIP's sub-tasks. It recomputes the overall
+ * progress for the TIP. We examine all sub-tasks and find
+ * the one that's most advanced (and non-failed).
+ */
+ void recomputeProgress() {
+ if (isComplete()) {
+ this.progress = 1;
+ } else if (failed) {
+ this.progress = 0;
+ } else {
+ double bestProgress = 0;
+ for (Iterator it = taskStatuses.keySet().iterator(); it.hasNext(); ) {
+ String taskid = (String) it.next();
+ TaskStatus status = (TaskStatus) taskStatuses.get(taskid);
+ if (status.getRunState() == TaskStatus.SUCCEEDED) {
+ bestProgress = 1;
+ break;
+ } else if (status.getRunState() == TaskStatus.RUNNING) {
+ bestProgress = Math.max(bestProgress, status.getProgress());
+ }
+ }
+ this.progress = bestProgress;
+ }
+ }
+
+ /////////////////////////////////////////////////
+ // "Action" methods that actually require the TIP
+ // to do something.
+ /////////////////////////////////////////////////
+ /**
+ * Return whether this TIP has an NDFS cache-driven task
+ * to run at the given taskTracker.
+ */
+ boolean hasTaskWithCacheHit(String taskTracker, TaskTrackerStatus tts) {
+ if (failed || isComplete() || recentTasks.size() > 0) {
+ return false;
+ } else {
+ try {
+ if (isMapTask()) {
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
+ String hints[][] = fs.getFileCacheHints(split.getFile(), split.getStart(), split.getLength());
+ for (int i = 0; i < hints.length; i++) {
+ for (int j = 0; j < hints[i].length; j++) {
+ if (hints[i][j].equals(tts.getHost())) {
+ return true;
+ }
+ }
+ }
+ }
+ } catch (IOException ie) {
+ }
+ return false;
+ }
+ }
+ /**
+ * Return whether this TIP has a non-speculative task to run
+ */
+ boolean hasTask() {
+ if (failed || isComplete() || recentTasks.size() > 0) {
+ return false;
+ } else {
+ for (Iterator it = taskStatuses.values().iterator(); it.hasNext(); ) {
+ TaskStatus ts = (TaskStatus) it.next();
+ if (ts.getRunState() == TaskStatus.RUNNING) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ /**
+ * Return whether the TIP has a speculative task to run. We
+ * only launch a speculative task if the current TIP is really
+ * far behind, and has been behind for a non-trivial amount of
+ * time.
+ */
+ boolean hasSpeculativeTask(double averageProgress) {
+ //
+ // REMIND - mjc - these constants should be examined
+ // in more depth eventually...
+ //
+ if (isMapTask() &&
+ (averageProgress - progress >= SPECULATIVE_GAP) &&
+ (System.currentTimeMillis() - startTime >= SPECULATIVE_LAG)) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Return a Task that can be sent to a TaskTracker for execution.
+ */
+ public Task getTaskToRun(String taskTracker, TaskTrackerStatus tts, double avgProgress) {
+ Task t = null;
+ if (hasTaskWithCacheHit(taskTracker, tts) ||
+ hasTask() ||
+ hasSpeculativeTask(avgProgress)) {
+
+ String taskid = (String) usableTaskIds.first();
+ usableTaskIds.remove(taskid);
+
+ if (isMapTask()) {
+ t = new MapTask(jobFile, taskid, split);
+ } else {
+ String mapIdPredecessors[][] = new String[predecessors.length][];
+ for (int i = 0; i < mapIdPredecessors.length; i++) {
+ mapIdPredecessors[i] = predecessors[i].getAllPossibleTaskIds();
+ }
+ t = new ReduceTask(jobFile, taskid, mapIdPredecessors, partition);
+ }
+ t.setConf(nutchConf);
+
+ recentTasks.add(taskid);
+
+ // Ask JobTracker to note that the task exists
+ jobtracker.createTaskEntry(taskid, taskTracker, this);
+ }
+ return t;
+ }
+}
diff --git a/src/java/org/apache/nutch/mapred/TaskRunner.java b/src/java/org/apache/nutch/mapred/TaskRunner.java
index a4acd17a8..0f1ca305a 100644
--- a/src/java/org/apache/nutch/mapred/TaskRunner.java
+++ b/src/java/org/apache/nutch/mapred/TaskRunner.java
@@ -33,6 +33,7 @@ abstract class TaskRunner extends Thread {
public static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.mapred.TaskRunner");
+ boolean killed = false;
private Process process;
private Task t;
private TaskTracker tracker;
@@ -51,7 +52,7 @@ abstract class TaskRunner extends Thread {
/** 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 {}
+ public boolean prepare() throws IOException {return true;}
/** Called when this task's output is no longer needed.
* This method is run in the parent process after the child exits. It should
@@ -62,7 +63,9 @@ abstract class TaskRunner extends Thread {
public final void run() {
try {
- prepare();
+ if (! prepare()) {
+ return;
+ }
String sep = System.getProperty("path.separator");
File workDir = new File(new File(t.getJobFile()).getParent(), "work");
@@ -72,7 +75,7 @@ abstract class TaskRunner extends Thread {
// 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
@@ -158,6 +161,7 @@ abstract class TaskRunner extends Thread {
if (process != null) {
process.destroy();
}
+ killed = true;
}
/**
diff --git a/src/java/org/apache/nutch/mapred/TaskStatus.java b/src/java/org/apache/nutch/mapred/TaskStatus.java
index ae6adc888..7a7bbfd27 100644
--- a/src/java/org/apache/nutch/mapred/TaskStatus.java
+++ b/src/java/org/apache/nutch/mapred/TaskStatus.java
@@ -34,6 +34,7 @@ public class TaskStatus implements Writable {
public static final int UNASSIGNED = 3;
private String taskid;
+ private boolean isMap;
private float progress;
private int runState;
private String diagnosticInfo;
@@ -41,8 +42,9 @@ public class TaskStatus implements Writable {
public TaskStatus() {}
- public TaskStatus(String taskid, float progress, int runState, String diagnosticInfo, String stateString) {
+ public TaskStatus(String taskid, boolean isMap, float progress, int runState, String diagnosticInfo, String stateString) {
this.taskid = taskid;
+ this.isMap = isMap;
this.progress = progress;
this.runState = runState;
this.diagnosticInfo = diagnosticInfo;
@@ -50,6 +52,7 @@ public class TaskStatus implements Writable {
}
public String getTaskId() { return taskid; }
+ public boolean getIsMap() { return isMap; }
public float getProgress() { return progress; }
public void setProgress(float progress) { this.progress = progress; }
public int getRunState() { return runState; }
@@ -64,6 +67,7 @@ public class TaskStatus implements Writable {
//////////////////////////////////////////////
public void write(DataOutput out) throws IOException {
UTF8.writeString(out, taskid);
+ out.writeBoolean(isMap);
out.writeFloat(progress);
out.writeInt(runState);
UTF8.writeString(out, diagnosticInfo);
@@ -72,6 +76,7 @@ public class TaskStatus implements Writable {
public void readFields(DataInput in) throws IOException {
this.taskid = UTF8.readString(in);
+ this.isMap = in.readBoolean();
this.progress = in.readFloat();
this.runState = in.readInt();
this.diagnosticInfo = UTF8.readString(in);
diff --git a/src/java/org/apache/nutch/mapred/TaskTracker.java b/src/java/org/apache/nutch/mapred/TaskTracker.java
index 9092e9b28..638f1d1a8 100644
--- a/src/java/org/apache/nutch/mapred/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.mapred;
+ package org.apache.nutch.mapred;
import org.apache.nutch.fs.*;
import org.apache.nutch.io.*;
@@ -33,7 +33,6 @@ import java.util.logging.*;
* @author Mike Cafarella
*******************************************************/
public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutputProtocol, Runnable {
- private int maxCurrentTask;
static final long WAIT_FOR_DONE = 3 * 1000;
private long taskTimeout;
@@ -66,6 +65,8 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
private NutchConf fConf;
private MapOutputFile mapOutputFile;
+ private int maxCurrentTasks;
+
/**
* Start with the local machine name, and the default JobTracker
*/
@@ -77,9 +78,10 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
* Start with the local machine name, and the addr of the target JobTracker
*/
public TaskTracker(InetSocketAddress jobTrackAddr, NutchConf conf) throws IOException {
+ maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2);
+
this.fConf = conf;
this.jobTrackAddr = jobTrackAddr;
- this.maxCurrentTask = conf.getInt("mapred.tasktracker.tasks.maximum", 2);
this.taskTimeout = conf.getInt("mapred.task.timeout", 10* 60 * 1000);
this.mapOutputFile = new MapOutputFile();
this.mapOutputFile.setConf(conf);
@@ -93,6 +95,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
*/
void initialize() throws IOException {
this.taskTrackerName = "tracker_" + (Math.abs(r.nextInt()) % 100000);
+ LOG.info("Starting tracker " + taskTrackerName);
this.localHostname = InetAddress.getLocalHost().getHostName();
new JobConf(this.fConf).deleteLocalFiles(SUBDIR);
@@ -108,7 +111,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
// RPC initialization
while (true) {
try {
- this.taskReportServer = RPC.getServer(this, this.taskReportPort, this.maxCurrentTask, false, this.fConf);
+ this.taskReportServer = RPC.getServer(this, this.taskReportPort, maxCurrentTasks, false, this.fConf);
this.taskReportServer.start();
break;
} catch (BindException e) {
@@ -119,7 +122,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
}
while (true) {
try {
- this.mapOutputServer = RPC.getServer(this, this.mapOutputPort, this.maxCurrentTask, false, this.fConf);
+ this.mapOutputServer = RPC.getServer(this, this.mapOutputPort, maxCurrentTasks, false, this.fConf);
this.mapOutputServer.start();
break;
} catch (BindException e) {
@@ -142,9 +145,14 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
* clean.
*/
public synchronized void close() throws IOException {
- // Kill running tasks
- while (tasks.size() > 0) {
- TaskInProgress tip = (TaskInProgress)tasks.get(tasks.firstKey());
+ //
+ // Kill running tasks. Do this in a 2nd vector, called 'tasksToClose',
+ // because calling jobHasFinished() may result in an edit to 'tasks'.
+ //
+ TreeMap tasksToClose = new TreeMap();
+ tasksToClose.putAll(tasks);
+ for (Iterator it = tasksToClose.values().iterator(); it.hasNext(); ) {
+ TaskInProgress tip = (TaskInProgress) it.next();
tip.jobHasFinished();
}
@@ -154,11 +162,21 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
} catch (InterruptedException ie) {
}
- // Shutdown local RPC servers
- if (taskReportServer != null) {
- taskReportServer.stop();
- taskReportServer = null;
- }
+ //
+ // Shutdown local RPC servers. Do them
+ // in parallel, as RPC servers can take a long
+ // time to shutdown. (They need to wait a full
+ // RPC timeout, which might be 10-30 seconds.)
+ //
+ new Thread() {
+ public void run() {
+ if (taskReportServer != null) {
+ taskReportServer.stop();
+ taskReportServer = null;
+ }
+ }
+ }.start();
+
if (mapOutputServer != null) {
mapOutputServer.stop();
mapOutputServer = null;
@@ -227,7 +245,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
//
// Check if we should create a new Task
//
- if (runningTasks.size() < this.maxCurrentTask) {
+ if (runningTasks.size() < maxCurrentTasks) {
Task t = jobClient.pollForNewTask(taskTrackerName);
if (t != null) {
TaskInProgress tip = new TaskInProgress(t, this.fConf);
@@ -254,10 +272,17 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
}
}
+ //
+ // Check for any Tasks that should be killed, even if
+ // the containing Job is still ongoing. (This happens
+ // with speculative execution, when one version of the
+ // task finished before another
+ //
+
//
// Check for any Tasks whose job may have ended
//
- String toCloseId = jobClient.pollForClosedTask(taskTrackerName);
+ String toCloseId = jobClient.pollForTaskWithClosedJob(taskTrackerName);
if (toCloseId != null) {
synchronized (this) {
TaskInProgress tip = (TaskInProgress) tasks.get(toCloseId);
@@ -288,7 +313,8 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
staleState = true;
}
} catch (Exception ex) {
- LOG.info("Lost connection to JobTracker [" + jobTrackAddr + "]. ex=" + ex + " Retrying...");
+ ex.printStackTrace();
+ LOG.info("Lost connection to JobTracker [" + jobTrackAddr + "]. Retrying...");
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
@@ -373,7 +399,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
/**
*/
public TaskStatus createStatus() {
- TaskStatus status = new TaskStatus(task.getTaskId(), progress, runstate, diagnosticInfo.toString(), (stateString == null) ? "" : stateString);
+ TaskStatus status = new TaskStatus(task.getTaskId(), task.isMapTask(), progress, runstate, diagnosticInfo.toString(), (stateString == null) ? "" : stateString);
if (diagnosticInfo.length() > 0) {
diagnosticInfo = new StringBuffer();
}
diff --git a/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java b/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java
index 5fc6c4541..b6dff30ed 100644
--- a/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java
+++ b/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java
@@ -77,6 +77,28 @@ public class TaskTrackerStatus implements Writable {
public Iterator taskReports() {
return taskReports.iterator();
}
+
+ /**
+ * Return the current MapTask count
+ */
+ public int countMapTasks() {
+ int mapCount = 0;
+ for (Iterator it = taskReports.iterator(); it.hasNext(); ) {
+ TaskStatus ts = (TaskStatus) it.next();
+ if (ts.getIsMap()) {
+ mapCount++;
+ }
+ }
+ return mapCount;
+ }
+
+ /**
+ * Return the current ReduceTask count
+ */
+ public int countReduceTasks() {
+ return taskReports.size() - countMapTasks();
+ }
+
/**
*/
public long getLastSeen() {
diff --git a/src/test/org/apache/nutch/mapred/MapredLoadTest.java b/src/test/org/apache/nutch/mapred/MapredLoadTest.java
new file mode 100644
index 000000000..5261de775
--- /dev/null
+++ b/src/test/org/apache/nutch/mapred/MapredLoadTest.java
@@ -0,0 +1,317 @@
+/**
+ * Copyright 2006 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.fs.*;
+import org.apache.nutch.io.*;
+import org.apache.nutch.util.*;
+import org.apache.nutch.mapred.lib.*;
+
+import java.io.*;
+import java.util.*;
+import java.math.*;
+
+/**********************************************************
+ * MapredLoadTest generates a bunch of work that exercises
+ * a Nutch Map-Reduce system (and NDFS, too). It goes through
+ * the following steps:
+ *
+ * 1) Take inputs 'range' and 'counts'.
+ * 2) Generate 'counts' random integers between 0 and range-1.
+ * 3) Create a file that lists each integer between 0 and range-1,
+ * and lists the number of times that integer was generated.
+ * 4) Emit a (very large) file that contains all the integers
+ * in the order generated.
+ * 5) After the file has been generated, read it back and count
+ * how many times each int was generated.
+ * 6) Compare this big count-map against the original one. If
+ * they match, then SUCCESS! Otherwise, FAILURE!
+ *
+ * OK, that's how we can think about it. What are the map-reduce
+ * steps that get the job done?
+ *
+ * 1) In a non-mapred thread, take the inputs 'range' and 'counts'.
+ * 2) In a non-mapread thread, generate the answer-key and write to disk.
+ * 3) In a mapred job, divide the answer key into K jobs.
+ * 4) A mapred 'generator' task consists of K map jobs. Each reads
+ * an individual "sub-key", and generates integers according to
+ * to it (though with a random ordering).
+ * 5) The generator's reduce task agglomerates all of those files
+ * into a single one.
+ * 6) A mapred 'reader' task consists of M map jobs. The output
+ * file is cut into M pieces. Each of the M jobs counts the
+ * individual ints in its chunk and creates a map of all seen ints.
+ * 7) A mapred job integrates all the count files into a single one.
+ *
+ **********************************************************/
+public class MapredLoadTest {
+ static class RandomGenMapper implements Mapper {
+ Random r = new Random();
+ public void configure(JobConf job) {
+ }
+
+ public void map(WritableComparable key, Writable val, OutputCollector out, Reporter reporter) throws IOException {
+ int randomVal = ((IntWritable) key).get();
+ int randomCount = ((IntWritable) val).get();
+
+ for (int i = 0; i < randomCount; i++) {
+ out.collect(new IntWritable(Math.abs(r.nextInt())), new IntWritable(randomVal));
+ }
+ }
+ }
+ static class RandomGenReducer implements Reducer {
+ public void configure(JobConf job) {
+ }
+
+ public void reduce(WritableComparable key, Iterator it, OutputCollector out, Reporter reporter) throws IOException {
+ int keyint = ((IntWritable) key).get();
+ while (it.hasNext()) {
+ int val = ((IntWritable) it.next()).get();
+ out.collect(new UTF8("" + val), new UTF8(""));
+ }
+ }
+ }
+ static class RandomCheckMapper implements Mapper {
+ public void configure(JobConf job) {
+ }
+
+ public void map(WritableComparable key, Writable val, OutputCollector out, Reporter reporter) throws IOException {
+ long pos = ((LongWritable) key).get();
+ UTF8 str = (UTF8) val;
+
+ out.collect(new IntWritable(Integer.parseInt(str.toString().trim())), new IntWritable(1));
+ }
+ }
+ static class RandomCheckReducer implements Reducer {
+ public void configure(JobConf job) {
+ }
+
+ public void reduce(WritableComparable key, Iterator it, OutputCollector out, Reporter reporter) throws IOException {
+ int keyint = ((IntWritable) key).get();
+ int count = 0;
+ while (it.hasNext()) {
+ it.next();
+ count++;
+ }
+ out.collect(new IntWritable(keyint), new IntWritable(count));
+ }
+ }
+
+ int range;
+ int counts;
+ Random r = new Random();
+ NutchConf nutchConf;
+
+ /**
+ * MapredLoadTest
+ */
+ public MapredLoadTest(int range, int counts, NutchConf nutchConf) throws IOException {
+ this.range = range;
+ this.counts = counts;
+ this.nutchConf = nutchConf;
+ }
+
+ /**
+ *
+ */
+ public void launch() throws IOException {
+ //
+ // Generate distribution of ints. This is the answer key.
+ //
+ int countsToGo = counts;
+ int dist[] = new int[range];
+ for (int i = 0; i < range; i++) {
+ double avgInts = (1.0 * countsToGo) / (range - i);
+ dist[i] = (int) Math.max(0, Math.round(avgInts + (Math.sqrt(avgInts) * r.nextGaussian())));
+ countsToGo -= dist[i];
+ }
+ if (countsToGo > 0) {
+ dist[dist.length-1] += countsToGo;
+ }
+
+ //
+ // Write the answer key to a file.
+ //
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
+ File testdir = new File("mapred.loadtest");
+ fs.mkdirs(testdir);
+
+ File randomIns = new File(testdir, "genins");
+ fs.mkdirs(randomIns);
+
+ File answerkey = new File(randomIns, "answer.key");
+ SequenceFile.Writer out = new SequenceFile.Writer(fs, answerkey.getPath(), IntWritable.class, IntWritable.class);
+ try {
+ for (int i = 0; i < range; i++) {
+ out.append(new IntWritable(i), new IntWritable(dist[i]));
+ }
+ } finally {
+ out.close();
+ }
+
+ //
+ // Now we need to generate the random numbers according to
+ // the above distribution.
+ //
+ // We create a lot of map tasks, each of which takes at least
+ // one "line" of the distribution. (That is, a certain number
+ // X is to be generated Y number of times.)
+ //
+ // A map task emits Y key/val pairs. The val is X. The key
+ // is a randomly-generated number.
+ //
+ // The reduce task gets its input sorted by key. That is, sorted
+ // in random order. It then emits a single line of text that
+ // for the given values. It does not emit the key.
+ //
+ // Because there's just one reduce task, we emit a single big
+ // file of random numbers.
+ //
+ File randomOuts = new File(testdir, "genouts");
+ fs.mkdirs(randomOuts);
+
+
+ JobConf genJob = new JobConf(nutchConf);
+ genJob.setInputDir(randomIns);
+ genJob.setInputKeyClass(IntWritable.class);
+ genJob.setInputValueClass(IntWritable.class);
+ genJob.setInputFormat(SequenceFileInputFormat.class);
+ genJob.setMapperClass(RandomGenMapper.class);
+
+ genJob.setOutputDir(randomOuts);
+ genJob.setOutputKeyClass(IntWritable.class);
+ genJob.setOutputValueClass(IntWritable.class);
+ genJob.setOutputFormat(TextOutputFormat.class);
+ genJob.setReducerClass(RandomGenReducer.class);
+ genJob.setNumReduceTasks(1);
+
+ JobClient.runJob(genJob);
+
+ //
+ // Next, we read the big file in and regenerate the
+ // original map.
+ //
+ // We have many map tasks, each of which read at least one
+ // of the output numbers. For each number read in, the
+ // map task emits a key/value pair where the key is the
+ // number and the value is "1".
+ //
+ // We have a single reduce task, which receives its input
+ // sorted by the key emitted above. For each key, there will
+ // be a certain number of "1" values. The reduce task sums
+ // these values to compute how many times the given key was
+ // emitted.
+ //
+ // The reduce task then emits a key/val pair where the key
+ // is the number in question, and the value is the number of
+ // times the key was emitted. This is the same format as the
+ // original answer key (except that numbers emitted zero times
+ // will not appear in the regenerated key.)
+ //
+ File finalOuts = new File(testdir, "finalouts");
+ fs.mkdirs(finalOuts);
+ JobConf checkJob = new JobConf(nutchConf);
+ checkJob.setInputDir(randomOuts);
+ checkJob.setInputKeyClass(LongWritable.class);
+ checkJob.setInputValueClass(UTF8.class);
+ checkJob.setInputFormat(TextInputFormat.class);
+ checkJob.setMapperClass(RandomCheckMapper.class);
+
+ checkJob.setOutputDir(finalOuts);
+ checkJob.setOutputKeyClass(IntWritable.class);
+ checkJob.setOutputValueClass(IntWritable.class);
+ checkJob.setOutputFormat(SequenceFileOutputFormat.class);
+ checkJob.setReducerClass(RandomCheckReducer.class);
+ checkJob.setNumReduceTasks(1);
+
+ JobClient.runJob(checkJob);
+
+ //
+ // Finally, we compare the reconstructed answer key with the
+ // original one. Remember, we need to ignore zero-count items
+ // in the original key.
+ //
+ boolean success = true;
+ File recomputedkey = new File(finalOuts, "part-00000");
+ SequenceFile.Reader in = new SequenceFile.Reader(fs, recomputedkey.getPath(), nutchConf);
+ int totalseen = 0;
+ try {
+ IntWritable key = new IntWritable();
+ IntWritable val = new IntWritable();
+ for (int i = 0; i < range; i++) {
+ if (dist[i] == 0) {
+ continue;
+ }
+ if (! in.next(key, val)) {
+ System.err.println("Cannot read entry " + i);
+ success = false;
+ break;
+ } else {
+ if ( !((key.get() == i ) && (val.get() == dist[i]))) {
+ System.err.println("Mismatch! Pos=" + key.get() + ", i=" + i + ", val=" + val.get() + ", dist[i]=" + dist[i]);
+ success = false;
+ }
+ totalseen += val.get();
+ }
+ }
+ if (success) {
+ if (in.next(key, val)) {
+ System.err.println("Unnecessary lines in recomputed key!");
+ success = false;
+ }
+ }
+ } finally {
+ in.close();
+ }
+ int originalTotal = 0;
+ for (int i = 0; i < dist.length; i++) {
+ originalTotal += dist[i];
+ }
+ System.out.println("Original sum: " + originalTotal);
+ System.out.println("Recomputed sum: " + totalseen);
+
+ //
+ // Write to "results" whether the test succeeded or not.
+ //
+ File resultFile = new File(testdir, "results");
+ BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(resultFile)));
+ try {
+ bw.write("Success=" + success + "\n");
+ System.out.println("Success=" + success);
+ } finally {
+ bw.close();
+ }
+ }
+
+ /**
+ * Launches all the tasks in order.
+ */
+ public static void main(String[] argv) throws Exception {
+ if (argv.length < 2) {
+ System.err.println("Usage: MapredLoadTest <range> <counts>");
+ System.err.println();
+ System.err.println("Note: a good test will have a <counts> value that is substantially larger than the <range>");
+ return;
+ }
+
+ int i = 0;
+ int range = Integer.parseInt(argv[i++]);
+ int counts = Integer.parseInt(argv[i++]);
+
+ MapredLoadTest mlt = new MapredLoadTest(range, counts, new NutchConf());
+ mlt.launch();
+ }
+}
diff --git a/src/webapps/jobtracker/jobdetails.jsp b/src/webapps/jobtracker/jobdetails.jsp
index 745b39898..95ad19d07 100644
--- a/src/webapps/jobtracker/jobdetails.jsp
+++ b/src/webapps/jobtracker/jobdetails.jsp
@@ -9,21 +9,28 @@
<%
String jobid = request.getParameter("jobid");
JobTracker tracker = JobTracker.getTracker();
- JobTracker.JobInProgress job = (JobTracker.JobInProgress) tracker.getJob(jobid);
+ JobInProgress job = (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);
+ Vector mapTaskReports[] = (job != null) ? tracker.getMapTaskReport(jobid) : null;
+ Vector reduceTaskReports[] = (job != null) ? tracker.getReduceTaskReport(jobid) : null;
%>
<html>
<title>Nutch MapReduce Job Details</title>
<body>
+<%
+ if (job == null) {
+ %>
+ No job found<br>
+ <%
+ } else {
+ %>
<h1>Job '<%=jobid%>'</h1>
<b>Job File:</b> <%=profile.getJobFile()%><br>
-<b>Start time:</b> <%= new Date(job.getStartTime())%><br>
+<b>The job started at:</b> <%= new Date(job.getStartTime())%><br>
<%
if (status.getRunState() == JobStatus.RUNNING) {
out.print("The job is still running.<br>\n");
@@ -38,19 +45,28 @@
<h2>Map Tasks</h2>
<center>
<table border=2 cellpadding="5" cellspacing="2">
- <tr><td align="center">Map Task Id</td><td>Pct Complete</td><td>State</td><td>Diagnostic Text</td></tr>
+ <tr><td align="center">Map Task Id</td><td>Pct Complete</td><td>Diagnostic Data</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>");
+ String tipid = (String) v.elementAt(0);
+ String progress = (String) v.elementAt(1);
+ int diagnosticSize = ((Integer) v.elementAt(2)).intValue();
+
+ out.print("<tr><td>" + tipid + "</td><td>" + progress + "</td><td>");
+ for (int j = 0; j < diagnosticSize; j++) {
+ Vector taskData = (Vector) v.elementAt(3 + ((2 * j)));
+ String taskStateString = (String) v.elementAt(3 + ((2 * j) + 1));
+ out.print(taskStateString);
+ out.print("<b>");
+
+ for (Iterator it2 = taskData.iterator(); it2.hasNext(); ) {
+ out.print("" + it2.next());
+ out.println("<b>");
}
}
+ out.print("</td>");
out.print("</tr>\n");
}
%>
@@ -62,25 +78,36 @@
<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>
+ <tr><td align="center">Reduce Task Id</td><td>Pct Complete</td><td>Diagnostic Data</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>");
+ String tipid = (String) v.elementAt(0);
+ String progress = (String) v.elementAt(1);
+ int diagnosticSize = ((Integer) v.elementAt(2)).intValue();
+
+ out.print("<tr><td>" + tipid + "</td><td>" + progress + "</td><td>");
+ for (int j = 0; j < diagnosticSize; j++) {
+ Vector taskData = (Vector) v.elementAt(3 + ((2 * j)));
+ String taskStateString = (String) v.elementAt(3 + ((2 * j) + 1));
+ out.print(taskStateString);
+ out.print("<b>");
+
+ for (Iterator it2 = taskData.iterator(); it2.hasNext(); ) {
+ out.print("" + it2.next());
+ out.println("<b>");
}
}
+ out.print("</td>");
out.print("</tr>\n");
}
%>
</table>
</center>
-
+ <%
+ }
+%>
<hr>
<a href="/jobtracker.jsp">Go back to JobTracker</a><br>
diff --git a/src/webapps/jobtracker/jobtracker.jsp b/src/webapps/jobtracker/jobtracker.jsp
index 5604bda8e..6c40659b5 100644
--- a/src/webapps/jobtracker/jobtracker.jsp
+++ b/src/webapps/jobtracker/jobtracker.jsp
@@ -46,22 +46,22 @@
out.print("<tr><td align=\"center\" colspan=\"8\"><b>" + label + " Jobs </b></td></tr>\n");
if (jobs.size() > 0) {
- out.print("<tr><td><b>Jobid</b></td><td><b>% complete</b></td><td><b>Required maps</b></td><td><b>maps attempted</b></td><td><b>maps completed</b></td><td><b>Required reduces</b></td><td><b>reduces attempted</b></td><td><b>reduces completed</b></td></tr>\n");
+ out.print("<tr><td><b>Jobid</b></td><td><b>% complete</b></td><td><b>Required maps</b></td><td><b>maps completed</b></td><td><b>Required reduces</b></td><td><b>reduces completed</b></td></tr>\n");
for (Iterator it = jobs.iterator(); it.hasNext(); ) {
- JobTracker.JobInProgress job = (JobTracker.JobInProgress) it.next();
+ JobInProgress job = (JobInProgress) it.next();
JobProfile profile = job.getProfile();
JobStatus status = job.getStatus();
String jobid = profile.getJobId();
- float completedRatio = (100 * job.completedRatio());
+ double completedRatio = (0.5 * (100 * status.mapProgress())) +
+ (0.5 * (100 * status.reduceProgress()));
+
int desiredMaps = job.desiredMaps();
- int attemptedMaps = job.attemptedMaps();
- int completedMaps = job.completedMaps();
int desiredReduces = job.desiredReduces();
- int attemptedReduces = job.attemptedReduces();
- int completedReduces = job.completedReduces();
+ int completedMaps = job.finishedMaps();
+ int completedReduces = job.finishedReduces();
- out.print("<tr><td><a href=\"jobdetails.jsp?jobid=" + jobid + "\">" + jobid + "</a></td><td>" + completedRatio + "%</td><td>" + desiredMaps + "</td><td>" + attemptedMaps + "</td><td>" + completedMaps + "</td><td>" + desiredReduces + "</td><td>" + attemptedReduces + "</td><td> " + completedReduces + "</td></tr>\n");
+ out.print("<tr><td><a href=\"jobdetails.jsp?jobid=" + jobid + "\">" + jobid + "</a></td><td>" + completedRatio + "%</td><td>" + desiredMaps + "</td><td>" + completedMaps + "</td><td>" + desiredReduces + "</td><td> " + completedReduces + "</td></tr>\n");
}
} else {
out.print("<tr><td align=\"center\" colspan=\"8\"><i>none</i></td></tr>\n");