JAL-2253 2 second timeout on ping URL, default 5 minutes on others
[jalview.git] / src / jalview / ext / ensembl / EnsemblRestClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.ext.ensembl;
22
23 import jalview.io.FileParse;
24 import jalview.util.StringUtils;
25
26 import java.io.BufferedReader;
27 import java.io.DataOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.net.HttpURLConnection;
32 import java.net.MalformedURLException;
33 import java.net.URL;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37
38 import javax.ws.rs.HttpMethod;
39
40 import org.json.simple.JSONArray;
41 import org.json.simple.JSONObject;
42 import org.json.simple.parser.JSONParser;
43
44 import com.stevesoft.pat.Regex;
45
46 /**
47  * Base class for Ensembl REST service clients
48  * 
49  * @author gmcarstairs
50  */
51 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
52 {
53   private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
54
55   private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
56
57   /*
58    * update these constants when Jalview has been checked / updated for
59    * changes to Ensembl REST API
60    * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
61    * @see http://rest.ensembl.org/info/rest?content-type=application/json
62    */
63   private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.6";
64
65   private static final String LATEST_ENSEMBL_REST_VERSION = "4.7";
66
67   private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
68
69   private static Map<String, EnsemblInfo> domainData;
70
71   // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
72   private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
73
74   private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
75
76   private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
77
78   private static final Regex TRANSCRIPT_REGEX = new Regex(
79           "(ENS)([A-Z]{3}|)T[0-9]{11}$");
80
81   private static final Regex GENE_REGEX = new Regex(
82           "(ENS)([A-Z]{3}|)G[0-9]{11}$");
83
84   static
85   {
86     domainData = new HashMap<String, EnsemblInfo>();
87     domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
88             LATEST_ENSEMBL_REST_VERSION));
89     domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
90             ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
91   }
92
93   protected volatile boolean inProgress = false;
94
95   /**
96    * Default constructor to use rest.ensembl.org
97    */
98   public EnsemblRestClient()
99   {
100     this(ENSEMBL_REST);
101   }
102
103   /**
104    * Constructor given the target domain to fetch data from
105    * 
106    * @param d
107    */
108   public EnsemblRestClient(String d)
109   {
110     setDomain(d);
111   }
112
113   /**
114    * Answers true if the query matches the regular expression pattern for an
115    * Ensembl transcript stable identifier
116    * 
117    * @param query
118    * @return
119    */
120   public boolean isTranscriptIdentifier(String query)
121   {
122     return query == null ? false : TRANSCRIPT_REGEX.search(query);
123   }
124
125   /**
126    * Answers true if the query matches the regular expression pattern for an
127    * Ensembl gene stable identifier
128    * 
129    * @param query
130    * @return
131    */
132   public boolean isGeneIdentifier(String query)
133   {
134     return query == null ? false : GENE_REGEX.search(query);
135   }
136
137   @Override
138   public boolean queryInProgress()
139   {
140     return inProgress;
141   }
142
143   @Override
144   public StringBuffer getRawRecords()
145   {
146     return null;
147   }
148
149   /**
150    * Returns the URL for the client http request
151    * 
152    * @param ids
153    * @return
154    * @throws MalformedURLException
155    */
156   protected abstract URL getUrl(List<String> ids)
157           throws MalformedURLException;
158
159   /**
160    * Returns true if client uses GET method, false if it uses POST
161    * 
162    * @return
163    */
164   protected abstract boolean useGetRequest();
165
166   /**
167    * Return the desired value for the Content-Type request header
168    * 
169    * @param multipleIds
170    * 
171    * @return
172    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
173    */
174   protected abstract String getRequestMimeType(boolean multipleIds);
175
176   /**
177    * Return the desired value for the Accept request header
178    * 
179    * @return
180    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
181    */
182   protected abstract String getResponseMimeType();
183
184   /**
185    * Checks Ensembl's REST 'ping' endpoint, and returns true if response
186    * indicates available, else false
187    * 
188    * @see http://rest.ensembl.org/documentation/info/ping
189    * @return
190    */
191   private boolean checkEnsembl()
192   {
193     BufferedReader br = null;
194     try
195     {
196       // note this format works for both ensembl and ensemblgenomes
197       // info/ping.json works for ensembl only (March 2016)
198       URL ping = new URL(getDomain()
199               + "/info/ping?content-type=application/json");
200
201       /*
202        * expect {"ping":1} if ok
203        * if ping takes more than 2 seconds to respond, treat as if unavailable
204        */
205       br = getHttpResponse(ping, null, 2 * 1000);
206       JSONParser jp = new JSONParser();
207       JSONObject val = (JSONObject) jp.parse(br);
208       String pingString = val.get("ping").toString();
209       return pingString != null;
210     } catch (Throwable t)
211     {
212       System.err.println("Error connecting to " + PING_URL + ": "
213               + t.getMessage());
214     } finally
215     {
216       if (br != null)
217       {
218         try
219         {
220           br.close();
221         } catch (IOException e)
222         {
223           // ignore
224         }
225       }
226     }
227     return false;
228   }
229
230   /**
231    * returns a reader to a Fasta response from the Ensembl sequence endpoint
232    * 
233    * @param ids
234    * @return
235    * @throws IOException
236    */
237   protected FileParse getSequenceReader(List<String> ids)
238           throws IOException
239   {
240     URL url = getUrl(ids);
241
242     BufferedReader reader = getHttpResponse(url, ids);
243     if (reader == null)
244     {
245       // request failed
246       return null;
247     }
248     FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
249     return fp;
250   }
251
252   /**
253    * Gets a reader to the HTTP response, using the default read timeout of 5
254    * minutes
255    * 
256    * @param url
257    * @param ids
258    * @return
259    * @throws IOException
260    */
261   protected BufferedReader getHttpResponse(URL url, List<String> ids)
262           throws IOException
263   {
264     return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
265   }
266
267   /**
268    * Writes the HTTP request and gets the response as a reader.
269    * 
270    * @param url
271    * @param ids
272    *          written as Json POST body if more than one
273    * @param readTimeout
274    *          in milliseconds
275    * @return
276    * @throws IOException
277    *           if response code was not 200, or other I/O error
278    */
279   protected BufferedReader getHttpResponse(URL url, List<String> ids,
280           int readTimeout) throws IOException
281   {
282     // long now = System.currentTimeMillis();
283     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
284
285     /*
286      * POST method allows multiple queries in one request; it is supported for
287      * sequence queries, but not for overlap
288      */
289     boolean multipleIds = ids != null && ids.size() > 1;
290     connection.setRequestMethod(multipleIds ? HttpMethod.POST
291             : HttpMethod.GET);
292     connection.setRequestProperty("Content-Type",
293             getRequestMimeType(multipleIds));
294     connection.setRequestProperty("Accept", getResponseMimeType());
295
296     connection.setUseCaches(false);
297     connection.setDoInput(true);
298     connection.setDoOutput(multipleIds);
299
300     connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
301     connection.setReadTimeout(readTimeout);
302
303     if (multipleIds)
304     {
305       writePostBody(connection, ids);
306     }
307
308     int responseCode = connection.getResponseCode();
309
310     if (responseCode != 200)
311     {
312       /*
313        * note: a GET request for an invalid id returns an error code e.g. 415
314        * but POST request returns 200 and an empty Fasta response 
315        */
316       System.err.println("Response code " + responseCode + " for " + url);
317       return null;
318     }
319     // get content
320     InputStream response = connection.getInputStream();
321
322     // System.out.println(getClass().getName() + " took "
323     // + (System.currentTimeMillis() - now) + "ms to fetch");
324
325     checkRateLimits(connection);
326
327     BufferedReader reader = null;
328     reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
329     return reader;
330   }
331
332   /**
333    * Inspect response headers for any sign of server overload and respect any
334    * 'retry-after' directive
335    * 
336    * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
337    * @param connection
338    */
339   void checkRateLimits(HttpURLConnection connection)
340   {
341     // number of requests allowed per time interval:
342     String limit = connection.getHeaderField("X-RateLimit-Limit");
343     // length of quota time interval in seconds:
344     // String period = connection.getHeaderField("X-RateLimit-Period");
345     // seconds remaining until usage quota is reset:
346     String reset = connection.getHeaderField("X-RateLimit-Reset");
347     // number of requests remaining from quota for current period:
348     String remaining = connection.getHeaderField("X-RateLimit-Remaining");
349     // number of seconds to wait before retrying (if remaining == 0)
350     String retryDelay = connection.getHeaderField("Retry-After");
351
352     // to test:
353     // retryDelay = "5";
354
355     EnsemblInfo info = domainData.get(getDomain());
356     if (retryDelay != null)
357     {
358       System.err.println("Ensembl REST service rate limit exceeded, wait "
359               + retryDelay + " seconds before retrying");
360       try
361       {
362         info.retryAfter = System.currentTimeMillis()
363                 + (1000 * Integer.valueOf(retryDelay));
364       } catch (NumberFormatException e)
365       {
366         System.err.println("Unexpected value for Retry-After: "
367                 + retryDelay);
368       }
369     }
370     else
371     {
372       info.retryAfter = 0;
373       // debug:
374       // System.out.println(String.format(
375       // "%s Ensembl requests remaining of %s (reset in %ss)",
376       // remaining, limit, reset));
377     }
378   }
379
380   /**
381    * Rechecks if Ensembl is responding, unless the last check was successful and
382    * the retest interval has not yet elapsed. Returns true if Ensembl is up,
383    * else false. Also retrieves and saves the current version of Ensembl data
384    * and REST services at intervals.
385    * 
386    * @return
387    */
388   protected boolean isEnsemblAvailable()
389   {
390     EnsemblInfo info = domainData.get(getDomain());
391
392     long now = System.currentTimeMillis();
393
394     /*
395      * check if we are waiting for 'Retry-After' to expire
396      */
397     if (info.retryAfter > now)
398     {
399       System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
400               + " secs to wait before retrying Ensembl");
401       return false;
402     }
403     else
404     {
405       info.retryAfter = 0;
406     }
407
408     /*
409      * recheck if Ensembl is up if it was down, or the recheck period has elapsed
410      */
411     boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
412     if (!info.restAvailable || retestAvailability)
413     {
414       info.restAvailable = checkEnsembl();
415       info.lastAvailableCheckTime = now;
416     }
417
418     /*
419      * refetch Ensembl versions if the recheck period has elapsed
420      */
421     boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
422     if (refetchVersion)
423     {
424       checkEnsemblRestVersion();
425       checkEnsemblDataVersion();
426       info.lastVersionCheckTime = now;
427     }
428
429     return info.restAvailable;
430   }
431
432   /**
433    * Constructs, writes and flushes the POST body of the request, containing the
434    * query ids in JSON format
435    * 
436    * @param connection
437    * @param ids
438    * @throws IOException
439    */
440   protected void writePostBody(HttpURLConnection connection,
441           List<String> ids) throws IOException
442   {
443     boolean first;
444     StringBuilder postBody = new StringBuilder(64);
445     postBody.append("{\"ids\":[");
446     first = true;
447     for (String id : ids)
448     {
449       if (!first)
450       {
451         postBody.append(",");
452       }
453       first = false;
454       postBody.append("\"");
455       postBody.append(id.trim());
456       postBody.append("\"");
457     }
458     postBody.append("]}");
459     byte[] thepostbody = postBody.toString().getBytes();
460     connection.setRequestProperty("Content-Length",
461             Integer.toString(thepostbody.length));
462     DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
463     wr.write(thepostbody);
464     wr.flush();
465     wr.close();
466   }
467
468   /**
469    * Fetches and checks Ensembl's REST version number
470    * 
471    * @return
472    */
473   private void checkEnsemblRestVersion()
474   {
475     EnsemblInfo info = domainData.get(getDomain());
476
477     JSONParser jp = new JSONParser();
478     URL url = null;
479     try
480     {
481       url = new URL(getDomain()
482               + "/info/rest?content-type=application/json");
483       BufferedReader br = getHttpResponse(url, null);
484       JSONObject val = (JSONObject) jp.parse(br);
485       String version = val.get("release").toString();
486       String majorVersion = version.substring(0, version.indexOf("."));
487       String expected = info.expectedRestVersion;
488       String expectedMajorVersion = expected.substring(0,
489               expected.indexOf("."));
490       info.restMajorVersionMismatch = false;
491       try
492       {
493         /*
494          * if actual REST major version is ahead of what we expect,
495          * record this in case we want to warn the user
496          */
497         if (Float.valueOf(majorVersion) > Float
498                 .valueOf(expectedMajorVersion))
499         {
500           info.restMajorVersionMismatch = true;
501         }
502       } catch (NumberFormatException e)
503       {
504         System.err.println("Error in REST version: " + e.toString());
505       }
506
507       /*
508        * check if REST version is later than what Jalview has tested against,
509        * if so warn; we don't worry if it is earlier (this indicates Jalview has
510        * been tested in advance against the next pending REST version)
511        */
512       boolean laterVersion = StringUtils.compareVersions(version, expected) == 1;
513       if (laterVersion)
514       {
515         System.err.println(String.format(
516                 "Expected %s REST version %s but found %s, see %s",
517                 getDbSource(), expected, version, REST_CHANGE_LOG));
518       }
519       info.restVersion = version;
520     } catch (Throwable t)
521     {
522       System.err.println("Error checking Ensembl REST version: "
523               + t.getMessage());
524     }
525   }
526
527   public boolean isRestMajorVersionMismatch()
528   {
529     return domainData.get(getDomain()).restMajorVersionMismatch;
530   }
531
532   /**
533    * Fetches and checks Ensembl's data version number
534    * 
535    * @return
536    */
537   private void checkEnsemblDataVersion()
538   {
539     JSONParser jp = new JSONParser();
540     URL url = null;
541     try
542     {
543       url = new URL(getDomain()
544               + "/info/data?content-type=application/json");
545       BufferedReader br = getHttpResponse(url, null);
546       JSONObject val = (JSONObject) jp.parse(br);
547       JSONArray versions = (JSONArray) val.get("releases");
548       domainData.get(getDomain()).dataVersion = versions.get(0).toString();
549     } catch (Throwable t)
550     {
551       System.err.println("Error checking Ensembl data version: "
552               + t.getMessage());
553     }
554   }
555
556   public String getEnsemblDataVersion()
557   {
558     return domainData.get(getDomain()).dataVersion;
559   }
560
561   @Override
562   public String getDbVersion()
563   {
564     return getEnsemblDataVersion();
565   }
566
567 }