Search in sources :

Example 26 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class JoinTaskExecutor method execute.

@Override
public ClusterTasksResult<Task> execute(ClusterState currentState, List<Task> joiningNodes) throws Exception {
    final ClusterTasksResult.Builder<Task> results = ClusterTasksResult.builder();
    final DiscoveryNodes currentNodes = currentState.nodes();
    boolean nodesChanged = false;
    ClusterState.Builder newState;
    if (joiningNodes.size() == 1 && joiningNodes.get(0).isFinishElectionTask()) {
        return results.successes(joiningNodes).build(currentState);
    } else if (currentNodes.getMasterNode() == null && joiningNodes.stream().anyMatch(Task::isBecomeMasterTask)) {
        assert joiningNodes.stream().anyMatch(Task::isFinishElectionTask) : "becoming a master but election is not finished " + joiningNodes;
        // use these joins to try and become the master.
        // Note that we don't have to do any validation of the amount of joining nodes - the commit
        // during the cluster state publishing guarantees that we have enough
        newState = becomeMasterAndTrimConflictingNodes(currentState, joiningNodes);
        nodesChanged = true;
    } else if (currentNodes.isLocalNodeElectedMaster() == false) {
        logger.trace("processing node joins, but we are not the master. current master: {}", currentNodes.getMasterNode());
        throw new NotMasterException("Node [" + currentNodes.getLocalNode() + "] not master for join request");
    } else {
        newState = ClusterState.builder(currentState);
    }
    DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder(newState.nodes());
    assert nodesBuilder.isLocalNodeElectedMaster();
    Version minClusterNodeVersion = newState.nodes().getMinNodeVersion();
    Version maxClusterNodeVersion = newState.nodes().getMaxNodeVersion();
    // we only enforce major version transitions on a fully formed clusters
    final boolean enforceMajorVersion = currentState.getBlocks().hasGlobalBlock(STATE_NOT_RECOVERED_BLOCK) == false;
    // processing any joins
    Map<String, String> joiniedNodeNameIds = new HashMap<>();
    for (final Task joinTask : joiningNodes) {
        if (joinTask.isBecomeMasterTask() || joinTask.isFinishElectionTask()) {
        // noop
        } else if (currentNodes.nodeExistsWithSameRoles(joinTask.node()) && !currentNodes.nodeExistsWithBWCVersion(joinTask.node())) {
            logger.debug("received a join request for an existing node [{}]", joinTask.node());
        } else {
            final DiscoveryNode node = joinTask.node();
            try {
                if (enforceMajorVersion) {
                    ensureMajorVersionBarrier(node.getVersion(), minClusterNodeVersion);
                }
                ensureNodesCompatibility(node.getVersion(), minClusterNodeVersion, maxClusterNodeVersion);
                // we do this validation quite late to prevent race conditions between nodes joining and importing dangling indices
                // we have to reject nodes that don't support all indices we have in this cluster
                ensureIndexCompatibility(node.getVersion(), currentState.getMetadata());
                nodesBuilder.add(node);
                nodesChanged = true;
                minClusterNodeVersion = Version.min(minClusterNodeVersion, node.getVersion());
                maxClusterNodeVersion = Version.max(maxClusterNodeVersion, node.getVersion());
                if (node.isMasterNode()) {
                    joiniedNodeNameIds.put(node.getName(), node.getId());
                }
            } catch (IllegalArgumentException | IllegalStateException e) {
                results.failure(joinTask, e);
                continue;
            }
        }
        results.success(joinTask);
    }
    if (nodesChanged) {
        rerouteService.reroute("post-join reroute", Priority.HIGH, ActionListener.wrap(r -> logger.trace("post-join reroute completed"), e -> logger.debug("post-join reroute failed", e)));
        if (joiniedNodeNameIds.isEmpty() == false) {
            Set<CoordinationMetadata.VotingConfigExclusion> currentVotingConfigExclusions = currentState.getVotingConfigExclusions();
            Set<CoordinationMetadata.VotingConfigExclusion> newVotingConfigExclusions = currentVotingConfigExclusions.stream().map(e -> {
                // Update nodeId in VotingConfigExclusion when a new node with excluded node name joins
                if (CoordinationMetadata.VotingConfigExclusion.MISSING_VALUE_MARKER.equals(e.getNodeId()) && joiniedNodeNameIds.containsKey(e.getNodeName())) {
                    return new CoordinationMetadata.VotingConfigExclusion(joiniedNodeNameIds.get(e.getNodeName()), e.getNodeName());
                } else {
                    return e;
                }
            }).collect(Collectors.toSet());
            // if VotingConfigExclusions did get updated
            if (newVotingConfigExclusions.equals(currentVotingConfigExclusions) == false) {
                CoordinationMetadata.Builder coordMetadataBuilder = CoordinationMetadata.builder(currentState.coordinationMetadata()).clearVotingConfigExclusions();
                newVotingConfigExclusions.forEach(coordMetadataBuilder::addVotingConfigExclusion);
                Metadata newMetadata = Metadata.builder(currentState.metadata()).coordinationMetadata(coordMetadataBuilder.build()).build();
                return results.build(allocationService.adaptAutoExpandReplicas(newState.nodes(nodesBuilder).metadata(newMetadata).build()));
            }
        }
        return results.build(allocationService.adaptAutoExpandReplicas(newState.nodes(nodesBuilder).build()));
    } else {
        // for the joining node to finalize its join and set us as a master
        return results.build(newState.build());
    }
}
Also used : DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) STATE_NOT_RECOVERED_BLOCK(org.opensearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) Version(org.opensearch.Version) Priority(org.opensearch.common.Priority) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) LegacyESVersion(org.opensearch.LegacyESVersion) Map(java.util.Map) NotMasterException(org.opensearch.cluster.NotMasterException) RerouteService(org.opensearch.cluster.routing.RerouteService) BiConsumer(java.util.function.BiConsumer) ActionListener(org.opensearch.action.ActionListener) ClusterBlocks(org.opensearch.cluster.block.ClusterBlocks) Collection(java.util.Collection) PersistentTasksCustomMetadata(org.opensearch.persistent.PersistentTasksCustomMetadata) Set(java.util.Set) ClusterStateTaskExecutor(org.opensearch.cluster.ClusterStateTaskExecutor) Settings(org.opensearch.common.settings.Settings) TransportService(org.opensearch.transport.TransportService) Collectors(java.util.stream.Collectors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Collections(java.util.Collections) ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) HashMap(java.util.HashMap) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) PersistentTasksCustomMetadata(org.opensearch.persistent.PersistentTasksCustomMetadata) Version(org.opensearch.Version) LegacyESVersion(org.opensearch.LegacyESVersion) NotMasterException(org.opensearch.cluster.NotMasterException) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes)

