Search in sources :

Example 56 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class StartDomainsCommand method executeCommand.

@Override
protected int executeCommand() throws CommandException {
    try {
        String[] domains = domainName0.split(",");
        for (String domainName : domains) {
            setDomainName(domainName);
            super.initDomain();
            programOpts.setHostAndPort(getAdminAddress());
            super.executeCommand();
            logger.fine("Started domain " + domainName);
        }
        return 0;
    } catch (Exception ex) {
        throw new CommandException(ex.getLocalizedMessage());
    }
}
Also used : CommandException(org.glassfish.api.admin.CommandException) CommandException(org.glassfish.api.admin.CommandException) CommandValidationException(org.glassfish.api.admin.CommandValidationException)

Example 57 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class StopDomainsCommand method executeCommand.

@Override
protected int executeCommand() throws CommandException {
    try {
        String[] domains = userArgDomainName.split(",");
        for (String domainName : domains) {
            setConfig(domainName);
            RemoteCLICommand cmd = new RemoteCLICommand("stop-domain", programOpts, env);
            logger.fine("Stopping domain " + domainName);
            try {
                cmd.executeAndReturnOutput("stop-domain");
            } catch (Exception e) {
            }
            logger.fine("Stopped domain");
        }
        return 0;
    } catch (Exception ex) {
        throw new CommandException(ex.getLocalizedMessage());
    }
}
Also used : CommandException(org.glassfish.api.admin.CommandException) RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand) CommandException(org.glassfish.api.admin.CommandException) CommandValidationException(org.glassfish.api.admin.CommandValidationException)

Example 58 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class RemoteAdminCommand method initializeDoUpload.

/**
 * Search all the parameters that were actually specified to see
 * if any of them are FILE type parameters.  If so, check for the
 * "--upload" option.
 */
private void initializeDoUpload() throws CommandException {
    boolean sawFile = false;
    boolean sawDirectory = false;
    /*
         * We don't upload directories, even when asked to upload.
         */
    boolean sawUploadableFile = false;
    for (Map.Entry<String, List<String>> param : options.entrySet()) {
        String paramName = param.getKey();
        if (// operands handled below
        paramName.equals("DEFAULT"))
            continue;
        ParamModel opt = commandModel.getModelFor(paramName);
        if (opt != null && (opt.getType() == File.class || opt.getType() == File[].class)) {
            sawFile = true;
            for (String fname : options.get(opt.getName())) {
                final File optionFile = new File(fname);
                sawDirectory |= optionFile.isDirectory();
                sawUploadableFile |= optionFile.isFile();
            }
        }
    }
    // now check the operands for files
    ParamModel operandParam = getOperandModel();
    if (operandParam != null && (operandParam.getType() == File.class || operandParam.getType() == File[].class)) {
        sawFile |= !operands.isEmpty();
        for (String operandValue : operands) {
            final File operandFile = new File(operandValue);
            sawDirectory |= operandFile.isDirectory();
            sawUploadableFile |= operandFile.isFile();
        }
    }
    if (sawFile) {
        logger.finer("Saw a file parameter");
        // found a FILE param, is doUpload set?
        String upString = getOption("upload");
        if (ok(upString))
            doUpload = Boolean.parseBoolean(upString);
        else
            doUpload = !isLocal(host) && sawUploadableFile;
        if (prohibitDirectoryUploads && sawDirectory && doUpload) {
            // oops, can't upload directories
            logger.finer("--upload=" + upString + ", doUpload=" + doUpload);
            throw new CommandException(strings.get("CantUploadDirectory"));
        }
    }
    if (addedUploadOption) {
        logger.finer("removing --upload option");
        // options.remove("upload");    // remove it
        // XXX - no remove method, have to copy it
        ParameterMap noptions = new ParameterMap();
        for (Map.Entry<String, List<String>> e : options.entrySet()) {
            if (!e.getKey().equals("upload"))
                noptions.set(e.getKey(), e.getValue());
        }
        options = noptions;
    }
    logger.finer("doUpload set to " + doUpload);
}
Also used : ParamModel(org.glassfish.api.admin.CommandModel.ParamModel) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) ParameterMap(org.glassfish.api.admin.ParameterMap) InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandException(org.glassfish.api.admin.CommandException) Map(java.util.Map) ParameterMap(org.glassfish.api.admin.ParameterMap) NamedNodeMap(org.w3c.dom.NamedNodeMap) SmartFile(com.sun.enterprise.universal.io.SmartFile) File(java.io.File)

