Skip to content

log messages from allocation commands #25955

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Aug 22, 2017
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,18 @@ protected ClusterRerouteResponse newResponse() {

@Override
protected void masterOperation(final ClusterRerouteRequest request, final ClusterState state, final ActionListener<ClusterRerouteResponse> listener) {
ActionListener<ClusterRerouteResponse> logWrapper = ActionListener.wrap(
response -> {
if (request.dryRun() == false) {
response.getExplanations().getYesDecisionMessages().forEach(logger::info);
}
listener.onResponse(response);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this go into a finally block in case an exception is thrown in getMessages?

Copy link
Contributor Author

@andyb-elastic andyb-elastic Aug 2, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good to me. If that were to happen without finally, would an error response with the exception be returned somewhere "upstream", or would the request handling just time out?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I presume that the error would be logged and the connection would hang until the client timed out (just a guess)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ActionListener#wrap protects against this:

    static <Response> ActionListener<Response> wrap(CheckedConsumer<Response, ? extends Exception> onResponse,
            Consumer<Exception> onFailure) {
        return new ActionListener<Response>() {
            @Override
            public void onResponse(Response response) {
                try {
                    onResponse.accept(response);
                } catch (Exception e) {
                    onFailure(e);
                }
            }

            @Override
            public void onFailure(Exception e) {
                onFailure.accept(e);
            }
        };
    }

},
listener::onFailure
);

clusterService.submitStateUpdateTask("cluster_reroute (api)", new ClusterRerouteResponseAckedClusterStateUpdateTask(logger,
allocationService, request, listener));
allocationService, request, logWrapper));
}

static class ClusterRerouteResponseAckedClusterStateUpdateTask extends AckedClusterStateUpdateTask<ClusterRerouteResponse> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.elasticsearch.cluster.routing.allocation;

import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent.Params;
Expand All @@ -28,6 +29,8 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* Class used to encapsulate a number of {@link RerouteExplanation}
Expand All @@ -49,6 +52,18 @@ public List<RerouteExplanation> explanations() {
return this.explanations;
}

/**
* Provides feedback from commands with a YES decision that should be displayed to the user after the command has been applied
*/
public List<String> getYesDecisionMessages() {
return explanations().stream()
.filter(explanation -> explanation.decisions().type().equals(Decision.Type.YES))
.map(explanation -> explanation.command().getMessage())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}

