FileDocCategorySizeDatePackage
StartDomainCommand.javaAPI DocGlassfish v2 API29386Fri Jun 29 05:21:20 BST 2007com.sun.enterprise.cli.commands

StartDomainCommand

public class StartDomainCommand extends BaseLifeCycleCommand
This is a sample Deploy command
version
$Revision: 1.28 $

Fields Summary
private static final String
SERVER_LOG_FILE_NAME
private static final String
LOGS_DIR
private static final String
VERBOSE
private static final String
APPLICATION_SERVER_8_0
private static final String
DTD_FILE_8_0
private static final String
DTD_FILE_8_1
private static final long
UPGRADE_TIMEOUT
private static final long
UPDATECENTER_TIMEOUT
private String
domainName
private com.sun.enterprise.admin.servermgmt.DomainConfig
config
private com.sun.enterprise.config.ConfigContext
cc
private com.sun.enterprise.admin.servermgmt.DomainsManager
mgr
private String
adminPwdAlias
private boolean
doBackupMessage
private static final boolean
enableBackups
Constructors Summary
Methods Summary
private voidcheckAndExecuteUpgrade(java.lang.String domainName)
This api checks and executes the upgrade commands. This api invokes checkIfVersion80(). If version is 8.0, then it will try to invoke asupgrade command.

domainName
-- name of domain, this parameter is required to figure out the version of domain.
throws
CommandException if error invoking asupgrade

        final String domainDir = getDomainsRoot();
        CLILogger.getInstance().printDebugMessage("domainDir = " + domainDir);
        final String installDir = System.getProperty(SystemPropertyConstants.INSTALL_ROOT_PROPERTY);
        CLILogger.getInstance().printDebugMessage("installDir = " + installDir);
        CLILogger.getInstance().printDebugMessage("domainName = " + domainName);
        final InplaceDomainUpgradeHandler ipuh =
                new InplaceDomainUpgradeHandler(config);
        if (ipuh.needsUpgrade()) {
              String domainDirOption = getOption(DOMAINDIR);
              String domainsDirProperty = System.getProperty(SystemPropertyConstants.DOMAINS_ROOT_PROPERTY);

              if (domainDirOption != null && domainDirOption.indexOf(domainsDirProperty) == -1){
                    throw new CommandException(getLocalizedString("UpgradeUnsupported", new Object[]{domainsDirProperty}));
                }
            try {
                final String sPasswordFile = createPasswordFileText();
                final String[] upgradeCmd;
                /*Need to prefix the upgrade command with CMD /c in case of Windows*/
                if(OS.isWindows())
                        upgradeCmd = new String[]    {"CMD",
                                                        "/c",
                                                      installDir + File.separator +
                                                      "bin" + File.separator +
                                                      "asupgrade", "-c", "-s",
                                                      domainDir+File.separator+domainName,
                                                      "-t", installDir +File.separator+ "domains",
                                                      "-noprompt" };
                else
                            upgradeCmd = new String[] {installDir + File.separator +
                                                      "bin" + File.separator +
                                                      "asupgrade", "-c", "-s",
                                                      domainDir+File.separator+domainName,
                                                      "-t", installDir +File.separator+ "domains",
                                                      "-noprompt" };

                ProcessExecutor pe = new ProcessExecutor(upgradeCmd, UPGRADE_TIMEOUT);
                /*
                 * ProcessExecutor's constructor replaces all the '/'s with '\' in case the OS is Windows.
                 * We don't want that for CMD /c. Hence need to replace it again
                 */
                if(OS.isWindows())
                        upgradeCmd[1] ="/c";

                System.out.println(getLocalizedString("StartingUpgrade"));
                pe.execute();  // timeout in 600sec or 10min
                Process process = pe.getSubProcess();
                int exitValue = process.waitFor();
                if (exitValue != 0) {
                    System.out.println(getLocalizedString("UpgradeFailed"));
                    throw new CommandException(getLocalizedString("UpgradeFailed"));
                }else {
                    System.out.println(getLocalizedString("UpgradeSuccessful"));
                    ipuh.touchUpgradedToFile();
                }
            }
            catch (Exception e) {
                    //e.printStackTrace();
                throw new CommandException(getLocalizedString("UpgradeFailed"), e);
            }
        } else {
            try {
                ipuh.touchUpgradedToFile();
            } catch(final IOException ioe) {
                throw new CommandException(ioe);
            }
        }
    
