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