From 67457710ad17d360c0750e16ae16f4dc9c3780d5 Mon Sep 17 00:00:00 2001 From: Chenyang Ji Date: Mon, 29 Jan 2024 19:06:00 -0800 Subject: [PATCH] Refactor record and service to make them generic Signed-off-by: Chenyang Ji --- CHANGELOG.md | 2 +- gradle/missing-javadoc.gradle | 1 - .../plugin/insights/QueryInsightsPlugin.java | 32 +- .../core/exporter/QueryInsightsExporter.java | 43 --- .../exporter/QueryInsightsExporterType.java | 35 -- .../QueryInsightsLocalIndexExporter.java | 187 ---------- .../insights/core/exporter/package-info.java | 12 - .../core/service/QueryInsightsService.java | 320 +++++++++++------- .../insights/rules/model/Attribute.java | 70 ++++ .../insights/rules/model/Measurement.java | 100 ++++++ .../insights/rules/model/MetricType.java | 78 +++++ .../rules/model/SearchQueryLatencyRecord.java | 111 ------ .../rules/model/SearchQueryRecord.java | 281 ++++++--------- .../settings/QueryInsightsSettings.java | 68 +--- .../mappings/top_n_queries_record.json | 40 --- .../insights/QueryInsightsPluginTests.java | 18 +- .../insights/QueryInsightsTestUtils.java | 104 +++--- .../exporter/QueryInsightsExporterTests.java | 35 -- .../QueryInsightsLocalIndexExporterTests.java | 256 -------------- .../service/QueryInsightsServiceTests.java | 250 +++++++++----- .../model/SearchQueryLatencyRecordTests.java | 50 --- .../rules/model/SearchQueryRecordTests.java | 71 ++++ 22 files changed, 903 insertions(+), 1261 deletions(-) delete mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporter.java delete mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterType.java delete mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporter.java delete mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/package-info.java create mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Attribute.java create mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Measurement.java create mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/MetricType.java delete mode 100644 plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecord.java delete mode 100644 plugins/query-insights/src/main/resources/mappings/top_n_queries_record.json delete mode 100644 plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterTests.java delete mode 100644 plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporterTests.java delete mode 100644 plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecordTests.java create mode 100644 plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecordTests.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 999218a869e87..325ff511de513 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -218,7 +218,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Extract cluster management for integration tests into JUnit test rule out of OpenSearchIntegTestCase ([#11877](https://github.com/opensearch-project/OpenSearch/pull/11877)), ([#12000](https://github.com/opensearch-project/OpenSearch/pull/12000)) - 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 Plugin Implementation ([#11903](https://github.com/opensearch-project/OpenSearch/pull/11903)) +- [Query Insights] Implement Query Insights plugin to support collecting and aggregating query level data and insights ([#11903](https://github.com/opensearch-project/OpenSearch/pull/11903)) ### Deprecated diff --git a/gradle/missing-javadoc.gradle b/gradle/missing-javadoc.gradle index d3fb9f82c3715..e9a6d798b8323 100644 --- a/gradle/missing-javadoc.gradle +++ b/gradle/missing-javadoc.gradle @@ -141,7 +141,6 @@ configure([ project(":plugins:mapper-annotated-text"), project(":plugins:mapper-murmur3"), project(":plugins:mapper-size"), - project(":plugins:query-insights"), project(":plugins:repository-azure"), project(":plugins:repository-gcs"), project(":plugins:repository-hdfs"), diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/QueryInsightsPlugin.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/QueryInsightsPlugin.java index 7000efb5bd9d2..e4fcc33879997 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/QueryInsightsPlugin.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/QueryInsightsPlugin.java @@ -18,20 +18,27 @@ import org.opensearch.common.settings.Setting; import org.opensearch.common.settings.Settings; import org.opensearch.common.settings.SettingsFilter; +import org.opensearch.common.unit.TimeValue; +import org.opensearch.common.util.concurrent.OpenSearchExecutors; import org.opensearch.core.action.ActionResponse; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.env.Environment; import org.opensearch.env.NodeEnvironment; +import org.opensearch.plugin.insights.core.service.QueryInsightsService; +import org.opensearch.plugin.insights.settings.QueryInsightsSettings; import org.opensearch.plugins.ActionPlugin; import org.opensearch.plugins.Plugin; import org.opensearch.repositories.RepositoriesService; import org.opensearch.rest.RestController; import org.opensearch.rest.RestHandler; import org.opensearch.script.ScriptService; +import org.opensearch.threadpool.ExecutorBuilder; +import org.opensearch.threadpool.ScalingExecutorBuilder; import org.opensearch.threadpool.ThreadPool; import org.opensearch.watcher.ResourceWatcherService; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Supplier; @@ -59,7 +66,23 @@ public Collection createComponents( IndexNameExpressionResolver indexNameExpressionResolver, Supplier repositoriesServiceSupplier ) { - return List.of(); + // create top n queries service + QueryInsightsService queryInsightsService = new QueryInsightsService(threadPool); + return List.of(queryInsightsService); + } + + @Override + public List> getExecutorBuilders(Settings settings) { + List> executorBuilders = new ArrayList<>(); + executorBuilders.add( + new ScalingExecutorBuilder( + QueryInsightsSettings.QUERY_INSIGHTS_EXECUTOR, + 1, + (OpenSearchExecutors.allocatedProcessors(settings) + 1) / 2, + TimeValue.timeValueMinutes(5) + ) + ); + return executorBuilders; } @Override @@ -82,6 +105,11 @@ public List getRestHandlers( @Override public List> getSettings() { - return List.of(); + return List.of( + // Settings for top N queries + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED, + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE, + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE + ); } } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporter.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporter.java deleted file mode 100644 index 5f53dbb6e39db..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporter.java +++ /dev/null @@ -1,43 +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.exporter; - -import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; - -import java.util.List; - -/** - * Simple abstract class to export data collected by search query analyzers - *

- * Mainly for use within the Query Insight framework - * - * @opensearch.internal - */ -public abstract class QueryInsightsExporter> { - private final String identifier; - - QueryInsightsExporter(String identifier) { - this.identifier = identifier; - } - - /** - * Export the data with the exporter. - * - * @param records the data to export - */ - public abstract void export(List records) throws Exception; - - /** - * Get the identifier of this exporter - * @return identifier of this exporter - */ - public String getIdentifier() { - return identifier; - } -} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterType.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterType.java deleted file mode 100644 index 7c2a9b86fb642..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterType.java +++ /dev/null @@ -1,35 +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.exporter; - -import java.util.Locale; - -/** - * Types for the Query Insights Exporters - * - * @opensearch.internal - */ -public enum QueryInsightsExporterType { - /** local index exporter */ - LOCAL_INDEX; - - @Override - public String toString() { - return super.toString().toLowerCase(Locale.ROOT); - } - - /** - * Parse QueryInsightsExporterType from String - * @param type the String representation of the QueryInsightsExporterType - * @return QueryInsightsExporterType - */ - public static QueryInsightsExporterType parse(String type) { - return valueOf(type.toUpperCase(Locale.ROOT)); - } -} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporter.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporter.java deleted file mode 100644 index d6317971f1d52..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporter.java +++ /dev/null @@ -1,187 +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.exporter; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.opensearch.action.admin.indices.create.CreateIndexRequest; -import org.opensearch.action.admin.indices.create.CreateIndexResponse; -import org.opensearch.action.bulk.BulkRequest; -import org.opensearch.action.bulk.BulkResponse; -import org.opensearch.action.index.IndexRequest; -import org.opensearch.action.support.WriteRequest; -import org.opensearch.client.Client; -import org.opensearch.cluster.ClusterState; -import org.opensearch.cluster.service.ClusterService; -import org.opensearch.common.settings.Settings; -import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.core.action.ActionListener; -import org.opensearch.core.rest.RestStatus; -import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Locale; -import java.util.Objects; - -/** - * Class to export data collected by search query analyzers to a local OpenSearch index - *

- * Internal used within the Query Insight framework - * - * @opensearch.internal - */ -public class QueryInsightsLocalIndexExporter> extends QueryInsightsExporter { - private static final Logger log = LogManager.getLogger(QueryInsightsLocalIndexExporter.class); - private static final int INDEX_TIMEOUT = 60; - - private final ClusterService clusterService; - private final Client client; - - /** The mapping for the local index that holds the data */ - private final InputStream localIndexMapping; - - /** - * Create a QueryInsightsLocalIndexExporter Object - * @param clusterService The clusterService of the node - * @param client The OpenSearch Client to support index operations - * @param localIndexName The local index name to export the data to - * @param localIndexMapping The mapping for the local index - */ - public QueryInsightsLocalIndexExporter( - ClusterService clusterService, - Client client, - String localIndexName, - InputStream localIndexMapping - ) { - super(localIndexName); - this.clusterService = clusterService; - this.client = client; - this.localIndexMapping = localIndexMapping; - } - - /** - * Export the data to the predefined local OpenSearch Index - * - * @param records the data to export - * @throws IOException if an error occurs - */ - @Override - public void export(List records) throws IOException { - if (records.size() == 0) { - return; - } - boolean indexExists = checkAndInitLocalIndex(new ActionListener<>() { - @Override - public void onResponse(CreateIndexResponse response) { - if (response.isAcknowledged()) { - log.debug(String.format(Locale.ROOT, "successfully initialized local index %s for query insight.", getIdentifier())); - try { - bulkRecord(records); - } catch (IOException e) { - log.error(String.format(Locale.ROOT, "fail to ingest query insight data to local index, error: %s", e)); - } - } else { - log.error( - String.format(Locale.ROOT, "request to created local index %s for query insight not acknowledged.", getIdentifier()) - ); - } - } - - @Override - public void onFailure(Exception e) { - log.error(String.format(Locale.ROOT, "error creating local index for query insight: %s", e)); - } - }); - - if (indexExists) { - bulkRecord(records); - } - } - - /** - * Util function to check if a local OpenSearch Index exists - * - * @return boolean - */ - private boolean checkIfIndexExists() { - ClusterState clusterState = clusterService.state(); - return clusterState.getRoutingTable().hasIndex(this.getIdentifier()); - } - - /** - * Check and initialize the local OpenSearch Index for the exporter - * - * @param listener the listener to be notified upon completion - * @return boolean to represent if the index has already been created before calling this function - * @throws IOException if an error occurs - */ - private synchronized boolean checkAndInitLocalIndex(ActionListener listener) throws IOException { - if (!checkIfIndexExists()) { - CreateIndexRequest createIndexRequest = new CreateIndexRequest(this.getIdentifier()).mapping(getIndexMappings()) - .settings(Settings.builder().put("index.hidden", false).build()); - client.admin().indices().create(createIndexRequest, listener); - return false; - } else { - return true; - } - } - - /** - * Get the index mapping of the local index - * - * @return String to represent the index mapping - * @throws IOException if an error occurs - */ - private String getIndexMappings() throws IOException { - return new String(Objects.requireNonNull(this.localIndexMapping).readAllBytes(), Charset.defaultCharset()); - } - - /** - * Bulk ingest the data into to the predefined local OpenSearch Index - * - * @param records the data to export - * @throws IOException if an error occurs - */ - private void bulkRecord(List records) throws IOException { - BulkRequest bulkRequest = new BulkRequest().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) - .timeout(TimeValue.timeValueSeconds(INDEX_TIMEOUT)); - for (T record : records) { - bulkRequest.add( - new IndexRequest(getIdentifier()).source(record.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)) - ); - } - client.bulk(bulkRequest, new ActionListener<>() { - @Override - public void onResponse(BulkResponse response) { - if (response.status().equals(RestStatus.CREATED) || response.status().equals(RestStatus.OK)) { - log.debug(String.format(Locale.ROOT, "successfully ingest data for %s! ", getIdentifier())); - } else { - log.error( - String.format( - Locale.ROOT, - "error when ingesting data for %s, error: %s", - getIdentifier(), - response.buildFailureMessage() - ) - ); - } - } - - @Override - public void onFailure(Exception e) { - log.error(String.format(Locale.ROOT, "failed to ingest data for %s, %s", getIdentifier(), e)); - } - }); - } -} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/package-info.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/package-info.java deleted file mode 100644 index 3ccbfc5c4cb24..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/exporter/package-info.java +++ /dev/null @@ -1,12 +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. - */ - -/** - * Exporters for Query Insights - */ -package org.opensearch.plugin.insights.core.exporter; diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/QueryInsightsService.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/QueryInsightsService.java index bf97707c7f3bd..4afb57e3a567f 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/QueryInsightsService.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/core/service/QueryInsightsService.java @@ -10,207 +10,291 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.opensearch.common.Nullable; import org.opensearch.common.inject.Inject; -import org.opensearch.common.lifecycle.AbstractLifecycleComponent; 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.rules.model.Measurement; +import org.opensearch.plugin.insights.rules.model.MetricType; import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; import org.opensearch.plugin.insights.settings.QueryInsightsSettings; -import org.opensearch.threadpool.Scheduler; import org.opensearch.threadpool.ThreadPool; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** - * Service responsible for gathering, analyzing, storing and exporting data related to - * search queries, based on certain dimensions. - * - * @param The type of record that stores in the service - * @param The type of Collection that holds the aggregated data - * @param The type of exporter that exports the aggregated and processed data + * Service responsible for gathering, analyzing, storing and exporting + * top N queries with high latency data for search queries * * @opensearch.internal */ -public abstract class QueryInsightsService, S extends Collection, E extends QueryInsightsExporter> - extends AbstractLifecycleComponent { +public class QueryInsightsService { private static final Logger log = LogManager.getLogger(QueryInsightsService.class); - /** enable insight data collection */ - private boolean enableCollect; - - /** enable insight data export */ - private boolean enableExport; - /** The internal thread-safe store that holds the query insight data */ - @Nullable - protected S store; + private static final TimeValue delay = TimeValue.ZERO; + /** + * The internal OpenSearch thread pool that execute async processing and exporting tasks + */ + private final ThreadPool threadPool; - /** The exporter that exports the query insight data to certain sink */ - @Nullable - protected E exporter; + /** + * enable insight data collection + */ + private final Map enableCollect = new HashMap<>(); - /** The export interval of this exporter, default to 1 day */ - protected TimeValue exportInterval = QueryInsightsSettings.MIN_EXPORT_INTERVAL; + private int topNSize = QueryInsightsSettings.DEFAULT_TOP_N_SIZE; - /** The internal OpenSearch thread pool that execute async processing and exporting tasks*/ - protected final ThreadPool threadPool; + private TimeValue windowSize = TimeValue.timeValueSeconds(QueryInsightsSettings.DEFAULT_WINDOW_SIZE); + /** + * The internal thread-safe store that holds the top n queries insight data, by different MetricType + */ + private final Map> topQueriesStores; /** - * Holds a reference to delayed operation {@link Scheduler.Cancellable} so it can be cancelled when - * the service closed concurrently. + * The internal store that holds historical top n queries insight data by different MetricType in the last window + */ + private final Map> topQueriesHistoryStores; + /** + * window start timestamp for each top queries collector */ - protected volatile Scheduler.Cancellable scheduledFuture; + private final Map topQueriesWindowStart = new HashMap<>(); /** - * Create the Query Insights Service object - * @param threadPool The OpenSearch thread pool to run async tasks - * @param store The in memory store to keep the Query Insights data - * @param exporter The optional {@link QueryInsightsExporter} to export the Query Insights data + * Create the TopQueriesByLatencyService Object + * + * @param threadPool The OpenSearch thread pool to run async tasks */ @Inject - public QueryInsightsService(ThreadPool threadPool, @Nullable S store, @Nullable E exporter) { + public QueryInsightsService(ThreadPool threadPool) { + topQueriesStores = new HashMap<>(); + topQueriesHistoryStores = new HashMap<>(); + for (MetricType metricType : MetricType.allMetricTypes()) { + topQueriesStores.put(metricType, new PriorityBlockingQueue<>(topNSize, (a, b) -> SearchQueryRecord.compare(a, b, metricType))); + topQueriesHistoryStores.put(metricType, new ArrayList<>()); + topQueriesWindowStart.put(metricType, -1L); + } this.threadPool = threadPool; - this.store = store; - this.exporter = exporter; } /** - * Ingest one record to the query insight store + * Ingest the query data into local stores * * @param record the record to ingest */ - protected void ingestQueryData(R record) { - if (enableCollect && this.store != null) { - this.store.add(record); + public void addRecord(SearchQueryRecord record) { + Map> measurements = record.getMeasurements(); + for (MetricType metricType : measurements.keySet()) { + if (!topQueriesStores.containsKey(metricType)) { + continue; + } + // add the record to corresponding priority queues to calculate top n queries insights + PriorityBlockingQueue store = topQueriesStores.get(metricType); + this.threadPool.schedule(() -> { + checkAndResetWindow(metricType, record.getTimestamp()); + if (record.getTimestamp() > topQueriesWindowStart.get(metricType)) { + store.add(record); + // remove top elements for fix sizing priority queue + if (store.size() > this.getTopNSize()) { + store.poll(); + } + } + }, delay, QueryInsightsSettings.QUERY_INSIGHTS_EXECUTOR); + } + } + + private synchronized void checkAndResetWindow(MetricType metricType, Long timestamp) { + Long windowStart = calculateWindowStart(timestamp); + // reset window if the current window is outdated + if (topQueriesWindowStart.get(metricType) < windowStart) { + // rotate the current window to history store only if the data belongs to the last window + if (topQueriesWindowStart.get(metricType) == windowStart - windowSize.getMillis()) { + topQueriesHistoryStores.put(metricType, new ArrayList<>(topQueriesStores.get(metricType))); + } else { + topQueriesHistoryStores.get(metricType).clear(); + } + topQueriesStores.get(metricType).clear(); + topQueriesWindowStart.put(metricType, windowStart); } } /** - * Get all records that are in the query insight store, + * Get all top queries records that are in the current query insight store, based on the input MetricType + * Optionally include top N records from the last window. + * * By default, return the records in sorted order. * + * @param metricType {@link MetricType} + * @param includeLastWindow if the top N queries from the last window should be included * @return List of the records that are in the query insight store * @throws IllegalArgumentException if query insight is disabled in the cluster */ - public List getQueryData() throws IllegalArgumentException { - if (!enableCollect) { - throw new IllegalArgumentException("Cannot get query data when query insight feature is not enabled."); + public List getTopNRecords(MetricType metricType, boolean includeLastWindow) throws IllegalArgumentException { + if (!enableCollect.containsKey(metricType) || !enableCollect.get(metricType)) { + throw new IllegalArgumentException( + String.format( + Locale.ROOT, + "Cannot get query data when query insight feature is not enabled for MetricType [%s].", + metricType + ) + ); } - clearOutdatedData(); - List queries = new ArrayList<>(store); - queries.sort(Collections.reverseOrder()); - return queries; + checkAndResetWindow(metricType, System.currentTimeMillis()); + List queries = new ArrayList<>(topQueriesStores.get(metricType)); + if (includeLastWindow) { + queries.addAll(topQueriesHistoryStores.get(metricType)); + } + return Stream.of(queries) + .flatMap(Collection::stream) + .sorted((a, b) -> SearchQueryRecord.compare(a, b, metricType) * -1) + .collect(Collectors.toList()); } /** - * Clear all outdated data in the store - */ - public abstract void clearOutdatedData(); - - /** - * Reset the exporter with new config + * Set flag to enable or disable Query Insights data collection * - * 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 + * @param metricType {@link MetricType} + * @param enable Flag to enable or disable Query Insights data collection */ - public abstract void resetExporter(boolean enabled, QueryInsightsExporterType type, String identifier); - - /** - * Clear all data in the store - */ - public void clearAllData() { - store.clear(); + public void enableCollection(MetricType metricType, boolean enable) { + this.enableCollect.put(metricType, enable); + // set topQueriesWindowStart to enable top n queries collection + if (enable) { + topQueriesWindowStart.put(metricType, calculateWindowStart(System.currentTimeMillis())); + } } /** - * Set flag to enable or disable Query Insights data collection - * @param enableCollect Flag to enable or disable Query Insights data collection + * Get if the Query Insights data collection is enabled for a MetricType + * + * @param metricType {@link MetricType} + * @return if the Query Insights data collection is enabled */ - public void setEnableCollect(boolean enableCollect) { - this.enableCollect = enableCollect; + public boolean isCollectionEnabled(MetricType metricType) { + return this.enableCollect.containsKey(metricType) && this.enableCollect.get(metricType); } /** - * Get if the Query Insights data collection is enabled - * @return if the Query Insights data collection is enabled + * Set the top N size for TopQueriesByLatencyService service. + * + * @param size the top N size to set */ - public boolean getEnableCollect() { - return this.enableCollect; + public void setTopNSize(int size) { + this.topNSize = size; } /** - * Set flag to enable or disable Query Insights data export - * @param enableExport + * Validate the top N size based on the internal constrains + * + * @param size the wanted top N size */ - public void setEnableExport(boolean enableExport) { - this.enableExport = enableExport; + 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 if the Query Insights data export is enabled - * @return if the Query Insights data export is enabled + * Get the top N size set for TopQueriesByLatencyService + * + * @return the top N size */ - public boolean getEnableExport() { - return this.enableExport; + public int getTopNSize() { + return this.topNSize; } /** - * Start the Query Insight Service. + * Set the window size for TopQueriesByLatencyService + * + * @param windowSize window size to set */ - @Override - protected void doStart() { - if (exporter != null && getEnableExport()) { - scheduledFuture = threadPool.scheduleWithFixedDelay(this::doExport, exportInterval, ThreadPool.Names.GENERIC); + public void setWindowSize(TimeValue windowSize) { + this.windowSize = windowSize; + for (MetricType metricType : MetricType.allMetricTypes()) { + topQueriesWindowStart.put(metricType, -1L); } } /** - * Stop the Query Insight Service + * Validate if the window size is valid, based on internal constrains. + * + * @param windowSize the window size to validate */ - @Override - protected void doStop() { - if (scheduledFuture != null) { - scheduledFuture.cancel(); - if (exporter != null && getEnableExport()) { - doExport(); - } + public void validateWindowSize(TimeValue windowSize) { + if (windowSize.compareTo(QueryInsightsSettings.MAX_WINDOW_SIZE) > 0 + || windowSize.compareTo(QueryInsightsSettings.MIN_WINDOW_SIZE) < 0) { + throw new IllegalArgumentException( + "Window size setting [" + + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey() + + "]" + + " should be between [" + + QueryInsightsSettings.MAX_WINDOW_SIZE + + "," + + QueryInsightsSettings.MAX_WINDOW_SIZE + + "]" + + "was (" + + windowSize + + ")" + ); } - } - - private void doExport() { - List storedData = getQueryData(); - try { - exporter.export(storedData); - } catch (Exception e) { - throw new RuntimeException(String.format(Locale.ROOT, "failed to export query insight data to sink, error: %s", e)); + if (!(60 % windowSize.getMinutes() == 0 || windowSize.getMinutes() % 60 == 0)) { + throw new IllegalArgumentException( + "Window size setting [" + + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE.getKey() + + "]" + + " should be divisible by 60 (1 hour)" + + "was (" + + windowSize + + ")" + ); } } - @Override - protected void doClose() {} - /** - * Get the export interval set for the {@link QueryInsightsExporter} - * @return export interval + * Get the size of top N queries store + * @param metricType {@link MetricType} + * @return top N queries store size */ - public TimeValue getExportInterval() { - return exportInterval; + public int getTopNStoreSize(MetricType metricType) { + return topQueriesStores.get(metricType).size(); } /** - * Set the export interval for the exporter. - * - * @param interval export interval + * Get the size of top N queries history store + * @param metricType {@link MetricType} + * @return top N queries history store size */ - public void setExportInterval(TimeValue interval) { - this.exportInterval = interval; + public int getTopNHistoryStoreSize(MetricType metricType) { + return topQueriesHistoryStores.get(metricType).size(); + } + + private Long calculateWindowStart(Long timestamp) { + LocalDateTime currentTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC")); + LocalDateTime windowStartTime = currentTime.truncatedTo(ChronoUnit.HOURS); + while (!windowStartTime.plusMinutes(windowSize.getMinutes()).isAfter(currentTime)) { + windowStartTime = windowStartTime.plusMinutes(windowSize.getMinutes()); + } + return windowStartTime.toInstant(ZoneOffset.UTC).getEpochSecond() * 1000; } } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Attribute.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Attribute.java new file mode 100644 index 0000000000000..cb798dd6ed1f4 --- /dev/null +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Attribute.java @@ -0,0 +1,70 @@ +/* + * 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.core.common.io.stream.StreamInput; +import org.opensearch.core.common.io.stream.StreamOutput; + +import java.io.IOException; +import java.util.Locale; + +/** + * Valid attributes for a search query record + */ +public enum Attribute { + /** + * The search query type + */ + SEARCH_TYPE, + /** + * The search query source + */ + SOURCE, + /** + * Total shards queried + */ + TOTAL_SHARDS, + /** + * The indices involved + */ + INDICES, + /** + * The per phase level latency map for a search query + */ + PHASE_LATENCY_MAP, + /** + * The node id for this request + */ + NODE_ID; + + /** + * Read an Attribute from a StreamInput + * @param in the StreamInput to read from + * @return Attribute + * @throws IOException IOException + */ + public static Attribute readFromStream(StreamInput in) throws IOException { + return Attribute.valueOf(in.readString().toUpperCase(Locale.ROOT)); + } + + /** + * Write Attribute to a StreamOutput + * @param out the StreamOutput to write + * @param attribute the Attribute to write + * @throws IOException IOException + */ + public static void writeTo(StreamOutput out, Attribute attribute) throws IOException { + out.writeString(attribute.toString()); + } + + @Override + public String toString() { + return this.name().toLowerCase(Locale.ROOT); + } +} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Measurement.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Measurement.java new file mode 100644 index 0000000000000..0d34b17a597db --- /dev/null +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/Measurement.java @@ -0,0 +1,100 @@ +/* + * 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.core.common.io.stream.StreamInput; +import org.opensearch.core.common.io.stream.StreamOutput; + +import java.io.IOException; +import java.util.Locale; + +/** + * Represents a measurement with a name and a corresponding value. + * + * @param the type of the value + */ +public class Measurement> { + String name; + T value; + + /** + * Create a Measurement from a StreamInput + * @param in the StreamInput to read from + * @throws IOException IOException + */ + @SuppressWarnings("unchecked") + public Measurement(StreamInput in) throws IOException { + this.name = in.readString(); + this.value = (T) in.readGenericValue(); + } + + /** + * Write Measurement to a StreamOutput + * @param out the StreamOutput to write + * @param measurement the Measurement to write + * @throws IOException IOException + */ + public static void writeTo(StreamOutput out, Measurement measurement) throws IOException { + out.writeString(measurement.getName()); + out.writeGenericValue(measurement.getValue()); + } + + /** + * Constructs a new Measurement with input name and value. + * + * @param name the name of the measurement + * @param value the value of the measurement + */ + public Measurement(String name, T value) { + this.name = name; + this.value = value; + } + + /** + * Returns the name of the measurement. + * + * @return the name of the measurement + */ + public String getName() { + return name; + } + + /** + * Returns the value of the measurement. + * + * @return the value of the measurement + */ + public T getValue() { + return value; + } + + /** + * Compare two measurements on the value + * @param other the other measure to compare + * @return 0 if the value that the two measurements holds are the same + * -1 if the value of the measurement is smaller than the other one + * 1 if the value of the measurement is greater than the other one + */ + @SuppressWarnings("unchecked") + public int compareTo(Measurement other) { + Number otherValue = other.getValue(); + if (value.getClass().equals(otherValue.getClass())) { + return value.compareTo((T) otherValue); + } else { + throw new UnsupportedOperationException( + String.format( + Locale.ROOT, + "comparison between different types are not supported : %s, %s", + value.getClass(), + otherValue.getClass() + ) + ); + } + } +} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/MetricType.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/MetricType.java new file mode 100644 index 0000000000000..2b03bec7a722f --- /dev/null +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/MetricType.java @@ -0,0 +1,78 @@ +/* + * 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.core.common.io.stream.StreamInput; +import org.opensearch.core.common.io.stream.StreamOutput; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Valid metric types for a search query record + */ +public enum MetricType { + /** + * Latency metric type + */ + LATENCY, + /** + * CPU usage metric type + */ + CPU, + /** + * JVM heap usage metric type + */ + JVM; + + /** + * Read a MetricType from a StreamInput + * @param in the StreamInput to read from + * @return MetricType + * @throws IOException IOException + */ + public static MetricType readFromStream(StreamInput in) throws IOException { + return fromString(in.readString()); + } + + /** + * Create MetricType from String + * @param metricType the String representation of MetricType + * @return MetricType + */ + public static MetricType fromString(String metricType) { + return MetricType.valueOf(metricType.toUpperCase(Locale.ROOT)); + } + + /** + * Write MetricType to a StreamOutput + * @param out the StreamOutput to write + * @param metricType the MetricType to write + * @throws IOException IOException + */ + public static void writeTo(StreamOutput out, MetricType metricType) throws IOException { + out.writeString(metricType.toString()); + } + + @Override + public String toString() { + return this.name().toLowerCase(Locale.ROOT); + } + + /** + * Get all valid metrics + * @return A set of String that contains all valid metrics + */ + public static Set allMetricTypes() { + return Arrays.stream(values()).collect(Collectors.toSet()); + } +} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecord.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecord.java deleted file mode 100644 index 97b423e092673..0000000000000 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryLatencyRecord.java +++ /dev/null @@ -1,111 +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.action.search.SearchType; -import org.opensearch.core.common.io.stream.StreamInput; -import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.core.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Map; - -/** - * The Latency record stored in the Query Insight Framework - * - * @opensearch.internal - */ -public final class SearchQueryLatencyRecord extends SearchQueryRecord { - - private static final String PHASE_LATENCY_MAP = "phaseLatencyMap"; - private static final String TOOK = "tookInNs"; - - // latency info for each search phase - private final Map phaseLatencyMap; - - /** - * Constructor for SearchQueryLatencyRecord - * - * @param in A {@link StreamInput} object. - * @throws IOException if the stream cannot be deserialized. - */ - public SearchQueryLatencyRecord(final StreamInput in) throws IOException { - super(in); - this.phaseLatencyMap = in.readMap(StreamInput::readString, StreamInput::readLong); - this.setValue(in.readLong()); - } - - @Override - protected void addCustomXContent(XContentBuilder builder, Params params) throws IOException { - builder.field(PHASE_LATENCY_MAP, this.getPhaseLatencyMap()); - builder.field(TOOK, this.getValue()); - } - - /** - * Constructor of the SearchQueryLatencyRecord - * - * @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 A map contains per-phase latency data - * @param tookInNanos Total time took to finish this request - */ - public SearchQueryLatencyRecord( - final Long timestamp, - final SearchType searchType, - final String source, - final int totalShards, - final String[] indices, - final Map propertyMap, - final Map phaseLatencyMap, - final Long tookInNanos - ) { - super(timestamp, searchType, source, totalShards, indices, propertyMap, tookInNanos); - this.phaseLatencyMap = phaseLatencyMap; - } - - /** - * Get the phase level latency map of this request record - * - * @return Map contains per-phase latency of this request record - */ - public Map getPhaseLatencyMap() { - return phaseLatencyMap; - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); - out.writeMap(phaseLatencyMap, StreamOutput::writeString, StreamOutput::writeLong); - out.writeLong(getValue()); - } - - /** - * Compare if two SearchQueryLatencyRecord are equal - * @param other The Other SearchQueryLatencyRecord to compare to - * @return boolean - */ - public boolean equals(SearchQueryLatencyRecord other) { - if (!super.equals(other)) { - return false; - } - for (String key : phaseLatencyMap.keySet()) { - if (!other.getPhaseLatencyMap().containsKey(key)) { - return false; - } - if (!phaseLatencyMap.get(key).equals(other.getPhaseLatencyMap().get(key))) { - return false; - } - } - return true; - } -} diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecord.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecord.java index f086a9e38c4cd..52ab26b40cba4 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecord.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecord.java @@ -8,252 +8,193 @@ package org.opensearch.plugin.insights.rules.model; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.opensearch.action.search.SearchType; +import org.opensearch.common.util.Maps; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import java.io.IOException; -import java.util.Locale; +import java.util.Arrays; import java.util.Map; /** * Simple abstract class that represent record stored in the Query Insight Framework * - * @param The value type associated with the record * @opensearch.internal */ -public abstract class SearchQueryRecord> - implements - Comparable>, - Writeable, - ToXContentObject { - - private static final Logger log = LogManager.getLogger(SearchQueryRecord.class); - private static final String TIMESTAMP = "timestamp"; - private static final String SEARCH_TYPE = "searchType"; - private static final String SOURCE = "source"; - private static final String TOTAL_SHARDS = "totalShards"; - private static final String INDICES = "indices"; - private static final String PROPERTY_MAP = "propertyMap"; - private static final String VALUE = "value"; - +public class SearchQueryRecord implements ToXContentObject, Writeable { private final Long timestamp; - - private final SearchType searchType; - - private final String source; - - private final int totalShards; - - private final String[] indices; - - // TODO: add user-account which initialized the request in the future - private final Map propertyMap; - - private T value; + private final Map> measurements; + private final Map attributes; /** - * Constructor of the SearchQueryRecord - * - * @param in A {@link StreamInput} object. - * @throws IOException if the stream cannot be deserialized. + * Constructor of SearchQueryRecord + * @param in the StreamInput to read the SearchQueryRecord from + * @throws IOException IOException * @throws ClassCastException ClassCastException */ public SearchQueryRecord(final StreamInput in) throws IOException, ClassCastException { this.timestamp = in.readLong(); - this.searchType = SearchType.fromString(in.readString().toLowerCase(Locale.ROOT)); - this.source = in.readString(); - this.totalShards = in.readInt(); - this.indices = in.readStringArray(); - this.propertyMap = in.readMap(); + this.measurements = in.readMap(MetricType::readFromStream, Measurement::new); + this.attributes = in.readMap(Attribute::readFromStream, StreamInput::readGenericValue); } /** - * Constructor of the SearchQueryRecord + * Constructor of SearchQueryRecord * * @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 value The value on this SearchQueryRecord + * @param measurements A list of Measurement associated with this query + * @param attributes A list of Attributes associated with this query */ public SearchQueryRecord( final Long timestamp, - final SearchType searchType, - final String source, - final int totalShards, - final String[] indices, - final Map propertyMap, - final T value + Map> measurements, + Map attributes ) { - this(timestamp, searchType, source, totalShards, indices, propertyMap); - this.value = value; - } + if (measurements == null) { + throw new IllegalArgumentException("Measurements cannot be null"); + } - /** - * Constructor of the SearchQueryRecord - * - * @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 - */ - public SearchQueryRecord( - final Long timestamp, - final SearchType searchType, - final String source, - final int totalShards, - final String[] indices, - final Map propertyMap - ) { + this.measurements = measurements; + this.attributes = attributes; this.timestamp = timestamp; - this.searchType = searchType; - this.source = source; - this.totalShards = totalShards; - this.indices = indices; - this.propertyMap = propertyMap; } /** - * The timestamp of the top query. + * Returns the observation time of the metric. + * + * @return the observation time in milliseconds */ - public Long getTimestamp() { + public long getTimestamp() { return timestamp; } /** - * The manner at which the search operation is executed. + * Returns the measurement associated with the specified name. + * + * @param name the name of the measurement + * @return the measurement object, or null if not found */ - public SearchType getSearchType() { - return searchType; + public Measurement getMeasurement(MetricType name) { + return measurements.get(name); } /** - * The search source that was executed by the query. + * Returns an unmodifiable map of all the measurements associated with the metric. + * + * @return an unmodifiable map of measurement names to measurement objects */ - public String getSource() { - return source; + public Map> getMeasurements() { + return measurements; } /** - * Total number of shards as part of the search query across all indices + * Returns an unmodifiable map of the attributes associated with the metric. + * + * @return an unmodifiable map of attribute keys to attribute values */ - public int getTotalShards() { - return totalShards; + public Map getAttributes() { + return attributes; } /** - * The indices involved in the search query + * Add an attribute to this record + * @param attribute attribute to add + * @param value the value associated with the attribute */ - public String[] getIndices() { - return indices; + public void addAttribute(Attribute attribute, Object value) { + attributes.put(attribute, value); } - /** - * Get the value of the query metric record - */ - public T getValue() { - return value; + @Override + public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { + builder.startObject(); + builder.field("timestamp", timestamp); + for (Map.Entry entry : attributes.entrySet()) { + builder.field(entry.getKey().toString(), entry.getValue()); + } + for (Map.Entry> entry : measurements.entrySet()) { + builder.field(entry.getKey().toString(), entry.getValue().getValue()); + } + return builder.endObject(); } /** - * Set the value of the query metric record - * @param value The value to set on the record + * Write a SearchQueryRecord to a StreamOutput + * @param out the StreamOutput to write + * @throws IOException IOException */ - public void setValue(T value) { - this.value = value; + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeLong(timestamp); + out.writeMap( + measurements, + (stream, metricType) -> MetricType.writeTo(out, metricType), + (stream, measurement) -> Measurement.writeTo(out, measurement) + ); + out.writeMap(attributes, (stream, attribute) -> Attribute.writeTo(out, attribute), StreamOutput::writeGenericValue); } /** - * Extra attributes and information about a search query + * Compare two SearchQueryRecord, based on the given MetricType + * + * @param a the first SearchQueryRecord to compare + * @param b the second SearchQueryRecord to compare + * @param metricType the MetricType to compare on + * @return 0 if the first SearchQueryRecord is numerically equal to the second SearchQueryRecord; + * -1 if the first SearchQueryRecord is numerically less than the second SearchQueryRecord; + * 1 if the first SearchQueryRecord is numerically greater than the second SearchQueryRecord. */ - public Map getPropertyMap() { - return propertyMap; - } - - @Override - public int compareTo(SearchQueryRecord otherRecord) { - return value.compareTo(otherRecord.getValue()); + public static int compare(SearchQueryRecord a, SearchQueryRecord b, MetricType metricType) { + return a.getMeasurement(metricType).compareTo(b.getMeasurement(metricType)); } /** - * Compare if two SearchQueryRecord are equal - * @param other The Other SearchQueryRecord to compare to - * @return boolean + * Check if a SearchQueryRecord is deep equal to another record + * @param o the other SearchQueryRecord record + * @return true if two records are deep equal, false otherwise. */ - public boolean equals(SearchQueryRecord other) { - if (!this.timestamp.equals(other.getTimestamp()) - || !this.searchType.equals(other.getSearchType()) - || !this.source.equals(other.getSource()) - || this.totalShards != other.getTotalShards() - || this.indices.length != other.getIndices().length - || this.propertyMap.size() != other.getPropertyMap().size() - || !this.value.equals(other.getValue())) { + @SuppressWarnings("unchecked") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof SearchQueryRecord)) { + return false; + } + SearchQueryRecord other = (SearchQueryRecord) o; + + Map> measurements2 = other.getMeasurements(); + Map attributes2 = other.getAttributes(); + if (timestamp != other.getTimestamp() || measurements.size() != measurements2.size() || attributes.size() != attributes2.size()) { return false; } - for (int i = 0; i < indices.length; i++) { - if (!indices[i].equals(other.getIndices()[i])) { + for (Map.Entry> entry : measurements.entrySet()) { + MetricType metricType = entry.getKey(); + Measurement measurement = entry.getValue(); + if (!measurements2.containsKey(metricType) + || !measurement.getName().equals(measurements2.get(metricType).getName()) + || !measurement.getValue().equals(measurements2.get(metricType).getValue())) { return false; } } - for (String key : propertyMap.keySet()) { - if (!other.getPropertyMap().containsKey(key)) { + for (Map.Entry entry : attributes.entrySet()) { + Attribute attribute = entry.getKey(); + Object value = entry.getValue(); + if (!attributes2.containsKey(attribute)) { return false; } - if (!propertyMap.get(key).equals(other.getPropertyMap().get(key))) { - return false; + if (value instanceof Object[]) { + return Arrays.deepEquals((Object[]) value, (Object[]) attributes2.get(attribute)); + } + else if (value instanceof Map) { + return Maps.deepEquals((Map) value, (Map) attributes2.get(attribute)); } } return true; } - - @SuppressWarnings("unchecked") - private T castToValue(Object obj) throws ClassCastException { - try { - return (T) obj; - } catch (Exception e) { - log.error(String.format(Locale.ROOT, "error casting query insight record value, error: %s", e)); - throw e; - } - } - - /** - * Add custom XContent fields to the record - * @param builder XContent builder - * @param params XContent parameters - * @throws IOException IOException - */ - protected abstract void addCustomXContent(XContentBuilder builder, Params params) throws IOException; - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - builder.field(TIMESTAMP, timestamp); - builder.field(SEARCH_TYPE, searchType); - builder.field(SOURCE, source); - builder.field(TOTAL_SHARDS, totalShards); - builder.field(INDICES, indices); - builder.field(PROPERTY_MAP, propertyMap); - addCustomXContent(builder, params); - return builder.endObject(); - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - out.writeLong(timestamp); - out.writeString(searchType.toString()); - out.writeString(source); - out.writeInt(totalShards); - out.writeStringArray(indices); - out.writeMap(propertyMap); - } } diff --git a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/settings/QueryInsightsSettings.java b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/settings/QueryInsightsSettings.java index 818959bf7f12a..839cd8b16658a 100644 --- a/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/settings/QueryInsightsSettings.java +++ b/plugins/query-insights/src/main/java/org/opensearch/plugin/insights/settings/QueryInsightsSettings.java @@ -10,9 +10,7 @@ import org.opensearch.common.settings.Setting; import org.opensearch.common.unit.TimeValue; -import org.opensearch.plugin.insights.core.exporter.QueryInsightsExporterType; -import java.util.Locale; import java.util.concurrent.TimeUnit; /** @@ -22,16 +20,20 @@ * @opensearch.experimental */ public class QueryInsightsSettings { + /** + * Executors settings + */ + public static final String QUERY_INSIGHTS_EXECUTOR = "query_insights_executor"; /** * Default Values and Settings */ public static final TimeValue MAX_WINDOW_SIZE = new TimeValue(21600, TimeUnit.SECONDS); + /** + * Minimal window size + */ + public static final TimeValue MIN_WINDOW_SIZE = new TimeValue(60, TimeUnit.SECONDS); /** Default N size for top N queries */ public static final int MAX_N_SIZE = 100; - /** Default min export interval for Query Insights exporters */ - public static final TimeValue MIN_EXPORT_INTERVAL = new TimeValue(1, TimeUnit.SECONDS); - /** Default local index mapping for top n queries records */ - public static final String DEFAULT_LOCAL_INDEX_MAPPING = "mappings/top_n_queries_record.json"; /** Default window size in seconds to keep the top N queries with latency data in query insight store */ public static final int DEFAULT_WINDOW_SIZE = 60; /** Default top N size to keep the data in query insight store */ @@ -80,60 +82,6 @@ public class QueryInsightsSettings { Setting.Property.Dynamic ); - /** - * Settings for exporters - */ - public static final String TOP_N_LATENCY_QUERIES_EXPORTER_PREFIX = TOP_N_LATENCY_QUERIES_PREFIX + ".exporter"; - - /** - * Boolean setting for enabling top queries by latency exporter - */ - public static final Setting TOP_N_LATENCY_QUERIES_EXPORTER_ENABLED = Setting.boolSetting( - TOP_N_LATENCY_QUERIES_EXPORTER_PREFIX + ".enabled", - false, - Setting.Property.Dynamic, - Setting.Property.NodeScope - ); - - /** - * Setting for top queries by latency exporter type - */ - public static final Setting TOP_N_LATENCY_QUERIES_EXPORTER_TYPE = new Setting<>( - TOP_N_LATENCY_QUERIES_EXPORTER_PREFIX + ".type", - QueryInsightsExporterType.LOCAL_INDEX.name(), - QueryInsightsExporterType::parse, - Setting.Property.Dynamic, - Setting.Property.NodeScope - ); - - /** - * Setting for top queries by latency exporter interval - */ - public static final Setting TOP_N_LATENCY_QUERIES_EXPORTER_INTERVAL = Setting.positiveTimeSetting( - TOP_N_LATENCY_QUERIES_EXPORTER_PREFIX + ".interval", - MIN_EXPORT_INTERVAL, - Setting.Property.NodeScope, - Setting.Property.Dynamic - ); - - /** - * Setting for identifier (e.g. index name for index exporter) top queries by latency exporter - * Default value is "top_queries_since_{current_timestamp}" - */ - public static final Setting TOP_N_LATENCY_QUERIES_EXPORTER_IDENTIFIER = Setting.simpleString( - TOP_N_LATENCY_QUERIES_EXPORTER_PREFIX + ".identifier", - "top_queries_since_" + System.currentTimeMillis(), - value -> { - if (value == null || value.length() == 0) { - throw new IllegalArgumentException( - String.format(Locale.ROOT, "Invalid index name for [%s]", TOP_N_LATENCY_QUERIES_EXPORTER_PREFIX + ".identifier") - ); - } - }, - Setting.Property.NodeScope, - Setting.Property.Dynamic - ); - /** * Default constructor */ diff --git a/plugins/query-insights/src/main/resources/mappings/top_n_queries_record.json b/plugins/query-insights/src/main/resources/mappings/top_n_queries_record.json deleted file mode 100644 index 3bdfa835e813e..0000000000000 --- a/plugins/query-insights/src/main/resources/mappings/top_n_queries_record.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "_meta" : { - "schema_version": 1 - }, - "properties" : { - "timestamp" : { - "type" : "date" - }, - "search_type" : { - "type" : "text", - "fields" : { - "keyword" : { - "type" : "keyword", - "ignore_above" : 256 - } - } - }, - "total_shards" : { - "type" : "integer" - }, - "indices" : { - "type" : "text", - "fields" : { - "keyword" : { - "type" : "keyword", - "ignore_above" : 256 - } - } - }, - "phase_latency_map" : { - "type" : "object" - }, - "property_map" : { - "type" : "object" - }, - "value" : { - "type" : "long" - } - } -} diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsPluginTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsPluginTests.java index 93031f0a865dd..f6d95450855de 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsPluginTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsPluginTests.java @@ -14,6 +14,7 @@ import org.opensearch.common.settings.ClusterSettings; import org.opensearch.common.settings.Settings; import org.opensearch.core.action.ActionResponse; +import org.opensearch.plugin.insights.core.service.QueryInsightsService; import org.opensearch.plugin.insights.settings.QueryInsightsSettings; import org.opensearch.plugins.ActionPlugin; import org.opensearch.rest.RestHandler; @@ -21,6 +22,7 @@ import org.opensearch.threadpool.ThreadPool; import org.junit.Before; +import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.mock; @@ -42,17 +44,20 @@ 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); clusterService = new ClusterService(settings, clusterSettings, threadPool); } public void testGetSettings() { - assertEquals(0, queryInsightsPlugin.getSettings().size()); + assertEquals( + Arrays.asList( + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_ENABLED, + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_SIZE, + QueryInsightsSettings.TOP_N_LATENCY_QUERIES_WINDOW_SIZE + ), + queryInsightsPlugin.getSettings() + ); } public void testCreateComponent() { @@ -69,7 +74,8 @@ public void testCreateComponent() { null, null ); - assertEquals(0, components.size()); + assertEquals(1, components.size()); + assertTrue(components.get(0) instanceof QueryInsightsService); } public void testGetRestHandlers() { diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsTestUtils.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsTestUtils.java index e62adc18a22f9..2977996107fce 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsTestUtils.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/QueryInsightsTestUtils.java @@ -9,24 +9,36 @@ package org.opensearch.plugin.insights; import org.opensearch.action.search.SearchType; +import org.opensearch.cluster.node.DiscoveryNode; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; +import org.opensearch.plugin.insights.rules.action.top_queries.TopQueries; +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 org.opensearch.test.VersionUtils; import java.io.IOException; import java.util.ArrayList; -import java.util.Comparator; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; +import static java.util.Collections.emptyMap; +import static java.util.Collections.emptySet; import static org.opensearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.opensearch.test.OpenSearchTestCase.buildNewFakeTransportAddress; +import static org.opensearch.test.OpenSearchTestCase.random; import static org.opensearch.test.OpenSearchTestCase.randomAlphaOfLengthBetween; import static org.opensearch.test.OpenSearchTestCase.randomArray; +import static org.opensearch.test.OpenSearchTestCase.randomDouble; import static org.opensearch.test.OpenSearchTestCase.randomIntBetween; import static org.opensearch.test.OpenSearchTestCase.randomLong; +import static org.opensearch.test.OpenSearchTestCase.randomLongBetween; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -34,43 +46,59 @@ final public class QueryInsightsTestUtils { public QueryInsightsTestUtils() {} - public static List generateQueryInsightRecords(int count) { - return generateQueryInsightRecords(count, count); + public static List generateQueryInsightRecords(int count) { + return generateQueryInsightRecords(count, count, System.currentTimeMillis(), 0); } /** * Creates a List of random Query Insight Records for testing purpose */ - public static List generateQueryInsightRecords(int lower, int upper) { - List records = new ArrayList<>(); + public static List generateQueryInsightRecords(int lower, int upper, long startTimeStamp, long interval) { + List records = new ArrayList<>(); int countOfRecords = randomIntBetween(lower, upper); + long timestamp = startTimeStamp; for (int i = 0; i < countOfRecords; ++i) { - Map propertyMap = new HashMap<>(); - int countOfProperties = randomIntBetween(2, 5); - for (int j = 0; j < countOfProperties; ++j) { - propertyMap.put(randomAlphaOfLengthBetween(5, 10), randomAlphaOfLengthBetween(5, 10)); - } + Map> measurements = Map.of( + MetricType.LATENCY, + new Measurement<>(MetricType.LATENCY.name(), randomLongBetween(1000, 10000)), + MetricType.CPU, + new Measurement<>(MetricType.CPU.name(), randomDouble()), + MetricType.JVM, + new Measurement<>(MetricType.JVM.name(), randomDouble()) + ); + Map phaseLatencyMap = new HashMap<>(); int countOfPhases = randomIntBetween(2, 5); for (int j = 0; j < countOfPhases; ++j) { phaseLatencyMap.put(randomAlphaOfLengthBetween(5, 10), randomLong()); } - records.add( - new SearchQueryLatencyRecord( - System.currentTimeMillis(), - SearchType.QUERY_THEN_FETCH, - "{\"size\":20}", - randomIntBetween(1, 100), - randomArray(1, 3, String[]::new, () -> randomAlphaOfLengthBetween(5, 10)), - propertyMap, - phaseLatencyMap, - phaseLatencyMap.values().stream().mapToLong(x -> x).sum() - ) - ); + Map attributes = new HashMap<>(); + attributes.put(Attribute.SEARCH_TYPE, SearchType.QUERY_THEN_FETCH.toString().toLowerCase(Locale.ROOT)); + attributes.put(Attribute.SOURCE, "{\"size\":20}"); + attributes.put(Attribute.TOTAL_SHARDS, randomIntBetween(1, 100)); + attributes.put(Attribute.INDICES, randomArray(1, 3, Object[]::new, () -> randomAlphaOfLengthBetween(5, 10))); + attributes.put(Attribute.PHASE_LATENCY_MAP, phaseLatencyMap); + + records.add(new SearchQueryRecord(timestamp, measurements, attributes)); + timestamp += interval; } return records; } + public static SearchQueryRecord createFixedSearchQueryRecord() { + long timestamp = 1706574180000L; + Map> measurements = Map.of( + MetricType.LATENCY, + new Measurement<>(MetricType.LATENCY.name(), 1L) + ); + + Map phaseLatencyMap = new HashMap<>(); + Map attributes = new HashMap<>(); + attributes.put(Attribute.SEARCH_TYPE, SearchType.QUERY_THEN_FETCH.toString().toLowerCase(Locale.ROOT)); + + return new SearchQueryRecord(timestamp, measurements, attributes); + } + public static void compareJson(ToXContent param1, ToXContent param2) throws IOException { if (param1 == null || param2 == null) { assertNull(param1); @@ -88,20 +116,12 @@ public static void compareJson(ToXContent param1, ToXContent param2) throws IOEx assertEquals(param1Builder.toString(), param2Builder.toString()); } - public static boolean checkRecordsEquals(List records1, List records2) { - if (records1.size() != records2.size()) { - return false; - } - for (int i = 0; i < records1.size(); i++) { - if (!records1.get(i).equals(records2.get(i))) { - return false; - } - } - return true; - } - - public static boolean checkRecordsEqualsWithoutOrder(List records1, List records2) { - Set set2 = new TreeSet<>(new LatencyRecordComparator()); + public static boolean checkRecordsEqualsWithoutOrder( + List records1, + List records2, + MetricType metricType + ) { + Set set2 = new TreeSet<>((a, b) -> SearchQueryRecord.compare(a, b, metricType)); set2.addAll(records2); if (records1.size() != records2.size()) { return false; @@ -113,14 +133,4 @@ public static boolean checkRecordsEqualsWithoutOrder(List { - @Override - public int compare(SearchQueryLatencyRecord record1, SearchQueryLatencyRecord record2) { - if (record1.equals(record2)) { - return 0; - } - return record1.compareTo(record2); - } - } } diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterTests.java deleted file mode 100644 index 64d296e501519..0000000000000 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsExporterTests.java +++ /dev/null @@ -1,35 +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.exporter; - -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; -import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; -import org.opensearch.test.OpenSearchTestCase; - -import java.util.List; - -/** - * Unit Tests for {@link QueryInsightsExporter}. - */ -public class QueryInsightsExporterTests extends OpenSearchTestCase { - public class DummyExporter> extends QueryInsightsExporter { - DummyExporter(String identifier) { - super(identifier); - } - - @Override - public void export(List records) {} - } - - public void testGetType() { - DummyExporter exporter = new DummyExporter<>("test-index"); - String identifier = exporter.getIdentifier(); - assertEquals("test-index", identifier); - } -} diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporterTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporterTests.java deleted file mode 100644 index f1cac56447cfb..0000000000000 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/exporter/QueryInsightsLocalIndexExporterTests.java +++ /dev/null @@ -1,256 +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.exporter; - -import org.opensearch.action.admin.indices.create.CreateIndexRequest; -import org.opensearch.action.admin.indices.create.CreateIndexResponse; -import org.opensearch.action.bulk.BulkItemResponse; -import org.opensearch.action.bulk.BulkRequest; -import org.opensearch.action.bulk.BulkResponse; -import org.opensearch.action.index.IndexRequest; -import org.opensearch.action.support.WriteRequest; -import org.opensearch.client.AdminClient; -import org.opensearch.client.Client; -import org.opensearch.client.IndicesAdminClient; -import org.opensearch.cluster.ClusterState; -import org.opensearch.cluster.routing.RoutingTable; -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.common.xcontent.XContentFactory; -import org.opensearch.core.action.ActionListener; -import org.opensearch.core.common.io.stream.InputStreamStreamInput; -import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.plugin.insights.QueryInsightsTestUtils; -import org.opensearch.plugin.insights.rules.model.SearchQueryLatencyRecord; -import org.opensearch.plugin.insights.settings.QueryInsightsSettings; -import org.opensearch.test.OpenSearchTestCase; -import org.junit.Before; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Phaser; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.doAnswer; -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 QueryInsightsLocalIndexExporter}. - */ -public class QueryInsightsLocalIndexExporterTests extends OpenSearchTestCase { - private final String LOCAL_INDEX_NAME = "top-queries"; - private final IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class); - private final AdminClient adminClient = mock(AdminClient.class); - private final Client client = mock(Client.class); - - private final ClusterState clusterState = mock(ClusterState.class); - private final RoutingTable mockRoutingTable = mock(RoutingTable.class); - - private final List records = QueryInsightsTestUtils.generateQueryInsightRecords(5, 10); - - private final Settings.Builder settingsBuilder = Settings.builder(); - private final Settings settings = settingsBuilder.build(); - - private final ClusterService clusterService = mock(ClusterService.class); - private final BulkRequest bulkRequest = new BulkRequest().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) - .timeout(TimeValue.timeValueSeconds(60)); - - private QueryInsightsLocalIndexExporter queryInsightLocalIndexExporter; - - @SuppressWarnings("unchecked") - @Before - public void setup() throws IOException { - final CreateIndexResponse createIndexResponse = new CreateIndexResponse(true, false, "test-index"); - doAnswer(invocation -> { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onResponse(createIndexResponse); - return null; - }).when(indicesAdminClient).create(any(CreateIndexRequest.class), any(ActionListener.class)); - - final BulkResponse bulkResponse = new BulkResponse(new BulkItemResponse[] {}, randomLong()); - doAnswer(invocation -> { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onResponse(bulkResponse); - return null; - }).when(client).bulk(any(BulkRequest.class), any(ActionListener.class)); - - when(adminClient.indices()).thenReturn(indicesAdminClient); - when(client.admin()).thenReturn(adminClient); - for (SearchQueryLatencyRecord record : records) { - bulkRequest.add( - new IndexRequest(LOCAL_INDEX_NAME).source(record.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)) - ); - } - 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); - - when(clusterService.getClusterSettings()).thenReturn(clusterSettings); - when(clusterService.state()).thenReturn(clusterState); - - final int length = randomIntBetween(1, 1024); - ByteArrayInputStream is = new ByteArrayInputStream(new byte[length]); - InputStreamStreamInput streamInput = new InputStreamStreamInput(is); - - queryInsightLocalIndexExporter = new QueryInsightsLocalIndexExporter<>(clusterService, client, LOCAL_INDEX_NAME, streamInput); - } - - public void testExportWhenIndexExists() throws IOException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(true); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - queryInsightLocalIndexExporter.export(records); - verify(client, times(1)).bulk( - argThat((BulkRequest request) -> request.requests().toString().equals(bulkRequest.requests().toString())), - any() - ); - } - - public void testConcurrentExportWhenIndexExists() throws InterruptedException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(true); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - int numBulk = 50; - Thread[] threads = new Thread[numBulk]; - Phaser phaser = new Phaser(numBulk + 1); - CountDownLatch countDownLatch = new CountDownLatch(numBulk); - - final List> queryInsightLocalIndexExporters = new ArrayList<>(); - for (int i = 0; i < numBulk; i++) { - queryInsightLocalIndexExporters.add(new QueryInsightsLocalIndexExporter<>(clusterService, client, LOCAL_INDEX_NAME, null)); - } - - for (int i = 0; i < numBulk; i++) { - int finalI = i; - threads[i] = new Thread(() -> { - phaser.arriveAndAwaitAdvance(); - QueryInsightsLocalIndexExporter thisExporter = queryInsightLocalIndexExporters.get(finalI); - try { - thisExporter.export(records); - } catch (IOException e) { - throw new RuntimeException(e); - } - countDownLatch.countDown(); - }); - threads[i].start(); - } - phaser.arriveAndAwaitAdvance(); - countDownLatch.await(); - - verify(client, times(numBulk)).bulk( - argThat((BulkRequest request) -> request.requests().toString().equals(bulkRequest.requests().toString())), - any() - ); - } - - public void testExportWhenIndexNotExists() throws IOException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(false); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - queryInsightLocalIndexExporter.export(records); - verify(indicesAdminClient, times(1)).create( - argThat((CreateIndexRequest request) -> request.index().equals(LOCAL_INDEX_NAME)), - any() - ); - } - - public void testConcurrentExportWhenIndexNotExists() throws InterruptedException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(false).thenReturn(true); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - - int numBulk = 50; - Thread[] threads = new Thread[numBulk]; - Phaser phaser = new Phaser(numBulk + 1); - CountDownLatch countDownLatch = new CountDownLatch(numBulk); - - final int length = randomIntBetween(1, 1024); - ByteArrayInputStream is = new ByteArrayInputStream(new byte[length]); - InputStreamStreamInput streamInput = new InputStreamStreamInput(is); - - final List> queryInsightLocalIndexExporters = new ArrayList<>(); - for (int i = 0; i < numBulk; i++) { - queryInsightLocalIndexExporters.add( - new QueryInsightsLocalIndexExporter<>(clusterService, client, LOCAL_INDEX_NAME, streamInput) - ); - } - - for (int i = 0; i < numBulk; i++) { - int finalI = i; - threads[i] = new Thread(() -> { - phaser.arriveAndAwaitAdvance(); - QueryInsightsLocalIndexExporter thisExporter = queryInsightLocalIndexExporters.get(finalI); - try { - thisExporter.export(records); - } catch (IOException e) { - throw new RuntimeException(e); - } - countDownLatch.countDown(); - }); - threads[i].start(); - } - phaser.arriveAndAwaitAdvance(); - countDownLatch.await(); - - verify(indicesAdminClient, times(1)).create( - argThat((CreateIndexRequest request) -> request.index().equals(LOCAL_INDEX_NAME)), - any() - ); - } - - public void testInitIndexSucceed() throws IOException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(false); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - queryInsightLocalIndexExporter.export(records); - verify(client, times(1)).bulk( - argThat((BulkRequest request) -> request.requests().toString().equals(bulkRequest.requests().toString())), - any() - ); - } - - @SuppressWarnings("unchecked") - public void testInitIndexFailed() throws IOException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(false); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - final CreateIndexResponse response = new CreateIndexResponse(false, false, "test-index"); - doAnswer(invocation -> { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onResponse(response); - return null; - }).when(indicesAdminClient).create(any(CreateIndexRequest.class), any(ActionListener.class)); - queryInsightLocalIndexExporter.export(records); - verify(client, times(0)).bulk( - argThat((BulkRequest request) -> request.requests().toString().equals(bulkRequest.requests().toString())), - any() - ); - } - - public void testBulkSucceed() throws IOException { - when(mockRoutingTable.hasIndex(anyString())).thenReturn(true); - when(clusterState.getRoutingTable()).thenReturn(mockRoutingTable); - queryInsightLocalIndexExporter.export(records); - verify(client, times(1)).bulk( - argThat((BulkRequest request) -> request.requests().toString().equals(bulkRequest.requests().toString())), - any() - ); - } -} diff --git a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/QueryInsightsServiceTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/QueryInsightsServiceTests.java index b3eaf61dbb9a7..8339f55a4b2eb 100644 --- a/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/QueryInsightsServiceTests.java +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/core/service/QueryInsightsServiceTests.java @@ -8,124 +8,200 @@ package org.opensearch.plugin.insights.core.service; -import org.opensearch.client.Client; -import org.opensearch.cluster.service.ClusterService; -import org.opensearch.common.settings.ClusterSettings; +import org.opensearch.cluster.coordination.DeterministicTaskQueue; 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.rules.model.MetricType; +import org.opensearch.plugin.insights.rules.model.SearchQueryRecord; import org.opensearch.plugin.insights.settings.QueryInsightsSettings; import org.opensearch.test.OpenSearchTestCase; -import org.opensearch.threadpool.Scheduler; import org.opensearch.threadpool.ThreadPool; import org.junit.Before; -import java.io.IOException; -import java.util.ArrayList; import java.util.List; - -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; +import java.util.concurrent.TimeUnit; /** * Unit Tests for {@link QueryInsightsService}. */ public class QueryInsightsServiceTests extends OpenSearchTestCase { - private ThreadPool threadPool = mock(ThreadPool.class); - private DummyQueryInsightsService dummyQueryInsightsService; - @SuppressWarnings("unchecked") - private QueryInsightsLocalIndexExporter exporter = mock(QueryInsightsLocalIndexExporter.class); - - static class DummyQueryInsightsService extends QueryInsightsService< - SearchQueryLatencyRecord, - ArrayList, - QueryInsightsLocalIndexExporter> { - public DummyQueryInsightsService( - ThreadPool threadPool, - ClusterService clusterService, - Client client, - QueryInsightsLocalIndexExporter exporter - ) { - super(threadPool, new ArrayList<>(), exporter); + + private DeterministicTaskQueue deterministicTaskQueue; + private ThreadPool threadPool; + private QueryInsightsService queryInsightsService; + + @Before + public void setup() { + final Settings settings = Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "top n queries tests").build(); + deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); + threadPool = deterministicTaskQueue.getThreadPool(); + queryInsightsService = new QueryInsightsService(threadPool); + queryInsightsService.enableCollection(MetricType.LATENCY, true); + queryInsightsService.enableCollection(MetricType.CPU, true); + queryInsightsService.enableCollection(MetricType.JVM, true); + queryInsightsService.setTopNSize(Integer.MAX_VALUE); + queryInsightsService.setWindowSize(new TimeValue(Long.MAX_VALUE)); + } + + public void testIngestQueryDataWithLargeWindow() { + final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); + for (SearchQueryRecord record : records) { + queryInsightsService.addRecord(record); } + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertTrue( + QueryInsightsTestUtils.checkRecordsEqualsWithoutOrder( + queryInsightsService.getTopNRecords(MetricType.LATENCY, false), + records, + MetricType.LATENCY + ) + ); + } - @Override - public void clearOutdatedData() {} + public void testConcurrentIngestQueryDataWithLargeWindow() { + final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); - @Override - public void resetExporter(boolean enabled, QueryInsightsExporterType type, String identifier) {} + int numRequests = records.size(); + for (int i = 0; i < numRequests; i++) { + int finalI = i; + threadPool.schedule(() -> { queryInsightsService.addRecord(records.get(finalI)); }, TimeValue.ZERO, ThreadPool.Names.GENERIC); + } + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertTrue( + QueryInsightsTestUtils.checkRecordsEqualsWithoutOrder( + queryInsightsService.getTopNRecords(MetricType.LATENCY, false), + records, + MetricType.LATENCY + ) + ); + } - public void doStart() { - super.doStart(); + public void testRollingWindow() { + // Create records with starting timestamp Monday, January 1, 2024 8:13:23 PM, with interval 10 minutes + final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10, 10, 1704140003000L, 1000 * 60 * 10); + queryInsightsService.setWindowSize(TimeValue.timeValueMinutes(10)); + queryInsightsService.addRecord(records.get(0)); + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNStoreSize(MetricType.LATENCY)); + assertEquals(0, queryInsightsService.getTopNHistoryStoreSize(MetricType.LATENCY)); + for (SearchQueryRecord record : records.subList(1, records.size())) { + queryInsightsService.addRecord(record); + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNStoreSize(MetricType.LATENCY)); + assertEquals(1, queryInsightsService.getTopNHistoryStoreSize(MetricType.LATENCY)); } + assertEquals(0, queryInsightsService.getTopNRecords(MetricType.LATENCY, false).size()); + } + + public void testRollingWindowWithHistory() { + // Create 2 records with starting Now and last 10 minutes + final List records = QueryInsightsTestUtils.generateQueryInsightRecords( + 2, + 2, + System.currentTimeMillis() - 1000 * 60 * 10, + 1000 * 60 * 10 + ); + queryInsightsService.setWindowSize(TimeValue.timeValueMinutes(3)); + queryInsightsService.addRecord(records.get(0)); + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNStoreSize(MetricType.LATENCY)); + assertEquals(0, queryInsightsService.getTopNHistoryStoreSize(MetricType.LATENCY)); + queryInsightsService.addRecord(records.get(1)); + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNStoreSize(MetricType.LATENCY)); + assertEquals(0, queryInsightsService.getTopNHistoryStoreSize(MetricType.LATENCY)); + assertEquals(1, queryInsightsService.getTopNRecords(MetricType.LATENCY, true).size()); + } - public void doStop() { - super.doStop(); + public void testSmallWindowClearOutdatedData() { + final List records = QueryInsightsTestUtils.generateQueryInsightRecords( + 2, + 2, + System.currentTimeMillis(), + 1000 * 60 * 20 + ); + queryInsightsService.setWindowSize(TimeValue.timeValueMinutes(10)); + + for (SearchQueryRecord record : records) { + queryInsightsService.addRecord(record); } + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertTrue(queryInsightsService.getTopNRecords(MetricType.LATENCY, false).size() <= 1); } - @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(); - 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); - dummyQueryInsightsService = new DummyQueryInsightsService(threadPool, clusterService, client, exporter); - when(threadPool.scheduleWithFixedDelay(any(), any(), any())).thenReturn(new Scheduler.Cancellable() { - @Override - public boolean cancel() { - return false; - } + public void testSmallNSize() { + final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); + queryInsightsService.setTopNSize(1); - @Override - public boolean isCancelled() { - return false; - } - }); + for (SearchQueryRecord record : records) { + queryInsightsService.addRecord(record); + } + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNRecords(MetricType.LATENCY, false).size()); + } + + public void testSmallNSizeWithCPU() { + final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); + queryInsightsService.setTopNSize(1); + + for (SearchQueryRecord record : records) { + queryInsightsService.addRecord(record); + } + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNRecords(MetricType.CPU, false).size()); } - public void testIngestDataWhenFeatureNotEnabled() { - dummyQueryInsightsService.setEnableCollect(false); - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(1); - dummyQueryInsightsService.ingestQueryData(records.get(0)); - assertThrows(IllegalArgumentException.class, () -> { dummyQueryInsightsService.getQueryData(); }); + public void testSmallNSizeWithJVM() { + final List records = QueryInsightsTestUtils.generateQueryInsightRecords(10); + queryInsightsService.setTopNSize(1); + + for (SearchQueryRecord record : records) { + queryInsightsService.addRecord(record); + } + runUntilTimeoutOrFinish(deterministicTaskQueue, 5000); + assertEquals(1, queryInsightsService.getTopNRecords(MetricType.JVM, false).size()); + } + + public void testValidateTopNSize() { + assertThrows( + IllegalArgumentException.class, + () -> { queryInsightsService.validateTopNSize(QueryInsightsSettings.MAX_N_SIZE + 1); } + ); } - public void testIngestDataWhenFeatureEnabled() { - dummyQueryInsightsService.setEnableCollect(true); - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(1); - dummyQueryInsightsService.ingestQueryData(records.get(0)); - assertEquals(records.get(0), dummyQueryInsightsService.getQueryData().get(0)); + public void testGetTopQueriesWhenNotEnabled() { + queryInsightsService.enableCollection(MetricType.LATENCY, false); + assertThrows(IllegalArgumentException.class, () -> { queryInsightsService.getTopNRecords(MetricType.LATENCY, false); }); } - public void testClearAllData() { - dummyQueryInsightsService.setEnableCollect(true); - dummyQueryInsightsService.setEnableCollect(true); - final List records = QueryInsightsTestUtils.generateQueryInsightRecords(1); - dummyQueryInsightsService.ingestQueryData(records.get(0)); - dummyQueryInsightsService.clearAllData(); - assertEquals(0, dummyQueryInsightsService.getQueryData().size()); + public void testValidateWindowSize() { + assertThrows(IllegalArgumentException.class, () -> { + queryInsightsService.validateWindowSize( + new TimeValue(QueryInsightsSettings.MAX_WINDOW_SIZE.getSeconds() + 1, TimeUnit.SECONDS) + ); + }); + assertThrows(IllegalArgumentException.class, () -> { + queryInsightsService.validateWindowSize( + new TimeValue(QueryInsightsSettings.MIN_WINDOW_SIZE.getSeconds() - 1, TimeUnit.SECONDS) + ); + }); + assertThrows( + IllegalArgumentException.class, + () -> { queryInsightsService.validateWindowSize(new TimeValue(7, TimeUnit.MINUTES)); } + ); } - public void testDoStartAndStop() throws IOException { - dummyQueryInsightsService.setEnableCollect(true); - dummyQueryInsightsService.setEnableExport(true); - dummyQueryInsightsService.doStart(); - verify(threadPool, times(1)).scheduleWithFixedDelay(any(), any(), any()); - dummyQueryInsightsService.doStop(); - verify(exporter, times(1)).export(any()); + 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/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/model/SearchQueryRecordTests.java b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecordTests.java new file mode 100644 index 0000000000000..12a6c7584b153 --- /dev/null +++ b/plugins/query-insights/src/test/java/org/opensearch/plugin/insights/rules/model/SearchQueryRecordTests.java @@ -0,0 +1,71 @@ +/* + * 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.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Granular tests for the {@link SearchQueryRecord} class. + */ +public class SearchQueryRecordTests 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 (SearchQueryRecord record : records) { + copiedRecords.add(roundTripRecord(record)); + } + assertEquals(records, copiedRecords); + + } + + public void testAllMetricTypes() { + Set allMetrics = MetricType.allMetricTypes(); + Set expected = new HashSet<>(Arrays.asList(MetricType.LATENCY, MetricType.CPU, MetricType.JVM)); + assertEquals(expected, allMetrics); + } + + public void testCompare() { + SearchQueryRecord record1 = QueryInsightsTestUtils.createFixedSearchQueryRecord(); + SearchQueryRecord record2 = QueryInsightsTestUtils.createFixedSearchQueryRecord(); + assertEquals(0, SearchQueryRecord.compare(record1, record2, MetricType.LATENCY)); + } + + public void testDeepEqual() { + SearchQueryRecord record1 = QueryInsightsTestUtils.createFixedSearchQueryRecord(); + SearchQueryRecord record2 = QueryInsightsTestUtils.createFixedSearchQueryRecord(); + assertEquals(record1, record2); + } + + /** + * Serialize and deserialize a SearchQueryRecord. + * @param record A SearchQueryRecord to serialize. + * @return The deserialized, "round-tripped" record. + */ + private static SearchQueryRecord roundTripRecord(SearchQueryRecord record) throws Exception { + try (BytesStreamOutput out = new BytesStreamOutput()) { + record.writeTo(out); + try (StreamInput in = out.bytes().streamInput()) { + return new SearchQueryRecord(in); + } + } + } +}