summaryrefslogtreecommitdiff
path: root/core/src/test/java/org/elasticsearch/index/TransportIndexFailuresIT.java
blob: 9dfeb4438adce1300e7c65a60fee3d9a91447442 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.elasticsearch.index;

import org.elasticsearch.action.index.IndexAction;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.discovery.zen.fd.FaultDetection;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.TransportService;

import java.util.Collection;
import java.util.List;

import static java.util.Collections.singleton;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED;
import static org.elasticsearch.cluster.routing.ShardRoutingState.UNASSIGNED;
import static org.hamcrest.Matchers.equalTo;

/**
 * Test failure when index replication actions fail mid-flight
 */
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0, transportClientRatio = 0)
@ESIntegTestCase.SuppressLocalMode
public class TransportIndexFailuresIT extends ESIntegTestCase {

    private static final Settings nodeSettings = Settings.settingsBuilder()
            .put("discovery.type", "zen") // <-- To override the local setting if set externally
            .put(FaultDetection.PING_TIMEOUT_SETTING.getKey(), "1s") // <-- for hitting simulated network failures quickly
            .put(FaultDetection.PING_RETRIES_SETTING.getKey(), "1") // <-- for hitting simulated network failures quickly
            .put(DiscoverySettings.PUBLISH_TIMEOUT_SETTING.getKey(), "1s") // <-- for hitting simulated network failures quickly
            .put("discovery.zen.minimum_master_nodes", 1)
            .build();

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return pluginList(MockTransportService.TestPlugin.class);
    }

    @Override
    protected int numberOfShards() {
        return 1;
    }

    @Override
    protected int numberOfReplicas() {
        return 1;
    }

    public void testNetworkPartitionDuringReplicaIndexOp() throws Exception {
        final String INDEX = "testidx";

        List<String> nodes = internalCluster().startNodesAsync(2, nodeSettings).get();

        // Create index test with 1 shard, 1 replica and ensure it is green
        createIndex(INDEX);
        ensureGreen(INDEX);

        // Disable allocation so the replica cannot be reallocated when it fails
        Settings s = Settings.builder().put("cluster.routing.allocation.enable", "none").build();
        client().admin().cluster().prepareUpdateSettings().setTransientSettings(s).get();

        // Determine which node holds the primary shard
        ClusterState state = getNodeClusterState(nodes.get(0));
        IndexShardRoutingTable shard = state.getRoutingTable().index(INDEX).shard(0);
        String primaryNode;
        String replicaNode;
        if (shard.getShards().get(0).primary()) {
            primaryNode = nodes.get(0);
            replicaNode = nodes.get(1);
        } else {
            primaryNode = nodes.get(1);
            replicaNode = nodes.get(0);
        }
        logger.info("--> primary shard is on {}", primaryNode);

        // Index a document to make sure everything works well
        IndexResponse resp = internalCluster().client(primaryNode).prepareIndex(INDEX, "doc").setSource("foo", "bar").get();
        assertThat("document exists on primary node",
                internalCluster().client(primaryNode).prepareGet(INDEX, "doc", resp.getId()).setPreference("_only_local").get().isExists(),
                equalTo(true));
        assertThat("document exists on replica node",
                internalCluster().client(replicaNode).prepareGet(INDEX, "doc", resp.getId()).setPreference("_only_local").get().isExists(),
                equalTo(true));

        // Disrupt the network so indexing requests fail to replicate
        logger.info("--> preventing index/replica operations");
        TransportService mockTransportService = internalCluster().getInstance(TransportService.class, primaryNode);
        ((MockTransportService) mockTransportService).addFailToSendNoConnectRule(
                internalCluster().getInstance(TransportService.class, replicaNode),
                singleton(IndexAction.NAME + "[r]")
        );
        mockTransportService = internalCluster().getInstance(TransportService.class, replicaNode);
        ((MockTransportService) mockTransportService).addFailToSendNoConnectRule(
                internalCluster().getInstance(TransportService.class, primaryNode),
                singleton(IndexAction.NAME + "[r]")
        );

        logger.info("--> indexing into primary");
        // the replica shard should now be marked as failed because the replication operation will fail
        resp = internalCluster().client(primaryNode).prepareIndex(INDEX, "doc").setSource("foo", "baz").get();
        // wait until the cluster reaches an exact yellow state, meaning replica has failed
        assertBusy(new Runnable() {
            @Override
            public void run() {
                assertThat(client().admin().cluster().prepareHealth().get().getStatus(), equalTo(ClusterHealthStatus.YELLOW));
            }
        });
        assertThat("document should still be indexed and available",
                client().prepareGet(INDEX, "doc", resp.getId()).get().isExists(), equalTo(true));

        state = getNodeClusterState(randomFrom(nodes.toArray(Strings.EMPTY_ARRAY)));
        RoutingNodes rn = state.getRoutingNodes();
        logger.info("--> counts: total: {}, unassigned: {}, initializing: {}, relocating: {}, started: {}",
                rn.shards(input -> true).size(),
                rn.shardsWithState(UNASSIGNED).size(),
                rn.shardsWithState(INITIALIZING).size(),
                rn.shardsWithState(RELOCATING).size(),
                rn.shardsWithState(STARTED).size());
        logger.info("--> unassigned: {}, initializing: {}, relocating: {}, started: {}",
                rn.shardsWithState(UNASSIGNED),
                rn.shardsWithState(INITIALIZING),
                rn.shardsWithState(RELOCATING),
                rn.shardsWithState(STARTED));

        assertThat("only a single shard is now active (replica should be failed and not reallocated)",
                rn.shardsWithState(STARTED).size(), equalTo(1));
    }

    private ClusterState getNodeClusterState(String node) {
        return internalCluster().client(node).admin().cluster().prepareState().setLocal(true).get().getState();
    }
}