Path: blob/master/src/java.net.http/share/classes/jdk/internal/net/http/Http2ClientImpl.java
41171 views
/*1* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package jdk.internal.net.http;2627import java.io.EOFException;28import java.io.IOException;29import java.io.UncheckedIOException;30import java.net.ConnectException;31import java.net.InetSocketAddress;32import java.net.URI;33import java.util.Base64;34import java.util.Collections;35import java.util.HashSet;36import java.util.Map;37import java.util.Set;38import java.util.concurrent.ConcurrentHashMap;39import java.util.concurrent.CompletableFuture;40import jdk.internal.net.http.common.Log;41import jdk.internal.net.http.common.Logger;42import jdk.internal.net.http.common.MinimalFuture;43import jdk.internal.net.http.common.Utils;44import jdk.internal.net.http.frame.SettingsFrame;45import static jdk.internal.net.http.frame.SettingsFrame.INITIAL_WINDOW_SIZE;46import static jdk.internal.net.http.frame.SettingsFrame.ENABLE_PUSH;47import static jdk.internal.net.http.frame.SettingsFrame.HEADER_TABLE_SIZE;48import static jdk.internal.net.http.frame.SettingsFrame.MAX_CONCURRENT_STREAMS;49import static jdk.internal.net.http.frame.SettingsFrame.MAX_FRAME_SIZE;5051/**52* Http2 specific aspects of HttpClientImpl53*/54class Http2ClientImpl {5556final static Logger debug =57Utils.getDebugLogger("Http2ClientImpl"::toString, Utils.DEBUG);5859private final HttpClientImpl client;6061Http2ClientImpl(HttpClientImpl client) {62this.client = client;63}6465/* Map key is "scheme:host:port" */66private final Map<String,Http2Connection> connections = new ConcurrentHashMap<>();6768private final Set<String> failures = Collections.synchronizedSet(new HashSet<>());6970/**71* When HTTP/2 requested only. The following describes the aggregate behavior including the72* calling code. In all cases, the HTTP2 connection cache73* is checked first for a suitable connection and that is returned if available.74* If not, a new connection is opened, except in https case when a previous negotiate failed.75* In that case, we want to continue using http/1.1. When a connection is to be opened and76* if multiple requests are sent in parallel then each will open a new connection.77*78* If negotiation/upgrade succeeds then79* one connection will be put in the cache and the others will be closed80* after the initial request completes (not strictly necessary for h2, only for h2c)81*82* If negotiate/upgrade fails, then any opened connections remain open (as http/1.1)83* and will be used and cached in the http/1 cache. Note, this method handles the84* https failure case only (by completing the CF with an ALPN exception, handled externally)85* The h2c upgrade is handled externally also.86*87* Specific CF behavior of this method.88* 1. completes with ALPN exception: h2 negotiate failed for first time. failure recorded.89* 2. completes with other exception: failure not recorded. Caller must handle90* 3. completes normally with null: no connection in cache for h2c or h2 failed previously91* 4. completes normally with connection: h2 or h2c connection in cache. Use it.92*/93CompletableFuture<Http2Connection> getConnectionFor(HttpRequestImpl req,94Exchange<?> exchange) {95URI uri = req.uri();96InetSocketAddress proxy = req.proxy();97String key = Http2Connection.keyFor(uri, proxy);9899synchronized (this) {100Http2Connection connection = connections.get(key);101if (connection != null) {102try {103if (connection.closed || !connection.reserveStream(true)) {104if (debug.on())105debug.log("removing found closed or closing connection: %s", connection);106deleteConnection(connection);107} else {108// fast path if connection already exists109if (debug.on())110debug.log("found connection in the pool: %s", connection);111return MinimalFuture.completedFuture(connection);112}113} catch (IOException e) {114// thrown by connection.reserveStream()115return MinimalFuture.failedFuture(e);116}117}118119if (!req.secure() || failures.contains(key)) {120// secure: negotiate failed before. Use http/1.1121// !secure: no connection available in cache. Attempt upgrade122if (debug.on()) debug.log("not found in connection pool");123return MinimalFuture.completedFuture(null);124}125}126return Http2Connection127.createAsync(req, this, exchange)128.whenComplete((conn, t) -> {129synchronized (Http2ClientImpl.this) {130if (conn != null) {131try {132conn.reserveStream(true);133} catch (IOException e) {134throw new UncheckedIOException(e); // shouldn't happen135}136offerConnection(conn);137} else {138Throwable cause = Utils.getCompletionCause(t);139if (cause instanceof Http2Connection.ALPNException)140failures.add(key);141}142}143});144}145146/*147* Cache the given connection, if no connection to the same148* destination exists. If one exists, then we let the initial stream149* complete but allow it to close itself upon completion.150* This situation should not arise with https because the request151* has not been sent as part of the initial alpn negotiation152*/153boolean offerConnection(Http2Connection c) {154if (debug.on()) debug.log("offering to the connection pool: %s", c);155if (c.closed || c.finalStream()) {156if (debug.on())157debug.log("skipping offered closed or closing connection: %s", c);158return false;159}160161String key = c.key();162synchronized(this) {163Http2Connection c1 = connections.putIfAbsent(key, c);164if (c1 != null) {165c.setFinalStream();166if (debug.on())167debug.log("existing entry in connection pool for %s", key);168return false;169}170if (debug.on())171debug.log("put in the connection pool: %s", c);172return true;173}174}175176void deleteConnection(Http2Connection c) {177if (debug.on())178debug.log("removing from the connection pool: %s", c);179synchronized (this) {180Http2Connection c1 = connections.get(c.key());181if (c1 != null && c1.equals(c)) {182connections.remove(c.key());183if (debug.on())184debug.log("removed from the connection pool: %s", c);185}186}187}188189private EOFException STOPPED;190void stop() {191if (debug.on()) debug.log("stopping");192STOPPED = new EOFException("HTTP/2 client stopped");193STOPPED.setStackTrace(new StackTraceElement[0]);194connections.values().forEach(this::close);195connections.clear();196}197198private void close(Http2Connection h2c) {199try { h2c.close(); } catch (Throwable t) {}200try { h2c.shutdown(STOPPED); } catch (Throwable t) {}201}202203HttpClientImpl client() {204return client;205}206207/** Returns the client settings as a base64 (url) encoded string */208String getSettingsString() {209SettingsFrame sf = getClientSettings();210byte[] settings = sf.toByteArray(); // without the header211Base64.Encoder encoder = Base64.getUrlEncoder()212.withoutPadding();213return encoder.encodeToString(settings);214}215216private static final int K = 1024;217218private static int getParameter(String property, int min, int max, int defaultValue) {219int value = Utils.getIntegerNetProperty(property, defaultValue);220// use default value if misconfigured221if (value < min || value > max) {222Log.logError("Property value for {0}={1} not in [{2}..{3}]: " +223"using default={4}", property, value, min, max, defaultValue);224value = defaultValue;225}226return value;227}228229// used for the connection window, to have a connection window size230// bigger than the initial stream window size.231int getConnectionWindowSize(SettingsFrame clientSettings) {232// Maximum size is 2^31-1. Don't allow window size to be less233// than the stream window size. HTTP/2 specify a default of 64 * K -1,234// but we use 2^26 by default for better performance.235int streamWindow = clientSettings.getParameter(INITIAL_WINDOW_SIZE);236237// The default is the max between the stream window size238// and the connection window size.239int defaultValue = Math.min(Integer.MAX_VALUE,240Math.max(streamWindow, K*K*32));241242return getParameter(243"jdk.httpclient.connectionWindowSize",244streamWindow, Integer.MAX_VALUE, defaultValue);245}246247SettingsFrame getClientSettings() {248SettingsFrame frame = new SettingsFrame();249// default defined for HTTP/2 is 4 K, we use 16 K.250frame.setParameter(HEADER_TABLE_SIZE, getParameter(251"jdk.httpclient.hpack.maxheadertablesize",2520, Integer.MAX_VALUE, 16 * K));253// O: does not accept push streams. 1: accepts push streams.254frame.setParameter(ENABLE_PUSH, getParameter(255"jdk.httpclient.enablepush",2560, 1, 1));257// HTTP/2 recommends to set the number of concurrent streams258// no lower than 100. We use 100. 0 means no stream would be259// accepted. That would render the client to be non functional,260// so we won't let 0 be configured for our Http2ClientImpl.261frame.setParameter(MAX_CONCURRENT_STREAMS, getParameter(262"jdk.httpclient.maxstreams",2631, Integer.MAX_VALUE, 100));264// Maximum size is 2^31-1. Don't allow window size to be less265// than the minimum frame size as this is likely to be a266// configuration error. HTTP/2 specify a default of 64 * K -1,267// but we use 16 M for better performance.268frame.setParameter(INITIAL_WINDOW_SIZE, getParameter(269"jdk.httpclient.windowsize",27016 * K, Integer.MAX_VALUE, 16*K*K));271// HTTP/2 specify a minimum size of 16 K, a maximum size of 2^24-1,272// and a default of 16 K. We use 16 K as default.273frame.setParameter(MAX_FRAME_SIZE, getParameter(274"jdk.httpclient.maxframesize",27516 * K, 16 * K * K -1, 16 * K));276return frame;277}278}279280281