Indexer.java revision 930
0N/A/*
0N/A * CDDL HEADER START
0N/A *
0N/A * The contents of this file are subject to the terms of the
0N/A * Common Development and Distribution License (the "License").
0N/A * You may not use this file except in compliance with the License.
0N/A *
0N/A * See LICENSE.txt included in this distribution for the specific
0N/A * language governing permissions and limitations under the License.
0N/A *
0N/A * When distributing Covered Code, include this CDDL HEADER in each
0N/A * file and include the License file at LICENSE.txt.
0N/A * If applicable, add the following below this CDDL HEADER, with the
0N/A * fields enclosed by brackets "[]" replaced with your own identifying
0N/A * information: Portions Copyright [yyyy] [name of copyright owner]
0N/A *
0N/A * CDDL HEADER END
0N/A */
0N/A
0N/A/*
0N/A * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
0N/A * Use is subject to license terms.
0N/A */
0N/Apackage org.opensolaris.opengrok.index;
0N/A
65N/Aimport java.io.File;
0N/Aimport java.io.IOException;
0N/Aimport java.net.InetAddress;
58N/Aimport java.text.ParseException;
77N/Aimport java.util.ArrayList;
0N/Aimport java.util.Collections;
0N/Aimport java.util.Comparator;
0N/Aimport java.util.List;
2N/Aimport java.util.concurrent.ExecutorService;
0N/Aimport java.util.concurrent.Executors;
58N/Aimport java.util.concurrent.TimeUnit;
58N/Aimport java.util.logging.Level;
8N/Aimport java.util.logging.Logger;
30N/Aimport org.opensolaris.opengrok.Info;
0N/Aimport org.opensolaris.opengrok.OpenGrokLogger;
77N/Aimport org.opensolaris.opengrok.analysis.AnalyzerGuru;
0N/Aimport org.opensolaris.opengrok.configuration.Project;
0N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
0N/Aimport org.opensolaris.opengrok.history.HistoryGuru;
0N/Aimport org.opensolaris.opengrok.util.Getopt;
0N/A
0N/A/**
0N/A * Creates and updates an inverted source index
0N/A * as well as generates Xref, file stats etc., if specified
77N/A * in the options
0N/A */
0N/A@SuppressWarnings({"PMD.AvoidPrintStackTrace", "PMD.SystemPrintln"})
0N/Apublic final class Indexer {
0N/A
58N/A private final static String ON = "on";
58N/A private final static String OFF = "off";
58N/A private static Indexer index = new Indexer();
58N/A private static final Logger log = Logger.getLogger(Indexer.class.getName());
77N/A
58N/A private static final String DERBY_EMBEDDED_DRIVER =
58N/A "org.apache.derby.jdbc.EmbeddedDriver";
0N/A
0N/A private static final String DERBY_CLIENT_DRIVER =
99N/A "org.apache.derby.jdbc.ClientDriver";
77N/A
0N/A public static Indexer getInstance() {
0N/A return index;
0N/A }
0N/A
0N/A /**
0N/A * Program entry point
0N/A * @param argv argument vector
0N/A */
0N/A @SuppressWarnings("PMD.UseStringBufferForStringAppends")
77N/A public static void main(String argv[]) {
99N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
77N/A boolean runIndex = true;
65N/A boolean update = true;
65N/A boolean optimizedChanged = false;
65N/A CommandLineOptions cmdOptions = new CommandLineOptions();
65N/A
0N/A if (argv.length == 0) {
30N/A System.err.println(cmdOptions.getUsage());
58N/A System.exit(1);
77N/A } else {
0N/A boolean searchRepositories = false;
0N/A ArrayList<String> subFiles = new ArrayList<String>();
0N/A ArrayList<String> repositories = new ArrayList<String>();
0N/A String configFilename = null;
0N/A String configHost = null;
0N/A boolean addProjects = false;
0N/A boolean refreshHistory = false;
0N/A String defaultProject = null;
0N/A boolean listFiles = false;
0N/A boolean createDict = false;
0N/A int noThreads = 2 + (2 * Runtime.getRuntime().availableProcessors());
11N/A
0N/A // Parse command line options:
58N/A Getopt getopt = new Getopt(argv, cmdOptions.getCommandString());
58N/A
58N/A try {
58N/A getopt.parse();
77N/A } catch (ParseException ex) {
77N/A System.err.println("OpenGrok: " + ex.getMessage());
77N/A System.err.println(cmdOptions.getUsage());
77N/A System.exit(1);
77N/A }
77N/A
77N/A try {
77N/A int cmd;
77N/A
77N/A // We need to read the configuration file first, since we
77N/A // will try to overwrite options..
77N/A while ((cmd = getopt.getOpt()) != -1) {
0N/A if (cmd == 'R') {
77N/A env.readConfiguration(new File(getopt.getOptarg()));
77N/A break;
77N/A }
99N/A }
99N/A
99N/A String databaseDriver = env.getDatabaseDriver();
99N/A String databaseURL = env.getDatabaseUrl();
77N/A
77N/A // Now we can handle all the other options..
77N/A getopt.reset();
77N/A while ((cmd = getopt.getOpt()) != -1) {
77N/A switch (cmd) {
77N/A case 't':
77N/A createDict = true;
77N/A runIndex = false;
77N/A break;
77N/A
77N/A case 'q':
77N/A env.setVerbose(false);
77N/A break;
77N/A case 'e':
77N/A env.setGenerateHtml(false);
77N/A break;
99N/A case 'P':
77N/A addProjects = true;
77N/A break;
77N/A case 'p':
77N/A defaultProject = getopt.getOptarg();
77N/A break;
77N/A case 'c':
77N/A env.setCtags(getopt.getOptarg());
77N/A break;
0N/A case 'w':
77N/A {
77N/A String webapp = getopt.getOptarg();
77N/A if (webapp.charAt(0) != '/' && !webapp.startsWith("http")) {
77N/A webapp = "/" + webapp;
77N/A }
77N/A if (webapp.endsWith("/")) {
77N/A env.setUrlPrefix(webapp + "s?");
77N/A } else {
77N/A env.setUrlPrefix(webapp + "/s?");
77N/A }
77N/A }
77N/A break;
77N/A case 'W':
77N/A configFilename = getopt.getOptarg();
77N/A break;
77N/A case 'U':
99N/A configHost = getopt.getOptarg();
77N/A break;
77N/A case 'R':
77N/A // already handled
77N/A break;
77N/A case 'n':
0N/A runIndex = false;
0N/A break;
77N/A case 'H':
77N/A refreshHistory = true;
77N/A break;
77N/A case 'h':
77N/A repositories.add(getopt.getOptarg());
99N/A break;
77N/A case 'D':
99N/A env.setStoreHistoryCacheInDB(true);
99N/A break;
99N/A case 'j':
99N/A databaseDriver = getopt.getOptarg();
99N/A // Should be a full class name, but we also accept
99N/A // the shorthands "client" and "embedded". Expand
99N/A // the shorthands here.
99N/A if ("client".equals(databaseDriver)) {
99N/A databaseDriver = DERBY_CLIENT_DRIVER;
77N/A } else if ("embedded".equals(databaseDriver)) {
99N/A databaseDriver = DERBY_EMBEDDED_DRIVER;
0N/A }
0N/A break;
0N/A case 'u':
77N/A databaseURL = getopt.getOptarg();
77N/A break;
77N/A case 'r':
77N/A {
77N/A if (getopt.getOptarg().equalsIgnoreCase(ON)) {
77N/A env.setRemoteScmSupported(true);
77N/A } else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
77N/A env.setRemoteScmSupported(false);
77N/A } else {
77N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r");
77N/A System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems");
77N/A System.err.println(" \"-r off\" will ignore SCM for remote systems");
77N/A }
58N/A }
58N/A break;
77N/A case 'O':
77N/A {
0N/A boolean oldval = env.isOptimizeDatabase();
0N/A if (getopt.getOptarg().equalsIgnoreCase(ON)) {
77N/A env.setOptimizeDatabase(true);
58N/A } else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
58N/A env.setOptimizeDatabase(false);
58N/A } else {
0N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O");
0N/A System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation");
0N/A System.err.println(" \"-O off\" disable optimization of the index database");
58N/A }
0N/A if (oldval != env.isOptimizeDatabase()) {
0N/A optimizedChanged = true;
0N/A }
0N/A }
58N/A break;
0N/A case 'v':
0N/A env.setVerbose(true);
0N/A break;
0N/A
58N/A case 's':
77N/A {
58N/A env.setSourceRoot(getopt.getOptarg());
58N/A File file = env.getSourceRootFile();
0N/A if (!file.isDirectory()) {
0N/A System.err.println("ERROR: source root must be a directory: " + file.toString());
0N/A System.exit(1);
0N/A }
77N/A }
99N/A break;
0N/A case 'd':
0N/A {
77N/A env.setDataRoot(getopt.getOptarg());
11N/A File file = env.getDataRootFile();
99N/A if (!file.isDirectory()) {
99N/A System.err.println("ERROR: data root must be a directory: " + file.toString());
99N/A System.exit(1);
99N/A }
11N/A }
58N/A break;
11N/A case 'i':
99N/A env.getIgnoredNames().add(getopt.getOptarg());
99N/A break;
99N/A case 'S':
11N/A searchRepositories = true;
77N/A break;
58N/A case 'Q':
77N/A if (getopt.getOptarg().equalsIgnoreCase(ON)) {
70N/A env.setQuickContextScan(true);
70N/A } else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
58N/A env.setQuickContextScan(false);
77N/A } else {
70N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q");
58N/A System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\"");
58N/A System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file.");
77N/A }
77N/A
99N/A break;
99N/A case 'm': {
99N/A try {
99N/A env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg()));
77N/A } catch (NumberFormatException exp) {
77N/A System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage());
77N/A System.exit(1);
77N/A }
77N/A break;
77N/A }
77N/A case 'a':
77N/A if (getopt.getOptarg().equalsIgnoreCase(ON)) {
77N/A env.setAllowLeadingWildcard(true);
77N/A } else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
58N/A env.setAllowLeadingWildcard(false);
77N/A } else {
77N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a");
77N/A System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard");
77N/A System.err.println(" \"-a off\" will disallow a search to start with a wildcard");
77N/A System.exit(1);
77N/A }
77N/A
77N/A break;
77N/A
99N/A case 'A':
58N/A {
99N/A String[] arg = getopt.getOptarg().split(":");
99N/A if (arg.length != 2) {
99N/A System.err.println("ERROR: You must specify: -A extension:class");
99N/A System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer");
58N/A System.err.println(" will use the C analyzer for all files ending with .foo");
99N/A System.err.println(" Ex: -A c:-");
99N/A System.err.println(" will disable the c-analyzer for for all files ending with .c");
99N/A System.exit(1);
99N/A }
58N/A
77N/A arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase();
58N/A if (arg[1].equals("-")) {
58N/A AnalyzerGuru.addExtension(arg[0], null);
58N/A break;
58N/A }
58N/A
58N/A try {
58N/A AnalyzerGuru.addExtension(
58N/A arg[0],
58N/A AnalyzerGuru.findFactory(arg[1]));
58N/A } catch (Exception e) {
58N/A System.err.println("Unable to use " + arg[1] +
58N/A " as a FileAnalyzerFactory");
99N/A e.printStackTrace();
65N/A System.exit(1);
58N/A }
58N/A }
58N/A break;
58N/A case 'L':
99N/A env.setWebappLAF(getopt.getOptarg());
99N/A break;
99N/A case 'T':
58N/A try {
58N/A noThreads = Integer.parseInt(getopt.getOptarg());
58N/A } catch (NumberFormatException exp) {
58N/A System.err.println("ERROR: Failed to parse argument to \"-T\": " + exp.getMessage());
58N/A System.exit(1);
58N/A }
58N/A break;
58N/A case 'l':
58N/A if (getopt.getOptarg().equalsIgnoreCase(ON)) {
58N/A env.setUsingLuceneLocking(true);
58N/A } else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
58N/A env.setUsingLuceneLocking(false);
58N/A } else {
58N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -l");
58N/A System.err.println(" Ex: \"-l on\" will enable locks in Lucene");
58N/A System.err.println(" \"-l off\" will disable locks in Lucene");
99N/A }
99N/A break;
99N/A case 'V':
58N/A System.out.println(Info.getFullVersion());
58N/A System.exit(0);
0N/A break;
99N/A
0N/A case '?':
0N/A System.err.println(cmdOptions.getUsage());
0N/A System.exit(0);
0N/A break;
0N/A
default:
System.err.println("Internal Error - Unimplemented cmdline option: " + (char) cmd);
System.exit(1);
}
}
int optind = getopt.getOptind();
if (optind != -1) {
while (optind < argv.length) {
subFiles.add(argv[optind]);
++optind;
}
}
if (env.storeHistoryCacheInDB()) {
// The default database driver is Derby's client driver.
if (databaseDriver == null) {
databaseDriver = DERBY_CLIENT_DRIVER;
}
// The default URL depends on the database driver.
if (databaseURL == null) {
StringBuilder defaultURL = new StringBuilder();
defaultURL.append("jdbc:derby:");
if (databaseDriver.equals(DERBY_EMBEDDED_DRIVER)) {
defaultURL
.append(env.getDataRootPath())
.append(File.separator);
} else {
defaultURL.append("//localhost/");
}
defaultURL.append("cachedb;create=true");
databaseURL = defaultURL.toString();
}
}
env.setDatabaseDriver(databaseDriver);
env.setDatabaseUrl(databaseURL);
getInstance().prepareIndexer(env, searchRepositories, addProjects,
defaultProject, configFilename, refreshHistory,
listFiles, createDict, subFiles, repositories);
if (runIndex || (optimizedChanged && env.isOptimizeDatabase())) {
IndexChangedListener progress = new DefaultIndexChangedListener();
getInstance().doIndexerExecution(update, noThreads, subFiles,
progress);
}
getInstance().sendToConfigHost(env, configHost);
} catch (IndexerException ex) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ex);
System.err.println(cmdOptions.getUsage());
System.exit(1);
} catch (IOException ioe) {
System.err.println("Got IOException " + ioe);
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ioe);
System.exit(1);
}
}
}
public void prepareIndexer(RuntimeEnvironment env,
boolean searchRepositories,
boolean addProjects,
String defaultProject,
String configFilename,
boolean refreshHistory,
boolean listFiles,
boolean createDict,
List<String> subFiles,
List<String> repositories) throws IndexerException, IOException {
if (env.getDataRootPath() == null) {
throw new IndexerException("ERROR: Please specify a DATA ROOT path");
}
if (env.getSourceRootFile() == null) {
throw new IndexerException("ERROR: please specify a SRC_ROOT with option -s !");
}
if (!env.validateExuberantCtags()) {
throw new IndexerException("Didn't find Exuberant Ctags");
}
if (searchRepositories) {
if (env.isVerbose()) {
System.out.println("Scanning for repositories...");
}
long start = System.currentTimeMillis();
HistoryGuru.getInstance().addRepositories(env.getSourceRootPath());
long time = (System.currentTimeMillis() - start) / 1000;
if (env.isVerbose()) {
System.out.println("Done searching for repositories (" + time + "s)");
}
}
if (addProjects) {
File files[] = env.getSourceRootFile().listFiles();
List<Project> projects = env.getProjects();
projects.clear();
for (File file : files) {
if (!file.getName().startsWith(".") && file.isDirectory()) {
Project p = new Project();
String name = file.getName();
p.setDescription(name);
p.setPath("/" + name);
projects.add(p);
}
}
// The projects should be sorted...
Collections.sort(projects, new Comparator<Project>() {
public int compare(Project p1, Project p2) {
String s1 = p1.getDescription();
String s2 = p2.getDescription();
int ret;
if (s1 == null) {
ret = (s2 == null) ? 0 : 1;
} else {
ret = s1.compareTo(s2);
}
return ret;
}
});
}
if (defaultProject != null) {
for (Project p : env.getProjects()) {
if (p.getPath().equals(defaultProject)) {
env.setDefaultProject(p);
break;
}
}
}
if (configFilename != null) {
if (env.isVerbose()) {
System.out.println("Writing configuration to " + configFilename);
System.out.flush();
}
env.writeConfiguration(new File(configFilename));
if (env.isVerbose()) {
System.out.println("Done...");
System.out.flush();
}
}
if (refreshHistory) {
HistoryGuru.getInstance().createCache();
} else if (repositories != null && !repositories.isEmpty()) {
HistoryGuru.getInstance().createCache(repositories);
}
if (listFiles) {
IndexDatabase.listAllFiles(subFiles);
}
if (createDict) {
IndexDatabase.listFrequentTokens(subFiles);
}
}
public void doIndexerExecution(final boolean update, int noThreads, List<String> subFiles,
IndexChangedListener progress)
throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
env.register();
log.info("Starting indexExecution");
ExecutorService executor = Executors.newFixedThreadPool(noThreads);
if (subFiles == null || subFiles.isEmpty()) {
if (update) {
IndexDatabase.updateAll(executor, progress);
} else if (env.isOptimizeDatabase()) {
IndexDatabase.optimizeAll(executor);
}
} else {
List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null && env.hasProjects()) {
System.err.println("Warning: Could not find a project for \"" + path + "\"");
} else {
IndexDatabase db;
if (project == null) {
db = new IndexDatabase();
} else {
db = new IndexDatabase(project);
}
int idx = dbs.indexOf(db);
if (idx != -1) {
db = dbs.get(idx);
}
if (db.addDirectory(path)) {
if (idx == -1) {
dbs.add(db);
}
} else {
System.err.println("Warning: Directory does not exist \"" + path + "\"");
}
}
}
for (final IndexDatabase db : dbs) {
final boolean optimize = env.isOptimizeDatabase();
db.addIndexChangedListener(progress);
executor.submit(new Runnable() {
public void run() {
try {
if (update) {
db.update();
} else if (optimize) {
db.optimize();
}
} catch (Exception e) {
if (update) {
OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while updating index", e);
} else {
OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while optimizing index", e);
}
e.printStackTrace();
}
}
});
}
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
// Wait forever
executor.awaitTermination(999,TimeUnit.DAYS);
} catch (InterruptedException exp) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Received interrupt while waiting for executor to finish", exp);
}
}
}
public void sendToConfigHost(RuntimeEnvironment env, String configHost) {
if (configHost != null) {
String[] cfg = configHost.split(":");
if (env.isVerbose()) {
log.info("Send configuration to: " + configHost);
}
if (cfg.length == 2) {
try {
InetAddress host = InetAddress.getByName(cfg[0]);
RuntimeEnvironment.getInstance().writeConfiguration(host, Integer.parseInt(cfg[1]));
} catch (Exception ex) {
log.log(Level.SEVERE, "Failed to send configuration to " + configHost, ex);
}
} else {
System.err.println("Syntax error: ");
for (String s : cfg) {
System.err.print("[" + s + "]");
}
System.err.println();
}
if (env.isVerbose()) {
log.info("Configuration update routine done, check previous output for errors.");
}
}
}
private Indexer() {
}
}