KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > server > Server


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2005 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  *
22  * --------------------------------------------------------------------------
23  * $Id: Server.java,v 1.120 2005/07/13 06:28:35 durieuxp Exp $
24  * --------------------------------------------------------------------------
25  */

26
27 package org.objectweb.jonas.server;
28
29 import java.rmi.RMISecurityManager JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.List JavaDoc;
32
33 import javax.management.MBeanServer JavaDoc;
34 import javax.management.MBeanServerFactory JavaDoc;
35 import javax.management.ObjectName JavaDoc;
36 import javax.management.modelmbean.ModelMBean JavaDoc;
37 import javax.management.remote.JMXServiceURL JavaDoc;
38 import javax.security.jacc.PolicyContext JavaDoc;
39 import javax.security.jacc.PolicyContextException JavaDoc;
40 import javax.security.jacc.PolicyContextHandler JavaDoc;
41
42 import org.apache.commons.modeler.ManagedBean;
43 import org.apache.commons.modeler.Registry;
44
45 import org.objectweb.carol.util.configuration.ConfigurationRepository;
46 import org.objectweb.carol.util.configuration.ProtocolConfiguration;
47
48 import org.objectweb.jonas_lib.I18n;
49 import org.objectweb.jonas_lib.deployment.work.WorkCleaner;
50 import org.objectweb.jonas_lib.version.Version;
51
52 import org.objectweb.jonas.adm.Adm;
53 import org.objectweb.jonas.common.JProp;
54 import org.objectweb.jonas.common.Log;
55 import org.objectweb.jonas.common.LogManagement;
56 import org.objectweb.jonas.jmx.J2eeObjectName;
57 import org.objectweb.jonas.jmx.JmxService;
58 import org.objectweb.jonas.jmx.JonasObjectName;
59 import org.objectweb.jonas.management.JonasMBeanTools;
60 import org.objectweb.jonas.management.ReconfigManager;
61 import org.objectweb.jonas.management.j2eemanagement.J2EEDomain;
62 import org.objectweb.jonas.security.PolicyProvider;
63 import org.objectweb.jonas.security.jacc.JPolicyContextHandler;
64 import org.objectweb.jonas.service.JonasAlreadyStartedException;
65 import org.objectweb.jonas.service.ServiceException;
66 import org.objectweb.jonas.service.ServiceManager;
67
68 import org.objectweb.util.monolog.api.BasicLevel;
69 import org.objectweb.util.monolog.api.Logger;
70 import org.objectweb.util.monolog.wrapper.javaLog.MonologFormatter;
71
72 /**
73  * This class implements an JOnAS Server.
74  * @author Philippe Coq
75  * @author Philippe Durieux
76  * @author Jeff Mesnil
77  * @author Regis Le Brettevillois - Libelis / JOnAS team - evidian Service as
78  * org.objectweb.jonas.service.Service 02/04/25
79  * @author Sebastien Chassande-Barrioz sebastien.chassande@inrialpes.fr Monolog
80  * for traces
81  * @author Adriana Danes 03/01/20: -Highlight configuration properties 03/03/..:
82  * -Force jmx service startup -Create and register the JonAS
83  * configuration MBean. This MBean manages JOnAS persistent
84  */

