ConfigInitializer.java
11.4 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
/*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.config;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import io.mycat.config.loader.zkprocess.comm.ZkConfig;
import io.mycat.config.loader.zkprocess.comm.ZkParamCfg;
import org.apache.log4j.Logger;
import io.mycat.backend.datasource.PhysicalDBNode;
import io.mycat.backend.datasource.PhysicalDBPool;
import io.mycat.backend.datasource.PhysicalDatasource;
import io.mycat.backend.jdbc.JDBCDatasource;
import io.mycat.backend.mysql.nio.MySQLDataSource;
import io.mycat.backend.postgresql.PostgreSQLDataSource;
import io.mycat.config.loader.ConfigLoader;
import io.mycat.config.loader.SchemaLoader;
import io.mycat.config.loader.xml.XMLConfigLoader;
import io.mycat.config.loader.xml.XMLSchemaLoader;
import io.mycat.config.model.DBHostConfig;
import io.mycat.config.model.DataHostConfig;
import io.mycat.config.model.DataNodeConfig;
import io.mycat.config.model.FirewallConfig;
import io.mycat.config.model.SchemaConfig;
import io.mycat.config.model.SystemConfig;
import io.mycat.config.model.UserConfig;
import io.mycat.config.util.ConfigException;
import io.mycat.route.sequence.handler.DistributedSequenceHandler;
import io.mycat.route.sequence.handler.IncrSequenceMySQLHandler;
import io.mycat.route.sequence.handler.IncrSequenceTimeHandler;
import io.mycat.route.sequence.handler.IncrSequenceZKHandler;
/**
* @author mycat
*/
public class ConfigInitializer {
private static final Logger LOGGER = Logger.getLogger( ConfigInitializer.class );
private volatile SystemConfig system;
private volatile MycatCluster cluster;
private volatile FirewallConfig firewall;
private volatile Map<String, UserConfig> users;
private volatile Map<String, SchemaConfig> schemas;
private volatile Map<String, PhysicalDBNode> dataNodes;
private volatile Map<String, PhysicalDBPool> dataHosts;
public ConfigInitializer(boolean loadDataHost) {
//读取rule.xml和schema.xml
SchemaLoader schemaLoader = new XMLSchemaLoader();
//读取server.xml
XMLConfigLoader configLoader = new XMLConfigLoader(schemaLoader);
schemaLoader = null;
//加载配置
this.system = configLoader.getSystemConfig();
this.users = configLoader.getUserConfigs();
this.schemas = configLoader.getSchemaConfigs();
//是否重新加载DataHost和对应的DataNode
if (loadDataHost) {
this.dataHosts = initDataHosts(configLoader);
this.dataNodes = initDataNodes(configLoader);
}
//权限管理
this.firewall = configLoader.getFirewallConfig();
this.cluster = initCobarCluster(configLoader);
//不同类型的全局序列处理器的配置加载
if (system.getSequnceHandlerType() == SystemConfig.SEQUENCEHANDLER_MYSQLDB) {
IncrSequenceMySQLHandler.getInstance().load();
}
if (system.getSequnceHandlerType() == SystemConfig.SEQUENCEHANDLER_LOCAL_TIME) {
IncrSequenceTimeHandler.getInstance().load();
}
if (system.getSequnceHandlerType() == SystemConfig.SEQUENCEHANDLER_ZK_DISTRIBUTED) {
DistributedSequenceHandler.getInstance(system).load();
}
if (system.getSequnceHandlerType() == SystemConfig.SEQUENCEHANDLER_ZK_GLOBAL_INCREMENT) {
IncrSequenceZKHandler.getInstance().load();
}
/**
* 配置文件初始化, 自检
*/
this.selfChecking0();
}
private void selfChecking0() throws ConfigException {
// 检查user与schema配置对应以及schema配置不为空
if (users == null || users.isEmpty()) {
throw new ConfigException("SelfCheck### user all node is empty!");
} else {
for (UserConfig uc : users.values()) {
if (uc == null) {
throw new ConfigException("SelfCheck### users node within the item is empty!");
}
Set<String> authSchemas = uc.getSchemas();
if (authSchemas == null) {
throw new ConfigException("SelfCheck### user " + uc.getName() + "refered schemas is empty!");
}
for (String schema : authSchemas) {
if ( !schemas.containsKey(schema) ) {
String errMsg = "SelfCheck### schema " + schema + " refered by user " + uc.getName() + " is not exist!";
throw new ConfigException(errMsg);
}
}
}
}
// schema 配置检测
for (SchemaConfig sc : schemas.values()) {
if (null == sc) {
throw new ConfigException("SelfCheck### schema all node is empty!");
} else {
// check dataNode / dataHost 节点
if ( this.dataNodes != null && this.dataHosts != null ) {
Set<String> dataNodeNames = sc.getAllDataNodes();
for(String dataNodeName: dataNodeNames) {
PhysicalDBNode node = this.dataNodes.get(dataNodeName);
if ( node == null ) {
throw new ConfigException("SelfCheck### schema dbnode is empty!");
}
}
}
}
}
}
public void testConnection() {
// 实际链路的连接测试
if ( this.dataNodes != null && this.dataHosts != null ) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
for(PhysicalDBNode dataNode: dataNodes.values() ) {
String database = dataNode.getDatabase();
PhysicalDBPool pool = dataNode.getDbPool();
for (PhysicalDatasource ds : pool.getAllDataSources()) {
String key = ds.getName() + "_" + database;
if ( map.get( key ) == null ) {
map.put( key, false );
boolean isConnected = false;
try {
isConnected = ds.testConnection( database );
map.put( key, isConnected );
} catch (IOException e) {
LOGGER.warn("test conn error:", e);
}
}
}
}
//
boolean isConnectivity = true;
for (Map.Entry<String, Boolean> entry : map.entrySet()) {
String key = entry.getKey();
Boolean value = entry.getValue();
if ( !value && isConnectivity ) {
LOGGER.warn("SelfCheck### test " + key + " database connection failed ");
isConnectivity = false;
} else {
LOGGER.info("SelfCheck### test " + key + " database connection success ");
}
}
if ( !isConnectivity ) {
throw new ConfigException("SelfCheck### there are some datasource connection failed, pls check!");
}
}
}
public SystemConfig getSystem() {
return system;
}
public MycatCluster getCluster() {
return cluster;
}
public FirewallConfig getFirewall() {
return firewall;
}
public Map<String, UserConfig> getUsers() {
return users;
}
public Map<String, SchemaConfig> getSchemas() {
return schemas;
}
public Map<String, PhysicalDBNode> getDataNodes() {
return dataNodes;
}
public Map<String, PhysicalDBPool> getDataHosts() {
return this.dataHosts;
}
private MycatCluster initCobarCluster(ConfigLoader configLoader) {
return new MycatCluster(configLoader.getClusterConfig());
}
private Map<String, PhysicalDBPool> initDataHosts(ConfigLoader configLoader) {
Map<String, DataHostConfig> nodeConfs = configLoader.getDataHosts();
boolean isBooster="booster".equalsIgnoreCase(ZkConfig.getInstance().getValue(ZkParamCfg.MYCAT_SERVER_TYPE) ) ;
//根据DataHost建立PhysicalDBPool,其实就是实际数据库连接池,每个DataHost对应一个PhysicalDBPool
Map<String, PhysicalDBPool> nodes = new HashMap<String, PhysicalDBPool>(
nodeConfs.size());
for (DataHostConfig conf : nodeConfs.values()) {
if(isBooster){
conf.setMinCon(2);
}
//建立PhysicalDBPool
PhysicalDBPool pool = getPhysicalDBPool(conf, configLoader);
nodes.put(pool.getHostName(), pool);
}
return nodes;
}
private PhysicalDatasource[] createDataSource(DataHostConfig conf,
String hostName, String dbType, String dbDriver,
DBHostConfig[] nodes, boolean isRead) {
PhysicalDatasource[] dataSources = new PhysicalDatasource[nodes.length];
if (dbType.equals("mysql") && dbDriver.equals("native")) {
for (int i = 0; i < nodes.length; i++) {
//设置最大idle时间,默认为30分钟
nodes[i].setIdleTimeout(system.getIdleTimeout());
MySQLDataSource ds = new MySQLDataSource(nodes[i], conf, isRead);
dataSources[i] = ds;
}
} else if (dbDriver.equals("jdbc")) {
for (int i = 0; i < nodes.length; i++) {
nodes[i].setIdleTimeout(system.getIdleTimeout());
JDBCDatasource ds = new JDBCDatasource(nodes[i], conf, isRead);
dataSources[i] = ds;
}
} else if ("postgresql".equalsIgnoreCase(dbType) && dbDriver.equalsIgnoreCase("native")){
for (int i = 0; i < nodes.length; i++) {
nodes[i].setIdleTimeout(system.getIdleTimeout());
PostgreSQLDataSource ds = new PostgreSQLDataSource(nodes[i], conf, isRead);
dataSources[i] = ds;
}
} else{
throw new ConfigException("not supported yet !" + hostName);
}
return dataSources;
}
private PhysicalDBPool getPhysicalDBPool(DataHostConfig conf,
ConfigLoader configLoader) {
String name = conf.getName();
//数据库类型,我们这里只讨论MySQL
String dbType = conf.getDbType();
//连接数据库驱动,我们这里只讨论MyCat自己实现的native
String dbDriver = conf.getDbDriver();
//针对所有写节点创建PhysicalDatasource
PhysicalDatasource[] writeSources = createDataSource(conf, name,
dbType, dbDriver, conf.getWriteHosts(), false);
Map<Integer, DBHostConfig[]> readHostsMap = conf.getReadHosts();
Map<Integer, PhysicalDatasource[]> readSourcesMap = new HashMap<Integer, PhysicalDatasource[]>(
readHostsMap.size());
//对于每个读节点建立key为writeHost下标value为readHost的PhysicalDatasource[]的哈希表
for (Map.Entry<Integer, DBHostConfig[]> entry : readHostsMap.entrySet()) {
PhysicalDatasource[] readSources = createDataSource(conf, name,
dbType, dbDriver, entry.getValue(), true);
readSourcesMap.put(entry.getKey(), readSources);
}
PhysicalDBPool pool = new PhysicalDBPool(conf.getName(), conf,
writeSources, readSourcesMap, conf.getBalance(),
conf.getWriteType());
pool.setSlaveIDs(conf.getSlaveIDs());
return pool;
}
private Map<String, PhysicalDBNode> initDataNodes(ConfigLoader configLoader) {
Map<String, DataNodeConfig> nodeConfs = configLoader.getDataNodes();
Map<String, PhysicalDBNode> nodes = new HashMap<String, PhysicalDBNode>(
nodeConfs.size());
for (DataNodeConfig conf : nodeConfs.values()) {
PhysicalDBPool pool = this.dataHosts.get(conf.getDataHost());
if (pool == null) {
throw new ConfigException("dataHost not exists "
+ conf.getDataHost());
}
PhysicalDBNode dataNode = new PhysicalDBNode(conf.getName(),
conf.getDatabase(), pool);
nodes.put(dataNode.getName(), dataNode);
}
return nodes;
}
}