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