Search in sources :

Example 16 with TestGatewayAllocator

use of org.elasticsearch.test.gateway.TestGatewayAllocator in project elasticsearch by elastic.

the class TransportShrinkActionTests method testShrinkIndexSettings.

public void testShrinkIndexSettings() {
    String indexName = randomAsciiOfLength(10);
    // create one that won't fail
    ClusterState clusterState = ClusterState.builder(createClusterState(indexName, randomIntBetween(2, 10), 0, Settings.builder().put("index.blocks.write", true).build())).nodes(DiscoveryNodes.builder().add(newNode("node1"))).build();
    AllocationService service = new AllocationService(Settings.builder().build(), new AllocationDeciders(Settings.EMPTY, Collections.singleton(new MaxRetryAllocationDecider(Settings.EMPTY))), new TestGatewayAllocator(), new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE);
    RoutingTable routingTable = service.reroute(clusterState, "reroute").routingTable();
    clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
    // now we start the shard
    routingTable = service.applyStartedShards(clusterState, routingTable.index(indexName).shardsWithState(ShardRoutingState.INITIALIZING)).routingTable();
    clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
    int numSourceShards = clusterState.metaData().index(indexName).getNumberOfShards();
    DocsStats stats = new DocsStats(randomIntBetween(0, (IndexWriter.MAX_DOCS) / numSourceShards), randomIntBetween(1, 1000));
    ShrinkRequest target = new ShrinkRequest("target", indexName);
    final ActiveShardCount activeShardCount = randomBoolean() ? ActiveShardCount.ALL : ActiveShardCount.ONE;
    target.setWaitForActiveShards(activeShardCount);
    CreateIndexClusterStateUpdateRequest request = TransportShrinkAction.prepareCreateIndexRequest(target, clusterState, (i) -> stats, new IndexNameExpressionResolver(Settings.EMPTY));
    assertNotNull(request.shrinkFrom());
    assertEquals(indexName, request.shrinkFrom().getName());
    assertEquals("1", request.settings().get("index.number_of_shards"));
    assertEquals("shrink_index", request.cause());
    assertEquals(request.waitForActiveShards(), activeShardCount);
}
Also used : TestGatewayAllocator(org.elasticsearch.test.gateway.TestGatewayAllocator) ClusterState(org.elasticsearch.cluster.ClusterState) BalancedShardsAllocator(org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator) AllocationDeciders(org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders) MaxRetryAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) CreateIndexClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) DocsStats(org.elasticsearch.index.shard.DocsStats) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService)

Example 17 with TestGatewayAllocator

use of org.elasticsearch.test.gateway.TestGatewayAllocator in project elasticsearch by elastic.

the class ClusterAllocationExplainActionTests method testInitializingOrRelocatingShardExplanation.

