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