Search in sources :

Example 71 with Server

use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.

the class ApplicationConfigListener method transactionCommited.

public void transactionCommited(final List<PropertyChangeEvent> changes) {
    boolean isUpdatingAttribute = true;
    for (PropertyChangeEvent event : changes) {
        Object oldValue = event.getOldValue();
        Object newValue = event.getNewValue();
        if (event.getSource() instanceof Applications) {
            if (event.getPropertyName().equals(ServerTags.APPLICATION)) {
                if (oldValue == null || newValue == null) {
                    // we are adding/removing application element here
                    // and updating existing attribute
                    isUpdatingAttribute = false;
                    break;
                }
            }
        } else if (event.getSource() instanceof Server || event.getSource() instanceof Cluster) {
            if (event.getPropertyName().equals(ServerTags.APPLICATION_REF)) {
                if (oldValue == null || newValue == null) {
                    // we are adding/removing application-ref element here
                    // and updating existing attribute
                    isUpdatingAttribute = false;
                    break;
                }
            }
        }
    }
    if (!isUpdatingAttribute) {
        // skip the config listener
        return;
    }
    for (PropertyChangeEvent event : changes) {
        if (event.getSource() instanceof Application || event.getSource() instanceof ApplicationRef || event.getSource() instanceof Property) {
            Object oldValue = event.getOldValue();
            Object newValue = event.getNewValue();
            String propertyName = null;
            if (oldValue != null && newValue != null && oldValue instanceof String && newValue instanceof String && !((String) oldValue).equals((String) newValue)) {
                // if it's an attribute change of the application
                // element or application-ref element
                Object parent = event.getSource();
                String appName = null;
                if (parent instanceof Application) {
                    appName = ((Application) parent).getName();
                    propertyName = event.getPropertyName();
                } else if (parent instanceof ApplicationRef) {
                    appName = ((ApplicationRef) parent).getRef();
                    propertyName = event.getPropertyName();
                } else if (parent instanceof Property) {
                    appName = ((Property) parent).getParent(Application.class).getName();
                    propertyName = ((Property) parent).getName();
                }
                // anything
                if (applications.getApplication(appName) == null) {
                    return;
                }
                if (ServerTags.ENABLED.equals(propertyName)) {
                    // enable or disable application accordingly
                    handleAppEnableChange(event.getSource(), appName, Boolean.valueOf((String) newValue));
                } else if (ServerTags.CONTEXT_ROOT.equals(propertyName) || ServerTags.VIRTUAL_SERVERS.equals(propertyName) || ServerTags.AVAILABILITY_ENABLED.equals(propertyName) || ServerTags.CDI_DEV_MODE_ENABLED_PROP.equals(propertyName)) {
                    // for other changes, reload the application
                    handleOtherAppConfigChanges(event.getSource(), appName);
                }
            }
        }
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) Applications(com.sun.enterprise.config.serverbeans.Applications) Server(com.sun.enterprise.config.serverbeans.Server) Cluster(com.sun.enterprise.config.serverbeans.Cluster) Application(com.sun.enterprise.config.serverbeans.Application) ApplicationRef(com.sun.enterprise.config.serverbeans.ApplicationRef) Property(org.jvnet.hk2.config.types.Property)

Example 72 with Server

use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.

the class CLIUtil method chooseRefContainer.

static RefContainer chooseRefContainer(final Domain domain, final String target, final ConfigBeansUtilities configBeansUtilities) {
    Config config = domain.getConfigs().getConfigByName(target);
    if (config != null) {
        return config;
    }
    Server server = configBeansUtilities.getServerNamed(target);
    if (server != null) {
        return server;
    }
    Cluster cluster = domain.getClusterNamed(target);
    if (cluster != null) {
        return cluster;
    }
    DeploymentGroup dg = domain.getDeploymentGroupNamed(target);
    return dg;
}
Also used : Server(com.sun.enterprise.config.serverbeans.Server) Config(com.sun.enterprise.config.serverbeans.Config) Cluster(com.sun.enterprise.config.serverbeans.Cluster) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup)

Example 73 with Server

use of com.sun.enterprise.config.serverbeans.Server 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 74 with Server

use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.

the class InstanceRegisterInstanceCommand method execute.

