Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

SOLR-15831: Refactor bin/solr and bin/solr.cmd to delegate args parsing and usage help to SolrCLI (#2580)

Eric Pugh661b1dac2284
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 7d28a9900e5..4196867eeef 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -234,6 +234,8 @@ Other Changes
* SOLR-17347: EnvUtils: Removed "env" methods, as they were problematic. Code should almost never
refer to env vars. (David Smiley)
+* SOLR-15831: Refactor bin/solr and bin/solr.cmd commands integration with AuthTool, DeleteTool, and PackageTool to delegate arg parsing to Java code. Removed limitation of PackageTool only being executed on an active Solr node. (Eric Pugh)
+
================== 9.6.1 ==================
Bug Fixes
---------------------
diff --git a/solr/bin/solr b/solr/bin/solr
index c9994af05cb..7e1629724f2 100755
--- a/solr/bin/solr
+++ b/solr/bin/solr
@@ -526,56 +526,6 @@ function print_usage() {
echo " <path>: The Zookeeper path to create. Leading slash is assumed if not present."
echo " Intermediate nodes are created as needed if not present."
echo ""
- elif [ "$CMD" == "auth" ]; then
- echo ""
- echo "Usage: solr auth enable [--type basicAuth] --credentials user:pass [--block-unknown <true|false>] [--update-include-file-only <true|false>] [-v]"
- echo " solr auth enable [--type basicAuth] --prompt <true|false> [--block-unknown <true|false>] [--update-include-file-only <true|false>] [-v]"
- echo " solr auth enable --type kerberos --config \"<kerberos configs>\" [--update-include-file-only <true|false>] [-v]"
- echo " solr auth disable [--update-include-file-only <true|false>] [-v]"
- echo ""
- echo " Updates or enables/disables authentication. Must be run on the machine hosting Solr."
- echo ""
- echo " --type or -t <type> The authentication mechanism (basicAuth or kerberos) to enable. Defaults to 'basicAuth'."
- echo ""
- echo " --credentials <user:pass> The username and password of the initial user. Applicable for basicAuth only."
- echo " Note: only one of --prompt or --credentials must be provided"
- echo ""
- echo " --config \"<configs>\" Configuration parameters (Solr startup parameters). Required and applicable only for Kerberos"
- echo ""
- echo " --solr-include-file <includeFilePath> Specify the full path to the include file in the environment."
- echo " If not specified this script looks for an include file named solr.in.sh to set environment variables. "
- echo " Specifically,the following locations are searched in this order:"
- echo " <script location>/."
- echo " $HOME/.solr.in.sh"
- echo " /usr/share/solr"
- echo " /usr/local/share/solr"
- echo " /etc/default"
- echo " /var/solr"
- echo " /opt/solr"
- echo ""
- echo " --prompt <true|false> Prompts the user to provide the credentials. Applicable for basicAuth only."
- echo " Note: only one of --prompt or --credentials must be provided"
- echo ""
- echo " --block-unknown <true|false> When true, this blocks out access to unauthenticated users. When not provided,"
- echo " this defaults to false (i.e. unauthenticated users can access all endpoints, except the"
- echo " operations like collection-edit, security-edit, core-admin-edit etc.). Check the reference"
- echo " guide for Basic Authentication for more details. Applicable for basicAuth only."
- echo ""
- echo " --update-include-file-only <true|false> Only update the solr.in.sh or solr.in.cmd file, and skip actual enabling/disabling"
- echo " authentication (i.e. don't update security.json)"
- echo ""
- echo " -z or --zk-host <zkHost> Zookeeper connection string. Unnecessary if ZK_HOST is defined in solr.in.sh."
- echo ""
- echo " -d or --dir <dir> Specify the Solr server directory"
- echo ""
- echo " -s or --solr-home <dir> Specify the Solr home directory. This is where any credentials or authentication"
- echo " configuration files (e.g. basicAuth.conf) would be placed."
- echo ""
- echo " -v/--verbose Enable more verbose output for this script."
- echo ""
- elif [ "$CMD" == "package" ]; then
- echo ""
- run_tool package "help"
fi
} # end print_usage
@@ -701,56 +651,6 @@ function get_status() {
} # end get_status
-function run_package() {
- runningSolrUrl=""
-
- numSolrs=$(find "$SOLR_PID_DIR" -name "solr-*.pid" -type f | wc -l | tr -d ' ')
- if [ "$numSolrs" != "0" ]; then
- #echo -e "\nFound $numSolrs Solr nodes: "
- while read PIDF
- do
- ID=$(cat "$PIDF")
- port=$(jetty_port "$ID")
- if [ "$port" != "" ]; then
- #echo -e "\nSolr process $ID running on port $port"
- runningSolrUrl="$SOLR_URL_SCHEME://$SOLR_TOOL_HOST:$port/solr"
- break
- CODE=$?
- echo ""
- else
- echo -e "\nSolr process $ID from $PIDF not found."
- CODE=1
- fi
- done < <(find "$SOLR_PID_DIR" -name "solr-*.pid" -type f)
- else
- # no pid files but check using ps just to be sure
- numSolrs=$(ps auxww | grep start\.jar | grep solr\.solr\.home | grep -v grep | wc -l | sed -e 's/^[ \t]*//')
- if [ "$numSolrs" != "0" ]; then
- echo -e "\nFound $numSolrs Solr nodes: "
- PROCESSES=$(ps auxww | grep start\.jar | grep solr\.solr\.home | grep -v grep | awk '{print $2}' | sort -r)
- for ID in $PROCESSES
- do
- port=$(jetty_port "$ID")
- if [ "$port" != "" ]; then
- echo ""
- echo "Solr process $ID running on port $port"
- runningSolrUrl="$SOLR_URL_SCHEME://$SOLR_TOOL_HOST:$port/solr"
- break
- CODE=$?
- echo ""
- fi
- done
- else
- echo -e "\nNo Solr nodes are running.\n"
- exit 1
- CODE=3
- fi
- fi
-
- run_tool package --solr-url "$runningSolrUrl" "$@"
- #exit $?
-}
-
# tries to gracefully stop Solr using the Jetty
# stop command and if that fails, then uses kill -9
# (will attempt to thread dump before killing)
@@ -877,6 +777,46 @@ if [[ "$SCRIPT_CMD" == "delete" ]]; then
exit $?
fi
+# manage packages
+if [[ "$SCRIPT_CMD" == "package" ]]; then
+ run_tool $SCRIPT_CMD $@
+ exit $?
+fi
+
+# configure authentication
+if [[ "$SCRIPT_CMD" == "auth" ]]; then
+ : "${SOLR_SERVER_DIR:=$DEFAULT_SERVER_DIR}"
+ if [ ! -e "$SOLR_SERVER_DIR" ]; then
+ echo -e "\nSolr server directory $SOLR_SERVER_DIR not found!\n"
+ exit 1
+ fi
+
+ if [ -z "${SOLR_HOME:-}" ]; then
+ SOLR_HOME="$SOLR_SERVER_DIR/solr"
+ elif [[ $SOLR_HOME != /* ]]; then
+ if [[ -d "$(pwd -P)/$SOLR_HOME" ]]; then
+ SOLR_HOME="$(pwd -P)/$SOLR_HOME"
+ elif [[ -d "$SOLR_SERVER_DIR/$SOLR_HOME" ]]; then
+ SOLR_HOME="$SOLR_SERVER_DIR/$SOLR_HOME"
+ SOLR_PID_DIR="$SOLR_HOME"
+ fi
+ fi
+
+ if [ -z "${AUTH_PORT:-}" ]; then
+ for ID in $(ps auxww | grep java | grep start\.jar | awk '{print $2}' | sort -r)
+ do
+ port=$(jetty_port "$ID")
+ if [ "$port" != "" ]; then
+ AUTH_PORT=$port
+ break
+ fi
+ done
+ fi
+
+ run_tool auth $@ --solr-url "$SOLR_URL_SCHEME://$SOLR_TOOL_HOST:${AUTH_PORT:-8983}" --auth-conf-dir "$SOLR_HOME" "--solr-include-file" "$SOLR_INCLUDE"
+ exit $?
+fi
+
# Prevent any zk subcommands from going through with out invoking zk command
if [[ "$SCRIPT_CMD" == "upconfig" || $SCRIPT_CMD == "downconfig" || $SCRIPT_CMD == "cp" || $SCRIPT_CMD == "rm" || $SCRIPT_CMD == "mv" || $SCRIPT_CMD == "ls" || $SCRIPT_CMD == "mkroot" || $SCRIPT_CMD == "linkconfig" || $SCRIPT_CMD == "updateacls" ]]; then
print_short_zk_usage "You must invoke this subcommand using the zk command. bin/solr zk $SCRIPT_CMD."
@@ -1062,165 +1002,6 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
exit $?
fi
-if [[ "$SCRIPT_CMD" == "package" ]]; then
- if [ $# -gt 0 ]; then
- while true; do
- case "$1" in
- --help|-h|-help)
- print_usage "$SCRIPT_CMD"
- exit 0
- ;;
- --)
- shift
- break
- ;;
- *)
- break # out-of-args, stop looping
-
- ;;
- esac
- done
- fi
- run_package "$@"
- exit $?
-fi
-
-if [[ "$SCRIPT_CMD" == "auth" ]]; then
-
- VERBOSE=""
-
- declare -a AUTH_PARAMS
- if [ $# -gt 0 ]; then
- while true; do
- case "${1:-}" in
- enable|disable)
- AUTH_OP=$1
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "$AUTH_OP")
- shift
- ;;
- -z|--zk-host|-zkHost|--zkHost)
- ZK_HOST="$2"
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "-z" "$ZK_HOST")
- shift 2
- ;;
- -t|--type|-type)
- AUTH_TYPE="$2"
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--type" "$AUTH_TYPE")
- shift 2
- ;;
- --credentials|-credentials)
- AUTH_CREDENTIALS="$2"
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--credentials" "$AUTH_CREDENTIALS")
- shift 2
- ;;
- --config|-config)
- AUTH_CONFIG="$(echo "$2"| base64)"
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--config" "$AUTH_CONFIG")
- shift 2
- ;;
- --solr-include-file|-solrIncludeFile)
- SOLR_INCLUDE="$2"
- shift 2
- ;;
- --prompt|-prompt)
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--prompt" "$2")
- shift 2
- ;;
- --block-unknown|-blockUnknown)
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--block-unknown" "$2")
- shift 2
- ;;
- --update-include-file-only|-updateIncludeFileOnly|--updateIncludeFileOnly)
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--update-include-file-only" "$2")
- shift 2
- ;;
- -v|--verbose|-verbose)
- VERBOSE="--verbose"
- shift
- ;;
- -d|--dir|-dir)
- if [[ -z "$2" || "${2:0:1}" == "-" ]]; then
- print_usage "$SCRIPT_CMD" "Server directory is required when using the $1 option!"
- exit 1
- fi
-
- if [[ "$2" == "." || "$2" == "./" || "$2" == ".." || "$2" == "../" ]]; then
- SOLR_SERVER_DIR="$(pwd -P)/$2"
- else
- # see if the arg value is relative to the tip vs full path
- if [[ "$2" != /* ]] && [[ -d "$SOLR_TIP/$2" ]]; then
- SOLR_SERVER_DIR="$SOLR_TIP/$2"
- else
- SOLR_SERVER_DIR="$2"
- fi
- fi
- # resolve it to an absolute path
- SOLR_SERVER_DIR="$(cd "$SOLR_SERVER_DIR" || (echo "SOLR_SERVER_DIR not found" && exit 1); pwd)"
- shift 2
- ;;
- -s|--solr-home|-solr.home)
- if [[ -z "$2" || "${2:0:1}" == "-" ]]; then
- print_usage "$SCRIPT_CMD" "Solr home directory is required when using the $1 option!"
- exit 1
- fi
-
- SOLR_HOME="$2"
- shift 2
- ;;
- --help|-h|-help)
- print_usage "$SCRIPT_CMD"
- exit 0
- ;;
- --)
- shift
- break
- ;;
- *)
- shift
- break
- ;;
- esac
- done
- fi
-
- : "${SOLR_SERVER_DIR:=$DEFAULT_SERVER_DIR}"
- if [ ! -e "$SOLR_SERVER_DIR" ]; then
- echo -e "\nSolr server directory $SOLR_SERVER_DIR not found!\n"
- exit 1
- fi
-
- if [ -z "${SOLR_HOME:-}" ]; then
- SOLR_HOME="$SOLR_SERVER_DIR/solr"
- elif [[ $SOLR_HOME != /* ]]; then
- if [[ -d "$(pwd -P)/$SOLR_HOME" ]]; then
- SOLR_HOME="$(pwd -P)/$SOLR_HOME"
- elif [[ -d "$SOLR_SERVER_DIR/$SOLR_HOME" ]]; then
- SOLR_HOME="$SOLR_SERVER_DIR/$SOLR_HOME"
- SOLR_PID_DIR="$SOLR_HOME"
- fi
- fi
-
- if [ -z "$AUTH_OP" ]; then
- print_usage "$SCRIPT_CMD"
- exit 0
- fi
-
- AUTH_PARAMS=("${AUTH_PARAMS[@]}" "--solr-include-file" "$SOLR_INCLUDE")
-
- if [ -z "${AUTH_PORT:-}" ]; then
- for ID in $(ps auxww | grep java | grep start\.jar | awk '{print $2}' | sort -r)
- do
- port=$(jetty_port "$ID")
- if [ "$port" != "" ]; then
- AUTH_PORT=$port
- break
- fi
- done
- fi
- run_tool auth "${AUTH_PARAMS[@]}" --solr-url "$SOLR_URL_SCHEME://$SOLR_TOOL_HOST:${AUTH_PORT:-8983}" --auth-conf-dir "$SOLR_HOME" $VERBOSE
- exit $?
-fi
-
if [[ "$SCRIPT_CMD" == "api" ]]; then
run_tool api "$@"
exit $?
diff --git a/solr/bin/solr.cmd b/solr/bin/solr.cmd
index 041d7701aa5..0eb25adce14 100755
--- a/solr/bin/solr.cmd
+++ b/solr/bin/solr.cmd
@@ -259,6 +259,7 @@ IF "%1"=="-version" goto run_solrcli
IF "%1"=="assert" goto run_solrcli
IF "%1"=="export" goto run_solrcli
IF "%1"=="package" goto run_solrcli
+IF "%1"=="auth" goto run_solrcli
IF "%1"=="api" goto run_solrcli
IF "%1"=="post" goto run_solrcli
@@ -302,7 +303,8 @@ IF "%SCRIPT_CMD%"=="create" goto run_solrcli
IF "%SCRIPT_CMD%"=="delete" goto run_solrcli
IF "%SCRIPT_CMD%"=="cluster" goto run_solrcli
IF "%SCRIPT_CMD%"=="zk" goto zk_usage
-IF "%SCRIPT_CMD%"=="auth" goto auth_usage
+IF "%SCRIPT_CMD%"=="auth" goto run_solrcli
+IF "%SCRIPT_CMD%"=="package" goto run_solrcli
IF "%SCRIPT_CMD%"=="status" goto run_solrcli
IF "%SCRIPT_CMD%"=="postlogs" goto run_solrcli
goto done
@@ -491,40 +493,6 @@ IF "%ZK_FULL%"=="true" (
)
goto done
-:auth_usage
-echo Usage: solr auth enable [--type basicAuth] --credentials user:pass [--block-unknown ^<true^|false^>] [--update-include-file-only ^<true^|false^>] [-v]
-echo solr auth enable [--type basicAuth] --prompt ^<true^|false^> [--block-unknown ^<true^|false^>] [--update-include-file-only ^<true^|false^>] [-v]
-echo solr auth disable [--update-include-file-only ^<true^|false^>] [-v]
-echo.
-echo Updates or enables/disables authentication. Must be run on the machine hosting Solr.
-echo.
-echo --type ^<type^> The authentication mechanism to enable. Defaults to 'basicAuth'.
-echo.
-echo --credentials ^<user:pass^> The username and password of the initial user
-echo Note: only one of --prompt or --credentials must be provided
-echo.
-echo --prompt ^<true^|false^> Prompts the user to provide the credentials
-echo Note: only one of --prompt or --credentials must be provided
-echo.
-echo --block-unknown ^<true^|false^> When true, this blocks out access to unauthenticated users. When not provided,
-echo this defaults to false (i.e. unauthenticated users can access all endpoints, except the
-echo operations like collection-edit, security-edit, core-admin-edit etc.^). Check the reference
-echo guide for Basic Authentication for more details.
-echo.
-echo --update-include-file-only ^<true^|false^> Only update the solr.in.sh or solr.in.cmd file, and skip actual enabling/disabling"
-echo authentication (i.e. don't update security.json^)"
-echo.
-echo -z zkHost Zookeeper connection string. Unnecessary if ZK_HOST is defined in solr.in.cmd.
-echo.
-echo -d ^<dir^> Specify the Solr server directory"
-echo.
-echo -s ^<dir^> Specify the Solr home directory. This is where any credentials or authentication"
-echo configuration files (e.g. basicAuth.conf^) would be placed."
-echo.
-echo -v Enable more verbose output
-echo.
-goto done
-
REM Really basic command-line arg parsing
:parse_args
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 47d4861370a..6fbafe21d43 100644
--- a/solr/core/src/java/org/apache/solr/cli/AuthTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/AuthTool.java
@@ -35,6 +35,7 @@ import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.DeprecatedAttributes;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.lucene.util.Constants;
@@ -59,6 +60,26 @@ public class AuthTool extends ToolBase {
return "auth";
}
+ @Override
+ public String getUsage() {
+ // Jan, the return "" causes
+ // Exception in thread "main" java.lang.IllegalArgumentException: cmdLineSyntax not provided
+ // at org.apache.commons.cli.HelpFormatter.printHelp(HelpFormatter.java:584)
+ // however return " " seems okay.
+ // return " ";
+ return "\n bin/solr auth enable [--type basicAuth] --credentials user:pass [--block-unknown <true|false>] [--update-include-file-only <true|false>] [-v]\n"
+ + " bin/solr auth enable [--type basicAuth] --prompt <true|false> [--block-unknown <true|false>] [--update-include-file-only <true|false>] [-v]\n"
+ + " bin/solr auth enable --type kerberos --config \\\"<kerberos configs>\\\" [--update-include-file-only <true|false>] [-v]\n"
+ + " bin/solr auth disable [--update-include-file-only <true|false>] [-v]\n";
+ }
+
+ @Override
+ public String getHeader() {
+ return "\nUpdates or enables/disables authentication. Must be run on the machine hosting Solr.\n"
+ + "\n"
+ + "List of options:";
+ }
+
List<String> authenticationVariables =
Arrays.asList(
"SOLR_AUTHENTICATION_CLIENT_BUILDER", "SOLR_AUTH_TYPE", "SOLR_AUTHENTICATION_OPTS");
@@ -89,10 +110,40 @@ public class AuthTool extends ToolBase {
.desc(
"Blocks all access for unknown users (requires authentication for all endpoints).")
.hasArg()
+ .argName("true|false")
+ .build(),
+ Option.builder("blockUnknown")
+ .longOpt("blockUnknown")
+ .deprecated(
+ DeprecatedAttributes.builder()
+ .setForRemoval(true)
+ .setSince("9.8")
+ .setDescription("Use --block-unknown instead")
+ .get())
+ .hasArg()
+ .argName("true|false")
+ .required(false)
+ .desc(
+ "Blocks all access for unknown users (requires authentication for all endpoints).")
.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("solrIncludeFile")
+ .longOpt("solrIncludeFile")
+ .deprecated(
+ DeprecatedAttributes.builder()
+ .setForRemoval(true)
+ .setSince("9.7")
+ .setDescription("Use --solr-include-file instead")
+ .get())
+ .hasArg()
+ .argName("FILE")
+ .required(false)
.desc(
"The Solr include file which contains overridable environment variables for configuring Solr configurations.")
.build(),
@@ -103,13 +154,43 @@ public class AuthTool extends ToolBase {
+ " authentication (i.e. don't update security.json).")
.hasArg()
.build(),
+ Option.builder()
+ .longOpt("updateIncludeFileOnly")
+ .deprecated(
+ DeprecatedAttributes.builder()
+ .setForRemoval(true)
+ .setSince("9.8")
+ .setDescription("Use --update-include-file-only instead")
+ .get())
+ .hasArg()
+ .argName("true|false")
+ .required(false)
+ .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).")
+ .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(),
+ Option.builder("solrIncludeFile")
+ .longOpt("solrIncludeFile")
+ .deprecated(
+ DeprecatedAttributes.builder()
+ .setForRemoval(true)
+ .setSince("9.7")
+ .setDescription("Use --solr-include-file instead")
+ .get())
+ .hasArg()
+ .argName("FILE")
+ .required(false)
+ .desc(
+ "The Solr include file which contains overridable environment variables for configuring Solr configurations.")
+ .build(),
SolrCLI.OPTION_SOLRURL,
SolrCLI.OPTION_SOLRURL_DEPRECATED,
SolrCLI.OPTION_ZKHOST,
@@ -127,25 +208,10 @@ public class AuthTool extends ToolBase {
}
}
- @Override
- public int runTool(CommandLine cli) throws Exception {
- SolrCLI.raiseLogLevelUnlessVerbose(cli);
-
- ensureArgumentIsValidBooleanIfPresent(cli, "block-unknown");
- ensureArgumentIsValidBooleanIfPresent(cli, "update-include-file-only");
+ // @Override
+ // public int runTool(CommandLine cli) throws Exception {
- String type = cli.getOptionValue("type", "basicAuth");
- switch (type) {
- case "basicAuth":
- return handleBasicAuth(cli);
- case "kerberos":
- return handleKerberos(cli);
- default:
- CLIO.out("Only type=basicAuth or kerberos supported at the moment.");
- SolrCLI.exit(1);
- }
- return 1;
- }
+ // }
private int handleKerberos(CommandLine cli) throws Exception {
String cmd = cli.getArgs()[0];
@@ -587,5 +653,22 @@ public class AuthTool extends ToolBase {
}
@Override
- public void runImpl(CommandLine cli) throws Exception {}
+ public void runImpl(CommandLine cli) throws Exception {
+ SolrCLI.raiseLogLevelUnlessVerbose(cli);
+
+ ensureArgumentIsValidBooleanIfPresent(cli, "block-unknown");
+ ensureArgumentIsValidBooleanIfPresent(cli, "update-include-file-only");
+
+ String type = cli.getOptionValue("type", "basicAuth");
+ switch (type) {
+ case "basicAuth":
+ handleBasicAuth(cli);
+ break;
+ case "kerberos":
+ handleKerberos(cli);
+ break;
+ default:
+ throw new IllegalStateException("Only type=basicAuth or kerberos supported at the moment.");
+ }
+ }
}
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 35b1d8e277f..1733b4bb197 100644
--- a/solr/core/src/java/org/apache/solr/cli/DeleteTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/DeleteTool.java
@@ -59,6 +59,16 @@ public class DeleteTool extends ToolBase {
return "delete";
}
+ @Override
+ public String getHeader() {
+ return "\nDeletes a core or collection depending on whether Solr is running in standalone (core) or SolrCloud"
+ + " mode (collection). If you're deleting a collection in SolrCloud mode, the default behavior is to also"
+ + " delete the configuration directory from Zookeeper so long as it is not being used by another collection.\n"
+ + " You can override this behavior by passing -deleteConfig false when running this command.\n"
+ + "\n"
+ + "List of options:";
+ }
+
@Override
public List<Option> getOptions() {
return List.of(
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 1765d3f464f..a8fdd5afd18 100644
--- a/solr/core/src/java/org/apache/solr/cli/PackageTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/PackageTool.java
@@ -16,8 +16,10 @@
*/
package org.apache.solr.cli;
-import static org.apache.solr.packagemanager.PackageUtils.print;
-import static org.apache.solr.packagemanager.PackageUtils.printGreen;
+import static org.apache.solr.cli.SolrCLI.printGreen;
+import static org.apache.solr.cli.SolrCLI.printRed;
+import static org.apache.solr.packagemanager.PackageUtils.format;
+import static org.apache.solr.packagemanager.PackageUtils.formatGreen;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
@@ -70,12 +72,6 @@ public class PackageTool extends ToolBase {
+ "don't print stack traces, hence special treatment is needed here.")
public void runImpl(CommandLine cli) throws Exception {
try {
- String cmd = cli.getArgList().size() == 0 ? "help" : cli.getArgs()[0];
-
- if (cmd.equalsIgnoreCase("help")) {
- printHelp();
- return;
- }
String solrUrl = SolrCLI.normalizeSolrUrl(cli);
String zkHost = SolrCLI.getZkHost(cli);
if (zkHost == null) {
@@ -84,6 +80,8 @@ public class PackageTool extends ToolBase {
log.info("ZK: {}", zkHost);
+ String cmd = cli.getArgs()[0];
+
try (SolrClient solrClient = SolrCLI.getSolrClient(cli, true)) {
packageManager = new PackageManager(solrClient, solrUrl, zkHost);
try {
@@ -94,7 +92,7 @@ public class PackageTool extends ToolBase {
String repoName = cli.getArgs()[1];
String repoUrl = cli.getArgs()[2];
repositoryManager.addRepository(repoName, repoUrl);
- PackageUtils.printGreen("Added repository: " + repoName);
+ printGreen("Added repository: " + repoName);
break;
case "add-key":
String keyFilename = cli.getArgs()[1];
@@ -102,17 +100,17 @@ public class PackageTool extends ToolBase {
repositoryManager.addKey(Files.readAllBytes(path), path.getFileName().toString());
break;
case "list-installed":
- PackageUtils.printGreen("Installed packages:\n-----");
+ printGreen("Installed packages:\n-----");
for (SolrPackageInstance pkg : packageManager.fetchInstalledPackageInstances()) {
- PackageUtils.printGreen(pkg);
+ printGreen(pkg);
}
break;
case "list-available":
- PackageUtils.printGreen("Available packages:\n-----");
+ printGreen("Available packages:\n-----");
for (SolrPackage pkg : repositoryManager.getPackages()) {
- PackageUtils.printGreen(pkg.name + " \t\t" + pkg.description);
+ printGreen(pkg.name + " \t\t" + pkg.description);
for (SolrPackageRelease version : pkg.versions) {
- PackageUtils.printGreen("\tVersion: " + version.version);
+ printGreen("\tVersion: " + version.version);
}
}
break;
@@ -121,9 +119,9 @@ public class PackageTool extends ToolBase {
String collection = cli.getOptionValue("collection");
Map<String, SolrPackageInstance> packages =
packageManager.getPackagesDeployed(collection);
- PackageUtils.printGreen("Packages deployed on " + collection + ":");
+ printGreen("Packages deployed on " + collection + ":");
for (String packageName : packages.keySet()) {
- PackageUtils.printGreen("\t" + packages.get(packageName));
+ printGreen("\t" + packages.get(packageName));
}
} else {
// nuance that we use a arg here instead of requiring a --package parameter with a
@@ -133,10 +131,9 @@ public class PackageTool extends ToolBase {
Map<String, String> deployedCollections =
packageManager.getDeployedCollections(packageName);
if (!deployedCollections.isEmpty()) {
- PackageUtils.printGreen(
- "Collections on which package " + packageName + " was deployed:");
+ printGreen("Collections on which package " + packageName + " was deployed:");
for (String collection : deployedCollections.keySet()) {
- PackageUtils.printGreen(
+ printGreen(
"\t"
+ collection
+ "("
@@ -146,8 +143,7 @@ public class PackageTool extends ToolBase {
+ ")");
}
} else {
- PackageUtils.printGreen(
- "Package " + packageName + " not deployed on any collection.");
+ printGreen("Package " + packageName + " not deployed on any collection.");
}
}
break;
@@ -158,9 +154,9 @@ public class PackageTool extends ToolBase {
String version = parsedVersion.second();
boolean success = repositoryManager.install(packageName, version);
if (success) {
- PackageUtils.printGreen(packageName + " installed.");
+ printGreen(packageName + " installed.");
} else {
- PackageUtils.printRed(packageName + " installation failed.");
+ printRed(packageName + " installation failed.");
}
break;
}
@@ -186,7 +182,7 @@ public class PackageTool extends ToolBase {
isUpdate,
noprompt);
} else {
- PackageUtils.printRed(
+ printRed(
"Either specify --cluster to deploy cluster level plugins or --collections <list-of-collections> to deploy collection level plugins");
}
break;
@@ -209,7 +205,7 @@ public class PackageTool extends ToolBase {
: new String[] {};
packageManager.undeploy(packageName, collections, cli.hasOption("cluster"));
} else {
- PackageUtils.printRed(
+ printRed(
"Either specify -cluster to undeploy cluster level plugins or -collections <list-of-collections> to undeploy collection level plugins");
}
break;
@@ -245,47 +241,60 @@ public class PackageTool extends ToolBase {
}
}
- private void printHelp() {
- print("Package Manager\n---------------");
- printGreen("./solr package add-repo <repository-name> <repository-url>");
- print("Add a repository to Solr.");
- print("");
- printGreen("./solr package add-key <file-containing-trusted-key>");
- print("Add a trusted key to Solr.");
- print("");
- printGreen("./solr package install <package-name>[:<version>] ");
- print(
+ @Override
+ public String getHeader() {
+ StringBuilder sb = new StringBuilder();
+ format(sb, "\n");
+ format(sb, "Package Manager\n---------------");
+ formatGreen(sb, "bin/solr package add-repo <repository-name> <repository-url>");
+ format(sb, "Add a repository to Solr.");
+ format(sb, "");
+ formatGreen(sb, "bin/solr package add-key <file-containing-trusted-key>");
+ format(sb, "Add a trusted key to Solr.");
+ format(sb, "");
+ formatGreen(sb, "bin/solr package install <package-name>[:<version>] ");
+ format(
+ sb,
"Install a package into Solr. This copies over the artifacts from the repository into Solr's internal package store and sets up classloader for this package to be used.");
- print("");
- printGreen(
- "./solr package deploy <package-name>[:<version>] [-y] [--update] -collections <comma-separated-collections> [-p <param1>=<val1> -p <param2>=<val2> ...] ");
- print(
+ format(sb, "");
+ formatGreen(
+ sb,
+ "bin/solr package deploy <package-name>[:<version>] [-y] [--update] -collections <comma-separated-collections> [-p <param1>=<val1> -p <param2>=<val2> ...] ");
+ format(
+ sb,
"Bootstraps a previously installed package into the specified collections. It the package accepts parameters for its setup commands, they can be specified (as per package documentation).");
- print("");
- printGreen("./solr package list-installed");
- print("Print a list of packages installed in Solr.");
- print("");
- printGreen("./solr package list-available");
- print("Print a list of packages available in the repositories.");
- print("");
- printGreen("./solr package list-deployed -c <collection>");
- print("Print a list of packages deployed on a given collection.");
- print("");
- printGreen("./solr package list-deployed <package-name>");
- print("Print a list of collections on which a given package has been deployed.");
- print("");
- printGreen("./solr package undeploy <package-name> -collections <comma-separated-collections>");
- print("Undeploy a package from specified collection(s)");
- print("");
- printGreen("./solr package uninstall <package-name>:<version>");
- print(
+ format(sb, "");
+ formatGreen(sb, "bin/solr package list-installed");
+ format(sb, "Print a list of packages installed in Solr.");
+ format(sb, "");
+ formatGreen(sb, "bin/solr package list-available");
+ format(sb, "Print a list of packages available in the repositories.");
+ format(sb, "");
+ formatGreen(sb, "bin/solr package list-deployed -c <collection>");
+ format(sb, "Print a list of packages deployed on a given collection.");
+ format(sb, "");
+ formatGreen(sb, "bin/solr package list-deployed <package-name>");
+ format(sb, "Print a list of collections on which a given package has been deployed.");
+ format(sb, "");
+ formatGreen(
+ sb, "bin/solr package undeploy <package-name> -collections <comma-separated-collections>");
+ format(sb, "Undeploy a package from specified collection(s)");
+ format(sb, "");
+ formatGreen(sb, "bin/solr package uninstall <package-name>:<version>");
+ format(
+ sb,
"Uninstall an unused package with specified version from Solr. Both package name and version are required.");
- print("\n");
- print(
+ format(sb, "\n");
+ format(
+ sb,
"Note: (a) Please add '--solr-url http://host:port' parameter if needed (usually on Windows).");
- print(
+ format(
+ sb,
" (b) Please make sure that all Solr nodes are started with '-Denable.packages=true' parameter.");
- print("\n");
+ format(sb, "\n");
+ format(sb, "\n");
+ format(sb, "List of options:");
+ return sb.toString();
}
/**
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 8463c1529e1..07582cf3a29 100755
--- a/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
+++ b/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
@@ -20,8 +20,6 @@ import static org.apache.solr.common.SolrException.ErrorCode.FORBIDDEN;
import static org.apache.solr.common.SolrException.ErrorCode.UNAUTHORIZED;
import static org.apache.solr.common.params.CommonParams.NAME;
import static org.apache.solr.common.params.CommonParams.SYSTEM_INFO_PATH;
-import static org.apache.solr.packagemanager.PackageUtils.print;
-import static org.apache.solr.packagemanager.PackageUtils.printGreen;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
@@ -77,6 +75,11 @@ import org.slf4j.LoggerFactory;
/** Command-line utility for working with Solr. */
public class SolrCLI implements CLIO {
+
+ public static String RED = "\u001B[31m";
+ public static String GREEN = "\u001B[32m";
+ public static String YELLOW = "\u001B[33m";
+
private static final long MAX_WAIT_FOR_CORE_LOAD_NANOS =
TimeUnit.NANOSECONDS.convert(1, TimeUnit.MINUTES);
@@ -756,4 +759,28 @@ public class SolrCLI implements CLIO {
Path configSetsPath = Paths.get("server/solr/configsets/");
return solrInstallDir.resolve(configSetsPath);
}
+
+ public static void print(Object message) {
+ print(null, message);
+ }
+
+ /** Console print using green color */
+ public static void printGreen(Object message) {
+ print(GREEN, message);
+ }
+
+ /** Console print using red color */
+ public static void printRed(Object message) {
+ print(RED, message);
+ }
+
+ public static void print(String color, Object message) {
+ String RESET = "\u001B[0m";
+
+ if (color != null) {
+ CLIO.out(color + String.valueOf(message) + RESET);
+ } else {
+ CLIO.out(String.valueOf(message));
+ }
+ }
}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java b/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java
index 8732f38356f..1b671c0e172 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java
@@ -17,6 +17,8 @@
package org.apache.solr.packagemanager;
+import static org.apache.solr.cli.SolrCLI.printGreen;
+import static org.apache.solr.cli.SolrCLI.printRed;
import static org.apache.solr.packagemanager.PackageUtils.getMapper;
import com.jayway.jsonpath.InvalidPathException;
@@ -101,7 +103,7 @@ public class PackageManager implements Closeable {
throws IOException, SolrServerException {
SolrPackageInstance packageInstance = getPackageInstance(packageName, version);
if (packageInstance == null) {
- PackageUtils.printRed(
+ printRed(
"Package "
+ packageName
+ ":"
@@ -114,7 +116,7 @@ public class PackageManager implements Closeable {
Map<String, String> collectionsDeployedOn = getDeployedCollections(packageName);
for (String collection : collectionsDeployedOn.keySet()) {
if (version.equals(collectionsDeployedOn.get(collection))) {
- PackageUtils.printRed(
+ printRed(
"Package "
+ packageName
+ " is currently deployed on collection: "
@@ -131,7 +133,7 @@ public class PackageManager implements Closeable {
SolrPackageInstance clusterPackageInstance = clusterPackages.get(clusterPackageName);
if (packageName.equals(clusterPackageName)
&& version.equals(clusterPackageInstance.version)) {
- PackageUtils.printRed(
+ printRed(
"Package "
+ packageName
+ "is currently deployed as a cluster-level plugin ("
@@ -143,7 +145,7 @@ public class PackageManager implements Closeable {
// Delete the package by calling the Package API and remove the Jar
- PackageUtils.printGreen("Executing Package API to remove this package...");
+ printGreen("Executing Package API to remove this package...");
PackagePayload.DelVersion del = new PackagePayload.DelVersion();
del.version = version;
del.pkg = packageName;
@@ -157,13 +159,12 @@ public class PackageManager implements Closeable {
try {
V2Response resp = req.process(solrClient);
- PackageUtils.printGreen("Response: " + resp.jsonStr());
+ printGreen("Response: " + resp.jsonStr());
} catch (SolrServerException | IOException e) {
throw new SolrException(ErrorCode.BAD_REQUEST, e);
}
- PackageUtils.printGreen(
- "Executing Package Store API to remove the " + packageName + " package...");
+ printGreen("Executing Package Store API to remove the " + packageName + " package...");
List<String> filesToDelete = new ArrayList<>(packageInstance.files);
filesToDelete.add(
@@ -171,11 +172,11 @@ public class PackageManager implements Closeable {
for (String filePath : filesToDelete) {
DistribFileStore.deleteZKFileEntry(zkClient, filePath);
String path = "/api/cluster/files" + filePath;
- PackageUtils.printGreen("Deleting " + path);
+ printGreen("Deleting " + path);
solrClient.request(new GenericSolrRequest(SolrRequest.METHOD.DELETE, path));
}
- PackageUtils.printGreen("Package uninstalled: " + packageName + ":" + version + ":-)");
+ printGreen("Package uninstalled: " + packageName + ":" + version + ":-)");
}
public List<SolrPackageInstance> fetchInstalledPackageInstances() throws SolrException {
@@ -364,7 +365,7 @@ public class PackageManager implements Closeable {
boolean verifySuccess =
verify(packageInstance, deployedCollections, shouldDeployClusterPlugins, overrides);
if (verifySuccess) {
- PackageUtils.printGreen(
+ printGreen(
"Deployed on "
+ deployedCollections
+ " and verified package: "
@@ -393,14 +394,13 @@ public class PackageManager implements Closeable {
getPackagesDeployed(collection).get(packageInstance.name);
if (packageInstance.equals(deployedPackage)) {
if (!pegToLatest) {
- PackageUtils.printRed(
- "Package " + packageInstance + " already deployed on " + collection);
+ printRed("Package " + packageInstance + " already deployed on " + collection);
previouslyDeployed.add(collection);
continue;
}
} else {
if (deployedPackage != null && !isUpdate) {
- PackageUtils.printRed(
+ printRed(
"Package "
+ deployedPackage
+ " already deployed on "
@@ -500,7 +500,7 @@ public class PackageManager implements Closeable {
packageInstance.parameterDefaults,
collectionParameterOverrides,
systemParams);
- PackageUtils.printGreen("Executing " + payload + " for path:" + path);
+ printGreen("Executing " + payload + " for path:" + path);
boolean shouldExecute = prompt(noprompt);
if (shouldExecute) {
SolrCLI.postJsonToSolr(solrClient, path, payload);
@@ -513,8 +513,7 @@ public class PackageManager implements Closeable {
ErrorCode.BAD_REQUEST, "Non-POST method not supported for setup commands");
}
} else {
- PackageUtils.printRed(
- "There is no setup command to execute for plugin: " + plugin.name);
+ printRed("There is no setup command to execute for plugin: " + plugin.name);
}
}
}
@@ -535,7 +534,7 @@ public class PackageManager implements Closeable {
}
if (!previouslyDeployed.isEmpty()) {
- PackageUtils.printRed(
+ printRed(
"Already Deployed on "
+ previouslyDeployed
+ ", package: "
@@ -563,7 +562,7 @@ public class PackageManager implements Closeable {
SolrPackageInstance deployedPackage =
getPackagesDeployedAsClusterLevelPlugins().get(packageInstance.name);
if (deployedPackage == null) {
- PackageUtils.printRed(
+ printRed(
"Cluster level plugin "
+ plugin.name
+ " from package "
@@ -573,13 +572,12 @@ public class PackageManager implements Closeable {
continue;
}
for (PluginMeta pluginMeta : (List<PluginMeta>) deployedPackage.getCustomData()) {
- PackageUtils.printGreen("Updating this plugin: " + pluginMeta);
+ printGreen("Updating this plugin: " + pluginMeta);
try {
// just update the version, let the other metadata same
pluginMeta.version = packageInstance.version;
String postBody = "{\"update\": " + Utils.toJSONString(pluginMeta) + "}";
- PackageUtils.printGreen(
- "Posting " + postBody + " to " + PackageUtils.CLUSTER_PLUGINS_PATH);
+ printGreen("Posting " + postBody + " to " + PackageUtils.CLUSTER_PLUGINS_PATH);
SolrCLI.postJsonToSolr(solrClient, PackageUtils.CLUSTER_PLUGINS_PATH, postBody);
} catch (Exception e) {
throw new SolrException(ErrorCode.SERVER_ERROR, e);
@@ -588,9 +586,9 @@ public class PackageManager implements Closeable {
numberOfClusterPluginsDeployed++;
}
if (numberOfClusterPluginsDeployed > 0) {
- PackageUtils.printGreen(numberOfClusterPluginsDeployed + " cluster level plugins updated.");
+ printGreen(numberOfClusterPluginsDeployed + " cluster level plugins updated.");
} else {
- PackageUtils.printRed("No cluster level plugin updated.");
+ printRed("No cluster level plugin updated.");
clusterPluginFailed = true;
}
} else {
@@ -613,7 +611,7 @@ public class PackageManager implements Closeable {
((Map<String, Object>) clusterprops.getOrDefault("plugin", Collections.emptyMap()))
.get(packageInstance.name + ":" + plugin.name);
if (pkg != null) {
- PackageUtils.printRed(
+ printRed(
"Cluster level plugin "
+ plugin.name
+ " from package "
@@ -650,7 +648,7 @@ public class PackageManager implements Closeable {
String path =
PackageUtils.resolve(
cmd.path, packageInstance.parameterDefaults, overridesMap, systemParams);
- PackageUtils.printGreen("Executing " + payload + " for path:" + path);
+ printGreen("Executing " + payload + " for path:" + path);
boolean shouldExecute = prompt(noprompt);
if (shouldExecute) {
SolrCLI.postJsonToSolr(solrClient, path, payload);
@@ -664,13 +662,13 @@ public class PackageManager implements Closeable {
ErrorCode.BAD_REQUEST, "Non-POST method not supported for setup commands");
}
} else {
- PackageUtils.printRed("There is no setup command to execute for plugin: " + plugin.name);
+ printRed("There is no setup command to execute for plugin: " + plugin.name);
}
}
if (numberOfClusterPluginsDeployed > 0) {
- PackageUtils.printGreen(numberOfClusterPluginsDeployed + " cluster level plugins setup.");
+ printGreen(numberOfClusterPluginsDeployed + " cluster level plugins setup.");
} else {
- PackageUtils.printRed("No cluster level plugin setup.");
+ printRed("No cluster level plugin setup.");
clusterPluginFailed = true;
}
}
@@ -681,13 +679,13 @@ public class PackageManager implements Closeable {
boolean shouldExecute = true;
if (!noprompt) { // show a prompt asking user to execute the setup command for the plugin
PackageUtils.print(
- PackageUtils.YELLOW,
+ SolrCLI.YELLOW,
"Execute this command. (If you choose no, you can manually deploy/undeploy this plugin later) (y/n): ");
try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) {
String userInput = scanner.next();
if ("no".trim().equalsIgnoreCase(userInput) || "n".trim().equalsIgnoreCase(userInput)) {
shouldExecute = false;
- PackageUtils.printRed(
+ printRed(
"Skipping setup command for deploying (deployment verification may fail)."
+ " Please run this step manually or refer to package documentation.");
}
@@ -768,13 +766,13 @@ public class PackageManager implements Closeable {
plugin.name);
String path =
PackageUtils.resolve(cmd.path, pkg.parameterDefaults, overridesMap, systemParams);
- PackageUtils.printGreen("Executing " + solrUrl + path + " for cluster level plugin");
+ printGreen("Executing " + solrUrl + path + " for cluster level plugin");
if ("GET".equalsIgnoreCase(cmd.method)) {
String response =
PackageUtils.getJsonStringFromNonCollectionApi(
solrClient, path, new ModifiableSolrParams());
- PackageUtils.printGreen(response);
+ printGreen(response);
String actualValue = null;
try {
String jsonPath =
@@ -782,16 +780,16 @@ public class PackageManager implements Closeable {
cmd.condition, pkg.parameterDefaults, overridesMap, systemParams);
actualValue = jsonPathRead(response, jsonPath);
} catch (PathNotFoundException ex) {
- PackageUtils.printRed("Failed to deploy plugin: " + plugin.name);
+ printRed("Failed to deploy plugin: " + plugin.name);
success = false;
}
if (actualValue != null) {
String expectedValue =
PackageUtils.resolve(
cmd.expected, pkg.parameterDefaults, overridesMap, systemParams);
- PackageUtils.printGreen("Actual: " + actualValue + ", expected: " + expectedValue);
+ printGreen("Actual: " + actualValue + ", expected: " + expectedValue);
if (!expectedValue.equals(actualValue)) {
- PackageUtils.printRed("Failed to deploy plugin: " + plugin.name);
+ printRed("Failed to deploy plugin: " + plugin.name);
success = false;
}
}
@@ -818,14 +816,13 @@ public class PackageManager implements Closeable {
String path =
PackageUtils.resolve(
cmd.path, pkg.parameterDefaults, collectionParameterOverrides, systemParams);
- PackageUtils.printGreen(
- "Executing " + solrUrl + path + " for collection:" + collection);
+ printGreen("Executing " + solrUrl + path + " for collection:" + collection);
if ("GET".equalsIgnoreCase(cmd.method)) {
String response =
PackageUtils.getJsonStringFromCollectionApi(
solrClient, path, new ModifiableSolrParams());
- PackageUtils.printGreen(response);
+ printGreen(response);
String actualValue = null;
try {
String jsonPath =
@@ -836,7 +833,7 @@ public class PackageManager implements Closeable {
systemParams);
actualValue = jsonPathRead(response, jsonPath);
} catch (PathNotFoundException ex) {
- PackageUtils.printRed("Failed to deploy plugin: " + plugin.name);
+ printRed("Failed to deploy plugin: " + plugin.name);
success = false;
}
if (actualValue != null) {
@@ -846,9 +843,9 @@ public class PackageManager implements Closeable {
pkg.parameterDefaults,
collectionParameterOverrides,
systemParams);
- PackageUtils.printGreen("Actual: " + actualValue + ", expected: " + expectedValue);
+ printGreen("Actual: " + actualValue + ", expected: " + expectedValue);
if (!expectedValue.equals(actualValue)) {
- PackageUtils.printRed("Failed to deploy plugin: " + plugin.name);
+ printRed("Failed to deploy plugin: " + plugin.name);
success = false;
}
}
@@ -927,7 +924,7 @@ public class PackageManager implements Closeable {
boolean pegToLatest = PackageUtils.LATEST.equals(version);
SolrPackageInstance packageInstance = getPackageInstance(packageName, version);
if (packageInstance == null) {
- PackageUtils.printRed(
+ printRed(
"Package instance doesn't exist: "
+ packageName
+ ":"
@@ -938,7 +935,7 @@ public class PackageManager implements Closeable {
Manifest manifest = packageInstance.manifest;
if (!SolrVersion.LATEST.satisfies(manifest.versionConstraint)) {
- PackageUtils.printRed(
+ printRed(
"Version incompatible! Solr version: "
+ SolrVersion.LATEST
+ ", package version constraint: "
@@ -956,8 +953,7 @@ public class PackageManager implements Closeable {
shouldInstallClusterPlugins,
parameters);
PackageUtils.print(
- res ? PackageUtils.GREEN : PackageUtils.RED,
- res ? "Deployment successful" : "Deployment failed");
+ res ? SolrCLI.GREEN : SolrCLI.RED, res ? "Deployment successful" : "Deployment failed");
}
/** Undeploys a package from given collections. */
@@ -971,8 +967,7 @@ public class PackageManager implements Closeable {
SolrPackageInstance deployedPackage =
getPackagesDeployedAsClusterLevelPlugins().get(packageName);
if (deployedPackage == null) {
- PackageUtils.printRed(
- "Cluster level plugins from package " + packageName + " not deployed.");
+ printRed("Cluster level plugins from package " + packageName + " not deployed.");
} else {
for (Plugin plugin : deployedPackage.plugins) {
if (!shouldUndeployClusterPlugins || !"cluster".equalsIgnoreCase(plugin.type)) continue;
@@ -1001,7 +996,7 @@ public class PackageManager implements Closeable {
deployedPackage.parameterDefaults,
Collections.emptyMap(),
systemParams);
- PackageUtils.printGreen("Executing " + payload + " for path:" + path);
+ printGreen("Executing " + payload + " for path:" + path);
SolrCLI.postJsonToSolr(solrClient, path, payload);
} catch (Exception ex) {
throw new SolrException(ErrorCode.SERVER_ERROR, ex);
@@ -1011,8 +1006,7 @@ public class PackageManager implements Closeable {
ErrorCode.BAD_REQUEST, "Non-POST method not supported for uninstall commands");
}
} else {
- PackageUtils.printRed(
- "There is no uninstall command to execute for plugin: " + plugin.name);
+ printRed("There is no uninstall command to execute for plugin: " + plugin.name);
}
}
}
@@ -1021,8 +1015,7 @@ public class PackageManager implements Closeable {
for (String collection : collections) {
SolrPackageInstance deployedPackage = getPackagesDeployed(collection).get(packageName);
if (deployedPackage == null) {
- PackageUtils.printRed(
- "Package " + packageName + " not deployed on collection " + collection);
+ printRed("Package " + packageName + " not deployed on collection " + collection);
continue;
}
Map<String, String> collectionParameterOverrides = getPackageParams(packageName, collection);
@@ -1059,7 +1052,7 @@ public class PackageManager implements Closeable {
deployedPackage.parameterDefaults,
collectionParameterOverrides,
systemParams);
- PackageUtils.printGreen("Executing " + payload + " for path:" + path);
+ printGreen("Executing " + payload + " for path:" + path);
SolrCLI.postJsonToSolr(solrClient, path, payload);
} catch (Exception ex) {
throw new SolrException(ErrorCode.SERVER_ERROR, ex);
@@ -1069,8 +1062,7 @@ public class PackageManager implements Closeable {
ErrorCode.BAD_REQUEST, "Non-POST method not supported for uninstall commands");
}
} else {
- PackageUtils.printRed(
- "There is no uninstall command to execute for plugin: " + plugin.name);
+ printRed("There is no uninstall command to execute for plugin: " + plugin.name);
}
}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/PackageUtils.java b/solr/core/src/java/org/apache/solr/packagemanager/PackageUtils.java
index d05c541243d..b3749d5cf8b 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/PackageUtils.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/PackageUtils.java
@@ -35,6 +35,7 @@ import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.lucene.util.SuppressForbidden;
+import org.apache.solr.cli.SolrCLI;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
@@ -255,27 +256,13 @@ public class PackageUtils {
return str;
}
- public static String BLACK = "\u001B[30m";
- public static String RED = "\u001B[31m";
- public static String GREEN = "\u001B[32m";
- public static String YELLOW = "\u001B[33m";
- public static String BLUE = "\u001B[34m";
- public static String PURPLE = "\u001B[35m";
- public static String CYAN = "\u001B[36m";
- public static String WHITE = "\u001B[37m";
-
/** Console print using green color */
- public static void printGreen(Object message) {
- PackageUtils.print(PackageUtils.GREEN, message);
- }
-
- /** Console print using red color */
- public static void printRed(Object message) {
- PackageUtils.print(PackageUtils.RED, message);
+ public static void formatGreen(StringBuilder sb, Object message) {
+ format(sb, SolrCLI.GREEN, message);
}
- public static void print(Object message) {
- print(null, message);
+ public static void format(StringBuilder sb, Object message) {
+ format(sb, null, message);
}
@SuppressForbidden(
@@ -290,6 +277,16 @@ public class PackageUtils {
}
}
+ public static void format(StringBuilder sb, String color, Object message) {
+ String RESET = "\u001B[0m";
+
+ if (color != null) {
+ sb.append(color + String.valueOf(message) + RESET + "\n");
+ } else {
+ sb.append(message + "\n");
+ }
+ }
+
public static String[] validateCollections(String collections[]) {
for (String c : collections) {
validateCollectionName(c);
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/RepositoryManager.java b/solr/core/src/java/org/apache/solr/packagemanager/RepositoryManager.java
index 09c0a209172..03605f26337 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/RepositoryManager.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/RepositoryManager.java
@@ -17,6 +17,7 @@
package org.apache.solr.packagemanager;
+import static org.apache.solr.cli.SolrCLI.printGreen;
import static org.apache.solr.common.params.CommonParams.SYSTEM_INFO_PATH;
import static org.apache.solr.packagemanager.PackageUtils.getMapper;
@@ -38,6 +39,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
+import org.apache.solr.cli.SolrCLI;
import org.apache.solr.client.api.util.SolrVersion;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
@@ -180,7 +182,7 @@ public class RepositoryManager {
try {
// post the manifest
- PackageUtils.printGreen("Posting manifest...");
+ printGreen("Posting manifest...");
if (release.manifest == null) {
String manifestJson = PackageUtils.getFileFromJarsAsString(downloaded, "manifest.json");
@@ -201,7 +203,7 @@ public class RepositoryManager {
null);
// post the artifacts
- PackageUtils.printGreen("Posting artifacts...");
+ printGreen("Posting artifacts...");
for (int i = 0; i < release.artifacts.size(); i++) {
PackageUtils.postFile(
solrClient,
@@ -216,7 +218,7 @@ public class RepositoryManager {
}
// Call Package API to add this version of the package
- PackageUtils.printGreen("Executing Package API to register this package...");
+ printGreen("Executing Package API to register this package...");
PackagePayload.AddVersion add = new PackagePayload.AddVersion();
add.version = version;
add.pkg = packageName;
@@ -244,7 +246,7 @@ public class RepositoryManager {
};
try {
NamedList<Object> resp = solrClient.request(request);
- PackageUtils.printGreen("Response: " + resp.jsonStr());
+ printGreen("Response: " + resp.jsonStr());
} catch (SolrServerException | IOException e) {
throw new SolrException(ErrorCode.BAD_REQUEST, e);
}
@@ -342,7 +344,7 @@ public class RepositoryManager {
public boolean install(String packageName, String version) throws SolrException {
SolrPackageRelease pkg = getLastPackageRelease(packageName);
if (pkg == null) {
- PackageUtils.printRed(
+ SolrCLI.printRed(
"Package "
+ packageName
+ " not found in any repository. Check list of available packages via \"solr package list-available\".");
@@ -358,7 +360,7 @@ public class RepositoryManager {
collectionsDeployedIn.get(collection).equals(SolrPackageLoader.LATEST))
.collect(Collectors.toList());
if (!collectionsPeggedToLatest.isEmpty()) {
- PackageUtils.printGreen(
+ printGreen(
"Collections that will be affected (since they are configured to use $LATEST): "
+ collectionsPeggedToLatest);
}
@@ -379,7 +381,7 @@ public class RepositoryManager {
false,
new String
[] {}); // Cluster level plugins don't work with peggedToLatest functionality
- PackageUtils.printGreen(
+ printGreen(
"Verifying version "
+ updatedPackage.version
+ " on "
@@ -387,7 +389,7 @@ public class RepositoryManager {
+ ", result: "
+ res);
if (!res) {
- PackageUtils.printRed("Failed verification after deployment");
+ SolrCLI.printRed("Failed verification after deployment");
return false;
}
}
diff --git a/solr/packaging/test/test_help.bats b/solr/packaging/test/test_help.bats
index 3702531e3f3..fe9c87866f1 100644
--- a/solr/packaging/test/test_help.bats
+++ b/solr/packaging/test/test_help.bats
@@ -98,7 +98,7 @@ setup() {
@test "auth help flag prints help" {
run solr auth --help
- assert_output --partial 'Usage: solr auth'
+ assert_output --partial 'bin/solr auth enable'
refute_output --partial 'ERROR'
}
diff --git a/solr/packaging/test/test_packages.bats b/solr/packaging/test/test_packages.bats
index 4ec786f717c..185b3381b83 100644
--- a/solr/packaging/test/test_packages.bats
+++ b/solr/packaging/test/test_packages.bats
@@ -28,18 +28,9 @@ teardown() {
solr stop --all >/dev/null 2>&1
}
-@test "package detects no running solr" {
- # not sure this is actually a good thing.. we may not want this..
- run solr package
- assert_output --partial "No Solr nodes are running."
-}
-
@test "lifecycle of package" {
run solr start -c -Denable.packages=true
- run solr package
- refute_output --partial "No Solr nodes are running."
-
run solr package --help
assert_output --partial "Add a repository to Solr"