1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
116
117
118
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
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
137
138 public static final String HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE = "hbase.client.max.perrequest.heapsize";
139
140
141
142
143 public static final long DEFAULT_HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE = 4194304;
144
145
146
147
148 public static final String HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE = "hbase.client.max.submit.heapsize";
149
150
151
152 public static final long DEFAULT_HBASE_CLIENT_MAX_SUBMIT_HEAPSIZE = DEFAULT_HBASE_CLIENT_MAX_PERREQUEST_HEAPSIZE;
153
154
155
156
157
158
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
166 public void waitUntilDone() throws InterruptedIOException;
167 }
168
169
170
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
202
203
204
205 private static class ReplicaResultState {
206 public ReplicaResultState(int callCount) {
207 this.callCount = callCount;
208 }
209
210
211 int callCount;
212
213
214 BatchErrors replicaErrors = null;
215
216 @Override
217 public String toString() {
218 return "[call count " + callCount + "; errors " + replicaErrors + "]";
219 }
220 }
221
222
223
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
238 private final int startLogErrorsCnt;
239
240
241
242
243 protected final int maxTotalConcurrentTasks;
244
245
246
247
248 protected final long maxHeapSizePerRequest;
249 protected final long maxHeapSizeSubmit;
250
251
252
253
254
255
256 protected final int maxConcurrentTasksPerRegion;
257
258
259
260
261 protected final int maxConcurrentTasksPerServer;
262 protected final long pause;
263 protected final long pauseForCQTBE;
264 protected int numTries;
265 protected int serverTrackerTimeout;
266 protected int rpcTimeout;
267 protected int operationTimeout;
268 protected long primaryCallTimeoutMicroseconds;
269
270 private final boolean logBatchErrorDetails;
271
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
330 : new ConnectionConfiguration(conf);
331 if (connConf == null) {
332
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
344
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
402
403
404
405
406
407
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
437
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
452
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
461
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
470
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
481
482
483
484
485
486
487
488
489
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();
504
505
506 List<Exception> locationErrors = null;
507 List<Integer> locationErrorRows = null;
508 RowCheckerHost checker = createRowCheckerHost();
509 boolean firstIter = true;
510 do {
511
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
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
538
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;
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
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
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
612
613
614
615
616
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
633
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
646
647
648
649
650
651
652
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
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());
686 }
687
688
689
690
691
692
693
694
695
696
697 protected class AsyncRequestFutureImpl<CResult> implements AsyncRequestFuture {
698
699
700
701
702
703
704
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;
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
748 if (!actionsByServer.isEmpty()) {
749 sendMultiAction(actionsByServer, 1, null, true);
750 }
751 }
752 }
753
754
755
756
757
758
759 private void addReplicaActions(int index, Map<ServerName, MultiAction<Row>> actionsByServer,
760 List<Action<Row>> unknownReplicaActions) {
761 if (results[index] != null) return;
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
772
773
774 if (results[index] != null) return;
775
776
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
804
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
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
839 return;
840 }
841 } catch (IOException e) {
842
843
844 receiveGlobalFailure(multiAction, server, numAttempt, e);
845 return;
846 } catch (Throwable t) {
847
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
855 receiveMultiAction(multiAction, server, res, numAttempt);
856 } catch (Throwable t) {
857
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
881
882
883
884 private final Object replicaResultLock = new Object();
885
886
887
888
889
890
891
892
893
894 private final Object[] results;
895
896
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
931
932
933
934
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) {
942 if (replicaGetIndices == null) {
943 replicaGetIndices = new ArrayList<Integer>(actions.size() - 1);
944 }
945 replicaGetIndices.add(posInList);
946 }
947 } else if (!hasAnyNonReplicaReqs) {
948
949 hasAnyNonReplicaReqs = true;
950 if (posInList > 0) {
951
952
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
999
1000
1001
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
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
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
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
1060
1061 int replicaId = action.getReplicaId();
1062 RegionLocations locs = findAllLocationsOrFail(action, true);
1063 if (locs == null) return null;
1064 HRegionLocation loc = locs.getRegionLocation(replicaId);
1065 if (loc == null || loc.getServerName() == null) {
1066 locs = findAllLocationsOrFail(action, false);
1067 if (locs == null) return null;
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
1103
1104
1105
1106
1107
1108
1109 private void sendMultiAction(Map<ServerName, MultiAction<Row>> actionsByServer,
1110 int numAttempt, List<Action<Row>> actionsForReplicaThread, boolean reuseThread) {
1111
1112
1113 int actionsRemaining = actionsByServer.size();
1114
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
1121
1122 if (runnables.size() > actionsRemaining) {
1123 actionsRemaining = runnables.size();
1124 }
1125
1126
1127
1128
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
1139
1140 LOG.warn("#" + id + ", the task was rejected by the pool. This is unexpected." +
1141 " Server is " + server.getServerName(), t);
1142 } else {
1143
1144 LOG.warn("Caught unexpected exception/error: ", t);
1145 }
1146 decTaskCounters(multiAction.getRegions(), server);
1147
1148
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
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
1174 Map<Long, DelayingRunner> actions = new HashMap<Long, DelayingRunner>(multiAction
1175 .size());
1176
1177
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
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
1216
1217
1218
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
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
1236 replicaRunnable.run();
1237 } else {
1238
1239
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
1250
1251
1252
1253
1254
1255
1256
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
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
1277
1278
1279
1280
1281
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
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
1299
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
1307
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
1332
1333
1334 private void resubmit(ServerName oldServer, List<Action<Row>> toReplay,
1335 int numAttempt, int failureCount, Throwable throwable) {
1336
1337
1338
1339
1340
1341
1342
1343
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
1351 backOffTime = errorsByServer.calculateBackoffTime(oldServer, pauseForCQTBE);
1352 } else {
1353 backOffTime = errorsByServer.calculateBackoffTime(oldServer, pause);
1354 }
1355 if (numAttempt > startLogErrorsCnt) {
1356
1357
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
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
1396
1397
1398
1399
1400
1401
1402 private void receiveMultiAction(MultiAction<Row> multiAction,
1403 ServerName server, MultiResponse responses, int numAttempt) {
1404 assert responses != null;
1405
1406
1407
1408
1409
1410
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
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
1429
1430
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
1449
1450 result = regionException;
1451 }
1452
1453 if (result instanceof Throwable) {
1454 Row row = sentAction.getAction();
1455 throwable = regionException != null ? regionException
1456 : ClientExceptionsUtil.findException(result);
1457
1458 if (!regionFailureRegistered) {
1459 regionFailureRegistered = true;
1460 try {
1461 connection.updateCachedLocations(
1462 tableName, regionName, row.getRow(), result, server);
1463 } catch (Throwable ex) {
1464
1465
1466 LOG.error("Couldn't update cached region locations: " + ex);
1467 }
1468 }
1469 if (retry == null) {
1470 errorsByServer.reportServerError(server);
1471
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
1492
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
1545
1546
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;
1558 } else if ((state = trySetResultSimple(
1559 index, action.getAction(), false, result, null, isStale)) == null) {
1560 return;
1561 }
1562 assert state != null;
1563
1564
1565
1566
1567
1568 synchronized (state) {
1569 if (state.callCount == 0) {
1570 return;
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
1586
1587
1588
1589
1590
1591 private void setError(int index, Row row, Throwable throwable, ServerName server) {
1592 ReplicaResultState state = null;
1593 if (results == null) {
1594
1595
1596
1597 errors.add(throwable, row, server);
1598 decActionCounter(index);
1599 return;
1600 } else if ((state = trySetResultSimple(
1601 index, row, true, throwable, server, false)) == null) {
1602 return;
1603 }
1604 assert state != null;
1605 BatchErrors target = null;
1606 boolean isActionDone = false;
1607 synchronized (state) {
1608 switch (state.callCount) {
1609 case 0: return;
1610 case 1: {
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) {
1629 errors.merge(state.replicaErrors);
1630 }
1631
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
1644
1645
1646
1647
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
1658
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
1683 errors.add((Throwable)result, row, server);
1684 }
1685
1686 if (resObj == null) {
1687
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) {
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
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
1838
1839 @VisibleForTesting
1840 protected RpcRetryingCaller<MultiResponse> createCaller(PayloadCarryingServerCallable callable,
1841 int rpcTimeout) {
1842 return rpcCallerFactory.<MultiResponse> newCaller(rpcTimeout);
1843 }
1844
1845 @VisibleForTesting
1846
1847 void waitUntilDone() throws InterruptedIOException {
1848 waitForMaximumCurrentTasks(0, null);
1849 }
1850
1851
1852 private void waitForMaximumCurrentTasks(int max, String tableName)
1853 throws InterruptedIOException {
1854 waitForMaximumCurrentTasks(max, tasksInProgress, id, tableName);
1855 }
1856
1857
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) {
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
1911
1912
1913
1914 public boolean hasError() {
1915 return globalErrors.hasErrors();
1916 }
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
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
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
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
1986
1987
1988
1989
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
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
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
2066
2067 @VisibleForTesting
2068 interface RowChecker {
2069 enum ReturnCode {
2070
2071
2072
2073 INCLUDE,
2074
2075
2076
2077 SKIP,
2078
2079
2080
2081 END
2082 };
2083 ReturnCode canTakeOperation(HRegionLocation loc, long rowSize);
2084
2085
2086
2087
2088
2089 void notifyFinal(ReturnCode code, HRegionLocation loc, long rowSize);
2090
2091
2092
2093 void reset() throws InterruptedIOException ;
2094 }
2095
2096
2097
2098
2099
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
2130
2131 @VisibleForTesting
2132 static class TaskCountChecker implements RowChecker {
2133 private static final long MAX_WAITING_TIME = 1000;
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
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
2189
2190
2191
2192
2193
2194
2195
2196 @Override
2197 public ReturnCode canTakeOperation(HRegionLocation loc, long rowSize) {
2198
2199 HRegionInfo regionInfo = loc.getRegionInfo();
2200 if (regionsIncluded.contains(regionInfo)) {
2201
2202 return ReturnCode.INCLUDE;
2203 }
2204 AtomicInteger regionCnt = taskCounterPerRegion.get(loc.getRegionInfo().getRegionName());
2205 if (regionCnt != null && regionCnt.get() >= maxConcurrentTasksPerRegion) {
2206
2207 return ReturnCode.SKIP;
2208 }
2209 int newServers = serversIncluded.size()
2210 + (serversIncluded.contains(loc.getServerName()) ? 0 : 1);
2211 if ((newServers + tasksInProgress.get()) > maxTotalConcurrentTasks) {
2212
2213 return ReturnCode.SKIP;
2214 }
2215 AtomicInteger serverCnt = taskCounterPerServer.get(loc.getServerName());
2216 if (serverCnt != null && serverCnt.get() >= maxConcurrentTasksPerServer) {
2217
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
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
2250 long currentRequestSize = serverRequestSizes.containsKey(loc.getServerName()) ?
2251 serverRequestSizes.get(loc.getServerName()) : 0L;
2252
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 }