Example 59 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class SSHUtil method validateKeyFile.

/**
 * This method validates either private or public key file. In case of private
 * key, it parses the key file contents to verify if it indeed contains a key
 * @param  file the key file
 * @return success if file exists, false otherwise
 */
public static boolean validateKeyFile(String file) throws CommandException {
    boolean ret = false;
    // if key exists, set prompt flag
    File f = new File(file);
    if (f.exists()) {
        if (!f.getName().endsWith(".pub")) {
            String key = null;
            try {
                key = FileUtils.readSmallFile(file);
            } catch (IOException ioe) {
                throw new CommandException(Strings.get("unable.to.read.key", file, ioe.getMessage()));
            }
            if (!key.startsWith("-----BEGIN ") && !key.endsWith(" PRIVATE KEY-----" + NL)) {
                throw new CommandException(Strings.get("invalid.key.file", file));
            }
        }
        ret = true;
    } else {
        throw new CommandException(Strings.get("key.does.not.exist", file));
    }
    return ret;
}
Also used : IOException(java.io.IOException) CommandException(org.glassfish.api.admin.CommandException) File(java.io.File)

Example 60 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class ClusterCommandHelper method runCommand.

/**
 * Loop through all instances in a cluster and execute a command for
 * each one.
 *
 * @param command       The string of the command to run. The instance
 *                      name will be used as the operand for the command.
 * @param map           A map of parameters to use for the command. May be
 *                      null if no parameters. When the command is
 *                      executed for a server instance, the instance name
 *                      is set as the DEFAULT parameter (operand)
 * @param targetName   The name of the cluster or deployment group containing the instances
 *                      to run the command against.
 * @param context       The AdminCommandContext to use when executing the
 *                      command.
 * @param verbose       true for more verbose output
 * @param rolling       Whether calls should be serialized to help with rolling restarts
 * @return              An ActionReport containing the results
 * @throws CommandException
 */
