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.util;
019
020import java.io.BufferedReader;
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStreamReader;
024import java.io.InputStream;
025import java.util.Arrays;
026import java.util.Map;
027import java.util.Timer;
028import java.util.TimerTask;
029import java.util.concurrent.atomic.AtomicBoolean;
030
031import org.apache.commons.logging.Log;
032import org.apache.commons.logging.LogFactory;
033import org.apache.hadoop.classification.InterfaceAudience;
034import org.apache.hadoop.classification.InterfaceStability;
035
036/** 
037 * A base class for running a Unix command.
038 * 
039 * <code>Shell</code> can be used to run unix commands like <code>du</code> or
040 * <code>df</code>. It also offers facilities to gate commands by 
041 * time-intervals.
042 */
043@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
044@InterfaceStability.Unstable
045abstract public class Shell {
046  
047  public static final Log LOG = LogFactory.getLog(Shell.class);
048  
049  private static boolean IS_JAVA7_OR_ABOVE =
050      System.getProperty("java.version").substring(0, 3).compareTo("1.7") >= 0;
051
052  public static boolean isJava7OrAbove() {
053    return IS_JAVA7_OR_ABOVE;
054  }
055
056  /**
057   * Maximum command line length in Windows
058   * KB830473 documents this as 8191
059   */
060  public static final int WINDOWS_MAX_SHELL_LENGHT = 8191;
061
062  /**
063   * Checks if a given command (String[]) fits in the Windows maximum command line length
064   * Note that the input is expected to already include space delimiters, no extra count
065   * will be added for delimiters.
066   *
067   * @param commands command parts, including any space delimiters
068   */
069  public static void checkWindowsCommandLineLength(String...commands)
070      throws IOException {
071    int len = 0;
072    for (String s: commands) {
073      len += s.length();
074    }
075    if (len > WINDOWS_MAX_SHELL_LENGHT) {
076      throw new IOException(String.format(
077          "The command line has a length of %d exceeds maximum allowed length of %d. " +
078          "Command starts with: %s",
079          len, WINDOWS_MAX_SHELL_LENGHT,
080          StringUtils.join("", commands).substring(0, 100)));
081    }
082  }
083
084  /** a Unix command to get the current user's name */
085  public final static String USER_NAME_COMMAND = "whoami";
086
087  /** Windows CreateProcess synchronization object */
088  public static final Object WindowsProcessLaunchLock = new Object();
089
090  // OSType detection
091
092  public enum OSType {
093    OS_TYPE_LINUX,
094    OS_TYPE_WIN,
095    OS_TYPE_SOLARIS,
096    OS_TYPE_MAC,
097    OS_TYPE_FREEBSD,
098    OS_TYPE_OTHER
099  }
100
101  public static final OSType osType = getOSType();
102
103  static private OSType getOSType() {
104    String osName = System.getProperty("os.name");
105    if (osName.startsWith("Windows")) {
106      return OSType.OS_TYPE_WIN;
107    } else if (osName.contains("SunOS") || osName.contains("Solaris")) {
108      return OSType.OS_TYPE_SOLARIS;
109    } else if (osName.contains("Mac")) {
110      return OSType.OS_TYPE_MAC;
111    } else if (osName.contains("FreeBSD")) {
112      return OSType.OS_TYPE_FREEBSD;
113    } else if (osName.startsWith("Linux")) {
114      return OSType.OS_TYPE_LINUX;
115    } else {
116      // Some other form of Unix
117      return OSType.OS_TYPE_OTHER;
118    }
119  }
120
121  // Helper static vars for each platform
122  public static final boolean WINDOWS = (osType == OSType.OS_TYPE_WIN);
123  public static final boolean SOLARIS = (osType == OSType.OS_TYPE_SOLARIS);
124  public static final boolean MAC     = (osType == OSType.OS_TYPE_MAC);
125  public static final boolean FREEBSD = (osType == OSType.OS_TYPE_FREEBSD);
126  public static final boolean LINUX   = (osType == OSType.OS_TYPE_LINUX);
127  public static final boolean OTHER   = (osType == OSType.OS_TYPE_OTHER);
128
129  public static final boolean PPC_64
130                = System.getProperties().getProperty("os.arch").contains("ppc64");
131
132  /** a Unix command to get the current user's groups list */
133  public static String[] getGroupsCommand() {
134    return (WINDOWS)? new String[]{"cmd", "/c", "groups"}
135                    : new String[]{"bash", "-c", "groups"};
136  }
137
138  /**
139   * a Unix command to get a given user's groups list.
140   * If the OS is not WINDOWS, the command will get the user's primary group
141   * first and finally get the groups list which includes the primary group.
142   * i.e. the user's primary group will be included twice.
143   */
144  public static String[] getGroupsForUserCommand(final String user) {
145    //'groups username' command return is non-consistent across different unixes
146    return (WINDOWS)? new String[] { WINUTILS, "groups", "-F", "\"" + user + "\""}
147                    : new String [] {"bash", "-c", "id -gn " + user
148                                     + "&& id -Gn " + user};
149  }
150
151  /** a Unix command to get a given netgroup's user list */
152  public static String[] getUsersForNetgroupCommand(final String netgroup) {
153    //'groups username' command return is non-consistent across different unixes
154    return (WINDOWS)? new String [] {"cmd", "/c", "getent netgroup " + netgroup}
155                    : new String [] {"bash", "-c", "getent netgroup " + netgroup};
156  }
157
158  /** Return a command to get permission information. */
159  public static String[] getGetPermissionCommand() {
160    return (WINDOWS) ? new String[] { WINUTILS, "ls", "-F" }
161                     : new String[] { "/bin/ls", "-ld" };
162  }
163
164  /** Return a command to set permission */
165  public static String[] getSetPermissionCommand(String perm, boolean recursive) {
166    if (recursive) {
167      return (WINDOWS) ? new String[] { WINUTILS, "chmod", "-R", perm }
168                         : new String[] { "chmod", "-R", perm };
169    } else {
170      return (WINDOWS) ? new String[] { WINUTILS, "chmod", perm }
171                       : new String[] { "chmod", perm };
172    }
173  }
174
175  /**
176   * Return a command to set permission for specific file.
177   * 
178   * @param perm String permission to set
179   * @param recursive boolean true to apply to all sub-directories recursively
180   * @param file String file to set
181   * @return String[] containing command and arguments
182   */
183  public static String[] getSetPermissionCommand(String perm, boolean recursive,
184                                                 String file) {
185    String[] baseCmd = getSetPermissionCommand(perm, recursive);
186    String[] cmdWithFile = Arrays.copyOf(baseCmd, baseCmd.length + 1);
187    cmdWithFile[cmdWithFile.length - 1] = file;
188    return cmdWithFile;
189  }
190
191  /** Return a command to set owner */
192  public static String[] getSetOwnerCommand(String owner) {
193    return (WINDOWS) ? new String[] { WINUTILS, "chown", "\"" + owner + "\"" }
194                     : new String[] { "chown", owner };
195  }
196  
197  /** Return a command to create symbolic links */
198  public static String[] getSymlinkCommand(String target, String link) {
199    return WINDOWS ? new String[] { WINUTILS, "symlink", link, target }
200                   : new String[] { "ln", "-s", target, link };
201  }
202
203  /** Return a command to read the target of the a symbolic link*/
204  public static String[] getReadlinkCommand(String link) {
205    return WINDOWS ? new String[] { WINUTILS, "readlink", link }
206        : new String[] { "readlink", link };
207  }
208
209  /** Return a command for determining if process with specified pid is alive. */
210  public static String[] getCheckProcessIsAliveCommand(String pid) {
211    return Shell.WINDOWS ?
212      new String[] { Shell.WINUTILS, "task", "isAlive", pid } :
213      isSetsidAvailable ?
214        new String[] { "kill", "-0", "--", "-" + pid } :
215        new String[] { "kill", "-0", pid };
216  }
217
218  /** Return a command to send a signal to a given pid */
219  public static String[] getSignalKillCommand(int code, String pid) {
220    return Shell.WINDOWS ?
221      new String[] { Shell.WINUTILS, "task", "kill", pid } :
222      isSetsidAvailable ?
223        new String[] { "kill", "-" + code, "--", "-" + pid } :
224        new String[] { "kill", "-" + code, pid };
225  }
226
227  /** Return a regular expression string that match environment variables */
228  public static String getEnvironmentVariableRegex() {
229    return (WINDOWS) ? "%([A-Za-z_][A-Za-z0-9_]*?)%" :
230      "\\$([A-Za-z_][A-Za-z0-9_]*)";
231  }
232  
233  /**
234   * Returns a File referencing a script with the given basename, inside the
235   * given parent directory.  The file extension is inferred by platform: ".cmd"
236   * on Windows, or ".sh" otherwise.
237   * 
238   * @param parent File parent directory
239   * @param basename String script file basename
240   * @return File referencing the script in the directory
241   */
242  public static File appendScriptExtension(File parent, String basename) {
243    return new File(parent, appendScriptExtension(basename));
244  }
245
246  /**
247   * Returns a script file name with the given basename.  The file extension is
248   * inferred by platform: ".cmd" on Windows, or ".sh" otherwise.
249   * 
250   * @param basename String script file basename
251   * @return String script file name
252   */
253  public static String appendScriptExtension(String basename) {
254    return basename + (WINDOWS ? ".cmd" : ".sh");
255  }
256
257  /**
258   * Returns a command to run the given script.  The script interpreter is
259   * inferred by platform: cmd on Windows or bash otherwise.
260   * 
261   * @param script File script to run
262   * @return String[] command to run the script
263   */
264  public static String[] getRunScriptCommand(File script) {
265    String absolutePath = script.getAbsolutePath();
266    return WINDOWS ? new String[] { "cmd", "/c", absolutePath } :
267      new String[] { "/bin/bash", absolutePath };
268  }
269
270  /** a Unix command to set permission */
271  public static final String SET_PERMISSION_COMMAND = "chmod";
272  /** a Unix command to set owner */
273  public static final String SET_OWNER_COMMAND = "chown";
274
275  /** a Unix command to set the change user's groups list */
276  public static final String SET_GROUP_COMMAND = "chgrp";
277  /** a Unix command to create a link */
278  public static final String LINK_COMMAND = "ln";
279  /** a Unix command to get a link target */
280  public static final String READ_LINK_COMMAND = "readlink";
281
282  /**Time after which the executing script would be timedout*/
283  protected long timeOutInterval = 0L;
284  /** If or not script timed out*/
285  private AtomicBoolean timedOut;
286
287
288  /** Centralized logic to discover and validate the sanity of the Hadoop 
289   *  home directory. Returns either NULL or a directory that exists and 
290   *  was specified via either -Dhadoop.home.dir or the HADOOP_HOME ENV 
291   *  variable.  This does a lot of work so it should only be called 
292   *  privately for initialization once per process.
293   **/
294  private static String checkHadoopHome() {
295
296    // first check the Dflag hadoop.home.dir with JVM scope
297    String home = System.getProperty("hadoop.home.dir");
298
299    // fall back to the system/user-global env variable
300    if (home == null) {
301      home = System.getenv("HADOOP_HOME");
302    }
303
304    try {
305       // couldn't find either setting for hadoop's home directory
306       if (home == null) {
307         throw new IOException("HADOOP_HOME or hadoop.home.dir are not set.");
308       }
309
310       if (home.startsWith("\"") && home.endsWith("\"")) {
311         home = home.substring(1, home.length()-1);
312       }
313
314       // check that the home setting is actually a directory that exists
315       File homedir = new File(home);
316       if (!homedir.isAbsolute() || !homedir.exists() || !homedir.isDirectory()) {
317         throw new IOException("Hadoop home directory " + homedir
318           + " does not exist, is not a directory, or is not an absolute path.");
319       }
320
321       home = homedir.getCanonicalPath();
322
323    } catch (IOException ioe) {
324      if (LOG.isDebugEnabled()) {
325        LOG.debug("Failed to detect a valid hadoop home directory", ioe);
326      }
327      home = null;
328    }
329    
330    return home;
331  }
332  private static String HADOOP_HOME_DIR = checkHadoopHome();
333
334  // Public getter, throws an exception if HADOOP_HOME failed validation
335  // checks and is being referenced downstream.
336  public static final String getHadoopHome() throws IOException {
337    if (HADOOP_HOME_DIR == null) {
338      throw new IOException("Misconfigured HADOOP_HOME cannot be referenced.");
339    }
340
341    return HADOOP_HOME_DIR;
342  }
343
344  /** fully qualify the path to a binary that should be in a known hadoop 
345   *  bin location. This is primarily useful for disambiguating call-outs 
346   *  to executable sub-components of Hadoop to avoid clashes with other 
347   *  executables that may be in the path.  Caveat:  this call doesn't 
348   *  just format the path to the bin directory.  It also checks for file 
349   *  existence of the composed path. The output of this call should be 
350   *  cached by callers.
351   * */
352  public static final String getQualifiedBinPath(String executable) 
353  throws IOException {
354    // construct hadoop bin path to the specified executable
355    String fullExeName = HADOOP_HOME_DIR + File.separator + "bin" 
356      + File.separator + executable;
357
358    File exeFile = new File(fullExeName);
359    if (!exeFile.exists()) {
360      throw new IOException("Could not locate executable " + fullExeName
361        + " in the Hadoop binaries.");
362    }
363
364    return exeFile.getCanonicalPath();
365  }
366
367  /** a Windows utility to emulate Unix commands */
368  public static final String WINUTILS = getWinUtilsPath();
369
370  public static final String getWinUtilsPath() {
371    String winUtilsPath = null;
372
373    try {
374      if (WINDOWS) {
375        winUtilsPath = getQualifiedBinPath("winutils.exe");
376      }
377    } catch (IOException ioe) {
378       LOG.error("Failed to locate the winutils binary in the hadoop binary path",
379         ioe);
380    }
381
382    return winUtilsPath;
383  }
384
385  public static final boolean isSetsidAvailable = isSetsidSupported();
386  private static boolean isSetsidSupported() {
387    if (Shell.WINDOWS) {
388      return false;
389    }
390    ShellCommandExecutor shexec = null;
391    boolean setsidSupported = true;
392    try {
393      String[] args = {"setsid", "bash", "-c", "echo $$"};
394      shexec = new ShellCommandExecutor(args);
395      shexec.execute();
396    } catch (IOException ioe) {
397      LOG.debug("setsid is not available on this machine. So not using it.");
398      setsidSupported = false;
399    } finally { // handle the exit code
400      if (LOG.isDebugEnabled()) {
401        LOG.debug("setsid exited with exit code "
402                 + (shexec != null ? shexec.getExitCode() : "(null executor)"));
403      }
404    }
405    return setsidSupported;
406  }
407
408  /** Token separator regex used to parse Shell tool outputs */
409  public static final String TOKEN_SEPARATOR_REGEX
410                = WINDOWS ? "[|\n\r]" : "[ \t\n\r\f]";
411
412  private long    interval;   // refresh interval in msec
413  private long    lastTime;   // last time the command was performed
414  final private boolean redirectErrorStream; // merge stdout and stderr
415  private Map<String, String> environment; // env for the command execution
416  private File dir;
417  private Process process; // sub process used to execute the command
418  private int exitCode;
419
420  /**If or not script finished executing*/
421  private volatile AtomicBoolean completed;
422  
423  public Shell() {
424    this(0L);
425  }
426  
427  public Shell(long interval) {
428    this(interval, false);
429  }
430
431  /**
432   * @param interval the minimum duration to wait before re-executing the 
433   *        command.
434   */
435  public Shell(long interval, boolean redirectErrorStream) {
436    this.interval = interval;
437    this.lastTime = (interval<0) ? 0 : -interval;
438    this.redirectErrorStream = redirectErrorStream;
439  }
440  
441  /** set the environment for the command 
442   * @param env Mapping of environment variables
443   */
444  protected void setEnvironment(Map<String, String> env) {
445    this.environment = env;
446  }
447
448  /** set the working directory 
449   * @param dir The directory where the command would be executed
450   */
451  protected void setWorkingDirectory(File dir) {
452    this.dir = dir;
453  }
454
455  /** check to see if a command needs to be executed and execute if needed */
456  protected void run() throws IOException {
457    if (lastTime + interval > Time.now())
458      return;
459    exitCode = 0; // reset for next run
460    runCommand();
461  }
462
463  /** Run a command */
464  private void runCommand() throws IOException { 
465    ProcessBuilder builder = new ProcessBuilder(getExecString());
466    Timer timeOutTimer = null;
467    ShellTimeoutTimerTask timeoutTimerTask = null;
468    timedOut = new AtomicBoolean(false);
469    completed = new AtomicBoolean(false);
470    
471    if (environment != null) {
472      builder.environment().putAll(this.environment);
473    }
474    if (dir != null) {
475      builder.directory(this.dir);
476    }
477
478    builder.redirectErrorStream(redirectErrorStream);
479    
480    if (Shell.WINDOWS) {
481      synchronized (WindowsProcessLaunchLock) {
482        // To workaround the race condition issue with child processes
483        // inheriting unintended handles during process launch that can
484        // lead to hangs on reading output and error streams, we
485        // serialize process creation. More info available at:
486        // http://support.microsoft.com/kb/315939
487        process = builder.start();
488      }
489    } else {
490      process = builder.start();
491    }
492
493    if (timeOutInterval > 0) {
494      timeOutTimer = new Timer("Shell command timeout");
495      timeoutTimerTask = new ShellTimeoutTimerTask(
496          this);
497      //One time scheduling.
498      timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
499    }
500    final BufferedReader errReader = 
501            new BufferedReader(new InputStreamReader(process
502                                                     .getErrorStream()));
503    BufferedReader inReader = 
504            new BufferedReader(new InputStreamReader(process
505                                                     .getInputStream()));
506    final StringBuffer errMsg = new StringBuffer();
507    
508    // read error and input streams as this would free up the buffers
509    // free the error stream buffer
510    Thread errThread = new Thread() {
511      @Override
512      public void run() {
513        try {
514          String line = errReader.readLine();
515          while((line != null) && !isInterrupted()) {
516            errMsg.append(line);
517            errMsg.append(System.getProperty("line.separator"));
518            line = errReader.readLine();
519          }
520        } catch(IOException ioe) {
521          LOG.warn("Error reading the error stream", ioe);
522        }
523      }
524    };
525    try {
526      errThread.start();
527    } catch (IllegalStateException ise) { }
528    try {
529      parseExecResult(inReader); // parse the output
530      // clear the input stream buffer
531      String line = inReader.readLine();
532      while(line != null) { 
533        line = inReader.readLine();
534      }
535      // wait for the process to finish and check the exit code
536      exitCode  = process.waitFor();
537      // make sure that the error thread exits
538      joinThread(errThread);
539      completed.set(true);
540      //the timeout thread handling
541      //taken care in finally block
542      if (exitCode != 0) {
543        throw new ExitCodeException(exitCode, errMsg.toString());
544      }
545    } catch (InterruptedException ie) {
546      throw new IOException(ie.toString());
547    } finally {
548      if (timeOutTimer != null) {
549        timeOutTimer.cancel();
550      }
551      // close the input stream
552      try {
553        // JDK 7 tries to automatically drain the input streams for us
554        // when the process exits, but since close is not synchronized,
555        // it creates a race if we close the stream first and the same
556        // fd is recycled.  the stream draining thread will attempt to
557        // drain that fd!!  it may block, OOM, or cause bizarre behavior
558        // see: https://bugs.openjdk.java.net/browse/JDK-8024521
559        //      issue is fixed in build 7u60
560        InputStream stdout = process.getInputStream();
561        synchronized (stdout) {
562          inReader.close();
563        }
564      } catch (IOException ioe) {
565        LOG.warn("Error while closing the input stream", ioe);
566      }
567      if (!completed.get()) {
568        errThread.interrupt();
569        joinThread(errThread);
570      }
571      try {
572        InputStream stderr = process.getErrorStream();
573        synchronized (stderr) {
574          errReader.close();
575        }
576      } catch (IOException ioe) {
577        LOG.warn("Error while closing the error stream", ioe);
578      }
579      process.destroy();
580      lastTime = Time.now();
581    }
582  }
583
584  private static void joinThread(Thread t) {
585    while (t.isAlive()) {
586      try {
587        t.join();
588      } catch (InterruptedException ie) {
589        if (LOG.isWarnEnabled()) {
590          LOG.warn("Interrupted while joining on: " + t, ie);
591        }
592        t.interrupt(); // propagate interrupt
593      }
594    }
595  }
596
597  /** return an array containing the command name & its parameters */ 
598  protected abstract String[] getExecString();
599  
600  /** Parse the execution result */
601  protected abstract void parseExecResult(BufferedReader lines)
602  throws IOException;
603
604  /** 
605   * Get the environment variable
606   */
607  public String getEnvironment(String env) {
608    return environment.get(env);
609  }
610  
611  /** get the current sub-process executing the given command 
612   * @return process executing the command
613   */
614  public Process getProcess() {
615    return process;
616  }
617
618  /** get the exit code 
619   * @return the exit code of the process
620   */
621  public int getExitCode() {
622    return exitCode;
623  }
624
625  /**
626   * This is an IOException with exit code added.
627   */
628  public static class ExitCodeException extends IOException {
629    private final int exitCode;
630    
631    public ExitCodeException(int exitCode, String message) {
632      super(message);
633      this.exitCode = exitCode;
634    }
635    
636    public int getExitCode() {
637      return exitCode;
638    }
639
640    @Override
641    public String toString() {
642      final StringBuilder sb =
643          new StringBuilder("ExitCodeException ");
644      sb.append("exitCode=").append(exitCode)
645        .append(": ");
646      sb.append(super.getMessage());
647      return sb.toString();
648    }
649  }
650  
651  public interface CommandExecutor {
652
653    void execute() throws IOException;
654
655    int getExitCode() throws IOException;
656
657    String getOutput() throws IOException;
658
659    void close();
660    
661  }
662  
663  /**
664   * A simple shell command executor.
665   * 
666   * <code>ShellCommandExecutor</code>should be used in cases where the output 
667   * of the command needs no explicit parsing and where the command, working 
668   * directory and the environment remains unchanged. The output of the command 
669   * is stored as-is and is expected to be small.
670   */
671  public static class ShellCommandExecutor extends Shell 
672      implements CommandExecutor {
673    
674    private String[] command;
675    private StringBuffer output;
676    
677    
678    public ShellCommandExecutor(String[] execString) {
679      this(execString, null);
680    }
681    
682    public ShellCommandExecutor(String[] execString, File dir) {
683      this(execString, dir, null);
684    }
685   
686    public ShellCommandExecutor(String[] execString, File dir, 
687                                 Map<String, String> env) {
688      this(execString, dir, env , 0L);
689    }
690
691    /**
692     * Create a new instance of the ShellCommandExecutor to execute a command.
693     * 
694     * @param execString The command to execute with arguments
695     * @param dir If not-null, specifies the directory which should be set
696     *            as the current working directory for the command.
697     *            If null, the current working directory is not modified.
698     * @param env If not-null, environment of the command will include the
699     *            key-value pairs specified in the map. If null, the current
700     *            environment is not modified.
701     * @param timeout Specifies the time in milliseconds, after which the
702     *                command will be killed and the status marked as timedout.
703     *                If 0, the command will not be timed out. 
704     */
705    public ShellCommandExecutor(String[] execString, File dir, 
706        Map<String, String> env, long timeout) {
707      command = execString.clone();
708      if (dir != null) {
709        setWorkingDirectory(dir);
710      }
711      if (env != null) {
712        setEnvironment(env);
713      }
714      timeOutInterval = timeout;
715    }
716        
717
718    /** Execute the shell command. */
719    public void execute() throws IOException {
720      this.run();    
721    }
722
723    @Override
724    public String[] getExecString() {
725      return command;
726    }
727
728    @Override
729    protected void parseExecResult(BufferedReader lines) throws IOException {
730      output = new StringBuffer();
731      char[] buf = new char[512];
732      int nRead;
733      while ( (nRead = lines.read(buf, 0, buf.length)) > 0 ) {
734        output.append(buf, 0, nRead);
735      }
736    }
737    
738    /** Get the output of the shell command.*/
739    public String getOutput() {
740      return (output == null) ? "" : output.toString();
741    }
742
743    /**
744     * Returns the commands of this instance.
745     * Arguments with spaces in are presented with quotes round; other
746     * arguments are presented raw
747     *
748     * @return a string representation of the object.
749     */
750    @Override
751    public String toString() {
752      StringBuilder builder = new StringBuilder();
753      String[] args = getExecString();
754      for (String s : args) {
755        if (s.indexOf(' ') >= 0) {
756          builder.append('"').append(s).append('"');
757        } else {
758          builder.append(s);
759        }
760        builder.append(' ');
761      }
762      return builder.toString();
763    }
764
765    @Override
766    public void close() {
767    }
768  }
769  
770  /**
771   * To check if the passed script to shell command executor timed out or
772   * not.
773   * 
774   * @return if the script timed out.
775   */
776  public boolean isTimedOut() {
777    return timedOut.get();
778  }
779  
780  /**
781   * Set if the command has timed out.
782   * 
783   */
784  private void setTimedOut() {
785    this.timedOut.set(true);
786  }
787  
788  /** 
789   * Static method to execute a shell command. 
790   * Covers most of the simple cases without requiring the user to implement  
791   * the <code>Shell</code> interface.
792   * @param cmd shell command to execute.
793   * @return the output of the executed command.
794   */
795  public static String execCommand(String ... cmd) throws IOException {
796    return execCommand(null, cmd, 0L);
797  }
798  
799  /** 
800   * Static method to execute a shell command. 
801   * Covers most of the simple cases without requiring the user to implement  
802   * the <code>Shell</code> interface.
803   * @param env the map of environment key=value
804   * @param cmd shell command to execute.
805   * @param timeout time in milliseconds after which script should be marked timeout
806   * @return the output of the executed command.o
807   */
808  
809  public static String execCommand(Map<String, String> env, String[] cmd,
810      long timeout) throws IOException {
811    ShellCommandExecutor exec = new ShellCommandExecutor(cmd, null, env, 
812                                                          timeout);
813    exec.execute();
814    return exec.getOutput();
815  }
816
817  /** 
818   * Static method to execute a shell command. 
819   * Covers most of the simple cases without requiring the user to implement  
820   * the <code>Shell</code> interface.
821   * @param env the map of environment key=value
822   * @param cmd shell command to execute.
823   * @return the output of the executed command.
824   */
825  public static String execCommand(Map<String,String> env, String ... cmd) 
826  throws IOException {
827    return execCommand(env, cmd, 0L);
828  }
829  
830  /**
831   * Timer which is used to timeout scripts spawned off by shell.
832   */
833  private static class ShellTimeoutTimerTask extends TimerTask {
834
835    private Shell shell;
836
837    public ShellTimeoutTimerTask(Shell shell) {
838      this.shell = shell;
839    }
840
841    @Override
842    public void run() {
843      Process p = shell.getProcess();
844      try {
845        p.exitValue();
846      } catch (Exception e) {
847        //Process has not terminated.
848        //So check if it has completed 
849        //if not just destroy it.
850        if (p != null && !shell.completed.get()) {
851          shell.setTimedOut();
852          p.destroy();
853        }
854      }
855    }
856  }
857}