1
0
Эх сурвалжийг харах

Remove Dead Code and Duplication from Metadata (#64938)

Just some random spots I found while researching other things.
Armin Braun 4 жил өмнө
parent
commit
2b1b1b387a

+ 3 - 11
server/src/main/java/org/elasticsearch/action/admin/indices/get/TransportGetIndexAction.java

@@ -38,7 +38,6 @@ import org.elasticsearch.indices.IndicesService;
 import org.elasticsearch.threadpool.ThreadPool;
 import org.elasticsearch.transport.TransportService;
 
-import java.io.IOException;
 import java.util.List;
 import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
@@ -82,13 +81,8 @@ public class TransportGetIndexAction extends TransportClusterInfoAction<GetIndex
             switch (feature) {
             case MAPPINGS:
                     if (!doneMappings) {
-                        try {
-                            mappingsResult = state.metadata().findMappings(concreteIndices, indicesService.getFieldFilter());
-                            doneMappings = true;
-                        } catch (IOException e) {
-                            listener.onFailure(e);
-                            return;
-                        }
+                        mappingsResult = state.metadata().findMappings(concreteIndices, indicesService.getFieldFilter());
+                        doneMappings = true;
                     }
                     break;
             case ALIASES:
@@ -123,8 +117,6 @@ public class TransportGetIndexAction extends TransportClusterInfoAction<GetIndex
                     throw new IllegalStateException("feature [" + feature + "] is not valid");
             }
         }
-        listener.onResponse(
-            new GetIndexResponse(concreteIndices, mappingsResult, aliasesResult, settings, defaultSettings, dataStreams)
-        );
+        listener.onResponse(new GetIndexResponse(concreteIndices, mappingsResult, aliasesResult, settings, defaultSettings, dataStreams));
     }
 }

+ 1 - 11
server/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/TransportGetMappingsAction.java

@@ -26,16 +26,12 @@ import org.elasticsearch.action.support.ActionFilters;
 import org.elasticsearch.action.support.master.info.TransportClusterInfoAction;
 import org.elasticsearch.cluster.ClusterState;
 import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
-import org.elasticsearch.cluster.metadata.MappingMetadata;
 import org.elasticsearch.cluster.service.ClusterService;
-import org.elasticsearch.common.collect.ImmutableOpenMap;
 import org.elasticsearch.common.inject.Inject;
 import org.elasticsearch.indices.IndicesService;
 import org.elasticsearch.threadpool.ThreadPool;
 import org.elasticsearch.transport.TransportService;
 
-import java.io.IOException;
-
 public class TransportGetMappingsAction extends TransportClusterInfoAction<GetMappingsRequest, GetMappingsResponse> {
 
     private static final Logger logger = LogManager.getLogger(TransportGetMappingsAction.class);
@@ -55,12 +51,6 @@ public class TransportGetMappingsAction extends TransportClusterInfoAction<GetMa
     protected void doMasterOperation(final GetMappingsRequest request, String[] concreteIndices, final ClusterState state,
                                      final ActionListener<GetMappingsResponse> listener) {
         logger.trace("serving getMapping request based on version {}", state.version());
-        try {
-            ImmutableOpenMap<String, MappingMetadata> result =
-                    state.metadata().findMappings(concreteIndices, indicesService.getFieldFilter());
-            listener.onResponse(new GetMappingsResponse(result));
-        } catch (IOException e) {
-            listener.onFailure(e);
-        }
+        listener.onResponse(new GetMappingsResponse(state.metadata().findMappings(concreteIndices, indicesService.getFieldFilter())));
     }
 }

+ 2 - 16
server/src/main/java/org/elasticsearch/cluster/ClusterState.java

@@ -19,7 +19,6 @@
 
 package org.elasticsearch.cluster;
 
-import com.carrotsearch.hppc.cursors.ObjectCursor;
 import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
 import org.elasticsearch.Version;
 import org.elasticsearch.cluster.block.ClusterBlock;
@@ -323,7 +322,7 @@ public class ClusterState implements ToXContentFragment, Diffable<ClusterState>
         ROUTING_NODES("routing_nodes"),
         CUSTOMS("customs");
 
-        private static Map<String, Metric> valueToEnum;
+        private static final Map<String, Metric> valueToEnum;
 
         static {
             valueToEnum = new HashMap<>();
@@ -365,7 +364,6 @@ public class ClusterState implements ToXContentFragment, Diffable<ClusterState>
     }
 
     @Override
-    @SuppressWarnings("unchecked")
     public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
         EnumSet<Metric> metrics = Metric.parseString(params.param("metric", "_all"), true);
 
