KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fr > dyade > aaa > agent > SCAdminHelper


1 /*
2  * Copyright (C) 2001 - 2003 ScalAgent Distributed Technologies
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17  * USA.
18  *
19  */

20 package fr.dyade.aaa.agent;
21
22 import java.io.*;
23 import java.net.*;
24 import java.util.*;
25
26 import org.objectweb.util.monolog.api.BasicLevel;
27 import org.objectweb.util.monolog.api.Logger;
28
29 import fr.dyade.aaa.agent.*;
30
31 public class SCAdminHelper {
32   /** Hashtable that contain all <code>Process</code> of running AgentServer */
33   protected Hashtable ASP = null;
34
35   protected Logger logmon = null;
36
37   public SCAdminHelper() {
38     // Get the logging monitor from current server MonologMonitorFactory
39
logmon = Debug.getLogger("fr.dyade.aaa.agent.SCAdmin");
40
41     ASP = new Hashtable();
42   }
43
44   /**
45    * Starts an agent server from its id.
46    *
47    * @param sid id of agent server to start
48    */

49   public String JavaDoc startAgentServer(short sid) throws Exception JavaDoc {
50     return startAgentServer(sid, null, null);
51   }
52
53   /**
54    * Starts an agent server from its id.
55    *
56    * @param sid id of agent server to start
57    * @param jvmarg arguments to pass to the created java program
58    */

59   public String JavaDoc startAgentServer(short sid,
60                                  String JavaDoc[] jvmarg) throws Exception JavaDoc {
61     return startAgentServer(sid, null, jvmarg, null);
62   }
63
64   /**
65    * Starts an agent server from its id.
66    *
67    * @param sid id of agent server to start
68    * @param dir new working directory for the created agent server,
69    * current working directory if <code>null</code>
70    * @param jvmarg arguments to pass to the created java program
71    */

72   public String JavaDoc startAgentServer(short sid,
73                                  File dir,
74                                  String JavaDoc[] jvmarg) throws Exception JavaDoc {
75     return startAgentServer(sid, dir, jvmarg,
76                             "fr.dyade.aaa.agent.AgentServer", null);
77   }
78
79   public String JavaDoc startAgentServer(short sid,
80                                  File dir,
81                                  String JavaDoc[] jvmarg,
82                  String JavaDoc[] servarg) throws Exception JavaDoc {
83     return startAgentServer(sid, dir, jvmarg,
84                             "fr.dyade.aaa.agent.AgentServer", servarg);
85   }
86
87   /**
88    * Starts an agent server from its id.
89    *
90    * @param sid id of agent server to start
91    * @param dir new working directory for the created agent server,
92    * current working directory if <code>null</code>
93    * @param jvmarg arguments to pass to the created java program
94    * @param className the name of the main class
95    * @param servarg additional arguments to pass to the created java program
96    */

97   public String JavaDoc startAgentServer(short sid,
98                                  File dir,
99                                  String JavaDoc[] jvmarg,
100                                  String JavaDoc className,
101                  String JavaDoc[] servarg) throws Exception JavaDoc {
102     logmon.log(BasicLevel.DEBUG,
103                "SCAdmin: start AgentServer#" + sid);
104
105     Process JavaDoc p = (Process JavaDoc) ASP.get(new Short JavaDoc(sid));
106     if (p != null) {
107       try {
108     logmon.log(BasicLevel.DEBUG,
109             "SCAdmin: AgentServer#" + sid + " -> " + p.exitValue());
110       } catch (IllegalThreadStateException JavaDoc exc) {
111         // there is already another AS#sid running
112
logmon.log(BasicLevel.WARN,
113             "SCAdmin: AgentServer#" + sid + " already running.");
114         throw new IllegalStateException JavaDoc("AgentServer#" + sid +
115                                         " already running.");
116       }
117     }
118
119     String JavaDoc javapath =
120       new File(new File(System.getProperty("java.home"), "bin"),
121                "java").getPath();
122     String JavaDoc classpath = System.getProperty("java.class.path");
123
124     Vector argv = new Vector();
125     argv.addElement(javapath);
126     argv.addElement("-classpath");
127     argv.addElement(classpath);
128     if (jvmarg != null) {
129       for (int i=0; i<jvmarg.length; i++)
130         argv.addElement(jvmarg[i]);
131     }
132     argv.addElement(className);
133     argv.addElement(Short.toString(sid));
134     argv.addElement("s" + sid);
135     if (servarg != null) {
136       for (int i=0; i<servarg.length; i++)
137         argv.addElement(servarg[i]);
138     }
139
140     String JavaDoc[] command = new String JavaDoc[argv.size()];
141     argv.copyInto(command);
142
143     logmon.log(BasicLevel.DEBUG,
144                "SCAdmin" + ": starts AgentServer#" + sid);
145     if (dir == null) {
146       p = Runtime.getRuntime().exec(command);
147     } else {
148       p = Runtime.getRuntime().exec(command, null, dir);
149     }
150     ASP.put(new Short JavaDoc(sid), p);
151     BufferedReader br =
152       new BufferedReader(new InputStreamReader(p.getInputStream()));
153     String JavaDoc line = br.readLine();
154     if (line != null) {
155       if (line.endsWith(AgentServer.ERRORSTRING)) {
156         StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
157         strBuf.append(line);
158         while (((line = br.readLine()) != null) &&
159                (! line.equals(AgentServer.ENDSTRING))) {
160           strBuf.append('\n');
161           strBuf.append(line);
162         }
163         line = strBuf.toString();
164       }
165     }
166     // Close all streams of subprocess in order to avoid deadlock due
167
// to limited buffer size.
168
try {
169       p.getInputStream().close();
170     } catch (Exception JavaDoc exc) {}
171     try {
172       p.getOutputStream().close();
173     } catch (Exception JavaDoc exc) {}
174     try {
175       p.getErrorStream().close();
176     } catch (Exception JavaDoc exc) {}
177     return line;
178   }
179
180   /**
181    * Kills this agent server process.
182    *
183    * @param sid id of agent server to stop
184    */

185   public void killAgentServer(short sid) throws Exception JavaDoc {
186     Process JavaDoc p = (Process JavaDoc) ASP.get(new Short JavaDoc(sid));
187
188     logmon.log(BasicLevel.DEBUG,
189                 "SCAdmin: kill AgentServer#" + sid + " [" + p + ']');
190
191     if (p != null) p.destroy();
192   }
193
194   /**
195    * Causes the current thread to wait, if necessary, until the process
196    * running this agent server has terminated.
197    *
198    * @param sid id of agent server to stop
199    * @return the exit value of the agent server.
200    * @exception UnknownServerException if the agent server is unknown.
201    */

202   public int joinAgentServer(short sid) throws Exception JavaDoc {
203     Process JavaDoc p = (Process JavaDoc) ASP.get(new Short JavaDoc(sid));
204
205     logmon.log(BasicLevel.DEBUG,
206                 "SCAdmin: join AgentServer#" + sid + " [" + p + ']');
207
208     // TODO: put it in previous method and set a Timer.
209
if (p != null) {
210       return p.waitFor();
211     } else {
212       throw new UnknownServerException();
213     }
214   }
215
216   /**
217    * Ask for the exit value of an agent server.
218    *
219    * @param sid id of agent server to stop
220    * @return the exit value of the agent server.
221    * @exception IllegalThreadStateException
222    * if the agent server is still running.
223    * @exception UnknownServerException
224    * if the agent server is unknown.
225    */

226   public int exitValue(short sid)
227     throws IllegalThreadStateException JavaDoc, UnknownServerException {
228     Process JavaDoc p = (Process JavaDoc)ASP.get(new Short JavaDoc(sid));
229     if (p != null) {
230       int res = p.exitValue();
231       return res;
232     } else {
233       throw new UnknownServerException();
234     }
235   }
236
237   /**
238    * Kill an agent server and remove it from the ASP table.
239    *
240    * @param sid id of agent server to stop
241    */

242   public void destroyAgentServer(short sid) throws Exception JavaDoc {
243     Short JavaDoc key = new Short JavaDoc(sid);
244     Process JavaDoc p = (Process JavaDoc)ASP.get(key);
245     if (p != null) {
246       ASP.remove(key);
247       p.destroy();
248     }
249   }
250
251   /**
252    * Stops cleanly an agent server from its id.
253    *
254    * @param sid id of agent server to stop
255    * @param port port of the corresponding AdminProxy.
256    */

257   public void stopAgentServer(short sid, int port) throws Exception JavaDoc {
258     stopAgentServer(sid, "localhost", port);
259   }
260
261   /**
262    * Stops cleanly an agent server from its id.
263    *
264    * @param sid id of agent server to stop
265    * @param host hostname of the agent server.
266    * @param port port of the corresponding AdminProxy.
267    */

268   public void stopAgentServer(short sid, String JavaDoc host, int port) throws Exception JavaDoc {
269     Socket socket = null;
270
271     logmon.log(BasicLevel.DEBUG, "SCAdmin: stop AgentServer#" + sid);
272
273     try {
274       socket = new Socket(host, port);
275       socket.getOutputStream().write(AdminProxy.STOP_SERVER.getBytes());
276       socket.getOutputStream().write('\n');
277       socket.getOutputStream().flush();
278       try {
279         socket.getInputStream().read();
280       } catch (SocketException exc) {
281         // Nothing to do: connection reset by peer:
282
}
283     } catch (Throwable JavaDoc exc) {
284       if (logmon.isLoggable(BasicLevel.DEBUG))
285         logmon.log(BasicLevel.DEBUG,
286                     "SCAdmin: Can't stop server#" + sid, exc);
287       throw new Exception JavaDoc("Can't stop server#" + sid +
288                           ": " + exc.getMessage());
289     } finally {
290       close(socket);
291       socket = null;
292     }
293   }
294
295   /**
296    * Stops violently an agent server from its id.
297    *
298    * @param sid id of agent server to stop
299    * @param port port of the corresponding AdminProxy.
300    */

301   public void crashAgentServer(short sid, int port) throws Exception JavaDoc {
302     crashAgentServer(sid, "localhost", port);
303   }
304
305   /**
306    * Stops violently an agent server from its id.
307    *
308    * @param sid id of agent server to stop
309    * @param host hostname of the agent server.
310    * @param port port of the corresponding AdminProxy.
311    */

312   public void crashAgentServer(short sid, String JavaDoc host, int port) throws Exception JavaDoc {
313     Socket socket = null;
314
315     logmon.log(BasicLevel.DEBUG, "SCAdmin: crash AgentServer#" + sid);
316
317     try {
318       socket = new Socket(host, port);
319       socket.getOutputStream().write(AdminProxy.CRASH_SERVER.getBytes());
320       socket.getOutputStream().write('\n');
321       socket.getOutputStream().flush();
322       try {
323         socket.getInputStream().read();
324       } catch (SocketException exc) {
325         // Nothing to do: connection reset by peer:
326
}
327     } catch (Throwable JavaDoc exc) {
328       if (logmon.isLoggable(BasicLevel.DEBUG))
329         logmon.log(BasicLevel.DEBUG,
330                     "SCAdmin: Can't crash server#" + sid, exc);
331       throw new Exception JavaDoc("Can't crash server#" + sid +
332                           ": " + exc.getMessage());
333     } finally {
334       close(socket);
335       socket = null;
336     }
337   }
338
339   static void close(Socket socket) {
340     try {
341       socket.getInputStream().close();
342     } catch (Exception JavaDoc exc) {}
343     try {
344       socket.getOutputStream().close();
345     } catch (Exception JavaDoc exc) {}
346     try {
347       socket.close();
348     } catch (Exception JavaDoc exc) {}
349   }
350 }
351
Popular Tags