KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > instance > ServerManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.instance;
25
26 //JDK imports
27
import java.io.File JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.util.logging.Level JavaDoc;
30 import java.util.logging.Logger JavaDoc;
31
32 //iAS imports
33
import com.sun.enterprise.util.ProcessExecutor;
34 import com.sun.enterprise.util.ExecException;
35 import com.sun.enterprise.config.ConfigException;
36 import com.sun.enterprise.server.Constants;
37 import com.sun.enterprise.util.StringUtils;
38 import com.sun.enterprise.util.io.FileUtils;
39 import com.sun.enterprise.util.OS;
40 /*installConfig is removed and we need better alternative */
41 import com.sun.enterprise.util.net.NetUtils;
42 import com.sun.enterprise.admin.common.constant.AdminConstants;
43 import com.sun.enterprise.config.ConfigContext;
44 import com.sun.enterprise.config.ConfigFactory;
45 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
46 import com.sun.enterprise.config.serverbeans.Server;
47 import com.sun.enterprise.config.serverbeans.Config;
48 import com.sun.enterprise.config.serverbeans.HttpService;
49 import com.sun.enterprise.config.serverbeans.HttpListener;
50 import com.sun.enterprise.config.serverbeans.IiopService;
51 import com.sun.enterprise.config.serverbeans.IiopListener;
52 import com.sun.enterprise.config.serverbeans.JmsService;
53 import com.sun.enterprise.config.serverbeans.JmsHost;
54 import com.sun.enterprise.admin.common.InitConfFileBean;
55
56 /**
57  * A class that acts as a helper when one has to take care of
58  * various instances. Such a situation would probably occur in case
59  * of administration as it has to administer all the instances in the
60  * given install. It is supposed to be a singleton.
61  * @author Jeet Kaul - originially.
62  * @author Kedar Mhaswade.
63  */

