Search in sources :

Example 1 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project OpenSearch by opensearch-project.

the class WildflyIT method testRestClient.

public void testRestClient() throws URISyntaxException, IOException {
    final String baseUrl = buildBaseUrl();
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final String endpoint = baseUrl + "/employees/1";
        logger.info("Connecting to uri: " + baseUrl);
        final HttpPut put = new HttpPut(new URI(endpoint));
        final String body = "{" + "  \"first_name\": \"John\"," + "  \"last_name\": \"Smith\"," + "  \"age\": 25," + "  \"about\": \"I love to go rock climbing\"," + "  \"interests\": [" + "    \"sports\"," + "    \"music\"" + "  ]" + "}";
        put.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = client.execute(put)) {
            int status = response.getStatusLine().getStatusCode();
            assertThat("expected a 201 response but got: " + status + " - body: " + EntityUtils.toString(response.getEntity()), status, equalTo(201));
        }
        logger.info("Fetching resource at " + endpoint);
        final HttpGet get = new HttpGet(new URI(endpoint));
        try (CloseableHttpResponse response = client.execute(get);
            XContentParser parser = JsonXContent.jsonXContent.createParser(new NamedXContentRegistry(ClusterModule.getNamedXWriteables()), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, response.getEntity().getContent())) {
            final Map<String, Object> map = parser.map();
            assertThat(map.get("first_name"), equalTo("John"));
            assertThat(map.get("last_name"), equalTo("Smith"));
            assertThat(map.get("age"), equalTo(25));
            assertThat(map.get("about"), equalTo("I love to go rock climbing"));
            final Object interests = map.get("interests");
            assertThat(interests, instanceOf(List.class));
            @SuppressWarnings("unchecked") final List<String> interestsAsList = (List<String>) interests;
            assertThat(interestsAsList, containsInAnyOrder("sports", "music"));
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) URI(java.net.URI) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) List(java.util.List) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 2 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project OpenSearch by opensearch-project.

the class BlobStoreRepository method writeUpdatedShardMetaDataAndComputeDeletes.

