1 /* Copyright (c) 2011 Peter Troshin
\r
3 * JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0
\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
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
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
15 * Any republication or derived work distributed in source code form
\r
16 * must include this copyright and license notice.
\r
18 package compbio.stat.collector;
\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
32 import org.apache.log4j.Logger;
\r
34 import compbio.engine.conf.PropertyHelperManager;
\r
35 import compbio.util.Util;
\r
36 import compbio.ws.client.Services;
\r
39 * The database must be stored in the application root directory and called
\r
40 * "ExecutionStatistic"
\r
45 public class StatDB {
\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
51 private static final Logger log = Logger.getLogger(StatDB.class);
\r
53 static Connection conn;
\r
55 private synchronized static Connection getDBConnection()
\r
56 throws SQLException {
\r
58 if (conn != null && !conn.isClosed()) {
\r
62 String dbpath = PropertyHelperManager.getLocalPath();
\r
63 log.info("Looking for JABAWS access statistics database at: "
\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
72 conn.setAutoCommit(true);
\r
74 * Runtime.getRuntime().addShutdownHook(new Thread() {
\r
76 * @Override public void run() { shutdownDBServer(); } });
\r
78 } catch (ClassNotFoundException e) {
\r
79 log.error(e.getMessage(), e);
\r
84 public StatDB() throws SQLException {
\r
85 this.conn = getDBConnection();
\r
89 * Connect to test database
\r
92 * @throws SQLException
\r
94 StatDB(boolean ignored) throws SQLException {
\r
95 this.conn = getTestDBConnection();
\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
107 // ServiceName,jobname,start,finish,inputSize,resultSize,isCancelled,isCollected
\r
110 * rs.getBoolean(i) will return true for any non-zero value and false for 0
\r
111 * on SMALLINT data column.
\r
113 * @throws SQLException
\r
115 private void createStatTable() throws SQLException {
\r
118 * Creating a statement object that we can use for running various SQL
\r
119 * statements commands against the database.
\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
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
149 void insertData(Set<JobStat> jobstatus) throws SQLException {
\r
150 log.info("Inserting " + jobstatus.size()
\r
151 + " new records into the statistics database");
\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
160 pstm.setString(1, js.webService.toString());
\r
162 if (!Util.isEmpty(js.clusterJobId)) {
\r
163 pstm.setString(2, js.clusterJobId);
\r
165 pstm.setString(2, null);
\r
168 pstm.setString(3, js.jobname);
\r
170 if (js.start != ExecutionStatCollector.UNDEFINED) {
\r
171 pstm.setTimestamp(4, new Timestamp(js.start));
\r
173 pstm.setTimestamp(4, null);
\r
175 if (js.finish != ExecutionStatCollector.UNDEFINED) {
\r
176 pstm.setTimestamp(5, new Timestamp(js.finish));
\r
178 pstm.setTimestamp(5, null);
\r
181 pstm.setLong(6, js.inputSize);
\r
183 pstm.setLong(7, js.resultSize);
\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
191 conn.setAutoCommit(true);
\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
202 date = res.getDate(1);
\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
216 public int getCancelledCount(Timestamp from, Timestamp to)
\r
217 throws SQLException {
\r
219 String cancelledQuery = "select count(*) from exec_stat where start BETWEEN ? and ? and isCancelled=1 ";
\r
220 return getIntResult(from, to, cancelledQuery);
\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
230 public int getIncompleteCount(Timestamp from, Timestamp to)
\r
231 throws SQLException {
\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
237 private int getIntResult(Timestamp from, Timestamp to, String query)
\r
238 throws SQLException {
\r
240 log.debug("getIntRes: QUERY: " + query);
\r
241 log.debug("getIntRes: FROM: " + from);
\r
242 log.debug("getIntRes: TO: " + to);
\r
244 PreparedStatement pstm = conn.prepareStatement(query);
\r
245 pstm.setTimestamp(1, from);
\r
246 pstm.setTimestamp(2, to);
\r
248 ResultSet res = pstm.getResultSet();
\r
249 boolean exist = res.next();
\r
252 count = res.getInt(1);
\r
254 log.debug("getIntRes: RES: " + count);
\r
260 public List<JobStat> readData(Timestamp from, Timestamp to,
\r
261 Services wservice, Boolean clusterOnly) throws SQLException {
\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
266 if (wservice != null) {
\r
267 query += " and service_name=? ";
\r
270 if (clusterOnly != null) {
\r
272 query += " and isClusterJob!=0 ";
\r
274 query += " and isClusterJob=0 ";
\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
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
290 List<JobStat> stats = new ArrayList<JobStat>();
\r
291 ResultSet rs = pstm.getResultSet();
\r
294 while (rs.next()) {
\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
302 log.debug("QUERY result len: " + rcount);
\r
310 * Removes the job if
\r
312 * 1) It has already been recorded
\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
318 * @throws SQLException
\r
320 public void removeRecordedJobs(Set<JobStat> fsJobs) throws SQLException {
\r
322 String query = "select job_id from exec_stat";
\r
324 Statement st = conn.createStatement();
\r
325 ResultSet result = st.executeQuery(query);
\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
338 public static synchronized final void shutdownDBServer() {
\r
339 // ## DATABASE SHUTDOWN SECTION ##
\r
341 * In embedded mode, an application should shut down Derby. Shutdown
\r
342 * throws the XJ015 exception to confirm success.
\r
345 if (conn != null) {
\r
348 } catch (SQLException e) {
\r
349 log.warn("Database commit failed with " + e.getLocalizedMessage());
\r
351 boolean gotSQLExc = false;
\r
353 DriverManager.getConnection("jdbc:derby:;shutdown=true");
\r
354 } catch (SQLException se) {
\r
355 if (se.getSQLState().equals("XJ015")) {
\r
360 log.warn("Database did not shut down normally");
\r
362 log.info("Database shut down normally");
\r
365 public static void main(String[] args) {
\r
366 // This is called from Ant cleanStatTable task
\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
374 // new StatDB().createStatTable();
\r
375 // insertData(null);
\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