Search in sources :

Example 1 with InputStreamStreamInput

use of org.opensearch.common.io.stream.InputStreamStreamInput in project OpenSearch by opensearch-project.

the class PercolatorFieldMapperTests method testImplicitlySetDefaultScriptLang.

public void testImplicitlySetDefaultScriptLang() throws Exception {
    addQueryFieldMappings();
    XContentBuilder query = jsonBuilder();
    query.startObject();
    query.startObject("script");
    if (randomBoolean()) {
        query.field("script", "return true");
    } else {
        query.startObject("script");
        query.field("source", "return true");
        query.endObject();
    }
    query.endObject();
    query.endObject();
    ParsedDocument doc = mapperService.documentMapper("doc").parse(new SourceToParse("test", "doc", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().rawField(fieldName, new BytesArray(Strings.toString(query)).streamInput(), query.contentType()).endObject()), XContentType.JSON));
    BytesRef querySource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue();
    try (InputStream in = new ByteArrayInputStream(querySource.bytes, querySource.offset, querySource.length)) {
        try (StreamInput input = new NamedWriteableAwareStreamInput(new InputStreamStreamInput(in), writableRegistry())) {
            // Query builder's content is stored via BinaryFieldMapper, which has a custom encoding
            // to encode multiple binary values into a single binary doc values field.
            // This is the reason we need to first need to read the number of values and
            // then the length of the field value in bytes.
            input.readVInt();
            input.readVInt();
            ScriptQueryBuilder queryBuilder = (ScriptQueryBuilder) input.readNamedWriteable(QueryBuilder.class);
            assertEquals(Script.DEFAULT_SCRIPT_LANG, queryBuilder.script().getLang());
        }
    }
    query = jsonBuilder();
    query.startObject();
    query.startObject("function_score");
    query.startArray("functions");
    query.startObject();
    query.startObject("script_score");
    if (randomBoolean()) {
        query.field("script", "return true");
    } else {
        query.startObject("script");
        query.field("source", "return true");
        query.endObject();
    }
    query.endObject();
    query.endObject();
    query.endArray();
    query.endObject();
    query.endObject();
    doc = mapperService.documentMapper("doc").parse(new SourceToParse("test", "doc", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().rawField(fieldName, new BytesArray(Strings.toString(query)).streamInput(), query.contentType()).endObject()), XContentType.JSON));
    querySource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue();
    try (InputStream in = new ByteArrayInputStream(querySource.bytes, querySource.offset, querySource.length)) {
        try (StreamInput input = new NamedWriteableAwareStreamInput(new InputStreamStreamInput(in), writableRegistry())) {
            input.readVInt();
            input.readVInt();
            FunctionScoreQueryBuilder queryBuilder = (FunctionScoreQueryBuilder) input.readNamedWriteable(QueryBuilder.class);
            ScriptScoreFunctionBuilder function = (ScriptScoreFunctionBuilder) queryBuilder.filterFunctionBuilders()[0].getScoreFunction();
            assertEquals(Script.DEFAULT_SCRIPT_LANG, function.getScript().getLang());
        }
    }
}
Also used : BytesArray(org.opensearch.common.bytes.BytesArray) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SourceToParse(org.opensearch.index.mapper.SourceToParse) BoostingQueryBuilder(org.opensearch.index.query.BoostingQueryBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) HasChildQueryBuilder(org.opensearch.join.query.HasChildQueryBuilder) ConstantScoreQueryBuilder(org.opensearch.index.query.ConstantScoreQueryBuilder) FunctionScoreQueryBuilder(org.opensearch.index.query.functionscore.FunctionScoreQueryBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) ScriptQueryBuilder(org.opensearch.index.query.ScriptQueryBuilder) DisMaxQueryBuilder(org.opensearch.index.query.DisMaxQueryBuilder) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) HasParentQueryBuilder(org.opensearch.join.query.HasParentQueryBuilder) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) ScriptQueryBuilder(org.opensearch.index.query.ScriptQueryBuilder) ScriptScoreFunctionBuilder(org.opensearch.index.query.functionscore.ScriptScoreFunctionBuilder) FunctionScoreQueryBuilder(org.opensearch.index.query.functionscore.FunctionScoreQueryBuilder) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) ByteArrayInputStream(java.io.ByteArrayInputStream) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) BytesRef(org.apache.lucene.util.BytesRef) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput)