public void testInitializingOrRelocatingShardExplanation() throws Exception {
    ShardRoutingState shardRoutingState = randomFrom(ShardRoutingState.INITIALIZING, ShardRoutingState.RELOCATING);
    ClusterState clusterState = ClusterStateCreationUtils.state("idx", randomBoolean(), shardRoutingState);
    ShardRouting shard = clusterState.getRoutingTable().index("idx").shard(0).primaryShard();
    RoutingAllocation allocation = new RoutingAllocation(new AllocationDeciders(Settings.EMPTY, Collections.emptyList()), clusterState.getRoutingNodes(), clusterState, null, System.nanoTime(), randomBoolean());
    ClusterAllocationExplanation cae = TransportClusterAllocationExplainAction.explainShard(shard, allocation, null, randomBoolean(), new TestGatewayAllocator(), new ShardsAllocator() {

        @Override
        public void allocate(RoutingAllocation allocation) {
        // no-op
        }

        @Override
        public ShardAllocationDecision decideShardAllocation(ShardRouting shard, RoutingAllocation allocation) {
            if (shard.initializing() || shard.relocating()) {
                return ShardAllocationDecision.NOT_TAKEN;
            } else {
                throw new UnsupportedOperationException("cannot explain");
            }
        }
    });
    assertEquals(shard.currentNodeId(), cae.getCurrentNode().getId());
    assertFalse(cae.getShardAllocationDecision().isDecisionTaken());
    assertFalse(cae.getShardAllocationDecision().getAllocateDecision().isDecisionTaken());
    assertFalse(cae.getShardAllocationDecision().getMoveDecision().isDecisionTaken());
    XContentBuilder builder = XContentFactory.jsonBuilder();
    cae.toXContent(builder, ToXContent.EMPTY_PARAMS);
    String explanation;
    if (shardRoutingState == ShardRoutingState.RELOCATING) {
        explanation = "the shard is in the process of relocating from node [] to node [], wait until " + "relocation has completed";
    } else {
        explanation = "the shard is in the process of initializing on node [], " + "wait until initialization has completed";
    }
    assertEquals("{\"index\":\"idx\",\"shard\":0,\"primary\":true,\"current_state\":\"" + shardRoutingState.toString().toLowerCase(Locale.ROOT) + "\",\"current_node\":" + "{\"id\":\"" + cae.getCurrentNode().getId() + "\",\"name\":\"" + cae.getCurrentNode().getName() + "\",\"transport_address\":\"" + cae.getCurrentNode().getAddress() + "\"},\"explanation\":\"" + explanation + "\"}", builder.string());
}
Also used : TestGatewayAllocator(org.elasticsearch.test.gateway.TestGatewayAllocator) ClusterState(org.elasticsearch.cluster.ClusterState) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) AllocationDeciders(org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders) ShardsAllocator(org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) RoutingAllocation(org.elasticsearch.cluster.routing.allocation.RoutingAllocation) ShardAllocationDecision(org.elasticsearch.cluster.routing.allocation.ShardAllocationDecision) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 18 with TestGatewayAllocator

use of org.elasticsearch.test.gateway.TestGatewayAllocator in project elasticsearch by elastic.

the class ClusterStateHealthTests method testClusterHealthWaitsForClusterStateApplication.

public void testClusterHealthWaitsForClusterStateApplication() throws InterruptedException, ExecutionException {
    final CountDownLatch applyLatch = new CountDownLatch(1);
    final CountDownLatch listenerCalled = new CountDownLatch(1);
    setState(clusterService, ClusterState.builder(clusterService.state()).nodes(DiscoveryNodes.builder(clusterService.state().nodes()).masterNodeId(null)).build());
    clusterService.addStateApplier(event -> {
        listenerCalled.countDown();
        try {
            applyLatch.await();
        } catch (InterruptedException e) {
            logger.debug("interrupted", e);
        }
    });
    logger.info("--> submit task to restore master");
    clusterService.submitStateUpdateTask("restore master", new LocalClusterUpdateTask() {

        @Override
        public ClusterTasksResult<LocalClusterUpdateTask> execute(ClusterState currentState) throws Exception {
            return newState(ClusterState.builder(currentState).nodes(DiscoveryNodes.builder(currentState.nodes()).masterNodeId(currentState.nodes().getLocalNodeId())).build());
        }

        @Override
        public void onFailure(String source, Exception e) {
            logger.warn("unexpected failure", e);
        }
    });
    logger.info("--> waiting for listener to be called and cluster state being blocked");
    listenerCalled.await();
    TransportClusterHealthAction action = new TransportClusterHealthAction(Settings.EMPTY, transportService, clusterService, threadPool, new ActionFilters(new HashSet<>()), indexNameExpressionResolver, new TestGatewayAllocator());
    PlainActionFuture<ClusterHealthResponse> listener = new PlainActionFuture<>();
    action.execute(new ClusterHealthRequest().waitForGreenStatus(), listener);
    assertFalse(listener.isDone());
    logger.info("--> realising task to restore master");
    applyLatch.countDown();
    listener.get();
}
Also used : TestGatewayAllocator(org.elasticsearch.test.gateway.TestGatewayAllocator) ClusterState(org.elasticsearch.cluster.ClusterState) LocalClusterUpdateTask(org.elasticsearch.cluster.LocalClusterUpdateTask) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ActionFilters(org.elasticsearch.action.support.ActionFilters) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) TransportClusterHealthAction(org.elasticsearch.action.admin.cluster.health.TransportClusterHealthAction) HashSet(java.util.HashSet)

