diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java index b2c3c29fe0703..6e673eddfda2b 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java @@ -16,7 +16,7 @@ import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.PlainActionFuture; -import org.elasticsearch.client.internal.Client; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.service.ClusterService; @@ -77,7 +77,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask { static final String DATABASES_INDEX_PATTERN = DATABASES_INDEX + "*"; static final int MAX_CHUNK_SIZE = 1024 * 1024; - private final Client client; + private final ProjectClient client; private final HttpClient httpClient; private final ClusterService clusterService; private final ThreadPool threadPool; @@ -99,7 +99,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask { private final ProjectId projectId; GeoIpDownloader( - Client client, + ProjectClient client, HttpClient httpClient, ClusterService clusterService, ThreadPool threadPool, @@ -116,7 +116,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask { ProjectId projectId ) { super(id, type, action, description, parentTask, headers); - this.client = client.projectClient(projectId); + this.client = client; this.httpClient = httpClient; this.clusterService = clusterService; this.threadPool = threadPool; diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTaskExecutor.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTaskExecutor.java index 6d55e94b0a23d..7e4a959a25788 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTaskExecutor.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTaskExecutor.java @@ -191,7 +191,7 @@ protected GeoIpDownloader createTask( ) { ProjectId projectId = projectResolver.getProjectId(); return new GeoIpDownloader( - client, + client.projectClient(projectId), httpClient, clusterService, threadPool, diff --git a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/DatabaseNodeServiceTests.java b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/DatabaseNodeServiceTests.java index 494c85e91ffeb..031fc91403cfb 100644 --- a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/DatabaseNodeServiceTests.java +++ b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/DatabaseNodeServiceTests.java @@ -17,6 +17,7 @@ import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.internal.Client; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.AliasMetadata; @@ -63,6 +64,7 @@ import org.junit.After; import org.junit.Before; import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; import org.mockito.stubbing.Answer; import java.io.ByteArrayInputStream; @@ -112,6 +114,7 @@ public class DatabaseNodeServiceTests extends ESTestCase { private Client client; + private ProjectClient projectClient; private Path geoIpTmpDir; private ThreadPool threadPool; private DatabaseNodeService databaseNodeService; @@ -138,7 +141,9 @@ public void setup() throws IOException { Settings settings = Settings.builder().put("resource.reload.interval.high", TimeValue.timeValueMillis(100)).build(); resourceWatcherService = new ResourceWatcherService(settings, threadPool); + projectClient = mock(ProjectClient.class); client = mock(Client.class); + when(client.projectClient(any())).thenReturn(projectClient); ingestService = mock(IngestService.class); clusterService = mock(ClusterService.class); geoIpTmpDir = createTempDir(); @@ -161,6 +166,8 @@ public void cleanup() { threadPool.shutdownNow(); Releasables.close(toRelease); toRelease.clear(); + verify(client, Mockito.atLeast(0)).projectClient(any()); + verifyNoMoreInteractions(client); } public void testCheckDatabases() throws Exception { @@ -181,7 +188,7 @@ public void testCheckDatabases() throws Exception { databaseNodeService.checkDatabases(state); DatabaseReaderLazyLoader database = databaseNodeService.getDatabaseReaderLazyLoader(projectId, "GeoIP2-City.mmdb"); assertThat(database, nullValue()); - verify(client, times(0)).search(any()); + verify(projectClient, times(0)).search(any()); verify(ingestService, times(0)).reloadPipeline(any(), anyString()); try (Stream files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) { assertEquals(0, files.count()); @@ -199,7 +206,7 @@ public void testCheckDatabases() throws Exception { databaseNodeService.checkDatabases(state); database = databaseNodeService.getDatabaseReaderLazyLoader(projectId, "GeoIP2-City.mmdb"); assertThat(database, notNullValue()); - verify(client, times(10)).search(any()); + verify(projectClient, times(10)).search(any()); try (Stream files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) { assertThat(files.count(), greaterThanOrEqualTo(1L)); } @@ -226,7 +233,7 @@ public void testCheckDatabases_dontCheckDatabaseOnNonIngestNode() throws Excepti databaseNodeService.checkDatabases(state); assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue()); - verify(client, never()).search(any()); + verify(projectClient, never()).search(any()); try (Stream files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) { assertThat(files.toList(), empty()); } @@ -246,7 +253,7 @@ public void testCheckDatabases_dontCheckDatabaseWhenNoDatabasesIndex() throws Ex databaseNodeService.checkDatabases(state); assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue()); - verify(client, never()).search(any()); + verify(projectClient, never()).search(any()); try (Stream files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) { assertThat(files.toList(), empty()); } @@ -261,7 +268,7 @@ public void testCheckDatabases_dontCheckDatabaseWhenGeoIpDownloadTask() throws E databaseNodeService.checkDatabases(state); assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue()); - verify(client, never()).search(any()); + verify(projectClient, never()).search(any()); try (Stream files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) { assertThat(files.toList(), empty()); } @@ -281,7 +288,7 @@ public void testRetrieveDatabase() throws Exception { verify(failureHandler, never()).accept(any()); verify(chunkConsumer, times(30)).accept(any()); verify(completedHandler, times(1)).run(); - verify(client, times(30)).search(any()); + verify(projectClient, times(30)).search(any()); } public void testRetrieveDatabaseCorruption() throws Exception { @@ -305,7 +312,7 @@ public void testRetrieveDatabaseCorruption() throws Exception { ); verify(chunkConsumer, times(10)).accept(any()); verify(completedHandler, times(0)).run(); - verify(client, times(10)).search(any()); + verify(projectClient, times(10)).search(any()); } public void testUpdateDatabase() throws Exception { @@ -371,8 +378,7 @@ private String mockSearches(String databaseName, int firstChunk, int lastChunk) }); requestMap.put(databaseName + "_" + i, actionFuture); } - when(client.projectClient(any())).thenReturn(client); - when(client.search(any())).thenAnswer(invocationOnMock -> { + when(projectClient.search(any())).thenAnswer(invocationOnMock -> { SearchRequest req = (SearchRequest) invocationOnMock.getArguments()[0]; TermQueryBuilder term = (TermQueryBuilder) req.source().query(); String id = (String) term.value(); diff --git a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java index ab20a925fcedb..a3c671e70f7b8 100644 --- a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java +++ b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java @@ -23,6 +23,7 @@ import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.index.TransportIndexAction; import org.elasticsearch.action.support.broadcast.BroadcastResponse; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlocks; import org.elasticsearch.cluster.metadata.IndexMetadata; @@ -702,12 +703,14 @@ private GeoIpTaskState.Metadata newGeoIpTaskStateMetadata(boolean expired) { return new GeoIpTaskState.Metadata(0, 0, 0, randomAlphaOfLength(20), lastChecked.toEpochMilli()); } - private static class MockClient extends NoOpClient { + private static class MockClient extends NoOpClient implements ProjectClient { private final Map, BiConsumer>> handlers = new HashMap<>(); + private final ProjectId projectId; private MockClient(ThreadPool threadPool, ProjectId projectId) { super(threadPool, TestProjectResolvers.singleProject(projectId)); + this.projectId = projectId; } public void addHandler( @@ -717,6 +720,11 @@ public void add handlers.put(action, listener); } + @Override + public ProjectId projectId() { + return projectId; + } + @SuppressWarnings("unchecked") @Override protected void doExecute( diff --git a/server/src/main/java/org/elasticsearch/client/internal/Client.java b/server/src/main/java/org/elasticsearch/client/internal/Client.java index 5903a9c4081a8..57ab5ab95930e 100644 --- a/server/src/main/java/org/elasticsearch/client/internal/Client.java +++ b/server/src/main/java/org/elasticsearch/client/internal/Client.java @@ -404,7 +404,7 @@ public interface Client extends ElasticsearchClient { /** * Returns a client that executes every request in the context of the given project. */ - Client projectClient(ProjectId projectId); + ProjectClient projectClient(ProjectId projectId); /** * Returns this client's project resolver. diff --git a/server/src/main/java/org/elasticsearch/client/internal/ProjectClient.java b/server/src/main/java/org/elasticsearch/client/internal/ProjectClient.java new file mode 100644 index 0000000000000..95e00a1899042 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/client/internal/ProjectClient.java @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side + * Public License v 1"; you may not use this file except in compliance with, at + * your election, the "Elastic License 2.0", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +package org.elasticsearch.client.internal; + +import org.elasticsearch.cluster.metadata.ProjectId; + +/** + * A {@link Client} that is scoped to a specific project. It should execute any request in the scope of that project. This scope is usually + * defined by the thread context. + */ +public interface ProjectClient extends Client { + + ProjectId projectId(); +} diff --git a/server/src/main/java/org/elasticsearch/client/internal/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/internal/support/AbstractClient.java index 9e2605b6acdff..a829042fb083a 100644 --- a/server/src/main/java/org/elasticsearch/client/internal/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/internal/support/AbstractClient.java @@ -76,8 +76,10 @@ import org.elasticsearch.client.internal.AdminClient; import org.elasticsearch.client.internal.Client; import org.elasticsearch.client.internal.FilterClient; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.project.ProjectResolver; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.core.Nullable; @@ -96,6 +98,7 @@ public abstract class AbstractClient implements Client { private final ThreadPool threadPool; private final ProjectResolver projectResolver; private final AdminClient admin; + private final ProjectClient defaultProjectClient; @SuppressWarnings("this-escape") public AbstractClient(Settings settings, ThreadPool threadPool, ProjectResolver projectResolver) { @@ -104,6 +107,14 @@ public AbstractClient(Settings settings, ThreadPool threadPool, ProjectResolver this.projectResolver = projectResolver; this.admin = new AdminClient(this); this.logger = LogManager.getLogger(this.getClass()); + // We create a dedicated project client for the default project to avoid having to reconstruct it on every invocation. + // This aims to reduce the overhead of creating a project client when the client is used in a single-project context. + // TODO: only create the default project client if the project resolver does not support multiple projects. + if (this instanceof ProjectClient == false) { + this.defaultProjectClient = new ProjectClientImpl(this, ProjectId.DEFAULT); + } else { + this.defaultProjectClient = null; + } } @Override @@ -417,29 +428,13 @@ protected void } @Override - public Client projectClient(ProjectId projectId) { + public ProjectClient projectClient(ProjectId projectId) { // We only take the shortcut when the given project ID matches the "current" project ID. If it doesn't, we'll let #executeOnProject // take care of error handling. if (projectResolver.supportsMultipleProjects() == false && projectId.equals(projectResolver.getProjectId())) { - return this; + return defaultProjectClient; } - return new FilterClient(this) { - @Override - protected void doExecute( - ActionType action, - Request request, - ActionListener listener - ) { - projectResolver.executeOnProject(projectId, () -> super.doExecute(action, request, listener)); - } - - @Override - public Client projectClient(ProjectId projectId) { - throw new IllegalStateException( - "Unable to create a project client for project [" + projectId + "], nested project client creation is not supported" - ); - } - }; + return new ProjectClientImpl(this, projectId); } /** @@ -477,4 +472,35 @@ public R get() throws InterruptedException, ExecutionException { return super.get(); } } + + private static class ProjectClientImpl extends FilterClient implements ProjectClient { + + private final ProjectId projectId; + + ProjectClientImpl(Client in, ProjectId projectId) { + super(in); + this.projectId = projectId; + } + + @Override + public ProjectId projectId() { + return projectId; + } + + @Override + protected void doExecute( + ActionType action, + Request request, + ActionListener listener + ) { + projectResolver().executeOnProject(projectId, () -> super.doExecute(action, request, listener)); + } + + @Override + public ProjectClient projectClient(ProjectId projectId) { + throw new IllegalStateException(Strings.format(""" + Unable to create a project client for project [%s] from project client with project ID [%s],\ + nested project client creation is not supported""", projectId, this.projectId)); + } + } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AbstractStepTestCase.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AbstractStepTestCase.java index 971751b0716fd..1e9c3e8ce4506 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AbstractStepTestCase.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AbstractStepTestCase.java @@ -10,6 +10,7 @@ import org.elasticsearch.client.internal.AdminClient; import org.elasticsearch.client.internal.Client; import org.elasticsearch.client.internal.IndicesAdminClient; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.ClusterStateObserver; import org.elasticsearch.cluster.ProjectState; import org.elasticsearch.cluster.metadata.IndexMetadata; @@ -26,6 +27,7 @@ public abstract class AbstractStepTestCase extends ESTestCase { protected Client client; + protected ProjectClient projectClient; protected AdminClient adminClient; protected IndicesAdminClient indicesClient; @@ -34,9 +36,10 @@ public void setupClient() { client = Mockito.mock(Client.class); adminClient = Mockito.mock(AdminClient.class); indicesClient = Mockito.mock(IndicesAdminClient.class); + projectClient = Mockito.mock(ProjectClient.class); - Mockito.when(client.projectClient(Mockito.any())).thenReturn(client); - Mockito.when(client.admin()).thenReturn(adminClient); + Mockito.when(client.projectClient(Mockito.any())).thenReturn(projectClient); + Mockito.when(projectClient.admin()).thenReturn(adminClient); Mockito.when(adminClient.indices()).thenReturn(indicesClient); } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CleanupSnapshotStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CleanupSnapshotStepTests.java index 9b2d5dfb22b7f..3cab71fbac240 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CleanupSnapshotStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CleanupSnapshotStepTests.java @@ -16,6 +16,7 @@ import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.LifecycleExecutionState; import org.elasticsearch.cluster.metadata.ProjectMetadata; +import org.elasticsearch.cluster.project.TestProjectResolvers; import org.elasticsearch.index.IndexVersion; import org.elasticsearch.test.client.NoOpClient; import org.elasticsearch.threadpool.ThreadPool; @@ -105,7 +106,7 @@ public void testPerformAction() { } private NoOpClient getDeleteSnapshotRequestAssertingClient(ThreadPool threadPool, String expectedSnapshotName) { - return new NoOpClient(threadPool) { + return new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())) { @Override protected void doExecute( ActionType action, diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CloseIndexStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CloseIndexStepTests.java index 1cc979c73a03f..0b2224fdecbf5 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CloseIndexStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CloseIndexStepTests.java @@ -82,7 +82,7 @@ public void onFailure(Exception e) { assertEquals(true, actionCompleted.get()); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).close(Mockito.any(), Mockito.any()); @@ -110,7 +110,7 @@ public void testPerformActionFailure() { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).close(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CreateSnapshotStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CreateSnapshotStepTests.java index a466308e75324..18e81203c28f2 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CreateSnapshotStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/CreateSnapshotStepTests.java @@ -154,7 +154,7 @@ public void testNextStepKey() { ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true)); { try (var threadPool = createThreadPool()) { - final var client = new NoOpClient(threadPool); + final var client = new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())); StepKey nextKeyOnComplete = randomStepKey(); StepKey nextKeyOnIncomplete = randomStepKey(); CreateSnapshotStep completeStep = new CreateSnapshotStep(randomStepKey(), nextKeyOnComplete, nextKeyOnIncomplete, client) { @@ -170,7 +170,7 @@ void createSnapshot(ProjectId projectId, IndexMetadata indexMetadata, ActionList { try (var threadPool = createThreadPool()) { - final var client = new NoOpClient(threadPool); + final var client = new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())); StepKey nextKeyOnComplete = randomStepKey(); StepKey nextKeyOnIncomplete = randomStepKey(); CreateSnapshotStep incompleteStep = new CreateSnapshotStep( @@ -191,7 +191,7 @@ void createSnapshot(ProjectId projectId, IndexMetadata indexMetadata, ActionList { try (var threadPool = createThreadPool()) { - final var client = new NoOpClient(threadPool); + final var client = new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())); StepKey nextKeyOnComplete = randomStepKey(); StepKey nextKeyOnIncomplete = randomStepKey(); CreateSnapshotStep doubleInvocationStep = new CreateSnapshotStep( diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DeleteStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DeleteStepTests.java index f969e7767dd96..c708f7b0703e9 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DeleteStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DeleteStepTests.java @@ -87,7 +87,7 @@ public void testDeleted() throws Exception { performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).delete(any(), any()); @@ -236,14 +236,14 @@ public void testDeleteWorksIfWriteIndexIsTheOnlyIndexInDataStream() throws Excep assertEquals(dataStreamName, request.getNames()[0]); listener.onResponse(null); return null; - }).when(client).execute(any(), any(), any()); + }).when(projectClient).execute(any(), any(), any()); // Try on the normal data stream - It should delete the data stream DeleteStep step = createRandomInstance(); performActionAndWait(step, index1, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).execute(any(), any(), any()); + Mockito.verify(projectClient).execute(any(), any(), any()); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.never()).indices(); Mockito.verify(indicesClient, Mockito.never()).delete(any(), any()); @@ -308,14 +308,14 @@ public void testDeleteWorksIfWriteIndexIsTheOnlyIndexInDataStreamWithFailureStor assertEquals(dataStreamName, request.getNames()[0]); listener.onResponse(null); return null; - }).when(client).execute(any(), any(), any()); + }).when(projectClient).execute(any(), any(), any()); // Again, the deletion should work since the data stream would be fully deleted anyway if the failure store were disabled. DeleteStep step = createRandomInstance(); performActionAndWait(step, index1, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).execute(any(), any(), any()); + Mockito.verify(projectClient).execute(any(), any(), any()); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.never()).indices(); Mockito.verify(indicesClient, Mockito.never()).delete(any(), any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DownsampleStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DownsampleStepTests.java index 6dc4b3f391202..6ba7b771212ee 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DownsampleStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/DownsampleStepTests.java @@ -15,6 +15,7 @@ import org.elasticsearch.cluster.metadata.LifecycleExecutionState; import org.elasticsearch.cluster.metadata.ProjectId; import org.elasticsearch.cluster.metadata.ProjectMetadata; +import org.elasticsearch.cluster.project.TestProjectResolvers; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.IndexVersion; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; @@ -252,7 +253,7 @@ public void testNextStepKey() { ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(sourceIndexMetadata, true)); { try (var threadPool = createThreadPool()) { - final var client = new NoOpClient(threadPool); + final var client = new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())); StepKey nextKey = randomStepKey(); DateHistogramInterval fixedInterval = ConfigTestHelpers.randomInterval(); TimeValue timeout = DownsampleAction.DEFAULT_WAIT_TIMEOUT; @@ -273,7 +274,7 @@ void performDownsampleIndex( } { try (var threadPool = createThreadPool()) { - final var client = new NoOpClient(threadPool); + final var client = new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())); StepKey nextKey = randomStepKey(); DateHistogramInterval fixedInterval = ConfigTestHelpers.randomInterval(); TimeValue timeout = DownsampleAction.DEFAULT_WAIT_TIMEOUT; @@ -316,6 +317,6 @@ private void mockClientDownsampleCall(String sourceIndex) { assertDownsampleActionRequest(request, sourceIndex); listener.onResponse(AcknowledgedResponse.of(true)); return null; - }).when(client).execute(Mockito.any(), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.any(), Mockito.any(), Mockito.any()); } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/OpenIndexStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/OpenIndexStepTests.java index 08f6abf9bd667..50b8b7aaec6fd 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/OpenIndexStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/OpenIndexStepTests.java @@ -66,7 +66,7 @@ public void testPerformAction() throws Exception { performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).open(Mockito.any(), Mockito.any()); @@ -96,7 +96,7 @@ public void testPerformActionFailure() { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).open(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/PauseFollowerIndexStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/PauseFollowerIndexStepTests.java index a00535786466c..90b796b030175 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/PauseFollowerIndexStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/PauseFollowerIndexStepTests.java @@ -50,7 +50,7 @@ public void testPauseFollowingIndex() throws Exception { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onResponse(AcknowledgedResponse.TRUE); return null; - }).when(client).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); PauseFollowerIndexStep step = new PauseFollowerIndexStep(randomStepKey(), randomStepKey(), client); performActionAndWait(step, indexMetadata, state, null); @@ -70,7 +70,7 @@ public void testRequestNotAcknowledged() { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onResponse(AcknowledgedResponse.FALSE); return null; - }).when(client).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); PauseFollowerIndexStep step = new PauseFollowerIndexStep(randomStepKey(), randomStepKey(), client); Exception e = expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null)); @@ -94,12 +94,12 @@ public void testPauseFollowingIndexFailed() { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onFailure(error); return null; - }).when(client).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); PauseFollowerIndexStep step = new PauseFollowerIndexStep(randomStepKey(), randomStepKey(), client); assertSame(error, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); - Mockito.verify(client).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); + Mockito.verify(projectClient).execute(Mockito.same(PauseFollowAction.INSTANCE), Mockito.any(), Mockito.any()); Mockito.verify(client).projectClient(state.projectId()); Mockito.verifyNoMoreInteractions(client); } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/RolloverStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/RolloverStepTests.java index a4e560a7a8d2d..9ebfd498b881b 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/RolloverStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/RolloverStepTests.java @@ -94,7 +94,7 @@ public void testPerformAction() throws Exception { performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).rolloverIndex(Mockito.any(), Mockito.any()); @@ -128,7 +128,7 @@ public void testPerformActionOnDataStream() throws Exception { performActionAndWait(step, indexToOperateOn, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).rolloverIndex(Mockito.any(), Mockito.any()); @@ -250,7 +250,7 @@ public void testPerformActionFailure() { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).rolloverIndex(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/SetSingleNodeAllocateStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/SetSingleNodeAllocateStepTests.java index fbf02a15cafe3..9f105361b97c1 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/SetSingleNodeAllocateStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/SetSingleNodeAllocateStepTests.java @@ -336,7 +336,7 @@ public void testPerformActionAttrsRequestFails() { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).updateSettings(Mockito.any(), Mockito.any()); @@ -666,7 +666,7 @@ private void assertNodeSelected( performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).updateSettings(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkActionTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkActionTests.java index 83c7d51cbfa61..e0b84ef28a79f 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkActionTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkActionTests.java @@ -13,6 +13,7 @@ import org.elasticsearch.client.internal.AdminClient; import org.elasticsearch.client.internal.Client; import org.elasticsearch.client.internal.IndicesAdminClient; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.ProjectState; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.LifecycleExecutionState; @@ -49,7 +50,7 @@ public void setUpClient() throws Exception { AdminClient adminClient = Mockito.mock(AdminClient.class); indicesClient = Mockito.mock(IndicesAdminClient.class); - Client projectClient = Mockito.mock(Client.class); + ProjectClient projectClient = Mockito.mock(ProjectClient.class); Mockito.when(client.projectClient(Mockito.any())).thenReturn(projectClient); Mockito.when(projectClient.admin()).thenReturn(adminClient); Mockito.when(adminClient.indices()).thenReturn(indicesClient); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkSetAliasStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkSetAliasStepTests.java index bae3e8cdb8acb..23c5f708c8637 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkSetAliasStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkSetAliasStepTests.java @@ -97,7 +97,7 @@ public void testPerformAction() throws Exception { performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).aliases(Mockito.any(), Mockito.any()); @@ -123,7 +123,7 @@ public void testPerformActionFailure() { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).aliases(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkStepTests.java index 469fd74349e03..d1b7e5d3e24f1 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ShrinkStepTests.java @@ -127,7 +127,7 @@ public void testPerformAction() throws Exception { performActionAndWait(step, sourceIndexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).resizeIndex(Mockito.any(), Mockito.any()); @@ -193,7 +193,7 @@ public void testPerformActionIsCompleteForUnAckedRequests() throws Exception { performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).resizeIndex(Mockito.any(), Mockito.any()); @@ -222,7 +222,7 @@ public void testPerformActionFailure() throws Exception { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).resizeIndex(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UnfollowFollowerIndexStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UnfollowFollowerIndexStepTests.java index ef94954275c5e..8aff252124b97 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UnfollowFollowerIndexStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UnfollowFollowerIndexStepTests.java @@ -42,7 +42,7 @@ public void testUnFollow() throws Exception { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onResponse(AcknowledgedResponse.TRUE); return null; - }).when(client).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); UnfollowFollowerIndexStep step = new UnfollowFollowerIndexStep(randomStepKey(), randomStepKey(), client); var state = projectStateWithEmptyProject(); @@ -62,7 +62,7 @@ public void testRequestNotAcknowledged() { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onResponse(AcknowledgedResponse.FALSE); return null; - }).when(client).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); UnfollowFollowerIndexStep step = new UnfollowFollowerIndexStep(randomStepKey(), randomStepKey(), client); var state = projectStateWithEmptyProject(); @@ -86,7 +86,7 @@ public void testUnFollowUnfollowFailed() { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onFailure(error); return null; - }).when(client).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); UnfollowFollowerIndexStep step = new UnfollowFollowerIndexStep(randomStepKey(), randomStepKey(), client); var state = projectStateWithEmptyProject(); @@ -110,7 +110,7 @@ public void testFailureToReleaseRetentionLeases() throws Exception { ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onFailure(error); return null; - }).when(client).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); + }).when(projectClient).execute(Mockito.same(UnfollowAction.INSTANCE), Mockito.any(), Mockito.any()); UnfollowFollowerIndexStep step = new UnfollowFollowerIndexStep(randomStepKey(), randomStepKey(), client); var state = projectStateWithEmptyProject(); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UpdateSettingsStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UpdateSettingsStepTests.java index 077104906098f..dce5211cad4e8 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UpdateSettingsStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/UpdateSettingsStepTests.java @@ -81,7 +81,7 @@ public void testPerformAction() throws Exception { performActionAndWait(step, indexMetadata, state, null); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).updateSettings(Mockito.any(), Mockito.any()); @@ -106,7 +106,7 @@ public void testPerformActionFailure() { assertSame(exception, expectThrows(Exception.class, () -> performActionAndWait(step, indexMetadata, state, null))); Mockito.verify(client).projectClient(state.projectId()); - Mockito.verify(client).admin(); + Mockito.verify(projectClient).admin(); Mockito.verifyNoMoreInteractions(client); Mockito.verify(adminClient, Mockito.only()).indices(); Mockito.verify(indicesClient, Mockito.only()).updateSettings(Mockito.any(), Mockito.any()); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/WaitForFollowShardTasksStepTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/WaitForFollowShardTasksStepTests.java index 22ee5db4001f8..457e46aa5acae 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/WaitForFollowShardTasksStepTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/WaitForFollowShardTasksStepTests.java @@ -204,6 +204,6 @@ private void mockFollowStatsCall(String expectedIndexName, List putIndexTemplateRequestCaptor; @Before @@ -63,14 +61,10 @@ public void setUpMocks() { when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); when(threadPool.generic()).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE); + projectClient = mock(ProjectClient.class); client = mock(Client.class); when(client.threadPool()).thenReturn(threadPool); - when(client.projectClient(any())).thenReturn(client); - AdminClient adminClient = mock(AdminClient.class); - IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class); - when(adminClient.indices()).thenReturn(indicesAdminClient); - when(client.admin()).thenReturn(adminClient); - doAnswer(withResponse(AcknowledgedResponse.TRUE)).when(indicesAdminClient).putTemplate(any(), any()); + when(client.projectClient(any())).thenReturn(projectClient); clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); @@ -97,7 +91,7 @@ public void testStateTemplate() { registry.clusterChanged(createClusterChangedEvent(nodes)); - verify(client, times(4)).execute( + verify(projectClient, times(4)).execute( same(TransportPutComposableIndexTemplateAction.TYPE), putIndexTemplateRequestCaptor.capture(), any() @@ -125,7 +119,7 @@ public void testStatsTemplate() { registry.clusterChanged(createClusterChangedEvent(nodes)); - verify(client, times(4)).execute( + verify(projectClient, times(4)).execute( same(TransportPutComposableIndexTemplateAction.TYPE), putIndexTemplateRequestCaptor.capture(), any() diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java index c36cfe1368794..49b8772967f48 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java @@ -6,13 +6,11 @@ */ package org.elasticsearch.xpack.watcher.support; -import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest; import org.elasticsearch.action.admin.indices.template.put.TransportPutComposableIndexTemplateAction; import org.elasticsearch.action.support.master.AcknowledgedResponse; -import org.elasticsearch.client.internal.AdminClient; import org.elasticsearch.client.internal.Client; -import org.elasticsearch.client.internal.IndicesAdminClient; +import org.elasticsearch.client.internal.ProjectClient; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.ClusterName; @@ -67,7 +65,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -82,6 +79,7 @@ public class WatcherIndexTemplateRegistryTests extends ESTestCase { private ClusterService clusterService; private ThreadPool threadPool; private Client client; + private ProjectClient projectClient; @SuppressWarnings("unchecked") @Before @@ -90,18 +88,10 @@ public void createRegistryAndClient() { when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); when(threadPool.generic()).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE); + projectClient = mock(ProjectClient.class); client = mock(Client.class); when(client.threadPool()).thenReturn(threadPool); - when(client.projectClient(any())).thenReturn(client); - AdminClient adminClient = mock(AdminClient.class); - IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class); - when(adminClient.indices()).thenReturn(indicesAdminClient); - when(client.admin()).thenReturn(adminClient); - doAnswer(invocationOnMock -> { - ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; - listener.onResponse(new TestPutIndexTemplateResponse(true)); - return null; - }).when(indicesAdminClient).putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class)); + when(client.projectClient(any())).thenReturn(projectClient); clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); @@ -129,12 +119,12 @@ public void testThatNonExistingTemplatesAreAddedImmediately() { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass( TransportPutComposableIndexTemplateAction.Request.class ); - verify(client, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); + verify(projectClient, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); ClusterChangedEvent newEvent = addTemplateToState(event); registry.clusterChanged(newEvent); argumentCaptor = ArgumentCaptor.forClass(TransportPutComposableIndexTemplateAction.Request.class); - verify(client, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); + verify(projectClient, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); TransportPutComposableIndexTemplateAction.Request req = argumentCaptor.getAllValues() .stream() .filter(r -> r.name().equals(WatcherIndexTemplateRegistryField.HISTORY_TEMPLATE_NAME)) @@ -159,15 +149,15 @@ public void testThatNonExistingTemplatesAreAddedEvenWithILMUsageDisabled() { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass( TransportPutComposableIndexTemplateAction.Request.class ); - verify(client, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); + verify(projectClient, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); // now delete one template from the cluster state and lets retry ClusterChangedEvent newEvent = addTemplateToState(event); registry.clusterChanged(newEvent); ArgumentCaptor captor = ArgumentCaptor.forClass(PutIndexTemplateRequest.class); - verify(client, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); + verify(projectClient, times(1)).execute(same(TransportPutComposableIndexTemplateAction.TYPE), argumentCaptor.capture(), any()); captor.getAllValues().forEach(req -> assertNull(req.settings().get("index.lifecycle.name"))); - verify(client, times(0)).execute(eq(ILMActions.PUT), any(), any()); + verify(projectClient, times(0)).execute(eq(ILMActions.PUT), any(), any()); } public void testThatNonExistingPoliciesAreAddedImmediately() { @@ -176,7 +166,7 @@ public void testThatNonExistingPoliciesAreAddedImmediately() { ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), nodes); registry.clusterChanged(event); - verify(client, times(1)).execute(eq(ILMActions.PUT), any(), any()); + verify(projectClient, times(1)).execute(eq(ILMActions.PUT), any(), any()); } public void testPolicyAlreadyExists() { @@ -190,7 +180,7 @@ public void testPolicyAlreadyExists() { policyMap.put(policy.getName(), policy); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), policyMap, nodes); registry.clusterChanged(event); - verify(client, times(0)).execute(eq(ILMActions.PUT), any(), any()); + verify(projectClient, times(0)).execute(eq(ILMActions.PUT), any(), any()); } public void testNoPolicyButILMDisabled() { @@ -206,7 +196,7 @@ public void testNoPolicyButILMDisabled() { ); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), Collections.emptyMap(), nodes); registry.clusterChanged(event); - verify(client, times(0)).execute(eq(ILMActions.PUT), any(), any()); + verify(projectClient, times(0)).execute(eq(ILMActions.PUT), any(), any()); } public void testPolicyAlreadyExistsButDiffers() throws IOException { @@ -226,7 +216,7 @@ public void testPolicyAlreadyExistsButDiffers() throws IOException { policyMap.put(policy.getName(), different); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), policyMap, nodes); registry.clusterChanged(event); - verify(client, times(0)).execute(eq(ILMActions.PUT), any(), any()); + verify(projectClient, times(0)).execute(eq(ILMActions.PUT), any(), any()); } }