Example 2 with InputStreamStreamInput

use of org.opensearch.common.io.stream.InputStreamStreamInput in project OpenSearch by opensearch-project.

the class PercolateQueryBuilder method createStore.

static PercolateQuery.QueryStore createStore(MappedFieldType queryBuilderFieldType, QueryShardContext context) {
    Version indexVersion = context.indexVersionCreated();
    NamedWriteableRegistry registry = context.getWriteableRegistry();
    return ctx -> {
        LeafReader leafReader = ctx.reader();
        BinaryDocValues binaryDocValues = leafReader.getBinaryDocValues(queryBuilderFieldType.name());
        if (binaryDocValues == null) {
            return docId -> null;
        }
        return docId -> {
            if (binaryDocValues.advanceExact(docId)) {
                BytesRef qbSource = binaryDocValues.binaryValue();
                try (InputStream in = new ByteArrayInputStream(qbSource.bytes, qbSource.offset, qbSource.length)) {
                    try (StreamInput input = new NamedWriteableAwareStreamInput(new InputStreamStreamInput(in, qbSource.length), registry)) {
                        input.setVersion(indexVersion);
                        // Query builder's content is stored via BinaryFieldMapper, which has a custom encoding
                        // to encode multiple binary values into a single binary doc values field.
                        // This is the reason we need to first need to read the number of values and
                        // then the length of the field value in bytes.
                        int numValues = input.readVInt();
                        assert numValues == 1;
                        int valueLength = input.readVInt();
                        assert valueLength > 0;
                        QueryBuilder queryBuilder = input.readNamedWriteable(QueryBuilder.class);
                        assert in.read() == -1;
                        queryBuilder = Rewriteable.rewrite(queryBuilder, context);
                        return queryBuilder.toQuery(context);
                    }
                }
            } else {
                return null;
            }
        };
    };
}
Also used : NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) Query(org.apache.lucene.search.Query) ConstructingObjectParser(org.opensearch.common.xcontent.ConstructingObjectParser) FieldNameAnalyzer(org.opensearch.index.analysis.FieldNameAnalyzer) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) Version(org.opensearch.Version) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) BitSet(org.apache.lucene.util.BitSet) OpenSearchException(org.opensearch.OpenSearchException) XContentParser(org.opensearch.common.xcontent.XContentParser) MapperService(org.opensearch.index.mapper.MapperService) ByteArrayInputStream(java.io.ByteArrayInputStream) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) Directory(org.apache.lucene.store.Directory) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) BitDocIdSet(org.apache.lucene.util.BitDocIdSet) Scorer(org.apache.lucene.search.Scorer) BytesRef(org.apache.lucene.util.BytesRef) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) DirectoryReader(org.apache.lucene.index.DirectoryReader) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) QueryShardException(org.opensearch.index.query.QueryShardException) Objects(java.util.Objects) IndexWriter(org.apache.lucene.index.IndexWriter) List(java.util.List) QueryBuilder(org.opensearch.index.query.QueryBuilder) LeafReader(org.apache.lucene.index.LeafReader) QueryShardContext(org.opensearch.index.query.QueryShardContext) XContentType(org.opensearch.common.xcontent.XContentType) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) IndexReader(org.apache.lucene.index.IndexReader) IndexSearcher(org.apache.lucene.search.IndexSearcher) ReaderUtil(org.apache.lucene.index.ReaderUtil) BytesReference(org.opensearch.common.bytes.BytesReference) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) Weight(org.apache.lucene.search.Weight) StreamOutput(org.opensearch.common.io.stream.StreamOutput) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) ParseField(org.opensearch.common.ParseField) Supplier(java.util.function.Supplier) ConstructingObjectParser.constructorArg(org.opensearch.common.xcontent.ConstructingObjectParser.constructorArg) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) BitSetProducer(org.apache.lucene.search.join.BitSetProducer) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) SourceToParse(org.opensearch.index.mapper.SourceToParse) ByteBuffersDirectory(org.apache.lucene.store.ByteBuffersDirectory) DelegatingAnalyzerWrapper(org.apache.lucene.analysis.DelegatingAnalyzerWrapper) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) ConstructingObjectParser.optionalConstructorArg(org.opensearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) ParseContext(org.opensearch.index.mapper.ParseContext) SetOnce(org.apache.lucene.util.SetOnce) Analyzer(org.apache.lucene.analysis.Analyzer) GetRequest(org.opensearch.action.get.GetRequest) Rewriteable(org.opensearch.index.query.Rewriteable) IOException(java.io.IOException) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) ScoreMode(org.apache.lucene.search.ScoreMode) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) QueryRewriteContext(org.opensearch.index.query.QueryRewriteContext) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ALLOW_EXPENSIVE_QUERIES(org.opensearch.search.SearchService.ALLOW_EXPENSIVE_QUERIES) Collections(java.util.Collections) IndexReaderContext(org.apache.lucene.index.IndexReaderContext) InputStream(java.io.InputStream) LeafReader(org.apache.lucene.index.LeafReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QueryBuilder(org.opensearch.index.query.QueryBuilder) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) Version(org.opensearch.Version) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) BytesRef(org.apache.lucene.util.BytesRef) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput)

