Collection findLiveCollectorHostsFromKnownCollector()

in ambari-metrics-common/src/main/java/org/apache/hadoop/metrics2/sink/timeline/AbstractTimelineMetricsSink.java [617:677]


  Collection<String> findLiveCollectorHostsFromKnownCollector(String host, String port) throws MetricCollectorUnavailableException {
    List<String> collectors = new ArrayList<>();
    HttpURLConnection connection = null;
    StringBuilder sb = new StringBuilder(getCollectorProtocol());
    sb.append("://");
    sb.append(host);
    sb.append(":");
    sb.append(port);
    sb.append(COLLECTOR_LIVE_NODES_PATH);
    String connectUrl = sb.toString();
    LOG.debug("Requesting live collector nodes : " + connectUrl);
    try {
      connection = getCollectorProtocol().startsWith("https") ?
        getSSLConnection(connectUrl) : getConnection(connectUrl);

      connection.setRequestMethod("GET");
      // 5 seconds for this op is plenty of wait time
      connection.setConnectTimeout(3000);
      connection.setReadTimeout(2000);

      int responseCode = connection.getResponseCode();

      switch (responseCode) {
        case 200 :
          try (InputStream in = connection.getInputStream()) {
            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer);
            try {
              collectors = gson.fromJson(writer.toString(), new TypeToken<List<String>>(){}.getType());
            } catch (JsonSyntaxException jse) {
              // Swallow this at the behest of still trying to POST
              LOG.debug("Exception deserializing the json data on live " +
                     "collector nodes.", jse);
            }
          }
          break;
        case 500 :
          String warnMsg = "Unable to connect to collector to find live nodes, Internal server error";
          throw new MetricCollectorUnavailableException(warnMsg);
        default :
          String msg = String.format("Unhandled response code (%d) at requesting live collector nodes!", responseCode);
          LOG.warn(msg);
      }

    } catch (IOException ioe) {
      StringBuilder errorMessage =
        new StringBuilder("Unable to connect to collector, " + connectUrl);
      try {
        if ((connection != null)) {
          errorMessage.append(cleanupInputStream(connection.getErrorStream()));
        }
      } catch (IOException e) {
        //NOP
      }
      LOG.debug(errorMessage);
      LOG.debug(ioe);
      String warnMsg = "Unable to connect to collector to find live nodes.";
      throw new MetricCollectorUnavailableException(warnMsg);
    }
    return collectors;
  }