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