private booleancheckIfRunning()
If already running, then return true.

        // note that isNotRunning declares 'throws Exception' !!!

        if(!isNotRunning(mgr, config))
        {
            // bnevins Oct 2004
            // This has officially been defined as an error.  So we have to throw an Exception.

            // bnevins Sept 2005
            // we don't want to print a message saying that they should try
            // using the backup config for this situation.
            CLILogger.getInstance().printDetailMessage(getLocalizedString("CannotStartDomainAlreadyRunning",
                   new Object[] {domainName}));
            return true;
        }
        return false;
    
private voidcheckIfStopping()

        if(isStopping(mgr, config))
        {
            throw new CommandException(getLocalizedString("CannotStartStoppingDomain",
                   new Object[] {domainName}));
        }
    
private booleancheckIfVersion80(java.lang.String domainName, java.lang.String domainDir, java.lang.String installDir)
This api check if the domain version is 8.0 or 8.1.

domainName
- domain name to figure out the version
domainDir
- domain directory
installDir
- install directory
throws
CommandExcpetion if error finding version

        final PEFileLayout layout = new PEFileLayout(config);
        final File domainFile = layout.getDomainConfigFile();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        try {

            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
                                      ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse(domainFile);
            String publicID = adminServerDoc.getDoctype().getPublicId();
            String systemID = adminServerDoc.getDoctype().getSystemId();
            CLILogger.getInstance().printDebugMessage("publicID = " + publicID);
            CLILogger.getInstance().printDebugMessage("systemID = " + systemID);
                //if domain.xml systemID=sun-domain_1_0 then the version is 8.0
                //if domain.xml systemID=sun-domain_1_1 then the version is 8.1
            if (publicID.indexOf(APPLICATION_SERVER_8_0) != -1 &&
                (systemID.indexOf(DTD_FILE_8_0) != -1 ||
                 systemID.indexOf(DTD_FILE_8_1) != -1 )) {
                return true;
            } else {
                return false;
            }
        }
        catch (Exception e)
        {
                //do nothing for now
                //e.printStackTrace();
        }
        return false;
    
private voidcheckOnBackup(com.sun.enterprise.admin.servermgmt.DomainConfig config)

        // the try/catch is extra protection because we're being
        // called from inside a catch block.

        if(config == null)
            return; // nothing we can do here...

        try
        {
            File domainsRoot    = new File(config.getRepositoryRoot());
            File domainRoot     = new File(domainsRoot, config.getDomainName());
            File configDir      = new File(domainRoot, "config");
            File domainxml      = new File(configDir, "domain.xml");
            File backup         = new File(configDir, "domain_bu.xml");

            if(backup.exists())
                pr("NoStartAdvice", backup.getAbsolutePath(), domainxml.getAbsolutePath());
        }
        catch(Exception e)
        {
        }
    
private voidconfigureAddons()

        try {
            AddonControl ac = new AddonControl();
            String domainInstanceRoot = getDomainsRoot() + File.separator + getDomainName();
            ac.configureDAS(new File(domainInstanceRoot));
        }catch(Throwable t) {
            CLILogger.getInstance().printDetailMessage(t.getLocalizedMessage());
        }

    
private java.lang.StringcreatePasswordFileText()
create a temporary passwordfile.txt that contains admin password and master password that is passed to asupgrade command.

        //create a temp passwordfile
        final File fPasswordFile = File.createTempFile("passwordfile", null);
        fPasswordFile.deleteOnExit();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                                          new FileWriter(fPasswordFile.toString())));
        out.println("AS_ADMIN_PASSWORD=" + "adminadmin");
        // hardcoding password because that's the best I can do here (Kedar)
        out.println("AS_ADMIN_MASTERPASSWORD=" + (String)config.get(DomainConfig.K_MASTER_PASSWORD));
        out.close();
        return fPasswordFile.toString();
    
private java.lang.StringgetDomainLogFile(java.lang.String domainName)
Returns the log file location for a domain

throws
CommandException

        String logFile = getDomainsRoot() + File.separator + domainName +
                         File.separator + LOGS_DIR + File.separator + SERVER_LOG_FILE_NAME;
        return logFile;
    
