KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > boot > ResinWatchdogManager


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.boot;
31
32 import com.caucho.config.Config;
33 import com.caucho.config.ConfigException;
34 import com.caucho.lifecycle.Lifecycle;
35 import com.caucho.log.EnvironmentStream;
36 import com.caucho.log.LogConfig;
37 import com.caucho.log.RotateStream;
38 import com.caucho.server.cluster.Cluster;
39 import com.caucho.server.cluster.ClusterServer;
40 import com.caucho.server.cluster.Server;
41 import com.caucho.server.dispatch.ServletMapping;
42 import com.caucho.server.host.Host;
43 import com.caucho.server.host.HostConfig;
44 import com.caucho.server.port.Port;
45 import com.caucho.server.port.ProtocolDispatchServer;
46 import com.caucho.server.webapp.WebApp;
47 import com.caucho.server.webapp.WebAppConfig;
48 import com.caucho.util.L10N;
49 import com.caucho.Version;
50 import com.caucho.vfs.Path;
51 import com.caucho.vfs.Vfs;
52 import com.caucho.vfs.WriteStream;
53
54 import java.io.File JavaDoc;
55 import java.io.IOException JavaDoc;
56 import java.net.URL JavaDoc;
57 import java.util.ArrayList JavaDoc;
58 import java.util.HashMap JavaDoc;
59 import java.util.logging.Level JavaDoc;
60 import java.util.logging.Logger JavaDoc;
61
62 /**
63  * Process responsible for watching a backend server.
64  */