public ActionReport runCommand(String command, ParameterMap map, String targetName, AdminCommandContext context, boolean verbose, boolean rolling) throws CommandException {
    // When we started
    final long startTime = System.currentTimeMillis();
    Logger logger = context.getLogger();
    ActionReport report = context.getActionReport();
    // Get the cluster specified by clusterName
    Cluster cluster = domain.getClusterNamed(targetName);
    if (cluster == null) {
        DeploymentGroup dg = domain.getDeploymentGroupNamed(targetName);
        if (dg == null) {
            String msg = Strings.get("cluster.command.unknownCluster", targetName);
            throw new CommandException(msg);
        }
    }
    // Get the list of servers in the cluster or deployment group.
    List<Server> targetServers = domain.getServersInTarget(targetName);
    // If the list of servers is empty, say so
    if (targetServers == null || targetServers.isEmpty()) {
        report.setActionExitCode(ExitCode.SUCCESS);
        report.setMessage(Strings.get("cluster.command.noInstances", targetName));
        return report;
    }
    int nInstances = targetServers.size();
    // We will save the name of the instances that worked and did
    // not work so we can summarize our results.
    StringBuilder failedServerNames = new StringBuilder();
    StringBuilder succeededServerNames = new StringBuilder();
    List<String> waitingForServerNames = new ArrayList<>();
    String msg;
    ReportResult reportResult = new ReportResult();
    boolean failureOccurred = false;
    progress = context.getProgressStatus();
    // Save command output to return in ActionReport
    StringBuilder output = new StringBuilder();
    // Optimize the oder of server instances to avoid clumping on nodes
    if (logger.isLoggable(Level.FINE))
        logger.fine(String.format("Original instance list %s", serverListToString(targetServers)));
    targetServers = optimizeServerListOrder(targetServers);
    // Holds responses from the threads running the command
    ArrayBlockingQueue<CommandRunnable> responseQueue = new ArrayBlockingQueue<CommandRunnable>(nInstances);
    int threadPoolSize = 1;
    if (!rolling) {
        // Make the thread pool use the smaller of the number of instances
        // or half the admin thread pool size
        int adminThreadPoolSize = getAdminThreadPoolSize(logger);
        threadPoolSize = Math.min(nInstances, adminThreadPoolSize / 2);
        if (threadPoolSize < 1) {
            threadPoolSize = 1;
        }
    }
    ExecutorService threadPool = Executors.newFixedThreadPool(threadPoolSize);
    if (map == null) {
        map = new ParameterMap();
    }
    msg = String.format("Executing %s on %d instances using a thread pool of size %d: %s", command, nInstances, threadPoolSize, serverListToString(targetServers));
    logger.info(msg);
    msg = Strings.get("cluster.command.executing", command, Integer.toString(nInstances));
    progress.setTotalStepCount(nInstances);
    progress.progress(msg);
    // instance name, and hand it off to the threadpool.
    for (Server server : targetServers) {
        String iname = server.getName();
        waitingForServerNames.add(iname);
        ParameterMap instanceParameterMap = new ParameterMap(map);
        // Set the instance name as the operand for the commnd
        instanceParameterMap.set("DEFAULT", iname);
        ActionReport instanceReport = runner.getActionReport("plain");
        instanceReport.setActionExitCode(ExitCode.SUCCESS);
        CommandInvocation invocation = runner.getCommandInvocation(command, instanceReport, context.getSubject());
        invocation.parameters(instanceParameterMap);
        msg = command + " " + iname;
        logger.info(msg);
        if (verbose) {
            output.append(msg).append(NL);
        }
        // Wrap the command invocation in a runnable and hand it off
        // to the thread pool
        CommandRunnable cmdRunnable = new CommandRunnable(invocation, instanceReport, responseQueue);
        cmdRunnable.setName(iname);
        threadPool.execute(cmdRunnable);
    }
    if (logger.isLoggable(Level.FINE))
        logger.fine(String.format("%s commands queued, waiting for responses", command));
    // Make sure we don't wait longer than the admin read timeout. Set
    // our limit to be 3 seconds less.
    long adminTimeout = RemoteRestAdminCommand.getReadTimeout() - 3000;
    if (adminTimeout <= 0) {
        // This should never be the case
        adminTimeout = 57 * 1000;
    }
    if (logger.isLoggable(Level.FINE))
        logger.fine(String.format("Initial cluster command timeout: %d ms", adminTimeout));
    // Now go get results from the response queue.
    for (int n = 0; n < nInstances; n++) {
        long timeLeft = adminTimeout - (System.currentTimeMillis() - startTime);
        if (timeLeft < 0) {
            timeLeft = 0;
        }
        CommandRunnable cmdRunnable = null;
        try {
            // cmdRunnable = responseQueue.take();
            cmdRunnable = responseQueue.poll(timeLeft, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // This thread has been interrupted. Abort
            threadPool.shutdownNow();
            msg = Strings.get("cluster.command.interrupted", targetName, Integer.toString(n), Integer.toString(nInstances), command);
            logger.warning(msg);
            output.append(msg).append(NL);
            failureOccurred = true;
            // Re-establish interrupted state on thread
            Thread.currentThread().interrupt();
            break;
        }
        if (cmdRunnable == null) {
            // We've timed out.
            break;
        }
        String iname = cmdRunnable.getName();
        waitingForServerNames.remove(iname);
        ActionReport instanceReport = cmdRunnable.getActionReport();
        if (logger.isLoggable(Level.FINE))
            logger.fine(String.format("Instance %d of %d (%s) has responded with %s", n + 1, nInstances, iname, instanceReport.getActionExitCode()));
        if (instanceReport.getActionExitCode() != ExitCode.SUCCESS) {
            // Bummer, the command had an error. Log and save output
            failureOccurred = true;
            failedServerNames.append(iname).append(" ");
            reportResult.failedServerNames.add(iname);
            msg = iname + ": " + instanceReport.getMessage();
            logger.severe(msg);
            output.append(msg).append(NL);
            msg = Strings.get("cluster.command.instancesFailed", command, iname);
            progress.progress(1, msg);
        } else {
            // Command worked. Note that too.
            succeededServerNames.append(iname).append(" ");
            reportResult.succeededServerNames.add(iname);
            progress.progress(1, iname);
        }
    }
    report.setActionExitCode(ExitCode.SUCCESS);
    if (failureOccurred) {
        report.setResultType(List.class, reportResult.failedServerNames);
    } else {
        report.setResultType(List.class, reportResult.succeededServerNames);
    }
    // had one or more failures.
    if (succeededServerNames.length() > 0 && (verbose || failureOccurred)) {
        output.append(NL + Strings.get("cluster.command.instancesSucceeded", command, succeededServerNames));
    }
    if (failureOccurred) {
        // Display summary of failed servers if we have any
        output.append(NL + Strings.get("cluster.command.instancesFailed", command, failedServerNames));
        if (succeededServerNames.length() > 0) {
            // At least one instance started. Warning.
            report.setActionExitCode(ExitCode.WARNING);
        } else {
            // No instance started. Failure
            report.setActionExitCode(ExitCode.FAILURE);
        }
    }
    // Check for server that did not respond
    if (!waitingForServerNames.isEmpty()) {
        msg = Strings.get("cluster.command.instancesTimedOut", command, listToString(waitingForServerNames));
        logger.warning(msg);
        if (output.length() > 0) {
            output.append(NL);
        }
        output.append(msg);
        report.setActionExitCode(ExitCode.WARNING);
    }
    report.setMessage(output.toString());
    threadPool.shutdown();
    return report;
}
Also used : Server(com.sun.enterprise.config.serverbeans.Server) ArrayList(java.util.ArrayList) Cluster(com.sun.enterprise.config.serverbeans.Cluster) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandException(org.glassfish.api.admin.CommandException) Logger(java.util.logging.Logger) ActionReport(org.glassfish.api.ActionReport) CommandInvocation(org.glassfish.api.admin.CommandRunner.CommandInvocation) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ExecutorService(java.util.concurrent.ExecutorService) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup)

