Ejemplo n.º 1
0
  /** Creates a DiscoveryNode representing the local node. */
  public static DiscoveryNode createLocal(
      Settings settings, TransportAddress publishAddress, String nodeIdSupplier) {
    Map<String, String> attributes = new HashMap<>(Node.NODE_ATTRIBUTES.get(settings).getAsMap());
    Set<DiscoveryNode.Role> roles = new HashSet<>();
    if (Node.NODE_INGEST_SETTING.get(settings)) {
      roles.add(DiscoveryNode.Role.INGEST);
    }
    if (Node.NODE_MASTER_SETTING.get(settings)) {
      roles.add(DiscoveryNode.Role.MASTER);
    }
    if (Node.NODE_DATA_SETTING.get(settings)) {
      roles.add(DiscoveryNode.Role.DATA);
    }

    return new DiscoveryNode(
        Node.NODE_NAME_SETTING.get(settings),
        nodeIdSupplier,
        publishAddress,
        attributes,
        roles,
        Version.CURRENT);
  }
  // pkg private for testing
  static Settings getAvailabilityZoneNodeAttributes(Settings settings, String azMetadataUrl) {
    if (AwsEc2Service.AUTO_ATTRIBUTE_SETTING.get(settings) == false) {
      return Settings.EMPTY;
    }
    Settings.Builder attrs = Settings.builder();

    final URL url;
    final URLConnection urlConnection;
    try {
      url = new URL(azMetadataUrl);
      logger.debug("obtaining ec2 [placement/availability-zone] from ec2 meta-data url {}", url);
      urlConnection = url.openConnection();
      urlConnection.setConnectTimeout(2000);
    } catch (IOException e) {
      // should not happen, we know the url is not malformed, and openConnection does not actually
      // hit network
      throw new UncheckedIOException(e);
    }

    try (InputStream in = urlConnection.getInputStream();
        BufferedReader urlReader =
            new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {

      String metadataResult = urlReader.readLine();
      if (metadataResult == null || metadataResult.length() == 0) {
        throw new IllegalStateException("no ec2 metadata returned from " + url);
      } else {
        attrs.put(Node.NODE_ATTRIBUTES.getKey() + "aws_availability_zone", metadataResult);
      }
    } catch (IOException e) {
      // this is lenient so the plugin does not fail when installed outside of ec2
      logger.error("failed to get metadata for [placement/availability-zone]", e);
    }

    return attrs.build();
  }