85 public class Server {
86
87
88     /**
89      * Property value for the default file
90      */

91     private static final String JavaDoc DEF_LOG_CONFIGFILE = "trace";
92
93     /**
94      * Internationalization
95      */

96     private static I18n i18n = I18n.getInstance(Server.class);
97
98     /**
99      * Property for the configuration log file
100      */

101     private static final String JavaDoc LOG_CONFIGFILE = "jonas.log.configfile";
102
103     /**
104      * Logger
105      */

106     private static Logger logger = null;
107
108     /**
109      * Property for the security propagation
110      */

111     private static final String JavaDoc SECURITY_PROPAGATION = "jonas.security.propagation";
112
113     /**
114      * Property for the Csiv2 propagation
115      */

116     private static final String JavaDoc CSIV2_PROPAGATION = "jonas.csiv2.propagation";
117
118     /**
119      * Property for the security manager
120      */

121     private static final String JavaDoc SECURITY_MANAGER = "jonas.security.manager";
122
123     /**
124      * J2EE Application Server Name
125      */

126     private static final String JavaDoc SERVERNAME = "JOnAS";
127
128     /**
129      * Default sleep value
130      */

131     private static final int SLEEP_VALUE = 10000;
132
133     /**
134      * Property for the transaction propagation
135      */

136     private static final String JavaDoc TRANSACTION_PROPAGATION = "jonas.transaction.propagation";
137
138     /**
139      * The Server singleton value
140      */

141     private static Server unique = null;
142
143     /**
144      * ID of the MBean server
145      */

146     private String JavaDoc idMbeanServer = null;
147
148     /**
149      * MBean Server
150      */

151     private MBeanServer JavaDoc mbeanServer = null;
152
153     /**
154      * Get the unique instance. Create it at first call.
155      * @return unique instance.
156      * @throws Exception if the Server can not be instanciate
157      */

158     public static Server getInstance() throws Exception JavaDoc {
159         if (unique == null) {
160             unique = new Server();
161         }
162         return unique;
163     }
164
165     /**
166      * Server main routine. No args.
167      * @param args the arguments of the server
168      * @exception Exception can not start server
169      */

170     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
171         Server server = null;
172
173         // Add Mx4J logger as wrapper (allow to put the right class for debug in
174
// the log)
175
// Also add carol class which print traces
176
System.setProperty(MonologFormatter.WRAPPERS_PROPERTY, "mx4j.log.CommonsLogger,mx4j.log.Logger,org.objectweb.carol.util.configuration.TraceCarol");
177
178         try {
179             server = Server.getInstance();
180             server.start();
181         } catch (JonasAlreadyStartedException e) {
182             // if we get this exception this means that
183
// we are trying to restart the same JOnAS
184
System.err.println(i18n.getMessage("Server.main.alreadyStarted", SERVERNAME));
185             // rethrow JonasAlreadyStartedException
186
throw e;
187         } catch (Exception JavaDoc e) {
188             // We don't use here the trace system.
189
System.err.println("JOnAS error: " + e);
190             e.printStackTrace(System.err);
191             System.err.println(SERVERNAME + " halting");
192             try {
193                 if (server != null) {
194                     server.stop();
195                 }
196             } catch (Exception JavaDoc he) {
197                 System.err.println("Exception when halting" + he.getMessage());
198                 throw he;
199             }
200             throw e;
201         }
202     }
203
204     /**
205      * Associated Adm object
206      */

207     private Adm adm = null;
208
209     /**
210      * J2EE Management domain
211      */

212     private String JavaDoc domainName = null;
213
214     /**
215      * J2EEServer associate
216      */

217     private J2EEServer j2EEServer = null;
218
219     /**
220      * File for log configuration
221      */

222     private String JavaDoc logConfigFile;
223
224     /**
225      * JOnAS configuration properties
226      */

227     private JProp props = null;
228
229     /**
230      * Current server name (the server instance name)
231      */

232     private String JavaDoc serverName = null;
233
234     /**
235      * The associated ServiceManager for JOnAS
236      */

237     private ServiceManager sm = null;
238
239
240     /**
241      * Private constructor to force only 1 instance.
242      * @throws Exception (for example if JProp can't read properties file)
243      */

244     private Server() throws Exception JavaDoc {
245         // read the JOnAS properties
246
props = JProp.getInstance();
247
248         // set configuration info into the Log System (monolog)
249
logConfigFile = props.getValue(LOG_CONFIGFILE, DEF_LOG_CONFIGFILE);
250         Log.configure(logConfigFile);
251
252         // get a logger for server traces
253
logger = Log.getLogger(Log.JONAS_SERVER_PREFIX);
254
255         // create the service manager
256
sm = ServiceManager.getInstance();
257
258         // prints JVM infos
259
logger.log(BasicLevel.INFO, jvmInfos());
260
261         // called only once for a JVM
262
PolicyProvider.init();
263
264     }
265
266
267
268     /**
269      * Gets J2EEServer.
270      * @return J2EEServer
271      */

272     public J2EEServer getJ2EEServer() {
273         return j2EEServer;
274     }
275
276     /**
277      * Initialize the MBean server
278      * @throws Exception if MBean server cannot be found/created
279      */

