Refine search
@Override public void unregisterService(String serviceId, String token) { String path = "/v1/agent/service/deregister/" + serviceId; final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<ClientResponse> reference = new AtomicReference<>(); try { if(connection == null || !connection.isOpen() || reqCounter >= maxReqPerConn) { if(logger.isDebugEnabled()) logger.debug("connection is closed with counter " + reqCounter + ", reconnecting..."); connection = client.connect(uri, Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, optionMap).get(); reqCounter = 0; } ClientRequest request = new ClientRequest().setMethod(Methods.PUT).setPath(path); request.getRequestHeaders().put(Headers.HOST, "localhost"); if(token != null) request.getRequestHeaders().put(HttpStringConstants.CONSUL_TOKEN, token); connection.sendRequest(request, client.createClientCallback(reference, latch)); latch.await(); reqCounter++; int statusCode = reference.get().getResponseCode(); if(statusCode >= 300){ System.out.println("body = " + reference.get().getAttachment(Http2Client.RESPONSE_BODY)); throw new Exception("Failed to unregister on Consul: " + statusCode); } } catch (Exception e) { logger.error("Exception:", e); } }
ClientRequest request = httpClientExchange.getRequest(); String connectionString = request.getRequestHeaders().getFirst(Headers.CONNECTION); if (connectionString != null) { if (Headers.CLOSE.equalToString(connectionString)) { state |= UPGRADE_REQUESTED; } else if (request.getProtocol() != Protocols.HTTP_1_1) { state |= CLOSE_REQ; if (request.getRequestHeaders().contains(Headers.UPGRADE)) { state |= UPGRADE_REQUESTED; conduit = httpRequestConduit; String fixedLengthString = request.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH); String transferEncodingString = request.getRequestHeaders().getLast(Headers.TRANSFER_ENCODING); return; conduit = new ChunkedStreamSinkConduit(conduit, httpClientExchange.getConnection().getBufferPool(), false, false, httpClientExchange.getRequest().getRequestHeaders(), requestFinishListener, httpClientExchange); } else { conduit = new ClientFixedLengthStreamSinkConduit(conduit, 0, false, false, currentRequest);
final AtomicReference<ClientResponse> reference = new AtomicReference<>(); final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try { connection.getIoThread().execute(new Runnable() { @Override public void run() { latch.await(10, TimeUnit.SECONDS); } catch (Exception e) { logger.error("IOException: ", e); throw new ClientException(e); } finally { IoUtils.safeClose(connection);
ConnectionHolder holder; if (idleConnections > 0 && idleConnections > coreCachedConnections && (holder = data.availableConnections.peek()) != null) { if (!holder.clientConnection.isOpen()) { IoUtils.safeClose(holder.clientConnection); idleConnections--; } else { data.timeoutKey = WorkerUtils.executeAfter(holder.clientConnection.getIoThread(), data.timeoutTask, remaining, TimeUnit.MILLISECONDS); return;
ClientStatistics stats = connectionHolder.clientConnection.getStatistics(); this.requestCount.incrementAndGet(); if(stats != null) { if (closed) { IoUtils.safeClose(connectionHolder.clientConnection); ConnectionHolder con = hostData.availableConnections.poll(); while (con != null) { IoUtils.safeClose(con.clientConnection); con = hostData.availableConnections.poll(); if (connection.isOpen() && !connection.isUpgraded()) { CallbackHolder callback = hostData.awaitingConnections.poll(); while (callback != null && callback.isCancelled()) { IoUtils.safeClose(holder.clientConnection); if(hostData.availableConnections.size() > coreCachedConnections) { if (hostData.nextTimeout <= 0) { hostData.timeoutKey = WorkerUtils.executeAfter(connection.getIoThread(), hostData.timeoutTask, timeToLive, TimeUnit.MILLISECONDS); hostData.nextTimeout = connectionHolder.timeout; } else if (connection.isOpen() && connection.isUpgraded()) { connection.getCloseSetter().set(null); handleClosedConnection(hostData, connectionHolder);
protected ResponseEntity<String> executeRequest( URI url, HttpString method, HttpHeaders headers, @Nullable String body) { CountDownLatch latch = new CountDownLatch(1); List<ClientResponse> responses = new CopyOnWriteArrayList<>(); this.httpClient.connect(url, this.worker, this.bufferPool, this.optionMap).get(); try { ClientRequest request = new ClientRequest().setMethod(method).setPath(url.getPath()); request.getRequestHeaders().add(HttpString.tryFromString(HttpHeaders.HOST), url.getHost()); if (StringUtils.hasLength(body)) { HttpString headerName = HttpString.tryFromString(HttpHeaders.CONTENT_LENGTH); request.getRequestHeaders().add(headerName, body.length()); connection.sendRequest(request, createRequestCallback(body, responses, latch)); latch.await(); ClientResponse response = responses.iterator().next(); HttpStatus status = HttpStatus.valueOf(response.getResponseCode()); IoUtils.safeClose(connection);
public PortForwarder(Config config, String podName) throws Exception { try { this.portForwardURI = URI.create(String.format(PORT_FWD, config.getMasterUrl(), config.getNamespace(), podName)); ClientRequest request = new ClientRequest() .setMethod(Methods.POST) .setPath(portForwardURI.getPath()); request.getRequestHeaders() .put(Headers.HOST, this.portForwardURI.getHost()) .put(Headers.CONNECTION, "Upgrade") .put(Headers.UPGRADE, "SPDY/3.1"); if (config.getOauthToken() != null) { request.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer " + config.getOauthToken()); final CountDownLatch latch = new CountDownLatch(1); final IOException[] holder = new IOException[1]; connection.sendRequest(request, new ClientCallback<ClientExchange>() { @Override public void completed(ClientExchange result) { latch.await(); if (holder[0] != null) { throw new IOException("Failed to establish portforward client connection", holder[0]); IoUtils.safeClose(connection);
@Override public void completed(ClientConnection connection) { ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath()); HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST); request.getRequestHeaders().add(headerName, url.getHost()); addHttpHeaders(request, headers); HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); connection.sendRequest(request, createReceiveCallback(transportRequest, url, httpHeaders, session, connectFuture)); }
if (hostPool.getUri().getScheme().equals("https")) { sslContext = next.context; if (sslContext != null) { break; if(!existingConnection.connection.isOpen()) { continue; next.errorListener.error(e); }, new URI(hostPoolAddress.getURI().getScheme(), hostPoolAddress.getURI().getUserInfo(), address.getHostAddress(), hostPoolAddress.getURI().getPort(), "/", null, null), worker, ssl, byteBufferPool, options); } catch (URISyntaxException e) { next.errorListener.error(e);
@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) {
@Override public void run() { final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(path); request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked"); request.getRequestHeaders().put(Headers.HOST, "localhost"); connection.sendRequest(request, client.createClientCallback(reference, latch, body)); } });
@Override public void getConnection(ProxyTarget target, HttpServerExchange exchange, ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit) { ClientConnection existing = exchange.getConnection().getAttachment(clientAttachmentKey); if (existing != null) { if (existing.isOpen()) { //this connection already has a client, re-use it callback.completed(exchange, new ProxyConnection(existing, uri.getPath() == null ? "/" : uri.getPath())); return; } else { exchange.getConnection().removeAttachment(clientAttachmentKey); } } client.connect(new ConnectNotifier(callback, exchange), uri, exchange.getIoThread(), exchange.getConnection().getByteBufferPool(), OptionMap.EMPTY); }
@Override public void completed(final ClientConnection connection) { final ServerConnection serverConnection = exchange.getConnection(); //we attach to the connection so it can be re-used serverConnection.putAttachment(clientAttachmentKey, connection); serverConnection.addCloseListener(new ServerConnection.CloseListener() { @Override public void closed(ServerConnection serverConnection) { IoUtils.safeClose(connection); } }); connection.getCloseSetter().set(new ChannelListener<Channel>() { @Override public void handleEvent(Channel channel) { serverConnection.removeAttachment(clientAttachmentKey); } }); callback.completed(exchange, new ProxyConnection(connection, uri.getPath() == null ? "/" : uri.getPath())); }
final boolean authAdded = retry || connection.getAuthenticationContext().prepareRequest(connection.getUri(), request, authenticationConfiguration); if (!request.getRequestHeaders().contains(Headers.HOST)) { String host; int port = connection.getUri().getPort(); if (port == -1) { host = connection.getUri().getHost(); } else { host = connection.getUri().getHost() + ":" + port; request.getRequestHeaders().put(Headers.HOST, host); if (request.getRequestHeaders().contains(Headers.CONTENT_TYPE)) { request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, Headers.CHUNKED.toString()); connection.getConnection().sendRequest(request, new ClientCallback<ClientExchange>() { @Override public void completed(ClientExchange result) {
@Override public void run() { final ClientRequest request = new ClientRequest(); requestURI.append(qs); outboundRequestHeaders.put(Headers.CONNECTION, "keep-alive"); if("h2c".equals(exchange.getRequestHeaders().getFirst(Headers.UPGRADE))) { exchange.getRequestHeaders().remove(Headers.UPGRADE); outboundRequestHeaders.put(Headers.CONNECTION, "keep-alive"); if(!exchange.getConnection().isPushSupported() && clientConnection.getConnection().isPushSupported()) { request.getRequestHeaders().put(Headers.X_DISABLE_PUSH, "true"); InetSocketAddress targetAddress = clientConnection.getConnection().getPeerAddress(InetSocketAddress.class); request.getRequestHeaders().put(Headers.HOST, targetAddress.getHostString() + ":" + targetAddress.getPort()); request.getRequestHeaders().put(Headers.X_FORWARDED_HOST, exchange.getRequestHeaders().getFirst(Headers.HOST)); log.debugf("Sending request %s to target %s for exchange %s", request, clientConnection.getConnection().getPeerAddress(), exchange); clientConnection.getConnection().sendRequest(request, new ClientCallback<ClientExchange>() { @Override public void completed(final ClientExchange result) {
@Override public void sendRequest(final ClientRequest request, final ClientCallback<ClientExchange> clientCallback) { if(http2Delegate != null) { http2Delegate.sendRequest(request, clientCallback); return; } if (anyAreSet(state, UPGRADE_REQUESTED | UPGRADED | CLOSE_REQ | CLOSED)) { clientCallback.failed(UndertowClientMessages.MESSAGES.invalidConnectionState()); return; } final HttpClientExchange httpClientExchange = new HttpClientExchange(clientCallback, request, this); boolean ssl = this.connection instanceof SslConnection; if(!ssl && !http2Tried && options.get(UndertowOptions.ENABLE_HTTP2, false) && !request.getRequestHeaders().contains(Headers.UPGRADE)) { //this is the first request, as we want to try a HTTP2 upgrade request.getRequestHeaders().put(new HttpString("HTTP2-Settings"), Http2ClearClientProvider.createSettingsFrame(options, bufferPool)); request.getRequestHeaders().put(Headers.UPGRADE, Http2Channel.CLEARTEXT_UPGRADE_STRING); request.getRequestHeaders().put(Headers.CONNECTION, "Upgrade, HTTP2-Settings"); http2Tried = true; } if (currentRequest == null) { initiateRequest(httpClientExchange); } else { pendingQueue.add(httpClientExchange); } }
@Override public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) { if(log.isDebugEnabled()) { log.debugf("Upgraded request %s to for exchange %s", result.getRequest(), exchange); } StreamConnection clientChannel = null; try { clientChannel = result.getConnection().performUpgrade(); 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, result.getConnection().getBufferPool()); Transfer.initiateTransfer(streamConnection.getSourceChannel(), clientChannel.getSinkChannel(), ChannelListeners.closingChannelListener(), ChannelListeners.writeShutdownChannelListener(ChannelListeners.<StreamSinkChannel>flushingChannelListener(ChannelListeners.closingChannelListener(), ChannelListeners.closingChannelExceptionHandler()), ChannelListeners.closingChannelExceptionHandler()), handler, handler, result.getConnection().getBufferPool()); } catch (IOException e) { IoUtils.safeClose(streamConnection, clientChannel); } } });
@Override public void done(boolean close) { if (!state.compareAndSet(1, 0)) { return; } if (close) { IoUtils.safeClose(connection); } timeout = System.currentTimeMillis() + connectionIdleTimeout; if (timeoutKey == null && connectionIdleTimeout > 0 && !close) { timeoutKey = connection.getIoThread().executeAfter(timeoutTask, connectionIdleTimeout, TimeUnit.MILLISECONDS); } returnConnection(this); }
public ClientResponse send(URI uri, Optional<String> httpMethod) throws Exception { HttpString method = httpMethod.map(String::toUpperCase).map(Methods::fromString).orElse(Methods.GET); ClientRequest request = new ClientRequest(); request.setMethod(method); request.setPath(URISupport.pathAndQueryOf(uri)); IoFuture<ClientConnection> connectFuture = client.connect(uri, worker, pool, OptionMap.EMPTY); UndertowClientResponseFuture responseFuture = new UndertowClientResponseFuture(); connectFuture.get().sendRequest(request, responseFuture); // We should set a timeout return responseFuture.get().getResponse(); } }
HostThreadData data = getData(); ConnectionHolder connectionHolder = data.availableConnections.poll(); while (connectionHolder != null && !connectionHolder.clientConnection.isOpen()) { connectionHolder = data.availableConnections.poll(); boolean upgradeRequest = exchange.getRequestHeaders().contains(Headers.UPGRADE); if (connectionHolder != null && (!upgradeRequest || connectionHolder.clientConnection.isUpgradeSupported())) { if (exclusive) { data.connections--;