Search in sources :

Example 1 with ConnectionPool

use of okhttp3.ConnectionPool in project buck by facebook.

the class ArtifactCaches method createHttpArtifactCache.

private static ArtifactCache createHttpArtifactCache(HttpCacheEntry cacheDescription, final String hostToReportToRemote, final BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem, ListeningExecutorService httpWriteExecutorService, ArtifactCacheBuckConfig config, NetworkCacheFactory factory, boolean distributedBuildModeEnabled) {
    // Setup the default client to use.
    OkHttpClient.Builder storeClientBuilder = new OkHttpClient.Builder();
    storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder().addHeader("X-BuckCache-User", stripNonAscii(System.getProperty("user.name", "<unknown>"))).addHeader("X-BuckCache-Host", stripNonAscii(hostToReportToRemote)).build()));
    int timeoutSeconds = cacheDescription.getTimeoutSeconds();
    setTimeouts(storeClientBuilder, timeoutSeconds);
    storeClientBuilder.connectionPool(new ConnectionPool(/* maxIdleConnections */
    (int) config.getThreadPoolSize(), /* keepAliveDurationMs */
    config.getThreadPoolKeepAliveDurationMillis(), TimeUnit.MILLISECONDS));
    // The artifact cache effectively only connects to a single host at a time. We should allow as
    // many concurrent connections to that host as we allow threads.
    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequestsPerHost((int) config.getThreadPoolSize());
    storeClientBuilder.dispatcher(dispatcher);
    final ImmutableMap<String, String> readHeaders = cacheDescription.getReadHeaders();
    final ImmutableMap<String, String> writeHeaders = cacheDescription.getWriteHeaders();
    // If write headers are specified, add them to every default client request.
    if (!writeHeaders.isEmpty()) {
        storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), writeHeaders).build()));
    }
    OkHttpClient storeClient = storeClientBuilder.build();
    // For fetches, use a client with a read timeout.
    OkHttpClient.Builder fetchClientBuilder = storeClient.newBuilder();
    setTimeouts(fetchClientBuilder, timeoutSeconds);
    // If read headers are specified, add them to every read client request.
    if (!readHeaders.isEmpty()) {
        fetchClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), readHeaders).build()));
    }
    fetchClientBuilder.networkInterceptors().add((chain -> {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), buckEventBus)).build();
    }));
    OkHttpClient fetchClient = fetchClientBuilder.build();
    HttpService fetchService;
    HttpService storeService;
    switch(config.getLoadBalancingType()) {
        case CLIENT_SLB:
            HttpLoadBalancer clientSideSlb = config.getSlbConfig().createClientSideSlb(new DefaultClock(), buckEventBus, new CommandThreadFactory("ArtifactCaches.HttpLoadBalancer", SLB_THREAD_PRIORITY));
            fetchService = new RetryingHttpService(buckEventBus, new LoadBalancedService(clientSideSlb, fetchClient, buckEventBus), config.getMaxFetchRetries());
            storeService = new LoadBalancedService(clientSideSlb, storeClient, buckEventBus);
            break;
        case SINGLE_SERVER:
            URI url = cacheDescription.getUrl();
            fetchService = new SingleUriService(url, fetchClient);
            storeService = new SingleUriService(url, storeClient);
            break;
        default:
            throw new IllegalArgumentException("Unknown HttpLoadBalancer type: " + config.getLoadBalancingType());
    }
    String cacheName = cacheDescription.getName().map(input -> "http-" + input).orElse("http");
    boolean doStore = cacheDescription.getCacheReadMode().isDoStore();
    return factory.newInstance(NetworkCacheArgs.builder().setThriftEndpointPath(config.getHybridThriftEndpoint()).setCacheName(cacheName).setRepository(config.getRepository()).setScheduleType(config.getScheduleType()).setFetchClient(fetchService).setStoreClient(storeService).setDoStore(doStore).setProjectFilesystem(projectFilesystem).setBuckEventBus(buckEventBus).setHttpWriteExecutorService(httpWriteExecutorService).setErrorTextTemplate(cacheDescription.getErrorMessageFormat()).setDistributedBuildModeEnabled(distributedBuildModeEnabled).build());
}
Also used : ConnectionPool(okhttp3.ConnectionPool) BuckEventBus(com.facebook.buck.event.BuckEventBus) Okio(okio.Okio) Source(okio.Source) BytesReceivedEvent(com.facebook.buck.event.NetworkEvent.BytesReceivedEvent) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) Dispatcher(okhttp3.Dispatcher) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) CommonGroups(com.facebook.buck.randomizedtrial.CommonGroups) BuckConfig(com.facebook.buck.cli.BuckConfig) ImmutableList(com.google.common.collect.ImmutableList) DefaultClock(com.facebook.buck.timing.DefaultClock) Map(java.util.Map) ForwardingSource(okio.ForwardingSource) Response(okhttp3.Response) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer) URI(java.net.URI) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Logger(com.facebook.buck.log.Logger) Request(okhttp3.Request) Buffer(okio.Buffer) SingleUriService(com.facebook.buck.slb.SingleUriService) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CharMatcher(com.google.common.base.CharMatcher) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) TimeUnit(java.util.concurrent.TimeUnit) BufferedSource(okio.BufferedSource) OkHttpClient(okhttp3.OkHttpClient) Optional(java.util.Optional) ConnectionPool(okhttp3.ConnectionPool) AsyncCloseable(com.facebook.buck.util.AsyncCloseable) RandomizedTrial(com.facebook.buck.randomizedtrial.RandomizedTrial) DirCacheExperimentEvent(com.facebook.buck.event.DirCacheExperimentEvent) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) OkHttpClient(okhttp3.OkHttpClient) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) Dispatcher(okhttp3.Dispatcher) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) URI(java.net.URI) Response(okhttp3.Response) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) HttpService(com.facebook.buck.slb.HttpService) DefaultClock(com.facebook.buck.timing.DefaultClock) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) SingleUriService(com.facebook.buck.slb.SingleUriService) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer)

