Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

SOLR-14115: Allow bin/solr zk commands to have parity with zkcli.sh commands. (#2298)

Eric Pugh963b62983a98
diff --git a/dev-tools/scripts/cloud.sh b/dev-tools/scripts/cloud.sh
index bd41154a34f..6f4f4bb548b 100755
--- a/dev-tools/scripts/cloud.sh
+++ b/dev-tools/scripts/cloud.sh
@@ -59,6 +59,9 @@
# that not using the embedded zookeeper is key to being able
# switch between testing setups and to test vs alternate versions
# of zookeeper if desired.
+#
+# An option is:
+# docker run --name my-zookeeper -p 2181:2181 -d zookeeper
#
# SETUP: 1. Place this script in a directory intended to hold all your
# testing installations of solr.
@@ -79,7 +82,7 @@
#
# ./cloud.sh stop
#
-# Compile and push new code to a running cluster (incl bounce the cluster)
+# Compile and push new code to a running cluster (including bounce the cluster)
#
# ./cloud.sh restart -r
#
@@ -310,13 +313,9 @@ start(){
findSolr
echo "SOLR=$SOLR"
- SOLR_ROOT=$("${SOLR}/server/scripts/cloud-scripts/zkcli.sh" -zkhost localhost:${ZK_PORT} -cmd getfile "/solr_${SAFE_DEST}" /dev/stdout);
- if [[ -z ${SOLR_ROOT} ]]; then
- # Need a fresh root in zookeeper...
- "${SOLR}/server/scripts/cloud-scripts/zkcli.sh" -zkhost localhost:${ZK_PORT} -cmd makepath "/solr_${SAFE_DEST}";
- "${SOLR}/server/scripts/cloud-scripts/zkcli.sh" -zkhost localhost:${ZK_PORT} -cmd put "/solr_${SAFE_DEST}" "created by cloud.sh"; # so we can test for existence next time
- fi
-
+ # Create the root if it doesn't already exist
+ ${SOLR}/bin/solr zk mkroot "/solr_${SAFE_DEST}" -z localhost:${ZK_PORT}
+
ACTUAL_NUM_NODES=$(ls -1 -d ${CLUSTER_WD}/n* | wc -l )
if [[ "$NUM_NODES" -eq 0 ]]; then
NUM_NODES=${ACTUAL_NUM_NODES}
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index ef0782c567c..816b634052a 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -101,6 +101,8 @@ Improvements
---------------------
* SOLR-16921: use -solrUrl to derive the zk host connection for bin/solr zk subcommands (Eric Pugh)
+* SOLR-14115: Add linkconfig, cluster, and updateacls as commands to SolrCLI. Allow bin/solr commands to have parity with zkcli.sh commands. (Eric Pugh)
+
Optimizations
---------------------
(No changes)
diff --git a/solr/bin/solr b/solr/bin/solr
index e9a45777b7a..69686f6e286 100755
--- a/solr/bin/solr
+++ b/solr/bin/solr
@@ -591,6 +591,8 @@ function print_short_zk_usage() {
echo " solr zk mv <src> <dest> [-z zkHost] [-s solrUrl]"
echo " solr zk ls [-r] <path> [-z zkHost] [-s solrUrl]"
echo " solr zk mkroot <path> [-z zkHost] [-s solrUrl]"
+ echo " solr zk linkconfig -confname <confname> -c <collection> [-z zkHost] [-s solrUrl]"
+ echo " solr zk updateacls <path> [-z zkHost] [-s solrUrl]"
echo ""
if [ "$1" == "" ]; then
@@ -876,7 +878,7 @@ if [[ "$SCRIPT_CMD" == "delete" ]]; then
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" ]]; then
+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."
exit $?
fi
@@ -893,7 +895,7 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
if [ $# -gt 0 ]; then
while true; do
case "${1:-}" in
- upconfig|downconfig|cp|rm|mv|ls|mkroot)
+ upconfig|downconfig|cp|rm|mv|ls|mkroot|linkconfig|updateacls)
ZK_OP=$1
shift 1
;;
@@ -910,25 +912,33 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
fi
ZK_SOLR_URL="$2"
shift 2
- ;;
- -n|-confname)
+ ;;
+ -n|--confname)
if [[ -z "$2" || "${2:0:1}" == "-" ]]; then
print_short_zk_usage "$SCRIPT_CMD" "Configuration name is required when using the $1 option!"
fi
CONFIGSET_CONFNAME="$2"
shift 2
;;
- -d|-confdir)
+ -d|--confdir)
if [[ -z "$2" || "${2:0:1}" == "-" ]]; then
print_short_zk_usage "$SCRIPT_CMD" "Configuration directory is required when using the $1 option!"
fi
CONFIGSET_CONFDIR="$2"
shift 2
;;
+ --solr-home)
+ ZK_SOLR_HOME="$2"
+ shift 2
+ ;;
-r)
ZK_RECURSE="true"
shift
;;
+ -c|-collection)
+ ZK_COLLECTION="$2"
+ shift
+ ;;
-V|-verbose)
VERBOSE="-verbose"
shift
@@ -961,9 +971,9 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
fi
if [ -z "$ZK_OP" ]; then
- print_short_zk_usage "Zookeeper operation (one of 'upconfig', 'downconfig', 'rm', 'mv', 'cp', 'ls', 'mkroot') is required!"
+ print_short_zk_usage "Zookeeper operation (one of 'upconfig', 'downconfig', 'rm', 'mv', 'cp', 'ls', 'mkroot', 'linkconfig', 'updateacls') is required!"
fi
-
+
if [[ "$ZK_OP" == "upconfig" || "$ZK_OP" == "downconfig" ]]; then
if [ -z "$CONFIGSET_CONFDIR" ]; then
print_short_zk_usage "Local directory of the configset (-d) argument is required!"
@@ -990,19 +1000,19 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
fi
CONNECTION_PARAMS=""
-
+
if [[ -z "$ZK_HOST" ]]; then
CONNECTION_PARAMS="-solrUrl ${ZK_SOLR_URL}"
else
CONNECTION_PARAMS="-zkHost ${ZK_HOST}"
- fi
+ fi
case "$ZK_OP" in
upconfig)
- run_tool "$ZK_OP" -confname "$CONFIGSET_CONFNAME" -confdir "$CONFIGSET_CONFDIR" $CONNECTION_PARAMS -configsetsDir "$SOLR_TIP/server/solr/configsets" $VERBOSE
+ run_tool "$ZK_OP" --confname "$CONFIGSET_CONFNAME" -confdir "$CONFIGSET_CONFDIR" $CONNECTION_PARAMS -configsetsDir "$SOLR_TIP/server/solr/configsets" $VERBOSE
;;
downconfig)
- run_tool "$ZK_OP" -confname "$CONFIGSET_CONFNAME" -confdir "$CONFIGSET_CONFDIR" $CONNECTION_PARAMS $VERBOSE
+ run_tool "$ZK_OP" --confname "$CONFIGSET_CONFNAME" -confdir "$CONFIGSET_CONFDIR" $CONNECTION_PARAMS $VERBOSE
;;
rm)
if [ -z "$ZK_SRC" ]; then
@@ -1014,7 +1024,12 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
run_tool "$ZK_OP" -src "$ZK_SRC" -dst "$ZK_DST" $CONNECTION_PARAMS $VERBOSE
;;
cp)
- run_tool "$ZK_OP" -src "$ZK_SRC" -dst "$ZK_DST" $CONNECTION_PARAMS -recurse "$ZK_RECURSE" $VERBOSE
+ if [ -z "$ZK_SOLR_HOME" ]; then
+ run_tool "$ZK_OP" -src "$ZK_SRC" -dst "$ZK_DST" $CONNECTION_PARAMS -recurse "$ZK_RECURSE" $VERBOSE
+ else
+ run_tool "$ZK_OP" -src "$ZK_SRC" -dst "$ZK_DST" $CONNECTION_PARAMS -recurse "$ZK_RECURSE" $VERBOSE --solr-home "$ZK_SOLR_HOME"
+ fi
+
;;
ls)
if [ -z "$ZK_SRC" ]; then
@@ -1026,7 +1041,13 @@ if [[ "$SCRIPT_CMD" == "zk" ]]; then
if [ -z "$ZK_SRC" ]; then
print_short_zk_usage "Zookeeper path to list must be specified when using the 'mkroot' command"
fi
- run_tool "$ZK_OP" -path "$ZK_SRC" $CONNECTION_PARAMS $VERBOSE
+ run_tool "$ZK_OP" --path "$ZK_SRC" $CONNECTION_PARAMS $VERBOSE
+ ;;
+ linkconfig)
+ run_tool "$ZK_OP" --confname "$CONFIGSET_CONFNAME" -c "$ZK_COLLECTION" $CONNECTION_PARAMS $VERBOSE
+ ;;
+ updateacls)
+ run_tool "$ZK_OP" --path "$ZK_SRC" $CONNECTION_PARAMS $VERBOSE
;;
*)
print_short_zk_usage "Unrecognized Zookeeper operation $ZK_OP"
diff --git a/solr/bin/solr.cmd b/solr/bin/solr.cmd
index aee0892653e..faf51b4eafc 100755
--- a/solr/bin/solr.cmd
+++ b/solr/bin/solr.cmd
@@ -298,6 +298,7 @@ IF "%SCRIPT_CMD%"=="stop" goto stop_usage
IF "%SCRIPT_CMD%"=="healthcheck" goto run_solrcli
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%"=="status" goto run_solrcli
@@ -478,6 +479,8 @@ echo solr zk rm [-r] ^<path^> [-z zkHost] [-s solrUrl]
echo solr zk mv ^<src^> ^<dest^> [-z zkHost] [-s solrUrl]
echo solr zk ls [-r] ^<path^> [-z zkHost] [-s solrUrl]
echo solr zk mkroot ^<path^> [-z zkHost] [-s solrUrl]
+echo solr zk linkconfig -confname ^<confname^> -c ^<collection^> [-z zkHost] [-s solrUrl]
+echo solr zk updateacls ^<path^> [-z zkHost] [-s solrUrl]
echo.
IF "%ZK_FULL%"=="true" (
goto zk_full_usage
@@ -1412,6 +1415,10 @@ IF "%1"=="-V" (
goto set_zk_op
) ELSE IF "%1"=="mkroot" (
goto set_zk_op
+) ELSE IF "%1"=="linkconfig" (
+ goto set_zk_op
+) ELSE IF "%1"=="updateacls" (
+ goto set_zk_op
) ELSE IF "%1"=="-n" (
goto set_config_name
) ELSE IF "%1"=="-r" (
@@ -1422,6 +1429,8 @@ IF "%1"=="-V" (
goto set_configdir
) ELSE IF "%1"=="-confdir" (
goto set_configdir
+) ELSE IF "%1"=="-c" (
+ goto set_collection_zk
) ELSE IF "%1"=="-z" (
goto set_config_zk
) ELSE IF "%1"=="/?" (
@@ -1470,6 +1479,12 @@ SHIFT
SHIFT
goto parse_zk_args
+:set_collection_zk
+set ZK_COLLECTION=%~2
+SHIFT
+SHIFT
+goto parse_zk_args
+
:set_config_zk
set ZK_HOST=%~2
SHIFT
@@ -1533,6 +1548,28 @@ IF "!ZK_OP!"=="upconfig" (
-Dlog4j.configurationFile="file:///%DEFAULT_SERVER_DIR%\resources\log4j2-console.xml" ^
-classpath "%DEFAULT_SERVER_DIR%\solr-webapp\webapp\WEB-INF\lib\*;%DEFAULT_SERVER_DIR%\lib\ext\*" ^
org.apache.solr.cli.SolrCLI !ZK_OP! -confname !CONFIGSET_NAME! -confdir !CONFIGSET_DIR! -zkHost !ZK_HOST! %ZK_VERBOSE%
+) ELSE IF "!ZK_OP!"=="linkconfig" (
+ IF "!CONFIGSET_NAME!"=="" (
+ set ERROR_MSG="-n option must be set for linkconfig"
+ goto zk_short_usage
+ )
+ IF "!ZK_COLLECTION!"=="" (
+ set ERROR_MSG="The -c option must be set for linkconfig."
+ goto zk_short_usage
+ )
+ "%JAVA%" %SOLR_SSL_OPTS% %AUTHC_OPTS% %SOLR_ZK_CREDS_AND_ACLS% %SOLR_TOOL_OPTS% -Dsolr.install.dir="%SOLR_TIP%" ^
+ -Dlog4j.configurationFile="file:///%DEFAULT_SERVER_DIR%\resources\log4j2-console.xml" ^
+ -classpath "%DEFAULT_SERVER_DIR%\solr-webapp\webapp\WEB-INF\lib\*;%DEFAULT_SERVER_DIR%\lib\ext\*" ^
+ org.apache.solr.cli.SolrCLI !ZK_OP! -confname !CONFIGSET_NAME! -c !ZK_COLLECTION! -zkHost !ZK_HOST! %ZK_VERBOSE%
+) ELSE IF "!ZK_OP!"=="updateacls" (
+ IF "%ZK_SRC"=="" (
+ set ERROR_MSG="Zookeeper path to remove must be specified when using the 'ls' command"
+ goto zk_short_usage
+ )
+ "%JAVA%" %SOLR_SSL_OPTS% %AUTHC_OPTS% %SOLR_ZK_CREDS_AND_ACLS% %SOLR_TOOL_OPTS% -Dsolr.install.dir="%SOLR_TIP%" ^
+ -Dlog4j.configurationFile="file:///%DEFAULT_SERVER_DIR%\resources\log4j2-console.xml" ^
+ -classpath "%DEFAULT_SERVER_DIR%\solr-webapp\webapp\WEB-INF\lib\*;%DEFAULT_SERVER_DIR%\lib\ext\*" ^
+ org.apache.solr.cli.SolrCLI !ZK_OP! -path !ZK_SRC! -zkHost !ZK_HOST! %ZK_VERBOSE%
) ELSE IF "!ZK_OP!"=="cp" (
IF "%ZK_SRC%"=="" (
set ERROR_MSG="<src> must be specified for 'cp' command"
diff --git a/solr/core/src/java/org/apache/solr/cli/ClusterTool.java b/solr/core/src/java/org/apache/solr/cli/ClusterTool.java
new file mode 100644
index 00000000000..167df8f0c00
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/cli/ClusterTool.java
@@ -0,0 +1,100 @@
+/*
+ * 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 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.solr.client.solrj.impl.SolrZkClientTimeout;
+import org.apache.solr.cloud.ZkController;
+import org.apache.solr.common.cloud.ClusterProperties;
+import org.apache.solr.common.cloud.SolrZkClient;
+
+/**
+ * Supports cluster command in the bin/solr script.
+ *
+ * <p>Set cluster properties by directly manipulating ZooKeeper.
+ */
+public class ClusterTool extends ToolBase {
+ // It is a shame this tool doesn't more closely mimic how the ConfigTool works.
+
+ public ClusterTool() {
+ this(CLIO.getOutStream());
+ }
+
+ public ClusterTool(PrintStream stdout) {
+ super(stdout);
+ }
+
+ @Override
+ public String getName() {
+ return "cluster";
+ }
+
+ @Override
+ public List<Option> getOptions() {
+ return List.of(
+ Option.builder()
+ .longOpt("property")
+ .argName("PROP")
+ .hasArg()
+ .required(true)
+ .desc("Name of the Cluster property to apply the action to, such as: 'urlScheme'.")
+ .build(),
+ Option.builder()
+ .longOpt("value")
+ .argName("VALUE")
+ .hasArg()
+ .required(false)
+ .desc("Set the property to this value.")
+ .build(),
+ SolrCLI.OPTION_ZKHOST);
+ }
+
+ @Override
+ public void runImpl(CommandLine cli) throws Exception {
+
+ String propertyName = cli.getOptionValue("property");
+ String propertyValue = cli.getOptionValue("value");
+ String zkHost = SolrCLI.getZkHost(cli);
+
+ if (!ZkController.checkChrootPath(zkHost, true)) {
+ throw new IllegalStateException(
+ "A chroot was specified in zkHost but the znode doesn't exist.");
+ }
+
+ try (SolrZkClient zkClient =
+ new SolrZkClient.Builder()
+ .withUrl(zkHost)
+ .withTimeout(SolrZkClientTimeout.DEFAULT_ZK_CLIENT_TIMEOUT, TimeUnit.MILLISECONDS)
+ .build()) {
+
+ ClusterProperties props = new ClusterProperties(zkClient);
+ try {
+ props.setClusterProperty(propertyName, propertyValue);
+ } catch (IOException ex) {
+ throw new Exception(
+ "Unable to set the cluster property due to following error : "
+ + ex.getLocalizedMessage());
+ }
+ }
+ }
+}
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 efe1ee20226..6c838e71a80 100644
--- a/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java
@@ -45,14 +45,16 @@ public class ConfigSetDownloadTool extends ToolBase {
@Override
public List<Option> getOptions() {
return List.of(
- Option.builder("confname")
- .argName("confname")
+ Option.builder("n")
+ .longOpt("confname")
+ .argName("NAME")
.hasArg()
.required(true)
.desc("Configset name in ZooKeeper.")
.build(),
- Option.builder("confdir")
- .argName("confdir")
+ Option.builder("d")
+ .longOpt("confdir")
+ .argName("DIR")
.hasArg()
.required(true)
.desc("Local directory with configs.")
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 0573df811b4..c82e0ee6356 100644
--- a/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java
@@ -46,14 +46,16 @@ public class ConfigSetUploadTool extends ToolBase {
@Override
public List<Option> getOptions() {
return List.of(
- Option.builder("confname")
- .argName("confname") // Comes out in help message
- .hasArg() // Has one sub-argument
- .required(true) // confname argument must be present
+ Option.builder("n")
+ .longOpt("confname")
+ .argName("NAME")
+ .hasArg()
+ .required(true)
.desc("Configset name in ZooKeeper.")
- .build(), // passed as -confname value
- Option.builder("confdir")
- .argName("confdir")
+ .build(),
+ Option.builder("d")
+ .longOpt("confdir")
+ .argName("DIR")
.hasArg()
.required(true)
.desc("Local directory with configs.")
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 80db530072e..5e7fcd894d6 100644
--- a/solr/core/src/java/org/apache/solr/cli/CreateTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/CreateTool.java
@@ -97,7 +97,7 @@ public class CreateTool extends ToolBase {
.build(),
Option.builder("d")
.longOpt("confdir")
- .argName("NAME")
+ .argName("DIR")
.hasArg()
.required(false)
.desc(
diff --git a/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java b/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java
new file mode 100644
index 00000000000..2d1a41d62b8
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java
@@ -0,0 +1,81 @@
+/*
+ * 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 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.solr.client.solrj.impl.SolrZkClientTimeout;
+import org.apache.solr.cloud.ZkController;
+import org.apache.solr.common.cloud.SolrZkClient;
+
+/** Supports linking a configset to a collection */
+public class LinkConfigTool extends ToolBase {
+
+ public LinkConfigTool() {
+ this(CLIO.getOutStream());
+ }
+
+ public LinkConfigTool(PrintStream stdout) {
+ super(stdout);
+ }
+
+ @Override
+ public String getName() {
+ return "linkconfig";
+ }
+
+ @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("confname")
+ .argName("NAME")
+ .hasArg()
+ .required(true)
+ .desc("Configset name in ZooKeeper.")
+ .build(),
+ SolrCLI.OPTION_ZKHOST);
+ }
+
+ @Override
+ public void runImpl(CommandLine cli) throws Exception {
+
+ String collection = cli.getOptionValue("name");
+ String confName = cli.getOptionValue("confname");
+ String zkHost = SolrCLI.getZkHost(cli);
+
+ try (SolrZkClient zkClient =
+ new SolrZkClient.Builder()
+ .withUrl(zkHost)
+ .withTimeout(SolrZkClientTimeout.DEFAULT_ZK_CLIENT_TIMEOUT, TimeUnit.MILLISECONDS)
+ .build()) {
+
+ ZkController.linkConfSet(zkClient, collection, confName);
+ }
+ }
+}
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 c81326e7702..27250c63845 100755
--- a/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
+++ b/solr/core/src/java/org/apache/solr/cli/SolrCLI.java
@@ -248,6 +248,9 @@ public class SolrCLI implements CLIO {
else if ("mv".equals(toolType)) return new ZkMvTool();
else if ("cp".equals(toolType)) return new ZkCpTool();
else if ("ls".equals(toolType)) return new ZkLsTool();
+ else if ("cluster".equals(toolType)) return new ClusterTool();
+ else if ("updateacls".equals(toolType)) return new UpdateACLTool();
+ else if ("linkconfig".equals(toolType)) return new LinkConfigTool();
else if ("mkroot".equals(toolType)) return new ZkMkrootTool();
else if ("assert".equals(toolType)) return new AssertTool();
else if ("auth".equals(toolType)) return new AuthTool();
diff --git a/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java b/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java
new file mode 100644
index 00000000000..53f29b41b56
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java
@@ -0,0 +1,83 @@
+/*
+ * 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 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.solr.client.solrj.impl.SolrZkClientTimeout;
+import org.apache.solr.cloud.ZkController;
+import org.apache.solr.common.cloud.SolrZkClient;
+
+/**
+ * Supports updating ACL for a path in ZK
+ *
+ * <p>Set ACL properties by directly manipulating ZooKeeper.
+ */
+public class UpdateACLTool extends ToolBase {
+ // It is a shame this tool doesn't more closely mimic how the ConfigTool works.
+
+ public UpdateACLTool() {
+ this(CLIO.getOutStream());
+ }
+
+ public UpdateACLTool(PrintStream stdout) {
+ super(stdout);
+ }
+
+ @Override
+ public String getName() {
+ return "updateacls";
+ }
+
+ @Override
+ public List<Option> getOptions() {
+ return List.of(
+ Option.builder()
+ .longOpt("path")
+ .argName("PATH")
+ .hasArg()
+ .required(true)
+ .desc("The path to update.")
+ .build(),
+ SolrCLI.OPTION_ZKHOST);
+ }
+
+ @Override
+ public void runImpl(CommandLine cli) throws Exception {
+
+ String path = cli.getOptionValue("path");
+ String zkHost = SolrCLI.getZkHost(cli);
+
+ if (!ZkController.checkChrootPath(zkHost, true)) {
+ throw new IllegalStateException(
+ "A chroot was specified in zkHost but the znode doesn't exist.");
+ }
+
+ try (SolrZkClient zkClient =
+ new SolrZkClient.Builder()
+ .withUrl(zkHost)
+ .withTimeout(SolrZkClientTimeout.DEFAULT_ZK_CLIENT_TIMEOUT, TimeUnit.MILLISECONDS)
+ .build()) {
+
+ zkClient.updateACLs(path);
+ }
+ }
+}
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 54f32b2538a..af1da32a71b 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java
@@ -18,13 +18,23 @@ package org.apache.solr.cli;
import java.io.PrintStream;
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.solr.client.solrj.impl.SolrZkClientTimeout;
+import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.util.Compressor;
+import org.apache.solr.common.util.StrUtils;
+import org.apache.solr.common.util.ZLibCompressor;
+import org.apache.solr.core.NodeConfig;
+import org.apache.solr.core.SolrXmlConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -55,6 +65,13 @@ public class ZkCpTool extends ToolBase {
.required(true)
.desc("Destination of copy, may be local or a Znode.")
.build(),
+ Option.builder()
+ .longOpt("solr-home")
+ .argName("DIR")
+ .hasArg()
+ .required(false)
+ .desc("Required to look up configuration for compressing state.json.")
+ .build(),
SolrCLI.OPTION_RECURSE,
SolrCLI.OPTION_ZKHOST,
SolrCLI.OPTION_SOLRURL,
@@ -77,36 +94,89 @@ public class ZkCpTool extends ToolBase {
+ " is running in standalone server mode, cp can only be used when running in SolrCloud mode.\n");
}
+ echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...", cli);
+ String src = cli.getOptionValue("src");
+ String dst = cli.getOptionValue("dst");
+ Boolean recurse = Boolean.parseBoolean(cli.getOptionValue("recurse"));
+ echo("Copying from '" + src + "' to '" + dst + "'. ZooKeeper at " + zkHost);
+
+ boolean srcIsZk = src.toLowerCase(Locale.ROOT).startsWith("zk:");
+ boolean dstIsZk = dst.toLowerCase(Locale.ROOT).startsWith("zk:");
+
+ String srcName = src;
+ if (srcIsZk) {
+ srcName = src.substring(3);
+ } else if (srcName.toLowerCase(Locale.ROOT).startsWith("file:")) {
+ srcName = srcName.substring(5);
+ }
+
+ String dstName = dst;
+ if (dstIsZk) {
+ dstName = dst.substring(3);
+ if (!dstName.startsWith("/")) {
+ dstName = "/" + dstName;
+ }
+ } else {
+ if (dstName.toLowerCase(Locale.ROOT).startsWith("file:")) {
+ dstName = dstName.substring(5);
+ }
+ }
+
+ int minStateByteLenForCompression = -1;
+ Compressor compressor = new ZLibCompressor();
+
+ if (dstIsZk) {
+ String solrHome = cli.getOptionValue("solr-home");
+ if (StrUtils.isNullOrEmpty(solrHome)) {
+ solrHome = System.getProperty("solr.home");
+ }
+
+ if (solrHome != null) {
+ echoIfVerbose("Using SolrHome: " + solrHome, cli);
+ try {
+ // Be aware that if you start Solr and pass in some variables via -D like
+ // solr start -DminStateByteLenForCompression=0 -c, this logic will not
+ // know about the -DminStateByteLenForCompression and only return the
+ // version set in the solr.xml. So you must edit solr.xml directly.
+ Path solrHomePath = Paths.get(solrHome);
+ Properties props = new Properties();
+ props.put(SolrXmlConfig.ZK_HOST, zkHost);
+ NodeConfig nodeConfig = NodeConfig.loadNodeConfig(solrHomePath, props);
+ minStateByteLenForCompression =
+ nodeConfig.getCloudConfig().getMinStateByteLenForCompression();
+ String stateCompressorClass = nodeConfig.getCloudConfig().getStateCompressorClass();
+ if (StrUtils.isNotNullOrEmpty(stateCompressorClass)) {
+ Class<? extends Compressor> compressionClass =
+ Class.forName(stateCompressorClass).asSubclass(Compressor.class);
+ compressor = compressionClass.getDeclaredConstructor().newInstance();
+ }
+ } catch (SolrException e) {
+ // Failed to load solr.xml
+ throw new IllegalStateException(
+ "Failed to load solr.xml from ZK or SolrHome, put/get operations on compressed data will use data as is. If your intention is to read and de-compress data or compress and write data, then solr.xml must be accessible.");
+ } catch (ClassNotFoundException
+ | NoSuchMethodException
+ | InstantiationException
+ | IllegalAccessException
+ | InvocationTargetException e) {
+ throw new IllegalStateException(
+ "Unable to find or instantiate compression class: " + e.getMessage());
+ }
+ }
+ }
+ if (minStateByteLenForCompression > -1) {
+ echoIfVerbose("Compression of state.json has been enabled", cli);
+ }
+
try (SolrZkClient zkClient =
new SolrZkClient.Builder()
.withUrl(zkHost)
.withTimeout(SolrZkClientTimeout.DEFAULT_ZK_CLIENT_TIMEOUT, TimeUnit.MILLISECONDS)
+ .withStateFileCompression(minStateByteLenForCompression, compressor)
.build()) {
- echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...", cli);
- String src = cli.getOptionValue("src");
- String dst = cli.getOptionValue("dst");
- Boolean recurse = Boolean.parseBoolean(cli.getOptionValue("recurse"));
- echo("Copying from '" + src + "' to '" + dst + "'. ZooKeeper at " + zkHost);
-
- boolean srcIsZk = src.toLowerCase(Locale.ROOT).startsWith("zk:");
- boolean dstIsZk = dst.toLowerCase(Locale.ROOT).startsWith("zk:");
-
- String srcName = src;
- if (srcIsZk) {
- srcName = src.substring(3);
- } else if (srcName.toLowerCase(Locale.ROOT).startsWith("file:")) {
- srcName = srcName.substring(5);
- }
- String dstName = dst;
- if (dstIsZk) {
- dstName = dst.substring(3);
- } else {
- if (dstName.toLowerCase(Locale.ROOT).startsWith("file:")) {
- dstName = dstName.substring(5);
- }
- }
zkClient.zkTransfer(srcName, srcIsZk, dstName, dstIsZk, recurse);
+
} catch (Exception e) {
log.error("Could not complete the zk operation for reason: ", e);
throw (e);
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 67e65bcff87..f1024eee43f 100644
--- a/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java
+++ b/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java
@@ -42,12 +42,19 @@ public class ZkMkrootTool extends ToolBase {
@Override
public List<Option> getOptions() {
return List.of(
- Option.builder("path")
- .argName("path")
+ Option.builder()
+ .longOpt("path")
+ .argName("PATH")
.hasArg()
.required(true)
.desc("Path to create.")
.build(),
+ Option.builder()
+ .longOpt("fail-on-exists")
+ .hasArg()
+ .required(false)
+ .desc("Raise an error if the root exists. Defaults to false.")
+ .build(),
SolrCLI.OPTION_ZKHOST,
SolrCLI.OPTION_SOLRURL,
SolrCLI.OPTION_VERBOSE);
@@ -62,6 +69,7 @@ public class ZkMkrootTool extends ToolBase {
public void runImpl(CommandLine cli) throws Exception {
SolrCLI.raiseLogLevelUnlessVerbose(cli);
String zkHost = SolrCLI.getZkHost(cli);
+ boolean failOnExists = cli.hasOption("fail-on-exists");
if (zkHost == null) {
throw new IllegalStateException(
@@ -79,7 +87,7 @@ public class ZkMkrootTool extends ToolBase {
String znode = cli.getOptionValue("path");
echo("Creating ZooKeeper path " + znode + " on ZooKeeper at " + zkHost);
- zkClient.makePath(znode, true);
+ zkClient.makePath(znode, failOnExists, true);
} catch (Exception e) {
log.error("Could not complete mkroot operation for reason: ", e);
throw (e);
diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java b/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java
index 39c8a95169b..856ef68581e 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java
@@ -317,7 +317,8 @@ public class ZkCLI implements CLIO {
.withConnTimeOut(
SolrZkClientTimeout.DEFAULT_ZK_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
.withReconnectListener(() -> {})
- .withCompressor(compressor)
+ // .withCompressor(compressor)
+ .withStateFileCompression(minStateByteLenForCompression, compressor)
.build()) {
if (line.getOptionValue(CMD).equalsIgnoreCase(BOOTSTRAP)) {
if (!line.hasOption(SOLRHOME)) {
@@ -420,7 +421,7 @@ public class ZkCLI implements CLIO {
byte[] data = arglist.get(1).getBytes(StandardCharsets.UTF_8);
if (shouldCompressData(data, path, minStateByteLenForCompression)) {
// state.json should be compressed before being put to ZK
- data = compressor.compressBytes(data, data.length / 10);
+ // data = compressor.compressBytes(data, data.length / 10);
}
if (zkClient.exists(path, true)) {
zkClient.setData(path, data, true);
@@ -441,7 +442,7 @@ public class ZkCLI implements CLIO {
byte[] data = Files.readAllBytes(Path.of(arglist.get(1)));
if (shouldCompressData(data, path, minStateByteLenForCompression)) {
// state.json should be compressed before being put to ZK
- data = compressor.compressBytes(data, data.length / 10);
+ // data = compressor.compressBytes(data, data.length / 10);
}
if (zkClient.exists(path, true)) {
zkClient.setData(path, data, true);
diff --git a/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java b/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java
new file mode 100644
index 00000000000..ec46f33a4c4
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java
@@ -0,0 +1,715 @@
+/*
+ * 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 static org.apache.solr.cli.SolrCLI.parseCmdLine;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.PrintStream;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.filefilter.RegexFileFilter;
+import org.apache.commons.io.filefilter.TrueFileFilter;
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.cloud.AbstractDistribZkTestBase;
+import org.apache.solr.cloud.AbstractZkTestCase;
+import org.apache.solr.cloud.ZkConfigSetService;
+import org.apache.solr.cloud.ZkTestServer;
+import org.apache.solr.common.cloud.ClusterProperties;
+import org.apache.solr.common.cloud.DigestZkACLProvider;
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.cloud.VMParamsAllAndReadonlyDigestZkACLProvider;
+import org.apache.solr.common.cloud.VMParamsZkCredentialsInjector;
+import org.apache.solr.common.cloud.ZkNodeProps;
+import org.apache.solr.common.cloud.ZkStateReader;
+import org.apache.solr.common.util.ZLibCompressor;
+import org.apache.solr.core.ConfigSetService;
+import org.apache.solr.util.ExternalPaths;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+// TODO: This test would be a lot faster if it used a solrhome with fewer config
+// files - there are a lot of them to upload
+// This was copied from org.apache.solr.cloud.ZkCLITest
+public class ZkSubcommandsTest extends SolrTestCaseJ4 {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ protected ZkTestServer zkServer;
+
+ protected Path zkDir;
+
+ private String solrHome;
+
+ private SolrZkClient zkClient;
+
+ private PrintStream originalSystemOut;
+
+ protected static final String SOLR_HOME = SolrTestCaseJ4.TEST_HOME();
+
+ @BeforeClass
+ public static void beforeClass() {
+ System.setProperty("solrcloud.skip.autorecovery", "true");
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ System.clearProperty("solrcloud.skip.autorecovery");
+ }
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ if (log.isInfoEnabled()) {
+ log.info("####SETUP_START {}", getTestName());
+ }
+
+ String exampleHome = legacyExampleCollection1SolrHome();
+
+ Path tmpDir = createTempDir();
+ solrHome = exampleHome;
+
+ originalSystemOut = System.out;
+
+ zkDir = tmpDir.resolve("zookeeper/server1/data");
+ log.info("ZooKeeper dataDir:{}", zkDir);
+ zkServer = new ZkTestServer(zkDir);
+ zkServer.run();
+ System.setProperty("zkHost", zkServer.getZkAddress());
+ // zkClient.close();
+
+ zkClient =
+ new SolrZkClient.Builder()
+ .withUrl(zkServer.getZkAddress())
+ .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
+ .build();
+ zkClient.makePath("/solr", false, true);
+
+ if (log.isInfoEnabled()) {
+ log.info("####SETUP_END {}", getTestName());
+ }
+ }
+
+ @Test
+ public void testPut() throws Exception {
+ // test put
+ String data = "my data";
+ File localFile = File.createTempFile("temp", ".data");
+ FileWriter writer = new FileWriter(localFile, StandardCharsets.UTF_8);
+ writer.write(data);
+ writer.close();
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ localFile.getAbsolutePath(),
+ "-dst",
+ "zk:/data.txt",
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ assertArrayEquals(
+ zkClient.getData("/data.txt", null, null, true), data.getBytes(StandardCharsets.UTF_8));
+
+ // test re-put to existing
+ data = "my data deux";
+
+ // Write text to the temporary file
+ writer = new FileWriter(localFile, StandardCharsets.UTF_8);
+ writer.write(data);
+ writer.close();
+
+ assertEquals(0, runTool(args, tool));
+
+ assertArrayEquals(
+ zkClient.getData("/data.txt", null, null, true), data.getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Test
+ public void testPutCompressed() throws Exception {
+ // test put compressed
+ System.setProperty("solr.home", solrHome);
+ System.setProperty("minStateByteLenForCompression", "0");
+
+ String data = "my data";
+
+ File localFile = File.createTempFile("state", ".json");
+ FileWriter writer = new FileWriter(localFile, StandardCharsets.UTF_8);
+ writer.write(data);
+ writer.close();
+
+ ZLibCompressor zLibCompressor = new ZLibCompressor();
+ byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
+ byte[] expected =
+ random().nextBoolean()
+ ? zLibCompressor.compressBytes(dataBytes)
+ : zLibCompressor.compressBytes(dataBytes);
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ localFile.getAbsolutePath(),
+ "-dst",
+ "zk:/state.json",
+ "-z",
+ zkServer.getZkAddress()
+ };
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ assertArrayEquals(zkClient.getZooKeeper().getData("/state.json", null, null), expected);
+
+ // test re-put to existing
+ data = "my data deux";
+ localFile = File.createTempFile("state", ".json");
+ writer = new FileWriter(localFile, StandardCharsets.UTF_8);
+ writer.write(data);
+ writer.close();
+
+ dataBytes = data.getBytes(StandardCharsets.UTF_8);
+ expected = zLibCompressor.compressBytes(dataBytes);
+
+ byte[] fromLoca =
+ new ZLibCompressor()
+ .compressBytes(Files.readAllBytes(Path.of(localFile.getAbsolutePath())));
+ assertArrayEquals("Should get back what we put in ZK", fromLoca, expected);
+
+ args =
+ new String[] {
+ "cp",
+ "-src",
+ localFile.getAbsolutePath(),
+ "-dst",
+ "zk:/state.json",
+ "-z",
+ zkServer.getZkAddress()
+ };
+ assertEquals(0, runTool(args, tool));
+
+ byte[] fromZk = zkClient.getZooKeeper().getData("/state.json", null, null);
+ byte[] fromLoc =
+ new ZLibCompressor()
+ .compressBytes(Files.readAllBytes(Path.of(localFile.getAbsolutePath())));
+ assertArrayEquals("Should get back what we put in ZK", fromLoc, fromZk);
+
+ assertArrayEquals(zkClient.getZooKeeper().getData("/state.json", null, null), expected);
+ }
+
+ @Test
+ public void testPutFile() throws Exception {
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ SOLR_HOME + File.separator + "solr-stress-new.xml",
+ "-dst",
+ "zk:/foo.xml",
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ String fromZk =
+ new String(zkClient.getData("/foo.xml", null, null, true), StandardCharsets.UTF_8);
+ Path localFile = Path.of(SOLR_HOME, "solr-stress-new.xml");
+ String fromLocalFile = Files.readString(localFile);
+ assertEquals("Should get back what we put in ZK", fromZk, fromLocalFile);
+ }
+
+ @Test
+ public void testPutFileWithoutSlash() throws Exception {
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ SOLR_HOME + File.separator + "solr-stress-new.xml",
+ "-dst",
+ "zk:foo.xml",
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ String fromZk =
+ new String(zkClient.getData("/foo.xml", null, null, true), StandardCharsets.UTF_8);
+ Path localFile = Path.of(SOLR_HOME, "solr-stress-new.xml");
+ String fromLocalFile = Files.readString(localFile);
+ assertEquals("Should get back what we put in ZK", fromZk, fromLocalFile);
+ }
+
+ @Test
+ public void testPutFileCompressed() throws Exception {
+ // test put file compressed
+ System.setProperty("solr.home", solrHome);
+ System.setProperty("minStateByteLenForCompression", "0");
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ SOLR_HOME + File.separator + "solr-stress-new.xml",
+ "-dst",
+ "zk:/state.json",
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ byte[] fromZk = zkClient.getZooKeeper().getData("/state.json", null, null);
+ Path locFile = Path.of(SOLR_HOME, "solr-stress-new.xml");
+ byte[] fromLoc = new ZLibCompressor().compressBytes(Files.readAllBytes(locFile));
+ assertArrayEquals("Should get back what we put in ZK", fromLoc, fromZk);
+
+ // Lets do it again
+ assertEquals(0, runTool(args, tool));
+
+ fromZk = zkClient.getZooKeeper().getData("/state.json", null, null);
+ locFile = Path.of(SOLR_HOME, "solr-stress-new.xml");
+ fromLoc = new ZLibCompressor().compressBytes(Files.readAllBytes(locFile));
+ assertArrayEquals("Should get back what we put in ZK", fromLoc, fromZk);
+ }
+
+ @Test
+ public void testPutFileNotExists() throws Exception {
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ SOLR_HOME + File.separator + "not-there.xml",
+ "-dst",
+ "zk:/foo.xml",
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(1, runTool(args, tool));
+ }
+
+ @Test
+ public void testLs() throws Exception {
+ zkClient.makePath("/test/path", true);
+
+ String[] args = new String[] {"ls", "-path", "/", "-r", "true", "-z", zkServer.getZkAddress()};
+
+ ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+ final PrintStream myOut = new PrintStream(byteStream, false, StandardCharsets.UTF_8);
+
+ ZkLsTool tool = new ZkLsTool(myOut);
+ assertEquals(0, runTool(args, tool));
+
+ final String standardOutput2 = byteStream.toString(StandardCharsets.UTF_8);
+
+ String separator2 = System.lineSeparator();
+ assertEquals(
+ "/" + separator2 + "/test" + separator2 + " path" + separator2 + "/solr" + separator2,
+ standardOutput2);
+ }
+
+ @Test
+ public void testUpConfigLinkConfigClearZk() throws Exception {
+ File tmpDir = createTempDir().toFile();
+
+ // test upconfig
+ String confsetname = "confsetone";
+
+ String[] args =
+ new String[] {
+ "upconfig",
+ "--confname",
+ confsetname,
+ "--confdir",
+ ExternalPaths.TECHPRODUCTS_CONFIGSET,
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ConfigSetUploadTool configSetUploadTool = new ConfigSetUploadTool();
+ assertEquals(0, runTool(args, configSetUploadTool));
+
+ assertTrue(zkClient.exists(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, true));
+ File confDir = new File(ExternalPaths.TECHPRODUCTS_CONFIGSET);
+ File[] files = confDir.listFiles();
+ List<String> zkFiles =
+ zkClient.getChildren(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, null, true);
+ assertEquals("Verify that all local files are uploaded to ZK", files.length, zkFiles.size());
+
+ // test linkconfig
+ args =
+ new String[] {
+ "linkconfig",
+ "--confname",
+ confsetname,
+ "-c",
+ "collection1",
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ LinkConfigTool linkConfigTool = new LinkConfigTool();
+ assertEquals(0, runTool(args, linkConfigTool));
+
+ ZkNodeProps collectionProps =
+ ZkNodeProps.load(
+ zkClient.getData(ZkStateReader.COLLECTIONS_ZKNODE + "/collection1", null, null, true));
+ assertTrue(collectionProps.containsKey("configName"));
+ assertEquals(confsetname, collectionProps.getStr("configName"));
+
+ // test down config
+ File configSetDir =
+ new File(
+ tmpDir, "solrtest-confdropspot-" + this.getClass().getName() + "-" + System.nanoTime());
+ assertFalse(configSetDir.exists());
+
+ args =
+ new String[] {
+ "downconfig",
+ "--confname",
+ confsetname,
+ "--confdir",
+ configSetDir.getAbsolutePath(),
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ConfigSetDownloadTool configSetDownloadTool = new ConfigSetDownloadTool();
+ assertEquals(0, runTool(args, configSetDownloadTool));
+
+ confDir = new File(configSetDir, "conf");
+ files = confDir.listFiles();
+ zkFiles =
+ zkClient.getChildren(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, null, true);
+ assertEquals(
+ "Comparing original conf files that were to be uploadedto what is in ZK",
+ files.length,
+ zkFiles.size());
+ assertEquals("Comparing downloaded files to what is in ZK", files.length, zkFiles.size());
+
+ File sourceConfDir = new File(ExternalPaths.TECHPRODUCTS_CONFIGSET);
+ // filter out all directories starting with . (e.g. .svn)
+ Collection<File> sourceFiles =
+ FileUtils.listFiles(
+ sourceConfDir, TrueFileFilter.INSTANCE, new RegexFileFilter("[^\\.].*"));
+ for (File sourceFile : sourceFiles) {
+ int indexOfRelativePath =
+ sourceFile
+ .getAbsolutePath()
+ .lastIndexOf("sample_techproducts_configs" + File.separator + "conf");
+ String relativePathofFile =
+ sourceFile
+ .getAbsolutePath()
+ .substring(indexOfRelativePath + 33, sourceFile.getAbsolutePath().length());
+ File downloadedFile = new File(confDir, relativePathofFile);
+ if (ConfigSetService.UPLOAD_FILENAME_EXCLUDE_PATTERN.matcher(relativePathofFile).matches()) {
+ assertFalse(
+ sourceFile.getAbsolutePath()
+ + " exists in ZK, downloaded:"
+ + downloadedFile.getAbsolutePath(),
+ downloadedFile.exists());
+ } else {
+ assertTrue(
+ downloadedFile.getAbsolutePath()
+ + " does not exist source:"
+ + sourceFile.getAbsolutePath(),
+ downloadedFile.exists());
+ assertTrue(
+ relativePathofFile + " content changed",
+ FileUtils.contentEquals(sourceFile, downloadedFile));
+ }
+ }
+
+ // test reset zk
+ args =
+ new String[] {
+ "rm", "-path", "zk:/configs/confsetone", "-r", "true", "-z", zkServer.getZkAddress()
+ };
+
+ ZkRmTool zkRmTool = new ZkRmTool();
+ assertEquals(0, runTool(args, zkRmTool));
+
+ assertEquals(0, zkClient.getChildren("/configs", null, true).size());
+ }
+
+ @Test
+ public void testGet() throws Exception {
+ String getNode = "/getNode";
+ byte[] data = "getNode-data".getBytes(StandardCharsets.UTF_8);
+ zkClient.create(getNode, data, CreateMode.PERSISTENT, true);
+
+ File localFile = File.createTempFile("temp", ".data");
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ "zk:" + getNode,
+ "-dst",
+ localFile.getAbsolutePath(),
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream();
+ final PrintStream myOut2 = new PrintStream(byteStream2, false, StandardCharsets.UTF_8);
+
+ ZkCpTool tool = new ZkCpTool(myOut2);
+ assertEquals(0, runTool(args, tool));
+
+ final String standardOutput2 = byteStream2.toString(StandardCharsets.UTF_8);
+ assertTrue(standardOutput2.startsWith("Copying from 'zk:/getNode'"));
+ byte[] fileBytes = Files.readAllBytes(Paths.get(localFile.getAbsolutePath()));
+ assertArrayEquals(data, fileBytes);
+ }
+
+ @Test
+ public void testGetCompressed() throws Exception {
+ System.setProperty("solr.home", solrHome);
+ System.setProperty("minStateByteLenForCompression", "0");
+
+ String getNode = "/getNode";
+ byte[] data = "getNode-data".getBytes(StandardCharsets.UTF_8);
+ ZLibCompressor zLibCompressor = new ZLibCompressor();
+ byte[] compressedData =
+ random().nextBoolean()
+ ? zLibCompressor.compressBytes(data)
+ : zLibCompressor.compressBytes(data, data.length / 10);
+ zkClient.create(getNode, compressedData, CreateMode.PERSISTENT, true);
+
+ File localFile = File.createTempFile("temp", ".data");
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ "zk:" + getNode,
+ "-dst",
+ localFile.getAbsolutePath(),
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ assertArrayEquals(data, Files.readAllBytes(Path.of(localFile.getAbsolutePath())));
+ }
+
+ @Test
+ public void testGetFile() throws Exception {
+ Path tmpDir = createTempDir();
+
+ String getNode = "/getFileNode";
+ byte[] data = "getFileNode-data".getBytes(StandardCharsets.UTF_8);
+ zkClient.create(getNode, data, CreateMode.PERSISTENT, true);
+
+ Path file =
+ tmpDir.resolve("solrtest-getfile-" + this.getClass().getName() + "-" + System.nanoTime());
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ "zk:" + getNode,
+ "-dst",
+ file.toAbsolutePath().toString(),
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+ assertArrayEquals(data, Files.readAllBytes(file));
+ }
+
+ @Test
+ public void testGetFileCompressed() throws Exception {
+ Path tmpDir = createTempDir();
+
+ String getNode = "/getFileNode";
+ byte[] data = "getFileNode-data".getBytes(StandardCharsets.UTF_8);
+ ZLibCompressor zLibCompressor = new ZLibCompressor();
+ byte[] compressedData =
+ random().nextBoolean()
+ ? zLibCompressor.compressBytes(data)
+ : zLibCompressor.compressBytes(data, data.length / 10);
+ zkClient.create(getNode, compressedData, CreateMode.PERSISTENT, true);
+
+ Path file =
+ tmpDir.resolve("solrtest-getfile-" + this.getClass().getName() + "-" + System.nanoTime());
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ "zk:" + getNode,
+ "-dst",
+ file.toAbsolutePath().toString(),
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(0, runTool(args, tool));
+
+ assertArrayEquals(data, Files.readAllBytes(file));
+ }
+
+ @Test
+ public void testGetFileNotExists() throws Exception {
+ String getNode = "/getFileNotExistsNode";
+
+ File file = createTempFile("newfile", null).toFile();
+
+ String[] args =
+ new String[] {
+ "cp",
+ "-src",
+ "zk:" + getNode,
+ "-dst",
+ file.getAbsolutePath(),
+ "-z",
+ zkServer.getZkAddress()
+ };
+
+ ZkCpTool tool = new ZkCpTool();
+ assertEquals(1, runTool(args, tool));
+ }
+
+ @Test
+ public void testInvalidZKAddress() throws Exception {
+
+ String[] args = new String[] {"ls", "-path", "/", "-r", "true", "-z", "----------:33332"};
+
+ ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream();
+ final PrintStream myOut2 = new PrintStream(byteStream2, false, StandardCharsets.UTF_8);
+
+ ZkLsTool tool = new ZkLsTool(myOut2);
+ assertEquals(1, runTool(args, tool));
+ }
+
+ @Test
+ public void testSetClusterProperty() throws Exception {
+ ClusterProperties properties = new ClusterProperties(zkClient);
+ // add property urlScheme=http
+ String[] args =
+ new String[] {
+ "cluster", "-property", "urlScheme", "-value", "http", "-z", zkServer.getZkAddress()
+ };
+ ClusterTool tool = new ClusterTool();
+ assertEquals(0, runTool(args, tool));
+
+ assertEquals("http", properties.getClusterProperty("urlScheme", "none"));
+
+ args = new String[] {"cluster", "-property", "urlScheme", "-z", zkServer.getZkAddress()};
+ assertEquals(0, runTool(args, tool));
+ assertNull(properties.getClusterProperty("urlScheme", (String) null));
+ }
+
+ @Test
+ public void testUpdateAcls() throws Exception {
+ try {
+ System.setProperty(
+ SolrZkClient.ZK_ACL_PROVIDER_CLASS_NAME_VM_PARAM_NAME,
+ DigestZkACLProvider.class.getName());
+ System.setProperty(
+ VMParamsZkCredentialsInjector.DEFAULT_DIGEST_READONLY_USERNAME_VM_PARAM_NAME, "user");
+ System.setProperty(
+ VMParamsZkCredentialsInjector.DEFAULT_DIGEST_READONLY_PASSWORD_VM_PARAM_NAME, "pass");
+ System.setProperty(
+ SolrZkClient.ZK_ACL_PROVIDER_CLASS_NAME_VM_PARAM_NAME,
+ VMParamsAllAndReadonlyDigestZkACLProvider.class.getName());
+ System.setProperty(
+ VMParamsAllAndReadonlyDigestZkACLProvider.DEFAULT_DIGEST_READONLY_USERNAME_VM_PARAM_NAME,
+ "user");
+ System.setProperty(
+ VMParamsAllAndReadonlyDigestZkACLProvider.DEFAULT_DIGEST_READONLY_PASSWORD_VM_PARAM_NAME,
+ "pass");
+
+ String[] args = new String[] {"updateacls", "--path", "/", "-z", zkServer.getZkAddress()};
+ UpdateACLTool tool = new UpdateACLTool();
+ assertEquals(0, runTool(args, tool));
+ } finally {
+ // Need to clear these before we open the next SolrZkClient
+ System.clearProperty(SolrZkClient.ZK_ACL_PROVIDER_CLASS_NAME_VM_PARAM_NAME);
+ System.clearProperty(
+ VMParamsAllAndReadonlyDigestZkACLProvider.DEFAULT_DIGEST_READONLY_USERNAME_VM_PARAM_NAME);
+ System.clearProperty(
+ VMParamsAllAndReadonlyDigestZkACLProvider.DEFAULT_DIGEST_READONLY_PASSWORD_VM_PARAM_NAME);
+ }
+
+ boolean excepted = false;
+ try (SolrZkClient zkClient =
+ new SolrZkClient.Builder()
+ .withUrl(zkServer.getZkAddress())
+ .withTimeout(
+ AbstractDistribZkTestBase.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
+ .build()) {
+ zkClient.getData("/", null, null, true);
+ } catch (KeeperException.NoAuthException e) {
+ excepted = true;
+ }
+ assertTrue("Did not fail to read.", excepted);
+ }
+
+ private int runTool(String[] args, Tool tool) throws Exception {
+ CommandLine cli = parseCmdLine(tool.getName(), args, tool.getOptions());
+ return tool.runTool(cli);
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ if (zkClient != null) {
+ zkClient.close();
+ }
+ if (zkServer != null) {
+ zkServer.shutdown();
+ }
+ System.clearProperty("solr.home");
+ System.clearProperty("minStateByteLenForCompression");
+ System.setOut(originalSystemOut);
+ super.tearDown();
+ }
+}
diff --git a/solr/packaging/test/test_zk.bats b/solr/packaging/test/test_zk.bats
index 723b8e57830..c3b1cae691d 100644
--- a/solr/packaging/test/test_zk.bats
+++ b/solr/packaging/test/test_zk.bats
@@ -19,7 +19,7 @@ load bats_helper
setup_file() {
common_clean_setup
- solr start -c
+ solr start -DminStateByteLenForCompression=0 -c
}
teardown_file() {
@@ -64,13 +64,20 @@ teardown() {
touch myfile2.txt
run solr zk cp myfile2.txt zk:myfile2.txt -z localhost:${ZK_PORT}
- assert_output --partial "Copying from 'myfile2.txt' to 'zk:myfile2.txt'. ZooKeeper at localhost:${ZK_PORT}"
sleep 1
run solr zk ls / -z localhost:${ZK_PORT}
assert_output --partial "myfile2.txt"
+
+ touch myfile3.txt
+ run solr zk cp myfile3.txt zk:/myfile3.txt -z localhost:${ZK_PORT}
+ assert_output --partial "Copying from 'myfile3.txt' to 'zk:/myfile3.txt'. ZooKeeper at localhost:${ZK_PORT}"
+ sleep 1
+ run solr zk ls / -z localhost:${ZK_PORT}
+ assert_output --partial "myfile3.txt"
rm myfile.txt
rm myfile2.txt
+ rm myfile3.txt
}
@test "upconfig" {
@@ -104,3 +111,19 @@ teardown() {
local path_value=${extracted_solrhome#*=}
[[ $path_value == "/path/to/solr/home" ]]
}
+
+
+@test "bin/solr zk cp gets 'solrhome' from '--solr-home' command line option" {
+ touch afile.txt
+
+ run solr zk cp afile.txt zk:/afile.txt -z localhost:${ZK_PORT} -verbose --solr-home ${SOLR_TIP}/server/solr
+ assert_output --partial "Using SolrHome: ${SOLR_TIP}/server/solr"
+ refute_output --partial 'Failed to load solr.xml from ZK or SolrHome'
+
+ # The -DminStateByteLenForCompression variable substitution on solr start is not seen
+ # by the ZkCpTool.java, so therefore we do not have compression unless solr.xml is directly edited.
+ #assert_output --partial 'Compression of state.json has been enabled'
+
+
+ rm afile.txt
+}
diff --git a/solr/server/scripts/cloud-scripts/zkcli.sh b/solr/server/scripts/cloud-scripts/zkcli.sh
index 4986d21c029..c9dd7a50b66 100755
--- a/solr/server/scripts/cloud-scripts/zkcli.sh
+++ b/solr/server/scripts/cloud-scripts/zkcli.sh
@@ -1,5 +1,7 @@
#!/usr/bin/env bash
+echo "WARNING: The zkcli.sh script has been deprecated in favour of the bin/solr equivalent commands."
+
# You can override pass the following parameters to this script:
#
@@ -25,4 +27,3 @@ solr_home="$sdir/../../solr"
#...
PATH=$JAVA_HOME/bin:$PATH $JVM $SOLR_ZK_CREDS_AND_ACLS $ZKCLI_JVM_FLAGS -Dlog4j.configurationFile=$log4j_config -Dsolr.home=$solr_home \
-classpath "$sdir/../../solr-webapp/webapp/WEB-INF/lib/*:$sdir/../../lib/ext/*:$sdir/../../lib/*" org.apache.solr.cloud.ZkCLI ${1+"$@"}
-
diff --git a/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc b/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc
index 4c579da15c4..3f0ac446665 100644
--- a/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc
+++ b/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc
@@ -229,7 +229,7 @@ The examples below use the `zkcli` tool that comes with Solr to do this.
[.tab-label]**nix Command*
[source,terminal]
----
-$ server/scripts/cloud-scripts/zkcli.sh -zkhost server1:2181,server2:2181,server3:2181 -cmd clusterprop -name urlScheme -val https
+$ bin/solr cluster -property urlSchema -value https -z server1:2181,server2:2181,server3:2181
----
====
@@ -238,7 +238,7 @@ $ server/scripts/cloud-scripts/zkcli.sh -zkhost server1:2181,server2:2181,server
[.tab-label]*Windows Command*
[source,powershell]
----
-C:\> server\scripts\cloud-scripts\zkcli.bat -zkhost server1:2181,server2:2181,server3:2181 -cmd clusterprop -name urlScheme -val https
+C:\> bin/solr.cmd -property urlSchema -value https -z server1:2181,server2:2181,server3:2181
----
=====
--
diff --git a/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-access-control.adoc b/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-access-control.adoc
index 47ef33be8bd..c3475809da6 100644
--- a/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-access-control.adoc
+++ b/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-access-control.adoc
@@ -548,7 +548,7 @@ Then run the command below appropriate for your operating system:
[.tab-label]**nix*
[source,bash]
----
-$ ./server/scripts/cloud-scripts/zkcli.sh -cmd updateacls /zk-path
+$ bin/solr zk updateacls /zk-path
----
====
@@ -557,7 +557,7 @@ $ ./server/scripts/cloud-scripts/zkcli.sh -cmd updateacls /zk-path
[.tab-label]*Windows*
[source,powershell]
----
-C:\\ server\scripts\cloud-scripts\zkcli.bat cmd updateacls /zk-path
+$ bin/solr.cmd zk updateacls /zk-path
----
====
--
diff --git a/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-utilities.adoc b/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-utilities.adoc
index b2f0b5dcff5..696e1d38bd2 100644
--- a/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-utilities.adoc
+++ b/solr/solr-ref-guide/modules/deployment-guide/pages/zookeeper-utilities.adoc
@@ -34,6 +34,8 @@ The `zkcli.sh` provided by Solr is not the same as the https://zookeeper.apache.
ZooKeeper's `zkCli.sh` provides a completely general, application-agnostic shell for manipulating data in ZooKeeper.
Solr's `zkcli.sh` – discussed in this section – is specific to Solr, and has command line arguments specific to dealing with Solr data in ZooKeeper.
+
+`zkcli.sh` has been deprecated in favour of the `bin/solr` commands which should be used instead.
====
== Using Solr's ZooKeeper CLI
diff --git a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SolrZkClient.java b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SolrZkClient.java
index 25b16e18fc4..ed1eaf86dd7 100644
--- a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SolrZkClient.java
+++ b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SolrZkClient.java
@@ -82,6 +82,7 @@ public class SolrZkClient implements Closeable {
private final ZkMetrics metrics = new ZkMetrics();
private Compressor compressor;
+ private int minStateByteLenForCompression;
public MapWriter getMetrics() {
return metrics::writeMap;
@@ -117,6 +118,7 @@ public class SolrZkClient implements Closeable {
builder.beforeReconnect,
builder.zkACLProvider,
builder.higherLevelIsClosed,
+ builder.minStateByteLenForCompression,
builder.compressor,
builder.solrClassLoader,
builder.useDefaultCredsAndACLs);
@@ -131,6 +133,7 @@ public class SolrZkClient implements Closeable {
BeforeReconnect beforeReconnect,
ZkACLProvider zkACLProvider,
IsClosed higherLevelIsClosed,
+ int minStateByteLenForCompression,
Compressor compressor,
SolrClassLoader solrClassLoader,
boolean useDefaultCredsAndACLs) {
@@ -228,6 +231,7 @@ public class SolrZkClient implements Closeable {
} else {
this.compressor = compressor;
}
+ this.minStateByteLenForCompression = minStateByteLenForCompression;
}
public ConnectionManager getConnectionManager() {
@@ -471,12 +475,16 @@ public class SolrZkClient implements Closeable {
}
/** Returns node's state */
- public Stat setData(
- final String path, final byte data[], final int version, boolean retryOnConnLoss)
+ public Stat setData(final String path, byte data[], final int version, boolean retryOnConnLoss)
throws KeeperException, InterruptedException {
Stat result = null;
+ if (SolrZkClient.shouldCompressData(data, path, minStateByteLenForCompression)) {
+ // state.json should be compressed before being put to ZK
+ data = compressor.compressBytes(data);
+ }
if (retryOnConnLoss) {
- result = zkCmdExecutor.retryOperation(() -> keeper.setData(path, data, version));
+ byte[] finalData = data;
+ result = zkCmdExecutor.retryOperation(() -> keeper.setData(path, finalData, version));
} else {
result = keeper.setData(path, data, version);
}
@@ -580,16 +588,9 @@ public class SolrZkClient implements Closeable {
makePath(path, null, CreateMode.PERSISTENT, null, failOnExists, retryOnConnLoss, 0);
}
- public void makePath(String path, Path data, boolean failOnExists, boolean retryOnConnLoss)
+ public void makePath(String path, byte[] data, boolean failOnExists, boolean retryOnConnLoss)
throws IOException, KeeperException, InterruptedException {
- makePath(
- path,
- Files.readAllBytes(data),
- CreateMode.PERSISTENT,
- null,
- failOnExists,
- retryOnConnLoss,
- 0);
+ makePath(path, data, CreateMode.PERSISTENT, null, failOnExists, retryOnConnLoss, 0);
}
public void makePath(String path, Path data, boolean retryOnConnLoss)
@@ -683,14 +684,20 @@ public class SolrZkClient implements Closeable {
throws KeeperException, InterruptedException {
log.debug("makePath: {}", path);
metrics.writes.increment();
- if (data != null) {
- metrics.bytesWritten.add(data.length);
- }
+
boolean retry = true;
if (path.startsWith("/")) {
path = path.substring(1, path.length());
}
+ if (SolrZkClient.shouldCompressData(data, path, minStateByteLenForCompression)) {
+ // state.json should be compressed before being put to ZK
+ data = compressor.compressBytes(data);
+ }
+ if (data != null) {
+ metrics.bytesWritten.add(data.length);
+ }
+
String[] paths = path.split("/");
StringBuilder sbPath = new StringBuilder();
for (int i = 0; i < paths.length; i++) {
@@ -764,14 +771,14 @@ public class SolrZkClient implements Closeable {
* Write file to ZooKeeper - default system encoding used.
*
* @param path path to upload file to e.g. /solr/conf/solrconfig.xml
- * @param data a filepath to read data from
+ * @param source a filepath to read data from
*/
- public Stat setData(String path, Path data, boolean retryOnConnLoss)
+ public Stat setData(String path, Path source, boolean retryOnConnLoss)
throws IOException, KeeperException, InterruptedException {
if (log.isDebugEnabled()) {
- log.debug("Write to ZooKeeper: {} to {}", data.toAbsolutePath(), path);
+ log.debug("Write to ZooKeeper: {} to {}", source.toAbsolutePath(), path);
}
- return setData(path, Files.readAllBytes(data), retryOnConnLoss);
+ return setData(path, Files.readAllBytes(source), retryOnConnLoss);
}
public List<OpResult> multi(final Iterable<Op> ops, boolean retryOnConnLoss)
@@ -1166,6 +1173,7 @@ public class SolrZkClient implements Closeable {
public boolean useDefaultCredsAndACLs = true;
public Compressor compressor;
+ private int minStateByteLenForCompression = -1;
public Builder withUrl(String server) {
this.zkServerAddress = server;
@@ -1183,6 +1191,20 @@ public class SolrZkClient implements Closeable {
return this;
}
+ /**
+ * If the state.json is greater than this many bytes and compression is enabled in solr.xml,
+ * then the data will be compressed
+ *
+ * @param minStateByteLenForCompression how big the state.json file can be
+ * @param compressor The compressor to use
+ */
+ public Builder withStateFileCompression(
+ int minStateByteLenForCompression, Compressor compressor) {
+ this.minStateByteLenForCompression = minStateByteLenForCompression;
+ this.compressor = compressor;
+ return this;
+ }
+
/**
* Sets the Zk connection timeout
*
@@ -1219,6 +1241,7 @@ public class SolrZkClient implements Closeable {
return this;
}
+ // I believe this doesn't make sense with out the minStateByteLenForCompression flag?
public Builder withCompressor(Compressor c) {
this.compressor = c;
return this;
@@ -1238,4 +1261,14 @@ public class SolrZkClient implements Closeable {
return new SolrZkClient(this);
}
}
+
+ static boolean shouldCompressData(byte[] data, String path, int minStateByteLenForCompression) {
+ if (path.endsWith("state.json")
+ && minStateByteLenForCompression > -1
+ && data.length > minStateByteLenForCompression) {
+ // state.json should be compressed before being put to ZK
+ return true;
+ }
+ return false;
+ }
}
diff --git a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java
index e40294a6683..7acb40eb3b5 100644
--- a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java
+++ b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java
@@ -179,7 +179,9 @@ public class ZkMaintenanceUtils {
// Single file ZK -> local copy where ZK is a leaf node
if (Files.isDirectory(Paths.get(dst))) {
- if (dst.endsWith(File.separator) == false) dst += File.separator;
+ if (dst.endsWith(File.separator) == false) {
+ dst += File.separator;
+ }
dst = normalizeDest(src, dst, srcIsZk, dstIsZk);
}
byte[] data = zkClient.getData(src, null, null, true);
@@ -323,7 +325,9 @@ public class ZkMaintenanceUtils {
final Path rootPath = Paths.get(path);
- if (!Files.exists(rootPath)) throw new IOException("Path " + rootPath + " does not exist");
+ if (!Files.exists(rootPath)) {
+ throw new IOException("Path " + rootPath + " does not exist");
+ }
int partsOffset =
Path.of(zkPath).getNameCount() - rootPath.getNameCount() - 1; // will be negative
@@ -357,7 +361,11 @@ public class ZkMaintenanceUtils {
zkClient.setData(zkNode, file, true);
} else if (file == rootPath) {
// We are only uploading a single file, preVisitDirectory was never called
- zkClient.makePath(zkNode, file, false, true);
+ if (zkClient.exists(zkPath, true)) {
+ zkClient.setData(zkPath, file, true);
+ } else {
+ zkClient.makePath(zkPath, Files.readAllBytes(file), false, true);
+ }
} else {
// Skip path parts here because they should have been created during
// preVisitDirectory
@@ -371,6 +379,7 @@ public class ZkMaintenanceUtils {
true,
pathParts);
}
+
} catch (KeeperException | InterruptedException e) {
throw new IOException(
"Error uploading file " + file + " to zookeeper path " + zkNode,
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/ZkTestServer.java b/solr/test-framework/src/java/org/apache/solr/cloud/ZkTestServer.java
index 4a2f97475d0..14d2a5a1f86 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/ZkTestServer.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/ZkTestServer.java
@@ -786,7 +786,7 @@ public class ZkTestServer {
if (log.isInfoEnabled()) {
log.info("put {} to {}", file.toAbsolutePath(), destPath);
}
- zkClient.makePath(destPath, file, false, true);
+ zkClient.makePath(destPath, Files.readAllBytes(file), false, true);
}
// static to share with distrib test