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