From ad79b5f5b5df39031a8d6361eed2c5d023f8d16c Mon Sep 17 00:00:00 2001 From: Yang Wang Date: Fri, 28 Feb 2025 15:07:43 +1100 Subject: [PATCH 1/5] Use singleton default-project instance in deserialization No need to create new instances for the default project-id sent across the wire. We can use the singleton field which should speeds up key comparsion for Map.get operations. Relates: #123662 --- .../org/elasticsearch/cluster/block/ClusterBlocks.java | 2 +- .../java/org/elasticsearch/cluster/metadata/Metadata.java | 2 +- .../java/org/elasticsearch/cluster/metadata/ProjectId.java | 7 ++++--- .../elasticsearch/cluster/metadata/ProjectMetadata.java | 2 +- .../elasticsearch/cluster/routing/GlobalRoutingTable.java | 2 +- .../command/AbstractAllocateAllocationCommand.java | 2 +- .../allocation/command/CancelAllocationCommand.java | 2 +- .../routing/allocation/command/MoveAllocationCommand.java | 2 +- .../multiproject/action/DeleteProjectAction.java | 2 +- .../multiproject/action/PutProjectAction.java | 2 +- 10 files changed, 13 insertions(+), 12 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java b/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java index 85298e495fd05..bbcd816410a45 100644 --- a/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java +++ b/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java @@ -438,7 +438,7 @@ private static void writeBlockSet(Set blocks, StreamOutput out) th public static ClusterBlocks readFrom(StreamInput in) throws IOException { if (in.getTransportVersion().onOrAfter(TransportVersions.MULTI_PROJECT)) { final Set global = readBlockSet(in); - final Map projectBlocksMap = in.readImmutableMap(ProjectId::new, ProjectBlocks::readFrom); + final Map projectBlocksMap = in.readImmutableMap(ProjectId::readFrom, ProjectBlocks::readFrom); if (global.isEmpty() && noProjectOrDefaultProjectOnly(projectBlocksMap) && projectBlocksMap.getOrDefault(Metadata.DEFAULT_PROJECT_ID, ProjectBlocks.EMPTY).indices().isEmpty()) { diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java b/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java index c6d0944ca6d90..f8af5c90fc1b3 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java @@ -1154,7 +1154,7 @@ public static Metadata readFrom(StreamInput in) throws IOException { builder.put(ReservedStateMetadata.readFrom(in)); } - builder.projectMetadata(in.readMap(ProjectId::new, ProjectMetadata::readFrom)); + builder.projectMetadata(in.readMap(ProjectId::readFrom, ProjectMetadata::readFrom)); } return builder.build(); } diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java index 71b7ef1557c57..6f4e123903e82 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java @@ -22,7 +22,7 @@ public record ProjectId(String id) implements Writeable, ToXContent { - public static final Reader READER = ProjectId::new; + public static final Reader READER = ProjectId::readFrom; private static final int MAX_LENGTH = 128; public ProjectId { @@ -53,8 +53,9 @@ private static boolean isValidIdChar(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == '-'; } - public ProjectId(StreamInput in) throws IOException { - this(in.readString()); + public static ProjectId readFrom(StreamInput in) throws IOException { + final var id = in.readString(); + return Metadata.DEFAULT_PROJECT_ID.id.equals(id) ? Metadata.DEFAULT_PROJECT_ID : new ProjectId(id); } @Override diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectMetadata.java b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectMetadata.java index 24adeedd7366e..5ec42b0dc357d 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectMetadata.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectMetadata.java @@ -2021,7 +2021,7 @@ public Iterator toXContentChunked(ToXContent.Params p) { } public static ProjectMetadata readFrom(StreamInput in) throws IOException { - ProjectId id = new ProjectId(in); + ProjectId id = ProjectId.readFrom(in); Builder builder = builder(id); Function mappingLookup; Map mappingMetadataMap = in.readMapValues(MappingMetadata::new, MappingMetadata::getSha256); diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/GlobalRoutingTable.java b/server/src/main/java/org/elasticsearch/cluster/routing/GlobalRoutingTable.java index 642ea54881acc..1e7960aa30728 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/GlobalRoutingTable.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/GlobalRoutingTable.java @@ -178,7 +178,7 @@ public static Diff readDiffFrom(StreamInput in) throws IOExc } public static GlobalRoutingTable readFrom(StreamInput in) throws IOException { - final var table = in.readImmutableOpenMap(ProjectId::new, RoutingTable::readFrom); + final var table = in.readImmutableOpenMap(ProjectId::readFrom, RoutingTable::readFrom); return new GlobalRoutingTable(table); } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java index 762f14dfc2d36..7abcef56af5f0 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AbstractAllocateAllocationCommand.java @@ -109,7 +109,7 @@ protected AbstractAllocateAllocationCommand(StreamInput in) throws IOException { shardId = in.readVInt(); node = in.readString(); if (in.getTransportVersion().onOrAfter(TransportVersions.MULTI_PROJECT)) { - projectId = new ProjectId(in); + projectId = ProjectId.readFrom(in); } else { projectId = Metadata.DEFAULT_PROJECT_ID; } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java index 281e01e486bc4..f8d569e83330f 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java @@ -84,7 +84,7 @@ public CancelAllocationCommand(StreamInput in) throws IOException { node = in.readString(); allowPrimary = in.readBoolean(); if (in.getTransportVersion().onOrAfter(TransportVersions.MULTI_PROJECT)) { - projectId = new ProjectId(in); + projectId = ProjectId.readFrom(in); } else { projectId = Metadata.DEFAULT_PROJECT_ID; } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java index 0745ef22a1f06..a9efc705a9685 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java @@ -69,7 +69,7 @@ public MoveAllocationCommand(StreamInput in) throws IOException { fromNode = in.readString(); toNode = in.readString(); if (in.getTransportVersion().onOrAfter(TransportVersions.MULTI_PROJECT)) { - projectId = new ProjectId(in); + projectId = ProjectId.readFrom(in); } else { projectId = Metadata.DEFAULT_PROJECT_ID; } diff --git a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/DeleteProjectAction.java b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/DeleteProjectAction.java index 1f0c207149601..56a6378c9f461 100644 --- a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/DeleteProjectAction.java +++ b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/DeleteProjectAction.java @@ -147,7 +147,7 @@ public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, ProjectId proj public Request(StreamInput in) throws IOException { super(in); - this.projectId = new ProjectId(in); + this.projectId = ProjectId.readFrom(in); } @Override diff --git a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java index 8fd829b7812cf..24f231446981a 100644 --- a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java +++ b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java @@ -132,7 +132,7 @@ public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, ProjectId proj public Request(StreamInput in) throws IOException { super(in); - this.projectId = new ProjectId(in); + this.projectId = ProjectId.readFrom(in); } @Override From c321026c0eeccfeb6c97b37a1d8ccd883165ba07 Mon Sep 17 00:00:00 2001 From: Yang Wang Date: Wed, 5 Mar 2025 15:52:03 +1100 Subject: [PATCH 2/5] Singleton default project-id for both constructors --- .../cluster/metadata/Metadata.java | 2 +- .../cluster/metadata/ProjectId.java | 43 +++++++++++-- .../project/AbstractProjectResolver.java | 4 +- .../TransportClusterHealthActionTests.java | 10 +-- .../TransportClusterStateActionTests.java | 6 +- .../TransportCreateIndexActionTests.java | 2 +- .../action/bulk/TransportBulkActionTests.java | 2 +- .../DataStreamsActionUtilTests.java | 3 +- .../action/support/ActiveShardCountTests.java | 3 +- .../BroadcastReplicationTests.java | 2 +- .../TransportMultiTermVectorsActionTests.java | 2 +- .../cluster/ClusterChangedEventTests.java | 9 ++- .../cluster/ClusterStateTests.java | 12 ++-- .../health/ClusterStateHealthTests.java | 20 +++--- .../IndexNameExpressionResolverTests.java | 64 +++++++++---------- .../MetadataCreateIndexServiceTests.java | 18 +++--- .../cluster/metadata/MetadataTests.java | 30 ++++----- .../cluster/metadata/ProjectIdTests.java | 16 ++--- .../metadata/ProjectMetadataTests.java | 2 +- .../cluster/project/ProjectResolverTests.java | 12 ++-- .../routing/GlobalRoutingTableTests.java | 13 ++-- .../cluster/routing/RoutingTableTests.java | 3 +- .../allocation/AllocationServiceTests.java | 12 ++-- .../allocation/IndexMetadataUpdaterTests.java | 6 +- .../ResizeAllocationDeciderTests.java | 6 +- ...ResizeSourceIndexSettingsUpdaterTests.java | 14 ++-- .../routing/allocation/RoutingNodesTests.java | 2 +- .../BalancedShardsAllocatorTests.java | 2 +- .../DesiredBalanceReconcilerTests.java | 4 +- .../allocator/OrderedShardsIteratorTests.java | 5 +- .../decider/DiskThresholdDeciderTests.java | 4 +- .../decider/FilterAllocationDeciderTests.java | 5 +- ...eOnlyWhenActiveAllocationDeciderTests.java | 3 +- .../structure/RoutingIteratorTests.java | 2 +- .../PersistedClusterStateServiceTests.java | 4 +- .../TimestampFieldMapperServiceTests.java | 3 +- .../ingest/IngestServiceTests.java | 28 ++++---- .../security/SecurityRolesMultiProjectIT.java | 12 ++-- .../action/RestDeleteProjectAction.java | 2 +- .../action/RestPutProjectAction.java | 2 +- .../action/DeleteProjectActionTests.java | 6 +- .../cluster/project/TestProjectResolvers.java | 2 +- .../org/elasticsearch/test/ESTestCase.java | 4 +- .../project/TestProjectResolversTests.java | 14 ++-- ...PrimaryFollowerAllocationDeciderTests.java | 4 +- .../AsyncTaskMaintenanceServiceTests.java | 8 +-- .../bwc/ArchiveAllocationDeciderTests.java | 5 +- .../action/GetJobsActionRequestTests.java | 13 ++-- .../SearchableSnapshotAllocatorTests.java | 2 +- .../authz/AuthorizationServiceTests.java | 4 +- .../authz/IndicesAndAliasesResolverTests.java | 2 +- 51 files changed, 243 insertions(+), 215 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java b/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java index 9c54ba5648d17..55c0c29247b5f 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java @@ -88,7 +88,7 @@ public class Metadata implements Diffable, ChunkedToXContent { public static final String UNKNOWN_CLUSTER_UUID = "_na_"; // TODO multi-project: verify that usages are really expected to work on the default project only, // and that they are not a stop-gap solution to make the tests pass - public static final ProjectId DEFAULT_PROJECT_ID = new ProjectId("default"); + public static final ProjectId DEFAULT_PROJECT_ID = ProjectId.DEFAULT; public enum XContentContext { /* Custom metadata should be returned as part of API call */ diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java index 6f4e123903e82..11212cea917fd 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java @@ -19,17 +19,40 @@ import org.elasticsearch.xcontent.XContentParser; import java.io.IOException; +import java.util.Objects; -public record ProjectId(String id) implements Writeable, ToXContent { +public class ProjectId implements Writeable, ToXContent { + private static final String DEFAULT_STRING = "default"; + public static final ProjectId DEFAULT = new ProjectId(DEFAULT_STRING); public static final Reader READER = ProjectId::readFrom; private static final int MAX_LENGTH = 128; - public ProjectId { + private final String id; + + private ProjectId(String id) { if (Strings.isNullOrBlank(id)) { throw new IllegalArgumentException("project-id cannot be empty"); } - assert isValidFormatId(id) : "project-id [" + id + "] must be alphanumeric ASCII with up to " + MAX_LENGTH + " chars"; + final boolean validFormatId = isValidFormatId(id); + if (validFormatId == false) { + final var message = "project-id [" + id + "] must be alphanumeric ASCII with up to " + MAX_LENGTH + " chars"; + assert false : message; + throw new IllegalArgumentException(message); + } + this.id = id; + } + + public String id() { + return id; + } + + public static ProjectId fromId(String id) { + if (DEFAULT_STRING.equals(id)) { + return DEFAULT; + } else { + return new ProjectId(id); + } } static boolean isValidFormatId(String id) { @@ -55,7 +78,7 @@ private static boolean isValidIdChar(char c) { public static ProjectId readFrom(StreamInput in) throws IOException { final var id = in.readString(); - return Metadata.DEFAULT_PROJECT_ID.id.equals(id) ? Metadata.DEFAULT_PROJECT_ID : new ProjectId(id); + return DEFAULT_STRING.equals(id) ? DEFAULT : new ProjectId(id); } @Override @@ -80,4 +103,16 @@ public static ProjectId ofNullable(@Nullable String id, @Nullable ProjectId fall public String toString() { return this.id; } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) return false; + ProjectId projectId = (ProjectId) o; + return Objects.equals(id, projectId.id); + } + + @Override + public int hashCode() { + return Objects.hashCode(id); + } } diff --git a/server/src/main/java/org/elasticsearch/cluster/project/AbstractProjectResolver.java b/server/src/main/java/org/elasticsearch/cluster/project/AbstractProjectResolver.java index 8d13c529379de..250a2ac04ea96 100644 --- a/server/src/main/java/org/elasticsearch/cluster/project/AbstractProjectResolver.java +++ b/server/src/main/java/org/elasticsearch/cluster/project/AbstractProjectResolver.java @@ -50,7 +50,7 @@ public ProjectId getProjectId() { if (headerValue == null) { return getFallbackProjectId(); } - return new ProjectId(headerValue); + return ProjectId.fromId(headerValue); } @Override @@ -89,7 +89,7 @@ public boolean supportsMultipleProjects() { } protected static ProjectMetadata findProject(Metadata metadata, String headerValue) { - var project = metadata.projects().get(new ProjectId(headerValue)); + var project = metadata.projects().get(ProjectId.fromId(headerValue)); if (project == null) { throw new IllegalArgumentException("Could not find project with id [" + headerValue + "]"); } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthActionTests.java index 0907ba663f465..bc06ed2356469 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthActionTests.java @@ -41,21 +41,21 @@ public void testWaitForInitializingShards() throws Exception { final String[] indices = { "test" }; final ClusterHealthRequest request = new ClusterHealthRequest(TEST_REQUEST_TIMEOUT); request.waitForNoInitializingShards(true); - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); ClusterState clusterState = randomClusterStateWithInitializingShards("test", 0, projectId); var project = clusterState.metadata().getProject(projectId); ClusterHealthResponse response = createResponse(indices, clusterState, project); assertThat(TransportClusterHealthAction.prepareResponse(request, response, project, null), equalTo(1)); request.waitForNoInitializingShards(true); - projectId = new ProjectId(randomUUID()); + projectId = randomUniqueProjectId(); clusterState = randomClusterStateWithInitializingShards("test", between(1, 10), projectId); project = clusterState.metadata().getProject(projectId); response = createResponse(indices, clusterState, project); assertThat(TransportClusterHealthAction.prepareResponse(request, response, project, null), equalTo(0)); request.waitForNoInitializingShards(false); - projectId = new ProjectId(randomUUID()); + projectId = randomUniqueProjectId(); clusterState = randomClusterStateWithInitializingShards("test", randomInt(20), projectId); project = clusterState.metadata().getProject(projectId); response = createResponse(indices, clusterState, project); @@ -67,7 +67,7 @@ public void testWaitForAllShards() { final ClusterHealthRequest request = new ClusterHealthRequest(TEST_REQUEST_TIMEOUT); request.waitForActiveShards(ActiveShardCount.ALL); - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); ClusterState clusterState = randomClusterStateWithInitializingShards("test", 1, projectId); var project = clusterState.metadata().getProject(projectId); ClusterHealthResponse response = createResponse(indices, clusterState, project); @@ -125,7 +125,7 @@ ClusterState randomClusterStateWithInitializingShards(String index, final int in } var projects = randomMap(0, 5, () -> { - var id = new ProjectId(randomUUID()); + var id = randomUniqueProjectId(); return Tuple.tuple(id, ProjectMetadata.builder(id).build()); }); return ClusterState.builder(ClusterName.DEFAULT) diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/state/TransportClusterStateActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/state/TransportClusterStateActionTests.java index d21809cdf4630..29bdaf9b6b7c5 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/state/TransportClusterStateActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/state/TransportClusterStateActionTests.java @@ -107,7 +107,7 @@ public void testGetClusterStateWithDefaultProjectOnly() throws Exception { public void testGetClusterStateForOneProjectOfMany() throws Exception { final Set indexNames = randomSet(1, 8, () -> randomAlphaOfLengthBetween(4, 12)); - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); final ProjectResolver projectResolver = TestProjectResolvers.singleProject(projectId); final ClusterStateRequest request = buildRandomRequest(indexNames); @@ -117,7 +117,7 @@ public void testGetClusterStateForOneProjectOfMany() throws Exception { final ProjectMetadata.Builder[] projects = new ProjectMetadata.Builder[numberOfProjects]; projects[0] = projectBuilder(projectId, indexNames); for (int i = 1; i < numberOfProjects; i++) { - projects[i] = projectBuilder(new ProjectId(randomUUID()), randomSet(0, 12, () -> randomAlphaOfLengthBetween(4, 12))); + projects[i] = projectBuilder(randomUniqueProjectId(), randomSet(0, 12, () -> randomAlphaOfLengthBetween(4, 12))); } final ClusterState state = buildClusterState(projects); @@ -133,7 +133,7 @@ public void testGetClusterStateForManyProjects() throws Exception { final ProjectId[] projectIds = new ProjectId[numberOfProjects]; final Set indexNames = randomSet(5, 20, () -> randomAlphaOfLengthBetween(4, 12)); for (int i = 0; i < numberOfProjects; i++) { - projectIds[i] = new ProjectId(randomUUID()); + projectIds[i] = randomUniqueProjectId(); projects[i] = projectBuilder(projectIds[i], randomSubsetOf(indexNames)); } final ClusterState state = buildClusterState(projects); diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/create/TransportCreateIndexActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/indices/create/TransportCreateIndexActionTests.java index 8417509e17a2f..10a086675fa6a 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/create/TransportCreateIndexActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/create/TransportCreateIndexActionTests.java @@ -61,7 +61,7 @@ public class TransportCreateIndexActionTests extends ESTestCase { private static final String UNMANAGED_SYSTEM_INDEX_NAME = ".my-system"; private static final String MANAGED_SYSTEM_INDEX_NAME = ".my-managed"; private static final String SYSTEM_ALIAS_NAME = ".my-alias"; - private static final ProjectId PROJECT_ID = new ProjectId("test_project_id"); + private static final ProjectId PROJECT_ID = ProjectId.fromId("test_project_id"); private static final ClusterState CLUSTER_STATE = ClusterState.builder(new ClusterName("test")) .metadata(Metadata.builder().build()) .putProjectMetadata(ProjectMetadata.builder(PROJECT_ID).build()) diff --git a/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTests.java b/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTests.java index fdc0abf5880f5..294cb1fbdb7db 100644 --- a/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTests.java @@ -632,7 +632,7 @@ public void testFailuresDuringPrerequisiteActions() throws InterruptedException // Construct a cluster state that contains the required data streams. // using a single, non-default project final ClusterState oldState = clusterService.state(); - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); final Metadata metadata = Metadata.builder(oldState.metadata()) .removeProject(Metadata.DEFAULT_PROJECT_ID) .put( diff --git a/server/src/test/java/org/elasticsearch/action/datastreams/DataStreamsActionUtilTests.java b/server/src/test/java/org/elasticsearch/action/datastreams/DataStreamsActionUtilTests.java index 3e06afac1d22f..873d700423bd5 100644 --- a/server/src/test/java/org/elasticsearch/action/datastreams/DataStreamsActionUtilTests.java +++ b/server/src/test/java/org/elasticsearch/action/datastreams/DataStreamsActionUtilTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver.ResolvedExpression; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; @@ -52,7 +51,7 @@ public void testDataStreamsResolveConcreteIndexNames() { var dataStreamFailureIndex1 = new Index(".fs-foo1", IndexMetadata.INDEX_UUID_NA_VALUE); var dataStreamFailureIndex2 = new Index(".fs-bar2", IndexMetadata.INDEX_UUID_NA_VALUE); - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); ClusterState clusterState = ClusterState.builder(new ClusterName("test-cluster")) .putProjectMetadata( ProjectMetadata.builder(projectId) diff --git a/server/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java b/server/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java index 86a90c3760c6d..1096f92e4c605 100644 --- a/server/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.cluster.TestShardRoutingRoleStrategies; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; @@ -63,7 +62,7 @@ public void testEnoughShardsWhenProjectIsGone() { .numberOfShards(randomIntBetween(1, 3)) .numberOfReplicas(randomIntBetween(1, 3)) .build(); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(indexMetadata, randomBoolean()).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(indexMetadata, randomBoolean()).build(); Index index = new Index(indexName, "_uuid"); ShardId shardId = new ShardId(index, 0); ShardRouting shardRouting = ShardRouting.newUnassigned( diff --git a/server/src/test/java/org/elasticsearch/action/support/replication/BroadcastReplicationTests.java b/server/src/test/java/org/elasticsearch/action/support/replication/BroadcastReplicationTests.java index 57532dc9860f9..c1567d72d059a 100644 --- a/server/src/test/java/org/elasticsearch/action/support/replication/BroadcastReplicationTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/replication/BroadcastReplicationTests.java @@ -116,7 +116,7 @@ public void setUp() throws Exception { ); transportService.start(); transportService.acceptIncomingRequests(); - projectId = new ProjectId(randomUUID()); + projectId = randomUniqueProjectId(); broadcastReplicationAction = new TestBroadcastReplicationAction( clusterService, transportService, diff --git a/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java b/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java index 70c4d0ca8ce54..0bd348e0e398e 100644 --- a/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java @@ -91,7 +91,7 @@ public static void beforeClass() throws Exception { emptySet() ); - ProjectId projectId = new ProjectId(randomBase64UUID()); + ProjectId projectId = randomUniqueProjectId(); projectResolver = TestProjectResolvers.singleProject(projectId); final Index index1 = new Index("index1", randomBase64UUID()); final Index index2 = new Index("index2", randomBase64UUID()); diff --git a/server/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java b/server/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java index 24b6d50a07820..c08c82e27fa8b 100644 --- a/server/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.cluster.metadata.IndexGraveyard; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeRole; @@ -485,8 +484,8 @@ public void testChangedCustomMetadataSet() { public void testChangedCustomMetadataSetMultiProject() { final CustomProjectMetadata project1Custom = new CustomProjectMetadata("project1"); final CustomProjectMetadata project2Custom = new CustomProjectMetadata("project2"); - final ProjectMetadata project1 = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); - final ProjectMetadata project2 = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + final ProjectMetadata project1 = ProjectMetadata.builder(randomUniqueProjectId()).build(); + final ProjectMetadata project2 = ProjectMetadata.builder(randomUniqueProjectId()).build(); final ClusterState originalState = ClusterState.builder(TEST_CLUSTER_NAME) .metadata(Metadata.builder().put(project1).put(project2).build()) .build(); @@ -514,7 +513,7 @@ public void testChangedCustomMetadataSetMultiProject() { // Add custom in completely new project newState = ClusterState.builder(originalState) .putProjectMetadata( - ProjectMetadata.builder(new ProjectId(randomUUID())).putCustom(project2Custom.getWriteableName(), project2Custom).build() + ProjectMetadata.builder(randomUniqueProjectId()).putCustom(project2Custom.getWriteableName(), project2Custom).build() ) .build(); event = new ClusterChangedEvent("_na_", originalState, newState); @@ -727,7 +726,7 @@ private static DiscoveryNode newNode(final String nodeId, Set // Create the metadata for a cluster state. private static ProjectMetadata createProject(final List indices) { - final ProjectMetadata.Builder builder = ProjectMetadata.builder(new ProjectId(randomUUID())); + final ProjectMetadata.Builder builder = ProjectMetadata.builder(randomUniqueProjectId()); for (Index index : indices) { builder.put(createIndexMetadata(index), true); } diff --git a/server/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java b/server/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java index b065e02754341..14e13cc2ab5ca 100644 --- a/server/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java @@ -151,7 +151,7 @@ public void testCopyAndUpdateMetadata() throws IOException { public void testGetNonExistingProjectStateThrows() { final List projects = IntStream.range(0, between(1, 3)) - .mapToObj(i -> MetadataTests.randomProject(new ProjectId("p_" + i), between(0, 5))) + .mapToObj(i -> MetadataTests.randomProject(ProjectId.fromId("p_" + i), between(0, 5))) .toList(); final Metadata metadata = MetadataTests.randomMetadata(projects); final ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(metadata).build(); @@ -835,7 +835,7 @@ private static ClusterState buildMultiProjectClusterState(DiscoveryNode... nodes .build() ) .put( - ProjectMetadata.builder(new ProjectId("3LftaL7hgfXAsF60Gm6jcD")) + ProjectMetadata.builder(ProjectId.fromId("3LftaL7hgfXAsF60Gm6jcD")) .put( IndexMetadata.builder("common-index") .settings( @@ -850,7 +850,7 @@ private static ClusterState buildMultiProjectClusterState(DiscoveryNode... nodes ) ) .put( - ProjectMetadata.builder(new ProjectId("tb5W0bx765nDVIwqJPw92G")) + ProjectMetadata.builder(ProjectId.fromId("tb5W0bx765nDVIwqJPw92G")) .put( IndexMetadata.builder("common-index") .settings( @@ -858,7 +858,7 @@ private static ClusterState buildMultiProjectClusterState(DiscoveryNode... nodes ) ) ) - .put(ProjectMetadata.builder(new ProjectId("WHyuJ0uqBYOPgHX9kYUXlZ"))) + .put(ProjectMetadata.builder(ProjectId.fromId("WHyuJ0uqBYOPgHX9kYUXlZ"))) .build(); final DiscoveryNodes.Builder discoveryNodes = DiscoveryNodes.builder(); for (var node : nodes) { @@ -874,8 +874,8 @@ private static ClusterState buildMultiProjectClusterState(DiscoveryNode... nodes .blocks( ClusterBlocks.builder() .addGlobalBlock(Metadata.CLUSTER_READ_ONLY_BLOCK) - .addIndexBlock(new ProjectId("tb5W0bx765nDVIwqJPw92G"), "common-index", IndexMetadata.INDEX_METADATA_BLOCK) - .addIndexBlock(new ProjectId("3LftaL7hgfXAsF60Gm6jcD"), "another-index", IndexMetadata.INDEX_READ_ONLY_BLOCK) + .addIndexBlock(ProjectId.fromId("tb5W0bx765nDVIwqJPw92G"), "common-index", IndexMetadata.INDEX_METADATA_BLOCK) + .addIndexBlock(ProjectId.fromId("3LftaL7hgfXAsF60Gm6jcD"), "another-index", IndexMetadata.INDEX_READ_ONLY_BLOCK) ) .build(); } diff --git a/server/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java b/server/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java index 9b530be665003..cd00b7749e899 100644 --- a/server/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java @@ -127,7 +127,7 @@ public void testClusterHealthWaitsForClusterStateApplication() throws Interrupte var projectId = state.metadata().projects().keySet().iterator().next(); // Randomly add an extra project. if (randomBoolean()) { - state = ClusterState.builder(state).putProjectMetadata(ProjectMetadata.builder(new ProjectId(randomUUID())).build()).build(); + state = ClusterState.builder(state).putProjectMetadata(ProjectMetadata.builder(randomUniqueProjectId()).build()).build(); } setState(clusterService, state); @@ -183,7 +183,7 @@ public void testClusterHealth() throws IOException { RoutingTableGenerator routingTableGenerator = new RoutingTableGenerator(); RoutingTableGenerator.ShardCounter counter = new RoutingTableGenerator.ShardCounter(); RoutingTable.Builder routingTable = RoutingTable.builder(); - ProjectId projectId = new ProjectId(randomUUID()); + ProjectId projectId = randomUniqueProjectId(); ProjectMetadata.Builder project = ProjectMetadata.builder(projectId); for (int i = randomInt(4); i >= 0; i--) { int numberOfShards = randomInt(3) + 1; @@ -215,7 +215,7 @@ public void testClusterHealth() throws IOException { public void testClusterHealthOnIndexCreation() { final String indexName = "test-idx"; final String[] indices = new String[] { indexName }; - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); final List clusterStates = simulateIndexCreationStates(indexName, false, projectId); for (int i = 0; i < clusterStates.size(); i++) { // make sure cluster health is always YELLOW, up until the last state where it should be GREEN @@ -232,7 +232,7 @@ public void testClusterHealthOnIndexCreation() { public void testClusterHealthOnIndexCreationWithFailedAllocations() { final String indexName = "test-idx"; final String[] indices = new String[] { indexName }; - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); final List clusterStates = simulateIndexCreationStates(indexName, true, projectId); for (int i = 0; i < clusterStates.size(); i++) { // make sure cluster health is YELLOW up until the final cluster state, which contains primary shard @@ -250,7 +250,7 @@ public void testClusterHealthOnIndexCreationWithFailedAllocations() { public void testClusterHealthOnClusterRecovery() { final String indexName = "test-idx"; final String[] indices = new String[] { indexName }; - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); final List clusterStates = simulateClusterRecoveryStates(indexName, false, false, projectId); for (int i = 0; i < clusterStates.size(); i++) { // make sure cluster health is YELLOW up until the final cluster state, when it turns GREEN @@ -267,7 +267,7 @@ public void testClusterHealthOnClusterRecovery() { public void testClusterHealthOnClusterRecoveryWithFailures() { final String indexName = "test-idx"; final String[] indices = new String[] { indexName }; - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); final List clusterStates = simulateClusterRecoveryStates(indexName, false, true, projectId); for (int i = 0; i < clusterStates.size(); i++) { // make sure cluster health is YELLOW up until the final cluster state, which contains primary shard @@ -285,7 +285,7 @@ public void testClusterHealthOnClusterRecoveryWithFailures() { public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIds() { final String indexName = "test-idx"; final String[] indices = new String[] { indexName }; - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); final List clusterStates = simulateClusterRecoveryStates(indexName, true, false, projectId); for (int i = 0; i < clusterStates.size(); i++) { // because there were previous allocation ids, we should be RED until the primaries are started, @@ -309,7 +309,7 @@ public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIds() { public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIdsAndAllocationFailures() { final String indexName = "test-idx"; final String[] indices = new String[] { indexName }; - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); for (final ClusterState clusterState : simulateClusterRecoveryStates(indexName, true, true, projectId)) { final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices, projectId); // if the inactive primaries are due solely to recovery (not failed allocation or previously being allocated) @@ -350,7 +350,7 @@ private List simulateIndexCreationStates( .put(projectId, RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY).addAsNew(indexMetadata)); final int nrOfProjects = randomIntBetween(0, 5); for (int i = 0; i < nrOfProjects; i++) { - var id = new ProjectId(randomUUID()); + var id = randomUniqueProjectId(); mdBuilder.put(ProjectMetadata.builder(id).build()); rtBuilder.put(id, RoutingTable.EMPTY_ROUTING_TABLE); } @@ -393,7 +393,7 @@ private List simulateClusterRecoveryStates( .put(projectId, RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY).addAsNew(indexMetadata)); final int nrOfProjects = randomIntBetween(0, 5); for (int i = 0; i < nrOfProjects; i++) { - var id = new ProjectId(randomUUID()); + var id = randomUniqueProjectId(); mdBuilder.put(ProjectMetadata.builder(id).build()); rtBuilder.put(id, RoutingTable.EMPTY_ROUTING_TABLE); } diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolverTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolverTests.java index f8d8b9dc8cd13..d2928a782da51 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolverTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolverTests.java @@ -108,7 +108,7 @@ public void setUp() throws Exception { } public void testConcreteIndexNamesStrictExpand() { - final ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + final ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foobar").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foofoo-closed").state(State.CLOSE)) @@ -182,7 +182,7 @@ public void testConcreteIndexNamesStrictExpand() { } public void testConcreteIndexNamesLenientExpand() { - final ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + final ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foobar").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foofoo-closed").state(State.CLOSE)) @@ -242,7 +242,7 @@ public void testConcreteIndexNamesLenientExpand() { } public void testConcreteIndexNamesIgnoreUnavailableDisallowEmpty() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo")) .put(indexBuilder("foobar")) .put(indexBuilder("foofoo-closed").state(IndexMetadata.State.CLOSE)) @@ -296,7 +296,7 @@ public void testConcreteIndexNamesIgnoreUnavailableDisallowEmpty() { } public void testConcreteIndexNamesExpandWildcards() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo").state(IndexMetadata.State.CLOSE)) .put(indexBuilder("bar")) .put(indexBuilder("foobar").putAlias(AliasMetadata.builder("barbaz"))) @@ -521,7 +521,7 @@ public void testConcreteIndexNamesExpandWildcards() { } public void testConcreteIndexNamesNoExpandWildcards() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foobar").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foofoo-closed").state(IndexMetadata.State.CLOSE)) @@ -649,7 +649,7 @@ public void testConcreteIndexNamesNoExpandWildcards() { } public void testIndexOptionsSingleIndexNoExpandWildcards() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foobar").putAlias(AliasMetadata.builder("foofoobar"))) .put(indexBuilder("foofoo-closed").state(IndexMetadata.State.CLOSE)) @@ -735,7 +735,7 @@ public void testIndexOptionsSingleIndexNoExpandWildcards() { } public void testIndexOptionsEmptyCluster() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndicesOptions options = IndicesOptions.strictExpandOpen(); final IndexNameExpressionResolver.Context context = new IndexNameExpressionResolver.Context( @@ -824,7 +824,7 @@ public void testIndexOptionsEmptyCluster() { } public void testConcreteIndicesIgnoreIndicesOneMissingIndex() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")) .build(); @@ -852,7 +852,7 @@ public void testConcreteIndicesIgnoreIndicesOneMissingIndex() { } public void testConcreteIndicesIgnoreIndicesOneMissingIndexOtherFound() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")) .build(); @@ -869,7 +869,7 @@ public void testConcreteIndicesIgnoreIndicesOneMissingIndexOtherFound() { } public void testConcreteIndicesIgnoreIndicesAllMissing() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")) .build(); @@ -898,7 +898,7 @@ public void testConcreteIndicesIgnoreIndicesAllMissing() { } public void testConcreteIndicesIgnoreIndicesEmptyRequest() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")) .build(); @@ -911,7 +911,7 @@ public void testConcreteIndicesIgnoreIndicesEmptyRequest() { } public void testConcreteIndicesNoIndicesErrorMessage() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndexNameExpressionResolver.Context context = new IndexNameExpressionResolver.Context( project, IndicesOptions.fromOptions(false, false, true, true), @@ -925,7 +925,7 @@ public void testConcreteIndicesNoIndicesErrorMessage() { } public void testConcreteIndicesNoIndicesErrorMessageNoExpand() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndexNameExpressionResolver.Context context = new IndexNameExpressionResolver.Context( project, IndicesOptions.fromOptions(false, false, false, false), @@ -939,7 +939,7 @@ public void testConcreteIndicesNoIndicesErrorMessageNoExpand() { } public void testConcreteIndicesWildcardExpansion() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("testXXX").state(State.OPEN)) .put(indexBuilder("testXXY").state(State.OPEN)) .put(indexBuilder("testXYY").state(State.CLOSE)) @@ -980,7 +980,7 @@ public void testConcreteIndicesWildcardExpansion() { } public void testConcreteIndicesWildcardWithNegation() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("testXXX").state(State.OPEN)) .put(indexBuilder("testXXY").state(State.OPEN)) .put(indexBuilder("testXYY").state(State.OPEN)) @@ -1073,7 +1073,7 @@ public void testConcreteIndicesWildcardWithNegation() { } public void testConcreteIndicesWildcardAndAliases() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("foo_foo").state(State.OPEN).putAlias(AliasMetadata.builder("foo"))) .put(indexBuilder("bar_bar").state(State.OPEN).putAlias(AliasMetadata.builder("foo"))) .build(); @@ -1174,7 +1174,7 @@ public void testHiddenAliasAndHiddenIndexResolution() { { // A visible index with a visible alias and a hidden index with a hidden alias - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder(visibleIndex).state(State.OPEN).putAlias(AliasMetadata.builder(visibleAlias))) .put( indexBuilder(hiddenIndex, Settings.builder().put(INDEX_HIDDEN_SETTING.getKey(), true).build()).state(State.OPEN) @@ -1217,7 +1217,7 @@ public void testHiddenAliasAndHiddenIndexResolution() { { // A visible alias that points to one hidden and one visible index - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder(visibleIndex).state(State.OPEN).putAlias(AliasMetadata.builder(visibleAlias))) .put( indexBuilder(hiddenIndex, Settings.builder().put(INDEX_HIDDEN_SETTING.getKey(), true).build()).state(State.OPEN) @@ -1243,7 +1243,7 @@ public void testHiddenAliasAndHiddenIndexResolution() { { // A hidden alias that points to one hidden and one visible index - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder(visibleIndex).state(State.OPEN).putAlias(AliasMetadata.builder(hiddenAlias).isHidden(true))) .put( indexBuilder(hiddenIndex, Settings.builder().put(INDEX_HIDDEN_SETTING.getKey(), true).build()).state(State.OPEN) @@ -1274,7 +1274,7 @@ public void testHiddenAliasAndHiddenIndexResolution() { { // A hidden alias with a dot-prefixed name that points to one hidden index with a dot prefix, and one hidden index without - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put( indexBuilder(dottedHiddenIndex, Settings.builder().put(INDEX_HIDDEN_SETTING.getKey(), true).build()).state(State.OPEN) .putAlias(AliasMetadata.builder(dottedHiddenAlias).isHidden(true)) @@ -1310,7 +1310,7 @@ public void testHiddenIndexWithVisibleAliasOverlappingNameResolution() { IndicesOptions excludeHiddenOptions = IndicesOptions.fromOptions(false, true, true, false, false, true, false, false, false); IndicesOptions includeHiddenOptions = IndicesOptions.fromOptions(false, true, true, false, true, true, false, false, false); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put( indexBuilder(hiddenIndex, Settings.builder().put(INDEX_HIDDEN_SETTING.getKey(), true).build()).state(State.OPEN) .putAlias(AliasMetadata.builder(hiddenAlias).isHidden(true)) @@ -1349,7 +1349,7 @@ public void testConcreteIndicesAllPatternRandom() { ); { - final ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + final ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndexNameExpressionResolver.Context context = new IndexNameExpressionResolver.Context( project, indicesOptions, @@ -1368,7 +1368,7 @@ public void testConcreteIndicesAllPatternRandom() { { // with existing indices, asking for all indices should return all open/closed indices depending on options - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("aaa").state(State.OPEN).putAlias(AliasMetadata.builder("aaa_alias1"))) .put(indexBuilder("bbb").state(State.OPEN).putAlias(AliasMetadata.builder("bbb_alias1"))) .put(indexBuilder("ccc").state(State.CLOSE).putAlias(AliasMetadata.builder("ccc_alias1"))) @@ -1402,7 +1402,7 @@ public void testConcreteIndicesAllPatternRandom() { public void testConcreteIndicesWildcardNoMatch() { for (int i = 0; i < 10; i++) { IndicesOptions indicesOptions = IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("aaa").state(State.OPEN).putAlias(AliasMetadata.builder("aaa_alias1"))) .put(indexBuilder("bbb").state(State.OPEN).putAlias(AliasMetadata.builder("bbb_alias1"))) .put(indexBuilder("ccc").state(State.CLOSE).putAlias(AliasMetadata.builder("ccc_alias1"))) @@ -1478,7 +1478,7 @@ public void testIsExplicitAllIndicesWildcard() { } public void testIndexOptionsFailClosedIndicesAndAliases() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put( indexBuilder("foo1-closed").state(IndexMetadata.State.CLOSE) .putAlias(AliasMetadata.builder("foobar1-closed")) @@ -1557,7 +1557,7 @@ public void testIndexOptionsFailClosedIndicesAndAliases() { } public void testDedupConcreteIndices() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("index1").putAlias(AliasMetadata.builder("alias1"))) .build(); IndicesOptions[] indicesOptions = new IndicesOptions[] { @@ -1577,7 +1577,7 @@ public void testDedupConcreteIndices() { } public void testFilterClosedIndicesOnAliases() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("test-0").state(State.OPEN).putAlias(AliasMetadata.builder("alias-0"))) .put(indexBuilder("test-1").state(IndexMetadata.State.CLOSE).putAlias(AliasMetadata.builder("alias-1"))) .build(); @@ -1848,7 +1848,7 @@ public IndicesOptions indicesOptions() { } public void testConcreteWriteIndexWithInvalidIndicesRequest() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("test-0").state(State.OPEN).putAlias(AliasMetadata.builder("test-alias"))) .build(); Function requestGen = (indices) -> new IndicesRequest() { @@ -2122,7 +2122,7 @@ public void testDeleteIndexIgnoresAliases() { } public void testIndicesAliasesRequestIgnoresAliases() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(indexBuilder("test-index").state(State.OPEN).putAlias(AliasMetadata.builder("test-alias"))) .put(indexBuilder("index").state(State.OPEN).putAlias(AliasMetadata.builder("test-alias2"))) .build(); @@ -2225,7 +2225,7 @@ public void testIndicesAliasesRequestTargetDataStreams() { final String dataStreamName = "my-data-stream"; IndexMetadata backingIndex = createBackingIndex(dataStreamName, 1).build(); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .put(backingIndex, false) .put(newInstance(dataStreamName, List.of(backingIndex.getIndex()))) .build(); @@ -2258,7 +2258,7 @@ public void testIndicesAliasesRequestTargetDataStreams() { } public void testInvalidIndex() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())).put(indexBuilder("test")).build(); + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()).put(indexBuilder("test")).build(); IndexNameExpressionResolver.Context context = new IndexNameExpressionResolver.Context( project, IndicesOptions.lenientExpandOpen(), @@ -3328,7 +3328,7 @@ public void testMathExpressionSupportWithOlderDate() { } public void testRemoteIndex() { - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()).build(); { IndicesOptions options = IndicesOptions.fromOptions(false, randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()); diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexServiceTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexServiceTests.java index e2bcc8e95aeaf..7c0fc80ea73c4 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexServiceTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexServiceTests.java @@ -565,7 +565,7 @@ public void testCreateIndexInUnknownProject() { new IndexSettingProviders(Set.of()) ); PlainActionFuture createIndexFuture = new PlainActionFuture<>(); - ProjectId unknownProjectId = new ProjectId(randomUUID()); + ProjectId unknownProjectId = randomUniqueProjectId(); checkerService.createIndex( TimeValue.MAX_VALUE, TimeValue.MAX_VALUE, @@ -931,7 +931,7 @@ public void testInvalidAliasName() { request.index(), request.aliases(), List.of(), - ProjectMetadata.builder(new ProjectId(randomUUID())).build(), + ProjectMetadata.builder(randomUniqueProjectId()).build(), xContentRegistry(), searchExecutionContext, IndexNameExpressionResolver::resolveDateMathExpression, @@ -949,7 +949,7 @@ public void testAliasNameWithMathExpression() { request.index(), request.aliases(), List.of(), - ProjectMetadata.builder(new ProjectId(randomUUID())).build(), + ProjectMetadata.builder(randomUniqueProjectId()).build(), xContentRegistry(), searchExecutionContext, IndexNameExpressionResolver::resolveDateMathExpression, @@ -983,7 +983,7 @@ public void testRequestDataHavePriorityOverTemplateData() throws Exception { request.index(), request.aliases(), MetadataIndexTemplateService.resolveAliases(List.of(templateMetadata)), - ProjectMetadata.builder(new ProjectId(randomUUID())).build(), + ProjectMetadata.builder(randomUniqueProjectId()).build(), xContentRegistry(), searchExecutionContext, IndexNameExpressionResolver::resolveDateMathExpression, @@ -1083,7 +1083,7 @@ public void testTemplateOrder() throws Exception { request.index(), request.aliases(), MetadataIndexTemplateService.resolveAliases(templates), - ProjectMetadata.builder(new ProjectId(randomUUID())).build(), + ProjectMetadata.builder(randomUniqueProjectId()).build(), xContentRegistry(), searchExecutionContext, IndexNameExpressionResolver::resolveDateMathExpression, @@ -1124,7 +1124,7 @@ public void testResolvedAliasInTemplate() { request.index(), request.aliases(), MetadataIndexTemplateService.resolveAliases(templates), - ProjectMetadata.builder(new ProjectId(randomUUID())).build(), + ProjectMetadata.builder(randomUniqueProjectId()).build(), xContentRegistry(), searchExecutionContext, IndexNameExpressionResolver::resolveDateMathExpression, @@ -1173,7 +1173,7 @@ public void testClusterStateCreateIndexThrowsWriteIndexValidationException() thr .numberOfShards(1) .numberOfReplicas(0) .build(); - ProjectId projectId = new ProjectId(randomUUID()); + ProjectId projectId = randomUniqueProjectId(); ClusterState currentClusterState = ClusterState.builder(ClusterState.EMPTY_STATE) .putProjectMetadata(ProjectMetadata.builder(projectId).put(existingWriteIndex, false)) .build(); @@ -1202,7 +1202,7 @@ public void testClusterStateCreateIndexThrowsWriteIndexValidationException() thr } public void testClusterStateCreateIndex() { - ProjectId projectId = new ProjectId(randomUUID()); + ProjectId projectId = randomUniqueProjectId(); ClusterState currentClusterState = ClusterState.builder(ClusterState.EMPTY_STATE) .putProjectMetadata(ProjectMetadata.builder(projectId)) .build(); @@ -1238,7 +1238,7 @@ public void testClusterStateCreateIndex() { } public void testClusterStateCreateIndexWithMetadataTransaction() { - ProjectId projectId = new ProjectId(randomUUID()); + ProjectId projectId = randomUniqueProjectId(); ClusterState currentClusterState = ClusterState.builder(ClusterState.EMPTY_STATE) .putProjectMetadata( ProjectMetadata.builder(projectId) diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataTests.java index 300005bf7d1d1..146dd13186b7e 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/MetadataTests.java @@ -679,10 +679,10 @@ public void testMetadataGlobalStateChangesOnClusterUUIDChanges() { public void testMetadataGlobalStateChangesOnProjectChanges() { final Metadata metadata1 = Metadata.builder().build(); - final Metadata metadata2 = Metadata.builder(metadata1).put(ProjectMetadata.builder(new ProjectId(randomUUID())).build()).build(); + final Metadata metadata2 = Metadata.builder(metadata1).put(ProjectMetadata.builder(randomUniqueProjectId()).build()).build(); final Metadata metadata3 = Metadata.builder(metadata1) .put( - ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata.builder(randomUniqueProjectId()) .put(IndexMetadata.builder("some-index").settings(indexSettings(IndexVersion.current(), 1, 1))) .build() ) @@ -690,7 +690,7 @@ public void testMetadataGlobalStateChangesOnProjectChanges() { // A project with a ProjectCustom. final Metadata metadata4 = Metadata.builder(metadata1) .put( - ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata.builder(randomUniqueProjectId()) .put("template", new ComponentTemplate(new Template(null, null, null), null, null)) .build() ) @@ -1568,8 +1568,8 @@ public void testSerialization() throws IOException { public void testMultiProjectSerialization() throws IOException { // TODO: this whole suite needs to be updated for multiple projects - ProjectMetadata project1 = randomProject(new ProjectId("1"), 1); - ProjectMetadata project2 = randomProject(new ProjectId("2"), randomIntBetween(2, 10)); + ProjectMetadata project1 = randomProject(ProjectId.fromId("1"), 1); + ProjectMetadata project2 = randomProject(ProjectId.fromId("2"), randomIntBetween(2, 10)); Metadata metadata = randomMetadata(List.of(project1, project2)); BytesStreamOutput out = new BytesStreamOutput(); metadata.writeTo(out); @@ -1632,7 +1632,7 @@ public void testDiffSerializationPreMultiProject() throws IOException { public void testGetNonExistingProjectThrows() { final List projects = IntStream.range(0, between(1, 3)) - .mapToObj(i -> randomProject(new ProjectId("p_" + i), between(0, 5))) + .mapToObj(i -> randomProject(ProjectId.fromId("p_" + i), between(0, 5))) .toList(); final Metadata metadata = randomMetadata(projects); expectThrows(IllegalArgumentException.class, () -> metadata.getProject(randomProjectIdOrDefault())); @@ -2587,7 +2587,7 @@ public void testEmptyDiffReturnsSameInstance() throws IOException { public void testMultiProjectXContent() throws IOException { final long lastAllocationId = randomNonNegativeLong(); - final List projects = randomList(1, 5, () -> randomProject(new ProjectId(randomUUID()), randomIntBetween(1, 3))) + final List projects = randomList(1, 5, () -> randomProject(randomUniqueProjectId(), randomIntBetween(1, 3))) .stream() .map( project -> ProjectMetadata.builder(project) @@ -2658,7 +2658,7 @@ public void testMultiProjectXContent() throws IOException { public void testSingleNonDefaultProjectXContent() throws IOException { // When ClusterStateAction acts in a project scope, it returns cluster state metadata that has a single project that may // not have the default project-id. We need to be able to convert this to XContent in the Rest response - final ProjectMetadata project = ProjectMetadata.builder(new ProjectId("c8af967d644b3219")) + final ProjectMetadata project = ProjectMetadata.builder(ProjectId.fromId("c8af967d644b3219")) .put(IndexMetadata.builder("index-1").settings(indexSettings(IndexVersion.current(), 1, 1)).build(), false) .put(IndexMetadata.builder("index-2").settings(indexSettings(IndexVersion.current(), 2, 2)).build(), false) .build(); @@ -2987,14 +2987,14 @@ public void testGetSingleProjectWithCustom() { assertNull(metadata.getSingleProjectWithCustom(type)); } { - Metadata metadata = Metadata.builder().put(ProjectMetadata.builder(new ProjectId(randomUUID())).build()).build(); + Metadata metadata = Metadata.builder().put(ProjectMetadata.builder(randomUniqueProjectId()).build()).build(); assertNull(metadata.getSingleProjectCustom(type)); assertNull(metadata.getSingleProjectWithCustom(type)); } { var ingestMetadata = new IngestMetadata(Map.of()); Metadata metadata = Metadata.builder() - .put(ProjectMetadata.builder(new ProjectId(randomUUID())).putCustom(type, ingestMetadata)) + .put(ProjectMetadata.builder(randomUniqueProjectId()).putCustom(type, ingestMetadata)) .build(); assertEquals(ingestMetadata, metadata.getSingleProjectCustom(type)); assertEquals(ingestMetadata, metadata.getSingleProjectWithCustom(type).custom(type)); @@ -3002,8 +3002,8 @@ public void testGetSingleProjectWithCustom() { { var ingestMetadata = new IngestMetadata(Map.of()); Metadata metadata = Metadata.builder() - .put(ProjectMetadata.builder(new ProjectId(randomUUID()))) - .put(ProjectMetadata.builder(new ProjectId(randomUUID())).putCustom(type, ingestMetadata)) + .put(ProjectMetadata.builder(randomUniqueProjectId())) + .put(ProjectMetadata.builder(randomUniqueProjectId()).putCustom(type, ingestMetadata)) .build(); assertEquals(ingestMetadata, metadata.getSingleProjectCustom(type)); assertEquals(ingestMetadata, metadata.getSingleProjectWithCustom(type).custom(type)); @@ -3011,8 +3011,8 @@ public void testGetSingleProjectWithCustom() { { var ingestMetadata = new IngestMetadata(Map.of()); Metadata metadata = Metadata.builder() - .put(ProjectMetadata.builder(new ProjectId(randomUUID())).putCustom(type, new IngestMetadata(Map.of()))) - .put(ProjectMetadata.builder(new ProjectId(randomUUID())).putCustom(type, ingestMetadata)) + .put(ProjectMetadata.builder(randomUniqueProjectId()).putCustom(type, new IngestMetadata(Map.of()))) + .put(ProjectMetadata.builder(randomUniqueProjectId()).putCustom(type, ingestMetadata)) .build(); assertThrows(UnsupportedOperationException.class, () -> metadata.getSingleProjectCustom(type)); assertThrows(UnsupportedOperationException.class, () -> metadata.getSingleProjectWithCustom(type)); @@ -3056,7 +3056,7 @@ public void testProjectLookupWithMultipleProjects() { final Metadata.Builder metadataBuilder = Metadata.builder(); final Map> indices = Maps.newMapWithExpectedSize(numberOfProjects); for (int p = 1; p <= numberOfProjects; p++) { - final ProjectId projectId = new ProjectId(org.elasticsearch.core.Strings.format("proj_%02d", p)); + final ProjectId projectId = ProjectId.fromId(org.elasticsearch.core.Strings.format("proj_%02d", p)); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(projectId); final int numberOfIndices = randomIntBetween(p, 10); diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectIdTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectIdTests.java index 0eaf81921889b..30fbfad730327 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectIdTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectIdTests.java @@ -22,9 +22,9 @@ public class ProjectIdTests extends AbstractWireSerializingTestCase { public void testCannotCreateBlankProjectId() { - expectThrows(IllegalArgumentException.class, () -> new ProjectId((String) null)); - expectThrows(IllegalArgumentException.class, () -> new ProjectId("")); - expectThrows(IllegalArgumentException.class, () -> new ProjectId(" ")); + expectThrows(IllegalArgumentException.class, () -> ProjectId.fromId(null)); + expectThrows(IllegalArgumentException.class, () -> ProjectId.fromId("")); + expectThrows(IllegalArgumentException.class, () -> ProjectId.fromId(" ")); } public void testValidateProjectId() { @@ -63,10 +63,10 @@ protected Writeable.Reader instanceReader() { @Override protected ProjectId createTestInstance() { return switch (randomIntBetween(1, 4)) { - case 1 -> new ProjectId(randomUUID()); - case 2 -> new ProjectId(randomAlphaOfLengthBetween(1, 30)); - case 3 -> new ProjectId(Long.toString(randomLongBetween(1, Long.MAX_VALUE))); - default -> new ProjectId(Long.toString(randomLongBetween(1, Long.MAX_VALUE), Character.MAX_RADIX)); + case 1 -> randomUniqueProjectId(); + case 2 -> ProjectId.fromId(randomAlphaOfLengthBetween(1, 30)); + case 3 -> ProjectId.fromId(Long.toString(randomLongBetween(1, Long.MAX_VALUE))); + default -> ProjectId.fromId(Long.toString(randomLongBetween(1, Long.MAX_VALUE), Character.MAX_RADIX)); }; } @@ -77,7 +77,7 @@ protected ProjectId mutateInstance(ProjectId instance) throws IOException { public void testToString() { String s = randomAlphaOfLengthBetween(8, 16); - ProjectId id = new ProjectId(s); + ProjectId id = ProjectId.fromId(s); assertThat(id.toString(), equalTo(s)); } } diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectMetadataTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectMetadataTests.java index c8dc8177b74eb..ee84c63a0cc37 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectMetadataTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/ProjectMetadataTests.java @@ -34,7 +34,7 @@ public class ProjectMetadataTests extends ESTestCase { public void testToXContent() throws IOException { - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); final ProjectMetadata.Builder builder = ProjectMetadata.builder(projectId); for (int i = 1; i <= 3; i++) { builder.put( diff --git a/server/src/test/java/org/elasticsearch/cluster/project/ProjectResolverTests.java b/server/src/test/java/org/elasticsearch/cluster/project/ProjectResolverTests.java index a1730181ee63f..6fdf1ce9fd619 100644 --- a/server/src/test/java/org/elasticsearch/cluster/project/ProjectResolverTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/project/ProjectResolverTests.java @@ -69,7 +69,7 @@ public void cleanup() { public void testGetById() { var projects = createProjects(); - var expectedProject = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + var expectedProject = ProjectMetadata.builder(randomUniqueProjectId()).build(); projects.put(expectedProject.id(), expectedProject); var metadata = Metadata.builder().projectMetadata(projects).build(); threadPool.getThreadContext().putHeader(Task.X_ELASTIC_PROJECT_ID_HTTP_HEADER, expectedProject.id().id()); @@ -114,7 +114,7 @@ public void testGetByIdNonExisting() { public void testGetAllProjectIdsWhenAllowed() { allowAllProjects = () -> true; var projects = createProjects(); - var randomProject = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + var randomProject = ProjectMetadata.builder(randomUniqueProjectId()).build(); projects.put(randomProject.id(), randomProject); var state = ClusterState.builder(ClusterName.DEFAULT).metadata(Metadata.builder().projectMetadata(projects).build()).build(); var actualProjects = resolver.getProjectIds(state); @@ -134,7 +134,7 @@ public void testGetAllProjectIdsWhenNotAllowed() { public void testGetProjectIdsWithHeader() { var projects = createProjects(); - var expectedProject = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + var expectedProject = ProjectMetadata.builder(randomUniqueProjectId()).build(); projects.put(expectedProject.id(), expectedProject); var state = ClusterState.builder(ClusterName.DEFAULT).metadata(Metadata.builder().projectMetadata(projects).build()).build(); threadPool.getThreadContext().putHeader(Task.X_ELASTIC_PROJECT_ID_HTTP_HEADER, expectedProject.id().id()); @@ -144,8 +144,8 @@ public void testGetProjectIdsWithHeader() { } public void testExecuteOnProject() { - final ProjectId projectId1 = new ProjectId("1-" + randomAlphaOfLength(4)); - final ProjectId projectId2 = new ProjectId("2-" + randomAlphaOfLength(4)); + final ProjectId projectId1 = randomUniqueProjectId(); + final ProjectId projectId2 = randomUniqueProjectId(); final Map projects = createProjects(); projects.put(projectId1, ProjectMetadata.builder(projectId1).build()); @@ -214,7 +214,7 @@ public void testShouldSupportsMultipleProjects() { private static Map createProjects() { return randomMap(0, 5, () -> { - var id = new ProjectId(randomUUID()); + var id = randomUniqueProjectId(); return Tuple.tuple(id, ProjectMetadata.builder(id).build()); }); } diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/GlobalRoutingTableTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/GlobalRoutingTableTests.java index 84774e499e13e..fbaaf876116b8 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/GlobalRoutingTableTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/GlobalRoutingTableTests.java @@ -31,6 +31,7 @@ import org.elasticsearch.index.IndexVersion; import org.elasticsearch.test.AbstractWireSerializingTestCase; import org.elasticsearch.test.DiffableTestUtils; +import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.TransportVersionUtils; import java.io.IOException; @@ -208,7 +209,7 @@ public void testInitializeProjects() { Set addition = randomSet( 1, 5, - () -> randomValueOtherThanMany(table1.routingTables()::containsKey, () -> new ProjectId(randomUUID())) + () -> randomValueOtherThanMany(table1.routingTables()::containsKey, ESTestCase::randomUniqueProjectId) ); var table2 = table1.initializeProjects(addition); assertThat(table2, not(sameInstance(table1))); @@ -223,7 +224,7 @@ public void testInitializeProjects() { public void testBuilderFromEmpty() { final int numberOfProjects = randomIntBetween(1, 10); - final ProjectId[] projectIds = randomArray(numberOfProjects, numberOfProjects, ProjectId[]::new, () -> new ProjectId(randomUUID())); + final ProjectId[] projectIds = randomArray(numberOfProjects, numberOfProjects, ProjectId[]::new, ESTestCase::randomUniqueProjectId); final Integer[] projectIndexCount = randomArray(numberOfProjects, numberOfProjects, Integer[]::new, () -> randomIntBetween(0, 12)); final GlobalRoutingTable.Builder builder = GlobalRoutingTable.builder(); @@ -272,8 +273,8 @@ public void testBuilderFromExisting() { public void testRoutingNodesRoundtrip() { final ClusterState clusterState = buildClusterState( Map.ofEntries( - Map.entry(new ProjectId(randomAlphaOfLength(11) + "1"), Set.of("test-a", "test-b", "test-c")), - Map.entry(new ProjectId(randomAlphaOfLength(11) + "2"), Set.of("test-a", "test-z")) + Map.entry(ProjectId.fromId(randomAlphaOfLength(11) + "1"), Set.of("test-a", "test-b", "test-c")), + Map.entry(ProjectId.fromId(randomAlphaOfLength(11) + "2"), Set.of("test-a", "test-z")) ) ); @@ -285,8 +286,8 @@ public void testRoutingNodesRoundtrip() { } public void testRebuildAfterShardInitialized() { - final ProjectId project1 = new ProjectId(randomAlphaOfLength(11) + "1"); - final ProjectId project2 = new ProjectId(randomAlphaOfLength(11) + "2"); + final ProjectId project1 = ProjectId.fromId(randomAlphaOfLength(11) + "1"); + final ProjectId project2 = ProjectId.fromId(randomAlphaOfLength(11) + "2"); final ClusterState clusterState = buildClusterState( Map.ofEntries(Map.entry(project1, Set.of("test-a", "test-b", "test-c")), Map.entry(project2, Set.of("test-b", "test-z"))) ); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java index 86171f467ccf0..1393be120f9ac 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.metadata.MetadataIndexStateService; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.node.DiscoveryNodes.Builder; @@ -382,7 +381,7 @@ public void testValidations() { final RoutingTableGenerator.ShardCounter counter = new RoutingTableGenerator.ShardCounter(); final IndexRoutingTable indexRoutingTable = routingTableGenerator.genIndexRoutingTable(indexMetadata, counter); indexMetadata = updateActiveAllocations(indexRoutingTable, indexMetadata); - var projectId = new ProjectId(randomUUID()); + var projectId = randomUniqueProjectId(); ProjectMetadata metadata = ProjectMetadata.builder(projectId).put(indexMetadata, true).build(); // test no validation errors assertTrue(indexRoutingTable.validate(metadata)); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationServiceTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationServiceTests.java index 2f96197b402f8..3e341413eb77f 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationServiceTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationServiceTests.java @@ -123,7 +123,9 @@ public void testAssignsPrimariesInPriorityOrderThenReplicas() { final int numberOfProjects = randomIntBetween(1, 5); final List projects = numberOfProjects == 1 ? List.of(ProjectMetadata.builder(Metadata.DEFAULT_PROJECT_ID)) - : IntStream.range(0, numberOfProjects).mapToObj(n -> ProjectMetadata.builder(new ProjectId(randomUUID() + "-" + n))).toList(); + : IntStream.range(0, numberOfProjects) + .mapToObj(n -> ProjectMetadata.builder(ProjectId.fromId(randomUUID() + "-" + n))) + .toList(); // throttle (incoming) recoveries in order to observe the order of operations, but do not throttle outgoing recoveries since // the effects of that depend on the earlier (random) allocations @@ -330,7 +332,7 @@ public void testExplainsNonAllocationOfShardWithUnknownAllocator() { public void testHealthStatusWithMultipleProjects() { final Supplier buildProject = () -> { - final ProjectMetadata.Builder builder = ProjectMetadata.builder(new ProjectId(randomUUID())); + final ProjectMetadata.Builder builder = ProjectMetadata.builder(randomUniqueProjectId()); final Set indices = randomSet(1, 8, () -> randomAlphaOfLengthBetween(3, 12)); indices.forEach( indexName -> builder.put( @@ -391,9 +393,9 @@ public void testAutoExpandReplicas() throws Exception { TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY ); - final ProjectId project1 = new ProjectId(randomUUID()); - final var project2 = new ProjectId(randomUUID()); - final var project3 = new ProjectId(randomUUID()); + final ProjectId project1 = randomUniqueProjectId(); + final var project2 = randomUniqueProjectId(); + final var project3 = randomUniqueProjectId(); // return same cluster state when there are no changes ClusterState state = ClusterState.builder(ClusterName.DEFAULT) diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/IndexMetadataUpdaterTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/IndexMetadataUpdaterTests.java index 4aa32531fcb6e..2d3b03f5161d4 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/IndexMetadataUpdaterTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/IndexMetadataUpdaterTests.java @@ -40,9 +40,9 @@ public class IndexMetadataUpdaterTests extends ESTestCase { public void testApplyChangesAcrossMultipleProjects() { final IndexMetadataUpdater updater = new IndexMetadataUpdater(); - final ProjectId project1 = new ProjectId(randomUUID()); - final ProjectId project2 = new ProjectId(randomUUID()); - final ProjectId project3 = new ProjectId(randomUUID()); + final ProjectId project1 = randomUniqueProjectId(); + final ProjectId project2 = randomUniqueProjectId(); + final ProjectId project3 = randomUniqueProjectId(); final DiscoveryNode node1 = DiscoveryNodeUtils.create("n1"); final DiscoveryNode node2 = DiscoveryNodeUtils.create("n2"); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeAllocationDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeAllocationDeciderTests.java index 13e3cbf57c467..cdf47ee1dc6cc 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeAllocationDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeAllocationDeciderTests.java @@ -70,7 +70,7 @@ public void setUp() throws Exception { private ClusterState createInitialClusterState(boolean startShards) { Metadata.Builder metaBuilder = Metadata.builder(); - projectId = new ProjectId(randomUUID()); + projectId = randomUniqueProjectId(); metaBuilder.put( ProjectMetadata.builder(projectId) .put( @@ -308,7 +308,7 @@ public void testSourcePrimaryActive() { public void testGetForcedInitialShardAllocationToNodes() { final int additionalProjects = randomIntBetween(0, 5); - projectId = additionalProjects == 0 ? Metadata.DEFAULT_PROJECT_ID : new ProjectId(randomUUID()); + projectId = additionalProjects == 0 ? Metadata.DEFAULT_PROJECT_ID : randomUniqueProjectId(); var source = IndexMetadata.builder("source") .settings(indexSettings(IndexVersion.current(), 1, 0).put(IndexMetadata.SETTING_INDEX_UUID, "uuid-1")) .build(); @@ -367,7 +367,7 @@ public void testGetForcedInitialShardAllocationToNodes() { private static void includeAdditionalProjects(int projectCount, Metadata.Builder metadataBuilder) { for (int i = 0; i < projectCount; i++) { - final ProjectMetadata.Builder project = ProjectMetadata.builder(new ProjectId(randomUUID())); + final ProjectMetadata.Builder project = ProjectMetadata.builder(randomUniqueProjectId()); for (String index : randomSubsetOf(List.of("source", "target", "index-" + i))) { final Settings.Builder indexSettings = indexSettings(IndexVersion.current(), randomIntBetween(1, 5), randomIntBetween(0, 2)) .put(IndexMetadata.SETTING_INDEX_UUID, randomUUID()); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeSourceIndexSettingsUpdaterTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeSourceIndexSettingsUpdaterTests.java index 7d1cd60b92828..9f6d13a2ed142 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeSourceIndexSettingsUpdaterTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/ResizeSourceIndexSettingsUpdaterTests.java @@ -61,7 +61,7 @@ public void testResizeIndexSettingsRemovedAfterStart() { final String targetIndex = "target"; final ProjectMetadata sourceProject = ProjectMetadata.builder( - additionalProjects == 0 ? Metadata.DEFAULT_PROJECT_ID : new ProjectId(randomUUID()) + additionalProjects == 0 ? Metadata.DEFAULT_PROJECT_ID : randomUniqueProjectId() ) .put( IndexMetadata.builder(sourceIndex) @@ -79,7 +79,7 @@ public void testResizeIndexSettingsRemovedAfterStart() { final Metadata.Builder mBuilder = Metadata.builder().put(sourceProject); for (int i = 0; i < additionalProjects; i++) { - final ProjectMetadata.Builder project = ProjectMetadata.builder(new ProjectId(randomUUID())); + final ProjectMetadata.Builder project = ProjectMetadata.builder(randomUniqueProjectId()); final int indexCount = randomIntBetween(0, 5); for (int j = 0; j < indexCount; j++) { project.put( @@ -226,9 +226,9 @@ public void testResizeIndexSettingsRemovedAfterStart() { public void testHandleChangesAcrossMultipleProjects() { final ResizeSourceIndexSettingsUpdater updater = new ResizeSourceIndexSettingsUpdater(); final Metadata metadata = Metadata.builder() - .put(ProjectMetadata.builder(new ProjectId("p1"))) + .put(ProjectMetadata.builder(ProjectId.fromId("p1"))) .put( - ProjectMetadata.builder(new ProjectId("p2")) + ProjectMetadata.builder(ProjectId.fromId("p2")) .put( IndexMetadata.builder("index-a") .settings( @@ -243,7 +243,7 @@ public void testHandleChangesAcrossMultipleProjects() { ) ) .put( - ProjectMetadata.builder(new ProjectId("p3")) + ProjectMetadata.builder(ProjectId.fromId("p3")) .put( IndexMetadata.builder("index-a") .settings(indexSettings(IndexVersion.current(), 1, 1).put(IndexMetadata.SETTING_INDEX_UUID, randomUUID())) @@ -263,7 +263,7 @@ public void testHandleChangesAcrossMultipleProjects() { ) ) .put( - ProjectMetadata.builder(new ProjectId("p4")) + ProjectMetadata.builder(ProjectId.fromId("p4")) .put( IndexMetadata.builder("index-a") .settings(indexSettings(IndexVersion.current(), 1, 1).put(IndexMetadata.SETTING_INDEX_UUID, randomUUID())) @@ -278,7 +278,7 @@ public void testHandleChangesAcrossMultipleProjects() { ) ) .put( - ProjectMetadata.builder(new ProjectId("p5")) + ProjectMetadata.builder(ProjectId.fromId("p5")) .put( IndexMetadata.builder("index-a") .settings( diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RoutingNodesTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RoutingNodesTests.java index aec5261efb24a..a053b5c6d515f 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RoutingNodesTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RoutingNodesTests.java @@ -427,7 +427,7 @@ public void testBuildRoutingNodesForMultipleProjects() { final int numberOfProjects = randomIntBetween(2, 10); int shardCount = 0; for (int i = 1; i <= numberOfProjects; i++) { - var projectId = new ProjectId("p" + i); + var projectId = ProjectId.fromId("p" + i); mb.put( ProjectMetadata.builder(projectId) .put( diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocatorTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocatorTests.java index ba64ffa80111d..b32621e62ab58 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocatorTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocatorTests.java @@ -142,7 +142,7 @@ public void testDecideShardAllocationWhenThereAreMultipleProjects() { // Create some projects with some assigned indices for (int i = 1; i <= numberOfProjects; i++) { - var projectId = new ProjectId(Strings.format("proj_%02d", i)); + var projectId = ProjectId.fromId(Strings.format("proj_%02d", i)); String[] indices = { // 2 indices that are unique to this project "index_proj_" + i + "a", diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/DesiredBalanceReconcilerTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/DesiredBalanceReconcilerTests.java index f2ca22937c80c..4eed552d5f1af 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/DesiredBalanceReconcilerTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/DesiredBalanceReconcilerTests.java @@ -229,9 +229,9 @@ private static void doTestUnassignedPrimariesBeforeUnassignedReplicas(boolean mu final ProjectId project0, project1; if (multiProject) { - project0 = new ProjectId(randomUUID()); + project0 = randomUniqueProjectId(); metadataBuilder.put(ProjectMetadata.builder(project0).put(indexMetadata0, true)); - project1 = new ProjectId(randomUUID()); + project1 = randomUniqueProjectId(); metadataBuilder.put(ProjectMetadata.builder(project1).put(indexMetadata1, true)); } else { project0 = Metadata.DEFAULT_PROJECT_ID; diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/OrderedShardsIteratorTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/OrderedShardsIteratorTests.java index 4799c63a13fef..c4345d50c394e 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/OrderedShardsIteratorTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/OrderedShardsIteratorTests.java @@ -16,7 +16,6 @@ import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.GlobalRoutingTable; @@ -185,9 +184,9 @@ public void testShouldOrderShardByPriorityAcrossMultipleProjects() { // "lookup" index in project 1, data streams in project 2 var metadata = Metadata.builder() - .put(ProjectMetadata.builder(new ProjectId(randomUUID())).put(lookup, false)) + .put(ProjectMetadata.builder(randomUniqueProjectId()).put(lookup, false)) .put( - ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata.builder(randomUniqueProjectId()) .put(ds1, false) .put(ds2, false) .put(DataStream.builder("data-stream", List.of(ds1.getIndex(), ds2.getIndex())).build()) diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java index 9c27ab0e3ca6e..9522629de8f0d 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java @@ -663,8 +663,8 @@ private void doTestShardRelocationsTakenIntoAccount(boolean testMaxHeadroom, boo var metadataBuilder = Metadata.builder(); final ProjectId projectId1, projectId2; if (multipleProjects) { - projectId1 = new ProjectId(randomUUID()); - projectId2 = new ProjectId(randomUUID()); + projectId1 = randomUniqueProjectId(); + projectId2 = randomUniqueProjectId(); metadataBuilder.put(ProjectMetadata.builder(projectId1).put(indexMetadata1, false)); metadataBuilder.put(ProjectMetadata.builder(projectId2).put(indexMetadata2, false)); } else { diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/FilterAllocationDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/FilterAllocationDeciderTests.java index a89db019fa579..e7459c2edfb31 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/FilterAllocationDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/FilterAllocationDeciderTests.java @@ -16,7 +16,6 @@ import org.elasticsearch.cluster.TestShardRoutingRoleStrategies; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeUtils; @@ -357,7 +356,7 @@ public void testWithMultipleProjects() { .attributes(Map.ofEntries(Map.entry("can_allocate", "false"))) .build(); - ProjectMetadata project1 = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project1 = ProjectMetadata.builder(randomUniqueProjectId()) .put( IndexMetadata.builder("index-a") .settings(indexSettings(IndexVersion.current(), 1, 1).put(IndexMetadata.SETTING_INDEX_UUID, randomUUID())) @@ -370,7 +369,7 @@ public void testWithMultipleProjects() { ) ) .build(); - ProjectMetadata project2 = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project2 = ProjectMetadata.builder(randomUniqueProjectId()) .put( IndexMetadata.builder("index-a") .settings( diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/RebalanceOnlyWhenActiveAllocationDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/RebalanceOnlyWhenActiveAllocationDeciderTests.java index f82bdd68511b3..0129b18fe7bba 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/RebalanceOnlyWhenActiveAllocationDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/RebalanceOnlyWhenActiveAllocationDeciderTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.cluster.TestShardRoutingRoleStrategies; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.GlobalRoutingTable; @@ -74,7 +73,7 @@ public void testAllowRebalanceForMultipleIndicesAcrossMultipleProjects() { final Iterator nodeItr = Iterators.cycling(nodeIds); for (int p = 1; p <= numberOfProjects; p++) { final int numberOfIndices = randomIntBetween(1, 3); - var project = ProjectMetadata.builder(new ProjectId(randomUUID())); + var project = ProjectMetadata.builder(randomUniqueProjectId()); var rt = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY); for (int i = 1; i <= numberOfIndices; i++) { final int numberOfShards = randomIntBetween(1, 5); diff --git a/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java b/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java index e76dcc82364c6..87230f9f8a9b0 100644 --- a/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java @@ -359,7 +359,7 @@ public void testShardsAndPreferNodeRouting() { Settings.builder().put("cluster.routing.allocation.node_concurrent_recoveries", 10).build() ); - ProjectId projectId = new ProjectId(randomUUID()); + ProjectId projectId = randomUniqueProjectId(); Metadata metadata = Metadata.builder() .put( ProjectMetadata.builder(projectId) diff --git a/server/src/test/java/org/elasticsearch/gateway/PersistedClusterStateServiceTests.java b/server/src/test/java/org/elasticsearch/gateway/PersistedClusterStateServiceTests.java index 9f5ca0e559126..40c5efaa8dec9 100644 --- a/server/src/test/java/org/elasticsearch/gateway/PersistedClusterStateServiceTests.java +++ b/server/src/test/java/org/elasticsearch/gateway/PersistedClusterStateServiceTests.java @@ -1028,7 +1028,7 @@ public void testPersistsAndReloadsIndexMetadataForMultipleIndicesInMultipleProje final PersistedClusterStateService persistedClusterStateService = newPersistedClusterStateService(nodeEnvironment); final long term = randomLongBetween(1L, Long.MAX_VALUE); - final List projectIds = randomList(1, 5, () -> new ProjectId(randomUUID())); + final List projectIds = randomList(1, 5, ESTestCase::randomUniqueProjectId); try (Writer writer = persistedClusterStateService.createWriter()) { final ClusterState clusterState = loadPersistedClusterState(persistedClusterStateService); @@ -1597,7 +1597,7 @@ public void testOldestIndexVersionIsCorrectlySerialized() throws IOException { IndexVersion.fromId(IndexVersion.current().id() + 1) }; int lastIndexNum = randomIntBetween(9, 50); Metadata.Builder b = Metadata.builder(); - List projects = randomList(1, 3, () -> ProjectMetadata.builder(new ProjectId(randomUUID()))); + List projects = randomList(1, 3, () -> ProjectMetadata.builder(randomUniqueProjectId())); projects.forEach(b::put); for (IndexVersion indexVersion : indexVersions) { String indexUUID = UUIDs.randomBase64UUID(random()); diff --git a/server/src/test/java/org/elasticsearch/indices/TimestampFieldMapperServiceTests.java b/server/src/test/java/org/elasticsearch/indices/TimestampFieldMapperServiceTests.java index 6cf0d66630edb..7ef1c56f27a4a 100644 --- a/server/src/test/java/org/elasticsearch/indices/TimestampFieldMapperServiceTests.java +++ b/server/src/test/java/org/elasticsearch/indices/TimestampFieldMapperServiceTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.core.Tuple; @@ -85,7 +84,7 @@ public void testApplyingClusterStateWithMultipleProjects() { private static ClusterState initialClusterState() { final var projects = randomMap(1, 5, () -> { - ProjectMetadata.Builder builder = ProjectMetadata.builder(new ProjectId(randomUUID())); + ProjectMetadata.Builder builder = ProjectMetadata.builder(randomUniqueProjectId()); randomList(5, () -> createIndex(randomBoolean())).forEach(index -> builder.put(index, false)); return Tuple.tuple(builder.getId(), builder.build()); }); diff --git a/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java b/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java index 86f5a4dae1ade..36ce4292c7d6d 100644 --- a/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java +++ b/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java @@ -2595,7 +2595,7 @@ public void testResolveRequiredOrDefaultPipelineDefaultPipeline() { .numberOfShards(1) .numberOfReplicas(0) .putAlias(AliasMetadata.builder("alias").writeIndex(true).build()); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); // index name matches with IDM: IndexRequest indexRequest = new IndexRequest("idx"); @@ -2615,7 +2615,7 @@ public void testResolveRequiredOrDefaultPipelineDefaultPipeline() { IndexTemplateMetadata.Builder templateBuilder = IndexTemplateMetadata.builder("name1") .patterns(List.of("id*")) .settings(settings(IndexVersion.current()).put(IndexSettings.DEFAULT_PIPELINE.getKey(), "default-pipeline")); - projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(templateBuilder).build(); + projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(templateBuilder).build(); indexRequest = new IndexRequest("idx"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -2629,7 +2629,7 @@ public void testResolveFinalPipeline() { .numberOfShards(1) .numberOfReplicas(0) .putAlias(AliasMetadata.builder("alias").writeIndex(true).build()); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); // index name matches with IDM: IndexRequest indexRequest = new IndexRequest("idx"); @@ -2651,7 +2651,7 @@ public void testResolveFinalPipeline() { IndexTemplateMetadata.Builder templateBuilder = IndexTemplateMetadata.builder("name1") .patterns(List.of("id*")) .settings(settings(IndexVersion.current()).put(IndexSettings.FINAL_PIPELINE.getKey(), "final-pipeline")); - projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(templateBuilder).build(); + projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(templateBuilder).build(); indexRequest = new IndexRequest("idx"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -2681,7 +2681,7 @@ public void testResolveFinalPipelineWithDateMathExpression() { public void testResolveRequestOrDefaultPipelineAndFinalPipeline() { // no pipeline: { - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndexRequest indexRequest = new IndexRequest("idx"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertFalse(hasPipeline(indexRequest)); @@ -2691,7 +2691,7 @@ public void testResolveRequestOrDefaultPipelineAndFinalPipeline() { // request pipeline: { - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline("request-pipeline"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -2705,7 +2705,7 @@ public void testResolveRequestOrDefaultPipelineAndFinalPipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.DEFAULT_PIPELINE.getKey(), "default-pipeline")) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline("request-pipeline"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -2719,7 +2719,7 @@ public void testResolveRequestOrDefaultPipelineAndFinalPipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.FINAL_PIPELINE.getKey(), "final-pipeline")) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline("request-pipeline"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -3099,7 +3099,7 @@ public void testPutPipelineWithVersionedUpdateIncrementsVersion() throws Excepti public void testResolvePipelinesWithNonePipeline() { // _none request pipeline: { - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline(NOOP_PIPELINE_NAME); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertFalse(hasPipeline(indexRequest)); @@ -3113,7 +3113,7 @@ public void testResolvePipelinesWithNonePipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.DEFAULT_PIPELINE.getKey(), NOOP_PIPELINE_NAME)) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertFalse(hasPipeline(indexRequest)); @@ -3127,7 +3127,7 @@ public void testResolvePipelinesWithNonePipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.DEFAULT_PIPELINE.getKey(), NOOP_PIPELINE_NAME)) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline("pipeline1"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -3141,7 +3141,7 @@ public void testResolvePipelinesWithNonePipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.DEFAULT_PIPELINE.getKey(), "default-pipeline")) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline(NOOP_PIPELINE_NAME); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertFalse(hasPipeline(indexRequest)); @@ -3155,7 +3155,7 @@ public void testResolvePipelinesWithNonePipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.FINAL_PIPELINE.getKey(), "final-pipeline")) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline(NOOP_PIPELINE_NAME); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); @@ -3170,7 +3170,7 @@ public void testResolvePipelinesWithNonePipeline() { .settings(settings(IndexVersion.current()).put(IndexSettings.FINAL_PIPELINE.getKey(), NOOP_PIPELINE_NAME)) .numberOfShards(1) .numberOfReplicas(0); - ProjectMetadata projectMetadata = ProjectMetadata.builder(new ProjectId(randomUUID())).put(builder).build(); + ProjectMetadata projectMetadata = ProjectMetadata.builder(randomUniqueProjectId()).put(builder).build(); IndexRequest indexRequest = new IndexRequest("idx").setPipeline("pipeline1"); IngestService.resolvePipelinesAndUpdateIndexRequest(indexRequest, indexRequest, projectMetadata); assertTrue(hasPipeline(indexRequest)); diff --git a/test/external-modules/multi-project/src/javaRestTest/java/org/elasticsearch/xpack/security/SecurityRolesMultiProjectIT.java b/test/external-modules/multi-project/src/javaRestTest/java/org/elasticsearch/xpack/security/SecurityRolesMultiProjectIT.java index f6e910a48081d..5f4d7eb19bfe2 100644 --- a/test/external-modules/multi-project/src/javaRestTest/java/org/elasticsearch/xpack/security/SecurityRolesMultiProjectIT.java +++ b/test/external-modules/multi-project/src/javaRestTest/java/org/elasticsearch/xpack/security/SecurityRolesMultiProjectIT.java @@ -60,8 +60,8 @@ protected Settings restClientSettings() { } public void testUsersWithSameRoleNamesInDifferentProjects() throws Exception { - var project1 = new ProjectId(randomIdentifier()); - var project2 = new ProjectId(randomIdentifier()); + var project1 = randomUniqueProjectId(); + var project2 = randomUniqueProjectId(); createProject(project1.id()); createProject(project2.id()); @@ -79,8 +79,8 @@ public void testUsersWithSameRoleNamesInDifferentProjects() throws Exception { } public void testInvalidateRoleInSingleProjectOnly() throws Exception { - var project1 = new ProjectId(randomIdentifier()); - var project2 = new ProjectId(randomIdentifier()); + var project1 = randomUniqueProjectId(); + var project2 = randomUniqueProjectId(); createProject(project1.id()); createProject(project2.id()); @@ -117,8 +117,8 @@ public void testUpdatingFileBasedRoleAffectsAllProjects() throws Exception { - monitor """, roleName))); - var project1 = new ProjectId(randomIdentifier()); - var project2 = new ProjectId(randomIdentifier()); + var project1 = randomUniqueProjectId(); + var project2 = randomUniqueProjectId(); createProject(project1.id()); createProject(project2.id()); diff --git a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestDeleteProjectAction.java b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestDeleteProjectAction.java index 264c53a360a51..0ce85ca2460c7 100644 --- a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestDeleteProjectAction.java +++ b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestDeleteProjectAction.java @@ -41,7 +41,7 @@ protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient final DeleteProjectAction.Request deleteProjectRequest = new DeleteProjectAction.Request( getMasterNodeTimeout(restRequest), getAckTimeout(restRequest), - new ProjectId(restRequest.param("id")) + ProjectId.fromId(restRequest.param("id")) ); return channel -> client.execute(DeleteProjectAction.INSTANCE, deleteProjectRequest, new RestToXContentListener<>(channel)); } diff --git a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestPutProjectAction.java b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestPutProjectAction.java index 170bbd6a62654..6d16735e69d06 100644 --- a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestPutProjectAction.java +++ b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/RestPutProjectAction.java @@ -41,7 +41,7 @@ protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient final PutProjectAction.Request putProjectRequest = new PutProjectAction.Request( getMasterNodeTimeout(restRequest), getAckTimeout(restRequest), - new ProjectId(restRequest.param("id")) + ProjectId.fromId(restRequest.param("id")) ); return channel -> client.execute(PutProjectAction.INSTANCE, putProjectRequest, new RestToXContentListener<>(channel)); } diff --git a/test/external-modules/multi-project/src/test/java/org/elasticsearch/multiproject/action/DeleteProjectActionTests.java b/test/external-modules/multi-project/src/test/java/org/elasticsearch/multiproject/action/DeleteProjectActionTests.java index c4cf82560d460..1fb11acb550f7 100644 --- a/test/external-modules/multi-project/src/test/java/org/elasticsearch/multiproject/action/DeleteProjectActionTests.java +++ b/test/external-modules/multi-project/src/test/java/org/elasticsearch/multiproject/action/DeleteProjectActionTests.java @@ -37,7 +37,7 @@ public void init() { } public void testSimpleDelete() throws Exception { - var projects = randomList(1, 5, () -> new ProjectId(randomUUID())); + var projects = randomList(1, 5, ESTestCase::randomUniqueProjectId); var deletedProjects = randomSubsetOf(projects); var state = buildState(projects); var tasks = deletedProjects.stream().map(this::createTask).toList(); @@ -56,13 +56,13 @@ public void testSimpleDelete() throws Exception { } public void testDeleteNonExisting() throws Exception { - var projects = randomList(1, 5, () -> new ProjectId(randomUUID())); + var projects = randomList(1, 5, ESTestCase::randomUniqueProjectId); var deletedProjects = randomSubsetOf(projects); var state = buildState(projects); var listener = ActionListener.assertAtLeastOnce( ActionTestUtils.assertNoSuccessListener(e -> assertTrue(e instanceof IllegalArgumentException)) ); - var nonExistingTask = createTask(new ProjectId(randomUUID()), listener); + var nonExistingTask = createTask(randomUniqueProjectId(), listener); var tasks = Stream.concat(Stream.of(nonExistingTask), deletedProjects.stream().map(this::createTask)).toList(); var result = ClusterStateTaskExecutorUtils.executeIgnoringFailures(state, executor, tasks); for (ProjectId deletedProject : deletedProjects) { diff --git a/test/framework/src/main/java/org/elasticsearch/cluster/project/TestProjectResolvers.java b/test/framework/src/main/java/org/elasticsearch/cluster/project/TestProjectResolvers.java index abf4620cc8167..951b5da7cfab9 100644 --- a/test/framework/src/main/java/org/elasticsearch/cluster/project/TestProjectResolvers.java +++ b/test/framework/src/main/java/org/elasticsearch/cluster/project/TestProjectResolvers.java @@ -165,7 +165,7 @@ public ProjectMetadata getProjectMetadata(Metadata metadata) { @Override public ProjectId getProjectId() { String headerValue = threadContext.getHeader(Task.X_ELASTIC_PROJECT_ID_HTTP_HEADER); - return headerValue != null ? new ProjectId(headerValue) : Metadata.DEFAULT_PROJECT_ID; + return headerValue != null ? ProjectId.fromId(headerValue) : Metadata.DEFAULT_PROJECT_ID; } @Override diff --git a/test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java index 2ed86cf701378..cc44fba22a196 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java @@ -1284,14 +1284,14 @@ public static String randomIdentifier() { * Returns a project id. This may be {@link Metadata#DEFAULT_PROJECT_ID}, or it may be a randomly-generated id. */ public static ProjectId randomProjectIdOrDefault() { - return randomBoolean() ? Metadata.DEFAULT_PROJECT_ID : new ProjectId(randomUUID()); + return randomBoolean() ? Metadata.DEFAULT_PROJECT_ID : randomUniqueProjectId(); } /** * Returns a new randomly-generated project id */ public static ProjectId randomUniqueProjectId() { - return new ProjectId(randomUUID()); + return ProjectId.fromId(randomUUID()); } public static String randomUUID() { diff --git a/test/framework/src/test/java/org/elasticsearch/cluster/project/TestProjectResolversTests.java b/test/framework/src/test/java/org/elasticsearch/cluster/project/TestProjectResolversTests.java index 6c05508ee8757..39a1ef7f48d72 100644 --- a/test/framework/src/test/java/org/elasticsearch/cluster/project/TestProjectResolversTests.java +++ b/test/framework/src/test/java/org/elasticsearch/cluster/project/TestProjectResolversTests.java @@ -35,7 +35,7 @@ public void testAllProjects() { } public void testSingleProject() { - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); final ProjectResolver projectResolver = TestProjectResolvers.singleProject(projectId); assertThat(projectResolver.getProjectId(), equalTo(projectId)); @@ -44,7 +44,7 @@ public void testSingleProject() { } public void testSingleProjectOnly_getProjectIdAndMetadata() { - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); final ClusterState state = buildClusterState(projectId); final ProjectResolver projectResolver = TestProjectResolvers.singleProjectOnly(); @@ -60,19 +60,19 @@ public void testSingleProjectOnly_getProjectIdAndMetadata() { public void testSingleProjectOnly_getProjectIds() { { final ProjectResolver projectResolver = TestProjectResolvers.singleProjectOnly(); - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); ClusterState state = buildClusterState(projectId); assertThat(state.metadata().projects().values(), hasSize(1)); expectThrows(UnsupportedOperationException.class, () -> projectResolver.getProjectIds(state)); projectResolver.executeOnProject(projectId, () -> assertThat(projectResolver.getProjectIds(state), contains(projectId))); - projectResolver.executeOnProject(new ProjectId(randomUUID()), () -> { + projectResolver.executeOnProject(randomUniqueProjectId(), () -> { expectThrows(IllegalArgumentException.class, () -> projectResolver.getProjectIds(state)); }); } { final ProjectResolver projectResolver = TestProjectResolvers.singleProjectOnly(); - final ProjectId projectId = new ProjectId(randomUUID()); + final ProjectId projectId = randomUniqueProjectId(); ClusterState state = buildClusterState(projectId, randomIntBetween(1, 10)); assertThat(state.metadata().projects().values().size(), greaterThan(1)); @@ -95,7 +95,7 @@ private ClusterState buildClusterState(ProjectId projectId, int numberOfExtraPro Metadata.Builder metadata = Metadata.builder(); metadata.put(ProjectMetadata.builder(projectId).build()); for (int i = 0; i < numberOfExtraProjects; i++) { - metadata.put(ProjectMetadata.builder(new ProjectId("p" + i + "_" + randomAlphaOfLength(8))).build()); + metadata.put(ProjectMetadata.builder(ProjectId.fromId("p" + i + "_" + randomAlphaOfLength(8))).build()); } return ClusterState.builder(new ClusterName(randomAlphaOfLengthBetween(4, 8))).metadata(metadata).build(); } @@ -103,7 +103,7 @@ private ClusterState buildClusterState(ProjectId projectId, int numberOfExtraPro private ClusterState buildClusterState(int numberOfProjects) { Metadata.Builder metadata = Metadata.builder(); for (int i = 0; i < numberOfProjects; i++) { - metadata.put(ProjectMetadata.builder(new ProjectId("p" + i + "_" + randomAlphaOfLength(8))).build()); + metadata.put(ProjectMetadata.builder(ProjectId.fromId("p" + i + "_" + randomAlphaOfLength(8))).build()); } return ClusterState.builder(new ClusterName(randomAlphaOfLengthBetween(4, 8))).metadata(metadata).build(); } diff --git a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/allocation/CcrPrimaryFollowerAllocationDeciderTests.java b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/allocation/CcrPrimaryFollowerAllocationDeciderTests.java index 3642db2f5cb93..b039e93093331 100644 --- a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/allocation/CcrPrimaryFollowerAllocationDeciderTests.java +++ b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/allocation/CcrPrimaryFollowerAllocationDeciderTests.java @@ -58,7 +58,7 @@ public void setupProject() { if (extraProjectCount == 0) { projectId = Metadata.DEFAULT_PROJECT_ID; } else { - projectId = new ProjectId(randomUUID()); + projectId = randomUniqueProjectId(); } } @@ -117,7 +117,7 @@ private Metadata createMetadata(IndexMetadata.Builder indexMetadata) { final Metadata.Builder metadataBuilder = Metadata.builder(); metadataBuilder.put(projectMetadata); for (int i = 0; i < extraProjectCount; i++) { - metadataBuilder.put(ProjectMetadata.builder(new ProjectId(randomUUID())).build()); + metadataBuilder.put(ProjectMetadata.builder(randomUniqueProjectId()).build()); } return metadataBuilder.build(); } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/async/AsyncTaskMaintenanceServiceTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/async/AsyncTaskMaintenanceServiceTests.java index 5ded307a8def3..491d2077039d8 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/async/AsyncTaskMaintenanceServiceTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/async/AsyncTaskMaintenanceServiceTests.java @@ -70,18 +70,18 @@ public void testStartStopDuringClusterChanges() { final Metadata.Builder metadataBuilder = Metadata.builder(); final GlobalRoutingTable.Builder grtBuilder = GlobalRoutingTable.builder(); - final ProjectId p1 = new ProjectId("p1"); + final ProjectId p1 = ProjectId.fromId("p1"); metadataBuilder.put(ProjectMetadata.builder(p1).put(getIndexMetadata(), false)); grtBuilder.put(p1, buildRoutingTableWithIndex(localNodeId)); - final ProjectId p2 = new ProjectId("p2"); + final ProjectId p2 = ProjectId.fromId("p2"); metadataBuilder.put(ProjectMetadata.builder(p2).put(getIndexMetadata(), false)); grtBuilder.put(p2, buildRoutingTableWithIndex(alternateNodeId)); - final ProjectId p3 = new ProjectId("p3"); + final ProjectId p3 = ProjectId.fromId("p3"); grtBuilder.put(p3, RoutingTable.builder()); - final ProjectId p4 = new ProjectId("p4"); + final ProjectId p4 = ProjectId.fromId("p4"); metadataBuilder.put(ProjectMetadata.builder(p4).put(getIndexMetadata(), false)); grtBuilder.put(p4, buildRoutingTableWithIndex(localNodeId)); diff --git a/x-pack/plugin/old-lucene-versions/src/test/java/org/elasticsearch/xpack/lucene/bwc/ArchiveAllocationDeciderTests.java b/x-pack/plugin/old-lucene-versions/src/test/java/org/elasticsearch/xpack/lucene/bwc/ArchiveAllocationDeciderTests.java index 0da93537a68e7..d2a534c241804 100644 --- a/x-pack/plugin/old-lucene-versions/src/test/java/org/elasticsearch/xpack/lucene/bwc/ArchiveAllocationDeciderTests.java +++ b/x-pack/plugin/old-lucene-versions/src/test/java/org/elasticsearch/xpack/lucene/bwc/ArchiveAllocationDeciderTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; @@ -62,14 +61,14 @@ private static void checkCanAllocate(IndexVersion indexVersion, boolean validLic true, ShardRoutingState.STARTED ); - final ProjectMetadata.Builder projectbuilder = ProjectMetadata.builder(new ProjectId(randomUUID())); + final ProjectMetadata.Builder projectbuilder = ProjectMetadata.builder(randomUniqueProjectId()); addIndex(projectbuilder, indexName, indexUuid, indexVersion); addRandomIndices(projectbuilder, randomIntBetween(1, 5)); final Metadata.Builder metadataBuilder = Metadata.builder(); metadataBuilder.put(projectbuilder); for (int p = randomIntBetween(0, 5); p > 0; p--) { - metadataBuilder.put(addRandomIndices(ProjectMetadata.builder(new ProjectId(randomUUID())), randomIntBetween(0, 10))); + metadataBuilder.put(addRandomIndices(ProjectMetadata.builder(randomUniqueProjectId()), randomIntBetween(0, 10))); } final ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(metadataBuilder).build(); diff --git a/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/GetJobsActionRequestTests.java b/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/GetJobsActionRequestTests.java index 5e8e5795739ef..547a3ce79ced1 100644 --- a/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/GetJobsActionRequestTests.java +++ b/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/GetJobsActionRequestTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.xpack.rollup.action; import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.util.Maps; @@ -43,7 +42,7 @@ protected Writeable.Reader instanceReader() { public void testStateCheckNoPersistentTasks() { GetRollupJobsAction.Request request = new GetRollupJobsAction.Request("foo"); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .putCustom(PersistentTasksCustomMetadata.TYPE, new PersistentTasksCustomMetadata(0L, Collections.emptyMap())) .build(); boolean hasRollupJobs = TransportGetRollupJobAction.stateHasRollupJobs(request, project); @@ -52,7 +51,7 @@ public void testStateCheckNoPersistentTasks() { public void testStateCheckAllNoPersistentTasks() { GetRollupJobsAction.Request request = new GetRollupJobsAction.Request("_all"); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .putCustom(PersistentTasksCustomMetadata.TYPE, new PersistentTasksCustomMetadata(0L, Collections.emptyMap())) .build(); boolean hasRollupJobs = TransportGetRollupJobAction.stateHasRollupJobs(request, project); @@ -65,7 +64,7 @@ public void testStateCheckNoMatchingPersistentTasks() { "bar", new PersistentTasksCustomMetadata.PersistentTask<>("bar", "bar", null, 1, null) ); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .putCustom(PersistentTasksCustomMetadata.TYPE, new PersistentTasksCustomMetadata(0L, tasks)) .build(); boolean hasRollupJobs = TransportGetRollupJobAction.stateHasRollupJobs(request, project); @@ -79,7 +78,7 @@ public void testStateCheckMatchingPersistentTasks() { "foo", new PersistentTasksCustomMetadata.PersistentTask<>("foo", RollupJob.NAME, job, 1, null) ); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .putCustom(PersistentTasksCustomMetadata.TYPE, new PersistentTasksCustomMetadata(0L, tasks)) .build(); boolean hasRollupJobs = TransportGetRollupJobAction.stateHasRollupJobs(request, project); @@ -93,7 +92,7 @@ public void testStateCheckAllMatchingPersistentTasks() { "foo", new PersistentTasksCustomMetadata.PersistentTask<>("foo", RollupJob.NAME, job, 1, null) ); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .putCustom(PersistentTasksCustomMetadata.TYPE, new PersistentTasksCustomMetadata(0L, tasks)) .build(); boolean hasRollupJobs = TransportGetRollupJobAction.stateHasRollupJobs(request, project); @@ -107,7 +106,7 @@ public void testStateCheckAllWithSeveralMatchingPersistentTasks() { Map> tasks = Maps.newMapWithExpectedSize(2); tasks.put("foo", new PersistentTasksCustomMetadata.PersistentTask<>("foo", RollupJob.NAME, job, 1, null)); tasks.put("bar", new PersistentTasksCustomMetadata.PersistentTask<>("bar", RollupJob.NAME, job2, 1, null)); - ProjectMetadata project = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata project = ProjectMetadata.builder(randomUniqueProjectId()) .putCustom(PersistentTasksCustomMetadata.TYPE, new PersistentTasksCustomMetadata(0L, tasks)) .build(); boolean hasRollupJobs = TransportGetRollupJobAction.stateHasRollupJobs(request, project); diff --git a/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotAllocatorTests.java b/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotAllocatorTests.java index b6658957f9a7d..33a110b36673b 100644 --- a/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotAllocatorTests.java +++ b/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotAllocatorTests.java @@ -233,7 +233,7 @@ private static Metadata buildSingleShardIndexMetadata(ShardId shardId, UnaryOper builder.put(buildSingleShardIndexProject(shardId, extraSettings)); for (int i = 0; i < extraProjects; i++) { - builder.put(ProjectMetadata.builder(new ProjectId("project-" + i)).build()); + builder.put(ProjectMetadata.builder(ProjectId.fromId("project-" + i)).build()); } return builder.build(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java index 9d4a1782891ca..e1250a7dd2081 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java @@ -271,7 +271,7 @@ public class AuthorizationServiceTests extends ESTestCase { @SuppressWarnings("unchecked") @Before public void setup() { - projectId = new ProjectId(randomUUID()); + projectId = randomUniqueProjectId(); fieldPermissionsCache = new FieldPermissionsCache(Settings.EMPTY); rolesStore = mock(CompositeRolesStore.class); clusterService = mock(ClusterService.class); @@ -1208,7 +1208,7 @@ public void testSearchAgainstIndex() { metadataBuilder.put(ProjectMetadata.builder(projectId).put(createIndexMetadata(indexName), true)); for (int p = 0; p < additionalProjects; p++) { - ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(new ProjectId(randomUUID())); + ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomUniqueProjectId()); int indices = randomIntBetween(1, 3); for (int i = 0; i < indices; i++) { projectBuilder.put(createIndexMetadata(i == 0 ? indexName : randomAlphaOfLength(12)), true); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java index 15ab948791116..d230aeeb5666c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java @@ -163,7 +163,7 @@ public void setup() { IndexMetadata dataStreamFailureStore1 = DataStreamTestHelper.createFailureStore(dataStreamName, 1).build(); IndexMetadata dataStreamFailureStore2 = DataStreamTestHelper.createFailureStore(dataStreamName, 2).build(); IndexMetadata dataStreamIndex3 = DataStreamTestHelper.createBackingIndex(otherDataStreamName, 1).build(); - ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(new ProjectId(randomUUID())) + ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomUniqueProjectId()) .put( indexBuilder("foo").putAlias(AliasMetadata.builder("foofoobar")) .putAlias(AliasMetadata.builder("foounauthorized")) From 2f9fb3bdcc981f406ef0c4000eb9e5c72f082fb3 Mon Sep 17 00:00:00 2001 From: Yang Wang Date: Wed, 5 Mar 2025 15:54:27 +1100 Subject: [PATCH 3/5] tweak --- .../java/org/elasticsearch/cluster/metadata/ProjectId.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java index 11212cea917fd..85b48c22c637a 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java @@ -34,8 +34,7 @@ private ProjectId(String id) { if (Strings.isNullOrBlank(id)) { throw new IllegalArgumentException("project-id cannot be empty"); } - final boolean validFormatId = isValidFormatId(id); - if (validFormatId == false) { + if (isValidFormatId(id) == false) { final var message = "project-id [" + id + "] must be alphanumeric ASCII with up to " + MAX_LENGTH + " chars"; assert false : message; throw new IllegalArgumentException(message); From 4234029dd8c5b86b237c22ba828d7cb8d65d52e5 Mon Sep 17 00:00:00 2001 From: Yang Wang Date: Wed, 5 Mar 2025 16:01:19 +1100 Subject: [PATCH 4/5] more tweak --- .../java/org/elasticsearch/cluster/metadata/ProjectId.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java index 85b48c22c637a..2363f9efa2b36 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/ProjectId.java @@ -76,8 +76,7 @@ private static boolean isValidIdChar(char c) { } public static ProjectId readFrom(StreamInput in) throws IOException { - final var id = in.readString(); - return DEFAULT_STRING.equals(id) ? DEFAULT : new ProjectId(id); + return fromId(in.readString()); } @Override From 6e10b4b33c4604fc2b8587c8e5af7e5745fafb05 Mon Sep 17 00:00:00 2001 From: Yang Wang Date: Wed, 5 Mar 2025 17:40:47 +1100 Subject: [PATCH 5/5] fix validation --- .../org/elasticsearch/multiproject/action/PutProjectAction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java index 24f231446981a..b6a799d4ce0e7 100644 --- a/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java +++ b/test/external-modules/multi-project/src/main/java/org/elasticsearch/multiproject/action/PutProjectAction.java @@ -121,7 +121,7 @@ public ClusterState execute(BatchExecutionContext batchExecution public static class Request extends AcknowledgedRequest { - private static final Pattern VALID_PROJECT_ID_PATTERN = Pattern.compile("[a-z0-9]+"); + private static final Pattern VALID_PROJECT_ID_PATTERN = Pattern.compile("[-_a-zA-Z0-9]+"); private final ProjectId projectId;