Skip to content
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

Make Transport Shard Bulk Action Async #39793

Merged
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
5ee4211
Make TransportBulkAction Non-Blocking
original-brownbear Mar 5, 2019
788efd3
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Mar 11, 2019
36508a6
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Mar 12, 2019
40a3c8d
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Mar 17, 2019
764b70b
shorter diff
original-brownbear Mar 17, 2019
6a59fa0
shorter
original-brownbear Mar 17, 2019
0bb09ee
shorter
original-brownbear Mar 17, 2019
9a22a36
fix duplication
original-brownbear Mar 17, 2019
8df5f96
fix test
original-brownbear Mar 17, 2019
b47e5f7
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Mar 22, 2019
f3b59c2
CR: handle bulk rejections after mapping updates
original-brownbear Mar 22, 2019
0b3b4ab
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Mar 24, 2019
a3c8cac
CR: add test for bulk rejection behaviour
original-brownbear Mar 24, 2019
7f8700a
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Mar 28, 2019
5780183
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Apr 3, 2019
e59c5ea
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Apr 4, 2019
c319bef
CR: comments
original-brownbear Apr 4, 2019
c5edc6e
dry up exception handling
original-brownbear Apr 4, 2019
e13ac0a
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Apr 5, 2019
7d6fd4a
CR comments
original-brownbear Apr 5, 2019
9e84385
revert needless change
original-brownbear Apr 5, 2019
2277d40
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Apr 5, 2019
3001b27
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Apr 5, 2019
3475e04
Merge remote-tracking branch 'elastic/master' into async-bulk-action
original-brownbear Apr 6, 2019
b0b844f
CR: Revert changes to shardOperationOnPrimary interface
original-brownbear Apr 6, 2019
79944b6
Revert "CR: Revert changes to shardOperationOnPrimary interface"
original-brownbear Apr 6, 2019
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 @@ -85,14 +85,16 @@ protected void acquireReplicaOperationPermit(final IndexShard replica,
}

