001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.mapred;
019
020import java.io.FileNotFoundException;
021import java.io.IOException;
022import java.net.InetSocketAddress;
023import java.net.URL;
024import java.security.PrivilegedExceptionAction;
025import java.util.ArrayList;
026import java.util.Collection;
027import java.util.List;
028
029import org.apache.hadoop.classification.InterfaceAudience;
030import org.apache.hadoop.classification.InterfaceStability;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.fs.FileStatus;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.io.Text;
036import org.apache.hadoop.mapred.ClusterStatus.BlackListInfo;
037import org.apache.hadoop.mapreduce.Cluster;
038import org.apache.hadoop.mapreduce.ClusterMetrics;
039import org.apache.hadoop.mapreduce.Job;
040import org.apache.hadoop.mapreduce.MRJobConfig;
041import org.apache.hadoop.mapreduce.QueueInfo;
042import org.apache.hadoop.mapreduce.TaskTrackerInfo;
043import org.apache.hadoop.mapreduce.TaskType;
044import org.apache.hadoop.mapreduce.filecache.DistributedCache;
045import org.apache.hadoop.mapreduce.security.token.delegation.DelegationTokenIdentifier;
046import org.apache.hadoop.mapreduce.tools.CLI;
047import org.apache.hadoop.mapreduce.util.ConfigUtil;
048import org.apache.hadoop.security.UserGroupInformation;
049import org.apache.hadoop.security.token.SecretManager.InvalidToken;
050import org.apache.hadoop.security.token.Token;
051import org.apache.hadoop.security.token.TokenRenewer;
052import org.apache.hadoop.util.Tool;
053import org.apache.hadoop.util.ToolRunner;
054
055/**
056 * <code>JobClient</code> is the primary interface for the user-job to interact
057 * with the cluster.
058 * 
059 * <code>JobClient</code> provides facilities to submit jobs, track their 
060 * progress, access component-tasks' reports/logs, get the Map-Reduce cluster
061 * status information etc.
062 * 
063 * <p>The job submission process involves:
064 * <ol>
065 *   <li>
066 *   Checking the input and output specifications of the job.
067 *   </li>
068 *   <li>
069 *   Computing the {@link InputSplit}s for the job.
070 *   </li>
071 *   <li>
072 *   Setup the requisite accounting information for the {@link DistributedCache} 
073 *   of the job, if necessary.
074 *   </li>
075 *   <li>
076 *   Copying the job's jar and configuration to the map-reduce system directory 
077 *   on the distributed file-system. 
078 *   </li>
079 *   <li>
080 *   Submitting the job to the cluster and optionally monitoring
081 *   it's status.
082 *   </li>
083 * </ol>
084 *  
085 * Normally the user creates the application, describes various facets of the
086 * job via {@link JobConf} and then uses the <code>JobClient</code> to submit 
087 * the job and monitor its progress.
088 * 
089 * <p>Here is an example on how to use <code>JobClient</code>:</p>
090 * <p><blockquote><pre>
091 *     // Create a new JobConf
092 *     JobConf job = new JobConf(new Configuration(), MyJob.class);
093 *     
094 *     // Specify various job-specific parameters     
095 *     job.setJobName("myjob");
096 *     
097 *     job.setInputPath(new Path("in"));
098 *     job.setOutputPath(new Path("out"));
099 *     
100 *     job.setMapperClass(MyJob.MyMapper.class);
101 *     job.setReducerClass(MyJob.MyReducer.class);
102 *
103 *     // Submit the job, then poll for progress until the job is complete
104 *     JobClient.runJob(job);
105 * </pre></blockquote>
106 * 
107 * <b id="JobControl">Job Control</b>
108 * 
109 * <p>At times clients would chain map-reduce jobs to accomplish complex tasks 
110 * which cannot be done via a single map-reduce job. This is fairly easy since 
111 * the output of the job, typically, goes to distributed file-system and that 
112 * can be used as the input for the next job.</p>
113 * 
114 * <p>However, this also means that the onus on ensuring jobs are complete 
115 * (success/failure) lies squarely on the clients. In such situations the 
116 * various job-control options are:
117 * <ol>
118 *   <li>
119 *   {@link #runJob(JobConf)} : submits the job and returns only after 
120 *   the job has completed.
121 *   </li>
122 *   <li>
123 *   {@link #submitJob(JobConf)} : only submits the job, then poll the 
124 *   returned handle to the {@link RunningJob} to query status and make 
125 *   scheduling decisions.
126 *   </li>
127 *   <li>
128 *   {@link JobConf#setJobEndNotificationURI(String)} : setup a notification
129 *   on job-completion, thus avoiding polling.
130 *   </li>
131 * </ol>
132 * 
133 * @see JobConf
134 * @see ClusterStatus
135 * @see Tool
136 * @see DistributedCache
137 */
138@InterfaceAudience.Public
139@InterfaceStability.Stable
140public class JobClient extends CLI {
141
142  @InterfaceAudience.Private
143  public static final String MAPREDUCE_CLIENT_RETRY_POLICY_ENABLED_KEY =
144      "mapreduce.jobclient.retry.policy.enabled";
145  @InterfaceAudience.Private
146  public static final boolean MAPREDUCE_CLIENT_RETRY_POLICY_ENABLED_DEFAULT =
147      false;
148  @InterfaceAudience.Private
149  public static final String MAPREDUCE_CLIENT_RETRY_POLICY_SPEC_KEY =
150      "mapreduce.jobclient.retry.policy.spec";
151  @InterfaceAudience.Private
152  public static final String MAPREDUCE_CLIENT_RETRY_POLICY_SPEC_DEFAULT =
153      "10000,6,60000,10"; // t1,n1,t2,n2,...
154
155  public static enum TaskStatusFilter { NONE, KILLED, FAILED, SUCCEEDED, ALL }
156  private TaskStatusFilter taskOutputFilter = TaskStatusFilter.FAILED; 
157  
158  private int maxRetry = MRJobConfig.DEFAULT_MR_CLIENT_JOB_MAX_RETRIES;
159  private long retryInterval =
160      MRJobConfig.DEFAULT_MR_CLIENT_JOB_RETRY_INTERVAL;
161
162  static{
163    ConfigUtil.loadResources();
164  }
165
166  /**
167   * A NetworkedJob is an implementation of RunningJob.  It holds
168   * a JobProfile object to provide some info, and interacts with the
169   * remote service to provide certain functionality.
170   */
171  static class NetworkedJob implements RunningJob {
172    Job job;
173    /**
174     * We store a JobProfile and a timestamp for when we last
175     * acquired the job profile.  If the job is null, then we cannot
176     * perform any of the tasks.  The job might be null if the cluster
177     * has completely forgotten about the job.  (eg, 24 hours after the
178     * job completes.)
179     */
180    public NetworkedJob(JobStatus status, Cluster cluster) throws IOException {
181      this(status, cluster, new JobConf(status.getJobFile()));
182    }
183    
184    private NetworkedJob(JobStatus status, Cluster cluster, JobConf conf)
185        throws IOException {
186      this(Job.getInstance(cluster, status, conf));
187    }
188
189    public NetworkedJob(Job job) throws IOException {
190      this.job = job;
191    }
192
193    public Configuration getConfiguration() {
194      return job.getConfiguration();
195    }
196
197    /**
198     * An identifier for the job
199     */
200    public JobID getID() {
201      return JobID.downgrade(job.getJobID());
202    }
203    
204    /** @deprecated This method is deprecated and will be removed. Applications should 
205     * rather use {@link #getID()}.*/
206    @Deprecated
207    public String getJobID() {
208      return getID().toString();
209    }
210    
211    /**
212     * The user-specified job name
213     */
214    public String getJobName() {
215      return job.getJobName();
216    }
217
218    /**
219     * The name of the job file
220     */
221    public String getJobFile() {
222      return job.getJobFile();
223    }
224
225    /**
226     * A URL where the job's status can be seen
227     */
228    public String getTrackingURL() {
229      return job.getTrackingURL();
230    }
231
232    /**
233     * A float between 0.0 and 1.0, indicating the % of map work
234     * completed.
235     */
236    public float mapProgress() throws IOException {
237      return job.mapProgress();
238    }
239
240    /**
241     * A float between 0.0 and 1.0, indicating the % of reduce work
242     * completed.
243     */
244    public float reduceProgress() throws IOException {
245      return job.reduceProgress();
246    }
247
248    /**
249     * A float between 0.0 and 1.0, indicating the % of cleanup work
250     * completed.
251     */
252    public float cleanupProgress() throws IOException {
253      try {
254        return job.cleanupProgress();
255      } catch (InterruptedException ie) {
256        throw new IOException(ie);
257      }
258    }
259
260    /**
261     * A float between 0.0 and 1.0, indicating the % of setup work
262     * completed.
263     */
264    public float setupProgress() throws IOException {
265      return job.setupProgress();
266    }
267
268    /**
269     * Returns immediately whether the whole job is done yet or not.
270     */
271    public synchronized boolean isComplete() throws IOException {
272      return job.isComplete();
273    }
274
275    /**
276     * True iff job completed successfully.
277     */
278    public synchronized boolean isSuccessful() throws IOException {
279      return job.isSuccessful();
280    }
281
282    /**
283     * Blocks until the job is finished
284     */
285    public void waitForCompletion() throws IOException {
286      try {
287        job.waitForCompletion(false);
288      } catch (InterruptedException ie) {
289        throw new IOException(ie);
290      } catch (ClassNotFoundException ce) {
291        throw new IOException(ce);
292      }
293    }
294
295    /**
296     * Tells the service to get the state of the current job.
297     */
298    public synchronized int getJobState() throws IOException {
299      try {
300        return job.getJobState().getValue();
301      } catch (InterruptedException ie) {
302        throw new IOException(ie);
303      }
304    }
305    
306    /**
307     * Tells the service to terminate the current job.
308     */
309    public synchronized void killJob() throws IOException {
310      job.killJob();
311    }
312   
313    
314    /** Set the priority of the job.
315    * @param priority new priority of the job. 
316    */
317    public synchronized void setJobPriority(String priority) 
318                                                throws IOException {
319      try {
320        job.setPriority(
321          org.apache.hadoop.mapreduce.JobPriority.valueOf(priority));
322      } catch (InterruptedException ie) {
323        throw new IOException(ie);
324      }
325    }
326    
327    /**
328     * Kill indicated task attempt.
329     * @param taskId the id of the task to kill.
330     * @param shouldFail if true the task is failed and added to failed tasks list, otherwise
331     * it is just killed, w/o affecting job failure status.
332     */
333    public synchronized void killTask(TaskAttemptID taskId,
334        boolean shouldFail) throws IOException {
335      if (shouldFail) {
336        job.failTask(taskId);
337      } else {
338        job.killTask(taskId);
339      }
340    }
341
342    /** @deprecated Applications should rather use {@link #killTask(TaskAttemptID, boolean)}*/
343    @Deprecated
344    public synchronized void killTask(String taskId, boolean shouldFail) throws IOException {
345      killTask(TaskAttemptID.forName(taskId), shouldFail);
346    }
347    
348    /**
349     * Fetch task completion events from cluster for this job. 
350     */
351    public synchronized TaskCompletionEvent[] getTaskCompletionEvents(
352        int startFrom) throws IOException {
353      try {
354        org.apache.hadoop.mapreduce.TaskCompletionEvent[] acls = 
355          job.getTaskCompletionEvents(startFrom, 10);
356        TaskCompletionEvent[] ret = new TaskCompletionEvent[acls.length];
357        for (int i = 0 ; i < acls.length; i++ ) {
358          ret[i] = TaskCompletionEvent.downgrade(acls[i]);
359        }
360        return ret;
361      } catch (InterruptedException ie) {
362        throw new IOException(ie);
363      }
364    }
365
366    /**
367     * Dump stats to screen
368     */
369    @Override
370    public String toString() {
371      return job.toString();
372    }
373        
374    /**
375     * Returns the counters for this job
376     */
377    public Counters getCounters() throws IOException {
378      Counters result = null;
379      org.apache.hadoop.mapreduce.Counters temp = job.getCounters();
380      if(temp != null) {
381        result = Counters.downgrade(temp);
382      }
383      return result;
384    }
385    
386    @Override
387    public String[] getTaskDiagnostics(TaskAttemptID id) throws IOException {
388      try { 
389        return job.getTaskDiagnostics(id);
390      } catch (InterruptedException ie) {
391        throw new IOException(ie);
392      }
393    }
394
395    public String getHistoryUrl() throws IOException {
396      try {
397        return job.getHistoryUrl();
398      } catch (InterruptedException ie) {
399        throw new IOException(ie);
400      }
401    }
402
403    public boolean isRetired() throws IOException {
404      try {
405        return job.isRetired();
406      } catch (InterruptedException ie) {
407        throw new IOException(ie);
408      }
409    }
410    
411    boolean monitorAndPrintJob() throws IOException, InterruptedException {
412      return job.monitorAndPrintJob();
413    }
414    
415    @Override
416    public String getFailureInfo() throws IOException {
417      try {
418        return job.getStatus().getFailureInfo();
419      } catch (InterruptedException ie) {
420        throw new IOException(ie);
421      }
422    }
423
424    @Override
425    public JobStatus getJobStatus() throws IOException {
426      try {
427        return JobStatus.downgrade(job.getStatus());
428      } catch (InterruptedException ie) {
429        throw new IOException(ie);
430      }
431    }
432  }
433
434  /**
435   * Ugi of the client. We store this ugi when the client is created and 
436   * then make sure that the same ugi is used to run the various protocols.
437   */
438  UserGroupInformation clientUgi;
439  
440  /**
441   * Create a job client.
442   */
443  public JobClient() {
444  }
445    
446  /**
447   * Build a job client with the given {@link JobConf}, and connect to the 
448   * default cluster
449   * 
450   * @param conf the job configuration.
451   * @throws IOException
452   */
453  public JobClient(JobConf conf) throws IOException {
454    init(conf);
455  }
456
457  /**
458   * Build a job client with the given {@link Configuration}, 
459   * and connect to the default cluster
460   * 
461   * @param conf the configuration.
462   * @throws IOException
463   */
464  public JobClient(Configuration conf) throws IOException {
465    init(new JobConf(conf));
466  }
467
468  /**
469   * Connect to the default cluster
470   * @param conf the job configuration.
471   * @throws IOException
472   */
473  public void init(JobConf conf) throws IOException {
474    setConf(conf);
475    cluster = new Cluster(conf);
476    clientUgi = UserGroupInformation.getCurrentUser();
477
478    maxRetry = conf.getInt(MRJobConfig.MR_CLIENT_JOB_MAX_RETRIES,
479      MRJobConfig.DEFAULT_MR_CLIENT_JOB_MAX_RETRIES);
480
481    retryInterval =
482      conf.getLong(MRJobConfig.MR_CLIENT_JOB_RETRY_INTERVAL,
483        MRJobConfig.DEFAULT_MR_CLIENT_JOB_RETRY_INTERVAL);
484
485  }
486
487  /**
488   * Build a job client, connect to the indicated job tracker.
489   * 
490   * @param jobTrackAddr the job tracker to connect to.
491   * @param conf configuration.
492   */
493  public JobClient(InetSocketAddress jobTrackAddr, 
494                   Configuration conf) throws IOException {
495    cluster = new Cluster(jobTrackAddr, conf);
496    clientUgi = UserGroupInformation.getCurrentUser();
497  }
498
499  /**
500   * Close the <code>JobClient</code>.
501   */
502  public synchronized void close() throws IOException {
503    cluster.close();
504  }
505
506  /**
507   * Get a filesystem handle.  We need this to prepare jobs
508   * for submission to the MapReduce system.
509   * 
510   * @return the filesystem handle.
511   */
512  public synchronized FileSystem getFs() throws IOException {
513    try { 
514      return cluster.getFileSystem();
515    } catch (InterruptedException ie) {
516      throw new IOException(ie);
517    }
518  }
519  
520  /**
521   * Get a handle to the Cluster
522   */
523  public Cluster getClusterHandle() {
524    return cluster;
525  }
526  
527  /**
528   * Submit a job to the MR system.
529   * 
530   * This returns a handle to the {@link RunningJob} which can be used to track
531   * the running-job.
532   * 
533   * @param jobFile the job configuration.
534   * @return a handle to the {@link RunningJob} which can be used to track the
535   *         running-job.
536   * @throws FileNotFoundException
537   * @throws InvalidJobConfException
538   * @throws IOException
539   */
540  public RunningJob submitJob(String jobFile) throws FileNotFoundException, 
541                                                     InvalidJobConfException, 
542                                                     IOException {
543    // Load in the submitted job details
544    JobConf job = new JobConf(jobFile);
545    return submitJob(job);
546  }
547    
548  /**
549   * Submit a job to the MR system.
550   * This returns a handle to the {@link RunningJob} which can be used to track
551   * the running-job.
552   * 
553   * @param conf the job configuration.
554   * @return a handle to the {@link RunningJob} which can be used to track the
555   *         running-job.
556   * @throws FileNotFoundException
557   * @throws IOException
558   */
559  public RunningJob submitJob(final JobConf conf) throws FileNotFoundException,
560                                                  IOException {
561    return submitJobInternal(conf);
562  }
563
564  @InterfaceAudience.Private
565  public RunningJob submitJobInternal(final JobConf conf)
566      throws FileNotFoundException, IOException {
567    try {
568      conf.setBooleanIfUnset("mapred.mapper.new-api", false);
569      conf.setBooleanIfUnset("mapred.reducer.new-api", false);
570      Job job = clientUgi.doAs(new PrivilegedExceptionAction<Job> () {
571        @Override
572        public Job run() throws IOException, ClassNotFoundException, 
573          InterruptedException {
574          Job job = Job.getInstance(conf);
575          job.submit();
576          return job;
577        }
578      });
579      // update our Cluster instance with the one created by Job for submission
580      // (we can't pass our Cluster instance to Job, since Job wraps the config
581      // instance, and the two configs would then diverge)
582      cluster = job.getCluster();
583      return new NetworkedJob(job);
584    } catch (InterruptedException ie) {
585      throw new IOException("interrupted", ie);
586    }
587  }
588
589  private Job getJobUsingCluster(final JobID jobid) throws IOException,
590  InterruptedException {
591    return clientUgi.doAs(new PrivilegedExceptionAction<Job>() {
592      public Job run() throws IOException, InterruptedException  {
593       return cluster.getJob(jobid);
594      }
595    });
596  }
597
598  protected RunningJob getJobInner(final JobID jobid) throws IOException {
599    try {
600      
601      Job job = getJobUsingCluster(jobid);
602      if (job != null) {
603        JobStatus status = JobStatus.downgrade(job.getStatus());
604        if (status != null) {
605          return new NetworkedJob(status, cluster,
606              new JobConf(job.getConfiguration()));
607        } 
608      }
609    } catch (InterruptedException ie) {
610      throw new IOException(ie);
611    }
612    return null;
613  }
614
615  /**
616   * Get an {@link RunningJob} object to track an ongoing job.  Returns
617   * null if the id does not correspond to any known job.
618   *
619   * @param jobid the jobid of the job.
620   * @return the {@link RunningJob} handle to track the job, null if the
621   *         <code>jobid</code> doesn't correspond to any known job.
622   * @throws IOException
623   */
624  public RunningJob getJob(final JobID jobid) throws IOException {
625     for (int i = 0;i <= maxRetry;i++) {
626       if (i > 0) {
627         try {
628           Thread.sleep(retryInterval);
629         } catch (Exception e) { }
630       }
631       RunningJob job = getJobInner(jobid);
632       if (job != null) {
633         return job;
634       }
635     }
636     return null;
637  }
638
639  /**@deprecated Applications should rather use {@link #getJob(JobID)}.
640   */
641  @Deprecated
642  public RunningJob getJob(String jobid) throws IOException {
643    return getJob(JobID.forName(jobid));
644  }
645  
646  private static final TaskReport[] EMPTY_TASK_REPORTS = new TaskReport[0];
647  
648  /**
649   * Get the information of the current state of the map tasks of a job.
650   * 
651   * @param jobId the job to query.
652   * @return the list of all of the map tips.
653   * @throws IOException
654   */
655  public TaskReport[] getMapTaskReports(JobID jobId) throws IOException {
656    return getTaskReports(jobId, TaskType.MAP);
657  }
658  
659  private TaskReport[] getTaskReports(final JobID jobId, TaskType type) throws 
660    IOException {
661    try {
662      Job j = getJobUsingCluster(jobId);
663      if(j == null) {
664        return EMPTY_TASK_REPORTS;
665      }
666      return TaskReport.downgradeArray(j.getTaskReports(type));
667    } catch (InterruptedException ie) {
668      throw new IOException(ie);
669    }
670  }
671  
672  /**@deprecated Applications should rather use {@link #getMapTaskReports(JobID)}*/
673  @Deprecated
674  public TaskReport[] getMapTaskReports(String jobId) throws IOException {
675    return getMapTaskReports(JobID.forName(jobId));
676  }
677  
678  /**
679   * Get the information of the current state of the reduce tasks of a job.
680   * 
681   * @param jobId the job to query.
682   * @return the list of all of the reduce tips.
683   * @throws IOException
684   */    
685  public TaskReport[] getReduceTaskReports(JobID jobId) throws IOException {
686    return getTaskReports(jobId, TaskType.REDUCE);
687  }
688
689  /**
690   * Get the information of the current state of the cleanup tasks of a job.
691   * 
692   * @param jobId the job to query.
693   * @return the list of all of the cleanup tips.
694   * @throws IOException
695   */    
696  public TaskReport[] getCleanupTaskReports(JobID jobId) throws IOException {
697    return getTaskReports(jobId, TaskType.JOB_CLEANUP);
698  }
699
700  /**
701   * Get the information of the current state of the setup tasks of a job.
702   * 
703   * @param jobId the job to query.
704   * @return the list of all of the setup tips.
705   * @throws IOException
706   */    
707  public TaskReport[] getSetupTaskReports(JobID jobId) throws IOException {
708    return getTaskReports(jobId, TaskType.JOB_SETUP);
709  }
710
711  
712  /**@deprecated Applications should rather use {@link #getReduceTaskReports(JobID)}*/
713  @Deprecated
714  public TaskReport[] getReduceTaskReports(String jobId) throws IOException {
715    return getReduceTaskReports(JobID.forName(jobId));
716  }
717  
718  /**
719   * Display the information about a job's tasks, of a particular type and
720   * in a particular state
721   * 
722   * @param jobId the ID of the job
723   * @param type the type of the task (map/reduce/setup/cleanup)
724   * @param state the state of the task 
725   * (pending/running/completed/failed/killed)
726   */
727  public void displayTasks(final JobID jobId, String type, String state) 
728  throws IOException {
729    try {
730      Job job = getJobUsingCluster(jobId);
731      super.displayTasks(job, type, state);
732    } catch (InterruptedException ie) {
733      throw new IOException(ie);
734    }
735  }
736  
737  /**
738   * Get status information about the Map-Reduce cluster.
739   *  
740   * @return the status information about the Map-Reduce cluster as an object
741   *         of {@link ClusterStatus}.
742   * @throws IOException
743   */
744  public ClusterStatus getClusterStatus() throws IOException {
745    try {
746      return clientUgi.doAs(new PrivilegedExceptionAction<ClusterStatus>() {
747        public ClusterStatus run() throws IOException, InterruptedException {
748          ClusterMetrics metrics = cluster.getClusterStatus();
749          return new ClusterStatus(metrics.getTaskTrackerCount(), metrics
750            .getBlackListedTaskTrackerCount(), cluster
751            .getTaskTrackerExpiryInterval(), metrics.getOccupiedMapSlots(),
752            metrics.getOccupiedReduceSlots(), metrics.getMapSlotCapacity(),
753            metrics.getReduceSlotCapacity(), cluster.getJobTrackerStatus(),
754            metrics.getDecommissionedTaskTrackerCount(), metrics
755              .getGrayListedTaskTrackerCount());
756        }
757      });
758    } catch (InterruptedException ie) {
759      throw new IOException(ie);
760    }
761  }
762
763  private  Collection<String> arrayToStringList(TaskTrackerInfo[] objs) {
764    Collection<String> list = new ArrayList<String>();
765    for (TaskTrackerInfo info: objs) {
766      list.add(info.getTaskTrackerName());
767    }
768    return list;
769  }
770
771  private  Collection<BlackListInfo> arrayToBlackListInfo(TaskTrackerInfo[] objs) {
772    Collection<BlackListInfo> list = new ArrayList<BlackListInfo>();
773    for (TaskTrackerInfo info: objs) {
774      BlackListInfo binfo = new BlackListInfo();
775      binfo.setTrackerName(info.getTaskTrackerName());
776      binfo.setReasonForBlackListing(info.getReasonForBlacklist());
777      binfo.setBlackListReport(info.getBlacklistReport());
778      list.add(binfo);
779    }
780    return list;
781  }
782
783  /**
784   * Get status information about the Map-Reduce cluster.
785   *  
786   * @param  detailed if true then get a detailed status including the
787   *         tracker names
788   * @return the status information about the Map-Reduce cluster as an object
789   *         of {@link ClusterStatus}.
790   * @throws IOException
791   */
792  public ClusterStatus getClusterStatus(boolean detailed) throws IOException {
793    try {
794      return clientUgi.doAs(new PrivilegedExceptionAction<ClusterStatus>() {
795        public ClusterStatus run() throws IOException, InterruptedException {
796        ClusterMetrics metrics = cluster.getClusterStatus();
797        return new ClusterStatus(arrayToStringList(cluster.getActiveTaskTrackers()),
798          arrayToBlackListInfo(cluster.getBlackListedTaskTrackers()),
799          cluster.getTaskTrackerExpiryInterval(), metrics.getOccupiedMapSlots(),
800          metrics.getOccupiedReduceSlots(), metrics.getMapSlotCapacity(),
801          metrics.getReduceSlotCapacity(), 
802          cluster.getJobTrackerStatus());
803        }
804      });
805    } catch (InterruptedException ie) {
806      throw new IOException(ie);
807    }
808  }
809    
810
811  /** 
812   * Get the jobs that are not completed and not failed.
813   * 
814   * @return array of {@link JobStatus} for the running/to-be-run jobs.
815   * @throws IOException
816   */
817  public JobStatus[] jobsToComplete() throws IOException {
818    List<JobStatus> stats = new ArrayList<JobStatus>();
819    for (JobStatus stat : getAllJobs()) {
820      if (!stat.isJobComplete()) {
821        stats.add(stat);
822      }
823    }
824    return stats.toArray(new JobStatus[0]);
825  }
826
827  /** 
828   * Get the jobs that are submitted.
829   * 
830   * @return array of {@link JobStatus} for the submitted jobs.
831   * @throws IOException
832   */
833  public JobStatus[] getAllJobs() throws IOException {
834    try {
835      org.apache.hadoop.mapreduce.JobStatus[] jobs = 
836          clientUgi.doAs(new PrivilegedExceptionAction<
837              org.apache.hadoop.mapreduce.JobStatus[]> () {
838            public org.apache.hadoop.mapreduce.JobStatus[] run() 
839                throws IOException, InterruptedException {
840              return cluster.getAllJobStatuses();
841            }
842          });
843      JobStatus[] stats = new JobStatus[jobs.length];
844      for (int i = 0; i < jobs.length; i++) {
845        stats[i] = JobStatus.downgrade(jobs[i]);
846      }
847      return stats;
848    } catch (InterruptedException ie) {
849      throw new IOException(ie);
850    }
851  }
852  
853  /** 
854   * Utility that submits a job, then polls for progress until the job is
855   * complete.
856   * 
857   * @param job the job configuration.
858   * @throws IOException if the job fails
859   */
860  public static RunningJob runJob(JobConf job) throws IOException {
861    JobClient jc = new JobClient(job);
862    RunningJob rj = jc.submitJob(job);
863    try {
864      if (!jc.monitorAndPrintJob(job, rj)) {
865        throw new IOException("Job failed!");
866      }
867    } catch (InterruptedException ie) {
868      Thread.currentThread().interrupt();
869    }
870    return rj;
871  }
872  
873  /**
874   * Monitor a job and print status in real-time as progress is made and tasks 
875   * fail.
876   * @param conf the job's configuration
877   * @param job the job to track
878   * @return true if the job succeeded
879   * @throws IOException if communication to the JobTracker fails
880   */
881  public boolean monitorAndPrintJob(JobConf conf, 
882                                    RunningJob job
883  ) throws IOException, InterruptedException {
884    return ((NetworkedJob)job).monitorAndPrintJob();
885  }
886
887  static String getTaskLogURL(TaskAttemptID taskId, String baseUrl) {
888    return (baseUrl + "/tasklog?plaintext=true&attemptid=" + taskId); 
889  }
890  
891  static Configuration getConfiguration(String jobTrackerSpec)
892  {
893    Configuration conf = new Configuration();
894    if (jobTrackerSpec != null) {        
895      if (jobTrackerSpec.indexOf(":") >= 0) {
896        conf.set("mapred.job.tracker", jobTrackerSpec);
897      } else {
898        String classpathFile = "hadoop-" + jobTrackerSpec + ".xml";
899        URL validate = conf.getResource(classpathFile);
900        if (validate == null) {
901          throw new RuntimeException(classpathFile + " not found on CLASSPATH");
902        }
903        conf.addResource(classpathFile);
904      }
905    }
906    return conf;
907  }
908
909  /**
910   * Sets the output filter for tasks. only those tasks are printed whose
911   * output matches the filter. 
912   * @param newValue task filter.
913   */
914  @Deprecated
915  public void setTaskOutputFilter(TaskStatusFilter newValue){
916    this.taskOutputFilter = newValue;
917  }
918    
919  /**
920   * Get the task output filter out of the JobConf.
921   * 
922   * @param job the JobConf to examine.
923   * @return the filter level.
924   */
925  public static TaskStatusFilter getTaskOutputFilter(JobConf job) {
926    return TaskStatusFilter.valueOf(job.get("jobclient.output.filter", 
927                                            "FAILED"));
928  }
929    
930  /**
931   * Modify the JobConf to set the task output filter.
932   * 
933   * @param job the JobConf to modify.
934   * @param newValue the value to set.
935   */
936  public static void setTaskOutputFilter(JobConf job, 
937                                         TaskStatusFilter newValue) {
938    job.set("jobclient.output.filter", newValue.toString());
939  }
940    
941  /**
942   * Returns task output filter.
943   * @return task filter. 
944   */
945  @Deprecated
946  public TaskStatusFilter getTaskOutputFilter(){
947    return this.taskOutputFilter; 
948  }
949
950  protected long getCounter(org.apache.hadoop.mapreduce.Counters cntrs,
951      String counterGroupName, String counterName) throws IOException {
952    Counters counters = Counters.downgrade(cntrs);
953    return counters.findCounter(counterGroupName, counterName).getValue();
954  }
955
956  /**
957   * Get status information about the max available Maps in the cluster.
958   *  
959   * @return the max available Maps in the cluster
960   * @throws IOException
961   */
962  public int getDefaultMaps() throws IOException {
963    try {
964      return clientUgi.doAs(new PrivilegedExceptionAction<Integer>() {
965        @Override
966        public Integer run() throws IOException, InterruptedException {
967          return cluster.getClusterStatus().getMapSlotCapacity();
968        }
969      });
970    } catch (InterruptedException ie) {
971      throw new IOException(ie);
972    }
973  }
974
975  /**
976   * Get status information about the max available Reduces in the cluster.
977   *  
978   * @return the max available Reduces in the cluster
979   * @throws IOException
980   */
981  public int getDefaultReduces() throws IOException {
982    try {
983      return clientUgi.doAs(new PrivilegedExceptionAction<Integer>() {
984        @Override
985        public Integer run() throws IOException, InterruptedException {
986          return cluster.getClusterStatus().getReduceSlotCapacity();
987        }
988      });
989    } catch (InterruptedException ie) {
990      throw new IOException(ie);
991    }
992  }
993
994  /**
995   * Grab the jobtracker system directory path where job-specific files are to be placed.
996   * 
997   * @return the system directory where job-specific files are to be placed.
998   */
999  public Path getSystemDir() {
1000    try {
1001      return clientUgi.doAs(new PrivilegedExceptionAction<Path>() {
1002        @Override
1003        public Path run() throws IOException, InterruptedException {
1004          return cluster.getSystemDir();
1005        }
1006      });
1007      } catch (IOException ioe) {
1008      return null;
1009    } catch (InterruptedException ie) {
1010      return null;
1011    }
1012  }
1013
1014  /**
1015   * Checks if the job directory is clean and has all the required components
1016   * for (re) starting the job
1017   */
1018  public static boolean isJobDirValid(Path jobDirPath, FileSystem fs)
1019      throws IOException {
1020    FileStatus[] contents = fs.listStatus(jobDirPath);
1021    int matchCount = 0;
1022    if (contents != null && contents.length >= 2) {
1023      for (FileStatus status : contents) {
1024        if ("job.xml".equals(status.getPath().getName())) {
1025          ++matchCount;
1026        }
1027        if ("job.split".equals(status.getPath().getName())) {
1028          ++matchCount;
1029        }
1030      }
1031      if (matchCount == 2) {
1032        return true;
1033      }
1034    }
1035    return false;
1036  }
1037
1038  /**
1039   * Fetch the staging area directory for the application
1040   * 
1041   * @return path to staging area directory
1042   * @throws IOException
1043   */
1044  public Path getStagingAreaDir() throws IOException {
1045    try {
1046      return clientUgi.doAs(new PrivilegedExceptionAction<Path>() {
1047        @Override
1048        public Path run() throws IOException, InterruptedException {
1049          return cluster.getStagingAreaDir();
1050        }
1051      });
1052    } catch (InterruptedException ie) {
1053      // throw RuntimeException instead for compatibility reasons
1054      throw new RuntimeException(ie);
1055    }
1056  }
1057
1058  private JobQueueInfo getJobQueueInfo(QueueInfo queue) {
1059    JobQueueInfo ret = new JobQueueInfo(queue);
1060    // make sure to convert any children
1061    if (queue.getQueueChildren().size() > 0) {
1062      List<JobQueueInfo> childQueues = new ArrayList<JobQueueInfo>(queue
1063          .getQueueChildren().size());
1064      for (QueueInfo child : queue.getQueueChildren()) {
1065        childQueues.add(getJobQueueInfo(child));
1066      }
1067      ret.setChildren(childQueues);
1068    }
1069    return ret;
1070  }
1071
1072  private JobQueueInfo[] getJobQueueInfoArray(QueueInfo[] queues)
1073      throws IOException {
1074    JobQueueInfo[] ret = new JobQueueInfo[queues.length];
1075    for (int i = 0; i < queues.length; i++) {
1076      ret[i] = getJobQueueInfo(queues[i]);
1077    }
1078    return ret;
1079  }
1080
1081  /**
1082   * Returns an array of queue information objects about root level queues
1083   * configured
1084   *
1085   * @return the array of root level JobQueueInfo objects
1086   * @throws IOException
1087   */
1088  public JobQueueInfo[] getRootQueues() throws IOException {
1089    try {
1090      return clientUgi.doAs(new PrivilegedExceptionAction<JobQueueInfo[]>() {
1091        public JobQueueInfo[] run() throws IOException, InterruptedException {
1092          return getJobQueueInfoArray(cluster.getRootQueues());
1093        }
1094      });
1095    } catch (InterruptedException ie) {
1096      throw new IOException(ie);
1097    }
1098  }
1099
1100  /**
1101   * Returns an array of queue information objects about immediate children
1102   * of queue queueName.
1103   * 
1104   * @param queueName
1105   * @return the array of immediate children JobQueueInfo objects
1106   * @throws IOException
1107   */
1108  public JobQueueInfo[] getChildQueues(final String queueName) throws IOException {
1109    try {
1110      return clientUgi.doAs(new PrivilegedExceptionAction<JobQueueInfo[]>() {
1111        public JobQueueInfo[] run() throws IOException, InterruptedException {
1112          return getJobQueueInfoArray(cluster.getChildQueues(queueName));
1113        }
1114      });
1115    } catch (InterruptedException ie) {
1116      throw new IOException(ie);
1117    }
1118  }
1119  
1120  /**
1121   * Return an array of queue information objects about all the Job Queues
1122   * configured.
1123   * 
1124   * @return Array of JobQueueInfo objects
1125   * @throws IOException
1126   */
1127  public JobQueueInfo[] getQueues() throws IOException {
1128    try {
1129      return clientUgi.doAs(new PrivilegedExceptionAction<JobQueueInfo[]>() {
1130        public JobQueueInfo[] run() throws IOException, InterruptedException {
1131          return getJobQueueInfoArray(cluster.getQueues());
1132        }
1133      });
1134    } catch (InterruptedException ie) {
1135      throw new IOException(ie);
1136    }
1137  }
1138  
1139  /**
1140   * Gets all the jobs which were added to particular Job Queue
1141   * 
1142   * @param queueName name of the Job Queue
1143   * @return Array of jobs present in the job queue
1144   * @throws IOException
1145   */
1146  
1147  public JobStatus[] getJobsFromQueue(final String queueName) throws IOException {
1148    try {
1149      QueueInfo queue = clientUgi.doAs(new PrivilegedExceptionAction<QueueInfo>() {
1150        @Override
1151        public QueueInfo run() throws IOException, InterruptedException {
1152          return cluster.getQueue(queueName);
1153        }
1154      });
1155      if (queue == null) {
1156        return null;
1157      }
1158      org.apache.hadoop.mapreduce.JobStatus[] stats = 
1159        queue.getJobStatuses();
1160      JobStatus[] ret = new JobStatus[stats.length];
1161      for (int i = 0 ; i < stats.length; i++ ) {
1162        ret[i] = JobStatus.downgrade(stats[i]);
1163      }
1164      return ret;
1165    } catch (InterruptedException ie) {
1166      throw new IOException(ie);
1167    }
1168  }
1169  
1170  /**
1171   * Gets the queue information associated to a particular Job Queue
1172   * 
1173   * @param queueName name of the job queue.
1174   * @return Queue information associated to particular queue.
1175   * @throws IOException
1176   */
1177  public JobQueueInfo getQueueInfo(final String queueName) throws IOException {
1178    try {
1179      QueueInfo queueInfo = clientUgi.doAs(new 
1180          PrivilegedExceptionAction<QueueInfo>() {
1181        public QueueInfo run() throws IOException, InterruptedException {
1182          return cluster.getQueue(queueName);
1183        }
1184      });
1185      if (queueInfo != null) {
1186        return new JobQueueInfo(queueInfo);
1187      }
1188      return null;
1189    } catch (InterruptedException ie) {
1190      throw new IOException(ie);
1191    }
1192  }
1193  
1194  /**
1195   * Gets the Queue ACLs for current user
1196   * @return array of QueueAclsInfo object for current user.
1197   * @throws IOException
1198   */
1199  public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException {
1200    try {
1201      org.apache.hadoop.mapreduce.QueueAclsInfo[] acls = 
1202        clientUgi.doAs(new 
1203            PrivilegedExceptionAction
1204            <org.apache.hadoop.mapreduce.QueueAclsInfo[]>() {
1205              public org.apache.hadoop.mapreduce.QueueAclsInfo[] run() 
1206              throws IOException, InterruptedException {
1207                return cluster.getQueueAclsForCurrentUser();
1208              }
1209        });
1210      QueueAclsInfo[] ret = new QueueAclsInfo[acls.length];
1211      for (int i = 0 ; i < acls.length; i++ ) {
1212        ret[i] = QueueAclsInfo.downgrade(acls[i]);
1213      }
1214      return ret;
1215    } catch (InterruptedException ie) {
1216      throw new IOException(ie);
1217    }
1218  }
1219
1220  /**
1221   * Get a delegation token for the user from the JobTracker.
1222   * @param renewer the user who can renew the token
1223   * @return the new token
1224   * @throws IOException
1225   */
1226  public Token<DelegationTokenIdentifier> 
1227    getDelegationToken(final Text renewer) throws IOException, InterruptedException {
1228    return clientUgi.doAs(new 
1229        PrivilegedExceptionAction<Token<DelegationTokenIdentifier>>() {
1230      public Token<DelegationTokenIdentifier> run() throws IOException, 
1231      InterruptedException {
1232        return cluster.getDelegationToken(renewer);
1233      }
1234    });
1235  }
1236
1237  /**
1238   * Renew a delegation token
1239   * @param token the token to renew
1240   * @return true if the renewal went well
1241   * @throws InvalidToken
1242   * @throws IOException
1243   * @deprecated Use {@link Token#renew} instead
1244   */
1245  public long renewDelegationToken(Token<DelegationTokenIdentifier> token
1246                                   ) throws InvalidToken, IOException, 
1247                                            InterruptedException {
1248    return token.renew(getConf());
1249  }
1250
1251  /**
1252   * Cancel a delegation token from the JobTracker
1253   * @param token the token to cancel
1254   * @throws IOException
1255   * @deprecated Use {@link Token#cancel} instead
1256   */
1257  public void cancelDelegationToken(Token<DelegationTokenIdentifier> token
1258                                    ) throws InvalidToken, IOException, 
1259                                             InterruptedException {
1260    token.cancel(getConf());
1261  }
1262
1263  /**
1264   */
1265  public static void main(String argv[]) throws Exception {
1266    int res = ToolRunner.run(new JobClient(), argv);
1267    System.exit(res);
1268  }
1269}
1270