@@ -646,19 +644,7 @@ public class ClusterState implements ToXContentFragment, Diffable<ClusterState>
         routingTable.writeTo(out);
         nodes.writeTo(out);
         blocks.writeTo(out);
-        // filter out custom states not supported by the other node
-        int numberOfCustoms = 0;
-        for (final ObjectCursor<Custom> cursor : customs.values()) {
-            if (VersionedNamedWriteable.shouldSerialize(out, cursor.value)) {
-                numberOfCustoms++;
-            }
-        }
-        out.writeVInt(numberOfCustoms);
-        for (final ObjectCursor<Custom> cursor : customs.values()) {
-            if (VersionedNamedWriteable.shouldSerialize(out, cursor.value)) {
-                out.writeNamedWriteable(cursor.value);
-            }
-        }
+        VersionedNamedWriteable.writeVersionedWritables(out, customs);
         if (out.getVersion().before(Version.V_8_0_0)) {
             out.writeVInt(-1); // used to be minimumMasterNodesOnPublishingMaster, which was used in 7.x for BWC with 6.x
         }

+ 8 - 64
server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java

@@ -386,8 +386,7 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
      *
      */
     public ImmutableOpenMap<String, MappingMetadata> findMappings(String[] concreteIndices,
-                                                                  Function<String, Predicate<String>> fieldFilter)
-            throws IOException {
+                                                                  Function<String, Predicate<String>> fieldFilter) {
         assert concreteIndices != null;
         if (concreteIndices.length == 0) {
             return ImmutableOpenMap.of();
@@ -560,22 +559,7 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
         if (writeIndex == null) {
             throw new IllegalArgumentException("alias [" + aliasOrIndex + "] does not have a write index");
         }
-        AliasMetadata aliasMd = writeIndex.getAliases().get(result.getName());
-        if (aliasMd.indexRouting() != null) {
-            if (aliasMd.indexRouting().indexOf(',') != -1) {
-                throw new IllegalArgumentException("index/alias [" + aliasOrIndex + "] provided with routing value ["
-                    + aliasMd.getIndexRouting() + "] that resolved to several routing values, rejecting operation");
-            }
-            if (routing != null) {
-                if (!routing.equals(aliasMd.indexRouting())) {
-                    throw new IllegalArgumentException("Alias [" + aliasOrIndex + "] has index routing associated with it ["
-                        + aliasMd.indexRouting() + "], and was provided with routing value [" + routing + "], rejecting operation");
-                }
-            }
-            // Alias routing overrides the parent routing (if any).
-            return aliasMd.indexRouting();
-        }
-        return routing;
+        return resolveRouting(routing, aliasOrIndex, writeIndex.getAliases().get(result.getName()));
     }
 
     /**
@@ -596,7 +580,10 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
         if (result.getIndices().size() > 1) {
             rejectSingleIndexOperation(aliasOrIndex, result);
         }
-        AliasMetadata aliasMd = alias.getFirstAliasMetadata();
+        return resolveRouting(routing, aliasOrIndex, alias.getFirstAliasMetadata());
+    }
+
+    private static String resolveRouting(@Nullable String routing, String aliasOrIndex, AliasMetadata aliasMd) {
         if (aliasMd.indexRouting() != null) {
             if (aliasMd.indexRouting().indexOf(',') != -1) {
                 throw new IllegalArgumentException("index/alias [" + aliasOrIndex + "] provided with routing value [" +
@@ -709,10 +696,6 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
         return this.customs;
     }
 
-    public ImmutableOpenMap<String, Custom> getCustoms() {
-        return this.customs;
-    }
-
     /**
      * The collection of index deletions in the cluster.
      */
@@ -748,28 +731,6 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
         return this.totalOpenIndexShards;
     }
 
