/** * Construct ConsulClient with all parameters from consul.yml config file. The other two constructors are * just for backward compatibility. * */ public ConsulClientImpl() { // Will use http/2 connection if tls is enabled as Consul only support HTTP/2 with TLS. String consulUrl = config.getConsulUrl().toLowerCase(); optionMap = consulUrl.startsWith("https") ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY; if(logger.isDebugEnabled()) logger.debug("url = " + consulUrl); if(config.getWait() != null && config.getWait().length() > 2) wait = config.getWait(); if(logger.isDebugEnabled()) logger.debug("wait = " + wait); try { uri = new URI(consulUrl); } catch (URISyntaxException e) { logger.error("Invalid URI " + consulUrl, e); throw new RuntimeException("Invalid URI " + consulUrl, e); } maxReqPerConn = config.getMaxReqPerConn() > 0 ? config.getMaxReqPerConn() : 1000000; }
return create(option2, value2);
@Override public void run() { exchange.getConnection().getIoThread().openStreamConnection(new InetSocketAddress(host, port), new ChannelListener<StreamConnection>() { @Override public void handleEvent(final StreamConnection clientChannel) { exchange.acceptConnectRequest(new HttpUpgradeListener() { @Override public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) { final ClosingExceptionHandler handler = new ClosingExceptionHandler(streamConnection, clientChannel); Transfer.initiateTransfer(clientChannel.getSourceChannel(), streamConnection.getSinkChannel(), ChannelListeners.closingChannelListener(), ChannelListeners.writeShutdownChannelListener(ChannelListeners.<StreamSinkChannel>flushingChannelListener(ChannelListeners.closingChannelListener(), ChannelListeners.closingChannelExceptionHandler()), ChannelListeners.closingChannelExceptionHandler()), handler, handler, exchange.getConnection().getByteBufferPool()); Transfer.initiateTransfer(streamConnection.getSourceChannel(), clientChannel.getSinkChannel(), ChannelListeners.closingChannelListener(), ChannelListeners.writeShutdownChannelListener(ChannelListeners.<StreamSinkChannel>flushingChannelListener(ChannelListeners.closingChannelListener(), ChannelListeners.closingChannelExceptionHandler()), ChannelListeners.closingChannelExceptionHandler()), handler, handler, exchange.getConnection().getByteBufferPool()); } }); exchange.setStatusCode(200); exchange.endExchange(); } }, OptionMap.create(Options.TCP_NODELAY, true)).addNotifier(new IoFuture.Notifier<StreamConnection, Object>() { @Override public void notify(IoFuture<? extends StreamConnection> ioFuture, Object attachment) { if(ioFuture.getStatus() == IoFuture.Status.FAILED) { exchange.setStatusCode(503); exchange.endExchange(); } } },null); } });
private HttpTargetContext getConnectionPoolForURI(URI uri) { HttpTargetContext context = uriConnectionPools.get(uri); if (context != null) { context.init(); return context; } for (ConfigSection target : targets) { if (target.getUri().equals(uri)) { target.getHttpTargetContext().init(); uriConnectionPools.put(uri, target.getHttpTargetContext()); return target.getHttpTargetContext(); } } synchronized (this) { context = uriConnectionPools.get(uri); if (context != null) { return context; } HttpConnectionPool pool = new HttpConnectionPool(maxConnections, maxStreamsPerConnection, worker, this.pool, OptionMap.create(UndertowOptions.ENABLE_HTTP2, enableHttp2), new HostPool(uri), idleTimeout); uriConnectionPools.put(uri, context = new HttpTargetContext(pool, eagerlyAcquireAffinity, uri)); context.init(); return context; } }
try { connection = client.connect(new URI(configUri), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get(); } catch (Exception e) { logger.error("Exeption:", e);
final ClientConnection connection; try { connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true): OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e);
final ClientConnection connection; try { connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true): OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e);
endpoint.addConnectionProvider("remote", remoteConnectionProviderFactory, OptionMap.create(Options.SSL_ENABLED, Boolean.TRUE, Options.SSL_STARTTLS, Boolean.TRUE)); endpoint.addConnectionProvider("remote+tls", remoteConnectionProviderFactory, OptionMap.create(Options.SECURE, Boolean.TRUE)); endpoint.addConnectionProvider("remoting", remoteConnectionProviderFactory, OptionMap.create(Options.SSL_ENABLED, Boolean.TRUE, Options.SSL_STARTTLS, Boolean.TRUE)); endpoint.addConnectionProvider("remote+http", httpUpgradeConnectionProviderFactory, OptionMap.create(Options.SSL_ENABLED, Boolean.FALSE, Options.SSL_STARTTLS, Boolean.TRUE)); endpoint.addConnectionProvider("remote+https", httpUpgradeConnectionProviderFactory, OptionMap.create(Options.SECURE, Boolean.TRUE)); endpoint.addConnectionProvider("http-remoting", httpUpgradeConnectionProviderFactory, OptionMap.create(Options.SSL_ENABLED, Boolean.FALSE, Options.SSL_STARTTLS, Boolean.TRUE)); endpoint.addConnectionProvider("https-remoting", httpUpgradeConnectionProviderFactory, OptionMap.create(Options.SECURE, Boolean.TRUE)); ok = true; return endpoint;
public static String derefToken(DerefRequest derefRequest) throws ClientException { final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try { connection = client.connect(new URI(derefRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, derefRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true): OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e); } final AtomicReference<ClientResponse> reference = new AtomicReference<>(); try { ClientRequest request = new ClientRequest().setPath(derefRequest.getUri()).setMethod(Methods.GET); request.getRequestHeaders().put(Headers.AUTHORIZATION, getBasicAuthHeader(derefRequest.getClientId(), derefRequest.getClientSecret())); request.getRequestHeaders().put(Headers.HOST, "localhost"); connection.sendRequest(request, client.createClientCallback(reference, latch)); latch.await(); } catch (Exception e) { logger.error("Exception: ", e); throw new ClientException(e); } finally { IoUtils.safeClose(connection); } return reference.get().getAttachment(Http2Client.RESPONSE_BODY); }
public static String getKey(KeyRequest keyRequest) throws ClientException { final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try { connection = client.connect(new URI(keyRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, keyRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true): OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e); } final AtomicReference<ClientResponse> reference = new AtomicReference<>(); try { ClientRequest request = new ClientRequest().setPath(keyRequest.getUri()).setMethod(Methods.GET); if (keyRequest.getClientId()!=null) { request.getRequestHeaders().put(Headers.AUTHORIZATION, getBasicAuthHeader(keyRequest.getClientId(), keyRequest.getClientSecret())); } request.getRequestHeaders().put(Headers.HOST, "localhost"); connection.sendRequest(request, client.createClientCallback(reference, latch)); latch.await(); } catch (Exception e) { logger.error("Exception: ", e); throw new ClientException(e); } finally { IoUtils.safeClose(connection); } return reference.get().getAttachment(Http2Client.RESPONSE_BODY); }
@Override public void start(StartContext startContext) throws StartException { //todo: this is a bit of a hack, as the proxy handler may be wrapped by a request controller handler for graceful shutdown ProxyHandler proxyHandler = (ProxyHandler) (this.proxyHandler.getValue() instanceof GlobalRequestControllerHandler ? ((GlobalRequestControllerHandler)this.proxyHandler.getValue()).getNext() : this.proxyHandler.getValue()); final LoadBalancingProxyClient client = (LoadBalancingProxyClient) proxyHandler.getProxyClient(); try { SSLContext sslContext = this.sslContext.getOptionalValue(); if (sslContext == null) { SecurityRealm securityRealm = this.securityRealm.getOptionalValue(); if (securityRealm != null) { sslContext = securityRealm.getSSLContext(); } } if (sslContext == null) { client.addHost(getUri(), instanceId, null, OptionMap.create(UndertowOptions.ENABLE_HTTP2, enableHttp2)); } else { OptionMap.Builder builder = OptionMap.builder(); builder.set(Options.USE_DIRECT_BUFFERS, true); OptionMap combined = builder.getMap(); XnioSsl xnioSsl = new UndertowXnioSsl(Xnio.getInstance(), combined, sslContext); client.addHost(getUri(), instanceId, xnioSsl, OptionMap.create(UndertowOptions.ENABLE_HTTP2, enableHttp2)); } } catch (URISyntaxException e) { throw new StartException(e); } }
WildflyHttpContext build() { XnioWorker worker = XnioWorker.getContextManager().get(); ByteBufferPool pool; if(bufferConfig == null) { pool=new DefaultByteBufferPool(true, 1024, 100, 0, LEAK_DETECTION); //TODO } else { pool = new DefaultByteBufferPool(bufferConfig.isDirect(), bufferConfig.getBufferSize(), bufferConfig.getMaxSize(), bufferConfig.getThreadLocalSize(), LEAK_DETECTION); } //TODO: ssl config ConfigSection[] connections = new ConfigSection[this.targets.size()]; long idleTimout = this.idleTimeout > 0 ? this.idleTimeout : 60000; int maxConnections = this.maxConnections > 0 ? this.maxConnections : 10; int maxStreamsPerConnection = this.maxStreamsPerConnection > 0 ? this.maxStreamsPerConnection : 10; for (int i = 0; i < this.targets.size(); ++i) { HttpConfigBuilder sb = this.targets.get(i); HostPool hp = new HostPool(sb.getUri()); boolean eager = this.eagerlyAcquireSession == null ? false : this.eagerlyAcquireSession; if (sb.getEagerlyAcquireSession() != null && sb.getEagerlyAcquireSession()) { eager = true; } boolean http2 = this.enableHttp2 == null ? true : this.enableHttp2; if(sb.getEnableHttp2() != null) { http2 = sb.getEnableHttp2(); } ConfigSection connection = new ConfigSection(new HttpTargetContext(new HttpConnectionPool(sb.getMaxConnections() > 0 ? sb.getMaxConnections() : maxConnections, sb.getMaxStreamsPerConnection() > 0 ? sb.getMaxStreamsPerConnection() : maxStreamsPerConnection, worker, pool, OptionMap.create(UndertowOptions.ENABLE_HTTP2, http2), hp, sb.getIdleTimeout() > 0 ? sb.getIdleTimeout() : idleTimout), eager, sb.getUri()), sb.getUri()); connections[i] = connection; } return new WildflyHttpContext(connections, maxConnections, maxStreamsPerConnection, idleTimeout, eagerlyAcquireSession == null ? false : eagerlyAcquireSession, worker, pool, enableHttp2 == null ? true : enableHttp2); }
xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), listener.sslContext); } else { OptionMap.Builder builder = OptionMap.builder() builder.set(Options.SSL_PROTOCOL, "TLSv1.2"); xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), JsseSslUtils.createSSLContext(listener.keyManagers, listener.trustManagers, new SecureRandom(), builder.getMap()));
private OptionMap getDefaultOptionMap() { return OptionMap.create(SSL_ENABLED, true, SSL_STARTTLS, true); }
/** * Create a new {@link XnioEventLoopGroup} which creates a new {@link XnioWorker} by itself and use it for all * operations. Using the given number of Threads to handle the IO. * * @throws IOException */ public XnioEventLoopGroup(int numThreads) throws IOException { this(Xnio.getInstance().createWorker(OptionMap.create(Options.WORKER_IO_THREADS, numThreads))); }
/** * 获取XnioWorker * * @return */ private XnioWorker getXnioWorker() { XnioWorker worker = null; try { worker = Xnio.getInstance().createWorker(OptionMap.create(Options.THREAD_DAEMON, true)); } catch (IOException ignored) { } return worker; }
private synchronized void createConnection() { try { endpoint = Remoting.createEndpoint("endpoint", OptionMap.EMPTY); endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(), OptionMap.create(Options.SSL_ENABLED, Boolean.FALSE)); // open a connection final IoFuture<Connection> futureConnection = endpoint.connect(new URI(hostUrl), OptionMap.create(Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE, Options.SASL_POLICY_NOPLAINTEXT, Boolean.FALSE), callbackHandler); connection = IoFutureHelper.get(futureConnection, 30L, TimeUnit.SECONDS); final EJBClientContext ejbClientContext = EJBClientContext.create(); ejbClientContext.registerConnection(connection); this.clientContext = ejbClientContext; } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
protected void addSslContext(ConnectionBuilder connectionBuilder) { SSLContext sslContext = getSslContext(); XnioSsl xnioSsl = new JsseXnioSsl(getXnio(), OptionMap.create(Options.USE_DIRECT_BUFFERS, true), sslContext); connectionBuilder.setSsl(xnioSsl); }
private void deployReverseProxyRoutes(final DeploymentContext context) throws URISyntaxException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { var lastHandler = context.rootHandler(); val ssl = new UndertowXnioSsl( Xnio.getInstance(), OptionMap.EMPTY ); val options = isHttp2EnabledForProxy ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY ; if ( !reverseRoutes.isEmpty() ) log.info( "Reverse Proxy rules:" ); for ( val rule : reverseRoutes ) { log.info( " > " + rule ); val target = URLMatcher.compile( rule.target() ); val proxyClient = createClientFor( rule, target, ssl, options ); lastHandler = new ProxyHandler( proxyClient, lastHandler ); } context.rootHandler( lastHandler ); }
@Override protected void setUpClient(NetworkHandler client, int port, boolean secure) throws IOException { HttpHandler handler = new ActHttpHandler(client); ByteBufferPool buffers = new DefaultByteBufferPool(true, 16 * 1024, -1, 4); HttpOpenListener openListener = new HttpOpenListener(buffers, serverOptions); openListener.setRootHandler(handler); ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener); if (!secure) { AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, socketOptions); server.resumeAccepts(); channels.add(server); } else { XnioSsl xnioSsl; try { SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore")); xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), sslContext); AcceptingChannel<SslConnection> sslServer = xnioSsl.createSslConnectionServer(worker, new InetSocketAddress(port), (ChannelListener)acceptListener, socketOptions); sslServer.resumeAccepts(); channels.add(sslServer); } catch (Exception e) { throw E.unexpected(e); } } }