Search in sources :

Example 11 with CommandInvocation

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

the class SetRestMonitoringConfigurationCommand method createDefaultRestMonitoringUser.

private void createDefaultRestMonitoringUser(ActionReport subActionReport, Subject subject) {
    CommandInvocation invocation = commandRunner.getCommandInvocation("create-file-user", subActionReport, subject, false);
    ParameterMap parameters = new ParameterMap();
    parameters.add("groups", "rest-monitoring");
    parameters.add("userpassword", "rest");
    parameters.add("target", target);
    parameters.add("authrealmname", "file");
    parameters.add("DEFAULT", DEFAULT_USER_NAME);
    invocation.parameters(parameters).execute();
}
Also used : ParameterMap(org.glassfish.api.admin.ParameterMap) CommandInvocation(org.glassfish.api.admin.CommandRunner.CommandInvocation)

Example 12 with CommandInvocation

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

the class AddInstanceToDeploymentGroupCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    Server server = domain.getServerNamed(instanceName);
    ActionReport report = context.getActionReport();
    if (server == null && env.isDas()) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage("Instance " + instanceName + " does not exist");
        return;
    }
    DeploymentGroup dg = domain.getDeploymentGroupNamed(deploymentGroup);
    if (dg == null && env.isDas()) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage("Deployment Group " + deploymentGroup + " does not exist");
        return;
    }
    // OK set up the reference
    try {
        ConfigSupport.apply((DeploymentGroup dg1) -> {
            DGServerRef ref = dg1.createChild(DGServerRef.class);
            ref.setRef(instanceName);
            dg1.getDGServerRef().add(ref);
            return ref;
        }, dg);
    } catch (TransactionFailure e) {
        report.setMessage("Failed to add instance to deployment group");
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(e);
    }
    // now run the command to add application ref to the instance
    for (ApplicationRef applicationRef : dg.getApplicationRef()) {
        CommandInvocation inv = commandRunner.getCommandInvocation("create-application-ref", report, context.getSubject());
        ParameterMap parameters = new ParameterMap();
        parameters.add("target", instanceName);
        parameters.add("name", applicationRef.getRef());
        parameters.add("virtualservers", applicationRef.getVirtualServers());
        parameters.add("enabled", applicationRef.getEnabled());
        parameters.add("lbenabled", applicationRef.getLbEnabled());
        inv.parameters(parameters).execute();
    }
    // for all resource refs add resource ref to instance
    for (ResourceRef resourceRef : dg.getResourceRef()) {
        CommandInvocation inv = commandRunner.getCommandInvocation("create-resource-ref", report, context.getSubject());
        ParameterMap parameters = new ParameterMap();
        parameters.add("target", instanceName);
        parameters.add("reference_name", resourceRef.getRef());
        parameters.add("enabled", resourceRef.getEnabled());
        inv.parameters(parameters).execute();
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Server(com.sun.enterprise.config.serverbeans.Server) DGServerRef(fish.payara.enterprise.config.serverbeans.DGServerRef) ParameterMap(org.glassfish.api.admin.ParameterMap) ResourceRef(com.sun.enterprise.config.serverbeans.ResourceRef) ActionReport(org.glassfish.api.ActionReport) ApplicationRef(com.sun.enterprise.config.serverbeans.ApplicationRef) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup) CommandInvocation(org.glassfish.api.admin.CommandRunner.CommandInvocation)

Example 13 with CommandInvocation

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

the class ResourceUtil method runCommandWithSse.

public static EventOutput runCommandWithSse(final String commandName, final ParameterMap parameters, final Subject subject, final SseCommandHelper.ActionReportProcessor processor) {
    CommandRunner cr = Globals.getDefaultHabitat().getService(CommandRunner.class);
    final RestActionReporter ar = new RestActionReporter();
    final CommandInvocation commandInvocation = cr.getCommandInvocation(commandName, ar, subject).parameters(parameters);
    return SseCommandHelper.invokeAsync(commandInvocation, new SseCommandHelper.ActionReportProcessor() {

        @Override
        public ActionReport process(ActionReport report, EventOutput ec) {
            addCommandLog(ar, commandName, parameters);
            if (processor != null) {
                return processor.process(report, ec);
            }
            return ar;
        }
    });
}
Also used : EventOutput(org.glassfish.jersey.media.sse.EventOutput) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) ActionReport(org.glassfish.api.ActionReport) CommandRunner(org.glassfish.api.admin.CommandRunner) CommandInvocation(org.glassfish.api.admin.CommandRunner.CommandInvocation)

