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