use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.
the class ProxyImpl method proxyRequest.
@Override
public Properties proxyRequest(UriInfo sourceUriInfo, Client client, ServiceLocator habitat) {
Properties proxiedResponse = new Properties();
try {
Domain domain = habitat.getService(Domain.class);
String forwardInstanceName = extractTargetInstanceName(sourceUriInfo);
Server forwardInstance = domain.getServerNamed(forwardInstanceName);
if (forwardInstance != null) {
UriBuilder forwardUriBuilder = constructForwardURLPath(sourceUriInfo);
// Host and Port are replaced to that of forwardInstanceName
URI forwardURI = forwardUriBuilder.scheme("https").host(forwardInstance.getAdminHost()).port(forwardInstance.getAdminPort()).build();
client = addAuthenticationInfo(client, forwardInstance, habitat);
WebTarget resourceBuilder = client.target(forwardURI);
SecureAdmin secureAdmin = habitat.getService(SecureAdmin.class);
Builder builder = resourceBuilder.request(MediaType.APPLICATION_JSON).header(SecureAdmin.Util.ADMIN_INDICATOR_HEADER_NAME, secureAdmin.getSpecialAdminIndicator());
// TODO if the target server is down, we get ClientResponseException. Need to handle it
Response response = builder.get(Response.class);
Response.Status status = Response.Status.fromStatusCode(response.getStatus());
if (status.getFamily() == javax.ws.rs.core.Response.Status.Family.SUCCESSFUL) {
String jsonDoc = response.readEntity(String.class);
Map responseMap = MarshallingUtils.buildMapFromDocument(jsonDoc);
Map resultExtraProperties = (Map) responseMap.get("extraProperties");
if (resultExtraProperties != null) {
Object entity = resultExtraProperties.get("entity");
if (entity != null) {
proxiedResponse.put("entity", entity);
}
@SuppressWarnings({ "unchecked" }) Map<String, String> childResources = (Map<String, String>) resultExtraProperties.get("childResources");
for (Map.Entry<String, String> entry : childResources.entrySet()) {
String targetURL = null;
try {
URL originalURL = new URL(entry.getValue());
// Construct targetURL which has host+port of DAS and path from originalURL
targetURL = constructTargetURLPath(sourceUriInfo, originalURL).build().toASCIIString();
} catch (MalformedURLException e) {
// TODO There was an exception while parsing URL. Need to decide what to do. For now ignore the child entry
}
entry.setValue(targetURL);
}
proxiedResponse.put("childResources", childResources);
}
Object message = responseMap.get("message");
if (message != null) {
proxiedResponse.put("message", message);
}
Object properties = responseMap.get("properties");
if (properties != null) {
proxiedResponse.put("properties", properties);
}
} else {
throw new WebApplicationException(response.readEntity(String.class), status);
}
} else {
// server == null
// TODO error to user. Can not locate server for whom data is being looked for
}
} catch (Exception ex) {
throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
}
return proxiedResponse;
}
use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.
the class ClusterOperationUtil method replicateCommand.
/**
* Replicates a given command on the given list of targets, optionally gathering
* downloaded result payloads from the instance commands into a directory.
* <p>
* If intermediateDownloadDir is non-null, then any files returned from
* the instances in the payload of the HTTP response will be stored in a
* directory tree like this:
* <pre>
* ${intermediateDownloadDir}/
* ${instanceA}/
* file(s) returned from instance A
* ${instanceB}/
* file(s) returned from instance B
* ...
* </pre>
* where ${instanceA}, ${instanceB}, etc. are the names of the instances to
* which the command was replicated. This method does no further processing
* on the downloaded files but leaves that to the calling command.
*/
public static ActionReport.ExitCode replicateCommand(String commandName, FailurePolicy failPolicy, FailurePolicy offlinePolicy, FailurePolicy neverStartedPolicy, List<Server> instancesForReplication, AdminCommandContext context, ParameterMap parameters, ServiceLocator habitat, final File intermediateDownloadDir) {
ActionReport.ExitCode returnValue = ActionReport.ExitCode.SUCCESS;
InstanceStateService instanceState = habitat.getService(InstanceStateService.class);
validateIntermediateDownloadDir(intermediateDownloadDir);
RemoteInstanceCommandHelper rich = new RemoteInstanceCommandHelper(habitat);
Map<String, Future<InstanceCommandResult>> futures = new HashMap<>();
try {
for (Server svr : instancesForReplication) {
if (instanceState.getState(svr.getName()) == InstanceState.StateType.NEVER_STARTED) {
// Do not replicate commands to instances that have never been started.
// For certain commands, warn about the failure to replicate even if
// the instance has never been started.
ActionReport.ExitCode finalResult = FailurePolicy.applyFailurePolicy(neverStartedPolicy, ActionReport.ExitCode.FAILURE);
if (!finalResult.equals(ActionReport.ExitCode.SUCCESS)) {
ActionReport aReport = context.getActionReport().addSubActionsReport();
if (finalResult.equals(ActionReport.ExitCode.FAILURE)) {
aReport.setMessage(strings.getLocalString("clusterutil.failneverstarted", "FAILURE: Instance {0} has never been started; command {1} was not replicated to that instance", svr.getName(), commandName));
} else {
aReport.setMessage(strings.getLocalString("clusterutil.warnneverstarted", "WARNING: Instance {0} has never been started; command {1} was not replicated to that instance", svr.getName(), commandName));
}
aReport.setActionExitCode(finalResult);
if (returnValue == ActionReport.ExitCode.SUCCESS)
returnValue = finalResult;
}
continue;
}
Config scfg = svr.getConfig();
// PAYARA-2162 Restart Required is set erroneously when _get-runtime-info is called
if (!Boolean.valueOf(scfg.getDynamicReconfigurationEnabled()) && !ALLOWED_COMMANDS.contains(commandName)) {
// Do not replicate to servers for which dynamic configuration is disabled
ActionReport aReport = context.getActionReport().addSubActionsReport();
aReport.setActionExitCode(ActionReport.ExitCode.WARNING);
aReport.setMessage(strings.getLocalString("clusterutil.dynrecfgdisabled", "WARNING: The command {0} was not replicated to instance {1} because the " + "dynamic-reconfiguration-enabled flag is set to false for config {2}", new Object[] { commandName, svr.getName(), scfg.getName() }));
instanceState.setState(svr.getName(), InstanceState.StateType.RESTART_REQUIRED, false);
instanceState.addFailedCommandToInstance(svr.getName(), commandName, parameters);
returnValue = ActionReport.ExitCode.WARNING;
continue;
}
String host = svr.getAdminHost();
int port = rich.getAdminPort(svr);
ActionReport aReport = context.getActionReport().addSubActionsReport();
InstanceCommandResult aResult = new InstanceCommandResult();
// InstanceCommandExecutor ice =
// new InstanceCommandExecutor(habitat, commandName, failPolicy, offlinePolicy,
// svr, host, port, LOGGER, parameters, aReport, aResult);
// if (CommandTarget.DAS.isValid(habitat, ice.getServer().getName()))
// continue;
// if (intermediateDownloadDir != null) {
// ice.setFileOutputDirectory(
// subdirectoryForInstance(intermediateDownloadDir, ice));
// }
// Future<InstanceCommandResult> f = instanceState.submitJob(svr, ice, aResult);
// TODO: Remove this if after only one remote admin call method will be choosen
Future<InstanceCommandResult> f;
if (useRest()) {
InstanceRestCommandExecutor ice = new InstanceRestCommandExecutor(habitat, commandName, failPolicy, offlinePolicy, svr, host, port, LOGGER, parameters, aReport, aResult);
if (CommandTarget.DAS.isValid(habitat, ice.getServer().getName())) {
continue;
}
if (intermediateDownloadDir != null) {
ice.setFileOutputDirectory(new File(intermediateDownloadDir, ice.getServer().getName()));
}
f = instanceState.submitJob(svr, ice, aResult);
} else {
LOGGER.log(Level.FINEST, "replicateCommand(): Use traditional way for replication - {0}", commandName);
InstanceRestCommandExecutor ice = new InstanceRestCommandExecutor(habitat, commandName, failPolicy, offlinePolicy, svr, host, port, LOGGER, parameters, aReport, aResult);
if (CommandTarget.DAS.isValid(habitat, ice.getServer().getName())) {
continue;
}
if (intermediateDownloadDir != null) {
ice.setFileOutputDirectory(new File(intermediateDownloadDir, ice.getServer().getName()));
}
f = instanceState.submitJob(svr, ice, aResult);
}
if (f == null) {
LOGGER.severe(AdminLoggerInfo.stateNotFound);
continue;
}
futures.put(svr.getName(), f);
LOGGER.fine(strings.getLocalString("dynamicreconfiguration.diagnostics.jobsubmitted", "Successfully submitted command {0} for execution at instance {1}", commandName, svr.getName()));
}
} catch (Exception ex) {
ActionReport aReport = context.getActionReport().addSubActionsReport();
ActionReport.ExitCode finalResult = FailurePolicy.applyFailurePolicy(failPolicy, ActionReport.ExitCode.FAILURE);
aReport.setActionExitCode(finalResult);
aReport.setMessage(strings.getLocalString("clusterutil.replicationfailed", "Error during command replication: {0}", ex.getLocalizedMessage()));
LOGGER.log(Level.SEVERE, AdminLoggerInfo.replicationError, ex.getLocalizedMessage());
if (returnValue == ActionReport.ExitCode.SUCCESS) {
returnValue = finalResult;
}
}
boolean gotFirstResponse = false;
long maxWaitTime = RemoteRestAdminCommand.getReadTimeout();
long timeBeforeAsadminTimeout = maxWaitTime;
long waitStart = System.currentTimeMillis();
for (Map.Entry<String, Future<InstanceCommandResult>> fe : futures.entrySet()) {
String s = fe.getKey();
ActionReport.ExitCode finalResult;
try {
LOGGER.fine(strings.getLocalString("dynamicreconfiguration.diagnostics.waitingonjob", "Waiting for command {0} to be completed at instance {1}", commandName, s));
Future<InstanceCommandResult> aFuture = fe.getValue();
InstanceCommandResult aResult = aFuture.get(maxWaitTime, TimeUnit.MILLISECONDS);
long elapsedTime = System.currentTimeMillis() - waitStart;
timeBeforeAsadminTimeout -= elapsedTime;
if (!gotFirstResponse) {
maxWaitTime = elapsedTime * 4;
gotFirstResponse = true;
}
if ((maxWaitTime > timeBeforeAsadminTimeout) || (maxWaitTime < 60000)) {
maxWaitTime = timeBeforeAsadminTimeout;
}
ActionReport iReport;
Server iServer;
if (useRest()) {
InstanceRestCommandExecutor ice = (InstanceRestCommandExecutor) aResult.getInstanceCommand();
iReport = ice.getReport();
iServer = ice.getServer();
} else {
InstanceRestCommandExecutor ice = (InstanceRestCommandExecutor) aResult.getInstanceCommand();
iReport = ice.getReport();
iServer = ice.getServer();
}
if (iReport.getActionExitCode() != ActionReport.ExitCode.FAILURE) {
completedInstances.add(iServer);
}
finalResult = FailurePolicy.applyFailurePolicy(failPolicy, iReport.getActionExitCode());
if (returnValue == ActionReport.ExitCode.SUCCESS) {
returnValue = finalResult;
}
if (finalResult != ActionReport.ExitCode.SUCCESS) {
instanceState.setState(s, InstanceState.StateType.RESTART_REQUIRED, false);
instanceState.addFailedCommandToInstance(s, commandName, parameters);
}
} catch (Exception ex) {
ActionReport aReport = context.getActionReport().addSubActionsReport();
finalResult = FailurePolicy.applyFailurePolicy(failPolicy, ActionReport.ExitCode.FAILURE);
if (finalResult == ActionReport.ExitCode.FAILURE) {
if (ex instanceof TimeoutException)
aReport.setMessage(strings.getLocalString("clusterutil.timeoutwhilewaiting", "Timed out while waiting for result from instance {0}", s));
else
aReport.setMessage(strings.getLocalString("clusterutil.exceptionwhilewaiting", "Exception while waiting for result from instance {0} : {1}", s, ex.getLocalizedMessage()));
}
aReport.setActionExitCode(finalResult);
if (returnValue == ActionReport.ExitCode.SUCCESS)
returnValue = finalResult;
instanceState.setState(s, InstanceState.StateType.RESTART_REQUIRED, false);
instanceState.addFailedCommandToInstance(s, commandName, parameters);
}
}
return returnValue;
}
use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.
the class TransactionServiceProperties method getJTSProperties.
public static synchronized Properties getJTSProperties(ServiceLocator serviceLocator, boolean isORBAvailable) {
if (orbAvailable == isORBAvailable && properties != null) {
// We will need to update the properties if ORB availability changed
return properties;
}
Properties jtsProperties = new Properties();
if (serviceLocator != null) {
jtsProperties.put(HABITAT, serviceLocator);
ProcessEnvironment processEnv = serviceLocator.getService(ProcessEnvironment.class);
if (processEnv.getProcessType().isServer()) {
TransactionService txnService = serviceLocator.getService(TransactionService.class, ServerEnvironment.DEFAULT_INSTANCE_NAME);
if (txnService != null) {
jtsProperties.put(Configuration.HEURISTIC_DIRECTION, txnService.getHeuristicDecision());
jtsProperties.put(Configuration.KEYPOINT_COUNT, txnService.getKeypointInterval());
String automaticRecovery = txnService.getAutomaticRecovery();
boolean isAutomaticRecovery = (isValueSet(automaticRecovery) && "true".equals(automaticRecovery));
if (isAutomaticRecovery) {
_logger.log(Level.FINE, "Recoverable J2EE Server");
jtsProperties.put(Configuration.MANUAL_RECOVERY, "true");
}
boolean disable_distributed_transaction_logging = false;
String dbLoggingResource = null;
for (Property prop : txnService.getProperty()) {
String name = prop.getName();
String value = prop.getValue();
if (name.equals("disable-distributed-transaction-logging")) {
if (isValueSet(value) && "true".equals(value)) {
disable_distributed_transaction_logging = true;
}
} else if (name.equals("xaresource-txn-timeout")) {
if (isValueSet(value)) {
_logger.log(Level.FINE, "XAResource transaction timeout is" + value);
TransactionManagerImpl.setXAResourceTimeOut(Integer.parseInt(value));
}
} else if (name.equals("db-logging-resource")) {
dbLoggingResource = value;
_logger.log(Level.FINE, "Transaction DB Logging Resource Name" + dbLoggingResource);
if (dbLoggingResource != null && (" ".equals(dbLoggingResource) || "".equals(dbLoggingResource))) {
dbLoggingResource = "jdbc/TxnDS";
}
} else if (name.equals("xa-servername")) {
if (isValueSet(value)) {
jtsProperties.put(JTS_XA_SERVER_NAME, value);
}
} else if (name.equals("pending-txn-cleanup-interval")) {
if (isValueSet(value)) {
jtsProperties.put("pending-txn-cleanup-interval", value);
}
} else if (name.equals(Configuration.COMMIT_ONE_PHASE_DURING_RECOVERY)) {
if (isValueSet(value)) {
jtsProperties.put(Configuration.COMMIT_ONE_PHASE_DURING_RECOVERY, value);
}
} else if (name.equals("add-wait-point-during-recovery")) {
if (isValueSet(value)) {
try {
FailureInducer.setWaitPointRecovery(Integer.parseInt(value));
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage());
}
}
}
}
if (dbLoggingResource != null) {
disable_distributed_transaction_logging = true;
jtsProperties.put(Configuration.DB_LOG_RESOURCE, dbLoggingResource);
}
/**
* JTS_SERVER_ID needs to be unique for each for server instance.
* This will be used as recovery identifier along with the hostname
* for example: if the hostname is 'tulsa' and iiop-listener-port is 3700
* recovery identifier will be tulsa,P3700
*/
// default value
int jtsServerId = DEFAULT_SERVER_ID;
if (isORBAvailable) {
jtsServerId = serviceLocator.<GlassFishORBHelper>getService(GlassFishORBHelper.class).getORBInitialPort();
if (jtsServerId == 0) {
// XXX Can this ever happen?
// default value
jtsServerId = DEFAULT_SERVER_ID;
}
}
jtsProperties.put(JTS_SERVER_ID, String.valueOf(jtsServerId));
/* ServerId is an J2SE persistent server activation
API. ServerId is scoped at the ORBD. Since
There is no ORBD present in J2EE the value of
ServerId is meaningless - except it must have
SOME value if persistent POAs are created.
*/
// For clusters - all servers in the cluster MUST
// have the same ServerId so when failover happens
// and requests are delivered to a new server, the
// ServerId in the request will match the new server.
String serverId = String.valueOf(DEFAULT_SERVER_ID);
System.setProperty(J2EE_SERVER_ID_PROP, serverId);
ServerContext ctx = serviceLocator.getService(ServerContext.class);
String instanceName = ctx.getInstanceName();
/**
* if the auto recovery is true, always transaction logs will be written irrespective of
* disable_distributed_transaction_logging.
* if the auto recovery is false, then disable_distributed_transaction_logging will be used
* to write transaction logs are not.If disable_distributed_transaction_logging is set to
* false(by default false) logs will be written, set to true logs won't be written.
*/
if (!isAutomaticRecovery && disable_distributed_transaction_logging) {
Configuration.disableFileLogging();
} else {
// if (dbLoggingResource == null) {
Domain domain = serviceLocator.getService(Domain.class);
Server server = domain.getServerNamed(instanceName);
// Check if the server system property is set
String logdir = getTXLogDir(server);
// if not, check if the cluster system property is set
if (logdir == null) {
Cluster cluster = server.getCluster();
if (cluster != null) {
logdir = getTXLogDir(cluster);
}
}
// No system properties are set - get tx log dir from transaction service
if (logdir == null) {
logdir = txnService.getTxLogDir();
}
if (logdir == null) {
logdir = domain.getLogRoot();
if (logdir == null) {
// logdir = FileUtil.getAbsolutePath(".." + File.separator + "logs");
logdir = ".." + File.separator + "logs";
}
} else if (!(new File(logdir)).isAbsolute()) {
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Relative pathname specified for transaction log directory : " + logdir);
}
String logroot = domain.getLogRoot();
if (logroot != null) {
logdir = logroot + File.separator + logdir;
} else {
// logdir = FileUtil.getAbsolutePath(".." + File.separator + "logs"
// + File.separator + logdir);
logdir = ".." + File.separator + "logs" + File.separator + logdir;
}
}
logdir += File.separator + instanceName + File.separator + "tx";
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "JTS log directory: " + logdir);
_logger.log(Level.FINE, "JTS Server id " + jtsServerId);
}
jtsProperties.put(Configuration.LOG_DIRECTORY, logdir);
}
jtsProperties.put(Configuration.COMMIT_RETRY, txnService.getRetryTimeoutInSeconds());
jtsProperties.put(Configuration.INSTANCE_NAME, instanceName);
}
}
}
properties = jtsProperties;
orbAvailable = isORBAvailable;
return properties;
}
use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.
the class SynchronizeRealmFromConfig method execute.
@Override
public void execute(AdminCommandContext context) {
Config realConfig = null;
try {
realConfig = configs.getConfigByName(target);
} catch (Exception ex) {
}
if (realConfig == null) {
Server targetServer = domain.getServerNamed(target);
if (targetServer != null) {
realConfig = domain.getConfigNamed(targetServer.getConfigRef());
}
com.sun.enterprise.config.serverbeans.Cluster cluster = domain.getClusterNamed(target);
if (cluster != null) {
realConfig = domain.getConfigNamed(cluster.getConfigRef());
}
}
ActionReport report = context.getActionReport();
try {
// TODO: can i use realConfig.equals(config) instead
if (realConfig.getName().equals(config.getName())) {
this.setRestartRequired(report);
return;
}
// this is not an active config so try and update the backend
// directly
Realm realm = realmsManager.getFromLoadedRealms(realConfig.getName(), realmName);
if (realm == null) {
// realm is not loaded yet
report.setMessage(_localStrings.getLocalString("REALM_SYNCH_SUCCESSFUL", "Synchronization of Realm {0} from Configuration Successful.", realmName));
report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
return;
}
// now we really need to update the realm in the backend from the config.
realmsManager.removeFromLoadedRealms(realConfig.getName(), realmName);
boolean done = this.instantiateRealm(realConfig, realmName);
if (done) {
report.setMessage(_localStrings.getLocalString("REALM_SYNCH_SUCCESSFUL", "Synchronization of Realm {0} from Configuration Successful.", new Object[] { realmName }));
report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
return;
}
} catch (BadRealmException ex) {
// throw new RuntimeException(ex);
report.setFailureCause(ex);
report.setActionExitCode(ExitCode.FAILURE);
} catch (NoSuchRealmException ex) {
// throw new RuntimeException(ex);
report.setFailureCause(ex);
report.setActionExitCode(ExitCode.FAILURE);
} catch (Exception ex) {
report.setFailureCause(ex);
report.setActionExitCode(ExitCode.FAILURE);
}
}
use of com.sun.enterprise.config.serverbeans.Server in project Payara by payara.
the class RestartDeploymentGroupCommand method doRolling.
private void doRolling(AdminCommandContext context) {
List<Server> servers = domain.getServersInTarget(deploymentGroup);
StringBuilder output = new StringBuilder();
Logger logger = context.getLogger();
for (Server server : servers) {
ParameterMap instanceParameterMap = new ParameterMap();
// Set the instance name as the operand for the commnd
instanceParameterMap.set("DEFAULT", server.getName());
ActionReport instanceReport = runner.getActionReport("plain");
instanceReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
CommandRunner.CommandInvocation invocation = runner.getCommandInvocation("stop-instance", instanceReport, context.getSubject());
invocation.parameters(instanceParameterMap);
String msg = "stop-instance" + " " + server.getName();
logger.info(msg);
if (verbose) {
output.append(msg).append(NL);
}
invocation.execute();
logger.info(invocation.report().getMessage());
if (verbose) {
output.append(invocation.report().getMessage()).append(NL);
}
instanceParameterMap = new ParameterMap();
// Set the instance name as the operand for the commnd
instanceParameterMap.set("DEFAULT", server.getName());
instanceReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
invocation = runner.getCommandInvocation("start-instance", instanceReport, context.getSubject());
invocation.parameters(instanceParameterMap);
msg = "start-instance" + " " + server.getName();
logger.info(msg);
if (verbose) {
output.append(msg).append(NL);
}
invocation.execute();
logger.info(invocation.report().getMessage());
if (verbose) {
output.append(invocation.report().getMessage()).append(NL);
}
try {
long delayVal = Long.parseLong(delay);
if (delayVal > 0) {
Thread.sleep(delayVal);
}
} catch (InterruptedException e) {
// ignore
}
}
}
Aggregations