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, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.client;
21  
22  import java.io.IOException;
23  import java.io.InterruptedIOException;
24  import java.lang.reflect.UndeclaredThrowableException;
25  import java.net.SocketTimeoutException;
26  import java.util.ArrayList;
27  import java.util.List;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.DoNotRetryIOException;
33  import org.apache.hadoop.hbase.HConstants;
34  import org.apache.hadoop.hbase.ipc.RpcClient;
35  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
36  import org.apache.hadoop.hbase.util.ExceptionUtil;
37  import org.apache.hadoop.ipc.RemoteException;
38  
39  import com.google.protobuf.ServiceException;
40  
41  /**
42   * Runs an rpc'ing {@link RetryingCallable}. Sets into rpc client
43   * threadlocal outstanding timeouts as so we don't persist too much.
44   * Dynamic rather than static so can set the generic appropriately.
45   */
46  @InterfaceAudience.Private
47  @edu.umd.cs.findbugs.annotations.SuppressWarnings
48      (value = "IS2_INCONSISTENT_SYNC", justification = "na")
49  public class RpcRetryingCaller<T> {
50    static final Log LOG = LogFactory.getLog(RpcRetryingCaller.class);
51    /**
52     * Timeout for the call including retries
53     */
54    private int callTimeout;
55    /**
56     * When we started making calls.
57     */
58    private long globalStartTime;
59    /**
60     * Start and end times for a single call.
61     */
62    private final static int MIN_RPC_TIMEOUT = 2000;
63    /** How many retries are allowed before we start to log */
64    private final int startLogErrorsCnt;
65  
66    private final long pause;
67    private final int retries;
68  
69    public RpcRetryingCaller(long pause, int retries, int startLogErrorsCnt) {
70      this.pause = pause;
71      this.retries = retries;
72      this.startLogErrorsCnt = startLogErrorsCnt;
73    }
74  
75    private void beforeCall() {
76      int remaining = (int)(callTimeout -
77        (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime));
78      if (remaining < MIN_RPC_TIMEOUT) {
79        // If there is no time left, we're trying anyway. It's too late.
80        // 0 means no timeout, and it's not the intent here. So we secure both cases by
81        // resetting to the minimum.
82        remaining = MIN_RPC_TIMEOUT;
83      }
84      RpcClient.setRpcTimeout(remaining);
85    }
86  
87    private void afterCall() {
88      RpcClient.resetRpcTimeout();
89    }
90  
91    public synchronized T callWithRetries(RetryingCallable<T> callable) throws IOException,
92        RuntimeException {
93      return callWithRetries(callable, HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
94    }
95  
96    /**
97     * Retries if invocation fails.
98     * @param callTimeout Timeout for this call
99     * @param callable The {@link RetryingCallable} to run.
100    * @return an object of type T
101    * @throws IOException if a remote or network exception occurs
102    * @throws RuntimeException other unspecified error
103    */
104   @edu.umd.cs.findbugs.annotations.SuppressWarnings
105       (value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "na")
106   public synchronized T callWithRetries(RetryingCallable<T> callable, int callTimeout)
107   throws IOException, RuntimeException {
108     this.callTimeout = callTimeout;
109     List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions =
110       new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
111     this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
112     for (int tries = 0;; tries++) {
113       long expectedSleep = 0;
114       try {
115         beforeCall();
116         callable.prepare(tries != 0); // if called with false, check table status on ZK
117         return callable.call();
118       } catch (Throwable t) {
119         if (tries > startLogErrorsCnt) {
120           LOG.info("Call exception, tries=" + tries + ", retries=" + retries + ", retryTime=" +
121               (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime) + "ms, msg="
122               + callable.getExceptionMessageAdditionalDetail());
123         }
124         // translateException throws exception when should not retry: i.e. when request is bad.
125         t = translateException(t);
126         callable.throwable(t, retries != 1);
127         RetriesExhaustedException.ThrowableWithExtraContext qt =
128             new RetriesExhaustedException.ThrowableWithExtraContext(t,
129                 EnvironmentEdgeManager.currentTimeMillis(), toString());
130         exceptions.add(qt);
131         ExceptionUtil.rethrowIfInterrupt(t);
132         if (tries >= retries - 1) {
133           throw new RetriesExhaustedException(tries, exceptions);
134         }
135         // If the server is dead, we need to wait a little before retrying, to give
136         //  a chance to the regions to be
137         // tries hasn't been bumped up yet so we use "tries + 1" to get right pause time
138         expectedSleep = callable.sleep(pause, tries + 1);
139 
140         // If, after the planned sleep, there won't be enough time left, we stop now.
141         long duration = singleCallDuration(expectedSleep);
142         if (duration > this.callTimeout) {
143           String msg = "callTimeout=" + this.callTimeout + ", callDuration=" + duration +
144               ": " + callable.getExceptionMessageAdditionalDetail();
145           throw (SocketTimeoutException)(new SocketTimeoutException(msg).initCause(t));
146         }
147       } finally {
148         afterCall();
149       }
150       try {
151         Thread.sleep(expectedSleep);
152       } catch (InterruptedException e) {
153         throw new InterruptedIOException("Interrupted after " + tries + " tries  on " + retries);
154       }
155     }
156   }
157 
158   /**
159    * @param expectedSleep
160    * @return Calculate how long a single call took
161    */
162   private long singleCallDuration(final long expectedSleep) {
163     return (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime)
164       + MIN_RPC_TIMEOUT + expectedSleep;
165   }
166 
167   /**
168    * Call the server once only.
169    * {@link RetryingCallable} has a strange shape so we can do retrys.  Use this invocation if you
170    * want to do a single call only (A call to {@link RetryingCallable#call()} will not likely
171    * succeed).
172    * @return an object of type T
173    * @throws IOException if a remote or network exception occurs
174    * @throws RuntimeException other unspecified error
175    */
176   public T callWithoutRetries(RetryingCallable<T> callable, int callTimeout)
177   throws IOException, RuntimeException {
178     // The code of this method should be shared with withRetries.
179     this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
180     this.callTimeout = callTimeout;
181     try {
182       beforeCall();
183       callable.prepare(false);
184       return callable.call();
185     } catch (Throwable t) {
186       Throwable t2 = translateException(t);
187       ExceptionUtil.rethrowIfInterrupt(t2);
188       // It would be nice to clear the location cache here.
189       if (t2 instanceof IOException) {
190         throw (IOException)t2;
191       } else {
192         throw new RuntimeException(t2);
193       }
194     } finally {
195       afterCall();
196     }
197   }
198 
199 
200   /**
201    * Get the good or the remote exception if any, throws the DoNotRetryIOException.
202    * @param t the throwable to analyze
203    * @return the translated exception, if it's not a DoNotRetryIOException
204    * @throws DoNotRetryIOException - if we find it, we throw it instead of translating.
205    */
206   static Throwable translateException(Throwable t) throws DoNotRetryIOException {
207     if (t instanceof UndeclaredThrowableException) {
208       if (t.getCause() != null) {
209         t = t.getCause();
210       }
211     }
212     if (t instanceof RemoteException) {
213       t = ((RemoteException)t).unwrapRemoteException();
214     }
215     if (t instanceof LinkageError) {
216       throw new DoNotRetryIOException(t);
217     }
218     if (t instanceof ServiceException) {
219       ServiceException se = (ServiceException)t;
220       Throwable cause = se.getCause();
221       if (cause != null && cause instanceof DoNotRetryIOException) {
222         throw (DoNotRetryIOException)cause;
223       }
224       // Don't let ServiceException out; its rpc specific.
225       t = cause;
226       // t could be a RemoteException so go aaround again.
227       translateException(t);
228     } else if (t instanceof DoNotRetryIOException) {
229       throw (DoNotRetryIOException)t;
230     }
231     return t;
232   }
233 }