This is an automated email from the ASF dual-hosted git repository.
alexpl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ignite.git
The following commit(s) were added to refs/heads/master by this push:
new fb2f608 IGNITE-12964 Java thin client: Cluster group API support -
Fixes #7796.
fb2f608 is described below
commit fb2f608005a29e9a558942dd648bac771bc44830
Author: Aleksey Plekhanov <[email protected]>
AuthorDate: Thu May 14 15:07:27 2020 +0300
IGNITE-12964 Java thin client: Cluster group API support - Fixes #7796.
Signed-off-by: Aleksey Plekhanov <[email protected]>
---
.../apache/ignite/client/ClientClusterGroup.java | 150 +++++
.../client/thin/ClientClusterGroupImpl.java | 739 ++++++++++++++++++++-
.../internal/client/thin/ClientClusterImpl.java | 11 +-
.../client/thin/ClientClusterNodeImpl.java | 166 +++++
.../internal/client/thin/ClientOperation.java | 2 +
.../client/thin/ProtocolBitmaskFeature.java | 5 +-
.../platform/client/ClientBitmaskFeature.java | 5 +-
.../cluster/ClientClusterGroupProjection.java | 4 +-
.../internal/client/thin/ClusterGroupTest.java | 429 ++++++++++++
.../org/apache/ignite/client/ClientTestSuite.java | 2 +
10 files changed, 1486 insertions(+), 27 deletions(-)
diff --git
a/modules/core/src/main/java/org/apache/ignite/client/ClientClusterGroup.java
b/modules/core/src/main/java/org/apache/ignite/client/ClientClusterGroup.java
index 08b451e..01f8d31 100644
---
a/modules/core/src/main/java/org/apache/ignite/client/ClientClusterGroup.java
+++
b/modules/core/src/main/java/org/apache/ignite/client/ClientClusterGroup.java
@@ -19,12 +19,52 @@ package org.apache.ignite.client;
import java.util.Collection;
import java.util.UUID;
+import java.util.function.Predicate;
+import org.apache.ignite.Ignition;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.jetbrains.annotations.Nullable;
/**
* Thin client cluster group facade. Defines a cluster group which contains
all or a subset of cluster nodes.
*/
public interface ClientClusterGroup {
/**
+ * Creates a cluster group over a given set of nodes.
+ *
+ * @param nodes Collection of nodes to create the cluster group from.
+ * @return Cluster group for the provided grid nodes.
+ */
+ public ClientClusterGroup forNodes(Collection<? extends ClusterNode>
nodes);
+
+ /**
+ * Creates a cluster group for the given node.
+ *
+ * @param node Node to create cluster group for.
+ * @param nodes Optional additional nodes to include into the cluster
group.
+ * @return Cluster group for the given nodes.
+ */
+ public ClientClusterGroup forNode(ClusterNode node, ClusterNode... nodes);
+
+ /**
+ * Creates a cluster group for nodes other than the given nodes.
+ *
+ * @param node Node to exclude from the new cluster group.
+ * @param nodes Optional additional nodes to exclude from the cluster
group.
+ * @return Cluster group that will contain all nodes from the original
cluster group excluding
+ * the given nodes.
+ */
+ public ClientClusterGroup forOthers(ClusterNode node, ClusterNode...
nodes);
+
+ /**
+ * Creates a cluster group for nodes not included into the given cluster
group.
+ *
+ * @param prj Cluster group to exclude from the new cluster group.
+ * @return Cluster group for nodes not included into the given cluster
group.
+ */
+ public ClientClusterGroup forOthers(ClientClusterGroup prj);
+
+ /**
* Creates a cluster group over nodes with specified node IDs.
*
* @param ids Collection of node IDs.
@@ -40,4 +80,114 @@ public interface ClientClusterGroup {
* @return Cluster group over the node with the specified node IDs.
*/
public ClientClusterGroup forNodeId(UUID id, UUID... ids);
+
+ /**
+ * Creates a new cluster group which includes all nodes that pass the
given predicate filter.
+ *
+ * @param p Predicate filter for nodes to include into the cluster group.
+ * @return Cluster group for nodes that passed the predicate filter.
+ */
+ public ClientClusterGroup forPredicate(Predicate<ClusterNode> p);
+
+ /**
+ * Creates a new cluster group for nodes containing given name and value
+ * specified in user attributes.
+ * <p>
+ * User attributes for every node are optional and can be specified in
+ * grid node configuration. See {@link
IgniteConfiguration#getUserAttributes()}
+ * for more information.
+ *
+ * @param name Name of the attribute.
+ * @param val Optional attribute value to match (if null, just check if
attribute exists).
+ * @return Cluster group for nodes containing specified attribute.
+ */
+ public ClientClusterGroup forAttribute(String name, @Nullable Object val);
+
+ /**
+ * Creates a cluster group of nodes started in server mode.
+ *
+ * @see Ignition#setClientMode(boolean)
+ * @see IgniteConfiguration#setClientMode(boolean)
+ * @return Cluster group of nodes started in server mode.
+ */
+ public ClientClusterGroup forServers();
+
+ /**
+ * Creates a cluster group of nodes started in client mode.
+
+ * @see Ignition#setClientMode(boolean)
+ * @see IgniteConfiguration#setClientMode(boolean)
+ * @return Cluster group of nodes started in client mode.
+ */
+ public ClientClusterGroup forClients();
+
+ /**
+ * Creates a cluster group with one random node from the current cluster
group.
+ *
+ * @return Cluster group containing one random node from the current
cluster group.
+ */
+ public ClientClusterGroup forRandom();
+
+ /**
+ * Creates a cluster group with one oldest node from the current cluster
group.
+ * The resulting cluster group is dynamic and will always pick the next
oldest
+ * node if the previous one leaves topology even after the cluster group
has
+ * been created.
+ * <p>
+ * Use {@link #node()} method to get the oldest node.
+ *
+ * @return Cluster group containing one oldest node from the current
cluster group.
+ */
+ public ClientClusterGroup forOldest();
+
+ /**
+ * Creates a cluster group with one youngest node in the current cluster
group.
+ * The resulting cluster group is dynamic and will always pick the newest
+ * node in the topology, even if more nodes entered after the cluster group
+ * has been created.
+ *
+ * @return Cluster group containing one youngest node from the current
cluster group.
+ */
+ public ClientClusterGroup forYoungest();
+
+ /**
+ * Gets cluster group consisting from the nodes in this cluster group
residing on the
+ * same host (with the same MAC address) as the given node.
+ *
+ * @param node Node to select the host for.
+ * @return Cluster group for nodes residing on the same host as the
specified node.
+ */
+ public ClientClusterGroup forHost(ClusterNode node);
+
+ /**
+ * Gets cluster group consisting from the nodes running on the hosts
specified.
+ *
+ * @param host Host name to get nodes to put in cluster
+ * @param hosts Host names to get nodes to put in cluster.
+ * @return Cluster group for nodes residing on the hosts specified.
+ */
+ public ClientClusterGroup forHost(String host, String... hosts);
+
+ /**
+ * Gets the read-only collection of nodes in this cluster group.
+ *
+ * @return All nodes in this cluster group.
+ */
+ public Collection<ClusterNode> nodes();
+
+ /**
+ * Gets a node for given ID from this cluster group.
+ *
+ * @param nid Node ID.
+ * @return Node with given ID from this cluster group or {@code null}, if
such node does not exist.
+ */
+ public ClusterNode node(UUID nid);
+
+ /**
+ * Gets first node from the list of nodes in this cluster group. This
method is specifically
+ * useful for cluster groups with one node only.
+ *
+ * @return First node from the list of nodes in this cluster group or
{@code null} if the cluster group is empty.
+ */
+ public ClusterNode node();
}
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterGroupImpl.java
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterGroupImpl.java
index 3fefb45..3425dc3 100644
---
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterGroupImpl.java
+++
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterGroupImpl.java
@@ -17,51 +17,764 @@
package org.apache.ignite.internal.client.thin;
+import java.io.IOException;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.function.Predicate;
import org.apache.ignite.client.ClientClusterGroup;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.client.ClientFeatureNotSupportedByServerException;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteProductVersion;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS;
/**
* Implementation of {@link ClientClusterGroup}.
*/
-@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
class ClientClusterGroupImpl implements ClientClusterGroup {
- /** Node id's. */
- private final Collection<UUID> nodeIds;
+ /** Channel. */
+ protected final ReliableChannel ch;
+
+ /** Binary marshaller. */
+ protected final ClientBinaryMarshaller marsh;
+
+ /** Projection filters. */
+ private final ProjectionFilters projectionFilters;
+
+ /** Cached topology version. */
+ private long cachedTopVer;
+
+ /** Cached node IDs. Should be changed atomically with cachedTopVer under
lock on ClientClusterGroupImpl instance. */
+ private Collection<UUID> cachedNodeIds;
+
+ /** Cached nodes. */
+ private final Map<UUID, ClusterNode> cachedNodes = new
ConcurrentHashMap<>();
/**
- * @param ids Ids.
+ *
*/
- ClientClusterGroupImpl(Collection<UUID> ids) {
- nodeIds = ids;
+ ClientClusterGroupImpl(ReliableChannel ch, ClientBinaryMarshaller marsh) {
+ this.ch = ch;
+ this.marsh = marsh;
+
+ projectionFilters = ProjectionFilters.FULL_PROJECTION;
+ }
+
+ /**
+ *
+ */
+ private ClientClusterGroupImpl(ReliableChannel ch, ClientBinaryMarshaller
marsh,
+ ProjectionFilters projectionFilters) {
+ this.ch = ch;
+ this.marsh = marsh;
+ this.projectionFilters = projectionFilters;
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forNodes(Collection<? extends
ClusterNode> nodes) {
+ A.notNull(nodes, "nodes");
+
+ ClientClusterGroupImpl grp =
forProjectionFilters(projectionFilters.forNodeIds(new
HashSet<>(F.nodeIds(nodes))));
+
+ for (ClusterNode node : nodes)
+ grp.cachedNodes.put(node.id(), node);
+
+ return grp;
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forNode(ClusterNode node,
ClusterNode... nodes) {
+ A.notNull(node, "node");
+
+ return forNodes(collection(ArrayList::new, node, nodes));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forOthers(ClusterNode node,
ClusterNode... nodes) {
+ A.notNull(node, "node");
+
+ Collection<ClusterNode> nodes0 = collection(U::newHashSet, node,
nodes);
+
+ return forPredicate(n -> !nodes0.contains(n));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forOthers(ClientClusterGroup prj) {
+ A.notNull(prj, "prj");
+
+ Collection<ClusterNode> nodes0 = prj.nodes();
+
+ return forPredicate(n -> !nodes0.contains(n));
}
/** {@inheritDoc} */
@Override public ClientClusterGroup forNodeIds(Collection<UUID> ids) {
- return new ClientClusterGroupImpl(new HashSet<>(ids));
+ A.notNull(ids, "ids");
+
+ return forProjectionFilters(projectionFilters.forNodeIds(new
HashSet<>(ids)));
}
/** {@inheritDoc} */
@Override public ClientClusterGroup forNodeId(UUID id, UUID... ids) {
- Collection<UUID> nodeIds = U.newHashSet(1 + (ids == null ? 0 :
ids.length));
+ A.notNull(id, "id");
+
+ return
forProjectionFilters(projectionFilters.forNodeIds(collection(ArrayList::new,
id, ids)));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forPredicate(Predicate<ClusterNode> p)
{
+ A.notNull(p, "p");
+
+ return forProjectionFilters(projectionFilters.forPredicate(p));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forAttribute(String name, @Nullable
Object val) {
+ A.notNull(name, "name");
+
+ return forProjectionFilters(projectionFilters.forAttribute(name, val));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forServers() {
+ return forProjectionFilters(projectionFilters.forNodeType(true));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forClients() {
+ return forProjectionFilters(projectionFilters.forNodeType(false));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forRandom() {
+ return forProjectionFilters(projectionFilters.forResultFilter(nodes ->
{
+ if (F.isEmpty(nodes))
+ return nodes;
+
+ return
Collections.singletonList(nodes.get(ThreadLocalRandom.current().nextInt(nodes.size())));
+ }));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forOldest() {
+ return forProjectionFilters(projectionFilters.forResultFilter(nodes ->
{
+ if (F.isEmpty(nodes))
+ return nodes;
+
+ return
nodes.stream().min(Comparator.comparing(ClusterNode::order)).map(Collections::singletonList)
+ .orElse(Collections.emptyList());
+ }));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forYoungest() {
+ return forProjectionFilters(projectionFilters.forResultFilter(nodes ->
{
+ if (F.isEmpty(nodes))
+ return nodes;
+
+ return
nodes.stream().max(Comparator.comparing(ClusterNode::order)).map(Collections::singletonList)
+ .orElse(Collections.emptyList());
+ }));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forHost(ClusterNode node) {
+ A.notNull(node, "node");
+
+ String macs = node.attribute(ATTR_MACS);
+
+ assert macs != null;
- nodeIds.add(id);
+ return forAttribute(ATTR_MACS, macs);
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClientClusterGroup forHost(String host, String... hosts) {
+ A.notNull(host, "host");
+
+ Collection<String> hosts0 = collection(U::newHashSet, host, hosts);
- if (!F.isEmpty(ids))
- nodeIds.addAll(Arrays.asList(ids));
+ return forPredicate(n -> {
+ for (String hostName : n.hostNames()) {
+ if (hosts0.contains(hostName))
+ return true;
+ }
- return new ClientClusterGroupImpl(nodeIds);
+ return false;
+ });
+ }
+
+ /**
+ * @param projectionFilters Projection filters.
+ */
+ private ClientClusterGroupImpl forProjectionFilters(ProjectionFilters
projectionFilters) {
+ return this.projectionFilters == projectionFilters ? this :
+ new ClientClusterGroupImpl(ch, marsh, projectionFilters);
+ }
+
+ /** {@inheritDoc} */
+ @Override public Collection<ClusterNode> nodes() {
+ return Collections.unmodifiableCollection(nodes0());
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override public ClusterNode node(UUID nid) {
+ ClusterNode node = cachedNodes.get(nid);
+
+ if (projectionFilters.resultFilter == null) {
+ if (node == null)
+ node = F.first(nodesByIds(Collections.singleton(nid)));
+
+ return node != null && projectionFilters.testAllPredicates(node) ?
node : null;
+ }
+ else
+ return F.find(nodes0(), null, F.nodeForNodeId(nid));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClusterNode node() {
+ return F.first(nodes0());
}
/**
* Gets node id's.
+ *
+ * Note: This method is for internal use only. For optimization purposes
it can return not existing node IDs if
+ * only filter by node IDs was explicitly set.
+ * Method also returns null if no filter was set (full projection needed).
*/
public Collection<UUID> nodeIds() {
- return nodeIds == null ? null :
Collections.unmodifiableCollection(nodeIds);
+ if (projectionFilters == ProjectionFilters.FULL_PROJECTION)
+ return null;
+ else if (projectionFilters.hasOnlyNodeIdsFilters())
+ return
Collections.unmodifiableCollection(projectionFilters.nodeIds);
+ else if (projectionFilters.hasOnlyServerSideFilters()) {
+ Collection<UUID> nodeIds = requestNodeIds();
+
+ if (projectionFilters.nodeIds != null)
+ nodeIds.retainAll(projectionFilters.nodeIds);
+
+ return nodeIds;
+ } else
+ return F.nodeIds(nodes0());
+ }
+
+ /**
+ *
+ */
+ private Collection<ClusterNode> nodes0() {
+ return projectionFilters.hasOnlyNodeIdsFilters() ?
nodesByIds(projectionFilters.nodeIds) :
+ nodesByIds(requestNodeIds());
+ }
+
+ /**
+ * Requests node IDs from the server.
+ */
+ private synchronized Collection<UUID> requestNodeIds() {
+ try {
+ return ch.service(ClientOperation.CLUSTER_GROUP_GET_NODE_IDS,
+ req -> {
+ if
(!req.clientChannel().protocolCtx().isFeatureSupported(ProtocolBitmaskFeature.CLUSTER_GROUPS))
+ throw new
ClientFeatureNotSupportedByServerException(ProtocolBitmaskFeature.CLUSTER_GROUPS);
+
+ try (BinaryWriterExImpl writer = new
BinaryWriterExImpl(marsh.context(), req.out(), null,
+ null)) {
+ writer.writeLong(cachedTopVer);
+
+ projectionFilters.write(writer);
+ }
+ },
+ res -> {
+ if (!res.in().readBoolean())
+ return new ArrayList<>(cachedNodeIds); // There were
no changes since last request.
+
+ long topVer = res.in().readLong(); // Topology version.
+
+ int nodesCnt = res.in().readInt();
+
+ Collection<UUID> nodeIds = new ArrayList<>(nodesCnt);
+
+ for (int i = 0; i < nodesCnt; i++)
+ nodeIds.add(new UUID(res.in().readLong(),
res.in().readLong()));
+
+ cachedNodes.keySet().retainAll(nodeIds);
+
+ cachedTopVer = topVer;
+
+ cachedNodeIds = nodeIds;
+
+ return new ArrayList<>(nodeIds);
+ });
+ }
+ catch (ClientError e) {
+ throw new ClientException(e);
+ }
+ }
+
+ /**
+ * Get nodes by IDs. Try to get them from cache first, if some of them not
found in cache, request them from
+ * the server.
+ *
+ * @param nodeIds Node ids.
+ */
+ private Collection<ClusterNode> nodesByIds(Collection<UUID> nodeIds) {
+ List<ClusterNode> nodes = new ArrayList<>();
+ Collection<UUID> nodesToReq = null;
+
+ for (UUID nodeId : nodeIds) {
+ ClusterNode node = cachedNodes.get(nodeId);
+
+ if (node != null) {
+ if (projectionFilters.testClientSidePredicates(node))
+ nodes.add(node);
+ }
+ else {
+ if (nodesToReq == null)
+ nodesToReq = new ArrayList<>(nodeIds.size());
+
+ nodesToReq.add(nodeId);
+ }
+ }
+
+ if (!F.isEmpty(nodesToReq))
+ nodes.addAll(requestNodesByIds(nodesToReq));
+
+ return projectionFilters.applyResultFilter(nodes);
+ }
+
+ /**
+ * Requests nodes from the server.
+ *
+ * @param nodeIds Node ids.
+ */
+ private Collection<ClusterNode> requestNodesByIds(Collection<UUID>
nodeIds) {
+ try {
+ return ch.service(ClientOperation.CLUSTER_GROUP_GET_NODE_INFO,
+ req -> {
+ if
(!req.clientChannel().protocolCtx().isFeatureSupported(ProtocolBitmaskFeature.CLUSTER_GROUPS))
+ throw new
ClientFeatureNotSupportedByServerException(ProtocolBitmaskFeature.CLUSTER_GROUPS);
+
+ req.out().writeInt(nodeIds.size());
+
+ for (UUID nodeId : nodeIds) {
+ req.out().writeLong(nodeId.getMostSignificantBits());
+ req.out().writeLong(nodeId.getLeastSignificantBits());
+ }
+ },
+ res -> {
+ try (BinaryReaderExImpl reader = new
BinaryReaderExImpl(marsh.context(), res.in(), null,
+ true)) {
+ int nodesCnt = reader.readInt();
+
+ Collection<ClusterNode> nodes = new ArrayList<>();
+
+ for (int i = 0; i < nodesCnt; i++) {
+ ClusterNode node = readClusterNode(reader);
+
+ cachedNodes.put(node.id(), node);
+
+ if
(projectionFilters.testClientSidePredicates(node))
+ nodes.add(node);
+ }
+
+ return nodes;
+ }
+ catch (IOException e) {
+ throw new ClientError(e);
+ }
+ });
+ }
+ catch (ClientError e) {
+ throw new ClientException(e);
+ }
+ }
+
+ /**
+ * @param reader Reader.
+ */
+ private ClusterNode readClusterNode(BinaryReaderExImpl reader) {
+ return new ClientClusterNodeImpl(
+ reader.readUuid(),
+ readNodeAttributes(reader),
+ reader.readCollection(), // Addresses.
+ reader.readCollection(), // Host names.
+ reader.readLong(), // Order.
+ reader.readBoolean(), // Is local.
+ reader.readBoolean(), // Is daemon.
+ reader.readBoolean(), // Is client.
+ reader.readObjectDetached(), // Consistent ID.
+ readProductVersion(reader)
+ );
+ }
+
+ /**
+ * @param reader Reader.
+ */
+ private Map<String, Object> readNodeAttributes(BinaryReaderExImpl reader) {
+ int attrCnt = reader.readInt();
+
+ Map<String, Object> attrs = new HashMap<>(attrCnt);
+
+ for (int i = 0; i < attrCnt; i++)
+ attrs.put(reader.readString(), reader.readObjectDetached());
+
+ return attrs;
+ }
+
+ /**
+ * @param reader Reader.
+ */
+ private IgniteProductVersion readProductVersion(BinaryReaderExImpl reader)
{
+ return new IgniteProductVersion(
+ reader.readByte(), // Major.
+ reader.readByte(), // Minor.
+ reader.readByte(), // Maintenance.
+ reader.readString(), // Stage.
+ reader.readLong(), // Revision timestamp.
+ reader.readByteArray() // Revision hash.
+ );
+ }
+
+ /**
+ * Build collection from the first element and array of elements.
+ *
+ * @param factory Collection factory.
+ * @param item First item.
+ * @param items Other items.
+ */
+ private static <T> Collection<T> collection(IntFunction<Collection<T>>
factory, T item, T... items) {
+ Collection<T> col = factory.apply((item != null ? 1 : 0) + (items ==
null ? 0 : items.length));
+
+ if (item != null)
+ col.add(item);
+
+ if (!F.isEmpty(items))
+ col.addAll(Arrays.asList(items));
+
+ return col;
+ }
+
+ /**
+ * Class to store cluster group projection filters.
+ */
+ private static class ProjectionFilters {
+ /** Projection without any filters for full set of nodes. */
+ public static final ProjectionFilters FULL_PROJECTION = new
ProjectionFilters();
+
+ /** Filter for empty projection. Will be returned if there are
mutually exclusive filters detected. */
+ public static final ProjectionFilters EMPTY_PROJECTION =
+ new ProjectionFilters(Collections.emptySet(), null, null, null,
null);
+
+ /** Filter by attribute name and value. */
+ private static final short ATTRIBUTE_FILTER = 1;
+
+ /** Filter by client or server nodes. */
+ private static final short NODE_TYPE_FILTER = 2;
+
+ /** Node id's. */
+ private final Collection<UUID> nodeIds;
+
+ /** Attributes. */
+ private final Map<String, Object> attrs;
+
+ /** Node type filter. {@code true} for server nodes, {@code false} for
client nodes. */
+ private final Boolean nodeType;
+
+ /** Client-side predicate. */
+ private final Predicate<ClusterNode> predicate;
+
+ /**
+ * Filter for result collection of nodes, applies when nodes has been
selected on server side and filtered by
+ * client-side predicates.
+ *
+ * Note: After first result filter is set all subsequent filters (both
server-side and client-side) should be
+ * applied only locally on list of nodes produced by result filter.
These filters will be chainded to the result
+ * filter.
+ * For example, if we have next filter chain:
forServers().forRandom().forAttribute(...) we can't apply
+ * forServers and forAttribute on server-side and then apply forRandom
filter, the result will be wrong.
+ * We should filter server nodes (apply all filters before "random"
result filter), get random node and after
+ * random node filter is applied check that the node matching the
attribute. */
+ private final Function<List<ClusterNode>, List<ClusterNode>>
resultFilter;
+
+ /**
+ * Default constructor.
+ */
+ ProjectionFilters() {
+ nodeIds = null;
+ attrs = null;
+ nodeType = null;
+ predicate = null;
+ resultFilter = null;
+ }
+
+ /**
+ * Constructor with null result filter.
+ */
+ ProjectionFilters(
+ Collection<UUID> nodeIds,
+ Map<String, Object> attrs,
+ Boolean nodeType,
+ Predicate<ClusterNode> predicate
+ ) {
+ this.nodeIds = nodeIds;
+ this.attrs = attrs;
+ this.nodeType = nodeType;
+ this.predicate = predicate;
+ resultFilter = null;
+ }
+
+ /**
+ * Full constructor.
+ */
+ ProjectionFilters(
+ Collection<UUID> nodeIds,
+ Map<String, Object> attrs,
+ Boolean nodeType,
+ Predicate<ClusterNode> predicate,
+ Function<List<ClusterNode>, List<ClusterNode>> resultFilter
+ ) {
+ this.nodeIds = nodeIds;
+ this.attrs = attrs;
+ this.nodeType = nodeType;
+ this.predicate = predicate;
+ this.resultFilter = resultFilter;
+ }
+
+ /**
+ * @param nodeIds Node ids.
+ */
+ ProjectionFilters forNodeIds(Collection<UUID> nodeIds) {
+ if (this == EMPTY_PROJECTION || nodeIds == null)
+ return this;
+
+ if (resultFilter != null)
+ return
forResultFilter(resultFilterForPredicate(predicateForNodeIds(nodeIds)));
+
+ if (this.nodeIds != null) {
+ if (this.nodeIds.equals(nodeIds))
+ return this;
+
+ Set<UUID> nodeIdsIntersect = new HashSet<>(this.nodeIds);
+
+ nodeIdsIntersect.retainAll(nodeIds);
+
+ nodeIds = nodeIdsIntersect;
+ }
+
+ if (nodeIds.isEmpty())
+ return EMPTY_PROJECTION;
+
+ return new ProjectionFilters(nodeIds, attrs, nodeType, predicate);
+ }
+
+ /**
+ * @param nodeType Node type ({@code true} for server, {@code false}
for client).
+ */
+ ProjectionFilters forNodeType(boolean nodeType) {
+ if (this == EMPTY_PROJECTION)
+ return this;
+
+ if (resultFilter != null)
+ return
forResultFilter(resultFilterForPredicate(predicateForNodeType(nodeType)));
+
+ if (this.nodeType != null)
+ return this.nodeType == nodeType ? this : EMPTY_PROJECTION;
+
+ return new ProjectionFilters(nodeIds, attrs, nodeType, predicate);
+ }
+
+ /**
+ * @param name Attribute name.
+ * @param val Attribute value (or {@code null}).
+ */
+ ProjectionFilters forAttribute(String name, @Nullable Object val) {
+ if (this == EMPTY_PROJECTION)
+ return this;
+
+ if (resultFilter != null)
+ return
forResultFilter(resultFilterForPredicate(predicateForAttribute(name, val)));
+
+ if (attrs == null)
+ return new ProjectionFilters(nodeIds,
Collections.singletonMap(name, val), nodeType, predicate);
+
+ Map<String, Object> attrsIntersect = new HashMap<>(attrs);
+
+ Object oldVal = attrsIntersect.putIfAbsent(name, val);
+
+ if (F.eq(val, oldVal))
+ return this;
+
+ return oldVal != null && val != null ? EMPTY_PROJECTION :
+ new ProjectionFilters(nodeIds, attrsIntersect, nodeType,
predicate);
+ }
+
+ /**
+ * @param p Client-side node predicate.
+ */
+ ProjectionFilters forPredicate(Predicate<ClusterNode> p) {
+ if (this == EMPTY_PROJECTION || p == null)
+ return this;
+
+ if (resultFilter != null)
+ return forResultFilter(resultFilterForPredicate(p));
+
+ return new ProjectionFilters(nodeIds, attrs, nodeType, predicate
== null ? p : predicate.and(p));
+ }
+
+ /**
+ * @param resultFilter Result filter.
+ */
+ ProjectionFilters forResultFilter(Function<List<ClusterNode>,
List<ClusterNode>> resultFilter) {
+ if (this == EMPTY_PROJECTION || resultFilter == null)
+ return this;
+
+ return new ProjectionFilters(nodeIds, attrs, nodeType, predicate,
this.resultFilter == null ?
+ resultFilter : this.resultFilter.andThen(resultFilter));
+ }
+
+ /**
+ *
+ */
+ boolean hasOnlyNodeIdsFilters() {
+ return nodeIds != null && nodeType == null && attrs == null &&
predicate == null && resultFilter == null;
+ }
+
+ /**
+ *
+ */
+ boolean hasOnlyServerSideFilters() {
+ return (nodeType != null || attrs != null) && predicate == null &&
resultFilter == null;
+ }
+
+ /**
+ * Test node for client-side predicates. Assuming server-side
predicates already tested on server-side.
+ *
+ * @param node Node.
+ */
+ boolean testClientSidePredicates(ClusterNode node) {
+ if (nodeIds != null && !nodeIds.contains(node.id()))
+ return false;
+
+ return predicate == null || predicate.test(node);
+ }
+
+ /**
+ * Test node for all predicates (including testing locally for
server-side predicates).
+ *
+ * @param node Node.
+ */
+ boolean testAllPredicates(ClusterNode node) {
+ if (nodeType != null && !predicateForNodeType(nodeType).test(node))
+ return false;
+
+ if (!F.isEmpty(attrs)) {
+ for (Map.Entry<String, Object> attr : attrs.entrySet()) {
+ if (!predicateForAttribute(attr.getKey(),
attr.getValue()).test(node))
+ return false;
+ }
+ }
+
+ return testClientSidePredicates(node);
+ }
+
+ /**
+ * @param nodes Nodes.
+ */
+ List<ClusterNode> applyResultFilter(List<ClusterNode> nodes) {
+ return resultFilter != null ? resultFilter.apply(nodes) : nodes;
+ }
+
+ /**
+ * Creates filter using given predicate.
+ *
+ * @param p Predicate.
+ */
+ static Function<List<ClusterNode>, List<ClusterNode>>
resultFilterForPredicate(Predicate<ClusterNode> p) {
+ return nodes -> {
+ if (F.isEmpty(nodes))
+ return nodes;
+
+ ArrayList<ClusterNode> nodes0 = new ArrayList<>();
+
+ for (ClusterNode node : nodes) {
+ if (p.test(node))
+ nodes0.add(node);
+ }
+
+ return nodes0;
+ };
+ }
+
+ /**
+ * Creates client-side predicate for {@code forNodeIds} filter.
+ *
+ * @param nodeIds Node IDs.
+ */
+ static Predicate<ClusterNode> predicateForNodeIds(Collection<UUID>
nodeIds) {
+ return node -> nodeIds.contains(node.id());
+ }
+
+ /**
+ * Creates client-side predicate for {@code forNodeType} filter.
+ *
+ * @param nodeType Node type ({@code true} for server, {@code false}
for client).
+ */
+ static Predicate<ClusterNode> predicateForNodeType(boolean nodeType) {
+ return node -> nodeType == !node.isClient();
+ }
+
+ /**
+ * Creates client-side predicate for {@code forAttribute} filter.
+ *
+ * @param name Attribute name.
+ * @param val Attribute value (or {@code null}).
+ */
+ static Predicate<ClusterNode> predicateForAttribute(String name,
@Nullable Object val) {
+ return val == null ? node -> node.attributes().containsKey(name) :
node -> val.equals(node.attribute(name));
+ }
+
+ /**
+ * @param writer Writer.
+ */
+ void write(BinaryWriterExImpl writer) {
+ int size = (attrs == null ? 0 : attrs.size()) + (nodeType == null
? 0 : 1);
+
+ writer.writeInt(size);
+
+ if (!F.isEmpty(attrs)) {
+ for (Map.Entry<String, Object> entry : attrs.entrySet()) {
+ writer.writeShort(ATTRIBUTE_FILTER);
+ writer.writeString(entry.getKey());
+ writer.writeObject(entry.getValue());
+ }
+ }
+
+ if (nodeType != null) {
+ writer.writeShort(NODE_TYPE_FILTER);
+ writer.writeBoolean(nodeType);
+ }
+ }
}
}
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterImpl.java
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterImpl.java
index 9d822cd..4fdbffc 100644
---
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterImpl.java
+++
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterImpl.java
@@ -28,20 +28,11 @@ import org.apache.ignite.internal.binary.BinaryWriterExImpl;
* Implementation of {@link ClientCluster}.
*/
class ClientClusterImpl extends ClientClusterGroupImpl implements
ClientCluster {
- /** Channel. */
- private final ReliableChannel ch;
-
- /** Binary marshaller. */
- private final ClientBinaryMarshaller marsh;
-
/**
* Constructor.
*/
ClientClusterImpl(ReliableChannel ch, ClientBinaryMarshaller marsh) {
- super(null);
-
- this.ch = ch;
- this.marsh = marsh;
+ super(ch, marsh);
}
/** {@inheritDoc} */
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterNodeImpl.java
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterNodeImpl.java
new file mode 100644
index 0000000..4a42cad
--- /dev/null
+++
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientClusterNodeImpl.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.client.thin;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.cluster.ClusterMetrics;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.lang.IgniteProductVersion;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Thin client implementation of {@link ClusterNode}.
+ */
+class ClientClusterNodeImpl implements ClusterNode {
+ /** Node id. */
+ private final UUID id;
+
+ /** Consistent id. */
+ private final Object consistentId;
+
+ /** Attributes. */
+ private final Map<String, Object> attrs;
+
+ /** Addresses. */
+ private final Collection<String> addresses;
+
+ /** Host names. */
+ private final Collection<String> hostNames;
+
+ /** Order. */
+ private final long order;
+
+ /** Version. */
+ private final IgniteProductVersion ver;
+
+ /** Is local. For thin-client this flag is {@code true} for node to which
client is connected. */
+ private final boolean isLoc;
+
+ /** Is daemon. */
+ private final boolean isDaemon;
+
+ /** Is client. */
+ private final boolean isClient;
+
+ /**
+ * Default constructor.
+ */
+ ClientClusterNodeImpl(
+ UUID id,
+ Map<String, Object> attrs,
+ Collection<String> addresses,
+ Collection<String> hostNames,
+ long order,
+ boolean isLoc,
+ boolean isDaemon,
+ boolean isClient,
+ Object consistentId,
+ IgniteProductVersion ver
+ ) {
+ this.id = id;
+ this.consistentId = consistentId;
+ this.attrs = Collections.unmodifiableMap(attrs);
+ this.addresses = Collections.unmodifiableCollection(addresses);
+ this.hostNames = Collections.unmodifiableCollection(hostNames);
+ this.order = order;
+ this.ver = ver;
+ this.isLoc = isLoc;
+ this.isDaemon = isDaemon;
+ this.isClient = isClient;
+ }
+
+ /** {@inheritDoc} */
+ @Override public UUID id() {
+ return id;
+ }
+
+ /** {@inheritDoc} */
+ @Override public Object consistentId() {
+ return consistentId;
+ }
+
+ /** {@inheritDoc} */
+ @Override public <T> @Nullable T attribute(String name) {
+ return (T)attrs.get(name);
+ }
+
+ /** {@inheritDoc} */
+ @Override public ClusterMetrics metrics() {
+ throw new UnsupportedOperationException("Metrics are not supported for
thin client implementation of ClusterNode");
+ }
+
+ /** {@inheritDoc} */
+ @Override public Map<String, Object> attributes() {
+ return attrs;
+ }
+
+ /** {@inheritDoc} */
+ @Override public Collection<String> addresses() {
+ return addresses;
+ }
+
+ /** {@inheritDoc} */
+ @Override public Collection<String> hostNames() {
+ return hostNames;
+ }
+
+ /** {@inheritDoc} */
+ @Override public long order() {
+ return order;
+ }
+
+ /** {@inheritDoc} */
+ @Override public IgniteProductVersion version() {
+ return ver;
+ }
+
+ /** {@inheritDoc} */
+ @Override public boolean isLocal() {
+ return isLoc;
+ }
+
+ /** {@inheritDoc} */
+ @Override public boolean isDaemon() {
+ return isDaemon;
+ }
+
+ /** {@inheritDoc} */
+ @Override public boolean isClient() {
+ return isClient;
+ }
+
+ /** {@inheritDoc} */
+ @Override public boolean equals(Object o) {
+ return F.eqNodes(this, o);
+ }
+
+ /** {@inheritDoc} */
+ @Override public int hashCode() {
+ return id.hashCode();
+ }
+
+ /** {@inheritDoc} */
+ @Override public String toString() {
+ return S.toString(ClientClusterNodeImpl.class, this);
+ }
+}
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientOperation.java
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientOperation.java
index d6529fb..3cf228c 100644
---
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientOperation.java
+++
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientOperation.java
@@ -70,6 +70,8 @@ enum ClientOperation {
/** Change cluster state. */CLUSTER_CHANGE_STATE(5001),
/** Get WAL state. */CLUSTER_GET_WAL_STATE(5003),
/** Change WAL state. */CLUSTER_CHANGE_WAL_STATE(5002),
+ /** Get nodes IDs by filter. */CLUSTER_GROUP_GET_NODE_IDS(5100),
+ /** Get nodes info by IDs. */CLUSTER_GROUP_GET_NODE_INFO(5101),
/** Execute compute task. */COMPUTE_TASK_EXECUTE(6000),
/** Finished compute task notification. */COMPUTE_TASK_FINISHED(6001,
true);
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ProtocolBitmaskFeature.java
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ProtocolBitmaskFeature.java
index 5e6e395..0896bb8 100644
---
a/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ProtocolBitmaskFeature.java
+++
b/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ProtocolBitmaskFeature.java
@@ -35,7 +35,10 @@ public enum ProtocolBitmaskFeature {
* Cluster operations (state and WAL). In addition to {@link
ProtocolVersionFeature#CLUSTER_API} this feature
* also allows to use other cluster states beside ACTIVE and INACTIVE.
*/
- CLUSTER_API(2);
+ CLUSTER_API(2),
+
+ /** Cluster groups. */
+ CLUSTER_GROUPS(4);
/** */
private static final EnumSet<ProtocolBitmaskFeature>
ALL_FEATURES_AS_ENUM_SET =
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/ClientBitmaskFeature.java
b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/ClientBitmaskFeature.java
index fc09214..b35e78c 100644
---
a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/ClientBitmaskFeature.java
+++
b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/ClientBitmaskFeature.java
@@ -34,7 +34,10 @@ public enum ClientBitmaskFeature implements
ThinProtocolFeature {
CLUSTER_API(2),
/** Client discovery. */
- CLUSTER_GROUP_GET_NODES_ENDPOINTS(3);
+ CLUSTER_GROUP_GET_NODES_ENDPOINTS(3),
+
+ /** Cluster groups. */
+ CLUSTER_GROUPS(4);
/** */
private static final EnumSet<ClientBitmaskFeature>
ALL_FEATURES_AS_ENUM_SET =
diff --git
a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cluster/ClientClusterGroupProjection.java
b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cluster/ClientClusterGroupProjection.java
index f992879..0cfe527 100644
---
a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cluster/ClientClusterGroupProjection.java
+++
b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cluster/ClientClusterGroupProjection.java
@@ -111,7 +111,7 @@ public class ClientClusterGroupProjection {
/**
* Attribute value.
*/
- private final String val;
+ private final Object val;
/**
* Ctor.
@@ -120,7 +120,7 @@ public class ClientClusterGroupProjection {
*/
public ForAttributeProjectionItem(BinaryRawReader reader) {
name = reader.readString();
- val = reader.readString();
+ val = reader.readObject();
}
/**
diff --git
a/modules/core/src/test/java/org/apache/ignite/internal/client/thin/ClusterGroupTest.java
b/modules/core/src/test/java/org/apache/ignite/internal/client/thin/ClusterGroupTest.java
new file mode 100644
index 0000000..5023e85
--- /dev/null
+++
b/modules/core/src/test/java/org/apache/ignite/internal/client/thin/ClusterGroupTest.java
@@ -0,0 +1,429 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.client.thin;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.Ignition;
+import org.apache.ignite.client.ClientClusterGroup;
+import org.apache.ignite.client.IgniteClient;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.ClientConfiguration;
+import org.apache.ignite.configuration.ClientConnectorConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+
+/**
+ * Checks cluster groups for thin client.
+ */
+public class ClusterGroupTest extends GridCommonAbstractTest {
+ /** Client connector address. */
+ private static final String CLIENT_CONN_ADDR = "127.0.0.1:" +
ClientConnectorConfiguration.DFLT_PORT;
+
+ /** Grid index attribute name. */
+ private static final String GRID_IDX_ATTR_NAME = "GRID_IDX";
+
+ /** Some custom attribute name. */
+ private static final String CUSTOM_ATTR_NAME = "CUSTOM_ATTR";
+
+ /** Custom attribute value. */
+ private static final String CUSTOM_ATTR_VAL = "VAL";
+
+ /** Client. */
+ private static IgniteClient client;
+
+ /** {@inheritDoc} */
+ @Override protected void beforeTestsStarted() throws Exception {
+ super.beforeTestsStarted();
+
+ startGrid(0, false, null);
+ startGrid(1, false, null);
+ startGrid(2, false, F.asMap(CUSTOM_ATTR_NAME, CUSTOM_ATTR_VAL));
+ startGrid(3, true, null);
+ startGrid(4, true, F.asMap(CUSTOM_ATTR_NAME, CUSTOM_ATTR_VAL));
+
+ client = Ignition.startClient(new
ClientConfiguration().setAddresses(CLIENT_CONN_ADDR));
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void afterTestsStopped() throws Exception {
+ super.afterTestsStopped();
+
+ client.close();
+ }
+
+ /**
+ * Test that thin client ClusterNode instances have the same field values
as server ClusterNode instances.
+ */
+ @Test
+ public void testClusterNodeFields() {
+ for (Ignite ignite : G.allGrids()) {
+ ClusterNode igniteNode = ignite.cluster().localNode();
+
+ ClusterNode clientNode = client.cluster().node(igniteNode.id());
+
+ assertEquals(igniteNode.id(), clientNode.id());
+ assertEquals(igniteNode.consistentId(), clientNode.consistentId());
+ // Some attribute values identical by content, but not equals
after marshalling/unmarshalling
+ // (for example values of type byte[]), so we can't compare whole
attribute maps using assertEquals.
+ assertEquals(igniteNode.attributes().keySet(),
clientNode.attributes().keySet());
+ assertEquals((Integer)igniteNode.attribute(GRID_IDX_ATTR_NAME),
clientNode.attribute(GRID_IDX_ATTR_NAME));
+ assertEquals(igniteNode.attribute(CUSTOM_ATTR_NAME),
clientNode.attribute(CUSTOM_ATTR_NAME));
+ assertEquals(new HashSet<>(igniteNode.addresses()), new
HashSet<>(clientNode.addresses()));
+ assertEquals(new HashSet<>(igniteNode.hostNames()), new
HashSet<>(clientNode.hostNames()));
+ assertEquals(igniteNode.order(), clientNode.order());
+ assertEquals(igniteNode.version(), clientNode.version());
+ assertEquals(igniteNode.isDaemon(), clientNode.isDaemon());
+ assertEquals(igniteNode.isClient(), clientNode.isClient());
+ }
+ }
+
+ /**
+ * Test forNode(), forNodes() methods.
+ */
+ @Test
+ public void testForNodes() {
+ ClusterNode node0 = client.cluster().node(grid(0).localNode().id());
+ ClusterNode node1 = client.cluster().node(grid(1).localNode().id());
+
+ assertNodes(client.cluster().forNode(node0, node1), 0, 1);
+ assertNodes(client.cluster().forNode(node0), 0);
+ assertNodes(client.cluster().forNode(node1), 1);
+ assertNodes(client.cluster().forNodes(F.asList(node0, node1)), 0, 1);
+ assertNodes(client.cluster().forNodes(F.asList(node0)), 0);
+ assertNodes(client.cluster().forNodes(F.asList(node0,
node1)).forNode(node0), 0);
+ assertNodes(client.cluster().forNode(node0,
node1).forNodes(F.asList(node0, node1)), 0, 1);
+ assertNodes(client.cluster().forNode(node0).forNodes(F.asList(node0,
node1)), 0);
+ assertNodes(client.cluster().forNode(node0).forNodes(F.asList(node1)));
+ }
+
+ /**
+ * Test forOthers() methods.
+ */
+ @Test
+ public void testForOthers() {
+ ClusterNode node0 = client.cluster().node(grid(0).localNode().id());
+ ClusterNode node1 = client.cluster().node(grid(1).localNode().id());
+
+ assertNodes(client.cluster().forOthers(node0, node1), 2, 3, 4);
+
assertNodes(client.cluster().forOthers(client.cluster().forOthers(node0,
node1)), 0, 1);
+ assertNodes(client.cluster().forOthers(node0).forOthers(node1), 2, 3,
4);
+ assertNodes(client.cluster().forOthers(node0, node1).forOthers(node1),
2, 3, 4);
+
assertNodes(client.cluster().forOthers(node0).forOthers(client.cluster().forOthers(node0,
node1)), 1);
+ }
+
+ /**
+ * Test forNodeId(), forNodeIds() methods.
+ */
+ @Test
+ public void testForNodeIds() {
+ UUID id0 = nodeId(0);
+ UUID id1 = nodeId(1);
+
+ assertNodes(client.cluster().forNodeId(id0, id1), 0, 1);
+ assertNodes(client.cluster().forNodeId(id0), 0);
+ assertNodes(client.cluster().forNodeId(id1), 1);
+ assertNodes(client.cluster().forNodeIds(F.asList(id0, id1)), 0, 1);
+ assertNodes(client.cluster().forNodeIds(F.asList(id0)), 0);
+ assertNodes(client.cluster().forNodeIds(F.asList(id0,
id1)).forNodeId(id0), 0);
+ assertNodes(client.cluster().forNodeId(id0,
id1).forNodeIds(F.asList(id0, id1)), 0, 1);
+ assertNodes(client.cluster().forNodeId(id0).forNodeIds(F.asList(id0,
id1)), 0);
+ assertNodes(client.cluster().forNodeId(id0).forNodeIds(F.asList(id1)));
+ assertNodes(client.cluster().forNodeId(UUID.randomUUID()));
+ assertNodes(client.cluster().forNodeIds(F.asList(UUID.randomUUID())));
+ }
+
+ /**
+ * Test forPredicate() method.
+ */
+ @Test
+ public void testForPredicate() {
+ assertNodes(client.cluster().forPredicate(ClusterNode::isClient), 3,
4);
+ assertNodes(client.cluster().forPredicate(n -> n.order() == 1), 0);
+
assertNodes(client.cluster().forPredicate(ClusterNode::isClient).forPredicate(n
-> !n.isClient()));
+
assertNodes(client.cluster().forPredicate(ClusterNode::isClient).forPredicate(n
-> n.order() == 5), 4);
+ }
+
+ /**
+ * Test forAttribute() method.
+ */
+ @Test
+ public void testForAttribute() {
+ assertNodes(client.cluster().forAttribute(CUSTOM_ATTR_NAME,
CUSTOM_ATTR_VAL), 2, 4);
+ assertNodes(client.cluster().forAttribute(CUSTOM_ATTR_NAME, null), 2,
4);
+ assertNodes(client.cluster().forAttribute(CUSTOM_ATTR_NAME,
CUSTOM_ATTR_VAL)
+ .forAttribute(CUSTOM_ATTR_NAME, CUSTOM_ATTR_VAL), 2, 4);
+ assertNodes(client.cluster().forAttribute(CUSTOM_ATTR_NAME, null)
+ .forAttribute(CUSTOM_ATTR_NAME, CUSTOM_ATTR_VAL), 2, 4);
+ assertNodes(client.cluster().forAttribute(CUSTOM_ATTR_NAME,
CUSTOM_ATTR_VAL)
+ .forAttribute(CUSTOM_ATTR_NAME, null), 2, 4);
+ assertNodes(client.cluster().forAttribute(GRID_IDX_ATTR_NAME, 0), 0);
+ assertNodes(client.cluster().forAttribute(GRID_IDX_ATTR_NAME,
0).forAttribute(GRID_IDX_ATTR_NAME, 1));
+ assertNodes(client.cluster().forAttribute(CUSTOM_ATTR_NAME,
CUSTOM_ATTR_VAL)
+ .forAttribute(GRID_IDX_ATTR_NAME, 2), 2);
+ }
+
+ /**
+ * Test forServers()/forClients() methods.
+ */
+ @Test
+ public void testForServersForClients() {
+ assertNodes(client.cluster().forServers(), 0, 1, 2);
+ assertNodes(client.cluster().forClients(), 3, 4);
+ assertNodes(client.cluster().forServers().forServers(), 0, 1, 2);
+ assertNodes(client.cluster().forClients().forClients(), 3, 4);
+ assertNodes(client.cluster().forServers().forClients());
+ }
+
+ /**
+ * Test forRandom()/forOldest()/forYoungest() methods.
+ */
+ @Test
+ public void testOneNodeFilters() {
+ assertEquals(1, client.cluster().forRandom().nodes().size());
+ assertNodes(client.cluster().forOldest(), 0);
+ assertNodes(client.cluster().forYoungest(), 4);
+ assertNodes(client.cluster().forOldest().forYoungest(), 0);
+ assertNodes(client.cluster().forYoungest().forOldest(), 4);
+ assertNodes(client.cluster().forOldest().forYoungest().forRandom(), 0);
+
+ assertEquals(grid(0).localNode(), client.cluster().forOldest().node());
+ assertEquals(grid(4).localNode(),
client.cluster().forYoungest().node());
+ }
+
+ /**
+ * Test forHost() methods.
+ */
+ @Test
+ public void testForHost() {
+ ClusterNode node0 = grid(0).localNode();
+ String hostName = F.first(node0.hostNames());
+
+ assertNodes(client.cluster().forHost(node0), 0, 1, 2, 3, 4);
+ assertNodes(client.cluster().forHost(hostName), 0, 1, 2, 3, 4);
+ assertNodes(client.cluster().forHost(node0).forHost(hostName), 0, 1,
2, 3, 4);
+ assertNodes(client.cluster().forHost(hostName, hostName), 0, 1, 2, 3,
4);
+ assertNodes(client.cluster().forHost("-"));
+ assertNodes(client.cluster().forHost("-", hostName), 0, 1, 2, 3, 4);
+ assertNodes(client.cluster().forHost("-").forHost(node0));
+ }
+
+ /**
+ * Test combination of different for... methods.
+ */
+ @Test
+ public void testForFiltersCombinations() {
+ assertNodes(client.cluster(), 0, 1, 2, 3, 4);
+
+
assertNodes(client.cluster().forServers().forAttribute(CUSTOM_ATTR_NAME,
CUSTOM_ATTR_VAL), 2);
+ assertNodes(client.cluster().forNodeId(nodeId(0), nodeId(1), nodeId(4))
+ .forAttribute(CUSTOM_ATTR_NAME,
CUSTOM_ATTR_VAL).forPredicate(ClusterNode::isClient), 4);
+
assertNodes(client.cluster().forClients().forOthers(grid(4).localNode()), 3);
+
+ // Check resultFilter chaining.
+ assertNodes(client.cluster().forOldest().forClients());
+
assertNodes(client.cluster().forNodeId(nodeId(0)).forOldest().forNodeId(nodeId(0)),
0);
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(1)).forOldest()
+ .forNodeId(nodeId(1)));
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forOldest().forClients());
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forYoungest().forClients(), 4);
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forOldest()
+ .forPredicate(ClusterNode::isClient));
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forYoungest()
+ .forPredicate(ClusterNode::isClient), 4);
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forOldest()
+ .forAttribute(CUSTOM_ATTR_NAME, null));
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forYoungest()
+ .forAttribute(CUSTOM_ATTR_NAME, null), 4);
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forOldest()
+ .forAttribute(CUSTOM_ATTR_NAME, CUSTOM_ATTR_VAL));
+ assertNodes(client.cluster().forNodeId(nodeId(0),
nodeId(4)).forYoungest()
+ .forAttribute(CUSTOM_ATTR_NAME, CUSTOM_ATTR_VAL), 4);
+ }
+
+ /**
+ * Test that ClusterNode doesn't requested each time from the server.
+ */
+ @Test
+ public void testClusterNodeCaching() {
+ ClientClusterGroup grp = client.cluster().forServers();
+
+ Collection<ClusterNode> nodes1 = grp.nodes();
+ Collection<ClusterNode> nodes2 = grp.nodes();
+
+ assertEquals(3, nodes1.size());
+ assertEquals(3, nodes2.size());
+
+ int foundCnt = 0;
+
+ for (ClusterNode node1 : nodes1) {
+ for (ClusterNode node2 : nodes2) {
+ if (F.eq(node1.id(), node2.id())) {
+ assertTrue(node1 == node2); // Should be exactly the same
instance.
+
+ foundCnt++;
+ }
+ }
+ }
+
+ assertEquals(3, foundCnt);
+ }
+
+ /**
+ * Test node(UUID) method.
+ */
+ @Test
+ public void testNodeById() {
+ UUID rndId = UUID.randomUUID();
+ ClusterNode node0 = client.cluster().node(nodeId(0));
+
+ assertNotNull(node0);
+ assertNull(client.cluster().node(rndId));
+ assertNull(client.cluster().forNodeId(rndId).node(rndId));
+
+ assertEquals(node0,
client.cluster().forNodeId(nodeId(0)).node(nodeId(0)));
+ assertNull(client.cluster().forNodeId(nodeId(0)).node(nodeId(1)));
+
+ assertEquals(node0, client.cluster().forNode(node0).node(nodeId(0)));
+ assertNull(client.cluster().forNode(node0).node(nodeId(1)));
+
+ assertEquals(node0, client.cluster().forServers().node(nodeId(0)));
+ assertNull(client.cluster().forServers().node(nodeId(3)));
+
+ assertEquals(node0, client.cluster().forAttribute(GRID_IDX_ATTR_NAME,
0).node(nodeId(0)));
+ assertNull(client.cluster().forAttribute(GRID_IDX_ATTR_NAME,
0).node(nodeId(1)));
+
+ assertEquals(node0, client.cluster().forOldest().node(nodeId(0)));
+ assertNull(client.cluster().forOldest().node(nodeId(1)));
+
+ assertEquals(node0, client.cluster().forServers().forNodeId(nodeId(0),
nodeId(1),
+ nodeId(3)).forOldest().node(nodeId(0)));
+ assertNull(client.cluster().forServers().forNodeId(nodeId(0),
nodeId(1), nodeId(3))
+ .forOldest().node(nodeId(1)));
+ }
+
+ /**
+ * Test nodeIds() method.
+ */
+ @Test
+ public void testNodeIds() {
+ // Check full projection.
+ assertNull(((ClientClusterGroupImpl)client.cluster()).nodeIds());
+
+ // Check filter only by node id.
+ Collection<UUID> nodeIds =
((ClientClusterGroupImpl)client.cluster().forNodeId(nodeId(0),
+ nodeId(1), UUID.randomUUID())).nodeIds();
+
+ assertTrue(nodeIds.contains(nodeId(0)));
+ assertTrue(nodeIds.contains(nodeId(1)));
+ assertFalse(nodeIds.contains(nodeId(2)));
+ assertFalse(nodeIds.contains(nodeId(3)));
+ assertFalse(nodeIds.contains(nodeId(4)));
+
+ // Check server-side filter.
+ nodeIds =
((ClientClusterGroupImpl)client.cluster().forServers()).nodeIds();
+
+ assertEquals(new HashSet<>(F.asList(nodeId(0), nodeId(1), nodeId(2))),
+ new HashSet<>(nodeIds));
+
+ // Check client-side filters.
+ nodeIds =
((ClientClusterGroupImpl)client.cluster().forPredicate(ClusterNode::isClient)).nodeIds();
+
+ assertEquals(new HashSet<>(F.asList(nodeId(3), nodeId(4))), new
HashSet<>(nodeIds));
+
+ nodeIds =
((ClientClusterGroupImpl)client.cluster().forOldest()).nodeIds();
+
+ assertEquals(Collections.singleton(nodeId(0)), new HashSet<>(nodeIds));
+
+ // Check filters combination.
+ nodeIds =
((ClientClusterGroupImpl)client.cluster().forServers().forClients()).nodeIds();
+
+ assertTrue(nodeIds.isEmpty());
+
+ nodeIds =
((ClientClusterGroupImpl)client.cluster().forServers().forNodeId(nodeId(0),
+ nodeId(1))).nodeIds();
+
+ assertEquals(new HashSet<>(F.asList(nodeId(0), nodeId(1))),
+ new HashSet<>(nodeIds));
+
+ nodeIds =
((ClientClusterGroupImpl)client.cluster().forNodeId(nodeId(1), nodeId(2),
+ nodeId(3),
UUID.randomUUID()).forServers().forYoungest()).nodeIds();
+
+ assertEquals(Collections.singleton(nodeId(2)), new HashSet<>(nodeIds));
+ }
+
+ /**
+ * Asserts that cluster group has the same nodes set as expected.
+ *
+ * @param grp Group.
+ * @param nodeIdxs Node idxs.
+ */
+ private void assertNodes(ClientClusterGroup grp, int... nodeIdxs) {
+ Collection<ClusterNode> expNodes = U.newHashSet(nodeIdxs.length);
+
+ if (nodeIdxs == null) {
+ assertTrue(F.isEmpty(grp.nodes()));
+
+ return;
+ }
+
+ for (int nodeIdx : nodeIdxs)
+ expNodes.add(grid(nodeIdx).localNode());
+
+ assertEquals(expNodes, new HashSet<>(grp.nodes()));
+ }
+
+ /**
+ * Start grid node with defined parameters.
+ */
+ private void startGrid(int idx, boolean client, Map<String, Object> attrs)
throws Exception {
+ IgniteConfiguration cfg =
getConfiguration(getTestIgniteInstanceName(idx));
+
+ if (attrs == null)
+ attrs = F.asMap(GRID_IDX_ATTR_NAME, idx);
+ else
+ attrs.put(GRID_IDX_ATTR_NAME, idx);
+
+ cfg.setUserAttributes(attrs);
+ cfg.setClientMode(client);
+ cfg.setDiscoverySpi(new
TestDiscoverySpi().setIpFinder(((TcpDiscoverySpi)cfg.getDiscoverySpi()).getIpFinder()));
+
+ startGrid(cfg);
+ }
+
+ /**
+ * SPI to override hosts for ClusterNodes.
+ */
+ private static class TestDiscoverySpi extends TcpDiscoverySpi {
+ /** {@inheritDoc} */
+ @Override protected void initLocalNode(int srvPort, boolean
addExtAddrAttr) {
+ super.initLocalNode(srvPort, addExtAddrAttr);
+
+ locNode.hostNames().add("dummy");
+ }
+ }
+}
diff --git
a/modules/indexing/src/test/java/org/apache/ignite/client/ClientTestSuite.java
b/modules/indexing/src/test/java/org/apache/ignite/client/ClientTestSuite.java
index 68bb391..07ac59f 100644
---
a/modules/indexing/src/test/java/org/apache/ignite/client/ClientTestSuite.java
+++
b/modules/indexing/src/test/java/org/apache/ignite/client/ClientTestSuite.java
@@ -18,6 +18,7 @@
package org.apache.ignite.client;
import org.apache.ignite.internal.client.thin.ClusterApiTest;
+import org.apache.ignite.internal.client.thin.ClusterGroupTest;
import org.apache.ignite.internal.client.thin.ComputeTaskTest;
import
org.apache.ignite.internal.client.thin.ThinClientPartitionAwarenessResourceReleaseTest;
import
org.apache.ignite.internal.client.thin.ThinClientPartitionAwarenessStableTopologyTest;
@@ -45,6 +46,7 @@ import org.junit.runners.Suite;
AsyncChannelTest.class,
ComputeTaskTest.class,
ClusterApiTest.class,
+ ClusterGroupTest.class,
ThinClientPartitionAwarenessStableTopologyTest.class,
ThinClientPartitionAwarenessUnstableTopologyTest.class,
ThinClientPartitionAwarenessResourceReleaseTest.class