standard function for bootstrapping discovery threads
[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             if (Cache.log.isDebugEnabled())
96             {
97               Cache.log.debug(ex);
98             }
99             // Deal with Transaction exceptions
100             wsInfo.appendProgressText(jobs[j].jobnum, "\n" + WebServiceName
101                     + " Server exception!\n" + ex.getMessage());
102             Cache.log.warn(WebServiceName + " job(" + jobs[j].jobnum
103                     + ") Server exception: " + ex.getMessage());
104
105             if (jobs[j].allowedServerExceptions > 0)
106             {
107               jobs[j].allowedServerExceptions--;
108               Cache.log.debug("Sleeping after a server exception.");
109               try
110               {
111                 Thread.sleep(5000);
112               } catch (InterruptedException ex1)
113               {
114               }
115             }
116             else
117             {
118               Cache.log.warn("Dropping job " + j + " " + jobs[j].jobId);
119               jobs[j].subjobComplete = true;
120               wsInfo.setStatus(jobs[j].jobnum,
121                       WebserviceInfo.STATE_STOPPED_SERVERERROR);
122             }
123           } catch (OutOfMemoryError er)
124           {
125             jobComplete = true;
126             jobs[j].subjobComplete = true;
127             jobs[j].clearResponse(); // may contain out of date result data
128             wsInfo.setStatus(jobs[j].jobnum,
129                     WebserviceInfo.STATE_STOPPED_ERROR);
130             Cache.log.error("Out of memory when retrieving Job " + j
131                     + " id:" + WsUrl + "/" + jobs[j].jobId, er);
132             new jalview.gui.OOMWarning("retrieving result for "
133                     + WebServiceName, er);
134             System.gc();
135           }
136         }
137         jstate.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
138       }
139       // Decide on overall state based on collected jobs[] states
140       if (jstate.running > 0)
141       {
142         wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);
143       }
144       else if (jstate.queuing > 0)
145       {
146         wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);
147       }
148       else
149       {
150         jobComplete = true;
151         if (jstate.finished > 0)
152         {
153           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
154         }
155         else if (jstate.error > 0)
156         {
157           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
158         }
159         else if (jstate.serror > 0)
160         {
161           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
162         }
163       }
164       if (!jobComplete)
165       {
166         try
167         {
168           Thread.sleep(5000);
169         } catch (InterruptedException e)
170         {
171           Cache.log
172                   .debug("Interrupted sleep waiting for next job poll.", e);
173         }
174         // System.out.println("I'm alive "+alTitle);
175       }
176     }
177     if (jobComplete && jobs != null)
178     {
179       parseResult(); // tidy up and make results available to user
180     }
181     else
182     {
183       Cache.log
184               .debug("WebServiceJob poll loop finished with no jobs created.");
185       wsInfo.setFinishedNoResults();
186     }
187   }
188
189
190   public AWSThread()
191   {
192     super();
193   }
194
195   public AWSThread(Runnable target)
196   {
197     super(target);
198   }
199
200   public AWSThread(String name)
201   {
202     super(name);
203   }
204
205   public AWSThread(ThreadGroup group, Runnable target)
206   {
207     super(group, target);
208   }
209
210   public AWSThread(ThreadGroup group, String name)
211   {
212     super(group, name);
213   }
214
215   public AWSThread(Runnable target, String name)
216   {
217     super(target, name);
218   }
219
220   public AWSThread(ThreadGroup group, Runnable target, String name)
221   {
222     super(group, target, name);
223   }
224
225   /**
226    * query web service for status of job. on return, job.result must not be null
227    * - if it is then it will be assumed that the job status query timed out and
228    * a server exception will be logged.
229    * 
230    * @param job
231    * @throws Exception
232    *           will be logged as a server exception for this job
233    */
234   public abstract void pollJob(AWsJob job) throws Exception;
235
236   /**
237    * submit job to web service
238    * 
239    * @param job
240    */
241   public abstract void StartJob(AWsJob job);
242
243   /**
244    * process the set of AWsJob objects into a set of results, and tidy up.
245    */
246   public abstract void parseResult();
247
248   /**
249    * helper function to conserve dataset references to sequence objects returned
250    * from web services 1. Propagates AlCodonFrame data from
251    * <code>codonframe</code> to <code>al</code>
252    * TODO: refactor to datamodel
253    * @param al
254    */
255   public void propagateDatasetMappings(Alignment al)
256   {
257     if (codonframe != null)
258     {
259       SequenceI[] alignment = al.getSequencesArray();
260       for (int sq = 0; sq < alignment.length; sq++)
261       {
262         for (int i = 0; i < codonframe.length; i++)
263         {
264           if (codonframe[i] != null
265                   && codonframe[i].involvesSequence(alignment[sq]))
266           {
267             al.addCodonFrame(codonframe[i]);
268             codonframe[i] = null;
269             break;
270           }
271         }
272       }
273     }
274   }
275
276   public AWSThread(ThreadGroup group, Runnable target, String name,
277           long stackSize)
278   {
279     super(group, target, name, stackSize);
280   }
281
282   /**
283    * 
284    * @return gap character to use for any alignment generation
285    */
286   public char getGapChar()
287   {
288     return defGapChar;
289   }
290
291   /**
292    * 
293    * @param alignFrame
294    *          reference for copying mappings across
295    * @param wsInfo
296    *          gui attachment point
297    * @param input
298    *          input data for the calculation
299    * @param webServiceName
300    *          name of service
301    * @param wsUrl
302    *          url of the service being invoked
303    */
304   public AWSThread(AlignFrame alignFrame, WebserviceInfo wsinfo,
305           AlignmentView input, String webServiceName, String wsUrl)
306   {
307     this(alignFrame, wsinfo, input, wsUrl);
308     WebServiceName = webServiceName;
309   }
310
311   /**
312    * 
313    * @param alframe
314    *          - reference for copying mappings and display styles across
315    * @param wsinfo2
316    *          - gui attachment point
317    * @param alview
318    *          - input data for the calculation
319    * @param wsurl2
320    *          - url of the service being invoked
321    */
322   public AWSThread(AlignFrame alframe, WebserviceInfo wsinfo2,
323           AlignmentView alview, String wsurl2)
324   {
325     super();
326     // this.alignFrame = alframe;
327     currentView = alframe.getCurrentView().getAlignment();
328     featureSettings = alframe.getFeatureRenderer().getSettings();
329     defGapChar = alframe.getViewport().getGapCharacter();
330     this.wsInfo = wsinfo2;
331     this.input = alview;
332     WsUrl = wsurl2;
333     if (alframe != null)
334     {
335       AlignedCodonFrame[] cf = alframe.getViewport().getAlignment()
336               .getCodonFrames();
337       if (cf != null)
338       {
339         codonframe = new AlignedCodonFrame[cf.length];
340         System.arraycopy(cf, 0, codonframe, 0, cf.length);
341       }
342     }
343   }
344 }