Example 27 with Version

use of org.opensearch.Version 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 28 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class CandidateQueryTests method testDuplicatedClauses.

public void testDuplicatedClauses() throws Exception {
    List<ParseContext.Document> docs = new ArrayList<>();
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    BooleanQuery.Builder builder1 = new BooleanQuery.Builder();
    builder1.add(new TermQuery(new Term("field", "value1")), Occur.MUST);
    builder1.add(new TermQuery(new Term("field", "value2")), Occur.MUST);
    builder.add(builder1.build(), Occur.MUST);
    BooleanQuery.Builder builder2 = new BooleanQuery.Builder();
    builder2.add(new TermQuery(new Term("field", "value2")), Occur.MUST);
    builder2.add(new TermQuery(new Term("field", "value3")), Occur.MUST);
    builder.add(builder2.build(), Occur.MUST);
    addQuery(builder.build(), docs);
    builder = new BooleanQuery.Builder().setMinimumNumberShouldMatch(2);
    builder1 = new BooleanQuery.Builder();
    builder1.add(new TermQuery(new Term("field", "value1")), Occur.MUST);
    builder1.add(new TermQuery(new Term("field", "value2")), Occur.MUST);
    builder.add(builder1.build(), Occur.SHOULD);
    builder2 = new BooleanQuery.Builder();
    builder2.add(new TermQuery(new Term("field", "value2")), Occur.MUST);
    builder2.add(new TermQuery(new Term("field", "value3")), Occur.MUST);
    builder.add(builder2.build(), Occur.SHOULD);
    BooleanQuery.Builder builder3 = new BooleanQuery.Builder();
    builder3.add(new TermQuery(new Term("field", "value3")), Occur.MUST);
    builder3.add(new TermQuery(new Term("field", "value4")), Occur.MUST);
    builder.add(builder3.build(), Occur.SHOULD);
    addQuery(builder.build(), docs);
    indexWriter.addDocuments(docs);
    indexWriter.close();
    directoryReader = DirectoryReader.open(directory);
    IndexSearcher shardSearcher = newSearcher(directoryReader);
    shardSearcher.setQueryCache(null);
    Version v = Version.CURRENT;
    List<BytesReference> sources = Collections.singletonList(new BytesArray("{}"));
    MemoryIndex memoryIndex = new MemoryIndex();
    memoryIndex.addField("field", "value1 value2 value3", new WhitespaceAnalyzer());
    IndexSearcher percolateSearcher = memoryIndex.createSearcher();
    PercolateQuery query = (PercolateQuery) fieldType.percolateQuery("_name", queryStore, sources, percolateSearcher, false, v);
    TopDocs topDocs = shardSearcher.search(query, 10, new Sort(SortField.FIELD_DOC));
    assertEquals(2L, topDocs.totalHits.value);
    assertEquals(0, topDocs.scoreDocs[0].doc);
    assertEquals(1, topDocs.scoreDocs[1].doc);
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) BytesReference(org.opensearch.common.bytes.BytesReference) WhitespaceAnalyzer(org.apache.lucene.analysis.core.WhitespaceAnalyzer) BooleanQuery(org.apache.lucene.search.BooleanQuery) BlendedTermQuery(org.apache.lucene.queries.BlendedTermQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) BytesArray(org.opensearch.common.bytes.BytesArray) ArrayList(java.util.ArrayList) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) TopDocs(org.apache.lucene.search.TopDocs) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) Version(org.opensearch.Version) Sort(org.apache.lucene.search.Sort)