Example 14 with CommandInvocation

use of org.glassfish.api.admin.CommandRunner.CommandInvocation 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)

Example 15 with CommandInvocation

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

the class CreateInstanceCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    ctx = context;
    logger = context.getLogger();
    if (!env.isDas()) {
        String msg = Strings.get("notAllowed");
        logger.warning(msg);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(msg);
        return;
    }
    // Make sure Node is valid
    theNode = nodes.getNode(node);
    if (theNode == null) {
        String msg = Strings.get("noSuchNode", node);
        logger.warning(msg);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(msg);
        return;
    }
    if (lbEnabled != null && clusterName == null) {
        String msg = Strings.get("lbenabledNotForStandaloneInstance");
        logger.warning(msg);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(msg);
        return;
    }
    nodeHost = theNode.getNodeHost();
    nodeDir = theNode.getNodeDirAbsolute();
    installDir = theNode.getInstallDir();
    if (theNode.isLocal()) {
        validateInstanceDirUnique(report, context);
        if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS && report.getActionExitCode() != ActionReport.ExitCode.WARNING) {
            // If we couldn't update domain.xml then stop!
            return;
        }
    }
    // First, update domain.xml by calling _register-instance
    CommandInvocation ci = cr.getCommandInvocation("_register-instance", report, context.getSubject());
    ParameterMap map = new ParameterMap();
    map.add("node", node);
    map.add("config", configRef);
    map.add("cluster", clusterName);
    map.add("deploymentgroup", deploymentGroup);
    if (lbEnabled != null) {
        map.add("lbenabled", lbEnabled.toString());
    }
    if (!checkPorts) {
        map.add("checkports", "false");
    }
    if (StringUtils.ok(portBase)) {
        map.add("portbase", portBase);
    }
    map.add("systemproperties", systemProperties);
    map.add("DEFAULT", instance);
    ci.parameters(map);
    ci.execute();
    if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS && report.getActionExitCode() != ActionReport.ExitCode.WARNING) {
        // If we couldn't update domain.xml then stop!
        return;
    }
    registerInstanceMessage = report.getMessage();
    // so installdir is product root. see register-instance above
    if (theNode.isLocal() && installDir == null) {
        ci = cr.getCommandInvocation("_update-node", report, context.getSubject());
        map = new ParameterMap();
        map.add("installdir", "${com.sun.aas.productRoot}");
        map.add("type", "CONFIG");
        map.add("DEFAULT", theNode.getName());
        ci.parameters(map);
        ci.execute();
        if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS && report.getActionExitCode() != ActionReport.ExitCode.WARNING) {
            // If we couldn't update domain.xml then stop!
            return;
        }
    }
    if (!validateDasOptions(context)) {
        report.setActionExitCode(ActionReport.ExitCode.WARNING);
        return;
    }
    // Then go create the instance filesystem on the node
    createInstanceFilesystem(context);
}
Also used : ActionReport(org.glassfish.api.ActionReport) CommandInvocation(org.glassfish.api.admin.CommandRunner.CommandInvocation)

Aggregations

CommandInvocation (org.glassfish.api.admin.CommandRunner.CommandInvocation)20 ActionReport (org.glassfish.api.ActionReport)13 ParameterMap (org.glassfish.api.admin.ParameterMap)6 Logger (java.util.logging.Logger)3 Node (com.sun.enterprise.config.serverbeans.Node)2 Server (com.sun.enterprise.config.serverbeans.Server)2 DeploymentGroup (fish.payara.enterprise.config.serverbeans.DeploymentGroup)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 RestActionReporter (org.glassfish.admin.rest.utils.xml.RestActionReporter)2 MessagePart (org.glassfish.api.ActionReport.MessagePart)2 CommandRunner (org.glassfish.api.admin.CommandRunner)2 ApplicationRef (com.sun.enterprise.config.serverbeans.ApplicationRef)1 Cluster (com.sun.enterprise.config.serverbeans.Cluster)1 ResourceRef (com.sun.enterprise.config.serverbeans.ResourceRef)1 TokenResolver (com.sun.enterprise.universal.glassfish.TokenResolver)1 RestMonitoringAuthModule (fish.payara.appserver.monitoring.rest.service.security.RestMonitoringAuthModule)1 AsadminRecorderService (fish.payara.asadmin.recorder.AsadminRecorderService)1 DGServerRef (fish.payara.enterprise.config.serverbeans.DGServerRef)1