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