use of com.sun.enterprise.config.serverbeans.Cluster 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;
}
use of com.sun.enterprise.config.serverbeans.Cluster 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;
}
use of com.sun.enterprise.config.serverbeans.Cluster 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;
}
}
use of com.sun.enterprise.config.serverbeans.Cluster in project Payara by payara.
the class SystemTasksImpl method setSystemPropertiesFromDomainXml.
private void setSystemPropertiesFromDomainXml() {
// precedence order from high to low
// 0. server
// 1. cluster
// 2. <server>-config or <cluster>-config
// 3. domain
// so we need to add System Properties in *reverse order* to get the
// right precedence.
List<SystemProperty> domainSPList = domain.getSystemProperty();
List<SystemProperty> configSPList = getConfigSystemProperties();
Cluster cluster = server.getCluster();
List<SystemProperty> clusterSPList = null;
if (cluster != null) {
clusterSPList = cluster.getSystemProperty();
}
List<SystemProperty> serverSPList = server.getSystemProperty();
setSystemProperties(domainSPList);
setSystemProperties(configSPList);
if (clusterSPList != null) {
setSystemProperties(clusterSPList);
}
setSystemProperties(serverSPList);
}
use of com.sun.enterprise.config.serverbeans.Cluster in project Payara by payara.
the class ConfigRefValidator method isValid.
@Override
public boolean isValid(final Named bean, final ConstraintValidatorContext constraintValidatorContext) {
if (bean == null)
return true;
Server server = null;
Cluster mycluster = null;
String configRef = null;
String serverName = null;
if (bean instanceof Server) {
server = (Server) bean;
configRef = server.getConfigRef();
serverName = server.getName();
} else if (bean instanceof Cluster) {
mycluster = (Cluster) bean;
configRef = mycluster.getConfigRef();
serverName = mycluster.getName();
}
// skip validation @NotNull is already on getConfigRef
if (configRef == null)
return true;
// cannot use default-config
if (configRef.equals(SystemPropertyConstants.TEMPLATE_CONFIG_NAME)) {
logger.warning(ConfigApiLoggerInfo.configRefDefaultconfig);
return false;
}
// cannot change config-ref of DAS
if (server != null) {
if (server.isDas() && !configRef.equals(SystemPropertyConstants.DAS_SERVER_CONFIG)) {
logger.warning(ConfigApiLoggerInfo.configRefDASconfig);
return false;
}
// cannot use server-config if not DAS
if (!server.isDas() && configRef.equals(SystemPropertyConstants.DAS_SERVER_CONFIG)) {
logger.warning(ConfigApiLoggerInfo.configRefServerconfig);
return false;
}
final Servers servers = server.getParent(Servers.class);
final Domain domain = servers.getParent(Domain.class);
final Configs configs = domain.getConfigs();
if (servers.getServer(serverName) != null) {
// validate for set, not _register-instance
// cannot change config ref of a clustered instance
Cluster cluster = domain.getClusterForInstance(serverName);
if (cluster != null) {
// cluster is not null during create-local-instance --cluster c1 i1
if (!cluster.getConfigRef().equals(configRef)) {
// During set when trying to change config-ref of a clustered instance,
// the value of desired config-ref will be different than the current config-ref.
// During _register-instance, (create-local-instance --cluster c1 i1)
// cluster.getConfigRef().equals(configRef) will be true and not come here.
logger.warning(ConfigApiLoggerInfo.configRefClusteredInstance);
return false;
}
}
// cannot use a non-existent config (Only used by set. _register-instance will fail earlier)
if (configs == null || configs.getConfigByName(configRef) == null) {
logger.warning(ConfigApiLoggerInfo.configRefNonexistent);
return false;
}
}
}
return true;
}
Aggregations