@Override
protected PrimaryResult<ShardRequest, ReplicationResponse> shardOperationOnPrimary(final ShardRequest shardRequest,
final IndexShard primary) throws Exception {
executeShardOperation(shardRequest, primary);
return new PrimaryResult<>(shardRequest, new ReplicationResponse());
protected void shardOperationOnPrimary(final ShardRequest shardRequest, final IndexShard primary,
ActionListener<PrimaryResult<ShardRequest, ReplicationResponse>> listener) {
ActionListener.completeWith(listener, () -> {
Copy link
Member

@dnhatn dnhatn Apr 6, 2019

Choose a reason for hiding this comment

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

Since most of write actions execute its primary action synchronously, maybe introduce an async method which uses the result from the sync version by default (see https://github.com/elastic/elasticsearch/blob/master/server/src/main/java/org/elasticsearch/action/support/single/shard/TransportSingleShardAction.java#L106-L120). We then can revert changes in other actions.

Copy link
Member Author

Choose a reason for hiding this comment

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

I tried doing this here, but ran into a bit of a mess with the slightly strange way we handle the overrides of this method where we constrain the type to WritePrimaryResult so I decided to not do it here to unblock another thing.
I like the idea though! => I'll open a PR that cleans this up (very) shortly :)

Copy link
Member

Choose a reason for hiding this comment

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

No worry. It's optional. Thanks for giving it a try.

executeShardOperation(shardRequest, primary);
return new PrimaryResult<>(shardRequest, new ReplicationResponse());
});
}

@Override
protected ReplicaResult shardOperationOnReplica(final ShardRequest shardRequest, final IndexShard replica) throws Exception {
protected ReplicaResult shardOperationOnReplica(final ShardRequest shardRequest, final IndexShard replica) {
executeShardOperation(shardRequest, replica);
return new ReplicaResult();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.elasticsearch.action.admin.indices.flush;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.action.support.replication.TransportReplicationAction;
Expand Down Expand Up @@ -51,11 +52,13 @@ protected ReplicationResponse newResponseInstance() {
}

@Override
protected PrimaryResult<ShardFlushRequest, ReplicationResponse> shardOperationOnPrimary(ShardFlushRequest shardRequest,
IndexShard primary) {
primary.flush(shardRequest.getRequest());
logger.trace("{} flush request executed on primary", primary.shardId());
return new PrimaryResult<ShardFlushRequest, ReplicationResponse>(shardRequest, new ReplicationResponse());
protected void shardOperationOnPrimary(ShardFlushRequest shardRequest, IndexShard primary,
ActionListener<PrimaryResult<ShardFlushRequest, ReplicationResponse>> listener) {
ActionListener.completeWith(listener, () -> {
primary.flush(shardRequest.getRequest());
logger.trace("{} flush request executed on primary", primary.shardId());
return new PrimaryResult<>(shardRequest, new ReplicationResponse());
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.elasticsearch.action.admin.indices.refresh;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.replication.BasicReplicationRequest;
import org.elasticsearch.action.support.replication.ReplicationResponse;
Expand Down Expand Up @@ -53,11 +54,13 @@ protected ReplicationResponse newResponseInstance() {
}

@Override
protected PrimaryResult<BasicReplicationRequest, ReplicationResponse> shardOperationOnPrimary(
BasicReplicationRequest shardRequest, IndexShard primary) {
primary.refresh("api");
logger.trace("{} refresh request executed on primary", primary.shardId());
return new PrimaryResult<>(shardRequest, new ReplicationResponse());
protected void shardOperationOnPrimary(BasicReplicationRequest shardRequest, IndexShard primary,
ActionListener<PrimaryResult<BasicReplicationRequest, ReplicationResponse>> listener) {
ActionListener.completeWith(listener, () -> {
primary.refresh("api");
logger.trace("{} refresh request executed on primary", primary.shardId());
return new PrimaryResult<>(shardRequest, new ReplicationResponse());
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.elasticsearch.action.bulk;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.shard.ShardId;

Expand All @@ -27,6 +28,6 @@ public interface MappingUpdatePerformer {
/**
* Update the mappings on the master.
*/
void updateMappings(Mapping update, ShardId shardId, String type);
void updateMappings(Mapping update, ShardId shardId, String type, ActionListener<Void> listener);

}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ public ClusterBlockLevel indexBlockLevel() {
}

@Override
protected WritePrimaryResult<ResyncReplicationRequest, ResyncReplicationResponse> shardOperationOnPrimary(
ResyncReplicationRequest request, IndexShard primary) {
final ResyncReplicationRequest replicaRequest = performOnPrimary(request);
return new WritePrimaryResult<>(replicaRequest, new ResyncReplicationResponse(), null, null, primary, logger);
protected void shardOperationOnPrimary(ResyncReplicationRequest request, IndexShard primary,
ActionListener<PrimaryResult<ResyncReplicationRequest, ResyncReplicationResponse>> listener) {
ActionListener.completeWith(listener,
() -> new WritePrimaryResult<>(performOnPrimary(request), new ResyncReplicationResponse(), null, null, primary, logger));
}

public static ResyncReplicationRequest performOnPrimary(ResyncReplicationRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,18 @@ public void execute() throws Exception {

totalShards.incrementAndGet();
pendingActions.incrementAndGet(); // increase by 1 until we finish all primary coordination
primaryResult = primary.perform(request);
primary.perform(request, ActionListener.wrap(
primaryResult -> handlePrimaryResult(primaryRouting, primaryId, primaryResult), resultListener::onFailure));
}

private void handlePrimaryResult(final ShardRouting primaryRouting, final ShardId primaryId, final PrimaryResultT primaryResult) {
original-brownbear marked this conversation as resolved.
Show resolved Hide resolved
this.primaryResult = primaryResult;
primary.updateLocalCheckpointForShard(primaryRouting.allocationId().getId(), primary.localCheckpoint());
final ReplicaRequest replicaRequest = primaryResult.replicaRequest();
if (replicaRequest != null) {
if (logger.isTraceEnabled()) {
logger.trace("[{}] op [{}] completed on primary for request [{}]", primaryId, opType, request);
}

// we have to get the replication group after successfully indexing into the primary in order to honour recovery semantics.
// we have to make sure that every operation indexed into the primary after recovery start will also be replicated
// to the recovery target. If we used an old replication group, we may miss a recovery that has started since then.
Expand All @@ -119,14 +123,14 @@ public void execute() throws Exception {
// This would entail that some shards could learn about a global checkpoint that would be higher than its local checkpoint.
final long globalCheckpoint = primary.globalCheckpoint();
// we have to capture the max_seq_no_of_updates after this request was completed on the primary to make sure the value of
// max_seq_no_of_updates on replica when this request is executed is at least the value on the primary when it was executed on.
// max_seq_no_of_updates on replica when this request is executed is at least the value on the primary when it was executed
// on.
final long maxSeqNoOfUpdatesOrDeletes = primary.maxSeqNoOfUpdatesOrDeletes();
assert maxSeqNoOfUpdatesOrDeletes != SequenceNumbers.UNASSIGNED_SEQ_NO : "seqno_of_updates still uninitialized";
final ReplicationGroup replicationGroup = primary.getReplicationGroup();
markUnavailableShardsAsStale(replicaRequest, replicationGroup);
performOnReplicas(replicaRequest, globalCheckpoint, maxSeqNoOfUpdatesOrDeletes, replicationGroup);
}

successfulShards.incrementAndGet(); // mark primary as successful
decPendingAndFinishIfNeeded();
}
Expand Down Expand Up @@ -312,9 +316,9 @@ public interface Primary<
* also complete after. Deal with it.
*
* @param request the request to perform
* @return the request to send to the replicas
* @param listener result listener
*/
PrimaryResultT perform(RequestT request) throws Exception;
void perform(RequestT request, ActionListener<PrimaryResultT> listener);

/**
* Notifies the primary of a local checkpoint for the given allocation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.store.AlreadyClosedException;
import org.elasticsearch.Assertions;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
Expand Down Expand Up @@ -192,8 +193,8 @@ protected void resolveRequest(final IndexMetaData indexMetaData, final Request r
* @param shardRequest the request to the primary shard
* @param primary the primary shard to perform the operation on
*/
protected abstract PrimaryResult<ReplicaRequest, Response> shardOperationOnPrimary(
Request shardRequest, IndexShard primary) throws Exception;
protected abstract void shardOperationOnPrimary(Request shardRequest, IndexShard primary,
ActionListener<PrimaryResult<ReplicaRequest, Response>> listener);

/**
* Synchronously execute the specified replica operation. This is done under a permit from
Expand Down Expand Up @@ -419,7 +420,7 @@ protected ReplicationOperation<Request, ReplicaRequest, PrimaryResult<ReplicaReq
}
}

protected static class PrimaryResult<ReplicaRequest extends ReplicationRequest<ReplicaRequest>,
public static class PrimaryResult<ReplicaRequest extends ReplicationRequest<ReplicaRequest>,
Response extends ReplicationResponse>
implements ReplicationOperation.PrimaryResult<ReplicaRequest> {
final ReplicaRequest replicaRequest;
Expand Down Expand Up @@ -918,11 +919,15 @@ public void failShard(String reason, Exception e) {
}

@Override
public PrimaryResult<ReplicaRequest, Response> perform(Request request) throws Exception {
PrimaryResult<ReplicaRequest, Response> result = shardOperationOnPrimary(request, indexShard);
assert result.replicaRequest() == null || result.finalFailure == null : "a replica request [" + result.replicaRequest()
+ "] with a primary failure [" + result.finalFailure + "]";
return result;
public void perform(Request request, ActionListener<PrimaryResult<ReplicaRequest, Response>> listener) {
if (Assertions.ENABLED) {
listener = ActionListener.map(listener, result -> {
assert result.replicaRequest() == null || result.finalFailure == null : "a replica request [" + result.replicaRequest()
+ "] with a primary failure [" + result.finalFailure + "]";
return result;
});
}
shardOperationOnPrimary(request, indexShard, listener);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,12 @@ protected ReplicationOperation.Replicas newReplicasProxy(long primaryTerm) {
/**
* Called on the primary with a reference to the primary {@linkplain IndexShard} to modify.
*
* @return the result of the operation on primary, including current translog location and operation response and failure
* async refresh is performed on the <code>primary</code> shard according to the <code>Request</code> refresh policy
* @param listener listener for the result of the operation on primary, including current translog location and operation response
* and failure async refresh is performed on the <code>primary</code> shard according to the <code>Request</code> refresh policy
*/
@Override
protected abstract WritePrimaryResult<ReplicaRequest, Response> shardOperationOnPrimary(
Request request, IndexShard primary) throws Exception;
protected abstract void shardOperationOnPrimary(
Request request, IndexShard primary, ActionListener<PrimaryResult<ReplicaRequest, Response>> listener);

/**
* Called once per replica with a reference to the replica {@linkplain IndexShard} to modify.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

package org.elasticsearch.cluster.action.index;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.support.master.MasterNodeRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
Expand All @@ -29,6 +31,7 @@
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.FutureUtils;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.mapper.MapperService;
Expand Down Expand Up @@ -57,34 +60,36 @@ private void setDynamicMappingUpdateTimeout(TimeValue dynamicMappingUpdateTimeou
this.dynamicMappingUpdateTimeout = dynamicMappingUpdateTimeout;
}


public void setClient(Client client) {
this.client = client.admin().indices();
}

private PutMappingRequestBuilder updateMappingRequest(Index index, String type, Mapping mappingUpdate, final TimeValue timeout) {
if (type.equals(MapperService.DEFAULT_MAPPING)) {
throw new IllegalArgumentException("_default_ mapping should not be updated");
}
return client.preparePutMapping().setConcreteIndex(index).setType(type).setSource(mappingUpdate.toString(), XContentType.JSON)
.setMasterNodeTimeout(timeout).setTimeout(TimeValue.ZERO);
}

/**
* Same as {@link #updateMappingOnMaster(Index, String, Mapping, TimeValue)}
* using the default timeout.
*/
public void updateMappingOnMaster(Index index, String type, Mapping mappingUpdate) {
updateMappingOnMaster(index, type, mappingUpdate, dynamicMappingUpdateTimeout);
}

/**
* Update mappings on the master node, waiting for the change to be committed,
* but not for the mapping update to be applied on all nodes. The timeout specified by
* {@code timeout} is the master node timeout ({@link MasterNodeRequest#masterNodeTimeout()}),
* potentially waiting for a master node to be available.
*/
public void updateMappingOnMaster(Index index, String type, Mapping mappingUpdate, TimeValue masterNodeTimeout) {
updateMappingRequest(index, type, mappingUpdate, masterNodeTimeout).get();
public void updateMappingOnMaster(Index index, String type, Mapping mappingUpdate, ActionListener<Void> listener) {
if (type.equals(MapperService.DEFAULT_MAPPING)) {
throw new IllegalArgumentException("_default_ mapping should not be updated");
}
client.preparePutMapping().setConcreteIndex(index).setType(type).setSource(mappingUpdate.toString(), XContentType.JSON)
.setMasterNodeTimeout(dynamicMappingUpdateTimeout).setTimeout(TimeValue.ZERO)
.execute(new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
listener.onResponse(null);
}

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

private static Exception unwrapException(Exception cause) {
return cause instanceof ElasticsearchException ? FutureUtils.unwrapEsException((ElasticsearchException) cause) : cause;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,19 @@ public static <T> T get(Future<T> future, long timeout, TimeUnit unit) {
public static RuntimeException rethrowExecutionException(ExecutionException e) {
if (e.getCause() instanceof ElasticsearchException) {
ElasticsearchException esEx = (ElasticsearchException) e.getCause();
Throwable root = esEx.unwrapCause();
if (root instanceof ElasticsearchException) {
return (ElasticsearchException) root;
} else if (root instanceof RuntimeException) {
return (RuntimeException) root;
}
return new UncategorizedExecutionException("Failed execution", root);
return unwrapEsException(esEx);
} else if (e.getCause() instanceof RuntimeException) {
return (RuntimeException) e.getCause();
} else {
return new UncategorizedExecutionException("Failed execution", e);
}
}

public static RuntimeException unwrapEsException(ElasticsearchException esEx) {
Throwable root = esEx.unwrapCause();
if (root instanceof ElasticsearchException || root instanceof RuntimeException) {
return (RuntimeException) root;
}
return new UncategorizedExecutionException("Failed execution", root);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,12 @@ protected void sendReplicaRequest(
}

@Override
protected PrimaryResult<Request, ReplicationResponse> shardOperationOnPrimary(
final Request request, final IndexShard indexShard) throws Exception {
maybeSyncTranslog(indexShard);
return new PrimaryResult<>(request, new ReplicationResponse());
protected void shardOperationOnPrimary(Request request, IndexShard indexShard,
ActionListener<PrimaryResult<Request, ReplicationResponse>> listener) {
ActionListener.completeWith(listener, () -> {
maybeSyncTranslog(indexShard);
return new PrimaryResult<>(request, new ReplicationResponse());
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,16 @@ public void backgroundSync(
}

@Override
protected PrimaryResult<Request, ReplicationResponse> shardOperationOnPrimary(
protected void shardOperationOnPrimary(
final Request request,
final IndexShard primary) throws WriteStateException {
assert request.waitForActiveShards().equals(ActiveShardCount.NONE) : request.waitForActiveShards();
Objects.requireNonNull(request);
Objects.requireNonNull(primary);
primary.persistRetentionLeases();
return new PrimaryResult<>(request, new ReplicationResponse());
final IndexShard primary, ActionListener<PrimaryResult<Request, ReplicationResponse>> listener) {
ActionListener.completeWith(listener, () -> {
assert request.waitForActiveShards().equals(ActiveShardCount.NONE) : request.waitForActiveShards();
Objects.requireNonNull(request);
Objects.requireNonNull(primary);
primary.persistRetentionLeases();
return new PrimaryResult<>(request, new ReplicationResponse());
});
}

@Override
Expand Down
Loading