Example 19 with TestGatewayAllocator

use of org.elasticsearch.test.gateway.TestGatewayAllocator in project elasticsearch by elastic.

the class MetaDataCreateIndexServiceTests method testValidateShrinkIndex.

public void testValidateShrinkIndex() {
    int numShards = randomIntBetween(2, 42);
    ClusterState state = createClusterState("source", numShards, randomIntBetween(0, 10), Settings.builder().put("index.blocks.write", true).build());
    assertEquals("index [source] already exists", expectThrows(ResourceAlreadyExistsException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(state, "target", Collections.emptySet(), "source", Settings.EMPTY)).getMessage());
    assertEquals("no such index", expectThrows(IndexNotFoundException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(state, "no such index", Collections.emptySet(), "target", Settings.EMPTY)).getMessage());
    assertEquals("can't shrink an index with only one shard", expectThrows(IllegalArgumentException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(createClusterState("source", 1, 0, Settings.builder().put("index.blocks.write", true).build()), "source", Collections.emptySet(), "target", Settings.EMPTY)).getMessage());
    assertEquals("the number of target shards must be less that the number of source shards", expectThrows(IllegalArgumentException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(createClusterState("source", 5, 0, Settings.builder().put("index.blocks.write", true).build()), "source", Collections.emptySet(), "target", Settings.builder().put("index.number_of_shards", 10).build())).getMessage());
    assertEquals("index source must be read-only to shrink index. use \"index.blocks.write=true\"", expectThrows(IllegalStateException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(createClusterState("source", randomIntBetween(2, 100), randomIntBetween(0, 10), Settings.EMPTY), "source", Collections.emptySet(), "target", Settings.EMPTY)).getMessage());
    assertEquals("index source must have all shards allocated on the same node to shrink index", expectThrows(IllegalStateException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(state, "source", Collections.emptySet(), "target", Settings.EMPTY)).getMessage());
    assertEquals("the number of source shards [8] must be a must be a multiple of [3]", expectThrows(IllegalArgumentException.class, () -> MetaDataCreateIndexService.validateShrinkIndex(createClusterState("source", 8, randomIntBetween(0, 10), Settings.builder().put("index.blocks.write", true).build()), "source", Collections.emptySet(), "target", Settings.builder().put("index.number_of_shards", 3).build())).getMessage());
    assertEquals("mappings are not allowed when shrinking indices, all mappings are copied from the source index", expectThrows(IllegalArgumentException.class, () -> {
        MetaDataCreateIndexService.validateShrinkIndex(state, "source", Collections.singleton("foo"), "target", Settings.EMPTY);
    }).getMessage());
    // create one that won't fail
    ClusterState clusterState = ClusterState.builder(createClusterState("source", numShards, 0, Settings.builder().put("index.blocks.write", true).build())).nodes(DiscoveryNodes.builder().add(newNode("node1"))).build();
    AllocationService service = new AllocationService(Settings.builder().build(), new AllocationDeciders(Settings.EMPTY, Collections.singleton(new MaxRetryAllocationDecider(Settings.EMPTY))), new TestGatewayAllocator(), new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE);
    RoutingTable routingTable = service.reroute(clusterState, "reroute").routingTable();
    clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
    // now we start the shard
    routingTable = service.applyStartedShards(clusterState, routingTable.index("source").shardsWithState(ShardRoutingState.INITIALIZING)).routingTable();
    clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
    int targetShards;
    do {
        targetShards = randomIntBetween(1, numShards / 2);
    } while (isShrinkable(numShards, targetShards) == false);
    MetaDataCreateIndexService.validateShrinkIndex(clusterState, "source", Collections.emptySet(), "target", Settings.builder().put("index.number_of_shards", targetShards).build());
}
Also used : TestGatewayAllocator(org.elasticsearch.test.gateway.TestGatewayAllocator) ClusterState(org.elasticsearch.cluster.ClusterState) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) BalancedShardsAllocator(org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator) AllocationDeciders(org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders) MaxRetryAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService)

Example 20 with TestGatewayAllocator

use of org.elasticsearch.test.gateway.TestGatewayAllocator in project elasticsearch by elastic.

