Search in sources :

Example 6 with ClusterBlockException

use of org.elasticsearch.cluster.block.ClusterBlockException in project elasticsearch by elastic.

the class TransportInstanceSingleOperationActionTests method testGlobalBlock.

public void testGlobalBlock() {
    Request request = new Request();
    PlainActionFuture<Response> listener = new PlainActionFuture<>();
    ClusterBlocks.Builder block = ClusterBlocks.builder().addGlobalBlock(new ClusterBlock(1, "", false, true, RestStatus.SERVICE_UNAVAILABLE, ClusterBlockLevel.ALL));
    setState(clusterService, ClusterState.builder(clusterService.state()).blocks(block));
    try {
        action.new AsyncSingleAction(request, listener).start();
        listener.get();
        fail("expected ClusterBlockException");
    } catch (Exception e) {
        if (ExceptionsHelper.unwrap(e, ClusterBlockException.class) == null) {
            logger.info("expected ClusterBlockException  but got ", e);
            fail("expected ClusterBlockException");
        }
    }
}
Also used : ActionResponse(org.elasticsearch.action.ActionResponse) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) IndicesRequest(org.elasticsearch.action.IndicesRequest) TimeoutException(java.util.concurrent.TimeoutException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) ExecutionException(java.util.concurrent.ExecutionException) TransportException(org.elasticsearch.transport.TransportException)

Example 7 with ClusterBlockException

use of org.elasticsearch.cluster.block.ClusterBlockException in project elasticsearch by elastic.

the class TransportMasterNodeActionTests method testLocalOperationWithBlocks.

public void testLocalOperationWithBlocks() throws ExecutionException, InterruptedException {
    final boolean retryableBlock = randomBoolean();
    final boolean unblockBeforeTimeout = randomBoolean();
    Request request = new Request().masterNodeTimeout(TimeValue.timeValueSeconds(unblockBeforeTimeout ? 60 : 0));
    PlainActionFuture<Response> listener = new PlainActionFuture<>();
    ClusterBlock block = new ClusterBlock(1, "", retryableBlock, true, randomFrom(RestStatus.values()), ClusterBlockLevel.ALL);
    ClusterState stateWithBlock = ClusterState.builder(ClusterStateCreationUtils.state(localNode, localNode, allNodes)).blocks(ClusterBlocks.builder().addGlobalBlock(block)).build();
    setState(clusterService, stateWithBlock);
    new Action(Settings.EMPTY, "testAction", transportService, clusterService, threadPool) {

        @Override
        protected ClusterBlockException checkBlock(Request request, ClusterState state) {
            Set<ClusterBlock> blocks = state.blocks().global();
            return blocks.isEmpty() ? null : new ClusterBlockException(blocks);
        }
    }.execute(request, listener);
    if (retryableBlock && unblockBeforeTimeout) {
        assertFalse(listener.isDone());
        setState(clusterService, ClusterState.builder(ClusterStateCreationUtils.state(localNode, localNode, allNodes)).blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).build());
        assertTrue(listener.isDone());
        listener.get();
        return;
    }
    assertTrue(listener.isDone());
    if (retryableBlock) {
        try {
            listener.get();
            fail("Expected exception but returned proper result");
        } catch (ExecutionException ex) {
            assertThat(ex.getCause(), instanceOf(MasterNotDiscoveredException.class));
            assertThat(ex.getCause().getCause(), instanceOf(ClusterBlockException.class));
        }
    } else {
        assertListenerThrows("ClusterBlockException should be thrown", listener, ClusterBlockException.class);
    }
}
Also used : ActionResponse(org.elasticsearch.action.ActionResponse) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) ClusterState(org.elasticsearch.cluster.ClusterState) HashSet(java.util.HashSet) Set(java.util.Set) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ExecutionException(java.util.concurrent.ExecutionException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException)

Example 8 with ClusterBlockException

use of org.elasticsearch.cluster.block.ClusterBlockException in project elasticsearch by elastic.

the class InternalClusterInfoService method refresh.

/**
     * Refreshes the ClusterInfo in a blocking fashion
     */
