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