@Override
public void execute(AdminCommandContext ctxt) {
    final ActionReport report = ctxt.getActionReport();
    try {
        // create node if it doesn't exist
        Node n = domain.getNodes().getNode(node);
        if (n == null) {
            ConfigSupport.apply(new SingleConfigCode<Nodes>() {

                @Override
                public Object run(Nodes param) throws PropertyVetoException, TransactionFailure {
                    Node newNode = param.createChild(Node.class);
                    newNode.setName(node);
                    if (installdir != null && !"".equals(installdir))
                        newNode.setInstallDir(installdir);
                    if (nodedir != null && !"".equals(nodedir))
                        newNode.setNodeDir(nodedir);
                    if (nodehost != null && !"".equals(nodehost))
                        newNode.setNodeHost(nodehost);
                    newNode.setType(type);
                    // comment out - not needed
                    /*if (type.equals("SSH")) {
                            SshConnector sshC = param.createChild(SshConnector.class);
                            if (sshHost != null && sshHost != "") {
                                sshC.setSshHost(sshHost);

                            }
                            if (sshPort != "-1" && sshPort != "") {
                                sshC.setSshPort(sshPort);

                            }
                            if (sshuser != null || sshkeyfile != null || sshpassword != null
                                    || sshkeypassphrase != null) {
                                SshAuth sshA = sshC.createChild(SshAuth.class);
                                if (sshuser != null && sshuser != "") {
                                    sshA.setUserName(sshuser);
                                }
                                if (sshkeyfile != null && sshkeyfile != "") {
                                    sshA.setKeyfile(sshkeyfile);
                                }
                                if (sshpassword != null && sshpassword != "") {
                                    sshA.setPassword(sshpassword);
                                }
                                if (sshkeypassphrase != null && sshkeypassphrase != "") {
                                    sshA.setKeyPassphrase(sshkeypassphrase);
                                }
                                sshC.setSshAuth(sshA);
                            }
                            if (sshC != null) {
                                newNode.setSshConnector(sshC);
                            }
                        }*/
                    param.getNode().add(newNode);
                    return newNode;
                }
            }, domain.getNodes());
        }
        // create server if it doesn't exist
        Server s = domain.getServers().getServer(instanceName);
        if (s == null) {
            ConfigSupport.apply(new SingleConfigCode<Servers>() {

                public Object run(Servers param) throws PropertyVetoException, TransactionFailure {
                    Server newServer = param.createChild(Server.class);
                    newServer.setConfigRef(config);
                    // newServer.setLbWeight(lbWeight);
                    newServer.setName(instanceName);
                    newServer.setNodeRef(node);
                    if (systemProperties != null) {
                        for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
                            final String propName = (String) entry.getKey();
                            final String propValue = (String) entry.getValue();
                            SystemProperty newSP = newServer.createChild(SystemProperty.class);
                            // newSP.setDescription(sp.getDescription());
                            newSP.setName(propName);
                            newSP.setValue(propValue);
                            newServer.getSystemProperty().add(newSP);
                        }
                    }
                    param.getServer().add(newServer);
                    return newServer;
                }
            }, domain.getServers());
            // create server-ref on cluster
            Cluster thisCluster = domain.getClusterNamed(clusterName);
            if (thisCluster != null) {
                ConfigSupport.apply(new SingleConfigCode<Cluster>() {

                    public Object run(Cluster param) throws PropertyVetoException, TransactionFailure {
                        ServerRef newServerRef = param.createChild(ServerRef.class);
                        newServerRef.setRef(instanceName);
                        newServerRef.setLbEnabled(lbEnabled);
                        param.getServerRef().add(newServerRef);
                        return param;
                    }
                }, thisCluster);
            }
        }
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
    } catch (TransactionFailure tfe) {
        report.setMessage(localStrings.getLocalString("register.instance.failed", "Instance {0} registration failed on {1}", instanceName, server.getName()));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(tfe);
        return;
    } catch (Exception e) {
        report.setMessage(localStrings.getLocalString("register.instance.failed", "Instance {0} registration failed on {1}", instanceName, server.getName()));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(e);
        return;
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Server(com.sun.enterprise.config.serverbeans.Server) Node(com.sun.enterprise.config.serverbeans.Node) Cluster(com.sun.enterprise.config.serverbeans.Cluster) ActionReport(org.glassfish.api.ActionReport) Servers(com.sun.enterprise.config.serverbeans.Servers) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty) Nodes(com.sun.enterprise.config.serverbeans.Nodes) PropertyVetoException(java.beans.PropertyVetoException) PropertyVetoException(java.beans.PropertyVetoException) ServerRef(com.sun.enterprise.config.serverbeans.ServerRef)

