Skip to content

The Unified and Autonomous Development Platform

Use cached JGit repo and Lucene FieldCache to improve performance.

robin shineed5011998292
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
index c134f59859..a013bd1d7e 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
@@ -1,7 +1,7 @@
package com.pmease.gitplex.search;
import static com.pmease.gitplex.search.FieldConstants.BLOB_ANALYZER_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_DEFS_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_CONTENT;
import static com.pmease.gitplex.search.FieldConstants.BLOB_HASH;
import static com.pmease.gitplex.search.FieldConstants.BLOB_PATH;
import static com.pmease.gitplex.search.FieldConstants.BLOB_SYMBOLS;
@@ -21,6 +21,7 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
@@ -40,18 +41,21 @@ import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
-import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.RepositoryCache;
+import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
+import org.eclipse.jgit.util.FS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.pmease.commons.git.GitUtils;
@@ -78,7 +82,7 @@ public class DefaultIndexManager implements IndexManager {
private final StorageManager storageManager;
- private final Analyzers analyzers;
+ private final Analyzers analyzers; // language analyzers, different from lucene analyzer
@Inject
public DefaultIndexManager(EventBus eventBus, StorageManager storageManager, Analyzers analyzers) {
@@ -89,7 +93,9 @@ public class DefaultIndexManager implements IndexManager {
}
private IndexWriterConfig newWriterConfig() {
- Analyzer analyzer = new StandardAnalyzer();
+ PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(),
+ ImmutableMap.<String, Analyzer>of(FieldConstants.BLOB_CONTENT.name(), new TriGramAnalyzer()));
+
IndexWriterConfig iwc = new IndexWriterConfig(Version.LATEST, analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
return iwc;
@@ -103,7 +109,7 @@ public class DefaultIndexManager implements IndexManager {
return null;
}
- private IndexResult index(FileRepository repo, String commitHash,
+ private IndexResult index(org.eclipse.jgit.lib.Repository repo, String commitHash,
IndexWriter writer, IndexSearcher searcher) throws Exception {
RevWalk revWalk = new RevWalk(repo);
TreeWalk treeWalk = new TreeWalk(repo);
@@ -205,13 +211,10 @@ public class DefaultIndexManager implements IndexManager {
Document document = new Document();
document.add(new StringField(BLOB_HASH.name(), blobId.name(), Store.YES));
document.add(new StringField(BLOB_PATH.name(), path, Store.YES));
- document.add(new Field(
- BLOB_SYMBOLS.name(),
- new LangTokenStream(analyzeResult.getSymbols()),
- TextField.TYPE_NOT_STORED));
+ document.add(new TextField(BLOB_CONTENT.name(), content, Store.YES));
if (analyzeResult.getOutline() != null) {
document.add(new Field(
- BLOB_DEFS_SYMBOLS.name(),
+ BLOB_SYMBOLS.name(),
new LangTokenStream(analyzeResult.getOutline().getSymbols()),
TextField.TYPE_NOT_STORED));
}
@@ -245,7 +248,8 @@ public class DefaultIndexManager implements IndexManager {
try (IndexReader reader = DirectoryReader.open(directory)) {
IndexSearcher searcher = new IndexSearcher(reader);
try (IndexWriter writer = new IndexWriter(directory, newWriterConfig())) {
- FileRepository repo = new FileRepository(repository.git().repoDir());
+ org.eclipse.jgit.lib.Repository repo =
+ RepositoryCache.open(FileKey.exact(repository.git().repoDir(), FS.DETECTED));
try {
indexResult = index(repo, commitHash, writer, searcher);
writer.commit();
@@ -259,7 +263,8 @@ public class DefaultIndexManager implements IndexManager {
}
} else {
try (IndexWriter writer = new IndexWriter(directory, newWriterConfig())) {
- FileRepository repo = new FileRepository(repository.git().repoDir());
+ org.eclipse.jgit.lib.Repository repo =
+ RepositoryCache.open(FileKey.exact(repository.git().repoDir(), FS.DETECTED));
try {
indexResult = index(repo, commitHash, writer, null);
writer.commit();
@@ -303,6 +308,7 @@ public class DefaultIndexManager implements IndexManager {
@Subscribe
public void repositoryRemoved(RepositoryRemoved event) {
+ eventBus.post(new IndexRemoving(event.getRepository()));
FileUtils.deleteDir(storageManager.getIndexDir(event.getRepository()));
}
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultSearchManager.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultSearchManager.java
index 3aea1e61a1..ee6c5b1c60 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultSearchManager.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultSearchManager.java
@@ -1,36 +1,42 @@
package com.pmease.gitplex.search;
-import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.apache.lucene.document.Document;
import org.apache.lucene.index.AtomicReaderContext;
+import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DirectoryReader;
-import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
-import org.eclipse.jgit.internal.storage.file.FileRepository;
-import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.RepositoryCache;
+import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.util.FS;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
+import com.google.common.eventbus.EventBus;
+import com.google.common.eventbus.Subscribe;
import com.pmease.commons.git.GitUtils;
import com.pmease.commons.lang.Analyzers;
-import com.pmease.commons.util.Charsets;
+import com.pmease.gitplex.core.events.SystemStopping;
import com.pmease.gitplex.core.manager.StorageManager;
import com.pmease.gitplex.core.model.Repository;
@@ -39,43 +45,113 @@ public class DefaultSearchManager implements SearchManager {
private final StorageManager storageManager;
- private final Analyzers analyzers;
+ private final Map<Long, SearcherManager> searcherManagers = new ConcurrentHashMap<>();
@Inject
- public DefaultSearchManager(StorageManager storageManager, Analyzers analyzers) {
+ public DefaultSearchManager(EventBus eventBus, StorageManager storageManager, Analyzers analyzers) {
+ eventBus.register(this);
this.storageManager = storageManager;
- this.analyzers = analyzers;
+ }
+
+ @Nullable
+ private SearcherManager getSearcherManager(Repository repository) {
+ try {
+ SearcherManager searcherManager = searcherManagers.get(repository.getId());
+ if (searcherManager == null) synchronized (searcherManagers) {
+ searcherManager = searcherManagers.get(repository.getId());
+ if (searcherManager == null) {
+ Directory directory = FSDirectory.open(storageManager.getIndexDir(repository));
+ if (DirectoryReader.indexExists(directory)) {
+ searcherManager = new SearcherManager(directory, null);
+ searcherManagers.put(repository.getId(), searcherManager);
+ }
+ }
+ }
+ return searcherManager;
+ } catch (IOException e) {
+ throw Throwables.propagate(e);
+ }
+ }
+
+ @Subscribe
+ public void indexRemoving(IndexRemoving event) {
+ synchronized (searcherManagers) {
+ SearcherManager searcherManager = searcherManagers.get(event.getRepository().getId());
+ if (searcherManager != null) {
+ try {
+ searcherManager.close();
+ } catch (IOException e) {
+ Throwables.propagate(e);
+ }
+ searcherManagers.remove(event.getRepository().getId());
+ }
+ }
+ }
+
+ @Subscribe
+ public void commitIndexed(CommitIndexed event) {
+ try {
+ getSearcherManager(event.getRepository()).maybeRefresh();
+ } catch (IOException e) {
+ Throwables.propagate(e);
+ }
+ }
+
+ @Subscribe
+ public void systemStopping(SystemStopping event) {
+ synchronized (searcherManagers) {
+ for (SearcherManager searcherManager: searcherManagers.values()) {
+ try {
+ searcherManager.close();
+ } catch (IOException e) {
+ Throwables.propagate(e);
+ }
+ }
+ searcherManagers.clear();
+ }
}
@Override
public List<SearchHit> search(Repository repository, String commitHash,
Query query, SearchHit after, int count) {
Preconditions.checkArgument(GitUtils.isHash(commitHash));
- File indexDir = storageManager.getIndexDir(repository);
-
- try (Directory directory = FSDirectory.open(indexDir)) {
- if (DirectoryReader.indexExists(directory)) {
- try (IndexReader reader = DirectoryReader.open(directory)) {
- final FileRepository repo = new FileRepository(repository.git().repoDir());
+ SearcherManager searcherManager = getSearcherManager(repository);
+ if (searcherManager != null) {
+ try {
+ final IndexSearcher searcher = searcherManager.acquire();
+ try {
+ final org.eclipse.jgit.lib.Repository repo =
+ RepositoryCache.open(FileKey.exact(repository.git().repoDir(), FS.DETECTED));
try {
final RevTree revTree = new RevWalk(repo).parseCommit(repo.resolve(commitHash)).getTree();
final List<SearchHit> hits = new ArrayList<>();
final Map<String, String> blobHashes = new HashMap<>();
- final IndexSearcher searcher = new IndexSearcher(reader);
+ final AtomicInteger skipped = new AtomicInteger(0);
searcher.search(query, new Collector() {
-
- private int docBase;
+
+ private AtomicReaderContext context;
@Override
public void setScorer(Scorer scorer) throws IOException {
}
-
+
@Override
public void collect(int doc) throws IOException {
- Document document = searcher.doc(docBase + doc);
+ if (hits.size() > 20)
+ return;
+
+ BinaryDocValues cachedBlobHashes = FieldCache.DEFAULT.getTerms(
+ context.reader(), FieldConstants.BLOB_HASH.name(), false);
+ BinaryDocValues cachedBlobPaths = FieldCache.DEFAULT.getTerms(
+ context.reader(), FieldConstants.BLOB_PATH.name(), false);
+
+ String blobHash = cachedBlobHashes.get(doc).utf8ToString();
+ String blobPath = cachedBlobPaths.get(doc).utf8ToString();
+ /*
+ Document document = searcher.doc(context.docBase + doc);
String blobHash = document.get(FieldConstants.BLOB_HASH.name());
String blobPath = document.get(FieldConstants.BLOB_PATH.name());
-
+ */
String blobHashOfCommit = blobHashes.get(blobPath);
if (blobHashOfCommit == null) {
TreeWalk treeWalk = TreeWalk.forPath(repo, blobPath, revTree);
@@ -88,18 +164,17 @@ public class DefaultSearchManager implements SearchManager {
blobHashes.put(blobPath, blobHashOfCommit);
}
if (blobHashOfCommit.equals(blobHash)) {
- byte[] bytes = repo.open(ObjectId.fromString(blobHash)).getCachedBytes();
- String fileContent = new String(bytes, Charsets.detectFrom(bytes));
- analyzers.analyze(fileContent, blobPath);
hits.add(new SearchHit(blobPath, 0, 0, null, null));
+ } else {
+ skipped.incrementAndGet();
}
}
-
+
@Override
public void setNextReader(AtomicReaderContext context) throws IOException {
- docBase = context.docBase;
+ this.context = context;
}
-
+
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
@@ -107,18 +182,22 @@ public class DefaultSearchManager implements SearchManager {
});
+ System.out.println();
+ System.out.println();
+ System.out.println("paths: " + blobHashes.size());
+ System.out.println("skipped: " + skipped.get());
return hits;
- } catch (Exception e) {
- throw Throwables.propagate(e);
} finally {
repo.close();
- }
+ }
+ } finally {
+ searcherManager.release(searcher);
}
- } else {
- return new ArrayList<>();
+ } catch (IOException e) {
+ throw Throwables.propagate(e);
}
- } catch (Exception e) {
- throw Throwables.propagate(e);
+ } else {
+ return new ArrayList<>();
}
}
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/FieldConstants.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/FieldConstants.java
index 5450c713c5..3dbd20afc6 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/FieldConstants.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/FieldConstants.java
@@ -4,7 +4,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;
public enum FieldConstants {
- BLOB_ANALYZER_VERSION, BLOB_HASH, BLOB_PATH, BLOB_DEFS_SYMBOLS, BLOB_SYMBOLS,
+ BLOB_ANALYZER_VERSION, BLOB_HASH, BLOB_PATH, BLOB_SYMBOLS, BLOB_CONTENT,
COMMIT_ANALYZERS_VERSION, COMMIT_HASH,
META, LAST_COMMIT, LAST_COMMIT_HASH, LAST_COMMIT_ANALYZERS_VERSION;
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/IndexRemoving.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/IndexRemoving.java
new file mode 100644
index 0000000000..ab21ce733e
--- /dev/null
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/IndexRemoving.java
@@ -0,0 +1,17 @@
+package com.pmease.gitplex.search;
+
+import com.pmease.gitplex.core.model.Repository;
+
+public class IndexRemoving {
+
+ private final Repository repository;
+
+ public IndexRemoving(Repository repository) {
+ this.repository = repository;
+ }
+
+ public Repository getRepository() {
+ return repository;
+ }
+
+}
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/TriGramAnalyzer.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/TriGramAnalyzer.java
new file mode 100644
index 0000000000..5b50361321
--- /dev/null
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/TriGramAnalyzer.java
@@ -0,0 +1,29 @@
+package com.pmease.gitplex.search;
+
+import java.io.IOException;
+import java.io.Reader;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.Tokenizer;
+import org.apache.lucene.analysis.core.LowerCaseFilter;
+import org.apache.lucene.analysis.ngram.NGramTokenizer;
+
+public class TriGramAnalyzer extends Analyzer {
+
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
+ Tokenizer src = new NGramTokenizer(reader, 3, 3);
+
+ TokenStream tok = new LowerCaseFilter(src);
+
+ return new TokenStreamComponents(src, tok) {
+ @Override
+ protected void setReader(final Reader reader) throws IOException {
+ super.setReader(reader);
+ }
+ };
+
+ }
+
+}
diff --git a/gitplex.search/src/test/java/com/pmease/gitplex/search/DefaultIndexManagerTest.java b/gitplex.search/src/test/java/com/pmease/gitplex/search/DefaultIndexManagerTest.java
index 90cfb3df02..f80e33ed21 100644
--- a/gitplex.search/src/test/java/com/pmease/gitplex/search/DefaultIndexManagerTest.java
+++ b/gitplex.search/src/test/java/com/pmease/gitplex/search/DefaultIndexManagerTest.java
@@ -1,6 +1,6 @@
package com.pmease.gitplex.search;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_DEFS_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_SYMBOLS;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
@@ -95,7 +95,7 @@ public class DefaultIndexManagerTest extends AbstractGitTest {
try (Directory directory = FSDirectory.open(indexDir)) {
try (IndexReader reader = DirectoryReader.open(directory)) {
IndexSearcher searcher = new IndexSearcher(reader);
- TopDocs topDocs = searcher.search(BLOB_DEFS_SYMBOLS.query("name"), Integer.MAX_VALUE);
+ TopDocs topDocs = searcher.search(BLOB_SYMBOLS.query("name"), Integer.MAX_VALUE);
assertEquals(2, topDocs.totalHits);
}
} catch (Exception e) {
@@ -115,7 +115,7 @@ public class DefaultIndexManagerTest extends AbstractGitTest {
try (Directory directory = FSDirectory.open(indexDir)) {
try (IndexReader reader = DirectoryReader.open(directory)) {
IndexSearcher searcher = new IndexSearcher(reader);
- TopDocs topDocs = searcher.search(BLOB_DEFS_SYMBOLS.query("name"), Integer.MAX_VALUE);
+ TopDocs topDocs = searcher.search(BLOB_SYMBOLS.query("name"), Integer.MAX_VALUE);
assertEquals(3, topDocs.totalHits);
}
} catch (Exception e) {
@@ -165,7 +165,7 @@ public class DefaultIndexManagerTest extends AbstractGitTest {
try (Directory directory = FSDirectory.open(indexDir)) {
try (IndexReader reader = DirectoryReader.open(directory)) {
IndexSearcher searcher = new IndexSearcher(reader);
- TopDocs topDocs = searcher.search(BLOB_DEFS_SYMBOLS.query("tiger"), Integer.MAX_VALUE);
+ TopDocs topDocs = searcher.search(BLOB_SYMBOLS.query("tiger"), Integer.MAX_VALUE);
assertEquals(2, topDocs.totalHits);
}
} catch (Exception e) {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/TestPage.java
index 7909b69d42..cb1722f623 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/TestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/TestPage.java
@@ -1,5 +1,6 @@
package com.pmease.gitplex.web.page;
+import org.apache.lucene.search.NGramPhraseQuery;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.link.Link;
@@ -26,9 +27,12 @@ public class TestPage extends CommonPage {
Repository repo = GitPlex.getInstance(Dao.class).load(Repository.class, 1L);
IndexManager indexManager = GitPlex.getInstance(IndexManager.class);
int count = 0;
- for (Commit commit: repo.git().log("master~500", "master", null, 0, 0)) {
- System.out.println(++count);
- indexManager.index(repo, commit.getHash());
+ for (Commit commit: repo.git().log("master~1", "master", null, 0, 0)) {
+ count++;
+// if (count % 100 == 0) {
+ System.out.println(++count);
+ indexManager.index(repo, commit.getHash());
+// }
}
}
@@ -43,8 +47,12 @@ public class TestPage extends CommonPage {
SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
long time = System.currentTimeMillis();
- System.out.println(searchManager.search(repo, repo.git().parseRevision("master", true),
- FieldConstants.BLOB_SYMBOLS.query("string"), null, 0).size());
+ NGramPhraseQuery query = new NGramPhraseQuery(3);
+// query.add(FieldConstants.BLOB_CONTENT.term("cryptd_alloc_aead"));
+ query.add(FieldConstants.BLOB_CONTENT.term("mai"));
+ query.add(FieldConstants.BLOB_CONTENT.term("ain"));
+ System.out.println("found: " + searchManager.search(repo, repo.git().parseRevision("master", true),
+ query, null, 0).size());
System.out.println("time: " + (System.currentTimeMillis()-time));
}