public final ClusterInfo refresh() {
    if (logger.isTraceEnabled()) {
        logger.trace("Performing ClusterInfoUpdateJob");
    }
    final CountDownLatch nodeLatch = updateNodeStats(new ActionListener<NodesStatsResponse>() {

        @Override
        public void onResponse(NodesStatsResponse nodeStatses) {
            ImmutableOpenMap.Builder<String, DiskUsage> newLeastAvaiableUsages = ImmutableOpenMap.builder();
            ImmutableOpenMap.Builder<String, DiskUsage> newMostAvaiableUsages = ImmutableOpenMap.builder();
            fillDiskUsagePerNode(logger, nodeStatses.getNodes(), newLeastAvaiableUsages, newMostAvaiableUsages);
            leastAvailableSpaceUsages = newLeastAvaiableUsages.build();
            mostAvailableSpaceUsages = newMostAvaiableUsages.build();
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof ReceiveTimeoutTransportException) {
                logger.error("NodeStatsAction timed out for ClusterInfoUpdateJob", e);
            } else {
                if (e instanceof ClusterBlockException) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Failed to execute NodeStatsAction for ClusterInfoUpdateJob", e);
                    }
                } else {
                    logger.warn("Failed to execute NodeStatsAction for ClusterInfoUpdateJob", e);
                }
                // we empty the usages list, to be safe - we don't know what's going on.
                leastAvailableSpaceUsages = ImmutableOpenMap.of();
                mostAvailableSpaceUsages = ImmutableOpenMap.of();
            }
        }
    });
    final CountDownLatch indicesLatch = updateIndicesStats(new ActionListener<IndicesStatsResponse>() {

        @Override
        public void onResponse(IndicesStatsResponse indicesStatsResponse) {
            ShardStats[] stats = indicesStatsResponse.getShards();
            ImmutableOpenMap.Builder<String, Long> newShardSizes = ImmutableOpenMap.builder();
            ImmutableOpenMap.Builder<ShardRouting, String> newShardRoutingToDataPath = ImmutableOpenMap.builder();
            buildShardLevelInfo(logger, stats, newShardSizes, newShardRoutingToDataPath, clusterService.state());
            shardSizes = newShardSizes.build();
            shardRoutingToDataPath = newShardRoutingToDataPath.build();
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof ReceiveTimeoutTransportException) {
                logger.error("IndicesStatsAction timed out for ClusterInfoUpdateJob", e);
            } else {
                if (e instanceof ClusterBlockException) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Failed to execute IndicesStatsAction for ClusterInfoUpdateJob", e);
                    }
                } else {
                    logger.warn("Failed to execute IndicesStatsAction for ClusterInfoUpdateJob", e);
                }
                // we empty the usages list, to be safe - we don't know what's going on.
                shardSizes = ImmutableOpenMap.of();
                shardRoutingToDataPath = ImmutableOpenMap.of();
            }
        }
    });
    try {
        nodeLatch.await(fetchTimeout.getMillis(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // restore interrupt status
        Thread.currentThread().interrupt();
        logger.warn("Failed to update node information for ClusterInfoUpdateJob within {} timeout", fetchTimeout);
    }
    try {
        indicesLatch.await(fetchTimeout.getMillis(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // restore interrupt status
        Thread.currentThread().interrupt();
        logger.warn("Failed to update shard information for ClusterInfoUpdateJob within {} timeout", fetchTimeout);
    }
    ClusterInfo clusterInfo = getClusterInfo();
    for (Listener l : listeners) {
        try {
            l.onNewInfo(clusterInfo);
        } catch (Exception e) {
            logger.info("Failed executing ClusterInfoService listener", e);
        }
    }
    return clusterInfo;
}
Also used : IndicesStatsResponse(org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse) LatchedActionListener(org.elasticsearch.action.LatchedActionListener) ActionListener(org.elasticsearch.action.ActionListener) CountDownLatch(java.util.concurrent.CountDownLatch) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) NodesStatsResponse(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException)

Example 9 with ClusterBlockException

use of org.elasticsearch.cluster.block.ClusterBlockException in project elasticsearch by elastic.

the class ElasticsearchExceptionTests method testToXContentWithHeadersAndMetadata.

public void testToXContentWithHeadersAndMetadata() throws IOException {
    ElasticsearchException e = new ElasticsearchException("foo", new ElasticsearchException("bar", new ElasticsearchException("baz", new ClusterBlockException(singleton(DiscoverySettings.NO_MASTER_BLOCK_WRITES)))));
    e.addHeader("foo_0", "0");
    e.addHeader("foo_1", "1");
    e.addMetadata("es.metadata_foo_0", "foo_0");
    e.addMetadata("es.metadata_foo_1", "foo_1");
    final String expectedJson = "{" + "\"type\":\"exception\"," + "\"reason\":\"foo\"," + "\"metadata_foo_0\":\"foo_0\"," + "\"metadata_foo_1\":\"foo_1\"," + "\"caused_by\":{" + "\"type\":\"exception\"," + "\"reason\":\"bar\"," + "\"caused_by\":{" + "\"type\":\"exception\"," + "\"reason\":\"baz\"," + "\"caused_by\":{" + "\"type\":\"cluster_block_exception\"," + "\"reason\":\"blocked by: [SERVICE_UNAVAILABLE/2/no master];\"" + "}" + "}" + "}," + "\"header\":{" + "\"foo_0\":\"0\"," + "\"foo_1\":\"1\"" + "}" + "}";
    assertExceptionAsJson(e, expectedJson);
    ElasticsearchException parsed;
    try (XContentParser parser = createParser(XContentType.JSON.xContent(), expectedJson)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "Elasticsearch exception [type=exception, reason=foo]");
    assertThat(parsed.getHeaderKeys(), hasSize(2));
    assertEquals(parsed.getHeader("foo_0").get(0), "0");
    assertEquals(parsed.getHeader("foo_1").get(0), "1");
    assertThat(parsed.getMetadataKeys(), hasSize(2));
    assertEquals(parsed.getMetadata("es.metadata_foo_0").get(0), "foo_0");
    assertEquals(parsed.getMetadata("es.metadata_foo_1").get(0), "foo_1");
    ElasticsearchException cause = (ElasticsearchException) parsed.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=bar]");
    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=baz]");
    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=cluster_block_exception, reason=blocked by: [SERVICE_UNAVAILABLE/2/no master];]");
}
Also used : ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 10 with ClusterBlockException