Aggregations

CommandException (org.glassfish.api.admin.CommandException)61 File (java.io.File)20 CommandValidationException (org.glassfish.api.admin.CommandValidationException)16 IOException (java.io.IOException)13 ParameterMap (org.glassfish.api.admin.ParameterMap)11 InvalidCommandException (org.glassfish.api.admin.InvalidCommandException)10 ActionReport (org.glassfish.api.ActionReport)9 ArrayList (java.util.ArrayList)6 RemoteCLICommand (com.sun.enterprise.admin.cli.remote.RemoteCLICommand)5 MiniXmlParserException (com.sun.enterprise.universal.xml.MiniXmlParserException)5 HostAndPort (com.sun.enterprise.util.HostAndPort)4 BackupException (com.sun.enterprise.backup.BackupException)3 BackupWarningException (com.sun.enterprise.backup.BackupWarningException)3 SmartFile (com.sun.enterprise.universal.io.SmartFile)3 FileNotFoundException (java.io.FileNotFoundException)3 UnknownHostException (java.net.UnknownHostException)3 Logger (java.util.logging.Logger)3 SFTPClient (org.glassfish.cluster.ssh.sftp.SFTPClient)3 CLIProcessExecutor (com.sun.enterprise.admin.cli.CLIProcessExecutor)2 PEDomainsManager (com.sun.enterprise.admin.servermgmt.pe.PEDomainsManager)2