Example 2 with ConnectionPool

use of okhttp3.ConnectionPool in project twitter4j by yusuke.

the class Http2ClientTest method testHttp2.

public void testHttp2() throws Exception {
    AlternativeHttpClientImpl.sPreferSpdy = false;
    AlternativeHttpClientImpl.sPreferHttp2 = true;
    AlternativeHttpClientImpl http = callOembed();
    // check HTTP/2.0
    Field f = http.getClass().getDeclaredField("okHttpClient");
    f.setAccessible(true);
    OkHttpClient client = (OkHttpClient) f.get(http);
    assertNotNull("ensure that OkHttpClient is used", client);
    ConnectionPool p = client.connectionPool();
    assertEquals(1, p.connectionCount());
    assertEquals(Protocol.HTTP_2, http.getLastRequestProtocol());
}
Also used : ConnectionPool(okhttp3.ConnectionPool) Field(java.lang.reflect.Field) OkHttpClient(okhttp3.OkHttpClient)

Example 3 with ConnectionPool

use of okhttp3.ConnectionPool in project twitter4j by yusuke.

the class Http2ClientTest method testNoSpdy.

public void testNoSpdy() throws Exception {
    AlternativeHttpClientImpl.sPreferSpdy = false;
    AlternativeHttpClientImpl.sPreferHttp2 = false;
    AlternativeHttpClientImpl http = callOembed();
    // check not SPDY
    Field f = http.getClass().getDeclaredField("okHttpClient");
    f.setAccessible(true);
    OkHttpClient client = (OkHttpClient) f.get(http);
    ConnectionPool p = client.connectionPool();
    assertEquals(1, p.connectionCount());
    assertEquals(Protocol.HTTP_1_1, http.getLastRequestProtocol());
}
Also used : ConnectionPool(okhttp3.ConnectionPool) Field(java.lang.reflect.Field) OkHttpClient(okhttp3.OkHttpClient)

Example 4 with ConnectionPool

use of okhttp3.ConnectionPool in project okhttp by square.

the class ConnectionPoolTest method inUseConnectionsNotEvicted.