Example 3 with InputStreamStreamInput

use of org.opensearch.common.io.stream.InputStreamStreamInput in project OpenSearch by opensearch-project.

the class ConcurrentSeqNoVersioningIT method runLinearizabilityChecker.

@SuppressForbidden(reason = "system out is ok for a command line tool")
private static void runLinearizabilityChecker(FileInputStream fileInputStream, long primaryTerm, long seqNo) throws IOException {
    StreamInput is = new InputStreamStreamInput(Base64.getDecoder().wrap(fileInputStream));
    is = new NamedWriteableAwareStreamInput(is, createNamedWriteableRegistry());
    LinearizabilityChecker.History history = readHistory(is);
    Version initialVersion = new Version(primaryTerm, seqNo);
    boolean result = new LinearizabilityChecker().isLinearizable(new CASSequentialSpec(initialVersion), history, missingResponseGenerator());
    System.out.println(LinearizabilityChecker.visualize(new CASSequentialSpec(initialVersion), history, missingResponseGenerator()));
    System.out.println("Linearizable?: " + result);
}
Also used : LinearizabilityChecker(org.opensearch.cluster.coordination.LinearizabilityChecker) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) SuppressForbidden(org.opensearch.common.SuppressForbidden)

Example 4 with InputStreamStreamInput

use of org.opensearch.common.io.stream.InputStreamStreamInput in project OpenSearch by opensearch-project.

the class StoreTests method testMetadataSnapshotStreaming.

public void testMetadataSnapshotStreaming() throws Exception {
    Store.MetadataSnapshot outMetadataSnapshot = createMetadataSnapshot();
    org.opensearch.Version targetNodeVersion = randomVersion(random());
    ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
    OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
    out.setVersion(targetNodeVersion);
    outMetadataSnapshot.writeTo(out);
    ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
    InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
    in.setVersion(targetNodeVersion);
    Store.MetadataSnapshot inMetadataSnapshot = new Store.MetadataSnapshot(in);
    Map<String, StoreFileMetadata> origEntries = new HashMap<>();
    origEntries.putAll(outMetadataSnapshot.asMap());
    for (Map.Entry<String, StoreFileMetadata> entry : inMetadataSnapshot.asMap().entrySet()) {
        assertThat(entry.getValue().name(), equalTo(origEntries.remove(entry.getKey()).name()));
    }
    assertThat(origEntries.size(), equalTo(0));
    assertThat(inMetadataSnapshot.getCommitUserData(), equalTo(outMetadataSnapshot.getCommitUserData()));
}
Also used : HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) OutputStreamStreamOutput(org.opensearch.common.io.stream.OutputStreamStreamOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) HashMap(java.util.HashMap) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput)