/**
* Read in a RoutingExplanations object
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.elasticsearch.index.shard.ShardNotFoundException;

import java.io.IOException;
import java.util.Optional;

/**
* Allocates an unassigned empty primary shard to a specific node. Use with extreme care as this will result in data loss.
Expand Down Expand Up @@ -72,6 +73,11 @@ public String name() {
return NAME;
}

@Override
public Optional<String> getMessage() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question, why did you do it here and not as part of the RoutingExplaination returned by execute()? I'm ok if you prefer this, but just wondering to your thinking?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thinking was that we didn't want to change the wire format of RerouteExplanation by adding the message to it (I think Yannick mentioned this), so here seemed like an okay place to generate the message.

Do you mean putting this message into one of the field of the Decision that the RerouteExplanation is constructed with? E.g.

public RerouteExplanation execute(RoutingAllocation allocation, boolean explain) {
    // ...
    return new RerouteExplanation(this, allocation.decision(Decision.YES, name() + " (allocation command)", "allocated an empty primary for ... rest of the message"));
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was was thinking about adding a message field to RerouteExplanation it self. The write thing is not a big deal IMO

return Optional.of("Allocated an empty primary for [" + index + "][" + shardId + "] on node [" + node + "]");
}

public static AllocateEmptyPrimaryAllocationCommand fromXContent(XContentParser parser) throws IOException {
return new Builder().parse(parser).build();
}
Expand Down Expand Up @@ -115,19 +121,22 @@ public RerouteExplanation execute(RoutingAllocation allocation, boolean explain)
}

if (shardRouting.recoverySource().getType() != RecoverySource.Type.EMPTY_STORE && acceptDataLoss == false) {
return explainOrThrowRejectedCommand(explain, allocation,
"allocating an empty primary for [" + index + "][" + shardId + "] can result in data loss. Please confirm by setting the accept_data_loss parameter to true");
String dataLossWarning = "allocating an empty primary for [" + index + "][" + shardId + "] can result in data loss. Please confirm " +
"by setting the accept_data_loss parameter to true";
return explainOrThrowRejectedCommand(explain, allocation, dataLossWarning);
}

UnassignedInfo unassignedInfoToUpdate = null;
if (shardRouting.unassignedInfo().getReason() != UnassignedInfo.Reason.FORCED_EMPTY_PRIMARY) {
unassignedInfoToUpdate = new UnassignedInfo(UnassignedInfo.Reason.FORCED_EMPTY_PRIMARY,
"force empty allocation from previous reason " + shardRouting.unassignedInfo().getReason() + ", " + shardRouting.unassignedInfo().getMessage(),
String unassignedInfoMessage = "force empty allocation from previous reason " + shardRouting.unassignedInfo().getReason() +
", " + shardRouting.unassignedInfo().getMessage();
unassignedInfoToUpdate = new UnassignedInfo(UnassignedInfo.Reason.FORCED_EMPTY_PRIMARY, unassignedInfoMessage,
shardRouting.unassignedInfo().getFailure(), 0, System.nanoTime(), System.currentTimeMillis(), false,
shardRouting.unassignedInfo().getLastAllocationStatus());
}

initializeUnassignedShard(allocation, routingNodes, routingNode, shardRouting, unassignedInfoToUpdate, StoreRecoverySource.EMPTY_STORE_INSTANCE);
initializeUnassignedShard(allocation, routingNodes, routingNode, shardRouting, unassignedInfoToUpdate,
StoreRecoverySource.EMPTY_STORE_INSTANCE);

return new RerouteExplanation(this, allocation.decision(Decision.YES, name() + " (allocation command)", "ignore deciders"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.elasticsearch.index.shard.ShardNotFoundException;

import java.io.IOException;
import java.util.Optional;

/**
* Allocates an unassigned stale primary shard to a specific node. Use with extreme care as this will result in data loss.
Expand Down Expand Up @@ -70,6 +71,11 @@ public String name() {
return NAME;
}

@Override
public Optional<String> getMessage() {
return Optional.of("Allocated a stale primary for [" + index + "][" + shardId + "] on node [" + node + "]");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log messages always start in lower case. Also I wonder if we should give this (and AllocateEmptyPrimaryAllocationCommand) a stronger wording, e.g. "force-allocated a stale primary ...", to make it clearer that this action has been explicitly forced by the user, not the system.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good idea, will make it more clear that it came from a command

}

public static AllocateStalePrimaryAllocationCommand fromXContent(XContentParser parser) throws IOException {
return new Builder().parse(parser).build();
}
Expand Down Expand Up @@ -113,8 +119,9 @@ public RerouteExplanation execute(RoutingAllocation allocation, boolean explain)
}

if (acceptDataLoss == false) {
return explainOrThrowRejectedCommand(explain, allocation,
"allocating an empty primary for [" + index + "][" + shardId + "] can result in data loss. Please confirm by setting the accept_data_loss parameter to true");
String dataLossWarning = "allocating an empty primary for [" + index + "][" + shardId + "] can result in data loss. Please " +
"confirm by setting the accept_data_loss parameter to true";
return explainOrThrowRejectedCommand(explain, allocation, dataLossWarning);
}

if (shardRouting.recoverySource().getType() != RecoverySource.Type.EXISTING_STORE) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Optional;

/**
* A command to move shards in some way.
Expand Down Expand Up @@ -61,4 +62,12 @@ interface Parser<T extends AllocationCommand> {
default String getWriteableName() {
return name();
}

/**
* Returns any feedback the command wants to provide for logging. This message should be appropriate to expose to the user after the
* command has been applied
*/
default Optional<String> getMessage() {
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,24 @@

package org.elasticsearch.cluster.allocation;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse;
import org.elasticsearch.action.admin.cluster.reroute.TransportClusterRerouteAction;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.allocation.RerouteExplanation;
import org.elasticsearch.cluster.routing.allocation.RoutingExplanations;
import org.elasticsearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider;
Expand All @@ -50,6 +54,7 @@
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.MockLogAppender;

import java.nio.file.Path;
import java.util.Arrays;
Expand All @@ -63,6 +68,7 @@
import static org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;

Expand Down Expand Up @@ -304,6 +310,84 @@ public void testRerouteExplain() {
assertThat(explanation.decisions().type(), equalTo(Decision.Type.YES));
}

public void testMessageLogging() throws Exception{
final Settings settings = Settings.builder()
.put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), Allocation.NONE.name())
.put(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), EnableAllocationDecider.Rebalance.NONE.name())
.build();