65 public class ResinWatchdogManager extends ProtocolDispatchServer {
66   private static L10N _L;
67   private static Logger JavaDoc _log;
68
69   private static ResinWatchdogManager _watchdog;
70
71   private Args _args;
72
73   private Lifecycle _lifecycle = new Lifecycle();
74
75   private ResinConfig _resin;
76
77   private Server _dispatchServer;
78
79   private Port _port;
80
81   private HashMap JavaDoc<String JavaDoc,ResinWatchdog> _activeServerMap
82     = new HashMap JavaDoc<String JavaDoc,ResinWatchdog>();
83
84   ResinWatchdogManager(String JavaDoc []argv)
85     throws Exception JavaDoc
86   {
87     _watchdog = this;
88
89     _args = new Args(argv);
90
91     Vfs.setPwd(_args.getRootDirectory());
92
93     _resin = readConfig(_args);
94
95     ResinWatchdog server = _resin.findServer(_args.getServerId());
96
97     Cluster cluster = new Cluster();
98     ClusterServer clusterServer = new ClusterServer(cluster);
99     if (server != null) {
100       clusterServer.setAddress(server.getAddress().getHostAddress());
101       clusterServer.setPort(server.getWatchdogPort());
102     }
103     else
104       clusterServer.setPort(6600);
105     _dispatchServer = new Server(clusterServer);
106
107     HostConfig hostConfig = new HostConfig();
108     hostConfig.setId("resin-admin");
109
110     hostConfig.init();
111     
112     _dispatchServer.addHost(hostConfig);
113     _dispatchServer.init();
114     _dispatchServer.start();
115
116     Host host = _dispatchServer.getHost("resin-admin", 0);
117
118     WebAppConfig webAppConfig = new WebAppConfig();
119     webAppConfig.setId("");
120
121     host.addWebApp(webAppConfig);
122
123     WebApp webApp = host.findWebAppByURI("/");
124
125     ServletMapping servlet = new ServletMapping();
126
127     servlet.setServletName("watchdog");
128     servlet.addURLPattern("/watchdog");
129     servlet.setServletClass("com.caucho.boot.ResinWatchdogServlet");
130     servlet.init();
131
132     webApp.addServletMapping(servlet);
133     try {
134       host.updateWebAppDeploy("/");
135     } catch (Throwable JavaDoc e) {
136       log().log(Level.WARNING, e.toString(), e);
137     }
138
139     webApp.start();
140   }
141
142   static ResinWatchdogManager getWatchdog()
143   {
144     return _watchdog;
145   }
146
147   /*
148   void start()
149     throws Throwable
150   {
151     Watchdog server = _resin.findServer(_args.getServerId());
152
153     if (server == null)
154       throw new ConfigException(L().l("No matching <server> found for -server '{0}'",
155                       _args.getServerId()));
156
157     _port = new Port();
158     _port.setAddress(server.getAddress().getHostAddress());
159     _port.setPort(server.getWatchdogPort());
160
161     _port.setProtocol(new HmuxProtocol());
162     _port.setServer(_dispatchServer);
163
164     System.out.println("PORT: " + server.getAddress() + " " + server.getWatchdogPort());
165
166     //_port.bind();
167     _port.start();
168     
169     startServer(_args.getServerId(), _args.getArgv());
170
171     _lifecycle.toActive();
172
173     while (_lifecycle.isActive()) {
174       synchronized (_lifecycle) {
175     try {
176       _lifecycle.wait(10000);
177     } catch (Exception e) {
178     }
179       }
180     }
181   }
182   */

183
184   void startServer(String JavaDoc []argv)
185     throws ConfigException
186   {
187     Args args = new Args(argv);
188
189     String JavaDoc serverId = args.getServerId();
190
191     Vfs.setPwd(_args.getRootDirectory());
192
193     ResinConfig resin = null;
194
195     try {
196       resin = readConfig(args);
197     } catch (ConfigException e) {
198       throw e;
199     } catch (Exception JavaDoc e) {
200       throw new ConfigException(e);
201     }
202     
203     ResinWatchdog server = resin.findServer(serverId);
204
205     if (server == null)
206       throw new ConfigException(L().l("No matching <server> found for -server '{0}' in '{1}'",
207                       serverId, _args.getResinConf()));
208
209     if (args.isVerbose())
210       server.setVerbose(args.isVerbose());
211
212     synchronized (_activeServerMap) {
213       if (_activeServerMap.get(serverId) != null) {
214     throw new IllegalStateException JavaDoc(L().l("-server '{0}' is already running.",
215                       serverId));
216       }
217
218       server.start(argv, args.getRootDirectory());
219       
220       _activeServerMap.put(serverId, server);
221     }
222   }
223
224   void stopServer(String JavaDoc serverId)
225   {
226     ResinWatchdog server = null;
227     
228     server = _resin.findServer(serverId);
229
230     if (server == null)
231       throw new ConfigException(L().l("No matching <server> found for -server '{0}' in {1}",
232                       serverId, _args.getResinConf()));
233     
234     synchronized (_activeServerMap) {
235       server = _activeServerMap.remove(serverId);
236     }
237
238     log().info(server + " stopping");
239
240     if (server == null)
241       throw new IllegalStateException JavaDoc(L().l("-server '{0}' is already stopped.",
242                       serverId));
243
244     server.stop();
245   }
246
247   private ResinConfig readConfig(Args args)
248     throws Exception JavaDoc
249   {
250     Config config = new Config();
251
252     Vfs.setPwd(args.getRootDirectory());
253     ResinConfig resin = new ResinConfig(args.getResinHome(),
254                     args.getRootDirectory());
255
256     config.configure(resin,
257              args.getResinConf(),
258              "com/caucho/server/resin/resin.rnc");
259
260     return resin;
261   }
262
263   public static void main(String JavaDoc []argv)
264     throws Throwable JavaDoc
265   {
266     try {
267       Path logPath = Vfs.lookup("log/watchdog-manager.log");
268
269       RotateStream stream = RotateStream.create(logPath);
270       stream.init();
271       WriteStream out = stream.getStream();
272       out.setDisableClose(true);
273
274       EnvironmentStream.setStdout(out);
275       EnvironmentStream.setStderr(out);
276
277       LogConfig log = new LogConfig();
278       log.setName("");
279       //log.setLevel("finer");
280
log.setPath(logPath);
281       log.init();
282
283       //Logger.getLogger("").setLevel(Level.FINER);
284

285       ResinWatchdogManager manager = new ResinWatchdogManager(argv);
286
287       manager.startServer(argv);
288     } catch (Exception JavaDoc e) {
289       e.printStackTrace();
290     }
291   }
292
293   //
294
// Utility static methods
295
//
296

297   static Path calculateResinHome()
298   {
299     String JavaDoc resinHome = System.getProperty("resin.home");
300
301     if (resinHome != null) {
302       return Vfs.lookup(resinHome);
303     }
304
305     // find the resin.jar as described by the classpath
306
// this may differ from the value given by getURL() because of
307
// symbolic links
308
String JavaDoc classPath = System.getProperty("java.class.path");
309
310     if (classPath.indexOf("resin.jar") >= 0) {
311       int q = classPath.indexOf("resin.jar") + "resin.jar".length();
312       int p = classPath.lastIndexOf(File.pathSeparatorChar, q - 1);
313
314       String JavaDoc resinJar;
315
316       if (p >= 0)
317     resinJar = classPath.substring(p + 1, q);
318       else
319     resinJar = classPath.substring(0, q);
320
321       return Vfs.lookup(resinJar).lookup("../..");
322     }
323
324     ClassLoader JavaDoc loader = ClassLoader.getSystemClassLoader();
325
326     URL JavaDoc url = loader.getResource("com/caucho/boot/ResinBoot.class");
327
328     String JavaDoc path = url.toString();
329
330     if (! path.startsWith("jar:"))
331       throw new RuntimeException JavaDoc(L().l("Resin/{0}: can't find jar for ResinBoot in {1}",
332                        Version.VERSION, path));
333
334     int p = path.indexOf(':');
335     int q = path.indexOf('!');
336
337     path = path.substring(p + 1, q);
338
339     Path pwd = Vfs.lookup(path).getParent().getParent();
340
341     return pwd;
342   }
343
344   static Path calculateResinRoot(Path resinHome)
345   {
346     String JavaDoc serverRoot = System.getProperty("server.root");
347
348     if (serverRoot != null)
349       return Vfs.lookup(serverRoot);
350
351     return resinHome;
352   }
353
354   static String JavaDoc calculateClassPath(Path resinHome)
355     throws IOException JavaDoc
356   {
357     ArrayList JavaDoc<String JavaDoc> classPath = new ArrayList JavaDoc<String JavaDoc>();
358
359     Path javaHome = Vfs.lookup(System.getProperty("java.home"));
360
361     if (javaHome.lookup("lib/tools.jar").canRead())
362       classPath.add(javaHome.lookup("lib/tools.jar").getNativePath());
363     else if (javaHome.getTail().startsWith("jre")) {
364       String JavaDoc tail = javaHome.getTail();
365       tail = "jdk" + tail.substring(3);
366       Path jdkHome = javaHome.getParent().lookup(tail);
367
368       if (jdkHome.lookup("lib/tools.jar").canRead())
369     classPath.add(jdkHome.lookup("lib/tools.jar").getNativePath());
370     }
371     
372     if (javaHome.lookup("../lib/tools.jar").canRead())
373       classPath.add(javaHome.lookup("../lib/tools.jar").getNativePath());
374
375     Path resinLib = resinHome.lookup("lib");
376
377     if (resinLib.lookup("pro.jar").canRead())
378       classPath.add(resinLib.lookup("pro.jar").getNativePath());
379     classPath.add(resinLib.lookup("resin.jar").getNativePath());
380     classPath.add(resinLib.lookup("jaxrpc-15.jar").getNativePath());
381           
382     String JavaDoc []list = resinLib.list();
383
384     for (int i = 0; i < list.length; i++) {
385       if (! list[i].endsWith(".jar"))
386     continue;
387       
388       Path item = resinLib.lookup(list[i]);
389
390       String JavaDoc pathName = item.getNativePath();
391
392       if (! classPath.contains(pathName))
393     classPath.add(pathName);
394     }
395
396     String JavaDoc cp = "";
397
398     for (int i = 0; i < classPath.size(); i++) {
399       if (! "".equals(cp))
400     cp += File.pathSeparatorChar;
401
402       cp += classPath.get(i);
403     }
404
405     return cp;
406   }
407
408   private static L10N L()
409   {
410     if (_L == null)
411       _L = new L10N(ResinBoot.class);
412
413     return _L;
414   }
415
416   private static Logger JavaDoc log()
417   {
418     if (_log == null)
419       _log = Logger.getLogger(ResinBoot.class.getName());
420
421     return _log;
422   }
423
424   static class Args {
425     private Path _resinHome;
426     private Path _rootDirectory;
427     private String JavaDoc []_argv;
428
429     private Path _resinConf;
430
431     private String JavaDoc _serverId = "";
432
433     private boolean _isVerbose;
434     
435     Args(String JavaDoc []argv)
436     {
437       _resinHome = calculateResinHome();
438       _rootDirectory = calculateResinRoot(_resinHome);
439       
440       _argv = argv;
441
442       _resinConf = _resinHome.lookup("conf/resin.conf");
443
444       parseCommandLine(argv);
445     }
446
447     Path getResinHome()
448     {
449       return _resinHome;
450     }
451
452     Path getRootDirectory()
453     {
454       return _rootDirectory;
455     }
456
457     Path getResinConf()
458     {
459       return _resinConf;
460     }
461
462     String JavaDoc getServerId()
463     {
464       return _serverId;
465     }
466
467     String JavaDoc []getArgv()
468     {
469       return _argv;
470     }
471
472     boolean isVerbose()
473     {
474       return _isVerbose;
475     }
476
477     private void parseCommandLine(String JavaDoc []argv)
478     {
479       for (int i = 0; i < argv.length; i++) {
480     String JavaDoc arg = argv[i];
481
482     if ("-conf".equals(arg)
483         || "--conf".equals(arg)) {
484       _resinConf = _resinHome.lookup(argv[i + 1]);
485       i++;
486     }
487     else if ("-resin-home".equals(arg)
488          || "--resin-home".equals(arg)) {
489       _resinHome = Vfs.lookup(argv[i + 1]);
490       i++;
491     }
492         else if ("-root-directory".equals(arg)
493                  || "--root-directory".equals(arg)) {
494           _rootDirectory = Vfs.lookup(argv[i + 1]);
495           i++;
496         }
497     else if ("-server-root".equals(arg)
498          || "--server-root".equals(arg)) {
499       _rootDirectory = Vfs.lookup(argv[i + 1]);
500       i++;
501     }
502     else if ("-server".equals(arg)
503          || "--server".equals(arg)) {
504       _serverId = argv[i + 1];
505       i++;
506     }
507     else if ("-verbose".equals(arg)
508          || "--verbose".equals(arg)) {
509       _isVerbose = true;
510     }
511       }
512     }
513   }
514 }
515
Popular Tags