001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc.simulator.crasher;
005:
006: import org.apache.commons.io.FileUtils;
007:
008: import com.tc.process.StreamCopier;
009:
010: import java.io.File;
011: import java.io.FileOutputStream;
012: import java.io.IOException;
013: import java.io.PrintStream;
014: import java.text.DateFormat;
015: import java.util.ArrayList;
016: import java.util.Date;
017: import java.util.List;
018:
019: public class ProcessContainer {
020:
021: private static int STOPPED = 1;
022: private static int RUNNING = 3;
023:
024: private final ProcessContainerConfig config;
025: private final List command = new ArrayList();
026: private final PrintStream out;
027: private final DateFormat dateFormat;
028:
029: private int state = STOPPED;
030: private Process process;
031: private Thread outcopy;
032: private Thread errcopy;
033:
034: public ProcessContainer(ProcessContainerConfig config)
035: throws IOException {
036: this .config = config;
037: this .dateFormat = config.getDateFormat();
038: createCommand();
039: System.out.println("command: " + command);
040: File outfile = new File(config.getOutputDirectory(), config
041: .getOutputPrefix()
042: + "." + config.getID() + ".out");
043: FileUtils.forceMkdir(outfile.getParentFile());
044: FileUtils.touch(outfile);
045: out = new PrintStream(new FileOutputStream(outfile));
046: }
047:
048: public synchronized boolean isStopped() {
049: return state == STOPPED;
050: }
051:
052: public synchronized void start() throws IOException {
053: if (state != STOPPED)
054: return;
055: println("starting process...");
056: this .process = Runtime.getRuntime().exec(
057: (String[]) command.toArray(new String[command.size()]));
058: this .outcopy = new Thread(new StreamCopier(this .process
059: .getInputStream(), out));
060: this .errcopy = new Thread(new StreamCopier(this .process
061: .getErrorStream(), out));
062: this .outcopy.start();
063: this .errcopy.start();
064: state = RUNNING;
065: }
066:
067: public synchronized void stop() {
068: if (state != RUNNING)
069: return;
070: println("stopping process...");
071: this .process.destroy();
072: synchronized (outcopy) {
073: outcopy.interrupt();
074: }
075: synchronized (errcopy) {
076: errcopy.interrupt();
077: }
078: state = STOPPED;
079: }
080:
081: private void println(Object o) {
082: out.println(prefix() + ":" + o);
083: }
084:
085: private String prefix() {
086: return dateFormat.format(new Date()) + ": "
087: + Thread.currentThread() + ": " + config.getID();
088: }
089:
090: private void createCommand() {
091: command.add(getJavaCommand());
092: command.addAll(config.getServerArgs());
093: command.add(config.getClassname());
094: command.addAll(config.getMainClassArgs());
095: }
096:
097: private String getJavaCommand() {
098: return "java";
099: }
100: }
|