c2dd29a1b154d51d9b314abbcc63e676c762ae9a
[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         void insertData(Set<JobStat> jobstatus) throws SQLException {\r
115                 log.info("Inserting " + jobstatus.size()\r
116                                 + " new records into the statistics database");\r
117 \r
118                 conn.setAutoCommit(false);\r
119                 String insert = "insert into exec_stat (service_name, cluster_job_id, job_id, start, finish, "\r
120                                 + "inputsize, resultsize, isCancelled, isCollected, isClusterJob) "\r
121                                 + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
122                 PreparedStatement pstm = conn.prepareStatement(insert);\r
123                 for (JobStat js : jobstatus) {\r
124                         // Has to present\r
125                         pstm.setString(1, js.webService.toString());\r
126 \r
127                         if (!Util.isEmpty(js.clusterJobId)) {\r
128                                 pstm.setString(2, js.clusterJobId);\r
129                         } else {\r
130                                 pstm.setString(2, null);\r
131                         }\r
132                         // Has to present\r
133                         pstm.setString(3, js.jobname);\r
134 \r
135                         if (js.start != ExecutionStatCollector.UNDEFINED) {\r
136                                 pstm.setTimestamp(4, new Timestamp(js.start));\r
137                         } else {\r
138                                 pstm.setTimestamp(4, null);\r
139                         }\r
140                         if (js.finish != ExecutionStatCollector.UNDEFINED) {\r
141                                 pstm.setTimestamp(5, new Timestamp(js.finish));\r
142                         } else {\r
143                                 pstm.setTimestamp(5, null);\r
144                         }\r
145                         // -1 if UNDEFINED\r
146                         pstm.setLong(6, js.inputSize);\r
147                         // -1 if UNDEFINED\r
148                         pstm.setLong(7, js.resultSize);\r
149 \r
150                         pstm.setBoolean(8, js.isCancelled);\r
151                         pstm.setBoolean(9, js.isCollected);\r
152                         pstm.setBoolean(10, js.isClusterJob());\r
153                         pstm.executeUpdate();\r
154                 }\r
155                 conn.commit();\r
156                 conn.setAutoCommit(true);\r
157                 pstm.close();\r
158         }\r
159 \r
160         public Date getEarliestRecord() throws SQLException {\r
161                 String query = "select min(start) from exec_stat";\r
162                 Statement st = conn.createStatement();\r
163                 ResultSet res = st.executeQuery(query);\r
164                 boolean exist = res.next();\r
165                 Date date = new Date();\r
166                 if (exist) {\r
167                         date = res.getDate(1);\r
168                 }\r
169 \r
170                 res.close();\r
171                 st.close();\r
172                 return date;\r
173         }\r
174 \r
175         public int getTotalJobsCount(Timestamp from, Timestamp to)\r
176                         throws SQLException {\r
177                 String allQuery = "select count(*) from exec_stat where start BETWEEN ? and ? ";\r
178                 return getIntResult(from, to, allQuery);\r
179         }\r
180 \r
181         public int getCancelledCount(Timestamp from, Timestamp to)\r
182                         throws SQLException {\r
183                 // js.isCancelled\r
184                 String cancelledQuery = "select count(*) from exec_stat where start BETWEEN ? and ?  and  isCancelled=1 ";\r
185                 return getIntResult(from, to, cancelledQuery);\r
186         }\r
187 \r
188         public int getAbandonedCount(Timestamp from, Timestamp to)\r
189                         throws SQLException {\r
190                 // !js.isCollected && !js.isCancelled && js.hasResult()\r
191                 String abandonedQuery = "select count(*) from exec_stat where start BETWEEN ? and ? and isCollected=0 and isCancelled=0 and resultsize>0 ";\r
192                 return getIntResult(from, to, abandonedQuery);\r
193         }\r
194 \r
195         public int getIncompleteCount(Timestamp from, Timestamp to)\r
196                         throws SQLException {\r
197                 // !js.hasResult()\r
198                 String incompleteQuery = "select count(*) from exec_stat where start BETWEEN ? and ?  and resultsize<=0 ";\r
199                 return getIntResult(from, to, incompleteQuery);\r
200         }\r
201 \r
202         private int getIntResult(Timestamp from, Timestamp to, String query)\r
203                         throws SQLException {\r
204 \r
205                 log.debug("getIntRes: QUERY: " + query);\r
206                 log.debug("getIntRes: FROM: " + from);\r
207                 log.debug("getIntRes: TO: " + to);\r
208 \r
209                 PreparedStatement pstm = conn.prepareStatement(query);\r
210                 pstm.setTimestamp(1, from);\r
211                 pstm.setTimestamp(2, to);\r
212                 pstm.execute();\r
213                 ResultSet res = pstm.getResultSet();\r
214                 boolean exist = res.next();\r
215                 int count = 0;\r
216                 if (exist) {\r
217                         count = res.getInt(1);\r
218                 }\r
219                 log.debug("getIntRes: RES: " + count);\r
220                 res.close();\r
221                 pstm.close();\r
222                 return count;\r
223         }\r
224 \r
225         public List<JobStat> readData(Timestamp from, Timestamp to,\r
226                         Services wservice, Boolean clusterOnly) throws SQLException {\r
227 \r
228                 String query = "select service_name, cluster_job_id, job_id, start, finish, inputsize, "\r
229                                 + "resultsize, isCancelled, isCollected from exec_stat where start BETWEEN ? and ? ";\r
230 \r
231                 if (wservice != null) {\r
232                         query += " and service_name=? ";\r
233                 }\r
234 \r
235                 if (clusterOnly != null) {\r
236                         if (clusterOnly) {\r
237                                 query += " and isClusterJob!=0 ";\r
238                         } else {\r
239                                 query += " and isClusterJob=0 ";\r
240                         }\r
241                 }\r
242 \r
243                 log.debug("QUERY: " + query);\r
244                 log.debug("FROM: " + from);\r
245                 log.debug("TO: " + to);\r
246                 log.debug("WS: " + wservice);\r
247 \r
248                 PreparedStatement pstm = conn.prepareStatement(query);\r
249                 pstm.setTimestamp(1, from);\r
250                 pstm.setTimestamp(2, to);\r
251                 if (wservice != null) {\r
252                         pstm.setString(3, wservice.toString());\r
253                 }\r
254                 pstm.execute();\r
255                 List<JobStat> stats = new ArrayList<JobStat>();\r
256                 ResultSet rs = pstm.getResultSet();\r
257                 int rcount = 0;\r
258 \r
259                 while (rs.next()) {\r
260                         rcount++;\r
261                         stats.add(JobStat.newInstance(Services.getService(rs.getString(1)),\r
262                                         rs.getString(2), rs.getString(3), rs.getTimestamp(4),\r
263                                         rs.getTimestamp(5), rs.getLong(6), rs.getLong(7),\r
264                                         rs.getBoolean(8), rs.getBoolean(9)));\r
265                 }\r
266 \r
267                 log.debug("QUERY result len: " + rcount);\r
268                 rs.close();\r
269                 pstm.close();\r
270 \r
271                 return stats;\r
272         }\r
273 \r
274         /**\r
275          * Removes the job if\r
276          * \r
277          * 1) It has already been recorded\r
278          * \r
279          * 2) It has not completed and did not timeout - this is to prevent\r
280          * recording the information on the incomplete jobs.\r
281          * \r
282          * @param fsJobs\r
283          * @throws SQLException\r
284          */\r
285         public void removeRecordedJobs(Set<JobStat> fsJobs) throws SQLException {\r
286 \r
287                 String query = "select job_id from exec_stat";\r
288 \r
289                 Statement st = conn.createStatement();\r
290                 ResultSet result = st.executeQuery(query);\r
291 \r
292                 while (result.next()) {\r
293                         String recordedJob = result.getString(1);\r
294                         JobStat recStat = JobStat.newIncompleteStat(recordedJob);\r
295                         if (fsJobs.contains(recStat)) {\r
296                                 fsJobs.remove(recStat);\r
297                         }\r
298                 }\r
299                 result.close();\r
300                 st.close();\r
301         }\r
302 \r
303         public static synchronized final void shutdownDBServer() {\r
304                 // ## DATABASE SHUTDOWN SECTION ##\r
305                 /***\r
306                  * In embedded mode, an application should shut down Derby. Shutdown\r
307                  * throws the XJ015 exception to confirm success.\r
308                  ***/\r
309                 try {\r
310                         if (conn != null) {\r
311                                 conn.close();\r
312                         }\r
313                 } catch (SQLException e) {\r
314                         log.warn("Database commit failed with " + e.getLocalizedMessage());\r
315                 }\r
316                 boolean gotSQLExc = false;\r
317                 try {\r
318                         DriverManager.getConnection("jdbc:derby:;shutdown=true");\r
319                 } catch (SQLException se) {\r
320                         if (se.getSQLState().equals("XJ015")) {\r
321                                 gotSQLExc = true;\r
322                         }\r
323                 }\r
324                 if (!gotSQLExc) {\r
325                         log.warn("Database did not shut down normally");\r
326                 } else {\r
327                         log.info("Database shut down normally");\r
328                 }\r
329         }\r
330         public static void main(String[] args) throws SQLException {\r
331                 // new StatDB().createStatTable();\r
332                 // insertData(null);\r
333                 /*\r
334                  * StatDB statdb = new StatDB(); Date from = new Date();\r
335                  * from.setMonth(1); System.out.println(new\r
336                  * StatProcessor(statdb.readData( new Timestamp(from.getTime()), new\r
337                  * Timestamp(new Date().getTime()), null, null)).reportStat());\r
338                  */\r
339         }\r
340 }\r