forked from oceanbase/obkv-table-client-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObTableClient.java
More file actions
3122 lines (2866 loc) · 141 KB
/
ObTableClient.java
File metadata and controls
3122 lines (2866 loc) · 141 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 Table Client Framework
* %%
* Copyright (C) 2021 OceanBase
* %%
* OBKV Table 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.rpc;
import com.alipay.oceanbase.rpc.bolt.transport.TransportCodes;
import com.alipay.oceanbase.rpc.checkandmutate.CheckAndInsUp;
import com.alipay.oceanbase.rpc.constant.Constants;
import com.alipay.oceanbase.rpc.exception.*;
import com.alipay.oceanbase.rpc.filter.ObTableFilter;
import com.alipay.oceanbase.rpc.get.Get;
import com.alipay.oceanbase.rpc.location.model.*;
import com.alipay.oceanbase.rpc.location.model.partition.*;
import com.alipay.oceanbase.rpc.mutation.*;
import com.alipay.oceanbase.rpc.protocol.payload.ObPayload;
import com.alipay.oceanbase.rpc.protocol.payload.Pcodes;
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.aggregation.ObTableAggregation;
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.ObBorderFlag;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.query.ObNewRange;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.query.ObTableQuery;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.query.ObTableQueryRequest;
import com.alipay.oceanbase.rpc.protocol.payload.impl.execute.syncquery.ObTableQueryAsyncRequest;
import com.alipay.oceanbase.rpc.table.*;
import com.alipay.oceanbase.rpc.table.api.TableBatchOps;
import com.alipay.oceanbase.rpc.table.api.TableQuery;
import com.alipay.oceanbase.rpc.threadlocal.ThreadLocalMap;
import com.alipay.oceanbase.rpc.util.*;
import com.alipay.remoting.util.StringUtils;
import org.slf4j.Logger;
import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static com.alipay.oceanbase.rpc.constant.Constants.*;
import static com.alipay.oceanbase.rpc.location.model.ObServerRoute.STRONG_READ;
import static com.alipay.oceanbase.rpc.property.Property.*;
import static com.alipay.oceanbase.rpc.protocol.payload.Constants.INVALID_TABLET_ID;
import static com.alipay.oceanbase.rpc.protocol.payload.impl.execute.ObTableOperationType.*;
import static com.alipay.oceanbase.rpc.util.TableClientLoggerFactory.*;
public class ObTableClient extends AbstractObTableClient implements Lifecycle {
private static final Logger logger = getLogger(ObTableClient.class);
private static final String usernameSeparators = ":;-;.";
private String dataSourceName;
private String paramURL;
/*
* user name
* Standard format: user@tenant#cluster
* NonStandard format: cluster:tenant:user
*/
private String fullUserName;
private String userName;
private String tenantName;
private String clusterName;
private String password;
private String database;
/*
* sys user auth to access meta table.
*/
private ObUserAuth sysUA = new ObUserAuth(
Constants.PROXY_SYS_USER_NAME,
"");
private volatile TableRoute tableRoute = null;
private volatile RunningMode runningMode = RunningMode.NORMAL;
/*
* TableName -> rowKey element
*/
private Map<String, Map<String, Integer>> tableRowKeyElement = new ConcurrentHashMap<String, Map<String, Integer>>();
private boolean retryOnChangeMasterTimes = true;
/*
* TableName -> Failures/Lock
*/
private ConcurrentHashMap<String, AtomicLong> tableContinuousFailures = new ConcurrentHashMap<String, AtomicLong>();
private volatile boolean initialized = false;
private volatile boolean closed = false;
private ReentrantLock statusLock = new ReentrantLock();
private String currentIDC;
private ObReadConsistency readConsistency = ObReadConsistency.STRONG;
private ObRoutePolicy obRoutePolicy = ObRoutePolicy.IDC_ORDER;
private boolean odpMode = false;
private String odpAddr = "127.0.0.1";
private int odpPort = 2883;
private Long clientId;
private Map<String, Object> TableConfigs = new HashMap<>();
/*
* Init.
*/
public void init() throws Exception {
if (initialized) {
return;
}
statusLock.lock();
try {
if (initialized) {
return;
}
// 1. init clientId
clientId = Math.abs(UUID.randomUUID().getLeastSignificantBits());
// 2. init table configs map
initTableConfigs();
// 3. init properties
initProperties();
// 4. init metadata
initMetadata();
initialized = true;
} catch (Throwable t) {
BOOT.warn("failed to init ObTableClient", t);
RUNTIME.warn("failed to init ObTableClient", t);
if (t instanceof ObTableException) {
throw t;
} else {
throw new RuntimeException(t);
}
} finally {
BOOT.info("init ObTableClient successfully");
statusLock.unlock();
}
}
/*
* Close.
*/
@Override
public void close() throws Exception {
if (closed) {
return;
}
statusLock.lock();
try {
if (closed) {
return;
}
closed = true;
if (tableRoute != null) {
tableRoute.close();
ObTable odpTable = tableRoute.getOdpTable();
if (odpTable != null) {
odpTable.close();
}
}
} finally {
BOOT.info("ObTableClient is closed");
statusLock.unlock();
}
}
/*
* Check status.
*/
public void checkStatus() throws IllegalStateException {
if (!initialized) {
throw new IllegalStateException("param url " + paramURL + "fullUserName "
+ fullUserName + " is not initialized");
}
if (closed) {
throw new IllegalStateException("param url " + paramURL + " fullUserName "
+ fullUserName + " is closed");
}
}
public Long getClientId() {
return clientId;
}
public Map<String, Object> getTableConfigs() {
return TableConfigs;
}
private void initTableConfigs() {
TableConfigs.put("client_id", clientId);
TableConfigs.put("runtime", new HashMap<String, String>());
TableConfigs.put("log", new HashMap<String, String>());
TableConfigs.put("route", new HashMap<String, String>());
TableConfigs.put("thread_pool", new HashMap<String, Boolean>());
}
private void initProperties() {
rpcConnectTimeout = parseToInt(RPC_CONNECT_TIMEOUT.getKey(), rpcConnectTimeout);
// metadata.refresh.interval is preferred.
metadataRefreshInterval = parseToLong(METADATA_REFRESH_INTERVAL.getKey(),
metadataRefreshInterval);
metadataRefreshInterval = parseToLong(METADATA_REFRESH_INTERNAL.getKey(),
metadataRefreshInterval);
metadataRefreshLockTimeout = parseToLong(METADATA_REFRESH_LOCK_TIMEOUT.getKey(),
metadataRefreshLockTimeout);
rsListAcquireConnectTimeout = parseToInt(RS_LIST_ACQUIRE_CONNECT_TIMEOUT.getKey(),
rsListAcquireConnectTimeout);
rsListAcquireReadTimeout = parseToInt(RS_LIST_ACQUIRE_READ_TIMEOUT.getKey(),
rsListAcquireReadTimeout);
rsListAcquireTryTimes = parseToInt(RS_LIST_ACQUIRE_TRY_TIMES.getKey(),
rsListAcquireTryTimes);
// rs.list.acquire.retry.interval is preferred.
rsListAcquireRetryInterval = parseToLong(RS_LIST_ACQUIRE_RETRY_INTERVAL.getKey(),
rsListAcquireRetryInterval);
rsListAcquireRetryInterval = parseToLong(RS_LIST_ACQUIRE_RETRY_INTERNAL.getKey(),
rsListAcquireRetryInterval);
tableEntryAcquireConnectTimeout = parseToLong(TABLE_ENTRY_ACQUIRE_CONNECT_TIMEOUT.getKey(),
tableEntryAcquireConnectTimeout);
tableEntryAcquireSocketTimeout = parseToLong(TABLE_ENTRY_ACQUIRE_SOCKET_TIMEOUT.getKey(),
tableEntryAcquireSocketTimeout);
// table.entry.refresh.interval.base is preferred.
tableEntryRefreshIntervalBase = parseToLong(TABLE_ENTRY_REFRESH_INTERVAL_BASE.getKey(),
tableEntryRefreshIntervalBase);
tableEntryRefreshIntervalBase = parseToLong(TABLE_ENTRY_REFRESH_INTERNAL_BASE.getKey(),
tableEntryRefreshIntervalBase);
// table.entry.refresh.interval.ceiling is preferred.
tableEntryRefreshIntervalCeiling = parseToLong(
TABLE_ENTRY_REFRESH_INTERVAL_CEILING.getKey(), tableEntryRefreshIntervalCeiling);
tableEntryRefreshIntervalCeiling = parseToLong(
TABLE_ENTRY_REFRESH_INTERNAL_CEILING.getKey(), tableEntryRefreshIntervalCeiling);
tableEntryRefreshIntervalWait = parseToBoolean(TABLE_ENTRY_REFRESH_INTERVAL_WAIT.getKey(),
tableEntryRefreshIntervalWait);
tableEntryRefreshLockTimeout = parseToLong(TABLE_ENTRY_REFRESH_LOCK_TIMEOUT.getKey(),
tableEntryRefreshLockTimeout);
ODPTableEntryRefreshLockTimeout = parseToLong(ODP_TABLE_ENTRY_REFRESH_LOCK_TIMEOUT.getKey(),
ODPTableEntryRefreshLockTimeout);
tableEntryRefreshTryTimes = parseToInt(TABLE_ENTRY_REFRESH_TRY_TIMES.getKey(),
tableEntryRefreshTryTimes);
tableEntryRefreshContinuousFailureCeiling = parseToInt(
TABLE_ENTRY_REFRESH_CONTINUOUS_FAILURE_CEILING.getKey(),
tableEntryRefreshContinuousFailureCeiling);
serverAddressPriorityTimeout = parseToLong(SERVER_ADDRESS_PRIORITY_TIMEOUT.getKey(),
serverAddressPriorityTimeout);
serverAddressCachingTimeout = parseToLong(SERVER_ADDRESS_CACHING_TIMEOUT.getKey(),
serverAddressCachingTimeout);
runtimeContinuousFailureCeiling = parseToInt(RUNTIME_CONTINUOUS_FAILURE_CEILING.getKey(),
runtimeContinuousFailureCeiling);
this.runtimeRetryTimes = parseToInt(RUNTIME_RETRY_TIMES.getKey(), this.runtimeRetryTimes);
runtimeRetryInterval = parseToInt(RUNTIME_RETRY_INTERVAL.getKey(), runtimeRetryInterval);
runtimeMaxWait = parseToLong(RUNTIME_MAX_WAIT.getKey(), runtimeMaxWait);
runtimeBatchMaxWait = parseToLong(RUNTIME_BATCH_MAX_WAIT.getKey(), runtimeBatchMaxWait);
rpcExecuteTimeout = parseToInt(RPC_EXECUTE_TIMEOUT.getKey(), rpcExecuteTimeout);
rpcLoginTimeout = parseToInt(RPC_LOGIN_TIMEOUT.getKey(), rpcLoginTimeout);
slowQueryMonitorThreshold = parseToLong(SLOW_QUERY_MONITOR_THRESHOLD.getKey(),
slowQueryMonitorThreshold);
maxConnExpiredTime = parseToLong(MAX_CONN_EXPIRED_TIME.getKey(), maxConnExpiredTime);
// add configs value to TableConfigs
// runtime
Object value = TableConfigs.get("runtime");
if (value instanceof Map) {
Map<String, String> runtimeMap = (Map<String, String>) value;
runtimeMap.put(RUNTIME_RETRY_TIMES.getKey(), String.valueOf(runtimeRetryTimes));
runtimeMap.put(RPC_EXECUTE_TIMEOUT.getKey(), String.valueOf(rpcExecuteTimeout));
runtimeMap.put(RUNTIME_MAX_WAIT.getKey(), String.valueOf(runtimeMaxWait));
runtimeMap.put(RUNTIME_RETRY_INTERVAL.getKey(), String.valueOf(runtimeRetryInterval));
runtimeMap.put(RUNTIME_RETRY_TIMES.getKey(), String.valueOf(runtimeRetryTimes));
runtimeMap.put(MAX_CONN_EXPIRED_TIME.getKey(), String.valueOf(maxConnExpiredTime));
}
// log
value = TableConfigs.get("log");
if (value instanceof Map) {
Map<String, String> logMap = (Map<String, String>) value;
logMap.put(SLOW_QUERY_MONITOR_THRESHOLD.getKey(), String.valueOf(slowQueryMonitorThreshold));
}
value = TableConfigs.get("route");
if (value instanceof Map) {
Map<String, String> routeMap = (Map<String, String>) value;
routeMap.put(METADATA_REFRESH_INTERVAL.getKey(), String.valueOf(metadataRefreshInterval));
routeMap.put(RUNTIME_CONTINUOUS_FAILURE_CEILING.getKey(), String.valueOf(runtimeContinuousFailureCeiling));
routeMap.put(SERVER_ADDRESS_CACHING_TIMEOUT.getKey(), String.valueOf(serverAddressCachingTimeout));
routeMap.put(SERVER_ADDRESS_PRIORITY_TIMEOUT.getKey(), String.valueOf(serverAddressPriorityTimeout));
routeMap.put(TABLE_ENTRY_ACQUIRE_CONNECT_TIMEOUT.getKey(), String.valueOf(tableEntryAcquireConnectTimeout));
routeMap.put(TABLE_ENTRY_ACQUIRE_SOCKET_TIMEOUT.getKey(), String.valueOf(tableEntryAcquireSocketTimeout));
routeMap.put(TABLE_ENTRY_REFRESH_INTERVAL_BASE.getKey(), String.valueOf(tableEntryRefreshIntervalBase));
routeMap.put(TABLE_ENTRY_REFRESH_INTERVAL_CEILING.getKey(), String.valueOf(tableEntryRefreshIntervalCeiling));
routeMap.put(TABLE_ENTRY_REFRESH_TRY_TIMES.getKey(), String.valueOf(tableEntryRefreshTryTimes));
}
Boolean useExecutor = false;
if (runtimeBatchExecutor != null) {
useExecutor = true;
}
value = TableConfigs.get("thread_pool");
if (value instanceof Map) {
Map<String, Boolean> threadPoolMap = (Map<String, Boolean>) value;
threadPoolMap.put(RUNTIME_BATCH_EXECUTOR.getKey(), useExecutor);
}
}
private void initMetadata() throws Exception {
BOOT.info("begin initMetadata for all tables in database: {}", this.database);
this.tableRoute = new TableRoute(this, sysUA);
if (odpMode) {
try {
tableRoute.buildOdpInfo(odpAddr, odpPort, runningMode);
} catch (Exception e) {
logger
.warn(
"The addr{}:{} failed to put into table roster, the node status may be wrong, Ignore",
odpAddr, odpPort);
throw e;
}
return;
}
// build ConfigServerInfo to get rsList
tableRoute.loadConfigServerInfo();
// build tableRoster and ServerRoster
TableEntryKey rootServerKey = new TableEntryKey(clusterName, tenantName,
OCEANBASE_DATABASE, ALL_DUMMY_TABLE);
tableRoute.initRoster(rootServerKey, initialized, runningMode);
// create background refresh-checker task
tableRoute.launchRouteRefresher();
}
public boolean isOdpMode() {
return odpMode;
}
public void setOdpMode(boolean odpMode) {
this.odpMode = odpMode;
}
public ObTable getOdpTable() {
if (tableRoute != null) {
return tableRoute.getOdpTable();
}
return null;
}
private abstract class TableExecuteCallback<T> {
private final Object[] rowKey;
TableExecuteCallback(Object[] rowKey) {
this.rowKey = rowKey;
}
void checkObTableOperationResult(String ip, int port, ObPayload request, ObPayload result) {
if (result == null) {
RUNTIME.error("client get unexpected NULL result");
throw new ObTableException("client get unexpected NULL result");
}
if (!(result instanceof ObTableOperationResult)) {
RUNTIME.error("client get unexpected result: " + result.getClass().getName());
throw new ObTableException("client get unexpected result: "
+ result.getClass().getName());
}
ObTableOperationResult obTableOperationResult = (ObTableOperationResult) result;
ObTableOperationRequest obTableOperationRequest = (ObTableOperationRequest) request;
obTableOperationResult.setExecuteHost(ip);
obTableOperationResult.setExecutePort(port);
long sequence = obTableOperationResult.getSequence() == 0 ? obTableOperationRequest
.getSequence() : obTableOperationResult.getSequence();
long uniqueId = obTableOperationResult.getUniqueId() == 0 ? obTableOperationRequest
.getUniqueId() : obTableOperationResult.getUniqueId();
ExceptionUtil.throwObTableException(ip, port, sequence, uniqueId,
obTableOperationResult.getHeader().getErrno(), obTableOperationResult.getHeader()
.getErrMsg());
}
void checkObTableQueryAndMutateResult(String ip, int port, ObPayload result) {
if (result == null) {
RUNTIME.error("client get unexpected NULL result");
throw new ObTableException("client get unexpected NULL result");
}
if (!(result instanceof ObTableQueryAndMutateResult)) {
RUNTIME.error("client get unexpected result: " + result.getClass().getName());
throw new ObTableException("client get unexpected result: "
+ result.getClass().getName());
}
// TODO: Add func like throwObTableException()
// which will output the ip / port / error information
}
abstract T execute(ObTableParam tableParam) throws Exception;
/*
* Get row key.
*/
public Object[] getRowKey() {
return this.rowKey;
}
}
private <T> T execute(String tableName, TableExecuteCallback<T> callback) throws Exception {
// force strong read by default, for backward compatibility.
return execute(tableName, callback, getRoute(false));
}
/**
* Execute with a route strategy.
*/
private <T> T execute(String tableName, TableExecuteCallback<T> callback, ObServerRoute route)
throws Exception {
if (tableName == null || tableName.isEmpty()) {
throw new IllegalArgumentException("table name is null");
}
int tryTimes = 0;
boolean needRefreshPartitionLocation = false;
long startExecute = System.currentTimeMillis();
Row rowKey = odpMode ? null : transformToRow(tableName, callback.getRowKey());
while (true) {
checkStatus();
long currentExecute = System.currentTimeMillis();
long costMillis = currentExecute - startExecute;
if (costMillis > runtimeMaxWait) {
throw new ObTableTimeoutExcetion("it has tried " + tryTimes
+ " times and it has waited " + costMillis
+ "/ms which exceeds response timeout "
+ runtimeMaxWait + "/ms");
}
tryTimes++;
ObTableParam tableParam = null;
try {
if (odpMode) {
ObTable odpTable = tableRoute.getOdpTable();
tableParam = new ObTableParam(odpTable);
} else {
if (tryTimes > 1 && needRefreshPartitionLocation) {
needRefreshPartitionLocation = false;
// refresh partition location
TableEntry entry = tableRoute.getTableEntry(tableName);
long partId = tableRoute.getPartId(entry, rowKey);
long tabletId = tableRoute.getTabletIdByPartId(entry, partId);
tableRoute.refreshPartitionLocation(tableName, tabletId, entry);
}
tableParam = getTableParamWithRoute(tableName, rowKey, route);
}
logger.debug("tableName: {}, tableParam obTable ip:port is {}:{}, ls_id: {}, tablet_id: {}",
tableName, tableParam.getObTable().getIp(), tableParam.getObTable().getPort(), tableParam.getLsId(), tableParam.getTabletId());
T t = callback.execute(tableParam);
resetExecuteContinuousFailureCount(tableName);
return t;
} catch (Exception ex) {
if (odpMode) {
// about routing problems, ODP will retry on their side
if (ex instanceof ObTableException) {
// errors needed to retry will retry until timeout
if (((ObTableException) ex).isNeedRetryError()) {
logger.warn(
"execute while meet server error in odp mode, need to retry, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
} else {
logger.warn("meet table exception when execute in odp mode." +
"tablename: {}, errMsg: {}", tableName, ex.getMessage());
throw ex;
}
} else {
logger.warn("meet exception when execute in odp mode." +
"tablename: {}, errMsg: {}", tableName, ex.getMessage());
throw ex;
}
} else {
needRefreshPartitionLocation = true;
if (ex instanceof ObTableReplicaNotReadableException) {
if (tableParam != null && System.currentTimeMillis() - startExecute < runtimeMaxWait) {
logger.warn("retry when replica not readable: {}", ex.getMessage());
route.addToBlackList(tableParam.getObTable().getIp());
} else {
logger.warn("timeout, cause replica is not readable, tryTimes={}", tryTimes);
RUNTIME.error("replica not readable", ex);
throw ex;
}
} else if (ex instanceof ObTableException
&& (((ObTableException) ex).isNeedRefreshTableEntry() || ((ObTableException) ex).isNeedRetryError())) {
if (ex instanceof ObTableNotExistException) {
String logMessage = String.format(
"exhaust retry while meet TableNotExist Exception, table name: %s, errorCode: %d",
tableName,
((ObTableException) ex).getErrorCode()
);
logger.warn(logMessage, ex);
throw ex;
}
if (retryOnChangeMasterTimes) {
if (ex instanceof ObTableNeedFetchMetaException) {
tableRoute.refreshMeta(tableName);
// reset failure count while fetch all route info
this.resetExecuteContinuousFailureCount(tableName);
} else if (((ObTableException) ex).isNeedRetryError()) {
// retry server errors, no need to refresh partition location
needRefreshPartitionLocation = false;
logger.warn(
"execute while meet server error, need to retry, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
}
} else {
String logMessage = String.format(
"retry is disabled while meet NeedRefresh Exception, table name: %s, errorCode: %d",
tableName,
((ObTableException) ex).getErrorCode()
);
logger.warn(logMessage, ex);
calculateContinuousFailure(tableName, ex.getMessage());
throw ex;
}
} else {
String logMessage;
if (ex instanceof ObTableException) {
logMessage = String.format(
"exhaust retry while meet Exception, table name: %s, batch ops refresh table, errorCode: %d",
tableName,
((ObTableException) ex).getErrorCode()
);
} else {
logMessage = String.format(
"exhaust retry while meet Exception, table name: %s, batch ops refresh table",
tableName
);
}
logger.warn(logMessage, ex);
if (ex instanceof ObTableTransportException &&
((ObTableTransportException) ex).getErrorCode() == TransportCodes.BOLT_TIMEOUT) {
logger.debug("client execute meet transport timeout, obTable ip:port is {}:{}",
tableParam.getObTable().getIp(), tableParam.getObTable().getPort());
syncRefreshMetadata(true);
TableEntry entry = tableRoute.getTableEntry(tableName);
long partId = tableRoute.getPartId(entry, rowKey);
long tabletId = tableRoute.getTabletIdByPartId(entry, partId);
tableRoute.refreshPartitionLocation(tableName, tabletId, entry);
tableParam.getObTable().setDirty();
}
calculateContinuousFailure(tableName, ex.getMessage());
throw ex;
}
}
}
Thread.sleep(runtimeRetryInterval);
}
}
private abstract class OperationExecuteCallback<T> {
private final Row rowKey;
private final TableQuery query;
OperationExecuteCallback(Row rowKey, TableQuery query) {
this.rowKey = rowKey;
this.query = query;
}
void checkResult(String ip, int port, ObPayload request, ObPayload result) {
if (result == null) {
RUNTIME.error("client get unexpected NULL result");
throw new ObTableException("client get unexpected NULL result");
}
if (result instanceof ObTableOperationResult) {
ObTableOperationResult obTableOperationResult = (ObTableOperationResult) result;
ObTableOperationRequest obTableOperationRequest = (ObTableOperationRequest) request;
obTableOperationResult.setExecuteHost(ip);
obTableOperationResult.setExecutePort(port);
long sequence = obTableOperationResult.getSequence() == 0 ? obTableOperationRequest
.getSequence() : obTableOperationResult.getSequence();
long uniqueId = obTableOperationResult.getUniqueId() == 0 ? obTableOperationRequest
.getUniqueId() : obTableOperationResult.getUniqueId();
ExceptionUtil.throwObTableException(ip, port, sequence, uniqueId,
obTableOperationResult.getHeader().getErrno(), obTableOperationResult
.getHeader().getErrMsg());
} else if (result instanceof ObTableQueryAndMutateResult) {
// TODO: Add func like throwObTableException()
// which will output the ip / port / error information
} else {
RUNTIME.error("client get unexpected result: " + result.getClass().getName());
throw new ObTableException("client get unexpected result: "
+ result.getClass().getName());
}
}
abstract T execute(ObTableParam tableParam) throws Exception;
/*
* Get row key.
*/
public Row getRowKey() {
return rowKey;
}
/*
* Get key ranges.
*/
public TableQuery getQuery() {
return query;
}
}
/**
* For mutation
*/
private <T> T execute(String tableName, OperationExecuteCallback<T> callback)
throws Exception {
// force strong read by default, for backward compatibility.
return execute(tableName, callback, getRoute(false));
}
/**
* Execute with a route strategy for mutation
*/
private <T> T execute(String tableName, OperationExecuteCallback<T> callback,
ObServerRoute route) throws Exception {
if (tableName == null || tableName.isEmpty()) {
throw new IllegalArgumentException("table name is null");
}
int tryTimes = 0;
boolean needRefreshPartitionLocation = false;
long startExecute = System.currentTimeMillis();
while (true) {
checkStatus();
long currentExecute = System.currentTimeMillis();
long costMillis = currentExecute - startExecute;
if (costMillis > runtimeMaxWait) {
throw new ObTableTimeoutExcetion("it has tried " + tryTimes
+ " times and it has waited " + costMillis
+ "/ms which exceeds response timeout "
+ runtimeMaxWait + "/ms");
}
tryTimes++;
ObTableParam tableParam = null;
try {
if (odpMode) {
if (null == callback.getRowKey() && null == callback.getQuery()) {
throw new ObTableException("RowKey or scan range is null");
}
ObTable odpTable = tableRoute.getOdpTable();
tableParam = new ObTableParam(odpTable);
} else {
if (null != callback.getRowKey()) {
if (tryTimes > 1 && needRefreshPartitionLocation) {
needRefreshPartitionLocation = false;
// refresh partition location
TableEntry entry = tableRoute.getTableEntry(tableName);
long partId = tableRoute.getPartId(entry, callback.getRowKey());
long tabletId = tableRoute.getTabletIdByPartId(entry, partId);
tableRoute.refreshPartitionLocation(tableName, tabletId, entry);
}
// using row key
tableParam = tableRoute.getTableParamWithRoute(tableName, callback.getRowKey(), route);
} else if (null != callback.getQuery()) {
if (tryTimes > 1 && needRefreshPartitionLocation) {
needRefreshPartitionLocation = false;
boolean isHKV = callback.getQuery().getEntityType() == ObTableEntityType.HKV;
tableRoute.refreshTabletLocationForAtomicQuery(tableName, callback.getQuery().getObTableQuery(), isHKV);
}
ObTableQuery tableQuery = callback.getQuery().getObTableQuery();
// using scan range
tableParam = tableRoute.getTableParam(tableName, tableQuery.getScanRangeColumns(),
tableQuery.getKeyRanges());
} else {
throw new ObTableException("RowKey or scan range is null");
}
}
logger.debug("tableName: {}, tableParam obTable ip:port is {}:{}, ls_id: {}, tablet_id: {}",
tableName, tableParam.getObTable().getIp(), tableParam.getObTable().getPort(), tableParam.getLsId(), tableParam.getTabletId());
T t = callback.execute(tableParam);
resetExecuteContinuousFailureCount(tableName);
return t;
} catch (Exception ex) {
RUNTIME.error("execute while meet exception", ex);
if (odpMode) {
// about routing problems, ODP will retry on their side
if (ex instanceof ObTableException) {
// errors needed to retry will retry until timeout
if (((ObTableException) ex).isNeedRetryError()) {
logger.warn(
"execute while meet server error in odp mode, need to retry, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
} else {
logger.warn("meet table exception when execute in odp mode." +
"tablename: {}, errMsg: {}", tableName, ex.getMessage());
throw ex;
}
} else {
logger.warn("meet exception when execute in odp mode." +
"tablename: {}, errMsg: {}", tableName, ex.getMessage());
throw ex;
}
} else {
needRefreshPartitionLocation = true;
if (ex instanceof ObTableReplicaNotReadableException) {
if (tableParam != null && System.currentTimeMillis() - startExecute > runtimeMaxWait) {
logger.warn("retry when replica not readable: {}", ex.getMessage());
route.addToBlackList(tableParam.getObTable().getIp());
} else {
logger.warn("timeout, cause replica is not readable, tryTimes={}", tryTimes);
RUNTIME.error("replica not readable", ex);
throw ex;
}
} else if (ex instanceof ObTableException
&& (((ObTableException) ex).isNeedRefreshTableEntry() || ((ObTableException) ex).isNeedRetryError())) {
if (ex instanceof ObTableNotExistException) {
String logMessage = String.format(
"exhaust retry while meet TableNotExist Exception, table name: %s, errorCode: %d",
tableName,
((ObTableException) ex).getErrorCode()
);
logger.warn(logMessage, ex);
throw ex;
}
if (retryOnChangeMasterTimes) {
if (ex instanceof ObTableNeedFetchMetaException) {
logger.warn("execute while meet need fetch meta error, need to retry, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
tableRoute.refreshMeta(tableName);
// reset failure count while fetch all route info
this.resetExecuteContinuousFailureCount(tableName);
} else if (((ObTableException) ex).isNeedRetryError()) {
// retry server errors, no need to refresh partition location
needRefreshPartitionLocation = false;
logger.warn(
"execute while meet server error, need to retry, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
}
} else {
String logMessage = String.format(
"retry is disabled while meet NeedRefresh Exception, table name: %s, errorCode: %d",
tableName,
((ObTableException) ex).getErrorCode()
);
logger.warn(logMessage, ex);
calculateContinuousFailure(tableName, ex.getMessage());
throw new ObTableRetryExhaustedException(logMessage, ex);
}
} else {
String logMessage;
if (ex instanceof ObTableException) {
logMessage = String.format(
"exhaust retry while meet Exception, table name: %s, batch ops refresh table, errorCode: %d",
tableName,
((ObTableException) ex).getErrorCode()
);
} else {
logMessage = String.format(
"exhaust retry while meet Exception, table name: %s, batch ops refresh table",
tableName
);
}
logger.warn(logMessage, ex);
if (ex instanceof ObTableTransportException &&
((ObTableTransportException) ex).getErrorCode() == TransportCodes.BOLT_TIMEOUT) {
logger.debug("client execute meet transport timeout, obTable ip:port is {}:{}",
tableParam.getObTable().getIp(), tableParam.getObTable().getPort());
syncRefreshMetadata(true);
TableEntry entry = tableRoute.getTableEntry(tableName);
long partId = tableRoute.getPartId(entry, callback.getRowKey());
long tabletId = tableRoute.getTabletIdByPartId(entry, partId);
tableRoute.refreshPartitionLocation(tableName, tabletId, entry);
tableParam.getObTable().setDirty();
}
calculateContinuousFailure(tableName, ex.getMessage());
throw ex;
}
}
}
Thread.sleep(runtimeRetryInterval);
}
}
/**
* Calculate continuous failure.
* @param tableName table name
* @param errorMsg err msg
* @throws Exception if failed
*/
public void calculateContinuousFailure(String tableName, String errorMsg) throws Exception {
AtomicLong tempFailures = new AtomicLong();
AtomicLong failures = tableContinuousFailures.putIfAbsent(tableName, tempFailures);
failures = (failures == null) ? tempFailures : failures; // check the first failure
if (failures.incrementAndGet() > runtimeContinuousFailureCeiling) {
logger.warn("refresh table entry {} while execute failed times exceeded {}, msg: {}",
tableName, runtimeContinuousFailureCeiling, errorMsg);
refreshMeta(tableName);
failures.set(0);
} else {
logger.warn("error msg: {}, current continues failure count: {}", errorMsg, failures);
}
}
/**
* Reset execute continuous failure count.
* @param tableName table name
*/
public void resetExecuteContinuousFailureCount(String tableName) {
AtomicLong failures = tableContinuousFailures.get(tableName);
if (failures != null) {
failures.set(0);
}
}
/**
* refresh all ob server synchronized just in case rslist has changed, it will not refresh if last refresh time is 1 min ago
* @param forceRefresh flag to force refresh the rsList if changes happen
* 1. cannot find table from tables, need refresh tables
* 2. server list refresh failed: {see com.alipay.oceanbase.obproxy.resource.ObServerStateProcessor#MAX_REFRESH_FAILURE}
*
* @throws Exception if fail
*/
public void syncRefreshMetadata(boolean forceRefresh) throws Exception {// do not refresh within 5 seconds even if forceRenew
checkStatus();
long lastRefreshMetadataTimestamp = tableRoute.getLastRefreshMetadataTimestamp();
if (System.currentTimeMillis() - lastRefreshMetadataTimestamp < tableEntryRefreshLockTimeout) {
logger
.warn(
"have to wait for more than {} seconds to refresh metadata, it has refreshed at: {}",
tableEntryRefreshLockTimeout, lastRefreshMetadataTimestamp);
return;
}
if (!forceRefresh
&& System.currentTimeMillis() - lastRefreshMetadataTimestamp < metadataRefreshInterval) {
logger
.warn(
"try to refresh metadata but need to wait, it has refreshed at: {}, dataSourceName: {}, url: {}",
lastRefreshMetadataTimestamp, dataSourceName, paramURL);
return;
}
Lock refreshMetaLock = tableRoute.refreshTableRosterLock;
boolean acquired = refreshMetaLock.tryLock(
metadataRefreshLockTimeout, TimeUnit.MILLISECONDS);
if (!acquired) {
String errMsg = "try to lock rsList refreshing timeout " + " refresh timeout: "
+ metadataRefreshLockTimeout + ".";
RUNTIME.error(errMsg);
// if not acquire lock, means that another thread is refreshing rsList and table roster
// after refreshing, new table roster can be shared by all threads
return;
}
try {
// double check timestamp
lastRefreshMetadataTimestamp = tableRoute.getLastRefreshMetadataTimestamp();
if (System.currentTimeMillis() - lastRefreshMetadataTimestamp < tableEntryRefreshLockTimeout) {
logger
.warn(
"have to wait for more than {} seconds to refresh metadata, it has refreshed at: {}",
tableEntryRefreshLockTimeout, lastRefreshMetadataTimestamp);
return;
}
if (!forceRefresh
&& System.currentTimeMillis() - lastRefreshMetadataTimestamp < metadataRefreshInterval) {
logger
.warn(
"try to refresh metadata but need to wait, it has refreshed at: {}, dataSourceName: {}, url: {}",
lastRefreshMetadataTimestamp, dataSourceName, paramURL);
return;
}
ConfigServerInfo newConfigServer = tableRoute.loadConfigServerInfo();
tableRoute.refreshRosterByRsList(newConfigServer.getRsList());
} finally {
refreshMetaLock.unlock();
}
}
/*
* return the table name that need get location
* for global index: return global index table name
* others: return primary table name
* @param dataTableName table name
* @param indexName used index name
* @param scanRangeColumns columns that need to be scaned
* @return the real table name
*/
public String getIndexTableName(final String dataTableName, final String indexName,
List<String> scanRangeColumns, boolean forceRefreshIndexInfo)
throws Exception {
return tableRoute.getIndexTableName(dataTableName, indexName, scanRangeColumns, forceRefreshIndexInfo);
}
public void eraseTableEntry(String tableName) {
tableRoute.eraseTableEntry(tableName);
}
@Override
public void setRpcExecuteTimeout(int rpcExecuteTimeout) {
this.properties.put(RPC_EXECUTE_TIMEOUT.getKey(), String.valueOf(rpcExecuteTimeout));
this.rpcExecuteTimeout = rpcExecuteTimeout;
if (tableRoute != null) {
ConcurrentHashMap<ObServerAddr, ObTable> tableRoster = tableRoute.getTableRoster().getTables();
if (null != tableRoster) {
for (ObTable obTable : tableRoster.values()) {
if (obTable != null) {
obTable.setObTableExecuteTimeout(rpcExecuteTimeout);
}
}
}
ObTable odpTable = tableRoute.getOdpTable();
if (null != odpTable) {
odpTable.setObTableExecuteTimeout(rpcExecuteTimeout);
}
}
}
/**
* Get or refresh table entry meta information.
* @param tableName table name
* @return TableEntry
* @throws Exception if fail
*/
public TableEntry getOrRefreshTableEntry(final String tableName, boolean forceRefresh)
throws Exception {
if (!forceRefresh) {
return tableRoute.getTableEntry(tableName);
}
return refreshMeta(tableName);
}
/**
* refresh table meta information except location
* @param tableName table name
* */
private TableEntry refreshMeta(String tableName) throws Exception {
return tableRoute.refreshMeta(tableName);
}
/**
* refresh table meta information except location
* only support by ODP version after 4.3.2
* @param tableName table name
* */
public TableEntry refreshOdpMeta(String tableName) throws Exception {
return tableRoute.refreshOdpMeta(tableName, true);
}
/**
* Refresh tablet location by tabletId
* @param tableName table name
* @param tabletId real tablet id
* @return TableEntry
* @throws Exception
* */
public TableEntry refreshTableLocationByTabletId(String tableName, Long tabletId) throws Exception {
return tableRoute.refreshPartitionLocation(tableName, tabletId, null);
}