001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import static org.apache.hadoop.hbase.client.ConnectionUtils.resetController;
021import static org.apache.hadoop.hbase.client.ConnectionUtils.translateException;
022
023import java.util.ArrayList;
024import java.util.List;
025import java.util.Map;
026import java.util.Optional;
027import java.util.OptionalLong;
028import java.util.concurrent.CompletableFuture;
029import java.util.concurrent.TimeUnit;
030import java.util.function.Consumer;
031import java.util.function.Supplier;
032import org.apache.hadoop.hbase.DoNotRetryIOException;
033import org.apache.hadoop.hbase.HBaseServerException;
034import org.apache.hadoop.hbase.NotServingRegionException;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.TableNotEnabledException;
037import org.apache.hadoop.hbase.TableNotFoundException;
038import org.apache.hadoop.hbase.client.backoff.HBaseServerExceptionPauseManager;
039import org.apache.hadoop.hbase.exceptions.ScannerResetException;
040import org.apache.hadoop.hbase.ipc.HBaseRpcController;
041import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
042import org.apache.hadoop.hbase.util.FutureUtils;
043import org.apache.yetus.audience.InterfaceAudience;
044import org.slf4j.Logger;
045import org.slf4j.LoggerFactory;
046
047import org.apache.hbase.thirdparty.io.netty.util.Timer;
048
049@InterfaceAudience.Private
050public abstract class AsyncRpcRetryingCaller<T> {
051
052  private static final Logger LOG = LoggerFactory.getLogger(AsyncRpcRetryingCaller.class);
053
054  private final Timer retryTimer;
055
056  private final int priority;
057
058  private final long startNs;
059
060  private int tries = 1;
061
062  private final int maxAttempts;
063
064  private final int startLogErrorsCnt;
065
066  private final List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions;
067
068  private final long rpcTimeoutNs;
069
070  protected final long operationTimeoutNs;
071
072  protected final AsyncConnectionImpl conn;
073
074  protected final CompletableFuture<T> future;
075
076  protected final HBaseRpcController controller;
077
078  private final HBaseServerExceptionPauseManager pauseManager;
079
080  public AsyncRpcRetryingCaller(Timer retryTimer, AsyncConnectionImpl conn, int priority,
081    long pauseNs, long pauseNsForServerOverloaded, int maxAttempts, long operationTimeoutNs,
082    long rpcTimeoutNs, int startLogErrorsCnt, Map<String, byte[]> requestAttributes) {
083    this.retryTimer = retryTimer;
084    this.conn = conn;
085    this.priority = priority;
086    this.maxAttempts = maxAttempts;
087    this.operationTimeoutNs = operationTimeoutNs;
088    this.rpcTimeoutNs = rpcTimeoutNs;
089    this.startLogErrorsCnt = startLogErrorsCnt;
090    this.future = new CompletableFuture<>();
091    this.controller = conn.rpcControllerFactory.newController();
092    this.controller.setPriority(priority);
093    this.controller.setRequestAttributes(requestAttributes);
094    this.exceptions = new ArrayList<>();
095    this.startNs = System.nanoTime();
096    this.pauseManager =
097      new HBaseServerExceptionPauseManager(pauseNs, pauseNsForServerOverloaded, operationTimeoutNs);
098  }
099
100  private long elapsedMs() {
101    return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
102  }
103
104  protected final long remainingTimeNs() {
105    return pauseManager.remainingTimeNs(startNs);
106  }
107
108  protected final void completeExceptionally() {
109    future.completeExceptionally(new RetriesExhaustedException(tries - 1, exceptions));
110  }
111
112  protected final void resetCallTimeout() {
113    long callTimeoutNs;
114    if (operationTimeoutNs > 0) {
115      callTimeoutNs = remainingTimeNs();
116      if (callTimeoutNs <= 0) {
117        completeExceptionally();
118        return;
119      }
120      callTimeoutNs = Math.min(callTimeoutNs, rpcTimeoutNs);
121    } else {
122      callTimeoutNs = rpcTimeoutNs;
123    }
124    resetController(controller, callTimeoutNs, priority, getTableName().orElse(null));
125  }
126
127  private void tryScheduleRetry(Throwable error) {
128    OptionalLong maybePauseNsToUse = pauseManager.getPauseNsFromException(error, tries, startNs);
129    if (!maybePauseNsToUse.isPresent()) {
130      completeExceptionally();
131      return;
132    }
133    long delayNs = maybePauseNsToUse.getAsLong();
134    tries++;
135
136    if (HBaseServerException.isServerOverloaded(error)) {
137      Optional<MetricsConnection> metrics = conn.getConnectionMetrics();
138      metrics.ifPresent(m -> m.incrementServerOverloadedBackoffTime(delayNs, TimeUnit.NANOSECONDS));
139    }
140    retryTimer.newTimeout(t -> doCall(), delayNs, TimeUnit.NANOSECONDS);
141  }
142
143  protected Optional<TableName> getTableName() {
144    return Optional.empty();
145  }
146
147  protected final void onError(Throwable t, Supplier<String> errMsg,
148    Consumer<Throwable> updateCachedLocation) {
149    if (future.isDone()) {
150      // Give up if the future is already done, this is possible if user has already canceled the
151      // future. And for timeline consistent read, we will also cancel some requests if we have
152      // already get one of the responses.
153      LOG.debug("The future is already done, canceled={}, give up retrying", future.isCancelled());
154      return;
155    }
156    Throwable error = translateException(t);
157    // We use this retrying caller to open a scanner, as it is idempotent, but we may throw
158    // ScannerResetException, which is a DoNotRetryIOException when opening a scanner as now we will
159    // also fetch data when opening a scanner. The intention here is that if we hit a
160    // ScannerResetException when scanning then we should try to open a new scanner, instead of
161    // retrying on the old one, so it is declared as a DoNotRetryIOException. But here we are
162    // exactly trying to open a new scanner, so we should retry on ScannerResetException.
163    if (error instanceof DoNotRetryIOException && !(error instanceof ScannerResetException)) {
164      future.completeExceptionally(error);
165      return;
166    }
167    if (tries > startLogErrorsCnt) {
168      LOG.warn(errMsg.get() + ", tries = " + tries + ", maxAttempts = " + maxAttempts
169        + ", timeout = " + TimeUnit.NANOSECONDS.toMillis(operationTimeoutNs)
170        + " ms, time elapsed = " + elapsedMs() + " ms", error);
171    }
172    updateCachedLocation.accept(error);
173    RetriesExhaustedException.ThrowableWithExtraContext qt =
174      new RetriesExhaustedException.ThrowableWithExtraContext(error,
175        EnvironmentEdgeManager.currentTime(), "");
176    exceptions.add(qt);
177    if (tries >= maxAttempts) {
178      completeExceptionally();
179      return;
180    }
181    // check whether the table has been disabled, notice that the check will introduce a request to
182    // meta, so here we only check for disabled for some specific exception types.
183    if (error instanceof NotServingRegionException || error instanceof RegionOfflineException) {
184      Optional<TableName> tableName = getTableName();
185      if (tableName.isPresent()) {
186        FutureUtils.addListener(conn.getAdmin().isTableDisabled(tableName.get()), (disabled, e) -> {
187          if (e != null) {
188            if (e instanceof TableNotFoundException) {
189              future.completeExceptionally(e);
190            } else {
191              // failed to test whether the table is disabled, not a big deal, continue retrying
192              tryScheduleRetry(error);
193            }
194            return;
195          }
196          if (disabled) {
197            future.completeExceptionally(new TableNotEnabledException(tableName.get()));
198          } else {
199            tryScheduleRetry(error);
200          }
201        });
202      } else {
203        tryScheduleRetry(error);
204      }
205    } else {
206      tryScheduleRetry(error);
207    }
208  }
209
210  protected abstract void doCall();
211
212  CompletableFuture<T> call() {
213    doCall();
214    return future;
215  }
216}