// updates the shard state metadata for shards of a snapshot that is to be deleted. Also computes the files to be cleaned up.
private void writeUpdatedShardMetaDataAndComputeDeletes(Collection<SnapshotId> snapshotIds, RepositoryData oldRepositoryData, boolean useUUIDs, ActionListener<Collection<ShardSnapshotMetaDeleteResult>> onAllShardsCompleted) {
    final Executor executor = threadPool.executor(ThreadPool.Names.SNAPSHOT);
    final List<IndexId> indices = oldRepositoryData.indicesToUpdateAfterRemovingSnapshot(snapshotIds);
    if (indices.isEmpty()) {
        onAllShardsCompleted.onResponse(Collections.emptyList());
        return;
    }
    // Listener that flattens out the delete results for each index
    final ActionListener<Collection<ShardSnapshotMetaDeleteResult>> deleteIndexMetadataListener = new GroupedActionListener<>(ActionListener.map(onAllShardsCompleted, res -> res.stream().flatMap(Collection::stream).collect(Collectors.toList())), indices.size());
    for (IndexId indexId : indices) {
        final Set<SnapshotId> survivingSnapshots = oldRepositoryData.getSnapshots(indexId).stream().filter(id -> snapshotIds.contains(id) == false).collect(Collectors.toSet());
        final StepListener<Collection<Integer>> shardCountListener = new StepListener<>();
        final Collection<String> indexMetaGenerations = snapshotIds.stream().map(id -> oldRepositoryData.indexMetaDataGenerations().indexMetaBlobId(id, indexId)).collect(Collectors.toSet());
        final ActionListener<Integer> allShardCountsListener = new GroupedActionListener<>(shardCountListener, indexMetaGenerations.size());
        final BlobContainer indexContainer = indexContainer(indexId);
        for (String indexMetaGeneration : indexMetaGenerations) {
            executor.execute(ActionRunnable.supply(allShardCountsListener, () -> {
                try {
                    return INDEX_METADATA_FORMAT.read(indexContainer, indexMetaGeneration, namedXContentRegistry).getNumberOfShards();
                } catch (Exception ex) {
                    logger.warn(() -> new ParameterizedMessage("[{}] [{}] failed to read metadata for index", indexMetaGeneration, indexId.getName()), ex);
                    // ignoring it and letting the cleanup deal with it.
                    return null;
                }
            }));
        }
        shardCountListener.whenComplete(counts -> {
            final int shardCount = counts.stream().mapToInt(i -> i).max().orElse(0);
            if (shardCount == 0) {
                deleteIndexMetadataListener.onResponse(null);
                return;
            }
            // Listener for collecting the results of removing the snapshot from each shard's metadata in the current index
            final ActionListener<ShardSnapshotMetaDeleteResult> allShardsListener = new GroupedActionListener<>(deleteIndexMetadataListener, shardCount);
            for (int shardId = 0; shardId < shardCount; shardId++) {
                final int finalShardId = shardId;
                executor.execute(new AbstractRunnable() {

                    @Override
                    protected void doRun() throws Exception {
                        final BlobContainer shardContainer = shardContainer(indexId, finalShardId);
                        final Set<String> blobs = shardContainer.listBlobs().keySet();
                        final BlobStoreIndexShardSnapshots blobStoreIndexShardSnapshots;
                        final long newGen;
                        if (useUUIDs) {
                            newGen = -1L;
                            blobStoreIndexShardSnapshots = buildBlobStoreIndexShardSnapshots(blobs, shardContainer, oldRepositoryData.shardGenerations().getShardGen(indexId, finalShardId)).v1();
                        } else {
                            Tuple<BlobStoreIndexShardSnapshots, Long> tuple = buildBlobStoreIndexShardSnapshots(blobs, shardContainer);
                            newGen = tuple.v2() + 1;
                            blobStoreIndexShardSnapshots = tuple.v1();
                        }
                        allShardsListener.onResponse(deleteFromShardSnapshotMeta(survivingSnapshots, indexId, finalShardId, snapshotIds, shardContainer, blobs, blobStoreIndexShardSnapshots, newGen));
                    }

                    @Override
                    public void onFailure(Exception ex) {
                        logger.warn(() -> new ParameterizedMessage("{} failed to delete shard data for shard [{}][{}]", snapshotIds, indexId.getName(), finalShardId), ex);
                        // Just passing null here to count down the listener instead of failing it, the stale data left behind
                        // here will be retried in the next delete or repository cleanup
                        allShardsListener.onResponse(null);
                    }
                });
            }
        }, deleteIndexMetadataListener::onFailure);
    }
}
Also used : Metadata(org.opensearch.cluster.metadata.Metadata) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) ActionListener(org.opensearch.action.ActionListener) IOContext(org.apache.lucene.store.IOContext) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) BlobStoreIndexShardSnapshot(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot) BlockingQueue(java.util.concurrent.BlockingQueue) AbstractLifecycleComponent(org.opensearch.common.component.AbstractLifecycleComponent) Logger(org.apache.logging.log4j.Logger) RepositoryOperation(org.opensearch.repositories.RepositoryOperation) Stream(java.util.stream.Stream) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) BytesArray(org.opensearch.common.bytes.BytesArray) BlobStoreIndexShardSnapshots(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshots) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) StepListener(org.opensearch.action.StepListener) XContentType(org.opensearch.common.xcontent.XContentType) IndexCommit(org.apache.lucene.index.IndexCommit) ThreadPool(org.opensearch.threadpool.ThreadPool) BlobContainer(org.opensearch.common.blobstore.BlobContainer) Releasable(org.opensearch.common.lease.Releasable) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) Numbers(org.opensearch.common.Numbers) SlicedInputStream(org.opensearch.index.snapshots.blobstore.SlicedInputStream) SnapshotException(org.opensearch.snapshots.SnapshotException) Streams(org.opensearch.common.io.Streams) CompressorFactory(org.opensearch.common.compress.CompressorFactory) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) RepositoryCleanupInProgress(org.opensearch.cluster.RepositoryCleanupInProgress) InputStreamIndexInput(org.opensearch.common.lucene.store.InputStreamIndexInput) LongStream(java.util.stream.LongStream) IndexInput(org.apache.lucene.store.IndexInput) SetOnce(org.apache.lucene.util.SetOnce) RepositoriesMetadata(org.opensearch.cluster.metadata.RepositoriesMetadata) Executor(java.util.concurrent.Executor) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) RepositoryMetadata(org.opensearch.cluster.metadata.RepositoryMetadata) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) AtomicLong(java.util.concurrent.atomic.AtomicLong) RepositoryCleanupResult(org.opensearch.repositories.RepositoryCleanupResult) BlobPath(org.opensearch.common.blobstore.BlobPath) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) CounterMetric(org.opensearch.common.metrics.CounterMetric) ShardGenerations(org.opensearch.repositories.ShardGenerations) NoSuchFileException(java.nio.file.NoSuchFileException) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) SnapshotFiles(org.opensearch.index.snapshots.blobstore.SnapshotFiles) SnapshotsService(org.opensearch.snapshots.SnapshotsService) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) XContentParser(org.opensearch.common.xcontent.XContentParser) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) IndexId(org.opensearch.repositories.IndexId) XContentFactory(org.opensearch.common.xcontent.XContentFactory) RepositoryStats(org.opensearch.repositories.RepositoryStats) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) RepositoryException(org.opensearch.repositories.RepositoryException) FileInfo.canonicalName(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot.FileInfo.canonicalName) BytesRef(org.apache.lucene.util.BytesRef) SnapshotId(org.opensearch.snapshots.SnapshotId) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Store(org.opensearch.index.store.Store) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) BlobStore(org.opensearch.common.blobstore.BlobStore) List(java.util.List) Optional(java.util.Optional) BytesReference(org.opensearch.common.bytes.BytesReference) RateLimitingInputStream(org.opensearch.index.snapshots.blobstore.RateLimitingInputStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ActionRunnable(org.opensearch.action.ActionRunnable) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) SnapshotDeletionsInProgress(org.opensearch.cluster.SnapshotDeletionsInProgress) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) FilterInputStream(java.io.FilterInputStream) IndexShardSnapshotStatus(org.opensearch.index.snapshots.IndexShardSnapshotStatus) IndexMetaDataGenerations(org.opensearch.repositories.IndexMetaDataGenerations) UUIDs(org.opensearch.common.UUIDs) StoreFileMetadata(org.opensearch.index.store.StoreFileMetadata) IndexOutput(org.apache.lucene.store.IndexOutput) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) RepositoryData(org.opensearch.repositories.RepositoryData) Setting(org.opensearch.common.settings.Setting) RepositoryShardId(org.opensearch.repositories.RepositoryShardId) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DeleteResult(org.opensearch.common.blobstore.DeleteResult) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) RateLimiter(org.apache.lucene.store.RateLimiter) InputStream(java.io.InputStream) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) Set(java.util.Set) BlobStoreIndexShardSnapshots(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshots) Executor(java.util.concurrent.Executor) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) IndexId(org.opensearch.repositories.IndexId) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) SnapshotException(org.opensearch.snapshots.SnapshotException) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) NoSuchFileException(java.nio.file.NoSuchFileException) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) RepositoryException(org.opensearch.repositories.RepositoryException) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) SnapshotId(org.opensearch.snapshots.SnapshotId) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) BlobContainer(org.opensearch.common.blobstore.BlobContainer) Collection(java.util.Collection) StepListener(org.opensearch.action.StepListener) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Tuple(org.opensearch.common.collect.Tuple)

