-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathObTableClient.java
3931 lines (3580 loc) · 179 KB
/
ObTableClient.java
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.alibaba.fastjson.JSON;
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.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.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 javax.sound.midi.SysexMessage;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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.LocationUtil.*;
import static com.alipay.oceanbase.rpc.location.model.ObServerRoute.STRONG_READ;
import static com.alipay.oceanbase.rpc.location.model.TableEntry.HBASE_ROW_KEY_ELEMENT;
import static com.alipay.oceanbase.rpc.location.model.partition.ObPartIdCalculator.*;
import static com.alipay.oceanbase.rpc.property.Property.*;
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 AtomicInteger tableEntryRefreshContinuousFailureCount = new AtomicInteger(
0);
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 OcpModel ocpModel = new OcpModel();
/*
* ServerAddr(all) -> ObTableConnection
*/
private volatile ConcurrentHashMap<ObServerAddr, ObTable> tableRoster = null;
/*
* current tenant server address order by priority desc
* <p>
* be careful about concurrency when change the element
*/
private final ServerRoster serverRoster = new ServerRoster();
private volatile RunningMode runningMode = RunningMode.NORMAL;
/*
* TableName -> TableEntry
*/
private Map<String, TableEntry> tableLocations = new ConcurrentHashMap<String, TableEntry>();
/*
* TableName -> ObIndexinfo
*/
private Map<String, ObIndexInfo> indexinfos = new ConcurrentHashMap<String, ObIndexInfo>();
private ConcurrentHashMap<String, Lock> refreshIndexInfoLocks = new ConcurrentHashMap<String, Lock>();
/*
* 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 ConcurrentHashMap<String, Lock> refreshTableLocks = new ConcurrentHashMap<String, Lock>();
private Lock refreshMetadataLock = new ReentrantLock();
private volatile long lastRefreshMetadataTimestamp;
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 ObTable odpTable = null;
// tableGroup <-> Table
private ConcurrentHashMap<String, Lock> TableGroupCacheLocks = new ConcurrentHashMap<String, Lock>();
private ConcurrentHashMap<String, String> TableGroupCache = new ConcurrentHashMap<String, String>(); // tableGroup -> Table
private ConcurrentHashMap<String, String> TableGroupInverted = new ConcurrentHashMap<String, String>(); // Table -> tableGroup
private RouteTableRefresher routeTableRefresher;
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();
// 5. run fresh table task
routeTableRefresher = new RouteTableRefresher(this);
routeTableRefresher.start();
initialized = true;
} catch (Throwable t) {
BOOT.warn("failed to init ObTableClient", t);
RUNTIME.warn("failed to init ObTableClient", t);
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 (routeTableRefresher != null) {
routeTableRefresher.finish();
}
if (tableRoster != null) {
Exception throwException = null;
List<ObServerAddr> exceptionObServers = new ArrayList<ObServerAddr>();
for (Map.Entry<ObServerAddr, ObTable> entry : tableRoster.entrySet()) {
try {
entry.getValue().close();
} catch (Exception e) {
// do not throw exception immediately
BOOT.error(LCD.convert("01-00004"), entry.getKey(), e);
RUNTIME.error(LCD.convert("01-00004"), entry.getKey(), e);
throwException = e;
exceptionObServers.add(entry.getKey());
}
}
if (exceptionObServers.size() > 0) {
StringBuilder sb = new StringBuilder();
sb.append("following ob servers [");
for (int i = 0; i < exceptionObServers.size(); i++) {
if (i != 0) {
sb.append(",");
}
sb.append(exceptionObServers.get(i));
}
sb.append("] close error.");
throw new ObTableCloseException(sb.toString(), throwException);
}
}
if (odpTable != null) {
odpTable.close();
}
} finally {
BOOT.info("ObTableClient is closed");
statusLock.unlock();
}
}
public RouteTableRefresher getRouteTableRefresher() {
return routeTableRefresher;
}
public Map<String, TableEntry> getTableLocations() {
return tableLocations;
}
/*
* 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);
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);
if (odpMode) {
try {
odpTable = new ObTable.Builder(odpAddr, odpPort) //
.setLoginInfo(tenantName, fullUserName, password, database) //
.setProperties(getProperties()).setConfigs(TableConfigs).build();
} 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;
}
this.ocpModel = loadOcpModel(paramURL, dataSourceName, rsListAcquireConnectTimeout,
rsListAcquireReadTimeout, rsListAcquireTryTimes, rsListAcquireRetryInterval);
List<ObServerAddr> servers = new ArrayList<ObServerAddr>();
ConcurrentHashMap<ObServerAddr, ObTable> tableRoster = new ConcurrentHashMap<ObServerAddr, ObTable>();
TableEntryKey rootServerKey = new TableEntryKey(clusterName, tenantName,
OCEANBASE_DATABASE, ALL_DUMMY_TABLE);
List<ObServerAddr> rsList = ocpModel.getObServerAddrs();
BOOT.info("{} success to get rsList, paramURL: {}, rsList: {},idc2Region: {}",
this.database, paramURL, JSON.toJSON(rsList), JSON.toJSON(ocpModel.getIdc2Region()));
TableEntry tableEntry = loadTableEntryRandomly(rsList,//
rootServerKey,//
tableEntryAcquireConnectTimeout,//
tableEntryAcquireSocketTimeout, sysUA, initialized);
BOOT.info("{} success to get tableEntry with rootServerKey all_dummy_tables {}",
this.database, JSON.toJSON(tableEntry));
List<ReplicaLocation> replicaLocations = tableEntry.getTableLocation()
.getReplicaLocations();
BOOT.info("{} success to get replicaLocation {}", this.database,
JSON.toJSON(replicaLocations));
for (ReplicaLocation replicaLocation : replicaLocations) {
ObServerInfo info = replicaLocation.getInfo();
ObServerAddr addr = replicaLocation.getAddr();
if (!info.isActive()) {
BOOT.warn("will not init location {} because status is {}", addr.toString(),
info.getStatus());
continue;
}
// 忽略初始化建连失败,否则client会初始化失败,导致应用无法启动的问题
// 初始化建连失败(可能性较小),如果后面这台server恢复,数据路由失败,就会重新刷新metadata
// 在失败100次后(RUNTIME_CONTINUOUS_FAILURE_CEILING),重新刷新建连
// 本地cache 1小时超时后(SERVER_ADDRESS_CACHING_TIMEOUT),重新刷新建连
// 应急可以直接observer切主
try {
ObTable obTable = new ObTable.Builder(addr.getIp(), addr.getSvrPort()) //
.setLoginInfo(tenantName, userName, password, database) //
.setProperties(getProperties()).setConfigs(TableConfigs).build();
tableRoster.put(addr, obTable);
servers.add(addr);
} catch (Exception e) {
BOOT.warn(
"The addr{}:{} failed to put into table roster, the node status may be wrong, Ignore",
addr.getIp(), addr.getSvrPort());
RUNTIME.warn("initMetadata meet exception", e);
e.printStackTrace();
}
}
if (servers.isEmpty()) {
BOOT.error("{} failed to connect any replicaLocation server: {}", this.database,
JSON.toJSON(replicaLocations));
throw new Exception("failed to connect any replicaLocation server");
}
BOOT.info("{} success to build server connection {}", this.database, JSON.toJSON(servers));
this.tableRoster = tableRoster;
this.serverRoster.reset(servers);
// Get Server LDC info for weak read consistency.
if (StringUtil.isEmpty(currentIDC)) {
currentIDC = ZoneUtil.getCurrentIDC();
}
String regionFromOcp = ocpModel.getIdc2Region(currentIDC);
BOOT.info("{} success get currentIDC {}, regionFromOcp {}", this.database, currentIDC,
regionFromOcp);
List<ObServerLdcItem> ldcServers = getServerLdc(serverRoster,
tableEntryAcquireConnectTimeout, tableEntryAcquireSocketTimeout,
serverAddressPriorityTimeout, serverAddressCachingTimeout, sysUA);
this.serverRoster.resetServerLdc(ObServerLdcLocation.buildLdcLocation(ldcServers,
currentIDC, regionFromOcp));
if (BOOT.isInfoEnabled()) {
BOOT.info("{} finish refresh serverRoster: {}", this.database,
JSON.toJSON(serverRoster));
BOOT.info("finish initMetadata for all tables for database {}", this.database);
}
this.lastRefreshMetadataTimestamp = System.currentTimeMillis();
}
public boolean isOdpMode() {
return odpMode;
}
public void setOdpMode(boolean odpMode) {
this.odpMode = odpMode;
}
public ObTable getOdpTable() {
return this.odpTable;
}
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(ObPair<Long, ObTableParam> obTable) 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");
}
boolean needRefreshTableEntry = false;
boolean needFetchAllRouteInfo = false;
int tryTimes = 0;
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++;
ObPair<Long, ObTableParam> obPair = null;
try {
if (odpMode) {
obPair = new ObPair<Long, ObTableParam>(0L, new ObTableParam(odpTable));
} else {
obPair = getTable(tableName, callback.getRowKey(),
needRefreshTableEntry, tableEntryRefreshIntervalWait,
needFetchAllRouteInfo, route);
}
T t = callback.execute(obPair);
resetExecuteContinuousFailureCount(tableName);
return t;
} catch (Exception ex) {
RUNTIME.error("execute while meet exception", ex);
if (odpMode) {
if ((tryTimes - 1) < runtimeRetryTimes) {
if (ex instanceof ObTableException) {
logger
.warn(
"execute while meet Exception, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
} else {
logger.warn("execute while meet Exception, errorMsg: {}, try times {}",
ex.getMessage(), tryTimes);
}
} else {
throw ex;
}
} else {
if (ex instanceof ObTableReplicaNotReadableException) {
if (obPair != null && (tryTimes - 1) < runtimeRetryTimes) {
logger.warn("retry when replica not readable: {}", ex.getMessage());
if (!odpMode) {
route.addToBlackList(obPair.getRight().getObTable().getIp());
}
} else {
logger.warn("exhaust retry when replica not readable: {}",
ex.getMessage());
RUNTIME.error("replica not readable", ex);
throw ex;
}
} else if (ex instanceof ObTableException
&& ((ObTableException) ex).isNeedRefreshTableEntry()) {
needRefreshTableEntry = true;
logger
.warn(
"refresh table while meet Exception needing refresh, errorCode: {}, errorMsg: {}",
((ObTableException) ex).getErrorCode(), ex.getMessage());
if (retryOnChangeMasterTimes && (tryTimes - 1) < runtimeRetryTimes) {
logger
.warn(
"retry while meet Exception needing refresh, errorCode: {} , errorMsg: {},retry times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
if (ex instanceof ObTableNeedFetchAllException) {
needFetchAllRouteInfo = true;
getOrRefreshTableEntry(tableName, true, true, true);
// reset failure count while fetch all route info
this.resetExecuteContinuousFailureCount(tableName);
}
} else {
calculateContinuousFailure(tableName, ex.getMessage());
throw ex;
}
} else {
calculateContinuousFailure(tableName, ex.getMessage());
throw ex;
}
}
}
Thread.sleep(runtimeRetryInterval);
}
}
private abstract class MutationExecuteCallback<T> {
private final Row rowKey;
private final List<ObNewRange> keyRanges;
MutationExecuteCallback(Row rowKey, List<ObNewRange> keyRanges) {
this.rowKey = rowKey;
this.keyRanges = keyRanges;
}
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(ObPair<Long, ObTableParam> obTable) throws Exception;
/*
* Get row key.
*/
public Row getRowKey() {
return rowKey;
}
/*
* Get key ranges.
*/
public List<ObNewRange> getKeyRanges() {
return keyRanges;
}
}
/**
* For mutation
*/
private <T> T executeMutation(String tableName, MutationExecuteCallback<T> callback)
throws Exception {
// force strong read by default, for backward compatibility.
return executeMutation(tableName, callback, getRoute(false));
}
/**
* Execute with a route strategy for mutation
*/
private <T> T executeMutation(String tableName, MutationExecuteCallback<T> callback,
ObServerRoute route) throws Exception {
if (tableName == null || tableName.isEmpty()) {
throw new IllegalArgumentException("table name is null");
}
boolean needRefreshTableEntry = false;
int tryTimes = 0;
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++;
ObPair<Long, ObTableParam> obPair = null;
try {
if (odpMode) {
obPair = new ObPair<Long, ObTableParam>(0L, new ObTableParam(odpTable));
} else {
if (null != callback.getRowKey()) {
// in the case of retry, the location always needs to be refreshed here
if (tryTimes > 1) {
TableEntry entry = getOrRefreshTableEntry(tableName, false, false, false);
Long partId = getPartition(entry, callback.getRowKey());
refreshTableLocationByTabletId(entry, tableName, getTabletIdByPartId(entry, partId));
}
// using row key
obPair = getTable(tableName, callback.getRowKey(), needRefreshTableEntry, tableEntryRefreshIntervalWait, false, route);
} else if (null != callback.getKeyRanges()) {
// using scan range
obPair = getTable(tableName, new ObTableQuery(),
callback.getKeyRanges());
} else {
throw new ObTableException("rowkey and scan range are null in mutation");
}
}
T t = callback.execute(obPair);
resetExecuteContinuousFailureCount(tableName);
return t;
} catch (Exception ex) {
RUNTIME.error("execute while meet exception", ex);
if (odpMode) {
if ((tryTimes - 1) < runtimeRetryTimes) {
if (ex instanceof ObTableException) {
logger
.warn(
"execute while meet Exception, errorCode: {} , errorMsg: {}, try times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
} else {
logger.warn(
"execute while meet Exception, exception: {}, try times {}", ex,
tryTimes);
}
} else {
throw ex;
}
} else {
if (ex instanceof ObTableReplicaNotReadableException) {
if (obPair != null && (tryTimes - 1) < runtimeRetryTimes) {
logger.warn("retry when replica not readable: {}", ex.getMessage());
if (!odpMode) {
route.addToBlackList(obPair.getRight().getObTable().getIp());
}
} else {
logger.warn("exhaust retry when replica not readable: {}",
ex.getMessage());
RUNTIME.error("replica not readable", ex);
throw ex;
}
} else if (ex instanceof ObTableException
&& ((ObTableException) ex).isNeedRefreshTableEntry()) {
// if the problem is the lack of row key name, throw directly
if (tableRowKeyElement.get(tableName) == null) {
throw ex;
}
needRefreshTableEntry = true;
logger
.warn(
"refresh table while meet Exception needing refresh, errorCode: {}, errorMsg: {}",
((ObTableException) ex).getErrorCode(), ex.getMessage());
if (retryOnChangeMasterTimes && (tryTimes - 1) < runtimeRetryTimes) {
logger
.warn(
"retry while meet Exception needing refresh, errorCode: {} , errorMsg: {},retry times {}",
((ObTableException) ex).getErrorCode(), ex.getMessage(),
tryTimes);
if (ex instanceof ObTableNeedFetchAllException) {
getOrRefreshTableEntry(tableName, needRefreshTableEntry, isTableEntryRefreshIntervalWait(), true);
// reset failure count while fetch all route info
this.resetExecuteContinuousFailureCount(tableName);
}
} else {
calculateContinuousFailure(tableName, ex.getMessage());
throw ex;
}
} else {
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);
getOrRefreshTableEntry(tableName, true, isTableEntryRefreshIntervalWait(), true);
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
* <p>
* 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() throws Exception {
if (System.currentTimeMillis() - lastRefreshMetadataTimestamp < metadataRefreshInterval) {
logger
.warn(
"try to lock metadata refreshing, it has refresh at: {}, dataSourceName: {}, url: {}",
lastRefreshMetadataTimestamp, dataSourceName, paramURL);
return;
}
boolean acquired = refreshMetadataLock.tryLock(metadataRefreshLockTimeout,
TimeUnit.MILLISECONDS);
if (!acquired) {
// TODO exception should be classified
String errMsg = "try to lock metadata refreshing timeout " + "dataSource:"
+ dataSourceName + " + refresh timeout:" + tableEntryRefreshLockTimeout
+ ".";
RUNTIME.error(errMsg);
throw new ObTableGetException(errMsg);
}
try {
if (System.currentTimeMillis() - lastRefreshMetadataTimestamp < metadataRefreshInterval) {
logger.warn("it has refresh metadata at: {}, dataSourceName: {}, url: {}",
lastRefreshMetadataTimestamp, dataSourceName, paramURL);
return;
}
if (logger.isInfoEnabled()) {
logger.info("start refresh metadata, ts: {}, dataSourceName: {}, url: {}",
lastRefreshMetadataTimestamp, dataSourceName, paramURL);
}
this.ocpModel = loadOcpModel(paramURL, //
dataSourceName,//
rsListAcquireConnectTimeout,//
rsListAcquireReadTimeout,//
rsListAcquireTryTimes, //
rsListAcquireRetryInterval);
TableEntryKey allDummyKey = new TableEntryKey(clusterName, tenantName,
OCEANBASE_DATABASE, ALL_DUMMY_TABLE);
List<ObServerAddr> rsList = ocpModel.getObServerAddrs();
TableEntry tableEntry = loadTableEntryRandomly(rsList,//
allDummyKey,//
tableEntryAcquireConnectTimeout,//
tableEntryAcquireSocketTimeout, sysUA, initialized);
List<ReplicaLocation> replicaLocations = tableEntry.getTableLocation()
.getReplicaLocations();
// update new ob table
List<ObServerAddr> servers = new ArrayList<ObServerAddr>();
for (ReplicaLocation replicaLocation : replicaLocations) {
ObServerAddr addr = replicaLocation.getAddr();
ObServerInfo info = replicaLocation.getInfo();
if (!info.isActive()) {
logger.warn("will not refresh location {} because status is {} stop time {}",
addr.toString(), info.getStatus(), info.getStopTime());
continue;
}
servers.add(addr);
if (tableRoster.containsKey(addr)) { // has ob table addr, continue
continue;
}
ObTable obTable = new ObTable.Builder(addr.getIp(), addr.getSvrPort()) //
.setLoginInfo(tenantName, userName, password, database) //
.setProperties(getProperties()).setConfigs(getTableConfigs())
.build();
ObTable oldObTable = tableRoster.putIfAbsent(addr, obTable); // not control concurrency
logger.warn("add new table addr, {}", addr.toString());
if (oldObTable != null) { // maybe create two ob table concurrently, close current ob table
obTable.close();
}
}
// clean useless ob table
for (ObServerAddr addr : tableRoster.keySet()) {