final String nodeName1 = internalCluster().startNode(settings);
assertThat(cluster().size(), equalTo(1));
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForNodes("1")
.execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));

final String nodeName2 = internalCluster().startNode(settings);
assertThat(cluster().size(), equalTo(2));
healthResponse = client().admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));

final String indexName = "test_index";
client().admin().indices().prepareCreate(indexName).setWaitForActiveShards(ActiveShardCount.NONE)
.setSettings(Settings.builder()
.put(IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 2)
.put(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1))
.execute().actionGet();

Logger actionLogger = Loggers.getLogger(TransportClusterRerouteAction.class);

MockLogAppender dryRunMockLog = new MockLogAppender();
dryRunMockLog.start();
dryRunMockLog.addExpectation(
new MockLogAppender.UnseenEventExpectation("no completed message logged on dry run",
TransportClusterRerouteAction.class.getName(), Level.INFO, "Allocated an empty primary*")
);
Loggers.addAppender(actionLogger, dryRunMockLog);

AllocationCommand dryRunAllocation = new AllocateEmptyPrimaryAllocationCommand(indexName, 0, nodeName1, true);
ClusterRerouteResponse dryRunResponse = client().admin().cluster().prepareReroute()
.setExplain(randomBoolean())
.setDryRun(true)
.add(dryRunAllocation)
.execute().actionGet();

// during a dry run, messages exist but are not logged or exposed
assertThat(dryRunResponse.getExplanations().getYesDecisionMessages(), hasSize(1));
assertThat(dryRunResponse.getExplanations().getYesDecisionMessages().get(0), containsString("Allocated an empty primary"));

dryRunMockLog.assertAllExpectationsMatched();
dryRunMockLog.stop();
Loggers.removeAppender(actionLogger, dryRunMockLog);

MockLogAppender allocateMockLog = new MockLogAppender();
allocateMockLog.start();
allocateMockLog.addExpectation(
new MockLogAppender.SeenEventExpectation("message for first allocate empty primary",
TransportClusterRerouteAction.class.getName(), Level.INFO, "Allocated an empty primary*" + nodeName1 + "*")
);
allocateMockLog.addExpectation(
new MockLogAppender.UnseenEventExpectation("no message for second allocate empty primary",
TransportClusterRerouteAction.class.getName(), Level.INFO, "Allocated an empty primary*" + nodeName2 + "*")
);
Loggers.addAppender(actionLogger, allocateMockLog);

AllocationCommand yesDecisionAllocation = new AllocateEmptyPrimaryAllocationCommand(indexName, 0, nodeName1, true);
AllocationCommand noDecisionAllocation = new AllocateEmptyPrimaryAllocationCommand("noexist", 1, nodeName2, true);
ClusterRerouteResponse response = client().admin().cluster().prepareReroute()
.setExplain(true) // so we get a NO decision back rather than an exception
.add(yesDecisionAllocation)
.add(noDecisionAllocation)
.execute().actionGet();

assertThat(response.getExplanations().getYesDecisionMessages(), hasSize(1));
assertThat(response.getExplanations().getYesDecisionMessages().get(0), containsString("Allocated an empty primary"));
assertThat(response.getExplanations().getYesDecisionMessages().get(0), containsString(nodeName1));

allocateMockLog.assertAllExpectationsMatched();
allocateMockLog.stop();
Loggers.removeAppender(actionLogger, allocateMockLog);
}

public void testClusterRerouteWithBlocks() throws Exception {
List<String> nodesIds = internalCluster().startNodes(2);

Expand Down