Example 75 with Server

use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.

the class NodeAgentConfigUpgrade method postConstruct.

public void postConstruct() {
    final NodeAgents nodeAgents = domain.getNodeAgents();
    if (nodeAgents == null) {
        createDefaultNodeList();
        return;
    }
    final List<NodeAgent> agList = nodeAgents.getNodeAgent();
    if (agList.size() == 0) {
        createDefaultNodeList();
        return;
    }
    try {
        ConfigSupport.apply(new SingleConfigCode<Domain>() {

            public Object run(Domain d) throws PropertyVetoException, TransactionFailure {
                Nodes nodes = d.createChild(Nodes.class);
                Transaction t = Transaction.getTransaction(d);
                if (t == null)
                    return null;
                for (NodeAgent na : agList) {
                    String host = null;
                    Node node = nodes.createChild(Node.class);
                    node.setName(na.getName());
                    node.setType("CONFIG");
                    JmxConnector jc = na.getJmxConnector();
                    if (jc != null) {
                        // get the properties and see if host name is specified
                        List<Property> agentProp = jc.getProperty();
                        for (Property p : agentProp) {
                            String name = p.getName();
                            if (name.equals("client-hostname")) {
                                // create the node with a host name
                                node.setNodeHost(p.getValue());
                                node.setInstallDir("${com.sun.aas.productRoot}");
                            }
                        }
                    }
                    nodes.getNode().add(node);
                }
                // Now add the builtin localhost node
                createDefaultNode(d, nodes);
                d.setNodes(nodes);
                List<Server> serverList = servers.getServer();
                if (serverList.size() <= 0)
                    return null;
                for (Server s : serverList) {
                    s = t.enroll(s);
                    s.setNodeRef(s.getNodeAgentRef());
                    s.setNodeAgentRef(null);
                }
                // remove the node-agent element
                // d.getNodeAgents().getNodeAgent().clear();
                d.setNodeAgents(null);
                return null;
            }
        }, domain);
    } catch (Exception e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, "Failure while upgrading node-agent from V2 to V3", e);
        throw new RuntimeException(e);
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Server(com.sun.enterprise.config.serverbeans.Server) Node(com.sun.enterprise.config.serverbeans.Node) NodeAgent(com.sun.enterprise.config.serverbeans.NodeAgent) JmxConnector(com.sun.enterprise.config.serverbeans.JmxConnector) NodeAgents(com.sun.enterprise.config.serverbeans.NodeAgents) Nodes(com.sun.enterprise.config.serverbeans.Nodes) PropertyVetoException(java.beans.PropertyVetoException) PropertyVetoException(java.beans.PropertyVetoException) Domain(com.sun.enterprise.config.serverbeans.Domain) Property(org.jvnet.hk2.config.types.Property)

Aggregations

Server (com.sun.enterprise.config.serverbeans.Server)86 ActionReport (org.glassfish.api.ActionReport)27 Cluster (com.sun.enterprise.config.serverbeans.Cluster)26 Domain (com.sun.enterprise.config.serverbeans.Domain)16 Config (com.sun.enterprise.config.serverbeans.Config)15 ArrayList (java.util.ArrayList)12 DeploymentGroup (fish.payara.enterprise.config.serverbeans.DeploymentGroup)11 PropertyVetoException (java.beans.PropertyVetoException)11 Properties (java.util.Properties)10 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)10 HashMap (java.util.HashMap)9 ApplicationRef (com.sun.enterprise.config.serverbeans.ApplicationRef)8 File (java.io.File)8 IOException (java.io.IOException)8 Test (org.junit.Test)8 Property (org.jvnet.hk2.config.types.Property)8 Node (com.sun.enterprise.config.serverbeans.Node)7 Map (java.util.Map)7 Logger (java.util.logging.Logger)7 ParameterMap (org.glassfish.api.admin.ParameterMap)7