JAL-3690 changed AWSThread to use Timer instead
[jalview.git] / src / jalview / ws / AWSThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentView;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.WebserviceInfo;
31 import jalview.util.MessageManager;
32 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
33
34 import java.util.ArrayList;
35 import java.util.List;
36 import java.util.Timer;
37 import java.util.TimerTask;
38
39 import static java.lang.String.format;
40
41 public abstract class AWSThread
42 {
43   
44   private final Timer timer = new Timer();
45
46   /**
47    * view that this job was associated with
48    */
49   protected AlignmentI currentView = null;
50
51   /**
52    * feature settings from view that job was associated with
53    */
54   protected FeatureRendererSettings featureSettings = null;
55
56   /**
57    * metadata about this web service
58    */
59   protected WebserviceInfo wsInfo = null;
60
61   /**
62    * original input data for this job
63    */
64   protected AlignmentView input = null;
65
66   /**
67    * dataset sequence relationships to be propagated onto new results
68    */
69   protected List<AlignedCodonFrame> codonframe = null;
70
71   /**
72    * are there jobs still running in this thread.
73    *
74    * fixme: initialize with an empty array?
75    */
76   protected boolean jobComplete = false;
77
78   /**
79    * one or more jobs being managed by this thread.
80    */
81   protected AWsJob[] jobs = null;
82
83   /**
84    * full name of service
85    */
86   protected String WebServiceName = null;
87
88   protected char defGapChar = '-';
89
90   /**
91    * header prepended to all output from job
92    */
93   protected String OutputHeader;
94
95   /**
96    * only used when reporting a web service out of memory error - the job ID
97    * will be concatenated to the URL
98    */
99   protected String WsUrl = null;
100
101   /*
102    * The AlignFrame from which the service was requested.
103    */
104   private AlignFrame alignFrame;
105
106   public void start()
107   {
108     if (jobs == null)
109     {
110       jobComplete = true;
111       Cache.log.debug(
112           "WebServiceJob poll loop finished with no jobs created.");
113       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
114       wsInfo.appendProgressText(
115           MessageManager.getString("info.no_jobs_ran"));
116       wsInfo.setFinishedNoResults();
117       return;
118     }
119     TimerTask task = new TimerTask() {
120       @Override
121       public void run() 
122       {
123         JobStateSummary jstate = new JobStateSummary();
124         for (final AWsJob job : jobs)
125         {
126           if (!job.submitted && job.hasValidInput())
127           {
128             StartJob(job);
129           }
130           Cache.log.debug(format(
131                   "Job %s is %ssubmitted", job, job.submitted ? "" : "not "));
132           if (job.submitted && !job.subjobComplete)
133           {
134             Cache.log.debug(format(
135                     "Polling Job %s Result state was:%s(ServerError=%b)",
136                     job, job.getState(), job.isServerError()));
137             try
138             {
139               pollJob(job);
140               if (!job.hasResponse())
141                 throw new Exception("Timed out when communicating with server. Try again later.");
142               else
143                 Cache.log.debug(format("Job %s Result state:%s(ServerError=%b)",
144                         job, job.getState(), job.isServerError()));
145             } catch (Exception exc)
146             {
147               // Deal with Transaction exceptions
148               wsInfo.appendProgressText(job.jobnum, MessageManager
149                       .formatMessage("info.server_exception", WebServiceName,
150                           exc.getMessage()));
151               // always output the exception's stack trace to the log
152               Cache.log.warn(format("%s job(%s) Server exception.",
153                       WebServiceName, job.jobnum));
154               exc.printStackTrace();
155               
156               if (job.allowedServerExceptions > 0)
157               {
158                 job.allowedServerExceptions--;
159               }
160               else
161               {
162                 Cache.log.warn(format("Dropping job %s %s", job, job.jobId));
163                 job.subjobComplete = true;
164                 wsInfo.setStatus(job.jobnum, WebserviceInfo.STATE_STOPPED_SERVERERROR);
165               }
166             } catch (OutOfMemoryError oomerror)
167             {
168               jobComplete = true;
169               job.subjobComplete = true;
170               job.clearResponse();
171               wsInfo.setStatus(job.jobnum, WebserviceInfo.STATE_STOPPED_ERROR);
172               Cache.log.error(format("Out of memory when retrieving Job %s id:%s/%s",
173                       job, WsUrl, job.jobId), oomerror);
174               new jalview.gui.OOMWarning("retrieving result for " + WebServiceName, oomerror);
175               System.gc();
176             }
177           }
178           jstate.updateJobPanelState(wsInfo, OutputHeader, job);
179         }
180         // Decide on overall state based on collected jobs[] states
181         updateGlobalStatus(jstate);
182         if (jobComplete)
183         {
184           // jobs should never be null at this point
185           parseResult(); // tidy up and make results available to user
186           timer.cancel();
187         }
188       }
189     };
190     timer.schedule(task, 0, 5000);
191   }
192
193   protected void updateGlobalStatus(JobStateSummary jstate)
194   {
195     if (jstate.running > 0)
196     {
197       wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);
198     }
199     else if (jstate.queuing > 0)
200     {
201       wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);
202     }
203     else
204     {
205       jobComplete = true;
206       if (jstate.finished > 0)
207       {
208         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
209       }
210       else if (jstate.error > 0)
211       {
212         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
213       }
214       else if (jstate.serror > 0)
215       {
216         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
217       }
218     }
219   }
220   
221   public void interrupt()
222   {
223     timer.cancel();
224   }
225
226   /**
227    * query web service for status of job. on return, job.result must not be null
228    * - if it is then it will be assumed that the job status query timed out and
229    * a server exception will be logged.
230    * 
231    * @param job
232    * @throws Exception
233    *           will be logged as a server exception for this job
234    */
235   public abstract void pollJob(AWsJob job) throws Exception;
236
237   /**
238    * submit job to web service
239    * 
240    * @param job
241    */
242   public abstract void StartJob(AWsJob job);
243
244   /**
245    * process the set of AWsJob objects into a set of results, and tidy up.
246    */
247   public abstract void parseResult();
248
249   /**
250    * helper function to conserve dataset references to sequence objects returned
251    * from web services 1. Propagates AlCodonFrame data from
252    * <code>codonframe</code> to <code>al</code> TODO: refactor to datamodel
253    * 
254    * @param al
255    */
256   public void propagateDatasetMappings(Alignment al)
257   {
258     if (codonframe != null)
259     {
260       SequenceI[] alignment = al.getSequencesArray();
261       for (int sq = 0; sq < alignment.length; sq++)
262       {
263         for (AlignedCodonFrame acf : codonframe)
264         {
265           final SequenceI seq = alignment[sq];
266           if (acf != null && acf.involvesSequence(seq))
267           {
268             al.addCodonFrame(acf);
269             break;
270           }
271         }
272       }
273     }
274   }
275
276   /**
277    * 
278    * @return gap character to use for any alignment generation
279    */
280   public char getGapChar()
281   {
282     return defGapChar;
283   }
284
285   /**
286    * 
287    * @param alignFrame
288    *          reference for copying mappings across
289    * @param wsinfo
290    *          gui attachment point
291    * @param input
292    *          input data for the calculation
293    * @param webServiceName
294    *          name of service
295    * @param wsUrl
296    *          url of the service being invoked
297    */
298   public AWSThread(AlignFrame alignFrame, WebserviceInfo wsinfo,
299           AlignmentView input, String webServiceName, String wsUrl)
300   {
301     this(alignFrame, wsinfo, input, wsUrl);
302     WebServiceName = webServiceName;
303   }
304
305   /**
306    * Extracts additional info from alignment view's context.
307    * 
308    * @param alframe
309    *          - reference for copying mappings and display styles across
310    * @param wsinfo2
311    *          - gui attachment point - may be null
312    * @param alview
313    *          - input data for the calculation
314    * @param wsurl2
315    *          - url of the service being invoked
316    */
317   public AWSThread(AlignFrame alframe, WebserviceInfo wsinfo2,
318           AlignmentView alview, String wsurl2)
319   {
320     super();
321     this.alignFrame = alframe;
322     currentView = alframe.getCurrentView().getAlignment();
323     featureSettings = alframe.getFeatureRenderer().getSettings();
324     defGapChar = alframe.getViewport().getGapCharacter();
325     this.wsInfo = wsinfo2;
326     this.input = alview;
327     WsUrl = wsurl2;
328     if (alframe != null)
329     {
330       List<AlignedCodonFrame> cf = alframe.getViewport().getAlignment()
331               .getCodonFrames();
332       if (cf != null)
333       {
334         codonframe = new ArrayList<>();
335         codonframe.addAll(cf);
336       }
337     }
338   }
339
340   protected AlignFrame getRequestingAlignFrame()
341   {
342     return this.alignFrame;
343   }
344 }