Skip to content

Commit

Permalink
Core: Add exponential retry strategy to REST client
Browse files Browse the repository at this point in the history
  • Loading branch information
nastra committed Aug 22, 2023
1 parent 74a7d95 commit 2c0c7a9
Show file tree
Hide file tree
Showing 3 changed files with 377 additions and 2 deletions.
@@ -0,0 +1,148 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.rest;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;
import java.time.Instant;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import javax.net.ssl.SSLException;
import org.apache.hc.client5.http.HttpRequestRetryStrategy;
import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.concurrent.CancellableDependency;
import org.apache.hc.core5.http.ConnectionClosedException;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.TimeValue;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;

/**
* Defines an exponential HTTP request retry strategy and provides the same characteristics as the
* {@link org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy},
*
* <p>using the following list of non-retriable I/O exception classes:<br>
*
* <ul>
* <li>InterruptedIOException
* <li>UnknownHostException
* <li>ConnectException
* <li>ConnectionClosedException
* <li>NoRouteToHostException
* <li>SSLException
* </ul>
*
* and retriable HTTP status codes:<br>
*
* <ul>
* <li>SC_TOO_MANY_REQUESTS (429)
* <li>SC_SERVICE_UNAVAILABLE (503)
* </ul>
*/
class ExponentialHttpRequestRetryStrategy implements HttpRequestRetryStrategy {
private final int maxRetries;
private final Set<Class<? extends IOException>> nonRetriableExceptions;
private final Set<Integer> retriableCodes;

ExponentialHttpRequestRetryStrategy(int maximumRetries) {
Preconditions.checkArgument(
maximumRetries > 0, "Cannot set retries to %s, the value must be positive", maximumRetries);
this.maxRetries = maximumRetries;
this.retriableCodes =
ImmutableSet.of(HttpStatus.SC_TOO_MANY_REQUESTS, HttpStatus.SC_SERVICE_UNAVAILABLE);
this.nonRetriableExceptions =
ImmutableSet.of(
InterruptedIOException.class,
UnknownHostException.class,
ConnectException.class,
ConnectionClosedException.class,
NoRouteToHostException.class,
SSLException.class);
}

@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}

if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
} else {
for (Class<? extends IOException> rejectException : nonRetriableExceptions) {
if (rejectException.isInstance(exception)) {
return false;
}
}
}

if (request instanceof CancellableDependency
&& ((CancellableDependency) request).isCancelled()) {
return false;
}

// Retry if the request is considered idempotent
return Method.isIdempotent(request.getMethod());
}

@Override
public boolean retryRequest(HttpResponse response, int execCount, HttpContext context) {
return execCount <= maxRetries && retriableCodes.contains(response.getCode());
}

@Override
public TimeValue getRetryInterval(HttpResponse response, int execCount, HttpContext context) {
// a server may send a 429 / 503 with a Retry-After header
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
Header header = response.getFirstHeader(HttpHeaders.RETRY_AFTER);
TimeValue retryAfter = null;
if (header != null) {
String value = header.getValue();
try {
retryAfter = TimeValue.ofSeconds(Long.parseLong(value));
} catch (NumberFormatException ignore) {
Instant retryAfterDate = DateUtils.parseStandardDate(value);
if (retryAfterDate != null) {
retryAfter =
TimeValue.ofMilliseconds(retryAfterDate.toEpochMilli() - System.currentTimeMillis());
}
}

if (TimeValue.isPositive(retryAfter)) {
return retryAfter;
}
}

int delayMillis = 1000 * (int) Math.min(Math.pow(2.0, (long) execCount - 1), 64.0);
int jitter = ThreadLocalRandom.current().nextInt(Math.max(1, (int) (delayMillis * 0.1)));

return TimeValue.ofMilliseconds(delayMillis + jitter);
}
}
32 changes: 30 additions & 2 deletions core/src/main/java/org/apache/iceberg/rest/HTTPClient.java
Expand Up @@ -26,10 +26,12 @@
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
Expand All @@ -47,6 +49,7 @@
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.util.TimeValue;
import org.apache.iceberg.IcebergBuild;
import org.apache.iceberg.common.DynConstructors;
import org.apache.iceberg.common.DynMethods;
Expand All @@ -71,6 +74,12 @@ public class HTTPClient implements RESTClient {
@VisibleForTesting
static final String CLIENT_GIT_COMMIT_SHORT_HEADER = "X-Client-Git-Commit-Short";

private static final String RETRY_STRATEGY = "rest.client.retry-strategy";
private static final String REST_MAX_RETRIES = "rest.client.max-retries";
private static final String REST_RETRY_INTERVAL_MILLIS = "rest.client.retry-interval-millis";
private static final String RETRY_STRATEGY_DEFAULT = "default";
private static final String RETRY_STRATEGY_EXPONENTIAL = "exponential";

private final String uri;
private final CloseableHttpClient httpClient;
private final ObjectMapper mapper;
Expand All @@ -79,7 +88,8 @@ private HTTPClient(
String uri,
Map<String, String> baseHeaders,
ObjectMapper objectMapper,
HttpRequestInterceptor requestInterceptor) {
HttpRequestInterceptor requestInterceptor,
Map<String, String> properties) {
this.uri = uri;
this.mapper = objectMapper;

Expand All @@ -96,6 +106,24 @@ private HTTPClient(
clientBuilder.addRequestInterceptorLast(requestInterceptor);
}

if (properties.containsKey(RETRY_STRATEGY)) {
String retryStrategy = properties.getOrDefault(RETRY_STRATEGY, RETRY_STRATEGY_DEFAULT);
if (RETRY_STRATEGY_DEFAULT.equalsIgnoreCase(retryStrategy)) {
// max retries = 1 and retry interval = 1000L are the defaults defined by
// DefaultHttpRequestRetryStrategy
int maxRetries = PropertyUtil.propertyAsInt(properties, REST_MAX_RETRIES, 1);
long retryIntervalMillis =
PropertyUtil.propertyAsLong(properties, REST_RETRY_INTERVAL_MILLIS, 1000L);

clientBuilder.setRetryStrategy(
new DefaultHttpRequestRetryStrategy(
maxRetries, TimeValue.of(retryIntervalMillis, TimeUnit.MILLISECONDS)));
} else if (RETRY_STRATEGY_EXPONENTIAL.equalsIgnoreCase(retryStrategy)) {
int maxRetries = PropertyUtil.propertyAsInt(properties, REST_MAX_RETRIES, 5);
clientBuilder.setRetryStrategy(new ExponentialHttpRequestRetryStrategy(maxRetries));
}
}

this.httpClient = clientBuilder.build();
}

Expand Down Expand Up @@ -466,7 +494,7 @@ public HTTPClient build() {
interceptor = loadInterceptorDynamically(SIGV4_REQUEST_INTERCEPTOR_IMPL, properties);
}

return new HTTPClient(uri, baseHeaders, mapper, interceptor);
return new HTTPClient(uri, baseHeaders, mapper, interceptor, properties);
}
}

Expand Down

0 comments on commit 2c0c7a9

Please sign in to comment.