use of org.glassfish.api.admin.CommandException in project Payara by payara.
the class LocalServerCommand method getAdminAddress.
/**
* Returns the admin address of a particular server. Note that this method
* should be called only when you own the server that is available on
* an accessible file system.
*
* @return HostAndPort object with admin server address
* @throws CommandException in case of parsing errors
*/
protected final HostAndPort getAdminAddress(String serverName) throws CommandException {
try {
MiniXmlParser parser = new MiniXmlParser(getDomainXml(), serverName);
List<HostAndPort> addrSet = parser.getAdminAddresses();
if (addrSet.size() > 0)
return addrSet.get(0);
else
throw new CommandException(strings.get("NoAdminPort"));
} catch (MiniXmlParserException ex) {
throw new CommandException(strings.get("NoAdminPortEx", ex), ex);
}
}
use of org.glassfish.api.admin.CommandException in project Payara by payara.
the class LocalServerCommand method getUptime.
/**
* Get uptime from the server.
*/
protected final long getUptime() throws CommandException {
RemoteCLICommand cmd = new RemoteCLICommand("uptime", programOpts, env);
String up = cmd.executeAndReturnOutput("uptime", "--milliseconds").trim();
long up_ms = parseUptime(up);
if (up_ms <= 0) {
throw new CommandException(strings.get("restart.dasNotRunning"));
}
logger.log(Level.FINER, "server uptime: {0}", up_ms);
return up_ms;
}
use of org.glassfish.api.admin.CommandException in project Payara by payara.
the class LocalServerCommand method retry.
private String retry(int times) throws CommandException {
String mpv;
// prompt times times
for (int i = 0; i < times; i++) {
// XXX - I18N
String prompt = strings.get("mp.prompt", (times - i));
char[] mpvArr = super.readPassword(prompt);
mpv = mpvArr != null ? new String(mpvArr) : null;
if (mpv == null)
throw new CommandException(strings.get("no.console"));
// ignore retries :)
if (verifyMasterPassword(mpv))
return mpv;
if (i < (times - 1))
logger.info(strings.get("retry.mp"));
// make them pay for typos?
// Thread.currentThread().sleep((i+1)*10000);
}
throw new CommandException(strings.get("mp.giveup", times));
}
use of org.glassfish.api.admin.CommandException in project Payara by payara.
the class RemoteAdminCommand method doHttpCommand.
/**
* Set up an HTTP connection, call cmd.prepareConnection so the consumer of
* the connection can further configure it, then open the connection (following
* redirects if needed), then call cmd.useConnection so the consumer of the
* connection can use it.
* <P>
* This method will try to execute the command repeatedly, for example,
* retrying with updated credentials (typically from the interactive user), etc., until the
* command succeeds or there are no more ways to retry that might succeed.
*
* @param uriString the URI to connect to
* @param httpMethod the HTTP method to use for the connection
* @param cmd the HttpCommand object
* @throws CommandException if anything goes wrong
*/
private void doHttpCommand(String uriString, String httpMethod, HttpCommand cmd, boolean isForMetadata) throws CommandException {
HttpURLConnection urlConnection;
/*
* There are various reasons we might retry the command - an authentication
* challenges from the DAS, shifting from an insecure connection to
* a secure one, etc. So just keep trying as long as it makes sense.
*
* Any exception handling code inside the loop that changes something
* about the connection or the request and wants to retry must set
* shoudTryCommandAgain to true.
*/
boolean shouldTryCommandAgain;
/*
* If the DAS challenges us for credentials and we've already sent
* the caller-provided ones, we might ask the user for a new set
* and use them. But we want to ask only once.
*/
boolean askedUserForCredentials = false;
/*
* On a subsequent retry we might need to use secure, even if the
* caller did not request it.
*/
boolean shouldUseSecure = secure;
/*
* Send the caller-provided credentials (typically from command line
* options or the password file) on the first attempt only if we know
* the connection will
* be secure.
*/
boolean usedCallerProvidedCredentials = secure;
/*
* Note: HttpConnectorAddress will set up SSL/TLS client cert
* handling if the current configuration calls for it.
*/
HttpConnectorAddress url = getHttpConnectorAddress(host, port, shouldUseSecure);
url.setInteractive(interactive);
do {
/*
* Any code that wants to trigger a retry will say so explicitly.
*/
shouldTryCommandAgain = false;
try {
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "URI: {0}", uriString);
logger.log(Level.FINER, "URL: {0}", url.toString());
logger.log(Level.FINER, "URL: {0}", url.toURL(uriString).toString());
logger.log(Level.FINER, "Password options: {0}", passwordOptions);
logger.log(Level.FINER, "Using auth info: User: {0}, Password: {1}", new Object[] { user, (password != null && password.length > 0) ? "<non-null>" : "<null>" });
}
final AuthenticationInfo authInfo = authenticationInfo();
if (authInfo != null) {
url.setAuthenticationInfo(authInfo);
}
urlConnection = (HttpURLConnection) url.openConnection(uriString);
urlConnection.setRequestProperty("User-Agent", responseFormatType);
if (passwordOptions != null) {
urlConnection.setRequestProperty("X-passwords", passwordOptions.toString());
}
if (authToken != null) {
/*
* If this request is for metadata then we expect to reuse
* the auth token.
*/
urlConnection.setRequestProperty(SecureAdmin.Util.ADMIN_ONE_TIME_AUTH_TOKEN_HEADER_NAME, (isForMetadata ? AuthTokenManager.markTokenForReuse(authToken) : authToken));
}
if (commandModel != null && isCommandModelFromCache() && commandModel instanceof CachedCommandModel) {
urlConnection.setRequestProperty(COMMAND_MODEL_MATCH_HEADER, ((CachedCommandModel) commandModel).getETag());
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "CommandModel ETag: {0}", ((CachedCommandModel) commandModel).getETag());
}
}
urlConnection.setRequestMethod(httpMethod);
urlConnection.setReadTimeout(readTimeout);
if (connectTimeout >= 0)
urlConnection.setConnectTimeout(connectTimeout);
addAdditionalHeaders(urlConnection);
cmd.prepareConnection(urlConnection);
urlConnection.connect();
/*
* We must handle redirection from http to https explicitly
* because, even if the HttpURLConnection's followRedirect is
* set to true, the Java SE implementation does not do so if the
* procotols are different.
*/
String redirection = checkConnect(urlConnection);
if (redirection != null) {
/*
* Log at FINER; at FINE it would appear routinely when used from
* asadmin.
*/
logger.log(Level.FINER, "Following redirection to " + redirection);
url = followRedirection(url, redirection);
shouldTryCommandAgain = true;
/*
* Record that, during the retry of this request, we should
* use https.
*/
shouldUseSecure = url.isSecure();
/*
* Record that, if this is a metadata request, the real
* request should use https also.
*/
secure = true;
urlConnection.disconnect();
continue;
}
/*
* No redirection, so we have established the connection.
* Now delegate again to the command processing to use the
* now-created connection.
*/
cmd.useConnection(urlConnection);
processHeaders(urlConnection);
logger.finer("doHttpCommand succeeds");
} catch (AuthenticationException authEx) {
logger.log(Level.FINER, "DAS has challenged for credentials");
/*
* The DAS has challenged us to provide valid credentials.
*
* We might have sent the request without credentials previously
* (because the connection was not secure, typically). In that case,
* retry using the caller provided credentials (if there are any).
*/
if (!usedCallerProvidedCredentials) {
logger.log(Level.FINER, "Have not tried caller-supplied credentials yet; will do that next");
usedCallerProvidedCredentials = true;
shouldTryCommandAgain = true;
continue;
}
/*
* We already tried the caller-provided credentials. Try to
* update the credentials if we haven't already done so.
*/
logger.log(Level.FINER, "Already used caller-supplied credentials");
if (askedUserForCredentials) {
/*
* We already updated the credentials once, and the updated
* ones did not work. No recourse.
*/
logger.log(Level.FINER, "Already tried with updated credentials; cannot authenticate");
throw authEx;
}
/*
* Try to update the creds.
*/
logger.log(Level.FINER, "Have not yet tried to update credentials, so will try to update them");
if (!updateAuthentication()) {
/*
* No updated credentials are avaiable, so we
* have no more options.
*/
logger.log(Level.FINER, "Could not update credentials; cannot authenticate");
throw authEx;
}
/*
* We have another set of credentials we can try.
*/
logger.log(Level.FINER, "Was able to update the credentials so will retry with the updated ones");
askedUserForCredentials = true;
shouldTryCommandAgain = true;
continue;
} catch (ConnectException ce) {
logger.finer("doHttpCommand: connect exception " + ce);
// this really means nobody was listening on the remote server
// note: ConnectException extends IOException and tells us more!
String msg = strings.get("ConnectException", host, port + "");
throw new CommandException(msg, ce);
} catch (UnknownHostException he) {
logger.finer("doHttpCommand: host exception " + he);
// bad host name
String msg = strings.get("UnknownHostException", host);
throw new CommandException(msg, he);
} catch (SocketException se) {
logger.finer("doHttpCommand: socket exception " + se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (serverAppearsSecure && !shouldUseSecure) {
if (retryUsingSecureConnection(host, port)) {
// retry using secure connection
shouldUseSecure = true;
usedCallerProvidedCredentials = true;
shouldTryCommandAgain = true;
continue;
}
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SSLException se) {
logger.finer("doHttpCommand: SSL exception " + se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (!serverAppearsSecure && secure) {
logger.log(Level.SEVERE, AdminLoggerInfo.mServerIsNotSecure, new Object[] { host, port });
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SocketTimeoutException e) {
logger.finer("doHttpCommand: read timeout " + e);
throw new CommandException(strings.get("ReadTimeout", (float) readTimeout / 1000), e);
} catch (IOException e) {
logger.finer("doHttpCommand: IO exception " + e);
throw new CommandException(strings.get("IOError", e.getMessage()), e);
} catch (CommandException e) {
throw e;
} catch (Exception e) {
// logger.log(Level.FINER, "doHttpCommand: exception", e);
logger.finer("doHttpCommand: exception " + e);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(buf));
logger.finer(buf.toString());
throw new CommandException(e);
}
} while (shouldTryCommandAgain);
// no longer needed
outboundPayload = null;
}
use of org.glassfish.api.admin.CommandException in project Payara by payara.
the class LocalOSGiShellCommand method executeCommand.
@Override
protected int executeCommand() throws CommandException, CommandValidationException {
ConsoleReader reader = null;
if (cmd == null) {
throw new CommandException("Remote command 'osgi' is not available.");
}
// restore echo flag, saved in validate
programOpts.setEcho(echo);
try {
if (encoding != null) {
// see Configuration.getEncoding()...
System.setProperty("input.encoding", encoding);
}
String[] args = new String[] { REMOTE_COMMAND, "asadmin-osgi-shell" };
args = enhanceForTarget(args);
shellType = cmd.executeAndReturnOutput(args).trim();
if (file == null) {
System.out.println(strings.get("multimodeIntro"));
reader = new ConsoleReader(REMOTE_COMMAND, new FileInputStream(FileDescriptor.in), System.out, null);
} else {
printPrompt = false;
if (!file.canRead()) {
throw new CommandException("File: " + file + " can not be read");
}
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
return;
}
@Override
public void write(byte[] b) throws IOException {
return;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
return;
}
};
reader = new ConsoleReader(REMOTE_COMMAND, new FileInputStream(file), out, null);
}
reader.setBellEnabled(false);
reader.addCompleter(getCommandCompleter());
return executeCommands(reader);
} catch (IOException e) {
throw new CommandException(e);
}
}
Aggregations