View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.client;
21  
22  import java.io.IOException;
23  import java.io.InterruptedIOException;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.Collections;
27  import java.util.Date;
28  import java.util.HashMap;
29  import java.util.Iterator;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.concurrent.ConcurrentHashMap;
34  import java.util.concurrent.ConcurrentMap;
35  import java.util.concurrent.ConcurrentSkipListMap;
36  import java.util.concurrent.ExecutorService;
37  import java.util.concurrent.RejectedExecutionException;
38  import java.util.concurrent.TimeUnit;
39  import java.util.concurrent.atomic.AtomicInteger;
40  import java.util.concurrent.atomic.AtomicLong;
41  
42  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  import org.apache.hadoop.hbase.classification.InterfaceAudience;
45  import org.apache.hadoop.conf.Configuration;
46  import org.apache.hadoop.hbase.DoNotRetryIOException;
47  import org.apache.hadoop.hbase.HConstants;
48  import org.apache.hadoop.hbase.HRegionInfo;
49  import org.apache.hadoop.hbase.HRegionLocation;
50  import org.apache.hadoop.hbase.RegionLocations;
51  import org.apache.hadoop.hbase.ServerName;
52  import org.apache.hadoop.hbase.TableName;
53  import org.apache.hadoop.hbase.client.backoff.ServerStatistics;
54  import org.apache.hadoop.hbase.client.coprocessor.Batch;
55  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
56  import org.apache.hadoop.hbase.util.Bytes;
57  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
58  import org.apache.htrace.Trace;
59  
60  import com.google.common.annotations.VisibleForTesting;
61  
62  /**
63   * This class  allows a continuous flow of requests. It's written to be compatible with a
64   * synchronous caller such as HTable.
65   * <p>
66   * The caller sends a buffer of operation, by calling submit. This class extract from this list
67   * the operations it can send, i.e. the operations that are on region that are not considered
68   * as busy. The process is asynchronous, i.e. it returns immediately when if has finished to
69   * iterate on the list. If, and only if, the maximum number of current task is reached, the call
70   * to submit will block. Alternatively, the caller can call submitAll, in which case all the
71   * operations will be sent. Each call to submit returns a future-like object that can be used
72   * to track operation progress.
73   * </p>
74   * <p>
75   * The class manages internally the retries.
76   * </p>
77   * <p>
78   * The class can be constructed in regular mode, or "global error" mode. In global error mode,
79   * AP tracks errors across all calls (each "future" also has global view of all errors). That
80   * mode is necessary for backward compat with HTable behavior, where multiple submissions are
81   * made and the errors can propagate using any put/flush call, from previous calls.
82   * In "regular" mode, the errors are tracked inside the Future object that is returned.
83   * The results are always tracked inside the Future object and can be retrieved when the call
84   * has finished. Partial results can also be retrieved if some part of multi-request failed.
85   * </p>
86   * <p>
87   * This class is thread safe in regular mode; in global error code, submitting operations and
88   * retrieving errors from different threads may be not thread safe.
89   * Internally, the class is thread safe enough to manage simultaneously new submission and results
90   * arising from older operations.
91   * </p>
92   * <p>
93   * Internally, this class works with {@link Row}, this mean it could be theoretically used for
94   * gets as well.
95   * </p>
96   */
97  @InterfaceAudience.Private
98  class AsyncProcess {
99    protected static final Log LOG = LogFactory.getLog(AsyncProcess.class);
100   protected static final AtomicLong COUNTER = new AtomicLong();
101 
102   public static final String PRIMARY_CALL_TIMEOUT_KEY = "hbase.client.primaryCallTimeout.multiget";
103 
104   /**
105    * Configure the number of failures after which the client will start logging. A few failures
106    * is fine: region moved, then is not opened, then is overloaded. We try to have an acceptable
107    * heuristic for the number of errors we don't log. 9 was chosen because we wait for 1s at
108    * this stage.
109    */
110   public static final String START_LOG_ERRORS_AFTER_COUNT_KEY =
111       "hbase.client.start.log.errors.counter";
112   public static final int DEFAULT_START_LOG_ERRORS_AFTER_COUNT = 9;
113 
114   /**
115    * The context used to wait for results from one submit call.
116    * 1) If AsyncProcess is set to track errors globally, and not per call (for HTable puts),
117    *    then errors and failed operations in this object will reflect global errors.
118    * 2) If submit call is made with needResults false, results will not be saved.
119    *  */
120   public static interface AsyncRequestFuture {
121     public boolean hasError();
122     public RetriesExhaustedWithDetailsException getErrors();
123     public List<? extends Row> getFailedOperations();
124     public Object[] getResults() throws InterruptedIOException;
125     /** Wait until all tasks are executed, successfully or not. */
126     public void waitUntilDone() throws InterruptedIOException;
127   }
128 
129   /** Return value from a submit that didn't contain any requests. */
130   private static final AsyncRequestFuture NO_REQS_RESULT = new AsyncRequestFuture() {
131     public final Object[] result = new Object[0];
132     @Override
133     public boolean hasError() { return false; }
134     @Override
135     public RetriesExhaustedWithDetailsException getErrors() { return null; }
136     @Override
137     public List<? extends Row> getFailedOperations() { return null; }
138     @Override
139     public Object[] getResults() { return result; }
140     @Override
141     public void waitUntilDone() throws InterruptedIOException {}
142   };
143 
144   /** Sync point for calls to multiple replicas for the same user request (Get).
145    * Created and put in the results array (we assume replica calls require results) when
146    * the replica calls are launched. See results for details of this process.
147    * POJO, all fields are public. To modify them, the object itself is locked. */
148   private static class ReplicaResultState {
149     public ReplicaResultState(int callCount) {
150       this.callCount = callCount;
151     }
152 
153     /** Number of calls outstanding, or 0 if a call succeeded (even with others outstanding). */
154     int callCount;
155     /** Errors for which it is not decided whether we will report them to user. If one of the
156      * calls succeeds, we will discard the errors that may have happened in the other calls. */
157     BatchErrors replicaErrors = null;
158 
159     @Override
160     public String toString() {
161       return "[call count " + callCount + "; errors " + replicaErrors + "]";
162     }
163   }
164 
165 
166   // TODO: many of the fields should be made private
167   protected final long id;
168 
169   protected final ClusterConnection connection;
170   protected final RpcRetryingCallerFactory rpcCallerFactory;
171   protected final RpcControllerFactory rpcFactory;
172   protected final BatchErrors globalErrors;
173   protected final ExecutorService pool;
174 
175   protected final AtomicLong tasksInProgress = new AtomicLong(0);
176   protected final ConcurrentMap<byte[], AtomicInteger> taskCounterPerRegion =
177       new ConcurrentSkipListMap<byte[], AtomicInteger>(Bytes.BYTES_COMPARATOR);
178   protected final ConcurrentMap<ServerName, AtomicInteger> taskCounterPerServer =
179       new ConcurrentHashMap<ServerName, AtomicInteger>();
180 
181   // Start configuration settings.
182   private final int startLogErrorsCnt;
183 
184   /**
185    * The number of tasks simultaneously executed on the cluster.
186    */
187   protected final int maxTotalConcurrentTasks;
188 
189   /**
190    * The number of tasks we run in parallel on a single region.
191    * With 1 (the default) , we ensure that the ordering of the queries is respected: we don't start
192    * a set of operations on a region before the previous one is done. As well, this limits
193    * the pressure we put on the region server.
194    */
195   protected final int maxConcurrentTasksPerRegion;
196 
197   /**
198    * The number of task simultaneously executed on a single region server.
199    */
200   protected final int maxConcurrentTasksPerServer;
201   protected final long pause;
202   protected int numTries;
203   protected int serverTrackerTimeout;
204   protected int timeout;
205   protected long primaryCallTimeoutMicroseconds;
206   // End configuration settings.
207 
208   protected static class BatchErrors {
209     private final List<Throwable> throwables = new ArrayList<Throwable>();
210     private final List<Row> actions = new ArrayList<Row>();
211     private final List<String> addresses = new ArrayList<String>();
212 
213     public synchronized void add(Throwable ex, Row row, ServerName serverName) {
214       if (row == null){
215         throw new IllegalArgumentException("row cannot be null. location=" + serverName);
216       }
217 
218       throwables.add(ex);
219       actions.add(row);
220       addresses.add(serverName != null ? serverName.toString() : "null");
221     }
222 
223     public boolean hasErrors() {
224       return !throwables.isEmpty();
225     }
226 
227     private synchronized RetriesExhaustedWithDetailsException makeException() {
228       return new RetriesExhaustedWithDetailsException(
229           new ArrayList<Throwable>(throwables),
230           new ArrayList<Row>(actions), new ArrayList<String>(addresses));
231     }
232 
233     public synchronized void clear() {
234       throwables.clear();
235       actions.clear();
236       addresses.clear();
237     }
238 
239     public synchronized void merge(BatchErrors other) {
240       throwables.addAll(other.throwables);
241       actions.addAll(other.actions);
242       addresses.addAll(other.addresses);
243     }
244   }
245 
246   public AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService pool,
247       RpcRetryingCallerFactory rpcCaller, boolean useGlobalErrors, RpcControllerFactory rpcFactory) {
248     if (hc == null) {
249       throw new IllegalArgumentException("HConnection cannot be null.");
250     }
251 
252     this.connection = hc;
253     this.pool = pool;
254     this.globalErrors = useGlobalErrors ? new BatchErrors() : null;
255 
256     this.id = COUNTER.incrementAndGet();
257 
258     this.pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
259         HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
260     this.numTries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
261         HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
262     this.timeout = conf.getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
263         HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
264     this.primaryCallTimeoutMicroseconds = conf.getInt(PRIMARY_CALL_TIMEOUT_KEY, 10000);
265 
266     this.maxTotalConcurrentTasks = conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
267       HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS);
268     this.maxConcurrentTasksPerServer = conf.getInt(HConstants.HBASE_CLIENT_MAX_PERSERVER_TASKS,
269           HConstants.DEFAULT_HBASE_CLIENT_MAX_PERSERVER_TASKS);
270     this.maxConcurrentTasksPerRegion = conf.getInt(HConstants.HBASE_CLIENT_MAX_PERREGION_TASKS,
271           HConstants.DEFAULT_HBASE_CLIENT_MAX_PERREGION_TASKS);
272 
273     this.startLogErrorsCnt =
274         conf.getInt(START_LOG_ERRORS_AFTER_COUNT_KEY, DEFAULT_START_LOG_ERRORS_AFTER_COUNT);
275 
276     if (this.maxTotalConcurrentTasks <= 0) {
277       throw new IllegalArgumentException("maxTotalConcurrentTasks=" + maxTotalConcurrentTasks);
278     }
279     if (this.maxConcurrentTasksPerServer <= 0) {
280       throw new IllegalArgumentException("maxConcurrentTasksPerServer=" +
281           maxConcurrentTasksPerServer);
282     }
283     if (this.maxConcurrentTasksPerRegion <= 0) {
284       throw new IllegalArgumentException("maxConcurrentTasksPerRegion=" +
285           maxConcurrentTasksPerRegion);
286     }
287 
288     // Server tracker allows us to do faster, and yet useful (hopefully), retries.
289     // However, if we are too useful, we might fail very quickly due to retry count limit.
290     // To avoid this, we are going to cheat for now (see HBASE-7659), and calculate maximum
291     // retry time if normal retries were used. Then we will retry until this time runs out.
292     // If we keep hitting one server, the net effect will be the incremental backoff, and
293     // essentially the same number of retries as planned. If we have to do faster retries,
294     // we will do more retries in aggregate, but the user will be none the wiser.
295     this.serverTrackerTimeout = 0;
296     for (int i = 0; i < this.numTries; ++i) {
297       serverTrackerTimeout += ConnectionUtils.getPauseTime(this.pause, i);
298     }
299 
300     this.rpcCallerFactory = rpcCaller;
301     this.rpcFactory = rpcFactory;
302   }
303 
304   /**
305    * @return pool if non null, otherwise returns this.pool if non null, otherwise throws
306    *         RuntimeException
307    */
308   private ExecutorService getPool(ExecutorService pool) {
309     if (pool != null) return pool;
310     if (this.pool != null) return this.pool;
311     throw new RuntimeException("Neither AsyncProcess nor request have ExecutorService");
312   }
313 
314   /**
315    * See {@link #submit(ExecutorService, TableName, List, boolean, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback, boolean)}.
316    * Uses default ExecutorService for this AP (must have been created with one).
317    */
318   public <CResult> AsyncRequestFuture submit(TableName tableName, List<? extends Row> rows,
319       boolean atLeastOne, Batch.Callback<CResult> callback, boolean needResults)
320       throws InterruptedIOException {
321     return submit(null, tableName, rows, atLeastOne, callback, needResults);
322   }
323 
324   /**
325    * Extract from the rows list what we can submit. The rows we can not submit are kept in the
326    * list. Does not send requests to replicas (not currently used for anything other
327    * than streaming puts anyway).
328    *
329    * @param pool ExecutorService to use.
330    * @param tableName The table for which this request is needed.
331    * @param callback Batch callback. Only called on success (94 behavior).
332    * @param needResults Whether results are needed, or can be discarded.
333    * @param rows - the submitted row. Modified by the method: we remove the rows we took.
334    * @param atLeastOne true if we should submit at least a subset.
335    */
336   public <CResult> AsyncRequestFuture submit(ExecutorService pool, TableName tableName,
337       List<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback,
338       boolean needResults) throws InterruptedIOException {
339     if (rows.isEmpty()) {
340       return NO_REQS_RESULT;
341     }
342 
343     Map<ServerName, MultiAction<Row>> actionsByServer =
344         new HashMap<ServerName, MultiAction<Row>>();
345     List<Action<Row>> retainedActions = new ArrayList<Action<Row>>(rows.size());
346 
347     NonceGenerator ng = this.connection.getNonceGenerator();
348     long nonceGroup = ng.getNonceGroup(); // Currently, nonce group is per entire client.
349 
350     // Location errors that happen before we decide what requests to take.
351     List<Exception> locationErrors = null;
352     List<Integer> locationErrorRows = null;
353     do {
354       // Wait until there is at least one slot for a new task.
355       waitForMaximumCurrentTasks(maxTotalConcurrentTasks - 1);
356 
357       // Remember the previous decisions about regions or region servers we put in the
358       //  final multi.
359       Map<Long, Boolean> regionIncluded = new HashMap<Long, Boolean>();
360       Map<ServerName, Boolean> serverIncluded = new HashMap<ServerName, Boolean>();
361 
362       int posInList = -1;
363       Iterator<? extends Row> it = rows.iterator();
364       while (it.hasNext()) {
365         Row r = it.next();
366         HRegionLocation loc;
367         try {
368           if (r == null) throw new IllegalArgumentException("#" + id + ", row cannot be null");
369           // Make sure we get 0-s replica.
370           RegionLocations locs = connection.locateRegion(
371               tableName, r.getRow(), true, true, RegionReplicaUtil.DEFAULT_REPLICA_ID);
372           if (locs == null || locs.isEmpty() || locs.getDefaultRegionLocation() == null) {
373             throw new IOException("#" + id + ", no location found, aborting submit for"
374                 + " tableName=" + tableName + " rowkey=" + Bytes.toStringBinary(r.getRow()));
375           }
376           loc = locs.getDefaultRegionLocation();
377         } catch (IOException ex) {
378           locationErrors = new ArrayList<Exception>();
379           locationErrorRows = new ArrayList<Integer>();
380           LOG.error("Failed to get region location ", ex);
381           // This action failed before creating ars. Retain it, but do not add to submit list.
382           // We will then add it to ars in an already-failed state.
383           retainedActions.add(new Action<Row>(r, ++posInList));
384           locationErrors.add(ex);
385           locationErrorRows.add(posInList);
386           it.remove();
387           break; // Backward compat: we stop considering actions on location error.
388         }
389 
390         if (canTakeOperation(loc, regionIncluded, serverIncluded)) {
391           Action<Row> action = new Action<Row>(r, ++posInList);
392           setNonce(ng, r, action);
393           retainedActions.add(action);
394           // TODO: replica-get is not supported on this path
395           byte[] regionName = loc.getRegionInfo().getRegionName();
396           addAction(loc.getServerName(), regionName, action, actionsByServer, nonceGroup);
397           it.remove();
398         }
399       }
400     } while (retainedActions.isEmpty() && atLeastOne && (locationErrors == null));
401 
402     if (retainedActions.isEmpty()) return NO_REQS_RESULT;
403 
404     return submitMultiActions(tableName, retainedActions, nonceGroup, callback, null, needResults,
405       locationErrors, locationErrorRows, actionsByServer, pool);
406   }
407 
408   <CResult> AsyncRequestFuture submitMultiActions(TableName tableName,
409       List<Action<Row>> retainedActions, long nonceGroup, Batch.Callback<CResult> callback,
410       Object[] results, boolean needResults, List<Exception> locationErrors,
411       List<Integer> locationErrorRows, Map<ServerName, MultiAction<Row>> actionsByServer,
412       ExecutorService pool) {
413     AsyncRequestFutureImpl<CResult> ars = createAsyncRequestFuture(
414       tableName, retainedActions, nonceGroup, pool, callback, results, needResults);
415     // Add location errors if any
416     if (locationErrors != null) {
417       for (int i = 0; i < locationErrors.size(); ++i) {
418         int originalIndex = locationErrorRows.get(i);
419         Row row = retainedActions.get(originalIndex).getAction();
420         ars.manageError(originalIndex, row,
421           Retry.NO_LOCATION_PROBLEM, locationErrors.get(i), null);
422       }
423     }
424     ars.sendMultiAction(actionsByServer, 1, null, false);
425     return ars;
426   }
427 
428   /**
429    * Helper that is used when grouping the actions per region server.
430    *
431    * @param loc - the destination. Must not be null.
432    * @param action - the action to add to the multiaction
433    * @param actionsByServer the multiaction per server
434    * @param nonceGroup Nonce group.
435    */
436   private static void addAction(ServerName server, byte[] regionName, Action<Row> action,
437       Map<ServerName, MultiAction<Row>> actionsByServer, long nonceGroup) {
438     MultiAction<Row> multiAction = actionsByServer.get(server);
439     if (multiAction == null) {
440       multiAction = new MultiAction<Row>();
441       actionsByServer.put(server, multiAction);
442     }
443     if (action.hasNonce() && !multiAction.hasNonceGroup()) {
444       multiAction.setNonceGroup(nonceGroup);
445     }
446 
447     multiAction.add(regionName, action);
448   }
449 
450   /**
451    * Check if we should send new operations to this region or region server.
452    * We're taking into account the past decision; if we have already accepted
453    * operation on a given region, we accept all operations for this region.
454    *
455    * @param loc; the region and the server name we want to use.
456    * @return true if this region is considered as busy.
457    */
458   protected boolean canTakeOperation(HRegionLocation loc,
459                                      Map<Long, Boolean> regionsIncluded,
460                                      Map<ServerName, Boolean> serversIncluded) {
461     long regionId = loc.getRegionInfo().getRegionId();
462     Boolean regionPrevious = regionsIncluded.get(regionId);
463 
464     if (regionPrevious != null) {
465       // We already know what to do with this region.
466       return regionPrevious;
467     }
468 
469     Boolean serverPrevious = serversIncluded.get(loc.getServerName());
470     if (Boolean.FALSE.equals(serverPrevious)) {
471       // It's a new region, on a region server that we have already excluded.
472       regionsIncluded.put(regionId, Boolean.FALSE);
473       return false;
474     }
475 
476     AtomicInteger regionCnt = taskCounterPerRegion.get(loc.getRegionInfo().getRegionName());
477     if (regionCnt != null && regionCnt.get() >= maxConcurrentTasksPerRegion) {
478       // Too many tasks on this region already.
479       regionsIncluded.put(regionId, Boolean.FALSE);
480       return false;
481     }
482 
483     if (serverPrevious == null) {
484       // The region is ok, but we need to decide for this region server.
485       int newServers = 0; // number of servers we're going to contact so far
486       for (Map.Entry<ServerName, Boolean> kv : serversIncluded.entrySet()) {
487         if (kv.getValue()) {
488           newServers++;
489         }
490       }
491 
492       // Do we have too many total tasks already?
493       boolean ok = (newServers + tasksInProgress.get()) < maxTotalConcurrentTasks;
494 
495       if (ok) {
496         // If the total is fine, is it ok for this individual server?
497         AtomicInteger serverCnt = taskCounterPerServer.get(loc.getServerName());
498         ok = (serverCnt == null || serverCnt.get() < maxConcurrentTasksPerServer);
499       }
500 
501       if (!ok) {
502         regionsIncluded.put(regionId, Boolean.FALSE);
503         serversIncluded.put(loc.getServerName(), Boolean.FALSE);
504         return false;
505       }
506 
507       serversIncluded.put(loc.getServerName(), Boolean.TRUE);
508     } else {
509       assert serverPrevious.equals(Boolean.TRUE);
510     }
511 
512     regionsIncluded.put(regionId, Boolean.TRUE);
513 
514     return true;
515   }
516 
517   /**
518    * See {@link #submitAll(ExecutorService, TableName, List, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback, Object[])}.
519    * Uses default ExecutorService for this AP (must have been created with one).
520    */
521   public <CResult> AsyncRequestFuture submitAll(TableName tableName,
522       List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results) {
523     return submitAll(null, tableName, rows, callback, results);
524   }
525 
526   /**
527    * Submit immediately the list of rows, whatever the server status. Kept for backward
528    * compatibility: it allows to be used with the batch interface that return an array of objects.
529    *
530    * @param pool ExecutorService to use.
531    * @param tableName name of the table for which the submission is made.
532    * @param rows the list of rows.
533    * @param callback the callback.
534    * @param results Optional array to return the results thru; backward compat.
535    */
536   public <CResult> AsyncRequestFuture submitAll(ExecutorService pool, TableName tableName,
537       List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results) {
538     List<Action<Row>> actions = new ArrayList<Action<Row>>(rows.size());
539 
540     // The position will be used by the processBatch to match the object array returned.
541     int posInList = -1;
542     NonceGenerator ng = this.connection.getNonceGenerator();
543     for (Row r : rows) {
544       posInList++;
545       if (r instanceof Put) {
546         Put put = (Put) r;
547         if (put.isEmpty()) {
548           throw new IllegalArgumentException("No columns to insert for #" + (posInList+1)+ " item");
549         }
550       }
551       Action<Row> action = new Action<Row>(r, posInList);
552       setNonce(ng, r, action);
553       actions.add(action);
554     }
555     AsyncRequestFutureImpl<CResult> ars = createAsyncRequestFuture(
556         tableName, actions, ng.getNonceGroup(), getPool(pool), callback, results, results != null);
557     ars.groupAndSendMultiAction(actions, 1);
558     return ars;
559   }
560 
561   private static void setNonce(NonceGenerator ng, Row r, Action<Row> action) {
562     if (!(r instanceof Append) && !(r instanceof Increment)) return;
563     action.setNonce(ng.newNonce()); // Action handles NO_NONCE, so it's ok if ng is disabled.
564   }
565 
566   /**
567    * The context, and return value, for a single submit/submitAll call.
568    * Note on how this class (one AP submit) works. Initially, all requests are split into groups
569    * by server; request is sent to each server in parallel; the RPC calls are not async so a
570    * thread per server is used. Every time some actions fail, regions/locations might have
571    * changed, so we re-group them by server and region again and send these groups in parallel
572    * too. The result, in case of retries, is a "tree" of threads, with parent exiting after
573    * scheduling children. This is why lots of code doesn't require any synchronization.
574    */
575   protected class AsyncRequestFutureImpl<CResult> implements AsyncRequestFuture {
576 
577     /**
578      * Runnable (that can be submitted to thread pool) that waits for when it's time
579      * to issue replica calls, finds region replicas, groups the requests by replica and
580      * issues the calls (on separate threads, via sendMultiAction).
581      * This is done on a separate thread because we don't want to wait on user thread for
582      * our asynchronous call, and usually we have to wait before making replica calls.
583      */
584     private final class ReplicaCallIssuingRunnable implements Runnable {
585       private final long startTime;
586       private final List<Action<Row>> initialActions;
587 
588       public ReplicaCallIssuingRunnable(List<Action<Row>> initialActions, long startTime) {
589         this.initialActions = initialActions;
590         this.startTime = startTime;
591       }
592 
593       @Override
594       public void run() {
595         boolean done = false;
596         if (primaryCallTimeoutMicroseconds > 0) {
597           try {
598             done = waitUntilDone(startTime * 1000L + primaryCallTimeoutMicroseconds);
599           } catch (InterruptedException ex) {
600             LOG.error("Replica thread was interrupted - no replica calls: " + ex.getMessage());
601             return;
602           }
603         }
604         if (done) return; // Done within primary timeout
605         Map<ServerName, MultiAction<Row>> actionsByServer =
606             new HashMap<ServerName, MultiAction<Row>>();
607         List<Action<Row>> unknownLocActions = new ArrayList<Action<Row>>();
608         if (replicaGetIndices == null) {
609           for (int i = 0; i < results.length; ++i) {
610             addReplicaActions(i, actionsByServer, unknownLocActions);
611           }
612         } else {
613           for (int replicaGetIndice : replicaGetIndices) {
614             addReplicaActions(replicaGetIndice, actionsByServer, unknownLocActions);
615           }
616         }
617         if (!actionsByServer.isEmpty()) {
618           sendMultiAction(actionsByServer, 1, null, unknownLocActions.isEmpty());
619         }
620         if (!unknownLocActions.isEmpty()) {
621           actionsByServer = new HashMap<ServerName, MultiAction<Row>>();
622           for (Action<Row> action : unknownLocActions) {
623             addReplicaActionsAgain(action, actionsByServer);
624           }
625           // Some actions may have completely failed, they are handled inside addAgain.
626           if (!actionsByServer.isEmpty()) {
627             sendMultiAction(actionsByServer, 1, null, true);
628           }
629         }
630       }
631 
632       /**
633        * Add replica actions to action map by server.
634        * @param index Index of the original action.
635        * @param actionsByServer The map by server to add it to.
636        */
637       private void addReplicaActions(int index, Map<ServerName, MultiAction<Row>> actionsByServer,
638           List<Action<Row>> unknownReplicaActions) {
639         if (results[index] != null) return; // opportunistic. Never goes from non-null to null.
640         Action<Row> action = initialActions.get(index);
641         RegionLocations loc = findAllLocationsOrFail(action, true);
642         if (loc == null) return;
643         HRegionLocation[] locs = loc.getRegionLocations();
644         if (locs.length == 1) {
645           LOG.warn("No replicas found for " + action.getAction());
646           return;
647         }
648         synchronized (replicaResultLock) {
649           // Don't run replica calls if the original has finished. We could do it e.g. if
650           // original has already failed before first replica call (unlikely given retries),
651           // but that would require additional synchronization w.r.t. returning to caller.
652           if (results[index] != null) return;
653           // We set the number of calls here. After that any path must call setResult/setError.
654           // True even for replicas that are not found - if we refuse to send we MUST set error.
655           results[index] = new ReplicaResultState(locs.length);
656         }
657         for (int i = 1; i < locs.length; ++i) {
658           Action<Row> replicaAction = new Action<Row>(action, i);
659           if (locs[i] != null) {
660             addAction(locs[i].getServerName(), locs[i].getRegionInfo().getRegionName(),
661                 replicaAction, actionsByServer, nonceGroup);
662           } else {
663             unknownReplicaActions.add(replicaAction);
664           }
665         }
666       }
667 
668       private void addReplicaActionsAgain(
669           Action<Row> action, Map<ServerName, MultiAction<Row>> actionsByServer) {
670         if (action.getReplicaId() == RegionReplicaUtil.DEFAULT_REPLICA_ID) {
671           throw new AssertionError("Cannot have default replica here");
672         }
673         HRegionLocation loc = getReplicaLocationOrFail(action);
674         if (loc == null) return;
675         addAction(loc.getServerName(), loc.getRegionInfo().getRegionName(),
676             action, actionsByServer, nonceGroup);
677       }
678     }
679 
680     /**
681      * Runnable (that can be submitted to thread pool) that submits MultiAction to a
682      * single server. The server call is synchronous, therefore we do it on a thread pool.
683      */
684     private final class SingleServerRequestRunnable implements Runnable {
685       private final MultiAction<Row> multiAction;
686       private final int numAttempt;
687       private final ServerName server;
688       private final Set<MultiServerCallable<Row>> callsInProgress;
689 
690       private SingleServerRequestRunnable(
691           MultiAction<Row> multiAction, int numAttempt, ServerName server,
692           Set<MultiServerCallable<Row>> callsInProgress) {
693         this.multiAction = multiAction;
694         this.numAttempt = numAttempt;
695         this.server = server;
696         this.callsInProgress = callsInProgress;
697       }
698 
699       @Override
700       public void run() {
701         MultiResponse res;
702         MultiServerCallable<Row> callable = null;
703         try {
704           callable = createCallable(server, tableName, multiAction);
705           try {
706             RpcRetryingCaller<MultiResponse> caller = createCaller(callable);
707             if (callsInProgress != null) callsInProgress.add(callable);
708             res = caller.callWithoutRetries(callable, timeout);
709 
710             if (res == null) {
711               // Cancelled
712               return;
713             }
714 
715           } catch (IOException e) {
716             // The service itself failed . It may be an error coming from the communication
717             //   layer, but, as well, a functional error raised by the server.
718             receiveGlobalFailure(multiAction, server, numAttempt, e);
719             return;
720           } catch (Throwable t) {
721             // This should not happen. Let's log & retry anyway.
722             LOG.error("#" + id + ", Caught throwable while calling. This is unexpected." +
723                 " Retrying. Server is " + server + ", tableName=" + tableName, t);
724             receiveGlobalFailure(multiAction, server, numAttempt, t);
725             return;
726           }
727 
728           // Normal case: we received an answer from the server, and it's not an exception.
729           receiveMultiAction(multiAction, server, res, numAttempt);
730         } catch (Throwable t) {
731               // Something really bad happened. We are on the send thread that will now die.
732               LOG.error("Internal AsyncProcess #" + id + " error for "
733                   + tableName + " processing for " + server, t);
734               throw new RuntimeException(t);
735         } finally {
736           decTaskCounters(multiAction.getRegions(), server);
737           if (callsInProgress != null && callable != null) {
738             callsInProgress.remove(callable);
739           }
740         }
741       }
742     }
743 
744     private final Batch.Callback<CResult> callback;
745     private final BatchErrors errors;
746     private final ConnectionManager.ServerErrorTracker errorsByServer;
747     private final ExecutorService pool;
748     private final Set<MultiServerCallable<Row>> callsInProgress;
749 
750 
751     private final TableName tableName;
752     private final AtomicLong actionsInProgress = new AtomicLong(-1);
753     /** The lock controls access to results. It is only held when populating results where
754      * there might be several callers (eventual consistency gets). For other requests,
755      * there's one unique call going on per result index. */
756     private final Object replicaResultLock = new Object();
757     /** Result array.  Null if results are not needed. Otherwise, each index corresponds to
758      * the action index in initial actions submitted. For most request types, has null-s for
759      * requests that are not done, and result/exception for those that are done.
760      * For eventual-consistency gets, initially the same applies; at some point, replica calls
761      * might be started, and ReplicaResultState is put at the corresponding indices. The
762      * returning calls check the type to detect when this is the case. After all calls are done,
763      * ReplicaResultState-s are replaced with results for the user. */
764     private final Object[] results;
765     /** Indices of replica gets in results. If null, all or no actions are replica-gets. */
766     private final int[] replicaGetIndices;
767     private final boolean hasAnyReplicaGets;
768     private final long nonceGroup;
769 
770     public AsyncRequestFutureImpl(TableName tableName, List<Action<Row>> actions, long nonceGroup,
771         ExecutorService pool, boolean needResults, Object[] results,
772         Batch.Callback<CResult> callback) {
773       this.pool = pool;
774       this.callback = callback;
775       this.nonceGroup = nonceGroup;
776       this.tableName = tableName;
777       this.actionsInProgress.set(actions.size());
778       if (results != null) {
779         assert needResults;
780         if (results.length != actions.size()) throw new AssertionError("results.length");
781         this.results = results;
782         for (int i = 0; i != this.results.length; ++i) {
783           results[i] = null;
784         }
785       } else {
786         this.results = needResults ? new Object[actions.size()] : null;
787       }
788       List<Integer> replicaGetIndices = null;
789       boolean hasAnyReplicaGets = false;
790       if (needResults) {
791         // Check to see if any requests might require replica calls.
792         // We expect that many requests will consist of all or no multi-replica gets; in such
793         // cases we would just use a boolean (hasAnyReplicaGets). If there's a mix, we will
794         // store the list of action indexes for which replica gets are possible, and set
795         // hasAnyReplicaGets to true.
796         boolean hasAnyNonReplicaReqs = false;
797         int posInList = 0;
798         for (Action<Row> action : actions) {
799           boolean isReplicaGet = isReplicaGet(action.getAction());
800           if (isReplicaGet) {
801             hasAnyReplicaGets = true;
802             if (hasAnyNonReplicaReqs) { // Mixed case
803               if (replicaGetIndices == null) {
804                 replicaGetIndices = new ArrayList<Integer>(actions.size() - 1);
805               }
806               replicaGetIndices.add(posInList);
807             }
808           } else if (!hasAnyNonReplicaReqs) {
809             // The first non-multi-replica request in the action list.
810             hasAnyNonReplicaReqs = true;
811             if (posInList > 0) {
812               // Add all the previous requests to the index lists. We know they are all
813               // replica-gets because this is the first non-multi-replica request in the list.
814               replicaGetIndices = new ArrayList<Integer>(actions.size() - 1);
815               for (int i = 0; i < posInList; ++i) {
816                 replicaGetIndices.add(i);
817               }
818             }
819           }
820           ++posInList;
821         }
822       }
823       this.hasAnyReplicaGets = hasAnyReplicaGets;
824       if (replicaGetIndices != null) {
825         this.replicaGetIndices = new int[replicaGetIndices.size()];
826         int i = 0;
827         for (Integer el : replicaGetIndices) {
828           this.replicaGetIndices[i++] = el;
829         }
830       } else {
831         this.replicaGetIndices = null;
832       }
833       this.callsInProgress = !hasAnyReplicaGets ? null :
834           Collections.newSetFromMap(new ConcurrentHashMap<MultiServerCallable<Row>, Boolean>());
835 
836       this.errorsByServer = createServerErrorTracker();
837       this.errors = (globalErrors != null) ? globalErrors : new BatchErrors();
838     }
839 
840     public Set<MultiServerCallable<Row>> getCallsInProgress() {
841       return callsInProgress;
842     }
843 
844     /**
845      * Group a list of actions per region servers, and send them.
846      *
847      * @param currentActions - the list of row to submit
848      * @param numAttempt - the current numAttempt (first attempt is 1)
849      */
850     private void groupAndSendMultiAction(List<Action<Row>> currentActions, int numAttempt) {
851       Map<ServerName, MultiAction<Row>> actionsByServer =
852           new HashMap<ServerName, MultiAction<Row>>();
853 
854       boolean isReplica = false;
855       List<Action<Row>> unknownReplicaActions = null;
856       for (Action<Row> action : currentActions) {
857         RegionLocations locs = findAllLocationsOrFail(action, true);
858         if (locs == null) continue;
859         boolean isReplicaAction = !RegionReplicaUtil.isDefaultReplica(action.getReplicaId());
860         if (isReplica && !isReplicaAction) {
861           // This is the property of the current implementation, not a requirement.
862           throw new AssertionError("Replica and non-replica actions in the same retry");
863         }
864         isReplica = isReplicaAction;
865         HRegionLocation loc = locs.getRegionLocation(action.getReplicaId());
866         if (loc == null || loc.getServerName() == null) {
867           if (isReplica) {
868             if (unknownReplicaActions == null) {
869               unknownReplicaActions = new ArrayList<Action<Row>>();
870             }
871             unknownReplicaActions.add(action);
872           } else {
873             // TODO: relies on primary location always being fetched
874             manageLocationError(action, null);
875           }
876         } else {
877           byte[] regionName = loc.getRegionInfo().getRegionName();
878           addAction(loc.getServerName(), regionName, action, actionsByServer, nonceGroup);
879         }
880       }
881       boolean doStartReplica = (numAttempt == 1 && !isReplica && hasAnyReplicaGets);
882       boolean hasUnknown = unknownReplicaActions != null && !unknownReplicaActions.isEmpty();
883 
884       if (!actionsByServer.isEmpty()) {
885         // If this is a first attempt to group and send, no replicas, we need replica thread.
886         sendMultiAction(actionsByServer, numAttempt, (doStartReplica && !hasUnknown)
887             ? currentActions : null, numAttempt > 1 && !hasUnknown);
888       }
889 
890       if (hasUnknown) {
891         actionsByServer = new HashMap<ServerName, MultiAction<Row>>();
892         for (Action<Row> action : unknownReplicaActions) {
893           HRegionLocation loc = getReplicaLocationOrFail(action);
894           if (loc == null) continue;
895           byte[] regionName = loc.getRegionInfo().getRegionName();
896           addAction(loc.getServerName(), regionName, action, actionsByServer, nonceGroup);
897         }
898         if (!actionsByServer.isEmpty()) {
899           sendMultiAction(
900               actionsByServer, numAttempt, doStartReplica ? currentActions : null, true);
901         }
902       }
903     }
904 
905     private HRegionLocation getReplicaLocationOrFail(Action<Row> action) {
906       // We are going to try get location once again. For each action, we'll do it once
907       // from cache, because the previous calls in the loop might populate it.
908       int replicaId = action.getReplicaId();
909       RegionLocations locs = findAllLocationsOrFail(action, true);
910       if (locs == null) return null; // manageError already called
911       HRegionLocation loc = locs.getRegionLocation(replicaId);
912       if (loc == null || loc.getServerName() == null) {
913         locs = findAllLocationsOrFail(action, false);
914         if (locs == null) return null; // manageError already called
915         loc = locs.getRegionLocation(replicaId);
916       }
917       if (loc == null || loc.getServerName() == null) {
918         manageLocationError(action, null);
919         return null;
920       }
921       return loc;
922     }
923 
924     private void manageLocationError(Action<Row> action, Exception ex) {
925       String msg = "Cannot get replica " + action.getReplicaId()
926           + " location for " + action.getAction();
927       LOG.error(msg);
928       if (ex == null) {
929         ex = new IOException(msg);
930       }
931       manageError(action.getOriginalIndex(), action.getAction(),
932           Retry.NO_LOCATION_PROBLEM, ex, null);
933     }
934 
935     private RegionLocations findAllLocationsOrFail(Action<Row> action, boolean useCache) {
936       if (action.getAction() == null) throw new IllegalArgumentException("#" + id +
937           ", row cannot be null");
938       RegionLocations loc = null;
939       try {
940         loc = connection.locateRegion(
941             tableName, action.getAction().getRow(), useCache, true, action.getReplicaId());
942       } catch (IOException ex) {
943         manageLocationError(action, ex);
944       }
945       return loc;
946     }
947 
948     /**
949      * Send a multi action structure to the servers, after a delay depending on the attempt
950      * number. Asynchronous.
951      *
952      * @param actionsByServer the actions structured by regions
953      * @param numAttempt the attempt number.
954      * @param actionsForReplicaThread original actions for replica thread; null on non-first call.
955      */
956     private void sendMultiAction(Map<ServerName, MultiAction<Row>> actionsByServer,
957         int numAttempt, List<Action<Row>> actionsForReplicaThread, boolean reuseThread) {
958       // Run the last item on the same thread if we are already on a send thread.
959       // We hope most of the time it will be the only item, so we can cut down on threads.
960       int actionsRemaining = actionsByServer.size();
961       // This iteration is by server (the HRegionLocation comparator is by server portion only).
962       for (Map.Entry<ServerName, MultiAction<Row>> e : actionsByServer.entrySet()) {
963         ServerName server = e.getKey();
964         MultiAction<Row> multiAction = e.getValue();
965         incTaskCounters(multiAction.getRegions(), server);
966         Collection<? extends Runnable> runnables = getNewMultiActionRunnable(server, multiAction,
967             numAttempt);
968         // make sure we correctly count the number of runnables before we try to reuse the send
969         // thread, in case we had to split the request into different runnables because of backoff
970         if (runnables.size() > actionsRemaining) {
971           actionsRemaining = runnables.size();
972         }
973 
974         // run all the runnables
975         for (Runnable runnable : runnables) {
976           if ((--actionsRemaining == 0) && reuseThread) {
977             runnable.run();
978           } else {
979             try {
980               pool.submit(runnable);
981             } catch (RejectedExecutionException ree) {
982               // This should never happen. But as the pool is provided by the end user, let's secure
983               //  this a little.
984               decTaskCounters(multiAction.getRegions(), server);
985               LOG.warn("#" + id + ", the task was rejected by the pool. This is unexpected." +
986                   " Server is " + server.getServerName(), ree);
987               // We're likely to fail again, but this will increment the attempt counter, so it will
988               //  finish.
989               receiveGlobalFailure(multiAction, server, numAttempt, ree);
990             }
991           }
992         }
993       }
994 
995       if (actionsForReplicaThread != null) {
996         startWaitingForReplicaCalls(actionsForReplicaThread);
997       }
998     }
999 
1000     private Collection<? extends Runnable> getNewMultiActionRunnable(ServerName server,
1001         MultiAction<Row> multiAction,
1002         int numAttempt) {
1003       // no stats to manage, just do the standard action
1004       if (AsyncProcess.this.connection.getStatisticsTracker() == null) {
1005         return Collections.singletonList(Trace.wrap("AsyncProcess.sendMultiAction",
1006             new SingleServerRequestRunnable(multiAction, numAttempt, server, callsInProgress)));
1007       }
1008 
1009       // group the actions by the amount of delay
1010       Map<Long, DelayingRunner> actions = new HashMap<Long, DelayingRunner>(multiAction
1011           .size());
1012 
1013       // split up the actions
1014       for (Map.Entry<byte[], List<Action<Row>>> e : multiAction.actions.entrySet()) {
1015         Long backoff = getBackoff(server, e.getKey());
1016         DelayingRunner runner = actions.get(backoff);
1017         if (runner == null) {
1018           actions.put(backoff, new DelayingRunner(backoff, e));
1019         } else {
1020           runner.add(e);
1021         }
1022       }
1023 
1024       List<Runnable> toReturn = new ArrayList<Runnable>(actions.size());
1025       for (DelayingRunner runner : actions.values()) {
1026         String traceText = "AsyncProcess.sendMultiAction";
1027         Runnable runnable =
1028             new SingleServerRequestRunnable(runner.getActions(), numAttempt, server,
1029                 callsInProgress);
1030         // use a delay runner only if we need to sleep for some time
1031         if (runner.getSleepTime() > 0) {
1032           runner.setRunner(runnable);
1033           traceText = "AsyncProcess.clientBackoff.sendMultiAction";
1034           runnable = runner;
1035         }
1036         runnable = Trace.wrap(traceText, runnable);
1037         toReturn.add(runnable);
1038 
1039       }
1040       return toReturn;
1041     }
1042 
1043     /**
1044      * @param server server location where the target region is hosted
1045      * @param regionName name of the region which we are going to write some data
1046      * @return the amount of time the client should wait until it submit a request to the
1047      * specified server and region
1048      */
1049     private Long getBackoff(ServerName server, byte[] regionName) {
1050       ServerStatisticTracker tracker = AsyncProcess.this.connection.getStatisticsTracker();
1051       ServerStatistics stats = tracker.getStats(server);
1052       return AsyncProcess.this.connection.getBackoffPolicy()
1053           .getBackoffTime(server, regionName, stats);
1054     }
1055 
1056     /**
1057      * Starts waiting to issue replica calls on a different thread; or issues them immediately.
1058      */
1059     private void startWaitingForReplicaCalls(List<Action<Row>> actionsForReplicaThread) {
1060       long startTime = EnvironmentEdgeManager.currentTime();
1061       ReplicaCallIssuingRunnable replicaRunnable = new ReplicaCallIssuingRunnable(
1062           actionsForReplicaThread, startTime);
1063       if (primaryCallTimeoutMicroseconds == 0) {
1064         // Start replica calls immediately.
1065         replicaRunnable.run();
1066       } else {
1067         // Start the thread that may kick off replica gets.
1068         // TODO: we could do it on the same thread, but it's a user thread, might be a bad idea.
1069         try {
1070           pool.submit(replicaRunnable);
1071         } catch (RejectedExecutionException ree) {
1072           LOG.warn("#" + id + ", replica task was rejected by the pool - no replica calls", ree);
1073         }
1074       }
1075     }
1076 
1077     /**
1078      * Check that we can retry acts accordingly: logs, set the error status.
1079      *
1080      * @param originalIndex the position in the list sent
1081      * @param row           the row
1082      * @param canRetry      if false, we won't retry whatever the settings.
1083      * @param throwable     the throwable, if any (can be null)
1084      * @param server        the location, if any (can be null)
1085      * @return true if the action can be retried, false otherwise.
1086      */
1087     public Retry manageError(int originalIndex, Row row, Retry canRetry,
1088                                 Throwable throwable, ServerName server) {
1089       if (canRetry == Retry.YES
1090           && throwable != null && throwable instanceof DoNotRetryIOException) {
1091         canRetry = Retry.NO_NOT_RETRIABLE;
1092       }
1093 
1094       if (canRetry != Retry.YES) {
1095         // Batch.Callback<Res> was not called on failure in 0.94. We keep this.
1096         setError(originalIndex, row, throwable, server);
1097       } else if (isActionComplete(originalIndex, row)) {
1098         canRetry = Retry.NO_OTHER_SUCCEEDED;
1099       }
1100       return canRetry;
1101     }
1102 
1103     /**
1104      * Resubmit all the actions from this multiaction after a failure.
1105      *
1106      * @param rsActions  the actions still to do from the initial list
1107      * @param server   the destination
1108      * @param numAttempt the number of attempts so far
1109      * @param t the throwable (if any) that caused the resubmit
1110      */
1111     private void receiveGlobalFailure(
1112         MultiAction<Row> rsActions, ServerName server, int numAttempt, Throwable t) {
1113       errorsByServer.reportServerError(server);
1114       Retry canRetry = errorsByServer.canRetryMore(numAttempt)
1115           ? Retry.YES : Retry.NO_RETRIES_EXHAUSTED;
1116 
1117       if (tableName == null) {
1118         // tableName is null when we made a cross-table RPC call.
1119         connection.clearCaches(server);
1120       }
1121       int failed = 0, stopped = 0;
1122       List<Action<Row>> toReplay = new ArrayList<Action<Row>>();
1123       for (Map.Entry<byte[], List<Action<Row>>> e : rsActions.actions.entrySet()) {
1124         byte[] regionName = e.getKey();
1125         byte[] row = e.getValue().iterator().next().getAction().getRow();
1126         // Do not use the exception for updating cache because it might be coming from
1127         // any of the regions in the MultiAction.
1128         // TODO: depending on type of exception we might not want to update cache at all?
1129         if (tableName != null) {
1130           connection.updateCachedLocations(tableName, regionName, row, null, server);
1131         }
1132         for (Action<Row> action : e.getValue()) {
1133           Retry retry = manageError(
1134               action.getOriginalIndex(), action.getAction(), canRetry, t, server);
1135           if (retry == Retry.YES) {
1136             toReplay.add(action);
1137           } else if (retry == Retry.NO_OTHER_SUCCEEDED) {
1138             ++stopped;
1139           } else {
1140             ++failed;
1141           }
1142         }
1143       }
1144 
1145       if (toReplay.isEmpty()) {
1146         logNoResubmit(server, numAttempt, rsActions.size(), t, failed, stopped);
1147       } else {
1148         resubmit(server, toReplay, numAttempt, rsActions.size(), t);
1149       }
1150     }
1151 
1152     /**
1153      * Log as much info as possible, and, if there is something to replay,
1154      * submit it again after a back off sleep.
1155      */
1156     private void resubmit(ServerName oldServer, List<Action<Row>> toReplay,
1157         int numAttempt, int failureCount, Throwable throwable) {
1158       // We have something to replay. We're going to sleep a little before.
1159 
1160       // We have two contradicting needs here:
1161       //  1) We want to get the new location after having slept, as it may change.
1162       //  2) We want to take into account the location when calculating the sleep time.
1163       // It should be possible to have some heuristics to take the right decision. Short term,
1164       //  we go for one.
1165       long backOffTime = errorsByServer.calculateBackoffTime(oldServer, pause);
1166       if (numAttempt > startLogErrorsCnt) {
1167         // We use this value to have some logs when we have multiple failures, but not too many
1168         //  logs, as errors are to be expected when a region moves, splits and so on
1169         LOG.info(createLog(numAttempt, failureCount, toReplay.size(),
1170             oldServer, throwable, backOffTime, true, null, -1, -1));
1171       }
1172 
1173       try {
1174         Thread.sleep(backOffTime);
1175       } catch (InterruptedException e) {
1176         LOG.warn("#" + id + ", not sent: " + toReplay.size() + " operations, " + oldServer, e);
1177         Thread.currentThread().interrupt();
1178         return;
1179       }
1180 
1181       groupAndSendMultiAction(toReplay, numAttempt + 1);
1182     }
1183 
1184     private void logNoResubmit(ServerName oldServer, int numAttempt,
1185         int failureCount, Throwable throwable, int failed, int stopped) {
1186       if (failureCount != 0 || numAttempt > startLogErrorsCnt + 1) {
1187         String timeStr = new Date(errorsByServer.getStartTrackingTime()).toString();
1188         String logMessage = createLog(numAttempt, failureCount, 0, oldServer,
1189             throwable, -1, false, timeStr, failed, stopped);
1190         if (failed != 0) {
1191           // Only log final failures as warning
1192           LOG.warn(logMessage);
1193         } else {
1194           LOG.info(logMessage);
1195         }
1196       }
1197     }
1198 
1199     /**
1200      * Called when we receive the result of a server query.
1201      *
1202      * @param multiAction    - the multiAction we sent
1203      * @param server       - the location. It's used as a server name.
1204      * @param responses      - the response, if any
1205      * @param numAttempt     - the attempt
1206      */
1207     private void receiveMultiAction(MultiAction<Row> multiAction,
1208         ServerName server, MultiResponse responses, int numAttempt) {
1209        assert responses != null;
1210 
1211       // Success or partial success
1212       // Analyze detailed results. We can still have individual failures to be redo.
1213       // two specific throwables are managed:
1214       //  - DoNotRetryIOException: we continue to retry for other actions
1215       //  - RegionMovedException: we update the cache with the new region location
1216 
1217       List<Action<Row>> toReplay = new ArrayList<Action<Row>>();
1218       Throwable throwable = null;
1219       int failureCount = 0;
1220       boolean canRetry = true;
1221 
1222       // Go by original action.
1223       int failed = 0, stopped = 0;
1224       for (Map.Entry<byte[], List<Action<Row>>> regionEntry : multiAction.actions.entrySet()) {
1225         byte[] regionName = regionEntry.getKey();
1226         Map<Integer, Object> regionResults = responses.getResults().get(regionName);
1227         if (regionResults == null) {
1228           if (!responses.getExceptions().containsKey(regionName)) {
1229             LOG.error("Server sent us neither results nor exceptions for "
1230                 + Bytes.toStringBinary(regionName));
1231             responses.getExceptions().put(regionName, new RuntimeException("Invalid response"));
1232           }
1233           continue;
1234         }
1235         boolean regionFailureRegistered = false;
1236         for (Action<Row> sentAction : regionEntry.getValue()) {
1237           Object result = regionResults.get(sentAction.getOriginalIndex());
1238           // Failure: retry if it's make sense else update the errors lists
1239           if (result == null || result instanceof Throwable) {
1240             Row row = sentAction.getAction();
1241             // Register corresponding failures once per server/once per region.
1242             if (!regionFailureRegistered) {
1243               regionFailureRegistered = true;
1244               connection.updateCachedLocations(
1245                   tableName, regionName, row.getRow(), result, server);
1246             }
1247             if (failureCount == 0) {
1248               errorsByServer.reportServerError(server);
1249               // We determine canRetry only once for all calls, after reporting server failure.
1250               canRetry = errorsByServer.canRetryMore(numAttempt);
1251             }
1252             ++failureCount;
1253             Retry retry = manageError(sentAction.getOriginalIndex(), row,
1254                 canRetry ? Retry.YES : Retry.NO_RETRIES_EXHAUSTED, (Throwable)result, server);
1255             if (retry == Retry.YES) {
1256               toReplay.add(sentAction);
1257             } else if (retry == Retry.NO_OTHER_SUCCEEDED) {
1258               ++stopped;
1259             } else {
1260               ++failed;
1261             }
1262           } else {
1263             // update the stats about the region, if its a user table. We don't want to slow down
1264             // updates to meta tables, especially from internal updates (master, etc).
1265             if (AsyncProcess.this.connection.getStatisticsTracker() != null) {
1266               result = ResultStatsUtil.updateStats(result,
1267                   AsyncProcess.this.connection.getStatisticsTracker(), server, regionName);
1268             }
1269 
1270             if (callback != null) {
1271               try {
1272                 //noinspection unchecked
1273                 // TODO: would callback expect a replica region name if it gets one?
1274                 this.callback.update(regionName, sentAction.getAction().getRow(), (CResult)result);
1275               } catch (Throwable t) {
1276                 LOG.error("User callback threw an exception for "
1277                     + Bytes.toStringBinary(regionName) + ", ignoring", t);
1278               }
1279             }
1280             setResult(sentAction, result);
1281           }
1282         }
1283       }
1284 
1285       // The failures global to a region. We will use for multiAction we sent previously to find the
1286       //   actions to replay.
1287       for (Map.Entry<byte[], Throwable> throwableEntry : responses.getExceptions().entrySet()) {
1288         throwable = throwableEntry.getValue();
1289         byte[] region = throwableEntry.getKey();
1290         List<Action<Row>> actions = multiAction.actions.get(region);
1291         if (actions == null || actions.isEmpty()) {
1292           throw new IllegalStateException("Wrong response for the region: " +
1293               HRegionInfo.encodeRegionName(region));
1294         }
1295 
1296         if (failureCount == 0) {
1297           errorsByServer.reportServerError(server);
1298           canRetry = errorsByServer.canRetryMore(numAttempt);
1299         }
1300         connection.updateCachedLocations(
1301             tableName, region, actions.get(0).getAction().getRow(), throwable, server);
1302         failureCount += actions.size();
1303 
1304         for (Action<Row> action : actions) {
1305           Row row = action.getAction();
1306           Retry retry = manageError(action.getOriginalIndex(), row,
1307               canRetry ? Retry.YES : Retry.NO_RETRIES_EXHAUSTED, throwable, server);
1308           if (retry == Retry.YES) {
1309             toReplay.add(action);
1310           } else if (retry == Retry.NO_OTHER_SUCCEEDED) {
1311             ++stopped;
1312           } else {
1313             ++failed;
1314           }
1315         }
1316       }
1317 
1318       if (toReplay.isEmpty()) {
1319         logNoResubmit(server, numAttempt, failureCount, throwable, failed, stopped);
1320       } else {
1321         resubmit(server, toReplay, numAttempt, failureCount, throwable);
1322       }
1323     }
1324 
1325     private String createLog(int numAttempt, int failureCount, int replaySize, ServerName sn,
1326         Throwable error, long backOffTime, boolean willRetry, String startTime,
1327         int failed, int stopped) {
1328       StringBuilder sb = new StringBuilder();
1329       sb.append("#").append(id).append(", table=").append(tableName).append(", ")
1330         .append("attempt=").append(numAttempt)
1331         .append("/").append(numTries).append(" ");
1332 
1333       if (failureCount > 0 || error != null){
1334         sb.append("failed=").append(failureCount).append("ops").append(", last exception: ").
1335             append(error == null ? "null" : error);
1336       } else {
1337         sb.append("succeeded");
1338       }
1339 
1340       sb.append(" on ").append(sn).append(", tracking started ").append(startTime);
1341 
1342       if (willRetry) {
1343         sb.append(", retrying after=").append(backOffTime).append("ms").
1344             append(", replay=").append(replaySize).append("ops");
1345       } else if (failureCount > 0) {
1346         if (stopped > 0) {
1347           sb.append("; not retrying ").append(stopped).append(" due to success from other replica");
1348         }
1349         if (failed > 0) {
1350           sb.append("; not retrying ").append(failed).append(" - final failure");
1351         }
1352 
1353       }
1354 
1355       return sb.toString();
1356     }
1357 
1358     /**
1359      * Sets the non-error result from a particular action.
1360      * @param action Action (request) that the server responded to.
1361      * @param result The result.
1362      */
1363     private void setResult(Action<Row> action, Object result) {
1364       if (result == null) {
1365         throw new RuntimeException("Result cannot be null");
1366       }
1367       ReplicaResultState state = null;
1368       boolean isStale = !RegionReplicaUtil.isDefaultReplica(action.getReplicaId());
1369       int index = action.getOriginalIndex();
1370       if (results == null) {
1371          decActionCounter(index);
1372          return; // Simple case, no replica requests.
1373       } else if ((state = trySetResultSimple(
1374           index, action.getAction(), false, result, null, isStale)) == null) {
1375         return; // Simple case, no replica requests.
1376       }
1377       assert state != null;
1378       // At this point we know that state is set to replica tracking class.
1379       // It could be that someone else is also looking at it; however, we know there can
1380       // only be one state object, and only one thread can set callCount to 0. Other threads
1381       // will either see state with callCount 0 after locking it; or will not see state at all
1382       // we will replace it with the result.
1383       synchronized (state) {
1384         if (state.callCount == 0) return; // someone already set the result
1385         state.callCount = 0;
1386       }
1387       synchronized (replicaResultLock) {
1388         if (results[index] != state) {
1389           throw new AssertionError("We set the callCount but someone else replaced the result");
1390         }
1391         results[index] = result;
1392       }
1393 
1394       decActionCounter(index);
1395     }
1396 
1397     /**
1398      * Sets the error from a particular action.
1399      * @param index Original action index.
1400      * @param row Original request.
1401      * @param throwable The resulting error.
1402      * @param server The source server.
1403      */
1404     private void setError(int index, Row row, Throwable throwable, ServerName server) {
1405       ReplicaResultState state = null;
1406       if (results == null) {
1407         // Note that we currently cannot have replica requests with null results. So it shouldn't
1408         // happen that multiple replica calls will call dAC for same actions with results == null.
1409         // Only one call per action should be present in this case.
1410         errors.add(throwable, row, server);
1411         decActionCounter(index);
1412         return; // Simple case, no replica requests.
1413       } else if ((state = trySetResultSimple(
1414           index, row, true, throwable, server, false)) == null) {
1415         return; // Simple case, no replica requests.
1416       }
1417       assert state != null;
1418       BatchErrors target = null; // Error will be added to final errors, or temp replica errors.
1419       boolean isActionDone = false;
1420       synchronized (state) {
1421         switch (state.callCount) {
1422           case 0: return; // someone already set the result
1423           case 1: { // All calls failed, we are the last error.
1424             target = errors;
1425             isActionDone = true;
1426             break;
1427           }
1428           default: {
1429             assert state.callCount > 1;
1430             if (state.replicaErrors == null) {
1431               state.replicaErrors = new BatchErrors();
1432             }
1433             target = state.replicaErrors;
1434             break;
1435           }
1436         }
1437         --state.callCount;
1438       }
1439       target.add(throwable, row, server);
1440       if (isActionDone) {
1441         if (state.replicaErrors != null) { // last call, no need to lock
1442           errors.merge(state.replicaErrors);
1443         }
1444         // See setResult for explanations.
1445         synchronized (replicaResultLock) {
1446           if (results[index] != state) {
1447             throw new AssertionError("We set the callCount but someone else replaced the result");
1448           }
1449           results[index] = throwable;
1450         }
1451         decActionCounter(index);
1452       }
1453     }
1454 
1455     /**
1456      * Checks if the action is complete; used on error to prevent needless retries.
1457      * Does not synchronize, assuming element index/field accesses are atomic.
1458      * This is an opportunistic optimization check, doesn't have to be strict.
1459      * @param index Original action index.
1460      * @param row Original request.
1461      */
1462     private boolean isActionComplete(int index, Row row) {
1463       if (!isReplicaGet(row)) return false;
1464       Object resObj = results[index];
1465       return (resObj != null) && (!(resObj instanceof ReplicaResultState)
1466           || ((ReplicaResultState)resObj).callCount == 0);
1467     }
1468 
1469     /**
1470      * Tries to set the result or error for a particular action as if there were no replica calls.
1471      * @return null if successful; replica state if there were in fact replica calls.
1472      */
1473     private ReplicaResultState trySetResultSimple(int index, Row row, boolean isError,
1474         Object result, ServerName server, boolean isFromReplica) {
1475       Object resObj = null;
1476       if (!isReplicaGet(row)) {
1477         if (isFromReplica) {
1478           throw new AssertionError("Unexpected stale result for " + row);
1479         }
1480         results[index] = result;
1481       } else {
1482         synchronized (replicaResultLock) {
1483           if ((resObj = results[index]) == null) {
1484             if (isFromReplica) {
1485               throw new AssertionError("Unexpected stale result for " + row);
1486             }
1487             results[index] = result;
1488           }
1489         }
1490       }
1491 
1492       ReplicaResultState rrs =
1493           (resObj instanceof ReplicaResultState) ? (ReplicaResultState)resObj : null;
1494       if (rrs == null && isError) {
1495         // The resObj is not replica state (null or already set).
1496         errors.add((Throwable)result, row, server);
1497       }
1498 
1499       if (resObj == null) {
1500         // resObj is null - no replica calls were made.
1501         decActionCounter(index);
1502         return null;
1503       }
1504       return rrs;
1505     }
1506 
1507     private void decActionCounter(int index) {
1508       long actionsRemaining = actionsInProgress.decrementAndGet();
1509       if (actionsRemaining < 0) {
1510         String error = buildDetailedErrorMsg("Incorrect actions in progress", index);
1511         throw new AssertionError(error);
1512       } else if (actionsRemaining == 0) {
1513         synchronized (actionsInProgress) {
1514           actionsInProgress.notifyAll();
1515         }
1516       }
1517     }
1518 
1519     private String buildDetailedErrorMsg(String string, int index) {
1520       String error = string + "; called for " + index +
1521           ", actionsInProgress " + actionsInProgress.get() + "; replica gets: ";
1522       if (replicaGetIndices != null) {
1523         for (int i = 0; i < replicaGetIndices.length; ++i) {
1524           error += replicaGetIndices[i] + ", ";
1525         }
1526       } else {
1527         error += (hasAnyReplicaGets ? "all" : "none");
1528       }
1529       error += "; results ";
1530       if (results != null) {
1531         for (int i = 0; i < results.length; ++i) {
1532           Object o = results[i];
1533           error += ((o == null) ? "null" : o.toString()) + ", ";
1534         }
1535       }
1536       return error;
1537     }
1538 
1539     @Override
1540     public void waitUntilDone() throws InterruptedIOException {
1541       try {
1542         waitUntilDone(Long.MAX_VALUE);
1543       } catch (InterruptedException iex) {
1544         throw new InterruptedIOException(iex.getMessage());
1545       } finally {
1546         if (callsInProgress != null) {
1547           for (MultiServerCallable<Row> clb : callsInProgress) {
1548             clb.cancel();
1549           }
1550         }
1551       }
1552     }
1553 
1554     private boolean waitUntilDone(long cutoff) throws InterruptedException {
1555       boolean hasWait = cutoff != Long.MAX_VALUE;
1556       long lastLog = EnvironmentEdgeManager.currentTime();
1557       long currentInProgress;
1558       while (0 != (currentInProgress = actionsInProgress.get())) {
1559         long now = EnvironmentEdgeManager.currentTime();
1560         if (hasWait && (now * 1000L) > cutoff) {
1561           return false;
1562         }
1563         if (!hasWait) { // Only log if wait is infinite.
1564           if (now > lastLog + 10000) {
1565             lastLog = now;
1566             LOG.info("#" + id + ", waiting for " + currentInProgress + "  actions to finish");
1567           }
1568         }
1569         synchronized (actionsInProgress) {
1570           if (actionsInProgress.get() == 0) break;
1571           if (!hasWait) {
1572             actionsInProgress.wait(100);
1573           } else {
1574             long waitMicroSecond = Math.min(100000L, (cutoff - now * 1000L));
1575             TimeUnit.MICROSECONDS.timedWait(actionsInProgress, waitMicroSecond);
1576           }
1577         }
1578       }
1579       return true;
1580     }
1581 
1582     @Override
1583     public boolean hasError() {
1584       return errors.hasErrors();
1585     }
1586 
1587     @Override
1588     public List<? extends Row> getFailedOperations() {
1589       return errors.actions;
1590     }
1591 
1592     @Override
1593     public RetriesExhaustedWithDetailsException getErrors() {
1594       return errors.makeException();
1595     }
1596 
1597     @Override
1598     public Object[] getResults() throws InterruptedIOException {
1599       waitUntilDone();
1600       return results;
1601     }
1602   }
1603 
1604   @VisibleForTesting
1605   /** Create AsyncRequestFuture. Isolated to be easily overridden in the tests. */
1606   protected <CResult> AsyncRequestFutureImpl<CResult> createAsyncRequestFuture(
1607       TableName tableName, List<Action<Row>> actions, long nonceGroup, ExecutorService pool,
1608       Batch.Callback<CResult> callback, Object[] results, boolean needResults) {
1609     return new AsyncRequestFutureImpl<CResult>(
1610         tableName, actions, nonceGroup, getPool(pool), needResults, results, callback);
1611   }
1612 
1613   /**
1614    * Create a callable. Isolated to be easily overridden in the tests.
1615    */
1616   @VisibleForTesting
1617   protected MultiServerCallable<Row> createCallable(final ServerName server,
1618       TableName tableName, final MultiAction<Row> multi) {
1619     return new MultiServerCallable<Row>(connection, tableName, server, this.rpcFactory, multi);
1620   }
1621 
1622   /**
1623    * Create a caller. Isolated to be easily overridden in the tests.
1624    */
1625   @VisibleForTesting
1626   protected RpcRetryingCaller<MultiResponse> createCaller(MultiServerCallable<Row> callable) {
1627     return rpcCallerFactory.<MultiResponse> newCaller();
1628   }
1629 
1630   @VisibleForTesting
1631   /** Waits until all outstanding tasks are done. Used in tests. */
1632   void waitUntilDone() throws InterruptedIOException {
1633     waitForMaximumCurrentTasks(0);
1634   }
1635 
1636   /** Wait until the async does not have more than max tasks in progress. */
1637   private void waitForMaximumCurrentTasks(int max) throws InterruptedIOException {
1638     long lastLog = EnvironmentEdgeManager.currentTime();
1639     long currentInProgress, oldInProgress = Long.MAX_VALUE;
1640     while ((currentInProgress = this.tasksInProgress.get()) > max) {
1641       if (oldInProgress != currentInProgress) { // Wait for in progress to change.
1642         long now = EnvironmentEdgeManager.currentTime();
1643         if (now > lastLog + 10000) {
1644           lastLog = now;
1645           LOG.info("#" + id + ", waiting for some tasks to finish. Expected max="
1646               + max + ", tasksInProgress=" + currentInProgress);
1647         }
1648       }
1649       oldInProgress = currentInProgress;
1650       try {
1651         synchronized (this.tasksInProgress) {
1652           if (tasksInProgress.get() != oldInProgress) break;
1653           this.tasksInProgress.wait(100);
1654         }
1655       } catch (InterruptedException e) {
1656         throw new InterruptedIOException("#" + id + ", interrupted." +
1657             " currentNumberOfTask=" + currentInProgress);
1658       }
1659     }
1660   }
1661 
1662   /**
1663    * Only used w/useGlobalErrors ctor argument, for HTable backward compat.
1664    * @return Whether there were any errors in any request since the last time
1665    *          {@link #waitForAllPreviousOpsAndReset(List)} was called, or AP was created.
1666    */
1667   public boolean hasError() {
1668     return globalErrors.hasErrors();
1669   }
1670 
1671   /**
1672    * Only used w/useGlobalErrors ctor argument, for HTable backward compat.
1673    * Waits for all previous operations to finish, and returns errors and (optionally)
1674    * failed operations themselves.
1675    * @param failedRows an optional list into which the rows that failed since the last time
1676    *        {@link #waitForAllPreviousOpsAndReset(List)} was called, or AP was created, are saved.
1677    * @return all the errors since the last time {@link #waitForAllPreviousOpsAndReset(List)}
1678    *          was called, or AP was created.
1679    */
1680   public RetriesExhaustedWithDetailsException waitForAllPreviousOpsAndReset(
1681       List<Row> failedRows) throws InterruptedIOException {
1682     waitForMaximumCurrentTasks(0);
1683     if (!globalErrors.hasErrors()) {
1684       return null;
1685     }
1686     if (failedRows != null) {
1687       failedRows.addAll(globalErrors.actions);
1688     }
1689     RetriesExhaustedWithDetailsException result = globalErrors.makeException();
1690     globalErrors.clear();
1691     return result;
1692   }
1693 
1694   /**
1695    * increment the tasks counters for a given set of regions. MT safe.
1696    */
1697   protected void incTaskCounters(Collection<byte[]> regions, ServerName sn) {
1698     tasksInProgress.incrementAndGet();
1699 
1700     AtomicInteger serverCnt = taskCounterPerServer.get(sn);
1701     if (serverCnt == null) {
1702       taskCounterPerServer.putIfAbsent(sn, new AtomicInteger());
1703       serverCnt = taskCounterPerServer.get(sn);
1704     }
1705     serverCnt.incrementAndGet();
1706 
1707     for (byte[] regBytes : regions) {
1708       AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes);
1709       if (regionCnt == null) {
1710         regionCnt = new AtomicInteger();
1711         AtomicInteger oldCnt = taskCounterPerRegion.putIfAbsent(regBytes, regionCnt);
1712         if (oldCnt != null) {
1713           regionCnt = oldCnt;
1714         }
1715       }
1716       regionCnt.incrementAndGet();
1717     }
1718   }
1719 
1720   /**
1721    * Decrements the counters for a given region and the region server. MT Safe.
1722    */
1723   protected void decTaskCounters(Collection<byte[]> regions, ServerName sn) {
1724     for (byte[] regBytes : regions) {
1725       AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes);
1726       regionCnt.decrementAndGet();
1727     }
1728 
1729     taskCounterPerServer.get(sn).decrementAndGet();
1730     tasksInProgress.decrementAndGet();
1731     synchronized (tasksInProgress) {
1732       tasksInProgress.notifyAll();
1733     }
1734   }
1735 
1736   /**
1737    * Creates the server error tracker to use inside process.
1738    * Currently, to preserve the main assumption about current retries, and to work well with
1739    * the retry-limit-based calculation, the calculation is local per Process object.
1740    * We may benefit from connection-wide tracking of server errors.
1741    * @return ServerErrorTracker to use, null if there is no ServerErrorTracker on this connection
1742    */
1743   protected ConnectionManager.ServerErrorTracker createServerErrorTracker() {
1744     return new ConnectionManager.ServerErrorTracker(
1745         this.serverTrackerTimeout, this.numTries);
1746   }
1747 
1748   private static boolean isReplicaGet(Row row) {
1749     return (row instanceof Get) && (((Get)row).getConsistency() == Consistency.TIMELINE);
1750   }
1751 
1752   /**
1753    * For manageError. Only used to make logging more clear, we don't actually care why we don't retry.
1754    */
1755   private enum Retry {
1756     YES,
1757     NO_LOCATION_PROBLEM,
1758     NO_NOT_RETRIABLE,
1759     NO_RETRIES_EXHAUSTED,
1760     NO_OTHER_SUCCEEDED
1761   }
1762 }