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.classification.InterfaceAudience;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.DoNotRetryIOException;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.ipc.RpcClient;
36  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
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  
64    private final long pause;
65    private final int retries;
66  
67    public RpcRetryingCaller(Configuration conf) {
68      this.pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
69        HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
70      this.retries =
71          conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
72            HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
73      this.callTimeout = conf.getInt(
74          HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
75          HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
76    }
77  
78    private void beforeCall() {
79      int remaining = (int)(callTimeout -
80        (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime));
81      if (remaining < MIN_RPC_TIMEOUT) {
82        // If there is no time left, we're trying anyway. It's too late.
83        // 0 means no timeout, and it's not the intent here. So we secure both cases by
84        // resetting to the minimum.
85        remaining = MIN_RPC_TIMEOUT;
86      }
87      RpcClient.setRpcTimeout(remaining);
88    }
89  
90    private void afterCall() {
91      RpcClient.resetRpcTimeout();
92    }
93  
94    public synchronized T callWithRetries(RetryingCallable<T> callable) throws IOException,
95        RuntimeException {
96      return callWithRetries(callable, HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
97    }
98  
99    /**
100    * Retries if invocation fails.
101    * @param callTimeout Timeout for this call
102    * @param callable The {@link RetryingCallable} to run.
103    * @return an object of type T
104    * @throws IOException if a remote or network exception occurs
105    * @throws RuntimeException other unspecified error
106    */
107   @edu.umd.cs.findbugs.annotations.SuppressWarnings
108       (value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "na")
109   public synchronized T callWithRetries(RetryingCallable<T> callable, int callTimeout)
110   throws IOException, RuntimeException {
111     this.callTimeout = callTimeout;
112     List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions =
113       new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
114     this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
115     for (int tries = 0;; tries++) {
116       long expectedSleep = 0;
117       try {
118         beforeCall();
119         callable.prepare(tries != 0); // if called with false, check table status on ZK
120         return callable.call();
121       } catch (Throwable t) {
122         if (LOG.isTraceEnabled()) {
123           LOG.trace("Call exception, tries=" + tries + ", retries=" + retries + ", retryTime=" +
124               (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime) + "ms", t);
125         }
126         // translateException throws exception when should not retry: i.e. when request is bad.
127         t = translateException(t);
128         callable.throwable(t, retries != 1);
129         RetriesExhaustedException.ThrowableWithExtraContext qt =
130             new RetriesExhaustedException.ThrowableWithExtraContext(t,
131                 EnvironmentEdgeManager.currentTimeMillis(), toString());
132         exceptions.add(qt);
133         if (tries >= retries - 1) {
134           throw new RetriesExhaustedException(tries, exceptions);
135         }
136         // If the server is dead, we need to wait a little before retrying, to give
137         //  a chance to the regions to be
138         // tries hasn't been bumped up yet so we use "tries + 1" to get right pause time
139         expectedSleep = callable.sleep(pause, tries + 1);
140 
141         // If, after the planned sleep, there won't be enough time left, we stop now.
142         long duration = singleCallDuration(expectedSleep);
143         if (duration > this.callTimeout) {
144           String msg = "callTimeout=" + this.callTimeout + ", callDuration=" + duration +
145               ": " + callable.getExceptionMessageAdditionalDetail();
146           throw (SocketTimeoutException)(new SocketTimeoutException(msg).initCause(t));
147         }
148       } finally {
149         afterCall();
150       }
151       try {
152         Thread.sleep(expectedSleep);
153       } catch (InterruptedException e) {
154         Thread.currentThread().interrupt();
155         throw new InterruptedIOException("Interrupted after " + tries + " tries  on " + retries);
156       }
157     }
158   }
159 
160   /**
161    * @param expectedSleep
162    * @return Calculate how long a single call took
163    */
164   private long singleCallDuration(final long expectedSleep) {
165     return (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime)
166       + MIN_RPC_TIMEOUT + expectedSleep;
167   }
168 
169   /**
170    * Call the server once only.
171    * {@link RetryingCallable} has a strange shape so we can do retrys.  Use this invocation if you
172    * want to do a single call only (A call to {@link RetryingCallable#call()} will not likely
173    * succeed).
174    * @return an object of type T
175    * @throws IOException if a remote or network exception occurs
176    * @throws RuntimeException other unspecified error
177    */
178   public T callWithoutRetries(RetryingCallable<T> callable)
179   throws IOException, RuntimeException {
180     // The code of this method should be shared with withRetries.
181     this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
182     try {
183       beforeCall();
184       callable.prepare(false);
185       return callable.call();
186     } catch (Throwable t) {
187       Throwable t2 = translateException(t);
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    * Get the good or the remote exception if any, throws the DoNotRetryIOException.
201    * @param t the throwable to analyze
202    * @return the translated exception, if it's not a DoNotRetryIOException
203    * @throws DoNotRetryIOException - if we find it, we throw it instead of translating.
204    */
205   static Throwable translateException(Throwable t) throws DoNotRetryIOException {
206     if (t instanceof UndeclaredThrowableException) {
207       if (t.getCause() != null) {
208         t = t.getCause();
209       }
210     }
211     if (t instanceof RemoteException) {
212       t = ((RemoteException)t).unwrapRemoteException();
213     }
214     if (t instanceof LinkageError) {
215       throw new DoNotRetryIOException(t);
216     }
217     if (t instanceof ServiceException) {
218       ServiceException se = (ServiceException)t;
219       Throwable cause = se.getCause();
220       if (cause != null && cause instanceof DoNotRetryIOException) {
221         throw (DoNotRetryIOException)cause;
222       }
223       // Don't let ServiceException out; its rpc specific.
224       t = cause;
225       // t could be a RemoteException so go aaround again.
226       translateException(t);
227     } else if (t instanceof DoNotRetryIOException) {
228       throw (DoNotRetryIOException)t;
229     }
230     return t;
231   }
232 }