AbstractShell.java 9.1 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Q
qiaozhanwei 已提交
17
package org.apache.dolphinscheduler.common.shell;
L
ligang 已提交
18 19 20 21 22 23 24 25 26 27 28 29

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

30 31 32
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

L
ligang 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

/** 
 * A base class for running a Unix command.
 * 
 * <code>AbstractShell</code> can be used to run unix commands like <code>du</code> or
 * <code>df</code>. It also offers facilities to gate commands by 
 * time-intervals.
 */
public abstract class AbstractShell {
  
  private static final Logger logger = LoggerFactory.getLogger(AbstractShell.class);
  


  /**
   * Time after which the executing script would be timedout
   */
  protected long timeOutInterval = 0L;
  /**
   * If or not script timed out
   */
  private AtomicBoolean timedOut;

  /**
   * refresh interval in msec
    */
  private long interval;

  /**
   * last time the command was performed
   */
  private long lastTime;

  /**
   * env for the command execution
   */
  private Map<String, String> environment;
  private File dir;

  /**
   * sub process used to execute the command
   */
  private Process process;
  private int exitCode;

  /**
   * If or not script finished executing
   */
  private volatile AtomicBoolean completed;
  
  public AbstractShell() {
    this(0L);
  }
  
  /**
   * @param interval the minimum duration to wait before re-executing the 
   *        command.
   */
  public AbstractShell(long interval ) {
    this.interval = interval;
    this.lastTime = (interval<0) ? 0 : -interval;
  }


  
  /**
   * set the environment for the command
   * @param env Mapping of environment variables
   */
  protected void setEnvironment(Map<String, String> env) {
    this.environment = env;
  }

  /**
   * set the working directory
   * @param dir The directory where the command would be executed
   */
  protected void setWorkingDirectory(File dir) {
    this.dir = dir;
  }

  /**
   * check to see if a command needs to be executed and execute if needed
D
dailidong 已提交
116
   * @throws IOException errors
L
ligang 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130
   */
  protected void run() throws IOException {
    if (lastTime + interval > System.currentTimeMillis()) {
      return;
    }
    // reset for next run
    exitCode = 0;
    runCommand();
  }

  
  /**
   * Run a command   actual work
   */
131
  private void runCommand() throws IOException {
L
ligang 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);
    
    if (environment != null) {
      builder.environment().putAll(this.environment);
    }
    if (dir != null) {
      builder.directory(this.dir);
    }
    
    process = builder.start();
    ProcessContainer.putProcess(process);

    if (timeOutInterval > 0) {
      timeOutTimer = new Timer();
      timeoutTimerTask = new ShellTimeoutTimerTask(
          this);
      //One time scheduling.
      timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = 
156 157 158 159 160
            new BufferedReader(
                    new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader =
            new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
161
    final StringBuilder errMsg = new StringBuilder();
L
ligang 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    
    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
      @Override
      public void run() {
        try {
          String line = errReader.readLine();
          while((line != null) && !isInterrupted()) {
            errMsg.append(line);
            errMsg.append(System.getProperty("line.separator"));
            line = errReader.readLine();
          }
        } catch(IOException ioe) {
          logger.warn("Error reading the error stream", ioe);
        }
      }
    };
180 181 182 183 184 185 186 187 188 189 190
    Thread inThread = new Thread() {
      @Override
      public void run() {
        try {
          parseExecResult(inReader);
        } catch (IOException ioe) {
          logger.warn("Error reading the in stream", ioe);
        }
        super.run();
      }
    };
L
ligang 已提交
191 192
    try {
      errThread.start();
193
      inThread.start();
L
ligang 已提交
194 195 196
    } catch (IllegalStateException ise) { }
    try {
      // parse the output
197
      exitCode = process.waitFor();
L
ligang 已提交
198
      try {
199
        // make sure that the error and in thread exits
L
ligang 已提交
200
        errThread.join();
201
        inThread.join();
L
ligang 已提交
202
      } catch (InterruptedException ie) {
203
        logger.warn("Interrupted while reading the error and in stream", ie);
L
ligang 已提交
204 205 206 207
      }
      completed.set(true);
      //the timeout thread handling
      //taken care in finally block
208
      if (exitCode != 0 || errMsg.length() > 0) {
L
ligang 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        throw new ExitCodeException(exitCode, errMsg.toString());
      }
    } catch (InterruptedException ie) {
      throw new IOException(ie.toString());
    } finally {
      if ((timeOutTimer!=null) && !timedOut.get()) {
        timeOutTimer.cancel();
      }
      // close the input stream
      try {
        inReader.close();
      } catch (IOException ioe) {
        logger.warn("Error while closing the input stream", ioe);
      }
      if (!completed.get()) {
        errThread.interrupt();
      }
      try {
        errReader.close();
      } catch (IOException ioe) {
        logger.warn("Error while closing the error stream", ioe);
      }
      ProcessContainer.removeProcess(process);
      process.destroy();
      lastTime = System.currentTimeMillis();
    }
  }

