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