) executableScript.unwrap(ctx);
}
} catch (Exception e) {
throw new IllegalArgumentException("failed to execute script", e);
diff --git a/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java b/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java
index 053f4aeaf33..345513d7f34 100644
--- a/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java
+++ b/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java
@@ -171,7 +171,7 @@ final class Bootstrap {
// placeholder
Settings nodeSettings = Settings.settingsBuilder()
.put(settings)
- .put(InternalSettingsPreparer.IGNORE_SYSTEM_PROPERTIES_SETTING, true)
+ .put(InternalSettingsPreparer.IGNORE_SYSTEM_PROPERTIES_SETTING.getKey(), true)
.build();
node = new Node(nodeSettings);
diff --git a/core/src/main/java/org/elasticsearch/client/Client.java b/core/src/main/java/org/elasticsearch/client/Client.java
index e7461dabfe1..f81ba9eb1b1 100644
--- a/core/src/main/java/org/elasticsearch/client/Client.java
+++ b/core/src/main/java/org/elasticsearch/client/Client.java
@@ -19,8 +19,12 @@
package org.elasticsearch.client;
+import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.ActionListener;
+import org.elasticsearch.action.ActionRequest;
+import org.elasticsearch.action.ActionRequestBuilder;
+import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
@@ -80,11 +84,13 @@ import org.elasticsearch.action.termvectors.TermVectorsResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
-import org.elasticsearch.client.support.Headers;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.lease.Releasable;
+import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
+import java.util.Map;
+
/**
* A client provides a one stop interface for performing actions/operations against the cluster.
*
@@ -100,7 +106,15 @@ import org.elasticsearch.common.settings.Settings;
*/
public interface Client extends ElasticsearchClient, Releasable {
- String CLIENT_TYPE_SETTING = "client.type";
+ Setting CLIENT_TYPE_SETTING_S = new Setting<>("client.type", "node", (s) -> {
+ switch (s) {
+ case "node":
+ case "transport":
+ return s;
+ default:
+ throw new IllegalArgumentException("Can't parse [client.type] must be one of [node, transport]");
+ }
+ }, false, Setting.Scope.CLUSTER);
/**
* The admin client that can be used to perform administrative operations.
@@ -597,5 +611,9 @@ public interface Client extends ElasticsearchClient, Releasable {
*/
Settings settings();
- Headers headers();
+ /**
+ * Returns a new lightweight Client that applies all given headers to each of the requests
+ * issued from it.
+ */
+ Client filterWithHeader(Map headers);
}
diff --git a/core/src/main/java/org/elasticsearch/client/FilterClient.java b/core/src/main/java/org/elasticsearch/client/FilterClient.java
index 77abceef17a..d2ea209a8c2 100644
--- a/core/src/main/java/org/elasticsearch/client/FilterClient.java
+++ b/core/src/main/java/org/elasticsearch/client/FilterClient.java
@@ -42,7 +42,7 @@ public abstract class FilterClient extends AbstractClient {
* @see #in()
*/
public FilterClient(Client in) {
- super(in.settings(), in.threadPool(), in.headers());
+ super(in.settings(), in.threadPool());
this.in = in;
}
diff --git a/core/src/main/java/org/elasticsearch/client/node/NodeClient.java b/core/src/main/java/org/elasticsearch/client/node/NodeClient.java
index 4f64f63f8d7..3e9bed9e25d 100644
--- a/core/src/main/java/org/elasticsearch/client/node/NodeClient.java
+++ b/core/src/main/java/org/elasticsearch/client/node/NodeClient.java
@@ -27,7 +27,6 @@ import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.GenericAction;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.client.support.AbstractClient;
-import org.elasticsearch.client.support.Headers;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.threadpool.ThreadPool;
@@ -44,8 +43,8 @@ public class NodeClient extends AbstractClient {
private final Map actions;
@Inject
- public NodeClient(Settings settings, ThreadPool threadPool, Headers headers, Map actions) {
- super(settings, threadPool, headers);
+ public NodeClient(Settings settings, ThreadPool threadPool, Map actions) {
+ super(settings, threadPool);
this.actions = unmodifiableMap(actions);
}
diff --git a/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java b/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java
index fb0891da8cc..de134887303 100644
--- a/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java
+++ b/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java
@@ -20,7 +20,6 @@
package org.elasticsearch.client.node;
import org.elasticsearch.client.Client;
-import org.elasticsearch.client.support.Headers;
import org.elasticsearch.common.inject.AbstractModule;
/**
@@ -30,7 +29,6 @@ public class NodeClientModule extends AbstractModule {
@Override
protected void configure() {
- bind(Headers.class).asEagerSingleton();
bind(Client.class).to(NodeClient.class).asEagerSingleton();
}
}
diff --git a/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java
index f8badc3a8fb..ac60df1d67a 100644
--- a/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java
+++ b/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java
@@ -332,13 +332,17 @@ import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.ClusterAdminClient;
import org.elasticsearch.client.ElasticsearchClient;
+import org.elasticsearch.client.FilterClient;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.threadpool.ThreadPool;
+import java.util.Map;
+
/**
*
*/
@@ -346,23 +350,15 @@ public abstract class AbstractClient extends AbstractComponent implements Client
private final ThreadPool threadPool;
private final Admin admin;
-
- private final Headers headers;
private final ThreadedActionListener.Wrapper threadedWrapper;
- public AbstractClient(Settings settings, ThreadPool threadPool, Headers headers) {
+ public AbstractClient(Settings settings, ThreadPool threadPool) {
super(settings);
this.threadPool = threadPool;
- this.headers = headers;
this.admin = new Admin(this);
this.threadedWrapper = new ThreadedActionListener.Wrapper(logger, settings, threadPool);
}
- @Override
- public Headers headers() {
- return this.headers;
- }
-
@Override
public final Settings settings() {
return this.settings;
@@ -398,7 +394,6 @@ public abstract class AbstractClient extends AbstractComponent implements Client
@Override
public final , Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder> void execute(
Action action, Request request, ActionListener listener) {
- headers.applyTo(request);
listener = threadedWrapper.wrap(listener);
doExecute(action, request, listener);
}
@@ -1757,4 +1752,17 @@ public abstract class AbstractClient extends AbstractComponent implements Client
execute(GetSettingsAction.INSTANCE, request, listener);
}
}
+
+ @Override
+ public Client filterWithHeader(Map headers) {
+ return new FilterClient(this) {
+ @Override
+ protected , Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder> void doExecute(Action action, Request request, ActionListener listener) {
+ ThreadContext threadContext = threadPool().getThreadContext();
+ try (ThreadContext.StoredContext ctx = threadContext.stashAndMergeHeaders(headers)) {
+ super.doExecute(action, request, listener);
+ }
+ }
+ };
+ }
}
diff --git a/core/src/main/java/org/elasticsearch/client/support/Headers.java b/core/src/main/java/org/elasticsearch/client/support/Headers.java
deleted file mode 100644
index f46bd0a1c9d..00000000000
--- a/core/src/main/java/org/elasticsearch/client/support/Headers.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.client.support;
-
-import org.elasticsearch.common.inject.Inject;
-import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.transport.TransportMessage;
-
-/**
- * Client request headers picked up from the client settings. Applied to every
- * request sent by the client (both transport and node clients)
- */
-public class Headers {
-
- public static final String PREFIX = "request.headers";
-
- public static final Headers EMPTY = new Headers(Settings.EMPTY) {
- @Override
- public > M applyTo(M message) {
- return message;
- }
- };
-
- private final Settings headers;
-
- @Inject
- public Headers(Settings settings) {
- headers = resolveHeaders(settings);
- }
-
- public > M applyTo(M message) {
- for (String key : headers.names()) {
- if (!message.hasHeader(key)) {
- message.putHeader(key, headers.get(key));
- }
- }
- return message;
- }
-
- public Settings headers() {
- return headers;
- }
-
- static Settings resolveHeaders(Settings settings) {
- Settings headers = settings.getAsSettings(PREFIX);
- return headers != null ? headers : Settings.EMPTY;
- }
-}
diff --git a/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java b/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java
index ea809a8cc38..419c4d566a5 100644
--- a/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java
+++ b/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java
@@ -28,7 +28,6 @@ import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.cache.recycler.PageCacheRecycler;
import org.elasticsearch.client.support.AbstractClient;
-import org.elasticsearch.client.support.Headers;
import org.elasticsearch.client.transport.support.TransportProxyClient;
import org.elasticsearch.cluster.ClusterNameModule;
import org.elasticsearch.cluster.node.DiscoveryNode;
@@ -115,7 +114,7 @@ public class TransportClient extends AbstractClient {
.put( InternalSettingsPreparer.prepareSettings(settings))
.put("network.server", false)
.put(Node.NODE_CLIENT_SETTING.getKey(), true)
- .put(CLIENT_TYPE_SETTING, CLIENT_TYPE);
+ .put(CLIENT_TYPE_SETTING_S.getKey(), CLIENT_TYPE);
return new PluginsService(settingsBuilder.build(), null, null, pluginClasses);
}
@@ -177,7 +176,7 @@ public class TransportClient extends AbstractClient {
private final TransportProxyClient proxy;
private TransportClient(Injector injector) {
- super(injector.getInstance(Settings.class), injector.getInstance(ThreadPool.class), injector.getInstance(Headers.class));
+ super(injector.getInstance(Settings.class), injector.getInstance(ThreadPool.class));
this.injector = injector;
nodesService = injector.getInstance(TransportClientNodesService.class);
proxy = injector.getInstance(TransportProxyClient.class);
diff --git a/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java b/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java
index 99c70255ca8..f9ee988d811 100644
--- a/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java
+++ b/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java
@@ -29,7 +29,6 @@ import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAct
import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Requests;
-import org.elasticsearch.client.support.Headers;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.component.AbstractComponent;
@@ -80,8 +79,6 @@ public class TransportClientNodesService extends AbstractComponent {
private final Version minCompatibilityVersion;
- private final Headers headers;
-
// nodes that are added to be discovered
private volatile List listedNodes = Collections.emptyList();
@@ -109,13 +106,12 @@ public class TransportClientNodesService extends AbstractComponent {
@Inject
public TransportClientNodesService(Settings settings, ClusterName clusterName, TransportService transportService,
- ThreadPool threadPool, Headers headers, Version version) {
+ ThreadPool threadPool, Version version) {
super(settings);
this.clusterName = clusterName;
this.transportService = transportService;
this.threadPool = threadPool;
this.minCompatibilityVersion = version.minimumCompatibilityVersion();
- this.headers = headers;
this.nodesSamplerInterval = CLIENT_TRANSPORT_NODES_SAMPLER_INTERVAL.get(this.settings);
this.pingTimeout = CLIENT_TRANSPORT_PING_TIMEOUT.get(this.settings).millis();
@@ -364,7 +360,7 @@ public class TransportClientNodesService extends AbstractComponent {
}
try {
LivenessResponse livenessResponse = transportService.submitRequest(listedNode, TransportLivenessAction.NAME,
- headers.applyTo(new LivenessRequest()),
+ new LivenessRequest(),
TransportRequestOptions.builder().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout).build(),
new FutureTransportResponseHandler() {
@Override
@@ -434,8 +430,7 @@ public class TransportClientNodesService extends AbstractComponent {
return;
}
}
- transportService.sendRequest(listedNode, ClusterStateAction.NAME,
- headers.applyTo(Requests.clusterStateRequest().clear().nodes(true).local(true)),
+ transportService.sendRequest(listedNode, ClusterStateAction.NAME, Requests.clusterStateRequest().clear().nodes(true).local(true),
TransportRequestOptions.builder().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout).build(),
new BaseTransportResponseHandler() {
diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterName.java b/core/src/main/java/org/elasticsearch/cluster/ClusterName.java
index 3a9dd82732c..daf3000d710 100644
--- a/core/src/main/java/org/elasticsearch/cluster/ClusterName.java
+++ b/core/src/main/java/org/elasticsearch/cluster/ClusterName.java
@@ -22,6 +22,7 @@ package org.elasticsearch.cluster;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
+import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import java.io.IOException;
@@ -31,18 +32,23 @@ import java.io.IOException;
*/
public class ClusterName implements Streamable {
- public static final String SETTING = "cluster.name";
+ public static final Setting CLUSTER_NAME_SETTING = new Setting<>("cluster.name", "elasticsearch", (s) -> {
+ if (s.isEmpty()) {
+ throw new IllegalArgumentException("[cluster.name] must not be empty");
+ }
+ return s;
+ }, false, Setting.Scope.CLUSTER);
- public static final ClusterName DEFAULT = new ClusterName("elasticsearch".intern());
+
+ public static final ClusterName DEFAULT = new ClusterName(CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY).intern());
private String value;
public static ClusterName clusterNameFromSettings(Settings settings) {
- return new ClusterName(settings.get("cluster.name", ClusterName.DEFAULT.value()));
+ return new ClusterName(CLUSTER_NAME_SETTING.get(settings));
}
private ClusterName() {
-
}
public ClusterName(String value) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterState.java b/core/src/main/java/org/elasticsearch/cluster/ClusterState.java
index dd8c737b6b0..2a4d57724cd 100644
--- a/core/src/main/java/org/elasticsearch/cluster/ClusterState.java
+++ b/core/src/main/java/org/elasticsearch/cluster/ClusterState.java
@@ -449,7 +449,7 @@ public class ClusterState implements ToXContent, Diffable {
builder.startObject("indices");
for (IndexMetaData indexMetaData : metaData()) {
- builder.startObject(indexMetaData.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
+ builder.startObject(indexMetaData.getIndex().getName(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("state", indexMetaData.getState().toString().toLowerCase(Locale.ENGLISH));
@@ -506,7 +506,7 @@ public class ClusterState implements ToXContent, Diffable {
builder.startObject("routing_table");
builder.startObject("indices");
for (IndexRoutingTable indexRoutingTable : routingTable()) {
- builder.startObject(indexRoutingTable.index(), XContentBuilder.FieldCaseConversion.NONE);
+ builder.startObject(indexRoutingTable.getIndex().getName(), XContentBuilder.FieldCaseConversion.NONE);
builder.startObject("shards");
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
builder.startArray(Integer.toString(indexShardRoutingTable.shardId().id()));
diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java b/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java
index df857623570..dd30a711688 100644
--- a/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java
+++ b/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java
@@ -23,6 +23,7 @@ import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.common.util.concurrent.ThreadContext;
import java.util.concurrent.atomic.AtomicReference;
@@ -44,6 +45,7 @@ public class ClusterStateObserver {
};
private final ClusterService clusterService;
+ private final ThreadContext contextHolder;
volatile TimeValue timeOutValue;
@@ -55,8 +57,8 @@ public class ClusterStateObserver {
volatile boolean timedOut;
- public ClusterStateObserver(ClusterService clusterService, ESLogger logger) {
- this(clusterService, new TimeValue(60000), logger);
+ public ClusterStateObserver(ClusterService clusterService, ESLogger logger, ThreadContext contextHolder) {
+ this(clusterService, new TimeValue(60000), logger, contextHolder);
}
/**
@@ -64,7 +66,7 @@ public class ClusterStateObserver {
* will fail any existing or new #waitForNextChange calls. Set to null
* to wait indefinitely
*/
- public ClusterStateObserver(ClusterService clusterService, @Nullable TimeValue timeout, ESLogger logger) {
+ public ClusterStateObserver(ClusterService clusterService, @Nullable TimeValue timeout, ESLogger logger, ThreadContext contextHolder) {
this.clusterService = clusterService;
this.lastObservedState = new AtomicReference<>(new ObservedState(clusterService.state()));
this.timeOutValue = timeout;
@@ -72,6 +74,7 @@ public class ClusterStateObserver {
this.startTimeNS = System.nanoTime();
}
this.logger = logger;
+ this.contextHolder = contextHolder;
}
/** last cluster state observer by this observer. Note that this may not be the current one */
@@ -146,7 +149,7 @@ public class ClusterStateObserver {
listener.onNewClusterState(newState.clusterState);
} else {
logger.trace("observer: sampled state rejected by predicate ({}). adding listener to ClusterService", newState);
- ObservingContext context = new ObservingContext(listener, changePredicate);
+ ObservingContext context = new ObservingContext(new ContextPreservingListener(listener, contextHolder.newStoredContext()), changePredicate);
if (!observingContext.compareAndSet(null, context)) {
throw new ElasticsearchException("already waiting for a cluster state change");
}
@@ -317,4 +320,33 @@ public class ClusterStateObserver {
return "version [" + clusterState.version() + "], status [" + status + "]";
}
}
+
+ private final static class ContextPreservingListener implements Listener {
+ private final Listener delegate;
+ private final ThreadContext.StoredContext tempContext;
+
+
+ private ContextPreservingListener(Listener delegate, ThreadContext.StoredContext storedContext) {
+ this.tempContext = storedContext;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void onNewClusterState(ClusterState state) {
+ tempContext.restore();
+ delegate.onNewClusterState(state);
+ }
+
+ @Override
+ public void onClusterServiceClose() {
+ tempContext.restore();
+ delegate.onClusterServiceClose();
+ }
+
+ @Override
+ public void onTimeout(TimeValue timeout) {
+ tempContext.restore();
+ delegate.onTimeout(timeout);
+ }
+ }
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java b/core/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java
index 9a112613b1d..78eef316332 100644
--- a/core/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java
+++ b/core/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java
@@ -162,7 +162,7 @@ public class SnapshotsInProgress extends AbstractDiffable implements Cus
List waitingShards = waitingIndicesMap.get(entry.key.getIndex());
if (waitingShards == null) {
waitingShards = new ArrayList<>();
- waitingIndicesMap.put(entry.key.getIndex(), waitingShards);
+ waitingIndicesMap.put(entry.key.getIndexName(), waitingShards);
}
waitingShards.add(entry.key);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java b/core/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java
index d4f453530bc..012cc66e110 100644
--- a/core/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java
+++ b/core/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java
@@ -103,7 +103,7 @@ public class NodeIndexDeletedAction extends AbstractComponent {
// master. If we can't acquire the locks here immediately there might be a shard of this index still holding on to the lock
// due to a "currently canceled recovery" or so. The shard will delete itself BEFORE the lock is released so it's guaranteed to be
// deleted by the time we get the lock
- indicesService.processPendingDeletes(new Index(index), indexSettings, new TimeValue(30, TimeUnit.MINUTES));
+ indicesService.processPendingDeletes(indexSettings.getIndex(), indexSettings, new TimeValue(30, TimeUnit.MINUTES));
transportService.sendRequest(clusterState.nodes().masterNode(),
INDEX_STORE_DELETED_ACTION_NAME, new NodeIndexStoreDeletedMessage(index, nodeId), EmptyTransportResponseHandler.INSTANCE_SAME);
} catch (LockObtainFailedException exc) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java b/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
index 276edc9b23d..4aca9a4e235 100644
--- a/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
+++ b/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
@@ -74,13 +74,15 @@ public class ShardStateAction extends AbstractComponent {
private final TransportService transportService;
private final ClusterService clusterService;
+ private final ThreadPool threadPool;
@Inject
public ShardStateAction(Settings settings, ClusterService clusterService, TransportService transportService,
- AllocationService allocationService, RoutingService routingService) {
+ AllocationService allocationService, RoutingService routingService, ThreadPool threadPool) {
super(settings);
this.transportService = transportService;
this.clusterService = clusterService;
+ this.threadPool = threadPool;
transportService.registerRequestHandler(SHARD_STARTED_ACTION_NAME, ShardRoutingEntry::new, ThreadPool.Names.SAME, new ShardStartedTransportHandler(clusterService, new ShardStartedClusterStateTaskExecutor(allocationService, logger), logger));
transportService.registerRequestHandler(SHARD_FAILED_ACTION_NAME, ShardRoutingEntry::new, ThreadPool.Names.SAME, new ShardFailedTransportHandler(clusterService, new ShardFailedClusterStateTaskExecutor(allocationService, routingService, logger), logger));
@@ -124,7 +126,7 @@ public class ShardStateAction extends AbstractComponent {
}
public void shardFailed(final ShardRouting shardRouting, final String indexUUID, final String message, @Nullable final Throwable failure, Listener listener) {
- ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger);
+ ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger, threadPool.getThreadContext());
ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, message, failure);
sendShardAction(SHARD_FAILED_ACTION_NAME, observer, shardRoutingEntry, listener);
}
@@ -290,7 +292,7 @@ public class ShardStateAction extends AbstractComponent {
}
public void shardStarted(final ShardRouting shardRouting, String indexUUID, final String message, Listener listener) {
- ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger);
+ ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger, threadPool.getThreadContext());
ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, message, null);
sendShardAction(SHARD_STARTED_ACTION_NAME, observer, shardRoutingEntry, listener);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java b/core/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java
index 0006c7da8c9..d48fc3138d9 100644
--- a/core/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java
+++ b/core/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java
@@ -304,29 +304,29 @@ public class ClusterBlocks extends AbstractDiffable {
public Builder addBlocks(IndexMetaData indexMetaData) {
if (indexMetaData.getState() == IndexMetaData.State.CLOSE) {
- addIndexBlock(indexMetaData.getIndex(), MetaDataIndexStateService.INDEX_CLOSED_BLOCK);
+ addIndexBlock(indexMetaData.getIndex().getName(), MetaDataIndexStateService.INDEX_CLOSED_BLOCK);
}
if (IndexMetaData.INDEX_READ_ONLY_SETTING.get(indexMetaData.getSettings())) {
- addIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_READ_ONLY_BLOCK);
+ addIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_READ_ONLY_BLOCK);
}
if (IndexMetaData.INDEX_BLOCKS_READ_SETTING.get(indexMetaData.getSettings())) {
- addIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_READ_BLOCK);
+ addIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_READ_BLOCK);
}
if (IndexMetaData.INDEX_BLOCKS_WRITE_SETTING.get(indexMetaData.getSettings())) {
- addIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_WRITE_BLOCK);
+ addIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_WRITE_BLOCK);
}
if (IndexMetaData.INDEX_BLOCKS_METADATA_SETTING.get(indexMetaData.getSettings())) {
- addIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_METADATA_BLOCK);
+ addIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_METADATA_BLOCK);
}
return this;
}
public Builder updateBlocks(IndexMetaData indexMetaData) {
- removeIndexBlock(indexMetaData.getIndex(), MetaDataIndexStateService.INDEX_CLOSED_BLOCK);
- removeIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_READ_ONLY_BLOCK);
- removeIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_READ_BLOCK);
- removeIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_WRITE_BLOCK);
- removeIndexBlock(indexMetaData.getIndex(), IndexMetaData.INDEX_METADATA_BLOCK);
+ removeIndexBlock(indexMetaData.getIndex().getName(), MetaDataIndexStateService.INDEX_CLOSED_BLOCK);
+ removeIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_READ_ONLY_BLOCK);
+ removeIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_READ_BLOCK);
+ removeIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_WRITE_BLOCK);
+ removeIndexBlock(indexMetaData.getIndex().getName(), IndexMetaData.INDEX_METADATA_BLOCK);
return addBlocks(indexMetaData);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/health/ClusterIndexHealth.java b/core/src/main/java/org/elasticsearch/cluster/health/ClusterIndexHealth.java
index 3fd10fd91da..ce1f3adb539 100644
--- a/core/src/main/java/org/elasticsearch/cluster/health/ClusterIndexHealth.java
+++ b/core/src/main/java/org/elasticsearch/cluster/health/ClusterIndexHealth.java
@@ -67,7 +67,7 @@ public final class ClusterIndexHealth implements Iterable, S
}
public ClusterIndexHealth(IndexMetaData indexMetaData, IndexRoutingTable indexRoutingTable) {
- this.index = indexMetaData.getIndex();
+ this.index = indexMetaData.getIndex().getName();
this.numberOfShards = indexMetaData.getNumberOfShards();
this.numberOfReplicas = indexMetaData.getNumberOfReplicas();
this.validationFailures = indexRoutingTable.validate(indexMetaData);
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasOrIndex.java b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasOrIndex.java
index b8de2ea5256..4ad9b7e5317 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasOrIndex.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasOrIndex.java
@@ -117,7 +117,7 @@ public interface AliasOrIndex {
@Override
public Tuple next() {
IndexMetaData indexMetaData = referenceIndexMetaDatas.get(index++);
- return new Tuple<>(indexMetaData.getIndex(), indexMetaData.getAliases().get(aliasName));
+ return new Tuple<>(indexMetaData.getIndex().getName(), indexMetaData.getAliases().get(aliasName));
}
@Override
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java
index e5b170b05a6..091fde6dec8 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java
@@ -97,7 +97,7 @@ public class AliasValidator extends AbstractComponent {
assert metaData != null;
if (metaData.hasIndex(alias)) {
- throw new InvalidAliasNameException(new Index(index), alias, "an index exists with the same name as the alias");
+ throw new InvalidAliasNameException(metaData.index(alias).getIndex(), alias, "an index exists with the same name as the alias");
}
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java
index b2772c0b2c1..4fdd11c4dd4 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java
@@ -29,13 +29,11 @@ import org.elasticsearch.cluster.DiffableUtils;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.node.DiscoveryNodeFilters;
-import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.collect.ImmutableOpenIntMap;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.collect.MapBuilder;
-import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
@@ -47,6 +45,7 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.rest.RestStatus;
import org.joda.time.DateTime;
@@ -72,7 +71,7 @@ import static org.elasticsearch.common.settings.Settings.writeSettingsToStream;
/**
*
*/
-public class IndexMetaData implements Diffable, FromXContentBuilder, ToXContent {
+public class IndexMetaData implements Diffable, FromXContentBuilder, ToXContent {
public interface Custom extends Diffable, ToXContent {
@@ -150,6 +149,7 @@ public class IndexMetaData implements Diffable, FromXContentBuild
throw new IllegalStateException("No state match for [" + state + "]");
}
}
+
public static final String INDEX_SETTING_PREFIX = "index.";
public static final String SETTING_NUMBER_OF_SHARDS = "index.number_of_shards";
public static final Setting INDEX_NUMBER_OF_SHARDS_SETTING = Setting.intSetting(SETTING_NUMBER_OF_SHARDS, 5, 1, false, Setting.Scope.INDEX);
@@ -196,15 +196,15 @@ public class IndexMetaData implements Diffable, FromXContentBuild
public static final Setting INDEX_ROUTING_EXCLUDE_GROUP_SETTING = Setting.groupSetting("index.routing.allocation.exclude.", true, Setting.Scope.INDEX);
public static final IndexMetaData PROTO = IndexMetaData.builder("")
- .settings(Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT))
- .numberOfShards(1).numberOfReplicas(0).build();
+ .settings(Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT))
+ .numberOfShards(1).numberOfReplicas(0).build();
public static final String KEY_ACTIVE_ALLOCATIONS = "active_allocations";
private final int numberOfShards;
private final int numberOfReplicas;
- private final String index;
+ private final Index index;
private final long version;
private final State state;
@@ -229,7 +229,7 @@ public class IndexMetaData implements Diffable, FromXContentBuild
private final Version indexUpgradedVersion;
private final org.apache.lucene.util.Version minimumCompatibleLuceneVersion;
- private IndexMetaData(String index, long version, State state, int numberOfShards, int numberOfReplicas, Settings settings,
+ private IndexMetaData(Index index, long version, State state, int numberOfShards, int numberOfReplicas, Settings settings,
ImmutableOpenMap mappings, ImmutableOpenMap aliases,
ImmutableOpenMap customs, ImmutableOpenIntMap> activeAllocationIds,
DiscoveryNodeFilters requireFilters, DiscoveryNodeFilters includeFilters, DiscoveryNodeFilters excludeFilters,
@@ -254,12 +254,12 @@ public class IndexMetaData implements Diffable, FromXContentBuild
this.minimumCompatibleLuceneVersion = minimumCompatibleLuceneVersion;
}
- public String getIndex() {
+ public Index getIndex() {
return index;
}
public String getIndexUUID() {
- return settings.get(SETTING_INDEX_UUID, INDEX_UUID_NA_VALUE);
+ return index.getUUID();
}
/**
@@ -466,7 +466,7 @@ public class IndexMetaData implements Diffable, FromXContentBuild
private final Diff>> activeAllocationIds;
public IndexMetaDataDiff(IndexMetaData before, IndexMetaData after) {
- index = after.index;
+ index = after.index.getName();
version = after.version;
state = after.state;
settings = after.settings;
@@ -486,16 +486,16 @@ public class IndexMetaData implements Diffable, FromXContentBuild
aliases = DiffableUtils.readImmutableOpenMapDiff(in, DiffableUtils.getStringKeySerializer(), AliasMetaData.PROTO);
customs = DiffableUtils.readImmutableOpenMapDiff(in, DiffableUtils.getStringKeySerializer(),
new DiffableUtils.DiffableValueSerializer() {
- @Override
- public Custom read(StreamInput in, String key) throws IOException {
- return lookupPrototypeSafe(key).readFrom(in);
- }
+ @Override
+ public Custom read(StreamInput in, String key) throws IOException {
+ return lookupPrototypeSafe(key).readFrom(in);
+ }
- @Override
- public Diff readDiff(StreamInput in, String key) throws IOException {
- return lookupPrototypeSafe(key).readDiffFrom(in);
- }
- });
+ @Override
+ public Diff readDiff(StreamInput in, String key) throws IOException {
+ return lookupPrototypeSafe(key).readDiffFrom(in);
+ }
+ });
activeAllocationIds = DiffableUtils.readImmutableOpenIntMapDiff(in, DiffableUtils.getVIntKeySerializer(),
DiffableUtils.StringSetValueSerializer.getInstance());
}
@@ -559,7 +559,7 @@ public class IndexMetaData implements Diffable, FromXContentBuild
@Override
public void writeTo(StreamOutput out) throws IOException {
- out.writeString(index);
+ out.writeString(index.getName()); // uuid will come as part of settings
out.writeLong(version);
out.writeByte(state.id());
writeSettingsToStream(settings, out);
@@ -611,7 +611,7 @@ public class IndexMetaData implements Diffable, FromXContentBuild
}
public Builder(IndexMetaData indexMetaData) {
- this.index = indexMetaData.getIndex();
+ this.index = indexMetaData.getIndex().getName();
this.state = indexMetaData.state;
this.version = indexMetaData.version;
this.settings = indexMetaData.getSettings();
@@ -791,19 +791,20 @@ public class IndexMetaData implements Diffable, FromXContentBuild
try {
minimumCompatibleLuceneVersion = org.apache.lucene.util.Version.parse(stringLuceneVersion);
} catch (ParseException ex) {
- throw new IllegalStateException("Cannot parse lucene version [" + stringLuceneVersion + "] in the [" + SETTING_VERSION_MINIMUM_COMPATIBLE +"] setting", ex);
+ throw new IllegalStateException("Cannot parse lucene version [" + stringLuceneVersion + "] in the [" + SETTING_VERSION_MINIMUM_COMPATIBLE + "] setting", ex);
}
} else {
minimumCompatibleLuceneVersion = null;
}
- return new IndexMetaData(index, version, state, numberOfShards, numberOfReplicas, tmpSettings, mappings.build(),
+ final String uuid = settings.get(SETTING_INDEX_UUID, INDEX_UUID_NA_VALUE);
+ return new IndexMetaData(new Index(index, uuid), version, state, numberOfShards, numberOfReplicas, tmpSettings, mappings.build(),
tmpAliases.build(), customs.build(), filledActiveAllocationIds.build(), requireFilters, includeFilters, excludeFilters,
indexCreatedVersion, indexUpgradedVersion, minimumCompatibleLuceneVersion);
}
public static void toXContent(IndexMetaData indexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
- builder.startObject(indexMetaData.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
+ builder.startObject(indexMetaData.getIndex().getName(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("version", indexMetaData.getVersion());
builder.field("state", indexMetaData.getState().toString().toLowerCase(Locale.ENGLISH));
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java
index d2f3a47b754..0661f6c4362 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java
@@ -159,7 +159,7 @@ public class IndexNameExpressionResolver extends AbstractComponent {
String[] indexNames = new String[resolvedIndices.size()];
int i = 0;
for (IndexMetaData indexMetaData : resolvedIndices) {
- indexNames[i++] = indexMetaData.getIndex();
+ indexNames[i++] = indexMetaData.getIndex().getName();
}
throw new IllegalArgumentException("Alias [" + expression + "] has more than one indices associated with it [" + Arrays.toString(indexNames) + "], can't execute a single index op");
}
@@ -167,14 +167,14 @@ public class IndexNameExpressionResolver extends AbstractComponent {
for (IndexMetaData index : resolvedIndices) {
if (index.getState() == IndexMetaData.State.CLOSE) {
if (failClosed) {
- throw new IndexClosedException(new Index(index.getIndex()));
+ throw new IndexClosedException(index.getIndex());
} else {
if (options.forbidClosedIndices() == false) {
- concreteIndices.add(index.getIndex());
+ concreteIndices.add(index.getIndex().getName());
}
}
} else if (index.getState() == IndexMetaData.State.OPEN) {
- concreteIndices.add(index.getIndex());
+ concreteIndices.add(index.getIndex().getName());
} else {
throw new IllegalStateException("index state [" + index.getState() + "] not supported");
}
@@ -640,7 +640,7 @@ public class IndexNameExpressionResolver extends AbstractComponent {
} else {
for (IndexMetaData meta : aliasOrIndex.getIndices()) {
if (excludeState == null || meta.getState() != excludeState) {
- expand.add(meta.getIndex());
+ expand.add(meta.getIndex().getName());
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaData.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaData.java
index 0e41dda1888..9fb526b7408 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaData.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaData.java
@@ -50,6 +50,7 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.discovery.DiscoverySettings;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.store.IndexStoreConfig;
import org.elasticsearch.indices.recovery.RecoverySettings;
@@ -229,7 +230,7 @@ public class MetaData implements Iterable, Diffable, Fr
public boolean equalsAliases(MetaData other) {
for (ObjectCursor cursor : other.indices().values()) {
IndexMetaData otherIndex = cursor.value;
- IndexMetaData thisIndex= indices().get(otherIndex.getIndex());
+ IndexMetaData thisIndex= index(otherIndex.getIndex());
if (thisIndex == null) {
return false;
}
@@ -416,7 +417,7 @@ public class MetaData implements Iterable, Diffable, Fr
String[] indexNames = new String[result.getIndices().size()];
int i = 0;
for (IndexMetaData indexMetaData : result.getIndices()) {
- indexNames[i++] = indexMetaData.getIndex();
+ indexNames[i++] = indexMetaData.getIndex().getName();
}
throw new IllegalArgumentException("Alias [" + aliasOrIndex + "] has more than one index associated with it [" + Arrays.toString(indexNames) + "], can't execute a single index op");
}
@@ -451,6 +452,10 @@ public class MetaData implements Iterable, Diffable, Fr
return indices.get(index);
}
+ public IndexMetaData index(Index index) {
+ return index(index.getName());
+ }
+
public ImmutableOpenMap indices() {
return this.indices;
}
@@ -815,19 +820,19 @@ public class MetaData implements Iterable, Diffable, Fr
// we know its a new one, increment the version and store
indexMetaDataBuilder.version(indexMetaDataBuilder.version() + 1);
IndexMetaData indexMetaData = indexMetaDataBuilder.build();
- indices.put(indexMetaData.getIndex(), indexMetaData);
+ indices.put(indexMetaData.getIndex().getName(), indexMetaData);
return this;
}
public Builder put(IndexMetaData indexMetaData, boolean incrementVersion) {
- if (indices.get(indexMetaData.getIndex()) == indexMetaData) {
+ if (indices.get(indexMetaData.getIndex().getName()) == indexMetaData) {
return this;
}
// if we put a new index metadata, increment its version
if (incrementVersion) {
indexMetaData = IndexMetaData.builder(indexMetaData).version(indexMetaData.getVersion() + 1).build();
}
- indices.put(indexMetaData.getIndex(), indexMetaData);
+ indices.put(indexMetaData.getIndex().getName(), indexMetaData);
return this;
}
@@ -964,7 +969,7 @@ public class MetaData implements Iterable, Diffable, Fr
// do the required operations, the bottleneck isn't resolving expressions into concrete indices.
List allIndicesLst = new ArrayList<>();
for (ObjectCursor cursor : indices.values()) {
- allIndicesLst.add(cursor.value.getIndex());
+ allIndicesLst.add(cursor.value.getIndex().getName());
}
String[] allIndices = allIndicesLst.toArray(new String[allIndicesLst.size()]);
@@ -973,9 +978,9 @@ public class MetaData implements Iterable, Diffable, Fr
for (ObjectCursor cursor : indices.values()) {
IndexMetaData indexMetaData = cursor.value;
if (indexMetaData.getState() == IndexMetaData.State.OPEN) {
- allOpenIndicesLst.add(indexMetaData.getIndex());
+ allOpenIndicesLst.add(indexMetaData.getIndex().getName());
} else if (indexMetaData.getState() == IndexMetaData.State.CLOSE) {
- allClosedIndicesLst.add(indexMetaData.getIndex());
+ allClosedIndicesLst.add(indexMetaData.getIndex().getName());
}
}
String[] allOpenIndices = allOpenIndicesLst.toArray(new String[allOpenIndicesLst.size()]);
@@ -985,7 +990,7 @@ public class MetaData implements Iterable, Diffable, Fr
SortedMap aliasAndIndexLookup = new TreeMap<>();
for (ObjectCursor cursor : indices.values()) {
IndexMetaData indexMetaData = cursor.value;
- aliasAndIndexLookup.put(indexMetaData.getIndex(), new AliasOrIndex.Index(indexMetaData));
+ aliasAndIndexLookup.put(indexMetaData.getIndex().getName(), new AliasOrIndex.Index(indexMetaData));
for (ObjectObjectCursor aliasCursor : indexMetaData.getAliases()) {
AliasMetaData aliasMetaData = aliasCursor.value;
@@ -998,7 +1003,7 @@ public class MetaData implements Iterable, Diffable, Fr
alias.addIndex(indexMetaData);
} else if (aliasOrIndex instanceof AliasOrIndex.Index) {
AliasOrIndex.Index index = (AliasOrIndex.Index) aliasOrIndex;
- throw new IllegalStateException("index and alias names need to be unique, but alias [" + aliasMetaData.getAlias() + "] and index [" + index.getIndex().getIndex() + "] have the same name");
+ throw new IllegalStateException("index and alias names need to be unique, but alias [" + aliasMetaData.getAlias() + "] and index " + index.getIndex().getIndex() + " have the same name");
} else {
throw new IllegalStateException("unexpected alias [" + aliasMetaData.getAlias() + "][" + aliasOrIndex + "]");
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java
index 2344e9af77c..fbf3446b2dd 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java
@@ -137,22 +137,22 @@ public class MetaDataCreateIndexService extends AbstractComponent {
public void validateIndexName(String index, ClusterState state) {
if (state.routingTable().hasIndex(index)) {
- throw new IndexAlreadyExistsException(new Index(index));
+ throw new IndexAlreadyExistsException(state.routingTable().index(index).getIndex());
}
if (state.metaData().hasIndex(index)) {
- throw new IndexAlreadyExistsException(new Index(index));
+ throw new IndexAlreadyExistsException(state.metaData().index(index).getIndex());
}
if (!Strings.validFileName(index)) {
- throw new InvalidIndexNameException(new Index(index), index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
+ throw new InvalidIndexNameException(index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
}
if (index.contains("#")) {
- throw new InvalidIndexNameException(new Index(index), index, "must not contain '#'");
+ throw new InvalidIndexNameException(index, "must not contain '#'");
}
if (index.charAt(0) == '_') {
- throw new InvalidIndexNameException(new Index(index), index, "must not start with '_'");
+ throw new InvalidIndexNameException(index, "must not start with '_'");
}
if (!index.toLowerCase(Locale.ROOT).equals(index)) {
- throw new InvalidIndexNameException(new Index(index), index, "must be lowercase");
+ throw new InvalidIndexNameException(index, "must be lowercase");
}
int byteCount = 0;
try {
@@ -162,15 +162,15 @@ public class MetaDataCreateIndexService extends AbstractComponent {
throw new ElasticsearchException("Unable to determine length of index name", e);
}
if (byteCount > MAX_INDEX_NAME_BYTES) {
- throw new InvalidIndexNameException(new Index(index), index,
+ throw new InvalidIndexNameException(index,
"index name is too long, (" + byteCount +
- " > " + MAX_INDEX_NAME_BYTES + ")");
+ " > " + MAX_INDEX_NAME_BYTES + ")");
}
if (state.metaData().hasAlias(index)) {
- throw new InvalidIndexNameException(new Index(index), index, "already exists as alias");
+ throw new InvalidIndexNameException(index, "already exists as alias");
}
if (index.equals(".") || index.equals("..")) {
- throw new InvalidIndexNameException(new Index(index), index, "must not be '.' or '..'");
+ throw new InvalidIndexNameException(index, "must not be '.' or '..'");
}
}
@@ -187,242 +187,242 @@ public class MetaDataCreateIndexService extends AbstractComponent {
return new ClusterStateUpdateResponse(acknowledged);
}
- @Override
- public ClusterState execute(ClusterState currentState) throws Exception {
- boolean indexCreated = false;
- String removalReason = null;
- try {
- validate(request, currentState);
-
- for (Alias alias : request.aliases()) {
- aliasValidator.validateAlias(alias, request.index(), currentState.metaData());
- }
-
- // we only find a template when its an API call (a new index)
- // find templates, highest order are better matching
- List templates = findTemplates(request, currentState, indexTemplateFilter);
-
- Map customs = new HashMap<>();
-
- // add the request mapping
- Map> mappings = new HashMap<>();
-
- Map templatesAliases = new HashMap<>();
-
- List templateNames = new ArrayList<>();
-
- for (Map.Entry entry : request.mappings().entrySet()) {
- mappings.put(entry.getKey(), parseMapping(entry.getValue()));
- }
-
- for (Map.Entry entry : request.customs().entrySet()) {
- customs.put(entry.getKey(), entry.getValue());
- }
-
- // apply templates, merging the mappings into the request mapping if exists
- for (IndexTemplateMetaData template : templates) {
- templateNames.add(template.getName());
- for (ObjectObjectCursor cursor : template.mappings()) {
- if (mappings.containsKey(cursor.key)) {
- XContentHelper.mergeDefaults(mappings.get(cursor.key), parseMapping(cursor.value.string()));
- } else {
- mappings.put(cursor.key, parseMapping(cursor.value.string()));
- }
- }
- // handle custom
- for (ObjectObjectCursor cursor : template.customs()) {
- String type = cursor.key;
- IndexMetaData.Custom custom = cursor.value;
- IndexMetaData.Custom existing = customs.get(type);
- if (existing == null) {
- customs.put(type, custom);
- } else {
- IndexMetaData.Custom merged = existing.mergeWith(custom);
- customs.put(type, merged);
- }
- }
- //handle aliases
- for (ObjectObjectCursor cursor : template.aliases()) {
- AliasMetaData aliasMetaData = cursor.value;
- //if an alias with same name came with the create index request itself,
- // ignore this one taken from the index template
- if (request.aliases().contains(new Alias(aliasMetaData.alias()))) {
- continue;
- }
- //if an alias with same name was already processed, ignore this one
- if (templatesAliases.containsKey(cursor.key)) {
- continue;
- }
-
- //Allow templatesAliases to be templated by replacing a token with the name of the index that we are applying it to
- if (aliasMetaData.alias().contains("{index}")) {
- String templatedAlias = aliasMetaData.alias().replace("{index}", request.index());
- aliasMetaData = AliasMetaData.newAliasMetaData(aliasMetaData, templatedAlias);
- }
-
- aliasValidator.validateAliasMetaData(aliasMetaData, request.index(), currentState.metaData());
- templatesAliases.put(aliasMetaData.alias(), aliasMetaData);
- }
- }
-
- Settings.Builder indexSettingsBuilder = settingsBuilder();
- // apply templates, here, in reverse order, since first ones are better matching
- for (int i = templates.size() - 1; i >= 0; i--) {
- indexSettingsBuilder.put(templates.get(i).settings());
- }
- // now, put the request settings, so they override templates
- indexSettingsBuilder.put(request.settings());
- if (request.index().equals(ScriptService.SCRIPT_INDEX)) {
- indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 1));
- } else {
- if (indexSettingsBuilder.get(SETTING_NUMBER_OF_SHARDS) == null) {
- indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
- }
- }
- if (request.index().equals(ScriptService.SCRIPT_INDEX)) {
- indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 0));
- indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, "0-all");
- } else {
- if (indexSettingsBuilder.get(SETTING_NUMBER_OF_REPLICAS) == null) {
- indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
- }
- }
-
- if (settings.get(SETTING_AUTO_EXPAND_REPLICAS) != null && indexSettingsBuilder.get(SETTING_AUTO_EXPAND_REPLICAS) == null) {
- indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, settings.get(SETTING_AUTO_EXPAND_REPLICAS));
- }
-
- if (indexSettingsBuilder.get(SETTING_VERSION_CREATED) == null) {
- DiscoveryNodes nodes = currentState.nodes();
- final Version createdVersion = Version.smallest(version, nodes.smallestNonClientNodeVersion());
- indexSettingsBuilder.put(SETTING_VERSION_CREATED, createdVersion);
- }
-
- if (indexSettingsBuilder.get(SETTING_CREATION_DATE) == null) {
- indexSettingsBuilder.put(SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis());
- }
-
- indexSettingsBuilder.put(SETTING_INDEX_UUID, Strings.randomBase64UUID());
-
- Settings actualIndexSettings = indexSettingsBuilder.build();
-
- // Set up everything, now locally create the index to see that things are ok, and apply
- final IndexMetaData tmpImd = IndexMetaData.builder(request.index()).settings(actualIndexSettings).build();
- // create the index here (on the master) to validate it can be created, as well as adding the mapping
- indicesService.createIndex(nodeServicesProvider, tmpImd, Collections.emptyList());
- indexCreated = true;
- // now add the mappings
- IndexService indexService = indicesService.indexServiceSafe(request.index());
- MapperService mapperService = indexService.mapperService();
- // first, add the default mapping
- if (mappings.containsKey(MapperService.DEFAULT_MAPPING)) {
+ @Override
+ public ClusterState execute(ClusterState currentState) throws Exception {
+ boolean indexCreated = false;
+ String removalReason = null;
try {
- mapperService.merge(MapperService.DEFAULT_MAPPING, new CompressedXContent(XContentFactory.jsonBuilder().map(mappings.get(MapperService.DEFAULT_MAPPING)).string()), MapperService.MergeReason.MAPPING_UPDATE, request.updateAllTypes());
- } catch (Exception e) {
- removalReason = "failed on parsing default mapping on index creation";
- throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, MapperService.DEFAULT_MAPPING, e.getMessage());
+ validate(request, currentState);
+
+ for (Alias alias : request.aliases()) {
+ aliasValidator.validateAlias(alias, request.index(), currentState.metaData());
+ }
+
+ // we only find a template when its an API call (a new index)
+ // find templates, highest order are better matching
+ List templates = findTemplates(request, currentState, indexTemplateFilter);
+
+ Map customs = new HashMap<>();
+
+ // add the request mapping
+ Map> mappings = new HashMap<>();
+
+ Map templatesAliases = new HashMap<>();
+
+ List templateNames = new ArrayList<>();
+
+ for (Map.Entry entry : request.mappings().entrySet()) {
+ mappings.put(entry.getKey(), parseMapping(entry.getValue()));
+ }
+
+ for (Map.Entry entry : request.customs().entrySet()) {
+ customs.put(entry.getKey(), entry.getValue());
+ }
+
+ // apply templates, merging the mappings into the request mapping if exists
+ for (IndexTemplateMetaData template : templates) {
+ templateNames.add(template.getName());
+ for (ObjectObjectCursor cursor : template.mappings()) {
+ if (mappings.containsKey(cursor.key)) {
+ XContentHelper.mergeDefaults(mappings.get(cursor.key), parseMapping(cursor.value.string()));
+ } else {
+ mappings.put(cursor.key, parseMapping(cursor.value.string()));
+ }
+ }
+ // handle custom
+ for (ObjectObjectCursor cursor : template.customs()) {
+ String type = cursor.key;
+ IndexMetaData.Custom custom = cursor.value;
+ IndexMetaData.Custom existing = customs.get(type);
+ if (existing == null) {
+ customs.put(type, custom);
+ } else {
+ IndexMetaData.Custom merged = existing.mergeWith(custom);
+ customs.put(type, merged);
+ }
+ }
+ //handle aliases
+ for (ObjectObjectCursor cursor : template.aliases()) {
+ AliasMetaData aliasMetaData = cursor.value;
+ //if an alias with same name came with the create index request itself,
+ // ignore this one taken from the index template
+ if (request.aliases().contains(new Alias(aliasMetaData.alias()))) {
+ continue;
+ }
+ //if an alias with same name was already processed, ignore this one
+ if (templatesAliases.containsKey(cursor.key)) {
+ continue;
+ }
+
+ //Allow templatesAliases to be templated by replacing a token with the name of the index that we are applying it to
+ if (aliasMetaData.alias().contains("{index}")) {
+ String templatedAlias = aliasMetaData.alias().replace("{index}", request.index());
+ aliasMetaData = AliasMetaData.newAliasMetaData(aliasMetaData, templatedAlias);
+ }
+
+ aliasValidator.validateAliasMetaData(aliasMetaData, request.index(), currentState.metaData());
+ templatesAliases.put(aliasMetaData.alias(), aliasMetaData);
+ }
+ }
+
+ Settings.Builder indexSettingsBuilder = settingsBuilder();
+ // apply templates, here, in reverse order, since first ones are better matching
+ for (int i = templates.size() - 1; i >= 0; i--) {
+ indexSettingsBuilder.put(templates.get(i).settings());
+ }
+ // now, put the request settings, so they override templates
+ indexSettingsBuilder.put(request.settings());
+ if (request.index().equals(ScriptService.SCRIPT_INDEX)) {
+ indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 1));
+ } else {
+ if (indexSettingsBuilder.get(SETTING_NUMBER_OF_SHARDS) == null) {
+ indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
+ }
+ }
+ if (request.index().equals(ScriptService.SCRIPT_INDEX)) {
+ indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 0));
+ indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, "0-all");
+ } else {
+ if (indexSettingsBuilder.get(SETTING_NUMBER_OF_REPLICAS) == null) {
+ indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
+ }
+ }
+
+ if (settings.get(SETTING_AUTO_EXPAND_REPLICAS) != null && indexSettingsBuilder.get(SETTING_AUTO_EXPAND_REPLICAS) == null) {
+ indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, settings.get(SETTING_AUTO_EXPAND_REPLICAS));
+ }
+
+ if (indexSettingsBuilder.get(SETTING_VERSION_CREATED) == null) {
+ DiscoveryNodes nodes = currentState.nodes();
+ final Version createdVersion = Version.smallest(version, nodes.smallestNonClientNodeVersion());
+ indexSettingsBuilder.put(SETTING_VERSION_CREATED, createdVersion);
+ }
+
+ if (indexSettingsBuilder.get(SETTING_CREATION_DATE) == null) {
+ indexSettingsBuilder.put(SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis());
+ }
+
+ indexSettingsBuilder.put(SETTING_INDEX_UUID, Strings.randomBase64UUID());
+
+ Settings actualIndexSettings = indexSettingsBuilder.build();
+
+ // Set up everything, now locally create the index to see that things are ok, and apply
+ final IndexMetaData tmpImd = IndexMetaData.builder(request.index()).settings(actualIndexSettings).build();
+ // create the index here (on the master) to validate it can be created, as well as adding the mapping
+ indicesService.createIndex(nodeServicesProvider, tmpImd, Collections.emptyList());
+ indexCreated = true;
+ // now add the mappings
+ IndexService indexService = indicesService.indexServiceSafe(request.index());
+ MapperService mapperService = indexService.mapperService();
+ // first, add the default mapping
+ if (mappings.containsKey(MapperService.DEFAULT_MAPPING)) {
+ try {
+ mapperService.merge(MapperService.DEFAULT_MAPPING, new CompressedXContent(XContentFactory.jsonBuilder().map(mappings.get(MapperService.DEFAULT_MAPPING)).string()), MapperService.MergeReason.MAPPING_UPDATE, request.updateAllTypes());
+ } catch (Exception e) {
+ removalReason = "failed on parsing default mapping on index creation";
+ throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, MapperService.DEFAULT_MAPPING, e.getMessage());
+ }
+ }
+ for (Map.Entry> entry : mappings.entrySet()) {
+ if (entry.getKey().equals(MapperService.DEFAULT_MAPPING)) {
+ continue;
+ }
+ try {
+ // apply the default here, its the first time we parse it
+ mapperService.merge(entry.getKey(), new CompressedXContent(XContentFactory.jsonBuilder().map(entry.getValue()).string()), MapperService.MergeReason.MAPPING_UPDATE, request.updateAllTypes());
+ } catch (Exception e) {
+ removalReason = "failed on parsing mappings on index creation";
+ throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, entry.getKey(), e.getMessage());
+ }
+ }
+
+ QueryShardContext queryShardContext = indexService.getQueryShardContext();
+ for (Alias alias : request.aliases()) {
+ if (Strings.hasLength(alias.filter())) {
+ aliasValidator.validateAliasFilter(alias.name(), alias.filter(), queryShardContext);
+ }
+ }
+ for (AliasMetaData aliasMetaData : templatesAliases.values()) {
+ if (aliasMetaData.filter() != null) {
+ aliasValidator.validateAliasFilter(aliasMetaData.alias(), aliasMetaData.filter().uncompressed(), queryShardContext);
+ }
+ }
+
+ // now, update the mappings with the actual source
+ Map mappingsMetaData = new HashMap<>();
+ for (DocumentMapper mapper : mapperService.docMappers(true)) {
+ MappingMetaData mappingMd = new MappingMetaData(mapper);
+ mappingsMetaData.put(mapper.type(), mappingMd);
+ }
+
+ final IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(request.index()).settings(actualIndexSettings);
+ for (MappingMetaData mappingMd : mappingsMetaData.values()) {
+ indexMetaDataBuilder.putMapping(mappingMd);
+ }
+
+ for (AliasMetaData aliasMetaData : templatesAliases.values()) {
+ indexMetaDataBuilder.putAlias(aliasMetaData);
+ }
+ for (Alias alias : request.aliases()) {
+ AliasMetaData aliasMetaData = AliasMetaData.builder(alias.name()).filter(alias.filter())
+ .indexRouting(alias.indexRouting()).searchRouting(alias.searchRouting()).build();
+ indexMetaDataBuilder.putAlias(aliasMetaData);
+ }
+
+ for (Map.Entry customEntry : customs.entrySet()) {
+ indexMetaDataBuilder.putCustom(customEntry.getKey(), customEntry.getValue());
+ }
+
+ indexMetaDataBuilder.state(request.state());
+
+ final IndexMetaData indexMetaData;
+ try {
+ indexMetaData = indexMetaDataBuilder.build();
+ } catch (Exception e) {
+ removalReason = "failed to build index metadata";
+ throw e;
+ }
+
+ indexService.getIndexEventListener().beforeIndexAddedToCluster(indexMetaData.getIndex(),
+ indexMetaData.getSettings());
+
+ MetaData newMetaData = MetaData.builder(currentState.metaData())
+ .put(indexMetaData, false)
+ .build();
+
+ String maybeShadowIndicator = IndexMetaData.isIndexUsingShadowReplicas(indexMetaData.getSettings()) ? "s" : "";
+ logger.info("[{}] creating index, cause [{}], templates {}, shards [{}]/[{}{}], mappings {}",
+ request.index(), request.cause(), templateNames, indexMetaData.getNumberOfShards(),
+ indexMetaData.getNumberOfReplicas(), maybeShadowIndicator, mappings.keySet());
+
+ ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
+ if (!request.blocks().isEmpty()) {
+ for (ClusterBlock block : request.blocks()) {
+ blocks.addIndexBlock(request.index(), block);
+ }
+ }
+ blocks.updateBlocks(indexMetaData);
+
+ ClusterState updatedState = ClusterState.builder(currentState).blocks(blocks).metaData(newMetaData).build();
+
+ if (request.state() == State.OPEN) {
+ RoutingTable.Builder routingTableBuilder = RoutingTable.builder(updatedState.routingTable())
+ .addAsNew(updatedState.metaData().index(request.index()));
+ RoutingAllocation.Result routingResult = allocationService.reroute(
+ ClusterState.builder(updatedState).routingTable(routingTableBuilder.build()).build(),
+ "index [" + request.index() + "] created");
+ updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build();
+ }
+ removalReason = "cleaning up after validating index on master";
+ return updatedState;
+ } finally {
+ if (indexCreated) {
+ // Index was already partially created - need to clean up
+ indicesService.removeIndex(request.index(), removalReason != null ? removalReason : "failed to create index");
+ }
}
}
- for (Map.Entry> entry : mappings.entrySet()) {
- if (entry.getKey().equals(MapperService.DEFAULT_MAPPING)) {
- continue;
- }
- try {
- // apply the default here, its the first time we parse it
- mapperService.merge(entry.getKey(), new CompressedXContent(XContentFactory.jsonBuilder().map(entry.getValue()).string()), MapperService.MergeReason.MAPPING_UPDATE, request.updateAllTypes());
- } catch (Exception e) {
- removalReason = "failed on parsing mappings on index creation";
- throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, entry.getKey(), e.getMessage());
- }
- }
-
- QueryShardContext queryShardContext = indexService.getQueryShardContext();
- for (Alias alias : request.aliases()) {
- if (Strings.hasLength(alias.filter())) {
- aliasValidator.validateAliasFilter(alias.name(), alias.filter(), queryShardContext);
- }
- }
- for (AliasMetaData aliasMetaData : templatesAliases.values()) {
- if (aliasMetaData.filter() != null) {
- aliasValidator.validateAliasFilter(aliasMetaData.alias(), aliasMetaData.filter().uncompressed(), queryShardContext);
- }
- }
-
- // now, update the mappings with the actual source
- Map mappingsMetaData = new HashMap<>();
- for (DocumentMapper mapper : mapperService.docMappers(true)) {
- MappingMetaData mappingMd = new MappingMetaData(mapper);
- mappingsMetaData.put(mapper.type(), mappingMd);
- }
-
- final IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(request.index()).settings(actualIndexSettings);
- for (MappingMetaData mappingMd : mappingsMetaData.values()) {
- indexMetaDataBuilder.putMapping(mappingMd);
- }
-
- for (AliasMetaData aliasMetaData : templatesAliases.values()) {
- indexMetaDataBuilder.putAlias(aliasMetaData);
- }
- for (Alias alias : request.aliases()) {
- AliasMetaData aliasMetaData = AliasMetaData.builder(alias.name()).filter(alias.filter())
- .indexRouting(alias.indexRouting()).searchRouting(alias.searchRouting()).build();
- indexMetaDataBuilder.putAlias(aliasMetaData);
- }
-
- for (Map.Entry customEntry : customs.entrySet()) {
- indexMetaDataBuilder.putCustom(customEntry.getKey(), customEntry.getValue());
- }
-
- indexMetaDataBuilder.state(request.state());
-
- final IndexMetaData indexMetaData;
- try {
- indexMetaData = indexMetaDataBuilder.build();
- } catch (Exception e) {
- removalReason = "failed to build index metadata";
- throw e;
- }
-
- indexService.getIndexEventListener().beforeIndexAddedToCluster(new Index(request.index()),
- indexMetaData.getSettings());
-
- MetaData newMetaData = MetaData.builder(currentState.metaData())
- .put(indexMetaData, false)
- .build();
-
- String maybeShadowIndicator = IndexMetaData.isIndexUsingShadowReplicas(indexMetaData.getSettings()) ? "s" : "";
- logger.info("[{}] creating index, cause [{}], templates {}, shards [{}]/[{}{}], mappings {}",
- request.index(), request.cause(), templateNames, indexMetaData.getNumberOfShards(),
- indexMetaData.getNumberOfReplicas(), maybeShadowIndicator, mappings.keySet());
-
- ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
- if (!request.blocks().isEmpty()) {
- for (ClusterBlock block : request.blocks()) {
- blocks.addIndexBlock(request.index(), block);
- }
- }
- blocks.updateBlocks(indexMetaData);
-
- ClusterState updatedState = ClusterState.builder(currentState).blocks(blocks).metaData(newMetaData).build();
-
- if (request.state() == State.OPEN) {
- RoutingTable.Builder routingTableBuilder = RoutingTable.builder(updatedState.routingTable())
- .addAsNew(updatedState.metaData().index(request.index()));
- RoutingAllocation.Result routingResult = allocationService.reroute(
- ClusterState.builder(updatedState).routingTable(routingTableBuilder.build()).build(),
- "index [" + request.index() + "] created");
- updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build();
- }
- removalReason = "cleaning up after validating index on master";
- return updatedState;
- } finally {
- if (indexCreated) {
- // Index was already partially created - need to clean up
- indicesService.removeIndex(request.index(), removalReason != null ? removalReason : "failed to create index");
- }
- }
- }
- });
+ });
}
private Map parseMapping(String mappingSource) throws Exception {
@@ -459,7 +459,7 @@ public class MetaDataCreateIndexService extends AbstractComponent {
if (validationErrors.isEmpty() == false) {
ValidationException validationException = new ValidationException();
validationException.addValidationErrors(validationErrors);
- throw new IndexCreationException(new Index(indexName), validationException);
+ throw new IndexCreationException(indexName, validationException);
}
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesService.java
index 1e9f968f7a6..fe53f206b19 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesService.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesService.java
@@ -112,9 +112,9 @@ public class MetaDataIndexAliasesService extends AbstractComponent {
logger.warn("[{}] failed to temporary create in order to apply alias action", e, indexMetaData.getIndex());
continue;
}
- indicesToClose.add(indexMetaData.getIndex());
+ indicesToClose.add(indexMetaData.getIndex().getName());
}
- indices.put(indexMetaData.getIndex(), indexService);
+ indices.put(indexMetaData.getIndex().getName(), indexService);
}
aliasValidator.validateAliasFilter(aliasAction.alias(), filter, indexService.getQueryShardContext());
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java
index 1d13fc2079e..a86d65779b4 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java
@@ -169,7 +169,7 @@ public class MetaDataMappingService extends AbstractComponent {
private boolean refreshIndexMapping(IndexService indexService, IndexMetaData.Builder builder) {
boolean dirty = false;
- String index = indexService.index().name();
+ String index = indexService.index().getName();
try {
List updatedTypes = new ArrayList<>();
for (DocumentMapper mapper : indexService.mapperService().docMappers(true)) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java
index 8e9dbc6b673..2d7ba4c3c05 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java
@@ -117,7 +117,7 @@ public class MetaDataUpdateSettingsService extends AbstractComponent implements
nrReplicasChanged.put(numberOfReplicas, new ArrayList<>());
}
- nrReplicasChanged.get(numberOfReplicas).add(indexMetaData.getIndex());
+ nrReplicasChanged.get(numberOfReplicas).add(indexMetaData.getIndex().getName());
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/IndexRoutingTable.java b/core/src/main/java/org/elasticsearch/cluster/routing/IndexRoutingTable.java
index bb186a64a8c..2778d287975 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/IndexRoutingTable.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/IndexRoutingTable.java
@@ -30,12 +30,12 @@ import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.collect.ImmutableOpenIntMap;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@@ -58,9 +58,9 @@ import java.util.Set;
*/
public class IndexRoutingTable extends AbstractDiffable implements Iterable {
- public static final IndexRoutingTable PROTO = builder("").build();
+ public static final IndexRoutingTable PROTO = builder(new Index("", "_na_")).build();
- private final String index;
+ private final Index index;
private final ShardShuffler shuffler;
// note, we assume that when the index routing is created, ShardRoutings are created for all possible number of
@@ -69,7 +69,7 @@ public class IndexRoutingTable extends AbstractDiffable imple
private final List allActiveShards;
- IndexRoutingTable(String index, ImmutableOpenIntMap shards) {
+ IndexRoutingTable(Index index, ImmutableOpenIntMap shards) {
this.index = index;
this.shuffler = new RotationShardShuffler(Randomness.get().nextInt());
this.shards = shards;
@@ -90,18 +90,8 @@ public class IndexRoutingTable extends AbstractDiffable imple
*
* @return id of the index
*/
- public String index() {
- return this.index;
- }
-
-
- /**
- * Return the index id
- *
- * @return id of the index
- */
- public String getIndex() {
- return index();
+ public Index getIndex() {
+ return index;
}
/**
@@ -118,13 +108,17 @@ public class IndexRoutingTable extends AbstractDiffable imple
}
public void validate(RoutingTableValidation validation, MetaData metaData) {
- if (!metaData.hasIndex(index())) {
- validation.addIndexFailure(index(), "Exists in routing does not exists in metadata");
+ if (!metaData.hasIndex(index.getName())) {
+ validation.addIndexFailure(index.getName(), "Exists in routing does not exists in metadata");
+ return;
+ }
+ IndexMetaData indexMetaData = metaData.index(index.getName());
+ if (indexMetaData.getIndexUUID().equals(index.getUUID()) == false) {
+ validation.addIndexFailure(index.getName(), "Exists in routing does not exists in metadata with the same uuid");
return;
}
- IndexMetaData indexMetaData = metaData.index(index());
for (String failure : validate(indexMetaData)) {
- validation.addIndexFailure(index, failure);
+ validation.addIndexFailure(index.getName(), failure);
}
}
@@ -154,7 +148,7 @@ public class IndexRoutingTable extends AbstractDiffable imple
+ "] routing table has wrong number of replicas, expected [" + indexMetaData.getNumberOfReplicas() + "], got [" + routingNumberOfReplicas + "]");
}
for (ShardRouting shardRouting : indexShardRoutingTable) {
- if (!shardRouting.index().equals(index())) {
+ if (!shardRouting.index().equals(index)) {
failures.add("shard routing has an index [" + shardRouting.index() + "] that is different than the routing table");
}
}
@@ -332,7 +326,7 @@ public class IndexRoutingTable extends AbstractDiffable imple
@Override
public IndexRoutingTable readFrom(StreamInput in) throws IOException {
- String index = in.readString();
+ Index index = Index.readIndex(in);
Builder builder = new Builder(index);
int size = in.readVInt();
@@ -345,23 +339,23 @@ public class IndexRoutingTable extends AbstractDiffable imple
@Override
public void writeTo(StreamOutput out) throws IOException {
- out.writeString(index);
+ index.writeTo(out);
out.writeVInt(shards.size());
for (IndexShardRoutingTable indexShard : this) {
IndexShardRoutingTable.Builder.writeToThin(indexShard, out);
}
}
- public static Builder builder(String index) {
+ public static Builder builder(Index index) {
return new Builder(index);
}
public static class Builder {
- private final String index;
+ private final Index index;
private final ImmutableOpenIntMap.Builder shards = ImmutableOpenIntMap.builder();
- public Builder(String index) {
+ public Builder(Index index) {
this.index = index;
}
@@ -422,11 +416,12 @@ public class IndexRoutingTable extends AbstractDiffable imple
* Initializes an index, to be restored from snapshot
*/
private Builder initializeAsRestore(IndexMetaData indexMetaData, RestoreSource restoreSource, IntSet ignoreShards, boolean asNew, UnassignedInfo unassignedInfo) {
+ assert indexMetaData.getIndex().equals(index);
if (!shards.isEmpty()) {
throw new IllegalStateException("trying to initialize an index with fresh shards, but already has shards created");
}
for (int shardId = 0; shardId < indexMetaData.getNumberOfShards(); shardId++) {
- IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(new ShardId(indexMetaData.getIndex(), shardId));
+ IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(new ShardId(index, shardId));
for (int i = 0; i <= indexMetaData.getNumberOfReplicas(); i++) {
if (asNew && ignoreShards.contains(shardId)) {
// This shards wasn't completely snapshotted - restore it as new shard
@@ -444,11 +439,12 @@ public class IndexRoutingTable extends AbstractDiffable imple
* Initializes a new empty index, with an option to control if its from an API or not.
*/
private Builder initializeEmpty(IndexMetaData indexMetaData, UnassignedInfo unassignedInfo) {
+ assert indexMetaData.getIndex().equals(index);
if (!shards.isEmpty()) {
throw new IllegalStateException("trying to initialize an index with fresh shards, but already has shards created");
}
for (int shardId = 0; shardId < indexMetaData.getNumberOfShards(); shardId++) {
- IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(new ShardId(indexMetaData.getIndex(), shardId));
+ IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(new ShardId(index, shardId));
for (int i = 0; i <= indexMetaData.getNumberOfReplicas(); i++) {
indexShardRoutingBuilder.addShard(ShardRouting.newUnassigned(index, shardId, null, i == 0, unassignedInfo));
}
@@ -539,21 +535,18 @@ public class IndexRoutingTable extends AbstractDiffable imple
ordered.add(indexShard);
}
- CollectionUtil.timSort(ordered, new Comparator() {
- @Override
- public int compare(IndexShardRoutingTable o1, IndexShardRoutingTable o2) {
- int v = o1.shardId().index().name().compareTo(
- o2.shardId().index().name());
- if (v == 0) {
- v = Integer.compare(o1.shardId().id(),
- o2.shardId().id());
- }
- return v;
+ CollectionUtil.timSort(ordered, (o1, o2) -> {
+ int v = o1.shardId().getIndex().getName().compareTo(
+ o2.shardId().getIndex().getName());
+ if (v == 0) {
+ v = Integer.compare(o1.shardId().id(),
+ o2.shardId().id());
}
+ return v;
});
for (IndexShardRoutingTable indexShard : ordered) {
- sb.append("----shard_id [").append(indexShard.shardId().index().name()).append("][").append(indexShard.shardId().id()).append("]\n");
+ sb.append("----shard_id [").append(indexShard.shardId().getIndex().getName()).append("][").append(indexShard.shardId().id()).append("]\n");
for (ShardRouting shard : indexShard) {
sb.append("--------").append(shard.shortSummary()).append("\n");
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java b/core/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java
index bcdb7a43fef..d5169428450 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java
@@ -26,6 +26,7 @@ import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.util.set.Sets;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
@@ -617,11 +618,11 @@ public class IndexShardRoutingTable implements Iterable {
}
public static IndexShardRoutingTable readFrom(StreamInput in) throws IOException {
- String index = in.readString();
+ Index index = Index.readIndex(in);
return readFromThin(in, index);
}
- public static IndexShardRoutingTable readFromThin(StreamInput in, String index) throws IOException {
+ public static IndexShardRoutingTable readFromThin(StreamInput in, Index index) throws IOException {
int iShardId = in.readVInt();
Builder builder = new Builder(new ShardId(index, iShardId));
@@ -635,7 +636,7 @@ public class IndexShardRoutingTable implements Iterable {
}
public static void writeTo(IndexShardRoutingTable indexShard, StreamOutput out) throws IOException {
- out.writeString(indexShard.shardId().index().name());
+ out.writeString(indexShard.shardId().getIndex().getName());
writeToThin(indexShard, out);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/OperationRouting.java b/core/src/main/java/org/elasticsearch/cluster/routing/OperationRouting.java
index 267dae80d55..184db017c10 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/OperationRouting.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/OperationRouting.java
@@ -29,6 +29,7 @@ import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.math.MathUtils;
import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardNotFoundException;
@@ -95,13 +96,14 @@ public class OperationRouting extends AbstractComponent {
// we use set here and not list since we might get duplicates
for (String index : concreteIndices) {
final IndexRoutingTable indexRouting = indexRoutingTable(clusterState, index);
+ final IndexMetaData indexMetaData = indexMetaData(clusterState, index);
final Set effectiveRouting = routing.get(index);
if (effectiveRouting != null) {
for (String r : effectiveRouting) {
- int shardId = generateShardId(clusterState, index, null, r);
+ int shardId = generateShardId(indexMetaData, null, r);
IndexShardRoutingTable indexShard = indexRouting.shard(shardId);
if (indexShard == null) {
- throw new ShardNotFoundException(new ShardId(index, shardId));
+ throw new ShardNotFoundException(new ShardId(indexRouting.getIndex(), shardId));
}
// we might get duplicates, but that's ok, they will override one another
set.add(indexShard);
@@ -204,20 +206,25 @@ public class OperationRouting extends AbstractComponent {
return indexRouting;
}
- protected IndexShardRoutingTable shards(ClusterState clusterState, String index, String id, String routing) {
- int shardId = generateShardId(clusterState, index, id, routing);
- return clusterState.getRoutingTable().shardRoutingTable(index, shardId);
- }
-
- public ShardId shardId(ClusterState clusterState, String index, String id, @Nullable String routing) {
- return new ShardId(index, generateShardId(clusterState, index, id, routing));
- }
-
- private int generateShardId(ClusterState clusterState, String index, String id, @Nullable String routing) {
+ protected IndexMetaData indexMetaData(ClusterState clusterState, String index) {
IndexMetaData indexMetaData = clusterState.metaData().index(index);
if (indexMetaData == null) {
throw new IndexNotFoundException(index);
}
+ return indexMetaData;
+ }
+
+ protected IndexShardRoutingTable shards(ClusterState clusterState, String index, String id, String routing) {
+ int shardId = generateShardId(indexMetaData(clusterState, index), id, routing);
+ return clusterState.getRoutingTable().shardRoutingTable(index, shardId);
+ }
+
+ public ShardId shardId(ClusterState clusterState, String index, String id, @Nullable String routing) {
+ IndexMetaData indexMetaData = indexMetaData(clusterState, index);
+ return new ShardId(indexMetaData.getIndex(), generateShardId(indexMetaData, id, routing));
+ }
+
+ private int generateShardId(IndexMetaData indexMetaData, String id, @Nullable String routing) {
final int hash;
if (routing == null) {
hash = Murmur3HashFunction.hash(id);
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNode.java b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNode.java
index ff6c8293420..77ae7b41d91 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNode.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNode.java
@@ -87,7 +87,7 @@ public class RoutingNode implements Iterable {
// TODO use Set with ShardIds for faster lookup.
for (ShardRouting shardRouting : shards) {
if (shardRouting.isSameShard(shard)) {
- throw new IllegalStateException("Trying to add a shard [" + shard.shardId().index().name() + "][" + shard.shardId().id() + "] to a node [" + nodeId + "] where it already exists");
+ throw new IllegalStateException("Trying to add a shard [" + shard.shardId().getIndex().getName() + "][" + shard.shardId().id() + "] to a node [" + nodeId + "] where it already exists");
}
}
shards.add(shard);
@@ -137,7 +137,7 @@ public class RoutingNode implements Iterable {
List shards = new ArrayList<>();
for (ShardRouting shardEntry : this) {
- if (!shardEntry.index().equals(index)) {
+ if (!shardEntry.getIndexName().equals(index)) {
continue;
}
for (ShardRoutingState state : states) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java
index 3a2567e3f46..6a6373f977d 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java
@@ -28,6 +28,7 @@ import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.collect.ImmutableOpenMap;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import java.util.ArrayList;
@@ -169,7 +170,7 @@ public class RoutingNodes implements Iterable {
} else if (routing.primary() == false) { // primary without relocationID is initial recovery
ShardRouting primary = findPrimary(routing);
if (primary == null && initializing) {
- primary = routingTable.index(routing.index()).shard(routing.shardId().id()).primary;
+ primary = routingTable.index(routing.index().getName()).shard(routing.shardId().id()).primary;
} else if (primary == null) {
throw new IllegalStateException("replica is initializing but primary is unassigned");
}
@@ -348,7 +349,7 @@ public class RoutingNodes implements Iterable {
*/
public boolean allReplicasActive(ShardRouting shardRouting) {
final List shards = assignedShards(shardRouting.shardId());
- if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index()).shard(shardRouting.id()).size()) {
+ if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index().getName()).shard(shardRouting.id()).size()) {
return false; // if we are empty nothing is active if we have less than total at least one is unassigned
}
for (ShardRouting shard : shards) {
@@ -778,7 +779,7 @@ public class RoutingNodes implements Iterable {
int inactivePrimaryCount = 0;
int inactiveShardCount = 0;
int relocating = 0;
- Map indicesAndShards = new HashMap<>();
+ Map indicesAndShards = new HashMap<>();
for (RoutingNode node : routingNodes) {
for (ShardRouting shard : node) {
if (!shard.active() && shard.relocatingNodeId() == null) {
@@ -800,10 +801,10 @@ public class RoutingNodes implements Iterable {
}
}
// Assert that the active shard routing are identical.
- Set> entries = indicesAndShards.entrySet();
+ Set> entries = indicesAndShards.entrySet();
final List shards = new ArrayList<>();
- for (Map.Entry e : entries) {
- String index = e.getKey();
+ for (Map.Entry e : entries) {
+ Index index = e.getKey();
for (int i = 0; i < e.getValue(); i++) {
for (RoutingNode routingNode : routingNodes) {
for (ShardRouting shardRouting : routingNode) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingTable.java b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingTable.java
index 4bf196d07d0..6d81556eb2c 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingTable.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingTable.java
@@ -31,6 +31,7 @@ import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.util.iterable.Iterables;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardNotFoundException;
@@ -88,6 +89,10 @@ public class RoutingTable implements Iterable, Diffable indicesRouting() {
return indicesRouting;
}
@@ -109,7 +114,7 @@ public class RoutingTable implements Iterable, Diffable, Diffable, Diffable, Diffable, Diffable shardRoutingEntries = Iterables.concat(routingNodes.unassigned(), routingNodes.unassigned().ignored());
for (ShardRouting shardRoutingEntry : shardRoutingEntries) {
- String index = shardRoutingEntry.index();
- IndexRoutingTable.Builder indexBuilder = indexRoutingTableBuilders.get(index);
+ Index index = shardRoutingEntry.index();
+ IndexRoutingTable.Builder indexBuilder = indexRoutingTableBuilders.get(index.getName());
if (indexBuilder == null) {
indexBuilder = new IndexRoutingTable.Builder(index);
- indexRoutingTableBuilders.put(index, indexBuilder);
+ indexRoutingTableBuilders.put(index.getName(), indexBuilder);
}
- IndexShardRoutingTable refData = routingNodes.routingTable().index(shardRoutingEntry.index()).shard(shardRoutingEntry.id());
+ IndexShardRoutingTable refData = routingNodes.routingTable().index(shardRoutingEntry.index().getName()).shard(shardRoutingEntry.id());
indexBuilder.addShard(refData, shardRoutingEntry);
}
@@ -446,7 +459,7 @@ public class RoutingTable implements Iterable, Diffable, Diffable, Diffable indexRoutingTable : indicesRouting.values()) {
- indicesRouting.put(indexRoutingTable.value.index(), indexRoutingTable.value.normalizeVersions());
+ indicesRouting.put(indexRoutingTable.value.getIndex().getName(), indexRoutingTable.value.normalizeVersions());
}
RoutingTable table = new RoutingTable(version, indicesRouting.build());
indicesRouting = null;
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/ShardRouting.java b/core/src/main/java/org/elasticsearch/cluster/routing/ShardRouting.java
index 5ffaee0f2f9..47509852d93 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/ShardRouting.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/ShardRouting.java
@@ -27,6 +27,7 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
@@ -44,7 +45,7 @@ public final class ShardRouting implements Streamable, ToXContent {
*/
public static final long UNAVAILABLE_EXPECTED_SHARD_SIZE = -1;
- private String index;
+ private Index index;
private int shardId;
private String currentNodeId;
private String relocatingNodeId;
@@ -75,7 +76,7 @@ public final class ShardRouting implements Streamable, ToXContent {
* A constructor to internally create shard routing instances, note, the internal flag should only be set to true
* by either this class or tests. Visible for testing.
*/
- ShardRouting(String index, int shardId, String currentNodeId,
+ ShardRouting(Index index, int shardId, String currentNodeId,
String relocatingNodeId, RestoreSource restoreSource, boolean primary, ShardRoutingState state, long version,
UnassignedInfo unassignedInfo, AllocationId allocationId, boolean internal, long expectedShardSize) {
this.index = index;
@@ -105,22 +106,19 @@ public final class ShardRouting implements Streamable, ToXContent {
/**
* Creates a new unassigned shard.
*/
- public static ShardRouting newUnassigned(String index, int shardId, RestoreSource restoreSource, boolean primary, UnassignedInfo unassignedInfo) {
+ public static ShardRouting newUnassigned(Index index, int shardId, RestoreSource restoreSource, boolean primary, UnassignedInfo unassignedInfo) {
return new ShardRouting(index, shardId, null, null, restoreSource, primary, ShardRoutingState.UNASSIGNED, 0, unassignedInfo, null, true, UNAVAILABLE_EXPECTED_SHARD_SIZE);
}
- /**
- * The index name.
- */
- public String index() {
+ public Index index() {
return this.index;
}
/**
* The index name.
*/
- public String getIndex() {
- return index();
+ public String getIndexName() {
+ return index().getName();
}
/**
@@ -302,13 +300,13 @@ public final class ShardRouting implements Streamable, ToXContent {
return entry;
}
- public static ShardRouting readShardRoutingEntry(StreamInput in, String index, int shardId) throws IOException {
+ public static ShardRouting readShardRoutingEntry(StreamInput in, Index index, int shardId) throws IOException {
ShardRouting entry = new ShardRouting();
entry.readFrom(in, index, shardId);
return entry;
}
- public void readFrom(StreamInput in, String index, int shardId) throws IOException {
+ public void readFrom(StreamInput in, Index index, int shardId) throws IOException {
this.index = index;
this.shardId = shardId;
readFromThin(in);
@@ -344,7 +342,7 @@ public final class ShardRouting implements Streamable, ToXContent {
@Override
public void readFrom(StreamInput in) throws IOException {
- readFrom(in, in.readString(), in.readVInt());
+ readFrom(in, Index.readIndex(in), in.readVInt());
}
/**
@@ -398,7 +396,7 @@ public final class ShardRouting implements Streamable, ToXContent {
@Override
public void writeTo(StreamOutput out) throws IOException {
- out.writeString(index);
+ index.writeTo(out);
out.writeVInt(shardId);
writeToThin(out);
}
@@ -720,7 +718,7 @@ public final class ShardRouting implements Streamable, ToXContent {
.field("node", currentNodeId())
.field("relocating_node", relocatingNodeId())
.field("shard", shardId().id())
- .field("index", shardId().index().name())
+ .field("index", shardId().getIndex().getName())
.field("version", version);
if (expectedShardSize != UNAVAILABLE_EXPECTED_SHARD_SIZE) {
builder.field("expected_shard_size_in_bytes", expectedShardSize);
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java b/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java
index 7c446aa13d0..68f210fc144 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java
@@ -269,7 +269,7 @@ public class UnassignedInfo implements ToXContent, Writeable {
long minDelaySetting = Long.MAX_VALUE;
for (ShardRouting shard : state.routingTable().shardsWithState(ShardRoutingState.UNASSIGNED)) {
if (shard.primary() == false) {
- IndexMetaData indexMetaData = state.metaData().index(shard.getIndex());
+ IndexMetaData indexMetaData = state.metaData().index(shard.getIndexName());
boolean delayed = shard.unassignedInfo().getLastComputedLeftDelayNanos() > 0;
long delayTimeoutSetting = shard.unassignedInfo().getAllocationDelayTimeoutSettingNanos(settings, indexMetaData.getSettings());
if (delayed && delayTimeoutSetting > 0 && delayTimeoutSetting < minDelaySetting) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationService.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationService.java
index 25937595556..99b1974f5d7 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationService.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationService.java
@@ -131,7 +131,7 @@ public class AllocationService extends AbstractComponent {
for (IndexRoutingTable indexRoutingTable : newRoutingTable) {
final IndexMetaData indexMetaData = currentMetaData.index(indexRoutingTable.getIndex());
if (indexMetaData == null) {
- throw new IllegalStateException("no metadata found for index [" + indexRoutingTable.index() + "]");
+ throw new IllegalStateException("no metadata found for index " + indexRoutingTable.getIndex().getName());
}
IndexMetaData.Builder indexMetaDataBuilder = null;
for (IndexShardRoutingTable shardRoutings : indexRoutingTable) {
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocator.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocator.java
index 80f634e13cf..574f12265a7 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocator.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocator.java
@@ -42,7 +42,6 @@ import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.gateway.PriorityComparator;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@@ -513,7 +512,7 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
final ModelNode sourceNode = nodes.get(node.nodeId());
assert sourceNode != null;
final NodeSorter sorter = newNodeSorter();
- sorter.reset(shard.getIndex());
+ sorter.reset(shard.getIndexName());
final ModelNode[] nodes = sorter.modelNodes;
assert sourceNode.containsShard(shard);
/*
@@ -591,24 +590,20 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
*/
final AllocationDeciders deciders = allocation.deciders();
final PriorityComparator secondaryComparator = PriorityComparator.getAllocationComparator(allocation);
- final Comparator comparator = new Comparator() {
- @Override
- public int compare(ShardRouting o1,
- ShardRouting o2) {
- if (o1.primary() ^ o2.primary()) {
- return o1.primary() ? -1 : o2.primary() ? 1 : 0;
- }
- final int indexCmp;
- if ((indexCmp = o1.index().compareTo(o2.index())) == 0) {
- return o1.getId() - o2.getId();
- }
- // this comparator is more expensive than all the others up there
- // that's why it's added last even though it could be easier to read
- // if we'd apply it earlier. this comparator will only differentiate across
- // indices all shards of the same index is treated equally.
- final int secondary = secondaryComparator.compare(o1, o2);
- return secondary == 0 ? indexCmp : secondary;
+ final Comparator comparator = (o1, o2) -> {
+ if (o1.primary() ^ o2.primary()) {
+ return o1.primary() ? -1 : o2.primary() ? 1 : 0;
}
+ final int indexCmp;
+ if ((indexCmp = o1.getIndexName().compareTo(o2.getIndexName())) == 0) {
+ return o1.getId() - o2.getId();
+ }
+ // this comparator is more expensive than all the others up there
+ // that's why it's added last even though it could be easier to read
+ // if we'd apply it earlier. this comparator will only differentiate across
+ // indices all shards of the same index is treated equally.
+ final int secondary = secondaryComparator.compare(o1, o2);
+ return secondary == 0 ? indexCmp : secondary;
};
/*
* we use 2 arrays and move replicas to the second array once we allocated an identical
@@ -655,7 +650,7 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
}
if (!node.containsShard(shard)) {
// simulate weight if we would add shard to node
- float currentWeight = weight.weightShardAdded(this, node, shard.index());
+ float currentWeight = weight.weightShardAdded(this, node, shard.getIndexName());
/*
* Unless the operation is not providing any gains we
* don't check deciders
@@ -678,8 +673,8 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
*/
if (currentDecision.type() == decision.type()) {
final int repId = shard.id();
- final int nodeHigh = node.highestPrimary(shard.index());
- final int minNodeHigh = minNode.highestPrimary(shard.index());
+ final int nodeHigh = node.highestPrimary(shard.index().getName());
+ final int minNodeHigh = minNode.highestPrimary(shard.getIndexName());
if ((((nodeHigh > repId && minNodeHigh > repId) || (nodeHigh < repId && minNodeHigh < repId)) && (nodeHigh < minNodeHigh))
|| (nodeHigh > minNodeHigh && nodeHigh > repId && minNodeHigh < repId)) {
minNode = node;
@@ -855,9 +850,9 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
}
public void addShard(ShardRouting shard, Decision decision) {
- ModelIndex index = indices.get(shard.index());
+ ModelIndex index = indices.get(shard.getIndexName());
if (index == null) {
- index = new ModelIndex(shard.index());
+ index = new ModelIndex(shard.getIndexName());
indices.put(index.getIndexId(), index);
}
index.addShard(shard, decision);
@@ -865,12 +860,12 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
}
public Decision removeShard(ShardRouting shard) {
- ModelIndex index = indices.get(shard.index());
+ ModelIndex index = indices.get(shard.getIndexName());
Decision removed = null;
if (index != null) {
removed = index.removeShard(shard);
if (removed != null && index.numShards() == 0) {
- indices.remove(shard.index());
+ indices.remove(shard.getIndexName());
}
}
numShards--;
@@ -890,7 +885,7 @@ public class BalancedShardsAllocator extends AbstractComponent implements Shards
}
public boolean containsShard(ShardRouting shard) {
- ModelIndex index = getIndex(shard.getIndex());
+ ModelIndex index = getIndex(shard.getIndexName());
return index == null ? false : index.containsShard(shard);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java
index 31fc51a8979..ed136d67d56 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java
@@ -35,7 +35,6 @@ import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
-import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
import java.util.function.Consumer;
@@ -101,15 +100,15 @@ public abstract class AbstractAllocateAllocationCommand implements AllocationCom
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
- builder.field(INDEX_KEY, shardId().index().name());
- builder.field(SHARD_KEY, shardId().id());
+ builder.field(INDEX_KEY, index());
+ builder.field(SHARD_KEY, shardId());
builder.field(NODE_KEY, node());
return builder;
}
public void writeTo(StreamOutput out) throws IOException {
- out.writeString(shardId.getIndex());
- out.writeVInt(shardId.getId());
+ out.writeString(index);
+ out.writeVInt(shardId);
out.writeString(node);
}
@@ -143,20 +142,32 @@ public abstract class AbstractAllocateAllocationCommand implements AllocationCom
}
}
- protected final ShardId shardId;
+ protected final String index;
+ protected final int shardId;
protected final String node;
- protected AbstractAllocateAllocationCommand(ShardId shardId, String node) {
+ protected AbstractAllocateAllocationCommand(String index, int shardId, String node) {
+ this.index = index;
this.shardId = shardId;
this.node = node;
}
+
+ /**
+ * Get the index name
+ *
+ * @return name of the index
+ */
+ public String index() {
+ return this.index;
+ }
+
/**
* Get the shard id
*
* @return id of the shard
*/
- public ShardId shardId() {
+ public int shardId() {
return this.shardId;
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateEmptyPrimaryAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateEmptyPrimaryAllocationCommand.java
index f607755bca1..c7ddefedc24 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateEmptyPrimaryAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateEmptyPrimaryAllocationCommand.java
@@ -51,8 +51,8 @@ public class AllocateEmptyPrimaryAllocationCommand extends BasePrimaryAllocation
* @param node node id of the node to assign the shard to
* @param acceptDataLoss whether the user agrees to data loss
*/
- public AllocateEmptyPrimaryAllocationCommand(ShardId shardId, String node, boolean acceptDataLoss) {
- super(shardId, node, acceptDataLoss);
+ public AllocateEmptyPrimaryAllocationCommand(String index, int shardId, String node, boolean acceptDataLoss) {
+ super(index, shardId, node, acceptDataLoss);
}
@Override
@@ -70,7 +70,7 @@ public class AllocateEmptyPrimaryAllocationCommand extends BasePrimaryAllocation
@Override
public AllocateEmptyPrimaryAllocationCommand build() {
validate();
- return new AllocateEmptyPrimaryAllocationCommand(new ShardId(index, shard), node, acceptDataLoss);
+ return new AllocateEmptyPrimaryAllocationCommand(index, shard, node, acceptDataLoss);
}
}
@@ -98,17 +98,17 @@ public class AllocateEmptyPrimaryAllocationCommand extends BasePrimaryAllocation
final ShardRouting shardRouting;
try {
- shardRouting = allocation.routingTable().shardRoutingTable(shardId).primaryShard();
+ shardRouting = allocation.routingTable().shardRoutingTable(index, shardId).primaryShard();
} catch (IndexNotFoundException | ShardNotFoundException e) {
return explainOrThrowRejectedCommand(explain, allocation, e);
}
if (shardRouting.unassigned() == false) {
- return explainOrThrowRejectedCommand(explain, allocation, "primary " + shardId + " is already assigned");
+ return explainOrThrowRejectedCommand(explain, allocation, "primary [" + index + "][" + shardId + "] is already assigned");
}
if (shardRouting.unassignedInfo().getReason() != UnassignedInfo.Reason.INDEX_CREATED && acceptDataLoss == false) {
return explainOrThrowRejectedCommand(explain, allocation,
- "allocating an empty primary for " + shardId + " can result in data loss. Please confirm by setting the accept_data_loss parameter to true");
+ "allocating an empty primary for [" + index + "][" + shardId + "] can result in data loss. Please confirm by setting the accept_data_loss parameter to true");
}
initializeUnassignedShard(allocation, routingNodes, routingNode, shardRouting,
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateReplicaAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateReplicaAllocationCommand.java
index f9d443a6618..616e08b8f3f 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateReplicaAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateReplicaAllocationCommand.java
@@ -47,11 +47,12 @@ public class AllocateReplicaAllocationCommand extends AbstractAllocateAllocation
/**
* Creates a new {@link AllocateReplicaAllocationCommand}
*
- * @param shardId {@link ShardId} of the shard to assign
+ * @param index index of the shard to assign
+ * @param shardId id of the shard to assign
* @param node node id of the node to assign the shard to
*/
- public AllocateReplicaAllocationCommand(ShardId shardId, String node) {
- super(shardId, node);
+ public AllocateReplicaAllocationCommand(String index, int shardId, String node) {
+ super(index, shardId, node);
}
@Override
@@ -69,7 +70,7 @@ public class AllocateReplicaAllocationCommand extends AbstractAllocateAllocation
@Override
public AllocateReplicaAllocationCommand build() {
validate();
- return new AllocateReplicaAllocationCommand(new ShardId(index, shard), node);
+ return new AllocateReplicaAllocationCommand(index, shard, node);
}
}
@@ -96,20 +97,20 @@ public class AllocateReplicaAllocationCommand extends AbstractAllocateAllocation
final ShardRouting primaryShardRouting;
try {
- primaryShardRouting = allocation.routingTable().shardRoutingTable(shardId).primaryShard();
+ primaryShardRouting = allocation.routingTable().shardRoutingTable(index, shardId).primaryShard();
} catch (IndexNotFoundException | ShardNotFoundException e) {
return explainOrThrowRejectedCommand(explain, allocation, e);
}
if (primaryShardRouting.unassigned()) {
return explainOrThrowRejectedCommand(explain, allocation,
- "trying to allocate a replica shard " + shardId + ", while corresponding primary shard is still unassigned");
+ "trying to allocate a replica shard [" + index + "][" + shardId + "], while corresponding primary shard is still unassigned");
}
- List replicaShardRoutings = allocation.routingTable().shardRoutingTable(shardId).replicaShardsWithState(ShardRoutingState.UNASSIGNED);
+ List replicaShardRoutings = allocation.routingTable().shardRoutingTable(index, shardId).replicaShardsWithState(ShardRoutingState.UNASSIGNED);
ShardRouting shardRouting;
if (replicaShardRoutings.isEmpty()) {
return explainOrThrowRejectedCommand(explain, allocation,
- "all copies of " + shardId +" are already assigned. Use the move allocation command instead");
+ "all copies of [" + index + "][" + shardId + "] are already assigned. Use the move allocation command instead");
} else {
shardRouting = replicaShardRoutings.get(0);
}
@@ -120,7 +121,7 @@ public class AllocateReplicaAllocationCommand extends AbstractAllocateAllocation
if (explain) {
return new RerouteExplanation(this, decision);
}
- throw new IllegalArgumentException("[" + name() + "] allocation of " + shardId + " on node " + discoNode + " is not allowed, reason: " + decision);
+ throw new IllegalArgumentException("[" + name() + "] allocation of [" + index + "][" + shardId + "] on node " + discoNode + " is not allowed, reason: " + decision);
}
initializeUnassignedShard(allocation, routingNodes, routingNode, shardRouting);
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateStalePrimaryAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateStalePrimaryAllocationCommand.java
index 22cedfc6aa3..5ccd9e9bb63 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateStalePrimaryAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateStalePrimaryAllocationCommand.java
@@ -47,12 +47,13 @@ public class AllocateStalePrimaryAllocationCommand extends BasePrimaryAllocation
/**
* Creates a new {@link AllocateStalePrimaryAllocationCommand}
*
- * @param shardId {@link ShardId} of the shard to assign
+ * @param index index of the shard to assign
+ * @param shardId id of the shard to assign
* @param node node id of the node to assign the shard to
* @param acceptDataLoss whether the user agrees to data loss
*/
- public AllocateStalePrimaryAllocationCommand(ShardId shardId, String node, boolean acceptDataLoss) {
- super(shardId, node, acceptDataLoss);
+ public AllocateStalePrimaryAllocationCommand(String index, int shardId, String node, boolean acceptDataLoss) {
+ super(index, shardId, node, acceptDataLoss);
}
@Override
@@ -70,7 +71,7 @@ public class AllocateStalePrimaryAllocationCommand extends BasePrimaryAllocation
@Override
public AllocateStalePrimaryAllocationCommand build() {
validate();
- return new AllocateStalePrimaryAllocationCommand(new ShardId(index, shard), node, acceptDataLoss);
+ return new AllocateStalePrimaryAllocationCommand(index, shard, node, acceptDataLoss);
}
}
@@ -98,23 +99,23 @@ public class AllocateStalePrimaryAllocationCommand extends BasePrimaryAllocation
final ShardRouting shardRouting;
try {
- shardRouting = allocation.routingTable().shardRoutingTable(shardId).primaryShard();
+ shardRouting = allocation.routingTable().shardRoutingTable(index, shardId).primaryShard();
} catch (IndexNotFoundException | ShardNotFoundException e) {
return explainOrThrowRejectedCommand(explain, allocation, e);
}
if (shardRouting.unassigned() == false) {
- return explainOrThrowRejectedCommand(explain, allocation, "primary " + shardId + " is already assigned");
+ return explainOrThrowRejectedCommand(explain, allocation, "primary [" + index + "][" + shardId + "] is already assigned");
}
if (acceptDataLoss == false) {
return explainOrThrowRejectedCommand(explain, allocation,
- "allocating an empty primary for " + shardId + " can result in data loss. Please confirm by setting the accept_data_loss parameter to true");
+ "allocating an empty primary for [" + index + "][" + shardId + "] can result in data loss. Please confirm by setting the accept_data_loss parameter to true");
}
- final IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.getIndex());
+ final IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.getIndexName());
if (shardRouting.allocatedPostIndexCreate(indexMetaData) == false) {
return explainOrThrowRejectedCommand(explain, allocation,
- "trying to allocate an existing primary shard " + shardId + ", while no such shard has ever been active");
+ "trying to allocate an existing primary shard [" + index + "][" + shardId + "], while no such shard has ever been active");
}
initializeUnassignedShard(allocation, routingNodes, routingNode, shardRouting);
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/BasePrimaryAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/BasePrimaryAllocationCommand.java
index 35c1711d646..b982952c1f1 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/BasePrimaryAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/BasePrimaryAllocationCommand.java
@@ -44,8 +44,8 @@ public abstract class BasePrimaryAllocationCommand extends AbstractAllocateAlloc
protected final boolean acceptDataLoss;
- protected BasePrimaryAllocationCommand(ShardId shardId, String node, boolean acceptDataLoss) {
- super(shardId, node);
+ protected BasePrimaryAllocationCommand(String index, int shardId, String node, boolean acceptDataLoss) {
+ super(index, shardId, node);
this.acceptDataLoss = acceptDataLoss;
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java
index c485cb3eab5..32eae8c19d7 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java
@@ -33,7 +33,6 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
-import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
@@ -53,12 +52,13 @@ public class CancelAllocationCommand implements AllocationCommand {
@Override
public CancelAllocationCommand readFrom(StreamInput in) throws IOException {
- return new CancelAllocationCommand(ShardId.readShardId(in), in.readString(), in.readBoolean());
+ return new CancelAllocationCommand(in.readString(), in.readVInt(), in.readString(), in.readBoolean());
}
@Override
public void writeTo(CancelAllocationCommand command, StreamOutput out) throws IOException {
- command.shardId().writeTo(out);
+ out.writeString(command.index());
+ out.writeVInt(command.shardId());
out.writeString(command.node());
out.writeBoolean(command.allowPrimary());
}
@@ -100,7 +100,7 @@ public class CancelAllocationCommand implements AllocationCommand {
if (nodeId == null) {
throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
}
- return new CancelAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
+ return new CancelAllocationCommand(index, shardId, nodeId, allowPrimary);
}
@Override
@@ -110,8 +110,8 @@ public class CancelAllocationCommand implements AllocationCommand {
} else {
builder.startObject(objectName);
}
- builder.field("index", command.shardId().index().name());
- builder.field("shard", command.shardId().id());
+ builder.field("index", command.index());
+ builder.field("shard", command.shardId());
builder.field("node", command.node());
builder.field("allow_primary", command.allowPrimary());
builder.endObject();
@@ -119,17 +119,20 @@ public class CancelAllocationCommand implements AllocationCommand {
}
- private final ShardId shardId;
+ private final String index;
+ private final int shardId;
private final String node;
private final boolean allowPrimary;
/**
* Creates a new {@link CancelAllocationCommand}
*
+ * @param index index of the shard which allocation should be canceled
* @param shardId id of the shard which allocation should be canceled
* @param node id of the node that manages the shard which allocation should be canceled
*/
- public CancelAllocationCommand(ShardId shardId, String node, boolean allowPrimary) {
+ public CancelAllocationCommand(String index, int shardId, String node, boolean allowPrimary) {
+ this.index = index;
this.shardId = shardId;
this.node = node;
this.allowPrimary = allowPrimary;
@@ -141,10 +144,18 @@ public class CancelAllocationCommand implements AllocationCommand {
}
/**
+ * Get the index of the shard which allocation should be canceled
+ * @return index of the shard which allocation should be canceled
+ */
+ public String index() {
+ return this.index;
+ }
+ /**
+
* Get the id of the shard which allocation should be canceled
* @return id of the shard which allocation should be canceled
*/
- public ShardId shardId() {
+ public int shardId() {
return this.shardId;
}
@@ -166,7 +177,10 @@ public class CancelAllocationCommand implements AllocationCommand {
boolean found = false;
for (RoutingNodes.RoutingNodeIterator it = allocation.routingNodes().routingNodeIter(discoNode.id()); it.hasNext(); ) {
ShardRouting shardRouting = it.next();
- if (!shardRouting.shardId().equals(shardId)) {
+ if (!shardRouting.shardId().getIndex().getName().equals(index)) {
+ continue;
+ }
+ if (shardRouting.shardId().id() != shardId) {
continue;
}
found = true;
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java
index ed535df2f48..75a9400807c 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java
@@ -32,7 +32,6 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
-import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
@@ -49,12 +48,13 @@ public class MoveAllocationCommand implements AllocationCommand {
@Override
public MoveAllocationCommand readFrom(StreamInput in) throws IOException {
- return new MoveAllocationCommand(ShardId.readShardId(in), in.readString(), in.readString());
+ return new MoveAllocationCommand(in.readString(), in.readVInt(), in.readString(), in.readString());
}
@Override
public void writeTo(MoveAllocationCommand command, StreamOutput out) throws IOException {
- command.shardId().writeTo(out);
+ out.writeString(command.index());
+ out.writeVInt(command.shardId());
out.writeString(command.fromNode());
out.writeString(command.toNode());
}
@@ -99,7 +99,7 @@ public class MoveAllocationCommand implements AllocationCommand {
if (toNode == null) {
throw new ElasticsearchParseException("[{}] command missing the to_node parameter", NAME);
}
- return new MoveAllocationCommand(new ShardId(index, shardId), fromNode, toNode);
+ return new MoveAllocationCommand(index, shardId, fromNode, toNode);
}
@Override
@@ -109,19 +109,21 @@ public class MoveAllocationCommand implements AllocationCommand {
} else {
builder.startObject(objectName);
}
- builder.field("index", command.shardId().index().name());
- builder.field("shard", command.shardId().id());
+ builder.field("index", command.index());
+ builder.field("shard", command.shardId());
builder.field("from_node", command.fromNode());
builder.field("to_node", command.toNode());
builder.endObject();
}
}
- private final ShardId shardId;
+ private final String index;
+ private final int shardId;
private final String fromNode;
private final String toNode;
- public MoveAllocationCommand(ShardId shardId, String fromNode, String toNode) {
+ public MoveAllocationCommand(String index, int shardId, String fromNode, String toNode) {
+ this.index = index;
this.shardId = shardId;
this.fromNode = fromNode;
this.toNode = toNode;
@@ -132,7 +134,9 @@ public class MoveAllocationCommand implements AllocationCommand {
return NAME;
}
- public ShardId shardId() {
+ public String index() {return index; }
+
+ public int shardId() {
return this.shardId;
}
@@ -152,7 +156,10 @@ public class MoveAllocationCommand implements AllocationCommand {
boolean found = false;
for (ShardRouting shardRouting : allocation.routingNodes().node(fromDiscoNode.id())) {
- if (!shardRouting.shardId().equals(shardId)) {
+ if (!shardRouting.shardId().getIndexName().equals(index)) {
+ continue;
+ }
+ if (shardRouting.shardId().id() != shardId) {
continue;
}
found = true;
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java
index 23624f050a9..c0120179767 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java
@@ -330,7 +330,7 @@ public class DiskThresholdDecider extends AllocationDecider {
}
// a flag for whether the primary shard has been previously allocated
- IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.getIndex());
+ IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.getIndexName());
boolean primaryHasBeenAllocated = shardRouting.primary() && shardRouting.allocatedPostIndexCreate(indexMetaData);
// checks for exact byte comparisons
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/EnableAllocationDecider.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/EnableAllocationDecider.java
index 3c2e649387a..9131355876b 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/EnableAllocationDecider.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/EnableAllocationDecider.java
@@ -92,7 +92,7 @@ public class EnableAllocationDecider extends AllocationDecider {
return allocation.decision(Decision.YES, NAME, "allocation disabling is ignored");
}
- final IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.getIndex());
+ final IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.getIndexName());
final Allocation enable;
if (INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.exists(indexMetaData.getSettings())) {
enable = INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.get(indexMetaData.getSettings());
diff --git a/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java b/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java
index 98d98414db3..b592eeb1469 100644
--- a/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java
+++ b/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java
@@ -190,7 +190,7 @@ public class InternalClusterService extends AbstractLifecycleComponent nodeAttributes = discoveryNodeService.buildAttributes();
// note, we rely on the fact that its a new id each time we start, see FD and "kill -9" handling
diff --git a/core/src/main/java/org/elasticsearch/common/ContextAndHeaderHolder.java b/core/src/main/java/org/elasticsearch/common/ContextAndHeaderHolder.java
deleted file mode 100644
index 9a3140dba1a..00000000000
--- a/core/src/main/java/org/elasticsearch/common/ContextAndHeaderHolder.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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.common;
-
-import com.carrotsearch.hppc.ObjectObjectAssociativeContainer;
-import com.carrotsearch.hppc.ObjectObjectHashMap;
-import org.elasticsearch.common.collect.ImmutableOpenMap;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- *
- */
-public class ContextAndHeaderHolder implements HasContextAndHeaders {
-
- private ObjectObjectHashMap