diff --git a/CHANGELOG.md b/CHANGELOG.md index da341454fcb40..6b78222aa742f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -224,7 +224,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Workaround for https://bugs.openjdk.org/browse/JDK-8323659 regression, introduced in JDK-21.0.2 ([#11968](https://github.com/opensearch-project/OpenSearch/pull/11968)) - Updates IpField to be searchable when only `doc_values` are enabled ([#11508](https://github.com/opensearch-project/OpenSearch/pull/11508)) - [Query Insights] Query Insights Framework which currently supports retrieving the most time-consuming queries within the last configured time window ([#11903](https://github.com/opensearch-project/OpenSearch/pull/11903)) -- [Query Insights] Implement Top N Queries Feature in Query Insights Framework([#11904](https://github.com/opensearch-project/OpenSearch/pull/11904)) +- [Query Insights] Implement Top N Queries feature to collect and gather information about high latency queries in a window ([#11904](https://github.com/opensearch-project/OpenSearch/pull/11904)) ### Deprecated diff --git a/plugins/query-insights/src/internalClusterTest/java/org/opensearch/plugin/insights/QueryInsightsPluginTransportIT.java b/plugins/query-insights/src/internalClusterTest/java/org/opensearch/plugin/insights/QueryInsightsPluginTransportIT.java index f1d8594affca7..c16a2edbdf3de 100644 --- a/plugins/query-insights/src/internalClusterTest/java/org/opensearch/plugin/insights/QueryInsightsPluginTransportIT.java +++ b/plugins/query-insights/src/internalClusterTest/java/org/opensearch/plugin/insights/QueryInsightsPluginTransportIT.java @@ -13,6 +13,7 @@ import org.opensearch.action.admin.cluster.node.info.NodesInfoRequest; import org.opensearch.action.admin.cluster.node.info.NodesInfoResponse; import org.opensearch.action.admin.cluster.node.info.PluginsAndModules; +import org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest; import org.opensearch.action.index.IndexResponse; import org.opensearch.action.search.SearchResponse; import org.opensearch.common.settings.Settings; @@ -20,6 +21,7 @@ import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesAction; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesRequest; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesResponse; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.plugins.Plugin; import org.opensearch.plugins.PluginInfo; import org.opensearch.test.OpenSearchIntegTestCase; @@ -28,6 +30,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -74,15 +77,69 @@ public void testQueryInsightPluginInstalled() { * Test get top queries when feature disabled */ public void testGetTopQueriesWhenFeatureDisabled() { - TopQueriesRequest request = new TopQueriesRequest(); + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY); TopQueriesResponse response = OpenSearchIntegTestCase.client().execute(TopQueriesAction.INSTANCE, request).actionGet(); Assert.assertNotEquals(0, response.failures().size()); Assert.assertEquals( - "Cannot get query data when query insight feature is not enabled.", + "Cannot get query data when query insight feature is not enabled for MetricType [latency].", response.failures().get(0).getCause().getCause().getMessage() ); } + /** + * Test update top query record when feature enabled + */ + public void testUpdateRecordWhenFeatureEnabled() throws ExecutionException, InterruptedException { + Settings commonSettings = Settings.builder().put(TOP_N_LATENCY_QUERIES_ENABLED.getKey(), "false").build(); + + logger.info("--> starting nodes for query insight testing"); + List nodes = internalCluster().startNodes(TOTAL_NUMBER_OF_NODES, Settings.builder().put(commonSettings).build()); + + logger.info("--> waiting for nodes to form a cluster"); + ClusterHealthResponse health = client().admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet(); + assertFalse(health.isTimedOut()); + + assertAcked( + prepareCreate("test").setSettings(Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 2)) + ); + ensureStableCluster(2); + logger.info("--> creating indices for query insight testing"); + for (int i = 0; i < 5; i++) { + IndexResponse response = client().prepareIndex("test_" + i).setId("" + i).setSource("field_" + i, "value_" + i).get(); + assertEquals("CREATED", response.status().toString()); + } + // making search requests to get top queries + for (int i = 0; i < TOTAL_SEARCH_REQUESTS; i++) { + SearchResponse searchResponse = internalCluster().client(randomFrom(nodes)) + .prepareSearch() + .setQuery(QueryBuilders.matchAllQuery()) + .get(); + assertEquals(searchResponse.getFailedShards(), 0); + } + + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY); + TopQueriesResponse response = OpenSearchIntegTestCase.client().execute(TopQueriesAction.INSTANCE, request).actionGet(); + Assert.assertNotEquals(0, response.failures().size()); + Assert.assertEquals( + "Cannot get query data when query insight feature is not enabled for MetricType [latency].", + response.failures().get(0).getCause().getCause().getMessage() + ); + + ClusterUpdateSettingsRequest updateSettingsRequest = new ClusterUpdateSettingsRequest().persistentSettings( + Settings.builder().put(TOP_N_LATENCY_QUERIES_ENABLED.getKey(), "true").build() + ); + assertAcked(internalCluster().client().admin().cluster().updateSettings(updateSettingsRequest).get()); + TopQueriesRequest request2 = new TopQueriesRequest(MetricType.LATENCY); + TopQueriesResponse response2 = OpenSearchIntegTestCase.client().execute(TopQueriesAction.INSTANCE, request2).actionGet(); + Assert.assertEquals(0, response2.failures().size()); + Assert.assertEquals(TOTAL_NUMBER_OF_NODES, response2.getNodes().size()); + for (int i = 0; i < TOTAL_NUMBER_OF_NODES; i++) { + Assert.assertEquals(0, response2.getNodes().get(i).getTopQueriesRecord().size()); + } + + internalCluster().stopAllNodes(); + } + /** * Test get top queries when feature enabled */ @@ -93,7 +150,7 @@ public void testGetTopQueriesWhenFeatureEnabled() { .put(TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey(), "600s") .build(); - logger.info("--> starting 2 nodes for query insight testing"); + logger.info("--> starting nodes for query insight testing"); List nodes = internalCluster().startNodes(TOTAL_NUMBER_OF_NODES, Settings.builder().put(commonSettings).build()); logger.info("--> waiting for nodes to form a cluster"); @@ -118,11 +175,11 @@ public void testGetTopQueriesWhenFeatureEnabled() { assertEquals(searchResponse.getFailedShards(), 0); } - TopQueriesRequest request = new TopQueriesRequest(); + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY); TopQueriesResponse response = OpenSearchIntegTestCase.client().execute(TopQueriesAction.INSTANCE, request).actionGet(); Assert.assertEquals(0, response.failures().size()); Assert.assertEquals(TOTAL_NUMBER_OF_NODES, response.getNodes().size()); - Assert.assertEquals(TOTAL_SEARCH_REQUESTS, response.getNodes().stream().mapToInt(o -> o.getLatencyRecords().size()).sum()); + Assert.assertEquals(TOTAL_SEARCH_REQUESTS, response.getNodes().stream().mapToInt(o -> o.getTopQueriesRecord().size()).sum()); internalCluster().stopAllNodes(); } @@ -137,7 +194,7 @@ public void testGetTopQueriesWithSmallTopN() { .put(TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey(), "600s") .build(); - logger.info("--> starting 2 nodes for query insight testing"); + logger.info("--> starting nodes for query insight testing"); List nodes = internalCluster().startNodes(TOTAL_NUMBER_OF_NODES, Settings.builder().put(commonSettings).build()); logger.info("--> waiting for nodes to form a cluster"); @@ -162,12 +219,11 @@ public void testGetTopQueriesWithSmallTopN() { assertEquals(searchResponse.getFailedShards(), 0); } - TopQueriesRequest request = new TopQueriesRequest(); + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY); TopQueriesResponse response = OpenSearchIntegTestCase.client().execute(TopQueriesAction.INSTANCE, request).actionGet(); Assert.assertEquals(0, response.failures().size()); Assert.assertEquals(TOTAL_NUMBER_OF_NODES, response.getNodes().size()); - // TODO: this should be 1 after changing to cluster level top N. - Assert.assertEquals(2, response.getNodes().stream().mapToInt(o -> o.getLatencyRecords().size()).sum()); + Assert.assertEquals(2, response.getNodes().stream().mapToInt(o -> o.getTopQueriesRecord().size()).sum()); internalCluster().stopAllNodes(); } @@ -179,10 +235,10 @@ public void testGetTopQueriesWithSmallWindowSize() { Settings commonSettings = Settings.builder() .put(TOP_N_LATENCY_QUERIES_ENABLED.getKey(), "true") .put(TOP_N_LATENCY_QUERIES_SIZE.getKey(), "100") - .put(TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey(), "0ms") + .put(TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey(), "1m") .build(); - logger.info("--> starting 2 nodes for query insight testing"); + logger.info("--> starting nodes for query insight testing"); List nodes = internalCluster().startNodes(TOTAL_NUMBER_OF_NODES, Settings.builder().put(commonSettings).build()); logger.info("--> waiting for nodes to form a cluster"); @@ -207,11 +263,10 @@ public void testGetTopQueriesWithSmallWindowSize() { assertEquals(searchResponse.getFailedShards(), 0); } - TopQueriesRequest request = new TopQueriesRequest(); + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY); TopQueriesResponse response = OpenSearchIntegTestCase.client().execute(TopQueriesAction.INSTANCE, request).actionGet(); Assert.assertEquals(0, response.failures().size()); Assert.assertEquals(TOTAL_NUMBER_OF_NODES, response.getNodes().size()); - Assert.assertEquals(0, response.getNodes().stream().mapToInt(o -> o.getLatencyRecords().size()).sum()); internalCluster().stopAllNodes(); } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/listener/QueryInsightsListener.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/listener/QueryInsightsListener.java new file mode 100644 index 0000000000000..3bc8215ec19e5 --- /dev/null +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/listener/QueryInsightsListener.java @@ -0,0 +1,141 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.insights.core.listener; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.opensearch.action.search.SearchPhaseContext; +import org.opensearch.action.search.SearchRequest; +import org.opensearch.action.search.SearchRequestContext; +import org.opensearch.action.search.SearchRequestOperationsListener; +import org.opensearch.cluster.service.ClusterService; +import org.opensearch.common.inject.Inject; +import org.opensearch.core.xcontent.ToXContent; +import org.opensearch.plugin.insights.core.service.QueryInsightsService; +import org.opensearch.plugin.insights.rules.model.Attribute; +import org.opensearch.plugin.insights.rules.model.Measurement; +import org.opensearch.plugin.insights.rules.model.MetricType; +import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED; +import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE; +import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE; + +/** + * The listener for top N queries by latency + * + * @opensearch.internal + */ +public final class QueryInsightsListener extends SearchRequestOperationsListener { + private static final ToXContent.Params FORMAT_PARAMS = new ToXContent.MapParams(Collections.singletonMap("pretty", "false")); + + private static final Logger log = LogManager.getLogger(QueryInsightsListener.class); + + private final QueryInsightsService queryInsightsService; + + /** + * Constructor for QueryInsightsListener + * + * @param clusterService The Node's cluster service. + * @param queryInsightsService The topQueriesByLatencyService associated with this listener + */ + @Inject + public QueryInsightsListener(ClusterService clusterService, QueryInsightsService queryInsightsService) { + this.queryInsightsService = queryInsightsService; + clusterService.getClusterSettings() + .addSettingsUpdateConsumer(TOP_N_LATENCY_QUERIES_ENABLED, v -> this.setEnabled(MetricType.LATENCY, v)); + clusterService.getClusterSettings() + .addSettingsUpdateConsumer( + TOP_N_LATENCY_QUERIES_SIZE, + this.queryInsightsService::setTopNSize, + this.queryInsightsService::validateTopNSize + ); + clusterService.getClusterSettings() + .addSettingsUpdateConsumer( + TOP_N_LATENCY_QUERIES_WINDOW_SIZE, + this.queryInsightsService::setWindowSize, + this.queryInsightsService::validateWindowSize + ); + this.setEnabled(MetricType.LATENCY, clusterService.getClusterSettings().get(TOP_N_LATENCY_QUERIES_ENABLED)); + this.queryInsightsService.setTopNSize(clusterService.getClusterSettings().get(TOP_N_LATENCY_QUERIES_SIZE)); + this.queryInsightsService.setWindowSize(clusterService.getClusterSettings().get(TOP_N_LATENCY_QUERIES_WINDOW_SIZE)); + } + + /** + * Enable or disable metric collection for {@link MetricType} + * + * @param metricType {@link MetricType} + * @param enabled boolean + */ + public void setEnabled(MetricType metricType, boolean enabled) { + this.queryInsightsService.enableCollection(metricType, enabled); + + // disable QueryInsightsListener only if collection for all metrics are disabled. + if (!enabled) { + for (MetricType t : MetricType.allMetricTypes()) { + if (this.queryInsightsService.isCollectionEnabled(t)) { + return; + } + } + super.setEnabled(false); + } else { + super.setEnabled(true); + } + } + + @Override + public boolean isEnabled() { + return super.isEnabled(); + } + + @Override + public void onPhaseStart(SearchPhaseContext context) {} + + @Override + public void onPhaseEnd(SearchPhaseContext context, SearchRequestContext searchRequestContext) {} + + @Override + public void onPhaseFailure(SearchPhaseContext context) {} + + @Override + public void onRequestStart(SearchRequestContext searchRequestContext) {} + + @Override + public void onRequestEnd(SearchPhaseContext context, SearchRequestContext searchRequestContext) { + SearchRequest request = context.getRequest(); + try { + Map> measurements = new HashMap<>(); + if (queryInsightsService.isCollectionEnabled(MetricType.LATENCY)) { + measurements.put( + MetricType.LATENCY, + new Measurement<>( + MetricType.LATENCY.name(), + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - searchRequestContext.getAbsoluteStartNanos()) + ) + ); + } + Map attributes = new HashMap<>(); + attributes.put(Attribute.SEARCH_TYPE, request.searchType().toString().toLowerCase(Locale.ROOT)); + attributes.put(Attribute.SOURCE, request.source().toString(FORMAT_PARAMS)); + attributes.put(Attribute.TOTAL_SHARDS, context.getNumShards()); + attributes.put(Attribute.INDICES, request.indices()); + attributes.put(Attribute.PHASE_LATENCY_MAP, searchRequestContext.phaseTookMap()); + SearchQueryRecord record = new SearchQueryRecord(request.getOrCreateAbsoluteStartMillis(), measurements, attributes); + queryInsightsService.addRecord(record); + } catch (Exception e) { + log.error(String.format(Locale.ROOT, "fail to ingest query insight data, error: %s", e)); + } + } +} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/listener/SearchQueryLatencyListener.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/listener/SearchQueryLatencyListener.java deleted file mode 100644 index c97391c74bf1c..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/listener/SearchQueryLatencyListener.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -package org.opensearch.plugin.insights.core.listener; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.opensearch.action.search.SearchPhaseContext; -import org.opensearch.action.search.SearchRequest; -import org.opensearch.action.search.SearchRequestContext; -import org.opensearch.action.search.SearchRequestOperationsListener; -import org.opensearch.cluster.service.ClusterService; -import org.opensearch.common.inject.Inject; -import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.plugin.insights.core.service.TopQueriesByLatencyService; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; - -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE; - -/** - * The listener for top N queries by latency - * - * @opensearch.internal - */ -public final class SearchQueryLatencyListener extends SearchRequestOperationsListener { - private static final ToXContent.Params FORMAT_PARAMS = new ToXContent.MapParams(Collections.singletonMap("pretty", "false")); - - private static final Logger log = LogManager.getLogger(SearchQueryLatencyListener.class); - - private final TopQueriesByLatencyService topQueriesByLatencyService; - - /** - * Constructor for SearchQueryLatencyListener - * - * @param clusterService The Node's cluster service. - * @param topQueriesByLatencyService The topQueriesByLatencyService associated with this listener - */ - @Inject - public SearchQueryLatencyListener(ClusterService clusterService, TopQueriesByLatencyService topQueriesByLatencyService) { - this.topQueriesByLatencyService = topQueriesByLatencyService; - clusterService.getClusterSettings().addSettingsUpdateConsumer(TOP_N_LATENCY_QUERIES_ENABLED, this::setEnabled); - clusterService.getClusterSettings() - .addSettingsUpdateConsumer( - TOP_N_LATENCY_QUERIES_SIZE, - this.topQueriesByLatencyService::setTopNSize, - this.topQueriesByLatencyService::validateTopNSize - ); - clusterService.getClusterSettings() - .addSettingsUpdateConsumer( - TOP_N_LATENCY_QUERIES_WINDOW_SIZE, - this.topQueriesByLatencyService::setWindowSize, - this.topQueriesByLatencyService::validateWindowSize - ); - clusterService.getClusterSettings() - .addSettingsUpdateConsumer(TOP_N_LATENCY_QUERIES_EXPORTER_TYPE, this.topQueriesByLatencyService::setExporterType); - clusterService.getClusterSettings() - .addSettingsUpdateConsumer( - TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL, - this.topQueriesByLatencyService::setExportInterval, - this.topQueriesByLatencyService::validateExportInterval - ); - clusterService.getClusterSettings() - .addSettingsUpdateConsumer(TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER, this.topQueriesByLatencyService::setExporterIdentifier); - clusterService.getClusterSettings() - .addSettingsUpdateConsumer(TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED, this.topQueriesByLatencyService::setExporterEnabled); - - this.setEnabled(clusterService.getClusterSettings().get(TOP_N_LATENCY_QUERIES_ENABLED)); - this.topQueriesByLatencyService.setTopNSize(clusterService.getClusterSettings().get(TOP_N_LATENCY_QUERIES_SIZE)); - this.topQueriesByLatencyService.setWindowSize(clusterService.getClusterSettings().get(TOP_N_LATENCY_QUERIES_WINDOW_SIZE)); - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - this.topQueriesByLatencyService.setEnableCollect(enabled); - } - - @Override - public boolean isEnabled() { - return super.isEnabled(); - } - - @Override - public void onPhaseStart(SearchPhaseContext context) {} - - @Override - public void onPhaseEnd(SearchPhaseContext context, SearchRequestContext searchRequestContext) {} - - @Override - public void onPhaseFailure(SearchPhaseContext context) {} - - @Override - public void onRequestStart(SearchRequestContext searchRequestContext) {} - - @Override - public void onRequestEnd(SearchPhaseContext context, SearchRequestContext searchRequestContext) { - SearchRequest request = context.getRequest(); - try { - topQueriesByLatencyService.ingestQueryData( - request.getOrCreateAbsoluteStartMillis(), - request.searchType(), - request.source().toString(FORMAT_PARAMS), - context.getNumShards(), - request.indices(), - new HashMap<>(), - searchRequestContext.phaseTookMap(), - System.nanoTime() - searchRequestContext.getAbsoluteStartNanos() - ); - } catch (Exception e) { - log.error(String.format(Locale.ROOT, "fail to ingest query insight data, error: %s", e)); - } - } -} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/TopQueriesByLatencyService.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/TopQueriesByLatencyService.java deleted file mode 100644 index 087600db2e1d9..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/TopQueriesByLatencyService.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -package org.opensearch.plugin.insights.core.service; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.opensearch.action.search.SearchType; -import org.opensearch.client.Client; -import org.opensearch.cluster.service.ClusterService; -import org.opensearch.common.inject.Inject; -import org.opensearch.common.unit.TimeValue; -import org.opensearch.plugin.insights.core.exporter.QueryInsightsExporter; -import org.opensearch.plugin.insights.core.exporter.QueryInsightsExporterType; -import org.opensearch.plugin.insights.core.exporter.QueryInsightsLocalIndexExporter; -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; -import org.opensearch.plugin.insights.settings.QueryInsightsSettings; -import org.opensearch.threadpool.ThreadPool; - -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.PriorityBlockingQueue; - -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.DEFAULT_LOCAL_INDEX_MAPPING; -import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.MIN_EXPORT_INTERVAL; - -/** - * Service responsible for gathering, analyzing, storing and exporting - * top N queries with high latency data for search queries - * - * @opensearch.internal - */ -public class TopQueriesByLatencyService extends QueryInsightsService< - SearchQueryLatencyRecord, - PriorityBlockingQueue, - QueryInsightsExporter> { - private static final Logger log = LogManager.getLogger(TopQueriesByLatencyService.class); - - private static final TimeValue delay = TimeValue.ZERO; - - private int topNSize = QueryInsightsSettings.DEFAULT_TOP_N_SIZE; - - private TimeValue windowSize = TimeValue.timeValueSeconds(QueryInsightsSettings.DEFAULT_WINDOW_SIZE); - - private final ClusterService clusterService; - private final Client client; - - /** - * Create the TopQueriesByLatencyService Object - * @param threadPool The OpenSearch thread pool to run async tasks - * @param clusterService The clusterService of this node - * @param client The OpenSearch Client - */ - @Inject - public TopQueriesByLatencyService(ThreadPool threadPool, ClusterService clusterService, Client client) { - super(threadPool, new PriorityBlockingQueue<>(), null); - this.clusterService = clusterService; - this.client = client; - } - - /** - * Ingest the query data into to the top N queries with latency store - * - * @param timestamp The timestamp of the query. - * @param searchType The manner at which the search operation is executed. see {@link SearchType} - * @param source The search source that was executed by the query. - * @param totalShards Total number of shards as part of the search query across all indices - * @param indices The indices involved in the search query - * @param propertyMap Extra attributes and information about a search query - * @param phaseLatencyMap Contains phase level latency information in a search query - * @param tookInNanos Total search request took time in nanoseconds - */ - public void ingestQueryData( - final Long timestamp, - final SearchType searchType, - final String source, - final int totalShards, - final String[] indices, - final Map propertyMap, - final Map phaseLatencyMap, - final Long tookInNanos - ) { - if (timestamp <= 0) { - log.error( - String.format( - Locale.ROOT, - "Invalid timestamp %s when ingesting query data to compute top n queries with latency", - timestamp - ) - ); - return; - } - if (totalShards <= 0) { - log.error( - String.format( - Locale.ROOT, - "Invalid totalShards %s when ingesting query data to compute top n queries with latency", - totalShards - ) - ); - return; - } - this.threadPool.schedule(() -> { - clearOutdatedData(); - super.ingestQueryData( - new SearchQueryLatencyRecord(timestamp, searchType, source, totalShards, indices, propertyMap, phaseLatencyMap, tookInNanos) - ); - // remove top elements for fix sizing priority queue - if (this.store.size() > this.getTopNSize()) { - this.store.poll(); - } - }, delay, ThreadPool.Names.GENERIC); - - log.debug(String.format(Locale.ROOT, "successfully ingested: %s", this.store)); - } - - @Override - public void clearOutdatedData() { - store.removeIf(record -> record.getTimestamp() < System.currentTimeMillis() - windowSize.getMillis()); - } - - /** - * Set the top N size for TopQueriesByLatencyService service. - * @param size the top N size to set - */ - public void setTopNSize(int size) { - this.topNSize = size; - } - - /** - * Validate the top N size based on the internal constrains - * @param size the wanted top N size - */ - public void validateTopNSize(int size) { - if (size > QueryInsightsSettings.MAX_N_SIZE) { - throw new IllegalArgumentException( - "Top N size setting [" - + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE.getKey() - + "]" - + " should be smaller than max top N size [" - + QueryInsightsSettings.MAX_N_SIZE - + "was (" - + size - + " > " - + QueryInsightsSettings.MAX_N_SIZE - + ")" - ); - } - } - - /** - * Get the top N size set for TopQueriesByLatencyService - * @return the top N size - */ - public int getTopNSize() { - return this.topNSize; - } - - /** - * Set the window size for TopQueriesByLatencyService - * @param windowSize window size to set - */ - public void setWindowSize(TimeValue windowSize) { - this.windowSize = windowSize; - } - - /** - * Validate if the window size is valid, based on internal constrains. - * @param windowSize the window size to validate - */ - public void validateWindowSize(TimeValue windowSize) { - if (windowSize.compareTo(QueryInsightsSettings.MAX_WINDOW_SIZE) > 0) { - throw new IllegalArgumentException( - "Window size setting [" - + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey() - + "]" - + " should be smaller than max window size [" - + QueryInsightsSettings.MAX_WINDOW_SIZE - + "was (" - + windowSize - + " > " - + QueryInsightsSettings.MAX_WINDOW_SIZE - + ")" - ); - } - } - - /** - * Get the window size set for TopQueriesByLatencyService - * @return the window size - */ - public TimeValue getWindowSize() { - return this.windowSize; - } - - /** - * Set the exporter type to export data generated in TopQueriesByLatencyService - * @param type The type of exporter, defined in {@link QueryInsightsExporterType} - */ - public void setExporterType(QueryInsightsExporterType type) { - resetExporter( - getEnableExport(), - type, - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER) - ); - } - - /** - * Set if the exporter is enabled - * @param enabled if the exporter is enabled - */ - public void setExporterEnabled(boolean enabled) { - super.setEnableExport(enabled); - resetExporter( - enabled, - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE), - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER) - ); - } - - /** - * Set the identifier of this exporter, which will be used when exporting the data - * - * For example, for local index exporter, this identifier would be used to define the index name - * @param identifier the identifier for the exporter - */ - public void setExporterIdentifier(String identifier) { - resetExporter( - getEnableExport(), - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE), - identifier - ); - } - - /** - * Set the export interval for the exporter - * @param interval export interval - */ - public void setExportInterval(TimeValue interval) { - super.setExportInterval(interval); - resetExporter( - getEnableExport(), - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE), - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER) - ); - } - - /** - * Validate if the export interval is valid, based on internal constrains. - * @param exportInterval the export interval to validate - */ - public void validateExportInterval(TimeValue exportInterval) { - if (exportInterval.getSeconds() < MIN_EXPORT_INTERVAL.getSeconds()) { - throw new IllegalArgumentException( - "Export Interval setting [" - + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL.getKey() - + "]" - + " should not be smaller than minimal export interval size [" - + MIN_EXPORT_INTERVAL - + "]" - + "was (" - + exportInterval - + " < " - + MIN_EXPORT_INTERVAL - + ")" - ); - } - } - - /** - * Reset the exporter with new config - * - * This function can be used to enable/disable an exporter, change the type of the exporter, - * or change the identifier of the exporter. - * @param enabled the enable flag to set on the exporter - * @param type The QueryInsightsExporterType to set on the exporter - * @param identifier the Identifier to set on the exporter - */ - public void resetExporter(boolean enabled, QueryInsightsExporterType type, String identifier) { - this.stop(); - this.exporter = null; - - if (!enabled) { - return; - } - if (type.equals(QueryInsightsExporterType.LOCAL_INDEX)) { - this.exporter = new QueryInsightsLocalIndexExporter<>( - clusterService, - client, - identifier, - TopQueriesByLatencyService.class.getClassLoader().getResourceAsStream(DEFAULT_LOCAL_INDEX_MAPPING) - ); - } - this.start(); - } - -} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueries.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueries.java index 138d23a365de3..640a0b82260b5 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueries.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueries.java @@ -10,12 +10,11 @@ import org.opensearch.action.support.nodes.BaseNodeResponse; import org.opensearch.cluster.node.DiscoveryNode; -import org.opensearch.common.Nullable; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; +import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; import java.io.IOException; import java.util.List; @@ -28,9 +27,8 @@ * @opensearch.internal */ public class TopQueries extends BaseNodeResponse implements ToXContentObject { - /** The store to keep the top N queries with latency records */ - @Nullable - private final List latencyRecords; + /** The store to keep the top N queries records */ + private final List topQueriesRecords; /** * Create the TopQueries Object from StreamInput @@ -39,23 +37,23 @@ public class TopQueries extends BaseNodeResponse implements ToXContentObject { */ public TopQueries(StreamInput in) throws IOException { super(in); - latencyRecords = in.readList(SearchQueryLatencyRecord::new); + topQueriesRecords = in.readList(SearchQueryRecord::new); } /** * Create the TopQueries Object * @param node A node that is part of the cluster. - * @param latencyRecords The top queries by latency records stored on this node + * @param searchQueryRecords A list of SearchQueryRecord associated in this TopQueries. */ - public TopQueries(DiscoveryNode node, @Nullable List latencyRecords) { + public TopQueries(DiscoveryNode node, List searchQueryRecords) { super(node); - this.latencyRecords = latencyRecords; + topQueriesRecords = searchQueryRecords; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (latencyRecords != null) { - for (SearchQueryLatencyRecord record : latencyRecords) { + if (topQueriesRecords != null) { + for (SearchQueryRecord record : topQueriesRecords) { record.toXContent(builder, params); } } @@ -65,17 +63,16 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - if (latencyRecords != null) { - out.writeList(latencyRecords); - } + out.writeList(topQueriesRecords); + } /** - * Get all latency records + * Get all top queries records * - * @return the latency records in this node response + * @return the top queries records in this node response */ - public List getLatencyRecords() { - return latencyRecords; + public List getTopQueriesRecord() { + return topQueriesRecords; } } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesAction.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesAction.java index 13dd198681ca8..b8ed69fa5692b 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesAction.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesAction.java @@ -24,7 +24,7 @@ public class TopQueriesAction extends ActionType { /** * The name of this Action */ - public static final String NAME = "cluster:monitor/insights/top_queries"; + public static final String NAME = "cluster:admin/opensearch/insights/top_queries"; private TopQueriesAction() { super(NAME, TopQueriesResponse::new); diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequest.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequest.java index a671e3a7fe176..27177fef25bea 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequest.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequest.java @@ -12,12 +12,9 @@ import org.opensearch.common.annotation.PublicApi; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.plugin.insights.rules.model.MetricType; import java.io.IOException; -import java.util.Arrays; -import java.util.Locale; -import java.util.Set; -import java.util.stream.Collectors; /** * A request to get cluster/node level top queries information. @@ -27,7 +24,7 @@ @PublicApi(since = "1.0.0") public class TopQueriesRequest extends BaseNodesRequest { - Metric metricType = Metric.LATENCY; + MetricType metricType; /** * Constructor for TopQueriesRequest @@ -37,76 +34,35 @@ public class TopQueriesRequest extends BaseNodesRequest { */ public TopQueriesRequest(StreamInput in) throws IOException { super(in); - setMetricType(in.readString()); + MetricType metricType = MetricType.readFromStream(in); + if (false == MetricType.allMetricTypes().contains(metricType)) { + throw new IllegalStateException("Invalid metric used in top queries request: " + metricType); + } + this.metricType = metricType; } /** * Get top queries from nodes based on the nodes ids specified. * If none are passed, cluster level top queries will be returned. * + * @param metricType {@link MetricType} * @param nodesIds the nodeIds specified in the request */ - public TopQueriesRequest(String... nodesIds) { + public TopQueriesRequest(MetricType metricType, String... nodesIds) { super(nodesIds); + this.metricType = metricType; } /** * Get the type of requested metrics */ - public Metric getMetricType() { + public MetricType getMetricType() { return metricType; } - /** - * Validate and set the metric type of requested metrics - * - * @param metricType the metric type to set to - * @return The current TopQueriesRequest - */ - public TopQueriesRequest setMetricType(String metricType) { - metricType = metricType.toUpperCase(Locale.ROOT); - if (false == Metric.allMetrics().contains(metricType)) { - throw new IllegalStateException("Invalid metric used in top queries request: " + metricType); - } - this.metricType = Metric.valueOf(metricType); - return this; - } - @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeString(metricType.metricName()); - } - - /** - * ALl supported metrics for top queries - */ - public enum Metric { - /** - * Latency metric type, used by top queries by latency - */ - LATENCY("LATENCY"); - - private final String metricName; - - Metric(String name) { - this.metricName = name; - } - - /** - * Get the metric name of the Metric - * @return the metric name - */ - public String metricName() { - return this.metricName; - } - - /** - * Get all valid metrics - * @return A set of String that contains all valid metrics - */ - public static Set allMetrics() { - return Arrays.stream(values()).map(Metric::metricName).collect(Collectors.toSet()); - } + out.writeString(metricType.toString()); } } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponse.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponse.java index b9afd2898ab07..fe7644de5629f 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponse.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponse.java @@ -17,11 +17,12 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; +import org.opensearch.plugin.insights.rules.model.Attribute; +import org.opensearch.plugin.insights.rules.model.MetricType; +import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; import java.io.IOException; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -34,6 +35,7 @@ public class TopQueriesResponse extends BaseNodesResponse implements ToXContentFragment { private static final String CLUSTER_LEVEL_RESULTS_KEY = "top_queries"; + private final MetricType metricType; private final int top_n_size; /** @@ -45,6 +47,7 @@ public class TopQueriesResponse extends BaseNodesResponse implements public TopQueriesResponse(StreamInput in) throws IOException { super(in); top_n_size = in.readInt(); + metricType = in.readEnum(MetricType.class); } /** @@ -54,10 +57,18 @@ public TopQueriesResponse(StreamInput in) throws IOException { * @param nodes A list that contains top queries results from all nodes * @param failures A list that contains FailedNodeException * @param top_n_size The top N size to return to the user + * @param metricType the {@link MetricType} to be returned in this response */ - public TopQueriesResponse(ClusterName clusterName, List nodes, List failures, int top_n_size) { + public TopQueriesResponse( + ClusterName clusterName, + List nodes, + List failures, + int top_n_size, + MetricType metricType + ) { super(clusterName, nodes, failures); this.top_n_size = top_n_size; + this.metricType = metricType; } @Override @@ -69,11 +80,13 @@ protected List readNodesFrom(StreamInput in) throws IOException { protected void writeNodesTo(StreamOutput out, List nodes) throws IOException { out.writeList(nodes); out.writeLong(top_n_size); + out.writeEnum(metricType); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { List results = getNodes(); + postProcess(results); builder.startObject(); toClusterLevelResult(builder, params, results); return builder.endObject(); @@ -92,6 +105,20 @@ public String toString() { } } + /** + * Post process the top queries results to add customized attributes + * + * @param results the top queries results + */ + private void postProcess(List results) { + for (TopQueries topQueries : results) { + String nodeId = topQueries.getNode().getId(); + for (SearchQueryRecord record : topQueries.getTopQueriesRecord()) { + record.addAttribute(Attribute.NODE_ID, nodeId); + } + } + } + /** * Merge top n queries results from nodes into cluster level results in XContent format. * @@ -101,16 +128,17 @@ public String toString() { * @throws IOException if an error occurs */ private void toClusterLevelResult(XContentBuilder builder, Params params, List results) throws IOException { - List all_records = results.stream() - .map(TopQueries::getLatencyRecords) + List all_records = results.stream() + .map(TopQueries::getTopQueriesRecord) .flatMap(Collection::stream) - .sorted(Collections.reverseOrder()) + .sorted((a, b) -> SearchQueryRecord.compare(a, b, metricType) * -1) .limit(top_n_size) .collect(Collectors.toList()); builder.startArray(CLUSTER_LEVEL_RESULTS_KEY); - for (SearchQueryLatencyRecord record : all_records) { + for (SearchQueryRecord record : all_records) { record.toXContent(builder, params); } builder.endArray(); } + } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/resthandler/top_queries/RestTopQueriesAction.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/resthandler/top_queries/RestTopQueriesAction.java index 9c0271842372d..654aab6eb1563 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/resthandler/top_queries/RestTopQueriesAction.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/resthandler/top_queries/RestTopQueriesAction.java @@ -16,6 +16,7 @@ import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesAction; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesRequest; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesResponse; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.rest.BaseRestHandler; import org.opensearch.rest.BytesRestResponse; import org.opensearch.rest.RestChannel; @@ -26,6 +27,7 @@ import java.util.List; import java.util.Locale; import java.util.Set; +import java.util.stream.Collectors; import static org.opensearch.plugin.insights.settings.QueryInsightsSettings.TOP_QUERIES_BASE_URI; import static org.opensearch.rest.RestRequest.Method.GET; @@ -37,7 +39,7 @@ */ public class RestTopQueriesAction extends BaseRestHandler { /** The metric types that are allowed in top N queries */ - static final Set ALLOWED_METRICS = TopQueriesRequest.Metric.allMetrics(); + static final Set ALLOWED_METRICS = MetricType.allMetricTypes().stream().map(MetricType::toString).collect(Collectors.toSet()); /** * Constructor for RestTopQueriesAction @@ -72,15 +74,13 @@ public RestChannelConsumer prepareRequest(final RestRequest request, final NodeC static TopQueriesRequest prepareRequest(final RestRequest request) { String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId")); - String metricType = request.param("type", TopQueriesRequest.Metric.LATENCY.metricName()).toUpperCase(Locale.ROOT); + String metricType = request.param("type", MetricType.LATENCY.toString()); if (!ALLOWED_METRICS.contains(metricType)) { throw new IllegalArgumentException( String.format(Locale.ROOT, "request [%s] contains invalid metric type [%s]", request.path(), metricType) ); } - TopQueriesRequest topQueriesRequest = new TopQueriesRequest(nodesIds); - topQueriesRequest.setMetricType(metricType); - return topQueriesRequest; + return new TopQueriesRequest(MetricType.fromString(metricType), nodesIds); } @Override diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesAction.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesAction.java index 66ba350f281b2..a4ddaca0a6cdc 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesAction.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesAction.java @@ -16,11 +16,12 @@ import org.opensearch.common.inject.Inject; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.plugin.insights.core.service.TopQueriesByLatencyService; +import org.opensearch.plugin.insights.core.service.QueryInsightsService; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueries; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesAction; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesRequest; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesResponse; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.plugin.insights.settings.QueryInsightsSettings; import org.opensearch.threadpool.ThreadPool; import org.opensearch.transport.TransportRequest; @@ -41,7 +42,7 @@ public class TransportTopQueriesAction extends TransportNodesAction< TransportTopQueriesAction.NodeRequest, TopQueries> { - private final TopQueriesByLatencyService topQueriesByLatencyService; + private final QueryInsightsService queryInsightsService; /** * Create the TransportTopQueriesAction Object @@ -49,7 +50,7 @@ public class TransportTopQueriesAction extends TransportNodesAction< * @param threadPool The OpenSearch thread pool to run async tasks * @param clusterService The clusterService of this node * @param transportService The TransportService of this node - * @param topQueriesByLatencyService The topQueriesByLatencyService associated with this Transport Action + * @param queryInsightsService The topQueriesByLatencyService associated with this Transport Action * @param actionFilters the action filters */ @Inject @@ -57,7 +58,7 @@ public TransportTopQueriesAction( ThreadPool threadPool, ClusterService clusterService, TransportService transportService, - TopQueriesByLatencyService topQueriesByLatencyService, + QueryInsightsService queryInsightsService, ActionFilters actionFilters ) { super( @@ -71,7 +72,7 @@ public TransportTopQueriesAction( ThreadPool.Names.GENERIC, TopQueries.class ); - this.topQueriesByLatencyService = topQueriesByLatencyService; + this.queryInsightsService = queryInsightsService; } @Override @@ -80,12 +81,13 @@ protected TopQueriesResponse newResponse( List responses, List failures ) { - if (topQueriesRequest.getMetricType() == TopQueriesRequest.Metric.LATENCY) { + if (topQueriesRequest.getMetricType() == MetricType.LATENCY) { return new TopQueriesResponse( clusterService.getClusterName(), responses, failures, - clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE) + clusterService.getClusterSettings().get(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE), + MetricType.LATENCY ); } else { throw new OpenSearchException(String.format(Locale.ROOT, "invalid metric type %s", topQueriesRequest.getMetricType())); @@ -105,8 +107,8 @@ protected TopQueries newNodeResponse(StreamInput in) throws IOException { @Override protected TopQueries nodeOperation(NodeRequest nodeRequest) { TopQueriesRequest request = nodeRequest.request; - if (request.getMetricType() == TopQueriesRequest.Metric.LATENCY) { - return new TopQueries(clusterService.localNode(), topQueriesByLatencyService.getQueryData()); + if (request.getMetricType() == MetricType.LATENCY) { + return new TopQueries(clusterService.localNode(), queryInsightsService.getTopNRecords(MetricType.LATENCY, true)); } else { throw new OpenSearchException(String.format(Locale.ROOT, "invalid metric type %s", request.getMetricType())); } diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/listener/SearchQueryLatencyListenerTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/listener/QueryInsightsListenerTests.java similarity index 57% rename from plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/listener/SearchQueryLatencyListenerTests.java rename to plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/listener/QueryInsightsListenerTests.java index 5228e0054c440..a6368bb0e180f 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/listener/SearchQueryLatencyListenerTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/listener/QueryInsightsListenerTests.java @@ -15,12 +15,14 @@ import org.opensearch.cluster.service.ClusterService; import org.opensearch.common.settings.ClusterSettings; import org.opensearch.common.settings.Settings; -import org.opensearch.plugin.insights.core.service.TopQueriesByLatencyService; +import org.opensearch.plugin.insights.core.service.QueryInsightsService; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.plugin.insights.settings.QueryInsightsSettings; import org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.opensearch.search.aggregations.support.ValueType; import org.opensearch.search.builder.SearchSourceBuilder; import org.opensearch.test.OpenSearchTestCase; +import org.junit.Before; import java.util.ArrayList; import java.util.HashMap; @@ -29,38 +31,35 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Phaser; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.anyMap; -import static org.mockito.Mockito.eq; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * Unit Tests for {@link SearchQueryLatencyListener}. + * Unit Tests for {@link QueryInsightsListener}. */ -public class SearchQueryLatencyListenerTests extends OpenSearchTestCase { - - public void testOnRequestEnd() { - final SearchRequestContext searchRequestContext = mock(SearchRequestContext.class); - final SearchPhaseContext searchPhaseContext = mock(SearchPhaseContext.class); - final SearchRequest searchRequest = mock(SearchRequest.class); - final TopQueriesByLatencyService topQueriesByLatencyService = mock(TopQueriesByLatencyService.class); - +public class QueryInsightsListenerTests extends OpenSearchTestCase { + private final SearchRequestContext searchRequestContext = mock(SearchRequestContext.class); + private final SearchPhaseContext searchPhaseContext = mock(SearchPhaseContext.class); + private final SearchRequest searchRequest = mock(SearchRequest.class); + private final QueryInsightsService queryInsightsService = mock(QueryInsightsService.class); + private ClusterService clusterService; + + @Before + public void setup() { Settings.Builder settingsBuilder = Settings.builder(); Settings settings = settingsBuilder.build(); ClusterSettings clusterSettings = new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED); clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE); clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER); - - ClusterService clusterService = new ClusterService(settings, clusterSettings, null); + clusterService = new ClusterService(settings, clusterSettings, null); + when(queryInsightsService.isCollectionEnabled(MetricType.LATENCY)).thenReturn(true); + } + public void testOnRequestEnd() { Long timestamp = System.currentTimeMillis() - 100L; SearchType searchType = SearchType.QUERY_THEN_FETCH; @@ -77,7 +76,7 @@ public void testOnRequestEnd() { int numberOfShards = 10; - SearchQueryLatencyListener searchQueryLatencyListener = new SearchQueryLatencyListener(clusterService, topQueriesByLatencyService); + QueryInsightsListener queryInsightsListener = new QueryInsightsListener(clusterService, queryInsightsService); when(searchRequest.getOrCreateAbsoluteStartMillis()).thenReturn(timestamp); when(searchRequest.searchType()).thenReturn(searchType); @@ -87,39 +86,12 @@ public void testOnRequestEnd() { when(searchPhaseContext.getRequest()).thenReturn(searchRequest); when(searchPhaseContext.getNumShards()).thenReturn(numberOfShards); - searchQueryLatencyListener.onRequestEnd(searchPhaseContext, searchRequestContext); - - verify(topQueriesByLatencyService, times(1)).ingestQueryData( - eq(timestamp), - eq(searchType), - eq(searchSourceBuilder.toString()), - eq(numberOfShards), - eq(indices), - anyMap(), - eq(phaseLatencyMap), - anyLong() - ); + queryInsightsListener.onRequestEnd(searchPhaseContext, searchRequestContext); + + verify(queryInsightsService, times(1)).addRecord(any()); } public void testConcurrentOnRequestEnd() throws InterruptedException { - final SearchRequestContext searchRequestContext = mock(SearchRequestContext.class); - final SearchPhaseContext searchPhaseContext = mock(SearchPhaseContext.class); - final SearchRequest searchRequest = mock(SearchRequest.class); - final TopQueriesByLatencyService topQueriesByLatencyService = mock(TopQueriesByLatencyService.class); - - Settings.Builder settingsBuilder = Settings.builder(); - Settings settings = settingsBuilder.build(); - ClusterSettings clusterSettings = new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER); - - ClusterService clusterService = new ClusterService(settings, clusterSettings, null); - Long timestamp = System.currentTimeMillis() - 100L; SearchType searchType = SearchType.QUERY_THEN_FETCH; @@ -136,7 +108,7 @@ public void testConcurrentOnRequestEnd() throws InterruptedException { int numberOfShards = 10; - final List searchListenersList = new ArrayList<>(); + final List searchListenersList = new ArrayList<>(); when(searchRequest.getOrCreateAbsoluteStartMillis()).thenReturn(timestamp); when(searchRequest.searchType()).thenReturn(searchType); @@ -152,14 +124,14 @@ public void testConcurrentOnRequestEnd() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(numRequests); for (int i = 0; i < numRequests; i++) { - searchListenersList.add(new SearchQueryLatencyListener(clusterService, topQueriesByLatencyService)); + searchListenersList.add(new QueryInsightsListener(clusterService, queryInsightsService)); } for (int i = 0; i < numRequests; i++) { int finalI = i; threads[i] = new Thread(() -> { phaser.arriveAndAwaitAdvance(); - SearchQueryLatencyListener thisListener = searchListenersList.get(finalI); + QueryInsightsListener thisListener = searchListenersList.get(finalI); thisListener.onRequestEnd(searchPhaseContext, searchRequestContext); countDownLatch.countDown(); }); @@ -168,15 +140,19 @@ public void testConcurrentOnRequestEnd() throws InterruptedException { phaser.arriveAndAwaitAdvance(); countDownLatch.await(); - verify(topQueriesByLatencyService, times(numRequests)).ingestQueryData( - eq(timestamp), - eq(searchType), - eq(searchSourceBuilder.toString()), - eq(numberOfShards), - eq(indices), - anyMap(), - eq(phaseLatencyMap), - anyLong() - ); + verify(queryInsightsService, times(numRequests)).addRecord(any()); + } + + public void testSetEnabled() { + when(queryInsightsService.isCollectionEnabled(MetricType.LATENCY)).thenReturn(true); + QueryInsightsListener queryInsightsListener = new QueryInsightsListener(clusterService, queryInsightsService); + queryInsightsListener.setEnabled(MetricType.LATENCY, true); + assertTrue(queryInsightsListener.isEnabled()); + + when(queryInsightsService.isCollectionEnabled(MetricType.LATENCY)).thenReturn(false); + when(queryInsightsService.isCollectionEnabled(MetricType.CPU)).thenReturn(false); + when(queryInsightsService.isCollectionEnabled(MetricType.JVM)).thenReturn(false); + queryInsightsListener.setEnabled(MetricType.LATENCY, false); + assertFalse(queryInsightsListener.isEnabled()); } } diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/TopQueriesByLatencyServiceTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/TopQueriesByLatencyServiceTests.java deleted file mode 100644 index 4ccb04e618f1a..0000000000000 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/TopQueriesByLatencyServiceTests.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -package org.opensearch.plugin.insights.core.service; - -import org.opensearch.client.Client; -import org.opensearch.cluster.coordination.DeterministicTaskQueue; -import org.opensearch.cluster.service.ClusterService; -import org.opensearch.common.settings.ClusterSettings; -import org.opensearch.common.settings.Settings; -import org.opensearch.common.unit.TimeValue; -import org.opensearch.node.Node; -import org.opensearch.plugin.insights.QueryInsightsTestUtils; -import org.opensearch.plugin.insights.core.exporter.QueryInsightsExporterType; -import org.opensearch.plugin.insights.core.exporter.QueryInsightsLocalIndexExporter; -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; -import org.opensearch.plugin.insights.settings.QueryInsightsSettings; -import org.opensearch.test.OpenSearchTestCase; -import org.opensearch.threadpool.ThreadPool; -import org.junit.After; -import org.junit.Before; - -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.mockito.Mockito.mock; - -/** - * Unit Tests for {@link TopQueriesByLatencyService}. - */ -public class TopQueriesByLatencyServiceTests extends OpenSearchTestCase { - - private DeterministicTaskQueue deterministicTaskQueue; - private ThreadPool threadPool; - private TopQueriesByLatencyService topQueriesByLatencyService; - - @Before - public void setup() { - final Client client = mock(Client.class); - final Settings settings = Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "top n queries tests").build(); - deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); - threadPool = deterministicTaskQueue.getThreadPool(); - ClusterSettings clusterSettings = new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER); - ClusterService clusterService = new ClusterService(settings, clusterSettings, threadPool); - topQueriesByLatencyService = new TopQueriesByLatencyService(threadPool, clusterService, client); - topQueriesByLatencyService.setEnableCollect(true); - topQueriesByLatencyService.setTopNSize(Integer.MAX_VALUE); - topQueriesByLatencyService.setWindowSize(new TimeValue(Long.MAX_VALUE)); - } - - @After - public void shutdown() { - topQueriesByLatencyService.stop(); - } - - public void testIngestQueryDataWithLargeWindow() { - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); - for (SearchQueryLatencyRecord record : records) { - topQueriesByLatencyService.ingestQueryData( - record.getTimestamp(), - record.getSearchType(), - record.getSource(), - record.getTotalShards(), - record.getIndices(), - record.getPropertyMap(), - record.getPhaseLatencyMap(), - record.getValue() - ); - } - runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); - assertTrue(QueryInsightsTestUtils.checkRecordsEqualsWithoutOrder(topQueriesByLatencyService.getQueryData(), records)); - } - - public void testConcurrentIngestQueryDataWithLargeWindow() { - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); - - int numRequests = records.size(); - for (int i = 0; i < numRequests; i++) { - int finalI = i; - threadPool.schedule(() -> { - topQueriesByLatencyService.ingestQueryData( - records.get(finalI).getTimestamp(), - records.get(finalI).getSearchType(), - records.get(finalI).getSource(), - records.get(finalI).getTotalShards(), - records.get(finalI).getIndices(), - records.get(finalI).getPropertyMap(), - records.get(finalI).getPhaseLatencyMap(), - records.get(finalI).getValue() - ); - }, TimeValue.ZERO, ThreadPool.Names.GENERIC); - } - runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); - assertTrue(QueryInsightsTestUtils.checkRecordsEqualsWithoutOrder(topQueriesByLatencyService.getQueryData(), records)); - } - - public void testSmallWindowClearOutdatedData() { - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); - topQueriesByLatencyService.setWindowSize(new TimeValue(-1)); - - for (SearchQueryLatencyRecord record : records) { - topQueriesByLatencyService.ingestQueryData( - record.getTimestamp(), - record.getSearchType(), - record.getSource(), - record.getTotalShards(), - record.getIndices(), - record.getPropertyMap(), - record.getPhaseLatencyMap(), - record.getValue() - ); - } - runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); - assertEquals(0, topQueriesByLatencyService.getQueryData().size()); - } - - public void testSmallNSize() { - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); - topQueriesByLatencyService.setTopNSize(1); - - for (SearchQueryLatencyRecord record : records) { - topQueriesByLatencyService.ingestQueryData( - record.getTimestamp(), - record.getSearchType(), - record.getSource(), - record.getTotalShards(), - record.getIndices(), - record.getPropertyMap(), - record.getPhaseLatencyMap(), - record.getValue() - ); - } - runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); - assertEquals(1, topQueriesByLatencyService.getQueryData().size()); - } - - public void testIngestQueryDataWithInvalidData() { - final SearchQueryLatencyRecord record = QueryInsightsTestUtils.generateQueryInsightRecords(1).get(0); - topQueriesByLatencyService.ingestQueryData( - -1L, - record.getSearchType(), - record.getSource(), - record.getTotalShards(), - record.getIndices(), - record.getPropertyMap(), - record.getPhaseLatencyMap(), - record.getValue() - ); - assertEquals(0, topQueriesByLatencyService.getQueryData().size()); - - topQueriesByLatencyService.ingestQueryData( - record.getTimestamp(), - record.getSearchType(), - record.getSource(), - -1, - record.getIndices(), - record.getPropertyMap(), - record.getPhaseLatencyMap(), - record.getValue() - ); - assertEquals(0, topQueriesByLatencyService.getQueryData().size()); - - } - - public void testValidateTopNSize() { - assertThrows( - IllegalArgumentException.class, - () -> { topQueriesByLatencyService.validateTopNSize(QueryInsightsSettings.MAX_N_SIZE + 1); } - ); - } - - public void testValidateWindowSize() { - assertThrows(IllegalArgumentException.class, () -> { - topQueriesByLatencyService.validateWindowSize( - new TimeValue(QueryInsightsSettings.MAX_WINDOW_SIZE.getSeconds() + 1, TimeUnit.SECONDS) - ); - }); - } - - public void testValidateInterval() { - assertThrows(IllegalArgumentException.class, () -> { - topQueriesByLatencyService.validateExportInterval( - new TimeValue(QueryInsightsSettings.MIN_EXPORT_INTERVAL.getSeconds() - 1, TimeUnit.SECONDS) - ); - }); - } - - public void testSetExporterTypeWhenDisabled() { - topQueriesByLatencyService.setExporterEnabled(false); - topQueriesByLatencyService.setExporterType(QueryInsightsExporterType.LOCAL_INDEX); - assertNull(topQueriesByLatencyService.exporter); - } - - public void testSetExporterTypeWhenEnabled() { - topQueriesByLatencyService.setExporterEnabled(true); - topQueriesByLatencyService.setExporterType(QueryInsightsExporterType.LOCAL_INDEX); - assertEquals(QueryInsightsLocalIndexExporter.class, topQueriesByLatencyService.exporter.getClass()); - } - - public void testSetExporterEnabled() { - topQueriesByLatencyService.setExporterEnabled(true); - assertEquals(QueryInsightsLocalIndexExporter.class, topQueriesByLatencyService.exporter.getClass()); - } - - public void testSetExporterDisabled() { - topQueriesByLatencyService.setExporterEnabled(false); - assertNull(topQueriesByLatencyService.exporter); - } - - public void testChangeIdentifierWhenEnabled() { - topQueriesByLatencyService.setExporterEnabled(true); - topQueriesByLatencyService.setExporterIdentifier("changed"); - assertEquals("changed", topQueriesByLatencyService.exporter.getIdentifier()); - } - - public void testChangeIdentifierWhenDisabled() { - topQueriesByLatencyService.setExporterEnabled(false); - topQueriesByLatencyService.setExporterIdentifier("changed"); - assertNull(topQueriesByLatencyService.exporter); - } - - public void testChangeIntervalWhenEnabled() { - topQueriesByLatencyService.setExporterEnabled(true); - TimeValue newInterval = TimeValue.timeValueMillis(randomLongBetween(1, 9999)); - topQueriesByLatencyService.setExportInterval(newInterval); - assertEquals(newInterval, topQueriesByLatencyService.getExportInterval()); - } - - public void testChangeIntervalWhenDisabled() { - topQueriesByLatencyService.setExporterEnabled(false); - TimeValue newInterval = TimeValue.timeValueMillis(randomLongBetween(1, 9999)); - topQueriesByLatencyService.setExportInterval(newInterval); - assertNull(topQueriesByLatencyService.exporter); - } - - private static void runUntilTimeoutOrFinish(DeterministicTaskQueue deterministicTaskQueue, long duration) { - final long endTime = deterministicTaskQueue.getCurrentTimeMillis() + duration; - while (deterministicTaskQueue.getCurrentTimeMillis() < endTime - && (deterministicTaskQueue.hasRunnableTasks() || deterministicTaskQueue.hasDeferredTasks())) { - if (deterministicTaskQueue.hasDeferredTasks() && randomBoolean()) { - deterministicTaskQueue.advanceTime(); - } else if (deterministicTaskQueue.hasRunnableTasks()) { - deterministicTaskQueue.runRandomTask(); - } - } - } -} diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequestTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequestTests.java index 07e98970fb628..619fd4b33a3dc 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequestTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesRequestTests.java @@ -10,6 +10,7 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.test.OpenSearchTestCase; /** @@ -21,8 +22,7 @@ public class TopQueriesRequestTests extends OpenSearchTestCase { * Check that we can set the metric type */ public void testSetMetricType() throws Exception { - TopQueriesRequest request = new TopQueriesRequest(randomAlphaOfLength(5)); - request.setMetricType(randomFrom(TopQueriesRequest.Metric.allMetrics())); + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY, randomAlphaOfLength(5)); TopQueriesRequest deserializedRequest = roundTripRequest(request); assertEquals(request.getMetricType(), deserializedRequest.getMetricType()); } diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponseTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponseTests.java index 11063cbedd248..eeee50d3da703 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponseTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesResponseTests.java @@ -10,11 +10,18 @@ import org.opensearch.cluster.ClusterName; import org.opensearch.common.io.stream.BytesStreamOutput; +import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.StreamInput; +import org.opensearch.core.xcontent.MediaTypeRegistry; +import org.opensearch.core.xcontent.ToXContent; +import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.plugin.insights.QueryInsightsTestUtils; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.test.OpenSearchTestCase; +import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -25,14 +32,29 @@ public class TopQueriesResponseTests extends OpenSearchTestCase { /** * Check serialization and deserialization */ - public void testToXContent() throws Exception { - TopQueries topQueries = QueryInsightsTestUtils.createTopQueries(); + public void testSerialize() throws Exception { + TopQueries topQueries = QueryInsightsTestUtils.createRandomTopQueries(); ClusterName clusterName = new ClusterName("test-cluster"); - TopQueriesResponse response = new TopQueriesResponse(clusterName, List.of(topQueries), new ArrayList<>(), 10); + TopQueriesResponse response = new TopQueriesResponse(clusterName, List.of(topQueries), new ArrayList<>(), 10, MetricType.LATENCY); TopQueriesResponse deserializedResponse = roundTripResponse(response); assertEquals(response.toString(), deserializedResponse.toString()); } + public void testToXContent() throws IOException { + char[] expectedXcontent = + "{\"top_queries\":[{\"timestamp\":1706574180000,\"node_id\":\"node_for_top_queries_test\",\"search_type\":\"query_then_fetch\",\"latency\":1}]}" + .toCharArray(); + TopQueries topQueries = QueryInsightsTestUtils.createFixedTopQueries(); + ClusterName clusterName = new ClusterName("test-cluster"); + TopQueriesResponse response = new TopQueriesResponse(clusterName, List.of(topQueries), new ArrayList<>(), 10, MetricType.LATENCY); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); + char[] xContent = BytesReference.bytes(response.toXContent(builder, ToXContent.EMPTY_PARAMS)).utf8ToString().toCharArray(); + Arrays.sort(expectedXcontent); + Arrays.sort(xContent); + + assertEquals(Arrays.hashCode(expectedXcontent), Arrays.hashCode(xContent)); + } + /** * Serialize and deserialize a TopQueriesResponse. * @param response A response to serialize. diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesTests.java index 4d0d641cf1a8d..7db08b53ad1df 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/action/top_queries/TopQueriesTests.java @@ -21,22 +21,15 @@ public class TopQueriesTests extends OpenSearchTestCase { public void testTopQueries() throws IOException { - TopQueries topQueries = QueryInsightsTestUtils.createTopQueries(); + TopQueries topQueries = QueryInsightsTestUtils.createRandomTopQueries(); try (BytesStreamOutput out = new BytesStreamOutput()) { topQueries.writeTo(out); try (StreamInput in = out.bytes().streamInput()) { TopQueries readTopQueries = new TopQueries(in); - assertExpected(topQueries, readTopQueries); + assertTrue( + QueryInsightsTestUtils.checkRecordsEquals(topQueries.getTopQueriesRecord(), readTopQueries.getTopQueriesRecord()) + ); } } } - - /** - * checks all properties that are expected to be unchanged. - */ - private void assertExpected(TopQueries topQueries, TopQueries readTopQueries) throws IOException { - for (int i = 0; i < topQueries.getLatencyRecords().size(); i++) { - QueryInsightsTestUtils.compareJson(topQueries.getLatencyRecords().get(i), readTopQueries.getLatencyRecords().get(i)); - } - } } diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecordTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecordTests.java deleted file mode 100644 index e704e768a43e6..0000000000000 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecordTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -package org.opensearch.plugin.insights.rules.model; - -import org.opensearch.common.io.stream.BytesStreamOutput; -import org.opensearch.core.common.io.stream.StreamInput; -import org.opensearch.plugin.insights.QueryInsightsTestUtils; -import org.opensearch.test.OpenSearchTestCase; - -import java.util.ArrayList; -import java.util.List; - -/** - * Granular tests for the {@link SearchQueryLatencyRecord} class. - */ -public class SearchQueryLatencyRecordTests extends OpenSearchTestCase { - - /** - * Check that if the serialization, deserialization and equals functions are working as expected - */ - public void testSerializationAndEquals() throws Exception { - List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); - List copiedRecords = new ArrayList<>(); - for (SearchQueryLatencyRecord record : records) { - copiedRecords.add(roundTripRecord(record)); - } - assertTrue(QueryInsightsTestUtils.checkRecordsEquals(records, copiedRecords)); - - } - - /** - * Serialize and deserialize a SearchQueryLatencyRecord. - * @param record A SearchQueryLatencyRecord to serialize. - * @return The deserialized, "round-tripped" record. - */ - private static SearchQueryLatencyRecord roundTripRecord(SearchQueryLatencyRecord record) throws Exception { - try (BytesStreamOutput out = new BytesStreamOutput()) { - record.writeTo(out); - try (StreamInput in = out.bytes().streamInput()) { - return new SearchQueryLatencyRecord(in); - } - } - } -} diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesActionTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesActionTests.java index 96b8ec63b5a47..a5f36b6e8cce0 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesActionTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/transport/top_queries/TransportTopQueriesActionTests.java @@ -12,9 +12,10 @@ import org.opensearch.cluster.service.ClusterService; import org.opensearch.common.settings.ClusterSettings; import org.opensearch.common.settings.Settings; -import org.opensearch.plugin.insights.core.service.TopQueriesByLatencyService; +import org.opensearch.plugin.insights.core.service.QueryInsightsService; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesRequest; import org.opensearch.plugin.insights.rules.action.top_queries.TopQueriesResponse; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.plugin.insights.settings.QueryInsightsSettings; import org.opensearch.test.OpenSearchTestCase; import org.opensearch.threadpool.ThreadPool; @@ -34,7 +35,7 @@ public class TransportTopQueriesActionTests extends OpenSearchTestCase { private final ClusterSettings clusterSettings = new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); private final ClusterService clusterService = new ClusterService(settings, clusterSettings, threadPool); private final TransportService transportService = mock(TransportService.class); - private final TopQueriesByLatencyService topQueriesByLatencyService = mock(TopQueriesByLatencyService.class); + private final QueryInsightsService topQueriesByLatencyService = mock(QueryInsightsService.class); private final ActionFilters actionFilters = mock(ActionFilters.class); private final TransportTopQueriesAction transportTopQueriesAction = new TransportTopQueriesAction( threadPool, @@ -56,14 +57,14 @@ public DummyParentAction( ThreadPool threadPool, ClusterService clusterService, TransportService transportService, - TopQueriesByLatencyService topQueriesByLatencyService, + QueryInsightsService topQueriesByLatencyService, ActionFilters actionFilters ) { super(threadPool, clusterService, transportService, topQueriesByLatencyService, actionFilters); } public TopQueriesResponse createNewResponse() { - TopQueriesRequest request = new TopQueriesRequest(); + TopQueriesRequest request = new TopQueriesRequest(MetricType.LATENCY); return newResponse(request, List.of(), List.of()); } } @@ -73,10 +74,6 @@ public void setup() { clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED); clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE); clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_TYPE); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL); - clusterSettings.registerSetting(QueryInsightsSettings.TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER); } public void testNewResponse() {