当前位置: 首页>>代码示例>>Java>>正文


Java ShardRouting.currentNodeId方法代码示例

本文整理汇总了Java中org.elasticsearch.cluster.routing.ShardRouting.currentNodeId方法的典型用法代码示例。如果您正苦于以下问题:Java ShardRouting.currentNodeId方法的具体用法?Java ShardRouting.currentNodeId怎么用?Java ShardRouting.currentNodeId使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.elasticsearch.cluster.routing.ShardRouting的用法示例。


在下文中一共展示了ShardRouting.currentNodeId方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: explainShard

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
public static ClusterAllocationExplanation explainShard(ShardRouting shardRouting, RoutingAllocation allocation,
                                                        ClusterInfo clusterInfo, boolean includeYesDecisions,
                                                        GatewayAllocator gatewayAllocator, ShardsAllocator shardAllocator) {
    allocation.setDebugMode(includeYesDecisions ? DebugMode.ON : DebugMode.EXCLUDE_YES_DECISIONS);

    ShardAllocationDecision shardDecision;
    if (shardRouting.initializing() || shardRouting.relocating()) {
        shardDecision = ShardAllocationDecision.NOT_TAKEN;
    } else {
        AllocateUnassignedDecision allocateDecision = shardRouting.unassigned() ?
            gatewayAllocator.decideUnassignedShardAllocation(shardRouting, allocation) : AllocateUnassignedDecision.NOT_TAKEN;
        if (allocateDecision.isDecisionTaken() == false) {
            shardDecision = shardAllocator.decideShardAllocation(shardRouting, allocation);
        } else {
            shardDecision = new ShardAllocationDecision(allocateDecision, MoveDecision.NOT_TAKEN);
        }
    }

    return new ClusterAllocationExplanation(shardRouting,
        shardRouting.currentNodeId() != null ? allocation.nodes().get(shardRouting.currentNodeId()) : null,
        shardRouting.relocatingNodeId() != null ? allocation.nodes().get(shardRouting.relocatingNodeId()) : null,
        clusterInfo, shardDecision);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:TransportClusterAllocationExplainAction.java

示例2: getTranslogDirs

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private Set<Path> getTranslogDirs(String indexName) throws IOException {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[]{indexName}, false);
    final Index idx = state.metaData().index(indexName).getIndex();
    List<ShardIterator> iterators = iterableAsArrayList(shardIterators);
    ShardIterator shardIterator = RandomPicks.randomFrom(random(), iterators);
    ShardRouting shardRouting = shardIterator.nextOrNull();
    assertNotNull(shardRouting);
    assertTrue(shardRouting.primary());
    assertTrue(shardRouting.assignedToNode());
    String nodeId = shardRouting.currentNodeId();
    NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
    Set<Path> translogDirs = new TreeSet<>(); // treeset makes sure iteration order is deterministic
    for (FsInfo.Path fsPath : nodeStatses.getNodes().get(0).getFs()) {
        String path = fsPath.getPath();
        final String relativeDataLocationPath =  "indices/"+ idx.getUUID() +"/" + Integer.toString(shardRouting.getId()) + "/translog";
        Path translogPath = PathUtils.get(path).resolve(relativeDataLocationPath);
        if (Files.isDirectory(translogPath)) {
            translogDirs.add(translogPath);
        }
    }
    return translogDirs;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:TruncateTranslogIT.java

示例3: testFindShardAssignedToNode

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
public void testFindShardAssignedToNode() {
    // find shard with given node
    final boolean primary = randomBoolean();
    ShardRoutingState[] replicaStates = new ShardRoutingState[0];
    if (primary == false) {
        replicaStates = new ShardRoutingState[] { ShardRoutingState.STARTED };
    }
    ClusterState clusterState = ClusterStateCreationUtils.state("idx", randomBoolean(), ShardRoutingState.STARTED, replicaStates);
    ShardRouting shardToExplain = primary ? clusterState.getRoutingTable().index("idx").shard(0).primaryShard() :
                                      clusterState.getRoutingTable().index("idx").shard(0).replicaShards().get(0);
    ClusterAllocationExplainRequest request = new ClusterAllocationExplainRequest("idx", 0, primary, shardToExplain.currentNodeId());
    RoutingAllocation allocation = routingAllocation(clusterState);
    ShardRouting foundShard = findShardToExplain(request, allocation);
    assertEquals(shardToExplain, foundShard);

    // shard is not assigned to given node
    String explainNode = null;
    for (RoutingNode routingNode : clusterState.getRoutingNodes()) {
        if (routingNode.nodeId().equals(shardToExplain.currentNodeId()) == false) {
            explainNode = routingNode.nodeId();
            break;
        }
    }
    final ClusterAllocationExplainRequest failingRequest = new ClusterAllocationExplainRequest("idx", 0, primary, explainNode);
    expectThrows(IllegalStateException.class, () -> findShardToExplain(failingRequest, allocation));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:ClusterAllocationExplainActionTests.java

示例4: processShardRouting

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private void processShardRouting(Map<String, Map<String, List<Integer>>> routing, ShardRouting shardRouting, ShardId shardId) {
    String node;
    int id;
    String index = shardId.getIndex();

    if (shardRouting == null) {
        node = service.localNode().id();
        id = UnassignedShard.markUnassigned(shardId.id());
    } else {
        node = shardRouting.currentNodeId();
        id = shardRouting.id();
    }
    Map<String, List<Integer>> nodeMap = routing.get(node);
    if (nodeMap == null) {
        nodeMap = new TreeMap<>();
        routing.put(node, nodeMap);
    }

    List<Integer> shards = nodeMap.get(index);
    if (shards == null) {
        shards = new ArrayList<>();
        nodeMap.put(index, shards);
    }
    shards.add(id);
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:26,代码来源:SysShardsTableInfo.java

示例5: processShardRouting

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private void processShardRouting(Map<String, Map<String, List<Integer>>> locations, ShardRouting shardRouting, ShardId shardId) {
    String node;
    if (shardRouting == null) {
        throw new NoShardAvailableActionException(shardId);
    }
    node = shardRouting.currentNodeId();
    Map<String, List<Integer>> nodeMap = locations.get(node);
    if (nodeMap == null) {
        nodeMap = new TreeMap<>();
        locations.put(shardRouting.currentNodeId(), nodeMap);
    }

    List<Integer> shards = nodeMap.get(shardRouting.getIndex());
    if (shards == null) {
        shards = new ArrayList<>();
        nodeMap.put(shardRouting.getIndex(), shards);
    }
    shards.add(shardRouting.id());
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:20,代码来源:BlobTableInfo.java

示例6: assertAllShardsOnNodes

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
/**
 * Asserts that all shards are allocated on nodes matching the given node pattern.
 */
public Set<String> assertAllShardsOnNodes(String index, String... pattern) {
    Set<String> nodes = new HashSet<>();
    ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
    for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
        for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
            for (ShardRouting shardRouting : indexShardRoutingTable) {
                if (shardRouting.currentNodeId() != null && index.equals(shardRouting.getIndexName())) {
                    String name = clusterState.nodes().get(shardRouting.currentNodeId()).getName();
                    nodes.add(name);
                    assertThat("Allocated on new node: " + name, Regex.simpleMatch(pattern, name), is(true));
                }
            }
        }
    }
    return nodes;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:ESIntegTestCase.java

示例7: performOn

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
@Override
public void performOn(ShardRouting replica, ReplicaRequest request, ActionListener<ReplicationOperation.ReplicaResponse> listener) {
    String nodeId = replica.currentNodeId();
    final DiscoveryNode node = clusterService.state().nodes().get(nodeId);
    if (node == null) {
        listener.onFailure(new NoNodeAvailableException("unknown node [" + nodeId + "]"));
        return;
    }
    final ConcreteShardRequest<ReplicaRequest> concreteShardRequest =
            new ConcreteShardRequest<>(request, replica.allocationId().getId());
    sendReplicaRequest(concreteShardRequest, node, listener);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:13,代码来源:TransportReplicationAction.java

示例8: corruptRandomPrimaryFile

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private ShardRouting corruptRandomPrimaryFile(final boolean includePerCommitFiles) throws IOException {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    Index test = state.metaData().index("test").getIndex();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[]{"test"}, false);
    List<ShardIterator> iterators = iterableAsArrayList(shardIterators);
    ShardIterator shardIterator = RandomPicks.randomFrom(random(), iterators);
    ShardRouting shardRouting = shardIterator.nextOrNull();
    assertNotNull(shardRouting);
    assertTrue(shardRouting.primary());
    assertTrue(shardRouting.assignedToNode());
    String nodeId = shardRouting.currentNodeId();
    NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
    Set<Path> files = new TreeSet<>(); // treeset makes sure iteration order is deterministic
    for (FsInfo.Path info : nodeStatses.getNodes().get(0).getFs()) {
        String path = info.getPath();
        Path file = PathUtils.get(path).resolve("indices").resolve(test.getUUID()).resolve(Integer.toString(shardRouting.getId())).resolve("index");
        if (Files.exists(file)) { // multi data path might only have one path in use
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
                for (Path item : stream) {
                    if (Files.isRegularFile(item) && "write.lock".equals(item.getFileName().toString()) == false) {
                        if (includePerCommitFiles || isPerSegmentFile(item.getFileName().toString())) {
                            files.add(item);
                        }
                    }
                }
            }
        }
    }
    pruneOldDeleteGenerations(files);
    CorruptionUtils.corruptFile(random(), files.toArray(new Path[0]));
    return shardRouting;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:33,代码来源:CorruptedFileIT.java

示例9: processShardRouting

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private void processShardRouting(Map<String, Map<String, List<Integer>>> locations, ShardRouting shardRouting) {
    String node = shardRouting.currentNodeId();
    Map<String, List<Integer>> nodeMap = locations.get(node);
    if (nodeMap == null) {
        nodeMap = new TreeMap<>();
        locations.put(shardRouting.currentNodeId(), nodeMap);
    }

    List<Integer> shards = nodeMap.get(shardRouting.getIndex());
    if (shards == null) {
        shards = new ArrayList<>();
        nodeMap.put(shardRouting.getIndex(), shards);
    }
    shards.add(shardRouting.id());
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:16,代码来源:DocTableInfo.java

示例10: buildTable

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private Table buildTable(RestRequest request, final ClusterStateResponse state, final NodesStatsResponse stats) {
    final ObjectIntScatterMap<String> allocs = new ObjectIntScatterMap<>();

    for (ShardRouting shard : state.getState().routingTable().allShards()) {
        String nodeId = "UNASSIGNED";

        if (shard.assignedToNode()) {
            nodeId = shard.currentNodeId();
        }

        allocs.addTo(nodeId, 1);
    }

    Table table = getTableWithHeader(request);

    for (NodeStats nodeStats : stats.getNodes()) {
        DiscoveryNode node = nodeStats.getNode();

        int shardCount = allocs.getOrDefault(node.getId(), 0);

        ByteSizeValue total = nodeStats.getFs().getTotal().getTotal();
        ByteSizeValue avail = nodeStats.getFs().getTotal().getAvailable();
        //if we don't know how much we use (non data nodes), it means 0
        long used = 0;
        short diskPercent = -1;
        if (total.getBytes() > 0) {
            used = total.getBytes() - avail.getBytes();
            if (used >= 0 && avail.getBytes() >= 0) {
                diskPercent = (short) (used * 100 / (used + avail.getBytes()));
            }
        }

        table.startRow();
        table.addCell(shardCount);
        table.addCell(nodeStats.getIndices().getStore().getSize());
        table.addCell(used < 0 ? null : new ByteSizeValue(used));
        table.addCell(avail.getBytes() < 0 ? null : avail);
        table.addCell(total.getBytes() < 0 ? null : total);
        table.addCell(diskPercent < 0 ? null : diskPercent);
        table.addCell(node.getHostName());
        table.addCell(node.getHostAddress());
        table.addCell(node.getName());
        table.endRow();
    }

    final String UNASSIGNED = "UNASSIGNED";
    if (allocs.containsKey(UNASSIGNED)) {
        table.startRow();
        table.addCell(allocs.get(UNASSIGNED));
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(UNASSIGNED);
        table.endRow();
    }

    return table;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:63,代码来源:RestAllocationAction.java

示例11: AsyncAction

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
protected AsyncAction(Task task, Request request, ActionListener<Response> listener) {
    this.task = task;
    this.request = request;
    this.listener = listener;

    clusterState = clusterService.state();
    nodes = clusterState.nodes();

    ClusterBlockException globalBlockException = checkGlobalBlock(clusterState, request);
    if (globalBlockException != null) {
        throw globalBlockException;
    }

    String[] concreteIndices = indexNameExpressionResolver.concreteIndexNames(clusterState, request);
    ClusterBlockException requestBlockException = checkRequestBlock(clusterState, request, concreteIndices);
    if (requestBlockException != null) {
        throw requestBlockException;
    }

    if (logger.isTraceEnabled()) {
        logger.trace("resolving shards for [{}] based on cluster state version [{}]", actionName, clusterState.version());
    }
    ShardsIterator shardIt = shards(clusterState, request, concreteIndices);
    nodeIds = new HashMap<>();

    for (ShardRouting shard : shardIt.asUnordered()) {
        // send a request to the shard only if it is assigned to a node that is in the local node's cluster state
        // a scenario in which a shard can be assigned but to a node that is not in the local node's cluster state
        // is when the shard is assigned to the master node, the local node has detected the master as failed
        // and a new master has not yet been elected; in this situation the local node will have removed the
        // master node from the local cluster state, but the shards assigned to the master will still be in the
        // routing table as such
        if (shard.assignedToNode() && nodes.get(shard.currentNodeId()) != null) {
            String nodeId = shard.currentNodeId();
            if (!nodeIds.containsKey(nodeId)) {
                nodeIds.put(nodeId, new ArrayList<>());
            }
            nodeIds.get(nodeId).add(shard);
        } else {
            unavailableShardExceptions.add(
                    new NoShardAvailableActionException(
                            shard.shardId(),
                            " no shards available for shard " + shard.toString() + " while executing " + actionName
                    )
            );
        }
    }

    responses = new AtomicReferenceArray<>(nodeIds.size());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:51,代码来源:TransportBroadcastByNodeAction.java

示例12: corruptRandomTranslogFiles

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private void corruptRandomTranslogFiles() throws IOException {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[]{"test"}, false);
    final Index test = state.metaData().index("test").getIndex();
    List<ShardIterator> iterators = iterableAsArrayList(shardIterators);
    ShardIterator shardIterator = RandomPicks.randomFrom(random(), iterators);
    ShardRouting shardRouting = shardIterator.nextOrNull();
    assertNotNull(shardRouting);
    assertTrue(shardRouting.primary());
    assertTrue(shardRouting.assignedToNode());
    String nodeId = shardRouting.currentNodeId();
    NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
    Set<Path> files = new TreeSet<>(); // treeset makes sure iteration order is deterministic
    for (FsInfo.Path fsPath : nodeStatses.getNodes().get(0).getFs()) {
        String path = fsPath.getPath();
        final String relativeDataLocationPath =  "indices/"+ test.getUUID() +"/" + Integer.toString(shardRouting.getId()) + "/translog";
        Path file = PathUtils.get(path).resolve(relativeDataLocationPath);
        if (Files.exists(file)) {
            logger.info("--> path: {}", file);
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
                for (Path item : stream) {
                    logger.info("--> File: {}", item);
                    if (Files.isRegularFile(item) && item.getFileName().toString().startsWith("translog-")) {
                        files.add(item);
                    }
                }
            }
        }
    }
    Path fileToCorrupt = null;
    if (!files.isEmpty()) {
        int corruptions = randomIntBetween(5, 20);
        for (int i = 0; i < corruptions; i++) {
            fileToCorrupt = RandomPicks.randomFrom(random(), files);
            try (FileChannel raf = FileChannel.open(fileToCorrupt, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
                // read
                raf.position(randomIntBetween(0, (int) Math.min(Integer.MAX_VALUE, raf.size() - 1)));
                long filePointer = raf.position();
                ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
                raf.read(bb);
                bb.flip();

                // corrupt
                byte oldValue = bb.get(0);
                byte newValue = (byte) (oldValue + 1);
                bb.put(0, newValue);

                // rewrite
                raf.position(filePointer);
                raf.write(bb);
                logger.info("--> corrupting file {} --  flipping at position {} from {} to {} file: {}",
                        fileToCorrupt, filePointer, Integer.toHexString(oldValue),
                        Integer.toHexString(newValue), fileToCorrupt);
            }
        }
    }
    assertThat("no file corrupted", fileToCorrupt, notNullValue());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:59,代码来源:CorruptedTranslogIT.java

示例13: testUnassignedShardsWithUnbalancedZones

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
public void testUnassignedShardsWithUnbalancedZones() {
    AllocationService strategy = createAllocationService(Settings.builder()
            .put("cluster.routing.allocation.node_concurrent_recoveries", 10)
            .put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE_SETTING.getKey(), "always")
            .put("cluster.routing.allocation.awareness.attributes", "zone")
            .build());

    logger.info("Building initial routing table for 'testUnassignedShardsWithUnbalancedZones'");

    MetaData metaData = MetaData.builder()
            .put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(4))
            .build();

    RoutingTable initialRoutingTable = RoutingTable.builder()
            .addAsNew(metaData.index("test"))
            .build();

    ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).metaData(metaData).routingTable(initialRoutingTable).build();

    logger.info("--> adding 5 nodes in different zones and do rerouting");
    clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
                    .add(newNode("A-0", singletonMap("zone", "a")))
                    .add(newNode("A-1", singletonMap("zone", "a")))
                    .add(newNode("A-2", singletonMap("zone", "a")))
                    .add(newNode("A-3", singletonMap("zone", "a")))
                    .add(newNode("A-4", singletonMap("zone", "a")))
                    .add(newNode("B-0", singletonMap("zone", "b")))
    ).build();
    clusterState = strategy.reroute(clusterState, "reroute");
    assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(0));
    assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));

    logger.info("--> start the shard (primary)");
    clusterState = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING));
    assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(1));
    assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(3));
    assertThat(clusterState.getRoutingNodes().shardsWithState(UNASSIGNED).size(), equalTo(1)); // Unassigned shard is expected.

    // Cancel all initializing shards and move started primary to another node.
    AllocationCommands commands = new AllocationCommands();
    String primaryNode = null;
    for (ShardRouting routing : clusterState.routingTable().allShards()) {
        if (routing.primary()) {
            primaryNode = routing.currentNodeId();
        } else if (routing.initializing()) {
            commands.add(new CancelAllocationCommand(routing.shardId().getIndexName(), routing.id(), routing.currentNodeId(), false));
        }
    }
    commands.add(new MoveAllocationCommand("test", 0, primaryNode, "A-4"));

    clusterState = strategy.reroute(clusterState, commands, false, false).getClusterState();

    assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(0));
    assertThat(clusterState.getRoutingNodes().shardsWithState(RELOCATING).size(), equalTo(1));
    assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(4)); // +1 for relocating shard.
    assertThat(clusterState.getRoutingNodes().shardsWithState(UNASSIGNED).size(), equalTo(1)); // Still 1 unassigned.
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:58,代码来源:AwarenessAllocationTests.java