64
65 public class ServerManager {
66
67     public static final String JavaDoc INSTALL_ROOT =
68         System.getProperty(Constants.INSTALL_ROOT);
69     public static final String JavaDoc INSTANCE_CFG_ROOT =
70         System.getProperty(Constants.IAS_ROOT);
71     public static final String JavaDoc DOC_DIR_NAME = "docroot";
72     public static final String JavaDoc ADMINSERVER_ID = "admin-server";
73
74     private static final ServerManager SHARED_INSTANCE = new ServerManager();
75     private static Logger JavaDoc sLogger =
76             Logger.getLogger(AdminConstants.kLoggerName);
77
78     /** Private constructor so that nobody else creates the instance */
79
80     private ServerManager() {
81     }
82
83     /** Static Method to get a reference to the singleton.
84      * @return instance of ServerManager class.
85     */

86
87     public static ServerManager instance(){
88         return SHARED_INSTANCE;
89     }
90
91     /**
92      * A method to find whether a Server Instance with given name exists
93      * in the install. The instanceID should be the one designated by the user
94      * while creating the instance. An Instance is recognized by the configuration
95      * stored in a folder (on file system) named <strong> https-</strong> id. (This is
96      * for historical reasons). So, there are as many instances as there are
97      * folders beginning with string https-. No other consideration will be
98      * given. This method always ignores admin server.
99      * @param instanceID representing the id of the Server Instance. May not be null.
100      * @return true if the given instance's config directory exists, false otherwise.
101     */

102
103     public boolean instanceExists(String JavaDoc instanceID) {
104         //KE: FIXTHIS: We can only tell if an instance exists by looking
105
//at domain.xml
106
if (instanceID.equals("server")) {
107             return true;
108         }
109         return false;
110     }
111
112     /**
113      * The instance names are not registered in any configuration file for iASSE.
114      * Hence this method scans the folder on disk where installation is done, each time
115      * it is called and returns the instance names. Note that all the instances
116      * are denoted by https-id folders in INSTALL_ROOT. This method returns
117      * an array of all ids. Note that admin server itself is NOT returned
118      * as an Instance.
119      * @return an array of all instance names. An array of zero length, if
120      * there isn't any. Never returns a null.
121      * @throws SecurityException, if there is no read permission to INSTALL_ROOT.
122     */

123
124     public String JavaDoc[] getInstanceNames(boolean countAdmin) {
125         //KE: FIXTHIS. We can get instances from domain.xml only.
126
return new String JavaDoc[] {"server"};
127     }
128
129     /**
130      * Returns the number of instances depending on whether the admin
131      * instance is to be counted.
132      * @param countAdmin true if the returned list should contain admin
133      * @return integer representing the number of server instances.
134     */

135
136     public int getNumInstances(boolean countAdmin) {
137         return ( getInstanceNames(countAdmin).length );
138     }
139
140     /**
141         Creates the given ServerInstance. InstanceDefinition may not be null.
142         Gives call to underlying cgi program
143         to actually create the new instance of iAS. The creation of instance
144         consists of creation of directory structure as per the definition of
145         instance.
146         Note that this method does an expensive Runtime.exec() internally.
147
148         @param instance the InstanceDefinition pertaining to instance to be created.
149         @throws ConfigException if there is any error in arguments and/or the
150         underlying program throws an error.
151         @throws IllegalArgumentException in case of null instance.
152     */

153
154     public void createServerInstance(InstanceDefinition instance) throws
155         IOException JavaDoc, ConfigException
156         {
157             /*
158              * Be very careful with this method. All the paths that are
159              * required to be put into the various config files for
160              * an instance have forward slashes regardless of the
161              * underlying platform.
162             */

163             /* Removing this entire method as it is not applicable to PE */
164             throw new UnsupportedOperationException JavaDoc("createServerInstance - not in PE");
165         }
166
167     /**
168         A method to delete the server instance with given name or id.
169         Unlike other methods to create, start and stop the instances, this
170         method does not depend on other lower level API. The file system folder
171         where the instance's configuration resides, is deleted.
172         Running instance should be soped before this call (in ServerController).
173         On NT the Service needs to be deleted - which is not yet implemented (01/26/02).
174         @param instanceName name of the instance(id) to be deleted - may not be null.
175         @throws ConfigException if the action encounters some problems.
176     */

177     public void deleteServerInstance(String JavaDoc instanceName) throws
178         ConfigException {
179             /* Removing this entire method as it is not applicable to PE */
180         throw new UnsupportedOperationException JavaDoc("deleteServerInstance - not in PE");
181     }
182     /**
183         Starts the given instance. The argument may not be null.
184         Gives call to start program inside the proper directory structure of
185         that instance (e.g. /export/iplanet/ias7/https-test/start).
186         The createServerInstance call has to succeed for this call to work.
187         Note that it gives call to an expensive Runtime.exec().
188         @param instance the InstanceDefinition pertaining to instance to be created.
189         @throws ConfigException if there is any error in arguments and/or the
190         underlying program throws an error.
191         @throws IllegalArgumentException in case of null instance.
192      */

193
194     public void startServerInstance(InstanceDefinition instance) throws
195         ConfigException, RuntimeException JavaDoc {
196         startServerInstance(instance, null);
197     }
198
199     public void startServerInstance(InstanceDefinition instance, String JavaDoc[] passwords) throws
200         ConfigException, RuntimeException JavaDoc {
201         if (instance == null) {
202             throw new IllegalArgumentException JavaDoc();
203         }
204         String JavaDoc[] startCommand = instance.getStartCommand();
205         String JavaDoc[] inputLines = null;
206         if(passwords!=null)
207             inputLines = passwords;
208         else
209             inputLines = new String JavaDoc[]{}; //to provoke stream closing
210
//startCommand = startCommand + " " + instance.getID() + " " + INSTALL_ROOT;
211
try {
212             sLogger.log(Level.FINE, "general.exec_cmd", startCommand[0]);
213             ProcessExecutor executor = new ProcessExecutor(startCommand, inputLines);
214             executor.execute();
215         }
216                 catch (ExecException ee) {
217                     sLogger.log(Level.WARNING, "general.exec_cmd", ee);
218                     throw new RuntimeException JavaDoc(Localizer.getValue(ExceptionType.SERVER_NO_START));
219                 }
220         catch (Exception JavaDoc e) {
221             throw new ConfigException(e.getMessage());
222         }
223     }
224
225     /**
226         Stops the given instance. The argument may not be null.
227         Gives call to stop program inside the proper directory structure of
228         that instance (e.g. /export/iplanet/ias7/https-test/stop).
229         The createServerInstance call has to succeed for this call to work.
230         Note that it gives call to an expensive Runtime.exec().
231         @param instance the InstanceDefinition pertaining to instance to be created.
232         @throws ConfigException if there is any error in arguments and/or the
233         underlying program throws an error.
234         @throws IllegalArgumentException in case of null instance.
235      */

236
237     public void stopServerInstance(InstanceDefinition instance) throws
238         ConfigException {
239         if (instance == null) {
240             throw new IllegalArgumentException JavaDoc();
241         }
242         String JavaDoc stopCommand[] = instance.getStopCommand();
243         try {
244             sLogger.log(Level.FINE, "general.exec_cmd", stopCommand[0]);
245             ProcessExecutor executor = new ProcessExecutor(stopCommand);
246             executor.execute();
247         }
248         catch (Exception JavaDoc e) {
249             throw new ConfigException(e.getMessage());
250         }
251     }
252
253     /**
254      */

255     public void restartServerInstance(InstanceDefinition instance)
256             throws ConfigException {
257         if (instance == null) {
258             throw new IllegalArgumentException JavaDoc();
259         }
260         String JavaDoc[] restartCommand = instance.getRestartCommand();
261         try {
262             sLogger.log(Level.FINE, "general.exec_cmd", restartCommand[0]);
263             ProcessExecutor executor = new ProcessExecutor(restartCommand);
264             executor.execute();
265         }
266         catch (Exception JavaDoc e) {
267             throw new ConfigException(e.getMessage());
268         }
269     }
270
271     public String JavaDoc[] getSecurityTokensForInstance(InstanceDefinition instance) throws
272         ConfigException, RuntimeException JavaDoc {
273         if (instance == null) {
274             throw new IllegalArgumentException JavaDoc();
275         }
276         String JavaDoc[] command = instance.getGetSecurityTokensCommand();
277         String JavaDoc[] inputLines = null;
278         try {
279             sLogger.log(Level.FINE, "general.gettokens_cmd", command[0]);
280             ProcessExecutor executor = new ProcessExecutor(command);
281             return executor.execute(true);
282         }
283                 catch (ExecException ee) {
284                         throw new RuntimeException JavaDoc(Localizer.getValue(ExceptionType.NO_RECEIVE_TOKENS));
285                 }
286         catch (Exception JavaDoc e) {
287             throw new ConfigException(e.getMessage());
288         }
289     }
290
291     /**
292         Returns the path of the mime.types.template file for this installation.
293         This templates file is stored in the templates directory.
294         @return path of template file for mime.types
295     */

296     public String JavaDoc getMimeTypesTemplateFilePath() {
297         final String JavaDoc libDirName = "lib";
298         final String JavaDoc installDirName = "install";
299         final String JavaDoc templateDirName = "templates";
300         final String JavaDoc mimeTemplateFileName = "mime.types.template";
301
302         String JavaDoc [] fileNames = new String JavaDoc[] {INSTALL_ROOT, libDirName,
303             installDirName, templateDirName, mimeTemplateFileName};
304         return ( StringUtils.makeFilePath(fileNames, false) );
305     }
306
307     /**
308      * This method is a wrapper over the other routine to get the port.
309      * It provides logging support and default ports.
310      * @param integer that caller indicates to return in case of a failure.
311      * @return a free port if available, the passed port otherwise.
312     */

313     private int getFreePort(int defaultPort) {
314         int port = NetUtils.getFreePort();
315         if (port == 0) {
316             /* log the stuff */
317             sLogger.log(Level.SEVERE, "general.free_port_failed");
318             return defaultPort;
319         }
320         else {
321             Integer JavaDoc portInteger = new Integer JavaDoc(port);
322             sLogger.log(Level.INFO, "general.free_port", portInteger);
323             return port;
324         }
325     }
326
327     /** Method to check whether the given port has clash with the
328      * http ports of other instances. It checks in the server.xml
329      * of various instances for this.*/

330
331     private boolean portTakenByHTTP(int port) {
332         boolean portTaken = true;
333         String JavaDoc portString = "" + port;
334         String JavaDoc[] instances = getInstanceNames(true);
335         /* count admin server also for this purpose */
336         try {
337             for (int i = 0 ; i < instances.length ; i++) {
338                 String JavaDoc instanceName = instances[i];
339                 InstanceEnvironment inst =
340                         new InstanceEnvironment(instanceName);
341                 String JavaDoc backURL = inst.getConfigFilePath();
342                 ConfigContext context = ConfigFactory.
343                         createConfigContext(backURL);
344                 Config rootElement = ServerBeansFactory.getConfigBean(context);
345
346                 HttpService httpService = rootElement.getHttpService();
347                 HttpListener[] httpListeners =
348                         httpService.getHttpListener();
349                 for (int j = 0 ; j < httpListeners.length ; j++) {
350                     String JavaDoc aPort = httpListeners[j].getPort();
351                     aPort = aPort.trim();
352                     sLogger.log(Level.FINE, "port = " + aPort);
353                     if (aPort.equals(portString)) {
354                         sLogger.log(Level.WARNING,
355                                 "general.port_occupied", instanceName);
356                         return portTaken;
357                     }
358                 }
359             }
360         }
361         catch (Exception JavaDoc e) {
362             sLogger.log(Level.WARNING, "general.port_derivation_failed", e);
363         }
364         return ( false );
365     }
366
367     /**
368      * Checks whether this port is occupied by any of the orb listeners.
369     */

370     private boolean portTakenByORB(int port) {
371         boolean portTaken = true;
372         String JavaDoc portString = "" + port;
373         String JavaDoc[] instances = getInstanceNames(true);
374         /* count admin server also for this purpose */
375         try {
376             for (int i = 0 ; i < instances.length ; i++) {
377                 String JavaDoc instanceName = instances[i];
378                 InstanceEnvironment inst =
379                         new InstanceEnvironment(instanceName);
380                 String JavaDoc backURL = inst.getConfigFilePath();
381                 ConfigContext context = ConfigFactory.
382                         createConfigContext(backURL);
383
384                 Config rootElement = ServerBeansFactory.getConfigBean(context);
385
386                 IiopService iiopService = rootElement.getIiopService();
387                 IiopListener[] iiopListeners = iiopService.getIiopListener();
388                 for (int j = 0 ; j < iiopListeners.length ; j++) {
389                     String JavaDoc aPort = iiopListeners[j].getPort();
390                     aPort = aPort.trim();
391                     sLogger.log(Level.FINE, "port = " + aPort);
392                     if (aPort.equals(portString)) {
393                         sLogger.log(Level.WARNING,
394                                 "general.port_occupied", instanceName);
395                         return portTaken;
396                     }
397                 }
398             }
399         }
400         catch (Exception JavaDoc e) {
401             sLogger.log(Level.WARNING, "general.port_derivation_failed", e);
402         }
403         return ( false );
404     }
405
406
407     /** Checks whether this port is taken by jms provider (imq broker).
408      */

409     private boolean portTakenByJMS(int port) {
410         boolean portTaken = true;
411         String JavaDoc portString = "" + port;
412         String JavaDoc[] instances = getInstanceNames(true);
413         /* count admin server also for this purpose */
414         try {
415             for (int i = 0 ; i < instances.length ; i++) {
416                 String JavaDoc instanceName = instances[i];
417                 InstanceEnvironment inst =
418                         new InstanceEnvironment(instanceName);
419                 String JavaDoc backURL = inst.getConfigFilePath();
420                 ConfigContext context = ConfigFactory.
421                         createConfigContext(backURL);
422                 JmsHost jmsHost = ServerBeansFactory.getJmsHostBean(context);
423                 String JavaDoc aPort = jmsHost.getPort();
424                 aPort = aPort.trim();
425                 sLogger.log(Level.FINE, "port = " + aPort);
426                 if (aPort.equals(portString)) {
427                     sLogger.log(Level.WARNING,
428                             "general.port_occupied", instanceName);
429                     return portTaken;
430                 }
431             }
432         }
433         catch (Exception JavaDoc e) {
434             sLogger.log(Level.WARNING, "general.port_derivation_failed", e);
435         }
436         return ( false );
437     }
438     /**
439      * Provides the domain name from the domain root
440      */

441     public String JavaDoc getDomainName(){
442         File JavaDoc domainRoot = new File JavaDoc(INSTANCE_CFG_ROOT);
443         return domainRoot.getName();
444     }
445
446     public String JavaDoc getInstanceUser(InstanceEnvironment env) throws IOException JavaDoc
447     {
448         /*
449             Need an alternative. PE conf does'nt include init.conf.
450             Ramakanth 04/23/2003
451          */

452         /*
453         if (env == null)
454         {
455             throw new IllegalArgumentException("env cant be null");
456         }
457         InitConfFileBean initConf = new InitConfFileBean();
458         initConf.readConfig(env.getInitFilePath());
459         String instanceUser = initConf.get_mag_var("User");
460         return instanceUser;
461         */

462         return System.getProperty("user.name");
463     }
464
465     /* for quick test please uncomment */
466 /*
467     public static void main(String args[]) throws Exception {
468      Logger logger = Logger.getLogger(AdminConstants.kLoggerName);
469
470         logger.log(Level.INFO,"Tests for com.sun.aas.instanceRoot given on command line...");
471         ServerManager sm = ServerManager.instance();
472         int num = sm.getNumInstances(false);
473         logger.log(Level.INFO,"No of instances excluding admin is = " + num);
474         String dom = sm.getDomainName();
475         System.out.println("Domain is : " + dom+"\n");
476         String[] instances = sm.getInstanceNames(false);
477         for (int i = 0 ; i < num ; i++) {
478             logger.log(Level.INFO,"instance id = " + instances[i]);
479         }
480         num = sm.getNumInstances(true);
481         //logger.log(Level.INFO,"No of instances including admin is = " + num);
482         instances = sm.getInstanceNames(true);
483         for (int j = 0 ; j < num ; j++) {
484             //logger.log(Level.INFO,"instance id = " + instances[j]);
485         }
486         //logger.log(Level.INFO,"The instance with name ias1 exists: " + sm.instanceExists("ias1"));
487         sm.deleteServerInstance("ias1");
488         sm.deleteServerInstance("admserv");
489     }
490 */

491     /* for quick test please uncomment */
492 }
493
Popular Tags