|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch B.V. under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package co.elastic.clients.transport.rest5_client.low_level.sniffer; |
| 21 | + |
| 22 | +import com.fasterxml.jackson.core.JsonFactory; |
| 23 | +import com.fasterxml.jackson.core.JsonParser; |
| 24 | +import com.fasterxml.jackson.core.JsonToken; |
| 25 | + |
| 26 | +import org.apache.commons.logging.Log; |
| 27 | +import org.apache.commons.logging.LogFactory; |
| 28 | +import org.apache.hc.core5.http.HttpEntity; |
| 29 | +import org.apache.hc.core5.http.HttpHost; |
| 30 | +import co.elastic.clients.transport.rest5_client.low_level.Node; |
| 31 | +import co.elastic.clients.transport.rest5_client.low_level.Node.Roles; |
| 32 | +import co.elastic.clients.transport.rest5_client.low_level.Request; |
| 33 | +import co.elastic.clients.transport.rest5_client.low_level.Response; |
| 34 | +import co.elastic.clients.transport.rest5_client.low_level.Rest5Client; |
| 35 | + |
| 36 | +import java.io.IOException; |
| 37 | +import java.io.InputStream; |
| 38 | +import java.net.URI; |
| 39 | +import java.util.ArrayList; |
| 40 | +import java.util.HashMap; |
| 41 | +import java.util.HashSet; |
| 42 | +import java.util.List; |
| 43 | +import java.util.Map; |
| 44 | +import java.util.Objects; |
| 45 | +import java.util.Set; |
| 46 | +import java.util.TreeSet; |
| 47 | +import java.util.concurrent.TimeUnit; |
| 48 | + |
| 49 | +import static java.util.Collections.singletonList; |
| 50 | +import static java.util.Collections.unmodifiableList; |
| 51 | +import static java.util.Collections.unmodifiableMap; |
| 52 | + |
| 53 | +/** |
| 54 | + * Class responsible for sniffing the http hosts from elasticsearch through the nodes info api and returning them back. |
| 55 | + * Compatible with elasticsearch 2.x+. |
| 56 | + */ |
| 57 | +public final class ElasticsearchNodesSniffer implements NodesSniffer { |
| 58 | + |
| 59 | + private static final Log logger = LogFactory.getLog(ElasticsearchNodesSniffer.class); |
| 60 | + |
| 61 | + public static final long DEFAULT_SNIFF_REQUEST_TIMEOUT = TimeUnit.SECONDS.toMillis(1); |
| 62 | + |
| 63 | + private final Rest5Client restClient; |
| 64 | + private final Request request; |
| 65 | + private final Scheme scheme; |
| 66 | + private final JsonFactory jsonFactory = new JsonFactory(); |
| 67 | + |
| 68 | + /** |
| 69 | + * Creates a new instance of the Elasticsearch sniffer. It will use the provided {@link Rest5Client} to fetch the hosts, |
| 70 | + * through the nodes info api, the default sniff request timeout value {@link #DEFAULT_SNIFF_REQUEST_TIMEOUT} and http |
| 71 | + * as the scheme for all the hosts. |
| 72 | + * @param restClient client used to fetch the hosts from elasticsearch through nodes info api. Usually the same instance |
| 73 | + * that is also provided to {@link Sniffer#builder(Rest5Client)}, so that the hosts are set to the same |
| 74 | + * client that was used to fetch them. |
| 75 | + */ |
| 76 | + public ElasticsearchNodesSniffer(Rest5Client restClient) { |
| 77 | + this(restClient, DEFAULT_SNIFF_REQUEST_TIMEOUT, ElasticsearchNodesSniffer.Scheme.HTTP); |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Creates a new instance of the Elasticsearch sniffer. It will use the provided {@link Rest5Client} to fetch the hosts |
| 82 | + * through the nodes info api, the provided sniff request timeout value and scheme. |
| 83 | + * @param restClient client used to fetch the hosts from elasticsearch through nodes info api. Usually the same instance |
| 84 | + * that is also provided to {@link Sniffer#builder(Rest5Client)}, so that the hosts are set to the same |
| 85 | + * client that was used to sniff them. |
| 86 | + * @param sniffRequestTimeoutMillis the sniff request timeout (in milliseconds) to be passed in as a query string parameter |
| 87 | + * to elasticsearch. Allows to halt the request without any failure, as only the nodes |
| 88 | + * that have responded within this timeout will be returned. |
| 89 | + * @param scheme the scheme to associate sniffed nodes with (as it is not returned by elasticsearch) |
| 90 | + */ |
| 91 | + public ElasticsearchNodesSniffer(Rest5Client restClient, long sniffRequestTimeoutMillis, Scheme scheme) { |
| 92 | + this.restClient = Objects.requireNonNull(restClient, "restClient cannot be null"); |
| 93 | + if (sniffRequestTimeoutMillis < 0) { |
| 94 | + throw new IllegalArgumentException("sniffRequestTimeoutMillis must be greater than 0"); |
| 95 | + } |
| 96 | + this.request = new Request("GET", "/_nodes/http"); |
| 97 | + request.addParameter("timeout", sniffRequestTimeoutMillis + "ms"); |
| 98 | + this.scheme = Objects.requireNonNull(scheme, "scheme cannot be null"); |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Calls the elasticsearch nodes info api, parses the response and returns all the found http hosts |
| 103 | + */ |
| 104 | + @Override |
| 105 | + public List<Node> sniff() throws IOException { |
| 106 | + Response response = restClient.performRequest(request); |
| 107 | + return readHosts(response.getEntity(), scheme, jsonFactory); |
| 108 | + } |
| 109 | + |
| 110 | + static List<Node> readHosts(HttpEntity entity, Scheme scheme, JsonFactory jsonFactory) throws IOException { |
| 111 | + try (InputStream inputStream = entity.getContent()) { |
| 112 | + JsonParser parser = jsonFactory.createParser(inputStream); |
| 113 | + if (parser.nextToken() != JsonToken.START_OBJECT) { |
| 114 | + throw new IOException("expected data to start with an object"); |
| 115 | + } |
| 116 | + List<Node> nodes = new ArrayList<>(); |
| 117 | + while (parser.nextToken() != JsonToken.END_OBJECT) { |
| 118 | + if (parser.getCurrentToken() == JsonToken.START_OBJECT) { |
| 119 | + if ("nodes".equals(parser.getCurrentName())) { |
| 120 | + while (parser.nextToken() != JsonToken.END_OBJECT) { |
| 121 | + JsonToken token = parser.nextToken(); |
| 122 | + assert token == JsonToken.START_OBJECT; |
| 123 | + String nodeId = parser.getCurrentName(); |
| 124 | + Node node = readNode(nodeId, parser, scheme); |
| 125 | + if (node != null) { |
| 126 | + nodes.add(node); |
| 127 | + } |
| 128 | + } |
| 129 | + } else { |
| 130 | + parser.skipChildren(); |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + return nodes; |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException { |
| 139 | + HttpHost publishedHost = null; |
| 140 | + /* |
| 141 | + * We sniff the bound hosts so we can look up the node based on any |
| 142 | + * address on which it is listening. This is useful in Elasticsearch's |
| 143 | + * test framework where we sometimes publish ipv6 addresses but the |
| 144 | + * tests contact the node on ipv4. |
| 145 | + */ |
| 146 | + Set<HttpHost> boundHosts = new HashSet<>(); |
| 147 | + String name = null; |
| 148 | + String version = null; |
| 149 | + /* |
| 150 | + * Multi-valued attributes come with key = `real_key.index` and we |
| 151 | + * unflip them after reading them because we can't rely on the order |
| 152 | + * that they arive. |
| 153 | + */ |
| 154 | + final Map<String, String> protoAttributes = new HashMap<String, String>(); |
| 155 | + |
| 156 | + boolean sawRoles = false; |
| 157 | + final Set<String> roles = new TreeSet<>(); |
| 158 | + |
| 159 | + String fieldName = null; |
| 160 | + while (parser.nextToken() != JsonToken.END_OBJECT) { |
| 161 | + if (parser.getCurrentToken() == JsonToken.FIELD_NAME) { |
| 162 | + fieldName = parser.getCurrentName(); |
| 163 | + } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) { |
| 164 | + if ("http".equals(fieldName)) { |
| 165 | + while (parser.nextToken() != JsonToken.END_OBJECT) { |
| 166 | + if (parser.getCurrentToken() == JsonToken.VALUE_STRING && "publish_address".equals(parser.getCurrentName())) { |
| 167 | + String address = parser.getValueAsString(); |
| 168 | + String host; |
| 169 | + URI publishAddressAsURI; |
| 170 | + |
| 171 | + // ES7 cname/ip:port format |
| 172 | + if (address.contains("/")) { |
| 173 | + String[] cnameAndURI = address.split("/", 2); |
| 174 | + publishAddressAsURI = URI.create(scheme + "://" + cnameAndURI[1]); |
| 175 | + host = cnameAndURI[0]; |
| 176 | + } else { |
| 177 | + publishAddressAsURI = URI.create(scheme + "://" + address); |
| 178 | + host = publishAddressAsURI.getHost(); |
| 179 | + } |
| 180 | + publishedHost = new HttpHost(publishAddressAsURI.getScheme(), host, publishAddressAsURI.getPort()); |
| 181 | + } else if (parser.currentToken() == JsonToken.START_ARRAY && "bound_address".equals(parser.getCurrentName())) { |
| 182 | + while (parser.nextToken() != JsonToken.END_ARRAY) { |
| 183 | + URI boundAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString()); |
| 184 | + boundHosts.add( |
| 185 | + new HttpHost(boundAddressAsURI.getScheme(), boundAddressAsURI.getHost(), boundAddressAsURI.getPort()) |
| 186 | + ); |
| 187 | + } |
| 188 | + } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) { |
| 189 | + parser.skipChildren(); |
| 190 | + } |
| 191 | + } |
| 192 | + } else if ("attributes".equals(fieldName)) { |
| 193 | + while (parser.nextToken() != JsonToken.END_OBJECT) { |
| 194 | + if (parser.getCurrentToken() == JsonToken.VALUE_STRING) { |
| 195 | + String oldValue = protoAttributes.put(parser.getCurrentName(), parser.getValueAsString()); |
| 196 | + if (oldValue != null) { |
| 197 | + throw new IOException("repeated attribute key [" + parser.getCurrentName() + "]"); |
| 198 | + } |
| 199 | + } else { |
| 200 | + parser.skipChildren(); |
| 201 | + } |
| 202 | + } |
| 203 | + } else { |
| 204 | + parser.skipChildren(); |
| 205 | + } |
| 206 | + } else if (parser.currentToken() == JsonToken.START_ARRAY) { |
| 207 | + if ("roles".equals(fieldName)) { |
| 208 | + sawRoles = true; |
| 209 | + while (parser.nextToken() != JsonToken.END_ARRAY) { |
| 210 | + roles.add(parser.getText()); |
| 211 | + } |
| 212 | + } else { |
| 213 | + parser.skipChildren(); |
| 214 | + } |
| 215 | + } else if (parser.currentToken().isScalarValue()) { |
| 216 | + if ("version".equals(fieldName)) { |
| 217 | + version = parser.getText(); |
| 218 | + } else if ("name".equals(fieldName)) { |
| 219 | + name = parser.getText(); |
| 220 | + } |
| 221 | + } |
| 222 | + } |
| 223 | + // http section is not present if http is not enabled on the node, ignore such nodes |
| 224 | + if (publishedHost == null) { |
| 225 | + logger.debug("skipping node [" + nodeId + "] with http disabled"); |
| 226 | + return null; |
| 227 | + } |
| 228 | + |
| 229 | + Map<String, List<String>> realAttributes = new HashMap<>(protoAttributes.size()); |
| 230 | + List<String> keys = new ArrayList<>(protoAttributes.keySet()); |
| 231 | + for (String key : keys) { |
| 232 | + if (key.endsWith(".0")) { |
| 233 | + String realKey = key.substring(0, key.length() - 2); |
| 234 | + List<String> values = new ArrayList<>(); |
| 235 | + int i = 0; |
| 236 | + while (true) { |
| 237 | + String value = protoAttributes.remove(realKey + "." + i); |
| 238 | + if (value == null) { |
| 239 | + break; |
| 240 | + } |
| 241 | + values.add(value); |
| 242 | + i++; |
| 243 | + } |
| 244 | + realAttributes.put(realKey, unmodifiableList(values)); |
| 245 | + } |
| 246 | + } |
| 247 | + for (Map.Entry<String, String> entry : protoAttributes.entrySet()) { |
| 248 | + realAttributes.put(entry.getKey(), singletonList(entry.getValue())); |
| 249 | + } |
| 250 | + |
| 251 | + if (version.startsWith("2.")) { |
| 252 | + /* |
| 253 | + * 2.x doesn't send roles, instead we try to read them from |
| 254 | + * attributes. |
| 255 | + */ |
| 256 | + boolean clientAttribute = v2RoleAttributeValue(realAttributes, "client", false); |
| 257 | + Boolean masterAttribute = v2RoleAttributeValue(realAttributes, "master", null); |
| 258 | + Boolean dataAttribute = v2RoleAttributeValue(realAttributes, "data", null); |
| 259 | + if ((masterAttribute == null && false == clientAttribute) || masterAttribute) { |
| 260 | + roles.add("master"); |
| 261 | + } |
| 262 | + if ((dataAttribute == null && false == clientAttribute) || dataAttribute) { |
| 263 | + roles.add("data"); |
| 264 | + } |
| 265 | + } else { |
| 266 | + assert sawRoles : "didn't see roles for [" + nodeId + "]"; |
| 267 | + } |
| 268 | + assert boundHosts.contains(publishedHost) : "[" + nodeId + "] doesn't make sense! publishedHost should be in boundHosts"; |
| 269 | + logger.trace("adding node [" + nodeId + "]"); |
| 270 | + return new Node(publishedHost, boundHosts, name, version, new Roles(roles), unmodifiableMap(realAttributes)); |
| 271 | + } |
| 272 | + |
| 273 | + /** |
| 274 | + * Returns {@code defaultValue} if the attribute didn't come back, |
| 275 | + * {@code true} or {@code false} if it did come back as |
| 276 | + * either of those, or throws an IOException if the attribute |
| 277 | + * came back in a strange way. |
| 278 | + */ |
| 279 | + private static Boolean v2RoleAttributeValue(Map<String, List<String>> attributes, String name, Boolean defaultValue) |
| 280 | + throws IOException { |
| 281 | + List<String> valueList = attributes.remove(name); |
| 282 | + if (valueList == null) { |
| 283 | + return defaultValue; |
| 284 | + } |
| 285 | + if (valueList.size() != 1) { |
| 286 | + throw new IOException("expected only a single attribute value for [" + name + "] but got " + valueList); |
| 287 | + } |
| 288 | + switch (valueList.get(0)) { |
| 289 | + case "true": |
| 290 | + return true; |
| 291 | + case "false": |
| 292 | + return false; |
| 293 | + default: |
| 294 | + throw new IOException("expected [" + name + "] to be either [true] or [false] but was [" + valueList.get(0) + "]"); |
| 295 | + } |
| 296 | + } |
| 297 | + |
| 298 | + public enum Scheme { |
| 299 | + HTTP("http"), |
| 300 | + HTTPS("https"); |
| 301 | + |
| 302 | + private final String name; |
| 303 | + |
| 304 | + Scheme(String name) { |
| 305 | + this.name = name; |
| 306 | + } |
| 307 | + |
| 308 | + @Override |
| 309 | + public String toString() { |
| 310 | + return name; |
| 311 | + } |
| 312 | + } |
| 313 | +} |
0 commit comments