Example 29 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class HasChildQueryBuilderTests method testSerializationBWC.

/**
 * Test (de)serialization on all previous released versions
 */
public void testSerializationBWC() throws IOException {
    for (Version version : VersionUtils.allReleasedVersions()) {
        HasChildQueryBuilder testQuery = createTestQueryBuilder();
        assertSerialization(testQuery, version);
    }
}
Also used : Version(org.opensearch.Version)

Example 30 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class VerifyVersionConstantsIT method testLuceneVersionConstant.

public void testLuceneVersionConstant() throws IOException, ParseException {
    final Response response = client().performRequest(new Request("GET", "/"));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    final ObjectPath objectPath = ObjectPath.createFromResponse(response);
    final String opensearchVersionString = objectPath.evaluate("version.number").toString();
    final Version opensearchVersion = Version.fromString(opensearchVersionString.replace("-SNAPSHOT", ""));
    final String luceneVersionString = objectPath.evaluate("version.lucene_version").toString();
    final org.apache.lucene.util.Version luceneVersion = org.apache.lucene.util.Version.parse(luceneVersionString);
    assertThat(opensearchVersion.luceneVersion, equalTo(luceneVersion));
}
Also used : Response(org.opensearch.client.Response) ObjectPath(org.opensearch.test.rest.yaml.ObjectPath) Version(org.opensearch.Version) Request(org.opensearch.client.Request)

Aggregations

Version (org.opensearch.Version)242 Settings (org.opensearch.common.settings.Settings)86 LegacyESVersion (org.opensearch.LegacyESVersion)84 ArrayList (java.util.ArrayList)59 IOException (java.io.IOException)54 List (java.util.List)54 Map (java.util.Map)50 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)42 Collections (java.util.Collections)39 HashMap (java.util.HashMap)38 ClusterState (org.opensearch.cluster.ClusterState)38 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)37 HashSet (java.util.HashSet)36 BytesReference (org.opensearch.common.bytes.BytesReference)36 TimeValue (org.opensearch.common.unit.TimeValue)36 Set (java.util.Set)35 Collectors (java.util.stream.Collectors)34 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)33 StreamInput (org.opensearch.common.io.stream.StreamInput)32 BytesArray (org.opensearch.common.bytes.BytesArray)30