use of org.xnio.http.RedirectException in project wildfly-core by wildfly.
the class ReloadHandler method ensureServerRebootComplete.
private void ensureServerRebootComplete(CommandContext ctx, ModelControllerClient client) throws CommandLineException {
final long start = System.currentTimeMillis();
final long timeoutMillis = ctx.getConfig().getConnectionTimeout() + 1000L;
final ModelNode getStateOp = new ModelNode();
if (ctx.isDomainMode()) {
final ParsedCommandLine args = ctx.getParsedCommandLine();
final String hostName = host.getValue(args);
getStateOp.get(Util.ADDRESS).add(Util.HOST, hostName);
}
getStateOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
// this is left for compatibility with older hosts, it could use runtime-configuration-state on newer hosts.
if (ctx.isDomainMode()) {
getStateOp.get(ClientConstants.NAME).set("host-state");
} else {
getStateOp.get(ClientConstants.NAME).set("server-state");
}
while (true) {
String serverState = null;
try {
final ModelNode response = client.execute(getStateOp);
if (Util.isSuccess(response)) {
serverState = response.get(ClientConstants.RESULT).asString();
if ("running".equals(serverState) || "restart-required".equals(serverState)) {
// we're reloaded and the server is started
break;
}
}
} catch (IOException e) {
// A Redirect Exception? Need to connect again the Client
// if that is an http to https redirect only.
Throwable ex = e;
while (ex != null) {
if (ex instanceof RedirectException) {
// Attempt to reconnect the context
if (Util.reconnectContext((RedirectException) ex, ctx)) {
return;
}
} else if (ex instanceof SaslException) {
// invalid (eg: change of security-realm or SASL reconfiguration).
try {
ctx.connectController();
return;
} catch (CommandLineException clex) {
// Not reconnected.
}
}
ex = ex.getCause();
}
// ignore and try again
} catch (IllegalStateException ex) {
// ignore and try again
// IllegalStateException is because the embedded server ModelControllerClient will
// throw that when the server-state / host-state is "stopping"
}
if (System.currentTimeMillis() - start > timeoutMillis) {
if (!"starting".equals(serverState)) {
ctx.disconnectController();
throw new CommandLineException("Failed to establish connection in " + (System.currentTimeMillis() - start) + "ms");
}
// else we don't wait any longer for start to finish
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
ctx.disconnectController();
throw new CommandLineException("Interrupted while pausing before reconnecting.", e);
}
}
}
use of org.xnio.http.RedirectException in project wildfly-core by wildfly.
the class CLIModelControllerClient method ensureConnected.
@Override
public void ensureConnected(long timeoutMillis) throws CommandLineException, IOException {
boolean doTry = true;
final long start = System.currentTimeMillis();
IOException ioe = null;
boolean timeoutOccured = false;
while (doTry) {
try {
// Can't be called locked, could create dead lock if close occured.
getOrCreateChannel().getConnection();
doTry = false;
} catch (IOException e) {
ioe = e;
synchronized (lock) {
if (strategy != null) {
StreamUtils.safeClose(strategy);
strategy = null;
}
lock.notifyAll();
}
}
if (ioe != null) {
if (ioe.getCause() != null && ioe.getCause() instanceof SaslException) {
throw new CommandLineException("Failed to establish connection", ioe);
}
if (System.currentTimeMillis() - start > timeoutMillis) {
if (timeoutOccured) {
throw new CommandLineException("Failed to establish connection in " + (System.currentTimeMillis() - start) + "ms", ioe);
} else {
timeoutOccured = true;
}
}
// Only propagate RedirectException at the end of timeout.
if (timeoutOccured) {
Throwable ex = ioe;
while (ex != null) {
if (ex instanceof RedirectException) {
// only http to https redirect.
try {
if (Util.isHttpsRedirect((RedirectException) ex, channelConfig.getUri().getScheme())) {
throw (RedirectException) ex;
}
} catch (URISyntaxException uriex) {
// XXX OK, would fail later.
}
}
ex = ex.getCause();
}
}
ioe = null;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new CommandLineException("Interrupted while pausing before reconnecting.", e);
}
}
}
}
use of org.xnio.http.RedirectException in project OpenUnison by TremoloSecurity.
the class ConnectionBuilder method connectImpl.
private IoFuture<WebSocketChannel> connectImpl(final URI uri, final FutureResult<WebSocketChannel> ioFuture, final int redirectCount) {
WebSocketLogger.REQUEST_LOGGER.debugf("Opening websocket connection to %s", uri);
final String scheme = uri.getScheme().equals("wss") ? "https" : "http";
final URI newUri;
try {
newUri = new URI(scheme, uri.getUserInfo(), uri.getHost(), uri.getPort() == -1 ? (uri.getScheme().equals("wss") ? 443 : 80) : uri.getPort(), uri.getPath().isEmpty() ? "/" : uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
final WebSocketClientHandshake handshake = WebSocketClientHandshake.create(version, newUri, clientNegotiation, clientExtensions);
final Map<String, String> originalHeaders = handshake.createHeaders();
originalHeaders.put(Headers.HOST_STRING, uri.getHost() + ":" + newUri.getPort());
final Map<String, List<String>> headers = new HashMap<>();
for (Map.Entry<String, String> entry : originalHeaders.entrySet()) {
List<String> list = new ArrayList<>();
list.add(entry.getValue());
headers.put(entry.getKey(), list);
}
headers.putAll(this.additionalHeaders);
if (clientNegotiation != null) {
clientNegotiation.beforeRequest(headers);
}
InetSocketAddress toBind = bindAddress;
String sysBind = System.getProperty(WebSocketClient.BIND_PROPERTY);
if (toBind == null && sysBind != null) {
toBind = new InetSocketAddress(sysBind, 0);
}
if (proxyUri != null) {
UndertowClient.getInstance().connect(new ClientCallback<ClientConnection>() {
@Override
public void completed(final ClientConnection connection) {
int port = uri.getPort() > 0 ? uri.getPort() : uri.getScheme().equals("https") || uri.getScheme().equals("wss") ? 443 : 80;
ClientRequest cr = new ClientRequest().setMethod(Methods.CONNECT).setPath(uri.getHost() + ":" + port).setProtocol(Protocols.HTTP_1_1);
cr.getRequestHeaders().put(Headers.HOST, proxyUri.getHost() + ":" + (proxyUri.getPort() > 0 ? proxyUri.getPort() : 80));
connection.sendRequest(cr, new ClientCallback<ClientExchange>() {
@Override
public void completed(ClientExchange result) {
result.setResponseListener(new ClientCallback<ClientExchange>() {
@Override
public void completed(ClientExchange response) {
try {
if (response.getResponse().getResponseCode() == 200) {
try {
StreamConnection targetConnection = connection.performUpgrade();
WebSocketLogger.REQUEST_LOGGER.debugf("Established websocket connection to %s", uri);
if (uri.getScheme().equals("wss") || uri.getScheme().equals("https")) {
handleConnectionWithExistingConnection(((UndertowXnioSsl) ssl).wrapExistingConnection(targetConnection, optionMap));
} else {
handleConnectionWithExistingConnection(targetConnection);
}
} catch (IOException e) {
ioFuture.setException(e);
} catch (Exception e) {
ioFuture.setException(new IOException(e));
}
} else {
ioFuture.setException(UndertowMessages.MESSAGES.proxyConnectionFailed(response.getResponse().getResponseCode()));
}
} catch (Exception e) {
ioFuture.setException(new IOException(e));
}
}
private void handleConnectionWithExistingConnection(StreamConnection targetConnection) {
final IoFuture<?> result;
result = HttpUpgrade.performUpgrade(targetConnection, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), handshake.handshakeChecker(newUri, headers));
result.addNotifier(new IoFuture.Notifier<Object, Object>() {
@Override
public void notify(IoFuture<?> res, Object attachment) {
if (res.getStatus() == IoFuture.Status.FAILED) {
ioFuture.setException(res.getException());
}
}
}, null);
ioFuture.addCancelHandler(new Cancellable() {
@Override
public Cancellable cancel() {
result.cancel();
return null;
}
});
}
@Override
public void failed(IOException e) {
ioFuture.setException(e);
}
});
}
@Override
public void failed(IOException e) {
ioFuture.setException(e);
}
});
}
@Override
public void failed(IOException e) {
ioFuture.setException(e);
}
}, bindAddress, proxyUri, worker, proxySsl, bufferPool, optionMap);
} else {
final IoFuture<?> result;
if (ssl != null) {
result = HttpUpgrade.performUpgrade(worker, ssl, toBind, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), null, optionMap, handshake.handshakeChecker(newUri, headers));
} else {
result = HttpUpgrade.performUpgrade(worker, toBind, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), null, optionMap, handshake.handshakeChecker(newUri, headers));
}
result.addNotifier(new IoFuture.Notifier<Object, Object>() {
@Override
public void notify(IoFuture<?> res, Object attachment) {
if (res.getStatus() == IoFuture.Status.FAILED) {
IOException exception = res.getException();
if (exception instanceof RedirectException) {
if (redirectCount == MAX_REDIRECTS) {
ioFuture.setException(UndertowMessages.MESSAGES.tooManyRedirects(exception));
} else {
String path = ((RedirectException) exception).getLocation();
try {
connectImpl(new URI(path), ioFuture, redirectCount + 1);
} catch (URISyntaxException e) {
ioFuture.setException(new IOException(e));
}
}
} else {
ioFuture.setException(exception);
}
}
}
}, null);
ioFuture.addCancelHandler(new Cancellable() {
@Override
public Cancellable cancel() {
result.cancel();
return null;
}
});
}
return ioFuture.getIoFuture();
}
use of org.xnio.http.RedirectException in project wildfly-core by wildfly.
the class ShutdownHandler method doHandle.
/* (non-Javadoc)
* @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
*/
@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
final ModelControllerClient client = ctx.getModelControllerClient();
if (client == null) {
throw new CommandLineException("Connection is not available.");
}
if (embeddedServerRef != null && embeddedServerRef.get() != null) {
embeddedServerRef.get().stop();
return;
}
if (!(client instanceof AwaiterModelControllerClient)) {
throw new CommandLineException("Unsupported ModelControllerClient implementation " + client.getClass().getName());
}
final AwaiterModelControllerClient cliClient = (AwaiterModelControllerClient) client;
final ModelNode op = this.buildRequestWithoutHeaders(ctx);
boolean disconnect = true;
final String restartValue = restart.getValue(ctx.getParsedCommandLine());
if (Util.TRUE.equals(restartValue) || ctx.isDomainMode() && !isLocalHost(ctx.getModelControllerClient(), host.getValue(ctx.getParsedCommandLine()))) {
disconnect = false;
}
try {
final ModelNode response = cliClient.execute(op, true);
if (!Util.isSuccess(response)) {
throw new CommandLineException(Util.getFailureDescription(response));
}
} catch (IOException e) {
// if it's not connected, it's assumed the connection has already been shutdown
if (cliClient.isConnected()) {
StreamUtils.safeClose(client);
throw new CommandLineException("Failed to execute :shutdown", e);
}
}
if (disconnect) {
ctx.disconnectController();
} else {
// waiting half a sec on my machine works perfectly
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new CommandLineException("Interrupted while pausing before reconnecting.", e);
}
try {
cliClient.ensureConnected(ctx.getConfig().getConnectionTimeout() + 1000L);
} catch (CommandLineException e) {
ctx.disconnectController();
throw e;
} catch (IOException ex) {
if (ex instanceof RedirectException) {
if (!Util.reconnectContext((RedirectException) ex, ctx)) {
throw new CommandLineException("Can't reconnect context.", ex);
}
} else {
throw new CommandLineException(ex);
}
}
}
}
use of org.xnio.http.RedirectException in project wildfly-core by wildfly.
the class CommandContextImpl method tryConnection.
/**
* Used to make a call to the server to verify that it is possible to connect.
*/
private void tryConnection(final ModelControllerClient client, ControllerAddress address) throws CommandLineException, RedirectException {
try {
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
builder.setOperationName(Util.READ_ATTRIBUTE);
builder.addProperty(Util.NAME, Util.NAME);
final long start = System.currentTimeMillis();
final long timeoutMillis = config.getConnectionTimeout() + 1000L;
boolean tryConnection = true;
while (tryConnection) {
final ModelNode response = client.execute(builder.buildRequest());
if (!Util.isSuccess(response)) {
// here we check whether the error is related to the access control permissions
// WFLYCTL0332: Permission denied
// WFLYCTL0313: Unauthorized to execute operation
final String failure = Util.getFailureDescription(response);
if (failure.contains("WFLYCTL0332")) {
StreamUtils.safeClose(client);
throw new CommandLineException("Connection refused based on the insufficient user permissions." + " Please, make sure the security-realm attribute is specified for the relevant management interface" + " (standalone.xml/host.xml) and review the access-control configuration (standalone.xml/domain.xml).");
} else if (failure.contains("WFLYCTL0379")) {
// system boot is in process
if (System.currentTimeMillis() - start > timeoutMillis) {
throw new CommandLineException("Timeout waiting for the system to boot.");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
disconnectController();
throw new CommandLineException("Interrupted while pausing before trying connection.", e);
}
} else {
// Otherwise, on one hand, we don't actually care what the response is,
// we just want to be sure the ModelControllerClient does not throw an Exception.
// On the other hand, reading name attribute is a very basic one which should always work
printLine("Warning! The connection check resulted in failure: " + Util.getFailureDescription(response));
tryConnection = false;
}
} else {
tryConnection = false;
}
}
} catch (Exception e) {
try {
Throwable current = e;
while (current != null) {
if (current instanceof SaslException) {
throw new CommandLineException("Unable to authenticate against controller at " + address.getHost() + ":" + address.getPort(), current);
}
if (current instanceof SSLException) {
throw new CommandLineException("Unable to negotiate SSL connection with controller at " + address.getHost() + ":" + address.getPort());
}
if (current instanceof RedirectException) {
throw (RedirectException) current;
}
if (current instanceof CommandLineException) {
throw (CommandLineException) current;
}
current = current.getCause();
}
// We don't know what happened, most likely a timeout.
throw new CommandLineException("The controller is not available at " + address.getHost() + ":" + address.getPort(), e);
} finally {
StreamUtils.safeClose(client);
}
}
}
Aggregations