  /**
D
dailidong 已提交
238 239 240
   *
   * @return an array containing the command name and its parameters
   */
L
ligang 已提交
241 242 243 244
  protected abstract String[] getExecString();
  
  /**
   * Parse the execution result
D
dailidong 已提交
245 246 247
   * @param lines lines
   * @throws IOException errors
   */
L
ligang 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  protected abstract void parseExecResult(BufferedReader lines)
  throws IOException;

  /**
   * get the current sub-process executing the given command
   * @return process executing the command
   */
  public Process getProcess() {
    return process;
  }

  /** get the exit code 
   * @return the exit code of the process
   */
  public int getExitCode() {
    return exitCode;
  }

  /**
   * Set if the command has timed out.
   * 
   */
  private void setTimedOut() {
    this.timedOut.set(true);
  }
  


  /**
   * Timer which is used to timeout scripts spawned off by shell.
   */
  private static class ShellTimeoutTimerTask extends TimerTask {

    private AbstractShell shell;

    public ShellTimeoutTimerTask(AbstractShell shell) {
      this.shell = shell;
    }

    @Override
    public void run() {
      Process p = shell.getProcess();
      try {
        p.exitValue();
      } catch (Exception e) {
        //Process has not terminated.
        //So check if it has completed 
        //if not just destroy it.
        if (p != null && !shell.completed.get()) {
          shell.setTimedOut();
          p.destroy();
        }
      }
    }
  }
  
  /**
   * This is an IOException with exit code added.
   */
  public static class ExitCodeException extends IOException {
    int exitCode;
    
    public ExitCodeException(int exitCode, String message) {
      super(message);
      this.exitCode = exitCode;
    }
    
    public int getExitCode() {
      return exitCode;
    }
  }
  
  /**
   * process manage container
   *
   */
  public static class ProcessContainer extends ConcurrentHashMap<Integer, Process>{
	  private static final ProcessContainer container = new ProcessContainer();
	  private ProcessContainer(){
		  super();
	  }
	  public static final ProcessContainer getInstance(){
		return container;
	  }
	  
	  public static void putProcess(Process process){
		  getInstance().put(process.hashCode(), process);
	  }
	  public static int processSize(){
		  return getInstance().size();
	  }
	  
	  public static void removeProcess(Process process){
		  getInstance().remove(process.hashCode());
	  }
	  
	  public static void destroyAllProcess(){
		  Set<Entry<Integer, Process>> set = getInstance().entrySet();
		  for (Entry<Integer, Process> entry : set) {
			try{  
			  entry.getValue().destroy();
		  	} catch (Exception e) {
350
		  		logger.error("Destroy All Processes error", e);
L
ligang 已提交
351 352 353 354 355 356 357
		  	}
		  }
		  
		  logger.info("close " + set.size() + " executing process tasks");
	  }
  }	  
}