Skip to content
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

[Rollup] Disallow index patterns that match rollup indices #30491

Merged
merged 5 commits into from
Jun 5, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContent;
Expand Down Expand Up @@ -173,7 +174,7 @@ public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params par
builder.endObject();
return builder;
}

@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(id);
Expand Down Expand Up @@ -336,6 +337,17 @@ public RollupJobConfig build() {
if (indexPattern == null || indexPattern.isEmpty()) {
throw new IllegalArgumentException("An index pattern is mandatory.");
}
if (Regex.isMatchAllPattern(indexPattern)) {
throw new IllegalArgumentException("Index pattern must not match all indices (as it would match it's own rollup index");
}
if (Regex.isSimpleMatchPattern(indexPattern)) {
if (Regex.simpleMatch(indexPattern, rollupIndex)) {
throw new IllegalArgumentException("Index pattern would match rollup index name which is not allowed.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch !

}
}
if (indexPattern.equals(rollupIndex)) {
throw new IllegalArgumentException("Rollup index may not be the same as the index pattern.");
}
if (rollupIndex == null || rollupIndex.isEmpty()) {
throw new IllegalArgumentException("A rollup index name is mandatory.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesRequest;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
Expand All @@ -44,10 +45,12 @@
import org.elasticsearch.xpack.core.XPackField;
import org.elasticsearch.xpack.core.rollup.RollupField;
import org.elasticsearch.xpack.core.rollup.action.PutRollupJobAction;
import org.elasticsearch.xpack.core.rollup.action.RollupJobCaps;
import org.elasticsearch.xpack.core.rollup.job.RollupJob;
import org.elasticsearch.xpack.core.rollup.job.RollupJobConfig;
import org.elasticsearch.xpack.rollup.Rollup;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -91,9 +94,16 @@ protected void masterOperation(PutRollupJobAction.Request request, ClusterState
return;
}

// Check to see if the index pattern matches any existing rollup indices
ActionRequestValidationException validationException = validateIndexPattern(request, clusterState);
if (validationException != null) {
listener.onFailure(validationException);
return;
}

FieldCapabilitiesRequest fieldCapsRequest = new FieldCapabilitiesRequest()
.indices(request.getConfig().getIndexPattern())
.fields(request.getConfig().getAllFields().toArray(new String[0]));
.indices(request.getConfig().getIndexPattern())
.fields(request.getConfig().getAllFields().toArray(new String[0]));

client.fieldCaps(fieldCapsRequest, new ActionListener<FieldCapabilitiesResponse>() {
@Override
Expand All @@ -115,6 +125,26 @@ public void onFailure(Exception e) {
});
}

/**
* Ensure that the index pattern doesn't match any pre-existing rollup indices. We don't need to check
* if the pattern would match it's own rollup index because the request already validated that.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can be less strict and only forbid mixing rollup and non-rollup indices in the same pattern ?
It should be fine to create the job if the pattern matches rollup indices only. Although I wonder if the problem of mixing indices (rollup and non-rollup) is not caught by the field validation. As you mentioned they have different field names so the validation of field names should fail all the time ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point about the field name validation, although i'm still a bit worried about unintended consequences of matching against a rollup index. Barring the "rollup a rollup" usecase, it doesn't seem wise to let users match against an existing rollup if we can help it?

But maybe it's not worth the extra complexity? If it matches another rollup index, that index will exist so we can validate against the fields and it should throw an exception. It also doesn't protect against future rollup indices from matching the defined pattern, so we'd be relying on field level validation there anyway.

I think I'm convinced. Will make the changes, should simplify the PR a bunch :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, it turns out to be a bit more complicated. The field-level validation is broken, due to how field caps behaves.

Field caps only tells you the caps for the fields that match, in the resolved indices. But it doesn't tell you about the indices that were resolved but didn't match any field. So we won't know the index pattern matched some random index without the correct fields.

That's unrelated to this change to this PR, but needs to be fixed for us to simplify. Going to see what it takes, we may have to manually resolve the indices anyway to check. Will keep you updated.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. We can also add the matching indices in field caps's response. Could be per field : the list of index that doesn't have a definition for the field or global: the list of indices that match the pattern and then you can infer which index is missing from the field's response. I think it's a valid feature to add even if we don't use it in rollups.

private static ActionRequestValidationException validateIndexPattern(PutRollupJobAction.Request request, ClusterState clusterState) {
IndexNameExpressionResolver resolver = new IndexNameExpressionResolver(Settings.EMPTY);
String[] indices = resolver.concreteIndexNames(clusterState, IndicesOptions.strictExpandOpenAndForbidClosed(),
request.getConfig().getIndexPattern());

ActionRequestValidationException validationException = new ActionRequestValidationException();

Arrays.stream(indices)
.forEach(index -> TransportGetRollupCapsAction.findRollupIndexCaps(index, clusterState.getMetaData().index(index))
.ifPresent(c -> validationException
.addValidationError("Index pattern [" + request.getConfig().getIndexPattern() + "] matches existing rollup index ["
+ index + "] from jobs " + c.getJobCaps().stream().map(RollupJobCaps::getJobID).collect(Collectors.toList()))));

return validationException.validationErrors().size() > 0 ? validationException : null;
}

private static RollupJob createRollupJob(RollupJobConfig config, ThreadPool threadPool) {
// ensure we only filter for the allowed headers
Map<String, String> filteredHeaders = threadPool.getThreadContext().getHeaders().entrySet().stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,37 @@ public void testEmptyIndexPattern() {
assertThat(e.getMessage(), equalTo("An index pattern is mandatory."));
}

public void testMatchAllIndexPattern() {
RollupJobConfig.Builder job = ConfigTestHelpers.getRollupJob("foo");
job.setIndexPattern("*");
Exception e = expectThrows(IllegalArgumentException.class, job::build);
assertThat(e.getMessage(), equalTo("Index pattern must not match all indices (as it would match it's own rollup index"));
}

public void testMatchOwnRollupPatternPrefix() {
RollupJobConfig.Builder job = ConfigTestHelpers.getRollupJob("foo");
job.setIndexPattern("foo-*");
job.setRollupIndex("foo-rollup");
Exception e = expectThrows(IllegalArgumentException.class, job::build);
assertThat(e.getMessage(), equalTo("Index pattern would match rollup index name which is not allowed."));
}

public void testMatchOwnRollupPatternSuffix() {
RollupJobConfig.Builder job = ConfigTestHelpers.getRollupJob("foo");
job.setIndexPattern("*-rollup");
job.setRollupIndex("foo-rollup");
Exception e = expectThrows(IllegalArgumentException.class, job::build);
assertThat(e.getMessage(), equalTo("Index pattern would match rollup index name which is not allowed."));
}

public void testIndexPatternIdenticalToRollup() {
RollupJobConfig.Builder job = ConfigTestHelpers.getRollupJob("foo");
job.setIndexPattern("foo");
job.setRollupIndex("foo");
Exception e = expectThrows(IllegalArgumentException.class, job::build);
assertThat(e.getMessage(), equalTo("Rollup index may not be the same as the index pattern."));
}

public void testEmptyRollupIndex() {
RollupJobConfig.Builder job = ConfigTestHelpers.getRollupJob("foo");
job.setRollupIndex("");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,5 +159,58 @@ setup:
]
}

---
"Index pattern matches existing rollup index":

- do:
headers:
Authorization: "Basic eF9wYWNrX3Jlc3RfdXNlcjp4LXBhY2stdGVzdC1wYXNzd29yZA==" # run as x_pack_rest_user, i.e. the test setup superuser
xpack.rollup.put_job:
id: foo
body: >
{
"index_pattern": "foo",
"rollup_index": "foo_rollup",
"cron": "*/30 * * * * ?",
"page_size" :10,
"groups" : {
"date_histogram": {
"field": "the_field",
"interval": "1h"
}
},
"metrics": [
{
"field": "value_field",
"metrics": ["min", "max", "sum"]
}
]
}
- is_true: acknowledged

- do:
catch: /Index pattern \[foo\*\] matches existing rollup index \[foo_rollup\] from jobs \[foo\]/
headers:
Authorization: "Basic eF9wYWNrX3Jlc3RfdXNlcjp4LXBhY2stdGVzdC1wYXNzd29yZA==" # run as x_pack_rest_user, i.e. the test setup superuser
xpack.rollup.put_job:
id: foo2
body: >
{
"index_pattern": "foo*",
"rollup_index": "some_index",
"cron": "*/30 * * * * ?",
"page_size" :10,
"groups" : {
"date_histogram": {
"field": "the_field",
"interval": "1h"
}
},
"metrics": [
{
"field": "value_field",
"metrics": ["min", "max", "sum"]
}
]
}