Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,7 @@ protected static boolean isXPackTemplate(String name) {
case "metrics":
case "metrics-settings":
case "metrics-mappings":
case ".snapshots":
return true;
default:
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ public static Map<String, String> filterSecurityHeaders(Map<String, String> head
public static final String ASYNC_SEARCH_ORIGIN = "async_search";
public static final String IDP_ORIGIN = "idp";
public static final String STACK_ORIGIN = "stack";
public static final String SEARCHABLE_SNAPSHOTS_ORIGIN = "searchable_snapshots";

private ClientHelper() {}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"index_patterns": [
".snapshots-${xpack.searchable_snapshots.template.version}"
],
"priority": 100,
"version": ${xpack.searchable_snapshots.template.version},
"template": {
"aliases": {
".snapshots": {}
},
"settings": {
Copy link
Member

Choose a reason for hiding this comment

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

Should .snapshots indices also have index.hidden: true set in their settings? (I can't remember right now whether dot-prefixed indices automatically are hidden)

"number_of_shards": 1,
"number_of_replicas": 0,
"auto_expand_replicas": "0-1",
"hidden": true
},
"mappings": {
"_doc": {
"_meta": {
"searchable-snapshot-version": "${xpack.searchable_snapshots.version}"
},
"dynamic": false,
"properties": {
}
}
}
},
"_meta": {
"description": "default index template for searchable snapshots cache installed by x-pack",
"managed": true
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ public Collection<Object> createComponents(
final Supplier<RepositoriesService> repositoriesServiceSupplier
) {
if (SEARCHABLE_SNAPSHOTS_FEATURE_ENABLED) {
SearchableSnapshotsTemplateRegistry.register(settings, clusterService, threadPool, client, xContentRegistry);
final CacheService cacheService = new CacheService(new NodeEnvironmentCacheCleaner(nodeEnvironment), settings);
this.cacheService.set(cacheService);
this.repositoriesServiceSupplier = repositoriesServiceSupplier;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.searchablesnapshots;

import org.elasticsearch.Version;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.template.IndexTemplateConfig;
import org.elasticsearch.xpack.core.template.IndexTemplateRegistry;

import java.util.List;
import java.util.Map;

import static org.elasticsearch.xpack.core.ClientHelper.SEARCHABLE_SNAPSHOTS_ORIGIN;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsConstants.SEARCHABLE_SNAPSHOTS_FEATURE_ENABLED;

public class SearchableSnapshotsTemplateRegistry extends IndexTemplateRegistry {

// history (please add a comment why you increased the version here)
// version 1: initial
static final int INDEX_TEMPLATE_VERSION = 1;

static final String SNAPSHOTS_CACHE_TEMPLATE_NAME = ".snapshots";
Copy link
Contributor

Choose a reason for hiding this comment

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

Could we call this something more specific, e.g. .snapshot-blob-cache? I worry that we might want to introduce other snapshot-related system indices in future, so the choice of a generic name now will result in confusion and/or a painful migration later.


private SearchableSnapshotsTemplateRegistry(
Settings nodeSettings,
ClusterService clusterService,
ThreadPool threadPool,
Client client,
NamedXContentRegistry xContentRegistry
) {
super(nodeSettings, clusterService, threadPool, client, xContentRegistry);
}

public static SearchableSnapshotsTemplateRegistry register(
Settings nodeSettings,
ClusterService clusterService,
ThreadPool threadPool,
Client client,
NamedXContentRegistry xContentRegistry
) {
// registers a cluster state listener
return new SearchableSnapshotsTemplateRegistry(nodeSettings, clusterService, threadPool, client, xContentRegistry);
}

@Override
protected String getOrigin() {
return SEARCHABLE_SNAPSHOTS_ORIGIN;
}

@Override
protected boolean requiresMasterNode() {
return true;
}

@Override
protected List<IndexTemplateConfig> getComposableTemplateConfigs() {
if (SEARCHABLE_SNAPSHOTS_FEATURE_ENABLED) {
return List.of(
new IndexTemplateConfig(
SNAPSHOTS_CACHE_TEMPLATE_NAME,
"/searchable-snapshots-template.json",
INDEX_TEMPLATE_VERSION,
"xpack.searchable_snapshots.template.version",
Map.of("xpack.searchable_snapshots.version", Version.CURRENT.toString())
)
);
}
return List.of();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryRequest;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
Expand Down Expand Up @@ -39,6 +40,8 @@

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;

public abstract class AbstractSearchableSnapshotsRestTestCase extends ESRestTestCase {
Expand Down Expand Up @@ -210,6 +213,20 @@ public void testClearCache() throws Exception {
});
}

public void testTemplate() throws Exception {
runSearchableSnapshotsTest((restoredIndexName, numDocs) -> {
final Map<String, Object> indexTemplate = indexTemplate(SearchableSnapshotsTemplateRegistry.SNAPSHOTS_CACHE_TEMPLATE_NAME);
assertThat("Expected searchable snapshots index template to exist", indexTemplate, notNullValue());
assertThat(extractValue(indexTemplate, "name"), equalTo(SearchableSnapshotsTemplateRegistry.SNAPSHOTS_CACHE_TEMPLATE_NAME));
assertThat(
extractValue(indexTemplate, "index_template.version"),
equalTo(SearchableSnapshotsTemplateRegistry.INDEX_TEMPLATE_VERSION)
);
final Version version = Version.fromString(extractValue(indexTemplate, "template.mappings._meta.searchable-snapshot-version"));
assertThat("Searchable snapshots index template plugin version is not up to date", version, equalTo(Version.CURRENT));
});
}

private void clearCache(String restoredIndexName) throws IOException {
final Request request = new Request(HttpPost.METHOD_NAME, restoredIndexName + "/_searchable_snapshots/cache/clear");
assertOK(client().performRequest(request));
Expand Down Expand Up @@ -406,6 +423,22 @@ protected static Map<String, Object> indexSettings(String index) throws IOExcept
return extractValue(responseAsMap(response), index + ".settings");
}

protected static Map<String, Object> indexTemplate(String template) throws IOException {
final Response response = client().performRequest(new Request(HttpGet.METHOD_NAME, "/_index_template/" + template));
assertThat(
"Failed to get index template [" + template + "]: " + response,
response.getStatusLine().getStatusCode(),
equalTo(RestStatus.OK.getStatus())
);
final List<?> indexTemplates = extractValue(responseAsMap(response), "index_templates");
assertThat(indexTemplates, notNullValue());
assertThat(indexTemplates, hasSize(greaterThanOrEqualTo(1)));

@SuppressWarnings("unchecked")
final Map<String, Object> indexTemplate = (Map<String, Object>) indexTemplates.get(0);
return indexTemplate;
}

protected static Map<String, Object> responseAsMap(Response response) throws IOException {
final XContentType xContentType = XContentType.fromMediaTypeOrFormat(response.getEntity().getContentType().getValue());
assertThat("Unknown XContentType", xContentType, notNullValue());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.searchablesnapshots;

import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.admin.indices.template.put.PutComposableIndexTemplateAction;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.ComposableIndexTemplate;
import org.elasticsearch.cluster.metadata.IndexTemplateMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.metadata.Template;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ClusterServiceUtils;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.client.NoOpClient;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;

import static java.util.Collections.emptyMap;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsTemplateRegistry.INDEX_TEMPLATE_VERSION;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsTemplateRegistry.SNAPSHOTS_CACHE_TEMPLATE_NAME;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

public class SearchableSnapshotsTemplateRegistryTests extends ESTestCase {

private void executeTest(
final ClusterState.Builder clusterState,
final BiFunction<ActionType<?>, ActionRequest, ActionResponse> consumer
) {
final ThreadPool threadPool = new TestThreadPool(getTestName());
try (ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool)) {
final NoOpClient client = new NoOpClient(threadPool) {
@Override
@SuppressWarnings("unchecked")
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
try {
listener.onResponse((Response) consumer.apply(action, request));
} catch (Exception e) {
listener.onFailure(e);
}
}
};

SearchableSnapshotsTemplateRegistry.register(Settings.EMPTY, clusterService, threadPool, client, xContentRegistry());
ClusterServiceUtils.setState(clusterService, clusterState);
} catch (Exception e) {
throw new AssertionError("", e);
} finally {
terminate(threadPool);
}
}

public void testTemplateDoesNotExist() throws Exception {
final ClusterState.Builder clusterState = newEmptyClusterState();

final PlainActionFuture<PutComposableIndexTemplateAction.Request> executed = PlainActionFuture.newFuture();
executeTest(clusterState, (action, request) -> {
if (action instanceof PutComposableIndexTemplateAction) {
assertThat(request, instanceOf(PutComposableIndexTemplateAction.Request.class));
executed.onResponse((PutComposableIndexTemplateAction.Request) request);
return new AcknowledgedResponse(true);
} else {
executed.onFailure(unsupportedAction(action));
return new AcknowledgedResponse(false);
}
});

assertComposableIndexTemplateRequest(executed.get());
}

public void testTemplateAlreadyExists() {
final ClusterState.Builder clusterState = newEmptyClusterState();
clusterState.metadata(
Metadata.builder()
.put(
".snapshots",
new ComposableIndexTemplate(
List.of(".snapshots-0"),
new Template(Settings.EMPTY, null, Map.of(".snapshots", AliasMetadata.builder(".snapshots").build())),
null,
123L,
1L,
emptyMap()
)
)
.build()
);

final AtomicBoolean executed = new AtomicBoolean(false);
executeTest(clusterState, (action, request) -> {
executed.set(true);
fail("Index template should not be created");
return null;
});
assertThat(executed.get(), is(false));
}

public void testTemplateShouldBeUpdated() throws Exception {
final ClusterState.Builder clusterState = newEmptyClusterState();
clusterState.metadata(
Metadata.builder()
.put(
IndexTemplateMetadata.builder(".snapshots")
.patterns(List.of(randomAlphaOfLength(10)))
.version(randomBoolean() ? 0 : null) // old or non-existent version
.putAlias(AliasMetadata.builder(randomAlphaOfLength(10)).build())
.build()
)
.build()
);

final PlainActionFuture<PutComposableIndexTemplateAction.Request> executed = PlainActionFuture.newFuture();
executeTest(clusterState, (action, request) -> {
if (action instanceof PutComposableIndexTemplateAction) {
assertThat(request, instanceOf(PutComposableIndexTemplateAction.Request.class));
executed.onResponse((PutComposableIndexTemplateAction.Request) request);
return new AcknowledgedResponse(true);
} else {
executed.onFailure(unsupportedAction(action));
return new AcknowledgedResponse(false);
}
});

assertComposableIndexTemplateRequest(executed.get());
}

public void testThatMissingMasterNodeDoesNothing() {
final ClusterState.Builder clusterState = newEmptyClusterState();
clusterState.nodes(DiscoveryNodes.builder(clusterState.nodes()).masterNodeId(null));

final AtomicBoolean executed = new AtomicBoolean(false);
executeTest(clusterState, (action, request) -> {
executed.set(true);
fail("if the master is missing nothing should happen");
return null;
});
assertThat(clusterState.build().nodes().getMasterNode(), nullValue());
assertThat(executed.get(), is(false));
}

private static void assertComposableIndexTemplateRequest(final PutComposableIndexTemplateAction.Request templateRequest) {
assertThat(templateRequest.name(), equalTo(SNAPSHOTS_CACHE_TEMPLATE_NAME));
final ComposableIndexTemplate indexTemplate = templateRequest.indexTemplate();
assertThat(indexTemplate.version(), equalTo((long) INDEX_TEMPLATE_VERSION));
assertThat(indexTemplate.indexPatterns(), hasItem(equalTo(SNAPSHOTS_CACHE_TEMPLATE_NAME + "-" + INDEX_TEMPLATE_VERSION)));
assertThat(indexTemplate.indexPatterns(), hasSize(1));
final List<String> aliases = new ArrayList<>(indexTemplate.template().aliases().keySet());
assertThat(aliases, hasItem(equalTo(SNAPSHOTS_CACHE_TEMPLATE_NAME)));
assertThat(aliases, hasSize(1));
}

private Exception unsupportedAction(ActionType<?> action) {
return new UnsupportedOperationException("The test [" + getTestName() + " ] does not support action [" + action.name() + ']');
}

private ClusterState.Builder newEmptyClusterState() {
final DiscoveryNode node = new DiscoveryNode(randomAlphaOfLength(10), buildNewFakeTransportAddress(), Version.CURRENT);
return ClusterState.builder(new ClusterName(getTestName()))
.version(0L)
.nodes(DiscoveryNodes.builder().add(node).localNodeId(node.getId()).masterNodeId(node.getId()));
}
}
Loading