Example 5 with InputStreamStreamInput

use of org.opensearch.common.io.stream.InputStreamStreamInput in project OpenSearch by opensearch-project.

the class StoreTests method testStreamStoreFilesMetadata.

public void testStreamStoreFilesMetadata() throws Exception {
    Store.MetadataSnapshot metadataSnapshot = createMetadataSnapshot();
    int numOfLeases = randomIntBetween(0, 10);
    List<RetentionLease> peerRecoveryRetentionLeases = new ArrayList<>();
    for (int i = 0; i < numOfLeases; i++) {
        peerRecoveryRetentionLeases.add(new RetentionLease(ReplicationTracker.getPeerRecoveryRetentionLeaseId(UUIDs.randomBase64UUID()), randomNonNegativeLong(), randomNonNegativeLong(), ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE));
    }
    TransportNodesListShardStoreMetadata.StoreFilesMetadata outStoreFileMetadata = new TransportNodesListShardStoreMetadata.StoreFilesMetadata(new ShardId("test", "_na_", 0), metadataSnapshot, peerRecoveryRetentionLeases);
    ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
    OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
    org.opensearch.Version targetNodeVersion = randomVersion(random());
    out.setVersion(targetNodeVersion);
    outStoreFileMetadata.writeTo(out);
    ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
    InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
    in.setVersion(targetNodeVersion);
    TransportNodesListShardStoreMetadata.StoreFilesMetadata inStoreFileMetadata = new TransportNodesListShardStoreMetadata.StoreFilesMetadata(in);
    Iterator<StoreFileMetadata> outFiles = outStoreFileMetadata.iterator();
    for (StoreFileMetadata inFile : inStoreFileMetadata) {
        assertThat(inFile.name(), equalTo(outFiles.next().name()));
    }
    assertThat(outStoreFileMetadata.syncId(), equalTo(inStoreFileMetadata.syncId()));
    assertThat(outStoreFileMetadata.peerRecoveryRetentionLeases(), equalTo(peerRecoveryRetentionLeases));
}
Also used : ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ShardId(org.opensearch.index.shard.ShardId) OutputStreamStreamOutput(org.opensearch.common.io.stream.OutputStreamStreamOutput) RetentionLease(org.opensearch.index.seqno.RetentionLease) ByteArrayInputStream(java.io.ByteArrayInputStream) TransportNodesListShardStoreMetadata(org.opensearch.indices.store.TransportNodesListShardStoreMetadata) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput)

Aggregations

InputStreamStreamInput (org.opensearch.common.io.stream.InputStreamStreamInput)21 ByteArrayInputStream (java.io.ByteArrayInputStream)14 StreamInput (org.opensearch.common.io.stream.StreamInput)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 OutputStreamStreamOutput (org.opensearch.common.io.stream.OutputStreamStreamOutput)9 NamedWriteableAwareStreamInput (org.opensearch.common.io.stream.NamedWriteableAwareStreamInput)7 InputStream (java.io.InputStream)5 IOException (java.io.IOException)4 QueryBuilder (org.opensearch.index.query.QueryBuilder)4 BytesRef (org.apache.lucene.util.BytesRef)3 OpenSearchException (org.opensearch.OpenSearchException)3 BytesArray (org.opensearch.common.bytes.BytesArray)3 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)3 EOFException (java.io.EOFException)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 Version (org.opensearch.Version)2 BytesReference (org.opensearch.common.bytes.BytesReference)2 NamedWriteableRegistry (org.opensearch.common.io.stream.NamedWriteableRegistry)2 ParsedDocument (org.opensearch.index.mapper.ParsedDocument)2