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