Skip to content

Commit

Permalink
Merge branch 'main' into codeowners-for-kibana-rd
Browse files Browse the repository at this point in the history
  • Loading branch information
elasticmachine authored Jul 12, 2023
2 parents dbd841a + 34b94c1 commit 254391b
Show file tree
Hide file tree
Showing 11 changed files with 178 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import org.elasticsearch.xpack.application.analytics.action.TransportPostAnalyticsEventAction;
import org.elasticsearch.xpack.application.analytics.action.TransportPutAnalyticsCollectionAction;
import org.elasticsearch.xpack.application.analytics.ingest.AnalyticsEventIngestConfig;
import org.elasticsearch.xpack.application.rules.QueryRulesConfig;
import org.elasticsearch.xpack.application.rules.QueryRulesIndexService;
import org.elasticsearch.xpack.application.rules.RuleQueryBuilder;
import org.elasticsearch.xpack.application.rules.action.DeleteQueryRulesetAction;
Expand Down Expand Up @@ -263,7 +264,8 @@ public List<Setting<?>> getSettings() {
AnalyticsEventIngestConfig.MAX_NUMBER_OF_EVENTS_PER_BULK_SETTING,
AnalyticsEventIngestConfig.FLUSH_DELAY_SETTING,
AnalyticsEventIngestConfig.MAX_NUMBER_OF_RETRIES_SETTING,
AnalyticsEventIngestConfig.MAX_BYTES_IN_FLIGHT_SETTING
AnalyticsEventIngestConfig.MAX_BYTES_IN_FLIGHT_SETTING,
QueryRulesConfig.MAX_RULE_LIMIT_SETTING
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import static org.elasticsearch.xpack.searchbusinessrules.PinnedQueryBuilder.DOCS_FIELD;
import static org.elasticsearch.xpack.searchbusinessrules.PinnedQueryBuilder.IDS_FIELD;
import static org.elasticsearch.xpack.searchbusinessrules.PinnedQueryBuilder.Item.INDEX_FIELD;
import static org.elasticsearch.xpack.searchbusinessrules.PinnedQueryBuilder.MAX_NUM_PINNED_HITS;

/**
* A query rule consists of:
Expand Down Expand Up @@ -113,14 +114,31 @@ public QueryRule(StreamInput in) throws IOException {

private void validate() {
if (type == QueryRuleType.PINNED) {
if (actions.containsKey("ids") == false && actions.containsKey("docs") == false) {
throw new ElasticsearchParseException("Pinned Query rule actions must contain either ids or docs");
boolean ruleContainsPinnedIds = actions.containsKey(IDS_FIELD.getPreferredName());
boolean ruleContainsPinnedDocs = actions.containsKey(DOCS_FIELD.getPreferredName());
if (ruleContainsPinnedIds ^ ruleContainsPinnedDocs) {
validatePinnedAction(actions.get(IDS_FIELD.getPreferredName()));
validatePinnedAction(actions.get(DOCS_FIELD.getPreferredName()));
} else {
throw new ElasticsearchParseException("pinned query rule actions must contain only one of either ids or docs");
}
} else {
throw new IllegalArgumentException("Unsupported QueryRuleType: " + type);
}
}

private void validatePinnedAction(Object action) {
if (action != null) {
if (action instanceof List == false) {
throw new ElasticsearchParseException("pinned query rule actions must be a list");
} else if (((List<?>) action).isEmpty()) {
throw new ElasticsearchParseException("pinned query rule actions cannot be empty");
} else if (((List<?>) action).size() > MAX_NUM_PINNED_HITS) {
throw new ElasticsearchParseException("pinned hits cannot exceed " + MAX_NUM_PINNED_HITS);
}
}
}

@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(id);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.application.rules;

import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.core.Strings;

import java.util.List;

public class QueryRulesConfig {

static final String SETTING_ROOT_PATH = "xpack.applications.rules";

private static final int DEFAULT_RULE_LIMIT = 100;
private static final int MIN_RULE_LIMIT = 1;
private static final int MAX_RULE_LIMIT = 1000;

/**
* Index setting describing the maximum number of {@link QueryRule}s that can be included
* in a query ruleset.
*/
public static final Setting<Integer> MAX_RULE_LIMIT_SETTING = Setting.intSetting(
Strings.format("%s.%s", SETTING_ROOT_PATH, "max_rules_per_ruleset"),
DEFAULT_RULE_LIMIT,
MIN_RULE_LIMIT,
MAX_RULE_LIMIT,
Setting.Property.Dynamic,
Setting.Property.NodeScope
);

public static List<Setting<?>> getSettings() {
return List.of(MAX_RULE_LIMIT_SETTING);
}

private QueryRulesConfig() {}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.client.internal.OriginSettingClient;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
Expand All @@ -44,6 +46,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

Expand All @@ -60,9 +63,11 @@ public class QueryRulesIndexService {
public static final String QUERY_RULES_CONCRETE_INDEX_NAME = ".query-rules-1";
public static final String QUERY_RULES_INDEX_NAME_PATTERN = ".query-rules-*";
private final Client clientWithOrigin;
private final ClusterSettings clusterSettings;

public QueryRulesIndexService(Client client) {
public QueryRulesIndexService(Client client, ClusterSettings clusterSettings) {
this.clientWithOrigin = new OriginSettingClient(client, ENT_SEARCH_ORIGIN);
this.clusterSettings = clusterSettings;
}

/**
Expand Down Expand Up @@ -212,6 +217,7 @@ private List<QueryRuleCriteria> parseCriteria(List<Map<String, Object>> rawCrite
*/
public void putQueryRuleset(QueryRuleset queryRuleset, ActionListener<IndexResponse> listener) {
try {
validateQueryRuleset(queryRuleset);
final IndexRequest indexRequest = new IndexRequest(QUERY_RULES_ALIAS_NAME).opType(DocWriteRequest.OpType.INDEX)
.id(queryRuleset.id())
.opType(DocWriteRequest.OpType.INDEX)
Expand All @@ -224,6 +230,22 @@ public void putQueryRuleset(QueryRuleset queryRuleset, ActionListener<IndexRespo

}

private void validateQueryRuleset(QueryRuleset queryRuleset) {
@SuppressWarnings("unchecked")
Setting<Integer> maxRuleLimitSetting = (Setting<Integer>) clusterSettings.get(QueryRulesConfig.MAX_RULE_LIMIT_SETTING.getKey());
int maxRuleLimit = clusterSettings.get(Objects.requireNonNull(maxRuleLimitSetting));
if (queryRuleset.rules().size() > maxRuleLimit) {
throw new IllegalArgumentException(
"The number of rules in a ruleset cannot exceed ["
+ maxRuleLimit
+ "]."
+ "This maximum can be set by changing the ["
+ QueryRulesConfig.MAX_RULE_LIMIT_SETTING.getKey()
+ "] setting."
);
}
}

public void deleteQueryRuleset(String resourceName, ActionListener<DeleteResponse> listener) {
try {
final DeleteRequest deleteRequest = new DeleteRequest(QUERY_RULES_ALIAS_NAME).id(resourceName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.HeaderWarning;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryRewriteContext;
Expand Down Expand Up @@ -121,10 +122,12 @@ private RuleQueryBuilder(
// PinnedQueryBuilder will return an error if we attmept to return more than the maximum number of
// pinned hits. Here, we truncate matching rules rather than return an error.
if (pinnedIds != null && pinnedIds.size() > MAX_NUM_PINNED_HITS) {
HeaderWarning.addWarning("Truncating query rule pinned hits to " + MAX_NUM_PINNED_HITS + " documents");
pinnedIds = pinnedIds.subList(0, MAX_NUM_PINNED_HITS);
}

if (pinnedDocs != null && pinnedDocs.size() > MAX_NUM_PINNED_HITS) {
HeaderWarning.addWarning("Truncating query rule pinned hits to " + MAX_NUM_PINNED_HITS + " documents");
pinnedDocs = pinnedDocs.subList(0, MAX_NUM_PINNED_HITS);
}

Expand Down Expand Up @@ -224,7 +227,6 @@ protected QueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) throws
}
QueryRuleset queryRuleset = QueryRuleset.fromXContentBytes(rulesetId, getResponse.getSourceAsBytesRef(), XContentType.JSON);
for (QueryRule rule : queryRuleset.rules()) {
logger.info("Applying rule: " + rule);
rule.applyRule(appliedRules, matchCriteria);
}
pinnedIdsSetOnce.set(appliedRules.pinnedIds().stream().distinct().toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.transport.TransportService;
Expand All @@ -21,9 +22,14 @@ public class TransportDeleteQueryRulesetAction extends HandledTransportAction<De
protected final QueryRulesIndexService systemIndexService;

@Inject
public TransportDeleteQueryRulesetAction(TransportService transportService, ActionFilters actionFilters, Client client) {
public TransportDeleteQueryRulesetAction(
TransportService transportService,
ClusterService clusterService,
ActionFilters actionFilters,
Client client
) {
super(DeleteQueryRulesetAction.NAME, transportService, actionFilters, DeleteQueryRulesetAction.Request::new);
this.systemIndexService = new QueryRulesIndexService(client);
this.systemIndexService = new QueryRulesIndexService(client, clusterService.getClusterSettings());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.transport.TransportService;
Expand All @@ -21,9 +22,14 @@ public class TransportGetQueryRulesetAction extends HandledTransportAction<GetQu
protected final QueryRulesIndexService systemIndexService;

@Inject
public TransportGetQueryRulesetAction(TransportService transportService, ActionFilters actionFilters, Client client) {
public TransportGetQueryRulesetAction(
TransportService transportService,
ClusterService clusterService,
ActionFilters actionFilters,
Client client
) {
super(GetQueryRulesetAction.NAME, transportService, actionFilters, GetQueryRulesetAction.Request::new);
this.systemIndexService = new QueryRulesIndexService(client);
this.systemIndexService = new QueryRulesIndexService(client, clusterService.getClusterSettings());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.transport.TransportService;
Expand All @@ -23,9 +24,14 @@ public class TransportListQueryRulesetsAction extends HandledTransportAction<
protected final QueryRulesIndexService systemIndexService;

@Inject
public TransportListQueryRulesetsAction(TransportService transportService, ActionFilters actionFilters, Client client) {
public TransportListQueryRulesetsAction(
TransportService transportService,
ClusterService clusterService,
ActionFilters actionFilters,
Client client
) {
super(ListQueryRulesetsAction.NAME, transportService, actionFilters, ListQueryRulesetsAction.Request::new);
this.systemIndexService = new QueryRulesIndexService(client);
this.systemIndexService = new QueryRulesIndexService(client, clusterService.getClusterSettings());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.transport.TransportService;
Expand All @@ -21,9 +22,14 @@ public class TransportPutQueryRulesetAction extends HandledTransportAction<PutQu
protected final QueryRulesIndexService systemIndexService;

@Inject
public TransportPutQueryRulesetAction(TransportService transportService, ActionFilters actionFilters, Client client) {
public TransportPutQueryRulesetAction(
TransportService transportService,
ClusterService clusterService,
ActionFilters actionFilters,
Client client
) {
super(PutQueryRulesetAction.NAME, transportService, actionFilters, PutQueryRulesetAction.Request::new);
this.systemIndexService = new QueryRulesIndexService(client);
this.systemIndexService = new QueryRulesIndexService(client, clusterService.getClusterSettings());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.application.rules;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

public class QueryRulesConfigTests extends ESTestCase {

public void testDefaultConfig() {
int maxRules = QueryRulesConfig.MAX_RULE_LIMIT_SETTING.get(Settings.EMPTY);
assertThat(maxRules, equalTo(100));
}

public void testCustomQueryRulesConfigMaxRulesPerRuleset() {
int customMaxRules = randomIntBetween(1, 1000);
Settings settings = createCustomSettings("max_rules_per_ruleset", Integer.toString(customMaxRules));
int maxRules = QueryRulesConfig.MAX_RULE_LIMIT_SETTING.get(settings);
assertThat(customMaxRules, equalTo(maxRules));
}

public void testCustomQueryRulesConfigMaxRulesPerRulesetTooHigh() {
int customMaxRules = randomIntBetween(1001, Integer.MAX_VALUE);
Settings settings = createCustomSettings("max_rules_per_ruleset", Integer.toString(customMaxRules));
Exception e = expectThrows(IllegalArgumentException.class, () -> QueryRulesConfig.MAX_RULE_LIMIT_SETTING.get(settings));
assertThat(e.getMessage(), containsString("[xpack.applications.rules.max_rules_per_ruleset] must be <= 1000"));
}

public void testCustomQueryRulesConfigMaxRulesPerRulesetTooLow() {
int maxRules = randomIntBetween(Integer.MIN_VALUE, 0);
Settings settings = createCustomSettings("max_rules_per_ruleset", Integer.toString(maxRules));
Exception e = expectThrows(IllegalArgumentException.class, () -> QueryRulesConfig.MAX_RULE_LIMIT_SETTING.get(settings));
assertThat(e.getMessage(), containsString("[xpack.applications.rules.max_rules_per_ruleset] must be >= 1"));
}

private static Settings createCustomSettings(String key, String value) {
key = QueryRulesConfig.SETTING_ROOT_PATH + "." + key;
return Settings.builder().put(key, value).build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.indices.SystemIndexDescriptor;
import org.elasticsearch.plugins.Plugin;
Expand All @@ -24,6 +26,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
Expand All @@ -40,7 +43,10 @@ public class QueryRulesIndexServiceTests extends ESSingleNodeTestCase {

@Before
public void setup() {
this.queryRulesIndexService = new QueryRulesIndexService(client());
Set<Setting<?>> settingsSet = ClusterSettings.BUILT_IN_CLUSTER_SETTINGS;
settingsSet.addAll(QueryRulesConfig.getSettings());
ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, settingsSet);
this.queryRulesIndexService = new QueryRulesIndexService(client(), clusterSettings);
}

@Override
Expand Down

0 comments on commit 254391b

Please sign in to comment.