JAL-3730 retry ping before failing; sysout logging changed to Cache.log
[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 java.io.DataOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.HttpURLConnection;
27 import java.net.MalformedURLException;
28 import java.net.ProtocolException;
29 import java.net.URL;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.ws.rs.HttpMethod;
35
36 import org.json.simple.parser.ParseException;
37
38 import jalview.bin.Cache;
39 import jalview.util.Platform;
40 import jalview.util.StringUtils;
41
42 /**
43  * Base class for Ensembl REST service clients
44  * 
45  * @author gmcarstairs
46  */
47 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
48 {
49   private static final int HTTP_OK = 200;
50
51   private static final int HTTP_OVERLOAD = 429;
52
53   static
54   {
55     Platform.addJ2SDirectDatabaseCall("http://rest.ensembl");
56     Platform.addJ2SDirectDatabaseCall("https://rest.ensembl");
57   }
58
59   /*
60    * constants for http retries and timeout;
61    * not final so they can be changed by a Groovy script
62    */
63   private static int PING_TIMEOUT_MS = 2 * 1000;
64
65   private static long PING_RETEST_INTERVAL = 10 * 1000L; // 10 seconds
66
67   private static int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
68
69   private static int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
70
71   private static int MAX_RETRIES = 3;
72
73   /*
74    * update these constants when Jalview has been checked / updated for
75    * changes to Ensembl REST API, and updated JAL-3018
76    * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
77    * @see http://rest.ensembl.org/info/rest?content-type=application/json
78    */
79   private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "12.0";
80
81   private static final String LATEST_ENSEMBL_REST_VERSION = "12.0";
82
83   private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
84
85   private static Map<String, EnsemblData> domainData;
86
87   private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
88
89   protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
90
91   static
92   {
93     domainData = new HashMap<>();
94     domainData.put(DEFAULT_ENSEMBL_BASEURL, new EnsemblData(
95             DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
96     domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL,
97             new EnsemblData(DEFAULT_ENSEMBL_GENOMES_BASEURL,
98                     LATEST_ENSEMBLGENOMES_REST_VERSION));
99   }
100
101   protected volatile boolean inProgress = false;
102
103   /**
104    * Default constructor to use rest.ensembl.org
105    */
106   public EnsemblRestClient()
107   {
108     super();
109
110     /*
111      * initialise domain info lazily
112      */
113     if (!domainData.containsKey(ensemblDomain))
114     {
115       domainData.put(ensemblDomain,
116               new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
117     }
118     if (!domainData.containsKey(ensemblGenomesDomain))
119     {
120       domainData.put(ensemblGenomesDomain, new EnsemblData(
121               ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
122     }
123   }
124
125   /**
126    * Constructor given the target domain to fetch data from
127    * 
128    * @param d
129    */
130   public EnsemblRestClient(String d)
131   {
132     setDomain(d);
133   }
134
135   @Override
136   public boolean queryInProgress()
137   {
138     return inProgress;
139   }
140
141   @Override
142   public StringBuffer getRawRecords()
143   {
144     return null;
145   }
146
147   /**
148    * Returns the URL for the client http request
149    * 
150    * @param ids
151    * @return
152    * @throws MalformedURLException
153    */
154   protected abstract URL getUrl(List<String> ids)
155           throws MalformedURLException;
156
157   /**
158    * Returns true if client uses GET method, false if it uses POST
159    * 
160    * @return
161    */
162   protected abstract boolean useGetRequest();
163
164   /**
165    * Returns the desired value for the Content-Type request header. Default is
166    * application/json, override if required to vary this.
167    * 
168    * @return
169    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
170    */
171   protected String getRequestMimeType()
172   {
173     return "application/json";
174   }
175
176   /**
177    * Return the desired value for the Accept request header. Default is
178    * application/json, override if required to vary this.
179    * 
180    * @return
181    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
182    */
183   protected String getResponseMimeType()
184   {
185     return "application/json";
186   }
187
188   /**
189    * Checks Ensembl's REST 'ping' endpoint, and returns true if response
190    * indicates available, else false
191    * 
192    * @see http://rest.ensembl.org/documentation/info/ping
193    * @return
194    */
195   boolean checkEnsembl()
196   {
197     String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
198     for (int i = 0 ; i < MAX_RETRIES ; i++)
199     {
200       if (pingEnsembl(pingUrl))
201       {
202         if (i > 0)
203         {
204           Cache.log.info("Ensembl ping responded on attempt " + (i+1));
205         }
206         return true;
207       }
208     }
209     Cache.log.error("Ensembl ping failed after " + MAX_RETRIES + " retries");
210     return false;
211   }
212
213   /**
214    * Connects to Ensembl REST service's 'ping' URL and answers true if
215    * successful, false if no reply, or no reply within the 2 second timeout
216    * 
217    * @param pingUrl
218    * @return
219    */
220   @SuppressWarnings("unchecked")
221   protected boolean pingEnsembl(String pingUrl)
222   {
223     try
224     {
225       // note this format works for both ensembl and ensemblgenomes
226       // info/ping.json works for ensembl only (March 2016)
227
228       /*
229        * expect {"ping":1} if ok
230        * if ping takes more than 2 seconds to respond, treat as if unavailable
231        */
232       Map<String, Object> val = (Map<String, Object>) getJSON(
233               new URL(pingUrl), null, PING_TIMEOUT_MS, MODE_MAP, null);
234       if (val == null)
235       {
236         return false;
237       }
238       String pingString = val.get("ping").toString();
239       return pingString != null;
240     } catch (Throwable t)
241     {
242       Cache.log.error(
243               "Error connecting to " + pingUrl + ": " + t.getMessage());
244       return false;
245     }
246   }
247
248   protected final static int MODE_ARRAY = 0;
249
250   protected final static int MODE_MAP = 1;
251
252   protected final static int MODE_ITERATOR = 2;
253
254   // /**
255   // * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
256   // * If the request failed the return value may be null.
257   // *
258   // * @param ids
259   // * @return
260   // * @throws IOException
261   // * @throws ParseException
262   // */
263   // protected Object getSequenceJSON(List<String> ids, int mode)
264   // throws IOException, ParseException
265   // {
266   // URL url = getUrl(ids);
267   // return getJSON(url, ids, -1, mode);
268   // }
269   //
270   // /**
271   // * Gets a reader to the HTTP response, using the default read timeout of 5
272   // * minutes
273   // *
274   // * @param url
275   // * @param ids
276   // * @return
277   // * @throws IOException
278   // */
279   // protected BufferedReader getHttpResponse(URL url, List<String> ids)
280   // throws IOException
281   // {
282   // return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
283   // }
284
285   /**
286    * Sends the HTTP request and gets the response as a reader. Returns null if
287    * the HTTP response code was not 200.
288    * 
289    * @param url
290    * @param ids
291    *          written as Json POST body if more than one
292    * @param readTimeout
293    *          in milliseconds
294    * @return
295    * @throws IOException
296    * @throws ParseException
297    */
298   private Object getJSON(URL url, List<String> ids, int readTimeout)
299           throws IOException, ParseException
300   {
301
302     if (readTimeout < 0)
303     {
304       readTimeout = DEFAULT_READ_TIMEOUT;
305     }
306     int retriesLeft = MAX_RETRIES;
307     HttpURLConnection connection = null;
308     int responseCode = 0;
309
310     Platform.setAjaxJSON(url);
311
312     while (retriesLeft > 0)
313     {
314       connection = tryConnection(url, ids, readTimeout);
315       responseCode = connection.getResponseCode();
316       if (responseCode == HTTP_OVERLOAD) // 429
317       {
318         retriesLeft--;
319         checkRetryAfter(connection);
320       }
321       else
322       {
323         retriesLeft = 0;
324       }
325     }
326     if (responseCode != HTTP_OK) // 200
327     {
328       /*
329        * note: a GET request for an invalid id returns an error code e.g. 415
330        * but POST request returns 200 and an empty Fasta response 
331        */
332       Cache.log.error("Response code " + responseCode);// + " for " + url);
333       return null;
334     }
335
336     InputStream response = connection.getInputStream();
337
338     // Platform.timeCheck(null, Platform.TIME_MARK);
339     Object ret = Platform.parseJSON(response);
340     // Platform.timeCheck("EnsemblRestClient.getJSON " + url,
341     // Platform.TIME_MARK);
342
343     return ret;
344   }
345
346   /**
347    * @param url
348    * @param ids
349    * @param readTimeout
350    * @return
351    * @throws IOException
352    * @throws ProtocolException
353    */
354   protected HttpURLConnection tryConnection(URL url, List<String> ids,
355           int readTimeout) throws IOException, ProtocolException
356   {
357     // System.out.println(System.currentTimeMillis() + " " + url);
358
359     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
360
361     /*
362      * POST method allows multiple queries in one request; it is supported for
363      * sequence queries, but not for overlap
364      */
365     boolean multipleIds = ids != null && ids.size() > 1;
366     connection.setRequestMethod(
367             multipleIds ? HttpMethod.POST : HttpMethod.GET);
368     connection.setRequestProperty("Content-Type", getRequestMimeType());
369     connection.setRequestProperty("Accept", getResponseMimeType());
370
371     connection.setDoInput(true);
372     connection.setDoOutput(multipleIds);
373
374     connection.setUseCaches(false);
375     connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
376     connection.setReadTimeout(readTimeout);
377
378     if (multipleIds)
379     {
380       writePostBody(connection, ids);
381     }
382     return connection;
383   }
384
385   /**
386    * Inspects response headers for a 'retry-after' directive, and waits for the
387    * directed period (if less than 10 seconds)
388    * 
389    * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
390    * @param connection
391    */
392   void checkRetryAfter(HttpURLConnection connection)
393   {
394     String retryDelay = connection.getHeaderField("Retry-After");
395
396     // to test:
397     // retryDelay = "5";
398
399     if (retryDelay != null)
400     {
401       try
402       {
403         int retrySecs = Integer.valueOf(retryDelay);
404         if (retrySecs > 0 && retrySecs < 10)
405         {
406           System.err.println(
407                   "Ensembl REST service rate limit exceeded, waiting "
408                           + retryDelay + " seconds before retrying");
409           Thread.sleep(1000 * retrySecs);
410         }
411       } catch (NumberFormatException | InterruptedException e)
412       {
413         System.err.println("Error handling Retry-After: " + e.getMessage());
414       }
415     }
416   }
417
418   /**
419    * Rechecks if Ensembl is responding, unless the last check was successful and
420    * the retest interval has not yet elapsed. Returns true if Ensembl is up,
421    * else false. Also retrieves and saves the current version of Ensembl data
422    * and REST services at intervals.
423    * 
424    * @return
425    */
426   protected boolean isEnsemblAvailable()
427   {
428     EnsemblData info = domainData.get(getDomain());
429
430     long now = System.currentTimeMillis();
431
432     /*
433      * recheck if Ensembl is up if it was down, or the recheck period has elapsed
434      */
435     boolean retestAvailability = (now
436             - info.lastAvailableCheckTime) > PING_RETEST_INTERVAL;
437     if (!info.restAvailable || retestAvailability)
438     {
439       info.restAvailable = checkEnsembl();
440       info.lastAvailableCheckTime = now;
441     }
442
443     /*
444      * refetch Ensembl versions if the recheck period has elapsed
445      */
446     boolean refetchVersion = (now
447             - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
448     if (refetchVersion)
449     {
450       checkEnsemblRestVersion();
451       checkEnsemblDataVersion();
452       info.lastVersionCheckTime = now;
453     }
454
455     return info.restAvailable;
456   }
457
458   /**
459    * Constructs, writes and flushes the POST body of the request, containing the
460    * query ids in JSON format
461    * 
462    * @param connection
463    * @param ids
464    * @throws IOException
465    */
466   protected void writePostBody(HttpURLConnection connection,
467           List<String> ids) throws IOException
468   {
469     boolean first;
470     StringBuilder postBody = new StringBuilder(64);
471     postBody.append("{\"ids\":[");
472     first = true;
473     for (int i = 0, n = ids.size(); i < n; i++)
474     {
475       String id = ids.get(i);
476       if (!first)
477       {
478         postBody.append(",");
479       }
480       first = false;
481       postBody.append("\"");
482       postBody.append(id.trim());
483       postBody.append("\"");
484     }
485     postBody.append("]}");
486     byte[] thepostbody = postBody.toString().getBytes();
487     connection.setRequestProperty("Content-Length",
488             Integer.toString(thepostbody.length));
489     DataOutputStream wr = new DataOutputStream(
490             connection.getOutputStream());
491     wr.write(thepostbody);
492     wr.flush();
493     wr.close();
494   }
495
496   /**
497    * Primary access point to parsed JSON data, including the call to retrieve
498    * and parsing.
499    * 
500    * @param url
501    *          request url; if null, getUrl(ids) will be used
502    * @param ids
503    *          optional; may be null
504    * @param msDelay
505    *          -1 for default delay
506    * @param mode
507    *          map, array, or array iterator
508    * @param mapKey
509    *          an optional key for an outer map
510    * @return a Map, List, Iterator, or null
511    * @throws IOException
512    * @throws ParseException
513    * 
514    * @author Bob Hanson 2019
515    */
516   @SuppressWarnings("unchecked")
517   protected Object getJSON(URL url, List<String> ids, int msDelay, int mode,
518           String mapKey) throws IOException, ParseException
519   {
520     if (url == null)
521     {
522       url = getUrl(ids);
523     }
524
525     Object json = (url == null ? null : getJSON(url, ids, msDelay));
526
527     if (json != null && mapKey != null)
528     {
529       json = ((Map<String, Object>) json).get(mapKey);
530     }
531     if (json == null)
532     {
533       return null;
534     }
535     switch (mode)
536     {
537     case MODE_ARRAY:
538     case MODE_MAP:
539       break;
540     case MODE_ITERATOR:
541       json = ((List<Object>) json).iterator();
542       break;
543     }
544     return json;
545   }
546
547   /**
548    * Fetches and checks Ensembl's REST version number
549    * 
550    * @return
551    */
552   @SuppressWarnings("unchecked")
553   private void checkEnsemblRestVersion()
554   {
555     EnsemblData info = domainData.get(getDomain());
556
557     try
558     {
559       Map<String, Object> val = (Map<String, Object>) getJSON(
560               new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON), null,
561               -1, MODE_MAP, null);
562       if (val == null)
563       {
564         return;
565       }
566       String version = val.get("release").toString();
567       String majorVersion = version.substring(0, version.indexOf("."));
568       String expected = info.expectedRestVersion;
569       String expectedMajorVersion = expected.substring(0,
570               expected.indexOf("."));
571       info.restMajorVersionMismatch = false;
572       try
573       {
574         /*
575          * if actual REST major version is ahead of what we expect,
576          * record this in case we want to warn the user
577          */
578         if (Float.valueOf(majorVersion) > Float
579                 .valueOf(expectedMajorVersion))
580         {
581           info.restMajorVersionMismatch = true;
582         }
583       } catch (NumberFormatException e)
584       {
585         System.err.println("Error in REST version: " + e.toString());
586       }
587
588       /*
589        * check if REST version is later than what Jalview has tested against,
590        * if so warn; we don't worry if it is earlier (this indicates Jalview has
591        * been tested in advance against the next pending REST version)
592        */
593       boolean laterVersion = StringUtils.compareVersions(version,
594               expected) == 1;
595       if (laterVersion)
596       {
597         System.err.println(String.format(
598                 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
599                 getDbSource(), expected, version, REST_CHANGE_LOG));
600       }
601       info.restVersion = version;
602     } catch (Throwable t)
603     {
604       System.err.println(
605               "Error checking Ensembl REST version: " + t.getMessage());
606     }
607   }
608
609   public boolean isRestMajorVersionMismatch()
610   {
611     return domainData.get(getDomain()).restMajorVersionMismatch;
612   }
613
614   /**
615    * Fetches and checks Ensembl's data version number
616    * 
617    * @return
618    */
619   @SuppressWarnings("unchecked")
620   private void checkEnsemblDataVersion()
621   {
622     Map<String, Object> val;
623     try
624     {
625       val = (Map<String, Object>) getJSON(
626               new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON), null,
627               -1, MODE_MAP, null);
628       if (val == null)
629       {
630         return;
631       }
632       List<Object> versions = (List<Object>) val.get("releases");
633       domainData.get(getDomain()).dataVersion = versions.get(0).toString();
634     } catch (Throwable e)
635     {// could be IOException | ParseException e) {
636       System.err.println(
637               "Error checking Ensembl data version: " + e.getMessage());
638     }
639   }
640
641   public String getEnsemblDataVersion()
642   {
643     return domainData.get(getDomain()).dataVersion;
644   }
645
646   @Override
647   public String getDbVersion()
648   {
649     return getEnsemblDataVersion();
650   }
651
652 }