示例14: testSerialization

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
public void testSerialization() throws Exception {
    Map<String, AliasFilter> indicesAndFilters = new HashMap<>();
    Set<DiscoveryNode> nodes = new HashSet<>();
    int numShards = randomIntBetween(1, 10);
    ClusterSearchShardsGroup[] clusterSearchShardsGroups = new ClusterSearchShardsGroup[numShards];
    for (int i = 0; i < numShards; i++) {
        String index = randomAsciiOfLengthBetween(3, 10);
        ShardId shardId = new ShardId(index, randomAsciiOfLength(12), i);
        String nodeId = randomAsciiOfLength(10);
        ShardRouting shardRouting = TestShardRouting.newShardRouting(shardId, nodeId, randomBoolean(), ShardRoutingState.STARTED);
        clusterSearchShardsGroups[i] = new ClusterSearchShardsGroup(shardId, new ShardRouting[]{shardRouting});
        DiscoveryNode node = new DiscoveryNode(shardRouting.currentNodeId(),
                new TransportAddress(TransportAddress.META_ADDRESS, randomInt(0xFFFF)), VersionUtils.randomVersion(random()));
        nodes.add(node);
        AliasFilter aliasFilter;
        if (randomBoolean()) {
            aliasFilter = new AliasFilter(RandomQueryBuilder.createQuery(random()), "alias-" + index);
        } else {
            aliasFilter = new AliasFilter(null, Strings.EMPTY_ARRAY);
        }
        indicesAndFilters.put(index, aliasFilter);
    }
    ClusterSearchShardsResponse clusterSearchShardsResponse = new ClusterSearchShardsResponse(clusterSearchShardsGroups,
            nodes.toArray(new DiscoveryNode[nodes.size()]), indicesAndFilters);

    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
    entries.addAll(searchModule.getNamedWriteables());
    NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(entries);
    Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0, Version.CURRENT);
    try(BytesStreamOutput out = new BytesStreamOutput()) {
        out.setVersion(version);
        clusterSearchShardsResponse.writeTo(out);
        try(StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), namedWriteableRegistry)) {
            in.setVersion(version);
            ClusterSearchShardsResponse deserialized = new ClusterSearchShardsResponse();
            deserialized.readFrom(in);
            assertArrayEquals(clusterSearchShardsResponse.getNodes(), deserialized.getNodes());
            assertEquals(clusterSearchShardsResponse.getGroups().length, deserialized.getGroups().length);
            for (int i = 0; i < clusterSearchShardsResponse.getGroups().length; i++) {
                ClusterSearchShardsGroup clusterSearchShardsGroup = clusterSearchShardsResponse.getGroups()[i];
                ClusterSearchShardsGroup deserializedGroup = deserialized.getGroups()[i];
                assertEquals(clusterSearchShardsGroup.getShardId(), deserializedGroup.getShardId());
                assertArrayEquals(clusterSearchShardsGroup.getShards(), deserializedGroup.getShards());
            }
            if (version.onOrAfter(Version.V_5_1_1_UNRELEASED)) {
                assertEquals(clusterSearchShardsResponse.getIndicesAndFilters(), deserialized.getIndicesAndFilters());
            } else {
                assertNull(deserialized.getIndicesAndFilters());
            }
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:54,代码来源:ClusterSearchShardsResponseTests.java

示例15: buildTable

import org.elasticsearch.cluster.routing.ShardRouting; //导入方法依赖的package包/类
private Table buildTable(RestRequest request, final ClusterStateResponse state, final NodesStatsResponse stats) {
    final ObjectIntScatterMap<String> allocs = new ObjectIntScatterMap<>();

    for (ShardRouting shard : state.getState().routingTable().allShards()) {
        String nodeId = "UNASSIGNED";

        if (shard.assignedToNode()) {
            nodeId = shard.currentNodeId();
        }

        allocs.addTo(nodeId, 1);
    }

    Table table = getTableWithHeader(request);

    for (NodeStats nodeStats : stats.getNodes()) {
        DiscoveryNode node = nodeStats.getNode();

        int shardCount = allocs.getOrDefault(node.id(), 0);

        ByteSizeValue total = nodeStats.getFs().getTotal().getTotal();
        ByteSizeValue avail = nodeStats.getFs().getTotal().getAvailable();
        //if we don't know how much we use (non data nodes), it means 0
        long used = 0;
        short diskPercent = -1;
        if (total.bytes() > 0) {
            used = total.bytes() - avail.bytes();
            if (used >= 0 && avail.bytes() >= 0) {
                diskPercent = (short) (used * 100 / (used + avail.bytes()));
            }
        }

        table.startRow();
        table.addCell(shardCount);
        table.addCell(nodeStats.getIndices().getStore().getSize());
        table.addCell(used < 0 ? null : new ByteSizeValue(used));
        table.addCell(avail.bytes() < 0 ? null : avail);
        table.addCell(total.bytes() < 0 ? null : total);
        table.addCell(diskPercent < 0 ? null : diskPercent);
        table.addCell(node.getHostName());
        table.addCell(node.getHostAddress());
        table.addCell(node.name());
        table.endRow();
    }

    final String UNASSIGNED = "UNASSIGNED";
    if (allocs.containsKey(UNASSIGNED)) {
        table.startRow();
        table.addCell(allocs.get(UNASSIGNED));
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(null);
        table.addCell(UNASSIGNED);
        table.endRow();
    }

    return table;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:63,代码来源:RestAllocationAction.java


注:本文中的org.elasticsearch.cluster.routing.ShardRouting.currentNodeId方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。