A bug fix, help text for stat jsp pages and style improvements
[jabaws.git] / webservices / compbio / stat / collector / ExecutionStatCollector.java
1 package compbio.stat.collector;\r
2 \r
3 import java.io.File;\r
4 import java.io.FileFilter;\r
5 import java.io.IOException;\r
6 import java.sql.SQLException;\r
7 import java.text.SimpleDateFormat;\r
8 import java.util.ArrayList;\r
9 import java.util.Date;\r
10 import java.util.HashMap;\r
11 import java.util.HashSet;\r
12 import java.util.List;\r
13 import java.util.Map;\r
14 import java.util.Set;\r
15 \r
16 import org.apache.log4j.Logger;\r
17 \r
18 import compbio.engine.client.Executable;\r
19 import compbio.engine.client.PathValidator;\r
20 import compbio.metadata.JobStatus;\r
21 import compbio.util.FileUtil;\r
22 import compbio.ws.client.Services;\r
23 \r
24 /**\r
25  * Number of runs of each WS = number of folders with name\r
26  * \r
27  * Number of successful runs = all runs with no result file\r
28  * \r
29  * Per period of time = limit per file creating time Runtime (avg/max) =\r
30  * \r
31  * started time - finished time\r
32  * \r
33  * Task & result size = result.size\r
34  * \r
35  * Abandoned runs - not collected runs\r
36  * \r
37  * Cancelled runs - cancelled\r
38  * \r
39  * Cluster vs local runs\r
40  * \r
41  * Reasons for failure = look in the err out?\r
42  * \r
43  * \r
44  * Metadata required:\r
45  * \r
46  * work directory for local and cluster tasks = from Helper or cmd parameter. WS\r
47  * names - enumeration. Status file names and content.\r
48  * \r
49  * @author pvtroshin\r
50  * \r
51  */\r
52 public class ExecutionStatCollector implements Runnable {\r
53 \r
54         static final int UNDEFINED = -1;\r
55 \r
56         private static final Logger log = Logger\r
57                         .getLogger(ExecutionStatCollector.class);\r
58 \r
59         static SimpleDateFormat DF = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");\r
60 \r
61         final private File workDirectory;\r
62         final private List<JobStat> stats;\r
63         /**\r
64          * Consider the job that has been working for longer than timeOutInHours\r
65          * completed, whatever the outcome\r
66          */\r
67         final private int timeOutInHours;\r
68 \r
69         /**\r
70          * List subdirectories in the job directory\r
71          * \r
72          * @param workDirectory\r
73          * @param timeOutInHours\r
74          */\r
75         public ExecutionStatCollector(String workDirectory, int timeOutInHours) {\r
76                 log.info("Starting stat collector for directory: " + workDirectory);\r
77                 log.info("Maximum allowed runtime(h): " + timeOutInHours);\r
78                 if (!PathValidator.isValidDirectory(workDirectory)) {\r
79                         throw new IllegalArgumentException("workDirectory '"\r
80                                         + workDirectory + "' does not exist!");\r
81                 }\r
82                 this.workDirectory = new File(workDirectory);\r
83                 stats = new ArrayList<JobStat>();\r
84                 if (timeOutInHours <= 0) {\r
85                         throw new IllegalArgumentException(\r
86                                         "Timeout value must be greater than 0! Given value: "\r
87                                                         + timeOutInHours);\r
88                 }\r
89                 this.timeOutInHours = timeOutInHours;\r
90         }\r
91 \r
92         boolean hasCompleted(JobDirectory jd) {\r
93                 JobStat jstat = jd.getJobStat();\r
94                 if (jstat.hasResult() || jstat.getIsCancelled()\r
95                                 || jstat.getIsFinished() || hasTimedOut(jd)) {\r
96                         return true;\r
97                 }\r
98                 return false;\r
99         }\r
100 \r
101         boolean hasTimedOut(JobDirectory jd) {\r
102                 return ((System.currentTimeMillis() - jd.jobdir.lastModified()) / (1000 * 60 * 60)) > timeOutInHours;\r
103         }\r
104 \r
105         StatProcessor getStats() {\r
106                 return new StatProcessor(stats);\r
107         }\r
108 \r
109         void writeStatToDB() throws SQLException {\r
110                 Set<JobStat> rjobs = new HashSet<JobStat>(stats);\r
111                 StatDB statdb = new StatDB();\r
112                 log.debug("Removing records that has already been recorded");\r
113 \r
114                 statdb.removeRecordedJobs(rjobs);\r
115                 log.debug("New records left: " + rjobs.size());\r
116                 statdb.insertData(rjobs);\r
117         }\r
118 \r
119         /*\r
120          * static void updateTime(File statFile) throws IOException { long lastMod =\r
121          * statFile.lastModified(); FileWriter fw = new FileWriter(statFile);\r
122          * fw.write(new Long(lastMod).toString()); fw.close(); }\r
123          */\r
124 \r
125         /**\r
126          * Not in use\r
127          */\r
128         public static void main(String[] args) throws IOException, SQLException {\r
129 \r
130                 // updateTime(new File(\r
131                 // "D:\\workspace\\JABA2\\jobsout\\AACon#170462904473672\\STARTED"));\r
132 \r
133                 File[] files = FileUtil.getFiles("Y:\\fc\\www-jws2\\jaba\\jobsout",\r
134                                 directories);\r
135                 List<JobStat> stats = new ArrayList<JobStat>();\r
136                 for (File file : files) {\r
137                         JobDirectory jd = new JobDirectory(file);\r
138                         stats.add(jd.getJobStat());\r
139                         // System.out.println(jd.getJobStat().getJobReportTabulated());\r
140                 }\r
141                 StatProcessor sp = new StatProcessor(stats);\r
142                 System.out.println(sp.reportStat());\r
143                 System.out.println();\r
144                 System.out.println("!!!!!!!!!!!!!!!!!!");\r
145                 System.out.println();\r
146 \r
147                 Set<JobStat> rjobs = new HashSet<JobStat>(sp.stats);\r
148                 StatDB statdb = new StatDB();\r
149                 statdb.removeRecordedJobs(rjobs);\r
150                 statdb.insertData(rjobs);\r
151         }\r
152 \r
153         static FileFilter directories = new FileFilter() {\r
154                 @Override\r
155                 public boolean accept(File pathname) {\r
156                         return pathname.isDirectory()\r
157                                         && !pathname.getName().startsWith(".");\r
158                 }\r
159         };\r
160 \r
161         static class JobDirectory {\r
162 \r
163                 File jobdir;\r
164                 Map<String, File> files = new HashMap<String, File>();\r
165 \r
166                 JobDirectory(File directory) {\r
167                         this.jobdir = directory;\r
168                         for (File f : jobdir.listFiles()) {\r
169                                 files.put(f.getName(), f);\r
170                         }\r
171                 }\r
172 \r
173                 boolean hasStatus(JobStatus status) {\r
174                         return files.containsKey(status.toString());\r
175                 }\r
176 \r
177                 boolean isCollected() {\r
178                         return hasStatus(JobStatus.COLLECTED);\r
179                 }\r
180 \r
181                 boolean isCancelled() {\r
182                         return hasStatus(JobStatus.CANCELLED);\r
183                 }\r
184 \r
185                 long getStartTime() {\r
186                         long starttime = UNDEFINED;\r
187                         File startfile = files.get(JobStatus.STARTED.toString());\r
188                         if (startfile == null) {\r
189                                 startfile = files.get(JobStatus.SUBMITTED.toString());\r
190                         }\r
191                         if (startfile != null) {\r
192                                 starttime = startfile.lastModified();\r
193                                 /*\r
194                                  * String start = FileUtil.readFileToString(startfile);\r
195                                  * starttime = Long.parseLong(start.trim());\r
196                                  */\r
197                         }\r
198                         return starttime;\r
199                 }\r
200 \r
201                 String getClusterJobID() {\r
202                         String clustjobId = "";\r
203                         File jobid = files.get("JOBID");\r
204                         try {\r
205                                 if (jobid != null) {\r
206                                         clustjobId = FileUtil.readFileToString(jobid);\r
207                                 }\r
208                         } catch (IOException ioe) {\r
209                                 log.error(\r
210                                                 "IO Exception while reading the content of JOBID file for job "\r
211                                                                 + jobid, ioe);\r
212                         }\r
213                         return clustjobId.trim();\r
214                 }\r
215 \r
216                 long getFinishedTime() {\r
217                         long ftime = UNDEFINED;\r
218                         File finished = files.get(JobStatus.FINISHED.toString());\r
219                         if (finished != null) {\r
220                                 ftime = finished.lastModified();\r
221                                 /*\r
222                                  * String start = FileUtil.readFileToString(finished); ftime =\r
223                                  * Long.parseLong(start.trim());\r
224                                  */\r
225                                 // System.out.println("f " + ftime);\r
226                         }\r
227                         /*\r
228                          * } catch (IOException e) { log.log(Level.WARN,\r
229                          * "Cannot parse finished time: " + e.getMessage(), e); } catch\r
230                          * (NumberFormatException e) { log.log(Level.WARN,\r
231                          * "Cannot parse finished time: " + e.getMessage(), e); }\r
232                          */\r
233                         return ftime;\r
234                 }\r
235 \r
236                 private Services getService() {\r
237                         return Services.getServiceByJobDirectory(jobdir);\r
238                 }\r
239 \r
240                 // Mafft, Muscle, Tcoffee, Clustal task:fasta.in result:fasta.out\r
241                 // Probcons task:fasta.in result:alignment.out\r
242                 /*\r
243                  * TODO replace with Universal names for WS!\r
244                  */\r
245                 long getResultSize() {\r
246                         Class<? extends Executable<?>> name = Services\r
247                                         .getRunnerByJobDirectory(jobdir);\r
248 \r
249                         File f = null;\r
250                         if (name.getSimpleName().equalsIgnoreCase("Probcons")) {\r
251                                 f = files.get("alignment.out");\r
252                         } else if (name.getSimpleName().equalsIgnoreCase("ClustalW")) {\r
253                                 f = files.get("output.txt");\r
254                         } else {\r
255                                 f = files.get("fasta.out");\r
256                         }\r
257                         if (f != null) {\r
258                                 return f.length();\r
259                         }\r
260                         return UNDEFINED;\r
261                 }\r
262 \r
263                 /*\r
264                  * TODO unify input!\r
265                  */\r
266                 long getInputSize() {\r
267                         Class<? extends Executable<?>> name = Services\r
268                                         .getRunnerByJobDirectory(jobdir);\r
269 \r
270                         File input = null;\r
271                         if (name.getSimpleName().equalsIgnoreCase("ClustalW")) {\r
272                                 input = files.get("input.txt");\r
273                         } else {\r
274                                 input = files.get("fasta.in");\r
275                         }\r
276 \r
277                         if (input != null) {\r
278                                 return input.length();\r
279                         }\r
280                         return UNDEFINED;\r
281                 }\r
282 \r
283                 JobStat getJobStat() {\r
284                         return JobStat.newInstance(getService(), getClusterJobID(),\r
285                                         jobdir.getName(), getStartTime(), getFinishedTime(),\r
286                                         getInputSize(), getResultSize(), isCancelled(),\r
287                                         isCollected());\r
288                 }\r
289 \r
290                 @Override\r
291                 public int hashCode() {\r
292                         final int prime = 31;\r
293                         int result = 1;\r
294                         result = prime * result\r
295                                         + ((jobdir == null) ? 0 : jobdir.hashCode());\r
296                         return result;\r
297                 }\r
298 \r
299                 @Override\r
300                 public boolean equals(Object obj) {\r
301                         if (this == obj)\r
302                                 return true;\r
303                         if (obj == null)\r
304                                 return false;\r
305                         if (getClass() != obj.getClass())\r
306                                 return false;\r
307                         JobDirectory other = (JobDirectory) obj;\r
308                         if (jobdir == null) {\r
309                                 if (other.jobdir != null)\r
310                                         return false;\r
311                         } else if (!jobdir.equals(other.jobdir))\r
312                                 return false;\r
313                         return true;\r
314                 }\r
315         }\r
316 \r
317         private void collectStatistics() {\r
318                 File[] files = workDirectory.listFiles(directories);\r
319                 for (File file : files) {\r
320                         JobDirectory jd = new JobDirectory(file);\r
321                         JobStat jstat = jd.getJobStat();\r
322                         // Do not record stats on the job that has not completed yet\r
323                         if (hasCompleted(jd)) {\r
324                                 stats.add(jstat);\r
325                         } else {\r
326                                 log.debug("Skipping the job: " + jstat);\r
327                                 log.debug("As it has not completed yet");\r
328                         }\r
329                         // System.out.println(jd.getJobStat().getJobReportTabulated());\r
330                 }\r
331         }\r
332 \r
333         @Override\r
334         public void run() {\r
335                 log.info("Started updating statistics at " + new Date());\r
336                 log.info("For directory: " + workDirectory.getAbsolutePath());\r
337 \r
338                 collectStatistics();\r
339 \r
340                 StatProcessor local_stats = getStats();\r
341                 log.info("Found " + local_stats.getJobNumber() + " jobs!");\r
342                 try {\r
343                         writeStatToDB();\r
344                 } catch (SQLException e) {\r
345                         log.error("Fails to update jobs statistics database!");\r
346                         log.error(e.getLocalizedMessage(), e);\r
347                 }\r
348                 log.info("Finished updating statistics at " + new Date());\r
349         }\r
350 }\r