the class NodeVersionAllocationDeciderTests method testRestoreDoesNotAllocateSnapshotOnOlderNodes.

public void testRestoreDoesNotAllocateSnapshotOnOlderNodes() {
    final DiscoveryNode newNode = new DiscoveryNode("newNode", buildNewFakeTransportAddress(), emptyMap(), MASTER_DATA_ROLES, Version.CURRENT);
    final DiscoveryNode oldNode1 = new DiscoveryNode("oldNode1", buildNewFakeTransportAddress(), emptyMap(), MASTER_DATA_ROLES, VersionUtils.getPreviousVersion());
    final DiscoveryNode oldNode2 = new DiscoveryNode("oldNode2", buildNewFakeTransportAddress(), emptyMap(), MASTER_DATA_ROLES, VersionUtils.getPreviousVersion());
    int numberOfShards = randomIntBetween(1, 3);
    final IndexMetaData.Builder indexMetaData = IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numberOfShards).numberOfReplicas(randomIntBetween(0, 3));
    for (int i = 0; i < numberOfShards; i++) {
        indexMetaData.putInSyncAllocationIds(i, Collections.singleton("_test_"));
    }
    MetaData metaData = MetaData.builder().put(indexMetaData).build();
    ClusterState state = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).metaData(metaData).routingTable(RoutingTable.builder().addAsRestore(metaData.index("test"), new SnapshotRecoverySource(new Snapshot("rep1", new SnapshotId("snp1", UUIDs.randomBase64UUID())), Version.CURRENT, "test")).build()).nodes(DiscoveryNodes.builder().add(newNode).add(oldNode1).add(oldNode2)).build();
    AllocationDeciders allocationDeciders = new AllocationDeciders(Settings.EMPTY, Arrays.asList(new ReplicaAfterPrimaryActiveAllocationDecider(Settings.EMPTY), new NodeVersionAllocationDecider(Settings.EMPTY)));
    AllocationService strategy = new MockAllocationService(Settings.EMPTY, allocationDeciders, new TestGatewayAllocator(), new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE);
    state = strategy.reroute(state, new AllocationCommands(), true, false).getClusterState();
    // Make sure that primary shards are only allocated on the new node
    for (int i = 0; i < numberOfShards; i++) {
        assertEquals("newNode", state.routingTable().index("test").getShards().get(i).primaryShard().currentNodeId());
    }
}
Also used : TestGatewayAllocator(org.elasticsearch.test.gateway.TestGatewayAllocator) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) BalancedShardsAllocator(org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator) AllocationDeciders(org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders) ReplicaAfterPrimaryActiveAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.ReplicaAfterPrimaryActiveAllocationDecider) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) AllocationCommands(org.elasticsearch.cluster.routing.allocation.command.AllocationCommands) Snapshot(org.elasticsearch.snapshots.Snapshot) SnapshotId(org.elasticsearch.snapshots.SnapshotId) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) NodeVersionAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.NodeVersionAllocationDecider)

Aggregations

ClusterState (org.elasticsearch.cluster.ClusterState)25 TestGatewayAllocator (org.elasticsearch.test.gateway.TestGatewayAllocator)25 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)18 MetaData (org.elasticsearch.cluster.metadata.MetaData)18 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)18 BalancedShardsAllocator (org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator)17 AllocationService (org.elasticsearch.cluster.routing.allocation.AllocationService)12 Settings (org.elasticsearch.common.settings.Settings)11 AllocationDeciders (org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders)10 ClusterSettings (org.elasticsearch.common.settings.ClusterSettings)10 IndexRoutingTable (org.elasticsearch.cluster.routing.IndexRoutingTable)8 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)8 ClusterInfo (org.elasticsearch.cluster.ClusterInfo)7 ClusterInfoService (org.elasticsearch.cluster.ClusterInfoService)7 DiskUsage (org.elasticsearch.cluster.DiskUsage)7 DevNullClusterInfo (org.elasticsearch.cluster.MockInternalClusterInfoService.DevNullClusterInfo)7 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)7 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)7 DiskThresholdSettings (org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings)7 ImmutableOpenMap (org.elasticsearch.common.collect.ImmutableOpenMap)7