Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

SOLR-17544: Prevent conflicting connection flags from being used via OptionGroup (#2725)

Eric Pugh01b38b35171d
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 751e19073fd..3a03a54985a 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -26,6 +26,8 @@ Improvements
* SOLR-16116: Apache Curator is now used to manage all Solr Zookeeper interactions. This should provide more stability in the Solr-Zookeeper interactions.
The solrj-zookeeper module, now has a dependency on curator. (Houston Putman, Kevin Risden, Mike Drob, David Smiley)
+* SOLR-17544: Solr CLI will now stop when you combine mutually exclusive options. Combining -s and -z options is a common example. (Eric Pugh, Christos Malliaridis)
+
Optimizations
---------------------
(No changes)
diff --git a/solr/core/src/java/org/apache/solr/cli/ApiTool.java b/solr/core/src/java/org/apache/solr/cli/ApiTool.java
index e9af6116fa9..02f893b3753 100644
--- a/solr/core/src/java/org/apache/solr/cli/ApiTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ApiTool.java
@@ -19,9 +19,9 @@ package org.apache.solr.cli;
import java.io.PrintStream;
import java.net.URI;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.JsonMapResponseParser;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
@@ -36,6 +36,16 @@ import org.noggit.JSONWriter;
* <p>Used to send an arbitrary HTTP request to a Solr API endpoint.
*/
public class ApiTool extends ToolBase {
+
+ private static final Option SOLR_URL_OPTION =
+ Option.builder("s")
+ .longOpt("solr-url")
+ .hasArg()
+ .argName("URL")
+ .required()
+ .desc("Send a GET request to a Solr API endpoint.")
+ .build();
+
public ApiTool() {
this(CLIO.getOutStream());
}
@@ -50,22 +60,16 @@ public class ApiTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("solr-url")
- .argName("URL")
- .hasArg()
- .required(true)
- .desc("Send a GET request to a Solr API endpoint.")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(SOLR_URL_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- String getUrl = cli.getOptionValue("solr-url");
- String response = callGet(getUrl, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ String getUrl = cli.getOptionValue(SOLR_URL_OPTION);
+ String response = callGet(getUrl, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
// pretty-print the response to stdout
echo(response);
diff --git a/solr/core/src/java/org/apache/solr/cli/AssertTool.java b/solr/core/src/java/org/apache/solr/cli/AssertTool.java
index 966e7993146..b710d0934b2 100644
--- a/solr/core/src/java/org/apache/solr/cli/AssertTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/AssertTool.java
@@ -23,10 +23,11 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileOwnerAttributeView;
-import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionGroup;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.HealthCheckRequest;
@@ -44,6 +45,105 @@ public class AssertTool extends ToolBase {
private static boolean useExitCode = false;
private static Long timeoutMs = 1000L;
+ private static final Option IS_NOT_ROOT_OPTION =
+ Option.builder().desc("Asserts that we are NOT the root user.").longOpt("not-root").build();
+
+ private static final Option IS_ROOT_OPTION =
+ Option.builder().desc("Asserts that we are the root user.").longOpt("root").build();
+
+ private static final OptionGroup ROOT_OPTION =
+ new OptionGroup().addOption(IS_NOT_ROOT_OPTION).addOption(IS_ROOT_OPTION);
+
+ private static final Option IS_NOT_RUNNING_ON_OPTION =
+ Option.builder()
+ .desc("Asserts that Solr is NOT running on a certain URL. Default timeout is 1000ms.")
+ .longOpt("not-started")
+ .hasArg()
+ .argName("url")
+ .build();
+
+ private static final Option IS_RUNNING_ON_OPTION =
+ Option.builder()
+ .desc("Asserts that Solr is running on a certain URL. Default timeout is 1000ms.")
+ .longOpt("started")
+ .hasArg()
+ .argName("url")
+ .build();
+
+ private static final OptionGroup RUNNING_OPTION =
+ new OptionGroup().addOption(IS_NOT_RUNNING_ON_OPTION).addOption(IS_RUNNING_ON_OPTION);
+
+ private static final Option SAME_USER_OPTION =
+ Option.builder()
+ .desc("Asserts that we run as same user that owns <directory>.")
+ .longOpt("same-user")
+ .hasArg()
+ .argName("directory")
+ .build();
+
+ private static final Option DIRECTORY_EXISTS_OPTION =
+ Option.builder()
+ .desc("Asserts that directory <directory> exists.")
+ .longOpt("exists")
+ .hasArg()
+ .argName("directory")
+ .build();
+
+ private static final Option DIRECTORY_NOT_EXISTS_OPTION =
+ Option.builder()
+ .desc("Asserts that directory <directory> does NOT exist.")
+ .longOpt("not-exists")
+ .hasArg()
+ .argName("directory")
+ .build();
+
+ private static final OptionGroup DIRECTORY_OPTION =
+ new OptionGroup().addOption(DIRECTORY_EXISTS_OPTION).addOption(DIRECTORY_NOT_EXISTS_OPTION);
+
+ private static final Option IS_CLOUD_OPTION =
+ Option.builder()
+ .desc(
+ "Asserts that Solr is running in cloud mode. Also fails if Solr not running. URL should be for root Solr path.")
+ .longOpt("cloud")
+ .hasArg()
+ .argName("url")
+ .build();
+
+ private static final Option IS_NOT_CLOUD_OPTION =
+ Option.builder()
+ .desc(
+ "Asserts that Solr is not running in cloud mode. Also fails if Solr not running. URL should be for root Solr path.")
+ .longOpt("not-cloud")
+ .hasArg()
+ .argName("url")
+ .build();
+
+ private static final OptionGroup CLOUD_OPTION =
+ new OptionGroup().addOption(IS_CLOUD_OPTION).addOption(IS_NOT_CLOUD_OPTION);
+
+ private static final Option MESSAGE_OPTION =
+ Option.builder()
+ .desc("Exception message to be used in place of the default error message.")
+ .longOpt("message")
+ .hasArg()
+ .argName("message")
+ .build();
+
+ private static final Option TIMEOUT_OPTION =
+ Option.builder()
+ .desc("Timeout in ms for commands supporting a timeout.")
+ .longOpt("timeout")
+ .hasArg()
+ .type(Long.class)
+ .argName("ms")
+ .build();
+
+ private static final Option EXIT_CODE_OPTION =
+ Option.builder()
+ .desc("Return an exit code instead of printing error message on assert fail.")
+ .longOpt("exitcode")
+ .build();
+
public AssertTool() {
this(CLIO.getOutStream());
}
@@ -58,72 +158,17 @@ public class AssertTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder().desc("Asserts that we are NOT the root user.").longOpt("not-root").build(),
- Option.builder().desc("Asserts that we are the root user.").longOpt("root").build(),
- Option.builder()
- .desc("Asserts that Solr is NOT running on a certain URL. Default timeout is 1000ms.")
- .longOpt("not-started")
- .hasArg(true)
- .argName("url")
- .build(),
- Option.builder()
- .desc("Asserts that Solr is running on a certain URL. Default timeout is 1000ms.")
- .longOpt("started")
- .hasArg(true)
- .argName("url")
- .build(),
- Option.builder()
- .desc("Asserts that we run as same user that owns <directory>.")
- .longOpt("same-user")
- .hasArg(true)
- .argName("directory")
- .build(),
- Option.builder()
- .desc("Asserts that directory <directory> exists.")
- .longOpt("exists")
- .hasArg(true)
- .argName("directory")
- .build(),
- Option.builder()
- .desc("Asserts that directory <directory> does NOT exist.")
- .longOpt("not-exists")
- .hasArg(true)
- .argName("directory")
- .build(),
- Option.builder()
- .desc(
- "Asserts that Solr is running in cloud mode. Also fails if Solr not running. URL should be for root Solr path.")
- .longOpt("cloud")
- .hasArg(true)
- .argName("url")
- .build(),
- Option.builder()
- .desc(
- "Asserts that Solr is not running in cloud mode. Also fails if Solr not running. URL should be for root Solr path.")
- .longOpt("not-cloud")
- .hasArg(true)
- .argName("url")
- .build(),
- Option.builder()
- .desc("Exception message to be used in place of the default error message.")
- .longOpt("message")
- .hasArg(true)
- .argName("message")
- .build(),
- Option.builder()
- .desc("Timeout in ms for commands supporting a timeout.")
- .longOpt("timeout")
- .hasArg(true)
- .type(Long.class)
- .argName("ms")
- .build(),
- Option.builder()
- .desc("Return an exit code instead of printing error message on assert fail.")
- .longOpt("exitcode")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOptionGroup(ROOT_OPTION)
+ .addOptionGroup(RUNNING_OPTION)
+ .addOption(SAME_USER_OPTION)
+ .addOptionGroup(DIRECTORY_OPTION)
+ .addOptionGroup(CLOUD_OPTION)
+ .addOption(MESSAGE_OPTION)
+ .addOption(TIMEOUT_OPTION)
+ .addOption(EXIT_CODE_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION);
}
/**
@@ -137,8 +182,6 @@ public class AssertTool extends ToolBase {
*/
@Override
public int runTool(CommandLine cli) throws Exception {
- verbose = cli.hasOption(SolrCLI.OPTION_VERBOSE.getLongOpt());
-
int toolExitStatus;
try {
toolExitStatus = runAssert(cli);
@@ -146,7 +189,7 @@ public class AssertTool extends ToolBase {
// since this is a CLI, spare the user the stacktrace
String excMsg = exc.getMessage();
if (excMsg != null) {
- if (verbose) {
+ if (isVerbose()) {
CLIO.err("\nERROR: " + exc + "\n");
} else {
CLIO.err("\nERROR: " + excMsg + "\n");
@@ -172,58 +215,49 @@ public class AssertTool extends ToolBase {
* @throws Exception if a tool failed, e.g. authentication failure
*/
protected int runAssert(CommandLine cli) throws Exception {
- if (cli.hasOption("m")) {
- message = cli.getOptionValue("m");
- }
- if (cli.hasOption("message")) {
- message = cli.getOptionValue("message");
- }
- if (cli.hasOption("timeout")) {
- timeoutMs = cli.getParsedOptionValue("timeout");
- }
- if (cli.hasOption("exitcode")) {
- useExitCode = true;
- }
+ message = cli.getOptionValue(MESSAGE_OPTION);
+ timeoutMs = cli.getParsedOptionValue(TIMEOUT_OPTION, timeoutMs);
+ useExitCode = cli.hasOption(EXIT_CODE_OPTION);
int ret = 0;
- if (cli.hasOption("root")) {
+ if (cli.hasOption(IS_ROOT_OPTION)) {
ret += assertRootUser();
}
- if (cli.hasOption("not-root")) {
+ if (cli.hasOption(IS_NOT_ROOT_OPTION)) {
ret += assertNotRootUser();
}
- if (cli.hasOption("exists")) {
- ret += assertFileExists(cli.getOptionValue("exists"));
+ if (cli.hasOption(DIRECTORY_EXISTS_OPTION)) {
+ ret += assertFileExists(cli.getOptionValue(DIRECTORY_EXISTS_OPTION));
}
- if (cli.hasOption("not-exists")) {
- ret += assertFileNotExists(cli.getOptionValue("not-exists"));
+ if (cli.hasOption(DIRECTORY_NOT_EXISTS_OPTION)) {
+ ret += assertFileNotExists(cli.getOptionValue(DIRECTORY_NOT_EXISTS_OPTION));
}
- if (cli.hasOption("same-user")) {
- ret += sameUser(cli.getOptionValue("same-user"));
+ if (cli.hasOption(SAME_USER_OPTION)) {
+ ret += sameUser(cli.getOptionValue(SAME_USER_OPTION));
}
- if (cli.hasOption("started")) {
+ if (cli.hasOption(IS_RUNNING_ON_OPTION)) {
ret +=
assertSolrRunning(
- cli.getOptionValue("started"),
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ cli.getOptionValue(IS_RUNNING_ON_OPTION),
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
}
- if (cli.hasOption("not-started")) {
+ if (cli.hasOption(IS_NOT_RUNNING_ON_OPTION)) {
ret +=
assertSolrNotRunning(
- cli.getOptionValue("not-started"),
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ cli.getOptionValue(IS_NOT_RUNNING_ON_OPTION),
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
}
- if (cli.hasOption("cloud")) {
+ if (cli.hasOption(IS_CLOUD_OPTION)) {
ret +=
assertSolrRunningInCloudMode(
- SolrCLI.normalizeSolrUrl(cli.getOptionValue("cloud")),
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ SolrCLI.normalizeSolrUrl(cli.getOptionValue(IS_CLOUD_OPTION)),
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
}
- if (cli.hasOption("not-cloud")) {
+ if (cli.hasOption(IS_NOT_CLOUD_OPTION)) {
ret +=
assertSolrNotRunningInCloudMode(
- SolrCLI.normalizeSolrUrl(cli.getOptionValue("not-cloud")),
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ SolrCLI.normalizeSolrUrl(cli.getOptionValue(IS_NOT_CLOUD_OPTION)),
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
}
return ret;
}
diff --git a/solr/core/src/java/org/apache/solr/cli/AuthTool.java b/solr/core/src/java/org/apache/solr/cli/AuthTool.java
index bc091073170..817b0093748 100644
--- a/solr/core/src/java/org/apache/solr/cli/AuthTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/AuthTool.java
@@ -35,8 +35,8 @@ import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.lucene.util.Constants;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.util.StrUtils;
@@ -46,6 +46,70 @@ import org.apache.zookeeper.KeeperException;
/** Supports auth command in the bin/solr script. */
public class AuthTool extends ToolBase {
+
+ private static final Option TYPE_OPTION =
+ Option.builder()
+ .longOpt("type")
+ .hasArg()
+ .desc(
+ "The authentication mechanism to enable (basicAuth or kerberos). Defaults to 'basicAuth'.")
+ .build();
+
+ private static final Option PROMPT_OPTION =
+ Option.builder()
+ .longOpt("prompt")
+ .hasArg()
+ .type(Boolean.class)
+ .desc(
+ "Prompts the user to provide the credentials. Use either --credentials or --prompt, not both.")
+ .build();
+
+ private static final Option CONFIG_OPTION =
+ Option.builder()
+ .longOpt("config")
+ .hasArgs()
+ .desc(
+ "Configuration parameters (Solr startup parameters). Required for Kerberos authentication.")
+ .build();
+
+ private static final Option BLOCK_UNKNOWN_OPTION =
+ Option.builder()
+ .longOpt("block-unknown")
+ .desc("Blocks all access for unknown users (requires authentication for all endpoints).")
+ .hasArg()
+ .argName("true|false")
+ .type(Boolean.class)
+ .build();
+
+ private static final Option SOLR_INCLUDE_FILE_OPTION =
+ Option.builder()
+ .longOpt("solr-include-file")
+ .hasArg()
+ .argName("FILE")
+ .desc(
+ "The Solr include file which contains overridable environment variables for configuring Solr configurations.")
+ .build();
+
+ private static final Option UPDATE_INCLUDE_FILE_OPTION =
+ Option.builder()
+ .longOpt("update-include-file-only")
+ .desc(
+ "Only update the solr.in.sh or solr.in.cmd file, and skip actual enabling/disabling"
+ + " authentication (i.e. don't update security.json).")
+ .hasArg()
+ .type(Boolean.class)
+ .build();
+
+ private static final Option AUTH_CONF_DIR_OPTION =
+ Option.builder()
+ .longOpt("auth-conf-dir")
+ .hasArg()
+ .argName("FILE")
+ .required()
+ .desc(
+ "This is where any authentication related configuration files, if any, would be placed.")
+ .build();
+
public AuthTool() {
this(CLIO.getOutStream());
}
@@ -84,79 +148,38 @@ public class AuthTool extends ToolBase {
"SOLR_AUTHENTICATION_CLIENT_BUILDER", "SOLR_AUTH_TYPE", "SOLR_AUTHENTICATION_OPTS");
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("type")
- .hasArg()
- .desc(
- "The authentication mechanism to enable (basicAuth or kerberos). Defaults to 'basicAuth'.")
- .build(),
- Option.builder()
- .longOpt("prompt")
- .hasArg()
- .desc(
- "Prompts the user to provide the credentials. Use either --credentials or --prompt, not both.")
- .build(),
- Option.builder()
- .longOpt("config")
- .hasArgs()
- .desc(
- "Configuration parameters (Solr startup parameters). Required for Kerberos authentication.")
- .build(),
- Option.builder()
- .longOpt("block-unknown")
- .desc(
- "Blocks all access for unknown users (requires authentication for all endpoints).")
- .hasArg()
- .argName("true|false")
- .build(),
- Option.builder()
- .longOpt("solr-include-file")
- .hasArg()
- .argName("FILE")
- .desc(
- "The Solr include file which contains overridable environment variables for configuring Solr configurations.")
- .build(),
- Option.builder()
- .longOpt("update-include-file-only")
- .desc(
- "Only update the solr.in.sh or solr.in.cmd file, and skip actual enabling/disabling"
- + " authentication (i.e. don't update security.json).")
- .hasArg()
- .build(),
- Option.builder()
- .longOpt("auth-conf-dir")
- .hasArg()
- .argName("FILE")
- .required()
- .desc(
- "This is where any authentication related configuration files, if any, would be placed.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(TYPE_OPTION)
+ .addOption(PROMPT_OPTION)
+ .addOption(CONFIG_OPTION)
+ .addOption(BLOCK_UNKNOWN_OPTION)
+ .addOption(SOLR_INCLUDE_FILE_OPTION)
+ .addOption(UPDATE_INCLUDE_FILE_OPTION)
+ .addOption(AUTH_CONF_DIR_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
- private void ensureArgumentIsValidBooleanIfPresent(CommandLine cli, String argName) {
- if (cli.hasOption(argName)) {
- final String value = cli.getOptionValue(argName);
+ private void ensureArgumentIsValidBooleanIfPresent(CommandLine cli, Option option) {
+ if (cli.hasOption(option)) {
+ final String value = cli.getOptionValue(option);
if (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
- echo("Argument [" + argName + "] must be either true or false, but was [" + value + "]");
+ echo(
+ "Argument ["
+ + option.getLongOpt()
+ + "] must be either true or false, but was ["
+ + value
+ + "]");
SolrCLI.exit(1);
}
}
}
- // @Override
- // public int runTool(CommandLine cli) throws Exception {
-
- // }
-
- private int handleKerberos(CommandLine cli) throws Exception {
+ private void handleKerberos(CommandLine cli) throws Exception {
String cmd = cli.getArgs()[0];
boolean updateIncludeFileOnly =
- Boolean.parseBoolean(cli.getOptionValue("update-include-file-only", "false"));
+ Boolean.parseBoolean(cli.getOptionValue(UPDATE_INCLUDE_FILE_OPTION, "false"));
String securityJson =
"{"
+ "\n \"authentication\":{"
@@ -176,7 +199,7 @@ public class AuthTool extends ToolBase {
CLIO.out(
"Unable to access ZooKeeper. Please add the following security.json to ZooKeeper (in case of SolrCloud):\n"
+ securityJson
- + "\n");
+ + "Dsolr.httpclient.config=[basicAuthConfFile]\n");
zkInaccessible = true;
}
if (zkHost == null) {
@@ -217,7 +240,7 @@ public class AuthTool extends ToolBase {
}
}
- String config = StrUtils.join(Arrays.asList(cli.getOptionValues("config")), ' ');
+ String config = StrUtils.join(Arrays.asList(cli.getOptionValues(CONFIG_OPTION)), ' ');
// config is base64 encoded (to get around parsing problems), decode it
config = config.replace(" ", "");
config =
@@ -226,7 +249,7 @@ public class AuthTool extends ToolBase {
StandardCharsets.UTF_8);
config = config.replace("\n", "").replace("\r", "");
- String solrIncludeFilename = cli.getOptionValue("solr-include-file");
+ String solrIncludeFilename = cli.getOptionValue(SOLR_INCLUDE_FILE_OPTION);
File includeFile = new File(solrIncludeFilename);
if (!includeFile.exists() || !includeFile.canWrite()) {
CLIO.out(
@@ -236,15 +259,14 @@ public class AuthTool extends ToolBase {
}
// update the solr.in.sh file to contain the necessary authentication lines
- updateIncludeFileEnableAuth(includeFile.toPath(), null, config, cli);
+ updateIncludeFileEnableAuth(includeFile.toPath(), null, config);
echo(
"Successfully enabled Kerberos authentication; please restart any running Solr nodes.");
- return 0;
-
+ return;
case "disable":
clearSecurityJson(cli, updateIncludeFileOnly);
- solrIncludeFilename = cli.getOptionValue("solr-include-file");
+ solrIncludeFilename = cli.getOptionValue(SOLR_INCLUDE_FILE_OPTION);
includeFile = new File(solrIncludeFilename);
if (!includeFile.exists() || !includeFile.canWrite()) {
CLIO.out(
@@ -255,38 +277,31 @@ public class AuthTool extends ToolBase {
}
// update the solr.in.sh file to comment out the necessary authentication lines
- updateIncludeFileDisableAuth(includeFile.toPath(), cli);
- return 0;
-
+ updateIncludeFileDisableAuth(includeFile.toPath());
+ return;
default:
CLIO.out("Valid auth commands are: enable, disable.");
SolrCLI.exit(1);
}
CLIO.out("Options not understood.");
- new HelpFormatter()
- .printHelp("bin/solr auth <enable|disable> [OPTIONS]", SolrCLI.getToolOptions(this));
- return 1;
+ SolrCLI.exit(1);
}
- private int handleBasicAuth(CommandLine cli) throws Exception {
+ private void handleBasicAuth(CommandLine cli) throws Exception {
String cmd = cli.getArgs()[0];
- boolean prompt = Boolean.parseBoolean(cli.getOptionValue("prompt", "false"));
+ boolean prompt = Boolean.parseBoolean(cli.getOptionValue(PROMPT_OPTION, "false"));
boolean updateIncludeFileOnly =
- Boolean.parseBoolean(cli.getOptionValue("update-include-file-only", "false"));
+ Boolean.parseBoolean(cli.getOptionValue(UPDATE_INCLUDE_FILE_OPTION, "false"));
switch (cmd) {
case "enable":
- if (!prompt && !cli.hasOption("credentials")) {
+ if (!prompt && !cli.hasOption(CommonCLIOptions.CREDENTIALS_OPTION)) {
CLIO.out("Option --credentials or --prompt is required with enable.");
- new HelpFormatter()
- .printHelp("bin/solr auth <enable|disable> [OPTIONS]", SolrCLI.getToolOptions(this));
SolrCLI.exit(1);
} else if (!prompt
- && (cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()) == null
- || !cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()).contains(":"))) {
+ && (cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION) == null
+ || !cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION).contains(":"))) {
CLIO.out("Option --credentials is not in correct format.");
- new HelpFormatter()
- .printHelp("bin/solr auth <enable|disable> [OPTIONS]", SolrCLI.getToolOptions(this));
SolrCLI.exit(1);
}
@@ -296,7 +311,7 @@ public class AuthTool extends ToolBase {
try {
zkHost = SolrCLI.getZkHost(cli);
} catch (Exception ex) {
- if (cli.hasOption("zk-host")) {
+ if (cli.hasOption(CommonCLIOptions.ZK_HOST_OPTION)) {
CLIO.out(
"Couldn't get ZooKeeper host. Please make sure that ZooKeeper is running and the correct zk-host has been passed in.");
} else {
@@ -306,7 +321,7 @@ public class AuthTool extends ToolBase {
SolrCLI.exit(1);
}
if (zkHost == null) {
- if (cli.hasOption("zk-host")) {
+ if (cli.hasOption(CommonCLIOptions.ZK_HOST_OPTION)) {
CLIO.out(
"Couldn't get ZooKeeper host. Please make sure that ZooKeeper is running and the correct zk-host has been passed in.");
} else {
@@ -323,8 +338,8 @@ public class AuthTool extends ToolBase {
}
String username, password;
- if (cli.hasOption(SolrCLI.OPTION_CREDENTIALS.getLongOpt())) {
- String credentials = cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt());
+ if (cli.hasOption(CommonCLIOptions.CREDENTIALS_OPTION)) {
+ String credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);
username = credentials.split(":")[0];
password = credentials.split(":")[1];
} else {
@@ -340,7 +355,8 @@ public class AuthTool extends ToolBase {
} while (password.length() == 0);
}
- boolean blockUnknown = Boolean.parseBoolean(cli.getOptionValue("block-unknown", "true"));
+ boolean blockUnknown =
+ Boolean.parseBoolean(cli.getOptionValue(BLOCK_UNKNOWN_OPTION, "true"));
String resourceName = "security.json";
final URL resource = SolrCore.class.getClassLoader().getResource(resourceName);
@@ -370,7 +386,7 @@ public class AuthTool extends ToolBase {
}
}
- String solrIncludeFilename = cli.getOptionValue("solr-include-file");
+ String solrIncludeFilename = cli.getOptionValue(SOLR_INCLUDE_FILE_OPTION);
File includeFile = new File(solrIncludeFilename);
if (!includeFile.exists() || !includeFile.canWrite()) {
CLIO.out(
@@ -378,7 +394,7 @@ public class AuthTool extends ToolBase {
printAuthEnablingInstructions(username, password);
System.exit(0);
}
- String authConfDir = cli.getOptionValue("auth-conf-dir");
+ String authConfDir = cli.getOptionValue(AUTH_CONF_DIR_OPTION);
File basicAuthConfFile = new File(authConfDir + File.separator + "basicAuth.conf");
if (!basicAuthConfFile.getParentFile().canWrite()) {
@@ -394,7 +410,7 @@ public class AuthTool extends ToolBase {
// update the solr.in.sh file to contain the necessary authentication lines
updateIncludeFileEnableAuth(
- includeFile.toPath(), basicAuthConfFile.getAbsolutePath(), null, cli);
+ includeFile.toPath(), basicAuthConfFile.getAbsolutePath(), null);
final String successMessage =
String.format(
Locale.ROOT,
@@ -402,12 +418,11 @@ public class AuthTool extends ToolBase {
username,
password);
echo(successMessage);
- return 0;
-
+ return;
case "disable":
clearSecurityJson(cli, updateIncludeFileOnly);
- solrIncludeFilename = cli.getOptionValue("solr-include-file");
+ solrIncludeFilename = cli.getOptionValue(SOLR_INCLUDE_FILE_OPTION);
includeFile = new File(solrIncludeFilename);
if (!includeFile.exists() || !includeFile.canWrite()) {
CLIO.out(
@@ -418,18 +433,15 @@ public class AuthTool extends ToolBase {
}
// update the solr.in.sh file to comment out the necessary authentication lines
- updateIncludeFileDisableAuth(includeFile.toPath(), cli);
- return 0;
-
+ updateIncludeFileDisableAuth(includeFile.toPath());
+ return;
default:
CLIO.out("Valid auth commands are: enable, disable.");
SolrCLI.exit(1);
}
CLIO.out("Options not understood.");
- new HelpFormatter()
- .printHelp("bin/solr auth <enable|disable> [OPTIONS]", SolrCLI.getToolOptions(this));
- return 1;
+ SolrCLI.exit(1);
}
private void checkSecurityJsonExists(SolrZkClient zkClient)
@@ -517,8 +529,7 @@ public class AuthTool extends ToolBase {
* null.
*/
private void updateIncludeFileEnableAuth(
- Path includeFile, String basicAuthConfFile, String kerberosConfig, CommandLine cli)
- throws IOException {
+ Path includeFile, String basicAuthConfFile, String kerberosConfig) throws IOException {
assert !(basicAuthConfFile != null
&& kerberosConfig != null); // only one of the two needs to be populated
List<String> includeFileLines = Files.readAllLines(includeFile, StandardCharsets.UTF_8);
@@ -552,7 +563,7 @@ public class AuthTool extends ToolBase {
includeFileLines.add("REM The following lines added by solr.cmd for enabling BasicAuth");
includeFileLines.add("set SOLR_AUTH_TYPE=kerberos");
includeFileLines.add(
- "set SOLR_AUTHENTICATION_OPTS=\"-Dsolr.httpclient.config=" + basicAuthConfFile + "\"");
+ "set SOLR_AUTHENTICATION_OPTS=\"-Dsolr.httpclient.config=basicAuthConfFile\"");
} else {
includeFileLines.add("# The following lines added by ./solr for enabling BasicAuth");
includeFileLines.add("SOLR_AUTH_TYPE=\"kerberos\"");
@@ -569,7 +580,7 @@ public class AuthTool extends ToolBase {
echoIfVerbose("Updated Solr include file: " + includeFile.toAbsolutePath());
}
- private void updateIncludeFileDisableAuth(Path includeFile, CommandLine cli) throws IOException {
+ private void updateIncludeFileDisableAuth(Path includeFile) throws IOException {
List<String> includeFileLines = Files.readAllLines(includeFile, StandardCharsets.UTF_8);
boolean hasChanged = false;
for (int i = 0; i < includeFileLines.size(); i++) {
@@ -594,12 +605,10 @@ public class AuthTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- ensureArgumentIsValidBooleanIfPresent(cli, "block-unknown");
- ensureArgumentIsValidBooleanIfPresent(cli, "update-include-file-only");
+ ensureArgumentIsValidBooleanIfPresent(cli, BLOCK_UNKNOWN_OPTION);
+ ensureArgumentIsValidBooleanIfPresent(cli, UPDATE_INCLUDE_FILE_OPTION);
- String type = cli.getOptionValue("type", "basicAuth");
+ String type = cli.getOptionValue(TYPE_OPTION, "basicAuth");
switch (type) {
case "basicAuth":
handleBasicAuth(cli);
diff --git a/solr/core/src/java/org/apache/solr/cli/ClusterTool.java b/solr/core/src/java/org/apache/solr/cli/ClusterTool.java
index 8b6bd17f56b..1c71b7b8fee 100644
--- a/solr/core/src/java/org/apache/solr/cli/ClusterTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ClusterTool.java
@@ -19,10 +19,10 @@ package org.apache.solr.cli;
import java.io.IOException;
import java.io.PrintStream;
-import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.impl.SolrZkClientTimeout;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.cloud.ClusterProperties;
@@ -36,6 +36,23 @@ import org.apache.solr.common.cloud.SolrZkClient;
public class ClusterTool extends ToolBase {
// It is a shame this tool doesn't more closely mimic how the ConfigTool works.
+ private static final Option PROPERTY_OPTION =
+ Option.builder()
+ .longOpt("property")
+ .hasArg()
+ .argName("PROPERTY")
+ .required()
+ .desc("Name of the Cluster property to apply the action to, such as: 'urlScheme'.")
+ .build();
+
+ private static final Option VALUE_OPTION =
+ Option.builder()
+ .longOpt("value")
+ .hasArg()
+ .argName("VALUE")
+ .desc("Set the property to this value.")
+ .build();
+
public ClusterTool() {
this(CLIO.getOutStream());
}
@@ -50,30 +67,18 @@ public class ClusterTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("property")
- .hasArg()
- .argName("PROPERTY")
- .required(true)
- .desc("Name of the Cluster property to apply the action to, such as: 'urlScheme'.")
- .build(),
- Option.builder()
- .longOpt("value")
- .hasArg()
- .argName("VALUE")
- .required(false)
- .desc("Set the property to this value.")
- .build(),
- SolrCLI.OPTION_ZKHOST);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(PROPERTY_OPTION)
+ .addOption(VALUE_OPTION)
+ .addOption(CommonCLIOptions.ZK_HOST_OPTION);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- String propertyName = cli.getOptionValue("property");
- String propertyValue = cli.getOptionValue("value");
+ String propertyName = cli.getOptionValue(PROPERTY_OPTION);
+ String propertyValue = cli.getOptionValue(VALUE_OPTION);
String zkHost = SolrCLI.getZkHost(cli);
if (!ZkController.checkChrootPath(zkHost, true)) {
diff --git a/solr/core/src/java/org/apache/solr/cli/CommonCLIOptions.java b/solr/core/src/java/org/apache/solr/cli/CommonCLIOptions.java
new file mode 100644
index 00000000000..93f02c3e359
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/cli/CommonCLIOptions.java
@@ -0,0 +1,74 @@
+/*
+ * 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.solr.cli;
+
+import org.apache.commons.cli.Option;
+
+public final class CommonCLIOptions {
+
+ private CommonCLIOptions() {}
+
+ public static final Option VERBOSE_OPTION =
+ Option.builder("v").longOpt("verbose").desc("Enable verbose command output.").build();
+
+ public static final Option HELP_OPTION =
+ Option.builder("h").longOpt("help").desc("Print this message.").build();
+
+ public static final Option ZK_HOST_OPTION =
+ Option.builder("z")
+ .longOpt("zk-host")
+ .hasArg()
+ .argName("HOST")
+ .desc(
+ "Zookeeper connection string; unnecessary if ZK_HOST is defined in solr.in.sh; otherwise, defaults to "
+ + DefaultValues.ZK_HOST
+ + '.')
+ .build();
+
+ public static final Option SOLR_URL_OPTION =
+ Option.builder("s")
+ .longOpt("solr-url")
+ .hasArg()
+ .argName("HOST")
+ .desc(
+ "Base Solr URL, which can be used to determine the zk-host if that's not known; defaults to: "
+ + SolrCLI.getDefaultSolrUrl()
+ + '.')
+ .build();
+
+ public static final Option RECURSIVE_OPTION =
+ Option.builder("r").longOpt("recursive").desc("Apply the command recursively.").build();
+
+ public static final Option CREDENTIALS_OPTION =
+ Option.builder("u")
+ .longOpt("credentials")
+ .hasArg()
+ .argName("credentials")
+ .desc(
+ "Credentials in the format username:password. Example: --credentials solr:SolrRocks")
+ .build();
+
+ public static final class DefaultValues {
+
+ private DefaultValues() {}
+
+ public static final String ZK_HOST = "localhost:9983";
+
+ public static final String DEFAULT_CONFIG_SET = "_default";
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java b/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java
index b0e5aaa6d4a..b55b939117b 100644
--- a/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java
@@ -21,9 +21,9 @@ import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.common.cloud.SolrZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,6 +32,24 @@ import org.slf4j.LoggerFactory;
public class ConfigSetDownloadTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option CONF_NAME_OPTION =
+ Option.builder("n")
+ .longOpt("conf-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Configset name in ZooKeeper.")
+ .build();
+
+ private static final Option CONF_DIR_OPTION =
+ Option.builder("d")
+ .longOpt("conf-dir")
+ .hasArg()
+ .argName("DIR")
+ .required()
+ .desc("Local directory with configs.")
+ .build();
+
public ConfigSetDownloadTool() {
this(CLIO.getOutStream());
}
@@ -41,25 +59,12 @@ public class ConfigSetDownloadTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("n")
- .longOpt("conf-name")
- .hasArg()
- .argName("NAME")
- .required(true)
- .desc("Configset name in ZooKeeper.")
- .build(),
- Option.builder("d")
- .longOpt("conf-dir")
- .hasArg()
- .argName("DIR")
- .required(true)
- .desc("Local directory with configs.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(CONF_NAME_OPTION)
+ .addOption(CONF_DIR_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -74,11 +79,10 @@ public class ConfigSetDownloadTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
- String confName = cli.getOptionValue("conf-name");
- String confDir = cli.getOptionValue("conf-dir");
+ String confName = cli.getOptionValue(CONF_NAME_OPTION);
+ String confDir = cli.getOptionValue(CONF_DIR_OPTION);
echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...");
try (SolrZkClient zkClient = SolrCLI.getSolrZkClient(cli, zkHost)) {
diff --git a/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java b/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java
index 597b901c7d0..b959245af2e 100644
--- a/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java
@@ -20,9 +20,9 @@ import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkMaintenanceUtils;
import org.apache.solr.core.ConfigSetService;
@@ -34,6 +34,24 @@ import org.slf4j.LoggerFactory;
public class ConfigSetUploadTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option CONF_NAME_OPTION =
+ Option.builder("n")
+ .longOpt("conf-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Configset name in ZooKeeper.")
+ .build();
+
+ private static final Option CONF_DIR_OPTION =
+ Option.builder("d")
+ .longOpt("conf-dir")
+ .hasArg()
+ .argName("DIR")
+ .required()
+ .desc("Local directory with configs.")
+ .build();
+
public ConfigSetUploadTool() {
this(CLIO.getOutStream());
}
@@ -43,25 +61,12 @@ public class ConfigSetUploadTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("n")
- .longOpt("conf-name")
- .hasArg()
- .argName("NAME")
- .required(true)
- .desc("Configset name in ZooKeeper.")
- .build(),
- Option.builder("d")
- .longOpt("conf-dir")
- .hasArg()
- .argName("DIR")
- .required(true)
- .desc("Local directory with configs.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(CONF_NAME_OPTION)
+ .addOption(CONF_DIR_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -76,14 +81,13 @@ public class ConfigSetUploadTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
final String solrInstallDir = System.getProperty("solr.install.dir");
Path solrInstallDirPath = Paths.get(solrInstallDir);
- String confName = cli.getOptionValue("conf-name");
- String confDir = cli.getOptionValue("conf-dir");
+ String confName = cli.getOptionValue(CONF_NAME_OPTION);
+ String confDir = cli.getOptionValue(CONF_DIR_OPTION);
echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...");
try (SolrZkClient zkClient = SolrCLI.getSolrZkClient(cli, zkHost)) {
diff --git a/solr/core/src/java/org/apache/solr/cli/ConfigTool.java b/solr/core/src/java/org/apache/solr/cli/ConfigTool.java
index 5cc3f0909d6..fdd18f24d4b 100644
--- a/solr/core/src/java/org/apache/solr/cli/ConfigTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ConfigTool.java
@@ -19,11 +19,11 @@ package org.apache.solr.cli;
import java.io.PrintStream;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.util.NamedList;
import org.noggit.CharArr;
@@ -36,6 +36,42 @@ import org.noggit.JSONWriter;
*/
public class ConfigTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the collection.")
+ .build();
+
+ private static final Option ACTION_OPTION =
+ Option.builder("a")
+ .longOpt("action")
+ .hasArg()
+ .argName("ACTION")
+ .desc(
+ "Config API action, one of: set-property, unset-property, set-user-property, unset-user-property; default is 'set-property'.")
+ .build();
+
+ private static final Option PROPERTY_OPTION =
+ Option.builder()
+ .longOpt("property")
+ .hasArg()
+ .argName("PROP")
+ .required()
+ .desc(
+ "Name of the Config API property to apply the action to, such as: 'updateHandler.autoSoftCommit.maxTime'.")
+ .build();
+
+ private static final Option VALUE_OPTION =
+ Option.builder("v")
+ .longOpt("value")
+ .hasArg()
+ .argName("VALUE")
+ .desc("Set the property to this value; accepts JSON objects and strings.")
+ .build();
+
public ConfigTool() {
this(CLIO.getOutStream());
}
@@ -50,50 +86,23 @@ public class ConfigTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the collection.")
- .build(),
- Option.builder("a")
- .longOpt("action")
- .argName("ACTION")
- .hasArg()
- .required(false)
- .desc(
- "Config API action, one of: set-property, unset-property, set-user-property, unset-user-property; default is 'set-property'.")
- .build(),
- Option.builder()
- .longOpt("property")
- .argName("PROP")
- .hasArg()
- .required(true)
- .desc(
- "Name of the Config API property to apply the action to, such as: 'updateHandler.autoSoftCommit.maxTime'.")
- .build(),
- Option.builder()
- .longOpt("value")
- .argName("VALUE")
- .hasArg()
- .required(false)
- .desc("Set the property to this value; accepts JSON objects and strings.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(ACTION_OPTION)
+ .addOption(PROPERTY_OPTION)
+ .addOption(VALUE_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
String solrUrl = SolrCLI.normalizeSolrUrl(cli);
- String action = cli.getOptionValue("action", "set-property");
- String collection = cli.getOptionValue("name");
- String property = cli.getOptionValue("property");
- String value = cli.getOptionValue("value");
+ String action = cli.getOptionValue(ACTION_OPTION, "set-property");
+ String collection = cli.getOptionValue(COLLECTION_NAME_OPTION);
+ String property = cli.getOptionValue(PROPERTY_OPTION);
+ String value = cli.getOptionValue(VALUE_OPTION);
// value is required unless the property is one of the unset- type.
if (!action.contains("unset-") && value == null) {
@@ -118,8 +127,7 @@ public class ConfigTool extends ToolBase {
echoIfVerbose(jsonBody);
try (SolrClient solrClient =
- SolrCLI.getSolrClient(
- solrUrl, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ SolrCLI.getSolrClient(solrUrl, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
NamedList<Object> result = SolrCLI.postJsonToSolr(solrClient, updatePath, jsonBody);
Integer statusCode = (Integer) result.findRecursive("responseHeader", "status");
if (statusCode == 0) {
diff --git a/solr/core/src/java/org/apache/solr/cli/CreateTool.java b/solr/core/src/java/org/apache/solr/cli/CreateTool.java
index 6c14ed6e21e..5fc57501d93 100644
--- a/solr/core/src/java/org/apache/solr/cli/CreateTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/CreateTool.java
@@ -21,15 +21,16 @@ import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.file.PathUtils;
+import org.apache.solr.cli.CommonCLIOptions.DefaultValues;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
@@ -52,6 +53,53 @@ import org.noggit.JSONWriter;
/** Supports create command in the bin/solr script. */
public class CreateTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of collection or core to create.")
+ .build();
+
+ private static final Option SHARDS_OPTION =
+ Option.builder("sh")
+ .longOpt("shards")
+ .hasArg()
+ .argName("#")
+ .type(Integer.class)
+ .desc("Number of shards; default is 1.")
+ .build();
+
+ private static final Option REPLICATION_FACTOR_OPTION =
+ Option.builder("rf")
+ .longOpt("replication-factor")
+ .hasArg()
+ .argName("#")
+ .type(Integer.class)
+ .desc(
+ "Number of copies of each document across the collection (replicas per shard); default is 1.")
+ .build();
+
+ private static final Option CONF_DIR_OPTION =
+ Option.builder("d")
+ .longOpt("conf-dir")
+ .hasArg()
+ .argName("DIR")
+ .desc(
+ "Configuration directory to copy when creating the new collection; default is "
+ + DefaultValues.DEFAULT_CONFIG_SET
+ + '.')
+ .build();
+
+ private static final Option CONF_NAME_OPTION =
+ Option.builder("n")
+ .longOpt("conf-name")
+ .hasArg()
+ .argName("NAME")
+ .desc("Configuration name; default is the collection name.")
+ .build();
+
public CreateTool() {
this(CLIO.getOutStream());
}
@@ -74,53 +122,22 @@ public class CreateTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .hasArg()
- .argName("NAME")
- .required(true)
- .desc("Name of collection or core to create.")
- .build(),
- Option.builder("sh")
- .longOpt("shards")
- .hasArg()
- .argName("#")
- .desc("Number of shards; default is 1.")
- .build(),
- Option.builder("rf")
- .longOpt("replication-factor")
- .hasArg()
- .argName("#")
- .desc(
- "Number of copies of each document across the collection (replicas per shard); default is 1.")
- .build(),
- Option.builder("d")
- .longOpt("conf-dir")
- .argName("DIR")
- .hasArg()
- .desc(
- "Configuration directory to copy when creating the new collection; default is "
- + SolrCLI.DEFAULT_CONFIG_SET
- + '.')
- .build(),
- Option.builder("n")
- .longOpt("conf-name")
- .argName("NAME")
- .hasArg()
- .required(false)
- .desc("Configuration name; default is the collection name.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ Options opts =
+ super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(SHARDS_OPTION)
+ .addOption(REPLICATION_FACTOR_OPTION)
+ .addOption(CONF_DIR_OPTION)
+ .addOption(CONF_NAME_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
+
+ return opts;
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
try (var solrClient = SolrCLI.getSolrClient(cli)) {
if (SolrCLI.isCloudMode(solrClient)) {
createCollection(cli);
@@ -131,11 +148,13 @@ public class CreateTool extends ToolBase {
}
protected void createCore(CommandLine cli, SolrClient solrClient) throws Exception {
- String coreName = cli.getOptionValue("name");
- String solrUrl = cli.getOptionValue("solr-url", SolrCLI.getDefaultSolrUrl());
+ String coreName = cli.getOptionValue(COLLECTION_NAME_OPTION);
+ String solrUrl =
+ cli.getOptionValue(CommonCLIOptions.SOLR_URL_OPTION, SolrCLI.getDefaultSolrUrl());
final String solrInstallDir = System.getProperty("solr.install.dir");
- final String confDirName = cli.getOptionValue("conf-dir", SolrCLI.DEFAULT_CONFIG_SET);
+ final String confDirName =
+ cli.getOptionValue(CONF_DIR_OPTION, DefaultValues.DEFAULT_CONFIG_SET);
// we allow them to pass a directory instead of a configset name
Path configsetDir = Paths.get(confDirName);
@@ -157,7 +176,7 @@ public class CreateTool extends ToolBase {
coreRootDirectory = (String) systemInfo.get("core_root");
if (SolrCLI.safeCheckCoreExists(
- solrUrl, coreName, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ solrUrl, coreName, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
throw new IllegalArgumentException(
"\nCore '"
+ coreName
@@ -204,7 +223,7 @@ public class CreateTool extends ToolBase {
.withConnectionTimeout(15, TimeUnit.SECONDS)
.withKeyStoreReloadInterval(-1, TimeUnit.SECONDS)
.withOptionalBasicAuthCredentials(
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
String zkHost = SolrCLI.getZkHost(cli);
echoIfVerbose("Connecting to ZooKeeper at " + zkHost);
try (CloudSolrClient cloudSolrClient = SolrCLI.getCloudHttp2SolrClient(zkHost, builder)) {
@@ -216,10 +235,10 @@ public class CreateTool extends ToolBase {
protected void createCollection(CloudSolrClient cloudSolrClient, CommandLine cli)
throws Exception {
- String collectionName = cli.getOptionValue("name");
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
final String solrInstallDir = System.getProperty("solr.install.dir");
- String confName = cli.getOptionValue("conf-name");
- String confDir = cli.getOptionValue("conf-dir", SolrCLI.DEFAULT_CONFIG_SET);
+ String confName = cli.getOptionValue(CONF_NAME_OPTION);
+ String confDir = cli.getOptionValue(CONF_DIR_OPTION, DefaultValues.DEFAULT_CONFIG_SET);
Path solrInstallDirPath = Paths.get(solrInstallDir);
Path confDirPath = Paths.get(confDir);
ensureConfDirExists(solrInstallDirPath, confDirPath);
@@ -231,19 +250,15 @@ public class CreateTool extends ToolBase {
"No live nodes found! Cannot create a collection until "
+ "there is at least 1 live node in the cluster.");
- String solrUrl = cli.getOptionValue("solr-url");
+ String solrUrl = cli.getOptionValue(CommonCLIOptions.SOLR_URL_OPTION);
if (solrUrl == null) {
String firstLiveNode = liveNodes.iterator().next();
solrUrl = ZkStateReader.from(cloudSolrClient).getBaseUrlForNodeName(firstLiveNode);
}
// build a URL to create the collection
- int numShards = Integer.parseInt(cli.getOptionValue("shards", String.valueOf(1)));
- int replicationFactor = 1;
-
- if (cli.hasOption("replication-factor")) {
- replicationFactor = Integer.parseInt(cli.getOptionValue("replication-factor"));
- }
+ int numShards = cli.getParsedOptionValue(SHARDS_OPTION, 1);
+ int replicationFactor = cli.getParsedOptionValue(REPLICATION_FACTOR_OPTION, 1);
boolean configExistsInZk =
confName != null
@@ -280,7 +295,7 @@ public class CreateTool extends ToolBase {
// since creating a collection is a heavy-weight operation, check for existence first
if (SolrCLI.safeCheckCollectionExists(
- solrUrl, collectionName, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ solrUrl, collectionName, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
throw new IllegalStateException(
"\nCollection '"
+ collectionName
@@ -339,13 +354,15 @@ public class CreateTool extends ToolBase {
}
private void printDefaultConfigsetWarningIfNecessary(CommandLine cli) {
- final String confDirectoryName = cli.getOptionValue("conf-dir", SolrCLI.DEFAULT_CONFIG_SET);
- final String confName = cli.getOptionValue("conf-name", "");
+ final String confDirectoryName =
+ cli.getOptionValue(CONF_DIR_OPTION, DefaultValues.DEFAULT_CONFIG_SET);
+ final String confName = cli.getOptionValue(CONF_NAME_OPTION, "");
if (confDirectoryName.equals("_default")
&& (confName.equals("") || confName.equals("_default"))) {
- final String collectionName = cli.getOptionValue("name");
- final String solrUrl = cli.getOptionValue("solr-url", SolrCLI.getDefaultSolrUrl());
+ final String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
+ final String solrUrl =
+ cli.getOptionValue(CommonCLIOptions.SOLR_URL_OPTION, SolrCLI.getDefaultSolrUrl());
final String curlCommand =
String.format(
Locale.ROOT,
diff --git a/solr/core/src/java/org/apache/solr/cli/DeleteTool.java b/solr/core/src/java/org/apache/solr/cli/DeleteTool.java
index bd6d5f97cc2..61e02161416 100644
--- a/solr/core/src/java/org/apache/solr/cli/DeleteTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/DeleteTool.java
@@ -16,18 +16,16 @@
*/
package org.apache.solr.cli;
-import static org.apache.solr.common.params.CommonParams.NAME;
-
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
import java.util.Collection;
-import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
@@ -47,6 +45,32 @@ import org.slf4j.LoggerFactory;
public class DeleteTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the core / collection to delete.")
+ .build();
+
+ private static final Option DELETE_CONFIG_OPTION =
+ Option.builder()
+ .longOpt("delete-config")
+ .hasArg()
+ .argName("true|false")
+ .type(Boolean.class)
+ .desc(
+ "Flag to indicate if the underlying configuration directory for a collection should also be deleted; default is true.")
+ .build();
+
+ private static final Option FORCE_OPTION =
+ Option.builder("f")
+ .longOpt("force")
+ .desc(
+ "Skip safety checks when deleting the configuration directory used by a collection.")
+ .build();
+
public DeleteTool() {
this(CLIO.getOutStream());
}
@@ -71,38 +95,17 @@ public class DeleteTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the core / collection to delete.")
- .build(),
- Option.builder()
- .longOpt("delete-config")
- .hasArg()
- .argName("true|false")
- .required(false)
- .desc(
- "Flag to indicate if the underlying configuration directory for a collection should also be deleted; default is true.")
- .build(),
- Option.builder("f")
- .longOpt("force")
- .required(false)
- .desc(
- "Skip safety checks when deleting the configuration directory used by a collection.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(DELETE_CONFIG_OPTION)
+ .addOption(FORCE_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
try (var solrClient = SolrCLI.getSolrClient(cli)) {
if (SolrCLI.isCloudMode(solrClient)) {
deleteCollection(cli);
@@ -118,7 +121,8 @@ public class DeleteTool extends ToolBase {
.withIdleTimeout(30, TimeUnit.SECONDS)
.withConnectionTimeout(15, TimeUnit.SECONDS)
.withKeyStoreReloadInterval(-1, TimeUnit.SECONDS)
- .withOptionalBasicAuthCredentials(cli.getOptionValue(("credentials")));
+ .withOptionalBasicAuthCredentials(
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
String zkHost = SolrCLI.getZkHost(cli);
try (CloudSolrClient cloudSolrClient = SolrCLI.getCloudHttp2SolrClient(zkHost, builder)) {
@@ -137,20 +141,17 @@ public class DeleteTool extends ToolBase {
+ "there is at least 1 live node in the cluster.");
ZkStateReader zkStateReader = ZkStateReader.from(cloudSolrClient);
- String collectionName = cli.getOptionValue(NAME);
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
if (!zkStateReader.getClusterState().hasCollection(collectionName)) {
throw new IllegalArgumentException("Collection " + collectionName + " not found!");
}
String configName =
zkStateReader.getClusterState().getCollection(collectionName).getConfigName();
- boolean deleteConfig = true;
- if (cli.hasOption("delete-config")) {
- deleteConfig = "true".equals(cli.getOptionValue("delete-config"));
- }
+ boolean deleteConfig = Boolean.parseBoolean(cli.getOptionValue(DELETE_CONFIG_OPTION, "true"));
if (deleteConfig && configName != null) {
- if (cli.hasOption("force")) {
+ if (cli.hasOption(FORCE_OPTION)) {
log.warn(
"Skipping safety checks, configuration directory {} will be deleted with impunity.",
configName);
@@ -224,7 +225,7 @@ public class DeleteTool extends ToolBase {
}
protected void deleteCore(CommandLine cli, SolrClient solrClient) throws Exception {
- String coreName = cli.getOptionValue(NAME);
+ String coreName = cli.getOptionValue(COLLECTION_NAME_OPTION);
echo("\nDeleting core '" + coreName + "' using CoreAdminRequest\n");
diff --git a/solr/core/src/java/org/apache/solr/cli/ExportTool.java b/solr/core/src/java/org/apache/solr/cli/ExportTool.java
index 699df52d330..5018855e597 100644
--- a/solr/core/src/java/org/apache/solr/cli/ExportTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ExportTool.java
@@ -55,6 +55,7 @@ import java.util.function.Consumer;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.lucene.util.SuppressForbidden;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
@@ -88,57 +89,76 @@ import org.noggit.JSONWriter;
/** Supports export command in the bin/solr script. */
public class ExportTool extends ToolBase {
+
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .desc("Name of the collection.")
+ .build();
+
+ private static final Option OUTPUT_OPTION =
+ Option.builder()
+ .longOpt("output")
+ .hasArg()
+ .argName("PATH")
+ .desc(
+ "Path to output the exported data, and optionally the file name, defaults to 'collection-name'.")
+ .build();
+
+ private static final Option FORMAT_OPTION =
+ Option.builder()
+ .longOpt("format")
+ .hasArg()
+ .argName("FORMAT")
+ .desc("Output format for exported docs (json, jsonl or javabin), defaulting to json.")
+ .build();
+
+ private static final Option COMPRESS_OPTION =
+ Option.builder().longOpt("compress").desc("Compress the output. Defaults to false.").build();
+
+ private static final Option LIMIT_OPTION =
+ Option.builder()
+ .longOpt("limit")
+ .hasArg()
+ .argName("#")
+ .desc("Maximum number of docs to download. Default is 100, use -1 for all docs.")
+ .build();
+
+ private static final Option QUERY_OPTION =
+ Option.builder()
+ .longOpt("query")
+ .hasArg()
+ .argName("QUERY")
+ .desc("A custom query, default is '*:*'.")
+ .build();
+
+ private static final Option FIELDS_OPTION =
+ Option.builder()
+ .longOpt("fields")
+ .hasArg()
+ .argName("FIELDA,FIELDB")
+ .desc("Comma separated list of fields to export. By default all fields are fetched.")
+ .build();
+
@Override
public String getName() {
return "export";
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .hasArg()
- .argName("NAME")
- .desc("Name of the collection.")
- .build(),
- Option.builder()
- .longOpt("output")
- .hasArg()
- .argName("PATH")
- .desc(
- "Path to output the exported data, and optionally the file name, defaults to 'collection-name'.")
- .build(),
- Option.builder()
- .longOpt("format")
- .hasArg()
- .argName("FORMAT")
- .desc("Output format for exported docs (json, jsonl or javabin), defaulting to json.")
- .build(),
- Option.builder()
- .longOpt("compress")
- .desc("Compress the output. Defaults to false.")
- .build(),
- Option.builder()
- .longOpt("limit")
- .hasArg()
- .argName("#")
- .desc("Maximum number of docs to download. Default is 100, use -1 for all docs.")
- .build(),
- Option.builder()
- .longOpt("query")
- .hasArg()
- .argName("QUERY")
- .desc("A custom query, default is '*:*'.")
- .build(),
- Option.builder()
- .longOpt("fields")
- .hasArg()
- .argName("FIELDA,FIELDB")
- .desc("Comma separated list of fields to export. By default all fields are fetched.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(OUTPUT_OPTION)
+ .addOption(FORMAT_OPTION)
+ .addOption(COMPRESS_OPTION)
+ .addOption(LIMIT_OPTION)
+ .addOption(QUERY_OPTION)
+ .addOption(FIELDS_OPTION)
+ .addOption(CommonCLIOptions.SOLR_URL_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION);
}
public abstract static class Info {
@@ -259,25 +279,27 @@ public class ExportTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
String url = null;
- if (cli.hasOption("solr-url")) {
- if (!cli.hasOption("name")) {
+ if (cli.hasOption(CommonCLIOptions.SOLR_URL_OPTION)) {
+ if (!cli.hasOption(COLLECTION_NAME_OPTION)) {
throw new IllegalArgumentException(
"Must specify -c / --name parameter with --solr-url to post documents.");
}
- url = SolrCLI.normalizeSolrUrl(cli) + "/solr/" + cli.getOptionValue("name");
+ url = SolrCLI.normalizeSolrUrl(cli) + "/solr/" + cli.getOptionValue(COLLECTION_NAME_OPTION);
} else {
// think about support --zk-host someday.
throw new IllegalArgumentException("Must specify --solr-url.");
}
- String credentials = cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt());
+ String credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);
Info info = new MultiThreadedRunner(url, credentials);
- info.query = cli.getOptionValue("query", "*:*");
+ info.query = cli.getOptionValue(QUERY_OPTION, "*:*");
info.setOutFormat(
- cli.getOptionValue("output"), cli.getOptionValue("format"), cli.hasOption("compress"));
- info.fields = cli.getOptionValue("fields");
- info.setLimit(cli.getOptionValue("limit", "100"));
+ cli.getOptionValue(OUTPUT_OPTION),
+ cli.getOptionValue(FORMAT_OPTION),
+ cli.hasOption(COMPRESS_OPTION));
+ info.fields = cli.getOptionValue(FIELDS_OPTION);
+ info.setLimit(cli.getOptionValue(LIMIT_OPTION, "100"));
info.output = super.stdout;
info.exportDocs();
}
diff --git a/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java b/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java
index dcc3aa91d11..6ec08f77d6c 100644
--- a/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java
@@ -30,6 +30,7 @@ import java.util.Map;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.CloudHttp2SolrClient;
@@ -53,19 +54,21 @@ import org.slf4j.LoggerFactory;
public class HealthcheckTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("COLLECTION")
+ .required()
+ .desc("Name of the collection to check.")
+ .build();
+
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .hasArg()
- .argName("COLLECTION")
- .required(true)
- .desc("Name of the collection to check.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
enum ShardState {
@@ -86,7 +89,6 @@ public class HealthcheckTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
if (zkHost == null) {
CLIO.err("Healthcheck tool only works in Solr Cloud mode.");
@@ -105,8 +107,7 @@ public class HealthcheckTool extends ToolBase {
}
protected void runCloudTool(CloudSolrClient cloudSolrClient, CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
- String collection = cli.getOptionValue("name");
+ String collection = cli.getOptionValue(COLLECTION_NAME_OPTION);
log.debug("Running healthcheck for {}", collection);
@@ -169,13 +170,13 @@ public class HealthcheckTool extends ToolBase {
q.set(DISTRIB, "false");
try (var solrClientForCollection =
SolrCLI.getSolrClient(
- coreUrl, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ coreUrl, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
qr = solrClientForCollection.query(q);
numDocs = qr.getResults().getNumFound();
try (var solrClient =
SolrCLI.getSolrClient(
replicaCoreProps.getBaseUrl(),
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
NamedList<Object> systemInfo =
solrClient.request(
new GenericSolrRequest(
diff --git a/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java b/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java
index da553eb735e..2261b96474d 100644
--- a/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java
@@ -18,10 +18,10 @@
package org.apache.solr.cli;
import java.io.PrintStream;
-import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.impl.SolrZkClientTimeout;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.cloud.SolrZkClient;
@@ -29,6 +29,24 @@ import org.apache.solr.common.cloud.SolrZkClient;
/** Supports linking a configset to a collection */
public class LinkConfigTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the collection to link.")
+ .build();
+
+ private static final Option CONF_NAME_OPTION =
+ Option.builder("n")
+ .longOpt("conf-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Configset name in ZooKeeper.")
+ .build();
+
public LinkConfigTool() {
this(CLIO.getOutStream());
}
@@ -48,30 +66,18 @@ public class LinkConfigTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the collection to link.")
- .build(),
- Option.builder("n")
- .longOpt("conf-name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Configset name in ZooKeeper.")
- .build(),
- SolrCLI.OPTION_ZKHOST);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(CONF_NAME_OPTION)
+ .addOption(CommonCLIOptions.ZK_HOST_OPTION);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- String collection = cli.getOptionValue("name");
- String confName = cli.getOptionValue("conf-name");
+ String collection = cli.getOptionValue(COLLECTION_NAME_OPTION);
+ String confName = cli.getOptionValue(CONF_NAME_OPTION);
String zkHost = SolrCLI.getZkHost(cli);
try (SolrZkClient zkClient =
diff --git a/solr/core/src/java/org/apache/solr/cli/PackageTool.java b/solr/core/src/java/org/apache/solr/cli/PackageTool.java
index 0089e896ad4..cb8bc6493ad 100644
--- a/solr/core/src/java/org/apache/solr/cli/PackageTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/PackageTool.java
@@ -24,10 +24,10 @@ import static org.apache.solr.packagemanager.PackageUtils.formatGreen;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.lucene.util.SuppressForbidden;
@@ -49,6 +49,49 @@ public class PackageTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option COLLECTIONS_OPTION =
+ Option.builder()
+ .longOpt("collections")
+ .hasArg()
+ .argName("COLLECTIONS")
+ .desc(
+ "Specifies that this action should affect plugins for the given collections only, excluding cluster level plugins.")
+ .build();
+
+ private static final Option CLUSTER_OPTION =
+ Option.builder()
+ .longOpt("cluster")
+ .desc("Specifies that this action should affect cluster-level plugins only.")
+ .build();
+
+ private static final Option PARAM_OPTION =
+ Option.builder()
+ .longOpt("param")
+ .hasArgs()
+ .argName("PARAMS")
+ .desc("List of parameters to be used with deploy command.")
+ .build();
+
+ private static final Option UPDATE_OPTION =
+ Option.builder()
+ .longOpt("update")
+ .desc("If a deployment is an update over a previous deployment.")
+ .build();
+
+ private static final Option COLLECTION_OPTION =
+ Option.builder("c")
+ .longOpt("collection")
+ .hasArg()
+ .argName("COLLECTION")
+ .desc("The collection to apply the package to, not required.")
+ .build();
+
+ private static final Option NO_PROMPT_OPTION =
+ Option.builder("y")
+ .longOpt("no-prompt")
+ .desc("Don't prompt for input; accept all default choices, defaults to false.")
+ .build();
+
@SuppressForbidden(
reason = "Need to turn off logging, and SLF4J doesn't seem to provide for a way.")
public PackageTool() {
@@ -115,8 +158,8 @@ public class PackageTool extends ToolBase {
}
break;
case "list-deployed":
- if (cli.hasOption("collection")) {
- String collection = cli.getOptionValue("collection");
+ if (cli.hasOption(COLLECTION_OPTION)) {
+ String collection = cli.getOptionValue(COLLECTION_OPTION);
Map<String, SolrPackageInstance> packages =
packageManager.getPackagesDeployed(collection);
printGreen("Packages deployed on " + collection + ":");
@@ -162,23 +205,23 @@ public class PackageTool extends ToolBase {
}
case "deploy":
{
- if (cli.hasOption("cluster") || cli.hasOption("collections")) {
+ if (cli.hasOption(CLUSTER_OPTION) || cli.hasOption(COLLECTIONS_OPTION)) {
Pair<String, String> parsedVersion = parsePackageVersion(cli.getArgList().get(1));
String packageName = parsedVersion.first();
String version = parsedVersion.second();
- boolean noPrompt = cli.hasOption("no-prompt");
- boolean isUpdate = cli.hasOption("update");
+ boolean noPrompt = cli.hasOption(NO_PROMPT_OPTION);
+ boolean isUpdate = cli.hasOption(UPDATE_OPTION);
String[] collections =
- cli.hasOption("collections")
+ cli.hasOption(COLLECTIONS_OPTION)
? PackageUtils.validateCollections(
- cli.getOptionValue("collections").split(","))
+ cli.getOptionValue(COLLECTIONS_OPTION).split(","))
: new String[] {};
- String[] parameters = cli.getOptionValues("param");
+ String[] parameters = cli.getOptionValues(PARAM_OPTION);
packageManager.deploy(
packageName,
version,
collections,
- cli.hasOption("cluster"),
+ cli.hasOption(CLUSTER_OPTION),
parameters,
isUpdate,
noPrompt);
@@ -190,7 +233,7 @@ public class PackageTool extends ToolBase {
}
case "undeploy":
{
- if (cli.hasOption("cluster") || cli.hasOption("collections")) {
+ if (cli.hasOption(CLUSTER_OPTION) || cli.hasOption(COLLECTIONS_OPTION)) {
Pair<String, String> parsedVersion = parsePackageVersion(cli.getArgList().get(1));
if (parsedVersion.second() != null) {
throw new SolrException(
@@ -200,13 +243,12 @@ public class PackageTool extends ToolBase {
}
String packageName = parsedVersion.first();
String[] collections =
- cli.hasOption("collections")
+ cli.hasOption(COLLECTIONS_OPTION)
? PackageUtils.validateCollections(
- cli.getOptionValue("collections").split(","))
+ cli.getOptionValue(COLLECTIONS_OPTION).split(","))
: new String[] {};
- packageManager.undeploy(packageName, collections, cli.hasOption("cluster"));
+ packageManager.undeploy(packageName, collections, cli.hasOption(CLUSTER_OPTION));
} else {
-
printRed(
"Either specify --cluster to undeploy cluster level plugins or -collections <list-of-collections> to undeploy collection level plugins");
}
@@ -318,41 +360,15 @@ public class PackageTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("collections")
- .hasArg()
- .argName("COLLECTIONS")
- .desc(
- "Specifies that this action should affect plugins for the given collections only, excluding cluster level plugins.")
- .build(),
- Option.builder()
- .longOpt("cluster")
- .desc("Specifies that this action should affect cluster-level plugins only.")
- .build(),
- Option.builder()
- .longOpt("param")
- .hasArgs()
- .argName("PARAMS")
- .desc("List of parameters to be used with deploy command.")
- .build(),
- Option.builder()
- .longOpt("update")
- .desc("If a deployment is an update over a previous deployment.")
- .build(),
- Option.builder("c")
- .longOpt("collection")
- .hasArg()
- .argName("COLLECTION")
- .desc("The collection to apply the package to, not required.")
- .build(),
- Option.builder("y")
- .longOpt("no-prompt")
- .desc("Don't prompt for input; accept all default choices, defaults to false.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTIONS_OPTION)
+ .addOption(CLUSTER_OPTION)
+ .addOption(PARAM_OPTION)
+ .addOption(UPDATE_OPTION)
+ .addOption(COLLECTION_OPTION)
+ .addOption(NO_PROMPT_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
}
diff --git a/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java b/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java
index 7be103ea923..e1efeb0b920 100644
--- a/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java
@@ -37,6 +37,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.Http2SolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
@@ -48,6 +49,24 @@ import org.apache.solr.handler.component.ShardRequest;
/** A command line tool for indexing Solr logs in the out-of-the-box log format. */
public class PostLogsTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the collection.")
+ .build();
+
+ private static final Option ROOT_DIR_OPTION =
+ Option.builder()
+ .longOpt("rootdir")
+ .hasArg()
+ .argName("DIRECTORY")
+ .required()
+ .desc("All files found at or below the root directory will be indexed.")
+ .build();
+
public PostLogsTool() {
this(CLIO.getOutStream());
}
@@ -62,38 +81,26 @@ public class PostLogsTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .hasArg()
- .required(true)
- .argName("NAME")
- .desc("Name of the collection.")
- .build(),
- Option.builder("rootdir")
- .longOpt("rootdir")
- .hasArg()
- .argName("DIRECTORY")
- .required(true)
- .desc("All files found at or below the root directory will be indexed.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(ROOT_DIR_OPTION)
+ .addOption(CommonCLIOptions.SOLR_URL_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
String url = null;
- if (cli.hasOption("solr-url")) {
- url = SolrCLI.normalizeSolrUrl(cli) + "/solr/" + cli.getOptionValue("name");
+ if (cli.hasOption(CommonCLIOptions.SOLR_URL_OPTION)) {
+ url = SolrCLI.normalizeSolrUrl(cli) + "/solr/" + cli.getOptionValue(COLLECTION_NAME_OPTION);
} else {
// Could be required arg, but maybe we want to support --zk-host option too?
throw new IllegalArgumentException("Must specify --solr-url.");
}
- String rootDir = cli.getOptionValue("rootdir");
- String credentials = cli.getOptionValue("credentials");
+ String rootDir = cli.getOptionValue(ROOT_DIR_OPTION);
+ String credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);
runCommand(url, rootDir, credentials);
}
diff --git a/solr/core/src/java/org/apache/solr/cli/PostTool.java b/solr/core/src/java/org/apache/solr/cli/PostTool.java
index b888fdca589..0e50e619043 100644
--- a/solr/core/src/java/org/apache/solr/cli/PostTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/PostTool.java
@@ -68,6 +68,7 @@ import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.solr.client.api.util.SolrVersion;
import org.apache.solr.client.solrj.SolrClient;
@@ -94,6 +95,93 @@ public class PostTool extends ToolBase {
private static final int MAX_WEB_DEPTH = 10;
public static final String DEFAULT_CONTENT_TYPE = "application/json";
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the collection.")
+ .build();
+
+ private static final Option SKIP_COMMIT_OPTION =
+ Option.builder()
+ .longOpt("skip-commit")
+ .desc("Do not 'commit', and thus changes won't be visible till a commit occurs.")
+ .build();
+
+ private static final Option OPTIMIZE_OPTION =
+ Option.builder("o")
+ .longOpt("optimize")
+ .desc("Issue an optimize at end of posting documents.")
+ .build();
+
+ private static final Option MODE_OPTION =
+ Option.builder()
+ .longOpt("mode")
+ .hasArg()
+ .argName("mode")
+ .desc(
+ "Which mode the Post tool is running in, 'files' crawls local directory, 'web' crawls website, 'args' processes input args, and 'stdin' reads a command from standard in. default: files.")
+ .build();
+
+ private static final Option RECURSIVE_OPTION =
+ Option.builder("r")
+ .longOpt("recursive")
+ .hasArg()
+ .argName("recursive")
+ .type(Integer.class)
+ .desc("For web crawl, how deep to go. default: 1")
+ .build();
+
+ private static final Option DELAY_OPTION =
+ Option.builder("d")
+ .longOpt("delay")
+ .hasArg()
+ .argName("delay")
+ .type(Integer.class)
+ .desc(
+ "If recursive then delay will be the wait time between posts. default: 10 for web, 0 for files")
+ .build();
+
+ private static final Option TYPE_OPTION =
+ Option.builder("t")
+ .longOpt("type")
+ .hasArg()
+ .argName("content-type")
+ .desc("Specify a specific mimetype to use, such as application/json.")
+ .build();
+
+ private static final Option FILE_TYPES_OPTION =
+ Option.builder("ft")
+ .longOpt("filetypes")
+ .hasArg()
+ .argName("<type>[,<type>,...]")
+ .desc("default: " + DEFAULT_FILE_TYPES)
+ .build();
+
+ private static final Option PARAMS_OPTION =
+ Option.builder()
+ .longOpt("params")
+ .hasArg()
+ .argName("<key>=<value>[&<key>=<value>...]")
+ .desc("Values must be URL-encoded; these pass through to Solr update request.")
+ .build();
+
+ private static final Option FORMAT_OPTION =
+ Option.builder()
+ .longOpt("format")
+ .desc(
+ "sends application/json content as Solr commands to /update instead of /update/json/docs.")
+ .build();
+
+ private static final Option DRY_RUN_OPTION =
+ Option.builder()
+ .longOpt("dry-run")
+ .desc(
+ "Performs a dry run of the posting process without actually sending documents to Solr. Only works with files mode.")
+ .build();
+
// Input args
int recursive = 0;
int delay = 0;
@@ -169,128 +257,68 @@ public class PostTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("c")
- .longOpt("name")
- .hasArg()
- .required(true)
- .argName("NAME")
- .desc("Name of the collection.")
- .build(),
- Option.builder()
- .longOpt("skip-commit")
- .desc("Do not 'commit', and thus changes won't be visible till a commit occurs.")
- .build(),
- Option.builder("o")
- .longOpt("optimize")
- .desc("Issue an optimize at end of posting documents.")
- .build(),
- Option.builder()
- .longOpt("mode")
- .hasArg()
- .argName("mode")
- .desc(
- "Which mode the Post tool is running in, 'files' crawls local directory, 'web' crawls website, 'args' processes input args, and 'stdin' reads a command from standard in. default: files.")
- .build(),
- Option.builder("r")
- .longOpt("recursive")
- .hasArg()
- .argName("recursive")
- .required(false)
- .desc("For web crawl, how deep to go. default: 1")
- .build(),
- Option.builder()
- .longOpt("delay")
- .hasArg()
- .argName("delay")
- .required(false)
- .desc(
- "If recursive then delay will be the wait time between posts. default: 10 for web, 0 for files")
- .build(),
- Option.builder("t")
- .longOpt("type")
- .hasArg()
- .argName("content-type")
- .required(false)
- .desc("Specify a specific mimetype to use, such as application/json.")
- .build(),
- Option.builder("ft")
- .longOpt("filetypes")
- .hasArg()
- .argName("<type>[,<type>,...]")
- .required(false)
- .desc("default: " + DEFAULT_FILE_TYPES)
- .build(),
- Option.builder()
- .longOpt("params")
- .hasArg()
- .argName("<key>=<value>[&<key>=<value>...]")
- .required(false)
- .desc("Values must be URL-encoded; these pass through to Solr update request.")
- .build(),
- Option.builder()
- .longOpt("format")
- .required(false)
- .desc(
- "sends application/json content as Solr commands to /update instead of /update/json/docs.")
- .build(),
- Option.builder()
- .longOpt("dry-run")
- .required(false)
- .desc(
- "Performs a dry run of the posting process without actually sending documents to Solr. Only works with files mode.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(SKIP_COMMIT_OPTION)
+ .addOption(OPTIMIZE_OPTION)
+ .addOption(MODE_OPTION)
+ .addOption(RECURSIVE_OPTION)
+ .addOption(DELAY_OPTION)
+ .addOption(TYPE_OPTION)
+ .addOption(FILE_TYPES_OPTION)
+ .addOption(PARAMS_OPTION)
+ .addOption(FORMAT_OPTION)
+ .addOption(DRY_RUN_OPTION)
+ .addOption(CommonCLIOptions.SOLR_URL_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
solrUpdateUrl = null;
- if (cli.hasOption("solr-url")) {
+ if (cli.hasOption(CommonCLIOptions.SOLR_URL_OPTION)) {
String url =
- SolrCLI.normalizeSolrUrl(cli) + "/solr/" + cli.getOptionValue("name") + "/update";
+ SolrCLI.normalizeSolrUrl(cli)
+ + "/solr/"
+ + cli.getOptionValue(COLLECTION_NAME_OPTION)
+ + "/update";
solrUpdateUrl = new URI(url);
} else {
- String url = SolrCLI.getDefaultSolrUrl() + "/solr/" + cli.getOptionValue("name") + "/update";
+ String url =
+ SolrCLI.getDefaultSolrUrl()
+ + "/solr/"
+ + cli.getOptionValue(COLLECTION_NAME_OPTION)
+ + "/update";
solrUpdateUrl = new URI(url);
}
- String mode = cli.getOptionValue("mode", DATA_MODE_FILES);
+ String mode = cli.getOptionValue(MODE_OPTION, DATA_MODE_FILES);
- dryRun = cli.hasOption("dry-run");
+ dryRun = cli.hasOption(DRY_RUN_OPTION);
- if (cli.hasOption("type")) {
- type = cli.getOptionValue("type");
+ if (cli.hasOption(TYPE_OPTION)) {
+ type = cli.getOptionValue(TYPE_OPTION);
// Turn off automatically looking up the mimetype in favour of what is passed in.
auto = false;
}
- format = cli.hasOption("format") ? FORMAT_SOLR : ""; // i.e not solr formatted json commands
-
- if (cli.hasOption("filetypes")) {
- fileTypes = cli.getOptionValue("filetypes");
- }
-
- delay = (mode.equals((DATA_MODE_WEB)) ? 10 : 0);
- if (cli.hasOption("delay")) {
- delay = Integer.parseInt(cli.getOptionValue("delay"));
- }
-
- recursive = Integer.parseInt(cli.getOptionValue("recursive", "1"));
+ format =
+ cli.hasOption(FORMAT_OPTION) ? FORMAT_SOLR : ""; // i.e not solr formatted json commands
+ fileTypes = cli.getOptionValue(FILE_TYPES_OPTION, PostTool.DEFAULT_FILE_TYPES);
- out = cli.hasOption(SolrCLI.OPTION_VERBOSE.getLongOpt()) ? CLIO.getOutStream() : null;
- commit = !cli.hasOption("skip-commit");
- optimize = cli.hasOption("optimize");
+ int defaultDelay = (mode.equals((DATA_MODE_WEB)) ? 10 : 0);
+ delay = cli.getParsedOptionValue(DELAY_OPTION, defaultDelay);
+ recursive = cli.getParsedOptionValue(RECURSIVE_OPTION, 1);
- credentials = cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt());
+ out = isVerbose() ? CLIO.getOutStream() : null;
+ commit = !cli.hasOption(SKIP_COMMIT_OPTION);
+ optimize = cli.hasOption(OPTIMIZE_OPTION);
+ credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);
args = cli.getArgs();
- params = cli.getOptionValue("params", "");
+ params = cli.getOptionValue(PARAMS_OPTION, "");
execute(mode);
}
diff --git a/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java b/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java
index 51f1d634703..99307cf74f0 100644
--- a/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java
@@ -28,7 +28,6 @@ import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
-import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
@@ -37,6 +36,7 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
@@ -67,6 +67,99 @@ public class RunExampleTool extends ToolBase {
private static final String PROMPT_NUMBER_TOO_LARGE =
"%d is too large! " + PROMPT_FOR_NUMBER_IN_RANGE;
+ private static final Option NO_PROMPT_OPTION =
+ Option.builder("y")
+ .longOpt("no-prompt")
+ .desc(
+ "Don't prompt for input; accept all defaults when running examples that accept user input.")
+ .build();
+
+ private static final Option EXAMPLE_OPTION =
+ Option.builder("e")
+ .longOpt("example")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the example to launch, one of: cloud, techproducts, schemaless, films.")
+ .build();
+
+ private static final Option SCRIPT_OPTION =
+ Option.builder()
+ .longOpt("script")
+ .hasArg()
+ .argName("PATH")
+ .desc("Path to the bin/solr script.")
+ .build();
+
+ private static final Option SERVER_DIR_OPTION =
+ Option.builder("d")
+ .longOpt("server-dir")
+ .hasArg()
+ .argName("DIR")
+ .required()
+ .desc("Path to the Solr server directory.")
+ .build();
+
+ private static final Option FORCE_OPTION =
+ Option.builder("f")
+ .longOpt("force")
+ .argName("FORCE")
+ .desc("Force option in case Solr is run as root.")
+ .build();
+
+ private static final Option EXAMPLE_DIR_OPTION =
+ Option.builder()
+ .longOpt("example-dir")
+ .hasArg()
+ .argName("DIR")
+ .desc(
+ "Path to the Solr example directory; if not provided, ${serverDir}/../example is expected to exist.")
+ .build();
+
+ private static final Option URL_SCHEME_OPTION =
+ Option.builder()
+ .longOpt("url-scheme")
+ .hasArg()
+ .argName("SCHEME")
+ .desc("Solr URL scheme: http or https, defaults to http if not specified.")
+ .build();
+
+ private static final Option PORT_OPTION =
+ Option.builder("p")
+ .longOpt("port")
+ .hasArg()
+ .argName("PORT")
+ .desc("Specify the port to start the Solr HTTP listener on; default is 8983.")
+ .build();
+
+ private static final Option HOST_OPTION =
+ Option.builder()
+ .longOpt("host")
+ .hasArg()
+ .argName("HOSTNAME")
+ .desc("Specify the hostname for this Solr instance.")
+ .build();
+
+ private static final Option USER_MANAGED_OPTION =
+ Option.builder().longOpt("user-managed").desc("Start Solr in User Managed mode.").build();
+
+ private static final Option MEMORY_OPTION =
+ Option.builder("m")
+ .longOpt("memory")
+ .hasArg()
+ .argName("MEM")
+ .desc(
+ "Sets the min (-Xms) and max (-Xmx) heap size for the JVM, such as: -m 4g results in: -Xms4g -Xmx4g; by default, this script sets the heap size to 512m.")
+ .build();
+
+ private static final Option JVM_OPTS_OPTION =
+ Option.builder()
+ .longOpt("jvm-opts")
+ .hasArg()
+ .argName("OPTS")
+ .desc("Additional options to be passed to the JVM when starting example Solr server(s).")
+ .build();
+
protected InputStream userInput;
protected Executor executor;
protected String script;
@@ -91,105 +184,35 @@ public class RunExampleTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder("y")
- .longOpt("no-prompt")
- .required(false)
- .desc(
- "Don't prompt for input; accept all defaults when running examples that accept user input.")
- .build(),
- Option.builder("e")
- .longOpt("example")
- .hasArg()
- .argName("NAME")
- .required(true)
- .desc("Name of the example to launch, one of: cloud, techproducts, schemaless, films.")
- .build(),
- Option.builder()
- .longOpt("script")
- .hasArg()
- .argName("PATH")
- .required(false)
- .desc("Path to the bin/solr script.")
- .build(),
- Option.builder()
- .longOpt("server-dir")
- .hasArg()
- .argName("DIR")
- .required(true)
- .desc("Path to the Solr server directory.")
- .build(),
- Option.builder("f")
- .longOpt("force")
- .argName("FORCE")
- .desc("Force option in case Solr is run as root.")
- .build(),
- Option.builder()
- .longOpt("example-dir")
- .hasArg()
- .argName("DIR")
- .required(false)
- .desc(
- "Path to the Solr example directory; if not provided, ${serverDir}/../example is expected to exist.")
- .build(),
- Option.builder()
- .longOpt("url-scheme")
- .hasArg()
- .argName("SCHEME")
- .required(false)
- .desc("Solr URL scheme: http or https, defaults to http if not specified.")
- .build(),
- Option.builder("p")
- .longOpt("port")
- .hasArg()
- .argName("PORT")
- .required(false)
- .desc("Specify the port to start the Solr HTTP listener on; default is 8983.")
- .build(),
- Option.builder()
- .longOpt("host")
- .hasArg()
- .argName("HOSTNAME")
- .required(false)
- .desc("Specify the hostname for this Solr instance.")
- .build(),
- Option.builder()
- .longOpt("user-managed")
- .required(false)
- .desc("Start Solr in User Managed mode.")
- .build(),
- Option.builder("m")
- .longOpt("memory")
- .hasArg()
- .argName("MEM")
- .required(false)
- .desc(
- "Sets the min (-Xms) and max (-Xmx) heap size for the JVM, such as: -m 4g results in: -Xms4g -Xmx4g; by default, this script sets the heap size to 512m.")
- .build(),
- Option.builder()
- .longOpt("jvm-opts")
- .hasArg()
- .argName("OPTS")
- .required(false)
- .desc(
- "Additional options to be passed to the JVM when starting example Solr server(s).")
- .build(),
- SolrCLI.OPTION_ZKHOST);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(NO_PROMPT_OPTION)
+ .addOption(EXAMPLE_OPTION)
+ .addOption(SCRIPT_OPTION)
+ .addOption(SERVER_DIR_OPTION)
+ .addOption(FORCE_OPTION)
+ .addOption(EXAMPLE_DIR_OPTION)
+ .addOption(URL_SCHEME_OPTION)
+ .addOption(PORT_OPTION)
+ .addOption(HOST_OPTION)
+ .addOption(USER_MANAGED_OPTION)
+ .addOption(MEMORY_OPTION)
+ .addOption(JVM_OPTS_OPTION)
+ .addOption(CommonCLIOptions.ZK_HOST_OPTION);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- this.urlScheme = cli.getOptionValue("url-scheme", "http");
+ this.urlScheme = cli.getOptionValue(URL_SCHEME_OPTION, "http");
- serverDir = new File(cli.getOptionValue("server-dir"));
+ serverDir = new File(cli.getOptionValue(SERVER_DIR_OPTION));
if (!serverDir.isDirectory())
throw new IllegalArgumentException(
"Value of --server-dir option is invalid! "
+ serverDir.getAbsolutePath()
+ " is not a directory!");
- script = cli.getOptionValue("script");
+ script = cli.getOptionValue(SCRIPT_OPTION);
if (script != null) {
if (!(new File(script)).isFile())
throw new IllegalArgumentException(
@@ -210,8 +233,8 @@ public class RunExampleTool extends ToolBase {
}
exampleDir =
- (cli.hasOption("example-dir"))
- ? new File(cli.getOptionValue("example-dir"))
+ (cli.hasOption(EXAMPLE_DIR_OPTION))
+ ? new File(cli.getOptionValue(EXAMPLE_DIR_OPTION))
: new File(serverDir.getParent(), "example");
if (!exampleDir.isDirectory())
throw new IllegalArgumentException(
@@ -227,7 +250,7 @@ public class RunExampleTool extends ToolBase {
+ "\nscript="
+ script);
- String exampleType = cli.getOptionValue("example");
+ String exampleType = cli.getOptionValue(EXAMPLE_OPTION);
if ("cloud".equals(exampleType)) {
runCloudExample(cli);
} else if ("techproducts".equals(exampleType)
@@ -248,11 +271,11 @@ public class RunExampleTool extends ToolBase {
String configSet =
"techproducts".equals(exampleName) ? "sample_techproducts_configs" : "_default";
- boolean isCloudMode = !cli.hasOption("user-managed");
- String zkHost = cli.getOptionValue('z');
+ boolean isCloudMode = !cli.hasOption(USER_MANAGED_OPTION);
+ String zkHost = cli.getOptionValue(CommonCLIOptions.ZK_HOST_OPTION);
int port =
Integer.parseInt(
- cli.getOptionValue('p', System.getenv().getOrDefault("SOLR_PORT", "8983")));
+ cli.getOptionValue(PORT_OPTION, System.getenv().getOrDefault("SOLR_PORT", "8983")));
Map<String, Object> nodeStatus =
startSolr(new File(exDir, "solr"), isCloudMode, cli, port, zkHost, 30);
@@ -264,7 +287,7 @@ public class RunExampleTool extends ToolBase {
boolean cloudMode = nodeStatus.get("cloud") != null;
if (cloudMode) {
if (SolrCLI.safeCheckCollectionExists(
- solrUrl, collectionName, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ solrUrl, collectionName, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
alreadyExists = true;
echo(
"\nWARNING: Collection '"
@@ -274,7 +297,7 @@ public class RunExampleTool extends ToolBase {
} else {
String coreName = collectionName;
if (SolrCLI.safeCheckCoreExists(
- solrUrl, coreName, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()))) {
+ solrUrl, coreName, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION))) {
alreadyExists = true;
echo(
"\nWARNING: Core '"
@@ -433,12 +456,12 @@ public class RunExampleTool extends ToolBase {
protected void runCloudExample(CommandLine cli) throws Exception {
- boolean prompt = !cli.hasOption("no-prompt");
+ boolean prompt = !cli.hasOption(NO_PROMPT_OPTION);
int numNodes = 2;
int[] cloudPorts = new int[] {8983, 7574, 8984, 7575};
int defaultPort =
Integer.parseInt(
- cli.getOptionValue('p', System.getenv().getOrDefault("SOLR_PORT", "8983")));
+ cli.getOptionValue(PORT_OPTION, System.getenv().getOrDefault("SOLR_PORT", "8983")));
if (defaultPort != 8983) {
// Override the old default port numbers if user has started the example overriding SOLR_PORT
cloudPorts = new int[] {defaultPort, defaultPort + 1, defaultPort + 2, defaultPort + 3};
@@ -502,7 +525,7 @@ public class RunExampleTool extends ToolBase {
}
// deal with extra args passed to the script to run the example
- String zkHost = cli.getOptionValue('z');
+ String zkHost = cli.getOptionValue(CommonCLIOptions.ZK_HOST_OPTION);
// start the first node (most likely with embedded ZK)
Map<String, Object> nodeStatus =
@@ -539,7 +562,7 @@ public class RunExampleTool extends ToolBase {
readInput,
prompt,
solrUrl,
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()));
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
echo("\n\nSolrCloud example running, please visit: " + solrUrl + " \n");
}
@@ -593,18 +616,17 @@ public class RunExampleTool extends ToolBase {
String extraArgs = readExtraArgs(cli.getArgs());
- String host = cli.getOptionValue("host");
- String memory = cli.getOptionValue('m');
+ String host = cli.getOptionValue(HOST_OPTION);
+ String memory = cli.getOptionValue(MEMORY_OPTION);
String hostArg = (host != null && !"localhost".equals(host)) ? " --host " + host : "";
String zkHostArg = (zkHost != null) ? " -z " + zkHost : "";
String memArg = (memory != null) ? " -m " + memory : "";
String cloudModeArg = cloudMode ? "" : "--user-managed";
- String forceArg = cli.hasOption("force") ? " --force" : "";
- String verboseArg = verbose ? "--verbose" : "";
+ String forceArg = cli.hasOption(FORCE_OPTION) ? " --force" : "";
+ String verboseArg = isVerbose() ? "--verbose" : "";
- String jvmOpts =
- cli.hasOption("jvm-opts") ? cli.getOptionValue("jvm-opts") : cli.getOptionValue('a');
+ String jvmOpts = cli.getOptionValue(JVM_OPTS_OPTION);
String jvmOptsArg = (jvmOpts != null) ? " --jvm-opts \"" + jvmOpts + "\"" : "";
File cwd = new File(System.getProperty("user.dir"));
@@ -694,7 +716,7 @@ public class RunExampleTool extends ToolBase {
if (code != 0) throw new Exception("Failed to start Solr using command: " + startCmd);
return getNodeStatus(
- solrUrl, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()), maxWaitSecs);
+ solrUrl, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION), maxWaitSecs);
}
protected Map<String, Object> checkPortConflict(
@@ -985,7 +1007,7 @@ public class RunExampleTool extends ToolBase {
}
} catch (NumberFormatException nfe) {
- if (verbose) echo(value + " is not a number!");
+ if (isVerbose()) echo(value + " is not a number!");
if (min != null && max != null) {
value =
diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java
index d80dfbc61ea..236a7416832 100644
--- a/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java
@@ -17,9 +17,9 @@
package org.apache.solr.cli;
import java.io.PrintStream;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
@@ -27,6 +27,24 @@ import org.apache.solr.client.solrj.response.CollectionAdminResponse;
/** Supports snapshot-create command in the bin/solr script. */
public class SnapshotCreateTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of collection to be snapshot.")
+ .build();
+
+ private static final Option SNAPSHOT_NAME_OPTION =
+ Option.builder()
+ .longOpt("snapshot-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the snapshot to produce")
+ .build();
+
public SnapshotCreateTool() {
this(CLIO.getOutStream());
}
@@ -41,33 +59,18 @@ public class SnapshotCreateTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_SOLRURL,
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of collection to be snapshot.")
- .build(),
- Option.builder()
- .longOpt("snapshot-name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the snapshot to produce")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(SNAPSHOT_NAME_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- String snapshotName = cli.getOptionValue("snapshot-name");
- String collectionName = cli.getOptionValue("name");
+ String snapshotName = cli.getOptionValue(SNAPSHOT_NAME_OPTION);
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
try (var solrClient = SolrCLI.getSolrClient(cli)) {
createSnapshot(solrClient, collectionName, snapshotName);
}
diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java
index d172391183e..53fa8ad002a 100644
--- a/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java
@@ -17,9 +17,9 @@
package org.apache.solr.cli;
import java.io.PrintStream;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
@@ -27,6 +27,24 @@ import org.apache.solr.client.solrj.response.CollectionAdminResponse;
/** Supports snapshot-delete command in the bin/solr script. */
public class SnapshotDeleteTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of collection to manage.")
+ .build();
+
+ private static final Option SNAPSHOT_NAME_OPTION =
+ Option.builder()
+ .longOpt("snapshot-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the snapshot to delete")
+ .build();
+
public SnapshotDeleteTool() {
this(CLIO.getOutStream());
}
@@ -41,33 +59,18 @@ public class SnapshotDeleteTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_SOLRURL,
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of collection to manage.")
- .build(),
- Option.builder()
- .longOpt("snapshot-name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the snapshot to delete")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(SNAPSHOT_NAME_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- String snapshotName = cli.getOptionValue("snapshot-name");
- String collectionName = cli.getOptionValue("name");
+ String snapshotName = cli.getOptionValue(SNAPSHOT_NAME_OPTION);
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
try (var solrClient = SolrCLI.getSolrClient(cli)) {
deleteSnapshot(solrClient, collectionName, snapshotName);
}
diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java
index a007b75f075..b76f36a7420 100644
--- a/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java
@@ -22,10 +22,10 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.List;
import java.util.Locale;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
@@ -37,6 +37,24 @@ import org.apache.solr.core.snapshots.SolrSnapshotManager;
/** Supports snapshot-describe command in the bin/solr script. */
public class SnapshotDescribeTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of collection to be snapshot.")
+ .build();
+
+ private static final Option SNAPSHOT_NAME_OPTION =
+ Option.builder()
+ .longOpt("snapshot-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the snapshot to describe")
+ .build();
+
public SnapshotDescribeTool() {
this(CLIO.getOutStream());
}
@@ -54,33 +72,18 @@ public class SnapshotDescribeTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_SOLRURL,
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of collection to be snapshot.")
- .build(),
- Option.builder()
- .longOpt("snapshot-name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the snapshot to describe")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(SNAPSHOT_NAME_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- String snapshotName = cli.getOptionValue("snapshot-name");
- String collectionName = cli.getOptionValue("name");
+ String snapshotName = cli.getOptionValue(SNAPSHOT_NAME_OPTION);
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
try (var solrClient = SolrCLI.getSolrClient(cli)) {
describeSnapshot(solrClient, collectionName, snapshotName);
}
diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java
index 8471ec79287..a51e91badb3 100644
--- a/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java
@@ -17,10 +17,10 @@
package org.apache.solr.cli;
import java.io.PrintStream;
-import java.util.List;
import java.util.Optional;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.common.params.CollectionAdminParams;
@@ -28,6 +28,51 @@ import org.apache.solr.common.params.CollectionAdminParams;
/** Supports snapshot-export command in the bin/solr script. */
public class SnapshotExportTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of collection to be snapshot.")
+ .build();
+
+ private static final Option SNAPSHOT_NAME_OPTION =
+ Option.builder()
+ .longOpt("snapshot-name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of the snapshot to be exported.")
+ .build();
+
+ private static final Option DEST_DIR_OPTION =
+ Option.builder()
+ .longOpt("dest-dir")
+ .hasArg()
+ .argName("DIR")
+ .required()
+ .desc("Path of a temporary directory on local filesystem during snapshot export command.")
+ .build();
+
+ private static final Option BACKUP_REPO_NAME_OPTION =
+ Option.builder()
+ .longOpt("backup-repo-name")
+ .hasArg()
+ .argName("DIR")
+ .desc(
+ "Specifies name of the backup repository to be used during snapshot export preparation.")
+ .build();
+
+ private static final Option ASYNC_ID_OPTION =
+ Option.builder()
+ .longOpt("async-id")
+ .hasArg()
+ .argName("ID")
+ .desc(
+ "Specifies the async request identifier to be used during snapshot export preparation.")
+ .build();
+
public SnapshotExportTool() {
this(CLIO.getOutStream());
}
@@ -42,60 +87,24 @@ public class SnapshotExportTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_SOLRURL,
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of collection to be snapshot.")
- .build(),
- Option.builder()
- .longOpt("snapshot-name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of the snapshot to be exported.")
- .build(),
- Option.builder()
- .longOpt("dest-dir")
- .argName("DIR")
- .hasArg()
- .required(true)
- .desc(
- "Path of a temporary directory on local filesystem during snapshot export command.")
- .build(),
- Option.builder()
- .longOpt("backup-repo-name")
- .argName("DIR")
- .hasArg()
- .required(false)
- .desc(
- "Specifies name of the backup repository to be used during snapshot export preparation.")
- .build(),
- Option.builder()
- .longOpt("async-id")
- .argName("ID")
- .hasArg()
- .required(false)
- .desc(
- "Specifies the async request identifier to be used during snapshot export preparation.")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(SNAPSHOT_NAME_OPTION)
+ .addOption(DEST_DIR_OPTION)
+ .addOption(BACKUP_REPO_NAME_OPTION)
+ .addOption(ASYNC_ID_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- String snapshotName = cli.getOptionValue("snapshot-name");
- String collectionName = cli.getOptionValue("name");
- String destDir = cli.getOptionValue("dest-dir");
- Optional<String> backupRepo = Optional.ofNullable(cli.getOptionValue("backup-repo-name"));
- Optional<String> asyncReqId = Optional.ofNullable(cli.getOptionValue("async-id"));
+ String snapshotName = cli.getOptionValue(SNAPSHOT_NAME_OPTION);
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
+ String destDir = cli.getOptionValue(DEST_DIR_OPTION);
+ Optional<String> backupRepo = Optional.ofNullable(cli.getOptionValue(BACKUP_REPO_NAME_OPTION));
+ Optional<String> asyncReqId = Optional.ofNullable(cli.getOptionValue(ASYNC_ID_OPTION));
try (var solrClient = SolrCLI.getSolrClient(cli)) {
exportSnapshot(solrClient, collectionName, snapshotName, destDir, backupRepo, asyncReqId);
diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java
index a1db955b0c0..87219ce6021 100644
--- a/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java
@@ -17,9 +17,9 @@
package org.apache.solr.cli;
import java.io.PrintStream;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
@@ -29,6 +29,15 @@ import org.apache.solr.core.snapshots.SolrSnapshotManager;
/** Supports snapshot-list command in the bin/solr script. */
public class SnapshotListTool extends ToolBase {
+ private static final Option COLLECTION_NAME_OPTION =
+ Option.builder("c")
+ .longOpt("name")
+ .hasArg()
+ .argName("NAME")
+ .required()
+ .desc("Name of collection to list snapshots for.")
+ .build();
+
public SnapshotListTool() {
this(CLIO.getOutStream());
}
@@ -43,25 +52,16 @@ public class SnapshotListTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_SOLRURL,
- Option.builder("c")
- .longOpt("name")
- .argName("NAME")
- .hasArg()
- .required(true)
- .desc("Name of collection to list snapshots for.")
- .build(),
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(COLLECTION_NAME_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- String collectionName = cli.getOptionValue("name");
+ String collectionName = cli.getOptionValue(COLLECTION_NAME_OPTION);
try (var solrClient = SolrCLI.getSolrClient(cli)) {
listSnapshots(solrClient, collectionName);
}
diff --git a/solr/core/src/java/org/apache/solr/cli/SolrCLI.java b/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
index 9f762459fcb..00a97b4434c 100755
--- a/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
+++ b/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
@@ -68,7 +68,6 @@ import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.EnvUtils;
import org.apache.solr.common.util.NamedList;
-import org.apache.solr.util.StartupLoggingUtils;
import org.apache.solr.util.configuration.SSLConfigurationsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,58 +84,6 @@ public class SolrCLI implements CLIO {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- public static final String ZK_HOST = "localhost:9983";
-
- public static final Option OPTION_ZKHOST =
- Option.builder("z")
- .longOpt("zk-host")
- .argName("HOST")
- .hasArg()
- .required(false)
- .desc(
- "Zookeeper connection string; unnecessary if ZK_HOST is defined in solr.in.sh; otherwise, defaults to "
- + ZK_HOST
- + '.')
- .build();
- public static final Option OPTION_SOLRURL =
- Option.builder("s")
- .longOpt("solr-url")
- .argName("HOST")
- .hasArg()
- .required(false)
- .desc(
- "Base Solr URL, which can be used to determine the zk-host if that's not known; defaults to: "
- + getDefaultSolrUrl()
- + '.')
- .build();
-
- public static final Option OPTION_VERBOSE =
- Option.builder()
- .longOpt("verbose")
- .required(false)
- .desc("Enable verbose command output.")
- .build();
-
- public static final Option OPTION_HELP =
- Option.builder("h").longOpt("help").required(false).desc("Print this message.").build();
-
- public static final Option OPTION_RECURSIVE =
- Option.builder("r")
- .longOpt("recursive")
- .required(false)
- .desc("Apply the command recursively.")
- .build();
-
- public static final Option OPTION_CREDENTIALS =
- Option.builder("u")
- .longOpt("credentials")
- .argName("credentials")
- .hasArg()
- .required(false)
- .desc(
- "Credentials in the format username:password. Example: --credentials solr:SolrRocks")
- .build();
-
public static void exit(int exitStatus) {
try {
System.exit(exitStatus);
@@ -272,12 +219,6 @@ public class SolrCLI implements CLIO {
}
}
- public static void raiseLogLevelUnlessVerbose(CommandLine cli) {
- if (!cli.hasOption(SolrCLI.OPTION_VERBOSE.getLongOpt())) {
- StartupLoggingUtils.changeLogLevel("WARN");
- }
- }
-
// Creates an instance of the requested tool, using classpath scanning if necessary
private static Tool newTool(String toolType) throws Exception {
if ("healthcheck".equals(toolType)) return new HealthcheckTool();
@@ -322,21 +263,6 @@ public class SolrCLI implements CLIO {
throw new IllegalArgumentException(toolType + " is not a valid command!");
}
- /** Returns tool options for given tool, for usage display purposes. Hides deprecated options. */
- public static Options getToolOptions(Tool tool) {
- Options options = new Options();
- options.addOption(OPTION_HELP);
- options.addOption(OPTION_VERBOSE);
-
- List<Option> toolOpts = tool.getOptions();
- for (Option toolOpt : toolOpts) {
- if (!toolOpt.isDeprecated()) {
- options.addOption(toolOpt);
- }
- }
- return options;
- }
-
/**
* Returns the value of the option with the given name, or the value of the deprecated option. If
* both values are null, then it returns the default value.
@@ -371,17 +297,7 @@ public class SolrCLI implements CLIO {
/** Parses the command-line arguments passed by the user. */
public static CommandLine processCommandLineArgs(Tool tool, String[] args) {
- List<Option> customOptions = tool.getOptions();
- Options options = new Options();
-
- options.addOption(OPTION_HELP);
- options.addOption(OPTION_VERBOSE);
-
- if (customOptions != null) {
- for (Option customOption : customOptions) {
- options.addOption(customOption);
- }
- }
+ Options options = tool.getOptions();
CommandLine cli = null;
try {
@@ -411,7 +327,7 @@ public class SolrCLI implements CLIO {
}
}
- if (cli.hasOption("help")) {
+ if (cli.hasOption(CommonCLIOptions.HELP_OPTION)) {
printToolHelp(tool);
exit(0);
}
@@ -422,16 +338,18 @@ public class SolrCLI implements CLIO {
/** Prints tool help for a given tool */
public static void printToolHelp(Tool tool) {
HelpFormatter formatter = getFormatter();
- Options optionsNoDeprecated = new Options();
- SolrCLI.getToolOptions(tool).getOptions().stream()
+ Options nonDeprecatedOptions = new Options();
+
+ tool.getOptions().getOptions().stream()
.filter(option -> !option.isDeprecated())
- .forEach(optionsNoDeprecated::addOption);
+ .forEach(nonDeprecatedOptions::addOption);
+
String usageString = tool.getUsage() == null ? "bin/solr " + tool.getName() : tool.getUsage();
boolean autoGenerateUsage = tool.getUsage() == null;
formatter.printHelp(
usageString,
"\n" + tool.getHeader(),
- optionsNoDeprecated,
+ nonDeprecatedOptions,
tool.getFooter(),
autoGenerateUsage);
}
@@ -543,13 +461,13 @@ public class SolrCLI implements CLIO {
public static SolrClient getSolrClient(CommandLine cli, boolean barePath) throws Exception {
String solrUrl = SolrCLI.normalizeSolrUrl(cli);
- String credentials = cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt());
+ String credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);
return getSolrClient(solrUrl, credentials, barePath);
}
public static SolrClient getSolrClient(CommandLine cli) throws Exception {
String solrUrl = SolrCLI.normalizeSolrUrl(cli);
- String credentials = cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt());
+ String credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);
return getSolrClient(solrUrl, credentials, false);
}
@@ -564,8 +482,6 @@ public class SolrCLI implements CLIO {
return solrClient.request(req);
}
- public static final String DEFAULT_CONFIG_SET = "_default";
-
private static final long MS_IN_MIN = 60 * 1000L;
private static final long MS_IN_HOUR = MS_IN_MIN * 60L;
private static final long MS_IN_DAY = MS_IN_HOUR * 24L;
@@ -672,10 +588,9 @@ public class SolrCLI implements CLIO {
* ZooKeeper.
*/
public static String normalizeSolrUrl(CommandLine cli) throws Exception {
- String solrUrl = cli.getOptionValue("solr-url");
-
+ String solrUrl = cli.getOptionValue(CommonCLIOptions.SOLR_URL_OPTION);
if (solrUrl == null) {
- String zkHost = cli.getOptionValue("zk-host");
+ String zkHost = cli.getOptionValue(CommonCLIOptions.ZK_HOST_OPTION);
if (zkHost == null) {
solrUrl = SolrCLI.getDefaultSolrUrl();
CLIO.err(
@@ -706,7 +621,7 @@ public class SolrCLI implements CLIO {
*/
public static String getZkHost(CommandLine cli) throws Exception {
- String zkHost = cli.getOptionValue("zk-host");
+ String zkHost = cli.getOptionValue(CommonCLIOptions.ZK_HOST_OPTION);
if (zkHost != null && !zkHost.isBlank()) {
return zkHost;
}
@@ -734,15 +649,11 @@ public class SolrCLI implements CLIO {
return zkHost;
}
- public static SolrZkClient getSolrZkClient(CommandLine cli) throws Exception {
- return getSolrZkClient(cli, getZkHost(cli));
- }
-
public static SolrZkClient getSolrZkClient(CommandLine cli, String zkHost) throws Exception {
if (zkHost == null) {
throw new IllegalStateException(
"Solr at "
- + cli.getOptionValue("solrUrl")
+ + cli.getOptionValue(CommonCLIOptions.SOLR_URL_OPTION)
+ " is running in standalone server mode, this command can only be used when running in SolrCloud mode.\n");
}
return new SolrZkClient.Builder()
diff --git a/solr/core/src/java/org/apache/solr/cli/StatusTool.java b/solr/core/src/java/org/apache/solr/cli/StatusTool.java
index 16ad16e5946..dcf0200e511 100644
--- a/solr/core/src/java/org/apache/solr/cli/StatusTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/StatusTool.java
@@ -17,8 +17,6 @@
package org.apache.solr.cli;
-import static org.apache.solr.cli.SolrCLI.OPTION_SOLRURL;
-
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
@@ -32,6 +30,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionGroup;
+import org.apache.commons.cli.Options;
import org.apache.solr.cli.SolrProcessManager.SolrProcess;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
@@ -49,65 +49,67 @@ import org.noggit.JSONWriter;
* <p>Get the status of a Solr server.
*/
public class StatusTool extends ToolBase {
- private final SolrProcessManager processMgr;
-
- public StatusTool() {
- this(CLIO.getOutStream());
- }
- public StatusTool(PrintStream stdout) {
- super(stdout);
- processMgr = new SolrProcessManager();
- }
-
- @Override
- public String getName() {
- return "status";
- }
-
- private static final Option OPTION_MAXWAITSECS =
+ private static final Option MAX_WAIT_SECS_OPTION =
Option.builder()
.longOpt("max-wait-secs")
- .argName("SECS")
.hasArg()
- .required(false)
+ .argName("SECS")
+ .type(Integer.class)
.deprecated() // Will make it a stealth option, not printed or complained about
.desc("Wait up to the specified number of seconds to see Solr running.")
.build();
- public static final Option OPTION_PORT =
+ public static final Option PORT_OPTION =
Option.builder("p")
.longOpt("port")
- .argName("PORT")
- .required(false)
.hasArg()
+ .argName("PORT")
+ .type(Integer.class)
.desc("Port on localhost to check status for")
.build();
- public static final Option OPTION_SHORT =
+ public static final Option SHORT_OPTION =
Option.builder()
.longOpt("short")
.argName("SHORT")
- .required(false)
.desc("Short format. Prints one URL per line for running instances")
.build();
+ private final SolrProcessManager processMgr;
+
+ public StatusTool() {
+ this(CLIO.getOutStream());
+ }
+
+ public StatusTool(PrintStream stdout) {
+ super(stdout);
+ processMgr = new SolrProcessManager();
+ }
+
@Override
- public List<Option> getOptions() {
- return List.of(OPTION_SOLRURL, OPTION_MAXWAITSECS, OPTION_PORT, OPTION_SHORT);
+ public String getName() {
+ return "status";
+ }
+
+ @Override
+ public Options getOptions() {
+ OptionGroup optionGroup = new OptionGroup();
+ optionGroup.addOption(PORT_OPTION);
+ optionGroup.addOption(CommonCLIOptions.SOLR_URL_OPTION);
+ return super.getOptions()
+ .addOption(MAX_WAIT_SECS_OPTION)
+ .addOption(SHORT_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(optionGroup);
}
@Override
public void runImpl(CommandLine cli) throws Exception {
- String solrUrl = cli.getOptionValue(OPTION_SOLRURL);
- Integer port =
- cli.hasOption(OPTION_PORT) ? Integer.parseInt(cli.getOptionValue(OPTION_PORT)) : null;
- boolean shortFormat = cli.hasOption(OPTION_SHORT);
- int maxWaitSecs = Integer.parseInt(cli.getOptionValue("max-wait-secs", "0"));
-
- if (port != null && solrUrl != null) {
- throw new IllegalArgumentException("Only one of port or url can be specified");
- }
+ String solrUrl = cli.getOptionValue(CommonCLIOptions.SOLR_URL_OPTION);
+ Integer port = cli.hasOption(PORT_OPTION) ? cli.getParsedOptionValue(PORT_OPTION) : null;
+ boolean shortFormat = cli.hasOption(SHORT_OPTION);
+ int maxWaitSecs = cli.getParsedOptionValue(MAX_WAIT_SECS_OPTION, 0);
if (solrUrl != null) {
if (!URLUtil.hasScheme(solrUrl)) {
@@ -165,8 +167,8 @@ public class StatusTool extends ToolBase {
}
private void printProcessStatus(SolrProcess process, CommandLine cli) throws Exception {
- int maxWaitSecs = Integer.parseInt(cli.getOptionValue("max-wait-secs", "0"));
- boolean shortFormat = cli.hasOption(OPTION_SHORT);
+ int maxWaitSecs = cli.getParsedOptionValue(MAX_WAIT_SECS_OPTION, 0);
+ boolean shortFormat = cli.hasOption(SHORT_OPTION);
String pidUrl = process.getLocalUrl();
if (shortFormat) {
CLIO.out(pidUrl);
@@ -227,7 +229,7 @@ public class StatusTool extends ToolBase {
try {
waitToSeeSolrUp(
solrUrl,
- cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt()),
+ cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION),
maxWaitSecs,
TimeUnit.SECONDS);
return true;
@@ -263,7 +265,7 @@ public class StatusTool extends ToolBase {
try {
CharArr arr = new CharArr();
new JSONWriter(arr, 2)
- .write(getStatus(solrUrl, cli.getOptionValue(SolrCLI.OPTION_CREDENTIALS.getLongOpt())));
+ .write(getStatus(solrUrl, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION)));
return arr.toString();
} catch (Exception exc) {
if (SolrCLI.exceptionIsAuthRelated(exc)) {
diff --git a/solr/core/src/java/org/apache/solr/cli/Tool.java b/solr/core/src/java/org/apache/solr/cli/Tool.java
index 0edde7cdae2..a95af511642 100644
--- a/solr/core/src/java/org/apache/solr/cli/Tool.java
+++ b/solr/core/src/java/org/apache/solr/cli/Tool.java
@@ -17,9 +17,8 @@
package org.apache.solr.cli;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
public interface Tool {
/** Defines the interface to a Solr tool that can be run from this command-line app. */
@@ -50,7 +49,12 @@ public interface Tool {
return "\nPlease see the Reference Guide for more tools documentation: https://solr.apache.org/guide/solr/latest/deployment-guide/solr-control-script-reference.html";
}
- List<Option> getOptions();
+ /**
+ * Retrieve the {@link Options} supported by this tool.
+ *
+ * @return The {@link Options} this tool supports.
+ */
+ Options getOptions();
int runTool(CommandLine cli) throws Exception;
}
diff --git a/solr/core/src/java/org/apache/solr/cli/ToolBase.java b/solr/core/src/java/org/apache/solr/cli/ToolBase.java
index d35b63e1528..b0a0e1063a7 100644
--- a/solr/core/src/java/org/apache/solr/cli/ToolBase.java
+++ b/solr/core/src/java/org/apache/solr/cli/ToolBase.java
@@ -19,11 +19,14 @@ package org.apache.solr.cli;
import java.io.PrintStream;
import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.OptionGroup;
+import org.apache.commons.cli.Options;
+import org.apache.solr.util.StartupLoggingUtils;
public abstract class ToolBase implements Tool {
+ private boolean verbose = false;
protected PrintStream stdout;
- protected boolean verbose = false;
protected ToolBase() {
this(CLIO.getOutStream());
@@ -48,9 +51,29 @@ public abstract class ToolBase implements Tool {
stdout.println(msg);
}
+ @Override
+ public Options getOptions() {
+ return new Options()
+ .addOption(CommonCLIOptions.HELP_OPTION)
+ .addOption(CommonCLIOptions.VERBOSE_OPTION);
+ }
+
+ /**
+ * Provides the two ways of connecting to Solr for CLI Tools
+ *
+ * @return OptionGroup validates that only one option is supplied by the caller.
+ */
+ public OptionGroup getConnectionOptions() {
+ OptionGroup optionGroup = new OptionGroup();
+ optionGroup.addOption(CommonCLIOptions.SOLR_URL_OPTION);
+ optionGroup.addOption(CommonCLIOptions.ZK_HOST_OPTION);
+ return optionGroup;
+ }
+
@Override
public int runTool(CommandLine cli) throws Exception {
- verbose = cli.hasOption(SolrCLI.OPTION_VERBOSE.getLongOpt());
+ verbose = cli.hasOption(CommonCLIOptions.VERBOSE_OPTION);
+ raiseLogLevelUnlessVerbose();
int toolExitStatus = 0;
try {
@@ -71,5 +94,11 @@ public abstract class ToolBase implements Tool {
return toolExitStatus;
}
+ private void raiseLogLevelUnlessVerbose() {
+ if (!verbose) {
+ StartupLoggingUtils.changeLogLevel("WARN");
+ }
+ }
+
public abstract void runImpl(CommandLine cli) throws Exception;
}
diff --git a/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java b/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java
index e9a9c5b444e..996ada0a213 100644
--- a/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java
@@ -18,10 +18,9 @@
package org.apache.solr.cli;
import java.io.PrintStream;
-import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.impl.SolrZkClientTimeout;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.cloud.SolrZkClient;
@@ -53,8 +52,8 @@ public class UpdateACLTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(SolrCLI.OPTION_ZKHOST);
+ public Options getOptions() {
+ return super.getOptions().addOption(CommonCLIOptions.ZK_HOST_OPTION);
}
@Override
diff --git a/solr/core/src/java/org/apache/solr/cli/VersionTool.java b/solr/core/src/java/org/apache/solr/cli/VersionTool.java
index f5e84e6c1f8..148bdf36a40 100644
--- a/solr/core/src/java/org/apache/solr/cli/VersionTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/VersionTool.java
@@ -17,10 +17,7 @@
package org.apache.solr.cli;
-import java.util.Collections;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.Option;
import org.apache.solr.client.api.util.SolrVersion;
public class VersionTool extends ToolBase {
@@ -30,11 +27,6 @@ public class VersionTool extends ToolBase {
return "version";
}
- @Override
- public List<Option> getOptions() {
- return Collections.emptyList();
- }
-
@Override
public void runImpl(CommandLine cli) throws Exception {
CLIO.out("Solr version is: " + SolrVersion.LATEST);
diff --git a/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java b/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java
index 488618e2f41..b2045ef3541 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java
@@ -23,12 +23,12 @@ import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.impl.SolrZkClientTimeout;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.SolrZkClient;
@@ -44,6 +44,14 @@ import org.slf4j.LoggerFactory;
public class ZkCpTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option SOLR_HOME_OPTION =
+ Option.builder()
+ .longOpt("solr-home")
+ .hasArg()
+ .argName("DIR")
+ .desc("Required to look up configuration for compressing state.json.")
+ .build();
+
public ZkCpTool() {
this(CLIO.getOutStream());
}
@@ -53,19 +61,12 @@ public class ZkCpTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("solr-home")
- .argName("DIR")
- .hasArg()
- .required(false)
- .desc("Required to look up configuration for compressing state.json.")
- .build(),
- SolrCLI.OPTION_RECURSIVE,
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(SOLR_HOME_OPTION)
+ .addOption(CommonCLIOptions.RECURSIVE_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -123,13 +124,12 @@ public class ZkCpTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...");
String src = cli.getArgs()[0];
String dst = cli.getArgs()[1];
- boolean recursive = cli.hasOption("recursive");
+ boolean recursive = cli.hasOption(CommonCLIOptions.RECURSIVE_OPTION);
echo("Copying from '" + src + "' to '" + dst + "'. ZooKeeper at " + zkHost);
boolean srcIsZk = src.toLowerCase(Locale.ROOT).startsWith("zk:");
@@ -158,7 +158,7 @@ public class ZkCpTool extends ToolBase {
Compressor compressor = new ZLibCompressor();
if (dstIsZk) {
- String solrHome = cli.getOptionValue("solr-home");
+ String solrHome = cli.getOptionValue(SOLR_HOME_OPTION);
if (StrUtils.isNullOrEmpty(solrHome)) {
solrHome = System.getProperty("solr.home");
}
diff --git a/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java b/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java
index cefb37b0e76..c8f1f55b266 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java
@@ -18,9 +18,8 @@ package org.apache.solr.cli;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.common.cloud.SolrZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,12 +37,11 @@ public class ZkLsTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_RECURSIVE,
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(CommonCLIOptions.RECURSIVE_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -59,14 +57,13 @@ public class ZkLsTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
String znode = cli.getArgs()[0];
try (SolrZkClient zkClient = SolrCLI.getSolrZkClient(cli, zkHost)) {
echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...");
- boolean recursive = cli.hasOption("recursive");
+ boolean recursive = cli.hasOption(CommonCLIOptions.RECURSIVE_OPTION);
echoIfVerbose(
"Getting listing for ZooKeeper node "
+ znode
diff --git a/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java b/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java
index 606586d1b4f..f2dc3703835 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java
@@ -20,9 +20,9 @@ import static org.apache.solr.packagemanager.PackageUtils.format;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.common.cloud.SolrZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,6 +31,13 @@ import org.slf4j.LoggerFactory;
public class ZkMkrootTool extends ToolBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Option FAIL_ON_EXISTS_OPTION =
+ Option.builder()
+ .longOpt("fail-on-exists")
+ .hasArg()
+ .desc("Raise an error if the root exists. Defaults to false.")
+ .build();
+
public ZkMkrootTool() {
this(CLIO.getOutStream());
}
@@ -40,17 +47,11 @@ public class ZkMkrootTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("fail-on-exists")
- .hasArg()
- .required(false)
- .desc("Raise an error if the root exists. Defaults to false.")
- .build(),
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(FAIL_ON_EXISTS_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -75,10 +76,9 @@ public class ZkMkrootTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
String znode = cli.getArgs()[0];
- boolean failOnExists = cli.hasOption("fail-on-exists");
+ boolean failOnExists = cli.hasOption(FAIL_ON_EXISTS_OPTION);
try (SolrZkClient zkClient = SolrCLI.getSolrZkClient(cli, zkHost)) {
echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...");
diff --git a/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java b/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java
index f49f1484c4b..41ca7d78822 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java
@@ -20,10 +20,9 @@ import static org.apache.solr.packagemanager.PackageUtils.format;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
-import java.util.List;
import java.util.Locale;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.cloud.SolrZkClient;
import org.slf4j.Logger;
@@ -42,8 +41,10 @@ public class ZkMvTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(SolrCLI.OPTION_SOLRURL, SolrCLI.OPTION_ZKHOST, SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -73,7 +74,6 @@ public class ZkMvTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
try (SolrZkClient zkClient = SolrCLI.getSolrZkClient(cli, zkHost)) {
diff --git a/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java b/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java
index 4f4e1bf62e6..cdb2e600334 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java
@@ -18,10 +18,9 @@ package org.apache.solr.cli;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
-import java.util.List;
import java.util.Locale;
import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.cloud.SolrZkClient;
import org.slf4j.Logger;
@@ -40,12 +39,11 @@ public class ZkRmTool extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- SolrCLI.OPTION_RECURSIVE,
- SolrCLI.OPTION_SOLRURL,
- SolrCLI.OPTION_ZKHOST,
- SolrCLI.OPTION_CREDENTIALS);
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(CommonCLIOptions.RECURSIVE_OPTION)
+ .addOption(CommonCLIOptions.CREDENTIALS_OPTION)
+ .addOptionGroup(getConnectionOptions());
}
@Override
@@ -60,11 +58,10 @@ public class ZkRmTool extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
String target = cli.getArgs()[0];
- boolean recursive = cli.hasOption("recursive");
+ boolean recursive = cli.hasOption(CommonCLIOptions.RECURSIVE_OPTION);
String znode = target;
if (target.toLowerCase(Locale.ROOT).startsWith("zk:")) {
diff --git a/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java b/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java
index 14b541d3b33..525030dab11 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java
@@ -19,13 +19,25 @@ package org.apache.solr.cli;
import static org.apache.solr.cli.SolrCLI.print;
import java.io.PrintStream;
-import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
/** Supports zk help information in the bin/solr script. */
public class ZkToolHelp extends ToolBase {
+ private static final Option PRINT_ZK_SUBCOMMAND_OPTION =
+ Option.builder()
+ .longOpt("print-zk-subcommand-usage")
+ .desc("Reminds user to prepend zk to invoke the command.")
+ .build();
+
+ private static final Option PRINT_LONG_ZK_USAGE_OPTION =
+ Option.builder()
+ .longOpt("print-long-zk-usage")
+ .desc("Invokes the detailed help for zk commands.")
+ .build();
+
public ZkToolHelp() {
this(CLIO.getOutStream());
}
@@ -35,18 +47,10 @@ public class ZkToolHelp extends ToolBase {
}
@Override
- public List<Option> getOptions() {
- return List.of(
- Option.builder()
- .longOpt("print-zk-subcommand-usage")
- .desc("Reminds user to prepend zk to invoke the command.")
- .required(false)
- .build(),
- Option.builder()
- .longOpt("print-long-zk-usage")
- .required(false)
- .desc("Invokes the detailed help for zk commands.")
- .build());
+ public Options getOptions() {
+ return super.getOptions()
+ .addOption(PRINT_ZK_SUBCOMMAND_OPTION)
+ .addOption(PRINT_LONG_ZK_USAGE_OPTION);
}
@Override
@@ -56,16 +60,14 @@ public class ZkToolHelp extends ToolBase {
@Override
public void runImpl(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- if (cli.hasOption("print-zk-subcommand-usage")) {
+ if (cli.hasOption(PRINT_ZK_SUBCOMMAND_OPTION)) {
String scriptCommand = cli.getArgs()[0];
print(
"You must invoke this subcommand using the zk command. bin/solr zk "
+ scriptCommand
+ ".");
}
- if (cli.hasOption("print-long-zk-usage")) {
+ if (cli.hasOption(PRINT_LONG_ZK_USAGE_OPTION)) {
print("usage:");
print(new ZkLsTool().getUsage());
print(new ZkCpTool().getUsage());
diff --git a/solr/core/src/test/org/apache/solr/cli/SolrCLITest.java b/solr/core/src/test/org/apache/solr/cli/SolrCLITest.java
index db9138e3311..4b5290a1ff7 100644
--- a/solr/core/src/test/org/apache/solr/cli/SolrCLITest.java
+++ b/solr/core/src/test/org/apache/solr/cli/SolrCLITest.java
@@ -45,7 +45,4 @@ public class SolrCLITest extends SolrTestCase {
assertEquals(
"106751991167 days, 7 hours, 12 minutes, 56 seconds", SolrCLI.uptime(Long.MAX_VALUE));
}
-
- @Test
- public void testGetCredentials() {}
}
diff --git a/solr/packaging/test/test_create.bats b/solr/packaging/test/test_create.bats
index a7a4c6b15d8..e9199358253 100644
--- a/solr/packaging/test/test_create.bats
+++ b/solr/packaging/test/test_create.bats
@@ -39,3 +39,8 @@ teardown() {
run solr create -c COLL_NAME
assert_output --partial "Created collection 'COLL_NAME'"
}
+
+@test "multiple connection options are prevented" {
+ run solr create -c COLL_NAME2 --solr-url http://localhost:${SOLR_PORT} -z localhost:${ZK_PORT}
+ assert_output --partial "The option 'z' was specified but an option from this group has already been selected: 's'"
+}
diff --git a/solr/packaging/test/test_status.bats b/solr/packaging/test/test_status.bats
index d1f8a53bcb4..5399a0b9fd6 100644
--- a/solr/packaging/test/test_status.bats
+++ b/solr/packaging/test/test_status.bats
@@ -53,11 +53,14 @@ teardown() {
solr stop
}
+@test "multiple connection options are prevented" {
+ run solr status --port ${SOLR_PORT} --solr-url http://localhost:${SOLR_PORT}
+ assert_output --partial "The option 's' was specified but an option from this group has already been selected: 'p'"
+}
+
@test "status with invalid --solr-url from user" {
- solr start
run solr status --solr-url http://invalidhost:${SOLR_PORT}
assert_output --partial "Solr at http://invalidhost:${SOLR_PORT} not online"
- solr stop
}
@test "status with --short format" {
diff --git a/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/SolrExporter.java b/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/SolrExporter.java
index ef24cda66a2..ebcff4e87a6 100644
--- a/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/SolrExporter.java
+++ b/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/SolrExporter.java
@@ -301,7 +301,7 @@ public class SolrExporter {
}
String configFile = commandLine.getOptionValue(configOption, DEFAULT_CONFIG);
- int numberOfThreads = commandLine.getParsedOptionValue("num-threads", DEFAULT_NUM_THREADS);
+ int numberOfThreads = commandLine.getParsedOptionValue(numThreadsOption, DEFAULT_NUM_THREADS);
int scrapeInterval =
commandLine.getParsedOptionValue(scrapeIntervalOption, DEFAULT_SCRAPE_INTERVAL);