ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/owl/trunk/tools/ClusterConnection.java
Revision: 95
Committed: Wed May 31 09:44:05 2006 UTC (18 years, 4 months ago) by duarte
File size: 15149 byte(s)
Log Message:
Adapted also ClusterConnection and checking methods in DataDistribution to text/numeric keys.
Some methods in ClusterConnection have not changed at all even though they deal with keys. I haven't changed them because they are applicable only to numeric keys:
insertIdxInMaster, getLastInsertId and getIdxSet
Line File contents
1 package tools;
2 import java.sql.*;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5
6 /**
7 * ClusterConnection class to wrap the master/node mysql servers so that is transparent to other programs
8 * @author Jose Duarte
9 */
10
11 public class ClusterConnection {
12
13 private String MASTERDB=DataDistribution.KEYMASTERDB;
14 private final String MASTERHOST=DataDistribution.MASTER;
15 private MySQLConnection nCon;
16 private MySQLConnection mCon;
17 public String keyTable;
18 public String key;
19 public String host;
20 public String db;
21 private String user;
22 private String password;
23
24 /**
25 * Create a ClusterConnection passing a key.
26 * @param db the database name
27 * @param key the key name: e.g. asu_id
28 * @param user the user name for connection to both master and nodes
29 * @param password the password for connection to both master and nodes
30 */
31 public ClusterConnection (String db,String key, String user,String password) {
32 setDb(db);
33 setUser(user);
34 setPassword(password);
35 // For nCon we create a connection to the master too.
36 // This is just a place holder because the actual node connection is not created until we create the statement
37 // If we don't do this then when closing the two connections an exception might occurr because we try to close a non existing object
38 this.nCon = new MySQLConnection(MASTERHOST,user,password,MASTERDB);
39 this.mCon = new MySQLConnection(MASTERHOST,user,password,MASTERDB);
40 this.key=key; //can't use the setKey method here before we've got the db field initialized
41 setKeyTable(db);
42 }
43
44 /**
45 * Create a ClusterConnection without passing a key. The key will be set later when we call createStatement(key,idx)
46 * @param db the database name
47 * @param user the user name for connection to both master and nodes
48 * @param password the password for connection to both master and nodes
49 */
50 public ClusterConnection (String db, String user,String password) {
51 setDb(db);
52 setUser(user);
53 setPassword(password);
54 // For nCon we create a connection to the master too.
55 // This is just a place holder because the actual node connection is not created until we create the statement
56 // If we don't do this then when closing the two connections an exception might occurr because we try to close a non existing object
57 this.nCon = new MySQLConnection(MASTERHOST,user,password,MASTERDB);
58 this.mCon = new MySQLConnection(MASTERHOST,user,password,MASTERDB);
59 }
60
61 public void close() {
62 this.nCon.close();
63 this.mCon.close();
64 }
65
66 public <T> String getHost4Idx (T idx) {
67 String host="";
68 String query = "SELECT client_name FROM "+keyTable+" AS m INNER JOIN clients_names AS c "+
69 "ON (m.client_id=c.client_id) WHERE "+key+"='"+idx+"';";
70 host=this.mCon.getStringFromDb(query);
71 return host;
72 }
73
74 public <T> void setHostFromIdx(T idx){
75 setHost(getHost4Idx(idx));
76 }
77
78 public void setHost(String host) {
79 this.host=host;
80 //Closing previous connection is essential
81 //If we don't close it a lot of connections stay open after using a ClusterConnection object for a while
82 this.nCon.close();
83 this.nCon = new MySQLConnection(host,user,password,db);
84 }
85
86 /**
87 * This method is strictly private. We shouldn't call this from another class as a key might not be set when we call it
88 * and thus we can't get the client_id from the master key table. Only to be called from createStatement(key,idx)
89 * @param idx the value of the id for a certain key already set
90 * @return a Stament object with a connection to the node that contains idx for key
91 */
92 private <T> Statement createStatement(T idx) { // to use when the field "key" is already set
93 setKeyTable();
94 Statement S=null;
95 this.setHostFromIdx(idx);
96 try {
97 S=this.nCon.createStatement();
98 }
99 catch (SQLException e){
100 System.err.println("SQLException: " + e.getMessage());
101 System.err.println("SQLState: " + e.getSQLState());
102 System.err.println("Couldn't create statement for the node connection, idx= "+idx+", exiting.");
103 System.exit(2);
104 }
105 return S;
106 }
107
108 /**
109 * This method is used to create a statement passing the key and idx. It will create a connection the the right node
110 * and return a Statement for that connection
111 * @param idx the key name
112 * @param idx the id value for that key
113 * @return a Statement object with a connection to the node that contains idx for key
114 */
115 public <T> Statement createStatement(String key,T idx) {
116 setKey(key);
117 return createStatement(idx);
118 }
119
120 /**
121 * To execute a sql update/insert query in the right node given a query, key and idx. Just a shortcut not to have to do the create statement and execute
122 * @param query the SQL query
123 * @param key the name of the key
124 * @param idx the id value for that key
125 */
126 public <T> void executeSql(String query,String key, T idx) throws SQLException {
127 Statement stmt;
128 stmt = this.createStatement(key,idx);
129 stmt.execute(query);
130 stmt.close();
131 }
132
133 /**
134 * To change the MASTERDB String, i.e. the name of the key master database. To be used in testing.
135 * @param db the name of the key master db we want to use instead of the default defined in the MASTERDB field
136 */
137 public void setKeyDb(String db) {
138 this.MASTERDB=db;
139 //Closing previous connection is essential
140 this.mCon.close();
141 this.mCon = new MySQLConnection(MASTERHOST,user,password,MASTERDB);
142 }
143
144 /**
145 * To set keyTable field in constructor (i.e. first time). Only to be used in constructor.
146 * @param db the database name
147 */
148 public void setKeyTable(String db) {
149 String query="SELECT key_master_table FROM dbs_keys WHERE db=\'"+db+"\' AND key_name=\'"+this.key+"\';";
150 this.keyTable=this.mCon.getStringFromDb(query);
151 }
152
153 /**
154 * To set the keyTable field when db is already set
155 * The value of keyTable is taken from the dbs_keys table in the database given the db and key.
156 */
157 public void setKeyTable() {
158 String query="SELECT key_master_table FROM dbs_keys WHERE db=\'"+this.db+"\' AND key_name=\'"+this.key+"\';";
159 this.keyTable=this.mCon.getStringFromDb(query);
160 }
161
162 public String getKeyTable() {
163 return this.keyTable;
164 }
165
166 /**
167 * To get the name of the target table where splitted data is stored in nodes, e.g. for keyTable pdbgraph__asu_list, we get asu_list
168 * @return
169 */
170 public String getTableOnNode(){
171 String table="";
172 if (this.keyTable.contains("__")) {
173 String[] tokens=this.keyTable.split("__");
174 table=tokens[1];
175 }
176 else {
177 System.err.println("Error! The keyTable field is not set in this ClusterConnection object.");
178 }
179 return table;
180 }
181
182 public void setUser(String user) {
183 this.user=user;
184 }
185
186 public void setPassword(String password) {
187 this.password=password;
188 }
189
190 public void setDb(String db){
191 this.db=db;
192 }
193
194 public void setKey(String key){
195 this.key=key;
196 setKeyTable();
197 }
198
199 public Statement createMasterStatement() {
200 Statement S=null;
201 try {
202 S=this.mCon.createStatement();
203 }
204 catch (SQLException e){
205 System.err.println("SQLException: " + e.getMessage());
206 System.err.println("SQLState: " + e.getSQLState());
207 System.err.println("Couldn't create statement for the master connection, exiting.");
208 System.exit(2);
209 }
210 return S;
211 }
212
213 public Object[] getAllIdxFromMaster(String key) {
214 this.setKey(key);
215 Object[] ids=null;
216 ArrayList<Object> idsAL=new ArrayList<Object>();
217 try {
218 String query="SELECT "+key+" FROM "+keyTable+";";
219 Statement S=this.mCon.createStatement();
220 ResultSet R=S.executeQuery(query);
221 while (R.next()){
222 idsAL.add(R.getInt(1));
223 }
224 R.close();
225 S.close();
226 }
227 catch (SQLException e){
228 System.err.println("SQLException: " + e.getMessage());
229 System.err.println("SQLState: " + e.getSQLState());
230 System.err.println("Couldn't get all indices from columnn "+key+" in table "+keyTable+" from "+MASTERDB+" database in "+MASTERHOST+", exiting.");
231 System.exit(2);
232 }
233 ids=new Object[idsAL.size()];
234 for (int i=0;i<idsAL.size();i++){
235 ids[i]=idsAL.get(i);
236 }
237 return ids;
238 }
239
240 /**
241 * To get all ids and clients_names pairs for a certain key. Useful when need to submit to all hosts using qsub -q
242 * @param key the name of the key
243 * @return HashMap with keys = indices, and values = node names where the corresponding index is stored
244 */
245 public HashMap<Object,String> getAllIdxAndClients (String key){
246 this.setKey(key);
247 HashMap<Object,String> idsAndClients=new HashMap<Object,String>();
248 try {
249 String query="SELECT a."+key+",c.client_name FROM "+keyTable+" AS a INNER JOIN clients_names AS c ON (a.client_id=c.client_id);";
250 Statement S=this.mCon.createStatement();
251 ResultSet R=S.executeQuery(query);
252 while (R.next()){
253 idsAndClients.put(R.getString(1),R.getString(2));
254 }
255 R.close();
256 S.close();
257 }
258 catch (SQLException e){
259 System.err.println("SQLException: " + e.getMessage());
260 System.err.println("SQLState: " + e.getSQLState());
261 System.err.println("Couldn't get all indices/client_names pairs from table "+keyTable+" from "+MASTERDB+" database in "+MASTERHOST+", exiting.");
262 System.exit(2);
263 }
264 return idsAndClients;
265 }
266
267 /**
268 * To get client_id for a certain idx and key
269 * @param key the key name
270 * @param idx the id value for that key (either a String or an int)
271 * @return the client_id for node that has the data for the idx for that key
272 */
273 //TODO will need to change the query. In general this method would return more than 1 client_id if the idx is not unique
274 public <T> int getHostId4Idx (String key,T idx) {
275 int hostId=0;
276 this.setKey(key);
277 String query;
278 int countCids=0;
279 query="SELECT count(client_id) FROM "+keyTable+" WHERE "+key+"='"+idx+"';";
280 countCids=this.mCon.getIntFromDb(query);
281 if (countCids!=1){
282 System.err.println("the query was: "+query);
283 System.err.println("Error! the count of client_ids for idx "+key+"= "+idx+" is " +countCids+
284 ". It must be 1! The values were taken from host: "+MASTERHOST+", database: "+MASTERDB+", table: "+keyTable+". Check what's wrong! Exiting now.");
285 System.exit(2);
286 }
287 else {
288 query="SELECT client_id FROM "+keyTable+" WHERE "+key+"='"+idx+"';";
289 hostId=this.mCon.getIntFromDb(query);
290 }
291 return hostId;
292 }
293
294 // next 4 methods here refer purely to numeric keys, won't change them to be general text/numeric
295 public void insertIdxInMaster(String key, int clientId) {
296 String query;
297 this.setKey(key);
298 try {
299 query="INSERT INTO "+this.keyTable+" (client_id) VALUES ("+clientId+");";
300 this.mCon.executeSql(query);
301 }
302 catch (SQLException E) {
303 System.err.println("SQLException: " + E.getMessage());
304 System.err.println("SQLState: " + E.getSQLState());
305 System.err.println("Couldn't insert new "+this.key+" in master table "+this.getKeyTable()+". The client_id for it was "+clientId+". Exiting.");
306 System.exit(2);
307 }
308 }
309
310 public void insertIdxInMaster(String keySrc,String keyDest,int idxSrc) {
311 this.setKey(keySrc);
312 int clientId=0;
313 clientId=this.getHostId4Idx(keySrc,idxSrc);
314 insertIdxInMaster(keyDest,clientId);
315 }
316
317 public int getLastInsertId(String key) {
318 int lastIdx=0;
319 this.setKey(key);
320 String query = "";
321 query = "SELECT LAST_INSERT_ID() FROM "+this.keyTable+" LIMIT 1;";
322 lastIdx=this.mCon.getIntFromDb(query);
323 return lastIdx;
324 }
325
326 public int[][] getIdxSet(String key) {
327 int[][] indMatrix=null;
328 this.setKey(key);
329 String query;
330 Statement S;
331 ResultSet R;
332 try {
333 // STEP 1 -- getting set of all client_ids
334 query="SELECT count(distinct client_id) FROM "+keyTable+";";
335 int count=0;
336 count=this.mCon.getIntFromDb(query);
337 S=this.mCon.createStatement();
338 query="SELECT DISTINCT client_id FROM "+keyTable+" ORDER BY client_id;";
339 R=S.executeQuery(query);
340
341 // STEP 2 -- putting sets of indices counts into temp tables c_<client_id> with a serial auto_increment field
342 int[] clids=new int[count]; //array to store all client_ids. To be used in loops later
343 int i=0;
344 while (R.next()){
345 Statement Sloop=this.mCon.createStatement();
346 int clid=R.getInt(1);
347 query="CREATE TEMPORARY TABLE c_"+clid+" (serial int(11) NOT NULL AUTO_INCREMENT,"+key+" int(11),client_id int(11), PRIMARY KEY(serial));";
348 Sloop.executeUpdate(query);
349 query="INSERT INTO c_"+clid+" ("+key+",client_id) SELECT "+key+",client_id FROM "+keyTable+" WHERE client_id="+clid+";";
350 Sloop.executeUpdate(query);
351 clids[i]=clid;
352 i++;
353 Sloop.close();
354 }
355
356 // STEP3 -- merging all c_<client_id> tables into a temp table tmp_allcs and selecting the client_id with the maximum count
357 //query="SELECT client_id,count(*) as c FROM c_34 GROUP BY client_id UNION SELECT client_id,count(*) as c FROM c_32 GROUP BY client_id;";
358 query="DROP TABLE IF EXISTS tmp_allcs;";
359 S.executeUpdate(query);
360 //this table must be permanent! otherwise cannot do the select max(c) later
361 query="CREATE TABLE IF NOT EXISTS tmp_allcs (client_id int(11), c int(11)) ENGINE=MEMORY;";
362 S.executeUpdate(query);
363 String unionStr="SELECT client_id,count(*) AS c FROM c_"+clids[0]+" GROUP BY client_id";
364 for (i=1;i<clids.length;i++) {
365 unionStr+=" UNION SELECT client_id,count(*) AS c FROM c_"+clids[i]+" GROUP BY client_id";
366 }
367 query="INSERT INTO tmp_allcs "+unionStr+";";
368 S.executeUpdate(query);
369 query="SELECT client_id,c FROM tmp_allcs WHERE c=(SELECT max(c) FROM tmp_allcs);";
370 R=S.executeQuery(query);
371 int clidMaxIdxCount=0;
372 int maxIdxCount=0;
373 if (R.next()) {
374 clidMaxIdxCount=R.getInt(1);
375 maxIdxCount=R.getInt(2);
376 }
377 query="DROP TABLE tmp_allcs;";
378 S.executeUpdate(query);
379
380 // STEP 4 -- join all c_<client_id> tables into a table with a serial column, and c_<client_id> columns each of them with the indices for each client_id
381 //query="SELECT c_34.serial,c_34.asu_id AS c_34,c_32.asu_id AS c_32,c_36.asu_id AS c_36 FROM c_34 LEFT JOIN c_32 ON (c_34.serial=c_32.serial) LEFT JOIN c_36 ON (c_34.serial=c_36.serial);";
382 String selectStr="c_"+clidMaxIdxCount+".serial, c_"+clidMaxIdxCount+"."+key+" AS c_"+clidMaxIdxCount;
383 String fromStr="c_"+clidMaxIdxCount;
384 for (i=0;i<clids.length;i++) {
385 if (clids[i]!=clidMaxIdxCount){
386 selectStr+=", c_"+clids[i]+"."+key+" AS c_"+clids[i];
387 fromStr+=" LEFT JOIN c_"+clids[i]+" ON (c_"+clidMaxIdxCount+".serial=c_"+clids[i]+".serial)";
388 }
389 }
390 query="CREATE TEMPORARY TABLE indices_matrix "+"SELECT "+selectStr+" FROM "+fromStr+";";
391 S.executeUpdate(query);
392
393 // STEP 5 -- put the table into a 2-dimensional array and return it
394 indMatrix = new int[maxIdxCount][clids.length];
395 query="SELECT * FROM indices_matrix";
396 R=S.executeQuery(query);
397 i=0;
398 while (R.next()) {
399 for (int j=0;j<clids.length;j++){
400 indMatrix[i][j]=R.getInt(j+2);
401 }
402 i++;
403 }
404 R.close();
405 S.close();
406 }
407 catch (SQLException e){
408 System.err.println("SQLException: " + e.getMessage());
409 System.err.println("SQLState: " + e.getSQLState());
410 System.err.println("Couldn't get the indices set from columnn "+key+" in table "+keyTable+" from "+MASTERDB+" database in "+MASTERHOST+", exiting.");
411 System.exit(2);
412 }
413 return indMatrix;
414 }
415
416
417 }

Properties

Name Value
svn:executable *