@Test
public void inUseConnectionsNotEvicted() throws Exception {
    ConnectionPool pool = new ConnectionPool(Integer.MAX_VALUE, 100L, TimeUnit.NANOSECONDS);
    // Prevent the cleanup runnable from being started.
    pool.cleanupRunning = true;
    RealConnection c1 = newConnection(pool, routeA1, 50L);
    synchronized (pool) {
        StreamAllocation streamAllocation = new StreamAllocation(pool, addressA, null);
        streamAllocation.acquire(c1);
    }
    // Running at time 50, the pool returns that nothing can be evicted until time 150.
    assertEquals(100L, pool.cleanup(50L));
    assertEquals(1, pool.connectionCount());
    assertFalse(c1.socket().isClosed());
    // Running at time 60, the pool returns that nothing can be evicted until time 160.
    assertEquals(100L, pool.cleanup(60L));
    assertEquals(1, pool.connectionCount());
    assertFalse(c1.socket().isClosed());
    // Running at time 160, the pool returns that nothing can be evicted until time 260.
    assertEquals(100L, pool.cleanup(160L));
    assertEquals(1, pool.connectionCount());
    assertFalse(c1.socket().isClosed());
}
Also used : StreamAllocation(okhttp3.internal.connection.StreamAllocation) RealConnection(okhttp3.internal.connection.RealConnection) Test(org.junit.Test)

Example 5 with ConnectionPool

use of okhttp3.ConnectionPool in project okhttp by square.

the class ConnectionPoolTest method connectionsEvictedWhenIdleLongEnough.

@Test
public void connectionsEvictedWhenIdleLongEnough() throws Exception {
    ConnectionPool pool = new ConnectionPool(Integer.MAX_VALUE, 100L, TimeUnit.NANOSECONDS);
    // Prevent the cleanup runnable from being started.
    pool.cleanupRunning = true;
    RealConnection c1 = newConnection(pool, routeA1, 50L);
    // Running at time 50, the pool returns that nothing can be evicted until time 150.
    assertEquals(100L, pool.cleanup(50L));
    assertEquals(1, pool.connectionCount());
    assertFalse(c1.socket().isClosed());
    // Running at time 60, the pool returns that nothing can be evicted until time 150.
    assertEquals(90L, pool.cleanup(60L));
    assertEquals(1, pool.connectionCount());
    assertFalse(c1.socket().isClosed());
    // Running at time 149, the pool returns that nothing can be evicted until time 150.
    assertEquals(1L, pool.cleanup(149L));
    assertEquals(1, pool.connectionCount());
    assertFalse(c1.socket().isClosed());
    // Running at time 150, the pool evicts.
    assertEquals(0, pool.cleanup(150L));
    assertEquals(0, pool.connectionCount());
    assertTrue(c1.socket().isClosed());
    // Running again, the pool reports that no further runs are necessary.
    assertEquals(-1, pool.cleanup(150L));
    assertEquals(0, pool.connectionCount());
    assertTrue(c1.socket().isClosed());
}
Also used : RealConnection(okhttp3.internal.connection.RealConnection) Test(org.junit.Test)

Aggregations

ConnectionPool (okhttp3.ConnectionPool)13 Test (org.junit.Test)12 OkHttpClient (okhttp3.OkHttpClient)11 MockResponse (okhttp3.mockwebserver.MockResponse)8 IOException (java.io.IOException)5 RealConnection (okhttp3.internal.connection.RealConnection)5 Field (java.lang.reflect.Field)4 Dispatcher (okhttp3.Dispatcher)3 Socket (java.net.Socket)2 Level (java.util.logging.Level)2 SimpleFormatter (java.util.logging.SimpleFormatter)2 HttpCodec (okhttp3.internal.http.HttpCodec)2 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)2 BuckConfig (com.facebook.buck.cli.BuckConfig)1 BuckEventBus (com.facebook.buck.event.BuckEventBus)1 DirCacheExperimentEvent (com.facebook.buck.event.DirCacheExperimentEvent)1 BytesReceivedEvent (com.facebook.buck.event.NetworkEvent.BytesReceivedEvent)1 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)1 CommandThreadFactory (com.facebook.buck.log.CommandThreadFactory)1 Logger (com.facebook.buck.log.Logger)1