View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.impl.classic;
28  
29  import java.io.IOException;
30  import java.io.InterruptedIOException;
31  
32  import org.apache.hc.client5.http.HttpRequestRetryStrategy;
33  import org.apache.hc.client5.http.HttpRoute;
34  import org.apache.hc.client5.http.classic.ExecChain;
35  import org.apache.hc.client5.http.classic.ExecChain.Scope;
36  import org.apache.hc.client5.http.protocol.HttpClientContext;
37  import org.apache.hc.client5.http.classic.ExecChainHandler;
38  import org.apache.hc.core5.annotation.Contract;
39  import org.apache.hc.core5.annotation.Internal;
40  import org.apache.hc.core5.annotation.ThreadingBehavior;
41  import org.apache.hc.core5.http.ClassicHttpRequest;
42  import org.apache.hc.core5.http.ClassicHttpResponse;
43  import org.apache.hc.core5.http.HttpEntity;
44  import org.apache.hc.core5.http.HttpException;
45  import org.apache.hc.core5.http.NoHttpResponseException;
46  import org.apache.hc.core5.util.Args;
47  import org.apache.hc.core5.util.TimeValue;
48  import org.slf4j.Logger;
49  import org.slf4j.LoggerFactory;
50  
51  /**
52   * Request executor in the request execution chain that is responsible for
53   * making a decision whether a request that failed due to an I/O exception
54   * or received a specific response from the target server should
55   * be re-executed.
56   * <p>
57   * Further responsibilities such as communication with the opposite
58   * endpoint is delegated to the next executor in the request execution
59   * chain.
60   * </p>
61   *
62   * @since 5.0
63   */
64  @Contract(threading = ThreadingBehavior.STATELESS)
65  @Internal
66  public class HttpRequestRetryExec implements ExecChainHandler {
67  
68      private static final Logger LOG = LoggerFactory.getLogger(HttpRequestRetryExec.class);
69  
70      private final HttpRequestRetryStrategy retryStrategy;
71  
72      public HttpRequestRetryExec(
73              final HttpRequestRetryStrategy retryStrategy) {
74           Args.notNull(retryStrategy, "retryStrategy");
75           this.retryStrategy = retryStrategy;
76      }
77  
78      @Override
79      public ClassicHttpResponse execute(
80              final ClassicHttpRequest request,
81              final Scope scope,
82              final ExecChain chain) throws IOException, HttpException {
83          Args.notNull(request, "request");
84          Args.notNull(scope, "scope");
85          final String exchangeId = scope.exchangeId;
86          final HttpRoute route = scope.route;
87          final HttpClientContext context = scope.clientContext;
88          ClassicHttpRequest currentRequest = request;
89  
90          for (int execCount = 1;; execCount++) {
91              final ClassicHttpResponse response;
92              try {
93                   response = chain.proceed(currentRequest, scope);
94              } catch (final IOException ex) {
95                  if (scope.execRuntime.isExecutionAborted()) {
96                      throw new RequestFailedException("Request aborted");
97                  }
98                  final HttpEntity requestEntity = request.getEntity();
99                  if (requestEntity != null && !requestEntity.isRepeatable()) {
100                     if (LOG.isDebugEnabled()) {
101                         LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
102                     }
103                     throw ex;
104                 }
105                 if (retryStrategy.retryRequest(request, ex, execCount, context)) {
106                     if (LOG.isDebugEnabled()) {
107                         LOG.debug("{}: {}", exchangeId, ex.getMessage(), ex);
108                     }
109                     if (LOG.isInfoEnabled()) {
110                         LOG.info("Recoverable I/O exception ({}) caught when processing request to {}",
111                                 ex.getClass().getName(), route);
112                     }
113                     currentRequest = ClassicRequestCopier.INSTANCE.copy(scope.originalRequest);
114                     continue;
115                 } else {
116                     if (ex instanceof NoHttpResponseException) {
117                         final NoHttpResponseException updatedex = new NoHttpResponseException(
118                                 route.getTargetHost().toHostString() + " failed to respond");
119                         updatedex.setStackTrace(ex.getStackTrace());
120                         throw updatedex;
121                     }
122                     throw ex;
123                 }
124             }
125 
126             try {
127                 final HttpEntity entity = request.getEntity();
128                 if (entity != null && !entity.isRepeatable()) {
129                     if (LOG.isDebugEnabled()) {
130                         LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
131                     }
132                     return response;
133                 }
134                 if (retryStrategy.retryRequest(response, execCount, context)) {
135                     response.close();
136                     final TimeValue nextInterval =
137                             retryStrategy.getRetryInterval(response, execCount, context);
138                     if (TimeValue.isPositive(nextInterval)) {
139                         try {
140                             if (LOG.isDebugEnabled()) {
141                                 LOG.debug("{}: wait for {}", exchangeId, nextInterval);
142                             }
143                             nextInterval.sleep();
144                         } catch (final InterruptedException e) {
145                             Thread.currentThread().interrupt();
146                             throw new InterruptedIOException();
147                         }
148                     }
149                     currentRequest = ClassicRequestCopier.INSTANCE.copy(scope.originalRequest);
150                 } else {
151                     return response;
152                 }
153             } catch (final RuntimeException ex) {
154                 response.close();
155                 throw ex;
156             }
157         }
158     }
159 
160 }