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 com.google.common.annotations.VisibleForTesting;
23  import java.io.IOException;
24  import java.io.InterruptedIOException;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Collection;
28  import java.util.Collections;
29  import java.util.Date;
30  import java.util.HashMap;
31  import java.util.HashSet;
32  import java.util.Iterator;
33  import java.util.LinkedList;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.Set;
37  import java.util.TreeSet;
38  import java.util.concurrent.ConcurrentHashMap;
39  import java.util.concurrent.ConcurrentMap;
40  import java.util.concurrent.ConcurrentSkipListMap;
41  import java.util.concurrent.ExecutorService;
42  import java.util.concurrent.RejectedExecutionException;
43  import java.util.concurrent.TimeUnit;
44  import java.util.concurrent.atomic.AtomicInteger;
45  import java.util.concurrent.atomic.AtomicLong;
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  import org.apache.hadoop.conf.Configuration;
49  import org.apache.hadoop.hbase.client.AsyncProcess.RowChecker.ReturnCode;
50  import org.apache.hadoop.hbase.CallQueueTooBigException;
51  import org.apache.hadoop.hbase.DoNotRetryIOException;
52  import org.apache.hadoop.hbase.HConstants;
53  import org.apache.hadoop.hbase.HRegionInfo;
54  import org.apache.hadoop.hbase.HRegionLocation;
55  import org.apache.hadoop.hbase.RegionLocations;
56  import org.apache.hadoop.hbase.RetryImmediatelyException;
57  import org.apache.hadoop.hbase.ServerName;
58  import org.apache.hadoop.hbase.TableName;
59  import org.apache.hadoop.hbase.classification.InterfaceAudience;
60  import org.apache.hadoop.hbase.client.backoff.ServerStatistics;
61  import org.apache.hadoop.hbase.client.coprocessor.Batch;
62  import org.apache.hadoop.hbase.exceptions.ClientExceptionsUtil;
63  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
64  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
65  import org.apache.hadoop.hbase.util.Bytes;
66  import org.apache.hadoop.hbase.util.EnvironmentEdge;
67  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
68  import org.apache.htrace.Trace;
69  
70  /**
71   * This class  allows a continuous flow of requests. It's written to be compatible with a
72   * synchronous caller such as HTable.
73   * <p>
74   * The caller sends a buffer of operation, by calling submit. This class extract from this list
75   * the operations it can send, i.e. the operations that are on region that are not considered
76   * as busy. The process is asynchronous, i.e. it returns immediately when if has finished to
77   * iterate on the list. If, and only if, the maximum number of current task is reached, the call
78   * to submit will block. Alternatively, the caller can call submitAll, in which case all the
79   * operations will be sent. Each call to submit returns a future-like object that can be used
80   * to track operation progress.
81   * </p>
82   * <p>
83   * The class manages internally the retries.
84   * </p>
85   * <p>
86   * The class can be constructed in regular mode, or "global error" mode. In global error mode,
87   * AP tracks errors across all calls (each "future" also has global view of all errors). That
88   * mode is necessary for backward compat with HTable behavior, where multiple submissions are
89   * made and the errors can propagate using any put/flush call, from previous calls.
90   * In "regular" mode, the errors are tracked inside the Future object that is returned.
91   * The results are always tracked inside the Future object and can be retrieved when the call
92   * has finished. Partial results can also be retrieved if some part of multi-request failed.
93   * </p>
94   * <p>
95   * This class is thread safe in regular mode; in global error code, submitting operations and
96   * retrieving errors from different threads may be not thread safe.
97   * Internally, the class is thread safe enough to manage simultaneously new submission and results
98   * arising from older operations.
99   * </p>
100  * <p>
101  * Internally, this class works with {@link Row}, this mean it could be theoretically used for
102  * gets as well.
103  * </p>
104  */
105 @InterfaceAudience.Private
106 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="JLM_JSR166_UTILCONCURRENT_MONITORENTER",
107   justification="Synchronization on tasks in progress counter is intended")
108 class AsyncProcess {
109   private static final Log LOG = LogFactory.getLog(AsyncProcess.class);
110   protected static final AtomicLong COUNTER = new AtomicLong();
111 
112   public static final String PRIMARY_CALL_TIMEOUT_KEY = "hbase.client.primaryCallTimeout.multiget";
113 
114   /**
115    * Configure the number of failures after which the client will start logging. A few failures
116    * is fine: region moved, then is not opened, then is overloaded. We try to have an acceptable
117    * heuristic for the number of errors we don't log. 9 was chosen because we wait for 1s at
118    * this stage.
119    */
120   public static final String START_LOG_ERRORS_AFTER_COUNT_KEY =
121       "hbase.client.start.log.errors.counter";
122   public static final int DEFAULT_START_LOG_ERRORS_AFTER_COUNT = 9;
123 
124   /**
125    * Configuration to decide whether to log details for batch error
126    */
127   public static final String LOG_DETAILS_FOR_BATCH_ERROR = "hbase.client.log.batcherrors.details";
128 
129   private final int thresholdToLogUndoneTaskDetails;
130   private static final String THRESHOLD_TO_LOG_UNDONE_TASK_DETAILS =
131       "hbase.client.threshold.log.details";
132   private static final int DEFAULT_THRESHOLD_TO_LOG_UNDONE_TASK_DETAILS = 10;
133   private final int THRESHOLD_TO_LOG_REGION_DETAILS = 2;
134 
135   /**
136    * The maximum size of single RegionServer.
137    */
138   public static final String HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE = "hbase.client.max.perrequest.heapsize";
139 
140   /**
141    * Default value of {@link #HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE}.
142    */
143   public static final long DEFAULT_HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE = 4194304;
144 
145   /**
146    * The maximum size of submit.
147    */
148   public static final String HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE = "hbase.client.max.submit.heapsize";
149   /**
150    * Default value of {@link #HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE}.
151    */
152   public static final long DEFAULT_HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE = DEFAULT_HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE;
153 
154   /**
155    * The context used to wait for results from one submit call.
156    * 1) If AsyncProcess is set to track errors globally, and not per call (for HTable puts),
157    *    then errors and failed operations in this object will reflect global errors.
158    * 2) If submit call is made with needResults false, results will not be saved.
159    *  */
160   public static interface AsyncRequestFuture {
161     public boolean hasError();
162     public RetriesExhaustedWithDetailsException getErrors();
163     public List<? extends Row> getFailedOperations();
164     public Object[] getResults() throws InterruptedIOException;
165     /** Wait until all tasks are executed, successfully or not. */
166     public void waitUntilDone() throws InterruptedIOException;
167   }
168 
169   /**
170    * Return value from a submit that didn't contain any requests.
171    */
172   private static final AsyncRequestFuture NO_REQS_RESULT = new AsyncRequestFuture() {
173 
174     final Object[] result = new Object[0];
175 
176     @Override
177     public boolean hasError() {
178       return false;
179     }
180 
181     @Override
182     public RetriesExhaustedWithDetailsException getErrors() {
183       return null;
184     }
185 
186     @Override
187     public List<? extends Row> getFailedOperations() {
188       return null;
189     }
190 
191     @Override
192     public Object[] getResults() {
193       return result;
194     }
195 
196     @Override
197     public void waitUntilDone() throws InterruptedIOException {
198     }
199   };
200 
201   /** Sync point for calls to multiple replicas for the same user request (Get).
202    * Created and put in the results array (we assume replica calls require results) when
203    * the replica calls are launched. See results for details of this process.
204    * POJO, all fields are public. To modify them, the object itself is locked. */
205   private static class ReplicaResultState {
206     public ReplicaResultState(int callCount) {
207       this.callCount = callCount;
208     }
209 
210     /** Number of calls outstanding, or 0 if a call succeeded (even with others outstanding). */
211     int callCount;
212     /** Errors for which it is not decided whether we will report them to user. If one of the
213      * calls succeeds, we will discard the errors that may have happened in the other calls. */
214     BatchErrors replicaErrors = null;
215 
216     @Override
217     public String toString() {
218       return "[call count " + callCount + "; errors " + replicaErrors + "]";
219     }
220   }
221 
222 
223   // TODO: many of the fields should be made private
224   protected final long id;
225 
226   protected final ClusterConnection connection;
227   protected final RpcRetryingCallerFactory rpcCallerFactory;
228   protected final RpcControllerFactory rpcFactory;
229   protected final BatchErrors globalErrors;
230   protected final ExecutorService pool;
231 
232   protected final AtomicLong tasksInProgress = new AtomicLong(0);
233   protected final ConcurrentMap<byte[], AtomicInteger> taskCounterPerRegion =
234       new ConcurrentSkipListMap<byte[], AtomicInteger>(Bytes.BYTES_COMPARATOR);
235   protected final ConcurrentMap<ServerName, AtomicInteger> taskCounterPerServer =
236       new ConcurrentHashMap<ServerName, AtomicInteger>();
237   // Start configuration settings.
238   private final int startLogErrorsCnt;
239 
240   /**
241    * The number of tasks simultaneously executed on the cluster.
242    */
243   protected final int maxTotalConcurrentTasks;
244 
245   /**
246    * The max heap size of all tasks simultaneously executed on a server.
247    */
248   protected final long maxHeapSizePerRequest;
249   protected final long maxHeapSizeSubmit;
250   /**
251    * The number of tasks we run in parallel on a single region.
252    * With 1 (the default) , we ensure that the ordering of the queries is respected: we don't start
253    * a set of operations on a region before the previous one is done. As well, this limits
254    * the pressure we put on the region server.
255    */
256   protected final int maxConcurrentTasksPerRegion;
257 
258   /**
259    * The number of task simultaneously executed on a single region server.
260    */
261   protected final int maxConcurrentTasksPerServer;
262   protected final long pause;
263   protected final long pauseForCQTBE;// pause for CallQueueTooBigException, if specified
264   protected int numTries;
265   protected int serverTrackerTimeout;
266   protected int rpcTimeout;
267   protected int operationTimeout;
268   protected long primaryCallTimeoutMicroseconds;
269   /** Whether to log details for batch errors */
270   private final boolean logBatchErrorDetails;
271   // End configuration settings.
272 
273   protected static class BatchErrors {
274     private final List<Throwable> throwables = new ArrayList<Throwable>();
275     private final List<Row> actions = new ArrayList<Row>();
276     private final List<String> addresses = new ArrayList<String>();
277 
278     public synchronized void add(Throwable ex, Row row, ServerName serverName) {
279       if (row == null){
280         throw new IllegalArgumentException("row cannot be null. location=" + serverName);
281       }
282 
283       throwables.add(ex);
284       actions.add(row);
285       addresses.add(serverName != null ? serverName.toString() : "null");
286     }
287 
288     public boolean hasErrors() {
289       return !throwables.isEmpty();
290     }
291 
292     private synchronized RetriesExhaustedWithDetailsException makeException(boolean logDetails) {
293       if (logDetails) {
294         LOG.error("Exception occurred! Exception details: " + throwables + ";\nActions: "
295             + actions);
296       }
297       return new RetriesExhaustedWithDetailsException(new ArrayList<Throwable>(throwables),
298           new ArrayList<Row>(actions), new ArrayList<String>(addresses));
299     }
300 
301     public synchronized void clear() {
302       throwables.clear();
303       actions.clear();
304       addresses.clear();
305     }
306 
307     public synchronized void merge(BatchErrors other) {
308       throwables.addAll(other.throwables);
309       actions.addAll(other.actions);
310       addresses.addAll(other.addresses);
311     }
312   }
313   public AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService pool,
314       RpcRetryingCallerFactory rpcCaller, boolean useGlobalErrors, RpcControllerFactory rpcFactory,
315       int rpcTimeout) {
316     if (hc == null) {
317       throw new IllegalArgumentException("HConnection cannot be null.");
318     }
319 
320     this.connection = hc;
321     this.pool = pool;
322     this.globalErrors = useGlobalErrors ? new BatchErrors() : null;
323 
324     this.id = COUNTER.incrementAndGet();
325 
326     ConnectionConfiguration connConf =
327       hc.getConfiguration() == conf
328         ? hc.getConnectionConfiguration()
329         // Slow: parse conf in ConnectionConfiguration constructor
330         : new ConnectionConfiguration(conf);
331     if (connConf == null) {
332       // Slow: parse conf in ConnectionConfiguration constructor
333       connConf = new ConnectionConfiguration(conf);
334     }
335 
336     this.pause = connConf.getPause();
337     this.pauseForCQTBE = connConf.getPauseForCQTBE();
338 
339     this.numTries = connConf.getRetriesNumber();
340     this.rpcTimeout = rpcTimeout;
341     this.operationTimeout = connConf.getOperationTimeout();
342 
343     // Parse config once and reuse config values of hc's AsyncProcess in AsyncProcess for put
344     // Can be null when constructing hc's AsyncProcess or it's not reusable
345     AsyncProcess globalAsyncProcess = hc.getConfiguration() == conf ? hc.getAsyncProcess() : null;
346 
347     this.primaryCallTimeoutMicroseconds =
348       globalAsyncProcess == null
349         ? conf.getInt(PRIMARY_CALL_TIMEOUT_KEY, 10000)
350         : globalAsyncProcess.primaryCallTimeoutMicroseconds;
351 
352     this.maxTotalConcurrentTasks =
353       globalAsyncProcess == null
354         ? conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
355               HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS)
356         : globalAsyncProcess.maxTotalConcurrentTasks;
357     this.maxConcurrentTasksPerServer =
358       globalAsyncProcess == null
359         ? conf.getInt(HConstants.HBASE_CLIENT_MAX_PERSERVER_TASKS,
360               HConstants.DEFAULT_HBASE_CLIENT_MAX_PERSERVER_TASKS)
361         : globalAsyncProcess.maxConcurrentTasksPerServer;
362     this.maxConcurrentTasksPerRegion =
363       globalAsyncProcess == null
364         ? conf.getInt(HConstants.HBASE_CLIENT_MAX_PERREGION_TASKS,
365               HConstants.DEFAULT_HBASE_CLIENT_MAX_PERREGION_TASKS)
366         : globalAsyncProcess.maxConcurrentTasksPerRegion;
367     this.maxHeapSizePerRequest =
368       globalAsyncProcess == null
369         ? conf.getLong(HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE,
370               DEFAULT_HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE)
371         : globalAsyncProcess.maxHeapSizePerRequest;
372     this.maxHeapSizeSubmit =
373       globalAsyncProcess == null
374         ? conf.getLong(HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE, DEFAULT_HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE)
375         : globalAsyncProcess.maxHeapSizeSubmit;
376     this.startLogErrorsCnt =
377       globalAsyncProcess == null
378         ? conf.getInt(START_LOG_ERRORS_AFTER_COUNT_KEY, DEFAULT_START_LOG_ERRORS_AFTER_COUNT)
379         : globalAsyncProcess.startLogErrorsCnt;
380 
381     if (this.maxTotalConcurrentTasks <= 0) {
382       throw new IllegalArgumentException("maxTotalConcurrentTasks=" + maxTotalConcurrentTasks);
383     }
384     if (this.maxConcurrentTasksPerServer <= 0) {
385       throw new IllegalArgumentException("maxConcurrentTasksPerServer=" +
386           maxConcurrentTasksPerServer);
387     }
388     if (this.maxConcurrentTasksPerRegion <= 0) {
389       throw new IllegalArgumentException("maxConcurrentTasksPerRegion=" +
390           maxConcurrentTasksPerRegion);
391     }
392     if (this.maxHeapSizePerRequest <= 0) {
393       throw new IllegalArgumentException("maxHeapSizePerServer=" +
394           maxHeapSizePerRequest);
395     }
396 
397     if (this.maxHeapSizeSubmit <= 0) {
398       throw new IllegalArgumentException("maxHeapSizeSubmit=" +
399           maxHeapSizeSubmit);
400     }
401     // Server tracker allows us to do faster, and yet useful (hopefully), retries.
402     // However, if we are too useful, we might fail very quickly due to retry count limit.
403     // To avoid this, we are going to cheat for now (see HBASE-7659), and calculate maximum
404     // retry time if normal retries were used. Then we will retry until this time runs out.
405     // If we keep hitting one server, the net effect will be the incremental backoff, and
406     // essentially the same number of retries as planned. If we have to do faster retries,
407     // we will do more retries in aggregate, but the user will be none the wiser.
408     this.serverTrackerTimeout = 0;
409     for (int i = 0; i < this.numTries; ++i) {
410       serverTrackerTimeout = (int) (serverTrackerTimeout + ConnectionUtils.getPauseTime(this.pause, i));
411     }
412 
413     this.rpcCallerFactory = rpcCaller;
414     this.rpcFactory = rpcFactory;
415     this.logBatchErrorDetails =
416       globalAsyncProcess == null
417         ? conf.getBoolean(LOG_DETAILS_FOR_BATCH_ERROR, false)
418         : globalAsyncProcess.logBatchErrorDetails;
419 
420     this.thresholdToLogUndoneTaskDetails =
421       globalAsyncProcess == null
422         ? conf.getInt(THRESHOLD_TO_LOG_UNDONE_TASK_DETAILS,
423               DEFAULT_THRESHOLD_TO_LOG_UNDONE_TASK_DETAILS)
424         : globalAsyncProcess.thresholdToLogUndoneTaskDetails;
425   }
426 
427   public void setRpcTimeout(int rpcTimeout) {
428     this.rpcTimeout = rpcTimeout;
429   }
430 
431   public void setOperationTimeout(int operationTimeout) {
432     this.operationTimeout = operationTimeout;
433   }
434 
435   /**
436    * @return pool if non null, otherwise returns this.pool if non null, otherwise throws
437    *         RuntimeException
438    */
439   @VisibleForTesting
440   ExecutorService getPool(ExecutorService pool) {
441     if (pool != null) {
442       return pool;
443     }
444     if (this.pool != null) {
445       return this.pool;
446     }
447     throw new RuntimeException("Neither AsyncProcess nor request have ExecutorService");
448   }
449 
450   /**
451    * See {@link #submit(ExecutorService, TableName, List, boolean, Batch.Callback, boolean)}.
452    * Uses default ExecutorService for this AP (must have been created with one).
453    */
454   public <CResult> AsyncRequestFuture submit(TableName tableName, final List<? extends Row> rows,
455       boolean atLeastOne, Batch.Callback<CResult> callback, boolean needResults)
456       throws InterruptedIOException {
457     return submit(null, tableName, rows, atLeastOne, callback, needResults);
458   }
459   /**
460    * See {@link #submit(ExecutorService, TableName, RowAccess, boolean, Batch.Callback, boolean)}.
461    * Uses default ExecutorService for this AP (must have been created with one).
462    */
463   public <CResult> AsyncRequestFuture submit(TableName tableName,
464       final RowAccess<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback,
465       boolean needResults) throws InterruptedIOException {
466     return submit(null, tableName, rows, atLeastOne, callback, needResults);
467   }
468   /**
469    * See {@link #submit(ExecutorService, TableName, RowAccess, boolean, Batch.Callback, boolean)}.
470    * Uses the {@link ListRowAccess} to wrap the {@link List}.
471    */
472   public <CResult> AsyncRequestFuture submit(ExecutorService pool, TableName tableName,
473       List<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback,
474       boolean needResults) throws InterruptedIOException {
475     return submit(pool, tableName, new ListRowAccess(rows), atLeastOne,
476       callback, needResults);
477   }
478 
479   /**
480    * Extract from the rows list what we can submit. The rows we can not submit are kept in the
481    * list. Does not send requests to replicas (not currently used for anything other
482    * than streaming puts anyway).
483    *
484    * @param pool ExecutorService to use.
485    * @param tableName The table for which this request is needed.
486    * @param callback Batch callback. Only called on success (94 behavior).
487    * @param needResults Whether results are needed, or can be discarded.
488    * @param rows - the submitted row. Modified by the method: we remove the rows we took.
489    * @param atLeastOne true if we should submit at least a subset.
490    */
491   public <CResult> AsyncRequestFuture submit(ExecutorService pool, TableName tableName,
492       RowAccess<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback,
493       boolean needResults) throws InterruptedIOException {
494     if (rows.isEmpty()) {
495       return NO_REQS_RESULT;
496     }
497 
498     Map<ServerName, MultiAction<Row>> actionsByServer =
499         new HashMap<ServerName, MultiAction<Row>>();
500     List<Action<Row>> retainedActions = new ArrayList<Action<Row>>(rows.size());
501 
502     NonceGenerator ng = this.connection.getNonceGenerator();
503     long nonceGroup = ng.getNonceGroup(); // Currently, nonce group is per entire client.
504 
505     // Location errors that happen before we decide what requests to take.
506     List<Exception> locationErrors = null;
507     List<Integer> locationErrorRows = null;
508     RowCheckerHost checker = createRowCheckerHost();
509     boolean firstIter = true;
510     do {
511       // Wait until there is at least one slot for a new task.
512       waitForMaximumCurrentTasks(maxTotalConcurrentTasks - 1, tableName.getNameAsString());
513       int posInList = -1;
514       if (!firstIter) {
515         checker.reset();
516       }
517       Iterator<? extends Row> it = rows.iterator();
518       while (it.hasNext()) {
519         Row r = it.next();
520         HRegionLocation loc;
521         try {
522           if (r == null) {
523             throw new IllegalArgumentException("#" + id + ", row cannot be null");
524           }
525           // Make sure we get 0-s replica.
526           RegionLocations locs = connection.locateRegion(
527               tableName, r.getRow(), true, true, RegionReplicaUtil.DEFAULT_REPLICA_ID);
528           if (locs == null || locs.isEmpty() || locs.getDefaultRegionLocation() == null) {
529             throw new IOException("#" + id + ", no location found, aborting submit for"
530                 + " tableName=" + tableName + " rowkey=" + Bytes.toStringBinary(r.getRow()));
531           }
532           loc = locs.getDefaultRegionLocation();
533         } catch (IOException ex) {
534           locationErrors = new ArrayList<Exception>();
535           locationErrorRows = new ArrayList<Integer>();
536           LOG.error("Failed to get region location ", ex);
537           // This action failed before creating ars. Retain it, but do not add to submit list.
538           // We will then add it to ars in an already-failed state.
539           int priority = HConstants.NORMAL_QOS;
540           if (r instanceof Mutation) {
541             priority = ((Mutation) r).getPriority();
542           }
543           retainedActions.add(new Action<Row>(r, ++posInList, priority));
544           locationErrors.add(ex);
545           locationErrorRows.add(posInList);
546           it.remove();
547           break; // Backward compat: we stop considering actions on location error.
548         }
549         long rowSize = (r instanceof Mutation) ? ((Mutation) r).heapSize() : 0;
550         ReturnCode code = checker.canTakeOperation(loc, rowSize);
551         if (code == ReturnCode.END) {
552           break;
553         }
554         if (code == ReturnCode.INCLUDE) {
555           int priority = HConstants.NORMAL_QOS;
556           if (r instanceof Mutation) {
557             priority = ((Mutation) r).getPriority();
558           }
559           Action<Row> action = new Action<Row>(r, ++posInList, priority);
560           setNonce(ng, r, action);
561           retainedActions.add(action);
562           // TODO: replica-get is not supported on this path
563           byte[] regionName = loc.getRegionInfo().getRegionName();
564           addAction(loc.getServerName(), regionName, action, actionsByServer, nonceGroup);
565           it.remove();
566         }
567       }
568       firstIter = false;
569     } while (retainedActions.isEmpty() && atLeastOne && (locationErrors == null));
570 
571     if (retainedActions.isEmpty()) return NO_REQS_RESULT;
572 
573     return submitMultiActions(tableName, retainedActions, nonceGroup, callback, null, needResults,
574         locationErrors, locationErrorRows, actionsByServer, pool);
575   }
576 
577   private RowCheckerHost createRowCheckerHost() {
578     return new RowCheckerHost(Arrays.asList(
579         new TaskCountChecker(maxTotalConcurrentTasks,
580           maxConcurrentTasksPerServer,
581           maxConcurrentTasksPerRegion,
582           tasksInProgress,
583           taskCounterPerServer,
584           taskCounterPerRegion)
585         , new RequestSizeChecker(maxHeapSizePerRequest)
586         , new SubmittedSizeChecker(maxHeapSizeSubmit)
587     ));
588   }
589   <CResult> AsyncRequestFuture submitMultiActions(TableName tableName,
590       List<Action<Row>> retainedActions, long nonceGroup, Batch.Callback<CResult> callback,
591       Object[] results, boolean needResults, List<Exception> locationErrors,
592       List<Integer> locationErrorRows, Map<ServerName, MultiAction<Row>> actionsByServer,
593       ExecutorService pool) {
594     AsyncRequestFutureImpl<CResult> ars = createAsyncRequestFuture(
595       tableName, retainedActions, nonceGroup, pool, callback, results, needResults, null,
596         operationTimeout, rpcTimeout);
597     // Add location errors if any
598     if (locationErrors != null) {
599       for (int i = 0; i < locationErrors.size(); ++i) {
600         int originalIndex = locationErrorRows.get(i);
601         Row row = retainedActions.get(originalIndex).getAction();
602         ars.manageError(originalIndex, row,
603             Retry.NO_LOCATION_PROBLEM, locationErrors.get(i), null);
604       }
605     }
606     ars.sendMultiAction(actionsByServer, 1, null, false);
607     return ars;
608   }
609 
610   /**
611    * Helper that is used when grouping the actions per region server.
612    *
613    * @param loc - the destination. Must not be null.
614    * @param action - the action to add to the multiaction
615    * @param actionsByServer the multiaction per server
616    * @param nonceGroup Nonce group.
617    */
618   private static void addAction(ServerName server, byte[] regionName, Action<Row> action,
619       Map<ServerName, MultiAction<Row>> actionsByServer, long nonceGroup) {
620     MultiAction<Row> multiAction = actionsByServer.get(server);
621     if (multiAction == null) {
622       multiAction = new MultiAction<Row>();
623       actionsByServer.put(server, multiAction);
624     }
625     if (action.hasNonce() && !multiAction.hasNonceGroup()) {
626       multiAction.setNonceGroup(nonceGroup);
627     }
628 
629     multiAction.add(regionName, action);
630   }
631   /**
632    * See {@link #submitAll(ExecutorService, TableName, List, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback, Object[])}.
633    * Uses default ExecutorService for this AP (must have been created with one).
634    */
635   public <CResult> AsyncRequestFuture submitAll(TableName tableName,
636       List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results) {
637     return submitAll(null, tableName, rows, callback, results, null, operationTimeout, rpcTimeout);
638   }
639 
640   public <CResult> AsyncRequestFuture submitAll(ExecutorService pool, TableName tableName,
641       List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results) {
642     return submitAll(pool, tableName, rows, callback, results, null, operationTimeout, rpcTimeout);
643   }
644   /**
645    * Submit immediately the list of rows, whatever the server status. Kept for backward
646    * compatibility: it allows to be used with the batch interface that return an array of objects.
647    *
648    * @param pool ExecutorService to use.
649    * @param tableName name of the table for which the submission is made.
650    * @param rows the list of rows.
651    * @param callback the callback.
652    * @param results Optional array to return the results thru; backward compat.
653    */
654   public <CResult> AsyncRequestFuture submitAll(ExecutorService pool, TableName tableName,
655       List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results,
656       PayloadCarryingServerCallable callable, int operationTimeout, int rpcTimeout) {
657     List<Action<Row>> actions = new ArrayList<Action<Row>>(rows.size());
658 
659     // The position will be used by the processBatch to match the object array returned.
660     int posInList = -1;
661     NonceGenerator ng = this.connection.getNonceGenerator();
662     int highestPriority = HConstants.PRIORITY_UNSET;
663     for (Row r : rows) {
664       posInList++;
665       if (r instanceof Put) {
666         Put put = (Put) r;
667         if (put.isEmpty()) {
668           throw new IllegalArgumentException("No columns to insert for #" + (posInList+1)+ " item");
669         }
670         highestPriority = Math.max(put.getPriority(), highestPriority);
671       }
672       Action<Row> action = new Action<Row>(r, posInList, highestPriority);
673       setNonce(ng, r, action);
674       actions.add(action);
675     }
676     AsyncRequestFutureImpl<CResult> ars = createAsyncRequestFuture(
677         tableName, actions, ng.getNonceGroup(), getPool(pool), callback, results, results != null,
678         callable, operationTimeout, rpcTimeout);
679     ars.groupAndSendMultiAction(actions, 1);
680     return ars;
681   }
682 
683   private static void setNonce(NonceGenerator ng, Row r, Action<Row> action) {
684     if (!(r instanceof Append) && !(r instanceof Increment)) return;
685     action.setNonce(ng.newNonce()); // Action handles NO_NONCE, so it's ok if ng is disabled.
686   }
687 
688   /**
689    * The context, and return value, for a single submit/submitAll call.
690    * Note on how this class (one AP submit) works. Initially, all requests are split into groups
691    * by server; request is sent to each server in parallel; the RPC calls are not async so a
692    * thread per server is used. Every time some actions fail, regions/locations might have
693    * changed, so we re-group them by server and region again and send these groups in parallel
694    * too. The result, in case of retries, is a "tree" of threads, with parent exiting after
695    * scheduling children. This is why lots of code doesn't require any synchronization.
696    */
697   protected class AsyncRequestFutureImpl<CResult> implements AsyncRequestFuture {
698 
699     /**
700      * Runnable (that can be submitted to thread pool) that waits for when it's time
701      * to issue replica calls, finds region replicas, groups the requests by replica and
702      * issues the calls (on separate threads, via sendMultiAction).
703      * This is done on a separate thread because we don't want to wait on user thread for
704      * our asynchronous call, and usually we have to wait before making replica calls.
705      */
706     private final class ReplicaCallIssuingRunnable implements Runnable {
707       private final long startTime;
708       private final List<Action<Row>> initialActions;
709 
710       public ReplicaCallIssuingRunnable(List<Action<Row>> initialActions, long startTime) {
711         this.initialActions = initialActions;
712         this.startTime = startTime;
713       }
714 
715       @Override
716       public void run() {
717         boolean done = false;
718         if (primaryCallTimeoutMicroseconds > 0) {
719           try {
720             done = waitUntilDone(startTime * 1000L + primaryCallTimeoutMicroseconds);
721           } catch (InterruptedException ex) {
722             LOG.error("Replica thread was interrupted - no replica calls: " + ex.getMessage());
723             return;
724           }
725         }
726         if (done) return; // Done within primary timeout
727         Map<ServerName, MultiAction<Row>> actionsByServer =
728             new HashMap<ServerName, MultiAction<Row>>();
729         List<Action<Row>> unknownLocActions = new ArrayList<Action<Row>>();
730         if (replicaGetIndices == null) {
731           for (int i = 0; i < results.length; ++i) {
732             addReplicaActions(i, actionsByServer, unknownLocActions);
733           }
734         } else {
735           for (int replicaGetIndice : replicaGetIndices) {
736             addReplicaActions(replicaGetIndice, actionsByServer, unknownLocActions);
737           }
738         }
739         if (!actionsByServer.isEmpty()) {
740           sendMultiAction(actionsByServer, 1, null, unknownLocActions.isEmpty());
741         }
742         if (!unknownLocActions.isEmpty()) {
743           actionsByServer = new HashMap<ServerName, MultiAction<Row>>();
744           for (Action<Row> action : unknownLocActions) {
745             addReplicaActionsAgain(action, actionsByServer);
746           }
747           // Some actions may have completely failed, they are handled inside addAgain.
748           if (!actionsByServer.isEmpty()) {
749             sendMultiAction(actionsByServer, 1, null, true);
750           }
751         }
752       }
753 
754       /**
755        * Add replica actions to action map by server.
756        * @param index Index of the original action.
757        * @param actionsByServer The map by server to add it to.
758        */
759       private void addReplicaActions(int index, Map<ServerName, MultiAction<Row>> actionsByServer,
760           List<Action<Row>> unknownReplicaActions) {
761         if (results[index] != null) return; // opportunistic. Never goes from non-null to null.
762         Action<Row> action = initialActions.get(index);
763         RegionLocations loc = findAllLocationsOrFail(action, true);
764         if (loc == null) return;
765         HRegionLocation[] locs = loc.getRegionLocations();
766         if (locs.length == 1) {
767           LOG.warn("No replicas found for " + action.getAction());
768           return;
769         }
770         synchronized (replicaResultLock) {
771           // Don't run replica calls if the original has finished. We could do it e.g. if
772           // original has already failed before first replica call (unlikely given retries),
773           // but that would require additional synchronization w.r.t. returning to caller.
774           if (results[index] != null) return;
775           // We set the number of calls here. After that any path must call setResult/setError.
776           // True even for replicas that are not found - if we refuse to send we MUST set error.
777           results[index] = new ReplicaResultState(locs.length);
778         }
779         for (int i = 1; i < locs.length; ++i) {
780           Action<Row> replicaAction = new Action<Row>(action, i);
781           if (locs[i] != null) {
782             addAction(locs[i].getServerName(), locs[i].getRegionInfo().getRegionName(),
783                 replicaAction, actionsByServer, nonceGroup);
784           } else {
785             unknownReplicaActions.add(replicaAction);
786           }
787         }
788       }
789 
790       private void addReplicaActionsAgain(
791           Action<Row> action, Map<ServerName, MultiAction<Row>> actionsByServer) {
792         if (action.getReplicaId() == RegionReplicaUtil.DEFAULT_REPLICA_ID) {
793           throw new AssertionError("Cannot have default replica here");
794         }
795         HRegionLocation loc = getReplicaLocationOrFail(action);
796         if (loc == null) return;
797         addAction(loc.getServerName(), loc.getRegionInfo().getRegionName(),
798             action, actionsByServer, nonceGroup);
799       }
800     }
801 
802     /**
803      * Runnable (that can be submitted to thread pool) that submits MultiAction to a
804      * single server. The server call is synchronous, therefore we do it on a thread pool.
805      */
806     @VisibleForTesting
807     class SingleServerRequestRunnable implements Runnable {
808       private final MultiAction<Row> multiAction;
809       private final int numAttempt;
810       private final ServerName server;
811       private final Set<PayloadCarryingServerCallable> callsInProgress;
812       @VisibleForTesting
813       SingleServerRequestRunnable(
814           MultiAction<Row> multiAction, int numAttempt, ServerName server,
815           Set<PayloadCarryingServerCallable> callsInProgress) {
816         this.multiAction = multiAction;
817         this.numAttempt = numAttempt;
818         this.server = server;
819         this.callsInProgress = callsInProgress;
820       }
821 
822       @Override
823       public void run() {
824         MultiResponse res = null;
825         PayloadCarryingServerCallable callable = currentCallable;
826         try {
827           // setup the callable based on the actions, if we don't have one already from the request
828           if (callable == null) {
829             callable = createCallable(server, tableName, multiAction);
830           }
831           RpcRetryingCaller<MultiResponse> caller = createCaller(callable, rpcTimeout);
832           try {
833             if (callsInProgress != null) {
834               callsInProgress.add(callable);
835             }
836             res = caller.callWithoutRetries(callable, operationTimeout);
837             if (res == null) {
838               // Cancelled
839               return;
840             }
841           } catch (IOException e) {
842             // The service itself failed . It may be an error coming from the communication
843             //   layer, but, as well, a functional error raised by the server.
844             receiveGlobalFailure(multiAction, server, numAttempt, e);
845             return;
846           } catch (Throwable t) {
847             // This should not happen. Let's log & retry anyway.
848             LOG.error("#" + id + ", Caught throwable while calling. This is unexpected." +
849                 " Retrying. Server is " + server + ", tableName=" + tableName, t);
850             receiveGlobalFailure(multiAction, server, numAttempt, t);
851             return;
852           }
853 
854           // Normal case: we received an answer from the server, and it's not an exception.
855           receiveMultiAction(multiAction, server, res, numAttempt);
856         } catch (Throwable t) {
857           // Something really bad happened. We are on the send thread that will now die.
858           LOG.error("Internal AsyncProcess #" + id + " error for "
859               + tableName + " processing for " + server, t);
860           throw new RuntimeException(t);
861         } finally {
862           decTaskCounters(multiAction.getRegions(), server);
863           if (callsInProgress != null && callable != null && res != null) {
864             callsInProgress.remove(callable);
865           }
866         }
867       }
868     }
869 
870     private final Batch.Callback<CResult> callback;
871     private final BatchErrors errors;
872     private final ConnectionManager.ServerErrorTracker errorsByServer;
873     private final ExecutorService pool;
874     private final Set<PayloadCarryingServerCallable> callsInProgress;
875 
876 
877     private final TableName tableName;
878     private final AtomicLong actionsInProgress = new AtomicLong(-1);
879     /**
880      * The lock controls access to results. It is only held when populating results where
881      * there might be several callers (eventual consistency gets). For other requests,
882      * there's one unique call going on per result index.
883      */
884     private final Object replicaResultLock = new Object();
885     /**
886      * Result array.  Null if results are not needed. Otherwise, each index corresponds to
887      * the action index in initial actions submitted. For most request types, has null-s for
888      * requests that are not done, and result/exception for those that are done.
889      * For eventual-consistency gets, initially the same applies; at some point, replica calls
890      * might be started, and ReplicaResultState is put at the corresponding indices. The
891      * returning calls check the type to detect when this is the case. After all calls are done,
892      * ReplicaResultState-s are replaced with results for the user.
893      */
894     private final Object[] results;
895     /**
896      * Indices of replica gets in results. If null, all or no actions are replica-gets.
897      */
898     private final int[] replicaGetIndices;
899     private final boolean hasAnyReplicaGets;
900     private final long nonceGroup;
901     private PayloadCarryingServerCallable currentCallable;
902     private int operationTimeout;
903     private int rpcTimeout;
904     private RetryingTimeTracker tracker;
905 
906     public AsyncRequestFutureImpl(TableName tableName, List<Action<Row>> actions, long nonceGroup,
907         ExecutorService pool, boolean needResults, Object[] results,
908         Batch.Callback<CResult> callback, PayloadCarryingServerCallable callable,
909         int operationTimeout, int rpcTimeout) {
910       this.pool = pool;
911       this.callback = callback;
912       this.nonceGroup = nonceGroup;
913       this.tableName = tableName;
914       this.actionsInProgress.set(actions.size());
915       if (results != null) {
916         assert needResults;
917         if (results.length != actions.size()) {
918           throw new AssertionError("results.length");
919         }
920         this.results = results;
921         for (int i = 0; i != this.results.length; ++i) {
922           results[i] = null;
923         }
924       } else {
925         this.results = needResults ? new Object[actions.size()] : null;
926       }
927       List<Integer> replicaGetIndices = null;
928       boolean hasAnyReplicaGets = false;
929       if (needResults) {
930         // Check to see if any requests might require replica calls.
931         // We expect that many requests will consist of all or no multi-replica gets; in such
932         // cases we would just use a boolean (hasAnyReplicaGets). If there's a mix, we will
933         // store the list of action indexes for which replica gets are possible, and set
934         // hasAnyReplicaGets to true.
935         boolean hasAnyNonReplicaReqs = false;
936         int posInList = 0;
937         for (Action<Row> action : actions) {
938           boolean isReplicaGet = isReplicaGet(action.getAction());
939           if (isReplicaGet) {
940             hasAnyReplicaGets = true;
941             if (hasAnyNonReplicaReqs) { // Mixed case
942               if (replicaGetIndices == null) {
943                 replicaGetIndices = new ArrayList<Integer>(actions.size() - 1);
944               }
945               replicaGetIndices.add(posInList);
946             }
947           } else if (!hasAnyNonReplicaReqs) {
948             // The first non-multi-replica request in the action list.
949             hasAnyNonReplicaReqs = true;
950             if (posInList > 0) {
951               // Add all the previous requests to the index lists. We know they are all
952               // replica-gets because this is the first non-multi-replica request in the list.
953               replicaGetIndices = new ArrayList<Integer>(actions.size() - 1);
954               for (int i = 0; i < posInList; ++i) {
955                 replicaGetIndices.add(i);
956               }
957             }
958           }
959           ++posInList;
960         }
961       }
962       this.hasAnyReplicaGets = hasAnyReplicaGets;
963       if (replicaGetIndices != null) {
964         this.replicaGetIndices = new int[replicaGetIndices.size()];
965         int i = 0;
966         for (Integer el : replicaGetIndices) {
967           this.replicaGetIndices[i++] = el;
968         }
969       } else {
970         this.replicaGetIndices = null;
971       }
972       this.callsInProgress = !hasAnyReplicaGets ? null :
973           Collections.newSetFromMap(
974               new ConcurrentHashMap<PayloadCarryingServerCallable, Boolean>());
975 
976       this.errorsByServer = createServerErrorTracker();
977       this.errors = (globalErrors != null) ? globalErrors : new BatchErrors();
978       this.currentCallable = callable;
979       this.operationTimeout = operationTimeout;
980       this.rpcTimeout = rpcTimeout;
981       if (callable == null) {
982         tracker = new RetryingTimeTracker();
983         tracker.start();
984       }
985     }
986 
987     public Set<PayloadCarryingServerCallable> getCallsInProgress() {
988       return callsInProgress;
989     }
990 
991     @VisibleForTesting
992     SingleServerRequestRunnable createSingleServerRequest(MultiAction<Row> multiAction, int numAttempt, ServerName server,
993       Set<PayloadCarryingServerCallable> callsInProgress) {
994       return new SingleServerRequestRunnable(multiAction, numAttempt, server, callsInProgress);
995     }
996 
997     /**
998      * Group a list of actions per region servers, and send them.
999      *
1000      * @param currentActions - the list of row to submit
1001      * @param numAttempt - the current numAttempt (first attempt is 1)
1002      */
1003     private void groupAndSendMultiAction(List<Action<Row>> currentActions, int numAttempt) {
1004       Map<ServerName, MultiAction<Row>> actionsByServer =
1005           new HashMap<ServerName, MultiAction<Row>>();
1006 
1007       boolean isReplica = false;
1008       List<Action<Row>> unknownReplicaActions = null;
1009       for (Action<Row> action : currentActions) {
1010         RegionLocations locs = findAllLocationsOrFail(action, true);
1011         if (locs == null) continue;
1012         boolean isReplicaAction = !RegionReplicaUtil.isDefaultReplica(action.getReplicaId());
1013         if (isReplica && !isReplicaAction) {
1014           // This is the property of the current implementation, not a requirement.
1015           throw new AssertionError("Replica and non-replica actions in the same retry");
1016         }
1017         isReplica = isReplicaAction;
1018         HRegionLocation loc = locs.getRegionLocation(action.getReplicaId());
1019         if (loc == null || loc.getServerName() == null) {
1020           if (isReplica) {
1021             if (unknownReplicaActions == null) {
1022               unknownReplicaActions = new ArrayList<Action<Row>>();
1023             }
1024             unknownReplicaActions.add(action);
1025           } else {
1026             // TODO: relies on primary location always being fetched
1027             manageLocationError(action, null);
1028           }
1029         } else {
1030           byte[] regionName = loc.getRegionInfo().getRegionName();
1031           addAction(loc.getServerName(), regionName, action, actionsByServer, nonceGroup);
1032         }
1033       }
1034       boolean doStartReplica = (numAttempt == 1 && !isReplica && hasAnyReplicaGets);
1035       boolean hasUnknown = unknownReplicaActions != null && !unknownReplicaActions.isEmpty();
1036 
1037       if (!actionsByServer.isEmpty()) {
1038         // If this is a first attempt to group and send, no replicas, we need replica thread.
1039         sendMultiAction(actionsByServer, numAttempt, (doStartReplica && !hasUnknown)
1040             ? currentActions : null, numAttempt > 1 && !hasUnknown);
1041       }
1042 
1043       if (hasUnknown) {
1044         actionsByServer = new HashMap<ServerName, MultiAction<Row>>();
1045         for (Action<Row> action : unknownReplicaActions) {
1046           HRegionLocation loc = getReplicaLocationOrFail(action);
1047           if (loc == null) continue;
1048           byte[] regionName = loc.getRegionInfo().getRegionName();
1049           addAction(loc.getServerName(), regionName, action, actionsByServer, nonceGroup);
1050         }
1051         if (!actionsByServer.isEmpty()) {
1052           sendMultiAction(
1053               actionsByServer, numAttempt, doStartReplica ? currentActions : null, true);
1054         }
1055       }
1056     }
1057 
1058     private HRegionLocation getReplicaLocationOrFail(Action<Row> action) {
1059       // We are going to try get location once again. For each action, we'll do it once
1060       // from cache, because the previous calls in the loop might populate it.
1061       int replicaId = action.getReplicaId();
1062       RegionLocations locs = findAllLocationsOrFail(action, true);
1063       if (locs == null) return null; // manageError already called
1064       HRegionLocation loc = locs.getRegionLocation(replicaId);
1065       if (loc == null || loc.getServerName() == null) {
1066         locs = findAllLocationsOrFail(action, false);
1067         if (locs == null) return null; // manageError already called
1068         loc = locs.getRegionLocation(replicaId);
1069       }
1070       if (loc == null || loc.getServerName() == null) {
1071         manageLocationError(action, null);
1072         return null;
1073       }
1074       return loc;
1075     }
1076 
1077     private void manageLocationError(Action<Row> action, Exception ex) {
1078       String msg = "Cannot get replica " + action.getReplicaId()
1079           + " location for " + action.getAction();
1080       LOG.error(msg);
1081       if (ex == null) {
1082         ex = new IOException(msg);
1083       }
1084       manageError(action.getOriginalIndex(), action.getAction(),
1085           Retry.NO_LOCATION_PROBLEM, ex, null);
1086     }
1087 
1088     private RegionLocations findAllLocationsOrFail(Action<Row> action, boolean useCache) {
1089       if (action.getAction() == null) throw new IllegalArgumentException("#" + id +
1090           ", row cannot be null");
1091       RegionLocations loc = null;
1092       try {
1093         loc = connection.locateRegion(
1094             tableName, action.getAction().getRow(), useCache, true, action.getReplicaId());
1095       } catch (IOException ex) {
1096         manageLocationError(action, ex);
1097       }
1098       return loc;
1099     }
1100 
1101     /**
1102      * Send a multi action structure to the servers, after a delay depending on the attempt
1103      * number. Asynchronous.
1104      *
1105      * @param actionsByServer the actions structured by regions
1106      * @param numAttempt the attempt number.
1107      * @param actionsForReplicaThread original actions for replica thread; null on non-first call.
1108      */
1109     private void sendMultiAction(Map<ServerName, MultiAction<Row>> actionsByServer,
1110         int numAttempt, List<Action<Row>> actionsForReplicaThread, boolean reuseThread) {
1111       // Run the last item on the same thread if we are already on a send thread.
1112       // We hope most of the time it will be the only item, so we can cut down on threads.
1113       int actionsRemaining = actionsByServer.size();
1114       // This iteration is by server (the HRegionLocation comparator is by server portion only).
1115       for (Map.Entry<ServerName, MultiAction<Row>> e : actionsByServer.entrySet()) {
1116         ServerName server = e.getKey();
1117         MultiAction<Row> multiAction = e.getValue();
1118         Collection<? extends Runnable> runnables = getNewMultiActionRunnable(server, multiAction,
1119             numAttempt);
1120         // make sure we correctly count the number of runnables before we try to reuse the send
1121         // thread, in case we had to split the request into different runnables because of backoff
1122         if (runnables.size() > actionsRemaining) {
1123           actionsRemaining = runnables.size();
1124         }
1125 
1126         // run all the runnables
1127         // HBASE-17475: Do not reuse the thread after stack reach a certain depth to prevent stack overflow
1128         // for now, we use HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER to control the depth
1129         for (Runnable runnable : runnables) {
1130           if ((--actionsRemaining == 0) && reuseThread
1131               && numAttempt % HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER != 0) {
1132             runnable.run();
1133           } else {
1134             try {
1135               pool.submit(runnable);
1136             } catch (Throwable t) {
1137               if (t instanceof RejectedExecutionException) {
1138                 // This should never happen. But as the pool is provided by the end user,
1139                // let's secure this a little.
1140                LOG.warn("#" + id + ", the task was rejected by the pool. This is unexpected." +
1141                   " Server is " + server.getServerName(), t);
1142               } else {
1143                 // see #HBASE-14359 for more details
1144                 LOG.warn("Caught unexpected exception/error: ", t);
1145               }
1146               decTaskCounters(multiAction.getRegions(), server);
1147               // We're likely to fail again, but this will increment the attempt counter,
1148              // so it will finish.
1149               receiveGlobalFailure(multiAction, server, numAttempt, t);
1150             }
1151           }
1152         }
1153       }
1154 
1155       if (actionsForReplicaThread != null) {
1156         startWaitingForReplicaCalls(actionsForReplicaThread);
1157       }
1158     }
1159 
1160     private Collection<? extends Runnable> getNewMultiActionRunnable(ServerName server,
1161         MultiAction<Row> multiAction,
1162         int numAttempt) {
1163       // no stats to manage, just do the standard action
1164       if (AsyncProcess.this.connection.getStatisticsTracker() == null) {
1165         if (connection.getConnectionMetrics() != null) {
1166           connection.getConnectionMetrics().incrNormalRunners();
1167         }
1168         incTaskCounters(multiAction.getRegions(), server);
1169         SingleServerRequestRunnable runnable = createSingleServerRequest(multiAction, numAttempt, server, callsInProgress);
1170         return Collections.singletonList(Trace.wrap("AsyncProcess.sendMultiAction", runnable));
1171       }
1172 
1173       // group the actions by the amount of delay
1174       Map<Long, DelayingRunner> actions = new HashMap<Long, DelayingRunner>(multiAction
1175           .size());
1176 
1177       // split up the actions
1178       for (Map.Entry<byte[], List<Action<Row>>> e : multiAction.actions.entrySet()) {
1179         Long backoff = getBackoff(server, e.getKey());
1180         DelayingRunner runner = actions.get(backoff);
1181         if (runner == null) {
1182           actions.put(backoff, new DelayingRunner(backoff, e));
1183         } else {
1184           runner.add(e);
1185         }
1186       }
1187 
1188       List<Runnable> toReturn = new ArrayList<Runnable>(actions.size());
1189       for (DelayingRunner runner : actions.values()) {
1190         incTaskCounters(runner.getActions().getRegions(), server);
1191         String traceText = "AsyncProcess.sendMultiAction";
1192         Runnable runnable = createSingleServerRequest(runner.getActions(), numAttempt, server, callsInProgress);
1193         // use a delay runner only if we need to sleep for some time
1194         if (runner.getSleepTime() > 0) {
1195           runner.setRunner(runnable);
1196           traceText = "AsyncProcess.clientBackoff.sendMultiAction";
1197           runnable = runner;
1198           if (connection.getConnectionMetrics() != null) {
1199             connection.getConnectionMetrics().incrDelayRunners();
1200             connection.getConnectionMetrics().updateDelayInterval(runner.getSleepTime());
1201           }
1202         } else {
1203           if (connection.getConnectionMetrics() != null) {
1204             connection.getConnectionMetrics().incrNormalRunners();
1205           }
1206         }
1207         runnable = Trace.wrap(traceText, runnable);
1208         toReturn.add(runnable);
1209 
1210       }
1211       return toReturn;
1212     }
1213 
1214     /**
1215      * @param server server location where the target region is hosted
1216      * @param regionName name of the region which we are going to write some data
1217      * @return the amount of time the client should wait until it submit a request to the
1218      * specified server and region
1219      */
1220     private Long getBackoff(ServerName server, byte[] regionName) {
1221       ServerStatisticTracker tracker = AsyncProcess.this.connection.getStatisticsTracker();
1222       ServerStatistics stats = tracker.getStats(server);
1223       return AsyncProcess.this.connection.getBackoffPolicy()
1224           .getBackoffTime(server, regionName, stats);
1225     }
1226 
1227     /**
1228      * Starts waiting to issue replica calls on a different thread; or issues them immediately.
1229      */
1230     private void startWaitingForReplicaCalls(List<Action<Row>> actionsForReplicaThread) {
1231       long startTime = EnvironmentEdgeManager.currentTime();
1232       ReplicaCallIssuingRunnable replicaRunnable = new ReplicaCallIssuingRunnable(
1233           actionsForReplicaThread, startTime);
1234       if (primaryCallTimeoutMicroseconds == 0) {
1235         // Start replica calls immediately.
1236         replicaRunnable.run();
1237       } else {
1238         // Start the thread that may kick off replica gets.
1239         // TODO: we could do it on the same thread, but it's a user thread, might be a bad idea.
1240         try {
1241           pool.submit(replicaRunnable);
1242         } catch (RejectedExecutionException ree) {
1243           LOG.warn("#" + id + ", replica task was rejected by the pool - no replica calls", ree);
1244         }
1245       }
1246     }
1247 
1248     /**
1249      * Check that we can retry acts accordingly: logs, set the error status.
1250      *
1251      * @param originalIndex the position in the list sent
1252      * @param row           the row
1253      * @param canRetry      if false, we won't retry whatever the settings.
1254      * @param throwable     the throwable, if any (can be null)
1255      * @param server        the location, if any (can be null)
1256      * @return true if the action can be retried, false otherwise.
1257      */
1258     public Retry manageError(int originalIndex, Row row, Retry canRetry,
1259                                 Throwable throwable, ServerName server) {
1260       if (canRetry == Retry.YES
1261           && throwable != null && (throwable instanceof DoNotRetryIOException ||
1262           throwable instanceof NeedUnmanagedConnectionException)) {
1263         canRetry = Retry.NO_NOT_RETRIABLE;
1264       }
1265 
1266       if (canRetry != Retry.YES) {
1267         // Batch.Callback<Res> was not called on failure in 0.94. We keep this.
1268         setError(originalIndex, row, throwable, server);
1269       } else if (isActionComplete(originalIndex, row)) {
1270         canRetry = Retry.NO_OTHER_SUCCEEDED;
1271       }
1272       return canRetry;
1273     }
1274 
1275     /**
1276      * Resubmit all the actions from this multiaction after a failure.
1277      *
1278      * @param rsActions  the actions still to do from the initial list
1279      * @param server   the destination
1280      * @param numAttempt the number of attempts so far
1281      * @param t the throwable (if any) that caused the resubmit
1282      */
1283     private void receiveGlobalFailure(
1284         MultiAction<Row> rsActions, ServerName server, int numAttempt, Throwable t) {
1285       errorsByServer.reportServerError(server);
1286       Retry canRetry = errorsByServer.canRetryMore(numAttempt)
1287           ? Retry.YES : Retry.NO_RETRIES_EXHAUSTED;
1288 
1289       if (tableName == null && ClientExceptionsUtil.isMetaClearingException(t)) {
1290         // tableName is null when we made a cross-table RPC call.
1291         connection.clearCaches(server);
1292       }
1293       int failed = 0, stopped = 0;
1294       List<Action<Row>> toReplay = new ArrayList<Action<Row>>();
1295       for (Map.Entry<byte[], List<Action<Row>>> e : rsActions.actions.entrySet()) {
1296         byte[] regionName = e.getKey();
1297         byte[] row = e.getValue().iterator().next().getAction().getRow();
1298         // Do not use the exception for updating cache because it might be coming from
1299         // any of the regions in the MultiAction.
1300         try {
1301           if (tableName != null) {
1302             connection.updateCachedLocations(tableName, regionName, row,
1303               ClientExceptionsUtil.isMetaClearingException(t) ? null : t, server);
1304           }
1305         } catch (Throwable ex) {
1306           // That should never happen, but if it did, we want to make sure
1307           // we still process errors
1308           LOG.error("Couldn't update cached region locations: " + ex);
1309         }
1310         for (Action<Row> action : e.getValue()) {
1311           Retry retry = manageError(
1312               action.getOriginalIndex(), action.getAction(), canRetry, t, server);
1313           if (retry == Retry.YES) {
1314             toReplay.add(action);
1315           } else if (retry == Retry.NO_OTHER_SUCCEEDED) {
1316             ++stopped;
1317           } else {
1318             ++failed;
1319           }
1320         }
1321       }
1322 
1323       if (toReplay.isEmpty()) {
1324         logNoResubmit(server, numAttempt, rsActions.size(), t, failed, stopped);
1325       } else {
1326         resubmit(server, toReplay, numAttempt, rsActions.size(), t);
1327       }
1328     }
1329 
1330     /**
1331      * Log as much info as possible, and, if there is something to replay,
1332      * submit it again after a back off sleep.
1333      */
1334     private void resubmit(ServerName oldServer, List<Action<Row>> toReplay,
1335         int numAttempt, int failureCount, Throwable throwable) {
1336       // We have something to replay. We're going to sleep a little before.
1337 
1338       // We have two contradicting needs here:
1339       //  1) We want to get the new location after having slept, as it may change.
1340       //  2) We want to take into account the location when calculating the sleep time.
1341       //  3) If all this is just because the response needed to be chunked try again FAST.
1342       // It should be possible to have some heuristics to take the right decision. Short term,
1343       //  we go for one.
1344       boolean retryImmediately = throwable instanceof RetryImmediatelyException;
1345       int nextAttemptNumber = retryImmediately ? numAttempt : numAttempt + 1;
1346       long backOffTime;
1347       if (retryImmediately) {
1348         backOffTime = 0;
1349       } else if (throwable instanceof CallQueueTooBigException) {
1350         // Give a special check on CQTBE, see #HBASE-17114
1351         backOffTime = errorsByServer.calculateBackoffTime(oldServer, pauseForCQTBE);
1352       } else {
1353         backOffTime = errorsByServer.calculateBackoffTime(oldServer, pause);
1354       }
1355       if (numAttempt > startLogErrorsCnt) {
1356         // We use this value to have some logs when we have multiple failures, but not too many
1357         //  logs, as errors are to be expected when a region moves, splits and so on
1358         LOG.info(createLog(numAttempt, failureCount, toReplay.size(),
1359             oldServer, throwable, backOffTime, true, null, -1, -1));
1360       }
1361 
1362       try {
1363         if (backOffTime > 0) {
1364           Thread.sleep(backOffTime);
1365         }
1366       } catch (InterruptedException e) {
1367         LOG.warn("#" + id + ", not sent: " + toReplay.size() + " operations, " + oldServer, e);
1368         Thread.currentThread().interrupt();
1369         return;
1370       }
1371 
1372       groupAndSendMultiAction(toReplay, nextAttemptNumber);
1373     }
1374 
1375     private void logNoResubmit(ServerName oldServer, int numAttempt,
1376         int failureCount, Throwable throwable, int failed, int stopped) {
1377       if (failureCount != 0 || numAttempt > startLogErrorsCnt + 1) {
1378         String timeStr = new Date(errorsByServer.getStartTrackingTime()).toString();
1379         String logMessage = createLog(numAttempt, failureCount, 0, oldServer,
1380             throwable, -1, false, timeStr, failed, stopped);
1381         if (failed != 0) {
1382           // Only log final failures as warning
1383           LOG.warn(logMessage);
1384         } else {
1385           LOG.info(logMessage);
1386         }
1387       }
1388     }
1389 
1390     @VisibleForTesting
1391     long getActionsInProgress() {
1392       return actionsInProgress.get();
1393     }
1394     /**
1395      * Called when we receive the result of a server query.
1396      *
1397      * @param multiAction    - the multiAction we sent
1398      * @param server       - the location. It's used as a server name.
1399      * @param responses      - the response, if any
1400      * @param numAttempt     - the attempt
1401      */
1402     private void receiveMultiAction(MultiAction<Row> multiAction,
1403         ServerName server, MultiResponse responses, int numAttempt) {
1404        assert responses != null;
1405 
1406       // Success or partial success
1407       // Analyze detailed results. We can still have individual failures to be redo.
1408       // two specific throwables are managed:
1409       //  - DoNotRetryIOException: we continue to retry for other actions
1410       //  - RegionMovedException: we update the cache with the new region location
1411 
1412       List<Action<Row>> toReplay = new ArrayList<Action<Row>>();
1413       Throwable throwable = null;
1414       int failureCount = 0;
1415       Retry retry = null;
1416 
1417       Map<byte[], MultiResponse.RegionResult> results = responses.getResults();
1418       updateStats(server, results);
1419 
1420       int failed = 0;
1421       int stopped = 0;
1422       // Go by original action.
1423       for (Map.Entry<byte[], List<Action<Row>>> regionEntry : multiAction.actions.entrySet()) {
1424         byte[] regionName = regionEntry.getKey();
1425         Throwable regionException = responses.getExceptions().get(regionName);
1426         if (tableName == null && regionException != null &&
1427               ClientExceptionsUtil.isMetaClearingException(regionException)) {
1428           // For multi-actions, we don't have a table name, but we want to make sure to clear the
1429           // cache in case there were location-related exceptions. We don't to clear the cache
1430           // for every possible exception that comes through, however.
1431           connection.clearCaches(server);
1432         }
1433         Map<Integer, Object> regionResults;
1434         if (results.containsKey(regionName)) {
1435           regionResults = results.get(regionName).result;
1436         } else {
1437           regionResults = Collections.emptyMap();
1438         }
1439         boolean regionFailureRegistered = false;
1440         for (Action<Row> sentAction : regionEntry.getValue()) {
1441           Object result = regionResults.get(sentAction.getOriginalIndex());
1442           if (result == null) {
1443             if (regionException == null) {
1444               LOG.error("Server sent us neither results nor exceptions for " + Bytes
1445                 .toStringBinary(regionName) + ", numAttempt:" + numAttempt);
1446               regionException = new RuntimeException("Invalid response");
1447             }
1448             // If the row operation encounters the region-lever error, the exception of action
1449             // may be null.
1450             result = regionException;
1451           }
1452           // Failure: retry if it's make sense else update the errors lists
1453           if (result instanceof Throwable) {
1454             Row row = sentAction.getAction();
1455             throwable = regionException != null ? regionException
1456               : ClientExceptionsUtil.findException(result);
1457             // Register corresponding failures once per server/once per region.
1458             if (!regionFailureRegistered) {
1459               regionFailureRegistered = true;
1460               try {
1461                 connection.updateCachedLocations(
1462                   tableName, regionName, row.getRow(), result, server);
1463               } catch (Throwable ex) {
1464                 // That should never happen, but if it did, we want to make sure
1465                 // we still process errors
1466                 LOG.error("Couldn't update cached region locations: " + ex);
1467               }
1468             }
1469             if (retry == null) {
1470               errorsByServer.reportServerError(server);
1471               // We determine canRetry only once for all calls, after reporting server failure.
1472               retry =
1473                 errorsByServer.canRetryMore(numAttempt) ? Retry.YES : Retry.NO_RETRIES_EXHAUSTED;
1474             }
1475             ++failureCount;
1476             switch (manageError(sentAction.getOriginalIndex(), row, retry, (Throwable) result,
1477               server)) {
1478               case YES:
1479                 toReplay.add(sentAction);
1480                 break;
1481               case NO_OTHER_SUCCEEDED:
1482                 ++stopped;
1483                 break;
1484               default:
1485                 ++failed;
1486                 break;
1487             }
1488           } else {
1489             if (callback != null) {
1490               try {
1491                 //noinspection unchecked
1492                 // TODO: would callback expect a replica region name if it gets one?
1493                 this.callback.update(regionName, sentAction.getAction().getRow(), (CResult) result);
1494               } catch (Throwable t) {
1495                 LOG.error("User callback threw an exception for "
1496                     + Bytes.toStringBinary(regionName) + ", ignoring", t);
1497               }
1498             }
1499             setResult(sentAction, result);
1500           }
1501         }
1502       }
1503       if (toReplay.isEmpty()) {
1504         logNoResubmit(server, numAttempt, failureCount, throwable, failed, stopped);
1505       } else {
1506         resubmit(server, toReplay, numAttempt, failureCount, throwable);
1507       }
1508     }
1509 
1510     private String createLog(int numAttempt, int failureCount, int replaySize, ServerName sn,
1511         Throwable error, long backOffTime, boolean willRetry, String startTime,
1512         int failed, int stopped) {
1513       StringBuilder sb = new StringBuilder();
1514       sb.append("#").append(id).append(", table=").append(tableName).append(", ")
1515         .append("attempt=").append(numAttempt)
1516         .append("/").append(numTries).append(" ");
1517 
1518       if (failureCount > 0 || error != null){
1519         sb.append("failed=").append(failureCount).append("ops").append(", last exception: ").
1520             append(error == null ? "null" : error);
1521       } else {
1522         sb.append("succeeded");
1523       }
1524 
1525       sb.append(" on ").append(sn).append(", tracking started ").append(startTime);
1526 
1527       if (willRetry) {
1528         sb.append(", retrying after=").append(backOffTime).append("ms").
1529             append(", replay=").append(replaySize).append("ops");
1530       } else if (failureCount > 0) {
1531         if (stopped > 0) {
1532           sb.append("; not retrying ").append(stopped).append(" due to success from other replica");
1533         }
1534         if (failed > 0) {
1535           sb.append("; not retrying ").append(failed).append(" - final failure");
1536         }
1537 
1538       }
1539 
1540       return sb.toString();
1541     }
1542 
1543     /**
1544      * Sets the non-error result from a particular action.
1545      * @param action Action (request) that the server responded to.
1546      * @param result The result.
1547      */
1548     private void setResult(Action<Row> action, Object result) {
1549       if (result == null) {
1550         throw new RuntimeException("Result cannot be null");
1551       }
1552       ReplicaResultState state = null;
1553       boolean isStale = !RegionReplicaUtil.isDefaultReplica(action.getReplicaId());
1554       int index = action.getOriginalIndex();
1555       if (results == null) {
1556          decActionCounter(index);
1557          return; // Simple case, no replica requests.
1558       } else if ((state = trySetResultSimple(
1559           index, action.getAction(), false, result, null, isStale)) == null) {
1560         return; // Simple case, no replica requests.
1561       }
1562       assert state != null;
1563       // At this point we know that state is set to replica tracking class.
1564       // It could be that someone else is also looking at it; however, we know there can
1565       // only be one state object, and only one thread can set callCount to 0. Other threads
1566       // will either see state with callCount 0 after locking it; or will not see state at all
1567       // we will replace it with the result.
1568       synchronized (state) {
1569         if (state.callCount == 0) {
1570           return; // someone already set the result
1571         }
1572         state.callCount = 0;
1573       }
1574       synchronized (replicaResultLock) {
1575         if (results[index] != state) {
1576           throw new AssertionError("We set the callCount but someone else replaced the result");
1577         }
1578         results[index] = result;
1579       }
1580 
1581       decActionCounter(index);
1582     }
1583 
1584     /**
1585      * Sets the error from a particular action.
1586      * @param index Original action index.
1587      * @param row Original request.
1588      * @param throwable The resulting error.
1589      * @param server The source server.
1590      */
1591     private void setError(int index, Row row, Throwable throwable, ServerName server) {
1592       ReplicaResultState state = null;
1593       if (results == null) {
1594         // Note that we currently cannot have replica requests with null results. So it shouldn't
1595         // happen that multiple replica calls will call dAC for same actions with results == null.
1596         // Only one call per action should be present in this case.
1597         errors.add(throwable, row, server);
1598         decActionCounter(index);
1599         return; // Simple case, no replica requests.
1600       } else if ((state = trySetResultSimple(
1601           index, row, true, throwable, server, false)) == null) {
1602         return; // Simple case, no replica requests.
1603       }
1604       assert state != null;
1605       BatchErrors target = null; // Error will be added to final errors, or temp replica errors.
1606       boolean isActionDone = false;
1607       synchronized (state) {
1608         switch (state.callCount) {
1609           case 0: return; // someone already set the result
1610           case 1: { // All calls failed, we are the last error.
1611             target = errors;
1612             isActionDone = true;
1613             break;
1614           }
1615           default: {
1616             assert state.callCount > 1;
1617             if (state.replicaErrors == null) {
1618               state.replicaErrors = new BatchErrors();
1619             }
1620             target = state.replicaErrors;
1621             break;
1622           }
1623         }
1624         --state.callCount;
1625       }
1626       target.add(throwable, row, server);
1627       if (isActionDone) {
1628         if (state.replicaErrors != null) { // last call, no need to lock
1629           errors.merge(state.replicaErrors);
1630         }
1631         // See setResult for explanations.
1632         synchronized (replicaResultLock) {
1633           if (results[index] != state) {
1634             throw new AssertionError("We set the callCount but someone else replaced the result");
1635           }
1636           results[index] = throwable;
1637         }
1638         decActionCounter(index);
1639       }
1640     }
1641 
1642     /**
1643      * Checks if the action is complete; used on error to prevent needless retries.
1644      * Does not synchronize, assuming element index/field accesses are atomic.
1645      * This is an opportunistic optimization check, doesn't have to be strict.
1646      * @param index Original action index.
1647      * @param row Original request.
1648      */
1649     private boolean isActionComplete(int index, Row row) {
1650       if (!isReplicaGet(row)) return false;
1651       Object resObj = results[index];
1652       return (resObj != null) && (!(resObj instanceof ReplicaResultState)
1653           || ((ReplicaResultState)resObj).callCount == 0);
1654     }
1655 
1656     /**
1657      * Tries to set the result or error for a particular action as if there were no replica calls.
1658      * @return null if successful; replica state if there were in fact replica calls.
1659      */
1660     private ReplicaResultState trySetResultSimple(int index, Row row, boolean isError,
1661         Object result, ServerName server, boolean isFromReplica) {
1662       Object resObj = null;
1663       if (!isReplicaGet(row)) {
1664         if (isFromReplica) {
1665           throw new AssertionError("Unexpected stale result for " + row);
1666         }
1667         results[index] = result;
1668       } else {
1669         synchronized (replicaResultLock) {
1670           if ((resObj = results[index]) == null) {
1671             if (isFromReplica) {
1672               throw new AssertionError("Unexpected stale result for " + row);
1673             }
1674             results[index] = result;
1675           }
1676         }
1677       }
1678 
1679       ReplicaResultState rrs =
1680           (resObj instanceof ReplicaResultState) ? (ReplicaResultState)resObj : null;
1681       if (rrs == null && isError) {
1682         // The resObj is not replica state (null or already set).
1683         errors.add((Throwable)result, row, server);
1684       }
1685 
1686       if (resObj == null) {
1687         // resObj is null - no replica calls were made.
1688         decActionCounter(index);
1689         return null;
1690       }
1691       return rrs;
1692     }
1693 
1694     private void decActionCounter(int index) {
1695       long actionsRemaining = actionsInProgress.decrementAndGet();
1696       if (actionsRemaining < 0) {
1697         String error = buildDetailedErrorMsg("Incorrect actions in progress", index);
1698         throw new AssertionError(error);
1699       } else if (actionsRemaining == 0) {
1700         synchronized (actionsInProgress) {
1701           actionsInProgress.notifyAll();
1702         }
1703       }
1704     }
1705 
1706     private String buildDetailedErrorMsg(String string, int index) {
1707       StringBuilder error = new StringBuilder(string);
1708       error.append("; called for ").
1709         append(index).
1710         append(", actionsInProgress ").
1711         append(actionsInProgress.get()).
1712         append("; replica gets: ");
1713       if (replicaGetIndices != null) {
1714         for (int i = 0; i < replicaGetIndices.length; ++i) {
1715           error.append(replicaGetIndices[i]).append(", ");
1716         }
1717       } else {
1718         error.append(hasAnyReplicaGets ? "all" : "none");
1719       }
1720       error.append("; results ");
1721       if (results != null) {
1722         for (int i = 0; i < results.length; ++i) {
1723           Object o = results[i];
1724           error.append(((o == null) ? "null" : o.toString())).append(", ");
1725         }
1726       }
1727       return error.toString();
1728     }
1729 
1730     @Override
1731     public void waitUntilDone() throws InterruptedIOException {
1732       try {
1733         waitUntilDone(Long.MAX_VALUE);
1734       } catch (InterruptedException iex) {
1735         throw new InterruptedIOException(iex.getMessage());
1736       } finally {
1737         if (callsInProgress != null) {
1738           for (PayloadCarryingServerCallable clb : callsInProgress) {
1739             clb.cancel();
1740           }
1741         }
1742       }
1743     }
1744 
1745     private boolean waitUntilDone(long cutoff) throws InterruptedException {
1746       boolean hasWait = cutoff != Long.MAX_VALUE;
1747       long lastLog = EnvironmentEdgeManager.currentTime();
1748       long currentInProgress;
1749       while (0 != (currentInProgress = actionsInProgress.get())) {
1750         long now = EnvironmentEdgeManager.currentTime();
1751         if (hasWait && (now * 1000L) > cutoff) {
1752           return false;
1753         }
1754         if (!hasWait) { // Only log if wait is infinite.
1755           if (now > lastLog + 10000) {
1756             lastLog = now;
1757             LOG.info("#" + id + ", waiting for " + currentInProgress
1758                 + "  actions to finish on table: " + tableName);
1759             if (currentInProgress <= thresholdToLogUndoneTaskDetails) {
1760               logDetailsOfUndoneTasks(currentInProgress);
1761             }
1762           }
1763         }
1764         synchronized (actionsInProgress) {
1765           if (actionsInProgress.get() == 0) break;
1766           if (!hasWait) {
1767             actionsInProgress.wait(10);
1768           } else {
1769             long waitMicroSecond = Math.min(100000L, (cutoff - now * 1000L));
1770             TimeUnit.MICROSECONDS.timedWait(actionsInProgress, waitMicroSecond);
1771           }
1772         }
1773       }
1774       return true;
1775     }
1776 
1777     @Override
1778     public boolean hasError() {
1779       return errors.hasErrors();
1780     }
1781 
1782     @Override
1783     public List<? extends Row> getFailedOperations() {
1784       return errors.actions;
1785     }
1786 
1787     @Override
1788     public RetriesExhaustedWithDetailsException getErrors() {
1789       return errors.makeException(logBatchErrorDetails);
1790     }
1791 
1792     @Override
1793     public Object[] getResults() throws InterruptedIOException {
1794       waitUntilDone();
1795       return results;
1796     }
1797 
1798     /**
1799      * Create a callable. Isolated to be easily overridden in the tests.
1800      */
1801     @VisibleForTesting
1802     protected MultiServerCallable<Row> createCallable(final ServerName server,
1803         TableName tableName, final MultiAction<Row> multi) {
1804       return new MultiServerCallable<Row>(connection, tableName, server,
1805           AsyncProcess.this.rpcFactory, multi, rpcTimeout, tracker, multi.getPriority());
1806     }
1807   }
1808 
1809   @VisibleForTesting
1810   protected void updateStats(ServerName server, Map<byte[], MultiResponse.RegionResult> results) {
1811     boolean metrics = AsyncProcess.this.connection.getConnectionMetrics() != null;
1812     boolean stats = AsyncProcess.this.connection.getStatisticsTracker() != null;
1813     if (!stats && !metrics) {
1814       return;
1815     }
1816     for (Map.Entry<byte[], MultiResponse.RegionResult> regionStats : results.entrySet()) {
1817       byte[] regionName = regionStats.getKey();
1818       ClientProtos.RegionLoadStats stat = regionStats.getValue().getStat();
1819       ResultStatsUtil.updateStats(AsyncProcess.this.connection.getStatisticsTracker(), server,
1820           regionName, stat);
1821       ResultStatsUtil.updateStats(AsyncProcess.this.connection.getConnectionMetrics(),
1822           server, regionName, stat);
1823     }
1824   }
1825 
1826   @VisibleForTesting
1827   <CResult> AsyncRequestFutureImpl<CResult> createAsyncRequestFuture(
1828       TableName tableName, List<Action<Row>> actions, long nonceGroup, ExecutorService pool,
1829       Batch.Callback<CResult> callback, Object[] results, boolean needResults,
1830       PayloadCarryingServerCallable callable, int operationTimeout, int rpcTimeout) {
1831     return new AsyncRequestFutureImpl<CResult>(
1832         tableName, actions, nonceGroup, getPool(pool), needResults,
1833         results, callback, callable, operationTimeout, rpcTimeout);
1834   }
1835 
1836   /**
1837    * Create a caller. Isolated to be easily overridden in the tests.
1838    */
1839   @VisibleForTesting
1840   protected RpcRetryingCaller<MultiResponse> createCaller(PayloadCarryingServerCallable callable,
1841       int rpcTimeout) {
1842     return rpcCallerFactory.<MultiResponse> newCaller(rpcTimeout);
1843   }
1844 
1845   @VisibleForTesting
1846   /** Waits until all outstanding tasks are done. Used in tests. */
1847   void waitUntilDone() throws InterruptedIOException {
1848     waitForMaximumCurrentTasks(0, null);
1849   }
1850 
1851   /** Wait until the async does not have more than max tasks in progress. */
1852   private void waitForMaximumCurrentTasks(int max, String tableName)
1853       throws InterruptedIOException {
1854     waitForMaximumCurrentTasks(max, tasksInProgress, id, tableName);
1855   }
1856 
1857   // Break out this method so testable
1858   @VisibleForTesting
1859   void waitForMaximumCurrentTasks(int max, final AtomicLong tasksInProgress, final long id,
1860       String tableName) throws InterruptedIOException {
1861     long lastLog = EnvironmentEdgeManager.currentTime();
1862     long currentInProgress, oldInProgress = Long.MAX_VALUE;
1863     while ((currentInProgress = tasksInProgress.get()) > max) {
1864       if (oldInProgress != currentInProgress) { // Wait for in progress to change.
1865         long now = EnvironmentEdgeManager.currentTime();
1866         if (now > lastLog + 10000) {
1867           lastLog = now;
1868           LOG.info("#" + id + ", waiting for some tasks to finish. Expected max="
1869               + max + ", tasksInProgress=" + currentInProgress +
1870               " hasError=" + hasError() + (tableName == null ? "" : ", tableName=" + tableName));
1871           if (currentInProgress <= thresholdToLogUndoneTaskDetails) {
1872             logDetailsOfUndoneTasks(currentInProgress);
1873           }
1874         }
1875       }
1876       oldInProgress = currentInProgress;
1877       try {
1878         synchronized (tasksInProgress) {
1879           if (tasksInProgress.get() == oldInProgress) {
1880             tasksInProgress.wait(10);
1881           }
1882         }
1883       } catch (InterruptedException e) {
1884         throw new InterruptedIOException("#" + id + ", interrupted." +
1885             " currentNumberOfTask=" + currentInProgress);
1886       }
1887     }
1888   }
1889 
1890   private void logDetailsOfUndoneTasks(long taskInProgress) {
1891     ArrayList<ServerName> servers = new ArrayList<ServerName>();
1892     for (Map.Entry<ServerName, AtomicInteger> entry : taskCounterPerServer.entrySet()) {
1893       if (entry.getValue().get() > 0) {
1894         servers.add(entry.getKey());
1895       }
1896     }
1897     LOG.info("Left over " + taskInProgress + " task(s) are processed on server(s): " + servers);
1898     if (taskInProgress <= THRESHOLD_TO_LOG_REGION_DETAILS) {
1899       ArrayList<String> regions = new ArrayList<String>();
1900       for (Map.Entry<byte[], AtomicInteger> entry : taskCounterPerRegion.entrySet()) {
1901         if (entry.getValue().get() > 0) {
1902           regions.add(Bytes.toString(entry.getKey()));
1903         }
1904       }
1905       LOG.info("Regions against which left over task(s) are processed: " + regions);
1906     }
1907   }
1908 
1909   /**
1910    * Only used w/useGlobalErrors ctor argument, for HTable backward compat.
1911    * @return Whether there were any errors in any request since the last time
1912    *          {@link #waitForAllPreviousOpsAndReset(List)} was called, or AP was created.
1913    */
1914   public boolean hasError() {
1915     return globalErrors.hasErrors();
1916   }
1917 
1918   /**
1919    * Only used w/useGlobalErrors ctor argument, for HTable backward compat.
1920    * Waits for all previous operations to finish, and returns errors and (optionally)
1921    * failed operations themselves.
1922    * @param failedRows an optional list into which the rows that failed since the last time
1923    *        {@link #waitForAllPreviousOpsAndReset(List)} was called, or AP was created, are saved.
1924    * @param tableName name of the table
1925    * @return all the errors since the last time {@link #waitForAllPreviousOpsAndReset(List)}
1926    *          was called, or AP was created.
1927    */
1928   public RetriesExhaustedWithDetailsException waitForAllPreviousOpsAndReset(
1929       List<Row> failedRows, String tableName) throws InterruptedIOException {
1930     waitForMaximumCurrentTasks(0, tableName);
1931     if (!globalErrors.hasErrors()) {
1932       return null;
1933     }
1934     if (failedRows != null) {
1935       failedRows.addAll(globalErrors.actions);
1936     }
1937     RetriesExhaustedWithDetailsException result = globalErrors.makeException(logBatchErrorDetails);
1938     globalErrors.clear();
1939     return result;
1940   }
1941 
1942   /**
1943    * increment the tasks counters for a given set of regions. MT safe.
1944    */
1945   protected void incTaskCounters(Collection<byte[]> regions, ServerName sn) {
1946     tasksInProgress.incrementAndGet();
1947 
1948     AtomicInteger serverCnt = taskCounterPerServer.get(sn);
1949     if (serverCnt == null) {
1950       taskCounterPerServer.putIfAbsent(sn, new AtomicInteger());
1951       serverCnt = taskCounterPerServer.get(sn);
1952     }
1953     serverCnt.incrementAndGet();
1954 
1955     for (byte[] regBytes : regions) {
1956       AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes);
1957       if (regionCnt == null) {
1958         regionCnt = new AtomicInteger();
1959         AtomicInteger oldCnt = taskCounterPerRegion.putIfAbsent(regBytes, regionCnt);
1960         if (oldCnt != null) {
1961           regionCnt = oldCnt;
1962         }
1963       }
1964       regionCnt.incrementAndGet();
1965     }
1966   }
1967 
1968   /**
1969    * Decrements the counters for a given region and the region server. MT Safe.
1970    */
1971   protected void decTaskCounters(Collection<byte[]> regions, ServerName sn) {
1972     for (byte[] regBytes : regions) {
1973       AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes);
1974       regionCnt.decrementAndGet();
1975     }
1976 
1977     taskCounterPerServer.get(sn).decrementAndGet();
1978     tasksInProgress.decrementAndGet();
1979     synchronized (tasksInProgress) {
1980       tasksInProgress.notifyAll();
1981     }
1982   }
1983 
1984   /**
1985    * Creates the server error tracker to use inside process.
1986    * Currently, to preserve the main assumption about current retries, and to work well with
1987    * the retry-limit-based calculation, the calculation is local per Process object.
1988    * We may benefit from connection-wide tracking of server errors.
1989    * @return ServerErrorTracker to use, null if there is no ServerErrorTracker on this connection
1990    */
1991   protected ConnectionManager.ServerErrorTracker createServerErrorTracker() {
1992     return new ConnectionManager.ServerErrorTracker(
1993         this.serverTrackerTimeout, this.numTries);
1994   }
1995 
1996   private static boolean isReplicaGet(Row row) {
1997     return (row instanceof Get) && (((Get)row).getConsistency() == Consistency.TIMELINE);
1998   }
1999 
2000   /**
2001    * For manageError. Only used to make logging more clear, we don't actually care why we don't retry.
2002    */
2003   private enum Retry {
2004     YES,
2005     NO_LOCATION_PROBLEM,
2006     NO_NOT_RETRIABLE,
2007     NO_RETRIES_EXHAUSTED,
2008     NO_OTHER_SUCCEEDED
2009   }
2010 
2011   /**
2012    * Collect all advices from checkers and make the final decision.
2013    */
2014   @VisibleForTesting
2015   static class RowCheckerHost {
2016     private final List<RowChecker> checkers;
2017     private boolean isEnd = false;
2018     RowCheckerHost(final List<RowChecker> checkers) {
2019       this.checkers = checkers;
2020     }
2021     void reset() throws InterruptedIOException {
2022       isEnd = false;
2023       InterruptedIOException e = null;
2024       for (RowChecker checker : checkers) {
2025         try {
2026           checker.reset();
2027         } catch (InterruptedIOException ex) {
2028           e = ex;
2029         }
2030       }
2031       if (e != null) {
2032         throw e;
2033       }
2034     }
2035     ReturnCode canTakeOperation(HRegionLocation loc, long rowSize) {
2036       if (isEnd) {
2037         return ReturnCode.END;
2038       }
2039       ReturnCode code = ReturnCode.INCLUDE;
2040       for (RowChecker checker : checkers) {
2041         switch (checker.canTakeOperation(loc, rowSize)) {
2042           case END:
2043             isEnd = true;
2044             code = ReturnCode.END;
2045             break;
2046           case SKIP:
2047             code = ReturnCode.SKIP;
2048             break;
2049           case INCLUDE:
2050           default:
2051             break;
2052         }
2053         if (code == ReturnCode.END) {
2054           break;
2055         }
2056       }
2057       for (RowChecker checker : checkers) {
2058         checker.notifyFinal(code, loc, rowSize);
2059       }
2060       return code;
2061     }
2062   }
2063 
2064   /**
2065    * Provide a way to control the flow of rows iteration.
2066    */
2067   @VisibleForTesting
2068   interface RowChecker {
2069     enum ReturnCode {
2070       /**
2071        * Accept current row.
2072        */
2073       INCLUDE,
2074       /**
2075        * Skip current row.
2076        */
2077       SKIP,
2078       /**
2079        * No more row can be included.
2080        */
2081       END
2082     };
2083     ReturnCode canTakeOperation(HRegionLocation loc, long rowSize);
2084     /**
2085      * Add the final ReturnCode to the checker.
2086      * The ReturnCode may be reversed, so the checker need the final decision to update
2087      * the inner state.
2088      */
2089     void notifyFinal(ReturnCode code, HRegionLocation loc, long rowSize);
2090     /**
2091      * Reset the inner state.
2092      */
2093     void reset() throws InterruptedIOException ;
2094   }
2095 
2096   /**
2097    * limit the heapsize of total submitted data.
2098    * Reduce the limit of heapsize for submitting quickly
2099    * if there is no running task.
2100    */
2101   @VisibleForTesting
2102   static class SubmittedSizeChecker implements RowChecker {
2103     private final long maxHeapSizeSubmit;
2104     private long heapSize = 0;
2105     SubmittedSizeChecker(final long maxHeapSizeSubmit) {
2106       this.maxHeapSizeSubmit = maxHeapSizeSubmit;
2107     }
2108     @Override
2109     public ReturnCode canTakeOperation(HRegionLocation loc, long rowSize) {
2110       if (heapSize >= maxHeapSizeSubmit) {
2111         return ReturnCode.END;
2112       }
2113       return ReturnCode.INCLUDE;
2114     }
2115 
2116     @Override
2117     public void notifyFinal(ReturnCode code, HRegionLocation loc, long rowSize) {
2118       if (code == ReturnCode.INCLUDE) {
2119         heapSize += rowSize;
2120       }
2121     }
2122 
2123     @Override
2124     public void reset() {
2125       heapSize = 0;
2126     }
2127   }
2128   /**
2129    * limit the max number of tasks in an AsyncProcess.
2130    */
2131   @VisibleForTesting
2132   static class TaskCountChecker implements RowChecker {
2133     private static final long MAX_WAITING_TIME = 1000; //ms
2134     private final Set<HRegionInfo> regionsIncluded = new HashSet<>();
2135     private final Set<ServerName> serversIncluded = new HashSet<>();
2136     private final int maxConcurrentTasksPerRegion;
2137     private final int maxTotalConcurrentTasks;
2138     private final int maxConcurrentTasksPerServer;
2139     private final Map<byte[], AtomicInteger> taskCounterPerRegion;
2140     private final Map<ServerName, AtomicInteger> taskCounterPerServer;
2141     private final Set<byte[]> busyRegions = new TreeSet<>(Bytes.BYTES_COMPARATOR);
2142     private final AtomicLong tasksInProgress;
2143     TaskCountChecker(final int maxTotalConcurrentTasks,
2144       final int maxConcurrentTasksPerServer,
2145       final int maxConcurrentTasksPerRegion,
2146       final AtomicLong tasksInProgress,
2147       final Map<ServerName, AtomicInteger> taskCounterPerServer,
2148       final Map<byte[], AtomicInteger> taskCounterPerRegion) {
2149       this.maxTotalConcurrentTasks = maxTotalConcurrentTasks;
2150       this.maxConcurrentTasksPerRegion = maxConcurrentTasksPerRegion;
2151       this.maxConcurrentTasksPerServer = maxConcurrentTasksPerServer;
2152       this.taskCounterPerRegion = taskCounterPerRegion;
2153       this.taskCounterPerServer = taskCounterPerServer;
2154       this.tasksInProgress = tasksInProgress;
2155     }
2156     @Override
2157     public void reset() throws InterruptedIOException {
2158       // prevent the busy-waiting
2159       waitForRegion();
2160       regionsIncluded.clear();
2161       serversIncluded.clear();
2162       busyRegions.clear();
2163     }
2164     private void waitForRegion() throws InterruptedIOException {
2165       if (busyRegions.isEmpty()) {
2166         return;
2167       }
2168       EnvironmentEdge ee = EnvironmentEdgeManager.getDelegate();
2169       final long start = ee.currentTime();
2170       while ((ee.currentTime() - start) <= MAX_WAITING_TIME) {
2171         for (byte[] region : busyRegions) {
2172           AtomicInteger count = taskCounterPerRegion.get(region);
2173           if (count == null || count.get() < maxConcurrentTasksPerRegion) {
2174             return;
2175           }
2176         }
2177         try {
2178           synchronized (tasksInProgress) {
2179             tasksInProgress.wait(10);
2180           }
2181         } catch (InterruptedException e) {
2182           throw new InterruptedIOException("Interrupted." +
2183               " tasksInProgress=" + tasksInProgress);
2184         }
2185       }
2186     }
2187     /**
2188      * 1) check the regions is allowed.
2189      * 2) check the concurrent tasks for regions.
2190      * 3) check the total concurrent tasks.
2191      * 4) check the concurrent tasks for server.
2192      * @param loc
2193      * @param rowSize
2194      * @return
2195      */
2196     @Override
2197     public ReturnCode canTakeOperation(HRegionLocation loc, long rowSize) {
2198 
2199       HRegionInfo regionInfo = loc.getRegionInfo();
2200       if (regionsIncluded.contains(regionInfo)) {
2201         // We already know what to do with this region.
2202         return ReturnCode.INCLUDE;
2203       }
2204       AtomicInteger regionCnt = taskCounterPerRegion.get(loc.getRegionInfo().getRegionName());
2205       if (regionCnt != null && regionCnt.get() >= maxConcurrentTasksPerRegion) {
2206         // Too many tasks on this region already.
2207         return ReturnCode.SKIP;
2208       }
2209       int newServers = serversIncluded.size()
2210         + (serversIncluded.contains(loc.getServerName()) ? 0 : 1);
2211       if ((newServers + tasksInProgress.get()) > maxTotalConcurrentTasks) {
2212         // Too many tasks.
2213         return ReturnCode.SKIP;
2214       }
2215       AtomicInteger serverCnt = taskCounterPerServer.get(loc.getServerName());
2216       if (serverCnt != null && serverCnt.get() >= maxConcurrentTasksPerServer) {
2217         // Too many tasks for this individual server
2218         return ReturnCode.SKIP;
2219       }
2220       return ReturnCode.INCLUDE;
2221     }
2222 
2223     @Override
2224     public void notifyFinal(ReturnCode code, HRegionLocation loc, long rowSize) {
2225       if (code == ReturnCode.INCLUDE) {
2226         regionsIncluded.add(loc.getRegionInfo());
2227         serversIncluded.add(loc.getServerName());
2228       }
2229       busyRegions.add(loc.getRegionInfo().getRegionName());
2230     }
2231   }
2232 
2233   /**
2234    * limit the request size for each regionserver.
2235    */
2236   @VisibleForTesting
2237   static class RequestSizeChecker implements RowChecker {
2238     private final long maxHeapSizePerRequest;
2239     private final Map<ServerName, Long> serverRequestSizes = new HashMap<>();
2240     RequestSizeChecker(final long maxHeapSizePerRequest) {
2241       this.maxHeapSizePerRequest = maxHeapSizePerRequest;
2242     }
2243     @Override
2244     public void reset() {
2245       serverRequestSizes.clear();
2246     }
2247     @Override
2248     public ReturnCode canTakeOperation(HRegionLocation loc, long rowSize) {
2249       // Is it ok for limit of request size?
2250       long currentRequestSize = serverRequestSizes.containsKey(loc.getServerName()) ?
2251         serverRequestSizes.get(loc.getServerName()) : 0L;
2252       // accept at least one request
2253       if (currentRequestSize == 0 || currentRequestSize + rowSize <= maxHeapSizePerRequest) {
2254         return ReturnCode.INCLUDE;
2255       }
2256       return ReturnCode.SKIP;
2257     }
2258 
2259     @Override
2260     public void notifyFinal(ReturnCode code, HRegionLocation loc, long rowSize) {
2261       if (code == ReturnCode.INCLUDE) {
2262         long currentRequestSize = serverRequestSizes.containsKey(loc.getServerName()) ?
2263           serverRequestSizes.get(loc.getServerName()) : 0L;
2264         serverRequestSizes.put(loc.getServerName(), currentRequestSize + rowSize);
2265       }
2266     }
2267   }
2268 
2269   public static class ListRowAccess<T> implements RowAccess<T> {
2270     private final List<T> data;
2271     ListRowAccess(final List<T> data) {
2272       this.data = data;
2273     }
2274 
2275     @Override
2276     public int size() {
2277       return data.size();
2278     }
2279 
2280     @Override
2281     public boolean isEmpty() {
2282       return data.isEmpty();
2283     }
2284 
2285     @Override
2286     public Iterator<T> iterator() {
2287       return data.iterator();
2288     }
2289   }
2290 }