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