1 package hudson.remoting; 2 3 import junit.framework.Assert; 4 5 import java.io.IOException ; 6 import java.io.PipedInputStream ; 7 import java.io.PipedOutputStream ; 8 import java.util.concurrent.ExecutorService ; 9 import java.util.concurrent.Executors ; 10 11 16 interface ChannelRunner { 17 Channel start() throws Exception ; 18 void stop(Channel channel) throws Exception ; 19 String getName(); 20 21 Class <? extends ChannelRunner>[] LIST = new Class [] { 22 InProcess.class, 23 Fork.class 24 }; 25 26 27 30 static class InProcess implements ChannelRunner { 31 private ExecutorService executor; 32 35 private Exception failure; 36 37 public Channel start() throws Exception { 38 final PipedInputStream in1 = new PipedInputStream (); 39 final PipedOutputStream out1 = new PipedOutputStream (in1); 40 41 final PipedInputStream in2 = new PipedInputStream (); 42 final PipedOutputStream out2 = new PipedOutputStream (in2); 43 44 executor = Executors.newCachedThreadPool(); 45 46 Thread t = new Thread ("south bridge runner") { 47 public void run() { 48 try { 49 Channel s = new Channel("south", executor, in2, out1); 50 s.join(); 51 System.out.println("south completed"); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 failure = e; 55 } catch (InterruptedException e) { 56 e.printStackTrace(); 57 failure = e; 58 } 59 } 60 }; 61 t.start(); 62 63 return new Channel("north", executor, in1, out2); 64 } 65 66 public void stop(Channel channel) throws Exception { 67 channel.close(); 68 69 System.out.println("north completed"); 70 71 executor.shutdown(); 72 73 if(failure!=null) 74 throw failure; } 76 77 public String getName() { 78 return "local"; 79 } 80 } 81 82 85 static class Fork implements ChannelRunner { 86 private Process proc; 87 private ExecutorService executor; 88 private Copier copier; 89 90 public Channel start() throws Exception { 91 System.out.println("forking a new process"); 92 proc = Runtime.getRuntime().exec("java hudson.remoting.Launcher"); 94 95 copier = new Copier("copier",proc.getErrorStream(),System.err); 96 copier.start(); 97 98 executor = Executors.newCachedThreadPool(); 99 return new Channel("north", executor, proc.getInputStream(), proc.getOutputStream()); 100 } 101 102 public void stop(Channel channel) throws Exception { 103 channel.close(); 104 105 System.out.println("north completed"); 106 107 executor.shutdown(); 108 109 copier.join(); 110 int r = proc.waitFor(); 111 System.out.println("south completed"); 112 113 Assert.assertEquals("exit code should have been 0",0,r); 114 } 115 116 public String getName() { 117 return "fork"; 118 } 119 } 120 } 121 | Popular Tags |