Example 3 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project OpenSearch by opensearch-project.

the class MetadataIndexTemplateServiceTests method testResolveMappings.

public void testResolveMappings() throws Exception {
    final MetadataIndexTemplateService service = getMetadataIndexTemplateService();
    ClusterState state = ClusterState.EMPTY_STATE;
    ComponentTemplate ct1 = new ComponentTemplate(new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"field1\": {\n" + "          \"type\": \"keyword\"\n" + "        }\n" + "      }\n" + "    }"), null), null, null);
    ComponentTemplate ct2 = new ComponentTemplate(new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"field2\": {\n" + "          \"type\": \"text\"\n" + "        }\n" + "      }\n" + "    }"), null), null, null);
    state = service.addComponentTemplate(state, true, "ct_high", ct1);
    state = service.addComponentTemplate(state, true, "ct_low", ct2);
    ComposableIndexTemplate it = new ComposableIndexTemplate(Arrays.asList("i*"), new Template(null, new CompressedXContent("{\n" + "    \"properties\": {\n" + "      \"field3\": {\n" + "        \"type\": \"integer\"\n" + "      }\n" + "    }\n" + "  }"), null), Arrays.asList("ct_low", "ct_high"), 0L, 1L, null, null);
    state = service.addIndexTemplateV2(state, true, "my-template", it);
    List<CompressedXContent> mappings = MetadataIndexTemplateService.collectMappings(state, "my-template", "my-index");
    assertNotNull(mappings);
    assertThat(mappings.size(), equalTo(3));
    List<Map<String, Object>> parsedMappings = mappings.stream().map(m -> {
        try {
            return MapperService.parseMapping(new NamedXContentRegistry(Collections.emptyList()), m.string());
        } catch (Exception e) {
            logger.error(e);
            fail("failed to parse mappings: " + m.string());
            return null;
        }
    }).collect(Collectors.toList());
    assertThat(parsedMappings.get(0), equalTo(Collections.singletonMap("_doc", Collections.singletonMap("properties", Collections.singletonMap("field2", Collections.singletonMap("type", "text"))))));
    assertThat(parsedMappings.get(1), equalTo(Collections.singletonMap("_doc", Collections.singletonMap("properties", Collections.singletonMap("field1", Collections.singletonMap("type", "keyword"))))));
    assertThat(parsedMappings.get(2), equalTo(Collections.singletonMap("_doc", Collections.singletonMap("properties", Collections.singletonMap("field3", Collections.singletonMap("type", "integer"))))));
}
Also used : Arrays(java.util.Arrays) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) TIMESTAMP_FIELD(org.opensearch.index.mapper.DataStreamFieldMapper.Defaults.TIMESTAMP_FIELD) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) MapperService(org.opensearch.index.mapper.MapperService) Alias(org.opensearch.action.admin.indices.alias.Alias) Settings.builder(org.opensearch.common.settings.Settings.builder) Map(java.util.Map) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) TimeValue(org.opensearch.common.unit.TimeValue) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Index(org.opensearch.index.Index) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) IndicesService(org.opensearch.indices.IndicesService) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) PutRequest(org.opensearch.cluster.metadata.MetadataIndexTemplateService.PutRequest) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ShardLimitValidatorTests.createTestShardLimitService(org.opensearch.indices.ShardLimitValidatorTests.createTestShardLimitService) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.is(org.hamcrest.Matchers.is) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) CompressedXContent(org.opensearch.common.compress.CompressedXContent) CoreMatchers.not(org.hamcrest.CoreMatchers.not) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Matchers.matchesRegex(org.hamcrest.Matchers.matchesRegex) ClusterState(org.opensearch.cluster.ClusterState) Environment(org.opensearch.env.Environment) Matchers.empty(org.hamcrest.Matchers.empty) IOException(java.io.IOException) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) TimeUnit(java.util.concurrent.TimeUnit) SystemIndices(org.opensearch.indices.SystemIndices) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) CoreMatchers.containsStringIgnoringCase(org.hamcrest.CoreMatchers.containsStringIgnoringCase) Collections(java.util.Collections) ClusterState(org.opensearch.cluster.ClusterState) CompressedXContent(org.opensearch.common.compress.CompressedXContent) Map(java.util.Map) HashMap(java.util.HashMap) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) IOException(java.io.IOException) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException)

