Skip to content

[WLM] introduce rule cardinality check #18663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Add support for search pipeline in search and msearch template ([#18564](https://github.com/opensearch-project/OpenSearch/pull/18564))
- Add BooleanQuery rewrite moving constant-scoring must clauses to filter clauses ([#18510](https://github.com/opensearch-project/OpenSearch/issues/18510))
- Add support for non-timing info in profiler ([#18460](https://github.com/opensearch-project/OpenSearch/issues/18460))
- Add the configurable limit on rule cardinality ([#18663](https://github.com/opensearch-project/OpenSearch/pull/18663))

### Changed
- Update Subject interface to use CheckedRunnable ([#18570](https://github.com/opensearch-project/OpenSearch/issues/18570))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ public interface RuleQueryMapper<T> {
* @return
*/
T from(GetRuleRequest request);

/**
* This method returns the cardinality query for the rule, this query should
* be constructed in such a way that it can be used to calculate the cardinality of the rules
* @return
*/
T getCardinalityQuery();
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@
import org.opensearch.action.support.clustermanager.AcknowledgedResponse;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.settings.Setting;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.index.engine.DocumentMissingException;
import org.opensearch.index.query.QueryBuilder;
Expand Down Expand Up @@ -52,9 +54,24 @@
* @opensearch.experimental
*/
public class IndexStoredRulePersistenceService implements RulePersistenceService {
// Default value for max rules count
public static final int MAX_ALLOWED_RULE_COUNT = 10000;

// max wlm rules setting name
public static final String MAX_RULES_COUNT_SETTING_NAME = "wlm.autotagging.max_rules";

// max wlm rules setting
public static final Setting<Integer> MAX_WLM_RULES_SETTING = Setting.intSetting(
MAX_RULES_COUNT_SETTING_NAME,
MAX_ALLOWED_RULE_COUNT,
10,
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
/**
* The system index name used for storing rules
*/
private int maxAllowedRulesCount;
private final String indexName;
private final Client client;
private final ClusterService clusterService;
Expand Down Expand Up @@ -87,6 +104,12 @@ public IndexStoredRulePersistenceService(
this.maxRulesPerPage = maxRulesPerPage;
this.parser = parser;
this.queryBuilder = queryBuilder;
this.maxAllowedRulesCount = MAX_WLM_RULES_SETTING.get(clusterService.getSettings());
clusterService.getClusterSettings().addSettingsUpdateConsumer(MAX_WLM_RULES_SETTING, this::setMaxAllowedRules);
}

private void setMaxAllowedRules(int maxAllowedRules) {
this.maxAllowedRulesCount = maxAllowedRules;
}

/**
Expand All @@ -101,12 +124,27 @@ public void createRule(CreateRuleRequest request, ActionListener<CreateRuleRespo
logger.error("Index {} does not exist", indexName);
listener.onFailure(new IllegalStateException("Index" + indexName + " does not exist"));
} else {
performCardinalityCheck(listener);
Rule rule = request.getRule();
validateNoDuplicateRule(rule, ActionListener.wrap(unused -> persistRule(rule, listener), listener::onFailure));
}
}
}

private void performCardinalityCheck(ActionListener<CreateRuleResponse> listener) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(queryBuilder.getCardinalityQuery()).get();
if (searchResponse.getHits().getTotalHits() != null && searchResponse.getHits().getTotalHits().value() >= maxAllowedRulesCount) {
listener.onFailure(
new OpenSearchRejectedExecutionException(
"This create operation will violate"
+ " the cardinality limit of "
+ MAX_ALLOWED_RULE_COUNT
+ ". Please delete some stale or redundant rules first"
)
);
}
}

/**
* Validates that no existing rule has the same attribute map as the given rule.
* This validation must be performed one at a time to prevent writing duplicate rules.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,9 @@ public QueryBuilder from(GetRuleRequest request) {
}
return boolQuery;
}

@Override
public QueryBuilder getCardinalityQuery() {
return QueryBuilders.matchAllQuery();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@
import org.opensearch.cluster.metadata.Metadata;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.action.ActionFuture;
import org.opensearch.common.settings.ClusterSettings;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException;
import org.opensearch.core.index.shard.ShardId;
import org.opensearch.index.engine.DocumentMissingException;
import org.opensearch.index.query.QueryBuilder;
Expand All @@ -50,6 +52,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -99,6 +102,11 @@ public void setUp() throws Exception {
client = setUpMockClient(searchRequestBuilder);
rule = mock(Rule.class);
clusterService = mock(ClusterService.class);
Settings testSettings = Settings.EMPTY;
ClusterSettings clusterSettings = new ClusterSettings(testSettings, new HashSet<>());
when(clusterService.getSettings()).thenReturn(testSettings);
clusterSettings.registerSetting(IndexStoredRulePersistenceService.MAX_WLM_RULES_SETTING);
when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
ClusterState clusterState = mock(ClusterState.class);
Metadata metadata = mock(Metadata.class);
when(clusterService.state()).thenReturn(clusterState);
Expand All @@ -109,6 +117,7 @@ public void setUp() throws Exception {
queryBuilder = mock(QueryBuilder.class);
when(queryBuilder.filter(any())).thenReturn(queryBuilder);
when(ruleQueryMapper.from(any(GetRuleRequest.class))).thenReturn(queryBuilder);
when(ruleQueryMapper.getCardinalityQuery()).thenReturn(mock(QueryBuilder.class));
when(ruleEntityParser.parse(anyString())).thenReturn(rule);

rulePersistenceService = new IndexStoredRulePersistenceService(
Expand Down Expand Up @@ -144,6 +153,25 @@ public void testCreateRuleOnExistingIndex() throws Exception {
assertNotNull(responseCaptor.getValue().getRule());
}

public void testCardinalityCheckBasedFailure() throws Exception {
CreateRuleRequest createRuleRequest = mock(CreateRuleRequest.class);
when(createRuleRequest.getRule()).thenReturn(rule);
when(rule.toXContent(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));

SearchResponse searchResponse = mock(SearchResponse.class);
when(searchResponse.getHits()).thenReturn(
new SearchHits(new SearchHit[] {}, new TotalHits(10000, TotalHits.Relation.EQUAL_TO), 1.0f)
);
when(searchRequestBuilder.get()).thenReturn(searchResponse);

ActionListener<CreateRuleResponse> listener = mock(ActionListener.class);
rulePersistenceService.createRule(createRuleRequest, listener);

ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(OpenSearchRejectedExecutionException.class);
verify(listener).onFailure(exceptionCaptor.capture());
assertNotNull(exceptionCaptor.getValue());
}

public void testConcurrentCreateDuplicateRules() throws InterruptedException {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
int threadCount = 10;
Expand Down
Loading