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