Search in sources :

Example 11 with RemoteCLICommand

use of com.sun.enterprise.admin.cli.remote.RemoteCLICommand in project Payara by payara.

the class SynchronizeInstanceCommand method synchronizeInstance.

/**
 * Synchronize this server instance.  Return true if server is synchronized.
 * Return false if synchronization failed, but no files were changed
 * (meaning that it is ok to bring the server up).
 * Throw a CommandException if synchronization failed in such a way that
 * instance startup should not be attempted.
 */
protected boolean synchronizeInstance() throws CommandException {
    File dasProperties = getServerDirs().getDasPropertiesFile();
    if (logger.isLoggable(Level.FINER))
        logger.finer("das.properties: " + dasProperties);
    if (!dasProperties.exists()) {
        logger.info(Strings.get("Sync.noDASConfigured", dasProperties.toString()));
        return false;
    }
    setDasDefaults(dasProperties);
    /*
         * Create the remote command object that we'll reuse for each request.
         */
    /*
         * Because we reuse the command, we also need to reuse the auth token
         * (if one is present).
         */
    final String origAuthToken = programOpts.getAuthToken();
    if (origAuthToken != null) {
        programOpts.setAuthToken(AuthTokenManager.markTokenForReuse(origAuthToken));
    }
    syncCmd = new RemoteCLICommand("_synchronize-files", programOpts, env);
    syncCmd.setFileOutputDirectory(instanceDir);
    /*
         * The sync state file records the fact that we're in the middle
         * of a synchronization attempt.  When we're done, we remove it.
         * If we crash, it will be left behind, and the next sync attempt
         * will notice it and force a full sync.
         */
    File syncState = new File(instanceDir, SYNC_STATE_FILE);
    boolean doFullSync = false;
    if (sync.equals("normal") && syncState.exists()) {
        String lastSync = DateFormat.getDateTimeInstance().format(new Date(syncState.lastModified()));
        logger.info(Strings.get("Sync.fullRequired", lastSync));
        doFullSync = true;
    }
    /*
         * Create the sync state file to indicate that
         * we've started synchronization.  If the file
         * already exists (e.g., from a previous failed
         * synchronization attempt), that's fine.
         */
    try {
        syncState.createNewFile();
    } catch (IOException ex) {
        logger.warning(Strings.get("Sync.cantCreateSyncState", syncState));
    }
    /*
         * If --sync full, we remove all local state related to the instance,
         * then do a sync.  We only remove the local directories that are
         * synchronized from the DAS; any other local directories (logs,
         * instance-private state) are left alone.
         */
    if (sync.equals("full") || doFullSync) {
        if (logger.isLoggable(Level.FINE))
            logger.fine(Strings.get("Instance.fullsync", instanceName));
        removeSubdirectory("config");
        removeSubdirectory("applications");
        removeSubdirectory("generated");
        removeSubdirectory("lib");
        removeSubdirectory("docroot");
    }
    File domainXml = new File(new File(instanceDir, "config"), "domain.xml");
    long dtime = domainXml.exists() ? domainXml.lastModified() : -1;
    File docroot = new File(instanceDir, "docroot");
    CommandException exc = null;
    try {
        /*
             * First, synchronize the config directory.
             */
        SyncRequest sr = getModTimes("config", SyncLevel.FILES);
        synchronizeFiles(sr);
        /*
             * Was domain.xml updated?
             * If not, we're all done.
             */
        if (domainXml.lastModified() == dtime) {
            if (logger.isLoggable(Level.FINE))
                logger.fine(Strings.get("Sync.alreadySynced"));
            if (!syncState.delete())
                logger.warning(Strings.get("Sync.cantDeleteSyncState", syncState));
            /*
                 * Note that we earlier marked the token for reuse.  It's OK
                 * to return immediately here with the DAS still willing to
                 * accept the same token again.  The token will expire and be
                 * cleaned up in a little while and it was never exposed in a
                 * way that could be intercepted and used illicitly.
                 */
            return true;
        }
        /*
             * Now synchronize the applications.
             */
        sr = getModTimes("applications", SyncLevel.DIRECTORY);
        synchronizeFiles(sr);
        /*
             * Did we get any archive files?  If so,
             * have to unzip them in the applications
             * directory.
             */
        File appsDir = new File(instanceDir, "applications");
        File archiveDir = new File(appsDir, "__internal");
        for (File adir : FileUtils.listFiles(archiveDir)) {
            File[] af = FileUtils.listFiles(adir);
            if (af.length != 1) {
                if (logger.isLoggable(Level.FINER))
                    logger.finer("IGNORING " + adir + ", # files " + af.length);
                continue;
            }
            File archive = af[0];
            File appDir = new File(appsDir, adir.getName());
            if (logger.isLoggable(Level.FINER))
                logger.finer("UNZIP " + archive + " TO " + appDir);
            try {
                expand(appDir, archive);
            } catch (Exception ex) {
            }
        }
        FileUtils.whack(archiveDir);
        /*
             * Next, the libraries.
             * We assume there's usually very few files in the
             * "lib" directory so we check them all individually.
             */
        sr = getModTimes("lib", SyncLevel.RECURSIVE);
        synchronizeFiles(sr);
        /*
             * Next, the docroot.
             * The docroot could be full of files, so we only check
             * one level.
             */
        sr = getModTimes("docroot", SyncLevel.DIRECTORY);
        synchronizeFiles(sr);
        /*
             * Check any subdirectories of the instance config directory.
             * We only expect one - the config-specific directory,
             * but since we don't have an easy way of knowing the
             * name of that directory, we include them all.  The
             * DAS will tell us to remove anything that shouldn't
             * be there.
             */
        sr = new SyncRequest();
        sr.instance = instanceName;
        sr.dir = "config-specific";
        File configDir = new File(instanceDir, "config");
        for (File f : configDir.listFiles()) {
            if (!f.isDirectory())
                continue;
            getFileModTimes(f, configDir, sr, SyncLevel.DIRECTORY);
        }
        /*
             * Before sending the last sync request revert to using the original
             * auth token, if one is present.  The token would be retired
             * later when it expires anyway, but this is just a little cleaner.
             */
        if (origAuthToken != null) {
            syncCmd.getProgramOptions().setAuthToken(origAuthToken);
        }
        synchronizeFiles(sr);
    } catch (ConnectException cex) {
        if (logger.isLoggable(Level.FINER))
            logger.finer("Couldn't connect to DAS: " + cex);
        /*
             * Don't chain the exception, otherwise asadmin will think it
             * it was a connect failure and will list the closest matching
             * local command.  Not what we want here.
             */
        exc = new CommandException(Strings.get("Sync.connectFailed", cex.getMessage()));
    } catch (CommandException ex) {
        if (logger.isLoggable(Level.FINER))
            logger.finer("Exception during synchronization: " + ex);
        exc = ex;
    }
    if (exc != null) {
        /*
             * Some unexpected failure.  If the domain.xml hasn't
             * changed, assume no local state has changed and it's safe
             * to remove the sync state file.  Otherwise, something has
             * changed, and we don't know how much has changed, so leave
             * the sync state file so we'll do a full sync the next time.
             * If nothing has changed, allow the server to come up.
             */
        if (domainXml.exists() && domainXml.lastModified() == dtime && docroot.isDirectory()) {
            // nothing changed and sync has completed at least once
            if (!syncState.delete())
                logger.warning(Strings.get("Sync.cantDeleteSyncState", syncState));
            return false;
        }
        throw exc;
    }
    /*
         * Success!  Remove sync state file.
         */
    if (!syncState.delete())
        logger.warning(Strings.get("Sync.cantDeleteSyncState", syncState));
    return true;
}
Also used : SyncRequest(com.sun.enterprise.util.cluster.SyncRequest) RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 12 with RemoteCLICommand

