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 User Rev File contents
1 duarte 16 package tools;
2 duarte 15 import java.sql.*;
3 duarte 67 import java.util.ArrayList;
4     import java.util.HashMap;
5 duarte 15
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 duarte 92 private String MASTERDB=DataDistribution.KEYMASTERDB;
14     private final String MASTERHOST=DataDistribution.MASTER;
15 duarte 81 private MySQLConnection nCon;
16     private MySQLConnection mCon;
17 duarte 15 public String keyTable;
18     public String key;
19     public String host;
20     public String db;
21     private String user;
22     private String password;
23 duarte 34
24     /**
25     * Create a ClusterConnection passing a key.
26 duarte 35 * @param db the database name
27 duarte 72 * @param key the key name: e.g. asu_id
28 duarte 35 * @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 duarte 34 */
31 duarte 15 public ClusterConnection (String db,String key, String user,String password) {
32 duarte 72 setDb(db);
33     setUser(user);
34     setPassword(password);
35 duarte 81 // 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 duarte 17 this.key=key; //can't use the setKey method here before we've got the db field initialized
41 duarte 34 setKeyTable(db);
42 duarte 15 }
43    
44 duarte 34 /**
45     * Create a ClusterConnection without passing a key. The key will be set later when we call createStatement(key,idx)
46 duarte 35 * @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 duarte 34 */
50 duarte 15 public ClusterConnection (String db, String user,String password) {
51     setDb(db);
52     setUser(user);
53 duarte 81 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 duarte 15 }
60    
61     public void close() {
62 duarte 81 this.nCon.close();
63     this.mCon.close();
64 duarte 15 }
65    
66 duarte 95 public <T> String getHost4Idx (T idx) {
67 duarte 15 String host="";
68 duarte 81 String query = "SELECT client_name FROM "+keyTable+" AS m INNER JOIN clients_names AS c "+
69 duarte 95 "ON (m.client_id=c.client_id) WHERE "+key+"='"+idx+"';";
70 duarte 81 host=this.mCon.getStringFromDb(query);
71 duarte 15 return host;
72     }
73    
74 duarte 95 public <T> void setHostFromIdx(T idx){
75 duarte 15 setHost(getHost4Idx(idx));
76     }
77    
78     public void setHost(String host) {
79     this.host=host;
80 duarte 81 //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 duarte 15 }
85 duarte 35
86 duarte 34 /**
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 duarte 35 * @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 duarte 34 */
92 duarte 95 private <T> Statement createStatement(T idx) { // to use when the field "key" is already set
93 duarte 34 setKeyTable();
94 duarte 15 Statement S=null;
95     this.setHostFromIdx(idx);
96     try {
97     S=this.nCon.createStatement();
98     }
99     catch (SQLException e){
100 duarte 33 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 duarte 15 System.exit(2);
104     }
105     return S;
106     }
107 duarte 35
108 duarte 34 /**
109 duarte 35 * 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 duarte 34 */
115 duarte 95 public <T> Statement createStatement(String key,T idx) {
116 duarte 15 setKey(key);
117     return createStatement(idx);
118     }
119    
120 duarte 35 /**
121 duarte 43 * 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 duarte 95 public <T> void executeSql(String query,String key, T idx) throws SQLException {
127 duarte 43 Statement stmt;
128 duarte 81 stmt = this.createStatement(key,idx);
129     stmt.execute(query);
130     stmt.close();
131 duarte 43 }
132 duarte 81
133 duarte 51 /**
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 duarte 81 //Closing previous connection is essential
140     this.mCon.close();
141     this.mCon = new MySQLConnection(MASTERHOST,user,password,MASTERDB);
142 duarte 51 }
143 duarte 43
144     /**
145 duarte 72 * To set keyTable field in constructor (i.e. first time). Only to be used in constructor.
146 duarte 35 * @param db the database name
147     */
148     public void setKeyTable(String db) {
149 duarte 72 String query="SELECT key_master_table FROM dbs_keys WHERE db=\'"+db+"\' AND key_name=\'"+this.key+"\';";
150 duarte 81 this.keyTable=this.mCon.getStringFromDb(query);
151 duarte 15 }
152    
153 duarte 35 /**
154 duarte 43 * To set the keyTable field when db is already set
155 duarte 72 * The value of keyTable is taken from the dbs_keys table in the database given the db and key.
156 duarte 35 */
157     public void setKeyTable() {
158 duarte 72 String query="SELECT key_master_table FROM dbs_keys WHERE db=\'"+this.db+"\' AND key_name=\'"+this.key+"\';";
159 duarte 81 this.keyTable=this.mCon.getStringFromDb(query);
160 duarte 15 }
161    
162 duarte 34 public String getKeyTable() {
163 duarte 15 return this.keyTable;
164     }
165    
166 duarte 72 /**
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 duarte 15 }
181 duarte 72
182 duarte 15 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 duarte 34 setKeyTable();
197 duarte 15 }
198    
199     public Statement createMasterStatement() {
200     Statement S=null;
201     try {
202     S=this.mCon.createStatement();
203     }
204     catch (SQLException e){
205 duarte 33 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 duarte 15 System.exit(2);
209     }
210     return S;
211     }
212 duarte 74
213 duarte 95 public Object[] getAllIdxFromMaster(String key) {
214 duarte 15 this.setKey(key);
215 duarte 95 Object[] ids=null;
216     ArrayList<Object> idsAL=new ArrayList<Object>();
217 duarte 67 try {
218 duarte 72 String query="SELECT "+key+" FROM "+keyTable+";";
219 duarte 67 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 duarte 15 }
227     catch (SQLException e){
228 duarte 33 System.err.println("SQLException: " + e.getMessage());
229     System.err.println("SQLState: " + e.getSQLState());
230 duarte 72 System.err.println("Couldn't get all indices from columnn "+key+" in table "+keyTable+" from "+MASTERDB+" database in "+MASTERHOST+", exiting.");
231 duarte 15 System.exit(2);
232     }
233 duarte 95 ids=new Object[idsAL.size()];
234 duarte 67 for (int i=0;i<idsAL.size();i++){
235     ids[i]=idsAL.get(i);
236     }
237     return ids;
238 duarte 15 }
239 duarte 95
240 duarte 35 /**
241 duarte 38 * 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 duarte 67 * @return HashMap with keys = indices, and values = node names where the corresponding index is stored
244 duarte 38 */
245 duarte 95 public HashMap<Object,String> getAllIdxAndClients (String key){
246 duarte 38 this.setKey(key);
247 duarte 95 HashMap<Object,String> idsAndClients=new HashMap<Object,String>();
248 duarte 38 try {
249 duarte 72 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 duarte 67 Statement S=this.mCon.createStatement();
251     ResultSet R=S.executeQuery(query);
252     while (R.next()){
253 duarte 95 idsAndClients.put(R.getString(1),R.getString(2));
254 duarte 67 }
255     R.close();
256     S.close();
257 duarte 38 }
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 duarte 67 return idsAndClients;
265 duarte 38 }
266    
267     /**
268 duarte 35 * To get client_id for a certain idx and key
269     * @param key the key name
270 duarte 95 * @param idx the id value for that key (either a String or an int)
271 duarte 35 * @return the client_id for node that has the data for the idx for that key
272     */
273 duarte 15 //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 duarte 95 public <T> int getHostId4Idx (String key,T idx) {
275 duarte 15 int hostId=0;
276     this.setKey(key);
277     String query;
278     int countCids=0;
279 duarte 95 query="SELECT count(client_id) FROM "+keyTable+" WHERE "+key+"='"+idx+"';";
280 duarte 81 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 duarte 15 }
287 duarte 81 else {
288 duarte 95 query="SELECT client_id FROM "+keyTable+" WHERE "+key+"='"+idx+"';";
289 duarte 81 hostId=this.mCon.getIntFromDb(query);
290 duarte 15 }
291     return hostId;
292     }
293    
294 duarte 95 // next 4 methods here refer purely to numeric keys, won't change them to be general text/numeric
295 duarte 15 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 duarte 81 this.mCon.executeSql(query);
301 duarte 15 }
302     catch (SQLException E) {
303 duarte 33 System.err.println("SQLException: " + E.getMessage());
304     System.err.println("SQLState: " + E.getSQLState());
305 duarte 72 System.err.println("Couldn't insert new "+this.key+" in master table "+this.getKeyTable()+". The client_id for it was "+clientId+". Exiting.");
306 duarte 15 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 duarte 81 query = "SELECT LAST_INSERT_ID() FROM "+this.keyTable+" LIMIT 1;";
322     lastIdx=this.mCon.getIntFromDb(query);
323 duarte 15 return lastIdx;
324 duarte 81 }
325 duarte 21
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 duarte 81 // STEP 1 -- getting set of all client_ids
334 duarte 21 query="SELECT count(distinct client_id) FROM "+keyTable+";";
335     int count=0;
336 duarte 81 count=this.mCon.getIntFromDb(query);
337     S=this.mCon.createStatement();
338 duarte 21 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 duarte 72 query="CREATE TEMPORARY TABLE c_"+clid+" (serial int(11) NOT NULL AUTO_INCREMENT,"+key+" int(11),client_id int(11), PRIMARY KEY(serial));";
348 duarte 21 Sloop.executeUpdate(query);
349 duarte 72 query="INSERT INTO c_"+clid+" ("+key+",client_id) SELECT "+key+",client_id FROM "+keyTable+" WHERE client_id="+clid+";";
350 duarte 21 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 duarte 72 String selectStr="c_"+clidMaxIdxCount+".serial, c_"+clidMaxIdxCount+"."+key+" AS c_"+clidMaxIdxCount;
383 duarte 21 String fromStr="c_"+clidMaxIdxCount;
384     for (i=0;i<clids.length;i++) {
385     if (clids[i]!=clidMaxIdxCount){
386 duarte 72 selectStr+=", c_"+clids[i]+"."+key+" AS c_"+clids[i];
387 duarte 21 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 duarte 22 indMatrix[i][j]=R.getInt(j+2);
401 duarte 21 }
402     i++;
403     }
404     R.close();
405     S.close();
406     }
407     catch (SQLException e){
408 duarte 33 System.err.println("SQLException: " + e.getMessage());
409     System.err.println("SQLState: " + e.getSQLState());
410 duarte 72 System.err.println("Couldn't get the indices set from columnn "+key+" in table "+keyTable+" from "+MASTERDB+" database in "+MASTERHOST+", exiting.");
411 duarte 21 System.exit(2);
412     }
413     return indMatrix;
414     }
415    
416    
417 duarte 15 }

Properties

Name Value
svn:executable *