package org.sonar.process.monitor;
import org.slf4j.LoggerFactory;
-import org.sonar.process.ProcessUtils;
/**
* This thread blocks as long as the monitored process is physically alive.
*/
class WatcherThread extends Thread {
- private final ProcessRef process;
+ private final ProcessRef processRef;
private final Monitor monitor;
WatcherThread(ProcessRef processRef, Monitor monitor) {
// and thread group
// -> do not override toString()
super(String.format("Watch[%s]", processRef.getKey()));
- this.process = processRef;
+ this.processRef = processRef;
this.monitor = monitor;
}
boolean alive = true;
while (alive) {
try {
- process.getProcess().waitFor();
- process.setTerminated(true);
- LoggerFactory.getLogger(getClass()).info(process + " is down");
+ processRef.getProcess().waitFor();
+ processRef.setTerminated(true);
+ alive = false;
+ LoggerFactory.getLogger(getClass()).info(String.format("%s is down", processRef));
+
// terminate all other processes, but in another thread
monitor.stop();
- alive = false;
} catch (InterruptedException ignored) {
- if (ProcessUtils.isAlive(process.getProcess())) {
- LoggerFactory.getLogger(getClass()).error(String.format(
- "Watcher of [%s] was interrupted but process is still alive. Killing it.", process.getKey()));
- }
- alive = false;
- } finally {
- process.hardKill();
+ // continue to watch process
}
}
}
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
public class WatcherThreadTest {
@Test(timeout = 10000L)
- public void kill_process_if_watcher_is_interrupted() throws Exception {
- ProcessRef ref = mock(ProcessRef.class, Mockito.RETURNS_DEEP_STUBS);
- when(ref.getProcess().waitFor()).thenAnswer(new Answer<Object>() {
- @Override
- public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
- throw new InterruptedException();
- }
- });
+ public void continue_even_if_interrupted() throws Exception {
Monitor monitor = mock(Monitor.class);
-
+ ProcessRef ref = mock(ProcessRef.class, Mockito.RETURNS_DEEP_STUBS);
+ when(ref.getProcess().waitFor()).thenThrow(new InterruptedException()).thenReturn(0);
WatcherThread watcher = new WatcherThread(ref, monitor);
watcher.start();
- verify(ref).hardKill();
+ watcher.join();
+ verify(monitor).stop();
}
}