use of com.sun.enterprise.admin.cli.remote.RemoteCLICommand in project Payara by payara.

the class ListDomainsCommand method getStatus.

private DomainInfo getStatus(String dn) throws IOException, CommandException {
    setDomainName(dn);
    initDomain();
    DomainInfo di = new DomainInfo();
    di.adminAddr = getAdminAddress();
    programOpts.setHostAndPort(di.adminAddr);
    di.status = isThisDAS(getDomainRootDir());
    if (di.status) {
        di.statusMsg = STRINGS.get("list.domains.StatusRunning", dn);
        try {
            RemoteCLICommand cmd = new RemoteCLICommand("_get-restart-required", programOpts, env);
            String restartRequired = cmd.executeAndReturnOutput("_get-restart-required");
            di.restartRequired = Boolean.parseBoolean(restartRequired.trim());
            if (di.restartRequired) {
                di.statusMsg = STRINGS.get("list.domains.StatusRestartRequired", dn);
            }
        } catch (Exception ex) {
        }
    } else {
        di.statusMsg = STRINGS.get("list.domains.StatusNotRunning", dn);
    }
    return di;
}
Also used : RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand) IOException(java.io.IOException) DomainException(com.sun.enterprise.admin.servermgmt.DomainException)

Example 13 with RemoteCLICommand