private voidinit()

        mgr = getFeatureFactory().getDomainsManager();
        config = getDomainConfig(domainName);
        config.setRefreshConfingContext(false);
        this.validateDomain();
        CLILogger.getInstance().printDetailMessage(getLocalizedString("StartingDomain",
                                         new Object[] {domainName}));
        if (!getBooleanOption(VERBOSE))
        {
            CLILogger.getInstance().printDetailMessage(getLocalizedString("LogRedirectedTo",
                new Object[] {getDomainLogFile(domainName)}));
        }
        this.checkAndExecuteUpgrade(domainName);
        this.configureAddons();
        /* Implementation note:
         It is important to note that the following call is made after all
         the possible changes to domain.xml (from invocation of asadmin start-domain to 
         invocation of launcher) are done. The following call to create the
         config context "caches" the config context and hence the config context
         is not recreated. It is important to preserve that call. 
        */
        final String xmlPath = new PEFileLayout(config).
            getDomainConfigFile().getAbsolutePath();
        this.cc = ConfigFactory.
            createConfigContext(xmlPath);

        
            //get port from ConfigFactory
        final HttpListener admin = ServerHelper.getHttpListener(cc,
                                   SystemPropertyConstants.DEFAULT_SERVER_INSTANCE_NAME,
                                   ServerHelper.ADMIN_HTTP_LISTNER_ID);
        if (admin != null) {
            final String port = admin.getPort();
                //set port and host options so that password can be retrieved from .asadminpass
            setOption("port", port);
            setOption("host", "localhost");            
        }
    
private booleanisNotRunning(com.sun.enterprise.admin.servermgmt.DomainsManager mgr, com.sun.enterprise.admin.servermgmt.DomainConfig cfg)

        // note that checking for kInstanceRunningCode is not desired here

        InstancesManager im = mgr.getInstancesManager(cfg);
        int state = im.getInstanceStatus();

        return state == Status.kInstanceNotRunningCode;
    
private booleanisStopping(com.sun.enterprise.admin.servermgmt.DomainsManager mgr, com.sun.enterprise.admin.servermgmt.DomainConfig cfg)

        InstancesManager im = mgr.getInstancesManager(cfg);
        int state = im.getInstanceStatus();

        return state == Status.kInstanceStoppingCode;
    
private voidpr(java.lang.String id, java.lang.Object o)

        String s = getLocalizedString(id, new Object[]{ o } );
        CLILogger.getInstance().printDetailMessage(s);
    
private voidpr(java.lang.String id, java.lang.Object o1, java.lang.Object o2)

        String s = getLocalizedString(id, new Object[]{ o1, o2 } );
        CLILogger.getInstance().printDetailMessage(s);
    
public voidrunCommand()
An abstract method that Executes the command

throws
CommandException

        CLILogger.getInstance().printDebugMessage("Launching UpdateCenter Thread");
        final Thread t = new Thread(new UpdateCenter(), "UpdateCenterThread");
        t.start();

        validateOptions();

        String domainName = null;
        try {
            domainName = getDomainName();
        } catch(Exception e)
        {
            CLILogger.getInstance().printDetailMessage(e.getLocalizedMessage());
            domainName = domainName==null?getLocalizedString("Undefined"):domainName;
            throw new CommandException(getLocalizedString("CannotStartDomain",
                       new Object[] {domainName}), e);
        }
        startDomain(domainName);
        if (t.isAlive()) {
            try {
                    //hopefully it'll never reach here
                    //if the updatecenter thread is still alive
                    //then give 0.5 sec more to end the thread before timeout

                    //update center timeout is configurable
                final String ucTo = System.getProperty("UPDATECENTER_TIMEOUT");
                long waitForUc = UPDATECENTER_TIMEOUT;
                if (ucTo != null) {
                    try {
                        waitForUc  = Long.parseLong(ucTo);
                    }
                    catch (NumberFormatException nfe) {
                        waitForUc = UPDATECENTER_TIMEOUT;
                    }
                    if (waitForUc < 1) waitForUc = UPDATECENTER_TIMEOUT;
                }
                t.join(waitForUc);
            }
            catch (InterruptedException ie) {
                    //ignore any exception coming from updatecenter
                    //since we want to want to interfere with domain startup
            }
        }
    
private voidsaveCopyOfConfig(com.sun.enterprise.admin.servermgmt.DomainConfig config)

        File domainsRoot    = new File(config.getRepositoryRoot());
        File domainRoot     = new File(domainsRoot, config.getDomainName());
        File configDir      = new File(domainRoot, "config");
        File domainxml      = new File(configDir, "domain.xml");
        File backup         = new File(configDir, "domain_bu.xml");

        try
        {
            FileUtils.copy(domainxml.getAbsolutePath(), backup.getAbsolutePath());
            pr("ConfigBackedupOK", backup.getAbsolutePath());
        }
        catch(Exception e)
        {
            pr("ConfigBackedupNot", domainxml.getAbsolutePath(), backup.getAbsolutePath());
        }
    