Example 4 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project OpenSearch by opensearch-project.

the class MetadataIndexTemplateServiceTests method testResolveConflictingMappings.

@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/pull/57393")
public void testResolveConflictingMappings() throws Exception {
    final MetadataIndexTemplateService service = getMetadataIndexTemplateService();
    ClusterState state = ClusterState.EMPTY_STATE;
    ComponentTemplate ct1 = new ComponentTemplate(new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"field2\": {\n" + "          \"type\": \"keyword\"\n" + "        }\n" + "      }\n" + "    }"), null), null, null);
    ComponentTemplate ct2 = new ComponentTemplate(new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"field2\": {\n" + "          \"type\": \"text\"\n" + "        }\n" + "      }\n" + "    }"), null), null, null);
    state = service.addComponentTemplate(state, true, "ct_high", ct1);
    state = service.addComponentTemplate(state, true, "ct_low", ct2);
    ComposableIndexTemplate it = new ComposableIndexTemplate(Collections.singletonList("i*"), new Template(null, new CompressedXContent("{\n" + "    \"properties\": {\n" + "      \"field\": {\n" + "        \"type\": \"keyword\"\n" + "      }\n" + "    }\n" + "  }"), null), Arrays.asList("ct_low", "ct_high"), 0L, 1L, null, null);
    state = service.addIndexTemplateV2(state, true, "my-template", it);
    List<CompressedXContent> mappings = MetadataIndexTemplateService.collectMappings(state, "my-template", "my-index");
    assertNotNull(mappings);
    assertThat(mappings.size(), equalTo(3));
    List<Map<String, Object>> parsedMappings = mappings.stream().map(m -> {
        try {
            return MapperService.parseMapping(new NamedXContentRegistry(Collections.emptyList()), m.string());
        } catch (Exception e) {
            logger.error(e);
            fail("failed to parse mappings: " + m.string());
            return null;
        }
    }).collect(Collectors.toList());
    // The order of mappings should be:
    // - ct_low
    // - ct_high
    // - index template
    // Because the first elements when merging mappings have the lowest precedence
    assertThat(parsedMappings.get(0), equalTo(Collections.singletonMap("_doc", Collections.singletonMap("properties", Collections.singletonMap("field2", Collections.singletonMap("type", "text"))))));
    assertThat(parsedMappings.get(1), equalTo(Collections.singletonMap("_doc", Collections.singletonMap("properties", Collections.singletonMap("field2", Collections.singletonMap("type", "keyword"))))));
    assertThat(parsedMappings.get(2), equalTo(Collections.singletonMap("_doc", Collections.singletonMap("properties", Collections.singletonMap("field", Collections.singletonMap("type", "keyword"))))));
}
Also used : Arrays(java.util.Arrays) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) TIMESTAMP_FIELD(org.opensearch.index.mapper.DataStreamFieldMapper.Defaults.TIMESTAMP_FIELD) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) MapperService(org.opensearch.index.mapper.MapperService) Alias(org.opensearch.action.admin.indices.alias.Alias) Settings.builder(org.opensearch.common.settings.Settings.builder) Map(java.util.Map) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) TimeValue(org.opensearch.common.unit.TimeValue) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Index(org.opensearch.index.Index) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) IndicesService(org.opensearch.indices.IndicesService) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) PutRequest(org.opensearch.cluster.metadata.MetadataIndexTemplateService.PutRequest) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ShardLimitValidatorTests.createTestShardLimitService(org.opensearch.indices.ShardLimitValidatorTests.createTestShardLimitService) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.is(org.hamcrest.Matchers.is) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) CompressedXContent(org.opensearch.common.compress.CompressedXContent) CoreMatchers.not(org.hamcrest.CoreMatchers.not) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Matchers.matchesRegex(org.hamcrest.Matchers.matchesRegex) ClusterState(org.opensearch.cluster.ClusterState) Environment(org.opensearch.env.Environment) Matchers.empty(org.hamcrest.Matchers.empty) IOException(java.io.IOException) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) TimeUnit(java.util.concurrent.TimeUnit) SystemIndices(org.opensearch.indices.SystemIndices) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) CoreMatchers.containsStringIgnoringCase(org.hamcrest.CoreMatchers.containsStringIgnoringCase) Collections(java.util.Collections) ClusterState(org.opensearch.cluster.ClusterState) CompressedXContent(org.opensearch.common.compress.CompressedXContent) Map(java.util.Map) HashMap(java.util.HashMap) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) IOException(java.io.IOException) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException)