use of com.sun.enterprise.admin.cli.remote.RemoteCLICommand in project Payara by payara.

the class LocalServerCommand method getUptime.

/**
 * Get uptime from the server.
 */
protected final long getUptime() throws CommandException {
    RemoteCLICommand cmd = new RemoteCLICommand("uptime", programOpts, env);
    String up = cmd.executeAndReturnOutput("uptime", "--milliseconds").trim();
    long up_ms = parseUptime(up);
    if (up_ms <= 0) {
        throw new CommandException(strings.get("restart.dasNotRunning"));
    }
    logger.log(Level.FINER, "server uptime: {0}", up_ms);
    return up_ms;
}
Also used : CommandException(org.glassfish.api.admin.CommandException) RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand)

Example 14 with RemoteCLICommand

use of com.sun.enterprise.admin.cli.remote.RemoteCLICommand in project Payara by payara.

the class LocalServerCommand method isRestartable.

/**
 * See if the server is restartable
 * As of March 2011 -- this only returns false if a passwordfile argument was given
 * when the server started -- but it is no longer available - i.e. the user
 * deleted it or made it unreadable.
 */
protected final boolean isRestartable() throws CommandException {
    // false negative is worse than false positive.
    // there is one and only one case where we return false
    RemoteCLICommand cmd = new RemoteCLICommand("_get-runtime-info", programOpts, env);
    ActionReport report = cmd.executeAndReturnActionReport("_get-runtime-info");
    if (report != null) {
        String val = report.findProperty("restartable_value");
        if (ok(val) && val.equals("false"))
            return false;
    }
    return true;
}
Also used : ActionReport(org.glassfish.api.ActionReport) RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand)

Example 15 with RemoteCLICommand

use of com.sun.enterprise.admin.cli.remote.RemoteCLICommand in project Payara by payara.

the class LocalServerCommand method isThisServer.

/**
 * See if the server is alive and is the one at the specified directory.
 *
 * @return true if it's the DAS at this domain directory
 */
protected final boolean isThisServer(File ourDir, String directoryKey) {
    if (!ok(directoryKey))
        throw new NullPointerException();
    ourDir = getUniquePath(ourDir);
    logger.log(Level.FINER, "Check if server is at location {0}", ourDir);
    try {
        RemoteCLICommand cmd = new RemoteCLICommand("__locations", programOpts, env);
        ActionReport report = cmd.executeAndReturnActionReport(new String[] { "__locations" });
        String theirDirPath = report.findProperty(directoryKey);
        logger.log(Level.FINER, "Remote server has root directory {0}", theirDirPath);
        if (ok(theirDirPath)) {
            File theirDir = getUniquePath(new File(theirDirPath));
            return theirDir.equals(ourDir);
        }
        return false;
    } catch (Exception ex) {
        return false;
    }
}
Also used : ActionReport(org.glassfish.api.ActionReport) SmartFile(com.sun.enterprise.universal.io.SmartFile) RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand) MiniXmlParserException(com.sun.enterprise.universal.xml.MiniXmlParserException) CommandException(org.glassfish.api.admin.CommandException)

Aggregations

RemoteCLICommand (com.sun.enterprise.admin.cli.remote.RemoteCLICommand)26 CommandException (org.glassfish.api.admin.CommandException)8 ActionReport (org.glassfish.api.ActionReport)4 ArrayList (java.util.ArrayList)3 DomainException (com.sun.enterprise.admin.servermgmt.DomainException)2 BackupException (com.sun.enterprise.backup.BackupException)2 BackupWarningException (com.sun.enterprise.backup.BackupWarningException)2 IOException (java.io.IOException)2 RemoteCommand (com.sun.enterprise.admin.cli.remote.RemoteCommand)1 SmartFile (com.sun.enterprise.universal.io.SmartFile)1 MiniXmlParserException (com.sun.enterprise.universal.xml.MiniXmlParserException)1 SyncRequest (com.sun.enterprise.util.cluster.SyncRequest)1 File (java.io.File)1 ConnectException (java.net.ConnectException)1 Singleton (javax.inject.Singleton)1 MessagePart (org.glassfish.api.ActionReport.MessagePart)1 ParamModel (org.glassfish.api.admin.CommandModel.ParamModel)1 CommandValidationException (org.glassfish.api.admin.CommandValidationException)1