Indexer.java revision 434
1024N/A/*
1024N/A * CDDL HEADER START
1024N/A *
1024N/A * The contents of this file are subject to the terms of the
1024N/A * Common Development and Distribution License (the "License").
1024N/A * You may not use this file except in compliance with the License.
1024N/A *
1024N/A * See LICENSE.txt included in this distribution for the specific
1024N/A * language governing permissions and limitations under the License.
1024N/A *
1024N/A * When distributing Covered Code, include this CDDL HEADER in each
1024N/A * file and include the License file at LICENSE.txt.
1024N/A * If applicable, add the following below this CDDL HEADER, with the
1024N/A * fields enclosed by brackets "[]" replaced with your own identifying
1024N/A * information: Portions Copyright [yyyy] [name of copyright owner]
1024N/A *
1024N/A * CDDL HEADER END
1024N/A */
1024N/A
1024N/A/*
1124N/A * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
1024N/A * Use is subject to license terms.
160N/A */
160N/Apackage org.opensolaris.opengrok.index;
1124N/A
160N/Aimport java.io.BufferedReader;
160N/Aimport java.io.File;
1124N/Aimport java.io.FileReader;
160N/Aimport java.io.IOException;
160N/Aimport java.net.InetAddress;
160N/Aimport java.text.ParseException;
160N/Aimport java.util.ArrayList;
160N/Aimport java.util.Collections;
160N/Aimport java.util.Comparator;
160N/Aimport java.util.List;
160N/Aimport java.util.concurrent.ExecutorService;
160N/Aimport java.util.concurrent.Executors;
160N/Aimport java.util.logging.Level;
160N/Aimport java.util.logging.Logger;
160N/Aimport org.opensolaris.opengrok.OpenGrokLogger;
160N/Aimport org.opensolaris.opengrok.analysis.AnalyzerGuru;
160N/Aimport org.opensolaris.opengrok.configuration.Project;
160N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
160N/Aimport org.opensolaris.opengrok.history.HistoryGuru;
160N/Aimport org.opensolaris.opengrok.util.Getopt;
160N/A
160N/A/**
160N/A * Creates and updates an inverted source index
160N/A * as well as generates Xref, file stats etc., if specified
160N/A * in the options
160N/A */
160N/A@SuppressWarnings({"PMD.AvoidPrintStackTrace","PMD.SystemPrintln"})
160N/Apublic class Indexer {
160N/A
345N/A private static Indexer index = new Indexer();
160N/A private static final Logger log = Logger.getLogger(Indexer.class.getName());
1024N/A
1024N/A public static Indexer getInstance() {
160N/A return index;
1024N/A }
1024N/A /**
160N/A * Program entry point
160N/A * @param argv argument vector
160N/A */
345N/A public static void main(String argv[]) {
160N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
160N/A boolean runIndex = true;
345N/A boolean update = true;
160N/A boolean optimizedChanged = false;
160N/A CommandLineOptions cmdOptions = new CommandLineOptions();
160N/A
160N/A if (argv.length == 0) {
160N/A System.err.println(cmdOptions.getUsage());
160N/A System.exit(1);
160N/A } else {
160N/A boolean searchRepositories = false;
160N/A ArrayList<String> subFiles = new ArrayList<String>();
160N/A ArrayList<String> repositories = new ArrayList<String>();
1185N/A String configFilename = null;
1185N/A String configHost = null;
160N/A boolean addProjects = false;
160N/A boolean refreshHistory = false;
160N/A String defaultProject = null;
1185N/A boolean listFiles = false;
1185N/A boolean createDict = false;
160N/A int noThreads = Runtime.getRuntime().availableProcessors();
1185N/A
1185N/A // Parse command line options:
1185N/A Getopt getopt = new Getopt(argv, cmdOptions.getCommandString());
604N/A
1185N/A try {
1185N/A getopt.parse();
1185N/A } catch (ParseException ex) {
605N/A System.err.println("OpenGrok: " + ex.getMessage());
605N/A System.err.println(cmdOptions.getUsage());
1185N/A System.exit(1);
605N/A }
605N/A
1185N/A try{
1185N/A int cmd;
1185N/A
1185N/A // We need to read the configuration file first, since we
1185N/A // will try to overwrite options..
1185N/A while ((cmd = getopt.getOpt()) != -1) {
1185N/A if (cmd == 'R') {
1185N/A env.readConfiguration(new File(getopt.getOptarg()));
1185N/A break;
605N/A }
160N/A }
160N/A
160N/A // Now we can handle all the other options..
160N/A getopt.reset();
1185N/A while ((cmd = getopt.getOpt()) != -1) {
1185N/A switch (cmd) {
1185N/A case 't':
1185N/A createDict = true;
1185N/A runIndex = false;
1185N/A break;
1185N/A
1185N/A case 'q': env.setVerbose(false); break;
1185N/A case 'e': env.setGenerateHtml(false); break;
1185N/A case 'P': addProjects = true; break;
160N/A case 'p': defaultProject = getopt.getOptarg(); break;
160N/A case 'c': env.setCtags(getopt.getOptarg()); break;
160N/A case 'w': {
160N/A String webapp = getopt.getOptarg();
160N/A if (webapp.startsWith("/") || webapp.startsWith("http")) {
1185N/A ;
1185N/A } else {
1185N/A webapp = "/" + webapp;
160N/A }
160N/A if (webapp.endsWith("/")) {
160N/A env.setUrlPrefix(webapp + "s?");
1185N/A } else {
1185N/A env.setUrlPrefix(webapp + "/s?");
160N/A }
160N/A }
160N/A break;
160N/A case 'W': configFilename = getopt.getOptarg(); break;
1185N/A case 'U': configHost = getopt.getOptarg(); break;
160N/A case 'R':
1185N/A // already handled
160N/A break;
160N/A case 'n': runIndex = false; break;
160N/A case 'H': refreshHistory = true; break;
160N/A case 'h' : repositories.add(getopt.getOptarg()); break;
160N/A case 'r': {
1185N/A if (getopt.getOptarg().equalsIgnoreCase("on")) {
160N/A env.setRemoteScmSupported(true);
160N/A } else if (getopt.getOptarg().equalsIgnoreCase("off")) {
160N/A env.setRemoteScmSupported(false);
160N/A } else {
160N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r");
160N/A System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems");
160N/A System.err.println(" \"-r off\" will ignore SCM for remote systems");
160N/A }
160N/A }
160N/A break;
160N/A case 'O': {
160N/A boolean oldval = env.isOptimizeDatabase();
160N/A if (getopt.getOptarg().equalsIgnoreCase("on")) {
160N/A env.setOptimizeDatabase(true);
160N/A } else if (getopt.getOptarg().equalsIgnoreCase("off")) {
160N/A env.setOptimizeDatabase(false);
292N/A } else {
292N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O");
292N/A System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation");
292N/A System.err.println(" \"-O off\" disable optimization of the index database");
160N/A }
160N/A if (oldval != env.isOptimizeDatabase()) {
160N/A optimizedChanged = true;
160N/A }
160N/A }
160N/A break;
160N/A case 'v': env.setVerbose(true); break;
160N/A
1025N/A case 's': {
1025N/A File file = new File(getopt.getOptarg());
1025N/A if (!file.isDirectory()) {
1185N/A System.err.println("ERROR: No such directory: " + file.toString());
1185N/A System.exit(1);
1185N/A }
1185N/A
1185N/A env.setSourceRootFile(file);
1185N/A break;
1185N/A }
1185N/A case 'd':
1185N/A env.setDataRoot(getopt.getOptarg());
1185N/A break;
1185N/A case 'i':
1185N/A env.getIgnoredNames().add(getopt.getOptarg());
1185N/A break;
1185N/A case 'S' : searchRepositories = true; break;
1185N/A case 'Q' :
1185N/A if (getopt.getOptarg().equalsIgnoreCase("on")) {
1185N/A env.setQuickContextScan(true);
1185N/A } else if (getopt.getOptarg().equalsIgnoreCase("off")) {
1185N/A env.setQuickContextScan(false);
1185N/A } else {
1185N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q");
1185N/A System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\"");
1185N/A System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file.");
1185N/A }
1185N/A
1185N/A break;
1185N/A case 'm' : {
1185N/A try {
1185N/A env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg()));
1185N/A } catch (NumberFormatException exp) {
1185N/A System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage());
1185N/A System.exit(1);
1185N/A }
1185N/A break;
1185N/A }
1185N/A case 'a' :
1185N/A if (getopt.getOptarg().equalsIgnoreCase("on")) {
1185N/A env.setAllowLeadingWildcard(true);
1185N/A } else if (getopt.getOptarg().equalsIgnoreCase("off")) {
1185N/A env.setAllowLeadingWildcard(false);
1025N/A } else {
1124N/A System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a");
1124N/A System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard");
1124N/A System.err.println(" \"-a off\" will disallow a search to start with a wildcard");
1124N/A System.exit(1);
1124N/A }
1124N/A
1124N/A break;
1124N/A
1124N/A case 'A': {
1124N/A String[] arg = getopt.getOptarg().split(":");
1124N/A if (arg.length != 2) {
1124N/A System.err.println("ERROR: You must specify: -A extension:class");
1124N/A System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer");
1124N/A System.err.println(" will use the C analyzer for all files ending with .foo");
1124N/A System.err.println(" Ex: -A c:-");
1145N/A System.err.println(" will disable the c-analyzer for for all files ending with .c");
1145N/A System.exit(1);
1145N/A }
1145N/A
1145N/A arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase();
1145N/A if (arg[1].equals("-")) {
1024N/A AnalyzerGuru.addExtension(arg[0], null);
1025N/A break;
}
try {
AnalyzerGuru.addExtension(
arg[0],
AnalyzerGuru.findFactory(arg[1]));
} catch (Exception e) {
System.err.println("Unable to use " + arg[1] +
" as a FileAnalyzerFactory");
e.printStackTrace();
System.exit(1);
}
}
break;
case 'L' :
env.setWebappLAF(getopt.getOptarg());
break;
case 'T' :
try {
noThreads = Integer.parseInt(getopt.getOptarg());
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-T\": " + exp.getMessage());
System.exit(1);
}
break;
case 'l' :
if (getopt.getOptarg().equalsIgnoreCase("on")) {
env.setUsingLuceneLocking(true);
} else if (getopt.getOptarg().equalsIgnoreCase("off")) {
env.setUsingLuceneLocking(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -l");
System.err.println(" Ex: \"-l on\" will enable locks in Lucene");
System.err.println(" \"-l off\" will disable locks in Lucene");
}
break;
case '?':
System.err.println(cmdOptions.getUsage());
System.exit(0);
break;
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;
}
}
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,
ArrayList<String> subFiles,
ArrayList<String> repositories) throws IndexerException,IOException {
if (env.getDataRootPath() == null) {
throw new IndexerException("ERROR: Please specify a DATA ROOT path");
}
if (env.getSourceRootFile() == null) {
File srcConfig = new File(env.getDataRootPath(), "SRC_ROOT");
String line = null;
if(srcConfig.exists()) {
try {
BufferedReader sr = new BufferedReader(new FileReader(srcConfig));
line = sr.readLine();
sr.close();
} catch (IOException e) {
}
}
if(line == null) {
throw new IndexerException("ERROR: please specify a SRC_ROOT with option -s !");
}
env.setSourceRoot(line);
if (!env.getSourceRootFile().isDirectory()) {
throw new IndexerException("ERROR: No such directory:" + line);
}
}
if (!env.validateExuberantCtags()) {
throw new IndexerException("Didn't find Exuberant Ctags");
}
if (searchRepositories) {
if (env.isVerbose()) {
System.out.println("Scanning for repositories...");
}
env.getRepositories().clear();
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()) {
projects.add(new Project(file.getName(), "/" + file.getName()));
}
}
// 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.size() > 0) {
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(project);
} else {
db = new IndexDatabase();
}
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) {
e.printStackTrace();
}
}
});
}
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
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 successfully updated");
}
}
}
private Indexer() {
}
}