New code update
[jabaws.git] / webservices / compbio / stat / collector / StatDB.java
1 /* Copyright (c) 2011 Peter Troshin\r
2  *  \r
3  *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0     \r
4  * \r
5  *  This library is free software; you can redistribute it and/or modify it under the terms of the\r
6  *  Apache License version 2 as published by the Apache Software Foundation\r
7  * \r
8  *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r
9  *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache \r
10  *  License for more details.\r
11  * \r
12  *  A copy of the license is in apache_license.txt. It is also available here:\r
13  * @see: http://www.apache.org/licenses/LICENSE-2.0.txt\r
14  * \r
15  * Any republication or derived work distributed in source code form\r
16  * must include this copyright and license notice.\r
17  */\r
18 package compbio.stat.collector;\r
19 \r
20 import java.sql.Connection;\r
21 import java.sql.DriverManager;\r
22 import java.sql.PreparedStatement;\r
23 import java.sql.ResultSet;\r
24 import java.sql.SQLException;\r
25 import java.sql.Statement;\r
26 import java.sql.Timestamp;\r
27 import java.util.ArrayList;\r
28 import java.util.Date;\r
29 import java.util.List;\r
30 import java.util.Set;\r
31 \r
32 import org.apache.log4j.Logger;\r
33 \r
34 import compbio.engine.conf.PropertyHelperManager;\r
35 import compbio.util.Util;\r
36 import compbio.ws.client.Services;\r
37 \r
38 /**\r
39  * The database must be stored in the application root directory and called\r
40  * "ExecutionStatistic"\r
41  * \r
42  * @author pvtroshin\r
43  * \r
44  */\r
45 public class StatDB {\r
46 \r
47         private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver";\r
48         private static final String protocol = "jdbc:derby:";\r
49         private static final String statDBName = "ExecutionStatistic";\r
50 \r
51         private static final Logger log = Logger.getLogger(StatDB.class);\r
52 \r
53         static Connection conn;\r
54 \r
55         private synchronized static Connection getDBConnection() throws SQLException {\r
56                 return getDBConnection(statDBName);\r
57         }\r
58 \r
59         private synchronized static Connection getDBConnection(String dbname) throws SQLException {\r
60 \r
61                 if (conn != null && !conn.isClosed()) {\r
62                         return conn;\r
63                 } else {\r
64                         try {\r
65                                 String dbpath = PropertyHelperManager.getLocalPath();\r
66                                 log.info("Looking for JABAWS access statistics database at: " + dbpath);\r
67                                 System.setProperty("derby.system.home", dbpath);\r
68                                 // Apparently under Tomcat webapp you cannot rely on Java\r
69                                 // auto discovery and have to register the driver explicitly\r
70                                 Class.forName(driver);\r
71                                 conn = DriverManager.getConnection(protocol + dbname + ";create=false");\r
72 \r
73                                 conn.setAutoCommit(true);\r
74                         } catch (ClassNotFoundException e) {\r
75                                 log.error(e.getMessage(), e);\r
76                         }\r
77                 }\r
78                 return conn;\r
79         }\r
80 \r
81         \r
82         public StatDB(String dbname) throws SQLException {\r
83                 this.conn = getDBConnection(dbname);\r
84         }\r
85 \r
86         public StatDB() throws SQLException {\r
87                 this.conn = getDBConnection();\r
88         }\r
89 \r
90         /**\r
91          * Connect to test database\r
92          * \r
93          * @param ignored\r
94          * @throws SQLException\r
95          */\r
96         StatDB(boolean ignored) throws SQLException {\r
97                 this.conn = getTestDBConnection();\r
98         }\r
99 \r
100         private static Connection getTestDBConnection() throws SQLException {\r
101                 System.setProperty("derby.system.home", "testsrc/testdata");\r
102                 Connection conn = DriverManager.getConnection(protocol + statDBName\r
103                                 + ";create=false");\r
104                 conn.setAutoCommit(true);\r
105                 log.debug("Connecting to the TEST database!");\r
106                 return conn;\r
107         }\r
108 \r
109         // ServiceName,jobname,start,finish,inputSize,resultSize,isCancelled,isCollected\r
110         /**\r
111          * \r
112          * rs.getBoolean(i) will return true for any non-zero value and false for 0\r
113          * on SMALLINT data column.\r
114          * \r
115          * @throws SQLException\r
116          */\r
117         private void createStatTable() throws SQLException {\r
118                 // Creating a statement object that we can use for running various SQL\r
119                 // statements commands against the database.\r
120                 Statement s = conn.createStatement();\r
121                 String create = "create table exec_stat("\r
122                                 + "number INT GENERATED ALWAYS AS IDENTITY,"\r
123                                 + "service_name VARCHAR(15) NOT NULL, "\r
124                                 + "cluster_job_id VARCHAR(30), "\r
125                                 + "job_id VARCHAR(35) NOT NULL PRIMARY KEY, "\r
126                                 + "start TIMESTAMP," + "finish TIMESTAMP,"\r
127                                 + "inputsize BIGINT," + "resultsize BIGINT,"\r
128                                 + "isCancelled SMALLINT NOT NULL,"\r
129                                 + "isCollected SMALLINT NOT NULL, "\r
130                                 + "isClusterJob SMALLINT NOT NULL)";\r
131                 // We create a table...\r
132                 log.debug(create);\r
133                 s.execute(create);\r
134                 s.close();\r
135                 conn.close();\r
136         }\r
137 \r
138         static void clearStatTable() throws SQLException {\r
139                 Connection conn = getDBConnection();\r
140                 String query = "delete from exec_stat";\r
141                 Statement st = conn.createStatement();\r
142                 st.executeUpdate(query);\r
143                 st.close();\r
144                 conn.commit();\r
145                 conn.close();\r
146         }\r
147 \r
148         void insertData(Set<JobStat> jobstatus) throws SQLException {\r
149                 log.info("Inserting " + jobstatus.size()\r
150                                 + " new records into the statistics database");\r
151 \r
152                 conn.setAutoCommit(false);\r
153                 String insert = "insert into exec_stat (service_name, cluster_job_id, job_id, start, finish, "\r
154                                 + "inputsize, resultsize, isCancelled, isCollected, isClusterJob) "\r
155                                 + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
156                 PreparedStatement pstm = conn.prepareStatement(insert);\r
157                 for (JobStat js : jobstatus) {\r
158                         // Has to present\r
159                         pstm.setString(1, js.webService.toString());\r
160 \r
161                         if (!Util.isEmpty(js.clusterJobId)) {\r
162                                 pstm.setString(2, js.clusterJobId);\r
163                         } else {\r
164                                 pstm.setString(2, null);\r
165                         }\r
166                         // Has to present\r
167                         pstm.setString(3, js.jobname);\r
168 \r
169                         if (js.start != ExecutionStatCollector.UNDEFINED) {\r
170                                 pstm.setTimestamp(4, new Timestamp(js.start));\r
171                         } else {\r
172                                 pstm.setTimestamp(4, null);\r
173                         }\r
174                         if (js.finish != ExecutionStatCollector.UNDEFINED) {\r
175                                 pstm.setTimestamp(5, new Timestamp(js.finish));\r
176                         } else {\r
177                                 pstm.setTimestamp(5, null);\r
178                         }\r
179                         // -1 if UNDEFINED\r
180                         pstm.setLong(6, js.inputSize);\r
181                         // -1 if UNDEFINED\r
182                         pstm.setLong(7, js.resultSize);\r
183 \r
184                         pstm.setBoolean(8, js.isCancelled);\r
185                         pstm.setBoolean(9, js.isCollected);\r
186                         pstm.setBoolean(10, js.isClusterJob());\r
187                         pstm.executeUpdate();\r
188                 }\r
189                 conn.commit();\r
190                 conn.setAutoCommit(true);\r
191                 pstm.close();\r
192         }\r
193 \r
194         public Date getEarliestRecord() throws SQLException {\r
195                 String query = "select min(start) from exec_stat";\r
196                 Statement st = conn.createStatement();\r
197                 ResultSet res = st.executeQuery(query);\r
198                 boolean exist = res.next();\r
199                 Date date = new Date();\r
200                 if (exist) {\r
201                         date = res.getDate(1);\r
202                 }\r
203                 res.close();\r
204                 st.close();\r
205                 return date;\r
206         }\r
207 \r
208         public int getTotalJobsCount(Timestamp from, Timestamp to)\r
209                         throws SQLException {\r
210                 String allQuery = "select count(*) from exec_stat where start BETWEEN ? and ? ";\r
211                 return getIntResult(from, to, allQuery);\r
212         }\r
213 \r
214         public int getCancelledCount(Timestamp from, Timestamp to)\r
215                         throws SQLException {\r
216                 // js.isCancelled\r
217                 String cancelledQuery = "select count(*) from exec_stat where start BETWEEN ? and ?  and  isCancelled=1 ";\r
218                 return getIntResult(from, to, cancelledQuery);\r
219         }\r
220 \r
221         public int getAbandonedCount(Timestamp from, Timestamp to)\r
222                         throws SQLException {\r
223                 // !js.isCollected && !js.isCancelled && js.hasResult()\r
224                 String abandonedQuery = "select count(*) from exec_stat where start BETWEEN ? and ? and isCollected=0 and isCancelled=0 and resultsize>0 ";\r
225                 return getIntResult(from, to, abandonedQuery);\r
226         }\r
227 \r
228         public int getIncompleteCount(Timestamp from, Timestamp to)\r
229                         throws SQLException {\r
230                 // !js.hasResult()\r
231                 String incompleteQuery = "select count(*) from exec_stat where start BETWEEN ? and ? and resultsize<=0 and isCancelled=0";\r
232                 return getIntResult(from, to, incompleteQuery);\r
233         }\r
234 \r
235         private int getIntResult(Timestamp from, Timestamp to, String query)\r
236                         throws SQLException {\r
237 \r
238                 log.debug("getIntRes: QUERY: " + query);\r
239                 log.debug("getIntRes: FROM: " + from);\r
240                 log.debug("getIntRes: TO: " + to);\r
241 \r
242                 PreparedStatement pstm = conn.prepareStatement(query);\r
243                 pstm.setTimestamp(1, from);\r
244                 pstm.setTimestamp(2, to);\r
245                 pstm.execute();\r
246                 ResultSet res = pstm.getResultSet();\r
247                 boolean exist = res.next();\r
248                 int count = 0;\r
249                 if (exist) {\r
250                         count = res.getInt(1);\r
251                 }\r
252                 log.debug("getIntRes: RES: " + count);\r
253                 res.close();\r
254                 pstm.close();\r
255                 return count;\r
256         }\r
257 \r
258         public List<JobStat> readData(Timestamp from, Timestamp to,\r
259                         Services wservice, Boolean clusterOnly) throws SQLException {\r
260 \r
261                 String query = "select service_name, cluster_job_id, job_id, start, finish, inputsize, "\r
262                                 + "resultsize, isCancelled, isCollected from exec_stat where start BETWEEN ? and ? ";\r
263 \r
264                 if (wservice != null) {\r
265                         query += " and service_name=? ";\r
266                 }\r
267 \r
268                 if (clusterOnly != null) {\r
269                         if (clusterOnly) {\r
270                                 query += " and isClusterJob!=0 ";\r
271                         } else {\r
272                                 query += " and isClusterJob=0 ";\r
273                         }\r
274                 }\r
275 \r
276                 log.debug("QUERY: " + query);\r
277                 log.debug("FROM: " + from);\r
278                 log.debug("TO: " + to);\r
279                 log.debug("WS: " + wservice);\r
280 \r
281                 PreparedStatement pstm = conn.prepareStatement(query);\r
282                 pstm.setTimestamp(1, from);\r
283                 pstm.setTimestamp(2, to);\r
284                 if (wservice != null) {\r
285                         pstm.setString(3, wservice.toString());\r
286                 }\r
287                 pstm.execute();\r
288                 List<JobStat> stats = new ArrayList<JobStat>();\r
289                 ResultSet rs = pstm.getResultSet();\r
290                 int rcount = 0;\r
291 \r
292                 while (rs.next()) {\r
293                         rcount++;\r
294                         stats.add(JobStat.newInstance(Services.getService(rs.getString(1)),\r
295                                         rs.getString(2), rs.getString(3), rs.getTimestamp(4),\r
296                                         rs.getTimestamp(5), rs.getLong(6), rs.getLong(7),\r
297                                         rs.getBoolean(8), rs.getBoolean(9)));\r
298                 }\r
299 \r
300                 log.debug("QUERY result len: " + rcount);\r
301                 rs.close();\r
302                 pstm.close();\r
303 \r
304                 return stats;\r
305         }\r
306 \r
307         /**\r
308          * Removes the job if\r
309          * \r
310          * 1) It has already been recorded\r
311          * \r
312          * 2) It has not completed and did not timeout - this is to prevent\r
313          * recording the information on the incomplete jobs.\r
314          * \r
315          * @param fsJobs\r
316          * @throws SQLException\r
317          */\r
318         public void removeRecordedJobs(Set<JobStat> fsJobs) throws SQLException {\r
319 \r
320                 String query = "select job_id from exec_stat";\r
321 \r
322                 Statement st = conn.createStatement();\r
323                 ResultSet result = st.executeQuery(query);\r
324 \r
325                 while (result.next()) {\r
326                         String recordedJob = result.getString(1);\r
327                         JobStat recStat = JobStat.newIncompleteStat(recordedJob);\r
328                         if (fsJobs.contains(recStat)) {\r
329                                 fsJobs.remove(recStat);\r
330                         }\r
331                 }\r
332                 result.close();\r
333                 st.close();\r
334         }\r
335 \r
336         public static synchronized final void shutdownDBServer() {\r
337                 // ## DATABASE SHUTDOWN SECTION ##\r
338                 /***\r
339                  * In embedded mode, an application should shut down Derby. Shutdown\r
340                  * throws the XJ015 exception to confirm success.\r
341                  ***/\r
342                 try {\r
343                         if (conn != null) {\r
344                                 conn.close();\r
345                         }\r
346                 } catch (SQLException e) {\r
347                         log.warn("Database commit failed with " + e.getLocalizedMessage());\r
348                 }\r
349                 boolean gotSQLExc = false;\r
350                 try {\r
351                         DriverManager.getConnection("jdbc:derby:;shutdown=true");\r
352                 } catch (SQLException se) {\r
353                         if (se.getSQLState().equals("XJ015")) {\r
354                                 gotSQLExc = true;\r
355                         }\r
356                 }\r
357                 if (!gotSQLExc) {\r
358                         log.warn("Database did not shut down normally");\r
359                 } else {\r
360                         log.info("Database shut down normally");\r
361                 }\r
362         }\r
363         public static void main(String[] args) {\r
364                 // This is called from Ant cleanStatTable task\r
365                 try {\r
366                         clearStatTable();\r
367                         shutdownDBServer();\r
368                 } catch (SQLException e) {\r
369                         System.err.println("Fails to clean up JABAWS stat database!");\r
370                         e.printStackTrace();\r
371                 }\r
372                 // new StatDB().createStatTable();\r
373                 // insertData(null);\r
374                 /*\r
375                  * StatDB statdb = new StatDB(); Date from = new Date();\r
376                  * from.setMonth(1); System.out.println(new\r
377                  * StatProcessor(statdb.readData( new Timestamp(from.getTime()), new\r
378                  * Timestamp(new Date().getTime()), null, null)).reportStat());\r
379                  */\r
380         }\r
381 }\r