use of org.elasticsearch.cluster.block.ClusterBlockException in project elasticsearch by elastic.

the class NoMasterNodeIT method testNoMasterActionsWriteMasterBlock.

public void testNoMasterActionsWriteMasterBlock() throws Exception {
    Settings settings = Settings.builder().put("discovery.type", "zen").put("action.auto_create_index", false).put("discovery.zen.minimum_master_nodes", 2).put(ZenDiscovery.PING_TIMEOUT_SETTING.getKey(), "200ms").put("discovery.initial_state_timeout", "500ms").put(DiscoverySettings.NO_MASTER_BLOCK_SETTING.getKey(), "write").build();
    internalCluster().startNode(settings);
    // start a second node, create an index, and then shut it down so we have no master block
    internalCluster().startNode(settings);
    prepareCreate("test1").setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).get();
    prepareCreate("test2").setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 2, IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).get();
    client().admin().cluster().prepareHealth("_all").setWaitForGreenStatus().get();
    client().prepareIndex("test1", "type1", "1").setSource("field", "value1").get();
    client().prepareIndex("test2", "type1", "1").setSource("field", "value1").get();
    refresh();
    ensureSearchable("test1", "test2");
    ClusterStateResponse clusterState = client().admin().cluster().prepareState().get();
    logger.info("Cluster state:\n{}", clusterState.getState());
    internalCluster().stopRandomDataNode();
    assertTrue(awaitBusy(() -> {
        ClusterState state = client().admin().cluster().prepareState().setLocal(true).get().getState();
        return state.blocks().hasGlobalBlock(DiscoverySettings.NO_MASTER_BLOCK_ID);
    }));
    GetResponse getResponse = client().prepareGet("test1", "type1", "1").get();
    assertExists(getResponse);
    SearchResponse countResponse = client().prepareSearch("test1").setSize(0).get();
    assertHitCount(countResponse, 1L);
    SearchResponse searchResponse = client().prepareSearch("test1").get();
    assertHitCount(searchResponse, 1L);
    countResponse = client().prepareSearch("test2").setSize(0).get();
    assertThat(countResponse.getTotalShards(), equalTo(2));
    assertThat(countResponse.getSuccessfulShards(), equalTo(1));
    TimeValue timeout = TimeValue.timeValueMillis(200);
    long now = System.currentTimeMillis();
    try {
        client().prepareUpdate("test1", "type1", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "value2").setTimeout(timeout).get();
        fail("Expected ClusterBlockException");
    } catch (ClusterBlockException e) {
        assertThat(System.currentTimeMillis() - now, greaterThan(timeout.millis() - 50));
        assertThat(e.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
    }
    now = System.currentTimeMillis();
    try {
        client().prepareIndex("test1", "type1", "1").setSource(XContentFactory.jsonBuilder().startObject().endObject()).setTimeout(timeout).get();
        fail("Expected ClusterBlockException");
    } catch (ClusterBlockException e) {
        assertThat(System.currentTimeMillis() - now, greaterThan(timeout.millis() - 50));
        assertThat(e.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
    }
    internalCluster().startNode(settings);
    client().admin().cluster().prepareHealth().setWaitForGreenStatus().setWaitForNodes("2").get();
}
Also used : ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) GetResponse(org.elasticsearch.action.get.GetResponse) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) Settings(org.elasticsearch.common.settings.Settings) DiscoverySettings(org.elasticsearch.discovery.DiscoverySettings) TimeValue(org.elasticsearch.common.unit.TimeValue) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Aggregations

ClusterBlockException (org.elasticsearch.cluster.block.ClusterBlockException)18 PlainActionFuture (org.elasticsearch.action.support.PlainActionFuture)4 ClusterBlock (org.elasticsearch.cluster.block.ClusterBlock)4 IndicesRequest (org.elasticsearch.action.IndicesRequest)3 ClusterBlocks (org.elasticsearch.cluster.block.ClusterBlocks)3 Settings (org.elasticsearch.common.settings.Settings)3 DiscoverySettings (org.elasticsearch.discovery.DiscoverySettings)3 IOException (java.io.IOException)2 ExecutionException (java.util.concurrent.ExecutionException)2 ActionResponse (org.elasticsearch.action.ActionResponse)2 CreateIndexResponse (org.elasticsearch.action.admin.indices.create.CreateIndexResponse)2 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)2 BroadcastRequest (org.elasticsearch.action.support.broadcast.BroadcastRequest)2 BroadcastResponse (org.elasticsearch.action.support.broadcast.BroadcastResponse)2 Releasable (org.elasticsearch.common.lease.Releasable)2 TransportResponse (org.elasticsearch.transport.TransportResponse)2 FeedException (com.rometools.rome.io.FeedException)1 MalformedURLException (java.net.MalformedURLException)1 ArrayList (java.util.ArrayList)1 Collections.emptyList (java.util.Collections.emptyList)1