saihemanth-cloudera commented on code in PR #6595: URL: https://github.com/apache/hive/pull/6595#discussion_r4320067610
########## standalone-metastore/metastore-search/src/main/java/org/apache/hive/search/index/Indexer.java: ########## @@ -0,0 +1,279 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hive.search.index; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ListMultimap; + +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.apache.hadoop.hive.common.DatabaseName; +import org.apache.hadoop.hive.metastore.Batchable; +import org.apache.hive.search.config.IndexOptions; +import org.apache.hive.search.exception.IndexIOException; +import org.apache.hive.search.inference.Embedder; +import org.apache.hive.search.inference.EmbedderRegistry; +import org.apache.hive.search.mapping.FieldSchema; +import org.apache.hive.search.mapping.TableDocument; +import org.apache.hive.search.mapping.TextFieldSchema; +import org.apache.hive.search.mapping.field.Field; +import org.apache.hive.search.mapping.field.TextField; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.IndexCommit; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy; +import org.apache.lucene.index.SnapshotDeletionPolicy; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class Indexer implements Closeable { + private static final Logger LOG = LoggerFactory.getLogger(Indexer.class); + private static final int EMBED_BATCH_SIZE = 256; + + private final IndexManager indexManager; + private final EmbedderRegistry modelRegistry; + private final int commitFlushThreshold; + private SnapshotDeletionPolicy snapshotter; + private FlushTrackingWriter writer; + + public Indexer(IndexManager index, EmbedderRegistry registry) { + this.indexManager = index; + this.modelRegistry = registry; + this.commitFlushThreshold = + new IndexOptions(index.mapping().configuration()).getCommitFlushes(); + } + + int flushesSinceCommit() { + return writer.flushesSinceCommit(); + } + + public void initialize() throws IOException { + IndexWriterConfig config = + new IndexWriterConfig(indexManager.mapping().analyzer()) + .setCommitOnClose(false) + .setRAMBufferSizeMB(indexManager.mapping().config().getWriteBufferSizeMb()); + SnapshotDeletionPolicy snapshotDeletionPolicy = + new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); + config.setIndexDeletionPolicy(snapshotDeletionPolicy); + this.snapshotter = snapshotDeletionPolicy; + this.writer = new FlushTrackingWriter(indexManager.directory(), config); + } + + public void syncBackup() throws IOException { + if (!indexManager.hasBackup()) { + return; + } + IndexCommit snapshot = snapshotter.snapshot(); Review Comment: The snapshot isn’t actually used by syncBackup(), so a concurrent commit can invalidate the files being copied. ########## standalone-metastore/metastore-search/src/main/java/org/apache/hive/search/metastore/BootstrapIndexer.java: ########## @@ -0,0 +1,291 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hive.search.metastore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.metastore.IMetaStoreClient; +import org.apache.hadoop.hive.metastore.RetryingMetaStoreClient; +import org.apache.hadoop.hive.metastore.api.Table; +import org.apache.hive.search.exception.IndexIOException; +import org.apache.hive.search.index.IndexManager; +import org.apache.hive.search.mapping.TableDocument; +import org.apache.hive.search.config.IndexOptions; +import org.apache.hive.search.index.Indexer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class BootstrapIndexer { + private static final Logger LOG = LoggerFactory.getLogger(BootstrapIndexer.class); + private static final List<TableDocument> END_OF_STREAM = List.of(); + + private final Configuration configuration; + private final IndexManager indexManager; + private final IndexOptions indexConfig; + private final Indexer indexer; + private final IMetaStoreClient client; + private final boolean shareFetchClient; + private Progress progress; + + /** Package-private for unit tests: fetch workers reuse the injected client. */ + BootstrapIndexer(IndexManager indexManager, + Indexer indexer, + IMetaStoreClient client, + boolean shareFetchClient) { + this.indexManager = indexManager; + this.configuration = indexManager.mapping().configuration(); + this.indexConfig = new IndexOptions(configuration); + this.indexer = indexer; + this.client = client; + this.shareFetchClient = shareFetchClient; + } + + void run(long notificationId) throws Exception { + long start = System.currentTimeMillis(); + List<String> databases = client.getAllDatabases(); Review Comment: This only bootstraps the default catalog. Existing tables in other catalogs will never be indexed. Do we only care about 'hive' catalog? ########## standalone-metastore/metastore-search/src/main/java/org/apache/hive/search/search/Searcher.java: ########## @@ -0,0 +1,296 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hive.search.search; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +import org.apache.commons.lang3.StringUtils; +import org.apache.hadoop.hive.common.TableName; +import org.apache.hadoop.hive.metastore.api.Table; +import org.apache.hive.search.config.SearchOptions; +import org.apache.hive.search.exception.InferenceException; +import org.apache.hive.search.exception.SearchException; +import org.apache.hive.search.mapping.FieldSchema; +import org.apache.hive.search.mapping.IndexMapping; +import org.apache.hive.search.mapping.TableDocument; +import org.apache.hive.search.mapping.TextFieldSchema; +import org.apache.hive.search.metastore.MetastoreTableMapper; +import org.apache.hive.search.metastore.TableBlobCodec; +import org.apache.hive.search.index.IndexManager; +import org.apache.hive.search.inference.Embedder; +import org.apache.hive.search.inference.EmbedderRegistry; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.IndexableField; +import org.apache.lucene.index.Term; +import org.apache.lucene.queryparser.simple.SimpleQueryParser; +import org.apache.lucene.search.BayesianScoreEstimator; +import org.apache.lucene.search.BayesianScoreQuery; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.BoostQuery; +import org.apache.lucene.search.ConstantScoreQuery; +import org.apache.lucene.search.DisjunctionMaxQuery; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.KnnFloatVectorQuery; +import org.apache.lucene.search.LogOddsFusionQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.SearcherManager; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.TopDocs; + +public final class Searcher implements AutoCloseable { + private final EmbedderRegistry embedderRegistry; + private final IndexSearcher indexSearcher; + private final SearcherManager searcherManager; + private final IndexMapping mapping; + private final SearchOptions searchConfig; + private final BayesianScoreEstimator.Parameters parameters; + private final long processedEventId; + + public Searcher(SearcherManager manager, + IndexManager indexManager, + EmbedderRegistry registry, + SearchOptions searchConfig, + BayesianScoreEstimator.Parameters parameters) throws IOException { + this.searcherManager = manager; + this.processedEventId = indexManager.getProcessedEventId(); + this.indexSearcher = manager.acquire(); + this.mapping = indexManager.mapping(); + this.searchConfig = searchConfig; + this.parameters = parameters; + this.embedderRegistry = Objects.requireNonNull(registry, "Embedder registry"); + } + + public TableSearchResult search(SearchQuery request) + throws SearchException, IOException { + if (StringUtils.isBlank(request.body().queryText())) { + throw new SearchException("query text is required"); + } + int size = request.limit() > 0 ? request.limit() : searchConfig.getDefaultLimit(); + int semanticK = searchConfig.semanticK(size); + Query query = + switch (request.body()) { + case MatchQuery match -> compileMatchQuery(match.resolve(mapping)); + case SemanticQuery semantic -> compileSemanticQuery(semantic.resolve(mapping), semanticK); + case HybridQuery hybrid -> compileFusionQuery(hybrid.resolve(mapping), semanticK); + }; + query = applyScopeFilter(query, request.catalogName(), request.databaseName()); + TopDocs topDocs = indexSearcher.search(query, size); + List<TableSearchHit> hits = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + hits.add(readHit(scoreDoc)); + } + return new TableSearchResult(hits, topDocs.totalHits.value(), processedEventId); + } + + public TableSearchResult loadTables(List<TableName> tableNames) throws SearchException, IOException { + if (tableNames == null || tableNames.isEmpty()) { + return new TableSearchResult(List.of(), 0, processedEventId); + } + List<String> ids = new ArrayList<>(tableNames.size()); + for (TableName table : tableNames) { + ids.add(MetastoreTableMapper.tableId(table)); + } + BooleanQuery.Builder builder = new BooleanQuery.Builder(); + for (String id : ids) { + builder.add( + new TermQuery(new Term("_id" + TableDocument.FILTER_SUFFIX, id)), + BooleanClause.Occur.SHOULD); + } + TopDocs hits = indexSearcher.search(builder.build(), ids.size()); + List<TableSearchHit> searchHits = new ArrayList<>(hits.scoreDocs.length); + for (ScoreDoc scoreDoc : hits.scoreDocs) { + searchHits.add(readHit(scoreDoc)); + } + return new TableSearchResult(searchHits, hits.totalHits.value(), processedEventId); + } + + private Query compileFusionQuery(HybridQuery query, int semanticK) + throws SearchException { + Query matchQuery = new BayesianScoreQuery( + compileMatchQuery(query.toMatchQuery().resolve(mapping)), + parameters.alpha(), parameters.beta(), parameters.baseRate()); + Query semanticQuery = compileSemanticQuery(query.toSemanticQuery().resolve(mapping), semanticK); + float semanticWeight = query.semanticWeight(searchConfig); + float[] weights = {1.0f - semanticWeight, semanticWeight}; + return new LogOddsFusionQuery(List.of(matchQuery, semanticQuery), + searchConfig.getFusionPrior(), weights); + } + + private Query applyScopeFilter(Query query, String catalogName, String databaseName) { + Query filter = compileScopeFilter(catalogName, databaseName); + if (filter == null) { + return query; + } + return new BooleanQuery.Builder() + .add(query, BooleanClause.Occur.MUST) + .add(filter, BooleanClause.Occur.FILTER) + .build(); + } + + private Query compileScopeFilter(String catalogName, String databaseName) { + boolean hasCatalog = StringUtils.isNotEmpty(catalogName); + boolean hasDatabase = StringUtils.isNotEmpty(databaseName); + if (!hasCatalog && !hasDatabase) { + return null; + } + if (hasCatalog && hasDatabase) { + return new PrefixQuery(new Term("_id" + TableDocument.FILTER_SUFFIX, + catalogName + "." + databaseName + ".")); + } + if (hasCatalog) { + return new PrefixQuery(new Term("_id" + TableDocument.FILTER_SUFFIX, catalogName + ".")); + } + return new TermQuery(new Term( + MetastoreTableMapper.FIELD_DB + TableDocument.FILTER_SUFFIX, databaseName)); + } + + private Query compileMatchQuery(MatchQuery match) + throws SearchException { + if (StringUtils.isNotEmpty(match.field())) { + return booleanShould(lexicalClausesForField(match.field(), match.queryText(), 1.0f), + "field '" + match.field() + "' is not lexically searchable"); + } + BooleanQuery.Builder builder = new BooleanQuery.Builder(); + boolean added = false; + for (MetastoreTableMapper.KeywordSearchField keywordField : MetastoreTableMapper.KEYWORD_SEARCH_FIELDS) { + for (Query clause : lexicalClausesForField( + keywordField.field(), match.queryText(), keywordField.boost())) { + builder.add(clause, BooleanClause.Occur.SHOULD); + added = true; + } + } + if (!added) { + throw new SearchException("No lexically searchable table fields are configured"); + } + return builder.build(); + } + + private Query booleanShould(List<Query> clauses, String ifEmptyMessage) throws SearchException { + if (clauses.isEmpty()) { + throw new SearchException(ifEmptyMessage); + } + if (clauses.size() == 1) { + return clauses.getFirst(); + } + BooleanQuery.Builder builder = new BooleanQuery.Builder(); + for (Query clause : clauses) { + builder.add(clause, BooleanClause.Occur.SHOULD); + } + return builder.build(); + } + + private List<Query> lexicalClausesForField(String field, String queryText, float boost) + throws SearchException { + FieldSchema schema = mapping.fieldSchema(field); + if (!(schema instanceof TextFieldSchema text)) { + return List.of(); + } + List<Query> clauses = new ArrayList<>(); + if (text.filter()) { + clauses.add(maybeBoost(compileFilterKeywordQuery(field, queryText), boost)); + if (text.lexical()) { + clauses.add(maybeBoost(compileFieldMatchQuery(field, queryText), boost)); + } + return clauses; + } + if (text.lexical()) { + clauses.add(maybeBoost(compileFieldMatchQuery(field, queryText), boost)); + } + return clauses; + } + + private Query maybeBoost(Query query, float boost) { + return boost == 1.0f ? query : boostKeywordQuery(query, boost); + } + + private static Query boostKeywordQuery(Query query, float boost) { + return new BoostQuery(new ConstantScoreQuery(query), boost); + } + + private Query compileFilterKeywordQuery(String field, String queryText) { + String normalized = queryText.trim().toLowerCase(Locale.ROOT); + if (normalized.isEmpty()) { + return new BooleanQuery.Builder().build(); + } + return new TermQuery(new Term(field + TableDocument.FILTER_SUFFIX, normalized)); + } + + private Query compileFieldMatchQuery(String field, String queryText) + throws SearchException { + FieldSchema schema = mapping.fieldSchema(field); + if (!(schema instanceof TextFieldSchema text) || !text.lexical()) { + throw new SearchException("field '" + field + "' is not lexically searchable"); + } + return new SimpleQueryParser(mapping.analyzer(), field).parse(queryText); + } + + private Query compileSemanticQuery(SemanticQuery semantic, int knnK) throws SearchException { + List<String> fields = mapping.resolveSemanticSearchFields(null); + FieldSchema schema = mapping.fieldSchema(fields.getFirst()); + if (!(schema instanceof TextFieldSchema text) || !text.semantic()) { + throw new SearchException("index has no semantically searchable fields configured"); + } + float[] embedding; + try { + embedding = embedderRegistry.get(text.semanticModel()) + .embed(Embedder.TaskType.QUERY, semantic.queryText()); Review Comment: pass this filter into the kNN query. Filtering after global top-K can drop all valid scoped results. ########## standalone-metastore/metastore-search/src/main/java/org/apache/hive/search/index/store/IndexBackupUtils.java: ########## @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hive.search.index.store; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.List; +import java.util.Optional; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hive.search.config.IndexStoreOptions; +import org.apache.hive.search.exception.IndexIOException; + +public final class IndexBackupUtils { + private IndexBackupUtils() {} + + /** Push local index state to the backup (remote) location. */ + public static boolean syncToBackup(IndexStateClient local, IndexStateClient remote) + throws IOException { + Optional<IndexManifest> localManifest = local.readManifest(); + if (localManifest.isEmpty()) { + return false; + } + Optional<IndexManifest> remoteManifest = remote.readManifest(); + IndexManifest localM = localManifest.get(); + if (remoteManifest.isPresent()) { + IndexManifest remoteM = remoteManifest.get(); + if (remoteM.lastEventId() > localM.lastEventId()) { + return false; + } + if (remoteM.lastEventId() == localM.lastEventId() && localM.sameFilesAs(remoteM)) { + return false; + } + } + applyDiff(local, remote, localM.diff(remoteManifest.orElse(null))); Review Comment: Please stage and atomically publish the backup. A failed sync can currently corrupt the last valid backup. ########## standalone-metastore/metastore-search/src/main/java/org/apache/hive/search/metastore/MetastoreCluster.java: ########## @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hive.search.metastore; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.common.TableName; +import org.apache.hadoop.hive.metastore.leader.LeaderElection; +import org.apache.hadoop.hive.metastore.leader.LeaderException; +import org.apache.hadoop.hive.metastore.leader.LeaseLeaderElection; + +@SuppressWarnings("rawtypes, unchecked") +public class MetastoreCluster implements AutoCloseable { + private static final String CLUSTER_ELECTION_METHOD = "metastore.index.election.method"; + private static final Map<String, Pair<LeaderElection, Object>> CACHED = new ConcurrentHashMap<>(); + + static { + try { + CACHED.put("default", Pair.of(new LeaseLeaderElection(), + new TableName("__INDEX_CATALOG__", "__INDEX_DATABASE__", "__INDEX_TABLE__"))); Review Comment: This cached election is closed after the first lifecycle and can’t be reused on reload. ########## standalone-metastore/metastore-search/src/main/java/org/apache/hive/search/metastore/BootstrapIndexer.java: ########## @@ -0,0 +1,291 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hive.search.metastore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.metastore.IMetaStoreClient; +import org.apache.hadoop.hive.metastore.RetryingMetaStoreClient; +import org.apache.hadoop.hive.metastore.api.Table; +import org.apache.hive.search.exception.IndexIOException; +import org.apache.hive.search.index.IndexManager; +import org.apache.hive.search.mapping.TableDocument; +import org.apache.hive.search.config.IndexOptions; +import org.apache.hive.search.index.Indexer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class BootstrapIndexer { + private static final Logger LOG = LoggerFactory.getLogger(BootstrapIndexer.class); + private static final List<TableDocument> END_OF_STREAM = List.of(); + + private final Configuration configuration; + private final IndexManager indexManager; + private final IndexOptions indexConfig; + private final Indexer indexer; + private final IMetaStoreClient client; + private final boolean shareFetchClient; + private Progress progress; + + /** Package-private for unit tests: fetch workers reuse the injected client. */ + BootstrapIndexer(IndexManager indexManager, + Indexer indexer, + IMetaStoreClient client, + boolean shareFetchClient) { + this.indexManager = indexManager; + this.configuration = indexManager.mapping().configuration(); + this.indexConfig = new IndexOptions(configuration); + this.indexer = indexer; + this.client = client; + this.shareFetchClient = shareFetchClient; + } + + void run(long notificationId) throws Exception { + long start = System.currentTimeMillis(); + List<String> databases = client.getAllDatabases(); + BatchPlan plan = planBatches(databases); + LOG.info("Bootstrap indexer planned {} table(s) in {} batch(es) across {} database(s)", + plan.plannedTableCount(), plan.batches().size(), databases.size()); + + BlockingQueue<List<TableDocument>> indexQueue = + new ArrayBlockingQueue<>(indexConfig.getBootstrapQueueDepth()); + AtomicReference<Exception> failure = new AtomicReference<>(); + AtomicLong indexedTables = new AtomicLong(); + CountDownLatch fetchDone = new CountDownLatch(plan.batches().size()); + progress = new Progress(indexedTables, plan.plannedTableCount, System.currentTimeMillis()); + indexManager.setBootstrapIndexer(this); + + Thread indexThread = startIndexConsumer(indexQueue, failure, indexedTables); + try (ExecutorService tableFetcher = Executors.newFixedThreadPool(indexConfig.getBootstrapFetchThreads(), + r -> { + Thread thread = new Thread(r, "Index-Bootstrap-Fetch"); + thread.setDaemon(true); + return thread; + })) { + for (TableBatch batch : plan.batches()) { + tableFetcher.submit(() -> fetchBatch(batch, indexQueue, failure, fetchDone)); + } + awaitFetchCompletion(fetchDone, failure); + indexQueue.put(END_OF_STREAM); + indexThread.join(); + rethrowFailure(failure); + indexer.flush(notificationId, true); + indexer.syncBackup(); + long elapsed = System.currentTimeMillis() - start; + LOG.info("Built index for {} tables in {} batch(es) over {}ms", + indexer.writer().getDocStats().numDocs, plan.batches().size(), elapsed); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IndexIOException("Bootstrap indexing interrupted", e); + } finally { + indexThread.interrupt(); + indexThread.join(TimeUnit.SECONDS.toMillis(30)); + } + } + + private BatchPlan planBatches(List<String> databases) throws Exception { + int batchSize = indexConfig.getBootstrapBatchSize(); + List<TableBatch> planned = new ArrayList<>(); + int plannedTableCount = 0; + for (String db : databases) { + List<String> tableNames = client.getAllTables(db); + plannedTableCount += tableNames.size(); + for (int idx = 0; idx < tableNames.size(); idx += batchSize) { + int end = Math.min(idx + batchSize, tableNames.size()); + planned.add(new TableBatch(db, List.copyOf(tableNames.subList(idx, end)))); + } + } + return new BatchPlan(planned, plannedTableCount); + } + + private void fetchBatch(TableBatch batch, + BlockingQueue<List<TableDocument>> indexQueue, + AtomicReference<Exception> failure, + CountDownLatch fetchDone) { + try { + if (failure.get() != null) { + return; + } + if (shareFetchClient) { + fetchBatch(batch, indexQueue, failure, client); + return; + } + try (IMetaStoreClient fetchClient = RetryingMetaStoreClient.getProxy(configuration, true)) { + fetchBatch(batch, indexQueue, failure, fetchClient); + } + } catch (Exception e) { + recordFailure(failure, e); + } finally { + fetchDone.countDown(); + } + } + + private void fetchBatch(TableBatch batch, + BlockingQueue<List<TableDocument>> indexQueue, + AtomicReference<Exception> failure, + IMetaStoreClient client) throws Exception { + if (failure.get() != null) { + return; + } + List<Table> tables = + client.getTableObjectsByName(batch.database(), batch.tableNames()); + List<TableDocument> documents = new ArrayList<>(tables.size()); + for (Table table : tables) { + documents.add(MetastoreTableMapper.fromTable(table, indexManager.mapping())); + } + indexQueue.put(documents); Review Comment: If indexing fails while this queue is full, producers can block forever. Please cancel them on failure. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
