-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathOHTable.java
More file actions
2412 lines (2247 loc) · 115 KB
/
OHTable.java
File metadata and controls
2412 lines (2247 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* #%L
* OBKV HBase Client Framework
* %%
* Copyright (C) 2022 OceanBase Group
* %%
* OBKV HBase Client Framework is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* #L%
*/
package com.alipay.oceanbase.hbase;
import com.alipay.oceanbase.hbase.exception.FeatureNotSupportedException;
import com.alipay.oceanbase.hbase.exception.OperationTimeoutException;
import com.alipay.oceanbase.hbase.execute.ServerCallable;
import com.alipay.oceanbase.hbase.filter.HBaseFilterUtils;
import com.alipay.oceanbase.hbase.result.ClientStreamScanner;
import com.alipay.oceanbase.hbase.util.*;
import com.alipay.oceanbase.rpc.ObGlobal;
import com.alipay.oceanbase.rpc.ObTableClient;
import com.alipay.oceanbase.rpc.exception.ObTableException;
import com.alipay.oceanbase.rpc.location.model.partition.Partition;
import com.alipay.oceanbase.rpc.exception.ObTableUnexpectedException;
import com.alipay.oceanbase.rpc.mutation.BatchOperation;
import com.alipay.oceanbase.rpc.mutation.result.BatchOperationResult;
import com.alipay.oceanbase.rpc.mutation.result.MutationResult;
import com.alipay.oceanbase.rpc.protocol.payload.ObPayload;
import com.alipay.oceanbase.rpc.protocol.payload.impl.ObObj;
import com.alipay.oceanbase.rpc.protocol.payload.impl.ObRowKey;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.*;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.mutate.ObTableQueryAndMutate;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.mutate.ObTableQueryAndMutateRequest;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.mutate.ObTableQueryAndMutateResult;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.query.*;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.syncquery.ObTableQueryAsyncRequest;
import com.alipay.oceanbase.rpc.queryandmutate.QueryAndMutate;
import com.alipay.oceanbase.rpc.stream.ObTableClientQueryAsyncStreamResult;
import com.alipay.oceanbase.rpc.stream.ObTableClientQueryStreamResult;
import com.alipay.oceanbase.rpc.table.ObHBaseParams;
import com.alipay.oceanbase.rpc.table.ObKVParams;
import com.alipay.oceanbase.rpc.table.ObTableClientQueryImpl;
import com.google.protobuf.*;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.io.TimeRange;
import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.hbase.util.VersionInfo;
import org.slf4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import static com.alipay.oceanbase.hbase.constants.OHConstants.*;
import static com.alipay.oceanbase.hbase.util.Preconditions.checkArgument;
import static com.alipay.oceanbase.hbase.util.TableHBaseLoggerFactory.LCD;
import static com.alipay.oceanbase.rpc.mutation.MutationFactory.colVal;
import static com.alipay.oceanbase.rpc.mutation.MutationFactory.row;
import static com.alipay.oceanbase.rpc.protocol.payload.impl.execute.ObTableOperation.getInstance;
import static com.alipay.oceanbase.rpc.protocol.payload.impl.execute.ObTableOperationType.*;
import static com.alipay.sofa.common.thread.SofaThreadPoolConstants.SOFA_THREAD_POOL_LOGGING_CAPABILITY;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static com.alipay.oceanbase.hbase.filter.HBaseFilterUtils.writeBytesWithEscape;
import static org.apache.hadoop.hbase.KeyValue.Type.*;
public class OHTable implements HTableInterface {
private static final Logger logger = TableHBaseLoggerFactory
.getLogger(OHTable.class);
/**
* the table client for oceanbase
*/
private final ObTableClient obTableClient;
/**
* the ohTable name in byte array
*/
private final byte[] tableName;
/**
* the ohTable name in string
*/
private final String tableNameString;
/**
* operation timeout whose default value is <code>Integer.MaxValue</code> decide the timeout of executing in pool.
* <p>
* if operation timeout is not equal to the default value mean the <code>Get</code> execute in the pool
*/
private int operationTimeout;
/**
* timeout for each rpc request
*/
private int rpcTimeout;
/**
* if the <code>Get</code> executing pool is specified by user cleanupPoolOnClose will be false ,
* which means that user is responsible for the pool
*/
private boolean cleanupPoolOnClose = true;
/**
* if the obTableClient is specified by user closeClientOnClose will be false ,
* which means that user is responsible for obTableClient
*/
private boolean closeClientOnClose = true;
/**
* when the operationExecuteInPool is true the <code>Get</code>
* will be executed in the pool.
*/
private ExecutorService executePool;
/**
* decide whether the <code>Get</code> request will be executed
* in the pool.
*/
private boolean operationExecuteInPool = false;
/**
* the buffer of put request
*/
private final ArrayList<Put> writeBuffer = new ArrayList<Put>();
/**
* when the put request reach the write buffer size the do put will
* flush commits automatically
*/
private long writeBufferSize;
/**
* whether flush the put automatically
*/
private boolean autoFlush = true;
/**
* the max size of put key value
*/
private int maxKeyValueSize;
// i.e., doPut checks the writebuffer every X Puts.
/**
* <code>Configuration</code> extends from hbase configuration
*/
private final Configuration configuration;
private int scannerTimeout;
/**
* the bufferedMutator to execute Puts
*/
private OHBufferedMutatorImpl mutator;
/**
* flag for whether closed
*/
private boolean isClosed = false;
/**
* Creates an object to access a HBase table.
* Shares oceanbase table obTableClient and other resources with other OHTable instances
* created with the same <code>configuration</code> instance. Uses already-populated
* region cache if one is available, populated by any other OHTable instances
* sharing this <code>configuration</code> instance. Recommended.
*
* @param configuration Configuration object to use.
* @param tableName Name of the table.
* @throws IllegalArgumentException if the param error
* @throws IOException if a remote or network exception occurs
*/
public OHTable(Configuration configuration, String tableName) throws IOException {
checkArgument(configuration != null, "configuration is null.");
checkArgument(isNotBlank(tableName), "tableNameString is blank.");
this.configuration = configuration;
this.tableName = tableName.getBytes();
this.tableNameString = tableName;
int maxThreads = configuration.getInt(HBASE_HTABLE_PRIVATE_THREADS_MAX,
DEFAULT_HBASE_HTABLE_PRIVATE_THREADS_MAX);
long keepAliveTime = configuration.getLong(HBASE_HTABLE_THREAD_KEEP_ALIVE_TIME,
DEFAULT_HBASE_HTABLE_THREAD_KEEP_ALIVE_TIME);
this.executePool = createDefaultThreadPoolExecutor(1, maxThreads, keepAliveTime);
OHConnectionConfiguration ohConnectionConf = new OHConnectionConfiguration(configuration);
int numRetries = ohConnectionConf.getNumRetries();
this.obTableClient = ObTableClientManager.getOrCreateObTableClient(setUserDefinedNamespace(
this.tableNameString, ohConnectionConf));
this.obTableClient.setRpcExecuteTimeout(ohConnectionConf.getRpcTimeout());
this.obTableClient.setRuntimeRetryTimes(numRetries);
setOperationTimeout(ohConnectionConf.getOperationTimeout());
finishSetUp();
}
/**
* Creates an object to access a HBase table.
* Shares oceanbase table obTableClient and other resources with other OHTable instances
* created with the same <code>configuration</code> instance. Uses already-populated
* region cache if one is available, populated by any other OHTable instances
* sharing this <code>configuration</code> instance. Recommended.
*
* @param configuration Configuration object to use.
* @param tableName Name of the table.
* @throws IOException if a remote or network exception occurs
* @throws IllegalArgumentException if the param error
*/
public OHTable(Configuration configuration, final byte[] tableName) throws IOException {
this(configuration, Arrays.toString(tableName));
}
/**
* Creates an object to access a HBase table.
* Shares oceanbase table obTableClient and other resources with other OHTable instances
* created with the same <code>configuration</code> instance. Uses already-populated
* region cache if one is available, populated by any other OHTable instances
* sharing this <code>configuration</code> instance.
* Use this constructor when the ExecutorService is externally managed.
*
* @param configuration Configuration object to use.
* @param tableName Name of the table.
* @param executePool ExecutorService to be used.
* @throws IOException if a remote or network exception occurs
* @throws IllegalArgumentException if the param error
*/
public OHTable(Configuration configuration, final byte[] tableName,
final ExecutorService executePool) throws IOException {
checkArgument(configuration != null, "configuration is null.");
checkArgument(tableName != null, "tableNameString is blank.");
checkArgument(executePool != null && !executePool.isShutdown(),
"executePool is null or executePool is shutdown");
this.configuration = configuration;
this.tableName = tableName;
this.tableNameString = Bytes.toString(tableName);
this.executePool = executePool;
this.cleanupPoolOnClose = false;
OHConnectionConfiguration ohConnectionConf = new OHConnectionConfiguration(configuration);
int numRetries = ohConnectionConf.getNumRetries();
this.obTableClient = ObTableClientManager.getOrCreateObTableClient(setUserDefinedNamespace(
this.tableNameString, ohConnectionConf));
this.obTableClient.setRpcExecuteTimeout(ohConnectionConf.getRpcTimeout());
this.obTableClient.setRuntimeRetryTimes(numRetries);
setOperationTimeout(ohConnectionConf.getOperationTimeout());
finishSetUp();
}
/**
* Creates an object to access a HBase table.
* Shares zookeeper connection and other resources with other OHTable instances
* created with the same <code>connection</code> instance.
* Use this constructor when the ExecutorService and HConnection instance are
* externally managed.
*
* @param tableName Name of the table.
* @param obTableClient Oceanbase obTableClient to be used.
* @param executePool ExecutorService to be used.
* @throws IllegalArgumentException if the param error
*/
@InterfaceAudience.Private
public OHTable(final byte[] tableName, final ObTableClient obTableClient,
final ExecutorService executePool) {
checkArgument(tableName != null, "tableNameString is blank.");
checkArgument(executePool != null && !executePool.isShutdown(),
"executePool is null or executePool is shutdown");
this.tableName = tableName;
this.tableNameString = Bytes.toString(tableName);
this.cleanupPoolOnClose = false;
this.closeClientOnClose = false;
this.executePool = executePool;
this.obTableClient = obTableClient;
this.configuration = HBaseConfiguration.create();
finishSetUp();
}
public OHTable(TableName tableName, Connection connection,
OHConnectionConfiguration connectionConfig, ExecutorService executePool)
throws IOException {
checkArgument(connection.getConfiguration() != null, "configuration is null.");
checkArgument(tableName != null, "tableName is null.");
checkArgument(connection.getConfiguration() != null, "configuration is null.");
checkArgument(tableName.getName() != null, "tableNameString is null.");
checkArgument(connectionConfig != null, "connectionConfig is null.");
this.tableNameString = Bytes.toString(tableName.getName());
this.configuration = connection.getConfiguration();
this.executePool = executePool;
if (executePool == null) {
int maxThreads = configuration.getInt(HBASE_HTABLE_PRIVATE_THREADS_MAX,
DEFAULT_HBASE_HTABLE_PRIVATE_THREADS_MAX);
long keepAliveTime = configuration.getLong(HBASE_HTABLE_THREAD_KEEP_ALIVE_TIME,
DEFAULT_HBASE_HTABLE_THREAD_KEEP_ALIVE_TIME);
this.executePool = createDefaultThreadPoolExecutor(1, maxThreads, keepAliveTime);
this.cleanupPoolOnClose = true;
} else {
this.cleanupPoolOnClose = false;
}
this.rpcTimeout = connectionConfig.getRpcTimeout();
this.operationTimeout = connectionConfig.getOperationTimeout();
this.operationExecuteInPool = this.configuration.getBoolean(
HBASE_CLIENT_OPERATION_EXECUTE_IN_POOL,
(this.operationTimeout != HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT));
this.maxKeyValueSize = connectionConfig.getMaxKeyValueSize();
this.writeBufferSize = connectionConfig.getWriteBufferSize();
this.tableName = tableName.getName();
int numRetries = connectionConfig.getNumRetries();
this.obTableClient = ObTableClientManager.getOrCreateObTableClient(setUserDefinedNamespace(
this.tableNameString, connectionConfig));
this.obTableClient.setRpcExecuteTimeout(rpcTimeout);
this.obTableClient.setRuntimeRetryTimes(numRetries);
setOperationTimeout(operationTimeout);
finishSetUp();
}
/**
* 创建默认的线程池
* Using the "direct handoff" approach, new threads will only be created
* if it is necessary and will grow unbounded. This could be bad but in HCM
* we only create as many Runnables as there are region servers. It means
* it also scales when new region servers are added.
* @param coreSize core size
* @param maxThreads max threads
* @param keepAliveTime keep alive time
* @return ThreadPoolExecutor
*/
@InterfaceAudience.Private
public static ThreadPoolExecutor createDefaultThreadPoolExecutor(int coreSize, int maxThreads,
long keepAliveTime) {
// NOTE: when SOFA_THREAD_POOL_LOGGING_CAPABILITY is set to true or not set,
// the static instance ThreadPoolGovernor will start a non-daemon thread pool
// monitor thread in the function ThreadPoolMonitorWrapper.startMonitor,
// which will prevent the client process from normal exit
if (System.getProperty(SOFA_THREAD_POOL_LOGGING_CAPABILITY) == null) {
System.setProperty(SOFA_THREAD_POOL_LOGGING_CAPABILITY, "false");
}
ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, maxThreads,
keepAliveTime, SECONDS, new SynchronousQueue<>(), Threads.newDaemonThreadFactory("ohtable"));
executor.allowCoreThreadTimeOut(true);
return executor;
}
/**
* 参数校验,防止在执行的时候才发现配置不正确
*/
private void finishSetUp() {
checkArgument(configuration != null, "configuration is null.");
checkArgument(tableName != null, "tableNameString is null.");
checkArgument(tableNameString != null, "tableNameString is null.");
this.scannerTimeout = HBaseConfiguration.getInt(configuration,
HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
this.rpcTimeout = configuration.getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
this.operationTimeout = this.configuration.getInt(
HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
this.operationExecuteInPool = this.configuration.getBoolean(
HBASE_CLIENT_OPERATION_EXECUTE_IN_POOL,
(this.operationTimeout != HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT));
this.maxKeyValueSize = this.configuration.getInt(MAX_KEYVALUE_SIZE_KEY,
MAX_KEYVALUE_SIZE_DEFAULT);
this.writeBufferSize = this.configuration.getLong(WRITE_BUFFER_SIZE_KEY,
WRITE_BUFFER_SIZE_DEFAULT);
}
public static OHConnectionConfiguration setUserDefinedNamespace(String tableNameString,
OHConnectionConfiguration ohConnectionConf) {
if (tableNameString.indexOf(':') != -1) {
String[] params = tableNameString.split(":");
if (params.length != 2) {
throw new IllegalArgumentException("Please check the format of self-defined "
+ "namespace and qualifier: { "
+ tableNameString + " }");
}
String database = params[0];
checkArgument(isNotBlank(database), "self-defined namespace cannot be blank or null { "
+ tableNameString + " }");
if (ohConnectionConf.isOdpMode()) {
ohConnectionConf.setDatabase(database);
} else {
String databaseSuffix = "database=" + database;
String paramUrl = ohConnectionConf.getParamUrl();
int databasePos = paramUrl.indexOf("database");
if (databasePos == -1) {
paramUrl += "&" + databaseSuffix;
} else {
paramUrl = paramUrl.substring(0, databasePos) + databaseSuffix;
}
ohConnectionConf.setParamUrl(paramUrl);
}
}
return ohConnectionConf;
}
@Override
public byte[] getTableName() {
return tableName;
}
@Override
public TableName getName() {
return TableName.valueOf(this.tableNameString);
}
@Override
public Configuration getConfiguration() {
return configuration;
}
@Override
public HTableDescriptor getTableDescriptor() throws IOException {
OHTableDescriptorExecutor executor = new OHTableDescriptorExecutor(tableNameString, obTableClient);
return executor.getTableDescriptor();
}
/**
* Test for the existence of columns in the table, as specified in the Get.
*
* This will return true if the Get matches one or more keys, false if not.
*
* Be carefully ,this is not a server-side call in real. May be optimized later
*
* @param get the Get
* @return true if the specified Get matches one or more keys, false if not
* @throws IOException e
*/
@Override
public boolean exists(Get get) throws IOException {
Get newGet = new Get(get);
newGet.setCheckExistenceOnly(true);
return this.get(newGet).getExists();
}
@Override
public boolean[] existsAll(List<Get> gets) throws IOException {
boolean[] ret = new boolean[gets.size()];
List<Get> newGets = new ArrayList<>();
// if just checkExistOnly, batch get will not return any result or row count
// therefore we have to set checkExistOnly as false and so the result can be returned
// TODO: adjust ExistOnly in server when using batch get
for (Get get : gets) {
Get newGet = new Get(get);
newGet.setCheckExistenceOnly(false);
newGets.add(newGet);
}
Result[] results = get(newGets);
for (int i = 0; i < results.length; ++i) {
ret[i] = !results[i].isEmpty();
}
return ret;
}
@Override
public Boolean[] exists(List<Get> gets) throws IOException {
boolean[] results = existsAll(gets);
Boolean[] objectResults = new Boolean[results.length];
for (int i = 0; i < results.length; ++i) {
objectResults[i] = results[i];
}
return objectResults;
}
private BatchOperation compatOldServerPut(final List<? extends Row> actions, final Object[] results, BatchError batchError, int i, List<Row> puts)
throws Exception {
BatchOperationResult tmpResults;
List<Integer> resultMapSingleOp = new LinkedList<>();
if (((Put)actions.get(i)).getFamilyCellMap().size() == 1) {
puts.clear();
Put put = (Put) actions.get(i++);
String family = Bytes.toString(put.getFamilyCellMap().firstKey());
// aggregate put
puts.add(put);
while (i < actions.size()) {
if (actions.get(i) instanceof Put && ((Put)actions.get(i)).getFamilyCellMap().size() == 1 && Objects.equals(
Bytes.toString(((Put) actions.get(i)).getFamilyCellMap().firstKey()),
family)) {
puts.add(actions.get(i++));
} else {
break;
}
}
String realTableName = getTargetTableName(tableNameString, family,
configuration);
BatchOperation batch = buildBatchOperation(realTableName, puts, false,
resultMapSingleOp);
tmpResults = batch.execute();
int index = 0;
for (int k = 0; k < resultMapSingleOp.size(); k++) {
if (tmpResults.getResults().get(index) instanceof ObTableException) {
if (results != null) {
results[i - puts.size() + k] = tmpResults.getResults().get(index);
}
batchError.add(
(ObTableException) tmpResults.getResults().get(index),
actions.get(i - puts.size() + k), null);
} else {
if (results != null) {
results[i - puts.size() + k] = new Result();
}
}
index += resultMapSingleOp.get(k);
}
return null;
} else {
// multi cf put
Put put = (Put) actions.get(i);
String realTableName = getTargetTableName(tableNameString);
return buildBatchOperation(realTableName,
Collections.singletonList(put),
true, resultMapSingleOp);
}
}
private BatchOperation compatOldServerDel(final List<? extends Row> actions, final Object[] results, BatchError batchError, int i)
throws Exception {
Delete delete = (Delete)actions.get(i);
List<Integer> resultMapSingleOp = new LinkedList<>();
if (delete.isEmpty()) {
return buildBatchOperation(tableNameString,
Collections.singletonList(delete), true,
resultMapSingleOp);
} else if (delete.getFamilyCellMap().size() > 1) {
boolean has_delete_family = delete.getFamilyMap().entrySet().stream()
.flatMap(entry -> entry.getValue().stream()).anyMatch(
kv -> KeyValue.Type.codeToType(
kv.getType()) == DeleteFamily || KeyValue.Type.codeToType(
kv.getType()) == DeleteFamilyVersion);
if (!has_delete_family) {
return buildBatchOperation(tableNameString,
Collections.singletonList(delete), true,
resultMapSingleOp);
} else {
for (Map.Entry<byte[], List<Cell>> entry : delete.getFamilyCellMap()
.entrySet()) {
byte[] family = entry.getKey();
String realTableName = getTargetTableName(tableNameString,
Bytes.toString(family), configuration);
// split delete
List<Cell> cells = entry.getValue();
Delete del = new Delete(delete.getRow());
del.getFamilyCellMap().put(family, cells);
BatchOperation batch = buildBatchOperation(realTableName,
Collections.singletonList(del), false,
resultMapSingleOp);
BatchOperationResult tmpResults = batch.execute();
if (tmpResults.getResults().get(0) instanceof ObTableException) {
if (results != null) {
results[i] = tmpResults.getResults().get(0);
}
batchError.add((ObTableException) tmpResults.getResults().get(0), actions.get(i), null);
}
}
if (results != null && results[i] == null) {
results[i] = new Result();
}
return null;
}
} else {
byte[] family = delete.getFamilyCellMap().firstKey();
String realTableName = getTargetTableName(tableNameString, Bytes.toString(family), configuration);
return buildBatchOperation(realTableName,
Collections.singletonList(delete),
false, resultMapSingleOp);
}
}
private void compatOldServerBatch(final List<? extends Row> actions, final Object[] results, BatchError batchError)
throws Exception {
for (Row row : actions) {
if (!(row instanceof Put) && !(row instanceof Delete)) {
throw new FeatureNotSupportedException(
"not supported other type in batch yet,only support put and delete");
}
}
List<Row> puts = new LinkedList<>();
BatchOperation batch;
for (int i = 0; i < actions.size(); i++) {
if (actions.get(i) instanceof Put) {
batch = compatOldServerPut(actions, results, batchError, i, puts);
if (!puts.isEmpty()) {
i = i + puts.size() - 1;
}
puts.clear();
} else {
batch = compatOldServerDel(actions, results, batchError, i);
}
if (batch != null) {
BatchOperationResult tmpResults = batch.execute();
if (tmpResults.getResults().get(0) instanceof ObTableException) {
if (results != null) {
results[i] = tmpResults.getResults().get(0);
}
batchError.add((ObTableException) tmpResults.getResults().get(0), actions.get(i), null);
} else {
if (results != null) {
results[i] = new Result();
}
}
}
}
}
@Override
public void batch(final List<? extends Row> actions, final Object[] results) throws IOException {
if (actions == null) {
return;
}
if (results != null) {
if (results.length != actions.size()) {
throw new AssertionError("results.length");
}
}
BatchError batchError = new BatchError();
obTableClient.setRuntimeBatchExecutor(executePool);
List<Integer> resultMapSingleOp = new LinkedList<>();
if (!ObGlobal.isHBaseBatchSupport()) {
try {
compatOldServerBatch(actions, results, batchError);
} catch (Exception e) {
throw new IOException(tableNameString + " table occurred unexpected error." , e);
}
} else {
String realTableName = getTargetTableName(actions);
BatchOperation batch = buildBatchOperation(realTableName, actions,
tableNameString.equals(realTableName), resultMapSingleOp);
BatchOperationResult tmpResults;
try {
tmpResults = batch.execute();
} catch (Exception e) {
throw new IOException(tableNameString + " table occurred unexpected error." , e);
}
int index = 0;
for (int i = 0; i != actions.size(); ++i) {
if (tmpResults.getResults().get(index) instanceof ObTableException) {
if (results != null) {
results[i] = tmpResults.getResults().get(index);
}
batchError.add((ObTableException) tmpResults.getResults().get(index), actions.get(i), null);
} else if (actions.get(i) instanceof Get) {
if (results != null) {
// get results have been wrapped in MutationResult, need to fetch it
if (tmpResults.getResults().get(index) instanceof MutationResult) {
MutationResult mutationResult = (MutationResult) tmpResults.getResults().get(index);
ObPayload innerResult = mutationResult.getResult();
if (innerResult instanceof ObTableSingleOpResult) {
ObTableSingleOpResult singleOpResult = (ObTableSingleOpResult) innerResult;
List<Cell> cells = generateGetResult(singleOpResult);
results[i] = Result.create(cells);
} else {
throw new ObTableUnexpectedException("Unexpected type of result in MutationResult");
}
} else {
throw new ObTableUnexpectedException("Unexpected type of result in batch");
}
}
} else {
if (results != null) {
results[i] = new Result();
}
}
index += resultMapSingleOp.get(i);
}
}
if (batchError.hasErrors()) {
throw batchError.makeException();
}
}
private List<Cell> generateGetResult(ObTableSingleOpResult getResult) throws IOException {
List<Cell> cells = new ArrayList<>();
ObTableSingleOpEntity singleOpEntity = getResult.getEntity();
// all values queried by this get are contained in properties
// qualifier in batch get result is always appended after family
List<ObObj> propertiesValues = singleOpEntity.getPropertiesValues();
int valueIdx = 0;
while (valueIdx < propertiesValues.size()) {
// values in propertiesValues like: [ K, Q, T, V, K, Q, T, V ... ]
// we need to retrieve K Q T V and construct them to cells: [ cell_0, cell_1, ... ]
byte[][] familyAndQualifier = new byte[2][];
try {
// split family and qualifier
familyAndQualifier = OHBaseFuncUtils
.extractFamilyFromQualifier((byte[]) propertiesValues.get(valueIdx + 1).getValue());
} catch (Exception e) {
throw new IOException(e);
}
KeyValue kv = new KeyValue((byte[]) propertiesValues.get(valueIdx).getValue(),//K
familyAndQualifier[0], // family
familyAndQualifier[1], // qualifiermat
(Long) propertiesValues.get(valueIdx + 2).getValue(), // T
(byte[]) propertiesValues.get(valueIdx + 3).getValue()// V
);
cells.add(kv);
valueIdx += 4;
}
return cells;
}
private String getTargetTableName(List<? extends Row> actions) {
byte[] family = null;
for (Row action : actions) {
if (action instanceof RowMutations || action instanceof RegionCoprocessorServiceExec) {
throw new FeatureNotSupportedException("not supported yet'");
} else {
Set<byte[]> familySet;
if (action instanceof Get) {
Get get = (Get) action;
familySet = get.familySet();
} else {
Mutation mutation = (Mutation) action;
familySet = mutation.getFamilyCellMap().keySet();
}
if (familySet == null) {
throw new ObTableUnexpectedException("Fail to get family set in action");
}
if (familySet.size() != 1) {
return getTargetTableName(tableNameString);
} else {
byte[] nextFamily = familySet.iterator().next();
if (family != null && !Arrays.equals(family, nextFamily)) {
return getTargetTableName(tableNameString);
} else if (family == null) {
family = nextFamily;
}
}
}
}
return getTargetTableName(tableNameString, Bytes.toString(family), configuration);
}
@Override
public Object[] batch(List<? extends Row> actions) throws IOException {
Object[] results = new Object[actions.size()];
batch(actions, results);
return results;
}
@Override
public <R> void batchCallback(List<? extends Row> actions, Object[] results,
Batch.Callback<R> callback) throws IOException,
InterruptedException {
try {
batch(actions, results);
} finally {
if (results != null) {
for (int i = 0; i < results.length; i++) {
if (!(results[i] instanceof ObTableException)) {
callback.update(null, actions.get(i).getRow(), (R) results[i]);
}
}
}
}
}
@Override
public <R> Object[] batchCallback(final List<? extends Row> actions,
final Batch.Callback<R> callback) throws IOException,
InterruptedException {
Object[] results = new Object[actions.size()];
batchCallback(actions, results, callback);
return results;
}
public static int compareByteArray(byte[] bt1, byte[] bt2) {
int minLength = Math.min(bt1.length, bt2.length);
for (int i = 0; i < minLength; i++) {
if (bt1[i] != bt2[i]) {
return bt1[i] - bt2[i];
}
}
return bt1.length - bt2.length;
}
private void getMaxRowFromResult(AbstractQueryStreamResult clientQueryStreamResult,
List<KeyValue> keyValueList, boolean isTableGroup,
byte[] family, boolean checkExistenceOnly) throws Exception {
byte[][] familyAndQualifier = new byte[2][];
KeyValue kv = null;
while (clientQueryStreamResult.next()) {
if (checkExistenceOnly) {
// Currently, checkExistOnly is set, and if the row exists, it returns an empty row.
keyValueList.add(new KeyValue());
return;
} else {
List<ObObj> row = clientQueryStreamResult.getRow();
if (kv == null
|| compareByteArray(kv.getRow(), (byte[]) row.get(0).getValue()) <= 0) {
if (kv != null
&& compareByteArray(kv.getRow(), (byte[]) row.get(0).getValue()) != 0) {
keyValueList.clear();
}
if (isTableGroup) {
// split family and qualifier
familyAndQualifier = OHBaseFuncUtils
.extractFamilyFromQualifier((byte[]) row.get(1).getValue());
} else {
familyAndQualifier[0] = family;
familyAndQualifier[1] = (byte[]) row.get(1).getValue();
}
kv = new KeyValue((byte[]) row.get(0).getValue(),//K
familyAndQualifier[0], // family
familyAndQualifier[1], // qualifiermat
(Long) row.get(2).getValue(), // T
(byte[]) row.get(3).getValue() // V
);
keyValueList.add(kv);
}
}
}
}
private String getTargetTableName(String tableNameString) {
if (configuration.getBoolean(HBASE_HTABLE_TEST_LOAD_ENABLE, false)) {
return tableNameString
+ configuration.get(HBASE_HTABLE_TEST_LOAD_SUFFIX,
DEFAULT_HBASE_HTABLE_TEST_LOAD_SUFFIX);
}
return tableNameString;
}
// To enable the server to identify the column family to which a qualifier belongs,
// the client writes the column family name into the qualifier.
// The server then parses this information to determine the table that needs to be operated on.
private void processColumnFilters(NavigableSet<byte[]> columnFilters,
Map<byte[], NavigableSet<byte[]>> familyMap) {
for (Map.Entry<byte[], NavigableSet<byte[]>> entry : familyMap.entrySet()) {
if (entry.getValue() != null) {
for (byte[] columnName : entry.getValue()) {
byte[] family = entry.getKey();
byte[] newQualifier = new byte[family.length + 1/* length of "." */ + columnName.length];
System.arraycopy(family, 0, newQualifier, 0, family.length);
newQualifier[family.length] = 0x2E; // 0x2E in utf-8 is "."
System.arraycopy(columnName, 0, newQualifier, family.length + 1, columnName.length);
columnFilters.add(newQualifier);
}
} else {
byte[] family = entry.getKey();
byte[] newQualifier = new byte[family.length + 1/* length of "."*/];
System.arraycopy(family, 0, newQualifier, 0, family.length);
newQualifier[family.length] = 0x2E; // 0x2E in utf-8 is "."
columnFilters.add(newQualifier);
}
}
}
@Override
public Result get(final Get get) throws IOException {
if (get.getFamilyMap().keySet().isEmpty()) {
// check nothing, use table group;
} else {
checkFamilyViolation(get.getFamilyMap().keySet(), false);
}
ServerCallable<Result> serverCallable = new ServerCallable<Result>(configuration,
obTableClient, tableNameString, get.getRow(), get.getRow(), operationTimeout) {
public Result call() throws IOException {
List<KeyValue> keyValueList = new ArrayList<>();
byte[] family = new byte[] {};
ObTableQuery obTableQuery;
try {
if (get.getFamilyMap().keySet().isEmpty()
|| get.getFamilyMap().size() > 1) {
// In a Get operation where the family map is greater than 1 or equal to 0,
// we handle this by appending the column family to the qualifier on the client side.
// The server can then use this information to filter the appropriate column families and qualifiers.
if (!get.getColumnFamilyTimeRange().isEmpty()) {
throw new FeatureNotSupportedException("setColumnFamilyTimeRange is only supported in single column family for now");
}
NavigableSet<byte[]> columnFilters = new TreeSet<>(Bytes.BYTES_COMPARATOR);
processColumnFilters(columnFilters, get.getFamilyMap());
obTableQuery = buildObTableQuery(get, columnFilters);
ObTableQueryAsyncRequest request = buildObTableQueryAsyncRequest(obTableQuery,
getTargetTableName(tableNameString));
ObTableClientQueryAsyncStreamResult clientQueryStreamResult = (ObTableClientQueryAsyncStreamResult) obTableClient
.execute(request);
getMaxRowFromResult(clientQueryStreamResult, keyValueList, true, family, get.isCheckExistenceOnly());
} else {
for (Map.Entry<byte[], NavigableSet<byte[]>> entry : get.getFamilyMap()
.entrySet()) {
family = entry.getKey();
if (!get.getColumnFamilyTimeRange().isEmpty()) {
Map<byte[], TimeRange> colFamTimeRangeMap = get.getColumnFamilyTimeRange();
if (colFamTimeRangeMap.size() > 1) {
throw new FeatureNotSupportedException("setColumnFamilyTimeRange is only supported in single column family for now");
} else if (colFamTimeRangeMap.get(family) == null) {
throw new IllegalArgumentException("Get family is not matched in ColumnFamilyTimeRange");
} else {
TimeRange tr = colFamTimeRangeMap.get(family);
get.setTimeRange(tr.getMin(), tr.getMax());
}
}
obTableQuery = buildObTableQuery(get, entry.getValue());
ObTableQueryRequest request = buildObTableQueryRequest(obTableQuery,
getTargetTableName(tableNameString, Bytes.toString(family),
configuration));
ObTableClientQueryStreamResult clientQueryStreamResult = (ObTableClientQueryStreamResult) obTableClient
.execute(request);
getMaxRowFromResult(clientQueryStreamResult, keyValueList, false,
family, get.isCheckExistenceOnly());
}
}
} catch (Exception e) {
logger.error(LCD.convert("01-00002"), tableNameString, Bytes.toString(family),
e);
throw new IOException("query table:" + tableNameString + " family "
+ Bytes.toString(family) + " error.", e);
}
if (get.isCheckExistenceOnly()) {
return Result.create(null, !keyValueList.isEmpty());
}
return new Result(keyValueList);
}
};
return executeServerCallable(serverCallable);
}
@Override
public Result[] get(List<Get> gets) throws IOException {
Result[] results = new Result[gets.size()];
if (ObGlobal.isHBaseBatchGetSupport()) { // get only supported in BatchSupport version
batch(gets, results);
} else {
List<Future<Result>> futures = new LinkedList<>();
for (int i = 0; i < gets.size(); i++) {
int index = i;
Future<Result> future = executePool.submit(() -> get(gets.get(index)));
futures.add(future);
}
for (int i = 0; i < gets.size(); i++) {
try {
results[i] = futures.get(i).get();
} catch (Exception e) {
throw new RuntimeException("gets occur error. index:{" + i + "}", e);
}
}
}
return results;
}
/**
* hbase的获取这个rowkey,没有的话就前一个rowkey,不支持
* @param row row
* @param family family
* @return Result
*/
@Override
public Result getRowOrBefore(byte[] row, byte[] family) {
throw new FeatureNotSupportedException("not supported yet.");
}
@Override
public ResultScanner getScanner(final Scan scan) throws IOException {
if (scan.getFamilyMap().keySet().isEmpty()) {
// check nothing, use table group;
} else {
checkFamilyViolation(scan.getFamilyMap().keySet(), false);
}
//be careful about the packet size ,may the packet exceed the max result size ,leading to error
ServerCallable<ResultScanner> serverCallable = new ServerCallable<ResultScanner>(
configuration, obTableClient, tableNameString, scan.getStartRow(), scan.getStopRow(),
operationTimeout) {
public ResultScanner call() throws IOException {
byte[] family = new byte[] {};
ObTableClientQueryAsyncStreamResult clientQueryAsyncStreamResult;
ObTableQueryAsyncRequest request;
ObTableQuery obTableQuery;
ObHTableFilter filter;
try {
if (scan.getFamilyMap().keySet().isEmpty()
|| scan.getFamilyMap().size() > 1) {
// In a Scan operation where the family map is greater than 1 or equal to 0,
// we handle this by appending the column family to the qualifier on the client side.
// The server can then use this information to filter the appropriate column families and qualifiers.
if (!scan.getColumnFamilyTimeRange().isEmpty()) {
throw new FeatureNotSupportedException("setColumnFamilyTimeRange is only supported in single column family for now");
}
NavigableSet<byte[]> columnFilters = new TreeSet<>(Bytes.BYTES_COMPARATOR);