KickJava   Java API By Example, From Geeks To Geeks.

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


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.el.EL;
35 import com.caucho.loader.Environment;
36 import com.caucho.server.resin.ResinELContext;
37 import com.caucho.util.L10N;
38 import com.caucho.vfs.Path;
39 import com.caucho.vfs.Vfs;
40 import com.caucho.Version;
41
42 import java.io.File JavaDoc;
43 import java.io.IOException JavaDoc;
44 import java.net.URL JavaDoc;
45 import java.util.logging.Level JavaDoc;
46 import java.util.logging.Logger JavaDoc;
47
48 /**
49  * ResinBoot is the main bootstrap class for Resin. It parses the
50  * resin.conf and looks for the <server> block matching the -server
51  * argument.
52  *
53  * <h3>Start Modes:</h3>
54  *
55  * The start modes are DIRECT, START, STOP, RESTART.
56  *
57  * <ul>
58  * <li>DIRECT starts a <server> from the command line
59  * <li>START starts a <server> with a Watchdog in the background
60  * <li>STOP stop the <server> Resin in the background
61  * </ul>
62  */

63 public class ResinBoot {
64   private static L10N _L;
65   private static Logger JavaDoc _log;
66
67   private String JavaDoc []_argv;
68
69   private Path _resinHome;
70   private Path _rootDirectory;
71   private Path _resinConf;
72   private String JavaDoc _serverId = "";
73   private boolean _isVerbose;
74   private boolean _isResinProfessional;
75
76   private ResinWatchdog _server;
77
78   private StartMode _startMode = StartMode.DIRECT;
79
80   ResinBoot(String JavaDoc []argv)
81     throws Exception JavaDoc
82   {
83     Environment.init();
84
85     _argv = argv;
86
87     calculateResinHome();
88     calculateRootDirectory();
89
90     parseCommandLine(argv);
91
92     // required for license check
93
System.setProperty("resin.home", _resinHome.getNativePath());
94
95     if (_resinConf == null) {
96       _resinConf = _rootDirectory.lookup("conf/resin.conf");
97
98       if (!_resinConf.exists()) {
99         Path resinHomeConf = _resinHome.lookup("conf/resin.conf");
100
101         if (resinHomeConf.exists())
102           _resinConf = resinHomeConf;
103       }
104     }
105
106     // watchdog/0210
107
// Vfs.setPwd(_rootDirectory);
108

109     if (! _resinConf.canRead()) {
110       throw new ConfigException(L().l("Resin/{0} can't open configuration file '{1}'",
111                                       Version.VERSION, _resinConf.getNativePath()));
112     }
113
114     // XXX: set _isResinProfessional
115

116     Config config = new Config();
117
118     ResinConfig conf = new ResinConfig(_resinHome, _rootDirectory);
119
120     ResinELContext elContext = new ResinBootELContext();
121
122     EL.setEnvironment(elContext, conf.getClassLoader());
123
124     /**
125      * XXX: the following setVar calls should not be necessary, but the
126      * EL.setEnviornment() call above is not effective:
127      */

128     config.setVar("java", elContext.getJavaVar());
129     config.setVar("resin", elContext.getResinVar());
130     config.setVar("server", elContext.getServerVar());
131
132     config.configure(conf, _resinConf, "com/caucho/server/resin/resin.rnc");
133
134     _server = conf.findServer(_serverId);
135
136     if (_server == null)
137       throw new ConfigException(L().l("Resin/{0}: -server '{1}' does not match any defined <server>\nin {2}.",
138                                       Version.VERSION, _serverId, _resinConf));
139
140     if (_isVerbose)
141       _server.setVerbose(_isVerbose);
142   }
143
144   private void calculateResinHome()
145   {
146     String JavaDoc resinHome = System.getProperty("resin.home");
147
148     if (resinHome != null) {
149       _resinHome = Vfs.lookup(resinHome);
150       return;
151     }
152
153     // find the resin.jar as described by the classpath
154
// this may differ from the value given by getURL() because of
155
// symbolic links
156
String JavaDoc classPath = System.getProperty("java.class.path");
157
158     if (classPath.indexOf("resin.jar") >= 0) {
159       int q = classPath.indexOf("resin.jar") + "resin.jar".length();
160       int p = classPath.lastIndexOf(File.pathSeparatorChar, q - 1);
161
162       String JavaDoc resinJar;
163
164       if (p >= 0)
165     resinJar = classPath.substring(p + 1, q);
166       else
167     resinJar = classPath.substring(0, q);
168
169       _resinHome = Vfs.lookup(resinJar).lookup("../..");
170       return;
171     }
172
173     ClassLoader JavaDoc loader = ClassLoader.getSystemClassLoader();
174
175     URL JavaDoc url = loader.getResource("com/caucho/boot/ResinBoot.class");
176
177     String JavaDoc path = url.toString();
178
179     if (! path.startsWith("jar:"))
180       throw new RuntimeException JavaDoc(L().l("Resin/{0}: can't find jar for ResinBoot.class in {1}",
181                        Version.VERSION, path));
182
183     int p = path.indexOf(':');
184     int q = path.indexOf('!');
185
186     path = path.substring(p + 1, q);
187
188     _resinHome = Vfs.lookup(path).getParent().getParent();
189   }
190
191   private void calculateRootDirectory()
192   {
193     String JavaDoc rootDirectory = System.getProperty("server.root");
194
195     if (rootDirectory != null) {
196       _rootDirectory = Vfs.lookup(rootDirectory);
197       return;
198     }
199
200     _rootDirectory = _resinHome;
201   }
202
203   private void parseCommandLine(String JavaDoc []argv)
204   {
205     String JavaDoc resinConf = null;
206
207     for (int i = 0; i < argv.length; i++) {
208       String JavaDoc arg = argv[i];
209
210       if ("-conf".equals(arg)
211       || "--conf".equals(arg)) {
212     resinConf = argv[i + 1];
213     i++;
214       }
215       else if ("-resin-home".equals(arg)
216            || "--resin-home".equals(arg)) {
217     _resinHome = Vfs.lookup(argv[i + 1]);
218     i++;
219       }
220       else if ("-root-directory".equals(arg)
221                || "--root-directory".equals(arg)) {
222         _rootDirectory = Vfs.lookup(argv[i + 1]);
223         i++;
224       }
225       else if ("-server-root".equals(arg)
226            || "--server-root".equals(arg)) {
227     _rootDirectory = Vfs.lookup(argv[i + 1]);
228     i++;
229       }
230       else if ("-server".equals(arg)
231            || "--server".equals(arg)) {
232     _serverId = argv[i + 1];
233     i++;
234       }
235       else if ("-verbose".equals(arg)
236            || "--verbose".equals(arg)) {
237     _isVerbose = true;
238     Logger.getLogger("").setLevel(Level.CONFIG);
239       }
240       else if ("-finer".equals(arg)
241            || "--finer".equals(arg)) {
242     _isVerbose = true;
243     Logger.getLogger("").setLevel(Level.FINER);
244       }
245       else if ("-fine".equals(arg)
246            || "--fine".equals(arg)) {
247     _isVerbose = true;
248     Logger.getLogger("").setLevel(Level.FINE);
249       }
250       else if (arg.startsWith("-J")
251            || arg.startsWith("-D")
252            || arg.startsWith("-X")) {
253       }
254       else if ("start".equals(arg)) {
255     _startMode = StartMode.START;
256       }
257       else if ("stop".equals(arg)) {
258     _startMode = StartMode.STOP;
259       }
260       else if ("restart".equals(arg)) {
261     _startMode = StartMode.RESTART;
262       }
263       else if ("shutdown".equals(arg)) {
264     _startMode = StartMode.SHUTDOWN;
265       }
266       else {
267         System.out.println(L().l("unknown argument '{0}'", argv[i]));
268         System.out.println();
269     usage();
270     System.exit(66);
271       }
272     }
273
274     if (resinConf != null) {
275       _resinConf = Vfs.getPwd().lookup(resinConf);
276
277       if (! _resinConf.exists() && _rootDirectory != null)
278         _resinConf = _rootDirectory.lookup(resinConf);
279
280       if (! _resinConf.exists() && _resinHome != null)
281         _resinConf = _resinHome.lookup(resinConf);
282
283       if (! _resinConf.exists())
284         throw new ConfigException(L().l("Resin/{0} can't find configuration file '{1}'", Version.VERSION, _resinConf.getNativePath()));
285     }
286   }
287
288   private static void usage()
289   {
290     System.err.println(L().l("usage: java -jar resin.jar [-options] [start | stop | restart]"));
291     System.err.println(L().l(""));
292     System.err.println(L().l("where options include:"));
293     System.err.println(L().l(" -conf <file> select a configuration file"));
294     System.err.println(L().l(" -resin-home <dir> select a resin home directory"));
295     System.err.println(L().l(" -root-directory <dir> select a root directory"));
296     System.err.println(L().l(" -server <id> select a <server> to run"));
297     System.err.println(L().l(" -verbose print verbose starting information"));
298   }
299
300   boolean start()
301     throws Exception JavaDoc
302   {
303     if (_startMode == StartMode.START) {
304       try {
305     _server.startWatchdog(_argv);
306     
307     System.out.println(L().l("Resin/{0} started -server '{1}'.",
308                  Version.VERSION, _server.getId()));
309       } catch (Exception JavaDoc e) {
310     System.out.println(L().l("Resin/{0} can't start -server '{1}'.\n{2}",
311                  Version.VERSION, _server.getId(),
312                  e.toString()));
313
314     log().log(Level.FINE, e.toString(), e);
315
316     System.exit(1);
317       }
318       
319       return false;
320     }
321     else if (_startMode == StartMode.STOP) {
322       try {
323     _server.stopWatchdog();
324     
325     System.out.println(L().l("Resin/{0} stopped -server '{1}'.",
326                  Version.VERSION, _server.getId()));
327       } catch (Exception JavaDoc e) {
328     System.out.println(L().l("Resin/{0} can't stop -server '{1}'.\n{2}",
329                  Version.VERSION, _server.getId(),
330                  e.toString()));
331
332     log().log(Level.FINE, e.toString(), e);
333
334     System.exit(1);
335       }
336       
337       return false;
338     }
339     else if (_startMode == StartMode.RESTART) {
340       try {
341     _server.restartWatchdog(_argv);
342     
343     System.out.println(L().l("Resin/{0} restarted -server '{1}'.",
344                  Version.VERSION, _server.getId()));
345       } catch (Exception JavaDoc e) {
346     System.out.println(L().l("Resin/{0} can't restart -server '{1}'.\n{2}",
347                  Version.VERSION, _server.getId(),
348                  e.toString()));
349
350     log().log(Level.FINE, e.toString(), e);
351
352     System.exit(1);
353       }
354       
355       return false;
356     }
357     else if (_startMode == StartMode.SHUTDOWN) {
358       try {
359     _server.shutdown();
360
361     System.out.println(L().l("Resin/{0} shutdown ResinWatchdogManager",
362                  Version.VERSION));
363       } catch (Exception JavaDoc e) {
364     System.out.println(L().l("Resin/{0} can't shutdown ResinWatchdogManager.\n{1}",
365                  Version.VERSION, e.toString()));
366
367     log().log(Level.FINE, e.toString(), e);
368
369     System.exit(1);
370       }
371
372       return false;
373     }
374     else {
375       return _server.startSingle(_argv, _rootDirectory) != 0;
376     }
377   }
378
379   /**
380    * The main start of the web server.
381    *
382    * <pre>
383    * -conf resin.conf : alternate configuration file
384    * -server web-a : &lt;server> to start
385    * <pre>
386    */

387   public static void main(String JavaDoc []argv)
388   {
389     try {
390       ResinBoot boot = new ResinBoot(argv);
391
392       while (boot.start()) {
393     try {
394       synchronized (boot) {
395         boot.wait(5000);
396       }
397     } catch (Throwable JavaDoc e) {
398     }
399       }
400     } catch (ConfigException e) {
401       System.out.println(e.getMessage());
402
403       System.exit(1);
404     } catch (Exception JavaDoc e) {
405       e.printStackTrace();
406       
407       System.exit(1);
408     }
409   }
410
411   private static L10N L()
412   {
413     if (_L == null)
414       _L = new L10N(ResinBoot.class);
415
416     return _L;
417   }
418
419   private static Logger JavaDoc log()
420   {
421     if (_log == null)
422       _log = Logger.getLogger(ResinBoot.class.getName());
423
424     return _log;
425   }
426
427   enum StartMode {
428     DIRECT,
429     START,
430     STOP,
431     RESTART,
432     SHUTDOWN
433   };
434
435   public class ResinBootELContext
436     extends ResinELContext
437   {
438     public Path getResinHome()
439     {
440       return _resinHome;
441     }
442
443     public Path getRootDirectory()
444     {
445       return _rootDirectory;
446     }
447
448     public Path getResinConf()
449     {
450       return _resinConf;
451     }
452
453     public String JavaDoc getServerId()
454     {
455       return _serverId;
456     }
457
458     public boolean isResinProfessional()
459     {
460       return _isResinProfessional;
461     }
462   }
463 }
464
Popular Tags