-    /**
-     * Identifies whether the array containing type names given as argument refers to all types
-     * The empty or null array identifies all types
-     *
-     * @param types the array containing types
-     * @return true if the provided array maps to all types, false otherwise
-     */
-    public static boolean isAllTypes(String[] types) {
-        return types == null || types.length == 0 || isExplicitAllType(types);
-    }
-
-    /**
-     * Identifies whether the array containing type names given as argument explicitly refers to all types
-     * The empty or null array doesn't explicitly map to all types
-     *
-     * @param types the array containing index names
-     * @return true if the provided array explicitly maps to all types, false otherwise
-     */
-    public static boolean isExplicitAllType(String[] types) {
-        return types != null && types.length == 1 && ALL.equals(types[0]);
-    }
-
     /**
      * @param concreteIndex The concrete index to check if routing is required
      * @return Whether routing is required according to the mapping for the specified index and type
@@ -973,19 +934,7 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
         for (ObjectCursor<IndexTemplateMetadata> cursor : templates.values()) {
             cursor.value.writeTo(out);
         }
-        // filter out custom states not supported by the other node
-        int numberOfCustoms = 0;
-        for (final ObjectCursor<Custom> cursor : customs.values()) {
-            if (VersionedNamedWriteable.shouldSerialize(out, cursor.value)) {
-                numberOfCustoms++;
-            }
-        }
-        out.writeVInt(numberOfCustoms);
-        for (final ObjectCursor<Custom> cursor : customs.values()) {
-            if (VersionedNamedWriteable.shouldSerialize(out, cursor.value)) {
-                out.writeNamedWriteable(cursor.value);
-            }
-        }
+        VersionedNamedWriteable.writeVersionedWritables(out, customs);
     }
 
     public static Builder builder() {
@@ -1215,8 +1164,7 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
         }
 
         public IndexGraveyard indexGraveyard() {
-            IndexGraveyard graveyard = (IndexGraveyard) getCustom(IndexGraveyard.TYPE);
-            return graveyard;
+            return (IndexGraveyard) getCustom(IndexGraveyard.TYPE);
         }
 
         public Builder updateSettings(Settings settings, String... indices) {
@@ -1275,10 +1223,6 @@ public class Metadata implements Iterable<IndexMetadata>, Diffable<Metadata>, To
             return this;
         }
 
-        public DiffableStringMap hashesOfConsistentSettings() {
-            return this.hashesOfConsistentSettings;
-        }
-
         public Builder hashesOfConsistentSettings(DiffableStringMap hashesOfConsistentSettings) {
             this.hashesOfConsistentSettings = hashesOfConsistentSettings;
             return this;

+ 27 - 0
server/src/main/java/org/elasticsearch/common/io/stream/VersionedNamedWriteable.java

@@ -19,7 +19,11 @@
 
 package org.elasticsearch.common.io.stream;
 
+import com.carrotsearch.hppc.cursors.ObjectCursor;
 import org.elasticsearch.Version;
+import org.elasticsearch.common.collect.ImmutableOpenMap;
+
+import java.io.IOException;
 
 /**
  * A {@link NamedWriteable} that has a minimum version associated with it.
@@ -50,4 +54,27 @@ public interface VersionedNamedWriteable extends NamedWriteable {
         return out.getVersion().onOrAfter(custom.getMinimalSupportedVersion());
     }
 
+    /**
+     * Writes all those values in the given map to {@code out} that pass the version check in {@link #shouldSerialize} as a list.
+     *
+     * @param out     stream to write to
+     * @param customs map of customs
+     * @param <T>     type of customs in map
+     */
+    static <T extends VersionedNamedWriteable> void writeVersionedWritables(StreamOutput out, ImmutableOpenMap<String, T> customs)
+            throws IOException {
+        // filter out custom states not supported by the other node
+        int numberOfCustoms = 0;
+        for (final ObjectCursor<T> cursor : customs.values()) {
+            if (shouldSerialize(out, cursor.value)) {
+                numberOfCustoms++;
+            }
+        }
+        out.writeVInt(numberOfCustoms);
+        for (final ObjectCursor<T> cursor : customs.values()) {
+            if (shouldSerialize(out, cursor.value)) {
+                out.writeNamedWriteable(cursor.value);
+            }
+        }
+    }
 }

+ 2 - 9
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/persistence/ElasticsearchMappings.java

@@ -97,7 +97,7 @@ public class ElasticsearchMappings {
     private ElasticsearchMappings() {
     }
 
-    static String[] mappingRequiresUpdate(ClusterState state, String[] concreteIndices, Version minVersion) throws IOException {
+    static String[] mappingRequiresUpdate(ClusterState state, String[] concreteIndices, Version minVersion) {
         List<String> indicesToUpdate = new ArrayList<>();
 
         ImmutableOpenMap<String, MappingMetadata> currentMapping = state.metadata().findMappings(concreteIndices,
@@ -156,14 +156,7 @@ public class ElasticsearchMappings {
         String[] concreteIndices = indexAbstraction.getIndices().stream().map(IndexMetadata::getIndex).map(Index::getName)
             .toArray(String[]::new);
 
-        String[] indicesThatRequireAnUpdate;
-        try {
-            indicesThatRequireAnUpdate = mappingRequiresUpdate(state, concreteIndices, Version.CURRENT);
-        } catch (IOException e) {
-            listener.onFailure(e);
-            return;
-        }
-
+        final String[] indicesThatRequireAnUpdate = mappingRequiresUpdate(state, concreteIndices, Version.CURRENT);
         if (indicesThatRequireAnUpdate.length > 0) {
             try {
                 String mapping = mappingSupplier.get();