280     private void initMBeanServer() throws Exception JavaDoc {
281
282         // Set domain name for creating MBeans
283
JonasObjectName.setDomain(domainName);
284
285         boolean existingMbeanServer = false;
286         // First, try to find an MBean Server
287
List JavaDoc mbeanServers = MBeanServerFactory.findMBeanServer(null);
288         if (mbeanServers.size() > 0) {
289             mbeanServer = (MBeanServer JavaDoc) mbeanServers.get(0);
290             existingMbeanServer = true;
291         } else {
292             // Need to create an MBean server
293
mbeanServer = MBeanServerFactory.createMBeanServer(domainName);
294         }
295
296         ObjectName JavaDoc mbeanServerDelegate = new ObjectName JavaDoc("JMImplementation:type=MBeanServerDelegate");
297         idMbeanServer = (String JavaDoc) mbeanServer.getAttribute(mbeanServerDelegate, "MBeanServerId");
298         if (existingMbeanServer) {
299             logger.log(BasicLevel.INFO, "Use an existing MBean server with id '" + idMbeanServer + "'.");
300         }
301     }
302
303
304     /**
305      * Initialize interception and carol
306      * @param props the JOnAS properties
307      * @param serverName the name of the server for creating mbeans
308      * @return list of protocols
309      * @throws Exception if carol init failed
310      */

311     public String JavaDoc initCarol(JProp props, String JavaDoc serverName) throws Exception JavaDoc {
312
313         // Intialize Carol
314
ConfigurationRepository.init(domainName, serverName);
315
316         // Initialize Interceptors
317
String JavaDoc sec = props.getValue(SECURITY_PROPAGATION, "false").trim();
318         String JavaDoc trans = props.getValue(TRANSACTION_PROPAGATION, "false").trim();
319         String JavaDoc csiv2 = props.getValue(CSIV2_PROPAGATION, "true").trim();
320
321         if (sec.equals("true")) {
322             // jrmp interceptors
323
ConfigurationRepository.addInterceptors("jrmp",
324                     "org.objectweb.jonas.security.interceptors.jrmp.SecurityInitializer");
325             // cmi interceptors
326
ConfigurationRepository.addInterceptors("cmi",
327                     "org.objectweb.jonas.security.interceptors.jrmp.SecurityInitializer");
328             // iiop interceptors flag
329
ConfigurationRepository.addInterceptors("iiop",
330                     "org.objectweb.jonas.security.interceptors.iiop.SecurityInitializer");
331
332         }
333
334         if (csiv2.equals("true")) {
335             ConfigurationRepository.addInterceptors("iiop", "org.objectweb.jonas.security.iiop.Csiv2Initializer");
336         }
337
338
339         if (trans.equals("true")) {
340             // jrmp interceptors flag
341
ConfigurationRepository.addInterceptors("jrmp", "org.objectweb.jotm.jta.rmi.JTAInterceptorInitializer");
342             // jrmp interceptors flag
343
ConfigurationRepository.addInterceptors("cmi", "org.objectweb.jotm.jta.rmi.JTAInterceptorInitializer");
344             // iiop interceptors flag
345
ConfigurationRepository.addInterceptors("iiop", "org.objectweb.jotm.ots.OTSORBInitializer");
346         }
347
348         // Set carol mode in server mode (will use fixed port if set)
349
System.setProperty("carol.server.mode", "true");
350
351         // get Carol configuration
352
// Should go as Carol MBean
353
String JavaDoc protocols = "";
354         String JavaDoc prefix = "rmi/";
355         ProtocolConfiguration[] protocolConfigurations = ConfigurationRepository.getConfigurations();
356         for (int c = 0; c < protocolConfigurations.length; c++) {
357             if (protocols == "") {
358                 protocols = prefix + protocolConfigurations[c].getName();
359             } else {
360                 protocols += "," + prefix + protocolConfigurations[c].getName();
361             }
362         }
363         return protocols;
364     }
365
366     /**
367      * Initialize the context handlers (JACC)
368      * @throws PolicyContextException if handlers can't be registered
369      */

370     private void initJACCPolicyContextHandlers() throws PolicyContextException JavaDoc {
371         PolicyContextHandler JavaDoc policyContextHandler = new JPolicyContextHandler();
372         String JavaDoc[] keys = policyContextHandler.getKeys();
373         for (int k = 0; k < keys.length; k++) {
374             PolicyContext.registerHandler(keys[k], policyContextHandler, true);
375         }
376     }
377
378     /**
379      * Stop the server and stop the JVM (MBean method)
380      * @throws Exception if the server can't be destroyed
381      */