Example 5 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project OpenSearch by opensearch-project.

the class NetworkModuleTests method testOverrideDefault.

public void testOverrideDefault() {
    Settings settings = Settings.builder().put(NetworkModule.HTTP_TYPE_SETTING.getKey(), "custom").put(NetworkModule.HTTP_DEFAULT_TYPE_SETTING.getKey(), "default_custom").put(NetworkModule.TRANSPORT_DEFAULT_TYPE_SETTING.getKey(), "local").put(NetworkModule.TRANSPORT_TYPE_KEY, "default_custom").build();
    // content doesn't matter we check reference equality
    Supplier<Transport> customTransport = () -> null;
    Supplier<HttpServerTransport> custom = FakeHttpTransport::new;
    Supplier<HttpServerTransport> def = FakeHttpTransport::new;
    NetworkModule module = newNetworkModule(settings, new NetworkPlugin() {

        @Override
        public Map<String, Supplier<Transport>> getTransports(Settings settings, ThreadPool threadPool, PageCacheRecycler pageCacheRecycler, CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry, NetworkService networkService) {
            return Collections.singletonMap("default_custom", customTransport);
        }

        @Override
        public Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays, PageCacheRecycler pageCacheRecycler, CircuitBreakerService circuitBreakerService, NamedXContentRegistry xContentRegistry, NetworkService networkService, HttpServerTransport.Dispatcher requestDispatcher, ClusterSettings clusterSettings) {
            Map<String, Supplier<HttpServerTransport>> supplierMap = new HashMap<>();
            supplierMap.put("custom", custom);
            supplierMap.put("default_custom", def);
            return supplierMap;
        }
    });
    assertSame(custom, module.getHttpServerTransportSupplier());
    assertSame(customTransport, module.getTransportSupplier());
}
Also used : NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) NetworkPlugin(org.opensearch.plugins.NetworkPlugin) ClusterSettings(org.opensearch.common.settings.ClusterSettings) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) HttpServerTransport(org.opensearch.http.HttpServerTransport) BigArrays(org.opensearch.common.util.BigArrays) PageCacheRecycler(org.opensearch.common.util.PageCacheRecycler) Transport(org.opensearch.transport.Transport) HttpServerTransport(org.opensearch.http.HttpServerTransport) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) HashMap(java.util.HashMap) Map(java.util.Map) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Settings(org.opensearch.common.settings.Settings)

Aggregations

NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)28 SearchModule (org.opensearch.search.SearchModule)14 NamedWriteableRegistry (org.opensearch.common.io.stream.NamedWriteableRegistry)13 BeforeClass (org.junit.BeforeClass)10 Settings (org.opensearch.common.settings.Settings)10 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)9 Map (java.util.Map)9 XContentParser (org.opensearch.common.xcontent.XContentParser)8 IOException (java.io.IOException)7 List (java.util.List)7 HashSet (java.util.HashSet)5 Set (java.util.Set)5 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)5 Version (org.opensearch.Version)5 ClusterState (org.opensearch.cluster.ClusterState)5 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 Collections.singletonList (java.util.Collections.singletonList)4 TimeUnit (java.util.concurrent.TimeUnit)4