Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add toXContent and fromXContent for DiscoveryNode and DiscoveryNodes #13576

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@
import org.opensearch.core.xcontent.XContentBuilder;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
* A transport address used for IP socket address (wraps {@link java.net.InetSocketAddress}).
Expand Down Expand Up @@ -162,4 +164,22 @@ public String toString() {
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.value(toString());
}

/**
* Converts a string in the format [hostname/ip]:[port] into a transport address.
* @throws UnknownHostException if the hostname or ip address is invalid
*/
public static TransportAddress fromString(String address) throws UnknownHostException {
dbwiddis marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't control the toString() you are using TransportAddress.toString() which calls NetworkAddress.format(address); . If toString() implementation changes, your fromString() will break.

String[] addressSplit = address.split(":");
if (addressSplit.length == 2) {
String hostname = addressSplit[0];
int port = Integer.parseInt(addressSplit[1]);
return new TransportAddress(InetAddress.getByName(hostname), port);
} else {
// this should be an IPv6 ip
int port = Integer.parseInt(addressSplit[addressSplit.length - 1]);
String hostname = String.join(":", Arrays.copyOfRange(addressSplit, 0, addressSplit.length - 1));
return new TransportAddress(Inet6Address.getByName(hostname), port);
}
}
}
114 changes: 110 additions & 4 deletions server/src/main/java/org/opensearch/cluster/node/DiscoveryNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@

package org.opensearch.cluster.node;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.Version;
import org.opensearch.cluster.metadata.Metadata;
import org.opensearch.common.UUIDs;
import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.settings.Setting;
Expand All @@ -43,6 +46,7 @@
import org.opensearch.core.common.transport.TransportAddress;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.node.Node;

import java.io.IOException;
Expand All @@ -60,6 +64,9 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.opensearch.cluster.metadata.Metadata.CONTEXT_MODE_API;
import static org.opensearch.cluster.metadata.Metadata.CONTEXT_MODE_PARAM;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.node.NodeRoleSettings.NODE_ROLES_SETTING;
import static org.opensearch.node.remotestore.RemoteStoreNodeAttribute.REMOTE_STORE_NODE_ATTRIBUTE_KEY_PREFIX;

Expand All @@ -72,6 +79,15 @@
public class DiscoveryNode implements Writeable, ToXContentFragment {

static final String COORDINATING_ONLY = "coordinating_only";
static final String KEY_NAME = "name";
static final String KEY_EPHEMERAL_ID = "ephemeral_id";
static final String KEY_HOST_NAME = "host_name";
static final String KEY_HOST_ADDRESS = "host_address";
static final String KEY_TRANSPORT_ADDRESS = "transport_address";
static final String KEY_ATTRIBUTES = "attributes";
static final String KEY_VERSION = "version";
static final String KEY_ROLES = "roles";
private static final Logger logger = LogManager.getLogger(DiscoveryNode.class);

public static boolean nodeRequiresLocalStorage(Settings settings) {
boolean localStorageEnable = Node.NODE_LOCAL_STORAGE_SETTING.get(settings);
Expand Down Expand Up @@ -544,21 +560,111 @@ public String toString() {

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
Metadata.XContentContext context = Metadata.XContentContext.valueOf(params.param(CONTEXT_MODE_PARAM, CONTEXT_MODE_API));
builder.startObject(getId());
builder.field("name", getName());
builder.field("ephemeral_id", getEphemeralId());
builder.field("transport_address", getAddress().toString());
builder.field(KEY_NAME, getName());
builder.field(KEY_EPHEMERAL_ID, getEphemeralId());
builder.field(KEY_TRANSPORT_ADDRESS, getAddress().toString());

builder.startObject("attributes");
builder.startObject(KEY_ATTRIBUTES);
for (Map.Entry<String, String> entry : attributes.entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
if (context == Metadata.XContentContext.GATEWAY) {
builder.field(KEY_HOST_NAME, getHostName());
builder.field(KEY_HOST_ADDRESS, getHostAddress());
builder.field(KEY_VERSION, getVersion().toString());
builder.startArray(KEY_ROLES);
for (DiscoveryNodeRole role : roles) {
builder.value(role.roleName());
}
builder.endArray();
}

builder.endObject();
return builder;
}

/**
* This method is able to parse either a complete XContentObject with start and end object
* or only a fragment with the key and value.
*/
public static DiscoveryNode fromXContent(XContentParser parser) throws IOException {
if (parser.currentToken() == null) { // fresh parser? move to the first token
parser.nextToken();
}
if (parser.currentToken() == XContentParser.Token.START_OBJECT) { // on a start object move to next token
parser.nextToken();
}
ensureExpectedToken(XContentParser.Token.FIELD_NAME, parser.currentToken(), parser);
String nodeId = parser.currentName();
String nodeName = null;
String hostName = null;
String hostAddress = null;
String ephemeralId = null;
TransportAddress transportAddress = null;
Map<String, String> attributes = new HashMap<>();
Set<DiscoveryNodeRole> roles = new HashSet<>();
Version version = null;
XContentParser.Token token = parser.nextToken();
ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser);
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
shiv0408 marked this conversation as resolved.
Show resolved Hide resolved
ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser);
String currentFieldName = parser.currentName();
token = parser.nextToken();
if (token.isValue()) {
switch (currentFieldName) {
case KEY_NAME:
nodeName = parser.text();
break;
case KEY_EPHEMERAL_ID:
ephemeralId = parser.text();
break;
case KEY_TRANSPORT_ADDRESS:
transportAddress = TransportAddress.fromString(parser.text());
shiv0408 marked this conversation as resolved.
Show resolved Hide resolved
break;
case KEY_HOST_NAME:
hostName = parser.text();
break;
case KEY_HOST_ADDRESS:
hostAddress = parser.text();
break;
case KEY_VERSION:
version = Version.fromString(parser.text());
break;
default:
logger.warn("unknown field [{}]", currentFieldName);
}
} else if (token == XContentParser.Token.START_OBJECT) {
assert currentFieldName.equals(KEY_ATTRIBUTES) : "expecting field with name ["
+ KEY_ATTRIBUTES
+ "] but found ["
+ currentFieldName
+ "]";
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser);
currentFieldName = parser.currentName();
token = parser.nextToken();
ensureExpectedToken(XContentParser.Token.VALUE_STRING, token, parser);
attributes.put(currentFieldName, parser.text());
}
} else if (token == XContentParser.Token.START_ARRAY) {
assert currentFieldName.equals(KEY_ROLES) : "expecting field with name ["
+ KEY_ROLES
+ "] but found ["
+ currentFieldName
+ "]";
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
roles.add(getRoleFromRoleName(parser.text()));
}
} else {
throw new IllegalArgumentException("unexpected token " + token);
}
}
return new DiscoveryNode(nodeName, nodeId, ephemeralId, hostName, hostAddress, transportAddress, attributes, roles, version);
}

