1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.client;
20
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.protobuf.Descriptors;
23 import com.google.protobuf.Message;
24 import com.google.protobuf.Service;
25 import com.google.protobuf.ServiceException;
26
27 import java.io.IOException;
28 import java.io.InterruptedIOException;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.NavigableMap;
34 import java.util.TreeMap;
35 import java.util.concurrent.Callable;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Future;
39 import java.util.concurrent.SynchronousQueue;
40 import java.util.concurrent.ThreadPoolExecutor;
41 import java.util.concurrent.TimeUnit;
42
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45 import org.apache.hadoop.conf.Configuration;
46 import org.apache.hadoop.hbase.Cell;
47 import org.apache.hadoop.hbase.DoNotRetryIOException;
48 import org.apache.hadoop.hbase.HBaseConfiguration;
49 import org.apache.hadoop.hbase.HConstants;
50 import org.apache.hadoop.hbase.HRegionInfo;
51 import org.apache.hadoop.hbase.HRegionLocation;
52 import org.apache.hadoop.hbase.HTableDescriptor;
53 import org.apache.hadoop.hbase.KeyValueUtil;
54 import org.apache.hadoop.hbase.ServerName;
55 import org.apache.hadoop.hbase.TableName;
56 import org.apache.hadoop.hbase.classification.InterfaceAudience;
57 import org.apache.hadoop.hbase.classification.InterfaceStability;
58 import org.apache.hadoop.hbase.client.AsyncProcess.AsyncRequestFuture;
59 import org.apache.hadoop.hbase.client.coprocessor.Batch;
60 import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback;
61 import org.apache.hadoop.hbase.filter.BinaryComparator;
62 import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
63 import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
64 import org.apache.hadoop.hbase.ipc.HBaseRpcController;
65 import org.apache.hadoop.hbase.ipc.RegionCoprocessorRpcChannel;
66 import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
67 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
68 import org.apache.hadoop.hbase.protobuf.RequestConverter;
69 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
70 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
71 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiRequest;
72 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateRequest;
73 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateResponse;
74 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionAction;
75 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.CompareType;
76 import org.apache.hadoop.hbase.util.Bytes;
77 import org.apache.hadoop.hbase.util.Pair;
78 import org.apache.hadoop.hbase.util.ReflectionUtils;
79 import org.apache.hadoop.hbase.util.Threads;
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
106
107
108
109
110
111
112
113 @InterfaceAudience.Private
114 @InterfaceStability.Stable
115 public class HTable implements HTableInterface, RegionLocator {
116 private static final Log LOG = LogFactory.getLog(HTable.class);
117 protected ClusterConnection connection;
118 private final TableName tableName;
119 private volatile Configuration configuration;
120 private ConnectionConfiguration connConfiguration;
121 protected BufferedMutatorImpl mutator;
122 private boolean autoFlush = true;
123 private boolean closed = false;
124 protected int scannerCaching;
125 protected long scannerMaxResultSize;
126 private ExecutorService pool;
127 private int operationTimeout;
128 private int readRpcTimeout;
129 private int writeRpcTimeout;
130 private final boolean cleanupPoolOnClose;
131 private final boolean cleanupConnectionOnClose;
132 private Consistency defaultConsistency = Consistency.STRONG;
133 private HRegionLocator locator;
134
135
136 protected AsyncProcess multiAp;
137 private RpcRetryingCallerFactory rpcCallerFactory;
138 private RpcControllerFactory rpcControllerFactory;
139
140
141
142
143
144
145
146
147
148 @Deprecated
149 public HTable(Configuration conf, final String tableName)
150 throws IOException {
151 this(conf, TableName.valueOf(tableName));
152 }
153
154
155
156
157
158
159
160
161
162 @Deprecated
163 public HTable(Configuration conf, final byte[] tableName)
164 throws IOException {
165 this(conf, TableName.valueOf(tableName));
166 }
167
168
169
170
171
172
173
174
175
176 @Deprecated
177 public HTable(Configuration conf, final TableName tableName)
178 throws IOException {
179 this.tableName = tableName;
180 this.cleanupPoolOnClose = this.cleanupConnectionOnClose = true;
181 if (conf == null) {
182 this.connection = null;
183 return;
184 }
185 this.connection = ConnectionManager.getConnectionInternal(conf);
186 this.configuration = conf;
187
188 this.pool = getDefaultExecutor(conf);
189 this.finishSetup();
190 }
191
192
193
194
195
196
197
198
199 @Deprecated
200 public HTable(TableName tableName, Connection connection) throws IOException {
201 this.tableName = tableName;
202 this.cleanupPoolOnClose = true;
203 this.cleanupConnectionOnClose = false;
204 this.connection = (ClusterConnection)connection;
205 this.configuration = connection.getConfiguration();
206
207 this.pool = getDefaultExecutor(this.configuration);
208 this.finishSetup();
209 }
210
211
212 @InterfaceAudience.Private
213 public static ThreadPoolExecutor getDefaultExecutor(Configuration conf) {
214 int maxThreads = conf.getInt("hbase.htable.threads.max", Integer.MAX_VALUE);
215 if (maxThreads == 0) {
216 maxThreads = 1;
217 }
218 long keepAliveTime = conf.getLong("hbase.htable.threads.keepalivetime", 60);
219
220
221
222
223
224 ThreadPoolExecutor pool = new ThreadPoolExecutor(1, maxThreads, keepAliveTime, TimeUnit.SECONDS,
225 new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("htable"));
226 pool.allowCoreThreadTimeOut(true);
227 return pool;
228 }
229
230
231
232
233
234
235
236
237
238
239 @Deprecated
240 public HTable(Configuration conf, final byte[] tableName, final ExecutorService pool)
241 throws IOException {
242 this(conf, TableName.valueOf(tableName), pool);
243 }
244
245
246
247
248
249
250
251
252
253
254 @Deprecated
255 public HTable(Configuration conf, final TableName tableName, final ExecutorService pool)
256 throws IOException {
257 this.connection = ConnectionManager.getConnectionInternal(conf);
258 this.configuration = conf;
259 this.pool = pool;
260 if (pool == null) {
261 this.pool = getDefaultExecutor(conf);
262 this.cleanupPoolOnClose = true;
263 } else {
264 this.cleanupPoolOnClose = false;
265 }
266 this.tableName = tableName;
267 this.cleanupConnectionOnClose = true;
268 this.finishSetup();
269 }
270
271
272
273
274
275
276
277
278
279 @Deprecated
280 public HTable(final byte[] tableName, final Connection connection,
281 final ExecutorService pool) throws IOException {
282 this(TableName.valueOf(tableName), connection, pool);
283 }
284
285
286 @Deprecated
287 public HTable(TableName tableName, final Connection connection,
288 final ExecutorService pool) throws IOException {
289 this(tableName, (ClusterConnection)connection, null, null, null, pool);
290 }
291
292
293
294
295
296
297
298
299
300
301 @InterfaceAudience.Private
302 public HTable(TableName tableName, final ClusterConnection connection,
303 final ConnectionConfiguration tableConfig,
304 final RpcRetryingCallerFactory rpcCallerFactory,
305 final RpcControllerFactory rpcControllerFactory,
306 final ExecutorService pool) throws IOException {
307 if (connection == null || connection.isClosed()) {
308 throw new IllegalArgumentException("Connection is null or closed.");
309 }
310 if (tableName == null) {
311 throw new IllegalArgumentException("Given table name is null");
312 }
313 this.tableName = tableName;
314 this.cleanupConnectionOnClose = false;
315 this.connection = connection;
316 this.configuration = connection.getConfiguration();
317 this.connConfiguration = tableConfig;
318 this.pool = pool;
319 if (pool == null) {
320 this.pool = getDefaultExecutor(this.configuration);
321 this.cleanupPoolOnClose = true;
322 } else {
323 this.cleanupPoolOnClose = false;
324 }
325
326 this.rpcCallerFactory = rpcCallerFactory;
327 this.rpcControllerFactory = rpcControllerFactory;
328
329 this.finishSetup();
330 }
331
332
333
334
335
336 @VisibleForTesting
337 protected HTable(ClusterConnection conn, BufferedMutatorParams params) throws IOException {
338 connection = conn;
339 tableName = params.getTableName();
340 connConfiguration = new ConnectionConfiguration(connection.getConfiguration());
341 cleanupPoolOnClose = false;
342 cleanupConnectionOnClose = false;
343
344 this.mutator = new BufferedMutatorImpl(conn, null, null, params);
345 this.readRpcTimeout = conn.getConfiguration().getInt(HConstants.HBASE_RPC_READ_TIMEOUT_KEY,
346 conn.getConfiguration().getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
347 HConstants.DEFAULT_HBASE_RPC_TIMEOUT));
348 this.writeRpcTimeout = conn.getConfiguration().getInt(HConstants.HBASE_RPC_WRITE_TIMEOUT_KEY,
349 conn.getConfiguration().getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
350 HConstants.DEFAULT_HBASE_RPC_TIMEOUT));
351 }
352
353
354
355
356 public static int getMaxKeyValueSize(Configuration conf) {
357 return conf.getInt("hbase.client.keyvalue.maxsize", -1);
358 }
359
360
361
362
363 private void finishSetup() throws IOException {
364 if (connConfiguration == null) {
365 connConfiguration = new ConnectionConfiguration(configuration);
366 }
367 this.operationTimeout = tableName.isSystemTable() ?
368 connConfiguration.getMetaOperationTimeout() : connConfiguration.getOperationTimeout();
369 this.readRpcTimeout = connConfiguration.getReadRpcTimeout();
370 this.writeRpcTimeout = connConfiguration.getWriteRpcTimeout();
371 this.scannerCaching = connConfiguration.getScannerCaching();
372 this.scannerMaxResultSize = connConfiguration.getScannerMaxResultSize();
373 if (this.rpcCallerFactory == null) {
374 this.rpcCallerFactory = connection.getNewRpcRetryingCallerFactory(configuration);
375 }
376 if (this.rpcControllerFactory == null) {
377 this.rpcControllerFactory = RpcControllerFactory.instantiate(configuration);
378 }
379
380
381 multiAp = this.connection.getAsyncProcess();
382
383 this.closed = false;
384
385 this.locator = new HRegionLocator(tableName, connection);
386 }
387
388
389
390
391 @Override
392 public Configuration getConfiguration() {
393 return configuration;
394 }
395
396
397
398
399
400
401
402
403
404
405 @Deprecated
406 public static boolean isTableEnabled(String tableName) throws IOException {
407 return isTableEnabled(TableName.valueOf(tableName));
408 }
409
410
411
412
413
414
415
416
417
418
419 @Deprecated
420 public static boolean isTableEnabled(byte[] tableName) throws IOException {
421 return isTableEnabled(TableName.valueOf(tableName));
422 }
423
424
425
426
427
428
429
430
431
432
433 @Deprecated
434 public static boolean isTableEnabled(TableName tableName) throws IOException {
435 return isTableEnabled(HBaseConfiguration.create(), tableName);
436 }
437
438
439
440
441
442
443
444
445
446 @Deprecated
447 public static boolean isTableEnabled(Configuration conf, String tableName)
448 throws IOException {
449 return isTableEnabled(conf, TableName.valueOf(tableName));
450 }
451
452
453
454
455
456
457
458
459
460 @Deprecated
461 public static boolean isTableEnabled(Configuration conf, byte[] tableName)
462 throws IOException {
463 return isTableEnabled(conf, TableName.valueOf(tableName));
464 }
465
466
467
468
469
470
471
472
473
474 @Deprecated
475 public static boolean isTableEnabled(Configuration conf,
476 final TableName tableName) throws IOException {
477 return HConnectionManager.execute(new HConnectable<Boolean>(conf) {
478 @Override
479 public Boolean connect(HConnection connection) throws IOException {
480 return connection.isTableEnabled(tableName);
481 }
482 });
483 }
484
485
486
487
488
489
490
491
492 @Deprecated
493 public HRegionLocation getRegionLocation(final String row)
494 throws IOException {
495 return getRegionLocation(Bytes.toBytes(row), false);
496 }
497
498
499
500
501 @Override
502 @Deprecated
503 public HRegionLocation getRegionLocation(final byte [] row)
504 throws IOException {
505 return locator.getRegionLocation(row);
506 }
507
508
509
510
511 @Override
512 @Deprecated
513 public HRegionLocation getRegionLocation(final byte [] row, boolean reload)
514 throws IOException {
515 return locator.getRegionLocation(row, reload);
516 }
517
518
519
520
521 @Override
522 public byte [] getTableName() {
523 return this.tableName.getName();
524 }
525
526 @Override
527 public TableName getName() {
528 return tableName;
529 }
530
531
532
533
534
535
536
537
538 @Deprecated
539 @VisibleForTesting
540 public HConnection getConnection() {
541 return this.connection;
542 }
543
544
545
546
547
548
549
550 @Deprecated
551 public int getScannerCaching() {
552 return scannerCaching;
553 }
554
555
556
557
558
559 @Deprecated
560 public List<Row> getWriteBuffer() {
561 return mutator == null ? null : mutator.getWriteBuffer();
562 }
563
564
565
566
567
568
569
570
571
572
573
574
575 @Deprecated
576 public void setScannerCaching(int scannerCaching) {
577 this.scannerCaching = scannerCaching;
578 }
579
580
581
582
583 @Override
584 public HTableDescriptor getTableDescriptor() throws IOException {
585 HTableDescriptor htd = HBaseAdmin.getTableDescriptor(tableName, connection, rpcCallerFactory,
586 rpcControllerFactory, operationTimeout, readRpcTimeout);
587 if (htd != null) {
588 return new UnmodifyableHTableDescriptor(htd);
589 }
590 return null;
591 }
592
593
594
595
596
597 @Override
598 @Deprecated
599 public byte [][] getStartKeys() throws IOException {
600 return locator.getStartKeys();
601 }
602
603
604
605
606
607 @Override
608 @Deprecated
609 public byte[][] getEndKeys() throws IOException {
610 return locator.getEndKeys();
611 }
612
613
614
615
616
617 @Override
618 @Deprecated
619 public Pair<byte[][],byte[][]> getStartEndKeys() throws IOException {
620 return locator.getStartEndKeys();
621 }
622
623
624
625
626
627
628
629
630
631 @Deprecated
632 public NavigableMap<HRegionInfo, ServerName> getRegionLocations() throws IOException {
633
634 return MetaScanner.allTableRegions(this.connection, getName());
635 }
636
637
638
639
640
641
642
643
644
645
646 @Override
647 @Deprecated
648 public List<HRegionLocation> getAllRegionLocations() throws IOException {
649 return locator.getAllRegionLocations();
650 }
651
652
653
654
655
656
657
658
659
660
661
662 @Deprecated
663 public List<HRegionLocation> getRegionsInRange(final byte [] startKey,
664 final byte [] endKey) throws IOException {
665 return getRegionsInRange(startKey, endKey, false);
666 }
667
668
669
670
671
672
673
674
675
676
677
678
679 @Deprecated
680 public List<HRegionLocation> getRegionsInRange(final byte [] startKey,
681 final byte [] endKey, final boolean reload) throws IOException {
682 return getKeysAndRegionsInRange(startKey, endKey, false, reload).getSecond();
683 }
684
685
686
687
688
689
690
691
692
693
694
695
696
697 @Deprecated
698 private Pair<List<byte[]>, List<HRegionLocation>> getKeysAndRegionsInRange(
699 final byte[] startKey, final byte[] endKey, final boolean includeEndKey)
700 throws IOException {
701 return getKeysAndRegionsInRange(startKey, endKey, includeEndKey, false);
702 }
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717 @Deprecated
718 private Pair<List<byte[]>, List<HRegionLocation>> getKeysAndRegionsInRange(
719 final byte[] startKey, final byte[] endKey, final boolean includeEndKey,
720 final boolean reload) throws IOException {
721 final boolean endKeyIsEndOfTable = Bytes.equals(endKey,HConstants.EMPTY_END_ROW);
722 if ((Bytes.compareTo(startKey, endKey) > 0) && !endKeyIsEndOfTable) {
723 throw new IllegalArgumentException(
724 "Invalid range: " + Bytes.toStringBinary(startKey) +
725 " > " + Bytes.toStringBinary(endKey));
726 }
727 List<byte[]> keysInRange = new ArrayList<byte[]>();
728 List<HRegionLocation> regionsInRange = new ArrayList<HRegionLocation>();
729 byte[] currentKey = startKey;
730 do {
731 HRegionLocation regionLocation = getRegionLocation(currentKey, reload);
732 keysInRange.add(currentKey);
733 regionsInRange.add(regionLocation);
734 currentKey = regionLocation.getRegionInfo().getEndKey();
735 } while (!Bytes.equals(currentKey, HConstants.EMPTY_END_ROW)
736 && (endKeyIsEndOfTable || Bytes.compareTo(currentKey, endKey) < 0
737 || (includeEndKey && Bytes.compareTo(currentKey, endKey) == 0)));
738 return new Pair<List<byte[]>, List<HRegionLocation>>(keysInRange,
739 regionsInRange);
740 }
741
742
743
744
745
746 @Override
747 @Deprecated
748 public Result getRowOrBefore(final byte[] row, final byte[] family)
749 throws IOException {
750 RegionServerCallable<Result> callable = new RegionServerCallable<Result>(this.connection,
751 tableName, row) {
752 @Override
753 public Result call(int callTimeout) throws IOException {
754 HBaseRpcController controller = rpcControllerFactory.newController();
755 controller.setPriority(tableName);
756 controller.setCallTimeout(callTimeout);
757 ClientProtos.GetRequest request = RequestConverter.buildGetRowOrBeforeRequest(
758 getLocation().getRegionInfo().getRegionName(), row, family);
759 try {
760 ClientProtos.GetResponse response = getStub().get(controller, request);
761 if (!response.hasResult()) return null;
762 return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
763 } catch (ServiceException se) {
764 throw ProtobufUtil.getRemoteException(se);
765 }
766 }
767 };
768 return rpcCallerFactory.<Result>newCaller(readRpcTimeout).callWithRetries(callable,
769 this.operationTimeout);
770 }
771
772
773
774
775
776 @Override
777 public ResultScanner getScanner(Scan scan) throws IOException {
778 if (scan.getCaching() <= 0) {
779 scan.setCaching(getScannerCaching());
780 }
781 if (scan.getMaxResultSize() <= 0) {
782 scan.setMaxResultSize(scannerMaxResultSize);
783 }
784 if (scan.getMvccReadPoint() > 0) {
785
786 scan.resetMvccReadPoint();
787 }
788
789 if (scan.isReversed()) {
790 return new ReversedClientScanner(getConfiguration(), scan, getName(),
791 this.connection, this.rpcCallerFactory, this.rpcControllerFactory,
792 pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
793 } else {
794 return new ClientSimpleScanner(getConfiguration(), scan, getName(), this.connection,
795 this.rpcCallerFactory, this.rpcControllerFactory,
796 pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
797 }
798 }
799
800
801
802
803
804 @Override
805 public ResultScanner getScanner(byte [] family) throws IOException {
806 Scan scan = new Scan();
807 scan.addFamily(family);
808 return getScanner(scan);
809 }
810
811
812
813
814
815 @Override
816 public ResultScanner getScanner(byte [] family, byte [] qualifier)
817 throws IOException {
818 Scan scan = new Scan();
819 scan.addColumn(family, qualifier);
820 return getScanner(scan);
821 }
822
823
824
825
826 @Override
827 public Result get(final Get get) throws IOException {
828 return get(get, get.isCheckExistenceOnly());
829 }
830
831 private Result get(Get get, final boolean checkExistenceOnly) throws IOException {
832
833 if (get.isCheckExistenceOnly() != checkExistenceOnly || get.getConsistency() == null) {
834 get = ReflectionUtils.newInstance(get.getClass(), get);
835 get.setCheckExistenceOnly(checkExistenceOnly);
836 if (get.getConsistency() == null){
837 get.setConsistency(defaultConsistency);
838 }
839 }
840
841 if (get.getConsistency() == Consistency.STRONG) {
842
843 final Get getReq = get;
844 RegionServerCallable<Result> callable = new RegionServerCallable<Result>(this.connection,
845 getName(), get.getRow(), get.getPriority()) {
846 @Override
847 public Result call(int callTimeout) throws IOException {
848 ClientProtos.GetRequest request =
849 RequestConverter.buildGetRequest(getLocation().getRegionInfo().getRegionName(), getReq);
850 HBaseRpcController controller = rpcControllerFactory.newController();
851 controller.setPriority(tableName);
852 controller.setPriority(getPriority());
853 controller.setCallTimeout(callTimeout);
854 try {
855 ClientProtos.GetResponse response = getStub().get(controller, request);
856 if (response == null) return null;
857 return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
858 } catch (ServiceException se) {
859 throw ProtobufUtil.getRemoteException(se);
860 }
861 }
862 };
863 return rpcCallerFactory.<Result>newCaller(readRpcTimeout).callWithRetries(callable,
864 this.operationTimeout);
865 }
866
867
868 RpcRetryingCallerWithReadReplicas callable = new RpcRetryingCallerWithReadReplicas(
869 rpcControllerFactory, tableName, this.connection, get, pool,
870 connConfiguration.getRetriesNumber(),
871 operationTimeout,
872 connConfiguration.getPrimaryCallTimeoutMicroSecond());
873 return callable.call(operationTimeout);
874 }
875
876
877
878
879
880 @Override
881 public Result[] get(List<Get> gets) throws IOException {
882 if (gets.size() == 1) {
883 return new Result[]{get(gets.get(0))};
884 }
885 try {
886 Object[] r1 = new Object[gets.size()];
887 batch((List<? extends Row>)gets, r1, readRpcTimeout);
888
889 Result [] results = new Result[r1.length];
890 int i=0;
891 for (Object o : r1) {
892
893 results[i++] = (Result) o;
894 }
895
896 return results;
897 } catch (InterruptedException e) {
898 throw (InterruptedIOException)new InterruptedIOException().initCause(e);
899 }
900 }
901
902 public void batch(final List<? extends Row> actions, final Object[] results, int rpcTimeout)
903 throws InterruptedException, IOException {
904 AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, actions, null, results, null,
905 operationTimeout, rpcTimeout);
906 ars.waitUntilDone();
907 if (ars.hasError()) {
908 throw ars.getErrors();
909 }
910 }
911
912
913
914
915 @Override
916 public void batch(final List<? extends Row> actions, final Object[] results)
917 throws InterruptedException, IOException {
918 AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, actions, null, results);
919 ars.waitUntilDone();
920 if (ars.hasError()) {
921 throw ars.getErrors();
922 }
923 }
924
925
926
927
928
929
930 @Deprecated
931 @Override
932 public Object[] batch(final List<? extends Row> actions)
933 throws InterruptedException, IOException {
934 Object[] results = new Object[actions.size()];
935 batch(actions, results);
936 return results;
937 }
938
939
940
941
942 @Override
943 public <R> void batchCallback(
944 final List<? extends Row> actions, final Object[] results, final Batch.Callback<R> callback)
945 throws IOException, InterruptedException {
946 connection.processBatchCallback(actions, tableName, pool, results, callback);
947 }
948
949
950
951
952
953
954
955
956 @Deprecated
957 @Override
958 public <R> Object[] batchCallback(
959 final List<? extends Row> actions, final Batch.Callback<R> callback) throws IOException,
960 InterruptedException {
961 Object[] results = new Object[actions.size()];
962 batchCallback(actions, results, callback);
963 return results;
964 }
965
966
967
968
969 @Override
970 public void delete(final Delete delete)
971 throws IOException {
972 RegionServerCallable<Boolean> callable = new RegionServerCallable<Boolean>(connection,
973 tableName, delete.getRow(), delete.getPriority()) {
974 @Override
975 public Boolean call(int callTimeout) throws IOException {
976 HBaseRpcController controller = rpcControllerFactory.newController();
977 controller.setPriority(tableName);
978 controller.setPriority(getPriority());
979 controller.setCallTimeout(callTimeout);
980
981 try {
982 MutateRequest request = RequestConverter.buildMutateRequest(
983 getLocation().getRegionInfo().getRegionName(), delete);
984 MutateResponse response = getStub().mutate(controller, request);
985 return Boolean.valueOf(response.getProcessed());
986 } catch (ServiceException se) {
987 throw ProtobufUtil.getRemoteException(se);
988 }
989 }
990 };
991 rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
992 this.operationTimeout);
993 }
994
995
996
997
998 @Override
999 public void delete(final List<Delete> deletes)
1000 throws IOException {
1001 Object[] results = new Object[deletes.size()];
1002 try {
1003 batch(deletes, results, writeRpcTimeout);
1004 } catch (InterruptedException e) {
1005 throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1006 } finally {
1007
1008
1009
1010 for (int i = results.length - 1; i>=0; i--) {
1011
1012 if (results[i] instanceof Result) {
1013 deletes.remove(i);
1014 }
1015 }
1016 }
1017 }
1018
1019
1020
1021
1022
1023 @Override
1024 public void put(final Put put) throws IOException {
1025 getBufferedMutator().mutate(put);
1026 if (autoFlush) {
1027 flushCommits();
1028 }
1029 }
1030
1031
1032
1033
1034
1035 @Override
1036 public void put(final List<Put> puts) throws IOException {
1037 getBufferedMutator().mutate(puts);
1038 if (autoFlush) {
1039 flushCommits();
1040 }
1041 }
1042
1043
1044
1045
1046 @Override
1047 public void mutateRow(final RowMutations rm) throws IOException {
1048 final RetryingTimeTracker tracker = new RetryingTimeTracker().start();
1049 PayloadCarryingServerCallable<MultiResponse> callable =
1050 new PayloadCarryingServerCallable<MultiResponse>(connection, getName(), rm.getRow(),
1051 rpcControllerFactory) {
1052 @Override
1053 public MultiResponse call(int callTimeout) throws IOException {
1054 controller.reset();
1055 controller.setPriority(tableName);
1056 controller.setPriority(rm.getMaxPriority());
1057 int remainingTime = tracker.getRemainingTime(callTimeout);
1058 if (remainingTime == 0) {
1059 throw new DoNotRetryIOException("Timeout for mutate row");
1060 }
1061 controller.setCallTimeout(remainingTime);
1062 try {
1063 RegionAction.Builder regionMutationBuilder = RequestConverter.buildRegionAction(
1064 getLocation().getRegionInfo().getRegionName(), rm);
1065 regionMutationBuilder.setAtomic(true);
1066 MultiRequest request =
1067 MultiRequest.newBuilder().addRegionAction(regionMutationBuilder.build()).build();
1068 ClientProtos.MultiResponse response = getStub().multi(controller, request);
1069 ClientProtos.RegionActionResult res = response.getRegionActionResultList().get(0);
1070 if (res.hasException()) {
1071 Throwable ex = ProtobufUtil.toException(res.getException());
1072 if (ex instanceof IOException) {
1073 throw (IOException) ex;
1074 }
1075 throw new IOException("Failed to mutate row: " +
1076 Bytes.toStringBinary(rm.getRow()), ex);
1077 }
1078 return ResponseConverter.getResults(request, response, controller.cellScanner());
1079 } catch (ServiceException se) {
1080 throw ProtobufUtil.getRemoteException(se);
1081 }
1082 }
1083 };
1084 AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, rm.getMutations(),
1085 null, null, callable, operationTimeout, writeRpcTimeout);
1086 ars.waitUntilDone();
1087 if (ars.hasError()) {
1088 throw ars.getErrors();
1089 }
1090 }
1091
1092
1093
1094
1095 @Override
1096 public Result append(final Append append) throws IOException {
1097 if (append.numFamilies() == 0) {
1098 throw new IOException(
1099 "Invalid arguments to append, no columns specified");
1100 }
1101
1102 NonceGenerator ng = this.connection.getNonceGenerator();
1103 final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce();
1104 RegionServerCallable<Result> callable =
1105 new RegionServerCallable<Result>(this.connection, getName(), append.getRow(), append.getPriority()) {
1106 @Override
1107 public Result call(int callTimeout) throws IOException {
1108 HBaseRpcController controller = rpcControllerFactory.newController();
1109 controller.setPriority(getTableName());
1110 controller.setCallTimeout(getPriority());
1111 try {
1112 MutateRequest request = RequestConverter.buildMutateRequest(
1113 getLocation().getRegionInfo().getRegionName(), append, nonceGroup, nonce);
1114 MutateResponse response = getStub().mutate(controller, request);
1115 if (!response.hasResult()) return null;
1116 return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
1117 } catch (ServiceException se) {
1118 throw ProtobufUtil.getRemoteException(se);
1119 }
1120 }
1121 };
1122 return rpcCallerFactory.<Result> newCaller(writeRpcTimeout).callWithRetries(callable,
1123 this.operationTimeout);
1124 }
1125
1126
1127
1128
1129 @Override
1130 public Result increment(final Increment increment) throws IOException {
1131 if (!increment.hasFamilies()) {
1132 throw new IOException(
1133 "Invalid arguments to increment, no columns specified");
1134 }
1135 NonceGenerator ng = this.connection.getNonceGenerator();
1136 final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce();
1137 RegionServerCallable<Result> callable = new RegionServerCallable<Result>(this.connection,
1138 getName(), increment.getRow(), increment.getPriority()) {
1139 @Override
1140 public Result call(int callTimeout) throws IOException {
1141 HBaseRpcController controller = rpcControllerFactory.newController();
1142 controller.setPriority(getTableName());
1143 controller.setPriority(getPriority());
1144 controller.setCallTimeout(callTimeout);
1145 try {
1146 MutateRequest request = RequestConverter.buildMutateRequest(
1147 getLocation().getRegionInfo().getRegionName(), increment, nonceGroup, nonce);
1148 MutateResponse response = getStub().mutate(controller, request);
1149 return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
1150 } catch (ServiceException se) {
1151 throw ProtobufUtil.getRemoteException(se);
1152 }
1153 }
1154 };
1155 return rpcCallerFactory.<Result> newCaller(writeRpcTimeout).callWithRetries(callable,
1156 this.operationTimeout);
1157 }
1158
1159
1160
1161
1162 @Override
1163 public long incrementColumnValue(final byte [] row, final byte [] family,
1164 final byte [] qualifier, final long amount)
1165 throws IOException {
1166 return incrementColumnValue(row, family, qualifier, amount, Durability.SYNC_WAL);
1167 }
1168
1169
1170
1171
1172
1173
1174
1175 @Deprecated
1176 @Override
1177 public long incrementColumnValue(final byte [] row, final byte [] family,
1178 final byte [] qualifier, final long amount, final boolean writeToWAL)
1179 throws IOException {
1180 return incrementColumnValue(row, family, qualifier, amount,
1181 writeToWAL? Durability.SYNC_WAL: Durability.SKIP_WAL);
1182 }
1183
1184
1185
1186
1187 @Override
1188 public long incrementColumnValue(final byte [] row, final byte [] family,
1189 final byte [] qualifier, final long amount, final Durability durability)
1190 throws IOException {
1191 NullPointerException npe = null;
1192 if (row == null) {
1193 npe = new NullPointerException("row is null");
1194 } else if (family == null) {
1195 npe = new NullPointerException("family is null");
1196 } else if (qualifier == null) {
1197 npe = new NullPointerException("qualifier is null");
1198 }
1199 if (npe != null) {
1200 throw new IOException(
1201 "Invalid arguments to incrementColumnValue", npe);
1202 }
1203
1204 NonceGenerator ng = this.connection.getNonceGenerator();
1205 final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce();
1206 RegionServerCallable<Long> callable =
1207 new RegionServerCallable<Long>(connection, getName(), row) {
1208 @Override
1209 public Long call(int callTimeout) throws IOException {
1210 HBaseRpcController controller = rpcControllerFactory.newController();
1211 controller.setPriority(getTableName());
1212 controller.setCallTimeout(callTimeout);
1213 try {
1214 MutateRequest request = RequestConverter.buildIncrementRequest(
1215 getLocation().getRegionInfo().getRegionName(), row, family,
1216 qualifier, amount, durability, nonceGroup, nonce);
1217 MutateResponse response = getStub().mutate(controller, request);
1218 Result result =
1219 ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
1220 return Long.valueOf(Bytes.toLong(result.getValue(family, qualifier)));
1221 } catch (ServiceException se) {
1222 throw ProtobufUtil.getRemoteException(se);
1223 }
1224 }
1225 };
1226 return rpcCallerFactory.<Long> newCaller(writeRpcTimeout).callWithRetries(callable,
1227 this.operationTimeout);
1228 }
1229
1230
1231
1232
1233 @Override
1234 public boolean checkAndPut(final byte [] row,
1235 final byte [] family, final byte [] qualifier, final byte [] value,
1236 final Put put)
1237 throws IOException {
1238 RegionServerCallable<Boolean> callable =
1239 new RegionServerCallable<Boolean>(connection, getName(), row, put.getPriority()) {
1240 @Override
1241 public Boolean call(int callTimeout) throws IOException {
1242 HBaseRpcController controller = rpcControllerFactory.newController();
1243 controller.setPriority(tableName);
1244 controller.setPriority(getPriority());
1245 controller.setCallTimeout(callTimeout);
1246 try {
1247 MutateRequest request = RequestConverter.buildMutateRequest(
1248 getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1249 new BinaryComparator(value), CompareType.EQUAL, put);
1250 MutateResponse response = getStub().mutate(controller, request);
1251 return Boolean.valueOf(response.getProcessed());
1252 } catch (ServiceException se) {
1253 throw ProtobufUtil.getRemoteException(se);
1254 }
1255 }
1256 };
1257 return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1258 this.operationTimeout);
1259 }
1260
1261
1262
1263
1264 @Override
1265 public boolean checkAndPut(final byte [] row, final byte [] family,
1266 final byte [] qualifier, final CompareOp compareOp, final byte [] value,
1267 final Put put)
1268 throws IOException {
1269 RegionServerCallable<Boolean> callable =
1270 new RegionServerCallable<Boolean>(connection, getName(), row, put.getPriority()) {
1271 @Override
1272 public Boolean call(int callTimeout) throws IOException {
1273 HBaseRpcController controller = rpcControllerFactory.newController();
1274 controller.setPriority(tableName);
1275 controller.setPriority(getPriority());
1276 controller.setCallTimeout(callTimeout);
1277 try {
1278 CompareType compareType = CompareType.valueOf(compareOp.name());
1279 MutateRequest request = RequestConverter.buildMutateRequest(
1280 getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1281 new BinaryComparator(value), compareType, put);
1282 MutateResponse response = getStub().mutate(controller, request);
1283 return Boolean.valueOf(response.getProcessed());
1284 } catch (ServiceException se) {
1285 throw ProtobufUtil.getRemoteException(se);
1286 }
1287 }
1288 };
1289 return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1290 this.operationTimeout);
1291 }
1292
1293
1294
1295
1296 @Override
1297 public boolean checkAndDelete(final byte [] row,
1298 final byte [] family, final byte [] qualifier, final byte [] value,
1299 final Delete delete)
1300 throws IOException {
1301 RegionServerCallable<Boolean> callable =
1302 new RegionServerCallable<Boolean>(connection, getName(), row, delete.getPriority()) {
1303 @Override
1304 public Boolean call(int callTimeout) throws IOException {
1305 HBaseRpcController controller = rpcControllerFactory.newController();
1306 controller.setPriority(tableName);
1307 controller.setPriority(getPriority());
1308 controller.setCallTimeout(callTimeout);
1309 try {
1310 MutateRequest request = RequestConverter.buildMutateRequest(
1311 getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1312 new BinaryComparator(value), CompareType.EQUAL, delete);
1313 MutateResponse response = getStub().mutate(controller, request);
1314 return Boolean.valueOf(response.getProcessed());
1315 } catch (ServiceException se) {
1316 throw ProtobufUtil.getRemoteException(se);
1317 }
1318 }
1319 };
1320 return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1321 this.operationTimeout);
1322 }
1323
1324
1325
1326
1327 @Override
1328 public boolean checkAndDelete(final byte [] row, final byte [] family,
1329 final byte [] qualifier, final CompareOp compareOp, final byte [] value,
1330 final Delete delete)
1331 throws IOException {
1332 RegionServerCallable<Boolean> callable =
1333 new RegionServerCallable<Boolean>(connection, getName(), row, delete.getPriority()) {
1334 @Override
1335 public Boolean call(int callTimeout) throws IOException {
1336 HBaseRpcController controller = rpcControllerFactory.newController();
1337 controller.setPriority(tableName);
1338 controller.setPriority(getPriority());
1339 controller.setCallTimeout(callTimeout);
1340 try {
1341 CompareType compareType = CompareType.valueOf(compareOp.name());
1342 MutateRequest request = RequestConverter.buildMutateRequest(
1343 getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1344 new BinaryComparator(value), compareType, delete);
1345 MutateResponse response = getStub().mutate(controller, request);
1346 return Boolean.valueOf(response.getProcessed());
1347 } catch (ServiceException se) {
1348 throw ProtobufUtil.getRemoteException(se);
1349 }
1350 }
1351 };
1352 return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1353 this.operationTimeout);
1354 }
1355
1356
1357
1358
1359 @Override
1360 public boolean checkAndMutate(final byte [] row, final byte [] family, final byte [] qualifier,
1361 final CompareOp compareOp, final byte [] value, final RowMutations rm)
1362 throws IOException {
1363 final RetryingTimeTracker tracker = new RetryingTimeTracker().start();
1364 PayloadCarryingServerCallable<MultiResponse> callable =
1365 new PayloadCarryingServerCallable<MultiResponse>(connection, getName(), row,
1366 rpcControllerFactory) {
1367 @Override
1368 public MultiResponse call(int callTimeout) throws IOException {
1369 controller.reset();
1370 controller.setPriority(tableName);
1371 controller.setPriority(rm.getMaxPriority());
1372 int remainingTime = tracker.getRemainingTime(callTimeout);
1373 if (remainingTime == 0) {
1374 throw new DoNotRetryIOException("Timeout for mutate row");
1375 }
1376 controller.setCallTimeout(remainingTime);
1377 try {
1378 CompareType compareType = CompareType.valueOf(compareOp.name());
1379 MultiRequest request = RequestConverter.buildMutateRequest(
1380 getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1381 new BinaryComparator(value), compareType, rm);
1382 ClientProtos.MultiResponse response = getStub().multi(controller, request);
1383 ClientProtos.RegionActionResult res = response.getRegionActionResultList().get(0);
1384 if (res.hasException()) {
1385 Throwable ex = ProtobufUtil.toException(res.getException());
1386 if(ex instanceof IOException) {
1387 throw (IOException)ex;
1388 }
1389 throw new IOException("Failed to checkAndMutate row: "+
1390 Bytes.toStringBinary(row), ex);
1391 }
1392 return ResponseConverter.getResults(request, response, controller.cellScanner());
1393 } catch (ServiceException se) {
1394 throw ProtobufUtil.getRemoteException(se);
1395 }
1396 }
1397 };
1398
1399
1400
1401
1402 Object[] results = new Object[rm.getMutations().size()];
1403 AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, rm.getMutations(),
1404 null, results, callable, operationTimeout, writeRpcTimeout);
1405 ars.waitUntilDone();
1406 if (ars.hasError()) {
1407 throw ars.getErrors();
1408 }
1409
1410 return ((Result)results[0]).getExists();
1411 }
1412
1413
1414
1415
1416 @Override
1417 public boolean exists(final Get get) throws IOException {
1418 Result r = get(get, true);
1419 assert r.getExists() != null;
1420 return r.getExists();
1421 }
1422
1423
1424
1425
1426 @Override
1427 public boolean[] existsAll(final List<Get> gets) throws IOException {
1428 if (gets.isEmpty()) return new boolean[]{};
1429 if (gets.size() == 1) return new boolean[]{exists(gets.get(0))};
1430
1431 ArrayList<Get> exists = new ArrayList<Get>(gets.size());
1432 for (Get g: gets){
1433 Get ge = new Get(g);
1434 ge.setCheckExistenceOnly(true);
1435 exists.add(ge);
1436 }
1437
1438 Object[] r1 = new Object[exists.size()];
1439 try {
1440 batch(exists, r1, readRpcTimeout);
1441 } catch (InterruptedException e) {
1442 throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1443 }
1444
1445
1446 boolean[] results = new boolean[r1.length];
1447 int i = 0;
1448 for (Object o : r1) {
1449
1450 results[i++] = ((Result)o).getExists();
1451 }
1452
1453 return results;
1454 }
1455
1456
1457
1458
1459 @Override
1460 @Deprecated
1461 public Boolean[] exists(final List<Get> gets) throws IOException {
1462 boolean[] results = existsAll(gets);
1463 Boolean[] objectResults = new Boolean[results.length];
1464 for (int i = 0; i < results.length; ++i) {
1465 objectResults[i] = results[i];
1466 }
1467 return objectResults;
1468 }
1469
1470
1471
1472
1473
1474 @Override
1475 public void flushCommits() throws IOException {
1476 if (mutator == null) {
1477
1478 return;
1479 }
1480 getBufferedMutator().flush();
1481 }
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494 public <R> void processBatchCallback(
1495 final List<? extends Row> list, final Object[] results, final Batch.Callback<R> callback)
1496 throws IOException, InterruptedException {
1497 this.batchCallback(list, results, callback);
1498 }
1499
1500 @Override
1501 public void close() throws IOException {
1502 if (this.closed) {
1503 return;
1504 }
1505 flushCommits();
1506 if (cleanupPoolOnClose) {
1507 this.pool.shutdown();
1508 try {
1509 boolean terminated = false;
1510 do {
1511
1512 terminated = this.pool.awaitTermination(60, TimeUnit.SECONDS);
1513 } while (!terminated);
1514 } catch (InterruptedException e) {
1515 this.pool.shutdownNow();
1516 LOG.warn("waitForTermination interrupted");
1517 }
1518 }
1519 if (cleanupConnectionOnClose) {
1520 if (this.connection != null) {
1521 this.connection.close();
1522 }
1523 }
1524 this.closed = true;
1525 }
1526
1527
1528 public void validatePut(final Put put) throws IllegalArgumentException {
1529 validatePut(put, connConfiguration.getMaxKeyValueSize());
1530 }
1531
1532
1533 public static void validatePut(Put put, int maxKeyValueSize) throws IllegalArgumentException {
1534 if (put.isEmpty()) {
1535 throw new IllegalArgumentException("No columns to insert");
1536 }
1537 if (maxKeyValueSize > 0) {
1538 for (List<Cell> list : put.getFamilyCellMap().values()) {
1539 for (Cell cell : list) {
1540 if (KeyValueUtil.length(cell) > maxKeyValueSize) {
1541 throw new IllegalArgumentException("KeyValue size too large");
1542 }
1543 }
1544 }
1545 }
1546 }
1547
1548
1549
1550
1551 @Override
1552 public boolean isAutoFlush() {
1553 return autoFlush;
1554 }
1555
1556
1557
1558
1559 @Deprecated
1560 @Override
1561 public void setAutoFlush(boolean autoFlush) {
1562 this.autoFlush = autoFlush;
1563 }
1564
1565
1566
1567
1568 @Override
1569 public void setAutoFlushTo(boolean autoFlush) {
1570 this.autoFlush = autoFlush;
1571 }
1572
1573
1574
1575
1576 @Override
1577 public void setAutoFlush(boolean autoFlush, boolean clearBufferOnFail) {
1578 this.autoFlush = autoFlush;
1579 }
1580
1581
1582
1583
1584
1585
1586
1587
1588 @Override
1589 public long getWriteBufferSize() {
1590 if (mutator == null) {
1591 return connConfiguration.getWriteBufferSize();
1592 } else {
1593 return mutator.getWriteBufferSize();
1594 }
1595 }
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605 @Override
1606 public void setWriteBufferSize(long writeBufferSize) throws IOException {
1607 getBufferedMutator();
1608 mutator.setWriteBufferSize(writeBufferSize);
1609 }
1610
1611
1612
1613
1614
1615 ExecutorService getPool() {
1616 return this.pool;
1617 }
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629 @Deprecated
1630 public static void setRegionCachePrefetch(final byte[] tableName,
1631 final boolean enable) throws IOException {
1632 }
1633
1634
1635
1636
1637 @Deprecated
1638 public static void setRegionCachePrefetch(
1639 final TableName tableName,
1640 final boolean enable) throws IOException {
1641 }
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654 @Deprecated
1655 public static void setRegionCachePrefetch(final Configuration conf,
1656 final byte[] tableName, final boolean enable) throws IOException {
1657 }
1658
1659
1660
1661
1662 @Deprecated
1663 public static void setRegionCachePrefetch(final Configuration conf,
1664 final TableName tableName,
1665 final boolean enable) throws IOException {
1666 }
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677 @Deprecated
1678 public static boolean getRegionCachePrefetch(final Configuration conf,
1679 final byte[] tableName) throws IOException {
1680 return false;
1681 }
1682
1683
1684
1685
1686 @Deprecated
1687 public static boolean getRegionCachePrefetch(final Configuration conf,
1688 final TableName tableName) throws IOException {
1689 return false;
1690 }
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700 @Deprecated
1701 public static boolean getRegionCachePrefetch(final byte[] tableName) throws IOException {
1702 return false;
1703 }
1704
1705
1706
1707
1708 @Deprecated
1709 public static boolean getRegionCachePrefetch(
1710 final TableName tableName) throws IOException {
1711 return false;
1712 }
1713
1714
1715
1716
1717
1718 public void clearRegionCache() {
1719 this.connection.clearRegionCache();
1720 }
1721
1722
1723
1724
1725 @Override
1726 public CoprocessorRpcChannel coprocessorService(byte[] row) {
1727 return new RegionCoprocessorRpcChannel(connection, tableName, row);
1728 }
1729
1730
1731
1732
1733 @Override
1734 public <T extends Service, R> Map<byte[],R> coprocessorService(final Class<T> service,
1735 byte[] startKey, byte[] endKey, final Batch.Call<T,R> callable)
1736 throws ServiceException, Throwable {
1737 final Map<byte[],R> results = Collections.synchronizedMap(
1738 new TreeMap<byte[], R>(Bytes.BYTES_COMPARATOR));
1739 coprocessorService(service, startKey, endKey, callable, new Batch.Callback<R>() {
1740 @Override
1741 public void update(byte[] region, byte[] row, R value) {
1742 if (region != null) {
1743 results.put(region, value);
1744 }
1745 }
1746 });
1747 return results;
1748 }
1749
1750
1751
1752
1753 @Override
1754 public <T extends Service, R> void coprocessorService(final Class<T> service,
1755 byte[] startKey, byte[] endKey, final Batch.Call<T,R> callable,
1756 final Batch.Callback<R> callback) throws ServiceException, Throwable {
1757
1758
1759 List<byte[]> keys = getStartKeysInRange(startKey, endKey);
1760
1761 Map<byte[],Future<R>> futures =
1762 new TreeMap<byte[],Future<R>>(Bytes.BYTES_COMPARATOR);
1763 for (final byte[] r : keys) {
1764 final RegionCoprocessorRpcChannel channel =
1765 new RegionCoprocessorRpcChannel(connection, tableName, r);
1766 Future<R> future = pool.submit(
1767 new Callable<R>() {
1768 @Override
1769 public R call() throws Exception {
1770 T instance = ProtobufUtil.newServiceStub(service, channel);
1771 R result = callable.call(instance);
1772 byte[] region = channel.getLastRegion();
1773 if (callback != null) {
1774 callback.update(region, r, result);
1775 }
1776 return result;
1777 }
1778 });
1779 futures.put(r, future);
1780 }
1781 for (Map.Entry<byte[],Future<R>> e : futures.entrySet()) {
1782 try {
1783 e.getValue().get();
1784 } catch (ExecutionException ee) {
1785 LOG.warn("Error calling coprocessor service " + service.getName() + " for row "
1786 + Bytes.toStringBinary(e.getKey()), ee);
1787 throw ee.getCause();
1788 } catch (InterruptedException ie) {
1789 throw new InterruptedIOException("Interrupted calling coprocessor service " + service.getName()
1790 + " for row " + Bytes.toStringBinary(e.getKey()))
1791 .initCause(ie);
1792 }
1793 }
1794 }
1795
1796 private List<byte[]> getStartKeysInRange(byte[] start, byte[] end)
1797 throws IOException {
1798 if (start == null) {
1799 start = HConstants.EMPTY_START_ROW;
1800 }
1801 if (end == null) {
1802 end = HConstants.EMPTY_END_ROW;
1803 }
1804 return getKeysAndRegionsInRange(start, end, true).getFirst();
1805 }
1806
1807 @Override
1808 public void setOperationTimeout(int operationTimeout) {
1809 this.operationTimeout = operationTimeout;
1810 if (mutator != null) {
1811 mutator.setOperationTimeout(operationTimeout);
1812 }
1813 multiAp.setOperationTimeout(operationTimeout);
1814 }
1815
1816 @Override
1817 public int getOperationTimeout() {
1818 return operationTimeout;
1819 }
1820
1821 @Override
1822 @Deprecated
1823 public int getRpcTimeout() {
1824 return readRpcTimeout;
1825 }
1826
1827 @Override
1828 @Deprecated
1829 public void setRpcTimeout(int rpcTimeout) {
1830 setWriteRpcTimeout(rpcTimeout);
1831 setReadRpcTimeout(rpcTimeout);
1832 }
1833
1834 @Override
1835 public int getWriteRpcTimeout() {
1836 return writeRpcTimeout;
1837 }
1838
1839 @Override
1840 public void setWriteRpcTimeout(int writeRpcTimeout) {
1841 this.writeRpcTimeout = writeRpcTimeout;
1842 if (mutator != null) {
1843 mutator.setRpcTimeout(writeRpcTimeout);
1844 }
1845 multiAp.setRpcTimeout(writeRpcTimeout);
1846 }
1847
1848 @Override
1849 public int getReadRpcTimeout() { return readRpcTimeout; }
1850
1851 @Override
1852 public void setReadRpcTimeout(int readRpcTimeout) {
1853 this.readRpcTimeout = readRpcTimeout;
1854 }
1855
1856 @Override
1857 public String toString() {
1858 return tableName + ";" + connection;
1859 }
1860
1861
1862
1863
1864 @Override
1865 public <R extends Message> Map<byte[], R> batchCoprocessorService(
1866 Descriptors.MethodDescriptor methodDescriptor, Message request,
1867 byte[] startKey, byte[] endKey, R responsePrototype) throws ServiceException, Throwable {
1868 final Map<byte[], R> results = Collections.synchronizedMap(new TreeMap<byte[], R>(
1869 Bytes.BYTES_COMPARATOR));
1870 batchCoprocessorService(methodDescriptor, request, startKey, endKey, responsePrototype,
1871 new Callback<R>() {
1872
1873 @Override
1874 public void update(byte[] region, byte[] row, R result) {
1875 if (region != null) {
1876 results.put(region, result);
1877 }
1878 }
1879 });
1880 return results;
1881 }
1882
1883
1884
1885
1886 @Override
1887 public <R extends Message> void batchCoprocessorService(
1888 final Descriptors.MethodDescriptor methodDescriptor, final Message request,
1889 byte[] startKey, byte[] endKey, final R responsePrototype, final Callback<R> callback)
1890 throws ServiceException, Throwable {
1891
1892 if (startKey == null) {
1893 startKey = HConstants.EMPTY_START_ROW;
1894 }
1895 if (endKey == null) {
1896 endKey = HConstants.EMPTY_END_ROW;
1897 }
1898
1899 Pair<List<byte[]>, List<HRegionLocation>> keysAndRegions =
1900 getKeysAndRegionsInRange(startKey, endKey, true);
1901 List<byte[]> keys = keysAndRegions.getFirst();
1902 List<HRegionLocation> regions = keysAndRegions.getSecond();
1903
1904
1905 if (keys.isEmpty()) {
1906 LOG.info("No regions were selected by key range start=" + Bytes.toStringBinary(startKey) +
1907 ", end=" + Bytes.toStringBinary(endKey));
1908 return;
1909 }
1910
1911 List<RegionCoprocessorServiceExec> execs = new ArrayList<RegionCoprocessorServiceExec>();
1912 final Map<byte[], RegionCoprocessorServiceExec> execsByRow =
1913 new TreeMap<byte[], RegionCoprocessorServiceExec>(Bytes.BYTES_COMPARATOR);
1914 for (int i = 0; i < keys.size(); i++) {
1915 final byte[] rowKey = keys.get(i);
1916 final byte[] region = regions.get(i).getRegionInfo().getRegionName();
1917 RegionCoprocessorServiceExec exec =
1918 new RegionCoprocessorServiceExec(region, rowKey, methodDescriptor, request);
1919 execs.add(exec);
1920 execsByRow.put(rowKey, exec);
1921 }
1922
1923
1924
1925 final List<Throwable> callbackErrorExceptions = new ArrayList<Throwable>();
1926 final List<Row> callbackErrorActions = new ArrayList<Row>();
1927 final List<String> callbackErrorServers = new ArrayList<String>();
1928 Object[] results = new Object[execs.size()];
1929
1930 AsyncProcess asyncProcess =
1931 new AsyncProcess(connection, configuration, pool,
1932 RpcRetryingCallerFactory.instantiate(configuration, connection.getStatisticsTracker()),
1933 true, RpcControllerFactory.instantiate(configuration), readRpcTimeout);
1934
1935 AsyncRequestFuture future = asyncProcess.submitAll(tableName, execs,
1936 new Callback<ClientProtos.CoprocessorServiceResult>() {
1937 @Override
1938 public void update(byte[] region, byte[] row,
1939 ClientProtos.CoprocessorServiceResult serviceResult) {
1940 if (LOG.isTraceEnabled()) {
1941 LOG.trace("Received result for endpoint " + methodDescriptor.getFullName() +
1942 ": region=" + Bytes.toStringBinary(region) +
1943 ", row=" + Bytes.toStringBinary(row) +
1944 ", value=" + serviceResult.getValue().getValue());
1945 }
1946 try {
1947 Message.Builder builder = responsePrototype.newBuilderForType();
1948 ProtobufUtil.mergeFrom(builder, serviceResult.getValue().getValue());
1949 callback.update(region, row, (R) builder.build());
1950 } catch (IOException e) {
1951 LOG.error("Unexpected response type from endpoint " + methodDescriptor.getFullName(),
1952 e);
1953 callbackErrorExceptions.add(e);
1954 callbackErrorActions.add(execsByRow.get(row));
1955 callbackErrorServers.add("null");
1956 }
1957 }
1958 }, results);
1959
1960 future.waitUntilDone();
1961
1962 if (future.hasError()) {
1963 throw future.getErrors();
1964 } else if (!callbackErrorExceptions.isEmpty()) {
1965 throw new RetriesExhaustedWithDetailsException(callbackErrorExceptions, callbackErrorActions,
1966 callbackErrorServers);
1967 }
1968 }
1969
1970 public RegionLocator getRegionLocator() {
1971 return this.locator;
1972 }
1973
1974 @VisibleForTesting
1975 BufferedMutator getBufferedMutator() throws IOException {
1976 if (mutator == null) {
1977 this.mutator = (BufferedMutatorImpl) connection.getBufferedMutator(
1978 new BufferedMutatorParams(tableName)
1979 .pool(pool)
1980 .writeBufferSize(connConfiguration.getWriteBufferSize())
1981 .maxKeyValueSize(connConfiguration.getMaxKeyValueSize())
1982 );
1983 mutator.setRpcTimeout(writeRpcTimeout);
1984 mutator.setOperationTimeout(operationTimeout);
1985 }
1986 return mutator;
1987 }
1988 }