382     public void kill() throws Exception JavaDoc {
383         if (adm != null) {
384             adm.killServer();
385         }
386     }
387
388     /**
389      * Start the server
390      * @throws Exception if server can't be started
391      */

392     public void start() throws Exception JavaDoc {
393         // Server name
394
serverName = props.getValue(JProp.JONAS_NAME, JProp.JONAS_DEF_NAME);
395
396         // Domain name
397
domainName = props.getValue(JProp.DOMAIN_NAME, JProp.JONAS_DEF_NAME);
398
399         initMBeanServer();
400
401         // Initialize Context Interceptors and Carol
402
String JavaDoc protocols = initCarol(props, serverName);
403
404         // RMI Security Manager
405
boolean useSecurityManager = new Boolean JavaDoc(props.getValue(SECURITY_MANAGER, "true").trim()).booleanValue();
406
407         if (useSecurityManager) {
408             if (System.getSecurityManager() == null) {
409                 System.setSecurityManager(new RMISecurityManager JavaDoc());
410             }
411         } else {
412             logger.log(BasicLevel.INFO, "Security manager is not set.");
413         }
414
415         // Initialize Policy Context handlers (JACC)
416
try {
417             initJACCPolicyContextHandlers();
418         } catch (PolicyContextException JavaDoc pce) {
419             logger.log(BasicLevel.ERROR, "Could not register JOnAS Policy Context Handlers");
420             throw pce;
421         }
422
423         // First of all, start registry service
424
sm.startRegistry();
425
426         // then, start JMX service (start an MBean server and create RMI
427
// connector for it registered in JNDI)
428

429         sm.startJmx(idMbeanServer);
430
431         // start the cleaner thread (deleting unused working files)
432
WorkCleaner.getInstance().start();
433
434         // Get the MBean register (and load mbeans-descriptors)
435
Registry oRegistry = JonasMBeanTools.getRegistry();
436
437         // Get domain name from environment
438
domainName = props.getValue(JProp.DOMAIN_NAME);
439
440         // Create and register a MBean for the Management Domain
441
ObjectName JavaDoc domainOn = null;
442
443         J2EEDomain j2eeDomain = null;
444         try {
445             // Create a JMX object name for the Domain MBean
446
domainOn = J2eeObjectName.J2EEDomain(domainName);
447             j2eeDomain = new J2EEDomain(domainOn.toString(), false, false, false);
448             ManagedBean oManaged = oRegistry.findManagedBean("J2EEDomain");
449             ModelMBean JavaDoc oMBean = oManaged.createMBean(j2eeDomain);
450             mbeanServer.registerMBean(oMBean, domainOn);
451         } catch (javax.management.InstanceAlreadyExistsException JavaDoc ae) {
452             // should never occur
453
if (logger.isLoggable(BasicLevel.DEBUG)) {
454                 logger.log(BasicLevel.DEBUG, ae);
455             }
456         } catch (Exception JavaDoc e) {
457             logger.log(BasicLevel.WARN, "Could not register J2EEDomain MBean");
458             e.printStackTrace();
459         }
460
461         // Create and register necessary MBeans for the server management
462
ObjectName JavaDoc serverOn = null;
463         try {
464             // Create and register a MBean allowing server reconfiguration
465
ReconfigManager reconfigManagerMBean = new ReconfigManager(props.getConfigFileEnv(), mbeanServer);
466             mbeanServer.registerMBean(reconfigManagerMBean, JonasObjectName.serverConfig());
467
468             // Create and register a MBean allowing the JOnAS server management
469
serverOn = J2eeObjectName.J2EEServer(domainName, serverName);
470             j2EEServer = new J2EEServer(serverOn.toString(), this, serverName, Version.NUMBER, Version.VENDOR,
471                     protocols);
472             ManagedBean oManaged = oRegistry.findManagedBean("J2EEServer");
473             ModelMBean JavaDoc oMBean = oManaged.createMBean(j2EEServer);
474             mbeanServer.registerMBean(oMBean, serverOn);
475
476             //Get the urls for the server to be added into the J2EEDomain mbean.
477
try {
478                 JmxService jmxService = ((JmxService) sm.getJmxService());
479                 JMXServiceURL JavaDoc[] connectorServerURLs = jmxService.getConnectorServerURLs();
480                 ArrayList JavaDoc urlsList = new ArrayList JavaDoc();
481                 for (int i = 0; i < connectorServerURLs.length; i++) {
482                     // The connectorServerURLs may contain null
483
// if the list of protocols in Carol contain
484
// other protocols than the standard ones (JRMP, JEREMIE,
485
// IIOP, CMI)
486
if (connectorServerURLs[i] != null) {
487                         urlsList.add(connectorServerURLs[i].toString());
488                     }
489                 }
490                 String JavaDoc[] urls = new String JavaDoc[urlsList.size()];
491                 for (int i = 0; i < urls.length; i++) {
492                     urls[i] = (String JavaDoc) urlsList.get(i);
493                 }
494                 j2eeDomain.addServer(serverOn.toString(), urls);
495                 j2eeDomain.setJmxService(jmxService);
496             } catch (ServiceException e) {
497                 // if there was a problem getting the urls
498
j2eeDomain.addServer(serverOn.toString(), null);
499             }
500
501             // Create and register a MBean for the logging service management
502
LogManagement logMBean = LogManagement.getInstance();
503             mbeanServer.registerMBean(logMBean, JonasObjectName.logService(logConfigFile));
504         } catch (Exception JavaDoc e) {
505             logger.log(BasicLevel.WARN, "Could not create J2EEServer MBean : " + e.getMessage(), e);
506         }
507
508         // Create the MBean for the corresponding JVM
509
ObjectName JavaDoc onJvm = null;
510         try {
511             onJvm = J2eeObjectName.JVM(domainName, serverName, serverName);
512             ManagedBean oManaged = oRegistry.findManagedBean("JVM");
513             JavaVm oJvm = new JavaVm(onJvm.toString(), props);
514             ModelMBean JavaDoc oMBean = oManaged.createMBean(oJvm);
515             mbeanServer.registerMBean(oMBean, onJvm);
516             // Update J2EEServer MBean
517
j2EEServer.addJavaVM(onJvm.toString());
518         } catch (Exception JavaDoc e) {
519             logger.log(BasicLevel.WARN, "Could not create JVM MBean : " + e.getMessage(), e);
520         }
521
522         // Creates the Adm instance for remote administration
523
try {
524             adm = new Adm(props);
525         } catch (Exception JavaDoc e) {
526             e.printStackTrace();
527             throw new Exception JavaDoc("Cannot create Adm : " + e);
528         }
529
530         // start all other services
531
sm.startServices();
532
533         // TM Server or EJB Server ?
534
boolean isEJB = true;
535         try {
536             sm.getEjbService();
537         } catch (ServiceException se) {
538             isEJB = false;
539         }
540         adm.serverReady(isEJB);
541
542         System.out.println(i18n.getMessage("Server.start.serverIsReady", serverName, Version.NUMBER));
543         logger.log(BasicLevel.INFO, i18n.getMessage("Server.start.serverStarted", serverName, protocols));
544
545         // Don't stop this thread to keep the server alive.
546

547         while (true) {
548             Thread.sleep(SLEEP_VALUE);
549         }
550     }
551
552     /**
553      * @return information on JVM currently used
554      */

555     public static String JavaDoc jvmInfos() {
556         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
557         sb.append("JVM used is ");
558         sb.append(System.getProperty("java.version"));
559         sb.append(" version of ");
560         sb.append(System.getProperty("java.vendor"));
561         sb.append(" vendor on ");
562         sb.append(System.getProperty("os.name"));
563         sb.append(" ");
564         sb.append(System.getProperty("os.version"));
565         sb.append("/");
566         sb.append(System.getProperty("os.arch"));
567         sb.append(" OS.");
568         return sb.toString();
569     }
570
571     /**
572      * Stop the server without stopping the JVM
573      * @throws Exception if the server can't be stopped
574      */

575     public void stop() throws Exception JavaDoc {
576         if (adm != null) {
577             System.out.println(i18n.getMessage("Server.stop.serverIsStopped", serverName));
578             logger.log(BasicLevel.INFO, i18n.getMessage("Server.stop.serverStopped", serverName));
579             adm.stopServer();
580         }
581     }
582
583     /**
584      * @return Returns the status of the server started or not.
585      */

586     public static boolean isStarted() {
587         return unique != null;
588     }
589 }
Popular Tags