private static Map<String, DiscoveryNodeRole> rolesToMap(final Stream<DiscoveryNodeRole> roles) {
return Collections.unmodifiableMap(roles.collect(Collectors.toMap(DiscoveryNodeRole::roleName, Function.identity())));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.opensearch.Version;
import org.opensearch.cluster.AbstractDiffable;
import org.opensearch.cluster.Diff;
import org.opensearch.cluster.metadata.Metadata;
import org.opensearch.common.Booleans;
import org.opensearch.common.Nullable;
import org.opensearch.common.annotation.PublicApi;
Expand All @@ -44,6 +45,9 @@
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.transport.TransportAddress;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;

import java.io.IOException;
import java.util.ArrayList;
Expand All @@ -59,16 +63,22 @@
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static org.opensearch.cluster.metadata.Metadata.CONTEXT_MODE_API;
import static org.opensearch.cluster.metadata.Metadata.CONTEXT_MODE_PARAM;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;

/**
* This class holds all {@link DiscoveryNode} in the cluster and provides convenience methods to
* access, modify merge / diff discovery nodes.
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public class DiscoveryNodes extends AbstractDiffable<DiscoveryNodes> implements Iterable<DiscoveryNode> {
public class DiscoveryNodes extends AbstractDiffable<DiscoveryNodes> implements Iterable<DiscoveryNode>, ToXContentObject {

public static final DiscoveryNodes EMPTY_NODES = builder().build();
public static final String KEY_NODES = "nodes";
public static final String KEY_CLUSTER_MANAGER = "cluster_manager";

private final Map<String, DiscoveryNode> nodes;
private final Map<String, DiscoveryNode> dataNodes;
Expand Down Expand Up @@ -566,6 +576,64 @@ public String toString() {
return sb.toString();
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
innerToXContent(builder, params);
builder.endObject();
return builder;
}

public XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(KEY_NODES);
for (DiscoveryNode node : this) {
node.toXContent(builder, params);
}
builder.endObject();
Metadata.XContentContext context = Metadata.XContentContext.valueOf(params.param(CONTEXT_MODE_PARAM, CONTEXT_MODE_API));
if (context == Metadata.XContentContext.GATEWAY && clusterManagerNodeId != null) {
builder.field(KEY_CLUSTER_MANAGER, clusterManagerNodeId);
}
return builder;
}

public static DiscoveryNodes fromXContent(XContentParser parser) throws IOException {
Builder builder = new Builder();
if (parser.currentToken() == null) { // fresh parser? move to the first token
parser.nextToken();
}
XContentParser.Token token = parser.currentToken();
ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser);
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser);
String currentFieldName = parser.currentName();
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
assert currentFieldName.equals(KEY_NODES) : "expecting field with name ["
+ KEY_NODES
+ "] but found ["
+ currentFieldName
+ "]";
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
builder.add(DiscoveryNode.fromXContent(parser));
}
} else if (token.isValue()) {
assert currentFieldName.equals(KEY_CLUSTER_MANAGER) : "expecting field with name ["
+ KEY_CLUSTER_MANAGER
+ "] but found ["
+ currentFieldName
+ "]";
String clusterManagerNodeId = parser.text();
if (clusterManagerNodeId != null) {
builder.clusterManagerNodeId(clusterManagerNodeId);
}
} else {
throw new IllegalArgumentException("unexpected token " + token);
}
}
return builder.build();
}

/**
* Delta between nodes.
*
Expand Down
Loading
Loading