private voidsaveExtraPasswordOptions()

            String[] extraPasswordOptions = mgr.getExtraPasswordOptions(config);
            if (extraPasswordOptions != null) {
                config.put(DomainConfig.K_EXTRA_PASSWORDS, getExtraPasswords(extraPasswordOptions));
            }
    
public voidstartDomain(java.lang.String DomainName)

        domainName = DomainName;
        long start  = System.currentTimeMillis();

        try
        {
            doBackupMessage = false;
            init();
            if (!checkIfRunning())
            {
                checkIfStopping();

                try
                {
                    validateAdminPassword();
                }
                catch(Exception e)
                {
                    throw new CommandValidationException(getLocalizedString(
                            "BadUsernameOrPassword"));
                }
                try
                {
                    validateMasterPassword();
                }
                catch(Exception e)
                {
                    throw new CommandValidationException(getLocalizedString(
                            "BadMasterPassword"));
                }
                saveExtraPasswordOptions();
                doBackupMessage = true;
                mgr.startDomain(config);

                if(enableBackups)
                {
                    saveCopyOfConfig(config);
                }

                if (startupNeedsAdminCreds()) {
                    CLILogger.getInstance().printDetailMessage(getLocalizedString("DomainStarted",
                                                                                  new Object[] {domainName}));
                } else {
                    CLILogger.getInstance().printDetailMessage(getLocalizedString("DomainReady",
                                                                                  new Object[] {domainName}));
                }
                final boolean terse = getBooleanOption(TERSE);
                new DomainReporter(config, terse, cc).report();
                long msec = System.currentTimeMillis() - start;

                    /* convert milliseconds duration to xxx.y seconds, where y is rounded off properly.
                     * E.g.
                     27999 -> 28.0
                     27449 --> 27.4
                     27450 -> 27.5
                    */
                double sec = ((double)Math.round( ((double)msec) / 100.0)) / 10.0;
                CLILogger.getInstance().printDebugMessage(getLocalizedString("DomainStartTime",
                                                                             new Object[] { sec }));
            }
        }
        catch(Exception e)
        {
            CLILogger.getInstance().printDetailMessage(e.getLocalizedMessage());

			if(enableBackups)
			{
				if(doBackupMessage)
					checkOnBackup(config);
			}

            throw new CommandException(getLocalizedString("CannotStartDomain",
                       new Object[] {domainName}), e);
        }     
    
private booleanstartupNeedsAdminCreds()

        try {
            return ( ServerHelper.isClusterAdminSupported(this.cc) );
        } catch (final ConfigException ce) {
            throw new RuntimeException (ce); //Unrecoverable
        }
    
private voidvalidateAdminPassword()

        //In PE, the admin user and password are options that are not needed and as
        //such are ignored.

        if (startupNeedsAdminCreds()) {
            config.put(DomainConfig.K_USER, getUser());
            config.put(DomainConfig.K_PASSWORD, getPassword());
            //Validate the admin user and password that was provided.
            if (getOption(S1ASCommand.PASSWORDFILE) != null )
                adminPwdAlias = RelativePathResolver.getAlias( (String)config.get(DomainConfig.K_PASSWORD));
            if (adminPwdAlias==null) {
                mgr.validateAdminUserAndPassword(config);
            }
        }
    
private voidvalidateDomain()

        // if the next line throws -- print backup availability message
        mgr.validateDomain(config, true);
    
private voidvalidateMasterPassword()

        final String masterPassword = getMasterPassword(new RepositoryManager(), config);
        config.put(DomainConfig.K_MASTER_PASSWORD, masterPassword);

        mgr.validateMasterPassword(config);
        if (adminPwdAlias!=null) {
            String domainsRoot =  (String)config.get(DomainConfig.K_DOMAINS_ROOT);
            String keyStoreFile= domainsRoot+ File.separator + domainName +  File.separator + "config" + File.separator +
                      PasswordAdapter.PASSWORD_ALIAS_KEYSTORE;
            PasswordAdapter p =
                new PasswordAdapter(keyStoreFile, masterPassword.toCharArray());
            String clearPwd = p.getPasswordForAlias(adminPwdAlias);
            config.put(DomainConfig.K_PASSWORD, clearPwd);
            mgr.validateAdminUserAndPassword(config);
        }
    
public booleanvalidateOptions()
An abstract method that validates the options on the specification in the xml properties file This method verifies for the correctness of number of operands and if all the required options are supplied by the client.

return
boolean returns true if success else returns false


                                                           
        
    
        return super.validateOptions();