View Javadoc

1   /**
2      This file is part of GoldenGate Project (named also GoldenGate or GG).
3   
4      Copyright 2009, Frederic Bregier, and individual contributors by the @author
5      tags. See the COPYRIGHT.txt in the distribution for a full listing of
6      individual contributors.
7   
8      All GoldenGate Project is free software: you can redistribute it and/or 
9      modify it under the terms of the GNU General Public License as published 
10     by the Free Software Foundation, either version 3 of the License, or
11     (at your option) any later version.
12  
13     GoldenGate is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17  
18     You should have received a copy of the GNU General Public License
19     along with GoldenGate .  If not, see <http://www.gnu.org/licenses/>.
20   */
21  package goldengate.commandexec.ssl.client.test;
22  
23  import goldengate.commandexec.client.LocalExecClientHandler;
24  import goldengate.commandexec.ssl.client.LocalExecSslClientPipelineFactory;
25  import goldengate.commandexec.utils.LocalExecResult;
26  import goldengate.common.crypto.ssl.GgSecureKeyStore;
27  import goldengate.common.crypto.ssl.GgSslContextFactory;
28  import goldengate.common.logging.GgSlf4JLoggerFactory;
29  
30  import java.net.InetAddress;
31  import java.net.InetSocketAddress;
32  import java.net.UnknownHostException;
33  import java.util.concurrent.ExecutorService;
34  import java.util.concurrent.Executors;
35  import java.util.concurrent.TimeUnit;
36  
37  import org.jboss.netty.bootstrap.ClientBootstrap;
38  import org.jboss.netty.channel.Channel;
39  import org.jboss.netty.channel.ChannelFuture;
40  import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
41  import org.jboss.netty.logging.InternalLoggerFactory;
42  
43  import ch.qos.logback.classic.Level;
44  
45  /**
46   * LocalExecSsl client.
47   *
48   * This class is an example of client.
49   *
50   * No client authentication On a bi-core Centrino2 vPro: 5/s in 50 sequential, 29/s in 10 threads with 50 sequential<br>
51   * With client authentication On a bi-core Centrino2 vPro: 3/s in 50 sequential, 27/s in 10 threads with 50 sequential
52   *
53   */
54  public class LocalExecSslClient extends Thread {
55  
56      static int nit = 50;
57      static int nth = 10;
58      static String command = "d:\\GG\\testexec.bat";
59      static int port = 9999;
60      static InetSocketAddress address;
61      // with client authentication
62      static String keyStoreFilename = "d:\\GG\\R66\\certs\\testclient2.jks";
63      // without client authentication
64      // static String keyStoreFilename = null;
65      static String keyStorePasswd = "testclient2";
66      static String keyPasswd = "client2";
67      static String keyTrustStoreFilename = "d:\\GG\\R66\\certs\\testclient.jks";
68      static String keyTrustStorePasswd = "testclient";
69      static LocalExecResult result;
70  
71      static int ok = 0;
72      static int ko = 0;
73  
74      static ExecutorService threadPool;
75      static ExecutorService threadPool2;
76      // Configure the client.
77      static ClientBootstrap bootstrap;
78      // Configure the pipeline factory.
79      static LocalExecSslClientPipelineFactory localExecClientPipelineFactory;
80  
81      /**
82       * Test & example main
83       * @param args ignored
84       * @throws Exception
85       */
86      public static void main(String[] args) throws Exception {
87          InternalLoggerFactory.setDefaultFactory(new GgSlf4JLoggerFactory(
88                  Level.WARN));
89          InetAddress addr;
90          byte []loop = {127,0,0,1};
91          try {
92              addr = InetAddress.getByAddress(loop);
93          } catch (UnknownHostException e) {
94              return;
95          }
96          address = new InetSocketAddress(addr, port);
97          threadPool = Executors.newCachedThreadPool();
98          threadPool2 = Executors.newCachedThreadPool();
99          // Configure the client.
100         bootstrap = new ClientBootstrap(
101                 new NioClientSocketChannelFactory(threadPool, threadPool2));
102         // Configure the pipeline factory.
103         // First create the SSL part
104         GgSecureKeyStore ggSecureKeyStore;
105         // For empty KeyStore
106         if (keyStoreFilename == null) {
107             ggSecureKeyStore =
108                 new GgSecureKeyStore(keyStorePasswd, keyPasswd);
109         } else {
110             ggSecureKeyStore =
111                 new GgSecureKeyStore(keyStoreFilename, keyStorePasswd, keyPasswd);
112         }
113 
114         if (keyTrustStoreFilename != null) {
115             // Load the client TrustStore
116             ggSecureKeyStore.initTrustStore(keyTrustStoreFilename, keyTrustStorePasswd, false);
117         } else {
118             ggSecureKeyStore.initEmptyTrustStore();
119         }
120         GgSslContextFactory ggSslContextFactory = new GgSslContextFactory(ggSecureKeyStore, false);
121         localExecClientPipelineFactory =
122                 new LocalExecSslClientPipelineFactory(ggSslContextFactory);
123         bootstrap.setPipelineFactory(localExecClientPipelineFactory);
124         try {
125             // Parse options.
126             LocalExecSslClient client = new LocalExecSslClient();
127             // run once
128             long first = System.currentTimeMillis();
129             client.connect();
130             client.runOnce();
131             client.disconnect();
132             long second = System.currentTimeMillis();
133             // print time for one exec
134             System.err.println("1=Total time in ms: "+(second-first)+" or "+(1*1000/(second-first))+" exec/s");
135             System.err.println("Result: " + ok+":"+ko);
136             ok = 0;
137             ko = 0;
138 
139             // Now run multiple within one thread
140             first = System.currentTimeMillis();
141             for (int i = 0; i < nit; i ++) {
142                 client.connect();
143                 client.runOnce();
144                 client.disconnect();
145             }
146             second = System.currentTimeMillis();
147             // print time for one exec
148             System.err.println(nit+"=Total time in ms: "+(second-first)+" or "+(nit*1000/(second-first))+" exec/s");
149             System.err.println("Result: " + ok+":"+ko);
150             ok = 0;
151             ko = 0;
152 
153             // Now run multiple within multiple threads
154             // Create multiple threads
155             ExecutorService executorService = Executors.newFixedThreadPool(nth);
156             first = System.currentTimeMillis();
157             // Starts all thread with a default number of execution
158             for (int i = 0; i < nth; i ++) {
159                 executorService.submit(new LocalExecSslClient());
160             }
161             Thread.sleep(500);
162             executorService.shutdown();
163             while (! executorService.awaitTermination(200, TimeUnit.MILLISECONDS)) {
164                 Thread.sleep(50);
165             }
166             second = System.currentTimeMillis();
167 
168             // print time for one exec
169             System.err.println((nit*nth)+"=Total time in ms: "+(second-first)+" or "+(nit*nth*1000/(second-first))+" exec/s");
170             System.err.println("Result: " + ok+":"+ko);
171             ok = 0;
172             ko = 0;
173 
174             // run once
175             first = System.currentTimeMillis();
176             client.connect();
177             client.runFinal();
178             client.disconnect();
179             second = System.currentTimeMillis();
180             // print time for one exec
181             System.err.println("1=Total time in ms: "+(second-first)+" or "+(1*1000/(second-first))+" exec/s");
182             System.err.println("Result: " + ok+":"+ko);
183             ok = 0;
184             ko = 0;
185         } finally {
186             // Shut down all thread pools to exit.
187             bootstrap.releaseExternalResources();
188             localExecClientPipelineFactory.releaseResources();
189         }
190     }
191 
192     /**
193      * Simple constructor
194      */
195     public LocalExecSslClient() {
196     }
197 
198     private Channel channel;
199     /**
200      * Run method for thread
201      */
202     public void run() {
203         connect();
204         for (int i = 0; i < nit; i ++) {
205             this.runOnce();
206         }
207         disconnect();
208     }
209 
210     /**
211      * Connect to the Server
212      */
213     private void connect() {
214         // Start the connection attempt.
215         ChannelFuture future = bootstrap.connect(address);
216 
217         // Wait until the connection attempt succeeds or fails.
218         try {
219             channel = future.await().getChannel();
220         } catch (InterruptedException e) {
221         }
222         if (!future.isSuccess()) {
223             System.err.println("Client Not Connected");
224             future.getCause().printStackTrace();
225             return;
226         }
227     }
228     /**
229      * Disconnect from the server
230      */
231     private void disconnect() {
232      // Close the connection. Make sure the close operation ends because
233         // all I/O operations are asynchronous in Netty.
234         try {
235             channel.close().await();
236         } catch (InterruptedException e) {
237         }
238     }
239     /**
240      * Run method both for not threaded execution and threaded execution
241      */
242     private void runOnce() {
243         // Initialize the command context
244         LocalExecClientHandler clientHandler =
245             (LocalExecClientHandler) channel.getPipeline().getLast();
246         clientHandler.initExecClient();
247         // Command to execute
248 
249         ChannelFuture lastWriteFuture = null;
250         String line = command+"\n";
251         if (line != null) {
252             // Sends the received line to the server.
253             lastWriteFuture = channel.write(line);
254             // Wait until all messages are flushed before closing the channel.
255             if (lastWriteFuture != null) {
256                 try {
257                     lastWriteFuture.await();
258                 } catch (InterruptedException e) {
259                 }
260             }
261             // Wait for the end of the exec command
262             LocalExecResult localExecResult = clientHandler.waitFor(10000);
263             int status = localExecResult.status;
264             if (status < 0) {
265                 System.err.println("Status: " + status + "\nResult: " +
266                         localExecResult.result);
267                 ko++;
268             } else {
269                 ok++;
270                 result = localExecResult;
271             }
272         }
273     }
274     /**
275      * Run method for closing Server
276      */
277     private void runFinal() {
278         // Initialize the command context
279         LocalExecClientHandler clientHandler =
280             (LocalExecClientHandler) channel.getPipeline().getLast();
281         clientHandler.initExecClient();
282         // Command to execute
283 
284         ChannelFuture lastWriteFuture = null;
285         String line = "-1000 stop\n";
286         if (line != null) {
287             // Sends the received line to the server.
288             lastWriteFuture = channel.write(line);
289             // Wait until all messages are flushed before closing the channel.
290             if (lastWriteFuture != null) {
291                 try {
292                     lastWriteFuture.await();
293                 } catch (InterruptedException e) {
294                 }
295             }
296             // Wait for the end of the exec command
297             LocalExecResult localExecResult = clientHandler.waitFor(10000);
298             int status = localExecResult.status;
299             if (status < 0) {
300                 System.err.println("Status: " + status + "\nResult: " +
301                         localExecResult.result);
302                 ko++;
303             } else {
304                 ok++;
305                 result = localExecResult;
306             }
307         }
308     }
309 }